diff --git a/.gitignore b/.gitignore index b2e126871c..403d7f5bbf 100644 --- a/.gitignore +++ b/.gitignore @@ -39,3 +39,7 @@ __pycache__/ *.exp *.log .vs/ + +# Predictor profiles are fitted from the user's own texture pools. +*.bcph +*.bcph.stamp diff --git a/README.md b/README.md index eddfc9d064..11082be186 100644 --- a/README.md +++ b/README.md @@ -65,7 +65,7 @@ work on booting can start as soon as one is available to a developer. | Audio banks (AWC: Opus, XMA2) | ✅ Exported whole. Opus repackaged **losslessly** as Ogg Opus; PCM (codec 0/2) as WAV; XMA2 decoded with ffmpeg. `--wav` adds 16-bit PCM WAV ([notes](docs/audio.md)) | | Music/radio config | ? Measured. **1,589** audio-config records with exact durations and AWC stream ids; station grouping and content-id lists; no per-track start offsets ([notes](docs/audio_config.md)) | | PE loader and import shims | ⚠️ Runs a stand-in executable end to end (`gta6rt --run`: CRT startup, statics, heap, files, threads, GDK imports through the shims, exit code back). Controllers through a GameInput shim on SDL3 (any controller SDL supports, rumble, DualSense trigger effects and lightbar; built when SDL3 is installed or with `-DLEONIDA_SDL3_FETCH=ON`, [notes](docs/gameinput.md)). `--trace-d3d12` logs every D3D12 call and its outcome for the first boot. Untested against the real executable | -| Xbox D3D12 → Vulkan | ⚠️ In progress. A Vulkan-backed device behind the Xbox-ABI proxy creates queues, command lists, fences, descriptor heaps, committed, placed and reserved resources, render-target and depth views (3D targets included), texture views and samplers (2D, cube, 1D and 3D views, the depth and stencil planes of depth-stencil textures, packed formats such as B5G6R5, B4G4R4A4 and R9G9B9E5, buffer SRVs — raw, structured and typed; they go into the bindless set), root signatures, pipelines and query heaps, and draws run on Vulkan. Barriers, clears, uploads, copies (BC included), colour resolves, predication, CPU-side texture reads and writes, and occlusion, timestamp and pipeline-statistics queries run on Vulkan, checked on one GPU. The console-shaped command-list proxy, the measured `PresentX` queue slots (30/32, layout-detected) wired to the presentation core, and `AllocateUploadMemory` (list slot 148, a mapped-upload arena whose addresses translate to buffer device addresses in root descriptors and IA/SO views) cover the console-ABI surface the package measures. Still open: the console list tail and the descriptor-table record model ([plan](docs/d3d12_vulkan.md)) | +| Xbox D3D12 → Vulkan | ⚠️ In progress. A Vulkan-backed device behind the Xbox-ABI proxy creates queues, command lists, fences, descriptor heaps, committed, placed and reserved resources, render-target and depth views (3D targets included), texture views and samplers (2D, cube, 1D and 3D views, the depth and stencil planes of depth-stencil textures, packed formats such as B5G6R5, B4G4R4A4 and R9G9B9E5, buffer SRVs — raw, structured and typed; they go into the bindless set), root signatures, pipelines and query heaps, and draws run on Vulkan. Barriers, clears, uploads, copies (BC included), colour resolves, predication, CPU-side texture reads and writes, and occlusion, timestamp and pipeline-statistics queries run on Vulkan, checked on one GPU. The console-shaped command-list proxy, the measured `PresentX` queue slots (30/32, layout-detected) wired to the presentation core, and `AllocateUploadMemory` (list slot 148, a mapped-upload arena whose addresses translate to buffer device addresses in root descriptors and IA/SO views) cover the console-ABI surface the package measures. Still open: the console list tail and the descriptor-table record model ([plan](docs/d3d12_vulkan.md), [console ABI](docs/d3d12_xs_console_abi.md)) | | Ray tracing (BVH) | ⚠️ In progress. `BuildRaytracingAccelerationStructure` builds BLASes and TLASes on the GPU in the console's XDXR BVH4 layout (the default; `LEONIDA_RT_AS=khr` uses Vulkan's own acceleration structures instead), which the translated shaders walk themselves through `image_bvh_intersect_ray` (all four triangle node types, TRI0-TRI3, with the barycentric remap byte); the GPU builder writes TRI0 and TRI1 leaves. Updates refit instead of rebuilding, and clone, compaction and the compacted/current postbuild sizes work; checked against a CPU reference on synthetic scenes. The build descriptions are recovered from the package's `XboxBvhBuilder.dll` ([notes](docs/xdxr.md)). The game's `*_bvh4.rpf` packs are measured: offline-built, dehydrated BLASes that rehydrate through that DLL with their geometry from the drawables in `levels.rpf` (measured on 8 of the 10 sampled BLAS; [notes](docs/bvh.md)). Not done in the builder: serialization. TRI1 pairing (no memory saved yet) and BOX16 nodes for `MINIMIZE_MEMORY` BLASes (an assumed switch) are in ([notes](docs/bvh.md)). Open: whether the game rehydrates the packs or rebuilds them ([#313](https://github.com/ItsNotRexed/Leonida/issues/313)) | The table above is written by hand. To measure it on your own checkout (unit and runtime tests, which rows of diff --git a/docs/README.md b/docs/README.md index 1fb607ec00..0b27ca2e79 100644 --- a/docs/README.md +++ b/docs/README.md @@ -76,14 +76,18 @@ method, scope and caveats. No game data is included. | [descriptor_lookup_intel.md](descriptor_lookup_intel.md) | Intel UHD Graphics 770 (Xe-LP, Windows, driver 101.6129) timings for the same lookups at 1k–100k live entries; both memory placements within 0.6% of each other. | | [d3d12_xs_surface.md](d3d12_xs_surface.md) | The 116-slot `d3d12_xs.dll` export surface; 83/83 standard GUIDs match the PC SDK. | | [xdxr.md](xdxr.md) | `BATCHED_DESC2` (`0x50`) and `XDXR_STREAM_DESC` (`0x10`) from `XboxBvhBuilder.dll`'s reads; stream records' offsets and defaults; offline statistics not in the package. | +| [d3d12_xs_console_abi.md](d3d12_xs_console_abi.md) | The D3D12.X console ABI the `d3d12_xs` shim must reproduce: device/queue/list vtable slots, command-list object fields and record encodings, root-argument SGPR rules, unified memory; sibling-layer measurements marked unverified here. | | [d3d12_command_objects.md](d3d12_command_objects.md) | Measured command queue/list/fence/`PresentX` surface; verified vs prior art vs open. | | [xbox_d3d12_xs.md](xbox_d3d12_xs.md) | The `d3d12_xs` graphics ABI quoted from Microsoft's public GDK reference: root signatures, state objects, DXIL libraries, hit groups, shader cache sessions; which pages are missing or NDA-gated. | | [runtime_imports.md](runtime_imports.md) | The 16 shipped modules' measured imports and shim/host/unimplemented split. | +| [linux_proton.md](linux_proton.md) | Building and booting under Proton/Wine on Linux, a healthy boot's timeline, and the test report of one Linux and two Windows machines | | [xmem_exe_calls.md](xmem_exe_calls.md) | How the retail executable calls `xmem.dll`: call sites and constant arguments per import (`tools/import_call_sites.py`), the 23 `XMemVirtualAlloc` calls that all pass an attribute word, and the inferred shape of the physical-page family. | | [exe_fail_fast.md](exe_fail_fast.md) | Where the retail executable stops itself (`int3`) on an import's result: 78 sites over 27 imports (`tools/import_fail_fast.py`), grouped by how `main` binds each import (all 13 non-host fatal-checked imports now bind to shims; 0 unbound). | | [audio_hal_exe_calls.md](audio_hal_exe_calls.md) | How the retail executable calls the 22 audio coprocessor, texture layout and DirectStorage imports that have no shim: call sites, constant arguments, and the four calls with a negative-result branch. | | [directstorage.md](directstorage.md) | Console DirectStorage: the DLL and ABI the title is expected to use (`DStorageGetFactory`, `dstorage_xs`, `XCRDAPI`), how sure that is and the evidence for it, and what `runtime/shims/dstorage.cpp` serves on the PC. The executable's own imports are unmeasured. | +| [cpu_features.md](cpu_features.md) | CPU instructions in the executable a desktop CPU may lack (`tools/cpu_feature_scan.py`): 19 SSE4a, 10 CLZERO and 4 MONITORX/MWAITX sites (AMD only) and 8 CLWB sites (Intel since Ice Lake), all real code; `#UD` on hosts without them. | | [xcl_compare.md](xcl_compare.md) | XCL's synthetic test title under `gta6rt --run` and under XCL (`tools/xcl_compare.py`): 5 of 50 checks pass here, both hangs are the documented manual-queue terminate deadlock, and each other difference mapped to an open item or a lead. | +| [directstorage.md](directstorage.md) | DirectStorage for the console title: the evidence for the DLL (`dstorage_xs.dll`, also `xcrdapi.dll`, `dstorage.dll`) and the console ABI with its confidence, and the shim: `GAME:` file open, queues, file and memory reads, status arrays, fences, events, cancel and errors, zlib requests inflated with their `E_DSTORAGE_ZLIB_*` errors; BCPack, swizzle and physical pages still open. | | [gameinput.md](gameinput.md) | The GameInput shim on SDL3: `GameInputCreate` and the v0 `IGameInput`/`IGameInputDevice`/`IGameInputReading`/`IGameInputDispatcher` surface on any SDL gamepad, DualSense adaptive-trigger approximation and lightbar, force-feedback motors and trigger haptics through SDL's haptic API; 261 checks on virtual joysticks and a fake haptic backend; by hand on an Xbox Series X pad (Bluetooth) and a DualSense (USB). 261 checks on virtual joysticks and a fake haptic backend, not yet tried on a real pad. | | [saves.md](saves.md) | Save containers: `JSAV` (index + JSON story save, byte-exact rebuild), `ASAV` header, `SLAYER1` packed copy (not decoded); `tools/saves.py` and import into the offline `XGameSave` folder; key hashes are case-sensitive joaat (`tools/save_keys.py`). | | [pipeline_check.md](pipeline_check.md) | Driver-level corpus check: the full corpus, 26,503 of 26,503 modules and pipelines, 0 failures (RTX 4060 Ti); an earlier 10/12-shard run, 22,092 modules and 2,217 compute pipelines, also had 0 failures. Driver-level corpus check: 10/12 shards, 22,092 modules, 2,217 compute pipelines, 0 failures. | diff --git a/docs/boot.md b/docs/boot.md index 49ceb2fd64..d8b6585b61 100644 --- a/docs/boot.md +++ b/docs/boot.md @@ -104,13 +104,29 @@ Useful switches: `int3_skipped` event, so a boot can be followed past soft asserts (an int3 followed by code that carries on). Diagnostic only: a correct run reaches none, so each skipped address is a finding, not a fix. A failed guest file open is always traced as `file_open_failed` (path, error, caller) when `--trace` is on. +* `LEONIDA_STUB_PIPELINES=1` creates a pipeline whose translated shader is missing (no shader library, or no entry + for its program) as a no-op stub instead of failing `CreateGraphicsPipelineState` / `CreateComputePipelineState`. + The stub is never registered, so `SetPipelineState` binds no PSO and its draws and dispatches are no-ops (D3D-482). + Diagnostic only, like `LEONIDA_SKIP_INT3`: it follows a boot past every pipeline the title creates without + translating or running a game shader, so nothing the title draws reaches the screen. Each stub is logged with a + power-of-two count. +* During `--run` on Vulkan, the runtime paints the package shell splash when the title shows its window. The first + direct queue presents it on the window's swapchain. Startup clears keep the splash visible until the first + non-black output replaces it. The runtime reads `ShellVisuals/SplashScreenImage` from + `MicrosoftGame.Config` or `SplashScreen/Image` from `appxmanifest.xml`, preserves the image's aspect ratio and + uses the same swapchain for PresentX. A surface without readback hands off at the first title present. + Set `LEONIDA_PACKAGE_SPLASH=0` to disable the splash. * `LEONIDA_VK_VALIDATION=1` enables the Khronos validation layer with the Vulkan backend (startup overhead; it is a diagnostic). +* `LEONIDA_DEVICE_FAULT=1` enables Vulkan device-loss diagnostics and checkpoints where available. The first + observed loss prints a `[rt] device-fault:` report to stderr. * `DISABLE_RTSS_LAYER=1` and `DISABLE_VULKAN_OBS_CAPTURE=1` when MSI Afterburner or OBS is installed; their implicit layers add swapchain usage that shows up as validation errors ([testing.md](testing.md), "Known problems"). * `--overlay DIR` sends the guest's writes to DIR instead of the default `\overlay` (useful when the package drive is read-only); the package itself is never written. + Set `LEONIDA_WRITE_DIR` to override that folder for one run. For a fresh first-run profile, + also set `LEONIDA_SAVE_DIR` to a separate empty directory for the local game-save provider. ## 3. Triage order diff --git a/docs/buffer_bounds.md b/docs/buffer_bounds.md index 9326fe5171..f5b4e6a55a 100644 --- a/docs/buffer_bounds.md +++ b/docs/buffer_bounds.md @@ -17,6 +17,10 @@ measured natively on AMD GPUs (SHADER-116). The translator reads this field and | 2 disabled | `N == 0` | same | same | | 3 raw | `offset + soffset + 4 > N`; `index * stride` moves the address but is not checked | `offset >= N`: differs | `offset + 4 > N`, without `soffset` | +The runtime writes mode 3 for raw SRVs/UAVs, mode 0 for structured views and mode 1 for typed views. +API-created CBVs mirror the observed inline console descriptor (mode 0, 16-byte rows). +`LEONIDA_CBV_RAW=1` selects mode 3 with a byte count. Root views carry a GPU VA. + - **RDNA2 follows Mesa's GFX11 column**, not the GFX10 one: of 732 cases, 729 match GFX11 and 696 match GFX10. Every GFX10 miss is an access that only partly fits, for example a raw buffer with `N = 3` read at offset 0. - **In raw mode `soffset` is part of the checked offset.** The 3 cases that match neither column are raw reads at diff --git a/docs/cpu_features.md b/docs/cpu_features.md index 4b72ca2f5a..5ecea005f7 100644 --- a/docs/cpu_features.md +++ b/docs/cpu_features.md @@ -58,6 +58,13 @@ in the image. `insertq`/`extrq` are bit-field operations on the low quadword. `cpu_emulation_test` checks each form against the CPU on a host that has it and against the handler on one that does not (an i7-10700K: all four lacking, all checks pass). +- The CLZERO routine is too hot for the #UD path: one exception and two `VirtualQuery` calls per 64-byte line. On an + i9-13900K the routine held one thread at ~99% for the whole boot (sampled: `VirtualQuery` under + `cpu_emulation::apply`) and the title presented ~3 frames a second. On a CPU without CLZERO the loader therefore + rewrites the routine's loops before any image code runs (`runtime/src/clzero_patch.h`): each of the two loop shapes + (6 + 4 sites) jumps to a stub within 2 GiB of the image that zeroes the line with eight 8-byte stores and keeps the + loop's registers and flags. Same boot afterwards: 164,946 PresentX in 300 s against 869 in 420 s, no CLZERO left on + the #UD path. `LEONIDA_CLZERO_PATCH=0` keeps the emulation; `clzero_patch_test` runs both shapes on any CPU. - The CPUID sites see the host's vendor, family and features, not the console's. What the game does with the answers is not measured here. diff --git a/docs/d3d12_command_objects.md b/docs/d3d12_command_objects.md index 5a214e3258..1aef122066 100644 --- a/docs/d3d12_command_objects.md +++ b/docs/d3d12_command_objects.md @@ -375,9 +375,10 @@ section 3.5a), and the console list has methods well past the PC tail: 71, 73, 8 FSR DLL. Slot 148 matters beyond the builder: the address it returns is written by the CPU and passed unchanged to the GPU -as a root SRV address, so console upload memory has the same address for the CPU and the GPU. A replacement must -return memory whose CPU pointer is also a valid GPU address (for this layer: inside the arena of -[d3d12_vulkan.md §3.3](d3d12_vulkan.md)). +as a root SRV address, so console upload memory has the same address for the CPU and the GPU. On a PC the two +address spaces differ, so `d3d12_xs_device.cpp` carves a bump arena out of persistently-mapped UPLOAD-heap +buffers: the title writes the mapped memory and the six root descriptor setters and the IA/SO view setters +translate the CPU pointer to the chunk's buffer device address before forwarding. The function at `0xd580` uses the 71/73 pair instead of the slot-146 barrier when the byte at RVA `0xd773c` is set. That byte is one of seven bools at `0xd7738`–`0xd773e` in zero-initialised `.bss`. The only accesses to them in @@ -764,6 +765,12 @@ Queues and fences are wrapped the same way. object implements but the proxy does not model is logged once and refused. - **The refused tail.** A slot past the public chain, up to the end of the proxy's own table (128 queue and 64 fence slots, every one a thunk), logs its first four argument words once and returns `E_NOTIMPL`. +- **Fence slot 12.** The one served slot past the chain. The retail executable calls it as + `(value, descriptor, flags)` and reads the return as a pointer to the fence's 64-bit completed value: it + compares that value with `~0` (device removed) and subtracts the value it waits for. The proxy returns a + per-fence mirror. Completion events refresh it immediately. A 10 ms wait timeout also refreshes it if the + fence rewinds below the pending event's threshold. Slot 12 and the CPU `Signal` (10) refresh it synchronously. + The descriptor's second word is a code pointer, which is not called. - **The guard region.** Each table sits at the end of the first page of a 64 KiB reservation, and the rest of that reservation is never committed. A slot past the table therefore faults on the vtable read itself, inside the reservation, and a vectored handler logs the slot before the fault goes on. A vtable read that @@ -830,7 +837,7 @@ command object. | Item | Why it is blocked | |---|---| | `PresentX` | No slot, signature, plane struct or swapchain/plane parameters. Prior art gives only names, the 2-plane/8-view limits and four flag names. | -| `CreateCommandQueueX` | No slot or parameter layout; only the UMD message and an inferred shape. | +| `CreateCommandQueueX` | No slot or parameter layout; only the UMD message and an inferred shape. The retail title calls device slot 48 as (desc, riid, out) with a 32-byte desc (#6954), which differs from the (pDesc, pShaderQueueParams, riid, out) shape inferred above. | | `SuspendX` / `ResumeX` | No slot or signature. | | Xbox queue/list/fence/allocator slot deviations | No runtime binary and no game executable; the package has no queue, fence or allocator client, and its only command-list client is the BVH builder. | | Builder's list field `+0x350` | Read once (`0x1d877`) and not explained by the inline buffer of section 3.5a, which covers `+0x18`, `+0x28`, `+0x30`, `+0x140`, `+0x141`, `+0x344` and `+0x544`. | diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index c9b15c42ae..722ff3a11d 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -91,7 +91,21 @@ enough for the bundled middleware's `d3d12_xs` calls, not for the game. The laye slot 62 where the PC interface it forwarded to presents `CreateStateObject` (different arity), and descriptor-heap start handles returned in RAX at heap slots 9/10. Implement the public chain plus those measured overrides explicitly; do not assume every slot. On the retail executable's higher device slots (`runtime/shims/d3d12_xs_device.cpp`), - slot 86 routes `CreatePipelineState(desc, riid, out)` to PC slot 47 (`ID3D12Device2::CreatePipelineState`), + slot 86 routes `CreatePipelineState(desc, riid, out)` to PC slot 47 (`ID3D12Device2::CreatePipelineState`) and keeps + a deep copy of the stream on the PSO it returns; slot 55 (`CreateDerivedPipelineState(pBasePSO, n, pRecords, riid, + out)`, `n` = 1..4 records of 0x14c bytes: a u32 tag, then the payload at +4) patches a copy of that stream and creates + the PSO through the same path. Tags 0 (`D3D12_DEPTH_STENCIL_DESC`, on DEPTH_STENCIL or DEPTH_STENCIL1), 1 + (`D3D12_RASTERIZER_DESC`), 2 (`D3D12_BLEND_DESC`) and 3 (sample mask) are the TomBox layout (GPL-3.0, + `create_derived_pso_x`), checked against the title's record writes in the retail build: tag 1 is the + rasterizer (0x2c bytes, always record 0 when present), tag 0 the DEPTH_STENCIL (0x34), tag 2 the BLEND (0x148). Tag 3 (sample mask, from TomBox) + is served although that function does not write it. Tag 5 (0x16 bytes: 16 zero bytes, then the StencilReadMask and + StencilWriteMask bytes at the DEPTH_STENCIL offsets 0x10/0x11, then zeros) overlays only those two bytes of the base's + DEPTH_STENCIL or DEPTH_STENCIL1, in record order; this is inferred from the title's writes, not measured at run time. + Any other tag, or a base that + was not created through slot 86/55, is refused (`E_INVALIDARG`/`E_FAIL`, null output). The stream + copy lives in `runtime/shims/d3d12_xs_pso_stream.cpp` and goes with the PSO (private data, released with it), + `D3D12_PIPELINE_STATE_SUBOBJECT_TYPE` values that the module does not walk (VIEW_INSTANCING) are not kept, + so a PSO built from them is refused as a base, slot 101 routes `CreateStateObject(desc, riid, out)` to PC slot 62 (`ID3D12Device5::CreateStateObject`), and slot 108 routes `GetResourceAllocationInfo2` (accepting the console C-ABI struct return with the return buffer in `RCX` and the device in `RDX`, expanding 56-byte `D3D12_RESOURCE_DESC` entries to `D3D12_RESOURCE_DESC1` and @@ -176,7 +190,7 @@ The command-list surface maps to the IR as follows: | `SetGraphicsRootSignature` / `SetComputeRootSignature` | state; select the pipeline layout and root map | | `Set*Root32BitConstant(s)` / `Set*Root*View` / `Set*RootDescriptorTable` | update root args; build the push-constant block at the draw/dispatch | | `SetDescriptorHeaps` | state; scan/populate the bindless arrays and hash table at execute | -| `IASetVertexBuffers` / `IASetIndexBuffer` / `IASetPrimitiveTopology` | state; bind arena buffer + offset, dynamic topology | +| `IASetVertexBuffers` / `IASetIndexBuffer` / `IASetPrimitiveTopology` | state; bind arena buffer + offset, dynamic topology. The console's rectangle list (17, PSO topology type 19) and quad list (19) are drawn as triangles, see *Console rectangle and quad lists* below | | `RSSetViewports` / `RSSetScissorRects` | state; dynamic viewport/scissor | | `OMSetRenderTargets` / `OMSetBlendFactor` / `OMSetStencilRef` | state; rendering scope and dynamic state | | `DrawInstanced` / `DrawIndexedInstanced` | command with a state snapshot | @@ -459,7 +473,15 @@ What is implemented (all of it testable without the game): are logged and refused until the trace shows what the game asks (question 11); - Single-sampled `A8_UNORM` 2D textures use one byte per texel in `VK_FORMAT_R8_UNORM`. Their SRVs expose (0, 0, 0, A) before applying the caller's component mapping. Format support includes `MIP` when the Vulkan - image supports multiple levels. Render-target, depth-stencil and UAV creation are unsupported for this format. + image supports multiple levels. Where the GPU has `VK_FORMAT_A8_UNORM_KHR` (`VK_KHR_maintenance5`) and can + sample, copy and blend it as a colour attachment, a texture created with `ALLOW_RENDER_TARGET` is stored in that + format instead: its RTVs, PSO `RTVFormats` and clears use the alpha channel, its SRVs view it in the same format + (the T# names its one channel X, gfx10's `channels_a`), and format support adds `RENDER_TARGET` and + `BLENDABLE`. Vulkan puts A8 in a compatibility class of its own, so the two kinds of A8 texture cannot share + an image. A castable-format list naming `A8_UNORM` itself is a no-op; any other format in it is refused with + `E_INVALIDARG` for such a render target, since no other format can view its image. Without that format, + render targets are refused as before; depth-stencil and UAV creation are + unsupported for this format. - reserved resources and `GetResourceTiling` (section 4.2); - query heaps for occlusion, timestamps and pipeline statistics, and `GetTimestampFrequency` on the queue (section 4.6); @@ -617,6 +639,9 @@ side inwards: covers a full 2048-sampler D3D12 heap plus room for literal and static S#s. - 2D images: up to 65536. - storage arrays: up to 4096 each. + - 2D-array images up to 16384, 3D and 1D images up to 4096 each (the title streams more cube maps, texture + arrays and 1D lookups than the defaults hold: each distinct T# of one takes its own index, and a native boot + filled the 1024 2D-array and 256 1D indices during the story load). Growth leaves 64 descriptors of each limit to the other sets of a pipeline layout. It also stays within `maxPerSetDescriptors`, which never shrinks the default counts, because a layout past it may still be @@ -631,9 +656,9 @@ side inwards: the last free index, `CreateShaderResourceView` and `CreateSampler` log once that the array is full, and a shader reads the fallback. `d3d12_descriptor_test` then fills each short array to its last index and checks that the next view and sampler are refused. - The other arrays keep their default counts. On an RTX 5070 (driver 621.24, 1048576 of each type - and 4000 samplers) the set has 65536 2D images, 3936 samplers and 4096 storage indices in 2D: 93793 - descriptors, 3-6 MiB at 32-64 bytes a descriptor. The device prints the counts it chose, and + The MS arrays keep their default counts. On an RTX 5070 (driver 621.24, 1048576 of each type + and 4000 samplers) the set has 65536 2D images, 3936 samplers, 16384 2D-array, 4096 3D and 4096 1D images and + 4096 storage indices in each dimension: 152929 descriptors, 5-10 MiB at 32-64 bytes a descriptor. The device prints the counts it chose, and `bindless_sizing_test` checks the rules on synthetic limits. - An image has one index in its dimension (2D, 2D array, 3D, 1D, 2DMS or 2DMS array), shared by the bindings for that dimension. The runtime adds sampled-image bindings in pairs for 2DMS and 2DMS array: @@ -751,7 +776,16 @@ D3D12 queue of the device is made in `info.queue_family`. And at most 8 retired next flush waits (logged once, with the descriptor lock released) for the submissions up to the oldest one's ticket, which is a wait for those queues' timelines and not for the device. The commit of a submit's result runs under `tracker_mutex_`, so a later flush never sees an earlier submit's outcome unrecorded. If the new generation cannot be -made (out of memory) the flush leaves the in-use set and the pending writes alone and fails. +made, the submission still goes ahead. A table buffer that finds device-local memory full goes to host-visible +memory (slower lookups, logged once). A freed generation is kept as a spare (at most one) and reused, pool and +buffers, by the next replacing flush, so steady texture churn allocates nothing. Failing that, the flush frees the +generations that have completed and retries; when every submission is done it rewrites the current table in place; +and otherwise it degrades: the pending descriptor writes go in place as on a flush that replaces nothing (they name +new or freed indices), the table keeps what it had, so keys added since read the fallback, and the change waits for +a later flush (logged at the first and each power of two, with what could not be made). It used to fail, and +`ExecuteCommandLists` refused the whole batch, which the title treats as fatal (a native boot died that way in the +story load once device-local memory was full). `vk_bindless_grow_test` covers the churn, the host fallback, the +in-place rewrite and the degraded flush, with allocations failed on purpose. Two bindless hazards that vkd3d-proton documents for games and that this change does not remove: descriptors written for resources allocated after the submit that reads them, and an image and a buffer descriptor aliasing one heap slot (vkd3d-proton PR #3033, https://github.com/HansKristian-Work/vkd3d-proton/pull/3033). Future path, not @@ -1046,7 +1080,10 @@ the game's present entry point (`PresentX`; the DXGI factory/swapchain and the p 1000 shaders of that stage): `[rt] d3d12: () is a 64-wide shader but this device cannot require that subgroup size ...`. For compute and mesh the fix is the build, `--wave64-emulate` (`make_game.py --wave64-emulate auto` picks it for this GPU); a wave64 vertex, geometry or pixel shader has no emulation yet - (the ~10,000 wave64 pixel shaders are the open case on NVIDIA, SHADER-10). + (the ~10,000 wave64 pixel shaders are the open case on NVIDIA, SHADER-10). A wave64 VS/PS/GS whose index entry + carries `wave64_graphics` tier A or B is not logged as inexact: the line says it runs at the device's size and + that the translator's partition-invariance analysis puts it in that tier, since cutting its wave into two 32-lane + halves does not change its results (tier C and entries without the analysis keep the conservative line). - **Test:** `subgroup_size_test` (CPU) checks the decision against AMD-like, NVIDIA-like and old-RADV properties and the resulting create-info chain; `d3d12_subgroup_test` (GPU) runs `cs_w64x_readlane` natively and with `--wave64-emulate`, and `cs_wqm_w32`, through D3D12 PSOs and compares the read-back words. @@ -1263,8 +1300,8 @@ and any validation error fails them. each one's synthetic FSSM program (`; fssm-at` / `; fssm-data` in the header) to `fssm/` and the translator puts its SHA-256 in `spirv/index.json`, so the layer's lookup is the one the game uses; the test loads that index as it is. An unknown program is refused. - - **User data:** root parameter 0 is a descriptor table (`s0:s1`, the VA of its first slot), parameter 1 four root - constants (`s2..s5`: the draw's clip offset, and a bias for the PS). + - **User data:** root parameter 0 is a descriptor table (`s8`, the 32-bit VA of its first slot), parameter 1 four + root constants (`s9..s12`: the draw's clip offset, and a bias for the PS), in the console's graphics layout. - **Vertex fetch:** the VS has no input layout. It `s_load`s a V# the application wrote into a shader-visible slot and fetches position and colour with `buffer_load_dwordx4 ... idxen`; the V# points at a DEFAULT-heap buffer in the arena. - **Code base:** the PS starts with `s_getpc_b64` and `s_load`s four floats from offset 0x100 of its own FSSM program, @@ -1535,6 +1572,66 @@ Arena VAs (at most 4095 MiB, so 32-bit) pass. A VA biased from outside the arena VAs above are at or above 2^40 as unsigned values. That is one more reason for the rule above that every buffer a console client can address is an arena range, whichever heap it comes from. +**Title-chosen addresses.** Two kinds of buffer address are the title's choice, not the layer's: +- device slot 133 (`CreatePlacedResourceX`) puts a buffer at the CPU address of the title's own pages; +- the title points root views and V#s at its own memory, for instance a per-frame constant ring (#8862, section + 3.5 of `docs/retail_boot_chain.md`). + +On Windows these are user-mode addresses far above 4 GiB, past the arena (at most 4095 MiB, and descriptor +tables must stay below 4 GiB), so `heap_base + VA` names nothing the layer made (the D3D-53 failure above). The layer +therefore replaces such an address, wherever it sees one, by the console VA of a GPU copy of that memory +(`runtime/src/title_va_alias.h`): + +| Where the address is | When it is replaced | +|---|---| +| Root CBV/SRV/UAV (`Set*Root*View`) | when the argument is set | +| CBV and buffer SRV/UAV V#s the layer writes (`Create*View`, slot 70, counter V#s included) | when the descriptor is written | +| Buffer V#s the title writes into a shader-visible CBV/SRV/UAV heap itself | before each `ExecuteCommandLists`, in place, for the tables the submitted lists bind and only the slots their root signatures declare | + +The copies: +- A **slot-133 buffer** whose pages cannot be imported is the per-submission shadow, and the shadow is an **arena + range** when it fits. Its console VA is its arena offset, which holds in a root argument, in a V#'s 48 bits and in + a 32-bit table pointer alike. Without room in the arena it keeps its own memory and is biased like an upload buffer + (logged once; raise `LEONIDA_ARENA_MB`). An **imported** slot-133 buffer is reached at its device address minus + `heap_base` (mod 2^64): exact for root arguments, and for a V# only when the driver put the import above the arena + (logged once otherwise). +- Any **other address in the title's memory** gets a window: the 64 KiB-aligned pages it covers, clipped to the + title's range, copied into the arena now and before every submission, through the same shadow refresh as slot 133 + (so dirty-page tracking for that refresh applies to both). Windows stay until the device goes, up to + `LEONIDA_TITLE_WINDOWS_MB` (64 MiB by default). A window that + cannot fit between the title's address reservations can use a separate mapped buffer. The buffer's device address + must fit as a positive 47-bit offset from the arena base. The same window cap and dirty-page refresh apply. + `LEONIDA_STREAM_BUFFER_WINDOWS=0` requires the window to fit in the arena. +- `LEONIDA_GEOMETRY_MB` sets the device-local memory cap for streamed buffer views. The default is 0. + A positive cap enables persistent copies of placed buffer SRVs and buffer descriptors in title memory. + A GPU-only reservation uses its paired CPU mapping. Matching source ranges share one copy. + The resource descriptor heap keeps its console indices and original CPU bytes. Its shader-visible copy + encodes each resolved buffer's offset from the arena base. CPU writes through either physical mapping, + file reads and XMem remaps invalidate the affected copies before their next submission. + During an untyped heap scan, an extent above 16 MiB with no format or an unrecognized descriptor + encoding reuses only an independently established geometry view. An explicit table or placed SRV can + establish that view. The Vulkan memory probe reports populated views, payload and reserved bytes, + upload totals, cap refusals and allocation failures. +- **Which pages changed** since the last refresh: where xmem reserved the title's memory with `MEM_WRITE_WATCH` + (`XMemVirtualAlloc`'s ordinary regions and the title's `VirtualAlloc` reservations, not placeholders or + physical-page windows), the kernel says (`GetWriteWatch` with reset, its answers kept for every copy over the page: + `leonida::title_write_watch` in `runtime/src/title_page_watch.h`); elsewhere a copied page is made read-only and the + title's first write faults (`ShadowPages`). `LEONIDA_WRITE_WATCH=0` guards everything; under Wine that is the + default and `=1` turns write watching on. A reservation the title releases and reserves again (at the same address + too) is new to every copy, all of it taken as written once. The title's own `XMemGetWriteWatch` and + `XMemResetWriteWatch` refuse a reservation write-watched for the copies, as the host refuses one that isn't. The + write-fault handler waits for the trackers' locks while the faulting thread may hold the process heap's lock (the + title's `XMemAlloc` blocks are `_aligned_malloc`'s), so the state changed under those locks allocates from a heap of + the runtime's own (`leonida::host_heap`), never the process heap. +- **Only the title's memory** gets a copy: the blocks and ranges the xmem shims hand the title (`XMemAlloc`, + `XMemAllocDefault`, `XMemVirtualAlloc`, the title's `VirtualAlloc`). An address anywhere else, the runtime's or a + host DLL's memory included, is left as it was and counted, as is an arena VA or a buffer the layer made. + +The title's own VA is still what `GetGPUVirtualAddress` answers, and vertex, index, copy and immediate-write calls +still resolve it through the buffer VA index, which knows slot-133 buffers by that VA. The copies are one way: what +the GPU writes into a copy does not reach the title's pages. A pointer the title hides elsewhere (a raw VA inside its +constant data that a shader dereferences) is not seen by the layer and keeps the title's VA. + Why not give each buffer its own BDA and set `heap_base = 0`? Because 25,865 of the 26,503 shaders (97.6%) truncate descriptor-table pointers to 32 bits, and host BDAs are not guaranteed to be below 4 GB. The arena keeps console VAs low and stable. @@ -1618,8 +1715,28 @@ The game can use D3D12 descriptors in three ways, and the layer must handle all translator input. No stride is read at run time: static offsets of T# loads are multiples of 32 and of S# loads multiples of 16, so the stride is compiled into the code. In the runtime shim, `CreateRootSignature` records the `CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED` and `SAMPLER_HEAP_DIRECTLY_INDEXED` root-signature flags and `SetDescriptorHeaps` - tracks the bound shader-visible heap GPU bases (`d3d12_set_descriptor_heaps`), while placing those bases into - per-stage user SGPRs remains open on question 3. + tracks the bound shader-visible heap GPU bases. A matched compute root signature and dispatch settle the + resource base for the Prop and Tree BatchCull programs. Their two explicit tables and one constant occupy + s4, s5 and s6. Both programs read the resource heap from s7, the next user dword. Supply its arena-relative + byte address in push-constant dword 7. The shader zero-extends this dword and adds the 32-bit resource + index shifted left by five. A 32-byte slot contains a four-dword buffer descriptor or an eight-dword image + descriptor. The host arena BDA remains in dwords 32–33. A matching runtime trace found s7 zero with the + resource heap bound. The PreSkin compute programs use s9. Graphics examples with resource-direct indexing + include PS_NoStripImmutableTable at s11 and VS_TransformD at s12. Their shader inputs establish the + destination dwords. The explicit graphics layouts and ordering for signatures with spills still need + independent root-signature evidence. + The runtime snapshots the bound resource and sampler heap pointers in that order after the explicit + arguments for direct and indirect compute dispatches with an inline signature. Set + `LEONIDA_COMPUTE_DIRECT_HEAPS=0` to restore the previous compute arguments. + Draws do the same in the graphics layout (`pack_stage(Stage::Pixel)`, from s8, one dword per table): the + resource heap's 32-bit shader VA goes in the dword after the explicit arguments, then the sampler heap's, each + only when the signature has its flag, snapshotted per draw. Vertex, pixel and geometry shaders share one + user-data block and that layout, so one write serves all three; a signature whose explicit arguments take + s8..s10 gives s11, one whose arguments take s8..s11 gives s12 (the two program reads above). A mesh shader reads + its arguments from s16, which is not modelled, so in a mesh pipeline only the pixel shader gets the heaps. A + signature that keeps the s0 graphics layout, or whose arguments fill s31, gets none (logged once). + `d3d12_graphics_direct_heaps_test` checks the recorded draws and what a vertex and a pixel shader read, with + and without the flags. Set `LEONIDA_GRAPHICS_DIRECT_HEAPS=0` to restore the previous draw arguments. 3. **Game-built descriptor memory.** The game writes raw T#/S# bytes into a heap itself, without calling `CreateShaderResourceView`. The shaders then read those bytes exactly as in case 1. @@ -2079,6 +2196,27 @@ Pipeline creation: and pipeline-cache UUID. When the file is absent or incompatible, the runtime starts with an empty cache. The offline checker matches the runtime's layout and subgroup request for compute shaders with no descriptor bindings and the standard 144-byte push-constant range. + The runtime writes its own `pipeline_cache.session.bin` on device teardown. A compatible session file + initializes the live cache directly if there is no offline seed. With both files present the session cache + merges into the offline seed. `LEONIDA_DIRECT_SESSION_CACHE=0` also uses a merge when only the session exists. + The files must match the Vulkan vendor, device and pipeline-cache UUID. Vulkan supplies an opaque snapshot. + Replacing part of the previous file would corrupt it. + `LEONIDA_PIPELINE_CACHE_BYTES` caps session writes (256 MiB by default, zero disables the session file). + `LEONIDA_SKIP_COMPUTE=[,...]` (`all`: every compute program) never builds the matching + compute programs and drops their dispatches, direct and indirect; the first dropped dispatch of each is logged. + It is a way past a program that hangs the GPU while the program or its input is fixed, not a fix. + `LEONIDA_STARTUP_CACHE_CHECKPOINTS=1` also schedules a snapshot after a successful pipeline build, + at most once per 120 seconds. It starts on the compile worker when queued builds have drained and the device + has no active builds. These snapshots have an additional 512 MiB ceiling. The driver fills a mapped staging + file directly. A successful snapshot atomically replaces the session. An interrupted write preserves the + previous cache; the next launch removes unheld staging files older than ten minutes. + `LEONIDA_TRACE_PIPELINE_COMPILE=1` records each graphics and compute build's trigger, thread, elapsed time, + SPIR-V size, shader names and Vulkan application-cache feedback (1 hit, 0 miss, -1 unavailable). It also + times cache reads, merges, writes and draw/dispatch pipeline lookups that take at least 1 ms. + `LEONIDA_ASYNC_PIPELINES=1` schedules cold first-use builds on the warm-up worker ahead of speculative work. + Replay skips a draw or dispatch while its pipeline is pending. Later uses find the completed handle. + A skipped dispatch can lose a one-time resource update. Synchronous first use is the default and strict + replay always uses it. `LEONIDA_COMPUTE_WARMUP=0` restricts the worker to pipelines requested by the title. `GetCachedBlob` records the vendor, device, driver version, `pipelineCacheUUID` and a SHA-256 of the description without `Flags`, sealed by a checksum (`runtime/src/cached_pso.h`). The answers are the host's, measured on an RTX 3060 and WARP: the same description is accepted; another @@ -2113,6 +2251,16 @@ The trace will enumerate them. - **Streams:** `CreatePipelineState` parses the stream in the d3dx12.h layout: a subobject type, then its description at that description's alignment, each subobject pointer-aligned. - Every type up to `RASTERIZER2` is read. + - The Vulkan backend selects console numbering when the PC reading fails or gives AS without MS and the + console reading has a verified DXIL kind-13 mesh stage. Slot 86 keeps that selected layout with canonical + tags and owned shader bytes so slot 55 can derive another PSO. `LEONIDA_XS_STREAM_ENUM=pc` selects PC only. + - With D3D12 tracing, each unsupported stream has one `PipelineStream::Refused` reason. Accepted mesh PSOs + have a separate `PipelineStream::Mesh` count. `LEONIDA_PSO_STREAM_AUDIT=1` also prints raw tags, + shader stages and FSSM hashes for unsupported or failed streams. The call number joins to the backend result. + - `LEONIDA_PSO_PROFILE=1` measures wall time and calling-thread CPU time for each Vulkan pipeline creation. + Begin and end records share an ID. + Compute records distinguish warmup, dispatch and eager creation. Graphics records name the lazy recipe's + stages and unbound attachment mask. Mesh draw totals are reported per command buffer with its submit result. - Missing subobjects take the runtime's defaults: depth test on with `LESS`, back-face culling, no blending, sample mask `0xFFFFFFFF`, one sample. - The stream becomes the same descriptions `CreateGraphicsPipelineState` and `CreateComputePipelineState` take, so @@ -2141,6 +2289,12 @@ The trace will enumerate them. - **What it doesn't cover:** whether the console flattens a 3D `DispatchMesh` grid the same way. That is an open question in `docs/design.md`, "Mesh shaders"; the test shader reads the workgroup ID directly. +### Console rectangle and quad lists + +The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiveTopology(17)`, with a PSO whose topology type is 19) and quad list (`IASetPrimitiveTopology(19)`). The facts are from xvalkyrie (GPL-3.0, commit `53af7df77c10`; no code taken): a rectangle is three corners and the fourth is v2 + v3 - v1 for the position and every interpolant, after the vertex stage; a quad is four vertices. The layer draws both as triangles (`d3d12_rect_list_test`, RTX 4090: 4096 of 4096 pixels, the colour plane exact, quad list bit-exact). +- **Rectangle list**: PSO type 19 builds a triangle-list pipeline plus a generated geometry stage (`src/rect_list_geometry.h`, written from the vertex shader's own outputs) that takes the three corners and emits the strip v1 v2 v3 v4 (same winding). It has to be post-vertex-stage: the translated vertex shaders fetch by V# themselves, and the fourth corner is a function of what they write. A corner value with the same bits at all three corners (a flat attribute) is copied. Needs `geometryShader` (else `E_NOTIMPL`), no application GS, and a vertex shader with no ClipDistance, CullDistance, Layer or ViewportIndex output. +- **Quad list**: one four-vertex triangle fan per quad (the pattern 0 1 2, 0 2 3). The translated vertex id is `VertexIndex - BaseVertex`, so each fan reads the index values 4q..4q+3: from the application's index buffer when the draw is indexed, else from a shared 0, 1, 2, ... buffer in the arena's reserved pages (16384 quads per draw at most, more are cut off with a log line), with the draw's first vertex as the vertex offset. A quad's instances are drawn together, so several overlapping blended instances rasterize quad by quad rather than instance by instance. The PSO type is the ordinary triangle type. + ## 4. Object model mapping | D3D12 / Xbox object | Vulkan / layer object | Notes | @@ -2504,6 +2658,29 @@ The trace will enumerate them. - `Map`/`Unmap`: upload/readback buffers map their host-visible memory; default-heap resources return `E_INVALIDARG` as D3D12 does. A texture in a CPU-visible custom heap maps only with a null pointer (its layout is the driver's), as on D3D12. +- GPU-writable slot-133 images on a default heap bind memory when replay, presentation or creation of a shader + view first needs their Vulkan image. D3D12 placement and logical attachment views can precede that bind. + A CPU-fillable, typed BC texture can initially sample an immutable zero image of the same format, extent, + layer count and mip count. A CPU upload or explicit GPU command gives the placement private backing and + republishes its existing descriptor keys. The cache holds at most 256 MiB. `LEONIDA_PLACED_IMAGE_DEFER=0` + restores eager binding. +- A slot-70 sampled texture whose source pages are unreadable reserves its image backing on the first + complete CPU read. Copies of descriptors written earlier resolve to the fallback until that upload succeeds. + `LEONIDA_TITLE_IMAGE_DEFER=0` allocates these textures eagerly. The memory probe reports the live unbound + image count and its Vulkan memory requirements in MiB. +- Small optimal Vulkan images synthesized for slot-70 texture views share memory pages. Each slice meets the + image's size, alignment and memory type requirements. The GPU retirement queue destroys the image before its + slice can be reused. Large images, dedicated-only images, and failed pool allocations use individual memory + allocations. `LEONIDA_TITLE_IMAGE_POOL=0` selects individual allocation for every image. With + `LEONIDA_MEM_PROBE` enabled, the texture census also reports logical Vulkan backing bytes for the registered + slot-70 and slot-133 images and the portion on non-device-local types. +- Sampled title images can use device-local memory even when Vulkan host image copies require a + host-visible memory type. The runtime queries the same image with and without host-transfer usage. + When only the latter permits plain device-local backing, it detiles the complete image into a reusable + staging buffer and transfers all its mips and layers together. Linear slot-133 placements retain host + copies. An allocation failure retries the original host-copyable image. `LEONIDA_TITLE_IMAGE_STAGING=0` + restores the original placement policy. With `LEONIDA_MEM_PROBE`, each title image class logs its + Vulkan memory type mask, mask without host transfer, and selected type. - `WriteToSubresource`/`ReadFromSubresource` (implemented in `d3d12_vulkan_device.cpp`) complete before they return, as D3D12 requires; a read cannot wait for a later submit. Textures in CPU-visible custom heaps are created with `VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT` when the device supports that usage with the requested @@ -2707,6 +2884,9 @@ The trace will enumerate them. ### 4.3 Barriers and layouts +Plain buffer copies order earlier transfer writes on the same queue before reading or writing the next range. +Set `LEONIDA_ORDER_BUFFER_COPIES=0` to omit this dependency when comparing replay behavior. + Track a current state/layout per subresource. D3D12 states are bitmasks; a combined state takes the union of the mapped stages/accesses, and if no single layout serves all uses, use `GENERAL` and log it. Legacy `D3D12_RESOURCE_STATE_*` maps to a (stage, access, layout) triple: @@ -2760,6 +2940,10 @@ mapped stages/accesses, and if no single layout serves all uses, use `GENERAL` a exact). Run on an RTX 4070 Ti (NVIDIA 620.70.06, Linux): part L natively with the validation layer 1.4.363 and no error, where the same barriers with `newLayout = UNDEFINED` give VUID-VkImageMemoryBarrier2-newLayout-01198 four times; the D3D12 tests under Wine. +- A rejected recording call logs ` rejected a call (d3d12_com.cpp:)` the first time each call site + rejects one (Barrier and CopyTextureRegion also print their arguments), and a batch the queue's replay refuses + logs `queue replay refused a batch at vulkan_backend.h:`, so a failed `Close` or + `ExecuteCommandLists failed: unsupported` names its cause. - `DiscardResource` (D3D-26): each discarded image subresource gets a barrier from `oldLayout = UNDEFINED` to the layout the tracker already has for it, so the driver may drop the contents while later commands see no layout change. The other cases are no-ops, which "contents undefined" allows: buffers, discards with rectangles (only @@ -3659,6 +3843,30 @@ Games and middleware call these every frame (PIX events), so they must be cheap changes nothing (`E_INVALIDARG`). Before #2533 the layer stored the name under a mistyped GUID. Names are not forwarded to `vkSetDebugUtilsObjectNameEXT` yet: one D3D12 object may own several Vulkan objects. +### 4.11 Vulkan device-loss diagnostics + +Set `LEONIDA_DEVICE_FAULT=1` before creating the runtime's Vulkan device to enable the supported device-fault and +NVIDIA checkpoint extensions. On the first observed device loss, stderr logs driver fault addresses, vendor data +and binary size, plus the checkpoints reached on each queue. Checkpoints identify the replay submission, its +original `ExecuteCommandLists` call, the zero-based list and command indices, and the most recent shader names +in that list when available. A checkpoint shows progress at a reported pipeline stage and can help narrow down +the faulting work. The loss report also lists the last 64 compute dispatches submitted across queues, including +direct group dimensions or indirect argument-buffer locations, even without driver checkpoints. These entries show +submission order. Set `LEONIDA_DEVICE_FAULT_ROOTS=1` to include each dispatch's 32 recorded root words in the local +diagnostic log. While this mode is enabled, a host thread samples the submission timelines once a second. If the +retired ticket stays behind submitted work for 15 seconds, it prints the CPU dispatch history. It also reports +when it cannot sample the submission lock for that long. A progress warning leaves D3D12 fence values and the +device state intact. The driver checkpoint and fault-info queries run after Vulkan reports device loss. This mode +is off by default. + +For a local pre-submit inspection, also set `LEONIDA_COMPUTE_INPUTS` to comma-separated shader name fragments and +`LEONIDA_COMPUTE_INPUT_SLOTS` to comma-separated decimal `root/slot` pairs. For example, `4/86,5/0,5/2,7/0` reads +four 32-byte descriptors. The probe logs the bound heap and root layout, the saved user SGPRs, observed descriptor +writer, buffer address, stride, record count and readable backing. It also follows the per-group scene indices of +the Prop and Tree cullers when both `5/0` and `4/86` are selected. Each sample is taken after CPU-side shadow +refresh and before queue submission. Earlier GPU writes may still be in flight. An imported heap can have a valid +shader offset beyond the arena. Keep probe output local. Unset `LEONIDA_COMPUTE_INPUTS` to disable it. + ## 5. Producing the shader contract The table below is the contract from [design.md](design.md#translator-status-and-runtime-contract) and where the @@ -3696,6 +3904,12 @@ struct entry { // 10 uints = 40 bytes ``` - Hash: FNV-1a over the eight key dwords as dwords (not bytes): `h = 2166136261; h = (h ^ key[i]) * 16777619`. +- Optional finalizer (`fnv1a_fmix32`): a module whose `index.json` meta says `"descriptor_hash": "fnv1a_fmix32"` runs + MurmurHash3's `fmix32` on that word before probing (`h ^= h >> 16; h *= 0x85EBCA6B; h ^= h >> 13; h *= 0xC2B2AE35; + h ^= h >> 16`, logical shifts). An absent key means bare `fnv1a`. `DescriptorTable` fixes one kind per table before its + first insert, taken from the modules' metas: all agree is that kind, mixed is the majority (the minority's lookups miss + to index 0), and `LEONIDA_DESCRIPTOR_HASH=fnv1a|fnv1a_fmix32` overrides. The two kinds' shared vectors are in + `runtime/test/descriptor_table_test.cpp`. - Probe: `slot = (h + k) & mask` for `k = 0..7`; the first entry whose eight key dwords match yields its `index`; no match yields 0. - The layer must keep the table sparse enough that no live key needs more than eight probes. When all eight slots are occupied, @@ -4310,8 +4524,9 @@ on a PC device behind the Xbox-ABI proxy). Measured: - `amd_fidelityfx_loader_xbox.dll`, `Bink2Scarlett.dll`, `libHttpClient.GDK.dll`, `XCurl.dll`: no `d3d12_xs` imports. -- The package layout XML, chunk 1001, lists `game_scarlett_master.exe`; the file is absent from the folder. No - claim in this document depends on the executable's contents. +- The package layout XML, chunk 1001, lists `game_scarlett_master.exe`; the file is absent from the folder. One + claim in this document comes from running the executable from a player's own copy: how it calls device slot 26 + (section 4.1; register roles and argument values only). No other claim depends on the executable's contents. - The repository's existing import survey (`docs/design.md`, "Baseline already recorded") records that the 16 bundled DLLs need only `xmem` and the two `d3d12_xs` root-signature calls; our scan of the six non-CRT DLLs is consistent. diff --git a/docs/d3d12_xs_console_abi.md b/docs/d3d12_xs_console_abi.md new file mode 100644 index 0000000000..e1ec05fc7d --- /dev/null +++ b/docs/d3d12_xs_console_abi.md @@ -0,0 +1,279 @@ +# The D3D12.X console ABI: vtable slots, object fields and record encodings + +Status: measured-facts note, sourced. This page collects the Xbox Series (`d3d12_xs`) ABI facts a +replacement runtime must reproduce — vtable slot numbers, object field layouts and the inline +record encodings the console SDK writes into a command-list object — for the layers that are still +missing: command lists, root arguments, descriptor heaps and present. It complements +[d3d12_vulkan.md](d3d12_vulkan.md) (the Vulkan layer plan) and +[d3d12_command_objects.md](d3d12_command_objects.md) (what this package's own DLLs measure). + +Provenance rules for this page, stated once: + +- **Sibling layer** — measured by a sibling open-source layer on retail Series titles and + published as findings. Not independently reproduced here; treat every such claim as unverified + on this package. +- **Package** — measured on this package's shipped DLLs (`XboxBvhBuilder.dll`, + `amd_fidelityfx_upscaler_xbox.dll`); see + [d3d12_command_objects.md](d3d12_command_objects.md) §§3.3–3.5a. +- **SDK** — the public Windows SDK `d3d12.h` order, for contrast. +- **Unconfirmed** — consistent with the surrounding facts but not yet measured anywhere we can + check. + +All slot numbers below are absolute vtable indices including `IUnknown` (0–2) and the +`ID3D12Object`/`ID3D12DeviceChild`/`ID3D12Pageable` base slots, as in +[d3d12_command_objects.md](d3d12_command_objects.md) §2. + +## 1. Device (`ID3D12DeviceX` over the PC `ID3D12Device` layout) + +The console device keeps the PC slot order where measured, with extra console methods placed in +slots the PC chain uses for newer interfaces, plus a tail of console-only methods. Slots marked +**Package** were called by the shipped upscaler or BVH-builder DLLs with the stated shapes; the +rest are **Sibling layer** measurements. + +| Slot | Method | Evidence | +|---:|---|---| +| 8, 48 | `CreateCommandQueue` variants | Sibling layer | +| 9 | `CreateCommandAllocator` | Sibling layer | +| 10, 60 | `CreateGraphicsPipelineState` variants | Sibling layer | +| 12 | `CreateCommandList` | Sibling layer | +| 14 | `CreateDescriptorHeap` | Package + sibling layer | +| 15 | `GetDescriptorHandleIncrementSize` | Package + sibling layer | +| 17, 18, 19 | `CreateConstantBufferView` / `CreateShaderResourceView` / `CreateUnorderedAccessView` | Package + sibling layer | +| 22 | `CreateSampler` | Sibling layer | +| 23, 24 | `CopyDescriptors` / `CopyDescriptorsSimple` | Package + sibling layer | +| 25 | `GetResourceAllocationInfo` | Sibling layer | +| 29, 44 | `CreatePlacedResource` variants | Sibling layer | +| 38 | `GetCopyableFootprints` | Package + sibling layer | +| 41 | `CreateCommandSignature` | Sibling layer | +| 52 | `SetDebugFlags` | Sibling layer | +| 55 | derived pipeline state | Sibling layer | +| 56, 57, 66, 67 | serialize / deserialize pipeline state | Sibling layer; the package's upscaler calls 67 as `DeserializeComputePipelineStateX` (console desc, `IID_ID3D12PipelineState`) — Package | +| 61 | `CreateSamplerX` | Sibling layer | +| 62 | `CreateComputePipelineState` with two extra args: `(desc, NULL, NULL, riid, ppv)`; the PC interface presents `CreateStateObject` at this slot | **Confirmed here**: Package ([d3d12_vulkan.md](d3d12_vulkan.md) §7) + sibling layer | +| 73 | `CreateCommandListX` | Sibling layer | +| 74, 75 | register / unregister page pool | Sibling layer | +| 76 | `CreateCommittedResource`, same signature family as PC slot 27 | **Confirmed here**: Package ([d3d12_vulkan.md](d3d12_vulkan.md) §7) + sibling layer | +| 78–81 | frame pacing: `SetFrameIntervalX`, `ScheduleFrameEventX`, `WaitFrameEventX`, `GetFrameStatisticsX` | Sibling layer | +| 86 | `CreatePipelineStateX` | Sibling layer | + +The slot-76 console resource descriptor is **larger than 52 bytes** (sibling layer); the package's +upscaler DLL writes a 3 at offset +52 (Package). The `Layout` field sits at +44; value `0x101` +denotes a 2D texture ([d3d12_vulkan.md](d3d12_vulkan.md) §7; a sibling layer measured the same on +retail titles). + +### 1.1 Two runtime layouts + +Two console runtime layouts exist: an older game-OS layout and a newer one in which the queue and +list slots shift **+2** (sibling layer). Detection rule (sibling layer): if a fence object is +passed to queue slot 16/17, the layout is newer — on the older layout those slots are +`GetTimestampFrequency`/`GetClockCalibration`. Which layout this package's titles were built +against is **unverified here**. + +## 2. Descriptor heap + +| Slot | Fact | Evidence | +|---:|---|---| +| 9, 10 | `GetCPUDescriptorHandleForHeapStart` / `GetGPUDescriptorHandleForHeapStart` return the 8-byte handle in `rax` on console; the PC convention is a hidden out-pointer | **Confirmed here**: Package + sibling layer | + +Descriptor contents (sibling layer): CBV/SRV/UAV heaps use **32-byte slots** in unified memory — a +T# is 8 dwords, a V# 4 dwords, inside the 32-byte slot; sampler heaps use **16-byte slots**. The +CPU handle, GPU handle and the address in title memory are the same value. + +## 3. Resource + +| Slot | Fact | Evidence | +|---:|---|---| +| 11 | `GetGPUVirtualAddress` returns the title-memory address | Sibling layer; consistent with the package measurement that a CPU pointer from list slot 148 is passed unchanged as a root SRV GPU address ([d3d12_command_objects.md](d3d12_command_objects.md) §3.3a) | + +## 4. Command queue + +Measured queue slots (sibling layer); the queue follows the two-layout rule of §1.1: + +| Method | Older layout | Newer layout | +|---|---:|---:| +| `Signal` | 14 | 16 | +| `Wait` | 15 | 17 | +| `GetTimestampFrequency` | 16 | 18 | +| `GetClockCalibration` | 17 | — (shifted) | +| `GetDesc` | 18 | — (shifted) | +| `SignalX` | 23 | 25 | +| `PresentX` | 30 | 32 | + +Console-only queue methods the layer does not model should return `S_OK` and log the call: +title frame pacing flows through some of them (sibling layer). + +## 5. Command list object + +Measured by a sibling layer with a fake list — a 600-slot vtable of logging thunks — that let the +console SDK's inline writers record into the object (sibling layer; the package's BVH builder and +upscaler independently measured `+0x18`, `+0x28`, `+0x30`, `+0x140`, `+0x141`, `+0x344` and +`+0x544` — Package, [d3d12_command_objects.md](d3d12_command_objects.md) §§3.4–3.5a). + +### 5.1 Object fields + +| Offset | Field | Evidence | +|---:|---|---| +| +0x00 | vtable pointer | Package + sibling layer | +| +0x18 | inline write pointer | Package + sibling layer | +| +0x28 | dispatch-record limit | Package + sibling layer | +| +0x30 | buffer end | Package + sibling layer | +| +0x140 | dirty flag byte, set when record header bits 31:30 are 0 | Package + sibling layer | +| +0x141 | pipeline flag byte, taken from bit 20 of the pipeline's record word at +0x20 | Package + sibling layer | +| +0x143 | flag byte; read by titles, written only by the runtime | Package (read 31+1 sites, never written) + sibling layer | +| +0x344 + 4·i | header word of root parameter *i* | Package + sibling layer | +| +0x544 | current pipeline record, 16 bytes | Package + sibling layer | + +### 5.2 Inline record encodings + +The console SDK's inline writers emit a record only while the write pointer is below the buffer +end; on a full buffer they call the vtable method the record stands for (Package + sibling layer). + +| Record | Encoding | Evidence | +|---|---|---| +| Pipeline | 28 B: `[PSO ptr][D3D12Core ptr][8 B flags][4 B]` | Package + sibling layer | +| Root parameter *i* | header at +0x344+4·i = `0xC0000000 \| i<<10` + const-offset·4 (bits 9:2) + `(count-1)<<16` | Sibling layer; header table itself confirmed Package | +| Root descriptor | header + 64-bit address = 12 B | Package + sibling layer | +| Root constants | one constant = 8 B; *n* constants = 4+4·*n* B | Package + sibling layer | +| Descriptor table | header + one 32-bit word = the 32-bit GPU address of the first descriptor | Sibling layer | +| `Dispatch` | `0x4002C400` (or `(0x1000BA00 \| flag) << 2`) followed by x, y, z = 16 B | Package + sibling layer | +| Indirect dispatch | `0x4003CC00`, 20 B total | Package (five-word form with W `0x8020`/`0x20`) + sibling layer | +| `IASetPrimitiveTopology` | `0xC000B600 \| topology` | Sibling layer | + +### 5.3 Method slots + +| Slot | Method | Evidence | +|---:|---|---| +| 9 | `Close` | Sibling layer | +| 10 | `Reset` | Sibling layer | +| 12 | `DrawInstanced` | Sibling layer | +| 13 | `DrawIndexedInstanced` | Sibling layer | +| 14 | `Dispatch` | Package + sibling layer | +| 15 | `CopyBufferRegion` | Package + sibling layer | +| 16 | `CopyTextureRegion` | Sibling layer | +| 17 | `CopyResource` | Sibling layer | +| 19 | `ResolveSubresource` | Sibling layer | +| 20 | `IASetPrimitiveTopology` | Sibling layer | +| 25 | `SetPipelineState` | Package + sibling layer | +| 26 | `ResourceBarrier` | Package + sibling layer | +| 32 | `SetDescriptorHeaps` | Package + sibling layer | +| 33 | `SetComputeRootSignature` | Package + sibling layer | +| 37, 39 | `Set*RootConstant(s)` | Package + sibling layer | +| 41, 43, 45 | `Set*RootDescriptor*` / table | Package + sibling layer | +| 48 | `IASetVertexBuffers` | Sibling layer | +| 51 | `ClearDepthStencilView` | Sibling layer | +| 80 | `ExecuteIndirect` | Sibling layer (note: the package measured slot 80 as a console-only call, a `Dispatch`-with-extra-word shape; slot assignments past 61 differ between the two sources — unconfirmed) | +| 83 | `CopyTextureRegionX` (older layout) | Sibling layer; the package measured a `CopyTextureRegion`-shaped call at slot 85 — consistent with the newer layout (+2) | +| 108 | `ResolveSubresourceRegion` | Sibling layer | +| 139 | `Reset(allocator, pso)` → PC slot 10 | **Measured here**: retail 1.0.2.1 (Pipodi) — the title creates a list, `Close`s at slot 9, then calls 139 with `(allocator proxy, 0)` before recording; the proxy unwraps the allocator and forwards to PC `Reset` | +| 146 | enhanced `Barrier` | **Confirmed here**: Package (console slot 146 takes one `D3D12_BARRIER_GROUP`; PC equivalent is GCL7 slot 80) | +| 148 | `AllocateUploadMemory` `(size, alignment)`; the returned CPU pointer is the GPU address in unified memory | Package + sibling layer | + +Layout shift on the list tail (sibling layer): from `CopyTextureRegionX` on, methods sit two slots +later in the newer layout — newer→older pairs 85→83, 86→84, 87→85, 90→88, 91→89, 92→90, 95→93, +96→94. + +The shim hands out console-shaped command lists by default: `GetCommandList`-shaped queries build +the proxy with the console vtable above. `LEONIDA_D3D12_LISTS=pc` makes it hand out PC-shaped lists +instead, for guests compiled against the PC headers (the `tiny_frame` test fixture calls through PC +vtable indices; without the variable its `ClearRenderTargetView` at PC slot 48 lands on the +console's `IASetVertexBuffers` and `Close` never runs). The device, queue, heap and fence stay +console-shaped either way. + +### 5.4 DMA command list + +| Slot | Method | Evidence | +|---:|---|---| +| 9 | `Close` | Sibling layer | +| 10 | `Reset` | Sibling layer | +| 11 | `CopyBufferRegion` | Sibling layer | +| 12 | `CopyTextureRegion` | Sibling layer | +| 13 | `CopyResource` | Sibling layer | + +## 6. Root arguments + +Sibling-layer measurements on retail titles: + +- **Compute.** The root arguments are a packed argument array in title memory; `io[0:1]` of the + dispatch record carries its address. +- **Graphics.** VS and PS receive root arguments in user SGPRs `s8..s31` — `s0..s7` are + driver-reserved; `s[4:5]` of a VS holds the fetch shader — 24 user SGPRs in total. Arguments + past those go through a table whose address is in `s[0:1]`. +- **Descriptor tables** take 4 bytes in the packed array: the record is the parameter header plus + one 32-bit word, the 32-bit GPU address of the first descriptor. +- **Root CBV.** The shader builds its own V#; a measured example sets `DST_SEL xyzw` plus the + format word from `s11`. + +## 7. Resource barriers (list slot 26) + +Sibling layer: console aliasing barriers behave as "any resource" barriers — both resource +pointers are null — where the PC API only allows those between placed or reserved resources. +Console-only state bits must be dropped before forwarding, or `Close` fails `E_INVALIDARG`. + +## 8. Unified memory + +Titles expect graphics memory where the CPU address equals the GPU address (sibling layer; +consistent with the package's slot-148 measurement in §3). + +- The sibling layer backs this with a fully-committed sub-4 GiB region at a 4 GiB-aligned virtual + address, opened via `ID3D12Device3::OpenExistingHeapFromAddress`. Measured limits: a partial + commit is rejected; a full 4 GiB is rejected; 4095 MiB works. +- For reservations above 4 GiB the measured technique is: reserve with `VirtualAlloc2` + `MEM_RESERVE_PLACEHOLDER`, split chunks with `VirtualFree` `MEM_PRESERVE_PLACEHOLDER`, back each + chunk with a `SEC_COMMIT` section mapped via `MapViewOfFile3` `MEM_REPLACE_PLACEHOLDER`. Each + chunk opens as its own heap with GPU/CPU coherence at the title's address. `SEC_RESERVE` + sections are refused even when fully committed. +- Buffers in unified memory are placed resources at 64 KiB alignment. A buffer at a + non-64 KiB-aligned console address is placed from the 64 KiB boundary below it and the copy + paths add the delta. +- `Map` of a unified-memory resource returns its console address. +- GPU-owned textures (resources with RT/DS/UAV flags) go into "arenas" — default heaps standing + for ranges of title addresses — because titles alias several textures at one address. + +## 9. `PresentX` + +Sibling layer: one frame is presented per console queue method call (`PresentX`, §4). The +presented back buffer is detected by tracking render-target binds (RTV creation and +`OMSetRenderTargets`) and `ExecuteCommandLists`. + +## 10. Shader-interface facts + +Measured on real console shaders by a sibling layer; where the claims overlap this repository's +translator docs they are mostly confirmed here. + +- An FSSM stage descriptor at +0x110 looks like `RSRC2`: `USER_SGPR` sits in bits 5:1 (e.g. + `0x18` → 12 SGPRs). A PS header carries an export-variant patch table from about +0x25C. +- User SGPRs (a compute example with 14 per `RSRC2`): `s4` = descriptor table 0, `s5` = table 1, + `s[6:7]` and `s[8:9]` = root CBVs; `s14`/`s15` = thread-group id x/y. +- Mesh-shader interface: `s3[27:24]` = wave index in the group, `v5` = group·128 + thread, + `s16..s24` = user data. +- Console GS runs on-chip: the ES writes vertices to LDS and `s_setpc`s to the GS. The GS writes + vertices to LDS at 64 B per vertex, base = `s2 + ([s8 + 0xB8] << 8)`, and uses `s_sendmsg` + emit/cut/done. No copy shader is present in the pack. +- `IASetPrimitiveTopology` value 17 is rectangle lists, drawn as two triangles on PC. +- Derivatives: console code computes cross-quad derivatives manually (DPP `quad_perm`, + `ds_swizzle`) and reads helper lanes. On PC, reads across quads need quad-aware lane reads: + `WaveReadLaneAt` leaves helper lanes out before SM 6.7, and enabling + `WaveOpsIncludeHelperLanes` caused a device hang in the sibling layer — whole-wave ballots then + never let helper lanes exit. +- A pixel shader doing `v_readfirstlane` after `s_wqm` can read a helper lane's value; the read + must take the value with a quad read inside its own quad plus a wave read from a live lane of + that quad. +- Memory model: a shared "mem" buffer used for flat accesses must be coherent + (`globallycoherent` on D3D12). Bottom-up BVH builds with atomics produce wrong child pointers + otherwise; console code relies on GLC/cache-invalidation semantics. +- ISG1 inputs a VS never reads get no fetch-shader VGPRs. + +## 11. Unverified here + +The sibling-layer measurements above were made on retail Series titles and that project's own +host runtime, not on this package or this layer. Still to be measured on this package: + +- **which runtime layout this title uses** — the older/newer detection rule of §1.1 needs a queue + call trace; +- **draw-record encodings for graphics** — only compute dispatches and copies were measured; the + graphics draw records and their sizes are unknown; +- the `PresentX` signature and plane struct (no signature is recovered anywhere; + [d3d12_command_objects.md](d3d12_command_objects.md) §4); +- queue/fence/allocator slots and the device creation slots 8/9/12/36 for the layout this title + uses ([d3d12_command_objects.md](d3d12_command_objects.md) §5.3); +- the exact newer→older slot pairs on the command-list tail beyond the measured set. diff --git a/docs/design.md b/docs/design.md index 2e0d0582a6..922b3c8151 100644 --- a/docs/design.md +++ b/docs/design.md @@ -84,6 +84,9 @@ This writes `reports/exe/` (JSON plus a readable summary). Check it in this orde `VERIFY` note of the runtime and the docs, with file and line. Notes in a shim whose class the exe calls are marked **called** and come first: those are the ones its first boot reaches, such as the `XStoreGameLicense` sizes. +7. **CPU instructions.** `python -I tools/cpu_feature_scan.py ` lists the instructions a desktop CPU may lack + (AMD-only, newer-Intel-only, privileged), with counts split by `.pdata` range. The retail executable has a few + AMD-only and CLWB sites that raise `#UD` on Intel hosts ([cpu_features.md](cpu_features.md)). Then `runtime\build\gta6rt.exe --dry-run ` maps the image and binds every import to the shim table without running any game code. It reports what it couldn't bind. @@ -274,6 +277,7 @@ How the generated SPIR-V expects the runtime to work: | Piece | Contract | |---|---| +| Heap-relative buffer device addresses | `Gen.host_addr` sign-extends the low 48 bits of the effective VA after adding any byte offset, then adds `%heap_base`. The runtime stores `device_address - heap_base` in a V#'s 48-bit base field. NVIDIA's Windows driver can place an imported buffer below the heap, so that offset is negative. Zero extension made the resulting device address too high by `2^48`. Console user-mode VAs below `2^47` and full-width root descriptor addresses already within the signed 48-bit range retain their values. A 64-bit base-plus-offset sum gives the correct address for effective VAs in that range, including when the sum crosses zero. Each new shader's `index.json` entry carries `"vsharp_base_sign_extended": true`. Check the field on all loaded entries before enabling below-arena imports for a library, because older modules can share an index with newly translated ones. `tests/semantic/test_vsharp_sext48.py` checks the emitted shifts, both reads against synthetic memory, and the metadata field. | | Null sources in 64-bit integer VALU compares | `v_cmp` and `v_cmpx` relations `eq`, `ne`, `lt`, `le`, `gt`, `ge` on `u64` and `i64` read `null` as the 64-bit value 0 in either source, like immediate `0`. Register pairs and immediates retain their existing semantics; `v_cmp` writes the active lane's comparison to VCC/SGPR, while `v_cmpx` narrows EXEC without changing VCC. Source: RDNA2 ISA special operand `null` reads zero; LLVM `llvm-mc -mcpu=gfx1013` accepts the encoding. CPU-checked by `tests/semantic/test_vcmp64_null_src.py` (both sources, signed/unsigned ordering, equality, e32/e64, EXEC and inactive lanes); **not GPU-verified, no corpus count**. | | `s_load_dword*` with `vcc` 64-bit base pointer | SMEM `s_load_dword*` accepts `vcc` (`{vcc_lo, vcc_hi}`, hardware `s[106:107]`) as its 64-bit base pointer in `Gen.scalar_load`, loading `%vcc` as the low dword and `%vcc_hi` as the high dword; `s_buffer_load*` still requires a 4-dword V# and rejects 2-dword `vcc`. Source: RDNA2 ISA SMEM `SBASE` encoding (`sbase = 53` -> `s[106:107] = vcc`). Confirmed by corpus count over the 2,684-shader pipeline library compute corpus (79 shaders use `vcc` as the `s_load` base: 72 `s_load_dwordx4 sgpr, vcc`, 6 `s_load_dwordx8 sgpr, vcc`, 1 `s_load_dwordx4 slist, vcc`; all 79 translate and pass `spirv-val` under `--wave64-emulate`) and CPU-checked by `tests/semantic/test_sload_vcc_base.py` (`spirv-as` + `spirv-val`); **not GPU-verified**. | | Execution model | One invocation = one lane. Compute and mesh waves derive lanes from the workgroup-local index; other stages use the subgroup lane. A wave = a subgroup, so cross-lane ops (`ds_swizzle`, `v_permlane*`, `v_readlane`/`v_writelane`, `v_mbcnt`) become subgroup shuffles. Wave32 pixel shaders split a 64-lane physical subgroup into two logical waves: lane IDs are `SubgroupLocalInvocationId & 31`, shuffle sources retain the current half (`& 32`), and ballots/votes use that half's 32-bit word. A value the translator knows is uniform (the bindless descriptor index) is read from the half's first running lane, never from a fixed lane, which need not be running (SHADER-1016). Other stage/wave combinations still require subgroup size == wave size or wave64 emulation. **Requires subgroup size == wave size** (wave32 maps directly onto NVIDIA GPUs; wave64 shaders need a 64-wide subgroup or emulation). `v_readlane_b32`/`v_writelane_b32` mask the lane select with 63 in wave64 (`S1[5:0]`) and 31 in wave32 (`S1[4:0]`); until SHADER-52 both used 63, so a wave32 select ≥ 32 pointed past a 32-wide subgroup. GPU-checked with `cs_w32_lane_wrap.asm` (lane 40 → 8). For the fragment-half rule, `ps_bitmask_perm` produced 4096/4096 exact pixels on an AMD Radeon RX 5700 XT; Vulkan reported a default subgroup size of 64 (range 32..64), but does not permit pinning fragment subgroup size on this device. CPU semantic tests compare a 64-lane wave32 pixel subgroup against two 32-lane subgroups for reads/writes, permutations, ballots, and votes. | @@ -282,7 +286,9 @@ How the generated SPIR-V expects the runtime to work: | EXEC | A per-invocation `active` flag. VALU writes and exports are masked by it, scalar ops aren't, and `v_cmpx`, saveexec and EXEC writes update it. Measured on native gfx1100 (8 threads): a `v_mov_b32` under `EXEC=0x0F` leaves the other lanes untouched, `EXEC=0` writes nothing, a store writes only active lanes and `v_cmpx_gt_u32` narrows EXEC (4 of 4 cases); note that AMD clang 20 rejects `v_add_co_u32`, `v_sub_co_u32`, `v_add_co_ci_u32` and `v_mad_u64_u32` for `gfx1100`, `gfx1101` and `gfx1102`, so this toolchain could not reproduce the RX 7600 result below, which leaves open whether those parts support the opcodes and says only that they could not be assembled here. **A pixel is written when its lane was on in EXEC at the last `exp ... vm` the path executed (if it executed one) and at the last export to the color target; a path with no export at all goes by EXEC at the end.** The `vm` half is the RDNA2 ISA reference guide's rule (30-November-2020, §11.1 and §11.2.1: EXEC at the export is the valid mask and the final one sent is used; an `exp null ... vm` carries only the mask). The color half is measured: an export sends data only for the lanes that are on, a later export to the same target replaces the earlier one for the whole wave, and a lane with no data from the last one is not written even when a later `exp null done vm` marks it valid. So `exp mrt0 done` (no `vm`) with every lane on, followed by an EXEC write, still writes every pixel, and EXEC off at that export and back on afterwards writes none. **Measured on RDNA2** (AMD Radeon iGPU, gfx1036, driver 26.10.1) with the pixel-shader oracle of #3061 (`ps_oracle.py`), hand-written ISA as the pixel shader of a real draw (wave64 stage): 18 programs that cut EXEC to half of the target before, between or after `exp mrt0` (with and without `vm` and `done`) and `exp null done vm`; all 18 fit the rule, 6 of them differed from the translator, which until 2026-11-23 discarded by EXEC at the end on a path without `vm` and kept the older export's value (or the output's initial value) for a lane that was off at the last color export. The latches (`%vm_mask`, `%col_mask_mrtN`) are only emitted where a path can write EXEC after a `vm` or color export; everywhere else EXEC at the end is the same mask and the SPIR-V is unchanged. With several color targets a pixel stays when any target got an export from its lane (Vulkan cannot skip one attachment per pixel; not measured, the oracle's pipeline has one target); `mrtz` is not part of the color mask (not measured). **Measuring exports needs `s_waitcnt expcnt(0)` after each one**: an export is asynchronous, and without the wait the hardware takes the data and the EXEC of a later moment (`v_mov v9, A; exp mrt0 v9 done vm; v_mov v9, B` shows B, and an EXEC write right after the export decides which pixels are written, which looks like "EXEC at the end decides"); 64 `s_nop 15` have the same effect as the wait. Checked on the CPU by `tests/semantic/test_export_valid_mask.py` and on the GPU by `runtime/test/shaders/ps_exp_color_mask.asm` (RTX 5080 and the Radeon). VALU scalar lane-mask destinations (`v_cmp_*`, `v_add_co_u32`, `v_add_co_ci_u32`, `v_sub_co_u32`, `v_sub_co_ci_u32`, `v_subrev_co_u32`, `v_subrev_co_ci_u32`, `v_mad_u64_u32`, `v_mad_i64_i32`) write 0 for lanes off in EXEC (`SDST[lane] = EXEC[lane] ? bit : 0`, AMD RDNA2 ISA). Until 2026-11-22 the six `*_co_*` ops and `v_mad_u64_u32`/`v_mad_i64_i32` did not AND the carry/sign bit with `active`, so inactive lanes leaked 1 bits into `VCC`/SGPR masks (`s_bcnt1`, `s_cbranch_vccz`, `v_cndmask_b32`). Checked on the CPU by `tests/semantic/test_carry_exec_mask.py` (wave32, wave64, and `--wave64-emulate` structure), and **hardware-verified on an AMD RX 7600 (gfx1102)** with `v_add_co_u32` and `v_add_co_ci_u32` carrying on every active lane: VCC reads `0xffffffff` with full EXEC, `0x0000ffff` for the mask `0x0000ffff` and `0xaaaaaaaa` for `0xaaaaaaaa` in wave32, `vcc_lo = 0x0000ffff` with `vcc_hi = 0x0000000f` for the same partial mask in wave64, and `0` when EXEC is 0 even with VCC preloaded to all ones; with one carrying lane under mask `0x0000ffff` VCC is `0x00000001`, and `v_sub_co_u32`/`v_subrev_co_u32` with a borrow under that mask give `0x0000ffff` too. The `*_co_ci_` forms, `v_mad_u64_u32` and `v_mad_i64_i32` share the same path but were not measured separately; it is also GPU-verified on native RDNA2 (gfx1036, AMD Radeon Graphics) with partial EXEC masks (inactive lanes write 0 in sdst for `v_add_co_u32` and `v_mad_u64_u32`). In a shader that writes EXEC, a run of two or more lane-local VALU instructions (no cross-lane read, no lane-mask, SCC, carry or EXEC write) sits inside one `if (active)` and writes its VGPRs directly, instead of an `OpSelect(active, new, old)` per write: the same result, but the driver predicates the run with its own EXEC instead of keeping both values live. On an RX 5700 XT (RADV) a pixel shader with 8 divergent if/else regions of `v_fma`/`v_mul`/`v_add`/`v_min`/`v_max` went from 0.85 ms to 0.69 ms (the same program as native SPIR-V: 0.65 ms). Not under `--wave64-emulate`. Checked by `tests/semantic/test_active_runs.py`. | | `s_*_saveexec_b32/b64`, `s_andn1/andn2_wrexec_b32/b64` | RDNA2 ISA SOP1. saveexec: `D = EXEC; EXEC = f(S0, EXEC); SCC = (EXEC != 0)`. wrexec: `EXEC = f(S0, EXEC); D = EXEC`. `f` is one of `and`, `or`, `xor`, `andn1` (`~S0 & EXEC`), `andn2` (`S0 & ~EXEC`), `orn1` (`~S0 \| EXEC`), `orn2` (`S0 \| ~EXEC`), `nand`, `nor`, `xnor`, the table in `Gen.EXEC_LOGIC`. The definitions match `tools/cf_ref.py` `_SAVEEXEC`, the FUZZ-8 model. Each invocation holds its own lane's bit (0 or ~0), so `f` is the bitwise op on that bit. A lane EXEC had off becomes active when `f` gives 1 for it (`nand`, `nor`, `orn1`, `orn2`, `xnor`, ...), as on hardware, and SCC is the wave vote. Until 2026-11-22 only `and`/`or`/`andn2_saveexec` and `andn2_wrexec` were translated. CPU-checked by `tests/semantic/test_saveexec_variants.py` (all ten saveexec kinds in wave32 and wave64, both wrexec kinds, partial EXEC and S0, an empty result, every lane against `cf_ref._SAVEEXEC`) and by `tools/cf_diff.py` (300 programs × wave32/64 still pass). Hardware-verified on native RDNA2 (`gfx1036`, Windows 11, driver `32.0.21045.29003`, wave32 & wave64, 0 mismatches): all 10 `saveexec` kinds and both `wrexec` kinds (`andn1`/`andn2`) match bit-for-bit on non-symmetric masks (`src0 = 0x0F0F0F0F`, `exec = 0x33333333` in wave32; `0x0F0F0F0F_00FF00FF` / `0x33333333_55555555` in wave64), zero-result `SCC = 0`, wave64 upper-32-bit-only `new_exec = 0x00000001_00000000` setting `SCC = 1`, and `sdst == src0` register aliasing (`s4, s4` and `s[4:5], s[4:5]`) reading original `src0` before writing old `EXEC` to `sdst`. **Not GPU-verified** for the seven new kinds. Measured on native gfx1100 (single 8-lane workgroup, 36 programs): all ten `saveexec` kinds and both `wrexec` forms follow `f` for three `S0`/`EXEC` pairs, including lanes `EXEC` had off being switched back on (`nand` with `S0=0x03`, `EXEC=0x0F` leaves `0xFFFFFFFC`, activating lanes 4-7), `D` holding the old `EXEC` for `saveexec` and the new one for `wrexec`, and `SCC` the `EXEC != 0` vote. | | Control flow | Reducible graphs use structured branches and natural loops. Irreducible graphs use the dispatch-loop form, which can also be forced with `--dispatch-loop` for comparisons. The control-flow unit test checks 18,228 generated graphs. Irreducible graphs use node splitting (`cfg_structure.split_irreducible`, up to `min(2*N, N+64)` blocks) and fall back to the dispatch-loop form when capped; it can also be forced with `--dispatch-loop` for comparisons. `cfg_structure.structure`, `cfg_structure.run`, and `rdna2spirv.assemble`'s structured emitter are iterative and hoist each guarded member's dominated tail continuation out of its enclosing guard (exact by strict dominance: no block outside the guard's subtree can target the continuation), keeping `OpSelectionMerge` nesting O(1) on sequential diamond/loop chains instead of nesting O(N) deep and hitting Python's recursion limit on multi-thousand-block shaders (e.g. 2,000 sequential diamonds nest to depth 2 instead of 2,000). The control-flow unit test (`tests/test_cfg_structure.py`) checks 20,000 generated graphs plus 2,000-diamond, 1,200-loop, and 1,500-early-exit chains. AMD A/B checks compare the two forms for selected pixel shaders with defined test inputs. For shaders that never export colour, the comparison checks pixel coverage. **Nesting is bounded (SHADER-299):** a tree deeper than `MAX_STRUCTURED_DEPTH` (16) is emitted in the dispatch-loop form instead, since `spirv-val` time grows roughly with the cube of the measured nesting depth. **Nesting is bounded (SHADER-299, SHADER-427):** a tree deeper than `MAX_STRUCTURED_DEPTH` (64; `--max-structured-depth N`, 0 = no bound) is emitted in the dispatch-loop form instead, since `spirv-val` time grows roughly with the cube of the measured nesting depth. Before #1904, over the 1.0.2.1 corpus (26,503 modules, `spirv-val` 2026.4): the deepest block of a module is nested 118 constructs deep, 12,963 modules are structured (median 15) and 6,000 of those are deeper than 16; an estimated 85% of the corpus's `spirv-val` time is in modules nested 20 or deeper. Median `spirv-val` time for the same module in each form: depth 20 181 -> 129 ms (1.4x), 30 507 -> 371 (1.4x), 50 1,712 -> 738 (2.3x), 64 2,692 -> 1,163 (2.3x), 77 5,122 -> 1,130 (4.5x), and the deepest (118) 13,683 -> 1,352 ms (10.1x). Depth 5-12 shows no gain (at depth 6 the flat form is slightly slower), which is why the bound first sat at 16. Since #1904 (`cfg_structure` hoists tails) the deepest tree in the corpus is 29: of 12,944 structured modules, 1,031 are deeper than 16 (747 CS, 284 PS), 57 deeper than 20, 24 deeper than 24. For those 1,031 the flat form saves only 12% of `spirv-val` time (1,235 -> 1,091 s summed, slowest module 8.3 -> 5.9 s), while on an RTX 5070 Ti (NVIDIA 621.24) it compiles slower: the 284 pixel shaders 1.67x (827 -> 1,382 s summed, two rounds), four compute modules at depth 19-24 2.0x (297 -> 591 s, 1.6-2.7x each), so the bound now sits above the corpus (SHADER-427). Both forms pass `spirv-val` on a 200-shader slice (200/200 each), and `gen.nesting` records the tree depth. AMD's Windows driver adds a reason to keep the structured form (SHADER-995): on a Radeon gfx1036 iGPU (32.0.21042.62) the dispatch-loop module of `XboxBvhBuilder.dll`'s `LeafRehydration` (tree depth 18, a 581-case switch) takes 34 minutes to create (XXDESIGN), where its structured module is created in 2.9 s; ten other programs of that DLL compile in the dispatch-loop form there in 0.4-40 s, 2.5-5x their structured time ([embedded_shaders.md](embedded_shaders.md), section 7). | +| Loop guard | Each loop counts header visits per invocation and exits through its structured merge at `--loop-limit N` (default 65536, zero disables). Counters reset on entry, including nested EXEC retries and atomic loops. A PC-dispatch visit counts a dispatch iteration. Natural exits within the budget preserve their outputs. Five-star-recomp (b12a952) reported a story-load timeout when the shader input made its exit condition unreachable. | | User data | **Push constants, 144 bytes:** dwords 0–31 = initial s0–s31 (the user SGPRs the console driver loads from the root signature: descriptor-table pointers, constants and so on), dwords 32–33 = the 64-bit **heap base**, dwords 34–35 = the **code base**: the Xbox VA where the runtime uploaded this shader's whole FSSM blob. `--mesh-compute` modules add dwords 36–37, the output buffer address (152 bytes; see "Mesh shaders as compute"). `--pc-tail-ubo` keeps only dwords 0–31 here (128 bytes) and moves the rest to a uniform block (see "Push-constant tail as a uniform block"). The runtime has to reproduce the console driver's root-signature-to-user-SGPR mapping; that comes from the exe or driver behaviour. | +| Direct resource heap | In the matched Prop/Tree BatchCull compute signature the two explicit tables and scalar constant occupy s4–s6. Bind the resource heap's uint32 arena-relative byte address at s7 (push-constant byte 28). The program supplies a zero high word and scales the resource index by 32 bytes. Other stages and signatures consume different SGPRs. See [descriptor heaps and the bindless model](d3d12_vulkan.md#34-descriptor-heaps-and-the-bindless-model) for the evidence and graphics examples. | | Xbox GPU addresses | Shaders build Xbox GPU virtual addresses, and some force the high dword to 0 (descriptor tables in the low 4 GB). Every memory access goes to **heap base + Xbox VA**, so the runtime maps the console's GPU address window into one host buffer-device-address allocation. | | Code-embedded data | 155 VS/PS had "undecodable words". They're **constant tables inside the code range** (float values like 0x3EF7…, plus zeros), read through `s_getpc_b64` + `s_add_u32`/`s_addc_u32` + `s_load` (147 of 155). The translator re-anchors each instruction to its true FSSM offset by matching encodings (when the llvm-mc messages give one offset per rejected word, `shader_ir.parse_file`'s `invalid_at`, those words are skipped exactly and nothing is searched forward: a forward search let a data word printed as a copy of a later instruction take that instruction's place and lose every one after it; counted on the 1.0.2.1 pipeline library with #327's vcc-tuple decoding, 36 compute programs that stopped at "cannot re-anchor" now translate and pass `spirv-val`, none lost; `tests/semantic/test_reanchor_llvm_offsets.py`), translates only code reachable from entry (a branch into data is rejected), and turns `s_getpc_b64` into code base + next-instruction offset. **The runtime uploads each shader's FSSM blob into the heap and passes that VA as the code base.** Re-anchoring compares bytes exactly, except that VOP3P `op_sel_hi[2]` (bit 14) is ignored on two-source packed ops: the compiler stores 0 there, and LLVM prints its default of 1. Unused VOP3/VOP3P `SRC1` (bits 49:41) and `SRC2` (bits 58:50) fields are also ignored when stored as 0 and printed as `0x80`: LLVM 23 re-encodes a source it doesn't read as inline constant 0 (one-source `v_rcp`/`v_log`/`v_sqrt_f32_e64`, two-source `v_sub_f32_e64`/`v_cmp_*_e64`/`v_mul_lo_u32`/`v_pk_mul_f16`). Both checks for clean listings and re-anchoring use the parsed operand count to apply this exception only to unused sources. A used source encoded as 0 reads `s0` and is never treated as inline zero. `tests/semantic/test_printed_encoding.py` checks used `SRC1`/`SRC2` and an unused field with synthetic listings. Confirmed by a count over the corpus with LLVM 23.1.5: without it, 1,471 of the 1,473 shaders with embedded data are rejected ("reachable instruction with normalized encoding"); with it, all 1,473 translate and pass `spirv-val`. Runs with LLVM 21 already translated all of them, so older LLVMs presumably print the stored 0 (not re-checked). Data words that decode with ignored fields set are printed re-encoded (e.g. `0xbe8d2242` as `s_rfe_b64` `0xbe802242`), so they can never match. Since the decoder consumed the same length, they are anchored in sequence and marked. A shader that can *reach* a marked word is rejected; none of the corpus does. All 155 now translate. A reachable instruction that falls through into words llvm-mc skipped (it printed no instruction there) is rejected too, as `fall-through into undecodable words`: until SHADER-813 the reachable path ended there without a word, so everything after the gap (exports, stores) was dropped from a module that still passed `spirv-val`. No VS/PS of the corpus has such a gap on a reachable path; in the FidelityFX FSPX programs it is the `v_dot4_i32_i8 ... op_sel` words LLVM 23 cannot decode (`docs/fspx.md`), so those programs are now refused instead of translated without their stores, until those words are decoded (#2038, #2323). `tests/test_rdna2spirv_decode.py` (`test_fall_through_into_undecodable_words_is_refused`). | | VOP3 opcode 0x140 | LLVM disassembly of the synthetic words in `tests/test_rdna2_decode.py` gives `v_mad_legacy_f32` on gfx1010 through gfx1013 and `v_fma_legacy_f32` on gfx1030. The direct decoder defaults to gfx1013, matching the disassembler CLI. Checked by the unit test `test_vop3_legacy_mad_fma_target` in `tests/test_rdna2_decode.py`, which decodes the same words directly and runs the Python disassembler backend for gfx1013 and gfx1030. | @@ -293,12 +299,14 @@ How the generated SPIR-V expects the runtime to work: | Sub-dword MUBUF loads and `GFX10_FORMAT_8_UINT` | `buffer_load_ubyte`, `buffer_load_sbyte`, `buffer_load_ushort` and `buffer_load_sshort` read 1 or 2 bytes at `Gen.buffer_address(..., elem=1 \| 2)` (same `OOB_SELECT` end check with element size 1 or 2 bytes; out-of-bounds returns 0 without reading memory; inactive lanes preserve `vdst`), zero- or sign-extending to 32 bits; 16-bit loads at byte offset 3 within a dword merge byte 0 of the next dword (`idx1 = (b3 == 3) ? 1 : 0`) without over-reading past the buffer. `FORMATS` adds code 5 (`GFX10_FORMAT_8_UINT`, 1-byte unsigned integer) for `tbuffer_load_format_*` / `buffer_load_format_*` (with `DST_SEL` integer 1). Needed by `XboxBvhBuilder.dll` (#1813 follow-ups: `Box16Rehydration`, `Box32Rehydration`, `ReloadTriangles`, `LeafRehydration`). CPU-checked by `tests/semantic/test_buffer_load_sub.py` and validated with `spirv-val` (native and `--wave64-emulate`). GPU-checked (TEST-510) through Vulkan by `runtime/test/shaders/cs_buf_load_sub.asm` (ubyte/sbyte/ushort/sshort zero- and sign-extended, the dword-crossing ushort at offset 3, and the RAW end check by element size: a ushort at 7 of 8 bytes reads 0, where a start-only check would read the next bytes) and `cs_buf_fmt8.asm` (`BUF_FMT_8_UINT` at offsets 0..3, out of range, an INVALID V# format, `DST_SEL` integer 1), both in `scripts/run_gpu_tests.py`: pass on an NVIDIA GeForce RTX 3070 Ti (driver 610.88) and, with the same eight words, on an AMD RX 7600 (`gfx1102`) and a Ryzen 5 9600X iGPU (`gfx1036`, RDNA2, RADV Mesa 27.0.0-devel), so the `vdst` preservation, the sign/zero extension, the ushort load across a dword and the element-size end check are GPU-checked on AMD too. `tools/hw_oracle` was not used for this; the Vulkan path above is what the translator runs. Not measured on AMD hardware (`tools/hw_oracle`). **Not GPU-verified.** Measured on an AMD Radeon RX 7900 XTX (`gfx1100`, driver 26.10.1) by running the instructions as a raw compute kernel (`tools/hw_oracle`, wave32, seeded synthetic bytes): the four loads zero-/sign-extend at byte offsets 0..7, the ushort at byte offset 3 merges byte 0 of the next dword, and with `NUM_RECORDS` = 8 the end check uses the element size (a ubyte at 7 reads where one at 8 returns 0, a ushort at 6 reads 0x5eee where one at 7 returns 0, an sshort at 7 returns 0 where an sbyte at 7 reads). `buffer_load_format_x` with `FORMAT` code 5 and `tbuffer_load_format_x format:[BUF_FMT_8_UINT]` return that byte zero-extended with the same 1-byte end check (at `NUM_RECORDS` 8, offset 7 reads 0x5e and 8 returns 0), and a V# whose `DST_SEL`s are 1/2/3/4 returns the integer 1 in all four components, not the fetched byte. The inactive-lane clause rests on the NVIDIA run. **Not GPU-verified.** | | 8/16-bit global stores and d16 loads | `global_store_byte`/`short` write the low 8/16 bits of the data VGPR (the `_d16_hi` forms its high half). `global_load_{u,s}byte_d16` and `global_load_short_d16` write the low 16 bits of `vdst` (the `_hi` forms the high 16) and keep the other half; `ubyte` zero-extends and `sbyte` sign-extends the byte to 16 bits. The address is the `global_load/store` one (`Gen.global_address`). The access goes one byte at a time, so a 16-bit access that crosses a dword (at byte 3) is exact too. A store merges each byte into its dword with atomic and/or, which keeps neighbouring bytes even when another lane writes them, as buffer byte stores do. A load reads each byte. Inactive lanes neither store nor load. The first-read analysis counts a d16 load's `vdst` as read, for the half it keeps. `global_load/store_dword_addtid` (lane-id and M0 addressing) raise `Unsupported`; until 2026-11-22 they crashed with `IndexError`, and the ten sub-dword ops raised `Unsupported`. CPU-checked by `tests/semantic/test_global_sub_dword.py` (every byte offset 0 to 7 for each op, an inactive lane, rejected forms, the first-read analysis). **Not GPU-verified.** Hardware-measured natively on `gfx1100`** (RX 7900 XTX, driver 26.10.1) with `tools/hw_oracle`, 16 cases that use the output buffer as scratch memory (seven stores, nine d16 loads), all matching: `b8`/`b16` change only the addressed bytes (`0x11223344` with `0xbeef` stored at offset 2 reads back `0xbeef3344`), `_d16_hi` stores take the data VGPR's high half (`0x12340000` at offset 0 gives `0x11221234`), a 16-bit store at offset 3 splits across the dword exactly (`0xfe223344` then `0x556677ca`), `ubyte`/`sbyte` d16 loads fill the low 16 bits of `vdst` and keep the other half (`0x85` gives `0xbeefff85` from a `0xbeef0000` vdst, `0x7f` gives `0xbeef007f`), `short`/`short_hi` d16 loads fill the low/high 16 and keep the rest, and both dword-crossing loads at offset 3 are exact (`0xbeef8811`, `0x88110000`). Not measured: an inactive lane. **Not GPU-verified.** | | Literal samplers | Some shaders build their S# from immediates (for example `0x92, 0xC00000, 0x14500000, 0`). The runtime registers those in the descriptor hash table too, by scanning the translated shaders' constant S# values, not only S#s the game binds. The translator lists them per shader (`literal_samplers` in the index). `CreateGraphicsPipelineState` and `CreateComputePipelineState` register each stage's list in the descriptor hash table, since no heap slot names these S#s. Until 2026-11-22 nothing called `register_samplers` (#1169) outside its test, so such a shader's lookup found the fallback sampler and sampled with the wrong filter. The game's `$PS_PassthroughCopy` drew a coordinate ramp point-sampled: worst error 0.0078, against 0.00049 once registered. Checked by `d3d12_m2_textured_test` (`ps_m2_literal.asm`: no key before the PSO, a sampler index after it). | -| Scalar/buffer memory | `s_load*`, `s_buffer_load*`, `buffer_load*` and `buffer_store*` use buffer device addresses (`PhysicalStorageBuffer64`). LLVM `VCCTuple` scalar register lists ending in `vcc_lo,vcc_hi` (e.g. `[s100,s101,s102,s103,s104,s105,vcc_lo,vcc_hi]`, `[s92,...,s105,vcc_lo,vcc_hi]`, seen in 6 FidelityFX FSPX shaders) are parsed as `slist` operands in `tools/shader_ir.py`, clear `vcc` from the lane-mask state in `tools/lane_masks.py`, and route `sN` slots to `%sgpr` and `vcc_lo`/`vcc_hi` to `%vcc`/`%vcc_hi` across SMEM loads, T#/S#/V# descriptor reads, and `global_*` `saddr`. `src_scc` reads `%scc` (0 or 1, RDNA2 inline constant 253), matching `scc`. `image_atomic_*` and `image_atomic_cmpswap` accept `a16` packed 16-bit unsigned coordinates (low half first, matching `image_store`). CPU-checked by `tests/semantic/test_fspx_rules.py` and validated with `spirv-val` (native and `--wave64-emulate`). **Not GPU-verified.** The base comes from the 64-bit SGPR pointer or the V# (dword0 \ \| dword1[15:0] << 32), and the stride is V# dword1[29:16]. **The runtime must put the game's GPU heap in buffer-device-addressable memory at the same addresses the game writes into descriptors** (or remap them). `s_load*` and `s_buffer_load*` take an immediate or an SGPR offset, or both at once (llvm-mc prints `sOFF offset:IMM`). Rules, measured on AMD Radeon RX 6800 (gfx1030, Windows driver 32.0.21045.29003) by running the instructions as a raw compute kernel, wave32 and wave64 (155 runs, every result either 0 or the stored data, wave32 = wave64 in every dword): **address** = (base & ~3) + (sOFF & ~3) + (IMM & ~3) + 4·i for dword i: base, sOFF and IMM are each truncated to a multiple of 4, then added (`s_buffer_load_dword s9, s[24:27], 0x3` with base & 3 = 1 reads +0, not bytes 4..7; sOFF 3 + IMM 3 reads +0 and sOFF 2 + IMM 6 reads +4, where truncating the sum gives +4 and +8; sOFF 8 + IMM 4 reads +12; the same for `s_load*` with pointer & 3 = 1 or 3). **`s_buffer_load*` bound**: dword i is 0, and memory is not read, when (sOFF & ~3) + (IMM & ~3) + 4·i + 4 > limit, with limit = NUM_RECORDS (V# dword2) bytes when the stride is 0 and NUM_RECORDS × stride bytes when it is not. Per dword (x4 at 0xc with NUM_RECORDS 21: data, data, 0, 0; x8 at 0 with 21: five data, three 0), on the truncated offset (IMM 0x10 with NUM_RECORDS 18: 0; IMM 0x13 with 21: the dword at +0x10; sOFF 0xe + IMM 2 with 16: the dword at +0xc; sOFF 0x10 + IMM 4 with 20: 0), not seeing base & 3 (base & 3 = 3, IMM 0x13, NUM_RECORDS 20: data); with a stride the test is still on bytes (stride 4, NUM_RECORDS 5: IMM 0x10 data, 0x14 0; stride 1, NUM_RECORDS 17: IMM 0x10 is 0, so it is not an index test). IMM is unsigned (0xffffc reads +0xffffc). OOB_SELECT (V# word3[29:28]) 0, 1, 2 and 3 gave the same pattern (7 probes per value). **`s_load*`**: no bound (+0x1ffffc reads the dword there); IMM is sign-extended from 21 bits and added in 64 bits (sOFF 8 + IMM −4 reads +4 where zero-extension reads 4 GiB further; sOFF 0xb + IMM −1 reads +4, so the negative IMM is truncated on its own: −1 → −4). **Negative sums** (SHADER-336), measured on the integrated GPU of a Ryzen 9 9950X3D (gfx1036, RDNA2, Windows driver 32.0.21045.16010) with `tools/smem_neg_probe.py --oracle hw`, wave32 = wave64: `s_load` with IMM −4 or −0x40 and no sOFF, sOFF 4 + IMM −8, sOFF 0xc + IMM −0x20 and the x2 form with sOFF 4 + IMM −0x10 read below the pointer at the 64-bit signed sum, and sOFF 6 + IMM −1 reads +0 (4 + −4, each term truncated on its own). `s_buffer_load` adds sOFF and IMM without wrapping at 32 bits: sOFF 0xfffffffc + IMM 8 and sOFF 0xfffffff0 + IMM 0x20 give 0 (past NUM_RECORDS 0x100), and sOFF 0xfffffffc, 0x80000000 and 0x7ffffffc alone give 0 (the translator has the same rule in both offset forms since #1686). An `s_buffer_load` IMM with bit 20 set (llvm-mc rejects it; −4, −0x10, 0x100000 and 0x100004 were encoded by hand) reads data that is neither 0 nor the buffer's own words, differently in wave32 and wave64: the bound does not hold for that encoding, so no compiler output uses it and the translator does not model it. `SmemHardwareRuleTests` in `tests/semantic/test_scalar_mem_smem.py` runs these rows with sOFF in a register and with sOFF known. **Measured since** on native RDNA2 (gfx1036, the Radeon iGPU of a Ryzen 7 9800X3D, Windows driver 32.0.21042.62) through `tools/hw_oracle`, one raw kernel, wave32 = wave64 in every dword (22 cases): **`x16`** takes the per-dword bound like x8 (`s_buffer_load_dwordx16` at offset 0 with NUM_RECORDS 0x24 gives nine data dwords and seven 0; offset 0x20 with 0x40 gives eight and eight; offset 4 with 0x3d gives fourteen and two; stride 4 with NUM_RECORDS 9 gives nine and seven), and `s_load_dwordx16` reads all sixteen; **NUM_RECORDS ≥ 2^31** is compared unsigned (0x80000000 and 0xffffffff with offset 0x10, and 0x80000000 with an x4 at 0x2f0, all read data); **NUM_RECORDS × stride ≥ 2^32** does not wrap (stride 4 × 0x40000001, stride 0x100 × 0x01000001 and stride 0x40 × 0x04000004 wrap to 4, 0x100 and 0x100 in 32 bits, yet offsets 0x10, 0x200 and 0x2f0 read data), as the translator's 64-bit product assumes; **V# dword1[31:30]** = 1, 2 or 3 changes nothing (a dword at 0x10, an x4 at 0xf8 with NUM_RECORDS 0x100 giving two data and two 0, and the same with stride 8 and NUM_RECORDS 4 at 0x18). Not measured: gfx1013 (PS5) itself. **Bound edges**, measured on the same GPU and driver with `tools/hw_oracle` (wave32 = wave64, every read inside a seeded region): `s_buffer_load_dwordx16` is bounded per dword like x8 (NUM_RECORDS 0x14 gives d0..d4 and 0 for d5..d15; 0x20 with IMM or sOFF 8 gives d0..d5); NUM_RECORDS × stride is not cut to 32 bits (stride 0x1000 × 0x100000 and 0x2000 × 0x80000 = 2^32, stride 8 × 0x20000001 = 2^32 + 8: all four dwords of an x4 at 0 are data; stride 8 × 1 gives two); NUM_RECORDS 0x80000000 and 0xFFFFFFFF are unsigned (an x4 at 0 reads all four). These are the rules the translator already used; `SmemHardwareRuleTests` pins them too (a 32-bit product, a signed NUM_RECORDS or one bound for the whole load each fail a test). Not measured: `x16` (gets the x8 rule), NUM_RECORDS ≥ 2^31 and NUM_RECORDS × stride ≥ 2^32, V# dword1[31:30], and gfx1013 (PS5) itself. `s_load`/`s_buffer_load` with sOFF + IMM < 0 (a negative IMM without sOFF included; the translator uses the 64-bit signed sum, an inference), an `s_buffer_load` IMM with bit 20 set (llvm-mc rejects it) or a negative one (kept as the 32-bit value: for stride 0 that is past any NUM_RECORDS below 4 GiB), `x16` (gets the x8 rule), sOFF ≥ 2^31, NUM_RECORDS ≥ 2^31 and NUM_RECORDS × stride ≥ 2^32, V# dword1[31:30], and gfx1013 (PS5) itself. The translator checks each `s_buffer_load` dword with its own structured `if` and an `OpPhi` with 0, so an out-of-range dword issues no load (when descriptor limit and offset are compile-time constants, in-range dwords fold to straight-line loads and out-of-range dwords emit constant zero without branches); `s_load` stays straight-line. Before this the translator added base + sOFF + IMM unaligned, had no `s_buffer_load` bound and zero-extended a negative `s_load` IMM. Checked by `tests/semantic/test_scalar_mem_smem.py` (`SmemHardwareRuleTests`, the measurement's rows, values and the addresses read; `SmemSoffsetImmTranslatorTests`) and by the GPU tests `runtime/test/shaders/cs_smem_soffset_imm.asm`, `cs_smem_bounds.asm`, `cs_smem_stride_align.asm` and `cs_smem_sload_neg.asm` (never run that one with a translator that zero-extends the immediate: it reads 4 GiB past the heap), all in `check.py` and `scripts/run_gpu_tests.py`, which pass on the RX 6800 (Vulkan, driver 26.11.2). See *Buffer bounds checking* below for the MUBUF `num_records` checks. **A constant SGPR offset** (`s_mov_b32 s12, C`, folded at translate time) is added as the run-time path adds `sOFF`: zero-extended, `& ~3`, after the immediate has been normalised (unsigned for `s_buffer_load`, 21-bit signed for `s_load`), with no 32-bit wrap. Until 2026-11-22 (#1686) the fold added it before the truncation, so `s12 = -4` with `offset:20` read byte 16 instead of being out of range, and an `s_load` `sOFF` of 2^20 or more was sign-extended from 21 bits (found by @Impre-visible; hardware measured by @Pierre-Kookis on gfx1036: 0xFFFFFFFC + 20 reads 0). CPU-checked by `tests/semantic/test_smem_const_offset.py` (each case constant vs run-time offset, and against the measured rule). | +| Pipeline-library DPP comparisons | Full-write VOPC f32 comparisons use the same DPP source permutation as VOP2. The decoder recovers DPP8 and unmodified DPP16 operands with full row and bank masks and bound control enabled. Handwritten tests check the recovered words and per-lane results. | +| Pipeline-library scalar operands | A scalar load may use VCC as a 64-bit pointer. In wave32 programs using that operand, scalar pair moves and XORs preserve both address words. Read its low and high data words, gathering a native wave's mask bits when a half is mask-valued. An emulated wave64 mask-valued pointer is refused. Where LLVM rejects a scalar, image or buffer tuple ending in VCC, `restore_vcc_tuples` recovers the tuple from its original bytes, following only reachable code. Hand-built memory and decoder cases in `test_library_compute_forms.py` and `test_vcc_tuple_fallback.py`. | +| Scalar/buffer memory | `s_load*`, `s_buffer_load*`, `buffer_load*` and `buffer_store*` use buffer device addresses (`PhysicalStorageBuffer64`). LLVM `VCCTuple` scalar register lists ending in `vcc_lo,vcc_hi` (e.g. `[s100,s101,s102,s103,s104,s105,vcc_lo,vcc_hi]`, `[s92,...,s105,vcc_lo,vcc_hi]`, seen in 6 FidelityFX FSPX shaders) are parsed as `slist` operands in `tools/shader_ir.py`, clear `vcc` from the lane-mask state in `tools/lane_masks.py`, and route `sN` slots to `%sgpr` and `vcc_lo`/`vcc_hi` to `%vcc`/`%vcc_hi` across SMEM loads, T#/S#/V# descriptor reads, and `global_*` `saddr`. `src_scc` reads `%scc` (0 or 1, RDNA2 inline constant 253), matching `scc`. `image_atomic_*` and `image_atomic_cmpswap` accept `a16` packed 16-bit unsigned coordinates (low half first, matching `image_store`). CPU-checked by `tests/semantic/test_fspx_rules.py` and validated with `spirv-val` (native and `--wave64-emulate`). **Not GPU-verified.** The base comes from the 64-bit SGPR pointer or the V# (dword0 \ \| dword1[15:0] << 32), and the stride is V# dword1[29:16]. **The runtime must put the game's GPU heap in buffer-device-addressable memory at the same addresses the game writes into descriptors** (or remap them). `s_load*` and `s_buffer_load*` take an immediate or an SGPR offset, or both at once (llvm-mc prints `sOFF offset:IMM`). Rules, measured on AMD Radeon RX 6800 (gfx1030, Windows driver 32.0.21045.29003) by running the instructions as a raw compute kernel, wave32 and wave64 (155 runs, every result either 0 or the stored data, wave32 = wave64 in every dword): **address** = (base & ~3) + (sOFF & ~3) + (IMM & ~3) + 4·i for dword i: base, sOFF and IMM are each truncated to a multiple of 4, then added (`s_buffer_load_dword s9, s[24:27], 0x3` with base & 3 = 1 reads +0, not bytes 4..7; sOFF 3 + IMM 3 reads +0 and sOFF 2 + IMM 6 reads +4, where truncating the sum gives +4 and +8; sOFF 8 + IMM 4 reads +12; the same for `s_load*` with pointer & 3 = 1 or 3). **`s_buffer_load*` bound**: dword i is 0, and memory is not read, when (sOFF & ~3) + (IMM & ~3) + 4·i + 4 > limit, with limit = NUM_RECORDS (V# dword2) bytes when the stride is 0 and NUM_RECORDS × stride bytes when it is not. Per dword (x4 at 0xc with NUM_RECORDS 21: data, data, 0, 0; x8 at 0 with 21: five data, three 0), on the truncated offset (IMM 0x10 with NUM_RECORDS 18: 0; IMM 0x13 with 21: the dword at +0x10; sOFF 0xe + IMM 2 with 16: the dword at +0xc; sOFF 0x10 + IMM 4 with 20: 0), not seeing base & 3 (base & 3 = 3, IMM 0x13, NUM_RECORDS 20: data); with a stride the test is still on bytes (stride 4, NUM_RECORDS 5: IMM 0x10 data, 0x14 0; stride 1, NUM_RECORDS 17: IMM 0x10 is 0, so it is not an index test). IMM is unsigned (0xffffc reads +0xffffc). OOB_SELECT (V# word3[29:28]) 0, 1, 2 and 3 gave the same pattern (7 probes per value). **`s_load*`**: no bound (+0x1ffffc reads the dword there); IMM is sign-extended from 21 bits and added in 64 bits (sOFF 8 + IMM −4 reads +4 where zero-extension reads 4 GiB further; sOFF 0xb + IMM −1 reads +4, so the negative IMM is truncated on its own: −1 → −4). **Negative sums** (SHADER-336), measured on the integrated GPU of a Ryzen 9 9950X3D (gfx1036, RDNA2, Windows driver 32.0.21045.16010) with `tools/smem_neg_probe.py --oracle hw`, wave32 = wave64: `s_load` with IMM −4 or −0x40 and no sOFF, sOFF 4 + IMM −8, sOFF 0xc + IMM −0x20 and the x2 form with sOFF 4 + IMM −0x10 read below the pointer at the 64-bit signed sum, and sOFF 6 + IMM −1 reads +0 (4 + −4, each term truncated on its own). `s_buffer_load` adds sOFF and IMM without wrapping at 32 bits: sOFF 0xfffffffc + IMM 8 and sOFF 0xfffffff0 + IMM 0x20 give 0 (past NUM_RECORDS 0x100), and sOFF 0xfffffffc, 0x80000000 and 0x7ffffffc alone give 0 (the translator has the same rule in both offset forms since #1686). An `s_buffer_load` IMM with bit 20 set (llvm-mc rejects it; −4, −0x10, 0x100000 and 0x100004 were encoded by hand) reads data that is neither 0 nor the buffer's own words, differently in wave32 and wave64: the bound does not hold for that encoding, so no compiler output uses it and the translator does not model it. `SmemHardwareRuleTests` in `tests/semantic/test_scalar_mem_smem.py` runs these rows with sOFF in a register and with sOFF known. **Measured since** on native RDNA2 (gfx1036, the Radeon iGPU of a Ryzen 7 9800X3D, Windows driver 32.0.21042.62) through `tools/hw_oracle`, one raw kernel, wave32 = wave64 in every dword (22 cases): **`x16`** takes the per-dword bound like x8 (`s_buffer_load_dwordx16` at offset 0 with NUM_RECORDS 0x24 gives nine data dwords and seven 0; offset 0x20 with 0x40 gives eight and eight; offset 4 with 0x3d gives fourteen and two; stride 4 with NUM_RECORDS 9 gives nine and seven), and `s_load_dwordx16` reads all sixteen; **NUM_RECORDS ≥ 2^31** is compared unsigned (0x80000000 and 0xffffffff with offset 0x10, and 0x80000000 with an x4 at 0x2f0, all read data); **NUM_RECORDS × stride ≥ 2^32** does not wrap (stride 4 × 0x40000001, stride 0x100 × 0x01000001 and stride 0x40 × 0x04000004 wrap to 4, 0x100 and 0x100 in 32 bits, yet offsets 0x10, 0x200 and 0x2f0 read data), as the translator's 64-bit product assumes; **V# dword1[31:30]** = 1, 2 or 3 changes nothing (a dword at 0x10, an x4 at 0xf8 with NUM_RECORDS 0x100 giving two data and two 0, and the same with stride 8 and NUM_RECORDS 4 at 0x18). Not measured: gfx1013 (PS5) itself. **Bound edges**, measured on the same GPU and driver with `tools/hw_oracle` (wave32 = wave64, every read inside a seeded region): `s_buffer_load_dwordx16` is bounded per dword like x8 (NUM_RECORDS 0x14 gives d0..d4 and 0 for d5..d15; 0x20 with IMM or sOFF 8 gives d0..d5); NUM_RECORDS × stride is not cut to 32 bits (stride 0x1000 × 0x100000 and 0x2000 × 0x80000 = 2^32, stride 8 × 0x20000001 = 2^32 + 8: all four dwords of an x4 at 0 are data; stride 8 × 1 gives two); NUM_RECORDS 0x80000000 and 0xFFFFFFFF are unsigned (an x4 at 0 reads all four). These are the rules the translator already used; `SmemHardwareRuleTests` pins them too (a 32-bit product, a signed NUM_RECORDS or one bound for the whole load each fail a test). Not measured: `x16` (gets the x8 rule), NUM_RECORDS ≥ 2^31 and NUM_RECORDS × stride ≥ 2^32, V# dword1[31:30], and gfx1013 (PS5) itself. `s_load`/`s_buffer_load` with sOFF + IMM < 0 (a negative IMM without sOFF included; the translator uses the 64-bit signed sum, an inference), an `s_buffer_load` IMM with bit 20 set (llvm-mc rejects it) or a negative one (kept as the 32-bit value: for stride 0 that is past any NUM_RECORDS below 4 GiB), `x16` (gets the x8 rule), sOFF ≥ 2^31, NUM_RECORDS ≥ 2^31 and NUM_RECORDS × stride ≥ 2^32, V# dword1[31:30], and gfx1013 (PS5) itself. The translator checks each `s_buffer_load` dword with its own structured `if` and an `OpPhi` with 0, so an out-of-range dword issues no load (when descriptor limit and offset are compile-time constants, in-range dwords fold to straight-line loads and out-of-range dwords emit constant zero without branches); `s_load` stays straight-line. Before this the translator added base + sOFF + IMM unaligned, had no `s_buffer_load` bound and zero-extended a negative `s_load` IMM. Checked by `tests/semantic/test_scalar_mem_smem.py` (`SmemHardwareRuleTests`, the measurement's rows, values and the addresses read; `SmemSoffsetImmTranslatorTests`) and by the GPU tests `runtime/test/shaders/cs_smem_soffset_imm.asm`, `cs_smem_bounds.asm`, `cs_smem_stride_align.asm` and `cs_smem_sload_neg.asm` (never run that one with a translator that zero-extends the immediate: it reads 4 GiB past the heap), all in `check.py` and `scripts/run_gpu_tests.py`, which pass on the RX 6800 (Vulkan, driver 26.11.2). See *Buffer bounds checking* below for the MUBUF `num_records` checks. **A constant SGPR offset** (`s_mov_b32 s12, C`, folded at translate time) is added as the run-time path adds `sOFF`: zero-extended, `& ~3`, after the immediate has been normalised (unsigned for `s_buffer_load`, 21-bit signed for `s_load`), with no 32-bit wrap. Until 2026-11-22 (#1686) the fold added it before the truncation, so `s12 = -4` with `offset:20` read byte 16 instead of being out of range, and an `s_load` `sOFF` of 2^20 or more was sign-extended from 21 bits (found by @Impre-visible; hardware measured by @Pierre-Kookis on gfx1036: 0xFFFFFFFC + 20 reads 0). CPU-checked by `tests/semantic/test_smem_const_offset.py` (each case constant vs run-time offset, and against the measured rule). Where llvm-mc rejects such a tuple, `restore_vcc_tuples` decodes it from the blob, and with it the instructions its junk text swallowed, up to the next instruction llvm-mc printed (corpus count: `docs/shader_library.md`, section 5). | | 2D array resource dimensions | For `image_get_resinfo` on a 2D array, X/Y are the width/height at the requested mip, Z is the view layer count and W is its mip count. The query reads the sampled array at binding 3. A native gfx1036 kernel returned (19,11,5,3), (9,5,5,3) and (4,2,5,3) for the three mips of a synthetic array. On RTX 5080 and Radeon Graphics the translated query matched those tuples and returned (4,2,3,2) at relative mip 1 with a view starting at mip 1 and covering three layers. The registered `ps_array_resinfo` draw checks all 4096 pixels against (8,8,12,1). | | Images and samplers | `image_sample_l` on 2D arrays used to read its LOD from the array layer; it now reads the LOD after all coordinates. `image_get_lod` and `image_gather4_lz` also work on 2D arrays. With `d16` every sample result is f16, packed two to a VGPR from the low half (the packed D16 of GFX10, as LLVM returns D16 image data); `image_sample_c_lz`/`_c_lz_o` follow it too, and until 2026-11-21 their compare result was written as f32 bits, which read as 0 in the low half. Checked by `tests/test_translate.py` (`test_depth_compare_sample_result_width`) and GPU-checked with `runtime/test/shaders/ps_sample_c_lz.asm` (`vk_texture_test dref`: a D32 texture and a LESS_OR_EQUAL compare sampler) on an NVIDIA GeForce RTX 2060 SUPER (Linux, driver 620.70.06): 4096/4096 pixels exact for f32 and `d16`; with the old translator the `d16` result read 0 in the 2048 pixels whose compare passes. | | Images and samplers (core) | Bindless. Set 0: binding 0 = 2D sampled images, 1 = samplers, 2 = descriptor hash table (storage buffer), 3 = 2D-array images (**cube textures are bound here as 6-layer 2D-array views**, cube arrays as 6N layers: the shader already selected the face with `v_cube*`), 4 = r32ui storage images, 5 = 1D, 6 = 3D. A cube sample's s and t come in [1, 2] and its third coordinate is 8·slice + face, as the hardware takes them (Mesa `ac_nir_lower_tex_coords.c`, LLPC `ImageBuilder.cpp`); the view is read at (s − 1, t − 1), layer 6·slice + face. GPU-checked with `runtime/test/shaders/ps_cube_sample.asm` (`vk_texture_test cube`). For a native Metal path, `tools/spirv_metal_set0.py` sizes set 0's runtime arrays from `vulkan_bindless.h` and moves each binding to its own argument-buffer ID range (binding b starts at the capacities of bindings 0..b-1 added up), to convert with SPIRV-Cross `--msl-decoration-binding`: SPIRV-Cross 1.4.363.0 otherwise puts every runtime array at one ID and comments all but one out as "Overlapping binding" (SHADER-161). `cs_imgstore` converted this way writes all 3×64 texels correctly in a native Metal dispatch on an Apple A18 Pro. | | Typed buffer loads | The format is V# word3[18:12] (GFX10_FORMAT, from Mesa's `gfx10-rsrc.json`, saved as `tools\gfx10_formats.json`). Supported: f32 ×1–4, u32 ×1–4, i32 ×1–4 (formats 21/63/73/76), f16 ×1/2/4, unorm8 ×1/2/4, snorm8 ×1/2/4, uint8 ×1/2/4, sint8 ×1/2/4, unorm16 ×1/2/4, snorm16 ×1/2/4, uint16 ×1/2/4, sint16 ×1/2/4, 10-10-10-2 and 2-10-10-10 unorm, and, since 2026-11-22, the other GFX10 buffer codes 1–77 (every USCALED/SSCALED, 10_11_11 and 11_11_10 FLOAT, the 10_10_10_2 and 2_10_10_10 families, 8_8_8_8 and 16_16_16_16 SINT and SCALED; see *Typed buffer formats*). Others (code 0 and 78 up) give 0. The 8- and 16-bit UINT/SINT formats 5, 6, 11, 12, 18, 19, 28, 61 and 70 were missing until 2026-11-22 and read 0: UINT channels zero-extend, SINT channels sign-extend, d16 packs them as 16-bit integers, measured natively on gfx1036 (wave32 and wave64) with `tools/hw_oracle` and checked word for word by `tests/semantic/test_buffer_format_narrow_int.py`; GPU-checked by `runtime/test/shaders/cs_fmt_int_narrow.asm`, whose 136 expected words are the same program run natively on gfx1036 (exact on an RTX 5080 and on the gfx1036 iGPU through Vulkan). Full-width SINT accesses preserve integer bits. D16 SINT loads saturate to signed 16-bit and D16 stores sign-extend, covered by the synthetic `cs_fmt_sint32.asm` readback. DST_SEL swizzle is applied (0→0, 1→1.0f for float/norm or integer 1 for UINT/SINT, 4..7→X..W). Missing channels repeat the format's own (component *c* = *c* mod *n*), measured on an RX 6700 (SHADER-86). UNORM/SNORM give the correctly rounded quotient by (2ⁿ−1), as the hardware does (0 mismatches vs hardware over 395,776 conversions on that GPU). It is built with integer ops (`Gen.norm_bits`): x/(2ⁿ−1) in binary is x's bits repeated, so a 64-bit multiply by the repeat pattern, `FindUMsb` and the round bit give the f32 exactly (the tail never ends, so there are no ties). `OpFDiv` is not enough on the GPU: Vulkan allows it 2.5 ULP, and on an RX 6700 (AMD Windows 26.11.2) and an RTX 5090 it returned the reciprocal-multiply bits (8_UNORM 130/256 exact, #599). Checked against exact values in `tests/semantic/test_norm_decode.py` (every value up to 8 bits, edges and the reciprocal-multiply misses for 10, 15 and 16 bits). 8_SNORM (2), 16_SNORM (8) and 8_8_SNORM (15) were missing until 2026-11-22 and decoded to 0. Format names list the channel widths from the top bit, so `2_10_10_10` (50) is R10G10B10A2 and `10_10_10_2` (44) has a 2-bit x (Mesa `gfx10_format_table.py`, `ac_formats.c`). Until 2026-11-22 the two were swapped, in stores too. Until 2026-11-21 an element that started mid-dword re-read dword 0 for its tail (`need` was `ceil(size/4)` and only the first dword was shifted); loads now take `need = ceil((byte_shift + size) / 4)` dwords and shift the whole window so the packed stream starts at the element (FUZZ-5, leftover from #234). The 10:10:10:2 order is checked by `cs_fmt_1010102` in `tests/semantic/test_value_semantics.py` (the shader decodes the format, so a GPU run can't check it). Mid-dword spanning elements are checked by `tests/semantic/test_buffer_load_format.py` (`CrossingDwordBoundary`); repeat / UNORM / DST_SEL 1 by the SHADER-86 cases in the same file. The `_xy` and `_xyz` forms (buffer and tbuffer) are GPU-checked by `cs_fmt_xy_xyz.asm`, whose words were measured natively on a Radeon 680M (gfx1035, RDNA2): they write only their 2 or 3 VGPRs, and missing channels repeat there too (TEST-185). | -| Descriptor hash table | `uint mask; entries[mask+1] of 10 uints: key[0..7], index, pad`. The key is a T# or a padded S#. FNV-1a over the eight key words selects the first slot. The shared SPIR-V lookup probes up to eight slots and returns index 0 on a miss. The runtime supplies a fallback at index 0 and maps live descriptor keys to bindless indices. Outside the wave64 emulation, the lookup's result goes through `OpGroupNonUniformBroadcastFirst` before it indexes the image or sampler array. The lookup key words come from SGPRs, so every invocation in a subgroup has the same index; the broadcast is an identity on all drivers and marks the value uniform for the compiler. It declares `GroupNonUniform` and `GroupNonUniformBallot`, without a shuffle capability or subgroup-lane input. The shader index records the capabilities; its `features` field lists optional Vulkan device features. Mesa ANV 26.2.7 on an Intel Alder Lake-S UHD (Xe-LP, Linux) segfaults in `vkCreate*Pipelines` on a sampler index taken straight from the probe loop when that sampler serves both a float and an integer image (`cs_sample_lz_int_d16`, `ps_ssharp`); with the broadcast both pass. Checked by the unit test `test_lookup_result_is_broadcast_before_use` in `tests/test_desc_cache.py` (standard library only: no GPU, LLVM or SPIRV-Tools). | +| Descriptor hash table | `uint mask; entries[mask+1] of 10 uints: key[0..7], index, pad`. The key is a T# or a padded S#. FNV-1a over the eight key words selects the first slot by default. With `--descriptor-hash=fnv1a_fmix32` the shader applies MurmurHash3 fmix32 before masking the slot. Every translated module then records `"descriptor_hash": "fnv1a_fmix32"` in its index entry. An absent key means `fnv1a`. The runtime and shader must select the same hash. The shared SPIR-V lookup probes up to eight slots and returns index 0 on a miss. The runtime supplies a fallback at index 0 and maps live descriptor keys to bindless indices. Outside the wave64 emulation, the lookup's result goes through `OpGroupNonUniformBroadcastFirst` before it indexes the image or sampler array. The lookup key words come from SGPRs, so every invocation in a subgroup has the same index; the broadcast is an identity on all drivers and marks the value uniform for the compiler. It declares `GroupNonUniform` and `GroupNonUniformBallot`, without a shuffle capability or subgroup-lane input. The shader index records the capabilities; its `features` field lists optional Vulkan device features. Mesa ANV 26.2.7 on an Intel Alder Lake-S UHD (Xe-LP, Linux) segfaults in `vkCreate*Pipelines` on a sampler index taken straight from the probe loop when that sampler serves both a float and an integer image (`cs_sample_lz_int_d16`, `ps_ssharp`); with the broadcast both pass. Checked by the unit test `test_lookup_result_is_broadcast_before_use` in `tests/test_desc_cache.py` (standard library only: no GPU, LLVM or SPIRV-Tools). | | Run-time format decode cost | A `buffer_load_format_*` whose format comes from the V# is decoded by table, without a branch: one shared function per output component (`%fmt_dec_c0`…`%fmt_dec_c3`) reads the format's kind, channel count and channel widths from the module table `%fmt_desc_tab`, and the kind picks the conversion with `OpSelect`; the exact UNORM/SNORM quotient comes from the shared `%fmt_norm_bits`, whose width's 64-bit repeat constant is read from `%fmt_norm_rep_tab`. A code outside the table gives zeros, a format with fewer channels repeats its own (component *c* = *c* mod *n*), and the element size is selected from the format alone (`%fmt_size_tab`), the per-lane byte offset added once. Until 2026-11-23 the shared function instead held every format's decode and a binary search over the codes (`OpSelectionMerge` with `DontFlatten`): 3,498 instructions and 306 branches in the module of a shader with one dynamic-format load (250,869 bytes). Now the four functions hold 565 instructions and no branch, and that module is 56,763 bytes. The decode functions take the format code and the element's four dwords as a `v4uint`, so their function type has a structure of its own: a type of `uint` × 5 repeats the type of the `x_round` helpers, and SPIR-V forbids two non-aggregate types with the same structure. Over the 1.0.2.1 corpus the 11,400 shaders that use this path all translate and pass \spirv-val\ (the previous translator included), and their modules shrink from 11,163,872,428 to 10,454,474,528 bytes (-6.35%). The 15,103 shaders without a run-time FORMAT come out byte for byte identical (checked on a 297-shader sample, every 51st of them). The values are unchanged: every one of the 128 codes gives the same words as the branch search, checked by `tests/semantic/test_format_decode_table.py` (each code against a reference decoded from the raw bits with exact quotients, plus the branch-free and shared-per-component shape). The old translation was confirmed on an RTX 4090 (621.01) against the decode-everything translation: identical output buffers for all 128 codes in four configurations (four byte alignments, out-of-range records, constant DST_SEL), xyzw and d16_xyzw. The branch-free decode costs more ALU per load than the search (every kind's conversion is computed and one is kept), so it trades run time for module size and compile time. | | 3D explicit-gradient texture samples | For `image_sample_d` and `image_sample_d_cl` on a 3D view, the first six address VGPRs contain dP/dx.xyz and dP/dy.xyz. XYZ and the optional minimum LOD follow. With `a16`, the six derivative VGPRs still hold f32; the following two words contain packed f16 coordinates and the optional clamp. The hand-written `tests/semantic/fixtures/volume_gradients.asm` checks the source registers of both gradients, coordinates and clamp. LLVM gfx1030 assembles all four forms and their modules validate for Vulkan 1.2. [LLVM GFX10 address sizing](https://reviews.llvm.org/D102231) and [SPIR-V Grad operands](https://registry.khronos.org/SPIR-V/specs/unified1/SPIRV.html#Image_Operands) | | `image_sample_c_l` | Scalar 2D depth comparison (`dmask:0x1`) takes the f32 reference, XY coordinates and explicit mip in that order. Under A16 the reference stays full-width; XY share a VGPR and LOD uses the next low half. D16 returns the comparison in the low half of the destination. Confirmed against LLVM AMDGPU's `llvm.amdgcn.image.sample[.a16].dim.ll` lowering and synthetic Vulkan 1.2 modules in `test_explicit_mip_depth_compare`. | @@ -307,12 +315,10 @@ How the generated SPIR-V expects the runtime to work: | Min-LOD clamp forms (`image_sample_cl`, `_b_cl`, `_c_cl`, `_c_b_cl`, and the `_o` forms) | The clamp is the component after the coordinates (address order: offset, bias, z-compare, coordinates, clamp), and becomes the `MinLod` image operand of the implicit-LOD sample (`OpImageSampleImplicitLod` / `OpImageSampleDrefImplicitLod`, with `Bias` and `Offset` before it in mask order), the same as the `image_sample_d_cl` that already existed; the module declares `MinLod` (`shaderResourceMinLod`, the harnesses skip a device without it). Outside the pixel stage there are no derivatives and the LOD is 0, so the clamp raises it: explicit `Lod = max(0, clamp)` and no `MinLod`. Under `a16` the clamp is packed with the coordinates (its own f16, with a pad after it in the last VGPR), as for `_d_cl`. With `--texel-offset-fallback` the Grad sample takes `Grad\|MinLod`. A clamp on a form that has no `_cl` instruction (`_l`, `_lz`, `_c_lz`) stays `Unsupported`. GPU tests: `ps_texture_cl` and `ps_texture_b_cl` on `vk_texture_test --two-mip` (coordinates / 4 so the unclamped LOD is -1; clamp 0.0 left of x = 32 reads mip 0 red, 1.0 from there on reads mip 1 cyan; dropping the MinLod operand turns the right half red); semantic: `tests/semantic/test_sample_cl.py` and the `_cl_o` forms in `tests/test_texel_offsets.py`. The compare forms (`_c_cl`, `_c_b_cl`) have no GPU test: the depth fixture has one mip level. Not translated: `_c_d`, `_c_cd`, `_d_cl` with compare, the g16 forms. | | Flat and scratch store operands | Register analysis reads the full address and data VGPR ranges and defines neither. A store after a block terminator can still appear in the listing scanned for PS live-ins. The CPU branch regression in `tests/semantic/test_store_liveins.py` checks both exported barycentric weights. LLVM gfx1013 confirms operand order. Reachable flat and scratch stores still raise `Unsupported`. | | Vertex fetch | `s_swappc_b64` at the start of a VS calls a driver-generated fetch program that isn't in the blob. It's replaced by Vulkan vertex inputs: each `ISG1` input-signature element (DXBC container) becomes an input at **location = its D3D input register**, typed by its component type, and is written to **v(4 + 4·register + component)**. That rule was checked over all 788 fetch-calling shaders: in 783 every read-before-write VGPR is predicted by it (715 exact). Reads of components the element doesn't declare (e.g. `.w` of an `xyz` position, 3 VS) are allowed: the fetch returns the format defaults (0, 0, 1), and Vulkan fills a `vec4` input from a narrower format the same way. Inputs are declared as `vec4`. **The runtime must bind vertex buffers by the game's D3D12 input layout, location = input register.** | -| `v_swap_b32` and pixel inputs | The swap reads and writes both VGPRs (AMD RDNA2 ISA, VOP1). A barycentric coordinate in the first operand is therefore a live input, and a coordinate or copy in the second operand is overwritten. When the swap changes an interpolation weight, the other incoming weight is still available to the pair. Checked by `tests/semantic/test_interp_computed_ij.py`: `test_swap_reads_both_incoming_barycentrics`, `test_swap_overwrites_interpolation_weight_in_second_operand` and `test_swapped_copies_swap_the_weights` run synthetic fragment exports through the SPIR-V interpreter. | +| `v_swap_b32` and pixel inputs | The swap reads and writes both VGPRs (AMD RDNA2 ISA, VOP1). A barycentric coordinate in the first operand is therefore a live input, and a coordinate or copy in the second operand is overwritten. When the swap changes an interpolation weight, the other incoming weight is still available to the pair. Synthetic `test_interp_computed_ij.py` fragment exports check the raw swap and interpolation through both forms. | | PS system inputs | v0–v1 = barycentrics (consumed by `v_interp`, which becomes attribute inputs). **v2.. = the `SV_Position` components the shader reads, packed in order**. Counted over all 12,101 PS listings of 1.0.2.1 (names starting with `.` included; `rdna2spirv.read_before_write_vgprs`, with `v_interp`'s I/J operands left out as the translator does, against the ISG1 read masks from `input_signature_full`; an earlier sample gave 2,531 of 3,000): in 12,098 the VGPRs they read before writing inside the system-input range (v2 up to the last hardware input) equal exactly the position components their input signature reads, then front face when its read mask is non-zero. The 1,639 PS that declare `SV_IsFrontFace` with read mask 0 never read that slot; the translator still places it, last of the inputs this layout models, so no other modelled input moves. The other 3 read fewer position components than their read mask says. Verified on 2,531 of 3,000 PS: the VGPRs they read before writing equal exactly the position components their input signature reads. Filled from `FragCoord`: xy/z directly, and **w directly too**, because AMD's position-w register holds 1/w (Mesa lowers `load_frag_coord_w_rcp` straight to `frag_pos[3]`, `ac_nir_lower_intrinsics_to_args.c`), the same as Vulkan's `FragCoord.w`. **Front face** follows the used position components when the signature declares `SV_IsFrontFace`, as ±1.0 (Mesa: `load_front_face` = `front_face > 0`). Only enabled inputs are packed, in hardware order (Mesa `radv_shader_args.c`: barycentric pairs, POS_X/Y/Z/W, FRONT_FACE, ANCILLARY, SAMPLE_COVERAGE, POS_FIXED_PT). That explains the earlier "unverified" shaders: of the 345 PS that read front face, 130 read pos.xy + front face and 141 pos.x/y/w + front face. That explains the earlier "unverified" shaders: 102 read pos.xy + front face, and 76 read pos.x/y/w + front face. **Raw barycentric reads** (321 PS, e.g. `v_readfirstlane_b32 s41, v1`): AMD interpolates P = P0 + i(P1 − P0) + j(P2 − P0), so i/j are the weights of vertices 1/2, which is `BaryCoordKHR.y`/`.z` (`VK_KHR_fragment_shader_barycentric`). GPU-checked with `runtime/test/shaders/ps_bary.asm`: raw i/j equal the interpolated weights on every pixel. `ps_persp_bary.asm` (the same code drawn by `vs_persp.asm`, clip w = 1, 2, 4) checks them, and the interpolated attributes, against perspective-correct CPU weights; the affine weights differ by at least 0.006 on every covered pixel (all 1158 judged), so `NoPerspective` interpolation fails it. The pair is perspective-center, the only pair this layout models; that holds for every corpus PS (row "PS interpolation modes"). A PS that reads any other unexplained register inside the system-input range is still rejected (none left in the corpus). Reads past the last hardware input are values undefined on some path, so zero stands in for them. 373 PS have one (and 85 more whose raw listing holds embedded data words). In each of the 373 a branch instruction comes earlier in listing order than the first such read; in 364 the register is written later in listing order, which suggests a loop-carried value (inferred from listing order, not measured on the control flow), in 9 never after the read. All register arrays start at zero, so translated shaders are deterministic. | | Partial pixel color exports | Each MRT retains channels from earlier exports when the current `exp` disables them. Uncompressed exports enable individual RGBA channels and compressed exports enable the RG and BA pairs. Partial MRT outputs start at zero so a channel the shader never writes keeps its existing translator default. The CPU test in `tests/semantic/test_export_valid_mask.py` checks the eight RGBA words from two interleaved targets in `partial_color_exports.asm`. [AMD RDNA 2 ISA, sections 11.1 and 11.2.1](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) | | Inputs and outputs | VS: **legacy (non-NGG) hardware VS, measured** over all 2,236 (`scripts/vs_input_survey.py`): no `exp prim`, no `s_sendmsg` (so no `GS_ALLOC_REQ`) and no `v_mbcnt` in any of them, and every one exports `pos0` and `param`. The input VGPRs are Mesa's GFX10 legacy-VS layout (`radv_shader_args.c`, `declare_vs_input_vgprs`, not `is_ngg`): `v0` = vertex id, `v1` unused, `v2` = primitive id, `v3` = instance id. On entry no VS reads `v1` or `v2`; 788 start with the fetch call (see *Vertex fetch*) and read the fetched attributes from `v4` up, and of the other 1,448, 1,052 read `v0` only, 386 `v0` and `v3`, and 10 neither (NGG would have put the VS inputs at `v5`/`v8`, after five GS VGPRs). **Both ids are zero-based on the hardware**: `v0` excludes the draw's base vertex and `v3` its first instance (Mesa `ac_nir_lower_intrinsics_to_args.c`: `vertex_id` is `load_vertex_id_zero_base`, `instance_id` is `load_instance_id`; the bases come in the `base_vertex` / `start_instance` SGPRs). Vulkan's `VertexIndex` / `InstanceIndex` include `firstVertex`/`vertexOffset` / `firstInstance`, so the translator seeds `v0 = VertexIndex - BaseVertex` and `v3 = InstanceIndex - BaseInstance` (`DrawParameters`, device feature `shaderDrawParameters`, in every VS's `features`). GPU-checked with `runtime/test/shaders/vs_base_ids.asm` (`VKH_DRAW=16,7`): `0x101` on every pixel, where `VertexIndex`/`InstanceIndex` alone gave `0x7111`. `exp pos0` → `Position`, `exp pos1..pos3` → `ClipDistance` / `CullDistance` (and `Layer`/`ViewportIndex` in VS when `pos1` is the misc vector), `exp paramN` → location N. RDNA2/GFX10 packs clip distances before cull distances contiguously across 4-component `pos` exports (up to 8 floats total), starting at `pos2` when a misc vector (`PointSize`, `EdgeFlag`, `ShadingRate`, `Layer`, `ViewportIndex`; GFX9+ packs `Layer` in `z[10:0]` and `ViewportIndex` in `z[19:16]`) occupies `pos1`, and at `pos1` otherwise (Mesa `src/amd/common/nir/ac_nir_prerast_utils.c`: `ac_nir_export_position`; AMD LLPC `lgc/lowering/LowerInOut.cpp`: `LowerInOut::visitReturnInst`). Slot assignment follows the DXBC `OSG1` signature (`SV_ClipDistance` = 2, `SV_CullDistance` = 3, `SV_RenderTargetArrayIndex` = 4, `SV_ViewportArrayIndex` = 5, `SV_ShadingRate` = 23), ordered by `(semantic_index, register, component)` with clip before cull; when `OSG1` is absent (or declares none of those system values), `pos1..pos3` exports are discarded. PS: `v_interp_*` attribute N → input location N. `exp mrtK` → the location of the K-th declared `SV_Target` (**Pixel colour exports**): colour exports are packed, so a shader that declares `SV_Target0` and `SV_Target2` exports `mrt0` and `mrt1`, and `mrt1` is render target 2. Counted over the 1.0.2.1 corpus (SHADER-210): of 10,500 pixel shaders with `SV_Target` outputs (OSG1 system value 64, register = semantic index in all 29,290), the 221 that declare non-consecutive targets all export `mrt0`..`mrt(k-1)`, never `mrtN` at register N. Without an OSG1 (hand-written listings, `run_gpu_tests.py` fixtures) `mrtK` is location K. An export past the declared targets is `Unsupported`. `tests/semantic/test_sparse_sv_target.py`. `exp mrtN` → location N, `exp mrtz` x → `FragDepth` only when x is on in an uncompressed export; the 16-bit `compr` form holds stencil and sample mask, never Z (Mesa `ac_nir_lower_ps_late.c` `emit_ps_mrtz_export`), and an export without Z must not declare `DepthReplacing`. `exp mrtN` → location N, `exp mrtz` x → `FragDepth`. | -| VS input layout, per PAL hardware stage | `scripts/vs_layout_census.py` joins every tag-0x0D payload's PAL stage record (`tools/pal_stages.py`) with its code markers over all 26,698 payloads of the 26,503 1.0.2.1 containers: the 2,236 stage-4 (VS) payloads are **all** legacy non-NGG — no `exp prim`, no `s_sendmsg`, no `v_mbcnt`, and every one exports `pos0` and `param` — so the Mesa GFX10 legacy-VS layout of *Inputs and outputs* holds for every VS the corpus translates, and `v0` = `VertexIndex` (zero-based, `DrawParameters`) is confirmed rather than NGG. The NGG markers belong to the 9,282 stage-7 payloads (every one has `exp prim`, `s_sendmsg MSG_GS_ALLOC_REQ` and `v_mbcnt`), the 195 stage-3 payloads are the geometry shaders (`s_sendmsg` + `v_mbcnt`, no position export), and the 195 stage-2 payloads are the ES variants of the next row; the PS (12,101) and CS (2,689) payloads carry `v_mbcnt` (332 and 266) and, in ten PS, an `s_sendmsg`, but no `exp prim`. | -| VS as ES (two-payload VS containers) | 195 `$VS_VoxelizeGeneric_*` containers carry **two** tag-0x0D payloads: besides the legacy VS above, a stage-2 (`es`) payload — the vertex shader compiled for the export-shader stage of a legacy geometry-shader pipeline. It has **no `exp`** (the vertex outputs go to LDS with `ds_write*` for the GS to read), takes its lane id from `v_mbcnt`, and on entry its read-before-write VGPRs are `v5`, `v9`, `v10`, `v11`, `v13` and `v14` (never `v0`/`v3`); none of the 195 starts with the fetch call. `fssm_unpack.py` defaults to the **last** payload, so the corpus translates the VS variant; the ES variant is untranslated, and which payload a GS-bound pipeline selects is open (`docs/fssm_crosscheck.md` §6). | | 16-bit results | From Mesa ACO (`aco_ir.cpp`: `instr_is_16bit`, `can_use_opsel`) for GFX10: **f16 VOP1/VOP2 ops** (`v_add/sub/subrev/mul/max/min_f16`, `v_fmac_f16`, `v_cvt_f16_f32`, f16 unary) and **opsel-capable VOP3 ops** (`v_fma_f16`, `_e64` forms of the 16-bit integer ops) are **partial writes that keep the high half**. The **VOP2 (`_e32`) 16-bit integer ops** (`v_lshrrev_b16`…) define the whole register, so the high half is modelled as zero. An op_sel destination bit writes the high half. The translator used to clear the high half on f16 ops; that's fixed. **op_sel on f16 VOP3 ops** (`v_fma_f16`, `v_med3_f16`, `v_add/sub/subrev/mul/max/min_f16`, f16 unary, `v_fmac_f16`): bit i (i < number of sources) reads the high half of source i, the last bit writes the high half of the destination; neg/abs apply to the selected half. Source: Mesa ACO `can_use_opsel` and the RDNA2 ISA VOP3 `OP_SEL` field. Checked by the structural tests in `tests/test_f16_op_sel.py` (which half is read, where the result goes) and the value tests in `tests/test_f16_op_sel_values.py`. **Hardware-verified** on an AMD RX 6800 (gfx1030), the instructions run as a raw compute kernel in wave32 and in wave64 (IEEE off, DX10 clamp on, denormals kept, round to nearest; the bytes assemble identically for gfx1013 and gfx1030): **`v_med3_f16`** with all 16 `op_sel` patterns, with neg/abs on a selected high half, with `clamp`, and with the destination also a source; the **plain forms** `v_add/sub/mul/max/min_f16` (`_e32`, and `_e64` with neg/abs/`clamp`), `v_fmac_f16` (`_e32`, and `_e64` with neg/abs; the accumulator is the low half of the destination), `v_rndne/floor/ceil/trunc/fract/sqrt/rcp/rsq_f16` (`_e32` and `_e64`) and `v_cvt_f16_f32`: low halves in, low half out, high half of the destination kept. 336 words per wave size (plus `v_rsq_f16_e64` and `v_ceil_f16_e64` in a later run), all as the rule says and as the translator computes. **Vulkan** (AMD Radeon RX 6800, Windows, driver 26.11.2; the nine `ps_f16_*` fixtures also pass on an NVIDIA RTX 4050 Laptop and an AMD Radeon 740M (RADV), both Linux): `ps_f16_med3_opsel`, `ps_f16_med3_mods`, `ps_f16_vop2`, `ps_f16_vop2b`, `ps_f16_vop1`, `ps_f16_vop1b`, whose expected words are the hardware ones (`tests/test_f16_hw_words.py` checks them against the rule and the translator without a GPU). **Not expressible, so not verified:** `op_sel` on the VOP2 and VOP1 ops in VOP3 encoding (`v_add/sub/mul/max/min_f16_e64`, `v_fmac_f16_e64`, the unary `_e64` forms, `v_cvt_f16_f32_e64`): llvm-mc 21 rejects the modifier for gfx1013 and gfx1030, and its disassembler prints bytes that have those bits set without it (`03 08 32 d5 01 05 02 00` comes back as `v_add_f16_e64 v3, v1, v2`). The translator's `op_sel` handling for these forms is therefore never reached from a disassembly listing and rests on the ISA field description alone; whether the hardware honours the bits there is unknown, and a blob that set them would be translated as if they were clear. Also unverified: NaN and denormal operands, other rounding and IEEE modes, outside the f16 transcendentals (measured, see the f16 transcendentals row). **Driver quirk (AMD Windows driver 26.11.1, RX 9070):** `valu_fuzz` f16 seed 3 programme 38 loses the high half of v26: `v_add_f16_e32 v26, v29, v32` then `v_sub_nc_u16_e64 v28, v32, v27 op_sel:[1,1,0]` then `v_add_f16_e64 v26, v26, v28` — the final add should keep `0xCD52` in the high half, but the GPU returns `0xEEEEEEEE` (native) / `0x00000000` (`--emulate`), all 64 threads. Bisected to the pair: the add's two sources must both have been produced by earlier partial writes; either alone, a NaN input alone, or `dst==src0` alone all pass. The emitted SPIR-V was checked with `spirv-dis` in both modes: the keep (load old v26, `AND 0xFFFF0000`, `OR` new low half, store to index 26) is present and correctly addressed, so the translator is clear and this is the driver miscompiling the pattern. Minimal reproducer: the three ops above with programme 38's inits (v26 `0xCD524000`, v28 `0xC692D243`, v29 `0xBC004200`, v32 `0xB35ABD4B`, v27 `0xB48ABA06`). Pinned by `tests/test_values.py` (`v_add_f16_e64_keep_hi`, `v_add_f16_e32_keep_hi`), which check the translator's keep, not the driver. Found and bisected by 1TrickOmen, reported on #634. | | 16-bit SDWA result with `dst_sel:DWORD` | A 16-bit op in SDWA form (`v_add/sub/subrev/mul/min/max_f16_sdwa`, the f16 unary ops, `v_cvt_u16_f16`, `v_cvt_i16_f16`, `v_cvt_f16_u16`, `v_cvt_f16_i16`) with `dst_sel:DWORD` writes the whole VGPR: the 16-bit result zero-extended, **whatever `dst_unused` says**. The keep-the-high-half rule of the row above is for the non-SDWA forms only; with `dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE` the high half is kept as usual. **Until 2026-11-22 the translator kept the high half for `dst_sel:DWORD`** (`Gen.insn` marked an SDWA destination only for a `dst_sel` other than DWORD). Measured natively on an AMD Radeon iGPU (gfx1036, RDNA2, Windows driver 26.10.1) with `python -I tools/sdwa_diff.py --oracle hw` (#2113) and with the program of `runtime/test/shaders/ps_sdwa_dword_hi.asm` through `tools/hw_oracle`: destinations 0xdeadbeef give 0x00004000 (`v_add_f16`, PRESERVE), 0x00000003 (`v_cvt_u16_f16`, PAD), 0x00004700 (`v_cvt_f16_u16`, PRESERVE), 0x0000c000 (`v_mul_f16`, SEXT); the same ops with `dst_sel:WORD_0 UNUSED_PRESERVE` give 0xdead4000, 0xdead0003, 0xdead4700, 0xdeadc000. GPU-checked through Vulkan with `ps_sdwa_dword_hi.asm` on an RTX 5080 (driver 616.92) and the same Radeon iGPU (4096/4096 pixels each); CPU-checked in `tests/semantic/test_value_semantics.py`. | | f16 inline constants | An inline float constant (`0.5`, `1.0`, `2.0`, `4.0`, their negatives, `0.15915494`) in an operand of a 16-bit float op is the **f16 value in the low half with a zero high half**, not f32 bits (the translator used to unpack the f32 pattern, whose low half is 0, so `v_add_f16 d, 1.0, v` added 0.0). Measured on an AMD RX 6800 (gfx1030) raw kernel, wave32 and wave64: `v_add/mul/max_f16`, `v_sub_f16_e64`, `v_fma_f16`, `v_fmac_f16`, `v_rcp_f16`, `v_med3_f16`, `v_cmp_lt_f16`, `v_cvt_f32_f16` (`0.5` gives `0x3f000000`), `v_cos_f16`, `v_pk_add_f16`/`v_pk_mul_f16` (the high result half sees 0.0), `v_pack_b32_f16`; `0.15915494` is `0x3118`; the high half `op_sel` selects from a constant reads +0.0 (`v_med3_f16`, `v_fma_f16`, `v_pack_b32_f16`, `v_pk_add_f16` with swapped halves). GPU tests `ps_f16_const`, `ps_f16_const2` and `ps_f16_pack` (Vulkan: AMD Radeon RX 6800, Windows, driver 26.11.2; all three fail without the fix). Constants in `v_fma_mix_f32`/`v_fma_mixlo/mixhi_f16` operands follow the same rule per operand (measured on an RDNA2 iGPU, gfx1036, SHADER-135): f32 bits where `op_sel_hi` makes the operand f32, the f16 constant with a zero high half where it makes it f16, so `op_sel` with `op_sel_hi` reads +0.0; an integer constant is its 32-bit integer. The translator gives the same words for the float constants in every `op_sel`/`op_sel_hi` combination and for the integer constants as f16 halves, but not for `1` and `64` as f32 operands: their bits are f32 denormals, which gfx1036 flushes to a zero of their sign (`denorm_mode_32 = 0`, the MODE the translator assumes for the game) and the translator keeps (difference 4 in docs/shader_validation.md, "f16 output modifiers, clamp and `v_fma_mix*` operands on RDNA2"). | @@ -335,7 +341,7 @@ How the generated SPIR-V expects the runtime to work: | Texel offsets | `image_sample*_o`: the first address dword packs signed 6-bit offsets (x [5:0], y [13:8], z [21:16]), which become the SPIR-V `Offset` operand. A non-constant `Offset` outside gather needs **`VK_KHR_maintenance8`**, and is validated with `spirv-val --allow-offset-texture-operand`. The operand is always a run-time value: the translator extracts the fields from the register, also when the shader loaded the dword from an immediate, so every `_o` sample needs the extension. `image_gather4_lz_o` / `_l_o` read x and y the same way; a gather `Offset` needs `shaderImageGatherExtended`, not maintenance8. **GPU-tested** with `runtime/test/shaders/ps_texoff.asm` on `vk_texture_test` (in `check.py` and `scripts/run_gpu_tests.py`; SKIP on a device without the extension), on an AMD Radeon RX 6800, Windows driver 26.11.2, maintenance8 enabled: an 8×8 texture whose texels are all different, a point sampler that clamps to the edge, 2D targets, mip 0. `image_sample_lz_o` with an offset computed per pixel (all 64 pairs of x, y in −4..3, none clamped), `image_sample_l_o` with (−3, +2) and `image_sample_lz_o` with (+16, −32) from immediates, and `image_gather4_lz_o` of red and of green with the per-pixel offset gave, on all 4096 pixels, the texels worked out by hand from this rule (derivation in the `.asm` header). Run with a sabotaged translator, the test fails when the sample offset is dropped, has x and y swapped, takes y from bit 6, or uses 4-bit or 5-bit fields, and when the gather offset is dropped, has x and y swapped or takes y from bit 6; 4-bit and 5-bit gather fields pass, because the gather offsets stay in −4..3. What it shows is that the translated SPIR-V implements this rule on Vulkan; it does not measure the field layout on the hardware. **It cannot see the sign extension on this driver**: with the fields read unsigned the same texels come back: `Offset` 60..63 sampled as −4..−1 and +32 as −32 (the device reports texel offset limits −64..63, gather −32..31). The sign extension and the gather field width are therefore pinned by the structural test `tests/test_texel_offsets.py` (signed, bit 8k, 6 bits, for `_lz_o`, `_l_o`, `_o`, 3D and gather) and are not GPU-tested through Vulkan. **The x field is measured on hardware:** `image_sample_lz_o` run as a raw compute kernel on the same RX 6800 (gfx1030, wave32 and wave64), on a 64×1 `R32_FLOAT` image whose texel i holds i, with a point sampler that clamps to the last texel: from texel 40, offset dword `0x20` reads texel 8 and `0x3c` reads texel 36 (unsigned would clamp both to 63); from texel 10, `0x1f` reads 41 and `0x20` clamps to 0; `0x40`, `0x80` and `0xc0` read the centre texel (bits 6–7 are ignored); and a non-zero y field, z field or top byte leaves x alone. All 36 rows fit x = sign-extended bits [5:0]. **The y and z fields are measured too** (SHADER-337): `tools/texoff_probe.py --oracle hw` on the integrated GPU of a Ryzen 9 9950X3D (gfx1036, RDNA2, Windows driver 32.0.21045.16010), wave32 and wave64, samples a linear `R32_SFLOAT` texture whose texel holds its index (2D 64×64 for y, 3D 64×1×64 for z) with `image_sample_lz_o` and a point sampler that clamps to the last texel. From row 40, y = `0x20` reads row 8 and `0x3c` row 36, `0x21` row 9 (unsigned would clamp all three to 63); from row 10, `0x1f` reads 41 and `0x20` clamps to 0 (unsigned: 42); `0xc0` (bits 14–15 set, field 0) reads row 40 and `0x7f` row 39, so those bits are ignored; x −2 with y −4 in one dword reads both. The z field at bits [21:16] gives the same 7 results on the 3D image. All 15 rows fit each field = sign-extended 6 bits, the bits above it ignored, which is the translator's rule; `tests/test_texoff_probe.py` checks that every row with a negative field tells the signed reading from the unsigned one. The (+16, −32) sample is outside Vulkan's guaranteed −8..7 and is judged only where the device limits cover it. **`image_sample_o`, `image_sample_b_o` and `image_gather4_l_o` are GPU-tested** with `runtime/test/shaders/ps_texoff_forms.asm` (the same texture, sampler and per-pixel offset as `ps_texoff`, all 64 offset pairs in −4..3; in `check.py` and `scripts/run_gpu_tests.py`): 4096/4096 pixels exact on an NVIDIA GeForce RTX 4090 (driver 621.24) and on the integrated GPU of a Ryzen 9 9950X3D (gfx1036, driver 32.0.21045.16010), both with maintenance8 enabled. Not GPU-tested: `_c_lz_o`, the z field (3D), 1D, 2D-array and cube targets (offset next to an array layer), wrap or mirror addressing, linear filtering, mips other than 0, other vendors' drivers, and a device without maintenance8 (the test skips there; the translator has no fallback for it). **Without maintenance8 (`--texel-offset-fallback`, NVIDIA Pascal for one):** an `image_sample*_o` gets no `Offset`; the offset is folded into the coordinate instead, as coordinate + offset ÷ the size of the sampled level. The level is 0 for `_lz` / `_c_lz`, the given LOD for `_l`, and `OpImageQueryLod`'s for implicit samples (plus the bias for `_b`), rounded the way the S#'s `MIP_FILTER` (word 2 [27:26], literal or read at run time) picks a level, and clamped to the image's levels: floored for linear, nearest with a tie rounding up for point (floor(LOD + 0.5), computed as floor + (fraction ≥ 0.5) so binary32 rounding of the sum can't move it; Vulkan allows either tie rule, and RTX 5070 GPUs (drivers 616.56, 621.01) sample LOD 0.5 and 0x3f000001 at mip 1, as `tools/image_query_probe.py` records RDNA2 doing) and for the value 3, and 0 for none, whose LOD the runtime holds in [0, 0.25] (SHADER-699: a point-mip sample at LOD 0.75 reads mip 1, so flooring shifted it by mip-0 texels; checked in `tests/test_texel_offsets.py` by evaluating the emitted level chain). A texel offset applies before wrapping and clamping, and an integer offset commutes with both, so the shift is exact for every address mode at that level. The one case that differs is a trilinear blend of two levels, where the coarser level moves by offset ÷ 2 of its texels. Implicit samples become `Grad` samples with the derivatives of the unshifted coordinate (× 2^bias for `_b`), so the LOD and anisotropy are those of the original sample even when the offset varies per pixel. Gathers keep their `Offset` (`shaderImageGatherExtended`). Only 4 of the 12,101 PS need it, all through `image_sample_o`. **GPU-tested** on an NVIDIA GeForce GTX 1060 6GB (no maintenance8; driver 560.94, Windows 10) with `LEONIDA_TEXOFF_FALLBACK=1`: `ps_texoff` and `ps_texoff_implicit` (the per-pixel sample as `image_sample_o`) are 4096/4096 pixels exact, with the +16/−32 sample judged too, since a coordinate shift has no device offset limit. Checked in `tests/test_texel_offsets.py`, including `spirv-val` without `--allow-offset-texture-operand`. | | A16 sample offsets | For the supported `image_sample*_o` forms, the first address VGPR retains the signed texel-offset fields. The following coordinates and any trailing LOD use packed binary16 halves, low half first. LLVM counts extra operands as whole words before packing coordinates and LOD ([getAddrSizeMIMGOp](https://llvm.org/docs/doxygen/AMDGPUBaseInfo_8cpp_source.html#l00342)). On RTX 5080 and Radeon Graphics, `ps_texoff.asm` checked 64 distinct offsets applied to packed U/V at texel (3,5) against the expected texel for each of 4096 pixels. Swapping the halves or dropping the offset changed 4032 pixels per GPU. | | `s_memtime`, `s_memrealtime` | Behind `--shader-clock khr` (default `off`: both stay `Unsupported`, as before). `s_memtime` is the per-CU shader clock: `OpReadClockKHR` with Subgroup scope; `s_memrealtime` is the constant-rate REFCLK counter: Device scope. The 64-bit result goes to the destination SGPR pair, low word first; other destinations are `Unsupported`. Each module declares `ShaderClockKHR` + `SPV_KHR_shader_clock` and lists `shaderSubgroupClock` and/or `shaderDeviceClock` in the index `features`, only for the scopes it reads. The runtime enables `VK_KHR_shader_clock` with whichever feature the GPU has (`VulkanDeviceInfo::shader_subgroup_clock` / `shader_device_clock`, checked by `d3d12_vulkan_device_test`); the shader library does not read `features`, which is why the rule is opt-in: a module with a scope the device lacks fails `vkCreateShaderModule`. Values are not comparable with a console GPU's (different clock and frequency), so time differences work and fixed-frequency assumptions don't. CPU-checked by `tests/semantic/test_smem_clock.py` (scopes, capability/extension, features, spirv-val, off by default). GPU: a PS reading both clocks creates its pipeline (`vk_pipeline_check`) on an RTX 6000 Ada (Linux) and an RX 9060 XT (RADV, #2817). The values themselves are not measured. | -| A16 gather offsets | On GFX10, `image_gather4_lz_o` and `image_gather4_l_o` take the packed signed texel offset in a full VGPR before the packed binary16 coordinates and optional LOD. LLVM [counts the extra operand before packing coordinate words](https://llvm.org/docs/doxygen/AMDGPUBaseInfo_8cpp_source.html#l00342). The synthetic `gather_offset_a16.asm` checks an offset of (−1,+1) with distinct U and V and a nonzero mip. Checked by the unit test `test_a16_offset_gathers_preserve_offset_and_unpack_uv_lod` in `tests/test_image_load_typed.py`, which translates that fixture and its `gather4_lz_o` variant and follows the offset fields and the packed U, V and LOD halves back to their source VGPRs. | +| A16 gather offsets | On GFX10, `image_gather4_lz_o` and `image_gather4_l_o` take the packed signed texel offset in a full VGPR before the packed binary16 coordinates and optional LOD. LLVM [counts the extra operand before packing coordinate words](https://llvm.org/docs/doxygen/AMDGPUBaseInfo_8cpp_source.html#l00342). The synthetic `gather_offset_a16.asm` checks an offset of (−1,+1) with distinct U and V and a nonzero mip. | | Optional device features | Shaders may need `fragmentShaderBarycentric`, `fragmentShaderPixelInterlock` and `maintenance8`. All three are present on an RTX 4060 Ti (and an RTX 2060 SUPER), and `runtime/test/vk_harness.cpp` enables them when available, as does the runtime's `create_vulkan_device_standalone`, each with its extension (`VulkanDeviceInfo::fragment_shader_barycentric`, `fragment_shader_interlock`, `maintenance8`; checked by `d3d12_vulkan_device_test`). All three are present on an RTX 4060 Ti, and `runtime/test/vk_harness.cpp` enables them when available. (It is guarded by the header macro `VK_KHR_MAINTENANCE_8_EXTENSION_NAME`, so older Vulkan headers build without it. `vk_texture_test` enables it too, and `shaderImageGatherExtended`.) A device without `fragmentShaderBarycentric` (NVIDIA Pascal) runs the raw-barycentric PS with `--bary-fallback` (below). Shaders translated with `--fma khr` need `VK_KHR_shader_fma` and its `shaderFmaFloat32` feature (`VkPhysicalDeviceShaderFmaFeaturesKHR`): `create_vulkan_device_standalone`, `runtime/test/vk_test_device.h` and the `vk_*` test programs enable it when the device offers it (`VulkanDeviceInfo::shader_fma`), and a test program refuses (exit 77) a module with `OpCapability FMAKHR` on a device without it. | | Wave size | **Most of the game's shaders are wave64: 23,841 of 26,503** (`fssm_header.wave_size()`: FSSM header flags word `u32[0xD4]` bit 5, `0x20` = wave32, `0` = wave64; 0 contradictions against GFX10 code-proven wave32/wave64 instructions across all 26,503 blobs): 10,974 of 12,101 PS, 9,282 of 9,282 mesh shaders, 2,236 of 2,236 VS, 1,154 of 2,689 CS and 195 of 195 GS, against 2,662 wave32 (1,535 CS and 1,127 PS). A full-corpus translation at `ec8ec4c9` marks exactly these 23,841 `wave64` (`subgroup_size` 64) in the index. Before the FSSM flag (#1900) the wave size came from code markers (64-bit EXEC/mask writes, `exec_hi`, `*_saveexec_b64`): at `6a6704df` they made 21,538 of the 26,487 shaders translated then wave64 (the figure quoted here was 21,545). 10,031 PS, 9,282 mesh shaders, 1,179 VS, 851 CS and 195 GS (the 16 shaders refused then are all wave64 CS by the flag; the figure quoted here was 21,545). Against the flag they call 2,287 wave64 shaders wave32 (943 PS, 1,057 VS, 287 CS), whose code has no 64-bit EXEC/mask marker, and none the other way. An older marker scan (`s_mov_b64 exec, -1`, `exec_hi`, `s_and/or_saveexec_b64` and 64-bit masks) counted 9,930 PS, 8,666 mesh shaders, 1,115 VS and 923 CS, but it left out the 769 listings whose names start with `.` (616 of them mesh shaders; Python's `glob` skips such names). Over all 26,503, the translator's own marker test (`WAVE64_RE`, or a 64-bit op on EXEC/VCC) on the code `translate()` keeps finds 21,554 wave64: 10,031 PS, 9,282 mesh shaders, 1,179 VS, 867 CS and 195 GS. With the 2,287 above that is exactly the flag's 23,841, and none contradicts it; read raw, 104 more wave32 listings (80 CS, 24 PS) seem to carry a marker, all from embedded data words decoded as instructions. The first marker scan (`s_mov_b64 exec, -1`, `exec_hi`, `s_and/or_saveexec_b64` and 64-bit masks, written into this row at `0082ad53`) counted 9,930 PS, 8,666 mesh shaders, 1,115 VS and 923 CS: 20,634 without the GS, so not the 21,545 total either. The translator maps a wave to a subgroup, and NVIDIA subgroups are 32 wide. What that means: (1) lane-independent code, which is most pixel-shader math, is exact; (2) wave-wide branch decisions and reductions are made per 32-lane half, which is exact unless scalar state computed for one half is later consumed by the other; (3) lane indices from `v_mbcnt_lo/hi` and wave IDs from the merged-wave SGPR must be 64-lane values. Mesh and compute shaders build thread IDs as wave_id·64 + mbcnt, so those need a mapping from `LocalInvocationIndex` (lane = index & 63, wave = index >> 6). Full fidelity needs either 64-wide subgroups (AMD GPUs, via `VK_EXT_subgroup_size_control` requiredSubgroupSize = 64) or emulating cross-half ops (ballot, readlane, shuffles across halves) through workgroup memory. | | Mesh shaders | NGG wave64 programs → `VK_EXT_mesh_shader` (`MeshEXT`). **PSV0** (DXBC) gives NumThreads (128×1×1 in the corpus), MaxOutputVertices/Primitives (128/128) and the topology (triangles). System inputs, from Mesa's RADV setup for mesh as NGG on GFX10.3: v5 = first launch vertex ID of the lane (the "vertex_id" slot), `linearGroupIndex * NumThreads + LocalInvocationIndex` with the linear index from WorkgroupId/NumWorkgroups; all 9,282/9,282 corpus mesh shaders read `v5` once with `v_readfirstlane_b32 sX, v5` and use `sX` only via `s_lshr_b32 D, sX, 7` to recover the group index (NumThreads is 128 in the corpus), matching TomBox's mesh ABI (`gid.x * numThreads + gi`) on 1D launches. GPU-checked with `runtime/test/shaders/ms_v5_workgroup.asm` (24/24 groups exact on RTX 4060 Ti and RTX 3080, and on an RTX 4050 Laptop and an AMD Radeon 740M (RADV)); still unverified on Xbox hardware: the low 7 bits of `v5` on lanes 1..127 and whether 3D `DispatchMesh` flattens XYZ or uses X only. The merged-wave-info SGPR (s3 in this ABI) = wave ID << 24, from LocalInvocationIndex >> 6; `v_mbcnt` lanes = LocalInvocationIndex & 63; user data in s16.. as usual. All 9,282 mesh-shader listings of 1.0.2.1 (names starting with `.` included) read exactly v5 before writing anything (`rdna2spirv.read_before_write_vgprs` over the code `translate()` keeps). An earlier sample of 1,500 put 27 aside as adding loop-carried registers; over the corpus no extra read is loop-carried. Read raw, 266 of the 309 listings with embedded data words seem to read more VGPRs, each after a branch (in 101 the register is written after the read); they come from data words decoded as instructions and are gone once the listing is re-anchored to the FSSM code and cut to reachable code, as `translate()` does. 1,473 of 1,500 sampled mesh shaders read exactly v5, and the rest only add loop-carried registers. Exports: on NGG, thread t exports vertex t (`pos0`, `paramN`) and primitive t (`prim`). They're staged per invocation; an all-`off` export is the dummy a wave with no vertices must issue, and writes nothing. `s_sendmsg GS_ALLOC_REQ` (m0 = prims << 12 \| verts, sent by thread 0) stores the counts in a workgroup variable. At shader end, in uniform control flow: workgroup barrier, `OpSetMeshOutputsEXT(min(verts, max), min(prims, max))`, then each thread writes its staged vertex (Position + Location N) and primitive (`PrimitiveTriangleIndicesEXT` = bits [8:0], [18:10], [28:20]; `CullPrimitiveEXT` = bit 31). `pos1..pos3` clip/cull distances are staged per invocation and emitted in a per-vertex `Block` output struct (`Position` + `ClipDistance`/`CullDistance` arrays, `VK_EXT_mesh_shader`) when used, keeping the standalone `%ms_out_pos` layout unchanged for shaders without `pos1+`. The distances are copied to that struct one float at a time, not as a whole array: SPIRV-Cross 1.4.363.0 turns a whole-array store into a mesh output into a C array assignment that Metal rejects (SHADER-155; `ms_clip` then compiles and draws its 2048/4096 pixels in a native Metal mesh draw on an Apple A18 Pro). GPU-checked with `runtime/test/shaders/ms_tri.asm` (`VKH_MESH=1 vk_harness`), built from the game's own idioms (thread ID from s3 and mbcnt across two waves, thread-0 ALLOC_REQ, per-thread exports): 0 error on every pixel. | @@ -354,6 +360,7 @@ How the generated SPIR-V expects the runtime to work: | Far branches | `s_getpc_b64; s_add_u32 K; s_addc_u32 0/−1; s_setpc_b64` on the same pair is a branch beyond `s_branch`'s ±32K-dword range. It's folded into one branch to (address after `s_getpc`) + K before CFG construction. The `s_sub_u32 K; s_subb_u32 0` form is the backward jump (a loop back-edge), as is `s_add_u32 -K; s_addc_u32 -1`. K is a byte distance, so the fold needs the instructions' `; encoding:` bytes; a listing without them is `Unsupported` ("without encoding"), not a crash. GPU-checked by `ps_far_branch.asm` (two forward jumps, a `sub`/`subb` loop, an `add`/`addc -1` loop and a conditional one run twice, K and the expected words derived by hand; RTX 5080 and Radeon gfx1036, 4096/4096 exact), CPU side `tests/semantic/test_far_branch.py`. | | No-op SOPP/SMEM (`s_icache_inv`, `s_ttracedata`, `s_ttracedata_imm`, `s_code_end`, `s_version`, `ds_nop`, `v_clrexcp`) | Instruction-cache invalidate, thread-trace data, end-of-code padding, the ISA version marker and the DS no-operation have no register, memory, SCC, VCC or EXEC effect, so they are in `NOOPS` with `s_nop` / `v_nop` / `v_pipeflush`. `v_clrexcp` clears the TRAPSTS exception bits, which nothing translated reads (`s_getreg_b32` is unsupported and there are no traps), so it is a no-op too (since 2026-11-22; before, both it and `ds_nop` raised `Unsupported`). The data-cache invalidations (`buffer_gl0_inv`, `buffer_gl1_inv`, `s_dcache_inv`, `s_gl1_inv`) concern coherence between waves and stay `Unsupported`. Source: RDNA2 ISA SOPP/SOPK/SMEM/DS/VOP1. CPU-checked by `tests/semantic/test_sopp_noops.py` (values, SCC and VCC survive; the data-cache invalidations are still rejected). | | Buffer format stores | `buffer_store_format_*` and `_d16_*` encode every format the loads decode (the same FORMATS table: f32/u32, f16, unorm/snorm 8/16/10-10-10-2, uint/sint 8/16, and the formats of the *Typed buffer formats* row). 1–2-byte elements are merged into their dword with atomic and/or so neighbours are kept. The atomics use element 0 of the array at the aligned dword address, which also compiles on MoltenVK 1.4.0 (checked with `cs_store` on an Apple M3 Max and Mesa llvmpipe). d16 data is unpacked first (f16 → float for float kinds, 16-bit integers for integer kinds). Before this, only four f32 formats, rgba16f and rgba8 unorm were stored, and everything else silently stored nothing. GPU-checked with `runtime/test/shaders/cs_store.asm` (rgba8 unorm, R10G10B10A2 (`2_10_10_10`), two r16f halves of one dword, d16 rgba16f: exact, neighbours untouched). `buffer_load_format_d16_*` packs pairs the same way. UNORM/SNORM stores convert NaN to zero before clamping. On native gfx1036, `buffer_store_format_d16_xyzw` into RGBA8_UNORM/SNORM matched clamp, scale by 255/127 and round to nearest even for all 63,488 finite binary16 encodings. Both infinities saturated and all 2,046 NaNs stored zero in both wave32 and wave64. The translated sweep matched all 65,536 bytes per format on RTX 5080 and Radeon Graphics. For normalized stores with format 56 (8/8/8/8) or 50 (10/10/10/2), a Z,Y,X,W descriptor exchanges the red and blue memory fields after filling absent input components with zero. Native gfx1036 confirmed both channel orders at all four instruction widths for packed and ordinary stores in wave32 and wave64. A store with fewer components than its format writes the whole element, with 0 for the components it doesn't give (`_xy` into 32_32_32_32 leaves z = w = 0, `_xyz` into 16_16_16_16 leaves w = 0); into a one-channel format only x is written. Measured natively on a Radeon 680M (gfx1035, RDNA2), and GPU-checked by `cs_fmt_xy_xyz.asm` for 32_32_32_32, 16_16_16_16, 8_8_8_8 UNORM and UINT and 32 (TEST-185). Unsigned integer stores saturate to the destination channel width. On native gfx1036, RGBA8_UINT, RG16_UINT and RGBA16_UINT clipped overflowing inputs to 255 or 65535, with RGBA32_UINT as a full-width control. For normalized stores with format 56 (8/8/8/8) or 50 (10/10/10/2), a Z,Y,X,W descriptor exchanges the red and blue memory fields after filling absent input components with zero; native gfx1036 confirmed both channel orders at all four instruction widths for packed and ordinary stores in wave32 and wave64. `tbuffer_store_format_*` is not translated. 8- and 16-bit SINT stores clamp the signed 32-bit value to [-2^(w-1), 2^(w-1) - 1] (300 stores 127 into 8_SINT, -129 stores -128), and the 8/16-bit UINT formats 5, 11 and 18 saturate like the others; measured natively on gfx1036 for x, xy, xyzw and d16_xyzw stores (a d16 half is read as a signed 16-bit integer for SINT, so 0xff80 stores -128) with the runtime's selectors (X001, XY01, XYZW) and checked by `tests/semantic/test_buffer_format_narrow_int.py` (until 2026-11-22 those formats stored nothing). `tbuffer_store_format_*` and its `_d16_*` forms take the instruction's format instead of the V#'s, as the tbuffer loads do: only that format is encoded, and its element size decides the bounds check (an 8_UNORM byte is stored where the V#'s 16-byte element would not fit; a 16-byte element is dropped where the V#'s 4-byte one would fit). A V# whose FORMAT is 0 (INVALID) still disables the store. No `format:` modifier is GFX10's default, BUF_FMT_8_UNORM; a format FORMATS has no encoder for stays `Unsupported`. Measured natively on a Radeon 680M (gfx1035, wave32 = wave64) and GPU-checked by `cs_tbuffer_store.asm` (13 stores: f32, f16, 8_8_8_8 UINT and UNORM, 2_10_10_10, d16, the default format, more and fewer components than the format has, both bounds cases, a V# with FORMAT 0; exact on an RTX 3050 and the 680M); CPU-checked by `tests/semantic/test_tbuffer_store.py`. | +| Dynamic typed-buffer stores | A seven-bit V# FORMAT selects one of the 77 existing encoders with a structured SPIR-V switch. Loads, bounds checks and stores share the element-size table. An unassigned code has size zero and leaves memory untouched. The hand-written `store_dynamic_vsharp.asm` fixture covers raw words for UINT and FLOAT, four FLOAT components, three unassigned codes and a sentinel past the destination. | | Typed buffer formats | `Gen.FORMATS` holds all 77 GFX10 codes a V# or MTBUF can carry (a buffer's `FORMAT` is 7 bits; codes from 128 are image-only, and there are no 5_6_5, 1_5_5_5, 5_5_5_1 or 4_4_4_4 buffer formats): the 8/16-bit UINT, SINT, USCALED and SSCALED families (USCALED/SSCALED: the integer converted to float, not divided), 10_11_11 and 11_11_10 in all seven numeric formats (the FLOAT ones are unsigned floats: 5 exponent bits, bias 15, 6 or 5 mantissa bits, no sign; the first number is the top field, so 36 has x in bits 10:0 and a 10-bit z on top), and the 10_10_10_2 (44–49) and 2_10_10_10 (50–55) families. Codes outside the table decode to 0 and store nothing. **Stores**: UINT and SINT saturate; UNORM and SNORM round the exact product once (`Gen.encode_norm_bits`: 0.3 · 65535 stores 19661; nearest even, but a half rounds away from zero in a 2-bit SNORM field); a SCALED store converts as the matching NORM format; float stores (16_FLOAT and the small floats) **round toward zero, saturate to the largest finite value (65504), keep a NaN a NaN and give 0 for a negative number in an unsigned float** (`Gen.ufloat_encode_bits`); **a two-component format stored through a V# takes channel y as its second component when DST_SEL_Y is Y and DST_SEL_Z a constant (the runtime's X,Y,0,1), channel w otherwise (identity XYZW: `_xy` writes (x, 0))**, and `tbuffer_store_format_*` takes (x, y) whatever the V# says. The typed-store encode is emitted once per module (`Gen.format_encode_call`: one encode function and one element-size function, each store site a call, like the shared decode), because inlined every site carried every format. **How confirmed**: `tools/buffer_format_fuzz.py --oracle hw` runs raw `buffer_load_format_xyzw` / `buffer_store_format_xyzw` / `_xy` / `tbuffer_*_format_*` kernels and compares every result word with a CPU model (a distinct value in every register). **Radeon 880M (gfx1150, RDNA3.5; GFX11 numbers its formats differently, so formats are mapped by name)**: 1,390,400 elements over the 63 formats GFX11 has, 0 mismatches. **Real RDNA2, gfx1036, by @AwkGrep256 on the Linux DRM backend ([#2022](https://github.com/ItsNotRexed/Leonida/pull/2022))**: the same totals, 1,330,469 validated and 26,523 elements of the (x, w) routing, 0 mismatches, and 199,144 elements of the 14 codes GFX11 lacks (10_11_11 and 11_11_10 non-FLOAT, 10_10_10_2 USCALED/SSCALED), 0 mismatches. Per-format counts in [buffer_formats.md](buffer_formats.md); `--negative-control` catches a wrong V# format on all but one or two elements. The translated SPIR-V is held to the same model by `tests/semantic/test_buffer_formats_all.py` (every added format, loads through the V# and tbuffer, stores, every older format's store, hand-worked values) and by the GPU test `cs_fmt_all.asm` (32 loads and 20 stores, on an AMD Radeon 880M and an NVIDIA RTX 5070); `cs_store`, `cs_fmt_*`, `cs_oob_*` and `cs_tbuffer_store` pass on both too. Three older stores used to differ from the hardware (f16 format stores rounded to nearest and overflowed to infinity, NORM stores rounded an f32 product twice, a two-component V# store always took (x, y)) and follow it now. **Unmeasured**: the console's gfx1013, d16 forms of the new kinds and of the (x, w) routing, `_xyz` into a two-component format, selector sets that reorder channels. | | No-op SOPP/SMEM (`s_icache_inv`, `s_ttracedata`, `s_ttracedata_imm`, `s_code_end`, `s_version`, `ds_nop`, `v_clrexcp`, `s_atc_probe`, `s_atc_probe_buffer`) | Instruction-cache invalidate, thread-trace data, end-of-code padding, the ISA version marker and the DS no-operation have no register, memory, SCC, VCC or EXEC effect, so they are in `NOOPS` with `s_nop` / `v_nop` / `v_pipeflush`. `v_clrexcp` clears the TRAPSTS exception bits, which nothing translated reads (`s_getreg_b32` is unsupported and there are no traps), so it is a no-op too (since 2026-11-22; before, both it and `ds_nop` raised `Unsupported`). `s_atc_probe` and `s_atc_probe_buffer` (SMEM) probe, that is prefetch, an address in the address translation cache: no data comes back and nothing is written, so they are no-ops too (since 2026-11-22). The data-cache invalidations (`buffer_gl0_inv`, `buffer_gl1_inv`, `s_dcache_inv`, `s_gl1_inv`) concern coherence between waves and stay `Unsupported`. Source: RDNA2 ISA SOPP/SOPK/SMEM/DS/VOP1. CPU-checked by `tests/semantic/test_sopp_noops.py` (values, SCC and VCC survive; the data-cache invalidations are still rejected). | | No-op SOPP/SMEM (`s_icache_inv`, `s_ttracedata`, `s_ttracedata_imm`, `s_code_end`, `s_version`, `ds_nop`, `v_clrexcp`, `s_atc_probe`, `s_atc_probe_buffer`, `s_incperflevel`, `s_decperflevel`, `s_wakeup`) | Instruction-cache invalidate, thread-trace data, end-of-code padding, the ISA version marker and the DS no-operation have no register, memory, SCC, VCC or EXEC effect, so they are in `NOOPS` with `s_nop` / `v_nop` / `v_pipeflush`. `v_clrexcp` clears the TRAPSTS exception bits, which nothing translated reads (`s_getreg_b32` is unsupported and there are no traps), so it is a no-op too (since 2026-11-22; before, both it and `ds_nop` raised `Unsupported`). `s_atc_probe` and `s_atc_probe_buffer` (SMEM) probe, that is prefetch, an address in the address translation cache: no data comes back and nothing is written, so they are no-ops too (since 2026-11-22). `s_incperflevel` and `s_decperflevel` increment or decrement a performance counter (RDNA2 ISA SOPP, SIMM16[3:0]) and `s_wakeup` pings the other waves of the threadgroup out of an `s_sleep`, which is itself a no-op here; none writes a register, memory, SCC, VCC or EXEC, so they are no-ops too (since 2026-11-22). The data-cache invalidations (`buffer_gl0_inv`, `buffer_gl1_inv`, `s_dcache_inv`, `s_gl1_inv`) concern coherence between waves and stay `Unsupported`. Source: RDNA2 ISA SOPP/SOPK/SMEM/DS/VOP1. CPU-checked by `tests/semantic/test_sopp_noops.py` (values, SCC and VCC survive; the data-cache invalidations are still rejected). | @@ -365,13 +372,13 @@ How the generated SPIR-V expects the runtime to work: | `v_mad_u64_u32`, `v_mad_i64_i32` | {sdst, D} = S0 × S1 + S2 as a 65-bit result (RDNA ISA pseudocode), the product unsigned or signed. sdst (a lane mask) gets bit 64 for active lanes and 0 for lanes off in EXEC (`EXEC[lane] ? bit64 : 0`, matching `v_cmp_*` and `*_co_*`): the carry out for u64, and for i64 the sign of the exact sum (bit 64 of a 65-bit two's-complement value), not a signed-overflow flag. `tools/lane_masks.py` tracks sdst as a lane mask (until 2026-11-22 it only matched `*_co_*`, so `s_bcnt1`/`s_ff1`/`v_mbcnt` on sdst read each lane's own mask word as plain data). `clamp` is rejected. Checked on the CPU by `tests/test_lane_masks.py`, `tests/semantic/test_alu_mad64.py` (including 64-lane `s_bcnt1_i32_b64`/`s_ff1_i32_b64` ballot tests), and `tests/semantic/test_carry_exec_mask.py` (EXEC masking on inactive lanes). **Hardware-verified on RDNA2** (AMD Radeon 680M, `gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137): unsigned carry, signed positive overflow `(-2³¹)² + INT64_MAX` giving `sdst = 0`, negative sum giving `sdst = 1`, and inactive EXEC lane leaving D untouched with `sdst = 0` all match bit-for-bit. | | Ray tracing | `image_bvh_intersect_ray` / `image_bvh64_intersect_ray` (64 CS: RT shadows) are one traversal step against AMD's hardware BVH node format. The traversal loop lives in the game's shader. The step is emulated over buffer reads following Mesa RADV's software path (`radv_nir_rt_common.c`, `intersect_ray_amd_software_box/_tri`; node layouts from `bvh_defines.h`). Node id = address >> 3 \| type (0–3 triangle, 4 box16, 5 box32). Box nodes give the four child ids, with misses and NaN boxes = `0xFFFFFFFF`, sorted by entry distance when descriptor bit 63 (box_sort_enable) is set. **The box test is the native one, measured on RDNA2** (SHADER-650; RX 6900 XT, gfx1030, `tools/hw_oracle` raw kernels, 338 cases: BOX32 and BOX16, four rays including negative directions, NaN in every position, empty boxes, planes on the origin, and every tie order of four children; the translator now matches all 338 bit for bit, `main` before it 43, and all 811 rounding cases below): per axis, the near plane is min and the far plane max when the inverse direction (taken as given, not clamped) is ≥ 0, swapped otherwise; t = (plane − origin) × inverse direction, so `0 × inf` is NaN. **Both the subtraction and the multiply round toward zero** (811 more cases, 800 randomized slabs at origins 2^18 to 2^27 away plus 11 ties: round-to-nearest predicts 769 of them, round-toward-zero all 811; among the ties, a box with min.x = 1 > max.x = 0 at origin.x = −2^25 is a hit on hardware because both planes round to the same t). The translator emulates this exactly: the subtraction's error comes from TwoSum, the product's error sign from a Dekker split of the two mantissas scaled to [1, 2), and a result rounded away from zero steps one ulp back; a finite overflow gives ±FLT_MAX. tnear = max of the three near t, tfar = min of the three far t, **each skipping NaN**; all three near or all three far NaN is a miss. Hit when max(tnear, 0) ≤ tfar and tnear < extent (the extent boundary itself was not measured). So a lone NaN bound leaves its own plane open (a box with min.x = NaN is hit wherever x ≤ max.x), an empty box (min > max on any axis, ±inf or ±65504 included) is a miss without a separate check, and a plane exactly on the origin along a zero-direction axis is open. The sort key is max(tnear, 0), so boxes around the origin tie at 0, ordered by the network (0,2) (1,3) (0,1) (2,3) (1,2) with a strict `<` swap (all 88 measured tie orders). `tests/semantic/test_image_bvh_box_hw.py` holds measured words. Triangle nodes read their three vertices from the slots the node type picks: TRI0 (0,1,2), TRI1 (1,3,2), TRI2 (2,3,4), TRI3 (2,4,0), 12 bytes each. They use the watertight test with RADV's shared edge/vertex tie-breaks and give (t/\|det\|, sign(det), b_i/\|det\|, b_j/\|det\|), or (inf, 1, 0, 0) on a miss. The weights i and j are chosen by the node type's byte of the triangle-ID word at +60: bits [1:0] and [3:2], 0/1/2 = vertex 0/1/2 and 3 = vertex 0, bits [7:4] ignored; `0x09` gives RADV's (v, w). Vertex slots and remap follow AMD GPURT (`CalcTriangleCompressionVertexIndices`, `SwizzleBarycentrics`) and the public XDXR software path ([bvh.md](bvh.md) §7a), and the hardware agrees. **The triangle step is the native one, measured on RDNA2** (AMD Radeon RX 6800, gfx1030, AMD Windows driver 26.11.2, Windows 11, 2026-11-22; the `tools/hw_oracle` kernels `tools/bvh_tri_probe.py` builds, hand-built nodes and rays: 14 kernels, 308 single-lane cases and 7 cases on 64 lanes, 1,204 results, each in both forms; the 32-bit form with the descriptor base at the node and the 64-bit form with base 0, wave32 and wave64, NSA and contiguous operands all gave the same words). A NaN anywhere in t max, the origin, the direction or the inverse direction, or an infinite origin, returns (+inf, 1.0, +0, +0). Otherwise the watertight test runs with its shear taken from the direction (kz = the axis of the largest \|d\|, ties x, y, z; kx and ky swapped when d[kz] < 0; Sz = 1/d[kz]): **the supplied inverse direction is not used**. With the edge functions U, V, W, det = U + V + W, T = t·det and k = \|d[kz]\|³, a hit returns (k·T, k·det, k·b_i, k·b_j) and a miss (copysign(inf, k·det), k·det, k·b_i, k·b_j): numerators over the denominator k·det, and a miss keeps the plane's barycentric numerators. det = 0 is a miss with word 0 = +inf. The hit needs t ≥ 0 (t = 0 hits); there is no test against t max. Every zero word is +0 and every NaN word 0xFFC00000, so a NaN det gives word 0 = −inf. An edge function of 0 is inside when its edge passes RDNA2's tie rule, which is not RADV's: the edge from P to Q (U: B→C, V: C→A, W: A→B), with (tx, ty) = Q′ − P′ in the sheared frame with the d[kz] < 0 swap of kx and ky undone, passes when ty = 0 ? sign(det)·tx > 0 : sign(d[kz])·sign(det)·ty > 0, and every zero edge must pass. Every shared edge and shared vertex gave exactly one hit. How this rule was found: the first fit (ty = 0 ? tx < 0 : sign(det)·ty > 0, on the 49 tie rows of the first measurement, all z dominant) was confounded, because every one of those rows had det < 0 with d[kz] > 0 or det > 0 with d[kz] < 0, and it was wrong in the cells it never saw. A second measurement (2026-11-23, same part and driver; 8 more kernels, 256 rows: ties with x, y and z dominant, both windings, both signs of d[kz], every edge direction class in each of those cells, tilted triangles with oblique rays, equal \|d\| components) fitted none of the eight rules registered before it ran. The rule above was then read off its x/y rows (post hoc), and it predicted the z-dominant bridge kernel `tri_t8` before that ran: 32 of 32 cases, 10 of them rows where it and the first fit disagree. The translator computes these words without a division, with the shear multiplied through by \|d[kz]\| (a shear divided by d[kz] gives the same words on every measured row but d.z = +inf, and divides by zero at d = 0; this form gives d = 0 → (+inf, 0, 0, 0) and d.z = +inf → (−inf, NaN, −inf, −inf) as measured, a fit after the runs), and fixes zero signs and NaN bits with integer selects, so every measured input is defined SPIR-V. `tests/semantic/test_image_bvh_tri_hw.py` asserts all 308 rows and 84 lane results of the first measurement and the 256 rows of the second bit for bit (the translator before it: 129 of the first 308; the first fit: 210 of the 256); `tests/semantic/test_image_bvh_tri.py` runs every node type and remap byte on the interpreter. **A consumer that divides by word 1** (t = w0/w1, weights w2/w1 and w3/w1) gets t and the weights on a hit (k cancels; word 1 keeps det's sign); +inf for t on a miss of either winding, with the plane's weights; t = +inf/+0 = +inf and weights 0/0 on a zero-area triangle; t = NaN with a NaN or inf vertex, so a `t < t max` test fails as on a miss; t = +inf with a NaN in the ray or an infinite origin. It must compare t with t max itself. The translator's earlier normalised words (t/\|det\|, sign(det), b_i/\|det\|, b_j/\|det\|; a miss (inf, 1, 0, 0)) gave such a consumer the same t on every row and the same weights on every hit except on 14 shared-edge rows (RADV's tie rule), 3 rows whose inverse direction is not 1/d, 3 rows with a NaN in the ray (it reported a hit or other words), the v0.x = −inf and d.z = +inf rows, and 14 rows that were undefined SPIR-V there (zero area, a NaN or inf vertex, a NaN, inf or zero ray). **Not measured:** gfx1013 (the console); node types 6 and 7; the box extent boundary; descriptor words other than w2 = 0xFFFFFFFF, w3 = 0x81000000 (return mode 0 included); the dominant axis on equal \|d\| components except where a measured tie row tells the axes apart: x for \|dx\| = \|dy\| > \|dz\| (only with dx, dy > 0), x for \|dx\| = \|dz\| > \|dy\| (not with dx > 0 > dz), y for \|dy\| = \|dz\| > \|dx\| (only with dy, dz of the same sign) and x with all three equal (in the four of the eight sign patterns that ran), which is the translator's `>=` order (a non-tie row gives the same words whatever the choice, and every sign pattern could show it with the right tie); rounding-sensitive inputs (every input is dyadic, so the divided versus multiplied-through shear and fused versus separate rounding are not told apart); d = 0 and infinite d beyond one row each; the remap's high nibble on TRI1–TRI3. These two references agree; one real pack BLAS is now matched, rehydrated and traversed (§7b), though the rule has not been counted over the whole corpus. The triangle rule has not been measured on the native instruction yet: `tools/hw_oracle` can run it on RDNA2, and box32 nodes were measured that way (gfx1036, address = base × 256 + (node & ~7) × 8 in both instruction widths, §7b), so the triangle counterpart is a possible follow-up rather than an impossibility. These two references agree; no game BVH is decoded yet to count over. The triangle rule has not been run natively yet; the box rule above has (`tools/hw_oracle` on an AMD RDNA2 card runs the instruction itself). `tests/semantic/test_image_bvh_tri.py` runs every node type and remap byte on the interpreter, including the descriptor-base case. The game's code divides by `.y` exactly as for the hardware's numerator/denominator. Address = descriptor base + ((node & ~7) << 3). The descriptor's dword0 is the base in 256-byte units: the game passes `ptr >> 8` there, and the `\| 0x30` its shader ORs is only the temporary address it uses to load `rootNodePtr`, not the descriptor base. Measured at base 0 and at base 0x1000 (structure at VA 0x1000, dword0 `0x10`): the GPU returns the CPU walker's children in the same order at both, so the `<< 8` is correct and a nonzero base needs no masking. `tests/semantic/test_image_bvh_tri.py` runs the nonzero base (`0x10` → `0x1000`). Address = descriptor base + ((node & ~7) << 3), base = descriptor bits [39:0] in 256-byte units (measured on gfx1030: the 32-bit form with a non-zero base and the 64-bit form with base 0 and the full address gave the same words in 71 cases). **The runtime must build the game's acceleration structures in this AMD node format** (RADV's GPU BVH builder produces it) wherever the game's D3D12 calls build them. Far branches with `s_sub_u32`/`s_subb_u32` (backward) are folded too. GPU-checked with `runtime/test/shaders/cs_bvh.asm`: sorted box children and the triangle result are exact; its box with a NaN min.x is entered at t = 0 and sorts first (`0x68 0x48 0x40 0xffffffff`), as native gfx1030 returns for that scene. The 32-bit form (11 address dwords: the node id has no high dword) runs the same scene in `cs_bvh32.asm` and gives the same eight words. Corpus counts (`tools/image_bvh_census.py`, static, [bvh.md](bvh.md) §7): 716 sites, 638 32-bit and 78 64-bit; the descriptor has box_sort_en 1, big_page 1, size all ones and type 8 at every site; on every path from the call, 397 sites take `v_rcp_f32` of word 1, multiply word 0 (335 also words 2 and 3) by it and read `sext(w1[31:16])`, all 716 read the words as integers (397 through shifts and `v_and_or_b32`/`v_lshl_or_b32`/`v_or3_b32`, 319 through `v_cmp_eq_u32` only), and none reads a word undivided as a float; 633 sites also have reads on some paths only, which the census leaves unclassified. | | Coverage | Every shader in the corpus translates. The remaining fidelity gap is wave64 cross-half code on 32-wide subgroups in VS/PS/GS (tier C of the *Wave64 graphics* row; tiers A and B are exact); compute and mesh shaders are exact there with `--wave64-emulate` (see the wave-size and wave64 rows). | -| Flat pixel inputs | A pixel input location read only by `v_interp_mov_f32` with the p0 select is declared `Flat` (a location a p10/p20 mov reads is `PerVertexKHR`, next row). A pixel input location read only by `v_interp_mov_f32` is declared `Flat`. Locations read with `v_interp_p1/p2` remain interpolated. The `ps_flat` GPU test passes integer IDs through the first vertex alongside interpolated UVs. On the CPU, `test_v_interp_mov_emits_flat_decoration` and `test_attribute_read_both_flat_and_interpolated_is_not_flat` in `tests/semantic/test_interp_mov_flat.py` check the Flat decoration of a p0-only location and that a location also read with p1/p2 is not decorated Flat. | +| Flat pixel inputs | A pixel input location read only by `v_interp_mov_f32` with the p0 select is declared `Flat` (a location a p10/p20 mov reads is `PerVertexKHR`, next row). A pixel input location read only by `v_interp_mov_f32` is declared `Flat`. Locations read with `v_interp_p1/p2` remain interpolated. The `ps_flat` GPU test passes integer IDs through the first vertex alongside interpolated UVs. | | v_interp operand guards (SHADER-177) | The single-lane model reads the attribute's own value for `v_interp_p1/p2`, which is only right when the VGPR source really holds the barycentric coordinate that op interpolates with — **p1 reads I = v0 and p2 reads J = v1, per op** — and `v_interp_mov_f32` p0 is the provoking vertex (p10/p20 are the deltas of the vertex-delta row above). A p1/p2 (f32 and f16 forms) whose source is not its own coordinate — v0 for p1, v1 for p2, each either the hardware register or a plain `v_mov_b32` copy rooted at it (the copy's single write in the whole shader, defined before the use, copy chains followed, and its source v0/v1 itself unwritten up to the copy: a copy of an already-overwritten v0/v1 carries a computed value — zeroing the source before copying renders (0,0) on hardware — while a write after the copy is fine, the copy saved the value) — is **Unsupported**, naming the register and the role, so a swapped p1(v1)/p2(v0) pair, a both-v0 pair, or a copy of an overwritten source is refused rather than silently mistranslated; `v_interp_mov_f32` with p10/p20 was **Unsupported** until the vertex-delta row above; any other select still is, naming it. `v_interp_mov_f32` with p10/p20 is **Unsupported**, naming the select. A **direct** v0/v1 read stays accepted even when the shader overwrites v0/v1 first (evaluate-at-offset/snapped barycentrics; up to 213 PS, #1218): modelling that computed value is the separate provenance follow-up. Zero corpus cost: over the 26,503-shader corpus every f32 I/J source is v0/v1 (117,001 / 116,997) except one PS whose four `v_interp_p2_f32` read J through `v_mov_b32 v14, v1` (its v1 unwritten up to the copy; the later overwrites are the saved-copy case), which the copy rule keeps translating (bit-identical .spv), every f16 source is v0/v1 (58,950 / 58,950), and all 6,926 `v_interp_mov_f32` use p0. Confirmed by `tests/semantic/test_interp_guards.py` (refusals name the operand and its role, including swapped and both-v0 pairs, a wrong-root copy, and a copy of an overwritten source; the copy, copy-chain, matching-role and saved-from-later-zero cases translate and compute; a second write or a dpp copy no longer qualifies; a mutation check that the guard consults the copy analysis) and by re-translating a 200-shader corpus slice plus that PS before and after: translated/valid counts and every .spv unchanged. | | Pixel-shader interpolants | When a sidecar `fssm/.fssm` holds a pixel-input table (`tools/fssm_header.py`: 8-byte records from 0x138 while the first byte is 6; table position = `v_interp attr` number), every position 0..count−1 is declared as a fragment input at that Location, including positions the code never reads (the table overcounts the code's distinct `v_interp` attrs in 775 of 12,101 PS: 300 by one, 475 by two or more; only the 10 records starting with kind 7 undercount). A 32-bit `v_interp` read (`p1/p2/mov`) of a 16-bit-flagged position (flag bit 4; **measured natively on RDNA2**, AMD Radeon 680M `gfx1035` in wave32 and wave64 via `tools/vinterp_hw_probe.py --oracle both`, SHADER-430: the VINTRP unit reads the same LDS parameter-cache dwords at `M0 + 48·attr + {8·c, 8·c + 4, 32 + 4·c}` with no hidden 16-bit unpacking, so `v_interp_mov_f32` returns the raw 32-bit parameter word and `v_interp_p1_f32`/`v_interp_p2_f32` interpolate those 32-bit words as binary32), and reads past the table still declare an input (the value is undefined on hardware). 11,199 such inputs corpus-wide, matching the `*_f16` interpolation opcodes in 99.7%) sees the value rounded to f16 (round to nearest, f16 denormals flushed to signed zero, back to f32) via a single `OpQuantizeToF16` (a `PackHalf2x16`/`UnpackHalf2x16` round-trip is folded to a no-op by at least one Vulkan driver, RTX 5080); reads through the `*_f16` opcodes already narrow and are unchanged (on a location an f16 op also reads, the f32 read is of the per-vertex raw word, "16-bit interpolation"; on gfx1036 a 32-bit `p1/p2_f32` read of a packed channel takes the raw LDS words as f32 bits, one fma each (SHADER-430, `tools/interp_hw_probe.py`); what P10/P20 words the SPI stores for such a channel is unverified), and reads past the table still declare an input (the value is undefined on hardware). Without a sidecar, or with an empty table, the output is byte-identical to the code-driven path. Confirmed by synthetic fixtures plus mini-interpreter agreement (`tests/test_rdna2spirv_pixelinput.py`: an f32 read of a flagged slot with input 1.1 yields the f16-rounded 1.099609375; unflagged and table-less controls yield exact 1.1) and `tests/test_vinterp_hw_probe.py`. The `index.json` entry records `ps_interpolants` (count) and `ps_fp16_interpolants` (flagged positions). | | PS interpolation modes (SHADER-181) | Every interpolated generic pixel input in this build is **perspective-correct at the pixel center**, and every other input is flat, so the single v0/v1 pair the code reads is `PERSP_CENTER`. The translator models exactly these two: Flat for `v_interp_mov_f32`, plain (perspective, center) inputs and `BaryCoordKHR` for `v_interp_p1/p2` and the f16 forms. Two records describe each input, and they state **different facts**: PSV0 (DXBC) stores the interpolation **mode**; the FSSM input record's flags byte (byte 7) stores the **read method** — bit 0 (0x01) marks `v_interp_mov_f32` (4,600 records), bit 1 (0x02) 32-bit `v_interp_p1/p2` (51,191; values 0 and 3 never occur), bit 3 (0x08) a Float16-typed parameter (11,619), bit 4 (0x10) the `*_f16` opcodes (11,199; 24 f16-read records lack it). The flag/usage cross-table over all 55,791 records has no contradiction: every bit-0 position the code reads is read only by `v_interp_mov_f32` (4,295 positions), every bit-1 position only by `v_interp_p1/p2` or the f16 forms (49,594), and no position is read both ways (1,902 positions are unread, and 88 reads fall past the table). **The mode is in PSV0, not the FSSM**: `tools/ps_interp_modes.py` decodes it from the PSV0 signature elements (`DXIL::InterpolationMode`, "must match D3D_INTERPOLATION_MODE": 1 Constant, 2 Linear, 3 LinearCentroid, 4 LinearNoperspective, 5 LinearNoperspectiveCentroid, 6 LinearSample, 7 LinearNoperspectiveSample; the 16-byte elements carry row, cols, semantic kind, component type and the mode — layout in the Pixel-shader inputs section) and maps the modes onto the `SPI_PS_INPUT_ENA` barycentric-pair bits (Mesa `gfx103.json` register type SPI_PS_INPUT_ENA: PERSP_SAMPLE/CENTER/CENTROID = bits 0/1/2, LINEAR_SAMPLE/CENTER/CENTROID = bits 4/5/6; the same type serves `SPI_PS_INPUT_ADDR`). **No FSSM word stores ENA/ADDR**: every u16 in bytes 0x00–0x138 of all 12,101 PS was compared against the signature-reconstructed ENA and only constant coincidences matched, and the register addresses (0x286CC/0x286D0, or 0xA1B3/0xA1B4 as context-register indices) appear in no PS blob, so the v2.. position layout of "PS system inputs" (one enabled pair) is the only ENA witness. The #2735 packed-component census matched PSV0, FSSM and disassembly for all 12,101 indexed PS. Of 101,024 declared input rows, 77,245 have a nonzero read mask. Census (12,101 PS; 101,024 declared / 77,245 read inputs): every arbitrary, clip and cull input is Constant (6,333 rows, 4,529 read) or Linear = perspective-centre (81,385 rows, attributes plus 1,806 `SV_ClipDistance` and 2 `SV_CullDistance`); zero centroid, sample or noperspective generics; per shader 6,350 linear only, 4,507 linear and constant, 6 constant only, 1,238 no interpolated input. 101,024 declared / 76,215 read inputs): every arbitrary, clip and cull input is Constant (6,333 rows, 3,652 read) or Linear = perspective-centre (81,385 rows, attributes plus 1,806 `SV_ClipDistance` and 2 `SV_CullDistance`); zero centroid, sample or noperspective generics; per shader 6,350 linear only, 4,507 linear and constant, 6 constant only, 1,238 no interpolated input. ISG1 has no mode field, and the DXIL part carries no bitcode. SV_Position is mode 4 (11,295 rows) or mode 5 (27), both noperspective by the D3D rule. With packed-component read masks, the classifier assigns 10,260 shaders to the perspective-centre pair and 1,841 to no pair. None classify as linear-centre. Hardware delivery of SV_Position is outside the scope of the census. Front face is a system input (1,984 rows, 345 read, at most one per shader). It assigns none to a linear pair. This count measures input classification; it does not directly measure how the hardware delivers SV_Position; front face is a system input (1,984 rows, 345 read, at most one per shader). SV_Position is mode 4 (11,295 rows) or mode 5 (27) — noperspective by the D3D rule — and is delivered through the system VGPRs in every shader except **4**, which interpolate it through the parameter cache with the *linear* pair (`FragCoord` stays at the pixel center, which only differs at partly covered MSAA pixels); front face is a system input (1,984 rows, 345 read, at most one per shader). The code reads **at most one** barycentric pair per shader: v0/v1 in 10,259, none in 1,841, and one shader reads J from v14 (a copy of v1), so the perspective-centre assumption holds for every interpolated generic input. **Mode and read method disagree in thousands of rows** — the residual surface for modelling is: those 4 linear-pair position shaders, Constant rows read via `p1/p2` or `*_f16` (2,190 records at the matching table position; flat semantics in hardware, not modelled), and Linear rows read only by `v_interp_mov_f32` (3,197; already declared `Flat`). The translator's table check (`check_read_methods`, the row below) compares each read's opcode against the record's read-method bits (`fssm_header.read_methods`) — since the bits restate the read method, it rejects 0 of 12,101 PS: a consistency check between the two encodings of the read, not a mode check (a centroid/sample/noperspective input would still read `v_interp_p1/p2` and pass; that every interpolated generic input is perspective-centre is the PSV0 census result above, so keying a refusal on genuinely unmodelled modes means decoding PSV0, not reading these bits). Counted with `tools/ps_interp_modes.py` (stdlib; PSV0, FSSM and disassembly in one pass; #1301 removed the earlier #1246 census tool in favour of it) on the 1.0.2.1 corpus; tests `tests/test_ps_interp_modes.py`, `tests/test_fssm_header.py` and `tests/test_rdna2spirv_pixelinput.py` (synthetic). No GPU test: no shader needs centroid or sample interpolation. **Not covered:** bit 3 (0x08) is set in 11,619 records (all 11,199 16-bit ones, 396 flat, 24 linear). The 213 PS that overwrite v0/v1 before a `v_interp` (SHADER-178) compute their own barycentrics in code; PSV0 gives them no other mode. | | `v_interp_mov_f32` p10 / p20 | The VINTRP mov returns one of the three values the hardware keeps per attribute for the p1/p2 pair, {P10, P20, P0}[S] (RDNA2 ISA, VINTRP; P = P0 + i·P10 + j·P20). p0 stays the provoking vertex (`Flat`, exact bits). p10 and p20 read the location `PerVertexKHR` (the per-vertex path the `*_f16` interps use, so the PS needs `fragmentShaderBarycentric`) and return P1 − P0 and P2 − P0 as one f32 `OpFSub` of the producer's words, vertices ordered as in the f16 row (BaryCoordKHR .y/.z weight vertices 1/2). Refused (`Unsupported`) under `--bary-fallback` and `--f16-interp-fallback` (no per-vertex inputs) and on a 16-bit-flagged interpolant (FSSM table), where whether the hardware forms the delta in f16 is unmeasured. Until 2026-11-22 both selects were refused; all 6,926 `v_interp_mov_f32` in the corpus use p0, so the corpus translation is unchanged. Confirmed on the CPU by `tests/semantic/test_interp_mov_delta.py` (distinct per-vertex words give the deltas, and P0 + i·P10 + j·P20 from the three movs matches the p1/p2 pair bit for bit). **Unverified:** a GPU run, and AMD's rounding of P10/P20 for denormal or NaN words. | | PS `v_interp` read methods (SHADER-181, translator side) | Bits 0–1 of the FSSM input record's flags byte (byte 7; `fssm_header.read_methods`) give the **read method** of each table position: bit 0 (0x01) = read through `v_interp_mov_f32`, bit 1 (0x02) = read through `v_interp_p1/p2` or the f16 forms. They do not give the D3D interpolation mode, which is PSV0's (row "PS interpolation modes", `tools/ps_interp_modes.py`, #1256). Exactly one bit is set in every corpus record (bit 1 in 51,191, bit 0 in 4,600). In all 12,101 PS every bit-0 position the code reads is read only by `v_interp_mov_f32` (4,295 read positions), every bit-1 position only by `p1/p2` or the f16 forms (49,594), and no position is read both ways (1,902 positions are unread, and 88 reads fall past the table). The translator follows the read method, which is what the code does: `v_interp_mov` → `Flat`, `p1/p2` → a plain input (perspective, pixel center; `BaryCoordKHR` for raw i/j). That this one pair is perspective-center holds because PSV0 lists no centroid, sample or noperspective generic input, and the code reads one barycentric pair (#1256). Table positions don't pair one-to-one with PSV0 rows, since the table keeps only the inputs the compiled code uses, so a PSV0 row's mode and the record's read method can differ at a paired position; #1256 counts those cases. `rdna2spirv.check_read_methods` refuses a PS whose read position disagrees with its record's read method (`v_interp_mov` of a bit-1 position, `p1/p2`/f16 of a bit-0 one), or whose record has neither or both bits, instead of reading it as perspective-center. It refuses 0 of 12,101 PS, and shard 0/12 translates byte-identically to before the check. `index.json` records `ps_flat_interpolants`, the bit-0 positions. Tests: `tests/test_rdna2spirv_pixelinput.py` and `tests/test_fssm_header.py` (synthetic). GPU-checked by @Vonsek on #1246 (RTX 5080 and Radeon integrated graphics, stock `ps_flat` with a hand-built table of read methods 2 and 1): the smooth channels match a per-center perspective reference, the flat channel keeps the provoking value, and flipping either record's read method makes the translator refuse the shader. Bit 3 (0x08, 11,619 records) is a Float16-typed parameter per #1256. | -| 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 the SPIR-V interpreter check both reads at two points of one triangle, and both fallback modes raise Unsupported (`test_p0_and_interpolated_read_of_one_f32_location` in `tests/semantic/test_interp_mov_flat.py`). [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) | +| 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) | | 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). | | 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. 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`). | | 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`). | @@ -410,8 +417,9 @@ How the generated SPIR-V expects the runtime to work: | Full-corpus pipeline build | `vk_pipeline_check pipeline_cache.bin --jobs 4` on an RTX 4060 Ti (NVIDIA 595 driver): **all 26,503 shaders become real pipelines, 0 failures** (cs 2,689, ps 12,101, ms 9,282, vs 2,236, gs 195; graphics stages with generated stub partners). Compile time 40,784 s of CPU (2.84 h wall on 4 threads): cs 23,633 s (mean 8.8 s; the ray-tracing ScreenProbes/RTShadowTrace shaders take 2-19 min each), ps 11,481 s, ms 5,395 s, vs 275 s. The resulting `VkPipelineCache` is 3.81 GB; seeding a run with it makes those pipelines instant, which is what a fast first boot needs. The cache is per driver and GPU, and a shader whose SPIR-V changes compiles again (the checker resumes from the file). Neither register storage (one variable per register) nor smaller SPIR-V cut NVIDIA compile time: the big ray-tracing shaders are expensive as such, so the runtime should compile them in the background rather than block on them. | | `v_cndmask_b32` source modifiers | `v_cndmask_b32` only moves bits, so a VOP3 `abs` on `src0`/`src1` clears bit 31 and `neg` flips it (`abs` first) as plain bit moves (`OpBitwiseAnd 0x7FFFFFFF`, then `OpBitwiseXor 0x80000000`, `Gen.src_u_sign_mods`), never `FAbs`/`OpFNegate`: a signalling NaN stays signalling and a denormal isn't flushed. Until 2026-11-23 the sources went through `Gen.modify`, and the mini interpreter quieted them (`-v1` of `0x7F800001` gave `0xFFC00001`, not `0xFF800001`). **Not measured on hardware for this instruction**: the rule follows the same VOP3 input modifiers measured as sign-bit moves on `v_cmp_class_f32` (gfx1036, all four IEEE/denorm modes, row "Floating-point class compare" above), and LLVM's AMDGPU backend moves `fneg`/`fabs` through a select into `v_cndmask_b32_e64`'s source modifiers (`AMDGPUTargetLowering::foldFreeOpFromSelect`), which is only exact if they are sign-bit moves. Checked on the CPU and with `spirv-val` by `tests/semantic/test_cndmask_sign_mods.py` (15 words including signalling/quiet NaNs, denormals, zeros and infinities x `v`, `-v`, `\|v\|`, `-\|v\|` x both operands). | | Wave-uniform branches | VCC and EXEC are wave-wide registers, but one invocation holds only its own lane's bit. `s_cbranch_vccz/vccnz/execz/execnz` therefore reduce the condition across the subgroup (`OpGroupNonUniformAny`), so the whole wave takes the branch together, as on hardware. Before this, each lane decided alone. A lane could skip scalar instructions that the hardware wave executes (its SGPRs went stale for later code), and cross-lane ops or barriers inside the block saw a split wave. `v_cmp`/`v_cmp_class`/64-bit compares now write 0 for inactive lanes (hardware VOPC behaviour), so the reduction sees the true mask. GPU-checked with `runtime/test/shaders/ps_uniform_branch.asm`: lanes whose own VCC bit is 0 run the block's scalar add when their wave has any set bit. `s_cbranch_scc0/1` stay per lane; SCC is uniform as long as the SGPRs feeding it are. | -| Compute shaders | FSSM header word **0x138 = `COMPUTE_PGM_RSRC2`**: USER_SGPR [5:1], TGID_X/Y/Z_EN [9:7], TG_SIZE_EN [10], TIDIG_COMP_CNT [12:11], LDS_SIZE [23:15] in 512-byte units. Words **0x13C/0x140/0x144 = thread-group size**. Counted over all 2,689 CS listings of 1.0.2.1 by the SGPRs each reads before writing (operand roles from `shader_meta._split_operands`, over the code `translate()` keeps; in wave64 code a lane mask printed as one SGPR covers the pair; an earlier check gave 2,281 exact): 2,540 read nothing past the user SGPRs and enabled TGIDs (2,193 up to the last of them, 342 fewer, 5 none), and the other 149 overshoot only through loop-carried registers in the straight-line check: every extra read follows a branch, and the register is written later in program order. Followed through the CFG (written on every path before the read), 22 still overshoot; each extra register is written on some other path (only loop-carried ones in 15), so these are values undefined on some path, not a missing input. Read raw, 268 overshoot: the other 119 are listings with embedded data words, decoded as instructions. 0x110, which looked similar, doesn't match. Layout: s0..user−1 = user data (push constants), then the enabled workgroup IDs (`WorkgroupId`), and v0/v1/v2 = thread ID x/y/z (`LocalInvocationId`, separate VGPRs on GFX10). Example: the 1,013 shaders with RSRC2 `0x998` have 12 user SGPRs, group ID x/y in s12/s13, and compute x = s12·32 + v0. Shaders with TG_SIZE_EN are rejected for now. GPU-checked with `runtime/test/shaders/cs_lds.asm` through `runtime/test/vk_compute_test.cpp`: 4 groups × 64 threads, LDS exchange between the two waves of a group behind `s_barrier`, store through a V# into the device-address heap, 0 mismatches. | -| Signed-byte dot products | `v_dot4_i32_i8 D, S0, S1, S2` (VOP3P) is S2 plus the sum of the four products of the sign-extended bytes of S0 and S1, modulo 2^32; `v_dot4c_i32_i8 D, S0, S1` (VOP2) adds the same sum to D. Emitted as four pairs of `OpBitFieldSExtract`, `OpIMul` and `OpIAdd`. **Confirmed on RDNA2 hardware** (gfx1036, raw kernels through `tools/hw_oracle`): 10 operand sets, both instructions and both source orders of the accumulating one, with sign-mixed bytes and sums that wrap; the measured words are the table in `tests/semantic/test_alu_dot4_i8.py`. `clamp` and `op_sel`/`op_sel_hi` are translated and checked against the same `gfx1036` hardware table: `clamp` saturates `v_dot4_i32_i8` to signed 32-bit `[-2^31, 2^31-1]` (both overflowing sets), and `op_sel`/`op_sel_hi` pick the 16-bit half of S0/S1 for byte pairs 0..1 and 2..3 (e.g. `op_sel` 2 / `op_sel_hi` 5 exchanges the 16-bit halves of S1, matching all 5 measured sets — the form of the 89 words `llvm-mc` does not decode, [fspx.md](fspx.md)); non-default S2 half selection stays refused. `neg_lo`/`neg_hi`, which `llvm-mc` accepts on `v_dot4_i32_i8` only, are not ignored (`neg_lo` flips bit 15 and `neg_hi` bit 31 of S0 or S1, and on S2 `neg_hi` clears bit 31 before `neg_lo` flips it; 5 sets under 8 forms, 45 words): any set bit stays Unsupported, while an all-zero field is the plain instruction. Counts: the 29 FSPX programs use the pair 27,271 times (`v_dot4c_i32_i8` 25,813, `v_dot4_i32_i8` 1,458), all in 13 programs; none of the game's own 26,503 shaders has either encoding (0 of the 12,791 words `llvm-mc` cannot decode there with gfx1013). | +| Compute shaders | FSSM header word **0x138 = `COMPUTE_PGM_RSRC2`**: USER_SGPR [5:1], TGID_X/Y/Z_EN [9:7], TG_SIZE_EN [10], TIDIG_COMP_CNT [12:11], LDS_SIZE [23:15] in 512-byte units. Words **0x13C/0x140/0x144 = thread-group size**. Counted over all 2,689 CS listings of 1.0.2.1 by the SGPRs each reads before writing (operand roles from `shader_meta._split_operands`, over the code `translate()` keeps; in wave64 code a lane mask printed as one SGPR covers the pair; an earlier check gave 2,281 exact): 2,540 read nothing past the user SGPRs and enabled TGIDs (2,193 up to the last of them, 342 fewer, 5 none), and the other 149 overshoot only through loop-carried registers in the straight-line check: every extra read follows a branch, and the register is written later in program order. Followed through the CFG (written on every path before the read), 22 still overshoot; each extra register is written on some other path (only loop-carried ones in 15), so these are values undefined on some path, not a missing input. Read raw, 268 overshoot: the other 119 are listings with embedded data words, decoded as instructions. 0x110, which looked similar, doesn't match. Layout: s0..user−1 = user data (push constants), then the enabled workgroup IDs (`WorkgroupId`), and v0/v1/v2 = thread ID x/y/z (`LocalInvocationId`, separate VGPRs on GFX10). Example: the 1,013 shaders with RSRC2 `0x998` have 12 user SGPRs, group ID x/y in s12/s13, and compute x = s12·32 + v0. With TG_SIZE_EN (none of the 2,689; 91 compute programs of the pipeline library, [shader_library.md](shader_library.md)) the next SGPR is the thread-group word, which the prologue writes: the number of waves in the group in bits [5:0] and this wave's index in it in bits [11:6], the wave index again in bits [24:20] and bit 31 set in the group's first wave (measured on gfx1036 through `tools/hw_oracle`, #6446: wave32 x 128 threads gives `80000004 00100044 00200084 003000c4`; one library program reads [24:20]; not measured on gfx1013) (Mesa `ac_nir_lower_intrinsics_to_args.c`, GFX6-10: `load_num_subgroups` and `load_subgroup_id` read those fields, and a wave64 compute shader's local invocation index is `mbcnt(~0, tg_size & 0xfc0)`; the library programs read it as `s_and_b32 sN, sTG, 0xfc0`, most of them then `v_mbcnt_lo_u32_b32`). Thread i is in wave i / W, as for `s_get_waveid_in_workgroup`. CPU-checked by `tests/semantic/test_cs_tg_size.py`, including the gfx1036 words. GPU-checked with `runtime/test/shaders/cs_lds.asm` through `runtime/test/vk_compute_test.cpp`: 4 groups × 64 threads, LDS exchange between the two waves of a group behind `s_barrier`, store through a V# into the device-address heap, 0 mismatches. | +| Scalar copies through VCC | SGPRs 106 and 107 can hold two data words, including a buffer descriptor's count and format. A 64-bit move through VCC preserves both when its reads within the block use them as data. Predicate users and live-out VCC constrain this inference. A wide scalar load into a tuple ending in VCC writes both physical words. The synthetic descriptor fixture checks numeric copies, a round trip, and a subsequent tuple load on wave32 and emulated wave64. | +| Signed-byte dot products | `v_dot4_i32_i8 D, S0, S1, S2` (VOP3P) is S2 plus the sum of the four products of the sign-extended bytes of S0 and S1, modulo 2^32; `v_dot4c_i32_i8 D, S0, S1` (VOP2) adds the same sum to D. Emitted as four pairs of `OpBitFieldSExtract`, `OpIMul` and `OpIAdd`. **Confirmed on RDNA2 hardware** (gfx1036, raw kernels through `tools/hw_oracle`): 10 operand sets, both instructions and both source orders of the accumulating one, with sign-mixed bytes and sums that wrap; the measured words are the table in `tests/semantic/test_alu_dot4_i8.py`. `clamp` and `op_sel`/`op_sel_hi` are translated and checked against the same `gfx1036` hardware table: `clamp` saturates `v_dot4_i32_i8` to signed 32-bit `[-2^31, 2^31-1]` (both overflowing sets), and `op_sel`/`op_sel_hi` pick the 16-bit half of S0/S1 for byte pairs 0..1 and 2..3 (e.g. `op_sel` 2 / `op_sel_hi` 5 exchanges the 16-bit halves of S1, matching all 5 measured sets — the form of the 89 words `llvm-mc` does not decode, [fspx.md](fspx.md)); non-default S2 half selection stays refused. A word `llvm-mc` does decode but prints with the default fields (op_sel_hi other than `[1,1,1]` with op_sel bit 1 clear: it re-encodes op_sel 0 / op_sel_hi 7, so the text names the wrong halves) takes the stored op_sel and op_sel_hi from the blob, in a clean listing (`check_printed_encodings`) and when re-anchoring, only when those two fields are the whole difference (`dot4_op_sel_fields`); anything else is still refused as a dropped field. Found in an FSPX program by luizwidmer/palmetto (GPL-3.0, ported); the fields are applied by the rule measured above, checked by `tests/semantic/test_dot4_printed_op_sel.py` (hand-built words); not re-counted over the corpus. `neg_lo`/`neg_hi`, which `llvm-mc` accepts on `v_dot4_i32_i8` only, are not ignored (`neg_lo` flips bit 15 and `neg_hi` bit 31 of S0 or S1, and on S2 `neg_hi` clears bit 31 before `neg_lo` flips it; 5 sets under 8 forms, 45 words): any set bit stays Unsupported, while an all-zero field is the plain instruction. Counts: the 29 FSPX programs use the pair 27,271 times (`v_dot4c_i32_i8` 25,813, `v_dot4_i32_i8` 1,458), all in 13 programs; none of the game's own 26,503 shaders has either encoding (0 of the 12,791 words `llvm-mc` cannot decode there with gfx1013). The measured unclamped `op_sel` 2 / `op_sel_hi` 5 form is also recovered from the bytes on a gap in a listing that `shader_disasm.py` did not print it into (`skipped_form`, #984). | | Workgroup barriers | `s_barrier` (cs/ms) is one `OpControlBarrier` (workgroup scope, workgroup memory). On RDNA every `s_barrier` counts against the same workgroup barrier and a wave that has ended no longer counts, while Vulkan requires a barrier to be reached by every invocation in uniform control flow. Under `--wave64-emulate` the round loop keeps a single barrier at the top level, so this holds. **Native wave32 compute shaders run in barrier rounds** when an `s_barrier` sits anywhere but a top-level block of the structured tree (one every invocation runs): under a guard, in a loop, or in the dispatch loop (`needs_barrier_rounds`, `bar_scheduler`). That is the emulated loop without its cross-lane part: `s_barrier` ends a segment, each invocation runs its blocks until its next `s_barrier` or the end, then the whole workgroup meets at one `OpControlBarrier` (the same workgroup/acquire-release/workgroup-memory semantics) at the end of the round. A wave that is done no longer holds the others, and a per-round count of the invocations not done (three `Workgroup` words, by round mod 3) ends the loop. A wave that is done no longer holds the others, and a per-round count of the invocations not done (three `Workgroup` words, by round mod 3, or a borrowed LDS word with a large LDS: "Barrier-round count in LDS (SHADER-579)") ends the loop. Cross-lane operations stay subgroup operations, as in the dispatch loop, since a wave's lanes run the same segment. A barrier in a top-level block keeps the single `OpControlBarrier` in place. In the 1.0.2.1 corpus 43 of the 55 wave32 cs shaders with `s_barrier` have one nested (SHADER-91's count), so those 43 now run in rounds. Why: an Intel GPU does not survive the nested form. `cs_barrier_divergent.asm` (two barrier sites in different branches), `cs_barrier_early_end.asm` (the other waves end without a barrier) and `cs_barrier_loop.asm` (a barrier in a loop whose trip count differs per wave) each lose the device (`vkQueueWaitIdle` → `VK_ERROR_DEVICE_LOST`) on an Intel Arrow Lake Xe-LPG iGPU (Windows 32.0.101.8132), and `cs_barrier_divergent` hangs or writes nothing on a UHD 770 (101.6129, #634). With barrier rounds all three pass there and on an RTX 5070 Ti Laptop (617.42). NVIDIA passed them before too (RTX 4070 Ti on 610.88 and 621.24, RTX 5090 on Linux 595.99, RTX 5070 Ti). **Still not proven on the native wave64 path** (wave64 cs and every ms, run natively only on AMD's 64-wide subgroups): there the barrier stays where `s_barrier` is, inside a selection or loop construct in every ms and most wave64 cs shaders of the corpus. Branches are scalar, so whole waves take the same path, and RDNA's own barrier counts the way the shader expects. | | Barrier-round count in LDS (SHADER-579) | Barrier rounds (see "Workgroup barriers") count the invocations not done in `%x_buf`, three `Workgroup` dwords (#930). On a full 32 KiB LDS that made 32,780 B, 12 bytes over the 32,768 B `maxComputeSharedMemorySize` of the AMD Windows (RX 9070 XT) and Intel (UHD 770) drivers, so the runtime refused those pipelines (2 native wave32 cs in towade's 1.0.2.1 corpus, [finding](https://github.com/ItsNotRexed/Leonida/pull/1882#issuecomment-7084298032)). Rule (`bar_counts_in_lds`): when the shader uses its LDS and the LDS array plus 12 bytes is over 16,384 B (the Vulkan minimum limit, so in practice an array of 16, 32 or 64 KiB), there is no `%x_buf`. The count borrows LDS word 0 at the end of each round (`bar_scheduler_tail`): after the round's barrier every invocation is done or waits at `s_barrier`, so no shader code runs; invocation 0 saves the word in a Function variable and clears it, barrier, every invocation not done adds 1 atomically, barrier, all read the count, barrier, invocation 0 stores the saved word back, barrier. The shader sees its LDS bit for bit as before, and the four extra barriers sit where the whole workgroup already waits, so `s_barrier`'s semantics are unchanged; the cost is four more `OpControlBarrier`s per round in those shaders only. Below the threshold `%x_buf` stays (12 bytes fit every device) with one barrier per round; a shader that never touches its LDS also keeps it (no array to borrow from, 12 B in all). A 32 KiB LDS is now exactly 32,768 B and a 64 KiB one 65,536 B (before: 65,548 B, refused or shrunk to its allocation). Not chosen: putting the count in LDS the shader never touches (unprovable with dynamic addresses), or deciding per device (the translator runs offline). Pinned by `tests/semantic/test_cs_barrier_counts_lds.py` (Workgroup bytes from the emitted SPIR-V and `lds_bytes` for 32 KiB, 64 KiB and small LDS, under a 32 KiB `--max-shared-memory`; ring shifts across 10 barriers that read word 0 and an early-ending wave in the workgroup interpreter, whose LDS starts as 0xDEADBEEF, in both wave orders). Confirmed by those CPU tests only; GPU runs on the 32 KiB devices are pending. | | LDS | A `Workgroup` uint array sized from LDS_SIZE, rounded up to a power of two that also covers every constant offset (15 of 486 shaders index past LDS_SIZE). Covers `ds_read/write_b32..b128`, `read2/write2` (+`st64`), `u16`/`i16`/`u8`/`i8` reads (also `ds_read_u16_d16`/`_d16_hi` and, since SHADER-85, `ds_read_u8_d16`/`_d16_hi` and `ds_read_i8_d16`/`_d16_hi`: the byte is zero- or sign-extended 8→16 into one half of the destination VGPR and the other half is kept, per the RDNA2 ISA DS opcode descriptions (opcodes 162–165) and as for the u16 d16 reads; GPU-checked with `cs_w32_lds_u8_d16.asm`, byte values 0x80/0xFF/0x7F with a non-zero `offset:`), `b16`/`b8` writes (atomic and/or, so neighbouring lanes don't race; a 16-bit read or write at byte 3 of a dword also reads or writes byte 0 of the next dword, as llc-15 `-mcpu=gfx1030 -mattr=+unaligned-access-mode` emits one `ds_read_u16`/`ds_write_b16 ... offset:3` for an align-1 halfword; until 2026-11-22 the reads extracted 16 bits at bit 24, undefined in SPIR-V, and the writes kept only byte 3; `tests/semantic/test_lds_u16_cross_dword.py`), the add/sub/min/max/and/or/xor atomics with and without return, `wrxchg`, `cmpst` (`OpAtomicCompareExchange` with DATA as comparator and DATA2 as value), and `ds_bpermute_b32` as a subgroup shuffle. GPU-checked with `cs_w32_lds_u8_d16.asm`, byte values 0x80/0xFF/0x7F with a non-zero `offset:`), `b16`/`b8` writes (atomic and/or, so neighbouring lanes don't race), the add/sub/min/max/and/or/xor atomics with and without return, `wrxchg`, `cmpst` (`OpAtomicCompareExchange` with DATA as comparator and DATA2 as value), and `ds_bpermute_b32` as a subgroup shuffle. `ds_permute_b32`, its forward (scatter) form, has no Vulkan equivalent: each source lane that is on in EXEC publishes `((vAddr + offset) >> 2) mod 32` and each destination lane scans the 32 sources of its half and keeps the last one that targets it (a shuffle of target and data per source lane; under `--wave64-emulate` two buffer rounds and a Function variable instead). Per the ISA pseudocode (`tmp[0..63] = 0`; `next if !EXEC[i]` on the source; `VGPR[VDST][i] = tmp[i]` only `if EXEC[i]`): a destination lane nobody targets gets 0, an off source sends nothing, an off destination keeps its VDST, and the half rule above applies as for `ds_bpermute_b32`. When several sources target one lane the ISA leaves the winner unpredictable ("the value from one of the writers"; its pseudocode says the highest-numbered); the translator takes the highest, and nothing may depend on it. Confirmed by the GPU tests `cs_w32_permute.asm` and, per half of a wave64, `cs_w64x_permute.asm` (SHADER-90: rotation, offset, unwritten lane = 0, off destination keeps its value, off source does not win), `cs_w32_partial_permute.asm` (a 20-thread wave32: a launched lane whose source lane was never launched gets 0, and a send to a missing lane is lost; the same words from a raw 20-thread `hw_oracle` kernel on `gfx1036`) and `tests/semantic/test_ds_permute.py`. **Hardware-verified on RDNA2 (`gfx1036`, AMD Ryzen 7 9800X3D iGPU, Linux AMDGPU DRM via `tools/hw_oracle`, wave32 and wave64, SHADER-133)** with `tools/ds_permute_probe.py` (9/9 cases exact in both wave sizes): unaddressed active lanes get 0, off destinations keep VDST, off sources send nothing, 2-/4-/32-way collisions deterministically take the highest-numbered active lane in the 32-lane half (matching the translator), `vAddr + offset` carries from the low 2 bits before `>> 2` mod 32, wave64 runs as two independent 32-lane halves (`+32` wraps within each half), and missing lanes of a partial wave (20 threads in wave32, 40 in wave64) send nothing. A source lane that is off in EXEC reads 0 and an off destination lane keeps its value (RDNA ISA §10.4.4), in wave32 as in wave64. In wave64 the permute also runs as two wave32s: each half reads lanes of its own half. Until 2026-11-21 lanes 32–63 of a 64-wide subgroup read the low half and inactive sources kept their value (`cs_w64x_bpermute`, AMD Radeon 880M); the wave32 path shuffled the raw value until the same day (`cs_bpermute32`: wave32, EXEC without lanes 8–15, so lane 6 reads 0; GPU-checked on RTX 5070 and Radeon 880M). A source lane that doesn't exist, in the missing lanes of a partial wave, also reads 0: the shuffle result is kept only where a ballot of the running invocations has the source lane, since SPIR-V leaves a shuffle from an invocation that isn't running undefined. Before this, RADV returned stale register values that changed between runs (`cs_w64x_partial`, a 40-thread group, native wave64 on AMD RX 6700 XT, RADV Mesa 26.3.1). Writes and atomics run only in active lanes. Indices wrap at the array size, where hardware would return 0 for out-of-range reads. `s_barrier` = `OpControlBarrier` Workgroup/Workgroup, AcquireRelease + WorkgroupMemory. | @@ -430,6 +438,7 @@ How the generated SPIR-V expects the runtime to work: | Compute workgroup IDs Y/Z | With four user SGPRs and only TGID_Y and TGID_Z enabled (RSRC2 `0x308`), s4 receives Y and s5 receives Z. The synthetic `cs_workgroup_yz.asm` fixture checks a 2 × 3 × 4 dispatch and each of its 24 origins against a CPU reference. | | Typed image stores | `image_store` (2D, 2D array, 3D, cube) writes the dmask components (missing ones = 0). The image's numeric type lives in the T# (word 1 FORMAT [28:20], 512 GFX10 formats), so it is decided at run time. A 512-bit table built from `tools/gfx10_formats.json` (30 UINT and 15 SINT formats) picks a **sint**, **uint** or **float** view (bindings 8 + 3·dim + class; dim 0 = 2D, 1 = 2D array, 2 = 3D; class 0 float, 1 uint, 2 sint). Views have Unknown format (`shaderStorageImageWriteWithoutFormat`). **The runtime binds every storage image into all three arrays of its dimension, or at least the one matching its format.** The earlier path wrote only component 0 as `r32ui`, which was wrong for every other format. GPU-checked with `runtime/test/shaders/cs_imgstore.asm` through `runtime/test/vk_store_test.cpp`: rgba8 unorm, r32 uint and r32 sint images, every texel correct. A cube storage image is bound as a six-layer 2D array (bindings 11/12/13 for float/uint/sint, `OpTypeImage ... 2D 0 1 0 2 Unknown`, `%v3int` coordinates (x, y, face)); `tfe` and `lwe` are refused. CPU-checked by `tests/semantic/test_image_cube_store_glc.py`. GPU-checked with `runtime/test/shaders/cs_imgstore_cube.asm` through `vk_store_test cube` (GPU-CUBE-STORE): rgba8 unorm, r32 uint and r32 sint cube images, each a cube-compatible 8x8 image of six layers bound through a six-layer 2D-array view at index 1-3 of bindings 11/12/13, and every texel of every face exact (the face selects the layer) on an RTX 4070 Ti (NVIDIA 620.70.06, Linux) and a Radeon 610M (`gfx1036`, RDNA2, RADV Mesa 26.2.6), natively and under `LEONIDA_W64_EMULATE=1`; the same fixture with the face held at 0 fails on both. | | Typed image loads | A noncoherent cube `image_load` reads the 2D-array sampled binding (3) with integer coordinates and layer. Its T# format selects the float, uint or sint alias, including for D16. The [RDNA2 ISA §8.2.1](https://docs.amd.com/v/u/en-US/rdna2-shader-instruction-set-architecture) assigns D16 conversion to the image format. The synthetic `cube_load_d16.asm` checks the generated views and format choices on the CPU. `image_load` on 1D/2D/2D-array/3D images uses the same T# FORMAT tables as stores, and fetches every format with `OpImageFetch` from the sampled array of its dimension (bindings 0, 3, 6, 5): UINT/SINT formats through **uint/sint aliases of that array** (same set and binding, an `OpTypeImage` of `%uint`/`%int`; Vulkan allows several variables on one binding when the descriptor type fits), everything else through the float array. A lookup miss (index 0) takes the float path, since the fallback there is RGBA8_UNORM. Results are the raw bits of the dmask components. **The runtime binds each image's view in its own format at its index of the sampled array** (what `bind_image` in `runtime/shims/d3d12_vulkan_device.cpp` already does for SRVs and UAVs), so the view's numeric type matches the alias that reads it. No storage image is read, so shaders that only load need neither `shaderStorageImageReadWithoutFormat` (missing on Intel Xe-LP, #619) nor `shaderStorageImageWriteWithoutFormat` (SHADER-151). Until 2026-11-22 integer formats were read with `OpImageRead` from the uint/sint storage arrays (bindings 8–19), which hold only unordered-access views and 256 entries: a read-only integer texture found the fallback there, or an index past the array's end. Like the float path, the fetch goes through the texture path, so it sees writes made before the dispatch, not ones made earlier in the same dispatch. **d16 loads take the same branch** (#1136) and pack the dmask components two per VGPR, low half first: f16 (round to nearest even, integer ops, no `PackHalf2x16`) from the float array, the low 16 bits of each value from the uint/sint aliases (truncated). **d16 loads take the same branch** (#1136) and pack the dmask components two per VGPR, low half first: f16 (round to nearest even, integer ops, no `PackHalf2x16`) from the float array, each value from the uint/sint aliases saturated to the 16-bit range of its signedness (`saturate_int16`). For odd component counts (1 or 3 in `dmask`), the trailing destination VGPR preserves its existing high 16 bits (`write_lo16`), matching native `gfx1036` hardware where a seeded `0x5a5a` high half survived 1-component UINT/SINT `image_load` and `image_load_mip`; until 2026-11-22 the unused high half was zeroed. Before #1136, a d16 load always read the float view, so a `Texture2D` `Load` returned garbage. CPU-checked by `tests/test_image_load_typed.py` (capabilities, bindings and component types for every dimension; the branch for all 512 FORMAT values, found and missed). GPU-checked with `runtime/test/shaders/cs_imgload.asm` through `vk_store_test load`, on a device made without `shaderStorageImageReadWithoutFormat`: r32 uint and r32 sint images filled before the dispatch, both read with `image_load` and their sum stored, every texel exact on an RTX 2080 Ti (NVIDIA 621.14, Windows 11), clean under the validation layer with GPU-assisted validation; the test fails a module that declares `StorageImageReadWithoutFormat`. d16: CPU-checked by `tests/test_image_load_d16_typed.py` (the uint/sint fetches go through the aliases, no storage image is read, the SPIR-V validates); GPU-checked with `runtime/test/shaders/cs_imgload_d16.asm` through `vk_store_test load`: both pre-filled texels read with d16 loads (the sint one sign-extended from bit 15 in the shader) and their sum stored, every texel exact on the RTX 2080 Ti with GPU-assisted validation (#1136 checked its first form, a store and d16 read-back in one dispatch, on an RTX 5070, and `cs_imgload_d16` passes unchanged on an AMD RX 7600 (gfx1102, RADV Mesa 27.0.0-devel) in `run_gpu_tests.py`). GPU-checked with `runtime/test/shaders/cs_imgload_d16.asm` through `vk_store_test load`: both pre-filled texels read with d16 loads (the sint one sign-extended from bit 15 in the shader) and their sum stored, every texel exact on the RTX 2080 Ti with GPU-assisted validation (#1136 checked its first form, a store and d16 read-back in one dispatch, on an RTX 5070). 2D `image_load_mip` uses the same numeric-type selection and passes the address register's mip to each fetch. Its D16 form packs the selected components in ascending order, two per VGPR. An RGBA8 two-level texture was checked on RTX 5080 and Radeon Graphics: all four exported halves matched the CPU reference for UINT, SINT and UNORM, and forcing level 0 changed every pixel. Checked on RTX 5080 and Radeon Graphics with R8G8B8A8 UINT, SINT and UNORM textures: level 1 matched the CPU reference at every pixel with GPU-assisted validation, and forcing level 0 changed all 4096 pixels for each format. Native gfx1036 saturated 32-bit UINT/SINT texels to the unsigned/signed 16-bit range in both D16 load forms; the translated 2D load matched both limits on RTX 5080 and Radeon Graphics. Native gfx1036 does the same on every dimension (SHADER-387, `tools/image_d16_probe.py`): 32_UINT and 32_32_UINT texels saturate to [0, 0xffff] and 32_SINT and 32_32_SINT texels to [-32768, 32767], never truncate, in 1D, 2D, 2D-array and 3D images, through `image_load` and `image_load_mip` alike; two-channel results pack x low and y high, and a one-channel result keeps the seeded high half. The translated d16 loads on 1D, 2D-array and 3D images still lack GPU checks. | +| Resident `image_load tfe` | When no lane faults, the status VGPR retains its prior value. The status follows the data VGPRs, with D16 packing two components per data VGPR. `cs_imgload_tfe` and `cs_imgload_d16_tfe` seed both status registers and check that the translated loads preserve them on fully resident images (GPU-checked on RTX 4070 Ti, Windows driver 630.20). The ordinary image-load lowering covers the resident case. Reporting sparse texel faults requires a separate lowering. [AMD RDNA 2 ISA §8.2.1, TFE and D16](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf), [LLVM AMDGPU instruction selection](https://github.com/llvm/llvm-project/blob/llvmorg-16.0.6/llvm/lib/Target/AMDGPU/AMDGPUInstructionSelector.cpp#L1804-L1833) | | Packed 2D mip-load addresses | For `image_load_mip` with `a16`, the first VGPR holds unsigned X (low half) and Y (high half). The low half of the second VGPR selects the mip and its high half is unused. Both ordinary and D16 results use the same address. LLVM gfx1030 assembles both forms in `tests/semantic/fixtures/packed_mip_load_2d.asm`. `tests/test_image_load_typed.py` checks the texel and mip operands of the float, UINT and SINT fetches, including noncontiguous address registers. [AMD RDNA 2 ISA, MIMG A16 field](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) | | 3D explicit-mip loads | `image_load_mip` reads x, y, z and mip from four address VGPRs. T# FORMAT selects the float, UINT or SINT 3D sampled view at binding 6. D16 narrows the selected components before packing them low half first. The unit test `test_volume_mip_fetch_uses_xyz_level_and_descriptor_type` in `tests/test_image_load_typed.py` checks the four address registers and the RGBA32 format selection on the translated module. Native gfx1036 measured UINT and SINT saturation for 3D `image_load_mip` at mip zero. [Volume load measurements](https://github.com/ItsNotRexed/Leonida/pull/2217) | | Typed 2D gathers | `image_gather4_lz(_o)` takes one channel from four taps. For `image_gather4_l(_o)` the four manual fetches share the rounded, clamped mip and addressed footprint. The T# FORMAT selects the float, UINT or SINT sampled image at binding 0. For d16, integer taps are packed low half first, two per VGPR; float taps round to f16. \| AMD RDNA 2 ISA §8.2 (MIMG D16). RTX 5080 and Radeon Graphics matched a CPU clamp-to-edge gather over all 4096 RGBA32F pixels for 8-bit UINT, SINT and UNORM, both packed and unpacked, with zero offset and with (+1,-1). Selecting red in place of green changed all 4096 pixels. Explicit LOD 1 on two-level UINT, SINT and UNORM images also matched all 4096 pixels for both offset forms on both GPUs. Forcing mip 0 changed every pixel. Native gfx1036 saturates out-of-range integer taps as in the typed image loads below. On the CPU, the unit tests `test_explicit_lod_gather_fetches_four_taps_from_each_typed_view` and `test_2d_gather_picks_the_sampled_type_and_selected_component` in `tests/test_image_load_typed.py` check the typed views at binding 0, the selected component, the shared mip footprint and the d16 packing. | @@ -444,7 +453,7 @@ How the generated SPIR-V expects the runtime to work: | VOP3 output and source modifiers in the game's forms, on RDNA2 | Every distinct float VALU form in the 26,503 listings that carries `clamp`, an omod (`mul:2`/`mul:4`/`div:2`), `op_sel`/`op_sel_hi` or neg/abs: 572 forms, 1,270,932 instructions (`v_mul_legacy_f32 … clamp` alone is 147,499; `v_fma_mix_f32` has 222 forms), up to 120 random operand triples each, run natively on gfx1036 (`tools/hw_oracle`, the game's MODE) and through the translator: 542 forms, 64,802 cases (the GFX10.1-only `v_mad_f32`/`v_mad_legacy_f32`/`v_mac_f32` and `v_permlanex16` are left out). 51,761 give the translator's word. The rest are differences already on record: NaN sign and payload (5,074); f32 denormal operands or results, and a denormal intermediate that the hardware flushes before the omod or clamp (1,178; SHADER-377); an omod turning a -0 result into +0 (121; the Output modifiers rows, #1281); 1 ulp or the known sin/cos precision in `v_rcp/v_rcp_iflag/v_log/v_sin/v_cos` with an omod (56); and 6,430 whose translation is undefined in SPIR-V, mostly `FClamp` of a NaN, where the hardware gives +0 under DX10_CLAMP (#2437; the f32/f16 clamp of a NaN gives +0 since 2026-11-24, see "Float min/max/med3 with NaN"). 182 cases were my harness's (three distinct SGPRs, over GFX10's two-read limit). No other modifier difference. `tests/semantic/test_alu_vop3_mods_hw.py` replays 1,616 matching words, up to three per form; it fails without `clamp` (326 rows) or without the omod (237). | | Byte permute | `v_perm_b32`: result byte i = BYTE_PERMUTE({src0, src1}, selector byte i), src1 = bytes 0–3 (AMD "RDNA 2" ISA reference, VOP3 opcode 836 V_PERM_B32, `byte_permute` pseudocode, page 189 of the PDF). Selector 0–7 picks that byte; **8, 9, 10, 11 give 0xff if bit 7 of byte 1, 3, 5, 7 is set, else 0x00**; 12 gives 0x00; 13 and above give 0xff. **Until 2026-11-21 selectors 8–11 gave 0x00 regardless of the sign bit**. In the 26,503-shader disassembled corpus (measured via `tools/feature_scan.py`), 0 of 10,500 shaders (11,930 `v_perm_b32` instructions) use selectors 8–11 or >= 13: all 11,258 immediate and 672 constant-register selectors (0 unresolved) use only bytes 0–7 (36,234) and 12 (11,486). GPU-checked with `runtime/test/shaders/ps_ops7.asm` (also `v_alignbit_b32` with a shift of 36, `v_med3_i32` vs `v_med3_u32`) and `ps_ops8.asm` (`v_mul_hi_u32/i32`, `v_bcnt_u32_b32`, `v_ffbl_b32`, `v_ffbh_u32` of 0, `v_xad_u32`, `v_add3_u32`), 4096/4096 pixels on an AMD Radeon iGPU (Ryzen 7 9800X3D, RDNA2, AMD driver 25.10.36) and an NVIDIA GeForce RTX 5070 (driver 621.24); before the fix `ps_ops7` gave 0x00000000 for the sign-selector word on both. Also executed by `tests/semantic/test_value_semantics.py`. When S2 is a literal or a currently known SGPR constant, the translator emits fixed byte extracts/inserts (including sign replication), folds the zero and 0xff bytes, and uses the selected source directly for a whole-word identity. `tests/semantic/test_perm_known_selector.py` checks the resulting words and that selector dispatch only remains for a clobbered SGPR. | | Sum of absolute differences (`v_sad_u8`, `v_sad_hi_u8`, `v_sad_u16`, `v_sad_u32`, `v_msad_u8`) | Unsigned, wrapping at 32 bits, with ABSDIFF(x, y) = `UMax − UMin`: `v_sad_u8` = S2 + the sum over the four bytes; `v_sad_hi_u8` = (that byte sum << 16) + S2; `v_sad_u16` = S2 + the sum over the two halves; `v_sad_u32` = \ \| S0 − S1\ \| + S2; `v_msad_u8` skips a byte where S1's byte is 0. `clamp` raises `Unsupported`: the ISA pseudocode doesn't say what it does to these ops. Source: RDNA2 ISA VOP3 opcodes 346–349 and 369 (pseudocode re-read for this row). CPU-checked by `tests/semantic/test_alu_sad.py` (#544): a 9×9 grid of edge words per op, 40 seeded cases, masked bytes, an SGPR source, `clamp` rejected; the PR also reports a 300-case differential run per op with 0 mismatches. None of them is in the translated corpus, and none is GPU-checked. **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). Measured on native gfx1036 (AMD Radeon Graphics, RDNA2) through tools/hw_oracle across edge byte/half patterns, zero masks, and wrap cases: all match the ISA reference with 0 mismatches. | -| Quad-byte SAD 64-bit source operands | The GFX10.3 `null` operand supplies zero for the 64-bit input window in all three quad-byte SAD operations and for the 64-bit addend of the two packed forms. Confirmed with LLVM gfx1030 assembly and scalar byte-difference references in `tests/semantic/test_alu_qsad.py` (`test_null_pixel_source_and_null_accumulator`) and `tests/semantic/test_alu_mqsad_u32.py` (`test_null_pixel_source`). | +| Quad-byte SAD 64-bit source operands | The GFX10.3 `null` operand supplies zero for the 64-bit input window in all three quad-byte SAD operations and for the 64-bit addend of the two packed forms. Confirmed with LLVM gfx1030 assembly and scalar byte-difference references in `test_alu_qsad.py` and `test_alu_mqsad_u32.py`. | | `v_mqsad_u32_u8` | Four masked byte-SADs with full 32-bit accumulators: D[k] = S2[k] + `v_msad_u8` of the 32-bit window S0[8k+31:8k] of the 64-bit S0 against S1, wrapping at 32 bits (S2 and D are four VGPRs). Every source is read before the first write; `clamp` raises `Unsupported`. Source: RDNA ISA pseudocode. CPU-checked by `tests/semantic/test_alu_mqsad_u32.py`. **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). Measured on native gfx1036 (AMD Radeon Graphics, RDNA2) through tools/hw_oracle across 64-bit sliding window and masked byte values against the 32-bit accumulators: bit-exact with the ISA reference. | | `s_sext_i32_i8`, `s_sext_i32_i16`, `s_flbit_i32` | The first two sign-extend the low byte or the low half of S0 to 32 bits (`OpBitFieldSExtract`). `s_flbit_i32` counts how many bits in a row from the MSB equal the sign bit, and gives −1 when all bits are the same (0 and −1); it is the scalar form of `v_ffbh_i32` and goes through the same code. None of the three writes SCC. Source: RDNA2 ISA SOP1 opcodes 23, 25 and 26. CPU-checked by `tests/semantic/test_salu_sext_flbit.py` (#549): edge words with SCC starting at 0 and at 1, and 30 seeded values with long runs of sign bits. Not in the translated corpus, not GPU-checked. **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137, SCC kept). Measured on native gfx1036 (AMD Radeon Graphics, RDNA2) through tools/hw_oracle and tools/salu_diff.py (500 programs, --oracle translator,hw): 500 pass, 0 mismatches against the reference; confirmed s_flbit_i32 gives 0xFFFFFFFF for 0 and -1. | | `v_lerp_u8` | Per byte i: `D.b[i] = (S0.b[i] + S1.b[i] + (S2.b[i] & 1)) >> 1`, an unsigned average where bit 0 of S2's byte decides whether 0.5 rounds up. The translator uses the per-byte identity `x + y = 2*(x & y) + (x ^ y)`. It clears each byte's low bit before shifting, then adds the rounding bit only to an odd sum. Each result fits in one byte, so the packed additions do not carry across bytes. The 9-bit sum shifted right by 1 fits back in its byte, so nothing carries between bytes. `clamp` raises `Unsupported` (the ISA doesn't define it for this op). Source: RDNA2 ISA VOP3 opcode 333. CPU-checked by `tests/semantic/test_alu_lerp_u8.py` (#577): a 9×9×5 grid of edge and rounding words, 40 seeded cases, an SGPR source with an inline S2, `clamp` rejected. The synthetic `tests/semantic/fixtures/lerp_packed_bytes.asm` gives exact words across a 64x64 draw on an RTX 3070 (NVIDIA 591.86). Not in the translated corpus, not GPU-checked. **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). Measured on native gfx1036 (AMD Radeon Graphics, RDNA2) through tools/hw_oracle across byte edge values and rounding bit variations: 0 mismatches against the ISA reference. | @@ -452,9 +461,9 @@ How the generated SPIR-V expects the runtime to work: | `v_bfi_b32` | `(S0 & S1) \| (~S0 & S2)` (RDNA2 ISA, VOP3 opcode 330). A literal or known same-block SGPR mask of zero or all ones selects S2 or S1 directly. A contiguous mask uses `OpBitFieldInsert` with S1 shifted down by the field offset, since RDNA2 reads the bits in place. For sparse constant masks the translator precomputes the complement. Runtime masks use the full bitwise expression. Checked by the hand-written `bfi_known_mask.asm` and `tests/semantic/test_bfi_known_mask.py`. | | `v_bfm_b32` | The low five bits of S0 give the width and those of S1 give the offset. The result is the low 32 bits of `((1 << width) - 1) << offset` (RDNA2 ISA §12.12, VOP3 opcode 867). Literal and same-block SGPR constants are folded in the translator, including zero width and shifts that discard the high bits. Runtime operands keep their low-five-bit masks. Checked by `tests/semantic/test_bfm_known_operands.py` and `test_alu_int_misc.py`. | | `s_bfe_u32` / `s_bfe_i32` past bit 31 | offset = S1[4:0], width = S1[22:16] (7 bits; S1 bits 23 to 31 are ignored). When offset + width > 32 the field stops at bit 31: width = min(width, 32 - offset), and `s_bfe_i32` sign-extends from the top bit that exists. Example: `s_bfe_i32 s4, 0xd2f90159, 0x7f001c` gives `0xfffffffd` (4-bit field `0xd`), not `0xd`. SCC = D ≠ 0. Source: measured on gfx1150 (Radeon 880M) with `tools/salu_diff.py --oracle hw`, 4000 random control words, all bit-exact, on gfx1201 (Radeon RX 9070, RDNA4) with 10,000 `salu_diff --oracle hw` programs, 0 mismatches (seed 500 with `--bfe-any`), and **on RDNA2** (AMD Radeon 680M, `gfx1035`: `tools/salu_diff.py --oracle hw,translator --bfe-any --programs 500 --seed 1`, 500/500 match, plus `tools/int_hw_probe.py --oracle both` wave32 and wave64, SHADER-137; and RDNA2 `gfx1036`, Windows 11, driver 26.10.1, `tools/hw_oracle` HIP launcher: `tools/salu_diff.py --oracle translator,hw --bfe-any --ops s_bfe_u32,s_bfe_i32 --programs 2000` with seeds 1, 2 and 3, 6,000 of 6,000 programs pass on both sides, plus seed 4 over every opcode with `--bfe-any`, 2,000 of 2,000, and `int_hw_probe.py`'s `salu_bfe_past31` cases in wave32 and wave64); the translator (`bfe_width`) already did this. `tools/salu_diff.py --oracle hw,translator --bfe-any --programs 500 --seed 1`, 500/500 match, plus `tools/int_hw_probe.py --oracle both` wave32 and wave64, SHADER-137); the translator (`bfe_width`) already did this. Source: measured on gfx1150 (Radeon 880M) with `tools/salu_diff.py --oracle hw`, 4000 random control words, all bit-exact, and on gfx1201 (Radeon RX 9070, RDNA4) with 10,000 `salu_diff --oracle hw` programs, 0 mismatches (seed 500 with `--bfe-any`); the translator (`bfe_width`) already did this. LLVM's v_bfe fold (`constantFoldBFE`) is analogous but has a 5-bit width. **RDNA2 is not measured**; the ISA pseudocode does not say. | -| 64-bit scalar data ops (`s_brev_b64`, `s_bfe_u64`/`s_bfe_i64`, `s_bitset0_b64`/`s_bitset1_b64`, `s_flbit_i32_b64`/`s_flbit_i32_i64`) | The SGPR pair is 64-bit data, as for `s_lshl_b64`; a pair that `lane_masks.py` marks as a lane mask (or EXEC) stays `Unsupported` (#210). `s_brev_b64`: D.lo = reverse(S0.hi), D.hi = reverse(S0.lo). `s_bfe_*64`: offset = S1[5:0], width = S1[22:16]; width 0 gives 0; a field past bit 63 stops there (the 64-bit form of the `s_bfe_u32` rule, LLVM `constantFoldBFE`); SCC = D ≠ 0. `s_bitset*_b64`: bit S0 & 63 of the pair cleared / set. `s_flbit_i32_b64`: zeros above the top 1 from bit 63, −1 for 0; `s_flbit_i32_i64`: the same of ~S0 when S0 < 0, −1 for 0 and −1. None but `s_bfe` writes SCC. Source: RDNA2 ISA SOP1/SOP2. CPU-checked by `tests/semantic/test_salu_brev_b64.py`, `test_salu_bfe_64.py`, `test_salu_bitset_b64.py`, `test_salu_flbit_64.py` (#723, #726, #729, #733). **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1), one raw wave32 kernel per op through `tools/hw_oracle`: `s_brev_b64` of 0x12345678_0000000F has low word 0x1E6A2C48, `s_bfe_u64(0x00000123_45678000, w16 o28)` = 0x1234, `s_bfe_i64(0x00000001_80000000, w2 o31)` has 0xFFFFFFFF in both words, `s_bitset1_b64(0, 40)` has high word 0x100, `s_flbit_i32_b64(0x00010000)` = 47 and `s_flbit_i32_i64(0xFFFFFFFF_FFFF0000)` = 48. These are the words `runtime/test/shaders/cs_w32_salu64.asm` expects. Also **hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). | -| `v_bfe_u32` / `v_bfe_i32` past bit 31 | offset = S1[4:0] and width = S2[4:0]: the bits above are ignored, so an offset of 36 reads as 4 and a width of 32 as 0 (a width of 0 gives 0). When offset + width > 32 the field stops at bit 31, as for `s_bfe`: width = min(width, 32 - offset), and `v_bfe_i32` sign-extends from bit 31. Example: `v_bfe_i32` of `0xd2f90159` with offset 28 and width 16 gives `0xfffffffd` (4-bit field `0xd`), not `0xd`, and `0x80000000` with offset 31 and width 4 gives `0xffffffff`. The translator (`bfe_width` for VGPR or SGPR offset and width, the same cut folded at translation time for constants) already did this. Source: **measured on RDNA2**, AMD Radeon 610M (`gfx1036`, Windows 11, AMD driver 32.0.11016.14003), wave32 and wave64 identical, 16 words over VGPR, inline-constant and literal operands: `tools/int_hw_probe.py --oracle both --group valu_bfe_past31`, 4/4 cases match the translator. The words are pinned on the CPU by the unit test `ValuBfeMeasuredOnRdna2.test_translator_gives_the_gfx1036_words` in `tests/test_int_hw_probe.py`. | -| `s_quadmask_b32`/`_b64`, `s_bitreplicate_b64_b32` | On scalar data (RDNA2 ISA SOP1): `s_quadmask_b32` sets D[i] to the OR of S0[4i+3:4i] for the 8 quads, `s_quadmask_b64` does the same for the 16 quads of the 64-bit S0 (D[63:16] = 0), and both set SCC = D != 0. `s_bitreplicate_b64_b32` copies each bit S0[i] to D[2i] and D[2i+1] and leaves SCC. Built from fixed shift/mask steps, with no loop. A lane-mask source (EXEC, VCC or an SGPR that `holds_lane_mask`) or an EXEC/VCC destination raises `Unsupported`: each invocation holds only its own lane's bit, and these ops read the other lanes of a quad or move bits between lanes. Until 2026-11-22 all three were rejected. CPU-checked by `tests/semantic/test_salu_quadmask_bitreplicate.py` (fixed and seeded values, SCC written or kept, immediates, aliasing, lane masks rejected). **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1) through `tools/hw_oracle`, one raw wave32 kernel per op: `s_quadmask_b32(0xF)` = 1 with SCC 1, `(0xF0000000)` = 0x80, `(0x0F0F0F0F)` = 0x55 (the set quads are 0, 2, 4 and 6), `(0)` = 0 with SCC 0; `s_quadmask_b64` of 0xF = 1 and of 0xF0000000_00000000 (quad 15, bits 60..63) = 0x8000 in the low word with D[63:16] = 0; `s_bitreplicate_b64_b32` of 5 = 0x33 and of 0x80000000 = 0xC0000000_00000000, with SCC left as it was. **GPU-checked** by `runtime/test/shaders/cs_w32_new_ops.asm` (`s_quadmask_b32(0x01020408)` = 0x55, `s_quadmask_b64(0x80000000_00000001)` low word 0x8001, `s_bitreplicate_b64_b32(0x80000001)` high word 0xC0000000, with the expected words from the ISA pseudocode), exact on the Radeon iGPU of a Ryzen 9 9950X3D (RDNA2, `gfx1036`, driver 26.10.1) and an RTX 5080 (driver 616.92). **Not GPU-verified.** | +| 64-bit scalar data ops (`s_brev_b64`, `s_bfe_u64`/`s_bfe_i64`, `s_bitset0_b64`/`s_bitset1_b64`, `s_flbit_i32_b64`/`s_flbit_i32_i64`) | The SGPR pair normally carries 64-bit data. In wave64, `s_flbit_i32_b64` can also gather both halves of a lane mask or EXEC before scanning it. The other operations require scalar data. `test_library_compute_forms.py` checks an empty mask and set bits in either half on native and emulated waves. `s_brev_b64`: D.lo = reverse(S0.hi), D.hi = reverse(S0.lo). `s_bfe_*64`: offset = S1[5:0], width = S1[22:16]; width 0 gives 0; a field past bit 63 stops there (the 64-bit form of the `s_bfe_u32` rule, LLVM `constantFoldBFE`); SCC = D ≠ 0. `s_bitset*_b64`: bit S0 & 63 of the pair cleared / set. `s_flbit_i32_b64`: zeros above the top 1 from bit 63, −1 for 0; `s_flbit_i32_i64`: the same of ~S0 when S0 < 0, −1 for 0 and −1. None but `s_bfe` writes SCC. Source: RDNA2 ISA SOP1/SOP2. CPU-checked by `tests/semantic/test_salu_brev_b64.py`, `test_salu_bfe_64.py`, `test_salu_bitset_b64.py`, `test_salu_flbit_64.py` (#723, #726, #729, #733). **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1), one raw wave32 kernel per op through `tools/hw_oracle`: `s_brev_b64` of 0x12345678_0000000F has low word 0x1E6A2C48, `s_bfe_u64(0x00000123_45678000, w16 o28)` = 0x1234, `s_bfe_i64(0x00000001_80000000, w2 o31)` has 0xFFFFFFFF in both words, `s_bitset1_b64(0, 40)` has high word 0x100, `s_flbit_i32_b64(0x00010000)` = 47 and `s_flbit_i32_i64(0xFFFFFFFF_FFFF0000)` = 48. These are the words `runtime/test/shaders/cs_w32_salu64.asm` expects. Also **hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). `tests/semantic/test_lane_mask_bitreplicate_flbit.py` runs EXEC and VCC masks on every lane of a wave64. `s_flbit_i32_i64` of a lane mask, and `s_flbit_i32_b64` of one in wave32 (whose `vcc_hi` is data), stay `Unsupported`. | +| `v_bfe_u32` / `v_bfe_i32` past bit 31 | offset = S1[4:0] and width = S2[4:0]: the bits above are ignored, so an offset of 36 reads as 4 and a width of 32 as 0 (a width of 0 gives 0). When offset + width > 32 the field stops at bit 31, as for `s_bfe`: width = min(width, 32 - offset), and `v_bfe_i32` sign-extends from bit 31. Example: `v_bfe_i32` of `0xd2f90159` with offset 28 and width 16 gives `0xfffffffd` (4-bit field `0xd`), not `0xd`, and `0x80000000` with offset 31 and width 4 gives `0xffffffff`. The translator (`bfe_width` for VGPR or SGPR offset and width, the same cut folded at translation time for constants) already did this. Source: **measured on RDNA2**, AMD Radeon 610M (`gfx1036`, Windows 11, AMD driver 32.0.11016.14003), wave32 and wave64 identical, 16 words over VGPR, inline-constant and literal operands: `tools/int_hw_probe.py --oracle both --group valu_bfe_past31`, 4/4 cases match the translator. The words are pinned on the CPU by `tests/test_int_hw_probe.py` (`ValuBfeMeasuredOnRdna2`). | +| `s_quadmask_b32`/`_b64`, `s_bitreplicate_b64_b32` | On scalar data (RDNA2 ISA SOP1): `s_quadmask_b32` sets D[i] to the OR of S0[4i+3:4i] for the 8 quads, `s_quadmask_b64` does the same for the 16 quads of the 64-bit S0 (D[63:16] = 0), and both set SCC = D != 0. `s_bitreplicate_b64_b32` copies each bit S0[i] to D[2i] and D[2i+1] and leaves SCC. Built from fixed shift/mask steps, with no loop. An EXEC destination, or in wave64 a VCC destination, of `s_bitreplicate_b64_b32` gives lane L bit L // 2 of S0 (in wave32 VCC's high word is data, so it stays `Unsupported`; EXEC since 6ecd922d9; VCC, which the 1.0.2.1 pipeline library writes from a constant, checked on every lane of a wave64 by `tests/semantic/test_lane_mask_bitreplicate_flbit.py`). A 32-bit lane-mask source (`exec_lo`/`exec_hi`, `vcc_lo`/`vcc_hi`) of `s_bitreplicate_b64_b32` into a scalar (non-EXEC/VCC) destination reads that half of the wave's mask as data (`Gen.wave_mask`, as `s_ff1_i32_b64` reads one) and replicates it as any scalar (#998, for 6 pipeline-library programs of 1.0.2.1). Confirmed only by the CPU interpreter on every lane of a wave64 (`test_lane_mask_bitreplicate_flbit.py`: EXEC halves and a compare's VCC halves, synthetic lines) and by the ISA pseudocode above; not measured on hardware. Any other lane-mask source (EXEC, VCC or an SGPR that `holds_lane_mask`) or EXEC/VCC destination raises `Unsupported`: each invocation holds only its own lane's bit, and these ops read the other lanes of a quad or move bits between lanes. Until 2026-11-22 all three were rejected. CPU-checked by `tests/semantic/test_salu_quadmask_bitreplicate.py` (fixed and seeded values, SCC written or kept, immediates, aliasing, lane masks rejected). **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1) through `tools/hw_oracle`, one raw wave32 kernel per op: `s_quadmask_b32(0xF)` = 1 with SCC 1, `(0xF0000000)` = 0x80, `(0x0F0F0F0F)` = 0x55 (the set quads are 0, 2, 4 and 6), `(0)` = 0 with SCC 0; `s_quadmask_b64` of 0xF = 1 and of 0xF0000000_00000000 (quad 15, bits 60..63) = 0x8000 in the low word with D[63:16] = 0; `s_bitreplicate_b64_b32` of 5 = 0x33 and of 0x80000000 = 0xC0000000_00000000, with SCC left as it was. **GPU-checked** by `runtime/test/shaders/cs_w32_new_ops.asm` (`s_quadmask_b32(0x01020408)` = 0x55, `s_quadmask_b64(0x80000000_00000001)` low word 0x8001, `s_bitreplicate_b64_b32(0x80000001)` high word 0xC0000000, with the expected words from the ISA pseudocode), exact on the Radeon iGPU of a Ryzen 9 9950X3D (RDNA2, `gfx1036`, driver 26.10.1) and an RTX 5080 (driver 616.92). **Not GPU-verified.** | | 64-bit scalar bitwise ops (`s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64`, `s_orn2_b64`, `s_nand_b64`, `s_nor_b64`, `s_xnor_b64`, `s_not_b64`) | Dispatched like `s_cselect_b64`: when destination is `exec`/`vcc` or any source is a lane mask (`holds_lane_mask` or `exec`/`vcc`), uses the per-lane mask path (`mask_src`/`mask_dst` including `null` dst) and votes SCC across the wave (`scc_from_mask`). Otherwise operates on both 32-bit dwords of non-mask 64-bit scalar data (SGPR pairs, sign-extended inline/literal immediates, `null` = 0), reads all source dwords before storing (preserving destination aliasing), accepts `null` destination, and sets `SCC = ((D.lo \ \| D.hi) != 0)`. Until 2026-11-22 these ops always took the lane-mask path, duplicating D.lo into D.hi and voting SCC on D.lo alone. `s_nand/nor/xnor_b64` compute `~(S0 op S1)` on both paths (a lane's mask value is 0 or ~0, so the NOT is per lane); until 2026-11-22 they were rejected as unsupported. Source: RDNA2 ISA SOP1/SOP2. CPU-checked by `tests/semantic/test_salu64_bitwise_data.py` (all 9 ops, 4-corner SCC, immediates, aliasing, stale mask overwrite, wave32/wave64 lane-mask regression, and `--wave64-emulate`); **Hardware-verified** on the same part through `tools/hw_oracle` for the plain-data path: `s_and_b64(0xFFFFFFFF_00000000, 0x0F0F0F0F_0F0F0F0F)` = 0x0F0F0000_00000000, `s_xnor_b64(0xFFFF0000_00000000, 0_FFFFFFFF)` = 0x0000FFFF_00000000, `s_nand_b64(0xFFFF0000_0, 0)` = 0xFFFFFFFF_FFFFFFFF, `s_not_b64(0x0000FFFF_0)` = 0xFFFF0000_FFFFFFFF and `s_andn2_b64(0xFFFF0000_0, 0)` = 0xFFFF0000_0, all with SCC 1, while `s_or_b64(0, 0)` = 0 with SCC 0: SCC = ((D.lo ≠ 0) or (D.hi ≠ 0)). The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way; on RDNA3 the same plain-data path is **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way; on RDNA3 the same plain-data path is **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo \| The measured plain-data words: The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way; on RDNA3 the same plain-data path is **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo \| The measured plain-data words: `s_and_b64(0xFFFFFFFF_00000000, 0x0F0F0F0F_0F0F0F0F)` = 0x0F0F0000_00000000, `s_xnor_b64(0xFFFF0000_00000000, 0_FFFFFFFF)` = 0x0000FFFF_00000000, `s_nand_b64(0xFFFF0000_0, 0)` = 0xFFFFFFFF_FFFFFFFF, `s_not_b64(0x0000FFFF_0)` = 0xFFFF0000_FFFFFFFF and `s_andn2_b64(0xFFFF0000_0, 0)` = 0xFFFF0000_0, all with SCC 1, while `s_or_b64(0, 0)` = 0 with SCC 0. The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way. **Not GPU-verified.** **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo \| The measured plain-data words: **Not GPU-verified.** **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo \| D.hi) != 0`, the `andn2`/`orn2` pairs separate negation of the second source from negation of the first, `s_not_b64` inverts both dwords and clears SCC on a zero result, and `s_nand_b64`/`s_nor_b64`/`s_xnor_b64` invert the per-dword result (`and`/`or` of all ones gives `0` with SCC 0, `xnor` of equal pairs gives all ones with SCC 1); the lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. The lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. D.hi) != 0`, the `andn2`/`orn2` pairs separate negation of the second source from negation of the first, `s_not_b64` inverts both dwords and clears SCC on a zero result, and `s_nand_b64`/`s_nor_b64`/`s_xnor_b64` invert the per-dword result (`and`/`or` of all ones gives `0` with SCC 0, `xnor` of equal pairs gives all ones with SCC 1); the lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. **Not GPU-verified.** **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way; on RDNA3 the same plain-data path is **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo | The measured plain-data words: `s_and_b64(0xFFFFFFFF_00000000, 0x0F0F0F0F_0F0F0F0F)` = 0x0F0F0000_00000000, `s_xnor_b64(0xFFFF0000_00000000, 0_FFFFFFFF)` = 0x0000FFFF_00000000, `s_nand_b64(0xFFFF0000_0, 0)` = 0xFFFFFFFF_FFFFFFFF, `s_not_b64(0x0000FFFF_0)` = 0xFFFF0000_FFFFFFFF and `s_andn2_b64(0xFFFF0000_0, 0)` = 0xFFFF0000_0, all with SCC 1, while `s_or_b64(0, 0)` = 0 with SCC 0. The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way. The lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. D.hi) != 0`, the `andn2`/`orn2` pairs separate negation of the second source from negation of the first, `s_not_b64` inverts both dwords and clears SCC on a zero result, and `s_nand_b64`/`s_nor_b64`/`s_xnor_b64` invert the per-dword result (`and`/`or` of all ones gives `0` with SCC 0, `xnor` of equal pairs gives all ones with SCC 1); the lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. \| | Constant lane masks (`Gen.mask_src` immediates) | A constant read as a lane mask is one bit per lane: lane L takes bit L. The 64-bit forms (`s_and/or/andn2_saveexec_b64`, `s_andn2_wrexec_b64`, `s_mov_b64`/`s_not_b64` into EXEC or VCC, `s_and/or/xor/andn2/orn2_b64` and `s_cselect_b64` on the lane-mask path) read the 64-bit value, an inline constant sign-extended (`-16` = lanes 4-63) and a literal with a zero high word, as `src64_data` reads 64-bit constants; the b32 forms (`s_*_saveexec_b32`, `s_andn2_wrexec_b32`) read the 32-bit value at bit L mod 32. 0 and -1 still give no lane and every lane, with no per-lane code. `s_bcnt0/1_i32_b64` and `s_ff0/1_i32_b64` of a constant read the constant's 64 bits via `src64_data` (scalar data: inline negative constants sign-extend to 64 bits, so `s_ff0_i32_b64 s0, -1` gives −1 rather than 32, and 32-bit literals zero-extend; CPU-checked in `tests/semantic/test_scalar_bitcmp.py`, **not yet GPU-verified**). `s_bcnt0/1_i32_b64` of a constant counts the constant's 64 bits (scalar data, like `s_ff0/1_i32_b64`). **Before this fix every lane took bit 0 of the constant**: `s_and_saveexec_b32 s7, 0xff00` with all 32 lanes on left none on, `5` left all 32 on, and `s_bcnt1_i32_b64 s0, 0xff00ff` gave 32. llvm-mc rejects a constant as the mask operand of `v_cndmask_b32_e64` / `v_add_co_ci_u32_e64` and decodes one as "Invalid immediate", so those VALU callers never see a constant. **A constant held in an SGPR** (`s_mov_b32 s20, 0x3ffffc00`) is read the same way when it reaches a mask consumer: `mask_src` takes bit L of an SGPR that `holds_lane_mask` doesn't flag (a pair in a wave64 64-bit context: the high SGPR for lanes 32-63). In a wave32 or wave64 program a 32-bit bitwise SALU op (`s_not_b32`, `s_and/or/xor/andn2/orn2/nand/nor/xnor_b32`, `s_cselect_b32`) that writes EXEC/VCC (`exec_lo`/`vcc_lo` in wave32; `exec_lo`/`exec_hi` and mask-holding `vcc_lo`/`vcc_hi` in wave64, including after `s_mov_b64 vcc, 0/-1`) skips scalar constant folding, reads its operands through `Gen._mask_b32_src` / `mask_src` (collecting the opposite half through `wave_mask` if a wave64 op mixes `lo` and `hi` halves), preserves the untouched half of EXEC/VCC in wave64 (`exec_half_write` / `put_mask`), and votes SCC over the wave (wave32) or that 32-lane half (wave64, `scc_any_half`), matching `s_not_b32` and the binary ops on lane-mask SGPRs too; into a plain SGPR with a constant it stays a data read, because `lane_masks.py` classifies that SGPR as data when the other operand is a constant (`s_and_b32 s20, exec_lo, 1` then `s_bcnt1` must count the wave's bits: found by @Pierre-Kookis on #1792, GPU-reproduced), and `s_mov_b32 exec_lo/exec_hi, sN` takes each lane's bit. In a wave32 program a 32-bit bitwise SOP2 (`s_and/or/xor/andn2/orn2/nand/nor/xnor_b32`, `s_cselect_b32`) that writes EXEC/VCC reads both operands through `mask_src` (`Gen.sop2_b32_srcs`); into a plain SGPR it stays a data read, because `lane_masks.py` classifies that SGPR as data when the other operand is a constant (`s_and_b32 s20, exec_lo, 1` then `s_bcnt1` must count the wave's bits: found by @Pierre-Kookis on #1792, GPU-reproduced), and `s_mov_b32 exec_lo/exec_hi, sN` takes each lane's bit. A real mask is unchanged: it holds 0 or ~0 per lane, and bit L of that is the same 0 or 1. Until 2026-11-22 these took the value whole, so `s_and_saveexec_b32 s6, s20` with that constant, or `s_and_b32 exec_lo, exec_lo, 0xff00`, left every lane on (found writing `cs_w32_saveexec_ext`, #1771; CPU-checked by `tests/semantic/test_mask_src_sgpr_const.py`, and `tools/cf_diff.py` / `tools/salu_diff.py` still pass). `s_not_b32` on lane masks, `s_and/or/xor_b32` with two immediates into `vcc_lo`, and wave64 half-mask bitwise ops (destination half preservation, `exec_hi`, and `scc_any_half`) are CPU-checked in `tests/semantic/test_salu_b32_lane_masks.py` (wave32, wave64, and `--wave64-emulate`, validated with `spirv-val`) and GPU-checked on gfx1036, RTX 5080 (`--wave64-emulate`), and RX 9060 XT (RADV). Not covered here: a b32 op on one half of a wave64 mask, masks read as data (#293), and a literal with bit 31 set in a 64-bit position (zero- vs sign-extension not measured). GPU-checked with `runtime/test/shaders/cs_w32_mask_imm.asm` and `cs_w64_mask_imm.asm` on an NVIDIA GeForce RTX 5080 (driver 616.92; wave64 with `LEONIDA_W64_EMULATE=1`) and an AMD Radeon RDNA2 iGPU (driver 26.10.1, native 64-wide subgroup): both failed before on both GPUs. Run across every lane in `tests/semantic/test_value_semantics.py` (`LaneMaskConstants`). **A computed value written to EXEC** (`s_lshl_b32`, `s_add_u32`, `s_bfm_b32`, and every other SALU result that reaches `exec_lo`/`exec_hi` through `Gen.dst`) takes each lane's bit too: until 2026-11-24 the generic path tested the value for non-zero, so `s_lshl_b32 exec_lo, 1, s5` ran all 32 lanes of that half (SHADER-1264; `Gen.exec_bit`). The words are the GPU's, recorded in `runtime/test/shaders/cs_w32_exec_computed.asm` and `cs_w64_exec_computed.asm` (RTX 5070), and `tests/semantic/test_exec_computed.py` replays them through the CPU interpreter. A value that already holds this lane's bit of a mask (0 or ~0) gives the same answer. | | Scalar select and pack (`s_cmov_b32`, `s_cmovk_i32`, `s_pack_ll/lh/hh_b32_b16`) | `s_cmov_b32` / `s_cmovk_i32`: D = SCC ? S0 : D (`s_cmovk_i32`'s S0 is the 16-bit immediate, sign-extended); SCC is read, not written; the destination must be an SGPR (a lane-mask destination, and `s_cmov_b64`, stay `Unsupported`, #210). `s_pack_*`: the low half of D from S0, the high half from S1, the letters naming the half of each (l = 15:0, h = 31:16), S0 first; GFX10 has no `s_pack_hl`; SCC not written. Source: RDNA2 ISA SOP1/SOP2/SOPK. CPU-checked by `tests/semantic/test_salu_cmov.py` and `test_salu_pack.py`; the translated shaders were run on NVIDIA by reviewers (`s_cmov*`: RTX 5090, RTX 4050 and Radeon 740M in #613; `s_pack_*`: RTX 5090 in #449). **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137, SCC kept). | @@ -480,7 +489,7 @@ How the generated SPIR-V expects the runtime to work: | `v_cvt_pknorm_i16_f32`, `v_cvt_pknorm_u16_f32` | D[15:0] from S0 and D[31:16] from S1: the f32 is clamped to [-1, 1] (i16) or [0, 1] (u16), multiplied by 32767 or 65535 and rounded to nearest even **once, from the exact product** (SHADER-363). Mesa ACO emits these opcodes for NIR `pack_snorm_2x16`/`pack_unorm_2x16`, which `nir_opcodes.py` defines as `fround_even(fclamp(x) * 32767.0 / 65535.0)`. Emitted as `FClamp`, `OpFMul`, `RoundEven` and a convert, not `PackSnorm2x16`, whose rounding GLSL leaves to the driver. The f32 `OpFMul` can land exactly on k + 0.5 when the exact product is just below or above it, and `RoundEven` would then pick the even neighbour; the product's error `Fma(c, s, -p)` is exact, so on such a tie the translator takes floor(p) + 1 when it is positive, floor(p) when negative, and `RoundEven` when it is 0 (an exact tie). Away from a tie the two roundings agree, since k + 0.5 is an f32 there. NaN gives 0, as `v_cvt_i32_f32` does. On gfx1035 (SHADER-137, `tools/int_hw_probe.py --oracle both`, wave32 and wave64) ±qNaN → 0, ±inf saturation and the round-to-nearest-even ties at ±0.5 match bit for bit. Source modifiers apply. VOP3 `clamp` is a hardware no-op on RDNA2 and is accepted without changing the result; other modifiers (`mul:*`/`div:*`, `op_sel:*`) raise `Unsupported`. Until 2026-11-22 both ops were rejected. **Measured on RDNA2:** on an iGPU (gfx1036, SHADER-339/363, `tools/pknorm_probe.py --oracle hw`) 74 of 74 NaN halves (quiet and signalling, both signs, payloads, in S0 and S1) gave 0 and 28 of 28 near-tie inputs (both directions) gave the single-rounded word, in wave32 and wave64 under the game's MODE and with IEEE 1, DX10_CLAMP 0 or f32 denormals kept; the translator matches all 134 probe words in all ten runs (it was one off on the 28 near ties before SHADER-363; additionally, `tools/cvt_norm_mods_probe.py --hw-arch gfx1036` verified `plain` vs VOP3 `clamp` across 40 edge/near-tie/NaN/±inf/subnormal pairs + 3 source-modifier cases across 6 `HW_REG_MODE` configurations and wave32/wave64 on `gfx1036` driver `32.0.21045.29003`: 2,064/2,064 words exact with 0 clamp diffs and 0 wave diffs). CPU-checked by `tests/semantic/test_alu_cvt_pknorm_f32.py` (the twelve measured near-tie words, ties at the scale steps, ±inf, ±NaN, subnormals, out-of-range values, 40 seeded pairs, abs/neg, `clamp`), `tests/semantic/test_cvt_norm_mods.py`, and `tests/test_pknorm_probe.py`. **GPU-verified through Vulkan** (wave32 synthetic compute shader via `vk_compute_test` with `VK_LAYER_KHRONOS_validation` `1.4.363`, 8 `v_cvt_pknorm_*` plain & `clamp` output words): bit-exact on `AMD Radeon RX 9070 XT` (driver `26.11.2 (LLPC)`, `driverVersion 2.0.416`, Vulkan `1.4.359`) and `AMD Radeon(TM) Graphics` (`gfx1036`, driver `26.11.2`, `driverVersion 2.0.353`, Vulkan `1.4.315`), 0 validation errors. | | f16 rounding (SHADER-55, SHADER-56) | **Narrowing to f16 uses integer ops, not `PackHalf2x16`.** Every f16 ALU result (`v_*_f16` VOP1/VOP2/VOP3, `v_pk_*_f16`, `v_cvt_f16_f32`, `v_interp_p2_f16`, `v_fma_mix*`) and `v_cvt_pkrtz_f16_f32` go through `Gen.f16_bits` (round to nearest even, or round toward zero for pkrtz; f16 denormals kept, f32 denormal inputs give ±0, NaN stays a quiet NaN). After a MODE.FP_ROUND toward-zero write the ALU results take the toward-zero form instead (`Gen.f16_res`; see Known approximations). GLSL.std.450 leaves `PackHalf2x16`'s rounding to the implementation, and drivers fold a `PackHalf2x16` → `UnpackHalf2x16` round trip to a no-op, so the next f16 op saw the unrounded f32: #513 (RTX 6000 Ada, `--wave64-emulate`, `v_pk_add_f16` → `v_pk_mul_f16` 1 ulp off), and pkrtz giving round-to-nearest on llvmpipe. **f16 FMAs round once** (`v_fma_f16`, `v_fmac_f16`, `v_pk_fma_f16`): x·y is exact in f32, TwoSum gives the exact error of the f32 sum, and round-to-odd at f32 then rounds correctly to f16. An RX 6700 matched a correctly rounded f16 FMA in 12,612 of 12,612 cases (#374); `Fma` then narrowing double-rounded. Checked by `tests/semantic/test_f16_int_convert.py` (edges + seeded sweep against Python's binary16), `tests/semantic/test_f16_fma_rounding.py` (exact rational reference; built near-tie cases fail on the old translation) and `tools/valu_fuzz.py --family f16` on an RTX 6000 Ada. Image/buffer d16 packing (#489) and the 16-bit interpolant quantize (#512) are separate. **Widening an f16 ALU operand doesn't trust `UnpackHalf2x16` with denormals** (`Gen.f16_in`): on an RTX 5060 Ti (610.88) it gives 0 for a denormal that an SDWA `BYTE_1` select produced, from an inline constant or a VGPR alike, while the same denormal as a literal or already in a VGPR widens right (a local probe of all four, before and after). It depends on the driver: `ps_sdwa_f16_const` failed this way on `main` with NVIDIA 610.88 (RTX 5060 Ti, RTX 3060 Ti, Windows), 595.99 (RTX 5090, Linux) and 580.173 (RTX 3060 Ti, Linux), and passed with 621.01 (RTX 5080) and 621.24 (RTX 5070, RTX 3080 Laptop) (#3220). So a half whose exponent field is 0 is widened as sign × mantissa × 2^-24 with integer ops. Confirmed by the GPU test `ps_sdwa_f16_const` (word y, the denormal `0x0040` × 1024.0 = `0x1c00`), which gave `0x0000` on an RTX 5060 Ti (610.88) natively and under `--wave64-emulate` before and 4096/4096 exact after, and by `tests/semantic/test_value_semantics.py` running it with a flushing `UnpackHalf2x16`. The other `UnpackHalf2x16` uses (packed-f16 reads, interpolants, d16 image results) are not changed. `v_fma_mix*` with f32 sources rounds once straight to f16 via round-to-odd in both nearest and toward-zero modes (measured on an RDNA2 iGPU, gfx1036: `tools/fma_mix_probe.py --oracle hw` gave the single-rounded word for all 7 of 7 tie inputs where the two rules differ, SHADER-135; see Known approximations). `v_fma_mix*` rounds once straight to f16 via round-to-odd in both nearest-even and toward-zero modes, matching hardware (7 of 7 tie inputs of `tools/fma_mix_probe.py --oracle hw` on gfx1036, SHADER-135; see Known approximations). `v_fma_mix*` rounds once straight to f16 via round-to-odd in both nearest and toward-zero modes (see Known approximations); the hardware rounds once: 7 of 7 tie inputs of `tools/fma_mix_probe.py --oracle hw` on gfx1036 (SHADER-135). `v_fma_mix*` with f32 sources uses `Fma` then narrows (two roundings, unmeasured) in nearest-even mode; toward zero it rounds once (see Known approximations). 7 of 7 tie inputs of `tools/fma_mix_probe.py --oracle hw` on gfx1036 (SHADER-135; not fixed yet); toward zero it rounds once (see Known approximations). | | `v_cvt_pknorm_i16_f16`, `v_cvt_pknorm_u16_f16` | VOP3 packed normalized conversion from two f16 sources (`D[15:0]` from `S0.f16`, `D[31:16]` from `S1.f16`): each selected f16 half (`op_sel[0..1]`, with `neg`/`abs` source modifiers and inline f16 constants via `Gen.f16_in`) is clamped to `[-1, 1]` (`i16`) or `[0, 1]` (`u16`), scaled by `32767` or `65535`, and rounded once to nearest even (`+inf → 32767`/`65535`, `-inf → -32767`/`0`, `NaN → 0`, `±0` and f16 denormals `→ 0`). Uses `cl * (scale + 1) - RoundEven(cl)` for `\|cl\| >= 0.25` to avoid binary32 double-rounding at near-tie f16 inputs (e.g. `0x3801` = `0.5 + 2^-11`). **Measured natively on RDNA2** (`AMD Radeon(TM) Graphics`, `gfx1036`, wave32 & wave64 via `tools/cvt_pknorm_f16_probe.py`): across all 65,536 binary16 inputs in `plain`, `clamp`, `op_sel:[0,0,1]`, and `op_sel:[0,0,1] clamp` (1,048,576 half evaluations) plus 33 targeted edge cases (264 words), VOP3 `clamp` is a **hardware no-op**, destination `op_sel[2] = 1` (`op_sel:[s0,s1,1]`) shifts the 32-bit packed result left by 16 bits (`D[31:16] = norm16(S0.f16)`, `D[15:0] = 0x0000`, overwriting prior `vdst` and dropping `S1`), and raw reserved VOP3 `omod` bits `[60:59]` (`1..3`) are ignored by silicon (rejected by `llvm-mc` on `gfx1036`). The translator accepts `clamp` (no-op) and `op_sel[2] = 1` (`OpShiftLeftLogical` by 16), while `mul:*`/`div:*`, VOP3P modifiers (`op_sel_hi:*`, `neg_lo:*`, `neg_hi:*`), `_dpp`/`_sdwa`, duplicate `op_sel:`, and malformed `op_sel` lists raise `Unsupported`. Output modifiers (`clamp`, `mul:*`, `div:*`), `op_sel` destination bit, and VOP3P modifiers raise `Unsupported`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) (VOP3 `v_cvt_pknorm_i16_f16` / `v_cvt_pknorm_u16_f16`) and LLVM AMDGPU `VOP3Instructions.td`. Checked bit-for-bit against an exact rational `fractions.Fraction` reference on the CPU (`spirv_mini_interp`) and with `spirv-val` by `tests/semantic/test_alu_cvt_pknorm_f16.py` and `tests/semantic/test_cvt_pknorm_f16_mods.py`, by unit tests `tests/test_cvt_pknorm_f16_probe.py`, and through Vulkan (`vk_compute_test` with `VK_LAYER_KHRONOS_validation`, 116/116 exact words, 0 clamp diffs, 0 validation errors) on `AMD Radeon RX 9070 XT` (driver `26.11.2 (LLPC)`) and `AMD Radeon(TM) Graphics` (`gfx1036`, driver `26.11.2`); not run on the shader corpus. Checked bit-for-bit against an exact rational `fractions.Fraction` reference on the CPU (`spirv_mini_interp`) and with `spirv-val` by `tests/semantic/test_alu_cvt_pknorm_f16.py`; **Hardware-verified on RDNA2** (AMD Radeon gfx1036, wave32 and wave64, `tools/int_hw_probe.py --oracle both --group valu_cvt_norm_f16`): 33 programs of four conversions each over +-0, +-1, 1 +- 1ulp, +-0.5 and the f16 neighbours of the 0.5 and 0.25 ties, an f16 denormal, +-65504, +-inf and quiet and signalling NaNs, with `op_sel:[1,0]`/`[0,1]` and `neg`/`abs`, all bit-identical to the translator. Not run on the shader corpus. **not GPU-verified** and not run on the shader corpus. . **Hardware-measured natively on `gfx1100`** (RX 7900 XTX, driver 26.10.1) with `tools/hw_oracle`, 38 cases against the same exact-rational model, all matching: the halves pack in the documented order (`0.3333 \| 0.5+2^-11` and `1.5 \| -0.5` are asymmetric), each result is one round-to-nearest-even of the exact `cl * 32767` or `cl * 65535` (`0x3801` gives `32799` for `u16`), out-of-range values and infinities saturate the same way (`+inf` gives `32767`/`65535`, `-inf` gives `-32767`/`0`, so an infinity clamps to `±1`), and `NaN` (quiet or signalling), `-0` and a denormal f16 input all give `0`. Not measured: the `op_sel` destination bit and the `neg`/`abs` source modifiers, and not run on the shader corpus. | -| `s_round_mode` | SIMM16[3:0] sets FP_ROUND. The translator accepts FP32 nearest-even with FP16/64 nearest-even or toward-zero and writes the same per-invocation state as `s_setreg_imm32_b32`. Other rounding modes raise Unsupported. AMD RDNA2 ISA tables 15 and 24; synthetic positive and negative halfway-neighbour conversions check both modes in one shader (`test_round_mode_switches_half_precision_color_rounding` in `tests/semantic/test_scalar_noop_waitcnt.py`). | +| `s_round_mode` | SIMM16[3:0] sets FP_ROUND. The translator accepts FP32 nearest-even with FP16/64 nearest-even or toward-zero and writes the same per-invocation state as `s_setreg_imm32_b32`. Other rounding modes raise Unsupported. AMD RDNA2 ISA tables 15 and 24; synthetic positive and negative halfway-neighbour conversions in `test_scalar_noop_waitcnt.py` check both modes in one shader. | | f16 narrowing size | `Gen.f16_bits` leaves out or shares steps where that can't change the result. In nearest-even mode there is no separate infinity select: infinity is already at or above the overflow threshold (65520), which gives 0x7C00. For `v_add_f16`, `v_sub_f16`, `v_subrev_f16` and `v_pk_add_f16` without omod (`exact_tiny`), the range below 2^-14 is neither rounded nor tested for underflow: a sum of two f16 values is a multiple of 2^-24, so there it is already an f16 value, and clamp keeps that true. With an omod the rounding stays, since `div:2` can create a tie. No range has an underflow test: below 2^-25 the shift is 25, which moves the mantissa (plus the rounding bias) out to 0. The subnormal range rounds like the normal one, by adding half - 1 + the kept low bit before the shift. When the program writes MODE, `Gen.f16_res` makes one pass: toward zero selects a bias of 0, the 65536 overflow threshold and 0x7BFF, and keeps the infinity select. Confirmed by running the emitted integer sequences before and after on all 2^32 f32 inputs (both roundings) and on all 2^32 f16 operand pairs (both roundings, with and without clamp): no difference. Regression test: `tests/semantic/test_f16_sum_narrowing.py`. | | `v_interp_p2_f16` clamp | The VOP3 `clamp` bit on `v_interp_p2_f16` clamps its f16 result to [0, 1], applied before the narrowing like the other f16 results (Mesa ACO `aco_opcodes.py` declares the op `dst(F16)`, which takes output modifiers; llvm-mc encodes `clamp` on it but no omod). Until 2026-11-22 the translator dropped it. Checked by `tests/semantic/test_interp_f16.py`: attributes 1.5 and -0.25 read with clamp give 1.0 and +0.0, and without it 1.5 and -0.25. No GPU test: `vs_ids` gives attributes in [0, 1) only. | | 16-bit interpolation (`v_interp_p1ll_f16` / `v_interp_p2_f16`, `high`) | A 16-bit varying shares its 32-bit param channel with another: the producer packs them as low half, high half (Mesa `ac_nir_prerast_utils.c`: `nir_pack_32_2x16_split` by `io_sem.high_16bits`), the PS sets `FP16_INTERP_MODE` (plus `ATTR1_VALID` when the high half is used, RADV `radv_ps_input_type_bits`), and the `high` bit picks the half on both ops of the pair (ACO `emit_interp_instr`, `aco_isel_helpers.cpp`; llvm-mc gfx1013 sets the same bit, byte 5 bit 0, on both: p1ll `v2, v0, attr0.x high` 0x00 → 0x01, p2 `v2, v1, attr0.x, v3 high` 0x02 → 0x03). The translated VS exports the channel's raw bits, so interpolating them as one f32 gives neither half. A location any `*_f16` interp reads is therefore declared `PerVertexKHR` (`vec4[3]`, no `Flat`; it still matches a producer's vec4 output at that location); this needs `VK_KHR_fragment_shader_barycentric` (`fragmentShaderBarycentric`) for every such PS, not just the raw-barycentric ones; the index records it like any capability (`features: ["fragmentShaderBarycentric"]`), so `vk_pipeline_check` and `vk_harness` skip such a PS on a device without it. Nothing picks `--bary-fallback` from the device: it is a translation-time flag. Each f16 read decodes its half of each vertex's word (`UnpackHalf2x16` component 0 or 1) and weights them as AMD does, P0 + i(P1 − P0) + j(P2 − P0) with i, j = `BaryCoordKHR`.y/.z, then p2 clamps and narrows as before. f32 reads of such a location (`p1/p2_f32`) interpolate the raw word the same way, and `v_interp_mov_f32` takes vertex 0's. Until 2026-11-22 `high` was ignored and both halves read the smooth-f32 interpolation of the whole word; abilliontokens counted `high` in 4,776 of 12,101 PS (39.5%, 51,684 instructions, always p1ll/p2 pairs, no `p1lv`), and Pipodi found 4,731 of those 4,776 read both halves of the same channel, with p1ll and p2 always agreeing on attribute, channel and `high`. Like the f32 path, the pair's I/J operands are not read: the weights come from `BaryCoordKHR` (213 PS that compute their own barycentrics into v0/v1 first are a separate gap). Confirmed by `tests/semantic/test_interp_f16_high.py` (per-vertex halves 0.5/1.5/2.5 and −4/8/16 at weights (0.25, 0.25, 0.5) give 1.75 and 9.0; fails on the old translation) and the GPU fixture `ps_interp_f16_high` drawn with `vs_f16_pack` (u and v packed in one channel both ways, f32 control) and, through `scripts/run_gpu_tests.py`, with the mesh producer `ms_f16_pack` (mesh `exp paramN` stores the same raw words, `Gen.ms_export`): both pass on an RTX 5070 and fail on the old translation (off by 0.984). spirv-val and `vk_pipeline_check` (real pipelines against the vec4 VS stubs, RTX 5070) also accept PS mixing high, low, f32 and flat reads of one location and of several. **Measured natively on RDNA2** (AMD Radeon 680M, `gfx1035`, wave32 and wave64 via `tools/vinterp_hw_probe.py --oracle both`, SHADER-430): the VINTRP unit reads `P0`, `P10` and `P20` from LDS at `M0 + 48·attr + {8·c, 8·c + 4, 32 + 4·c}`; `v_interp_p1ll_f16` (and `v_interp_p1lv_f16`, taking `P0.half` from `vsrc2`) widens the selected f16 half (`[15:0]` or `[31:16]` with `high`) to binary32 and writes the fused binary32 `fma(i, f32(P10.half), f32(P0.half))`, while `v_interp_p2_f16` rounds the exact `partial_f32 + j · f32(P20.half)` once to f16 following `MODE.FP_ROUND.16_64` (like `v_fma_mixlo_f16`, whereas the translator narrows the f32 sum) and writes `vdst[15:0]` while hardware keeps `vdst[31:16]`; f16 subnormal halves are preserved with `denorm_mode_16_64 = 3` (`0x0001 + 0.5·0x0200 + 0.5·0x0200 → 0x0201`, flushed to `±0` when `0`), and f16 NaN halves quiet with payload preserved (`0x7e05 → 0x7e05`, `0x7c01 → 0x7e01`). **ALU half measured on AMD hardware** (SHADER-430, `tools/interp_hw_probe.py`, gfx1036, every case matched; `docs/shader_validation.md`): `p1ll_f16` widens the chosen f16 halves exactly and computes fma(h10, I, h0) with one rounding to f32. `p2_f16` computes fma(h20, J, p1ll) and rounds it once, straight to f16: 30 hand-built ties gave that result and never f32-then-f16. It keeps vdst's high 16 bits. The translator used to zero them and now keeps them (`write_lo16`; `test_p2_f16_keeps_the_high_half_of_vdst`). **Still unverified:** what the SPI writes into LDS for a packed channel in a real draw (P10/P20 as f32 differences of the raw words, or per-half f16 differences under `FP16_INTERP_MODE`), which needs a pixel-shader harness; also f16 inf/NaN halves and `p1lv_f16`. **Unverified:** AMD hardware (whether it computes P10/P20 in f16 or rounds the p1ll intermediate differently), f16 denormal and NaN halves. **`--bary-fallback`** has no per-vertex inputs, so it keeps the old smooth-f32 read and cannot honour `high`; `check.py` skips the fixture there. MoltenVK can't compile `PerVertexKHR`: see the next row. | @@ -498,6 +507,7 @@ How the generated SPIR-V expects the runtime to work: | `v_cmp_*_f64`, `v_cmpx_*_f64` | All 16 binary64 vector compare predicates (`f`, `lt`, `eq`, `le`, `gt`, `lg`, `ge`, `o`, `u`, `nge`, `nlg`, `ngt`, `nle`, `neq`, `nlt`, `tru`) for both `v_cmp_` (VCC/SGPR lane mask) and `v_cmpx_` (EXEC narrowing), lowered in `Gen.compare_f64_cond` via pure 32-bit `%uint` IEEE-754 ordering (NaN detection, `-0.0` canonicalized to `+0.0`, sign-magnitude to monotonic unsigned 64-bit key) with no `Float64` capability required and no denormal flushing. Supports VGPR/SGPR pairs, `fimm`, sign-extended inline integers (`-16..64`), 32-bit upper-half literals, and VOP3 `abs`/`neg` sign-bit modifiers on both sources; inactive lanes write 0 for `v_cmp_*_f64` and stay inactive for `v_cmpx_*_f64`. Source: AMD RDNA2 ISA VOPC/VOP3 binary64 compares. CPU-checked by `tests/semantic/test_cmp_f64.py` (all 16 predicates across full IEEE-754 edge grid including subnormals/1-ULP pairs/±0/±inf/sNaN/qNaN, SGPR pairs, constants, `abs`/`neg`, `v_cmpx_*_f64`, inactive lanes, no `Float64` capability, bad-operand rejections). GPU-checked by `runtime/test/shaders/cs_w32_cmp_f64.asm`: all 16 predicates of both forms on 256 memory-fed pairs (the product of 16 values: ±inf, ±max, the 1-ULP neighbours of ±1, the smallest subnormals, ±0, the smallest normal, a NaN with its payload in the low dword only, a negative quiet NaN), `tru` with the odd threads off (an inactive lane gets VCC 0 and stays off through `v_cmpx_`), and `lt`/`nge` with `abs`/`neg`, all 1536 heap words exact on an RTX 4070 Ti (NVIDIA 620.70.06, Linux) and on llvmpipe (subgroup 8). That run checks the translated SPIR-V on a driver against IEEE-754, not RDNA2 itself; SGPR-pair and constant operands are not in it. Measured on native gfx1100 (single thread, 116 cases): all 16 predicates return IEEE-754 results (`eq` on `NaN` is 0 while `neq`/`nlt`/`nge`/`ngt` are 1, `lg` is 0 for `NaN` with `o`/`u` splitting on it, `eq(+0.0, -0.0)` is 1, `inf` compares equal to itself) and `v_cmpx_*_f64` narrows `EXEC` instead of writing `VCC`. | | Whole-quad mode (`s_wqm_b64` / `s_wqm_b32`) | A lane mask register holds only this lane's bit, so WQM on one (EXEC, VCC, an SGPR the mask analysis found) ORs the bit of the lane's quad, lanes 4n..4n+3 of the wave: two `OpGroupNonUniformQuadSwap` (horizontal, then vertical; capability `GroupNonUniformQuad`) in the default mode in fragment and compute shaders (quad operations are only guaranteed there; vertex, geometry and mesh shaders shuffle from the quad's four lanes), or the four lanes' values read through `%x_buf` under `--wave64-emulate` (no subgroup operation there). A quad never crosses lane 31/32, so the mask bits are exact per half on a 32-wide subgroup; SCC is a wave vote, so on wave64 it needs a 64-wide subgroup or `--wave64-emulate` (as every wave-wide mask op). The result goes to EXEC, VCC or an SGPR pair as a mask, SCC = the wave-wide any of it (same vote as the other mask ops). A 32-bit form in wave64 (`exec_lo`/`exec_hi`, `vcc_lo`/`vcc_hi`, a half-mask SGPR) writes only its own half (`exec_half_write`) and votes SCC over that half only (`cs_wqm_w64_half`). A source that is not a lane mask (a value loaded from memory, a literal) is data: `((x \| x>>1 \| x>>2 \| x>>3) & 0x11111111) * 15` per 32-bit word and SCC = result != 0, no subgroup operation. Assumptions: in compute and mesh shaders the subgroup lane is `LocalInvocationIndex` mod the subgroup size (as for every cross-lane op); a hardware quad is four consecutive lanes of a wave, and in a pixel shader Vulkan's quad (the 2x2 pixels, helper invocations included) is the same four lanes; GPU-checked on both AMD and NVIDIA with `ps_wqm.asm` (every 2x2 block of a 64x64 target, fully covered). **Helper lanes at a triangle edge, measured on RDNA2** (gfx1036, wave64, raw ISA through `tools/ps_oracle.py` on RADV; `tools/ps_helper_probe.py`, docs/shader_validation.md): a pixel wave's entry EXEC is exactly its covered pixels (helpers off); `s_wqm_b64 exec, exec` turns on exactly the quads with a covered pixel, which are packed from lane 0 (a quad with no covered pixel isn't in the wave); lane % 4 = (x & 1) + 2 (y & 1), so lanes 0-3 are top-left, top-right, bottom-left, bottom-right; a helper's `v_interp` gives its own pixel centre (extrapolated, as precisely as a covered pixel), and its v0/v1 hold its own I/J before `s_wqm` too; without `s_wqm` its VGPRs aren't written; an `exp ... vm` with helpers on in EXEC writes no pixel outside the triangle. Not covered: helper-invocation behaviour at triangle edges is untested, and in native mode an absent invocation in a partial quad (a compute group whose size is not a multiple of 4) gives an undefined value (emulated, the missing lanes of a partial wave read as 0). Before this the instruction was the identity, so helper lanes stayed off (#156 SHADER-34: `s_wqm_b64` appears in 4,285 pixel shaders). GPU-checked with `runtime/test/shaders/cs_wqm_w64.asm`, `cs_wqm_w64_half.asm`, `cs_wqm_w32.asm` and `ps_wqm.asm` on AMD Radeon 880M (subgroup 64) and NVIDIA GeForce RTX 5070 Laptop (subgroup 32; `cs_wqm_w64` there needs `LEONIDA_W64_EMULATE=1`), with and without `--wave64-emulate`. | | `buffer_atomic_{and,or,xor,swap}_x2` | `M = op(M, DATA)` on the 64-bit element at the MUBUF address (two dwords, low first); with `glc` the old 64 bits are returned in `vdata[0:1]`. A bitwise op or an exchange leaves the same memory done one dword at a time, so each dword is its own 32-bit `OpAtomic*` and no Int64 atomics are needed. **Approximation:** the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done. Each dword is its own 32-bit `OpAtomic*`, so no Int64 atomics are needed; a bitwise op leaves the same memory that way, since its bits are independent. **Approximation:** an exchange can tear, since two lanes swapping into one element at once can leave one's low dword with the other's high dword (A.lo, B.lo, B.hi, A.hi), and the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done. **Bounds:** the check covers the whole 8-byte element, all or nothing, as for a typed 32_32 element (`buffer_address(elem="fmt")`). An out-of-range or inactive lane leaves memory alone and returns 0, as `buffer_atomic` does. How hardware treats a 64-bit atomic that is only partly in range is **not measured**. Still `Unsupported`: `add/sub/min/max_x2` and `cmpswap_x2`. Until 2026-11-22 every `_x2` buffer atomic was rejected. CPU-checked by `tests/semantic/test_buffer_atomics_x2.py` (the four ops with and without `glc`, an element ending exactly at `num_records`, half and fully out of range, seeded values, rejected forms). **Not GPU-verified.** | +| Per-lane descriptor selection | The translator executes the first-active-lane read, EXEC selection, scalar descriptor load and remaining-lane retry as ordinary wave instructions. The hand-written `waterfall_table_offset.asm` fixture reads four different buffers and checks every lane on wave32, native wave64 and emulated wave64. The graphics partition analysis accepts an unmodified full-word integer equality as evidence that selected lanes hold the first lane's word. A float comparison accepts both signs of zero. The signed-zero execution fixture produces different raw outputs when a 64-lane group is split and therefore requires tier C. See Marvis's VIctory waterfall analysis (b1c8306, ffe310e) for the distinction between comparing descriptor words and comparing the offset of a descriptor load. | | Wave64 graphics: partition invariance (SHADER-10) | A wave64 VS/PS/GS on a 32-wide subgroup is exact **iff its observable results do not change when the wave is cut into two 32-lane halves** (the host forms the subgroups of graphics stages, so there is no partner half to exchange with). `tools/wave64_halves.py` decides it from the code (forward taint dataflow over the basic blocks, plus control dependence on wave-wide votes) and the translator records it in `index.json` as `wave64_graphics` (`A`/`B`/`C`), `wave64_graphics_reasons` (tier C) and `wave64_graphics_idioms` (tier B). **A**: only per-lane arithmetic, votes that skip lane-masked work (`s_cbranch_execz/execnz`; `vccz/vccnz` whose run side starts by narrowing EXEC to that VCC and whose other side is the join, with no code of its own: a half that votes no runs that side, the wave does not; the same holds for `s_cbranch_execz/execnz`: the side that runs when EXEC is zero is taken by a half with no active lane, so it must be the join (or only jumps to it) or the exit of a loop the vote closes, else tier C `unsafe-execz-branch`; `s_cbranch_scc*` after a vote is the same kind of skip, any other reader of that SCC, `s_cselect`/`s_cmov`/`s_addc`, is tier C; a vote is on the mask register's value when it was taken, so a new value in that register before the branch (`v_cmp` into the pair or VCC, `s_mov_b64`, `s_cselect_b64`: none of them writes SCC) ends it, and the branch is judged as a plain SCC branch, SHADER-820), whole-quad masks, `ds_bpermute`/`ds_permute`/`v_permlane16`/`v_permlanex16`/`ds_swizzle` (they stay inside a half), a `ds_bpermute`/`ds_permute` address made from the lane id (`v_mbcnt_lo` then `v_mbcnt_hi` of -1) when it is the same modulo 128 bytes in the wave and in a half (the id is 0..63 there and 0..31 here, equal modulo 32 lanes; sums, differences and bitwise ops with invariant values keep that, a left shift by c multiplies the modulus by 2^c, and the permute uses address bits 2..6 of its half only: `(id ^ 1) << 2` is exact, `id << 1`, a right shift of the id or the low count alone stay tier C `lane-id`), loops closed by `execnz` with no scalar state carried, and the early exit of a pixel kill: `s_cbranch_scc0/scc1` (or `vccz/vccnz`) on a lane mask's own "not empty" (the last SCC writer is a 64-bit logic op into that mask, e.g. `s_andn2_b64 live, live, exec`, or `s_cmp_lg_u64 mask, 0`, and nothing rewrites the mask before the branch) to a block that only sets EXEC from that mask or 0 (`s_mov_b64 exec`, or `s_and_b64 exec` with it), may then export with that EXEC (an export is allowed, not required), and ends (no other code, store or successor), while the run side narrows EXEC into the mask's whole quads before anything but mask arithmetic (`s_mov_b64`, `s_and_b64`, `s_wqm_b64`) runs, the narrowing itself possibly an `s_and_saveexec_b64` / `s_andn2_saveexec_b64` (or `_wrexec_`) whose source is inside, and keeps it inside on every path from there, loops included (a must-dataflow: an EXEC write keeps it inside only when it is provably a subset: `v_cmpx`, `s_and_b64` with one operand known inside, `s_andn2_b64` / `s_andn2_saveexec_b64` whose first operand is, `s_and_saveexec_b64` while inside or from one that is, `s_andn1`/`s_or`/`s_xor_saveexec_b64` only while inside (the latter two also from one that is), and copies, `s_wqm_b64`, `s_or_b64` and `s_xor_b64` of operands known to be inside (0 counts as inside); a saveexec destination holds the old EXEC and a wrexec one the new, each inside only if that EXEC was), and no `exp ... vm` can run before the vote. A half whose mask is empty then writes nothing and discards its pixels in the exit, and in the wave its lanes are off to the end, so the wave discards them too; an exit shared by several kills reads a mask redefined behind the earlier votes and stays tier C. GPU-checked by `ps_w64_a_discard` (below). `s_cbranch_scc*` after a vote is the same kind of skip, any other reader of that SCC, `s_cselect`/`s_cmov`/`s_addc`, is tier C; a vote is on the mask register's value when it was taken, so a new value in that register before the branch (`v_cmp` into the pair or VCC, `s_mov_b64`, `s_cselect_b64`: none of them writes SCC) ends it, and the branch is judged as a plain SCC branch, SHADER-820), whole-quad masks, `ds_bpermute`/`v_permlane16` (they stay inside a half, not GPU-tested here: no fixture; `s_cbranch_scc*` after a vote is the same kind of skip, any other reader of that SCC, `s_cselect`/`s_cmov`/`s_addc`, is tier C), whole-quad masks, `ds_bpermute`/`v_permlane16` (they stay inside a half, not GPU-tested here: no fixture; `ds_swizzle` and `v_permlanex16` likewise; GPU-checked at required 64 and 32 lanes by `ps_w64_a_bpermute`, `ps_w64_a_permlane` (`v_permlane16` and `v_permlanex16`) and `ps_w64_a_swizzle` in `w64_graphics.py`, TEST-433), loops closed by `execnz` with no scalar state carried. `ds_swizzle` and `v_permlanex16` likewise), loops closed by `execnz` with no scalar state carried. A `vccz`/`vccnz` on a wave-uniform compare is no lane vote and is tier A too: a `v_cmp` made while EXEC is the launch mask from untainted immediates, scalars that are no lane mask and VGPRs written from them (optionally ANDed with EXEC, the LLVM form `s_and_b64 vcc, exec, s[..]`) gives every launch lane or none, so each half votes as the wave does and both sides may have code and scalars of their own (if/else, a uniform loop back edge; the mask itself read as data, e.g. exported, is still tier C `cross-lane`), while the same compare under a narrowed EXEC (a half with no active lane votes no and keeps its own scalars) or on a tainted value (`v_readfirstlane` of a varying VGPR, a lane count, an AND with a lane mask) stays tier C; confirmed on the wave interpreter (`UniformVote` in `tests/semantic/test_wave64_halves.py`: 64 lanes against two waves of 32, equal for the accepted forms with s4 = 9 and s4 = 1, different for each near miss) and by `ps_w64_a_uniform_vote`, which gives its derived words on an NVIDIA GeForce RTX 5080 (Linux, driver 580.65.06, 32 only). **B**: also a waterfall loop (`v_readfirstlane` of a varying value, `v_cmp_eq` against the same VGPR, `saveexec`, body, `s_xor exec`, `execnz`; the scalar only used inside the body), a wave-aggregated atomic (`s_bcnt1` of EXEC, `v_mbcnt` rank of that same EXEC, one `buffer_atomic_add` of that count (the count of the mask the rank ranks) by the rank-0 lane only, at a wave-uniform address (a uniform VGPR, or one the elected lane wrote from scalars and constants since EXEC last changed; a per-lane address such as a pixel coordinate is tier C `elected-lane`, since each half elects its own lane and bumps another counter), `v_readfirstlane` of the result with EXEC restored, base + rank as a store address, the rank counting the very mask the atomic's count was taken of (a rank of the entry EXEC or of a saved copy next to a base of the narrowed one is tier C `lane-rank`); the rank alone or the base alone is not a slot: exact as a set of slots, **the order of the slots within a wave is not preserved**, a 64-lane wave takes one run of slots, two halves take two), `v_readfirstlane` / `v_readlane` of a VGPR written from scalars and constants while EXEC was the launch mask (the same in every lane), a `v_writelane` / `v_readlane` spill pair on one constant lane below 32. **C**: anything else that reaches an export, a store's data, a branch or EXEC: lane count / rank / first-lane index / raw lane id (`v_mbcnt` of -1), `v_readlane` of a varying value at any lane (on a wave64 every lane gets hardware lane N, in halves each half gets its own lane N, so lane 7 is as wrong as lane 40; the research note's row 9 is too generous here); an analysis failure is tier C with reason `analysis-error` (the translation does not fail), `v_writelane` to a non-constant or >= 32 lane, a 32-bit access to half of a lane mask (`exec_hi`, `vcc_hi`, a mask pair's odd register), a mask read as data (including a mask combined by `s_and/or/andn2_b64` with a register that is not one: a user value, a loaded mask), a scalar defined behind a wave-wide vote and read where it may not have run (`s_add s5, s5, 1` after `s_cbranch_vccz`; a trip count in an SGPR of a divergent loop: the halves vote differently), a branch on a count, an elected-lane side effect that is not a count, `ds_append`/`ds_consume`. The check is conservative: unknown means C. `--wave64-graphics=warn` (default) marks tier C and counts it in the summary line, `error` refuses it (`Unsupported`), `off` skips the analysis; `python tools/wave64_halves.py --census /index.json` prints tier, reason and idiom counts (no names); it complements `tools/wave64_graphics_scan.py` (#1132), which counts candidate cross-half opcodes in the disassembly before translation and decides nothing. **Corpus census** (1.0.2.1, all 26,503 shaders translated at `main` `f847748c` with `--wave64-emulate`, `--census` over that index): 13,405 wave64 graphics shaders (2,236 VS, 10,974 PS, 195 GS, the FSSM header's wave size, see *Wave size*); tier A 4,033 (30.1%), B 85 (0.6%), C 9,287 (69.3%): VS 1,455/79/702, PS 2,383/6/8,585, GS 195/0/0. Tier C reasons (a shader can have several): unsafe-vote-branch 8,285, tainted-branch 6,547, tainted-exec 5,189, cross-lane 4,764, stale-scalar 3,415, mask-half 759, unsafe-execz-branch 583, first-lane 353, waterfall-scalar 161, lane-id 152, lane-count 1. Idiom tags, counted on every shader that carries one whatever its tier (`--census` prints them as "tier B idioms"; 85 shaders are tier B): readfirstlane-uniform 626, lane-spill 287, waterfall 35. (Earlier censuses counted 11,405 shaders, from when the wave size came from code markers: TEST-319 had A 1,919, B 17, C 9,469 with all 195 GS in C; its re-run with the GS ring rule below and #1982 had A 2,117, B 17, C 9,271 with all 195 GS in A.) The lane-id bpermute rule moves no corpus shader. (The TEST-319 census, from when the wave size came from code markers and before the GS ring-address rule below, counted 11,405 shaders: A 1,919, B 17, C 9,469, with all 195 GS in C.) The lane-id bpermute rule moves no corpus shader. **Corpus census** (TEST-319, 1.0.2.1, `--census` over the translated index, re-run with the GS ring rule below and #1982): 11,405 wave64 graphics shaders (1,179 VS, 10,031 PS, 195 GS); tier A 2,117 (18.6%), B 17 (0.1%), C 9,271 (81.3%): VS 479/14/686, PS 1,443/3/8,585, GS 195/0/0. Tier C reasons (a shader can have several): unsafe-vote-branch 8,285, tainted-branch 6,550, tainted-exec 5,189, cross-lane 4,760, stale-scalar 3,415, mask-half 758, unsafe-execz-branch 583, first-lane 353, waterfall-scalar 161, lane-id 152, lane-count 1. 11,405 wave64 graphics shaders (1,179 VS, 10,031 PS, 195 GS); tier A 1,919 (16.8%), B 17 (0.1%), C 9,469 (83.0%): VS 465/14/700, PS 1,454/3/8,574, GS 0/0/195. Tier C reasons (a shader can have several): unsafe-vote-branch 8,175, tainted-branch 6,582, cross-lane 6,111, tainted-exec 4,959, stale-scalar 3,162, mask-half 758, unsafe-execz-branch 583, first-lane 353, lane-id 277, waterfall-scalar 167, lane-count 1. Tier B idioms: readfirstlane-uniform 558, lane-spill 287, waterfall 35. The lane-id bpermute rule moves no corpus shader. **Corpus coverage is not measured here**: it needs a run over the game's shaders by someone who has them. **Rewrite (the only one the emission needs)**: `v_readlane_b32` of a proven-uniform VGPR reads the lane's own copy instead of shuffling from lane N, because a subgroup shuffle from lane >= 32 of a 32-wide subgroup is undefined (143 of 144 test shaders translate byte-identically to origin/main, only `ps_w64_b_readlane_uniform` changed). Everything else tier B needs is what the translator already emits per subgroup: the ballot/count/rank/first-lane words of `wave_mask` are the subgroup's own (the high word is 0), `v_readfirstlane` is the subgroup's first active lane, a waterfall runs once per distinct value of the subgroup. GPU-checked on AMD Radeon 880M (driver 26.11.2; `requiredSubgroupSizeStages` has FRAGMENT, size 32..64) with `runtime/test/shaders/w64_graphics.py`: each `ps_w64_*` fixture drawn with the fragment subgroup size required to 64 (one hardware wave) and to 32 (two halves). `ps_w64_a_skip`, `_b_waterfall`, `_b_readfirstlane`, `_b_readlane_uniform` and `_b_ballot_atomic` (counter 1024 and the 1024 slot words as a set; slot order differs) match each other and the words their headers derive; `_c_bcnt_export`, `_c_lane_id`, `_c_readlane`, `_c_vote_stale`, `_c_vote_else`, `_c_scc_vote`, `_c_execz_sgpr` (an SGPR written on the exec-zero side and exported) and `_c_waterfall_count` differ between 64 and 32 (the detector is right). `ps_w64_a_one_lane` is the case where only one pixel votes yes (so one half votes and the other does not, in the wave and in the halves): its skip regions (`execz`, `vccz`, `vccnz` with a jump-only fall-through) give equal images at 64 and 32; `_c_vote_else` (code on the vote's no side) and `_c_scc_vote` (SCC of a vote as data) differ. `ps_w64_a_discard` (three kills, two of them dropping whole regions so that some halves lose every pixel while the other half of their wave lives) was drawn on an AMD Radeon RX 580 (RADV, Mesa 26.0.8, required size 64, saved with `W64G_SAVE_REF`) and an NVIDIA GeForce RTX 5070 (32 only, driver 620.73.04, compared with `W64G_REF`): both equal the derived words, discarded pixels keeping the clear value, and each other. NVIDIA GeForce RTX 5070 Laptop (32 only, driver 617.42): tier A/B fixtures equal the derived words and the 880M@64 images (`W64G_SAVE_REF` / `W64G_REF`), tier C fixtures differ from the 880M@64 images. `ps_w64_a_permlane`, `_a_swizzle` and `_a_bpermute` (TEST-319: permlane16 neighbour selects, permlanex16 there and back, swizzle quad-permute, swap and broadcast modes, bpermute from lane-id addresses; every read stays in the pixel's 2x2 quad or comes back, so the words do not depend on how pixels are packed into lanes) give the derived words on an NVIDIA GeForce RTX 5070 (Linux, driver 620.73.04, 32 only). With an AMD Radeon RX 580 (Polaris, RADV Mesa 26.0.8) as the 64-lane reference (`W64G_SAVE_REF`; GCN has one subgroup size, 64, in every stage but no FRAGMENT in `requiredSubgroupSizeStages`, so `vk_harness` counts a requested size equal to a device's only size as applied), the RTX 5070 run of every fixture (`W64G_REF`) equals the reference for all 13 tier A/B fixtures and differs from it for all 11 tier C ones, pixel and vertex; the same reads in a vertex shader run on the wave interpreter (64 lanes against two waves of 32, equal) because a GPU's partial vertex waves leave the lanes they would read empty. Vertex shaders: the VS stage cannot be forced on the 880M (no VERTEX in `requiredSubgroupSizeStages`), so VS is covered by the strict wave interpreter (`tests/semantic/test_wave64_halves.py`: 64 lanes against two waves of 32; tier A/B equal, tier C differs); geometry shaders are not tested (the corpus ones are wave64, see *Wave size*; no fixture). 64 lanes against two waves of 32; tier A/B equal, tier C differs), and on RADV also on the GPU (TEST-251): RADV runs the VS stage (NGG) as wave64 by default and as wave32 with `RADV_PERFTEST=gewave32` (GFX10+, seen in the `RADV_DEBUG=shaders` dump: 64-bit EXEC operations against `exec_lo`), so `w64_graphics.py` draws each `vs_w64_*` fixture both ways, 960 zero-area vertices (`VKH_VERTICES`) that store four words each to the heap, with `vs_w64_c_lane_id` as the probe that the wave size changed (largest lane id 63, then 31). RADV packs 62 or 64 vertices into a wave64 and 30 or 32 into a wave32, so the 32-lane run repacks the vertices rather than halving the waves; tier A/B words are keyed on the vertex index, which makes this the stricter test. `vs_w64_a_skip`, `_b_waterfall`, `_b_readlane_uniform` (readfirstlane and readlane 40/63 of uniform VGPRs) and `_b_ballot_atomic` (240 slots as a set) give the derived words at both sizes; `_c_bcnt_export`, `_c_readlane` and `_c_lane_id` differ (the detector is right), on an RX 9070 XT (GFX1201) and a Ryzen 9800X3D iGPU (GFX1036, RDNA2), RADV Mesa 26.3.1; geometry shaders are not tested (no fixture; the corpus has 195 wave64 geometry shaders, all tier C, see the census). `_c_bcnt_export`, `_c_readlane` and `_c_lane_id` differ (the detector is right), on an RX 9070 XT (GFX1201) and a Ryzen 9800X3D iGPU (GFX1036, RDNA2), RADV Mesa 26.3.1; geometry shaders likewise (TEST-251): RADV runs the GS stage (NGG) as wave64 by default and as wave32 with `gewave32`, and `w64_graphics.py` draws each `gs_w64_*` fixture after `vs_ids` (960 vertices, 320 triangles, `VKH_GS`), each invocation finding its triangle from `vs_ids`'s vertex number and storing four words to the heap, with `gs_w64_c_lane_id` as the probe (largest lane id 41, RADV puts at most 42 GS invocations in a wave64, then 31). **LDS writes of a legacy GS:** `rdna2spirv.gs_ds` maps one to an output slot from its offset alone and drops the VGPR address (the lane's GSVS area), so `wave64_halves.py` checks only the data a GS `ds_write` writes, not its address; before, a lane id that only formed the GSVS base made the shader tier C `lane-id`. Confirmed three ways: a hand-written GS with the base `lane id * 96` translates, after `spirv-opt -O`, to the same instructions as without it; `gs_w64_a_ring` (that shape) gives the derived records at wave64 and wave32 on both GPUs; and `tests/semantic/test_wave64_halves.py` (`GeometryRing`) keeps the lane id in the written data, or in a memory store's address, tier C. The corpus GS were that false tier C: all 195 contain `v_mbcnt_hi`, all 195 were tier C in the TEST-319 census, and `wave64_halves.py --census` on the corpus translated at `f847748c` puts all 195 in tier A. `_c_bcnt_export`, `_c_readlane` and `_c_lane_id` differ (the detector is right), on an RX 9070 XT (GFX1201) and a Ryzen 9800X3D iGPU (GFX1036, RDNA2), RADV Mesa 26.3.1; geometry shaders are not tested (the corpus ones are wave64, see *Wave size*; no fixture). The corpus GS form their GSVS base from `v_mbcnt_lo/hi` (all 195 contain `v_mbcnt_hi`): they were all a false tier C, and the census above has all 195 at tier A. `wave64_halves.py --census` on a translated corpus shows it. `_c_bcnt_export`, `_c_readlane` and `_c_lane_id` differ (the detector is right), on an RX 9070 XT (GFX1201) and a Ryzen 9800X3D iGPU (GFX1036, RDNA2), RADV Mesa 26.3.1; geometry shaders are not tested (the corpus ones are wave32; no fixture). Not checked: helper lanes of partial quads; `VK_KHR_shader_maximal_reconvergence` is assumed for waterfall and election loops. Tiers A and B assume subgroups of at least 32 lanes: a fragment stage may run fewer live lanes than the subgroup size it reports (Intel UHD 770: gl_SubgroupSize 32, ballot count 16, a shuffle from lane L^16 returns garbage; measured by kapitche, TEST-433), so `w64_graphics.py` skips the tier A/B pixel fixtures on a device whose minimum subgroup size is below 32 when neither the 64 nor the 32 run took effect; deriving the skip from a measured live fragment width (ballot count) in `vk_harness` is a follow-up. **ADD_TID_ENABLE** (SHADER-833, finding by @shdann in #4571): an access with no `idxen` through a V# whose word3 is a literal (`s_mov_b32` earlier in the block, the notion `rdna2spirv` uses for `sgpr_imm`) with bit 23 set takes the wave lane as its index (`idxen` ignores the bit, see *Swizzled buffer addressing*), so its `buffer_load*`/`tbuffer_load*` result and its `buffer_store*`/`tbuffer_store*`/`buffer_atomic*` address carry the raw lane id: tier C `lane-id`. A literal with the bit clear, and every access with `idxen`, are unchanged. **Assumption**: through a run-time V# (loaded from memory or user data) tiers A and B take ADD_TID_ENABLE as 0 for an access without `idxen`; the code cannot say otherwise. The literal is tracked with the same folds `rdna2spirv` applies to `sgpr_imm` (mirrored in `Analysis.literal_sgpr`: `s_mov_b32/b64`, `s_movk_i32`, `s_pack_*`, `s_bfm_b32`, `s_not_b32`, `s_and/lshl/lshr_b32`, `s_mul_i32`; other folded ops count as run-time). The corpus census was not re-measured with this rule: its tier counts above are from before it and may change. Follow-up, needs the game: count the bound V#s with word3 bit 23 set at run time, and re-run `--census`. | | Wave64 graphics: a uniform vote under whole-quad EXEC (SHADER-W64-WQM-UVOTE) | SHADER-10 (the row above) takes a `vccz`/`vccnz` on a wave-uniform compare for no lane vote only while EXEC is the launch mask. A pixel shader that needs derivatives starts with `s_wqm_b64 exec, exec`, and LLVM branches on uniform conditions inside that region in the same form: `v_cmp_* sN, ` / `s_and_b64 vcc, exec, s[N:N+1]` / `s_cbranch_vccnz` (or the compare straight into VCC). **That is exact too, for a compare of immediates and scalars**: it is the same in every lane, so its mask is every lane of EXEC or none; EXEC is the whole quads of the launch mask, a quad is four consecutive lanes and never straddles the two 32-lane halves, and a half that runs has a launch lane, so EXEC has a lane in every half that runs and each half votes as the wave does. Both sides of the branch may then have code and scalars of their own (if/else, a uniform loop back edge), as under the launch mask. `tools/wave64_halves.py` carries it as a dataflow fact (`q`: EXEC is the whole quads of the launch mask), set by `s_wqm_b64 exec, exec` while EXEC is the launch mask and dropped by every other write to EXEC; `uniform_cmp` and the `s_and_b64 .., exec, ..` of a uniform mask accept it next to the launch mask. **What stays tier C, and why**: a VGPR source, even one SHADER-10 calls uniform (it was written under the launch mask, and the helper lanes EXEC now includes never got it, so they compare what they held; a VGPR written inside the region is refused as well, because the analysis does not tell the two apart); the whole quads of a narrowed EXEC, and any narrowing after the `s_wqm_b64` (a half can be empty); whole quads saved and put back later, or made in a register and copied to EXEC (only the write by `s_wqm_b64 exec, exec` is modelled); and a compare on a path where a scalar was read out of a uniform VGPR from a lane the launch mask may not have written, by `v_readlane_b32` at any time or by `v_readfirstlane_b32` while EXEC was not the launch mask (`qr`, kept for the rest of the path: SHADER-10 treats such a scalar as uniform, this rule does not build on that). **Corpus** (1.0.2.1, all 26,503, `wave64_halves.analyse` on every wave64 VS/PS/GS, with SHADER-W64-SDST-PAIR on `main` `3ed8e50b7` as the baseline, because the listings name the compare's destination by one register and without that rule the vote is hidden behind `tainted-branch`): **452 pixel shaders go from tier C to A**, no shader moves the other way and no vertex or geometry shader moves: A 5,267 to 5,719, B 397, C 7,741 to 7,289 (PS 3,545/34/7,395 to 3,997/34/6,943). Reasons: `unsafe-vote-branch` 7,362 to 6,861, `tainted-exec` 5,829 to 5,793, `stale-scalar` 3,287 to 3,254, the others unchanged; 802 shaders still have `unsafe-vote-branch` as their only reason. CPU-checked by `tests/semantic/test_wave64_halves_wqm_uvote.py`: the accepted forms in both printed forms of the destination, ten near misses that stay tier C, and a vertex and a pixel shader run on the wave interpreter as one wave of 64 lanes and as two of 32, equal and equal to the derived words with s4 = 9 and s4 = 1 (every lane covered there: the interpreters do not model a helper lane in a quad swap, so partial coverage rests on the argument above). GPU-checked by `ps_w64_a_wqm_uniform_vote` (`w64_graphics.py`: an if/else on a compare into VCC, the LLVM form through an SGPR pair and a loop closed by the vote, all under `s_wqm_b64 exec, exec`, EXEC put back before the export), which gives the words its header derives on an NVIDIA GeForce RTX 4070 Ti (Linux, driver 620.70.06, 32 only). That device has one subgroup size, so the 64-lane image was not drawn there and the full-screen draw has no partly covered quad; the run confirms the translated SPIR-V against the ISA reference, not native RDNA2 behaviour. | | GFX10.1 (console gfx1013) / GFX10.3 (gfx1030, gfx1036 oracle) opcode differences | Found by disassembling every opcode of every GFX10 encoding (SOP1/SOP2/SOPK/SOPC/SOPP, SMEM, VOP1/VOP2/VOPC/VOP3/VOP3P, DS, FLAT/GLOBAL/SCRATCH, MUBUF/MTBUF, MIMG) with LLVM 21 `llvm-mc` for `-mcpu=gfx1013` and for `gfx1030`/`gfx1036` (the two gfx103x lists are identical). Every other opcode slot decodes to the same mnemonic on both, so the hardware-oracle rows measured on gfx1036 are about the same instructions the console runs (the microarchitectures still differ, which no opcode table shows). **On gfx1013 only:** `v_mac_f32`/`v_mad_f32` (VOP2 0x1f, VOP3 0x11f/0x141) and `v_mac_legacy_f32`/`v_mad_legacy_f32` (VOP2 0x06, VOP3 0x106/0x140), translated (rows above; not measurable on gfx103x, where 0x06/0x106/0x140 are the fused `v_fmac_legacy_f32`/`v_fma_legacy_f32`); `v_mul_lo_i32` (VOP3 0x16b; `Unsupported` until #3504 translates it); `s_get_waveid_in_workgroup` (SMEM 0x2a), translated in compute and mesh shaders; scalar stores (`s_store_dword*`, `s_buffer_store_dword*`), scalar atomics (`s_atomic_*`, `s_buffer_atomic_*`, 32- and 64-bit), scalar scratch (`s_scratch_load/store_dword*`), `s_dcache_wb`, `s_dcache_discard(_x2)` and the 31 LDS `ds_*_src2_*` forms, all `Unsupported`. **On gfx103x only:** `v_dot2c_f32_f16`, `v_dot4c_i32_i8`, the VOP3P `v_dot2_f32_f16`, `v_dot2_i32_i16`/`u32_u16`, `v_dot4_i32_i8`/`u32_u8`, `v_dot8_i32_i4`/`u32_u4`, `v_fmac_legacy_f32`/`v_fma_legacy_f32`, `global_load/store_dword_addtid`, `global_atomic_csub`, `buffer_atomic_csub`. The console's code can't contain these; the translator handles the integer dot products (rows above, measured on gfx1036) and refuses the rest, so a listing disassembled for the wrong target (VOP2 0x06 printed as `v_fmac_legacy_f32`) fails loudly instead of being translated as a fused multiply-add. Not covered by the sweep: opcodes whose operand template did not decode on either target, and behaviour that differs without an opcode change. | @@ -515,7 +525,7 @@ How the generated SPIR-V expects the runtime to work: | Formerly untranslated | Mesh (9,282), geometry (195) and compute (2,689) now translate; `s_swappc_b64` is replaced by Vulkan vertex inputs (see *Vertex fetch*) and the `tbuffer_load_format_*` forms use the instruction's format. Packed `tbuffer_load_format_d16_{x,xy,xyz,xyzw}` load two 16-bit components per VGPR, with the same final partial write as MUBUF. Native gfx1036 wave32/64 confirmed all four widths for RGBA8_UINT and RGBA8_UNORM with a conflicting 32_UINT V# format. Both packed and ordinary MTBUF loads ignore the V# channel selectors and use identity for the instruction format, zero-filling missing channels. Native gfx1036 measurements compared multiple V# permutations with MUBUF as a control. An INVALID V# format (0) suppresses the MTBUF fetch even at a valid address inside its bounds. Native gfx1036 wave32/64 returned zero components at all four widths and preserved the untouched half of an odd D16 destination, as specified for unbound resources in the [RDNA2 ISA, §8.1.4](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf). A translated vertex fetch on RTX 5080 and Radeon Graphics also followed a change to the instruction format between two draws with identical vertex records and V#. Fixed UNORM and SNORM loads share the exact integer quotient for each magnitude width across instructions and channels (checked against rationally rounded binary32 values on RTX 5080 and Radeon Graphics). The gfx1013 disassembler omits `format:` for the [GFX10 MTBUF default](https://llvm.org/docs/AMDGPUModifierSyntax.html#ufmt), `BUF_FMT_8_UNORM` (code 1). A few rare ops are still reported by name rather than guessed. | | `v_cubema_f32` signed zero | Whenever the selected major axis is ±0.0, `v_cubema_f32` returns `+0.0` (`0x00000000`), never `-0.0` (`0x80000000`), while preserving NaNs and signed non-zero major-axis values (`2.0 * m`). Emitted as `OpFOrdEqual %bool m %f0` selecting `%f0` over `OpFMul m 2.0`, so `-0.0` maps to `+0.0`, NaN compares false and propagates, and non-zero finite/infinite values double with sign preserved. Until 2026-11-22 both `tools/rdna2spirv.py` and `tools/f32_fuzz.py` multiplied `m` by `2.0` directly and returned `-0.0` when `z = -0.0` on `(±0.0, ±0.0, -0.0)` (or when `-0.0` was selected alongside NaN axes). **Measured natively on RDNA2** (`gfx1036`, AMD Radeon(TM) Graphics, Windows driver `32.0.21042.62`, wave32 & wave64, all four MODE combinations `flush`/`keep`/`no_dx10`/`ieee` via `tools/hw_oracle/`): all 8 `(±0.0, ±0.0, ±0.0)` triples, `-v` source negation of `+0.0`, `mul:2`, negative denormals, and `(-0.0, qNaN, qNaN)` returned `0x00000000`, while `(-qNaN, 1.0, 1.0)` returned `0xffc00000` and `(-1.0, qNaN, qNaN)` returned `0xc0000000`. Checked by `tests/semantic/test_valu_cube.py` (`test_signed_zero_triples_and_nan_cubema`), `tests/test_f32_fuzz.py` (`test_cube_major_axis`), and `tools/f32_fuzz.py --oracle hw --ops v_cubema_f32,v_cubeid_f32,v_cubesc_f32,v_cubetc_f32`. | | `v_dot2c_i32_i16`, `v_dot8c_i32_i4` | VOP2/VOP3 accumulating forms of `v_dot2_i32_i16` and `v_dot8_i32_i4` (`D = sum(S0.elem[k] * S1.elem[k]) + D`, signed 2×16-bit and 8×4-bit). Wraps at 32 bits by default and saturates to `[INT32_MIN, INT32_MAX]` with VOP3 `clamp` (sharing the `v_dot2_i32_i16`/`v_dot8_i32_i4` signed-carry path); `op_sel`, `neg`/`abs`, and DPP/SDWA are refused. Registered in read-before-write VGPR tracking alongside `v_dot4c_i32_i8`. Source: LLVM AMDGPU `VOP2Instructions.td` (`HasDot4Insts` / `HasDot3Insts`, `gfx908` VOP2/VOP3 syntax; not in the default `gfx1013`/`gfx103x` feature set). **Not measured on AMD hardware** (translated Vulkan lowering checked on RTX 5070 by @duudiis: 40,960/40,960 exact words across wave32 and emulated wave64). Checked bit-for-bit on the CPU (`spirv_mini_interp`) and with `spirv-val` by `tests/semantic/test_alu_dotc.py`; not run on the shader corpus. | -| Out-of-bounds typed buffer loads and `DST_SEL=1` | When a MUBUF `buffer_load_format_{x,xy,xyz,xyzw}` or `buffer_load_format_d16_{x,xy,xyz,xyzw}` is out of bounds (`OOB_SELECT` 0–3, `num_records == 0`, partial-element spill, or swizzled OOB), memory is not accessed and raw data channels (`DST_SEL` 4..7) read 0, while the V# `DST_SEL` swizzle still runs: `DST_SEL=0` returns 0 and `DST_SEL=1` returns `1.0f` (`0x3F800000`, `d16` `0x3C00`) iff V# `FORMAT[6:0]` is a valid float, normalized or scaled buffer format (`1..77` ending in `_UNORM`, `_SNORM`, `_USCALED`, `_SSCALED`, or `_FLOAT`), and integer `1` (`0x00000001`, `d16` `0x0001`) for `UINT`/`SINT`, `INVALID` (`0`), and reserved codes (`78..127`). `d16_x` and `d16_xyz` preserve the unaddressed upper 16 bits of the final destination VGPR, and MTBUF `tbuffer_load_format_*` ignores V# `DST_SEL` on both out-of-bounds and `FORMAT=0` loads (returning 0 in addressed channels). Until 2026-11-22 `Gen.buffer_load_format` clamped the post-swizzle result to 0 when `in_b` was false (`SHADER-429`), dropping `DST_SEL=1` on out-of-bounds loads and returning `1.0f` instead of `1` for `DST_SEL=1` with `FORMAT=0`. **Hardware-verified on RDNA2** (`gfx1036`, Windows 11, driver `32.0.21042.62`, wave32 and wave64, 746 kernels via `tools/hw_oracle`: all 41 `Gen.FORMATS` across `xyzw`/`d16_xyzw`/`d16_xyz`/`d16_x`, all 128 7-bit `FORMAT` codes `0..127` for both `f32` and `d16`, `OOB_SELECT` 0–3, partial spill, swizzled OOB, MTBUF controls, and inactive EXEC lanes), Vulkan GPU-checked across all 128 7-bit `FORMAT` codes (`xyzw`, `d16_xyzw`, `d16_xyz`, `d16_x`) and the `cs_fmt_*`/`cs_oob_*`/`cs_bounds`/`cs_buf_*` fixtures on NVIDIA GeForce RTX 5090 (driver `32.0.16.1088`) and AMD Radeon Graphics (`gfx1036`, driver `32.0.21042.62`), and CPU/`spirv-val`-checked by `tests/semantic/test_buffer_oob_dst_sel.py`. | +| Out-of-bounds typed buffer loads and `DST_SEL=1` | When a MUBUF `buffer_load_format_{x,xy,xyz,xyzw}` or `buffer_load_format_d16_{x,xy,xyz,xyzw}` is out of bounds (`OOB_SELECT` 0–3, `num_records == 0`, partial-element spill, or swizzled OOB), memory is not accessed and raw data channels (`DST_SEL` 4..7) read 0, while the V# `DST_SEL` swizzle still runs: `DST_SEL=0` returns 0 and `DST_SEL=1` returns `1.0f` (`0x3F800000`, `d16` `0x3C00`) iff V# `FORMAT[6:0]` is a valid float, normalized or scaled buffer format (`1..77` ending in `_UNORM`, `_SNORM`, `_USCALED`, `_SSCALED`, or `_FLOAT`), and integer `1` (`0x00000001`, `d16` `0x0001`) for `UINT`/`SINT`, `INVALID` (`0`), and reserved codes (`78..127`). `d16_x` and `d16_xyz` preserve the unaddressed upper 16 bits of the final destination VGPR, and MTBUF `tbuffer_load_format_*` ignores V# `DST_SEL` on both out-of-bounds and `FORMAT=0` loads (returning 0 in addressed channels). Until 2026-11-22 `Gen.buffer_load_format` clamped the post-swizzle result to 0 when `in_b` was false (`SHADER-429`), dropping `DST_SEL=1` on out-of-bounds loads and returning `1.0f` instead of `1` for `DST_SEL=1` with `FORMAT=0`. For a dynamic MUBUF FORMAT with no decoded data channels (INVALID or reserved), the shader skips the physical load even when the descriptor has a nonempty, in-range span. DST_SEL constants still apply. The interpreter read-log fixture and RTX 4070 readback cover FORMAT 0, 78, 127 and valid control 20. **Hardware-verified on RDNA2** (`gfx1036`, Windows 11, driver `32.0.21042.62`, wave32 and wave64, 746 kernels via `tools/hw_oracle`: all 41 `Gen.FORMATS` across `xyzw`/`d16_xyzw`/`d16_xyz`/`d16_x`, all 128 7-bit `FORMAT` codes `0..127` for both `f32` and `d16`, `OOB_SELECT` 0–3, partial spill, swizzled OOB, MTBUF controls, and inactive EXEC lanes), Vulkan GPU-checked across all 128 7-bit `FORMAT` codes (`xyzw`, `d16_xyzw`, `d16_xyz`, `d16_x`) and the `cs_fmt_*`/`cs_oob_*`/`cs_bounds`/`cs_buf_*` fixtures on NVIDIA GeForce RTX 5090 (driver `32.0.16.1088`) and AMD Radeon Graphics (`gfx1036`, driver `32.0.21042.62`), and CPU/`spirv-val`-checked by `tests/semantic/test_buffer_oob_dst_sel.py`. | | `v_div_fixup_f32` | Measured natively on an AMD Radeon(TM) Graphics RDNA2 GPU (`gfx1036`, not the console's `gfx1013`; Windows driver 32.0.21042.62, `tools/hw_oracle`, wave32 and wave64 identical on every case: 256 seeded triples across 4 MODEs plus 73 targeted special-case/modifier rows, 0 mismatches). Computes `div_fixup_f32(S0=quotient, S1=denom, S2=numer)` with pure integer SPIR-V ops under the game's inferred MODE (`IEEE=0`, `denorm32=0`, `DX10_CLAMP=1`): VOP3 `abs` (clear bit 31) then `neg` (flip bit 31) apply bitwise to `S0`/`S1`/`S2` before classification (including NaN payloads); `S1`/`S2` subnormals flush to signed zero (`exp == 0`) while `S0` subnormals are preserved; priority order is (1) `NaN(S2) → S2`, (2) `NaN(S1) → S1` (signalling NaNs pass unchanged under `IEEE=0`, quieted only when `IEEE=1`), (3) `0/0` or `±inf/±inf → 0xFFC00000` (`-qNaN`), (4) `zero(S2) ∨ inf(S1) → ±0.0`, (5) `zero(S1) ∨ inf(S2) → ±inf`, (6) `exp(S2) − exp(S1) ≤ −151 → ±0.0` (pure biased-exponent check, beats `NaN(S0)` and `inf(S0)`; no overflow check), (7) `NaN(S0) → ±inf`, (8) `copysign(S0, sign(S1) ⊕ sign(S2))`. Output modifiers `mul:2`/`mul:4`/`div:2` apply before `clamp`, and `clamp` maps NaN to `+0.0` (`DX10_CLAMP=1`) before `FClamp` to `[0, 1]`. Not modelled: `IEEE=1` sNaN quieting, `denorm32=3` keeping `S1`/`S2` subnormals, and the hardware `omod` `-0 → +0` quirk (same as the other f32 ops). Checked bit-for-bit against 73 measured `gfx1036` words in `tests/semantic/test_alu_div_fixup_f32.py`. | | Atomic natural alignment, 64-bit bounds, and `buffer_atomic_{fmin,fmax}` | Measured natively on RDNA2 (AMD Radeon(TM) Graphics, `gfx1036`, Windows driver `32.0.21042.62`, wave32 and wave64 via `tools/hw_oracle/`): **natural alignment** is enforced on every 32-bit and 64-bit buffer/global atomic (`buffer_atomic*`, `buffer_atomic*_x2`, `global_atomic*`, `global_atomic*_x2`), even under `OOB_SELECT = 2` (DISABLED). A 32-bit atomic requires `(addr & 3) == 0` (`offset = 1, 2` and `base + 2, offset = 0` are dropped; `base + 2, offset = 2` succeeds) and a 64-bit `_x2` atomic requires `(addr & 7) == 0` (`offset = 2, 4` and `base + 4, offset = 0` are dropped; `base + 4, offset = 4` succeeds). When dropped (OOB or unaligned), memory is untouched, an active `glc` lane receives `0` (32-bit) or `(0, 0)` (64-bit) in `vdst`/`vdata`, and an inactive lane (`EXEC = 0`) preserves `vdst`/`vdata`. Independently confirmed on a second `gfx1036` (driver `24.10.24`): without the alignment guard, an unaligned SPIR-V `OpAtomicAdd` corrupts the aligned dword (`100 -> 0xDEADBEF3`), whereas with the guard memory stays untouched and `0` is returned. `Gen.atomic_aligned` guards all six atomic emitters on `addr & 3 == 0` / `addr & 7 == 0`, merges `0` via `OpPhi` on skipped paths, and writes through `Gen.dst` so inactive lanes keep their prior register value while active unaligned/OOB lanes receive `0`. **64-bit partial bounds (`buffer_atomic*_x2`)**: the same `gfx1036` wave32/wave64 measurements confirm the all-or-nothing 8-byte bounds rule (`fixed_fmt = 62`) across all four `OOB_SELECT` modes (answering the unmeasured note in the `buffer_atomic_{and,or,xor,swap}_x2` row): mode 3 (RAW) requires `offs + 8 <= num_records` (`0/8` and `8/16` succeed; `0/7`, `0/5`, `0/4`, `8/15`, `8/12` drop cleanly); mode 0 (STRUCTURED_WITH_OFFSET) requires `idx < num_records` and `off + 8 <= stride` (`stride = 8, off = 0`, `stride = 16, off = 8`, `stride = 12, off = 0` succeed; `stride = 7, off = 0` and `stride = 12, off = 8` drop); mode 1 (STRUCTURED) checks `idx < num_records`; mode 2 (DISABLED) checks `num_records != 0`. **`buffer_atomic_{fmin,fmax}`**: lowered via `Gen.buffer_atomic_float` sharing `Gen._emit_atomic_fminmax_cas` (relaxed Device-scope `OpAtomicLoad` seed + `OpAtomicCompareExchange` + `GLSL.std.450` `NMin`/`NMax` CAS loop, no float-atomic extension required), enforcing V# bounds, 4-byte alignment, and `glc` return (`lds` and non-1-VGPR `vdata` raise `Unsupported`). On `gfx1036`, normal floats, `±inf`, `-0` vs `+0` (`fmin(-0, +0) = -0`, `fmax(-0, +0) = +0`), and `qNaN` (returns the non-NaN operand) match `NMin`/`NMax`; **known approximation**: the `gfx1036` L2 atomic unit quiets `sNaN` (`0x7f800001 -> 0x7fc00001`) regardless of `MODE`, while f32 subnormal handling follows the wave's `MODE.denorm32` and preserves sign (independently verified on a second `gfx1036`, wave32/wave64: under `denorm32 = 0`, subnormals flush to signed zero — `fmax(0x80000001, 0x80000002) -> 0x80000000 (-0)`, `fmax(0x00000001, 0x00000002) -> +0` — whereas under `denorm32 = 3`, subnormals are preserved and `NMin`/`NMax` is exact); `NMin`/`NMax` does not model `sNaN` quieting or `denorm32 = 0` subnormal flushing. CPU-checked by `tests/semantic/test_buffer_atomic_fminmax_and_align.py` (value grid, multi-lane CAS contention, OOB/partial-bounds matrix, inactive vs active-unaligned distinction across all six atomic families, and SPIR-V structural checks). | @@ -618,10 +628,22 @@ occurs, and those 860 are the blobs whose 0x120/0x12C/0x130 directory words are ids 0/1 and the API ids 4/5 are not in the corpus; the rest of a record is not decoded. `tools/pal_stages.py` prints the records of an FSSM or a container (every tag-0x0D payload); `tests/test_pal_stages.py` covers the layout with synthetic blobs. -`scripts/vs_layout_census.py` checks these hardware ids against the code of every payload: every stage-7 -payload carries the NGG markers (`exp prim`, `s_sendmsg MSG_GS_ALLOC_REQ`, `v_mbcnt`), every stage-4 payload -is a legacy non-NGG VS, and the stage-2 ES payloads have no `exp` (they write the vertex outputs to LDS for -the geometry stage) — see *VS input layout, per PAL hardware stage* and *VS as ES* above. + +## PAL stage descriptors + +The FSSM header starts a table of 0x88-byte hardware-stage records at offset 0x100. A record's first qword is +`0x000000C0_0002_AAHH`: `HH` (byte 0) is the PAL hardware stage and `AA` (byte 1) the API stage. Record k +starts at `0x100 + 0x88*k`; the table ends at the first zero or non-tag qword. On the 26,503-blob corpus +26,308 blobs carry one record and 195 (all GS) carry two, the second at 0x188 being the same shader's VS +copy. API ids: 0 VS (2,236), 1 PS (12,101), 2 GS (195), 3 CS (2,689), 6 MS (9,282), each equal to the carve +index's stage. Hardware ids: 2 ES (the first tag-0x0D payload of the 195 two-payload VS containers), 3 GS +(195), 4 VS (2,431, the 195 GS copies included), 5 PS (12,101), 6 CS (2,689) and 7 (9,282, every mesh +shader: the NGG/primitive path). Unused record fields are zero in 25,643 records; 1,055 records (860 blobs, +the 195 GS pairs included) carry paired `0xDEADBEEFDEADBEEF` qwords, a lone 32-bit `0xDEADBEEF` never +occurs, and those 860 are the blobs whose 0x120/0x12C/0x130 directory words are `0xDEADBEEF`. The hardware +ids 0/1 and the API ids 4/5 are not in the corpus; the rest of a record is not decoded. +`tools/pal_stages.py` prints the records of an FSSM or a container (every tag-0x0D payload); +`tests/test_pal_stages.py` covers the layout with synthetic blobs. ## Pixel-shader inputs diff --git a/docs/directstorage.md b/docs/directstorage.md index dc2987a559..919d52282a 100644 --- a/docs/directstorage.md +++ b/docs/directstorage.md @@ -59,7 +59,8 @@ The first boot with the executable settles most of this: the dry-run report show - **Factory**: one object for the process, never freed (its reference count does not drop below one). `SetDebugFlags` and `SetCpuAffinity` are stored only (a console core mask means nothing on the host). `SetStagingBufferSize` accepts 0, 16, 20, 24, 28 and 32 MiB, fails with `E_DSTORAGE_INVALID_STAGING_BUFFER_SIZE` - otherwise and with `E_DSTORAGE_STAGING_BUFFER_LOCKED` while a queue or file exists; there is no staging buffer. + otherwise and with `E_DSTORAGE_STAGING_BUFFER_LOCKED` while a queue or file exists. This records the + console setting. Host transform scratch is allocated on demand. `GetStats` reports the counts the shim keeps (queues per priority, requests, bytes, files, errors, zlib inflates: `TotalDecompressionRequestCount` grows when a zlib request's inflate starts, which is after its checks passed and its source was read, `PendingDecompressionRequestCount` is the inflates running, and @@ -92,16 +93,12 @@ The first boot with the executable settles most of this: the dry-run report show (`E_DSTORAGE_INVALID_FILE_HANDLE`); 3. reserved option bits (`E_DSTORAGE_RESERVED_FIELDS`), then the source type against the queue's (`E_DSTORAGE_INVALID_SOURCE_TYPE`); - 4. BCPack mode above 7, swizzle mode above 4 (`_INVALID_BCPACK_MODE`, `_INVALID_SWIZZLE_MODE`), then BCPack or - swizzle, with or without zlib, then physical pages (`E_NOTIMPL`, logged once: later PRs); - 5. an `IntermediateSize` (`_INVALID_INTERMEDIATE_SIZE`: it is the size between the inflate and the BCPack decode, - so only a zlib + BCPack request has one), a `DestinationSize` other than `SourceSize` without zlib, or not - larger than `SourceSize` with it (`_INVALID_DESTINATION_SIZE`: the rule `dstorageerr.h` gives for that code, - and what `DSTORAGE_REQUEST` says of `DestinationSize`), more than 1 GiB in total, then a buffer over 32 MiB - (`_REQUEST_TOO_LARGE` for both: `DSTORAGE_REQUEST` allows a buffer over 32 MiB only with 64 KiB or 2 MiB pages, - which are not implemented yet; the source is never larger than the destination here, so the destination's - limit covers it), then a zlib file request whose `FileOffset` is not 16-byte aligned (`_INVALID_FILE_OFFSET`, - as `DSTORAGE_REQUEST` requires); + 4. a BCPack mode above 7 or swizzle mode above 4. BC2 is reserved here for a future decoder (`E_NOTIMPL`); + 5. a nonzero `IntermediateSize` is required only for combined zlib and BCPack. Compressed + requests require a larger output than source, complete BC blocks and complete swizzle groups. + Raw requests require equal source and destination sizes. File offsets used for decompression + must be 16-byte aligned. The total memory bound is 1 GiB, with ordinary buffers limited to + 32 MiB apiece. Page lists can exceed the 32 MiB bound; 6. a null destination, a null source (memory) or a null file (`E_INVALIDARG`), a closed file (`_FILE_NOT_OPEN`); 7. a zero size: a success that touches no memory (an assumption: the reference does not say); 8. a range past the end of the file (`E_DSTORAGE_END_OF_FILE`), then a destination or source the process cannot @@ -114,8 +111,7 @@ The first boot with the executable settles most of this: the dry-run report show buffer and inflated there by the runtime's RFC 1950 inflater (`leonida::zlib_inflate` in `runtime/src/shader_library.h`, the one the shader library uses for XBCH blobs). The result is copied to `Destination` only when it is exactly `DestinationSize` bytes, so a stream that fails leaves the destination as it - was, and a memory source inside its own destination (in-place loading) inflates correctly. Both buffers are at - most 32 MiB (step 5). Step 5 also means a stream of stored blocks only, which is larger than what it holds, is + was, and a memory source inside its own destination (in-place loading) inflates correctly. For ordinary destinations, step 5 also means a stream of stored blocks only, which is larger than what it holds, is refused with `_INVALID_DESTINATION_SIZE` before it is read, as the documented rule implies. The stream is a zlib stream: the two header bytes, the deflate blocks (stored, fixed and dynamic Huffman), the Adler-32 of the result. Bytes after the Adler-32 are not read, so a `SourceSize` rounded up @@ -152,21 +148,66 @@ The first boot with the executable settles most of this: the dry-run report show worker; later enqueues are dropped and recorded as `E_DSTORAGE_QUEUE_CLOSED`. The last `Release` closes the same way, so a queue released with requests in flight finishes them first. -## Not done yet (later PRs) - -- **BCPack** (`BcpackMode`; `tools/bcpack.py` is the reference decoder), then **swizzle** (`SwizzleMode`). The - decode order is DEFLATE, BCPack, swizzle; with both zlib and BCPack `IntermediateSize` is the size between them - (the inflate's output, the BCPack decoder's input), and `FileOffset` must be 16-byte aligned. Each becomes a stage - after `inflate_request`'s inflate and before its destination write, so the request checks above stay where they - are. -- **Physical pages** (`SourceIsPhysicalPages`, `DestinationIsPhysicalPages`): arrays of 64 KiB page numbers from - `XMemAllocatePhysicalPages`; needs the `xmem` shim to translate a page number to the address it mapped. -- **GPU memory**: the console API has no GPU destinations of its own (memory is unified, so a destination is an - address). An address inside memory the Vulkan layer backs will need its write routed to that memory. The destination - is written in two places, both in `execute_request` (`read_file_range` for a file source, `guarded_move` for a - memory source), so that change stays inside the request path. -- **Parallel reads**: the worker reads one request at a time. Overlapped reads with in-order retirement of - notifications would keep the order guarantee. +## Streamed texture requests + +- Two adjacent file-backed transforms can read and decode concurrently into private buffers. A queue has + one ordered publisher. Mutable memory inputs, page-list resolution, status slots, events, fences, and + overlapping destinations retain their enqueue order. At most two helpers run across all queues and each + assisted request has a 16 MiB eligibility limit. A shared 64 MiB window covers private source, + intermediate, output and page-number buffers across queues. Each transform releases its previous input + and each request releases the final buffer at retirement. A valid request larger than the window runs + alone, bounded by the ABI maximum of two 1 GiB payloads. Raw buffer reads use no private staging. + With tracing enabled, `ds-staging` reports the process peak reservation and return to zero. The figure + excludes title destinations, allocator overhead and fixed decoder stacks. `LEONIDA_DSTORAGE_WORKERS=1` + restores serial execution. + Inflate expands LZ matches in bulk and batches Adler-32 reductions. `LEONIDA_DSTORAGE_FAST_INFLATE=0` + selects the original bytewise path. BCPack indexes the entropy model by the high slot byte. + `LEONIDA_DSTORAGE_FAST_BCPACK=0` selects the scalar bucket search. +- With `LEONIDA_DSTORAGE_TRACE=1`, `tools/dstorage_census.py ` totals retirements, errors and bytes + by shape, plus microseconds spent reading, inflating, decoding BC blocks, unshuffling, publishing and + notifying. `--from-file story000` starts the measurement at the first story archive request and counts + every subsequent retirement across queues. Stage times can overlap. Each failure reports its process-wide count + for that HRESULT even with request tracing disabled. +- The worker inflates zlib to `IntermediateSize` when BCPack follows, rebuilds standard BC blocks, then + applies the optional DirectStorage macro-unshuffle. Each stage validates its entire output before a destination + write. Typed zlib errors propagate through the combined path. +- `runtime/src/bcpack.cpp` ports the interleaved rANS and strict block rebuilders from `tools/bcpack.py` for + BC1, BC3, BC4, BC5, BC6H and BC7. The predictor window holds 256 blocks. The build generates the lookup + tables from the existing codec modules. Damaged streams and missing predictors or inconsistent blocks + exceeding the reference tolerance give `E_DSTORAGE_DECOMPRESSION_ERROR`. BC2 has no reference decoder. + The runtime accepts the reference's fitted BC1/3/4/5 predictors for streamed art. + `LEONIDA_DSTORAGE_FITTED=0` requires confirmed entries. Fitted blocks can differ from console output. + The runtime stage of `make_game.py` generates `/shaders/bcpack/history.bcph` locally. + The loader finds it relative to the shader folder selected by `LEONIDA_SHADERS` or the packaged + `shader_path.txt`. `LEONIDA_DSTORAGE_HISTORY` overrides the path; a value of `0` disables external history. + The load diagnostic reports BC6H row coverage and BC7 endpoint/index field coverage. Standalone generation: + + ```sh + python3 -I tools/build_dstorage_history.py --out /shaders/bcpack/history.bcph + ``` + + The fitter follows the physical block offset of packed 2D mips, including those that start past the first + 256 blocks of a stream. It combines adjacent mips from the same layer with full-stream index anchor + and shared-p-bit constraints. A shared p-bit can relate low red endpoint bits even when its sibling + mip supplies only the leading bits. These local fits preserve the recorded precision and exact reference + bits. A profile can still lack endpoint values or exceed the reference consistency tolerance. Such a request reports a decompression error before publication. +- The four swizzle modes interleave stripes from request-wide component planes into 16 KiB (mode 1) or + 32 KiB (modes 2–4) groups. The enum names give the successive stripe widths. The shipped BC4 sample + separates its endpoint planes from indices across the inflated source. The title's compute shader does + the within-group shuffle and the stored blocks already follow the texture layout. + [Microsoft texture shuffling sample](https://learn.microsoft.com/en-us/samples/microsoft/xbox-gdk-samples/directstoragetextureshuffling/) +- Physical destinations and memory sources use 64 KiB pages with byte offsets in the first page. + The worker reads the page list after submit, resolves and commits every page before copying, and holds + xmem's map lock through the transfer. A successful scatter notifies the texture refill tracker at + each mapped VA. Ordinary GPU alias destinations use the paired CPU view. Raw file writes into title + memory go through the shared kernel-write helper, which pins each kernel write, commits first-touch pages + on an access error and retries once. The superseded `LEONIDA_DSTORAGE_PIN_FILE_READS` switch is retired. +- `LEONIDA_DSTORAGE_EXTENDED=0` restores the old refusal for page lists, BCPack and nonzero swizzle. + `LEONIDA_DSTORAGE_TRACE=1` logs each retired request, worker timestamp, options, source file/range, sizes, destination, + cancellation and HRESULT. Queue pointers connect those lines to status slots, fences and events. + Failures always log the full request. An access violation also records the CPU mapping and protection. + With startup tracing enabled, `dstorage_failure` events share its clock with title exceptions. + Pool fill lines report whether a successful texture upload used any nonzero detiled bytes. ## Tests @@ -181,10 +222,14 @@ synthetic streams only: two made with Python's `zlib` (level 9: one dynamic-Huff fixed-Huffman block) from text the test rebuilds, and stored-block streams the test builds, one of them a stored block followed by the dynamic one. They are read from a file and from memory (also in place); a bad header, a preset dictionary, a reserved block type, a truncated stream, an Adler-32 mismatch, a stream shorter and one longer -than `DestinationSize`, a stored stream larger than its result, an unaligned offset, an `IntermediateSize`, zlib with -BCPack or swizzle (`E_NOTIMPL`), an unreadable source and an unwritable destination each get their code, a failed +than `DestinationSize`, a stored stream larger than its result, an unaligned offset, an invalid `IntermediateSize`, an unreadable source and an unwritable destination each get their code, a failed stream leaves its destination untouched, and the decompression statistics count them. +The extended tests encode hand-built lane symbols with `tests/test_bcpack.py`. All six modes are compared +byte-for-byte with the Python decoder through the queue, both bare and zlib-wrapped. Additional cases cover +truncation, all four swizzle patterns across three groups, an invalid second page, late page-list updates, +a decode crossing two reversed pages, both CPU refill ranges, gather, and event/status ordering. + ## Sources and licences | Source | Facts used | Licence / use | diff --git a/docs/embedded_shaders.md b/docs/embedded_shaders.md index ed3a254d71..8c154b9d6f 100644 --- a/docs/embedded_shaders.md +++ b/docs/embedded_shaders.md @@ -8,8 +8,9 @@ hold counts, offsets, chunk names and module identifiers. ## 1. Why they matter `tools/shader_carve.py` carves `shaders.rpf` only. Two DLLs in the same package carry compute programs of their -own, and `make_game.py`'s `shaders` stage translates both sets after the game's shaders (section 7 for the -builder, [fspx.md](fspx.md) for FidelityFX): +own, and the game executable carries graphics programs inline; `make_game.py`'s `shaders` stage translates all +three sets after the game's shaders (section 7 for the builder and the executable, [fspx.md](fspx.md) for +FidelityFX): * `XboxBvhBuilder.dll`, Microsoft's XDXR acceleration-structure builder. Its constructor creates compute PSOs through device slot 62, and the builder is on the critical path for ray tracing. @@ -42,7 +43,7 @@ validator rejects it (the scan reports both counts). ### Retail executable (`game_scarlett_master.exe`, RT-5) Scanning the retail executable (120,181,760 bytes, SHA-256 `e95020b2fa4a721db3df59fdecf75621730ac559d8835252f6c3b658d5a08993`) -with `tools/pe_shader_containers.py` finds **10** valid DXBC containers (9,520 bytes total, file offsets +for literal DXBC headers finds **10** valid containers (9,520 bytes total, file offsets `0x688cd3c`..`0x688fdf6`, sizes 924–992 bytes) and 1 rejected `DXBC` hit: * **Stages (`PSV0`):** **1** vertex shader (`0x688cd3c`, 992 bytes) and **9** pixel shaders (924–980 bytes). Unlike the @@ -53,6 +54,9 @@ with `tools/pe_shader_containers.py` finds **10** valid DXBC containers (9,520 b unpack via `tools/fssm_unpack.py` (10/10 `FSSM`, 1,245–4,176 bytes), disassemble cleanly via `tools/shader_disasm.py --backend python` (10/10 clean), translate via `tools/rdna2spirv.py` (10/10 translated, all wave64 tier A), and pass `vk_pipeline_check` on an NVIDIA GeForce RTX 5060 Laptop GPU (driver `617.14`, Windows 11): **10/10 modules and 10/10 pipelines OK** (1 VS, 9 PS, 0 failed, 0 skipped). + The build now extracts and translates these 10 in its own `exe` stage (section 7), and the runtime loads them + from `/exe/index.json`; one of them is the VS that 14 graphics PSOs named and could not create before + that step existed (section 7, measured). **Every one of the 52 containers carries two representations of its program:** @@ -290,12 +294,57 @@ The last line also gets `--wave64-emulate` and the fallback flags of the build, emulated modules made at the default cap, `RadixAlloc` is refused (`declares 37084 bytes of workgroup memory`, `0x80004001`) after 28 creations. +**Packed pixel shaders.** The executable also holds two native pixel shaders in SGD5 records (their file offsets +are measured locally and not kept here). Both stored lengths include the 12-byte header. Raw deflate yields a +complete DXBC of 1,324 or 1,052 bytes. Their FSSM SHA-256 keys are +`cae1e27820adde6a6cb35e308290164ad8cf7107f0fe147d50a2053d7ceeb4b8` and +`879cb2e326c5e5333935a0b2b1dd9c3c2adc1b03e546d1f84f993d912b4f66b0`. The first is +`PS_ClearMulti4_f05fef9c_Wrapped`, requested by two graphics streams whose lookup failed with the old index. +`pe_shader_containers.py` checks the stored lengths, inflates the complete stream and validates the inner +container. It appends packed XBCH records after the plain containers to preserve their existing file names. +Three other packed DXBCs have no native XBCH entry. The 12 native programs (1 VS, 11 PS) all translate, pass +`spirv-val`, and compile with the pipeline checker's partner stubs on an RTX 4070. + +The clear shader lookup failed for two distinct graphics state keys. + +- `589de82a8d0f07c4eaa73fa3d25a69c3c6d0eb79cca5bc970f129313a180b207` +- `550e747ba7a5fd9b1467ed8c33be3276ed434621d919c6aa179bdb629086389d` + +Both use the VS `exe/container_00` (FSSM `01ac7810dcabd62afcd904b231e90d9a031a51808a700e3349290bec5f0d426f`) +and the recovered PS `exe/container_10`. Both declare two render targets, RT0 format 87 (BGRA8 UNORM) and +DSV format 20 (D32 FLOAT S8X24 UINT). Their translated VS and PS pass the pairwise interface check. + +**The executable's native containers (`exe_shaders()`).** After the builder's step, the same stage runs +`pe_shader_containers.py /game_scarlett_master.exe --extract /shaders/exe`, then `fssm_unpack.py`, +`shader_disasm.py` and `rdna2spirv.py` as in the recipe above, into `/shaders/spirv/exe`. The executable +passes these containers inline to `CreatePipelineState`, so no archive holds them; the key is `fssm_sha256` again. +The step is reused on the same conditions as the builder's (the image, the three tools before the translator, the +translator, llvm-mc, the wave64 mode and the fallback flags) and reports every program left untranslated on every +run. Measured on 1.0.2.1: **12/12 translate and pass `spirv-val`** (1 VS, 11 PS, 1,245–4,239 bytes); the VS's +SHA-256 is `01ac7810dcabd62afcd904b231e90d9a031a51808a700e3349290bec5f0d426f`. + +**That VS is why 14 graphics PSOs failed (measured).** On the base commit, a 100 s boot refused **14** of 50,469 +`CreatePipelineState` calls, every one with `no translated vs for FSSM sha256 01ac...`: none of the 26,503 indexed +`fssm` blobs has that SHA-256, because the container is in the executable and the build never extracted it. The +translator supports it (all 10 executable containers unpack, disassemble and translate cleanly, wave64 tier A), so +the gap was extraction, not translation. With this step and the runtime index, the same boot creates all 14 +(**0 failed**, 10 `exe` entries loaded). The 14 calls have 13 distinct signatures (one repeats) and share one +paired PS (`452212e59d983c3b6404328105153b5b26a435f5d7780dbcedc0c46a51ecec60`, `exe/container_06`, a colour +passthrough); their target layouts are R8G8B8A8_UNORM and R8G8B8A8_UNORM_SRGB, R11G11B10_FLOAT, R10G10B10A2_UNORM, +A8_UNORM and B8G8R8A8_UNORM, with and without D32_FLOAT_S8X24_UINT, plus one 5-RT layout. The VS has only +`SV_VertexID` as an input and reads two streams (position, colour) out of the title's memory through a descriptor +in its root arguments, so these are quad/UI draws (Scaleform-style), not a texture composite; the B8G8R8A8 layouts +can write a backbuffer-format target. A 150 s boot with late-frame captures (`LEONIDA_CAPTURE_EVERY=300`, frames +1 to 6,901, so the last ones about 110 s in) was still all black (24/24 frames, mean rgb 0.00), so this VS was not +the black-frame cause; see the presentation notes for that. + **Run time.** `ShaderLibrary::load(dir)` (`runtime/src/shader_library.h`) reads `/index.json`, then -`/fspx/index.json` and `/bvh/index.json` when they are there. The builder's entries are named -`bvh/`, the path of their module below ``, and go into the table of the game's shaders, so -`create_compute` finds them through the lookup it already had (`compute_program()` gives an `FSSM` program, looked up -by `(cs, fssm_sha256)`). A missing or unreadable `bvh/index.json` leaves the other indexes loaded, and the main -index is still required. `bvh_size()` counts the entries, which `shader_library_corpus_test` leaves out of the +`/fspx/index.json`, `/bvh/index.json` and `/exe/index.json` when they are there. The builder's +entries are named `bvh/` and the executable's `exe/`, the path of their module below ``, and go +into the table of the game's shaders, so `create_graphics` and `create_compute` find them through the lookups they +already had (`compute_program()` gives an `FSSM` program, looked up by `(cs, fssm_sha256)`). A missing or +unreadable `bvh/index.json` or `exe/index.json` leaves the other indexes loaded, and the main index is still +required. `bvh_size()` and `exe_size()` count those entries, which `shader_library_corpus_test` leaves out of the entries a carved container must reach, like the FSPX ones. **Measured: `LEONIDA_BVH_DEVICE=vulkan bvh_builder_test`** (package 1.0.2.1, `LEONIDA_BVH_RECORD62=1`, diff --git a/docs/fspx.md b/docs/fspx.md index a603545e93..6493dc2b71 100644 --- a/docs/fspx.md +++ b/docs/fspx.md @@ -136,6 +136,12 @@ program whose kind 0 is too short for word 4 keeps the code heuristic. SGPRs (`s[0:1]`, `s4`..`s15`), `M0`, `VCC`, `EXEC` (including inactive lanes across 64 threads) and `SCC` (both 0 and 1) unchanged, and execution resumes cleanly at `+36` bytes. So they are hardware no-ops on RDNA2. - `tools/fspx_unpack.py` disassembles from the end of the prologue. + - **A 24-byte variant**: some programs of the pipeline library in `shaders.rpf` (`tools/shader_library.py`) carry + only the first two of those words, at words 0 and 3, and their code starts at word 6 (`s_inst_prefetch` in all of + them). Counted on the 1.0.2.1 library: 50 of 2,684 programs; read from word 0 they never decode (the prologue + words are invalid encodings and the rest desyncs), and only 1 of the 50 translated. With `code_range` taking + the 24-byte form, all 50 disassemble with 0 invalid words and 49 translate and pass `spirv-val` (the other one + stops at `s_sethalt`). A program whose words 0, 3 and 6 are all prologue words still takes the 36-byte form. - **Target.** The programs use `v_dot4_i32_i8` (1,458 times) and `v_dot4c_i32_i8` (25,813 times), which fits the provider's name (`FSR4_Int8`). `llvm-mc` (LLVM 23.1.5) decodes them for `gfx1011`, `gfx1012`, `gfx1030`, `gfx1031`, `gfx1033`, `gfx1034` and `gfx1036`, but not for `gfx1010`, `gfx1013` (the target `shader_disasm.py` uses for the @@ -149,6 +155,20 @@ program whose kind 0 is too short for word 4 keeps the code heuristic. `op_sel` 2 and `op_sel_hi` 5 the result is the dot product with the two 16-bit halves of the second source exchanged, in all 5 operand sets (4 of them give another word under the plain rule). So `op_sel` selects halves here as it does for the packed 16-bit ops. The words are in `tests/semantic/test_alu_dot4_i8.py`. + - `tools/shader_disasm.py` (so `fspx_unpack.py --disasm` and `make_game.py`) prints such a word as + `v_dot4_i32_i8 vD, a, b, c op_sel:[0,1,0] op_sel_hi:[1,0,1]` with its real encoding. A dword pair that llvm-mc + rejected, with exactly opcode 0x16, `op_sel` 2, `op_sel_hi` 5, no `clamp` and no `neg`, is decoded with the two + fields at their defaults and then given the fields and the encoding back, so the translator reads it and its + encoding check against the blob passes. Any other `op_sel`/`op_sel_hi` value, `clamp` or `neg` is still + undecodable (only this one was measured). A pair llvm-mc accepted, such as a literal followed by an instruction, + is never touched. `tests/semantic/test_fspx_dot4_op_sel_disasm.py` checks it with llvm-mc (the 5 measured + operand sets, and the forms that stay refused); the 89 words of the real programs are not re-run here, because + that needs the package's DLL. + When a listing lacks that pass, the translator decodes the same exact form from the original bytes on a gap + in the listing (`rdna2spirv.skipped_form`); other undecodable words keep the reachable-code check. A + `v_dot4_i32_i8` that llvm-mc decodes but prints with the default `op_sel`/`op_sel_hi` (for example an inline + integer second source whose low half is replicated) takes the stored fields from the blob when they are the + only difference (`rdna2spirv.dot4_op_sel_fields`, docs/design.md "Signed-byte dot products"). ## Kind 7: records @@ -230,8 +250,71 @@ with a blob holding the dword 0, so the DLL creates no compute scratch buffer; w Not done here: using kind 0 at run time beyond what the translated module already carries (its thread-group size and `RSRC2`). +**Slot 57 (`DeserializeGraphicsPipelineStateX`, graphics FSPX).** At one call site (measured locally), the retail +title calls device slot 57 (`+0x1c8`) with `IID_ID3D12PipelineState` (`{765a30f3-f624-4c6f-a828-ace948622445}`) and a +104-byte description (`+0x00..+0x60`) populated from the zlib-compressed pipeline library in `shaders.rpf` +([shader_library.md](shader_library.md): 25,471 graphics records + 2,693 compute records): + +| Offset | Field | Measured layout | +|---|---|---| +| `+0x00` | `ID3D12RootSignature*` | Root signature pointer | +| `+0x08`, `+0x10` | `state_blob`, `state_blob_size` | 380..404 B (388 B in 24,797 records; 380 B in depth-only boot PSO 3) | +| `+0x18`, `+0x20` | `pipeline_blob`, `pipeline_blob_size` | 80..224 B (188 B = `0xbc` in boot PSOs 1..3); holds the `D3D12_INPUT_ELEMENT_DESC` array | +| `+0x28`, `+0x30` | `prog_a`, `prog_a_size` | First native RDNA2 kind-6 program (448 / 768 B `ps` in boot PSOs 1..2; `0/0` in boot PSO 3) | +| `+0x38`, `+0x40` | `stage_a`, `stage_a_size` | Stage blob (kind 2, 208 B in boot PSOs 1..2; `0/0` in boot PSO 3) | +| `+0x48`, `+0x50` | `prog_b`, `prog_b_size` | Second native RDNA2 kind-6 program (384 / 320 B `vs` in boot PSOs 1..3) | +| `+0x58`, `+0x60` | `stage_b`, `stage_b_size` | Stage blob (kind 2, 752 B in boot PSOs 1..3) | + +- **First three boot graphics PSOs (matched in `shaders.rpf` pipeline library):** + 1. Record 8916 (`2f04ef59bc062cf8`): state 388 B (`0x4005d808`), pipeline blob 188 B (`0xea6f6e56`), `ps` prog 842 (448 B, SHA-256 `9e5ffd2c6c521c03...`), `vs` prog 843 (384 B, SHA-256 `160fbe4368fb1a63...`). + 2. Record 8917 (`f7808a66fb6b97c1`): state 388 B (`0x4005d808`), pipeline blob 188 B (`0x542385d2`), `ps` prog 844 (768 B, SHA-256 `947014e8b0771be5...`), `vs` prog 845 (320 B, SHA-256 `a2dce0214f82c742...`). + 3. Record 12511 (`e750e10eacb97b9c`): state 380 B (`0x4005d808`), pipeline blob 188 B (`0xfb724939`), no `ps`, `vs` prog 5636 (320 B, SHA-256 `f6bfddbad6aef3cd...`). + In the library, the 448/768 B program at `+0x28` is the pixel shader (`ps`, paired with the 208 B stage blob) and the + 384/320 B program at `+0x48` is the vertex shader (`vs`, paired with the 752 B stage blob). Programs are looked up by + `sha256(program bytes)` in `/fspx_gfx/index.json` (`ShaderLibrary::fspx_gfx_size()`, separate from + `fspx_size()`), and their `stage` (`"vs"` / `"ps"` / `"ms"`) is taken from the index entry rather than the blob slot. +- **Measured `pipeline blob` layout (188 B = `0xbc`):** + - `+0x00`: u32 per-PSO checksum (`0xea6f6e56` / `0x542385d2` / `0xfb724939`) + - `+0x04`: u32 `0x1000` (constant across 2,642 blobs), `+0x08`: `0`, `+0x0c`: `1` + - `+0x10`: u32 per-element field-block size (`0x1c` = 28 B = 7 u32 in PSOs 1..2; `0` in PSO 3 where the stride remains 28 B) + - `+0x1c`: u32 `0xffffffff`, `+0x24`: `0x00130100` (PSOs 1..2) / `0x00130037` (PSO 3), `+0x28`: `1` + - `+0x38`: u32 `0x70` (or `0x6d`) = `4 + n * 28 + sum(len(name) + 1)` + - `+0x3c`: u32 `0x0c` (constant across 2,642 blobs) + - `+0x4c`: u32 element count (`3` across the library) + - `+0x50`: u32 maximum name stride including NUL (`9` or `6`) + - `+0x54..`: variable-length element array. Each element is a NUL-terminated ASCII semantic name followed by 7 u32s + (28 B): `+0x00` `InputSlot` (`0`), `+0x04` `DXGI_FORMAT` (`6` = `R32G32B32_FLOAT` for `POSITION` at `0x54`/`0x5d`, + `28` = `R8G8B8A8_UNORM` for `COLOR` at `0x79`/`0x7f`, `16` = `R32G32_FLOAT` for `TEXCOORD` at `0x9b`/`0xa4`), + `+0x08` `SemanticIndex` (`0`), `+0x0c` `AlignedByteOffset` (`0`, `12`, `16`). The stored blob truncates the unused + tail of the final 28-byte block by 1..4 bytes (`0xa4 + 28 = 0xc0 > 0xbc` in PSO 1), so the parser bounds-checks + every 4-byte read against `blob_size`. +- **Measured `state blob` (380..388 B) and `stage blob` (kind 2):** + - `state blob`: `+0x000` version tag (`0x4005d800` in 15,632 records, `0x4005d808` in 9,159, `0x4005d810` in 6), + `+0x004` family (`4` in 12,735 or `6` in 12,062), `+0x02c = 2`, `+0x07c` (`0xcc0010` / `0` / `0xcc0011`), + `+0x0f4 = 5`, `+0x0f8 = 1`, `+0x0fc = 0x33333333` (`0.1f`), `+0x100..+0x11c` (`0x00060006` x8), `+0x150 = 0x40`, + `+0x158 = 0xffffffff`, `+0x17c = 0x10000a00`. Unidentified offsets are logged once per offset while safe default + raster/depth/blend state is used. + - `stage blob`: `+0x00 = 2` (graphics stage blob), `+0x04` payload size (`196` in 208 B blobs), `+0x08 = 0x66`, + `+0x0c = 0x40 | flags`, followed by records `0x41` (32 B input/output signature), `0x42` (32 B output signature) + and `0x43` (20 B: tag + 16 B opaque digest). + ## Translation status +In wave64, VALU compares and carry outputs write both predicate words. Conditional selects and carry inputs +read the corresponding word for each half-wave. Earlier LLVM listings used wave32 register spellings for these +operands. The translator uses the dispatch wave size to recover their width in cached listings. + +All 29 distinct program and dispatch-state pairs in the measured DLL resolve through the compute pipeline lookup. +The eight recovered programs pass Vulkan 1.2 SPIR-V validation. The original container and the split pipeline +parts select the same module. Changing one bit of the supplied state rejects the candidate in all 29 cases. + +On an RTX 4070, passes 1, 2, 7, 9, 10, 11 and 12 matched every byte of the 32 MiB reference tensor for one +workgroup. Five references came from the TuxBox native gfx1036 tensor measurements. The other two came from +an independent ISA interpreter. The postpass matched all 81,920 reference image components with a maximum +finite absolute error of 5.96e-8. These checks use deterministic inputs. + +### Earlier measurements + With `tools/fspx_unpack.py --disasm` and `tools/rdna2spirv.py` on the 29 programs (`main` at `aa2988cc` with the `v_fma_mix*` literal repair in [design.md](design.md), "Printed encodings"): **Wave size.** On `main` at `aa2988cc`, `make_game.py`'s FSPX step translates 26 of the 29, and each now gets the diff --git a/docs/linux_proton.md b/docs/linux_proton.md new file mode 100644 index 0000000000..30107cfeb3 --- /dev/null +++ b/docs/linux_proton.md @@ -0,0 +1,120 @@ +# Linux (Proton/Wine) and second-machine test report + +This page describes how the runtime is built and booted on Linux through Proton's Wine, what a healthy boot looks +like there, and what was observed on the machines that tested this branch (one Linux, two native Windows). It holds +counts, timings and settings only: no game data, no traces. + +Status in one line: on Linux/Proton and on native Windows the retail 1.0.2.1 package launches, shows its launch +movie, first-run pages and landing prompt, runs the story load to its end with the loading slideshow drawing its +artwork, and enters the world phase. A first world frame has not been verified yet on any of the three machines; what +stops it is listed under [Where it stops](#where-it-stops). + +## Test machines + +| | Linux | Windows A | Windows B | +|---|---|---|---| +| OS | CachyOS (Arch), kernel 7.3 | Windows 11 | Windows 11 | +| Run through | Proton Experimental (Wine 11) | native | native | +| CPU | Ryzen 5 5600X | Core i9-13900K | Ryzen 7 9800X3D | +| GPU, driver | RTX 4070 12 GB, NVIDIA 620.73 | RTX 4070 Ti 12 GB, NVIDIA 630.20 | RTX 5070 | +| RAM | 16 GB (+32 GB swap file) | 64 GB | not reported yet | +| Toolchain | clang-cl 23 + xwin SDK, Ninja, ccache | MSVC 2022, SDK 26100 | - | +| Results here | yes, ~80 boots on 2026-11-24 | yes | joining; none yet | + +Windows A reaches every stage three to five times faster than the Linux machine (initialisation ~70 s against +~180 s, story load from ~110 s against ~240-300 s), so it is the better machine for iterating on the world phase; +the Linux machine is the one that shows what 16 GB of RAM allows. + +## Building on Linux + +The runtime is a Windows executable. On Linux it is cross-built with clang-cl against an [xwin](https://github.com/Jake-Shadle/xwin) +copy of the Windows SDK: + +```sh +scripts/linux-boot/configure-worktree.sh # XWIN_DIR=, SDL3_SRC= for an offline configure +cmake --build /runtime/build/boot --target gta6rt -j6 +``` + +`gta6rt_tls_host.dll` is built with the `gta6rt` target and must stay next to the executable. Unit tests are Windows +executables too and run under Wine (`scripts/run_wine_tests.py`, or directly with the same `wine` binary and a +prefix of their own: sharing the game's prefix with tests breaks its window). + +## Booting on Linux + +`scripts/linux-boot/boot.sh` is the plain launcher and `run-boot.sh` wraps it as a `systemd --user` unit with a +memory sampler, a GPU lock, a build lock (no compile while the game runs) and a digest after the boot. They assume +the layout the comments at their top describe (`/opt/leonida` for traces, overlay and caches; the package under +`/opt/gta6`); adjust the paths at the top to yours. What matters: + +- **Wine:** Proton Experimental's `files/bin/wine` with its own prefix (`WINEPREFIX`), `WINEDLLOVERRIDES="mscoree,mshtml="`. +- **No network:** the title runs inside `unshare -rn` (new user and network namespace). Nothing is online. +- **Backend:** `LEONIDA_D3D12=vulkan`, `LEONIDA_SHADERS=`. +- **NVIDIA shader cache:** `__GL_SHADER_DISK_CACHE_SIZE` raised (the library is ~19 GB of SPIR-V) and + `__GL_SHADER_DISK_CACHE_SKIP_CLEANUP=1`. +- **Input:** a pad through GameInput/SDL3, or the keyboard pad (`LEONIDA_KEYBOARD_PAD=always`), or a script: + `LEONIDA_INPUT_SCRIPT=a@210,a@240` presses A at those seconds (any length since this branch; it was cut at 63 + characters before). +- **Window:** frames are presented in the title's own window; `LEONIDA_PRESENT_WINDOW=own|hidden` chooses otherwise. + +Three setup mistakes each give a blank or empty picture without an error: the executable's embedded shaders missing +from the library (`exe/index.json`), a build without SDL3 (no pad), and a BCPack predictor file that was never +generated (`tools/build_dstorage_history.py`; without it the loading art and most BC7 textures stay empty). + +## What a healthy boot looks like (Linux machine) + +| Time | Stage | +|---|---| +| 0-10 s | package splash | +| ~60-90 s | launch movie, then the landing prompt appears while initialisation finishes | +| ~180 s | initialisation done; A is accepted | +| ~240-300 s | story load starts: loading slideshow with its artwork | +| ~540-630 s | story load ends (about 38,000 streamed images registered), world phase begins | + +On Windows A the same stages are at ~70 s, ~110 s and ~190 s. + +## What this branch changes to get there + +Each item was a stop on at least one of the machines. Tests named in the pull request cover them. + +- **Presentation:** frames go to the title's own window (they went to a window that was never shown). +- **DirectStorage:** reads pin write-watched destination pages, page-list scatter/gather, BCPack and unshuffle, a + locally generated predictor file, bounded staging. +- **Story-load allocation stall:** one device allocation per streamed texture exhausted the driver's CPU-visible + mappings near 16,000 images; small streamed images now share pooled pages. +- **Images on plain device-local memory:** host-copy usage excluded it on NVIDIA and 4.8 GB of images spilled into + host memory; streamed images are now filled through staging. +- **Deferred backing:** placed and streamed images get private memory at their first write or GPU copy. VRAM at the + end of the load went from 11.8 GB to ~5 GB on Linux; on Windows A host private memory went from 22-24 GB to 11.9 GB. +- **Enhanced barrier into `LAYOUT_UNDEFINED`:** accepted; it failed `Close`, which the title treats as fatal. +- **Bindless table:** a table rebuild that cannot allocate no longer refuses the whole submission; larger image + arrays; a hash finalizer for the descriptor table (runtime and translator halves, off until a library carries it). +- **Translator:** loop bounds on every emitted loop (5,128 compute modules have loops), the eight FidelityFX programs + that used an instruction form the disassembler skips (all 29 translate), buffer bounds modes per view kind. +- **Directly indexed descriptor heaps:** the heap offset is supplied in the user-data dword after the explicit root + arguments for compute and for VS/PS/GS draws. Mesh stages are not covered yet. +- **Title buffers at raw addresses:** a window outside the arena when title reservations fragment it; opt-in + persistent device-local copies of streamed buffer views. +- **Native Windows:** write faults on shared pages retried under the tracker lock, one tracker per run of shared + pages, write-watched title memory, a fault-lock that never waits for the process heap. +- **Diagnostics:** device-loss report with the last dispatches and NVIDIA checkpoints, a probe for the descriptors a + compute dispatch receives, memory probe, press log. All off by default. + +## Where it stops + +- **Streamed memory that never reaches its destination.** The title calls queue slot 31 (`CopyPageMappingsBatchX`) + about 300 times per boot and this branch still ignores it; tens of thousands of streamed views wait for memory + that never becomes readable. An open pull request in this repository implements it. +- **Culling compute at world start** reads buffers named by descriptors in the directly indexed heap; with the + point above unfixed those reads leave mapped memory and the device is lost (NVIDIA Xid 13/109 on Linux). +- **Mesh stages** do not get the heap offset yet. +- **16 GB of RAM:** at the end of the load the process holds ~14.6 GB (RAM plus swap) on the Linux machine after the + cuts above. zram made this worse (compressed pages still occupy RAM); a swap file on disk is the better choice. +- **Initialisation takes ~180 s under Proton** against ~70 s natively. Not investigated. +- **Under Wine** a thread that takes an access violation while holding the process heap lock can still deadlock + with xmem's fault handler; the test for it is skipped there. + +## Reporting a result + +Say the machine (OS, GPU and driver, RAM), the commit, the environment switches that differ from the defaults, and +counts: presents, the last stage reached with its time, the first refusal or device-loss line. Keep logs and traces +on the machine that produced them. diff --git a/docs/movies.md b/docs/movies.md index a338069bd2..f7c1b06183 100644 --- a/docs/movies.md +++ b/docs/movies.md @@ -1,15 +1,10 @@ # Movies (`movies.rpf`) -**Status: indexed. All 515 Bink 2 streams have been enumerated and their fixed headers read; the first two frames -of every stream, and the start of every audio track, decode with the package's own Bink 2 library. The RPF9 table -of contents is encrypted, but the streams can be named from the game's mount lists -([section 8](#8-names-from-the-mount-lists)). Nothing here is a playback path yet.** -**Status: indexed and decode-checked. All 515 Bink 2 streams have been enumerated, their fixed headers read, and -frame 0 of every stream decoded with the package's own Bink 2 library (515/515). The RPF9 table of contents is -encrypted, but the streams can be named from the game's mount lists ([section 8](#8-names-from-the-mount-lists)). -Nothing here is a playback path yet.** - -Every number below was measured on the Xbox Series 1.0.2.1 package on 2026-11-21. The archive is read-only. No +All 515 Bink 2 streams have been indexed and their first two frames decoded with the package's library. The mount +lists supply the stream names ([section 8](#8-names-from-the-mount-lists)). The title also plays the publisher +stinger after the first A press on the account picker. + +The archive measurements below use the Xbox Series 1.0.2.1 package. The archive is read-only. No game video, audio, frames, carved streams or reports that quote them are in this repository; the tools write only offsets and header facts. Commands are at the end. @@ -326,9 +321,15 @@ The loader-side runs behind these numbers are recorded in [`runtime/test/bink_de returned 145,920 bytes on frame 0 and 7,680 bytes on frame 1 across all 229 tracks (with frame 2 also checked on 1-, 2-, and 4-track samples; later frames were not swept and may return 7,680 or 0 bytes). Which language or mix role the game assigns to track IDs `0, 1, 2, 3` at run time remains unknown. -- **Playback integration.** The executable is not in the package. Where the game calls `BinkOpen`, which flags it - passes, whether it uses `BinkDoFrameAsync`, `BinkGoto`, subtitles or the GPU path, and how it schedules movies - against streaming are all unknown. +- **Startup playback.** In two boots the title opened the archive twice about 1.2 s after entering the loader. + The separately loaded `Bink2Scarlett.dll` opens the metadata from the title; playback retains the handle + and registers mapped frame buffers. The title's frame wrapper has a CPU + multi-worker decode and wait path and a synchronous fallback. Three rotating sets of linear R8 planes (one + 3840×2160 and two 1920×1080 per set) reach the slot-133 texture uploader. `VS_Bink` / `PS_BinkNoAlpha` bind + the three plane descriptors at table offsets 0x20, 0x40 and 0x60 and draw to an RGBA8 intermediate. The UI + plane then reaches the swapchain. A capture after the first A matched an independently CPU-decoded frame of the + only 4K, 450-frame stream with 0.9994 spatial RGB correlation at 128×72. The preceding shell visual is a static + package image ([boot switches](boot.md)). - **Bink2Scarlett ABI.** [ABI over the archive](#abi-over-the-archive) gives the `HBINK` and `BINKSUMMARY` fields that match the stream header, the bytes `BinkGetSummary` writes (+0x00..+0x8F), and the return values of `BinkWait`, `BinkDoFrame` and `BinkCopyToBuffer`. The rest of both structures, the async API, the GPU API and the XAudio2 setup are not @@ -342,8 +343,8 @@ The loader-side runs behind these numbers are recorded in [`runtime/test/bink_de project does not decode them. - **Whether every frame of all 515 streams decodes correctly.** All 515 open and decode their first two frames through the package's DLL ([coverage above](#decode-coverage-over-the-whole-archive)); nine were decoded as a - sample with frames viewed. No stream was decoded from its first frame to its last, and nothing compares the - output with a reference. + sample with frames viewed. The 450-frame publisher stinger also has a complete CPU decode and a swapchain comparison. + The other streams have partial coverage. - **Why 22,812 bytes at the end are unread.** They are not a `KB2` stream and not zero. They may be an RPF footer or leftover table data; the encrypted TOC prevents a name-level answer. - **Full-stream playback beyond frame 0.** All 515 streams open and decode frame 0 with `Bink2Scarlett.dll` diff --git a/docs/pipeline_check.md b/docs/pipeline_check.md index 0de55d4848..8ce85ff025 100644 --- a/docs/pipeline_check.md +++ b/docs/pipeline_check.md @@ -24,6 +24,8 @@ For an index entry with `lds_bytes`, the checker compares the reported workgroup limit counts as a module failure before Vulkan receives the shader. Older indexes without this field still use the normal driver check. Mesh pipelines on devices without mesh shader support still use the existing feature skip. +Build with `make_game.py --stages shaders --compact-spirv` to run SPIRV-Tools local load elimination, redundant value elimination and dead-code elimination before validation. The same flag works on `tools/rdna2spirv.py` and `scripts/translate_pipeline_compute.py`. It preserves stage interfaces, descriptor bindings and specialization constants. Omit the flag for an unoptimized comparison. On NVIDIA use separate empty pipeline caches and set `__GL_SHADER_DISK_CACHE=0` for both arms. Use one pipeline per checker process with `--jobs 1 --slow 0` for per-module timings. + ## Options `vk_pipeline_check [cache.bin] [options]` diff --git a/docs/retail_boot_chain.md b/docs/retail_boot_chain.md index da0605bb05..e693b2a2b3 100644 --- a/docs/retail_boot_chain.md +++ b/docs/retail_boot_chain.md @@ -22,7 +22,7 @@ stand-ins named below (not pull requests yet). Own 1.0.2.1 copy, Windows 11, RTX | 5 | Fatal assert when `DStorageGetFactory` returns null | #4348 | | 6 | `XMemAllocatePhysicalPages` unimplemented; the title asserts on FALSE | Local stand-in, §2 | | 7 | `D3D12XboxCreateDevice` succeeds; device slot 26 is called with its arguments swapped | Local, §3.1 | -| 8 | Device slot 48 is forwarded to the PC slot 48 and fails | Local, §3.2 | +| 8 | Device slot 48 is forwarded to the PC slot 48 and fails | #6954 | | 9 | Device slot 73 is forwarded to the PC slot 73; the title then reads through a null list | #2490's list proxy plus local routing, §3.3 | | 10 | An `XMemVirtualAlloc` reserve of about 185 MiB with type `0x42000`, attribute 7 and `PAGE_NOACCESS` is refused with `ERROR_INVALID_PARAMETER`. `0x40000` is `MEM_RESERVE_PLACEHOLDER` on the PC, which `VirtualAlloc` refuses and only `VirtualAlloc2` accepts; stop 11 supports the same reading on the console | Local: reserve it with `VirtualAlloc2(MEM_RESERVE \| MEM_RESERVE_PLACEHOLDER)` | | 11 | The title carves five sub-ranges out of that placeholder with `MEM_RESERVE \| MEM_REPLACE_PLACEHOLDER \| MEM_PHYSICAL \| MEM_LARGE_PAGES` (`0x20406000`) at addresses inside it, then allocates a second batch of physical pages | Local: a physical reserve inside a known placeholder stays a placeholder (the page maps split it); other `MEM_REPLACE_PLACEHOLDER` calls split the range and allocate it in place | diff --git a/docs/runtime_imports.md b/docs/runtime_imports.md index 34422cc0a9..fc0787e1e8 100644 --- a/docs/runtime_imports.md +++ b/docs/runtime_imports.md @@ -163,15 +163,17 @@ policy "other" (none is counted as returning an `HRESULT`), and they come from s | `xapu.dll` | 5: `XApuConnect`, `XApuDequeueResult`, `XApuDisconnect`, `XApuEnqueueCommand`, `XApuGetResultCount` | the audio processing unit | | `AcpHal.dll` | 9: `AcpHalAllocateShapeContexts`, `AcpHalCreate`, `AcpHalReleaseShapeContexts`, `ApuAlloc`, `ApuCreateHeap`, `ApuFree`, `ApuIsVirtualAddressValid`, `ApuMapApuAddress`, `ApuMapVirtualAddress` | the audio hardware layer | -The game executable imports two functions from `xg_xs.dll`, the console's texture layout library: -`XGSuggestSwizzleMode` (2 call sites, in the helper that fills a texture description) and `XGCreateTextureComputer` -(4 call sites, which use slots 1, 2, 8 and 10 of the returned object's vtable). The runtime has no model of the console -resource layout, so `runtime/shims/xg_xs.cpp` computes none: both return `E_NOTIMPL` and write no layout. Two of the -four `XGCreateTextureComputer` callers ignore the HRESULT and call through the object at once, so the shim still stores -a static object in the out pointer; its slot 1 (read as `Release`) does nothing, and every other slot up to 31 logs its -index and caller once and returns `E_NOTIMPL` without writing its arguments. The call shapes and the reasoning are at -the top of the file; `xg_xs_test` covers them. Textures whose layout the game asks for are therefore not laid out yet. -The table above was measured before this shim and still lists these two as unimplemented; they are served now. +The game executable imports two functions from `xg_xs.dll`, the console's texture layout library. +`XGSuggestSwizzleMode` writes the Xbox layout encoding `0x100 | mode`, including when its output aliases the +description. `XGCreateTextureComputer` returns a refcounted computer for supported layouts. Slot 2 writes the Series +layout, slot 8 copies linear source rows into a subresource, and slot 10 reports 64 KiB tiled-resource geometry. +Rows and tile extents are computed in storage elements, so block-compressed formats use one 4x4 block as an element. +Packed mips share a block at the start of each slice, followed by the other mips from smallest to largest. +The shim covers single-sample linear textures, 2D 4 KiB standard and 64 KiB standard/display textures, and single-mip +4 KiB standard volumes. Unsupported descriptions return a failure and a fallback object because two measured +callers dereference the output without checking the HRESULT. Set `LEONIDA_XG_TRACE=1` to log the first 1024 calls +per entry point. See [the source notes](../runtime/shims/xg_xs_THIRD_PARTY.md) and `xg_xs_test`. The table above +predates the shim. Only two of these DLLs have a shim in the repository (`xmem.dll` and `d3d12_xs.dll`), and they are not complete: they hold 8 of the 30 unimplemented imports. The other 22 are in five DLLs (`xg_xs.dll`, `XCRDAPI.dll`, `chad.dll`, @@ -266,6 +268,43 @@ and the `api-ms-win-core-file-*` sets a GDK title links against. `runtime/test/file_system_test.cpp` (ctest `file_system`) covers this over folders it makes in `%TEMP%`. +## Console identity in the registry + +GTA VI does not only ask `XSystemGetDeviceType` which console it runs on. Code linked into the executable opens +`HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\OEM`, reads the `DWORD` value `ConsoleMode` +(`0x64` Series X, `0x60` Series S) and closes the key. A missing value means a PC, and a PC takes the PC memory +budgets and resolution, so without an answer the title does not run as the console build. It decides the console +model, and with it the back buffer size (1920x1080 for Series S, 3840x2160 for Series X). + +Measured with `tools/pe_inspect.py` on the retail 1.0.2.1 package: + +| Module | Imports | From | +|---|---|---| +| `game_scarlett_master.exe` | `RegOpenKeyW`, `RegQueryValueExW`, `RegCloseKey` | `ADVAPI32.dll` | +| `libHttpClient.GDK.dll` | the same three and `RegOpenKeyExW` | `ADVAPI32.dll` | +| `XCurl.dll` | `RegOpenKeyExW`, `RegQueryValueExW`, `RegCloseKey`; `RegOpenKeyW` | `api-ms-win-core-registry-l1-1-0.dll`; `-l2-1-0.dll` | + +Before `runtime/shims/console_registry.cpp` the loader bound all of them to the host's advapi32 (`pe_inspect` labels +them `shim` only because it ran on Linux, with no `System32` to find them in). Under Proton the lead wrote the value +into the Wine prefix; on a Windows PC the key does not exist and writing it needs administrator rights. + +`console_registry.cpp` now serves the four functions under `advapi32.dll` and the registry API sets. It answers only +`HKLM\Software\Microsoft\Windows NT\CurrentVersion\OEM` / `ConsoleMode`, with a pseudo key; every other key, +value and handle goes to the host's advapi32 unchanged. It follows the `RegQueryValueExW` contract for the value: +`REG_DWORD` is reported when the type pointer is set, a null data pointer is a size query (4 bytes), a buffer under +4 bytes gives `ERROR_MORE_DATA` with the size, and a data pointer without a size is `ERROR_INVALID_PARAMETER`. + +One setting drives both answers (`runtime/shims/console_identity.h`): `LEONIDA_DEVICE_TYPE` 6 gives `ConsoleMode` +`0x60`, 7 (also the default) gives `0x64`, 8 (devkit) gives `0x68`. For the types that have no value (0, 1, 2 to 5) the +key is not ours and the host registry answers, so a missing key stays missing, as on a PC. The first answer of each +value is logged once: `[rt] registry: ConsoleMode answered 0x64 (LEONIDA_DEVICE_TYPE=7)`. `advapi32.dll` is a host +module in `rt::shims::owns_dll`: `LoadLibrary("advapi32.dll")` still returns the real module. + +Credit: the pseudo key design and the value numbers follow VIctory `crates/victory-hle/src/modules/xsystem.rs` +(`mod device_type`, GPL-3.0-or-later, commit 2849477); `0x68` for the devkit follows xbox-emulator +`crates/compat/xpal` and `compat-common/src/gdk/hook.rs` (GPL-3.0, commit 0284e83). The test is +`runtime/test/console_registry_test.cpp` (`ctest -R console_registry`). + ## When an unimplemented import is called The table above has no unimplemented imports, but the game executable will. A call to one used to return 0 @@ -295,23 +334,30 @@ measurement in `d3d12_vulkan.md`, because its page could not be found. Not every console module is reached through an import table. `libHttpClient.GDK.dll` and `XCurl.dll` both use the GDK runtime, but `dumpbin /imports` shows **no import of `xgameruntime.dll`** in either. Both carry the wide string `xgameruntime.dll` and the ASCII names `InitializeApiImpl`, `InitializeApiImplEx`, `InitializeApiImplEx2`, -`QueryApiImpl` and `UninitializeApiImpl`, next to a statically linked `XGameRuntimeInitialize`. So `xgameruntime.lib`'s -thunks `LoadLibraryW` the runtime and `GetProcAddress` those five names at run time. xodus-gaming/xgameruntime-docs +`QueryApiImpl`, `UninitializeApiImpl` and `XErrorReport` (one block of strings in each DLL), next to a statically +linked `XGameRuntimeInitialize`. So `xgameruntime.lib`'s thunks `LoadLibraryW` the runtime and `GetProcAddress` those +six names at run time. A runtime without `XErrorReport` is refused before any initializer is called: with only the +five entry points served, the package's own libHttpClient `HCInitialize` returned `0x89240101` +(`E_GAMERUNTIME_DLL_NOT_FOUND`) and XCurl's `curl_global_init` returned `CURLE_FAILED_INIT`, both called through +`gta6rt --run` by a stand-in program that loads the two DLLs from the package. xodus-gaming/xgameruntime-docs (GPL-3.0) documents the same mechanism for PC GDK titles: `InitializeApiImplEx2` is what `XGameRuntimeInitialize[WithOptions]` calls, and `QueryApiImpl` hands out the runtime's COM classes, whose methods mostly correspond one to one to the `xgameruntime.lib` functions. The executable is very likely linked the same way. Bound to the host, those calls would load the PC's Gaming Services runtime, or fail, and never reach the offline shims. `runtime/shims/library_loader.cpp` therefore answers `LoadLibrary*` and `GetModuleHandle*` for a module the -shim registry owns (`rt::shims::owns_dll`: `xgameruntime.dll`, `d3d12_xs.dll`, `xmem.dll`, `xg_xs.dll`, `gameinput.dll`) -with a pseudo-handle, and `GetProcAddress` on it resolves through the registry. A name the registry doesn't serve is `NULL` +shim registry owns (`rt::shims::owns_dll`: `xgameruntime.dll`, `d3d12_xs.dll`, `xmem.dll`, `xg_xs.dll`, `gameinput.dll`, and the +DirectStorage modules `dstorage_xs.dll`, `xcrdapi.dll` and `dstorage.dll`, [directstorage.md](directstorage.md)) with a +pseudo-handle, and `GetProcAddress` on it resolves through the registry. A name the registry doesn't serve is `NULL` with `ERROR_PROC_NOT_FOUND` and is logged once. Every other module goes to the host unchanged. -`runtime/shims/xgameruntime.cpp` serves the five entry points. The initializers succeed offline and log the GDK -version and mode once. `QueryApiImpl` serves `XThreadingImpl`, `XErrorImpl`, `XNetworkingImpl`, `XSystemImpl`, -`XPersistentLocalStorageImpl`, `XPackageImpl`, `XGameImpl`, `XGameRuntimeFeatureImpl` and `XSystemAnalyticsImpl` -(below), and `XUserImpl`, `XGameSaveImpl`, `XStoreImpl`, `XGameEventImpl`, `XGameUiImpl`, `XGameStreamingImpl`, -`XDisplayImpl`, `XUserDeviceImpl`, `XAccessibilityImpl` and `XLauncherImpl` from xgameruntime-docs' layout (below); for any other class it logs +`runtime/shims/xgameruntime.cpp` serves the five entry points and `XErrorReport(HRESULT, const char*)`, the same +function as `IXErrorImpl` slot 3 (below), so a report reaches the callback `XErrorSetCallback` set either way. The +initializers succeed offline and log the GDK version and mode once. `QueryApiImpl` serves `XThreadingImpl`, +`XErrorImpl`, `XNetworkingImpl`, `XSystemImpl`, `XPersistentLocalStorageImpl`, `XPackageImpl`, `XGameImpl`, +`XGameRuntimeFeatureImpl` and `XSystemAnalyticsImpl` (below), and `XUserImpl`, `XGameSaveImpl`, `XStoreImpl`, +`XGameEventImpl`, `XGameUiImpl`, `XGameStreamingImpl`, `XDisplayImpl`, `XUserDeviceImpl`, `XAccessibilityImpl` and +`XLauncherImpl` from xgameruntime-docs' layout (below); for any other class it logs the class and interface id and returns `0x80070032`, the documented error for a class the runtime doesn't provide, so the first boot with the executable lists the classes to implement next. `xgameruntime_test` drives this path through the api-set binding `XCurl.dll` uses, and calls the classes `xgameruntime.cpp` serves slot by slot. @@ -322,7 +368,8 @@ the api-set binding `XCurl.dll` uses, and calls the classes `xgameruntime.cpp` s pointers to 64-bit locals (the result is not read), compares the pair with the one it saw last and keeps it. On the host that load would find a PC's Gaming Services runtime, which bypasses the offline classes, or nothing, in which case XCurl returns `0x87E00196`. The shims own `gameplatformservices.dll` too: its `QueryApiImpl` is the offline -one, and `GetApiVersionImpl(uint64_t*, uint64_t*)` writes the same two values every time. +one, and `GetApiVersionImpl(uint64_t*, uint64_t*)` writes the same two values every time. `curl_global_init` also +asks that module for `InitializeApiImpl`, which is not served; the call succeeds without it. ### Class layouts, measured @@ -343,7 +390,7 @@ count and width, the function at that position of xgameruntime-docs' "Layout" li | `XNetworkingImpl` (`IXNetworkingImpl2`, slots 3-20) | 11-17 (`XCurl.dll`), 3-20 (`libHttpClient.GDK.dll`, each in its documented argument shape, e.g. 18-20 (enum, u64 pointer / u64 / pointer)) | the Utf16 `XNetworkingQuerySecurityInformationForUrl*` trio, `XNetworkingVerifyServerCertificate`, `XNetworkingGetConnectivityHint`, `XNetworkingRegister/UnregisterConnectivityHintChanged` (pointer, bool). Served offline, asked for with `IXNetworkingImpl2`'s id | | `XSystemImpl` (`IXSystemImpl5`, slots 3-8 known) | 3-8 (`libHttpClient.GDK.dll`) | 3-5 `XSystemGetConsoleId` / `GetXboxLiveSandboxId` / `GetAppSpecificDeviceId` (size, pointer, pointer each), 6 `XSystemHandleTrack` (two pointers, IXSystemImpl3), 7 `XSystemIsHandleValid` (pointer), 8 `XSystemAllowFullDownloadBandwidth` (bool, IXSystemImpl4); IXSystemImpl2 and 5 add no known method. Served offline | | `XPersistentLocalStorageImpl` (`IXPersistentLocalStorageImpl3`, slots 3-8) | none called (the table of ids only) | slots 3-7 are `XPersistentLocalStorageGetPathSize` / `GetPath` / `GetSpaceInfo` / `PromptUserForSpaceAsync` / `PromptUserForSpaceResult`, slot 8 `XPersistentLocalStorageMountForPackage` (IXPersistentLocalStorageImpl3). Slots from the public xgameruntime-docs and Wine IDL, not measured in a caller. Served offline: the folder is `\.gta6rt-persistent`, which `GAME:` does not see, the quota is the 2048 MB of `MicrosoftGame.Config`, a prompt for space the quota holds succeeds, and `MountForPackage` is `E_NOTIMPL` | -| `XPackageImpl` (`IXPackageImpl3`) | 3-19, 22, 24-27, 30, 32-34, 37-40 (`libHttpClient.GDK.dll`) | slots 3-34 are IXPackageImpl's 32 entries, 35-38 IXPackageImpl2's 4, 39-40 IXPackageImpl3's 2. Served offline: 3 identifier, 4 packaged process, 11 user locale, 24-26 mount path size / path / close; the rest log once and return `E_NOTIMPL` | +| `XPackageImpl` (`IXPackageImpl3`, `IXPackageImpl4`) | 3-19, 22, 24-27, 30, 32-34, 37-40 (`libHttpClient.GDK.dll`); 3-7, 9, 12, 14, 16-19, 25, 26, 34, 37-39 (the retail executable, as `IXPackageImpl4`) | slots 3-34 are IXPackageImpl's 32 entries, 35-38 IXPackageImpl2's 4, 39-40 IXPackageImpl3's 2, 41 IXPackageImpl4's `XPackageGetPackageKind`. Served offline: 3 identifier, 4 packaged process, 5-10 installation monitor (create, close, progress complete, no update, progress registration, unregister), 11 user locale, 12-19 chunks of the fully installed package (every selector Ready, declared languages enumerated, install order / install / async install complete at once with a monitor, 0-byte download estimate, uninstall accepted with nothing removed; ported from VIctory's xpackage.rs), 22 unregister installed, 23-26 mount / path size / path / close, 34 uninstall package, 37-38 mount with UI (a mapped content package mounts, any other completes with `E_GAMEPACKAGE_NO_PACKAGE_IDENTIFIER`), 39 `XPackageEnumeratePackages` (S_OK, the callback never runs: no content packages to list; VIctory answers the title's call the same way); the rest log once and return `E_NOTIMPL` | | `XGameImpl` (`IXGameImpl3`, slots 3-5) | none in the package's DLLs (`libHttpClient.GDK.dll` holds its id only in the linked id table); the executable's requests are unmeasured | from the xgameruntime IDL: 3 `XGameGetXboxTitleId` (pointer), 4 `XLaunchNewGame` (two strings and a user handle, `void`), 5 `XLaunchRestartOnCrash` (string, u32). Served offline: the title id is `MicrosoftGame.Config`'s `` (`E_FAIL` without one), a new game launch is logged and ignored, a crash restart succeeds with nothing registered | **Two layout sources, and where they differ.** Besides xgameruntime-docs (GPL; facts only), the LGPL @@ -389,8 +436,11 @@ trio (23-25). What the slots must answer is still **not measured**; that is the - **Validity:** handles are looked up in a live set, never read, so a closed or foreign pointer is refused without touching its memory, and a double close does nothing. Unregistering a change callback is never pending, so it returns true for any token. `XUserIsStoreUser` is true, as documented for console. +- **First calls:** every served slot writes one `[rt] xgameruntime: XUser first call: ...` line with its + arguments and answer (`XUserGetGamertag` one per component, with the text it returned), so a boot log shows whether + the title added its user and read the gamertag its player-select prompt shows (T7 in `docs/re/takes/other-projects.md`). -`xgameruntime_user_test` calls every served slot with the documented arguments. +`xgameruntime_user_test` calls every served slot with the documented arguments and reads back the first-call lines. `XGameSaveImpl` (`runtime/shims/xgameruntime_gamesave.cpp`) is served from the same layout, also **not measured**: - **Interfaces:** the class id doubles as `IXGameSaveImpl`'s; `IXGameSaveImpl2` (adds the three `XGameSaveFiles` diff --git a/docs/shader_library.md b/docs/shader_library.md index be62ed2b68..2652aac051 100644 --- a/docs/shader_library.md +++ b/docs/shader_library.md @@ -154,7 +154,9 @@ python -I tools/rdna2spirv.py /library/disasm --out /library/spirv reads (`native_blob`, `cs_dispatch_state`). A compute program also gets `fspx/.state`, its record's state blob (FSPX kind 0) as it is, whose SHA-256 is the index's `fspx_state_sha256`; in the 1.0.2.1 `shaders.rpf` library, every compute program has one distinct state-blob index across `library.json`'s `compute` table (2,684 programs, - 2,693 records). It also writes `index.json` with each program's stage, and + 2,693 records). A program that records use with different state blobs is written once per distinct state, the + first under its name and each further one as `_state_`, so each pair of keys has an entry + (the library measured above has no such program). It also writes `index.json` with each program's stage, and `library.json` with the header and both pipeline tables, stage to program name. Programs are named `lib__`. * `--disasm` writes `disasm/.s` for the code after the prologue, as `fspx_unpack.py --disasm` does. @@ -163,6 +165,8 @@ python -I tools/rdna2spirv.py /library/disasm --out /library/spirv interface. * `--save` writes the reassembled library. A saved file is also accepted as input. * `--stages` limits the output to some stages. +* `--compute-hashes FILE` instead writes only the compute programs whose code has one of the SHA-256 digests listed + in `FILE` (`fspx_code_sha256`), with every state they are used with. A digest no compute program has is an error. The output is game data and must stay in your work folder. `tests/test_shader_library.py` builds libraries and archives by hand and covers the header, both tables, the size checks, the search in an archive and the digest @@ -180,6 +184,29 @@ them and the state key is the record's state blob. The step is redone as a whole `llvm-mc`, the wave64 mode or the flags change (`library_build.json`, written last), and a clash of both keys between different modules fails it, as for the FSPX step. Graphics pipelines are not translated by the build. +### Resuming a compute-only batch on Linux + +Run `tools/shader_library.py` with `--stages cs --disasm --jobs 2` and the carved containers, or select the +kind-6 hashes with `--compute-hashes`. For an unpacked library with its input `index.json`, use the compute batch. + +```sh +python3 -I scripts/translate_pipeline_compute.py /path/to/unpacked --out /path/to/spirv/library --wave64-emulate +``` + +Use a dedicated output folder. The two workers run at nice 19. Each has a 768 MiB address-space limit and uses one +SPIRV-Tools process at a time (four processes total). `--jobs 1` uses a single worker and `--memory-mib` changes +the per-process limit. A rerun checks each module against its checksum and the listing, source container, FSPX +sidecars, toolchain and wave mode. It retries failures. Only validated modules enter the runtime index. Its +atomic replacement follows both workers, so an interrupted run leaves the previous index readable. A partial +run exits nonzero and writes the reasons to `failures.json`, keyed by kind-6 and kind-0 SHA-256. Old modules +can still be used by a runtime that already opened the preceding index. + +Among 2,680 compute programs, 46 start with two 12-byte literal-bearing VOP3 NOP hash carriers. Their body +starts at byte 24. The three-record form starts at byte 36. The no-op measurements are in `docs/fspx.md`. +A hash literal can resemble an instruction. `shader_library.py` excludes both complete carrier records before +looking for the end of the program. LLVM input uses one dword per line, including within multiword instructions, +so its diagnostic for an invalid word echoes at most four source bytes. + ## 5. Translation With `--carve` and `rdna2spirv.py` at `main` `aa2988cc` (llvm-mc 23, `gfx1013`), **17,955 of the 21,522 programs @@ -199,9 +226,16 @@ What stops the rest, by the translator's message: run into `vcc` (SGPRs 106 and 107): `s_load_dwordx8`/`x4`/`x16` writing `s[100:107]`, `s[104:107]` or `s[92:107]`, and image instructions whose resource is `s[100:107]`. In the compute programs alone that is 37,952 SMEM, 22,248 MIMG and 2,298 MUBUF words. The same words with the register field one tuple lower decode; with - `gfx1030` they don't either. The FSSM shaders don't use these tuples; the pipeline builds use them often. A decoder - fallback for these encodings would cover most of the remaining programs. The translator already reads - `[s100,...,vcc_lo,vcc_hi]` lists (design.md *Scalar/buffer memory*). + `gfx1030` they don't either. The FSSM shaders don't use these tuples; the pipeline builds use them often. The translator + now decodes these words from the blob with `rdna2_decode` (`restore_vcc_tuples`) and reads them as the + `[s100,...,vcc_lo,vcc_hi]` lists it already takes (design.md *Scalar/buffer memory*); synthetic cases are in + `tests/semantic/test_vcc_tuple_fallback.py`. The junk llvm-mc prints at such a word's second dword is often longer + than that dword (an 8-byte `exp`, say) and swallows the instruction after the tuple too, so the words after a restored + instruction are decoded from the blob until the stream is back at one llvm-mc printed. A word llvm-mc itself rejected + is not taken for swallowed code and stays refused. They are decoded for the program's own wave size: in wave64 a + swallowed VOP3 compare writes an SGPR pair. The table above was measured before both changes. Measured since, + over the 2,684 compute programs (llvm-mc 21.1.8): 1,816 translate with the tuples alone and 2,567 with the swallowed + instructions, all of which pass `spirv-val`; the modules of the 1,816 are byte-identical. * **443: an instruction llvm-mc prints with another encoding than the blob's** (`v_fma_mix*`, `v_interp_p2_f16`): the existing `check_printed_encodings` refusal. * **90 CS: "CS thread-group-size SGPR"**: RSRC2 `TG_SIZE_EN`, which no FSSM compute shader sets. diff --git a/docs/xdxr.md b/docs/xdxr.md index 1a2d104a47..1b8a4cc274 100644 --- a/docs/xdxr.md +++ b/docs/xdxr.md @@ -112,6 +112,40 @@ type is one of two checks, and neither reads past the `InfoType` field: None of the 15 other DLLs in the package names the type or an offline builder. +## 4a. The runtime serves the DLL itself + +`runtime/shims/xbox_bvh_builder.cpp` serves the seven exports the executable imports with the layer's own XDXR +builder (`runtime/src/xdxr_build.*`), so the bundled DLL is not loaded and its 52 console programs are never created. +Their pipeline compile (31.2 s for one of them on an RTX 4080, 59.5 s for all 52 on an RX 9070 XT, #7231/#7049) runs +on the title's thread, longer than its ~30 s startup watchdog, so a cold first boot ends at the builder (boot stop 18). +`LEONIDA_BVH_BUILDER=console` turns the shim off. + +The executable's imports and call sites, measured statically on 1.0.2.1. The counts are `call [rip+disp32]` +through the import table. For `Batched2X`, IDA finds 8 direct calls: 4 in each of two sibling functions with no +static reference, reached through a table (#7516), so 2 of them are calls of another form. + +| Export | Call sites | The shim | +|---|---:|---| +| `XboxBvhBuilder(ID3D12Device11*, bool)` | 1 | keeps the device in a table keyed by `this`; writes nothing into the title's object | +| `~XboxBvhBuilder()` | 1 | releases that entry | +| `Set64BitMortonCodes(bool)` | 8 | recorded; the layer's builder has no such option | +| `GetRaytracingAccelerationStructurePrebuildInfo(INPUTS*, XDXR_STREAM_DESC*, PREBUILD_INFO*)` | 3 | the layer's sizes | +| `BuildRaytracingAccelerationStructureBatched2X(GCL6*, UINT, BATCHED_DESC2*)` | 6 (8) | one layer build per element (§1), with its postbuild descriptions | +| `CopyRaytracingAccelerationStructure(GCL4*, dest, source, mode)` | 2 | the layer's copy | +| `RehydrateRaytracingAccelerationStructureBatched2X(GCL8*, UINT, BUILD_DESC*, UINT64*)` | 4 | `E_NOTIMPL` for now | + +**Where it differs from the DLL:** +- **Stream records (§3):** they tune the console builder's heuristics, so they are ignored (logged once). The result + is still a valid BVH of the same geometry, in the node format the traversal shaders read. +- **Validation errors:** the DLL throws them as C++ exceptions. A shim must not throw into the title, so an element + the DLL would refuse is skipped with a log line. The offline-statistics postbuild type (`0x10`, §4) is one of + those. +- **Rehydration** is the next step: rebuild each structure on the GPU from the source geometry its description + carries ([bvh.md](bvh.md) §4a), in the leaf frame `compressionParams` gives. + +`xbox_bvh_builder_test` calls every export through the shim registry, the way the title's imports bind, and +`xdxr_bvh.py check-build` checks the BLAS, TLAS and compacted BLAS it builds (ctest `xbox_bvh_builder_check`). + ## 5. What is still open - The names of the stream record types and of their values. diff --git a/make_game.py b/make_game.py index 0f5c499cbc..9b1b30a880 100644 --- a/make_game.py +++ b/make_game.py @@ -1328,6 +1328,8 @@ def shaders(game: str, work: str, jobs: int, emulate: bool = False, keep_emulate if not os.path.isfile(translated): need("spirv-as", "Install the Vulkan SDK (it includes spirv-as and spirv-val) and reopen the terminal.") need("spirv-val", "Install the Vulkan SDK and reopen the terminal.") + if "--compact-spirv" in fallbacks: + need("spirv-opt", "Install SPIRV-Tools with spirv-opt to use --compact-spirv.") log(f"shaders: translating RDNA2 to SPIR-V on {jobs} processes (the longest step)") # The mode and the translator's digest go down before the translation starts, while there is no index.json: # a stop at any point then leaves either no index (translated again) or an index with the right mode and @@ -1345,6 +1347,7 @@ def shaders(game: str, work: str, jobs: int, emulate: bool = False, keep_emulate fspx_shaders(game, work, signature, emulate=emulate, fallbacks=fallbacks) bvh_shaders(game, work, signature, jobs, emulate=emulate, fallbacks=fallbacks) library_shaders(game, work, signature, jobs, emulate=emulate, fallbacks=fallbacks) + exe_shaders(game, work, signature, jobs, emulate=emulate, fallbacks=fallbacks) log("shaders: done") @@ -1666,17 +1669,123 @@ def bvh_shaders(game: str, work: str, mc_signature: str, jobs: int = 1, emulate: f.write(settings + "\n") +EXE_IMAGE = "game_scarlett_master.exe" +EXE_TOOLS = ("pe_shader_containers.py", "fssm_unpack.py", "shader_disasm.py") # as BVH_TOOLS, for the executable + + +def exe_settings(image: str, mc_signature: str, emulate: bool, fallbacks: tuple[str, ...]) -> str: + """What the executable's shader outputs depend on, as one line: the image, the extracting, unpacking and + translating tools, llvm-mc, the wave64 mode and the fallback flags.""" + return json.dumps({"image": file_sha256(image), "tools": sources_digest(TOOLS, EXE_TOOLS), + "translator": translation_sources_digest(), "llvm_mc": mc_signature, + "wave64_emulate": bool(emulate), "fallbacks": list(fallbacks)}, sort_keys=True) + + +def exe_programs(unpacked: str, spirv: str) -> "tuple[list[str], list[str]] | None": + """The programs pe_shader_containers.py extracted from the executable, by file stem, and the ones among them + the runtime cannot find: no entry with an fssm_sha256 in /index.json, or no module beside it. None when + either index is missing or unreadable, or names a module that is not there.""" + try: + extracted = sorted(shader_stems(os.path.join(unpacked, "index.json"), "file", ".dxbc")) + with open(os.path.join(spirv, "index.json"), encoding="utf-8") as f: + index = json.load(f) + except (OSError, ValueError): + return None + if not isinstance(index, dict) or not all(os.path.isfile(os.path.join(spirv, name + ".spv")) for name in index): + return None + found = {name for name, meta in index.items() + if isinstance(meta, dict) and isinstance(meta.get("fssm_sha256"), str)} + return extracted, [name for name in extracted if name not in found] + + +def exe_report(programs: "tuple[list[str], list[str]]") -> None: + """One line with the counts, and one that names every program left without a module. It is printed on every + run, also when the step itself is reused: a program the translator has no rule for is never dropped quietly.""" + extracted, missing = programs + log(f"shaders: {len(extracted) - len(missing)} of {len(extracted)} {EXE_IMAGE} programs translated") + if missing: + log(f"shaders: NOT translated: {', '.join(missing)}. The runtime has no module for " + f"{'it' if len(missing) == 1 else 'them'}, so every graphics pipeline that names " + f"{'it' if len(missing) == 1 else 'them'} is refused (E_INVALIDARG). When the step runs, rdna2spirv.py " + "prints the instruction each one stops at") + + +def exe_shaders(game: str, work: str, mc_signature: str, jobs: int = 1, emulate: bool = False, + fallbacks: tuple[str, ...] = ()) -> None: + """game_scarlett_master.exe's own DXBC containers (docs/embedded_shaders.md, "Retail executable"): the + executable passes them inline to CreatePipelineState, so no shader archive holds them. pe_shader_containers.py + extracts its plain and packed programs into /shaders/exe, fssm_unpack.py and shader_disasm.py unpack and disassemble + their FSSM programs there, and rdna2spirv.py translates them into /shaders/spirv/exe, where the runtime's + shader library finds them by fssm_sha256, the key of the game's own shaders. Those neither feed nor depend on + this step. + + The programs take seconds, so the step runs whole. Reuse requires both indexes, the translated modules and + a matching exe_build.json (exe_settings).""" + image = os.path.join(game, EXE_IMAGE) + unpacked = os.path.join(work, "shaders", "exe") + spirv = os.path.join(work, "shaders", "spirv", "exe") + extracted = os.path.join(unpacked, "index.json") + unpack_index = os.path.join(unpacked, "fssm_index.json") + translated = os.path.join(spirv, "index.json") + settings_file = os.path.join(spirv, "exe_build.json") + if not os.path.isfile(image): + # A work folder used before with a package that had the image still holds that run's index, and the runtime + # loads /exe/index.json whenever it is there. Without the index the old modules are not found. + drop(translated, settings_file) + log(f"shaders: no {EXE_IMAGE} in the game folder, so no executable shader programs to translate") + return + settings = exe_settings(image, mc_signature, emulate, fallbacks) + programs = exe_programs(unpacked, spirv) if read_shader_setting(settings_file) == settings else None + if programs: + exe_report(programs) + return + log(f"shaders: extracting and translating the graphics programs of {EXE_IMAGE}") + drop(translated, settings_file, extracted, unpack_index) + # pe_shader_containers.py never overwrites a container (a second run would write _NN.dxbc beside the + # first), and a program that no longer translates must not keep a module from the run before. + for folder, suffixes in ((unpacked, (".dxbc",)), (os.path.join(unpacked, "fssm"), (".fssm",)), + (os.path.join(unpacked, "disasm"), (".s",)), (spirv, (".spv", ".spvasm"))): + if os.path.isdir(folder): + with os.scandir(folder) as entries: + for entry in entries: + if entry.name.endswith(suffixes) and entry.is_file(follow_symlinks=False): + os.unlink(entry.path) + py("pe_shader_containers.py", image, "--extract", unpacked) + py("fssm_unpack.py", unpacked, "--carve-index", extracted) + # rdna2spirv.py reads each program's stage from index.json and its FSSM blob from fssm/, both in the parent of + # the listings' folder, so the disassembly sits inside the extraction folder as it does for shaders.rpf. + disasm = os.path.join(unpacked, "disasm") + py("shader_disasm.py", os.path.join(unpacked, "fssm"), "--unpack-index", unpack_index, "--out", disasm, + "--mcpu", "gfx1013", "--jobs", jobs) + extra = (["--wave64-emulate"] if emulate else []) + list(fallbacks) + py("rdna2spirv.py", disasm, "--out", spirv, "--no-asm", *extra) + programs = exe_programs(unpacked, spirv) + if not programs or len(programs[1]) == len(programs[0]): + drop(translated) # an empty or unreadable index would read as a finished step + fail(f"shaders: none of {EXE_IMAGE}'s programs translated, so their index is not kept. Run the shaders " + "stage again; if it happens again, the tool output above is why.") + exe_report(programs) + with open(settings_file, "w", encoding="utf-8", newline="\n") as f: + f.write(settings + "\n") + + WAVE64_MODES = ("auto", "on", "off") # The translator's fallback flags make_game.py can forward, and the argparse attribute each one reads. FALLBACK_FLAGS = (("--no-float-controls", "no_float_controls"), ("--bary-fallback", "bary_fallback"), ("--texel-offset-fallback", "texel_offset_fallback"), ("--mesh-compute", "mesh_compute"), - ("--f16-interp-fallback", "f16_interp_fallback"), ("--pc-tail-ubo", "pc_tail_ubo")) + ("--f16-interp-fallback", "f16_interp_fallback"), ("--pc-tail-ubo", "pc_tail_ubo"), + ("--compact-spirv", "compact_spirv")) def fallback_flags(a) -> tuple[str, ...]: """The fallback flags the parsed arguments ask for, in a stable order (the order they are recorded in).""" - return tuple(flag for flag, attr in FALLBACK_FLAGS if getattr(a, attr, False)) + flags = tuple(flag for flag, attr in FALLBACK_FLAGS if getattr(a, attr, False)) + descriptor_hash = getattr(a, "descriptor_hash", "fnv1a") + if descriptor_hash != "fnv1a": + flags += (f"--descriptor-hash={descriptor_hash}",) + limit = getattr(a, "loop_limit", None) + return flags if limit is None else (*flags, f"--loop-limit={limit}") def recorded_fallback_flags(work: str) -> tuple[str, ...]: @@ -1840,7 +1949,7 @@ def runtime_gpu_max_push_constants(): # Source and data files that produce the translated modules, metadata, partner stubs and native PSO catalog. TRANSLATION_SOURCES = ("rdna2spirv.py", "shader_ir.py", "cfg_structure.py", "file_mode.py", "fssm_header.py", "lane_masks.py", "wave64_halves.py", - "wave64_emulate_opt.py", "shader_meta.py", "spirv_stubs.py", "spirv_asm.py", "spirv_asm_tables.py", + "wave64_emulate_opt.py", "spirv_loop_guard.py", "shader_meta.py", "spirv_stubs.py", "spirv_asm.py", "spirv_asm_tables.py", "spirv_opt.py", "report_paths.py", "replace_retry.py", "fssm_unpack.py", "shader_stage_manifest.py", "rdna2_decode.py", "rdna2_isa_tables.py", "gfx10_formats.json", "native_pso_hashes.py", "shader_carve.py", "shader_carve_accel.py") @@ -2440,6 +2549,12 @@ def runtime(game: str, out: str, v: dict, runtime_build: str | None = None, jobs f.write(os.path.abspath(game)) if work is not None: shader_dir = os.path.join(os.path.abspath(work), "shaders", "spirv") + from ttpf_mips import find_pools + if find_pools(game): + profile = os.path.join(os.path.dirname(shader_dir), "bcpack", "history.bcph") + native = os.path.join(build, "bcpack_history_train.exe") + trainer = ["--trainer", native] if os.name == "nt" and os.path.isfile(native) else [] + py("build_dstorage_history.py", game, "--out", profile, "--if-needed", *trainer) # Wine's path converter takes the original Unix filename bytes. The Windows reader expects UTF-8. encoded = shader_dir.encode("utf-8") if os.name == "nt" else os.fsencode(shader_dir) pending = tempfile.NamedTemporaryFile(dir=out, delete=False) @@ -2553,13 +2668,23 @@ def pipelines(work: str, out: str, jobs: "int | None" = None, *, runtime_build: report = os.path.join(out, "pipeline_crashes.json") drop(inflight, skip, report) # every module gets a fresh chance on each run (a new translator may have fixed it) # --jobs: make_game.py's own; without it vk_pipeline_check uses half the hardware threads whatever was asked - base = [exe, spirv, cache, *(["--jobs", str(jobs)] if jobs else [])] + jobs_args = ["--jobs", str(jobs)] if jobs else [] + base = [exe, spirv, cache, *jobs_args] + + def seed_bvh() -> None: + bvh = os.path.join(spirv, "bvh") + if not os.path.isfile(os.path.join(bvh, "index.json")): + return + log("pipelines: creating XboxBvhBuilder compute pipelines") + run([exe, bvh, cache, *jobs_args]) + if not checker_supports(exe, "--inflight-file", "--skip-file"): # An older build takes any argument it doesn't know as the cache path, so it would write the cache into # pipeline_inflight.txt and exit 0. Run it as before: a module that kills it stops the stage. log("pipelines: this vk_pipeline_check has no --inflight-file; rebuild the runtime stage so a module that " "crashes the driver is skipped instead of stopping the stage") run(base) + seed_bvh() log("pipelines: done") return base += ["--inflight-file", inflight] @@ -2635,6 +2760,7 @@ def check_range(start: int = 0, count: "int | None" = None) -> int: why = f"; {len(crashed)} module(s) took the driver down and were counted as failed (with their SPIR-V " \ f"hashes in pipeline_crashes.json): " + ", ".join(crashed) if crashed else "" fail(f"vk_pipeline_check exited with {exit_label(code)}{why}") + seed_bvh() log("pipelines: done") @@ -2883,6 +3009,11 @@ def main() -> int: help="translate wave64 compute and mesh shaders to be exact on any subgroup size (needed on " "32-wide GPUs: NVIDIA, Intel). auto (default) checks GPU subgroup support and prefers " "native wave64 on affected AMD Windows drivers") + ap.add_argument("--descriptor-hash", choices=("fnv1a", "fnv1a_fmix32"), default="fnv1a", + help="translate all stages for the selected runtime descriptor table hash") + ap.add_argument("--loop-limit", type=int, help="translator loop visit limit (default 65536, 0 disables)") + ap.add_argument("--compact-spirv", action="store_true", + help="run the translator's compact binary pass on all shader libraries (requires spirv-opt)") ap.add_argument("--no-float-controls", action="store_true", help="translate without SignedZeroInfNanPreserve and DenormPreserve (Depends on: #664), for " "devices whose vk_pipeline_check skips a shader without " @@ -2912,6 +3043,8 @@ def main() -> int: help="plain console logs (default when stdout is not a TTY); skip the LEONIDA setup screen " "and per-stage log view") a = ap.parse_args() + if a.loop_limit is not None and not 0 <= a.loop_limit <= 0xffffffff: + ap.error("--loop-limit must be in 0..4294967295") stages = STAGES if a.stages is not None: stages = [s.strip() for s in a.stages.split(",") if s.strip()] diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index de10c26e81..81c8dba636 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -146,11 +146,26 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) message(FATAL_ERROR "LEONIDA_REQUIRE_XMA2_DECODER is enabled, but the Rust XMA2 decoder is unavailable") endif() + find_package(Python3 COMPONENTS Interpreter REQUIRED) + set(bcpack_tools "${CMAKE_CURRENT_SOURCE_DIR}/../tools") + set(bcpack_tables "${CMAKE_CURRENT_BINARY_DIR}/bcpack_tables.inc") + add_custom_command(OUTPUT "${bcpack_tables}" + COMMAND "${Python3_EXECUTABLE}" -I "${bcpack_tools}/gen_bcpack_runtime_tables.py" "${bcpack_tables}" + DEPENDS "${bcpack_tools}/gen_bcpack_runtime_tables.py" "${bcpack_tools}/bcpack.py" + "${bcpack_tools}/bcpack_tables.py" "${bcpack_tools}/bcpack_tables_bptc.py" + VERBATIM) + add_executable(bcpack_history_train "../tools/bcpack_history_train.cpp" "${bcpack_tables}") + target_include_directories(bcpack_history_train PRIVATE "${CMAKE_CURRENT_BINARY_DIR}") + add_library(gta6rt_bcpack STATIC src/bcpack.cpp "${bcpack_tables}") + target_include_directories(gta6rt_bcpack PRIVATE "${CMAKE_CURRENT_BINARY_DIR}") + add_executable(gta6rt src/main.cpp src/host_cpu.cpp src/pe_loader.cpp + src/thread_stacks.cpp shims/registry.cpp + shims/console_registry.cpp shims/file_system.cpp shims/winhttp_offline.cpp shims/ws2_offline.cpp @@ -159,11 +174,13 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) shims/acphal.cpp shims/d3d12_xs.cpp shims/d3d12_xs_device.cpp + shims/d3d12_xs_pso_stream.cpp shims/xgameruntime.cpp shims/xgameruntime_user.cpp shims/xgameruntime_gamesave.cpp shims/xgameruntime_store.cpp shims/xgameruntime_offline.cpp + shims/xbox_bvh_builder.cpp shims/library_loader.cpp shims/process.cpp shims/com_shim.cpp @@ -171,11 +188,11 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) shims/xapu_chad.cpp shims/dstorage.cpp ) - # dstorage.cpp's guarded_move turns an access violation in a title's buffer into E_DSTORAGE_ACCESS_VIOLATION with - # __try. MSVC always catches it; clang-cl only with asynchronous exceptions (as for tiny_dll below). A source file - # property, so gta6rt and dstorage_test both get it. - set_source_files_properties(shims/dstorage.cpp PROPERTIES COMPILE_OPTIONS "$<$:/EHa>") - add_dependencies(gta6rt gta6rt_tls_host) + # These sources use __try to handle access violations. MSVC always catches them; clang-cl needs asynchronous + # exceptions (as for tiny_dll below). A source file property also applies to dstorage_test. + set_source_files_properties(shims/dstorage.cpp src/thread_stacks.cpp + PROPERTIES COMPILE_OPTIONS "$<$:/EHa>") + add_dependencies(gta6rt gta6rt_tls_host bcpack_history_train) target_compile_definitions(gta6rt PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE) target_compile_options(gta6rt PRIVATE /W4 /permissive- /utf-8) # Static shim tables register themselves at startup; keep the linker from dropping their objects. @@ -190,7 +207,7 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) # scripts/build_runtime.ps1. set(GTA6RT_STACK 8388608) target_link_options(gta6rt PRIVATE /OPT:NOREF ${GTA6RT_HOST_BASE} /STACK:${GTA6RT_STACK}) - target_link_libraries(gta6rt PRIVATE gta6rt_d3d12_xs_rootsig gta6rt_xtaskqueue psapi) + target_link_libraries(gta6rt PRIVATE gta6rt_bcpack gta6rt_d3d12_xs_rootsig gta6rt_xtaskqueue psapi) # Root-signature forwarding test: needs a real PC d3d12.lib to serialize the synthetic descriptors. # find_library searches %LIB% (a Developer Prompt), not the Windows SDK the Visual Studio generator links @@ -212,6 +229,7 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) shims/registry.cpp shims/d3d12_xs.cpp shims/d3d12_xs_device.cpp + shims/d3d12_xs_pso_stream.cpp ) target_link_libraries(root_sig_test PRIVATE gta6rt_d3d12_xs_rootsig ${D3D12_LIBRARY}) target_compile_definitions(root_sig_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) @@ -236,6 +254,7 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) shims/registry.cpp shims/d3d12_xs.cpp shims/d3d12_xs_device.cpp + shims/d3d12_xs_pso_stream.cpp ) target_link_libraries(device_proxy_test PRIVATE gta6rt_d3d12_xs_rootsig ${D3D12_LIBRARY} ${DXGI_LIBRARY}) target_compile_definitions(device_proxy_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) @@ -249,6 +268,7 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) add_executable(xs_proxy_mock_test test/xs_proxy_mock_test.cpp shims/d3d12_xs_device.cpp + shims/d3d12_xs_pso_stream.cpp ) target_compile_definitions(xs_proxy_mock_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) target_compile_options(xs_proxy_mock_test PRIVATE /W4 /permissive- /utf-8 /EHsc) @@ -269,6 +289,13 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) target_link_options(xmem_test PRIVATE /OPT:NOREF) target_link_libraries(xmem_test PRIVATE psapi) + # The title's CLZERO loops rewritten to stubs on a CPU without CLZERO (src/clzero_patch.h): both loop shapes are + # found, patched and run, so the test runs on any x86-64 CPU. + add_executable(clzero_patch_test test/clzero_patch_test.cpp) + target_include_directories(clzero_patch_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) + target_compile_definitions(clzero_patch_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(clzero_patch_test PRIVATE /W4 /permissive- /utf-8) + # xg_xs shim: the two exports and the texture computer's slots against the measured call shapes. add_executable(xg_xs_test test/xg_xs_test.cpp @@ -305,16 +332,25 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) # Xbox DirectStorage (DStorageGetFactory under dstorage_xs.dll, xcrdapi.dll and dstorage.dll) over synthetic files: # GAME: paths through the file shims, queues, status arrays, fences and errors. No GPU, no game data. + set(dstorage_vectors "${CMAKE_CURRENT_BINARY_DIR}/dstorage_vectors.inc") + add_custom_command(OUTPUT "${dstorage_vectors}" + COMMAND "${Python3_EXECUTABLE}" -I "${CMAKE_CURRENT_SOURCE_DIR}/test/dstorage_vectors.py" "${dstorage_vectors}" + DEPENDS test/dstorage_vectors.py ../tests/test_bcpack.py "${bcpack_tools}/bcpack.py" + "${bcpack_tools}/bcpack_tables.py" "${bcpack_tools}/bcpack_tables_bptc.py" + VERBATIM) add_executable(dstorage_test + "${dstorage_vectors}" test/dstorage_test.cpp + shims/xmem.cpp shims/dstorage.cpp shims/file_system.cpp shims/registry.cpp ) - target_include_directories(dstorage_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) + target_include_directories(dstorage_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims "${CMAKE_CURRENT_BINARY_DIR}") target_compile_definitions(dstorage_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) target_compile_options(dstorage_test PRIVATE /W4 /permissive- /utf-8) target_link_options(dstorage_test PRIVATE /OPT:NOREF) + target_link_libraries(dstorage_test PRIVATE gta6rt_bcpack psapi) # xapu.dll and chad.dll, the APU and audio DSP command queues, resolved through the registry like xmem_test. add_executable(xapu_chad_test @@ -327,6 +363,30 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) target_compile_options(xapu_chad_test PRIVATE /W4 /permissive- /utf-8) target_link_options(xapu_chad_test PRIVATE /OPT:NOREF) + # The boot stack's earlier xapu.dll and chad.dll shims (shims/xapu.cpp, shims/chad.cpp), which gta6rt no longer + # links (it serves both DLLs from xapu_chad.cpp): their ABI tests stay as tests of those files. + # xapu shim ABI test: resolves the registered xapu.dll exports through the registry. + add_executable(xapu_test + test/xapu_test.cpp + shims/xapu.cpp + shims/registry.cpp + ) + target_include_directories(xapu_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) + target_compile_definitions(xapu_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(xapu_test PRIVATE /W4 /permissive- /utf-8) + target_link_options(xapu_test PRIVATE /OPT:NOREF) + + # chad shim ABI test: resolves the registered chad.dll exports through the registry. + add_executable(chad_test + test/chad_test.cpp + shims/chad.cpp + shims/registry.cpp + ) + target_include_directories(chad_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) + target_compile_definitions(chad_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(chad_test PRIVATE /W4 /permissive- /utf-8) + target_link_options(chad_test PRIVATE /OPT:NOREF) + # The process shim's command line: GetCommandLineW must parse (CommandLineToArgvW) back to its __wargv. add_executable(process_cmdline_test test/process_cmdline_test.cpp @@ -406,6 +466,38 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) target_compile_options(bcrypt_rng_test PRIVATE /W4 /permissive- /utf-8) target_link_options(bcrypt_rng_test PRIVATE /OPT:NOREF) + # LEONIDA_STACKS's sampler (src/thread_stacks.cpp): call chains of helper threads, no game data. + add_executable(thread_stacks_test + test/thread_stacks_test.cpp + src/thread_stacks.cpp + shims/registry.cpp + ) + target_include_directories(thread_stacks_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) + target_compile_definitions(thread_stacks_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE) + target_compile_options(thread_stacks_test PRIVATE /W4 /permissive- /utf-8) + target_link_options(thread_stacks_test PRIVATE /OPT:NOREF) + + # kernel_writes (src/title_page_watch.h): a file read into reserved, first-touch memory retried after a commit. + add_executable(kernel_writes_test test/kernel_writes_test.cpp) + target_compile_definitions(kernel_writes_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE) + target_compile_options(kernel_writes_test PRIVATE /W4 /permissive- /utf-8) + + # title_write_watch (src/title_page_watch.h): the journal that shares write-watch answers between trackers. + add_executable(title_write_watch_test test/title_write_watch_test.cpp) + target_compile_definitions(title_write_watch_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE) + target_compile_options(title_write_watch_test PRIVATE /W4 /permissive- /utf-8) + + # Console model in the registry (ConsoleMode) against LEONIDA_DEVICE_TYPE. + add_executable(console_registry_test + test/console_registry_test.cpp + shims/console_registry.cpp + shims/registry.cpp + ) + target_include_directories(console_registry_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) + target_compile_definitions(console_registry_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(console_registry_test PRIVATE /W4 /permissive- /utf-8) + target_link_options(console_registry_test PRIVATE /OPT:NOREF) + # Synthetic tests for the atomic API reference lifecycle. add_executable(api_ref_state_test test/api_ref_state_test.cpp) target_include_directories(api_ref_state_test PRIVATE @@ -544,6 +636,20 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) FetchContent_MakeAvailable(SDL3) endif() endif() + if(NOT (LEONIDA_SDL3 AND TARGET SDL3::SDL3-static)) + # Nothing served gameinput.dll in a build without SDL3, so the loader fell through to the host's gameinput.dll and + # that one answers GameInputCreate with a null interface the title dereferences. Keep the object identity honest. + target_sources(gta6rt PRIVATE shims/gameinput_no_sdl.cpp) + add_executable(gameinput_no_sdl_test + test/gameinput_no_sdl_test.cpp + shims/gameinput_no_sdl.cpp + shims/registry.cpp + ) + target_include_directories(gameinput_no_sdl_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) + target_compile_definitions(gameinput_no_sdl_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(gameinput_no_sdl_test PRIVATE /W4 /permissive- /utf-8) + target_link_options(gameinput_no_sdl_test PRIVATE /OPT:NOREF) + endif() if(LEONIDA_SDL3 AND TARGET SDL3::SDL3-static) target_sources(gta6rt PRIVATE shims/gameinput.cpp) target_link_libraries(gta6rt PRIVATE SDL3::SDL3-static) @@ -579,6 +685,9 @@ if(BUILD_TESTING) add_executable(gfx10_tiling_test test/gfx10_tiling_test.cpp) add_test(NAME gfx10_tiling COMMAND gfx10_tiling_test) + add_executable(d3d12_xs_frame_events_test test/d3d12_xs_frame_events_test.cpp) + add_test(NAME d3d12_xs_frame_events COMMAND d3d12_xs_frame_events_test) + add_executable(retire_tickets_test test/retire_tickets_test.cpp) add_test(NAME retire_tickets COMMAND retire_tickets_test) # VulkanContext::buffer_at's VA index (runtime/src/buffer_va_index.h): pure stdlib, no Vulkan instance. @@ -588,9 +697,25 @@ if(BUILD_TESTING) add_executable(xbox_present_readback_size_test test/xbox_present_readback_size_test.cpp) add_test(NAME xbox_present_readback_size COMMAND xbox_present_readback_size_test) + # The title's own window, where PresentX shows its frames (shims/title_window.h): user32 only, no device. + if(WIN32) + add_executable(title_window_test test/title_window_test.cpp) + target_include_directories(title_window_test PRIVATE shims) + target_compile_definitions(title_window_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE) + if(MSVC) + target_compile_options(title_window_test PRIVATE /W4 /permissive- /utf-8) + endif() + target_link_libraries(title_window_test PRIVATE user32) + add_test(NAME title_window COMMAND title_window_test) + endif() + add_executable(pipeline_cache_file_test test/pipeline_cache_file_test.cpp) add_test(NAME pipeline_cache_file COMMAND pipeline_cache_file_test) + # D3D-704's session-cache limit and header check: pure stdlib, no Vulkan headers. + add_executable(pipeline_cache_store_test test/pipeline_cache_store_test.cpp) + add_test(NAME pipeline_cache_store COMMAND pipeline_cache_store_test) + add_executable(xdxr_build_output_test test/xdxr_build_output_test.cpp) add_test(NAME xdxr_build_output COMMAND xdxr_build_output_test) @@ -717,6 +842,7 @@ if(BUILD_TESTING) shims/xmem.cpp shims/d3d12_xs.cpp shims/d3d12_xs_device.cpp + shims/d3d12_xs_pso_stream.cpp ) target_include_directories(pe_loader_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src @@ -869,6 +995,7 @@ if(BUILD_TESTING) shims/xmem.cpp shims/d3d12_xs.cpp shims/d3d12_xs_device.cpp + shims/d3d12_xs_pso_stream.cpp ) target_include_directories(test_pe_loader_bounds PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src @@ -893,6 +1020,7 @@ if(BUILD_TESTING) shims/xmem.cpp shims/d3d12_xs.cpp shims/d3d12_xs_device.cpp + shims/d3d12_xs_pso_stream.cpp ) target_include_directories(pe_loader_fuzz PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src @@ -978,6 +1106,61 @@ if(BUILD_TESTING) COMMAND loader_tls_test "$" ) + # Module TLS index 0 fixture: an EXE built /GA, so its thread_local reads go straight to + # ThreadLocalStoragePointer[0] as a game executable's can. The loader must give a mapped executable index 0; + # loader_tls_index0_test maps it next to tiny_tls.dll and run_tiny_tls_ga runs it under gta6rt. Ordinary test + # code, no game data. The test checks the /GA code shape only where the compiler is MSVC, which implements /GA. + add_executable(tiny_tls_ga test/fixtures/tiny_tls_ga.cpp) + target_compile_options(tiny_tls_ga PRIVATE /W4 /permissive- /utf-8 /EHsc /GA) + set_target_properties(tiny_tls_ga PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" + ARCHIVE_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" + ) + add_executable(loader_tls_index0_test + test/loader_tls_index0_test.cpp + src/pe_loader.cpp + shims/registry.cpp + ) + target_include_directories(loader_tls_index0_test PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/src + ) + target_compile_definitions(loader_tls_index0_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + $<$:LEONIDA_GA_FIXTURE_IS_GA=1>) + target_compile_options(loader_tls_index0_test PRIVATE /W4 /permissive- /utf-8 /EHsc) + # Loaded by the threads scenario before the TLS helper: its DllMain(DLL_THREAD_ATTACH) runs test code first. + add_library(tiny_thread_hook SHARED test/fixtures/tiny_thread_hook.cpp) + target_compile_definitions(tiny_thread_hook PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(tiny_thread_hook PRIVATE /W4 /permissive- /utf-8 /GS-) + set_target_properties(tiny_thread_hook PROPERTIES + OUTPUT_NAME tiny_thread_hook + PREFIX "" + RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" + ARCHIVE_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" + ) + add_dependencies(loader_tls_index0_test tiny_tls_ga tiny_tls tiny_thread_hook gta6rt_tls_host) + # Imports tiny_tls.dll and tiny_tls_cb_only.dll, so gta6rt needs a helper clone for one of them + # (check_tls_clone_cleanup.cmake). + add_executable(tiny_tls_clones test/fixtures/tiny_tls_clones.cpp) + target_link_libraries(tiny_tls_clones PRIVATE tiny_tls tiny_tls_cb_only) + target_compile_options(tiny_tls_clones PRIVATE /W4 /permissive- /utf-8) + set_target_properties(tiny_tls_clones PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" + ARCHIVE_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" + ) + # One process per scenario: the reservation is once per process. loader_tls_index0 (runs) reserves at start, + # loader_tls_index0_threads reserves while threads are being created, loader_tls_index0_noreserve never does. + foreach(scenario runs threads noreserve) + if(scenario STREQUAL "runs") + set(name loader_tls_index0) + else() + set(name loader_tls_index0_${scenario}) + endif() + add_test(NAME ${name} + COMMAND loader_tls_index0_test ${scenario} "$" "$" + "$" + ) + endforeach() + # DisableThreadLibraryCalls from a mapped DllMain (shims/library_loader.cpp). The fixture is built without the CRT, so # DllMain's only work is that one call. No game files. add_library(dll_thread_calls SHARED test/fixtures/dll_thread_calls.cpp) @@ -1100,8 +1283,21 @@ if(BUILD_TESTING) # The routes are read once per process, so each override case is its own test. add_test(NAME xs_proxy_mock_env_slots COMMAND xs_proxy_mock_test --env-slots) add_test(NAME xs_proxy_mock_env_slots_invalid COMMAND xs_proxy_mock_test --env-slots-invalid) + add_test(NAME xs_proxy_mock_env_slots_70 COMMAND xs_proxy_mock_test --env-slots-70) add_test(NAME xs_proxy_mock_env_slots_74 COMMAND xs_proxy_mock_test --env-slots-74) endif() + add_executable(pso_stream_test + test/pso_stream_test.cpp + shims/d3d12_xs_pso_stream.cpp + ) + target_include_directories(pso_stream_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) + target_compile_definitions(pso_stream_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(pso_stream_test PRIVATE /W4 /permissive- /utf-8) + target_link_options(pso_stream_test PRIVATE /OPT:NOREF) + if(TARGET pso_stream_test) + add_test(NAME pso_stream COMMAND pso_stream_test) + endif() + if(TARGET root_sig_test) add_test(NAME root_sig COMMAND root_sig_test) endif() @@ -1187,6 +1383,7 @@ if(BUILD_TESTING) shims/xmem.cpp shims/d3d12_xs.cpp shims/d3d12_xs_device.cpp + shims/d3d12_xs_pso_stream.cpp ) target_compile_definitions(fsr_dispatch_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS) target_compile_options(fsr_dispatch_test PRIVATE /W4 /permissive- /EHsc /utf-8) @@ -1204,6 +1401,7 @@ if(BUILD_TESTING) shims/xmem.cpp shims/d3d12_xs.cpp shims/d3d12_xs_device.cpp + shims/d3d12_xs_pso_stream.cpp ) target_compile_definitions(bvh_builder_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS) target_compile_options(bvh_builder_test PRIVATE /W4 /permissive- /EHsc /utf-8) @@ -1230,8 +1428,17 @@ if(BUILD_TESTING) add_test(NAME bink_audio COMMAND bink_audio_test) set_tests_properties(bink_audio PROPERTIES SKIP_RETURN_CODE 77) endif() + if(WIN32 AND TARGET clzero_patch_test) + add_test(NAME clzero_patch COMMAND clzero_patch_test) + endif() if(WIN32 AND TARGET xmem_test) add_test(NAME xmem COMMAND xmem_test) + # The same with write watching off: no reservation is write-watched for the shadows. + add_test(NAME xmem_no_write_watch COMMAND xmem_test) + set_tests_properties(xmem_no_write_watch PROPERTIES ENVIRONMENT "LEONIDA_WRITE_WATCH=0") + # And with it on whatever the host's default (off under Wine). + add_test(NAME xmem_write_watch COMMAND xmem_test) + set_tests_properties(xmem_write_watch PROPERTIES ENVIRONMENT "LEONIDA_WRITE_WATCH=1") endif() if(WIN32 AND TARGET xg_xs_test) add_test(NAME xg_xs COMMAND xg_xs_test) @@ -1246,6 +1453,12 @@ if(BUILD_TESTING) if(WIN32 AND TARGET xapu_chad_test) add_test(NAME xapu_chad COMMAND xapu_chad_test) endif() + if(WIN32 AND TARGET xapu_test) + add_test(NAME xapu COMMAND xapu_test) + endif() + if(WIN32 AND TARGET chad_test) + add_test(NAME chad COMMAND chad_test) + endif() if(WIN32 AND TARGET process_cmdline_test) add_test(NAME process_cmdline COMMAND process_cmdline_test) endif() @@ -1269,6 +1482,21 @@ if(BUILD_TESTING) add_test(NAME bcrypt_rng_seeded COMMAND bcrypt_rng_test --seeded) set_tests_properties(bcrypt_rng_seeded PROPERTIES ENVIRONMENT "LEONIDA_RNG_SEED=0x123456789abcdef0") endif() + if(WIN32 AND TARGET kernel_writes_test) + add_test(NAME kernel_writes COMMAND kernel_writes_test) + endif() + if(WIN32 AND TARGET title_write_watch_test) + add_test(NAME title_write_watch COMMAND title_write_watch_test) + add_test(NAME title_write_watch_on COMMAND title_write_watch_test) + set_tests_properties(title_write_watch_on PROPERTIES ENVIRONMENT "LEONIDA_WRITE_WATCH=1") + endif() + if(WIN32 AND TARGET thread_stacks_test) + add_test(NAME thread_stacks COMMAND thread_stacks_test) + set_tests_properties(thread_stacks PROPERTIES TIMEOUT 60) + endif() + if(WIN32 AND TARGET console_registry_test) + add_test(NAME console_registry COMMAND console_registry_test) + endif() if(WIN32 AND TARGET api_ref_state_test) add_test(NAME api_ref_state COMMAND api_ref_state_test) set_tests_properties(api_ref_state PROPERTIES TIMEOUT 30) @@ -1338,6 +1566,9 @@ if(BUILD_TESTING) target_compile_options(active_input_test PRIVATE /W4 /permissive- /utf-8) endif() add_test(NAME active_input COMMAND active_input_test) + if(WIN32 AND TARGET gameinput_no_sdl_test) + add_test(NAME gameinput_no_sdl COMMAND gameinput_no_sdl_test) + endif() if(WIN32 AND TARGET gameinput_test) add_test(NAME gameinput COMMAND gameinput_test) add_test(NAME gameinput_script COMMAND gameinput_test --input-script) @@ -1409,6 +1640,15 @@ if(BUILD_TESTING) "-DTOOL=$" "-DWANT=${GTA6RT_STACK}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_stack_reserve.cmake") add_test(NAME run_tiny_game_stack COMMAND gta6rt --run $ -- hello 42 stack) + # A /GA executable under --run and --init reads its TLS from slot 0, and the trace names gta6rt.exe as the image + # whose index 0 moved. + add_test(NAME run_tiny_tls_ga COMMAND ${CMAKE_COMMAND} + "-DLOADER=$" "-DGUEST=$" "-DTRACE_DIR=${CMAKE_CURRENT_BINARY_DIR}" + "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_tls_index0.cmake") + # Clone files are deleted when gta6rt exits normally; only the home clone outlives the run, until the next one. + add_test(NAME run_tiny_tls_clone_cleanup COMMAND ${CMAKE_COMMAND} + "-DLOADER=$" "-DGUEST=$" "-DTRACE_DIR=${CMAKE_CURRENT_BINARY_DIR}" + "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_tls_clone_cleanup.cmake") # GAME: is the game folder, absolute, when gta6rt is given a bare image name or `--game-dir .`. add_test(NAME run_tiny_game_dir COMMAND ${CMAKE_COMMAND} "-DLOADER=$" "-DGUEST=$" @@ -1434,6 +1674,7 @@ if(LEONIDA_D3D12_SHIM_TESTS) shims/d3d12_xs.cpp shims/registry.cpp shims/d3d12_xs_device.cpp + shims/d3d12_xs_pso_stream.cpp ) target_include_directories(d3d12_xs_root_signature_test PRIVATE shims) target_compile_definitions(d3d12_xs_root_signature_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) @@ -1483,6 +1724,10 @@ if(NOT TARGET Vulkan::Headers) endif() endif() if(TARGET Vulkan::Headers) + add_executable(vulkan_device_fault_test test/vulkan_device_fault_test.cpp) + target_link_libraries(vulkan_device_fault_test PRIVATE Vulkan::Headers) + add_test(NAME vulkan_device_fault COMMAND vulkan_device_fault_test) + foreach(tool vk_harness vk_ps_sweep vk_texture_test vk_sampler_test vk_compute_test vk_store_test vk_pipeline_check vk_command_replay_test vk_bindless_test vk_image_fuzz vk_descriptor_bench depth24_convert_test vk_predicate_capture_test vk_predicated_copy_test vk_xdxr_build_test vk_queue_test vk_sandbox) @@ -1668,6 +1913,20 @@ if(TARGET Vulkan::Headers) add_test(NAME vk_fence_dispatcher_sync COMMAND vk_fence_dispatcher_sync_test) set_tests_properties(vk_fence_dispatcher_sync PROPERTIES SKIP_RETURN_CODE 77) endif() + # The bindless set under view churn (bounded table, spare generations) and failed allocations (host table, in-place + # rewrite, a degraded flush instead of a refused submission). + add_executable(vk_bindless_grow_test test/vk_bindless_grow_test.cpp) + target_link_libraries(vk_bindless_grow_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) + if(WIN32) + target_compile_definitions(vk_bindless_grow_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + endif() + if(MSVC) + target_compile_options(vk_bindless_grow_test PRIVATE /W4 /permissive- /utf-8) + endif() + if(BUILD_TESTING) + add_test(NAME vk_bindless_grow COMMAND vk_bindless_grow_test) + set_tests_properties(vk_bindless_grow PROPERTIES SKIP_RETURN_CODE 77) + endif() # CPU-only: the bindless set's array sizes from synthetic device limits. add_executable(bindless_sizing_test test/bindless_sizing_test.cpp) target_link_libraries(bindless_sizing_test PRIVATE Vulkan::Headers) @@ -1802,10 +2061,10 @@ if(TARGET Vulkan::Headers) DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/../tools/gen_d3d12_stubs.py ${LEONIDA_D3D12_HEADER} COMMENT "Generating D3D12 COM stubs" VERBATIM) - add_library(gta6rt_d3d12_com STATIC shims/d3d12_com.cpp shims/d3d12_vulkan_device.cpp shims/d3d12_xs_device.cpp shims/xbox_present.cpp - shims/dxgi_com.cpp ${LEONIDA_STUBS}) # d3d12_vulkan_device.cpp reads the PC device behind the proxy (#224) + add_library(gta6rt_d3d12_com STATIC shims/d3d12_com.cpp shims/d3d12_vulkan_device.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp shims/xbox_present.cpp + shims/dxgi_com.cpp shims/package_splash.cpp ${LEONIDA_STUBS}) # d3d12_vulkan_device.cpp reads the PC device behind the proxy (#224) target_include_directories(gta6rt_d3d12_com PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/generated) - target_link_libraries(gta6rt_d3d12_com PUBLIC Vulkan::Headers gta6rt_root_signature) + target_link_libraries(gta6rt_d3d12_com PUBLIC Vulkan::Headers gta6rt_root_signature PRIVATE ole32 windowscodecs xmllite shlwapi user32 gdi32) target_compile_definitions(gta6rt_d3d12_com PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) # /bigobj: a Debug build of d3d12_vulkan_device.cpp has more sections than a COFF object holds by default # (fatal error C1128), because without optimisation every inline function keeps its own COMDAT. @@ -1929,6 +2188,24 @@ if(TARGET Vulkan::Headers) set_tests_properties(d3d12_xdxr_rt_check PROPERTIES FIXTURES_REQUIRED d3d12_xdxr_cases SKIP_RETURN_CODE 77) endif() + # XboxBvhBuilder.dll served by the layer's builder (RT-5, boot stop 18): the seven exports the executable imports, + # through the shim registry as the title binds them; the structures are checked like d3d12_xdxr_rt's. + set(LEONIDA_XBOX_BVH_BUILDER_OUT "${CMAKE_CURRENT_BINARY_DIR}/xbox_bvh_builder_cases") + add_executable(xbox_bvh_builder_test test/xbox_bvh_builder_test.cpp shims/xbox_bvh_builder.cpp shims/registry.cpp) + target_link_libraries(xbox_bvh_builder_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(xbox_bvh_builder_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(xbox_bvh_builder_test PRIVATE /W4 /permissive- /utf-8) + target_link_options(xbox_bvh_builder_test PRIVATE /OPT:NOREF) + add_test(NAME xbox_bvh_builder COMMAND xbox_bvh_builder_test "${LEONIDA_XBOX_BVH_BUILDER_OUT}") + set_tests_properties(xbox_bvh_builder PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60 FIXTURES_SETUP xbox_bvh_builder_cases) + add_test(NAME xbox_bvh_builder_console COMMAND xbox_bvh_builder_test --console) + set_tests_properties(xbox_bvh_builder_console PROPERTIES ENVIRONMENT "LEONIDA_BVH_BUILDER=console") + if(Python3_FOUND) + add_test(NAME xbox_bvh_builder_check COMMAND "${Python3_EXECUTABLE}" -I + "${CMAKE_CURRENT_SOURCE_DIR}/../tools/xdxr_bvh.py" check-build "${LEONIDA_XBOX_BVH_BUILDER_OUT}" --rays 1000) + set_tests_properties(xbox_bvh_builder_check PROPERTIES FIXTURES_REQUIRED xbox_bvh_builder_cases SKIP_RETURN_CODE 77) + endif() + # GCL8's QueryInterface and its one method need an allocator and a list, not a Vulkan device. add_executable(d3d12_gcl8_test test/d3d12_gcl8_test.cpp) target_link_libraries(d3d12_gcl8_test PRIVATE gta6rt_d3d12_com) @@ -2108,6 +2385,14 @@ if(TARGET Vulkan::Headers) target_compile_options(d3d12_existing_heap_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_existing_heap COMMAND d3d12_existing_heap_test) set_tests_properties(d3d12_existing_heap PROPERTIES SKIP_RETURN_CODE 77) + # The same with write watching off: the guarded cases only, the concurrent writers among them. + add_test(NAME d3d12_existing_heap_no_write_watch COMMAND d3d12_existing_heap_test) + set_tests_properties(d3d12_existing_heap_no_write_watch PROPERTIES SKIP_RETURN_CODE 77 + ENVIRONMENT "LEONIDA_WRITE_WATCH=0") + # And with it on whatever the host's default (off under Wine). + add_test(NAME d3d12_existing_heap_write_watch COMMAND d3d12_existing_heap_test) + set_tests_properties(d3d12_existing_heap_write_watch PROPERTIES SKIP_RETURN_CODE 77 + ENVIRONMENT "LEONIDA_WRITE_WATCH=1") # Slot 133 on untouched xmem physical pages: committed through the pages hook, then imported. xmem.cpp and # registry.cpp are compiled in, as xmem_test does, to reach the registered XMem* exports. add_executable(d3d12_xmem_placed_test test/d3d12_xmem_placed_test.cpp shims/xmem.cpp shims/registry.cpp) @@ -2333,6 +2618,12 @@ if(TARGET Vulkan::Headers) target_compile_options(d3d12_texture1d_target_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_texture1d_target COMMAND d3d12_texture1d_target_test) set_tests_properties(d3d12_texture1d_target PROPERTIES SKIP_RETURN_CODE 77) # no Vulkan GPU, or Wine + add_executable(d3d12_a8_dimensions_test test/d3d12_a8_dimensions_test.cpp) + target_link_libraries(d3d12_a8_dimensions_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_a8_dimensions_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_a8_dimensions_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_a8_dimensions COMMAND d3d12_a8_dimensions_test) + set_tests_properties(d3d12_a8_dimensions PROPERTIES SKIP_RETURN_CODE 77) # no Vulkan GPU, or Wine # ArraySize -1 in array RTVs and DSVs (every slice from the first on), against the host on the same adapter # and WARP. @@ -2450,6 +2741,14 @@ if(TARGET Vulkan::Headers) add_test(NAME d3d12_typeless_depth COMMAND d3d12_typeless_depth_test) set_tests_properties(d3d12_typeless_depth PROPERTIES SKIP_RETURN_CODE 77) + # Manifest selection, aspect-fit decoding and Vulkan upload of a synthetic package splash. + add_executable(package_splash_test test/package_splash_test.cpp) + target_link_libraries(package_splash_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(package_splash_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(package_splash_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME package_splash COMMAND package_splash_test) + set_tests_properties(package_splash PROPERTIES SKIP_RETURN_CODE 77) + # WriteToSubresource/ReadFromSubresource arguments and bytes, compared with the host runtime. add_executable(d3d12_subresource_copy_test test/d3d12_subresource_copy_test.cpp) target_link_libraries(d3d12_subresource_copy_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) @@ -2491,7 +2790,7 @@ if(TARGET Vulkan::Headers) set_tests_properties(d3d12_present PROPERTIES SKIP_RETURN_CODE 77) # Per-pipeline --f16-interp-fallback linking (SHADER-378): 16-param VS + colliding PS rendered on Vulkan. - add_executable(d3d12_f16_halves_test test/d3d12_f16_halves_test.cpp shims/d3d12_xs_device.cpp) + add_executable(d3d12_f16_halves_test test/d3d12_f16_halves_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp) target_link_libraries(d3d12_f16_halves_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) target_compile_definitions(d3d12_f16_halves_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) target_compile_options(d3d12_f16_halves_test PRIVATE /W4 /permissive- /utf-8) @@ -2505,7 +2804,10 @@ if(TARGET Vulkan::Headers) target_compile_options(xbox_present_test PRIVATE /W4 /permissive- /utf-8) # Needs a Vulkan GPU and a window; exits 77 (skipped) without a Vulkan device. add_test(NAME xbox_present COMMAND xbox_present_test) - set_tests_properties(xbox_present PROPERTIES SKIP_RETURN_CODE 77) + # The test pins plane 1's composition on its overlay flag (section 4.5). The runtime's default blends plane 1 over + # plane 0 whatever its flags (696d00286: the retail title presents both planes with Flags 0); + # LEONIDA_PRESENT_PLANE1=0 is that rule's switch back. + set_tests_properties(xbox_present PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_PRESENT_PLANE1=0") # TEST-528: a real boot-movie frame (the package's Bink2Scarlett.dll) uploaded through the Xbox-ABI proxy and # presented with PresentX, checked against the decoded BGRA. Package-gated like bink_decode_test: skips (77) @@ -2527,7 +2829,7 @@ if(TARGET Vulkan::Headers) # First light through D3D12 (docs/first_light.md): the real model and translated VS/PS that tools/first_light.py # wrote to LEONIDA_FIRST_LIGHT_DIR, drawn through the device proxy. Skips (77) unless that variable is set. - add_executable(d3d12_first_light_test test/d3d12_first_light_test.cpp shims/d3d12_xs_device.cpp) + add_executable(d3d12_first_light_test test/d3d12_first_light_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp) target_link_libraries(d3d12_first_light_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_first_light_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS) target_compile_options(d3d12_first_light_test PRIVATE /W4 /permissive- /utf-8) @@ -2574,6 +2876,15 @@ if(TARGET Vulkan::Headers) add_test(NAME d3d12_translated_draw COMMAND d3d12_translated_draw_test) set_tests_properties(d3d12_translated_draw PROPERTIES SKIP_RETURN_CODE 77) + # The console's rectangle and quad lists (src/rect_list_geometry.h), through the same translated vs_m15 / ps_m15. + add_executable(d3d12_rect_list_test test/d3d12_rect_list_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_M15_FILES}) + target_link_libraries(d3d12_rect_list_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_rect_list_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_M15_DIR="${LEONIDA_M15_DIR}") + target_compile_options(d3d12_rect_list_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_rect_list COMMAND d3d12_rect_list_test) + set_tests_properties(d3d12_rect_list PROPERTIES SKIP_RETURN_CODE 77) + # vk_bindless_test (the bindless set and its table at the Vulkan level, no D3D12) takes the translated vs_ids, # ps_tex and ps_imgatomic; it was only run by scripts/run_gpu_tests.py and check.py until D3D-314 needed it. set(LEONIDA_BINDLESS_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/bindless_shaders) @@ -2675,7 +2986,7 @@ if(TARGET Vulkan::Headers) ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_m3_query.asm COMMENT "Translating M3 frame and single-output occlusion-probe shaders" VERBATIM) - add_executable(d3d12_m3_frame_test test/d3d12_m3_frame_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_M3_FILES}) + add_executable(d3d12_m3_frame_test test/d3d12_m3_frame_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_M3_FILES}) target_link_libraries(d3d12_m3_frame_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_m3_frame_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_TEST_M3_DIR="${LEONIDA_M3_DIR}") @@ -2706,7 +3017,7 @@ if(TARGET Vulkan::Headers) ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/cs_m4_indirect.asm COMMENT "Translating cs_m4_fill and cs_m4_indirect for the compute test" VERBATIM) - add_executable(d3d12_m4_compute_test test/d3d12_m4_compute_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_M4_FILES}) + add_executable(d3d12_m4_compute_test test/d3d12_m4_compute_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_M4_FILES}) target_link_libraries(d3d12_m4_compute_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_m4_compute_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_TEST_M4_DIR="${LEONIDA_M4_DIR}") @@ -2734,7 +3045,7 @@ if(TARGET Vulkan::Headers) ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/cs_buf_counter.asm COMMENT "Translating cs_buf_typed and cs_buf_counter for the buffer UAV test" VERBATIM) - add_executable(d3d12_buffer_uav_test test/d3d12_buffer_uav_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_BUFFER_UAV_FILES}) + add_executable(d3d12_buffer_uav_test test/d3d12_buffer_uav_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_BUFFER_UAV_FILES}) target_link_libraries(d3d12_buffer_uav_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_buffer_uav_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_TEST_BUFFER_UAV_DIR="${LEONIDA_BUFFER_UAV_DIR}") @@ -2757,7 +3068,8 @@ if(TARGET Vulkan::Headers) # aliasing / §3.3 backing coverage. add_executable(d3d12_console_descriptor_heap_test test/d3d12_console_descriptor_heap_test.cpp shims/d3d12_xs_device.cpp) target_link_libraries(d3d12_console_descriptor_heap_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_console_descriptor_heap_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + # LEONIDA_VULKAN_DEVICE: slot 14 creates the console heap on the Vulkan device it links, as in gta6rt. + target_compile_definitions(d3d12_console_descriptor_heap_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_VULKAN_DEVICE) target_compile_options(d3d12_console_descriptor_heap_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_console_descriptor_heap COMMAND d3d12_console_descriptor_heap_test) set_tests_properties(d3d12_console_descriptor_heap PROPERTIES SKIP_RETURN_CODE 77) @@ -2889,15 +3201,25 @@ if(TARGET Vulkan::Headers) DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_user_data.comp COMMENT "Compiling the compute test shader" VERBATIM) - add_executable(d3d12_compute_test test/d3d12_compute_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_TEST_CS}) + add_executable(d3d12_compute_test test/d3d12_compute_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_TEST_CS}) target_link_libraries(d3d12_compute_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_compute_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_TEST_CS_SPV="${LEONIDA_TEST_CS}") target_compile_options(d3d12_compute_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_compute COMMAND d3d12_compute_test) set_tests_properties(d3d12_compute PROPERTIES SKIP_RETURN_CODE 77) + # A buffer at the title's own VA (device slot 133) read by the same shader through a root view and a V#. + add_executable(d3d12_title_va_test test/d3d12_title_va_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_TEST_CS}) + target_link_libraries(d3d12_title_va_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_title_va_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_CS_SPV="${LEONIDA_TEST_CS}") + target_compile_options(d3d12_title_va_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_title_va COMMAND d3d12_title_va_test) + add_test(NAME d3d12_geometry_views COMMAND d3d12_title_va_test) + set_tests_properties(d3d12_geometry_views PROPERTIES ENVIRONMENT "LEONIDA_GEOMETRY_MB=16" SKIP_RETURN_CODE 77) + set_tests_properties(d3d12_title_va PROPERTIES SKIP_RETURN_CODE 77) # Compute PSOs from FSPX programs (docs/fspx.md): an ACCC container at slot 62 and a bare kind-6 program. - add_executable(d3d12_fspx_compute_test test/d3d12_fspx_compute_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_TEST_CS}) + add_executable(d3d12_fspx_compute_test test/d3d12_fspx_compute_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_TEST_CS}) target_link_libraries(d3d12_fspx_compute_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_fspx_compute_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_TEST_CS_SPV="${LEONIDA_TEST_CS}") @@ -2924,7 +3246,7 @@ if(TARGET Vulkan::Headers) COMMENT "Compiling the draw test shader ${source}" VERBATIM) endforeach() - add_executable(d3d12_draw_test test/d3d12_draw_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_TEST_VS} + add_executable(d3d12_draw_test test/d3d12_draw_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_TEST_VS} ${LEONIDA_TEST_PS} ${LEONIDA_TEST_PS_UINT} ${LEONIDA_TEST_VS_FULLSCREEN} ${LEONIDA_TEST_VS_INT}) target_link_libraries(d3d12_draw_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_draw_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX @@ -2934,7 +3256,16 @@ if(TARGET Vulkan::Headers) LEONIDA_TEST_VS_INT_SPV="${LEONIDA_TEST_VS_INT}") target_compile_options(d3d12_draw_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_draw COMMAND d3d12_draw_test) - set_tests_properties(d3d12_draw PROPERTIES SKIP_RETURN_CODE 77) + add_test(NAME d3d12_title_index_window COMMAND d3d12_draw_test --title-index-window) + add_test(NAME d3d12_title_vertex_window COMMAND d3d12_draw_test --title-vertex-window) + # LEONIDA_STUB_PIPELINES: a pipeline with no translated shader is a no-op stub when the switch is on. + add_executable(d3d12_stub_pipelines_test test/d3d12_stub_pipelines_test.cpp) + target_link_libraries(d3d12_stub_pipelines_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_stub_pipelines_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_stub_pipelines_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_stub_pipelines COMMAND d3d12_stub_pipelines_test) + set_tests_properties(d3d12_stub_pipelines PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30) + set_tests_properties(d3d12_draw d3d12_title_index_window d3d12_title_vertex_window PROPERTIES SKIP_RETURN_CODE 77) # Graphics & compute PSO descriptor validation parity against live Windows D3D12 (WARP and HW). add_executable(d3d12_pso_validation_test test/d3d12_pso_validation_test.cpp ${LEONIDA_TEST_VS} ${LEONIDA_TEST_PS} ${LEONIDA_TEST_PS_UINT} ${LEONIDA_TEST_VS_FULLSCREEN} ${LEONIDA_TEST_CS}) @@ -2946,8 +3277,11 @@ if(TARGET Vulkan::Headers) LEONIDA_TEST_CS_SPV="${LEONIDA_TEST_CS}") target_compile_options(d3d12_pso_validation_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_pso_validation COMMAND d3d12_pso_validation_test) + # LEONIDA_COMPUTE_WARMUP=0: the warm-up thread of lazy compute pipelines (9d15c13a0) may still be building one + # when this test releases its device and exits, and the process then dies after its PASS line (exit 3 under + # Wine). The race is the warm-up thread's, not the validation's; see MERGE-NOTES. set_tests_properties(d3d12_pso_validation PROPERTIES SKIP_RETURN_CODE 77 - FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") + FAIL_REGULAR_EXPRESSION "Validation Error;VUID-" ENVIRONMENT "LEONIDA_COMPUTE_WARMUP=0") # Conservative raster Tier 1, with geometric coverage bounds and host D3D12 references. set(LEONIDA_CONSERVATIVE_VS ${CMAKE_CURRENT_BINARY_DIR}/generated/vs_conservative.spv) set(LEONIDA_CONSERVATIVE_PS ${CMAKE_CURRENT_BINARY_DIR}/generated/ps_conservative.spv) @@ -3022,6 +3356,32 @@ if(TARGET Vulkan::Headers) target_compile_options(d3d12_geometry_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_geometry COMMAND d3d12_geometry_test) set_tests_properties(d3d12_geometry PROPERTIES SKIP_RETURN_CODE 77) + # Directly indexed heaps for draws: the VS and PS read the heap dwords after the explicit root arguments. + set(LEONIDA_TEST_VS_USER_DATA_WINDOW ${CMAKE_CURRENT_BINARY_DIR}/generated/vs_user_data_window.spv) + set(LEONIDA_TEST_PS_USER_DATA_WINDOW ${CMAKE_CURRENT_BINARY_DIR}/generated/ps_user_data_window.spv) + foreach(pair "vs_user_data_window.vert;${LEONIDA_TEST_VS_USER_DATA_WINDOW}" + "ps_user_data_window.frag;${LEONIDA_TEST_PS_USER_DATA_WINDOW}") + list(GET pair 0 source) + list(GET pair 1 output) + add_custom_command( + OUTPUT ${output} + COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${output} + ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${source} + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${source} + COMMENT "Compiling the direct heaps test shader ${source}" + VERBATIM) + endforeach() + add_executable(d3d12_graphics_direct_heaps_test test/d3d12_graphics_direct_heaps_test.cpp + shims/d3d12_xs_device.cpp ${LEONIDA_TEST_VS_USER_DATA_WINDOW} ${LEONIDA_TEST_PS_USER_DATA_WINDOW}) + target_link_libraries(d3d12_graphics_direct_heaps_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_graphics_direct_heaps_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_VS_SPV="${LEONIDA_TEST_VS_USER_DATA_WINDOW}" + LEONIDA_TEST_PS_SPV="${LEONIDA_TEST_PS_USER_DATA_WINDOW}") + target_compile_options(d3d12_graphics_direct_heaps_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_graphics_direct_heaps COMMAND d3d12_graphics_direct_heaps_test) + add_test(NAME d3d12_graphics_direct_heaps_off COMMAND d3d12_graphics_direct_heaps_test --off) + set_tests_properties(d3d12_graphics_direct_heaps d3d12_graphics_direct_heaps_off PROPERTIES SKIP_RETURN_CODE 77) + set_tests_properties(d3d12_graphics_direct_heaps_off PROPERTIES ENVIRONMENT LEONIDA_GRAPHICS_DIRECT_HEAPS=0) # D3D-309: D24 depth bias and 24-bit depth in draws, with and without a pixel shader and with a geometry shader # (src/depth24_fragment.h). set(LEONIDA_TEST_VS_DEPTH ${CMAKE_CURRENT_BINARY_DIR}/generated/vs_depth.spv) @@ -3138,11 +3498,21 @@ if(TARGET Vulkan::Headers) DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/ms_draw.mesh COMMENT "Compiling the mesh test shader ms_draw.mesh" VERBATIM) - add_executable(d3d12_mesh_test test/d3d12_mesh_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_TEST_MS} - ${LEONIDA_TEST_PS} ${LEONIDA_TEST_VS_FULLSCREEN}) + # The mesh test's signature is on the s0 fallback layout (see d3d12_mesh_test.cpp), so its pixel shader is + # ps_draw.frag reading the tint VA at s2:s3 instead of s10:s11. + set(LEONIDA_TEST_PS_S0 ${CMAKE_CURRENT_BINARY_DIR}/generated/ps_draw_s0.spv) + add_custom_command( + OUTPUT ${LEONIDA_TEST_PS_S0} + COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -DROOT_BASE=0 -o ${LEONIDA_TEST_PS_S0} + ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/ps_draw.frag + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/ps_draw.frag + COMMENT "Compiling the mesh test's pixel shader ps_draw.frag (s0 layout)" + VERBATIM) + add_executable(d3d12_mesh_test test/d3d12_mesh_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_TEST_MS} + ${LEONIDA_TEST_PS_S0} ${LEONIDA_TEST_VS_FULLSCREEN}) target_link_libraries(d3d12_mesh_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_mesh_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_TEST_MS_SPV="${LEONIDA_TEST_MS}" LEONIDA_TEST_PS_SPV="${LEONIDA_TEST_PS}" + LEONIDA_TEST_MS_SPV="${LEONIDA_TEST_MS}" LEONIDA_TEST_PS_SPV="${LEONIDA_TEST_PS_S0}" LEONIDA_TEST_VS_FULLSCREEN_SPV="${LEONIDA_TEST_VS_FULLSCREEN}") target_compile_options(d3d12_mesh_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_mesh COMMAND d3d12_mesh_test) @@ -3204,7 +3574,7 @@ if(TARGET Vulkan::Headers) VERBATIM) list(APPEND LEONIDA_SG_INDEXES ${output}) endforeach() - add_executable(d3d12_subgroup_test test/d3d12_subgroup_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_SG_INDEXES}) + add_executable(d3d12_subgroup_test test/d3d12_subgroup_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_SG_INDEXES}) target_link_libraries(d3d12_subgroup_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_subgroup_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_TEST_SUBGROUP_SHADERS="${LEONIDA_SG_DIR}") @@ -3234,7 +3604,7 @@ if(TARGET Vulkan::Headers) # The loader can create this device instead of the host's (D3D12XboxCreateDevice, LEONIDA_D3D12=vulkan). if(TARGET gta6rt) - target_link_libraries(gta6rt PRIVATE gta6rt_d3d12_com) + target_link_libraries(gta6rt PRIVATE gta6rt_d3d12_com user32) # user32: the PresentX window target_compile_definitions(gta6rt PRIVATE LEONIDA_VULKAN_DEVICE) # A stand-in title that imports d3d12_xs.dll!D3D12XboxCreateDevice and runs a clear and a readback on the @@ -3436,6 +3806,12 @@ if(TARGET Vulkan::Headers) target_compile_definitions(d3d12_state_map_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) endif() add_test(NAME d3d12_state_map COMMAND d3d12_state_map_test) + add_executable(vulkan_title_image_pool_test test/vulkan_title_image_pool_test.cpp) + target_link_libraries(vulkan_title_image_pool_test PRIVATE Vulkan::Headers) + if(WIN32) + target_compile_definitions(vulkan_title_image_pool_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + endif() + add_test(NAME vulkan_title_image_pool COMMAND vulkan_title_image_pool_test) add_executable(indirect_dispatch_count_alloc_test test/indirect_dispatch_count_alloc_test.cpp) target_link_libraries(indirect_dispatch_count_alloc_test PRIVATE Vulkan::Headers) if(WIN32) @@ -3495,6 +3871,12 @@ if(TARGET Vulkan::Headers) target_link_libraries(arena_size_test PRIVATE Vulkan::Headers) add_test(NAME arena_size COMMAND arena_size_test) # Queue construction cleans its Vulkan handles if holder registration runs out of host memory. + add_executable(vk_host_texture_order_test test/vk_host_texture_order_test.cpp) + target_link_libraries(vk_host_texture_order_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) + if(WIN32) + target_compile_definitions(vk_host_texture_order_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + endif() + add_test(NAME vk_host_texture_order COMMAND vk_host_texture_order_test) add_executable(vk_queue_constructor_oom_test test/vk_queue_constructor_oom_test.cpp) target_link_libraries(vk_queue_constructor_oom_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) if(WIN32) @@ -3514,6 +3896,10 @@ if(TARGET Vulkan::Headers) endif() endif() add_test(NAME vk_xdxr_postbuild_readback COMMAND vk_xdxr_postbuild_readback_test) + + # Title-placed buffer VAs (device slot 133) and the console VA shaders reach them by (src/title_va_alias.h). + add_executable(title_va_alias_test test/title_va_alias_test.cpp) + add_test(NAME title_va_alias COMMAND title_va_alias_test) endif() else() include("${CMAKE_CURRENT_SOURCE_DIR}/cmake/vulkan_headers_missing.cmake") diff --git a/runtime/README.md b/runtime/README.md index f30515a500..c36a39a9fa 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -147,6 +147,16 @@ basename when it has a character outside ASCII (`Loader::find_loaded_module_w`, module names compare case-insensitively with the system's own table (`CompareStringOrdinal`), as Windows compares them; a narrow name outside ASCII compares the same way through the ANSI code page. +The game's code is built for the console's AMD Zen 2 and uses a few of its instructions without asking CPUID: SSE4a +`insertq`/`extrq`, `clzero` and `monitorx`/`mwaitx` (no Intel CPU has them) and `clwb` (Intel since Ice Lake) +([docs/cpu_features.md](../docs/cpu_features.md)). A host without one raises `#UD` there, so `gta6rt` installs a +vectored handler before any image code runs (`src/cpu_emulation.h`): it recognises those encodings at the faulting +address, does the same work on the thread's context and continues after the instruction. It prints one `[rt] cpu:` +line at startup naming what the host lacks, and one the first time each instruction is emulated. On a host that has +them the CPU runs them and the handler never sees them. Each emulated instruction costs an exception round trip, so a +hot loop of them is slow; patching such a site in place is a later step. `cpu_emulation_test` runs every form for +real: natively on a Zen host, through the handler on an Intel one. + `module_names` checks native and mapped renamed DLLs, distinct Unicode identities, basename cache reuse, existing ACP aliases, the wide and case-insensitive lookups, export execution, and path errors. On native Windows with Python available, `run_module_names` compares original renamed EXEs through native execution and `--dry-run`, `--init`, @@ -170,8 +180,28 @@ clone of the helper from `%TEMP%\leonida_tls_host__.dll`, so up to 16 once and a further one is rejected with an error instead of sharing a slot. Images without a TLS directory (or with an all-zero one) load normally. -A `/GA` executable's code reaches its static TLS directly at index 0 (`mov r64, gs:[58h]`), but the -loader can only get that image an index from the OS, and it need not be 0. Before the image's sections +An executable (an image without `IMAGE_FILE_DLL`, the game's EXE under `--run`, `--init` and `--dry-run`) gets +module TLS index 0 instead, as Windows gives the process EXE. MSVC code built with `/GA` relies on that: it reads +`ThreadLocalStoragePointer[0]` directly and never loads `_tls_index`. A `thread_local int v = 42;` EXE built +`/O2 /GA /MD` printed `tls_index=0 value=42` natively but `tls_index=6 value=0` under `gta6rt --run` when it got a +helper's index. Index 0 belongs to `gta6rt.exe` itself (measured: Windows gives it to the process EXE, the trace event +below names it, and `gta6rt.exe` has a 1398-byte TLS template when measured and no TLS callbacks), and all of its own +TLS reads go through `_tls_index`. So `gta6rt.exe` moves off index 0 once, at start (`rt::reserve_tls_index0()`, +called from a CRT initializer that runs before any of gta6rt's own static initializers): it writes one more clone of the +helper, `leonida_tls_host__home.dll`, whose TLS directory covers a copy of `gta6rt.exe`'s template (the +helper carries a 16 KiB array for it), swaps slots 0 and that clone's index on the calling thread and writes the +clone's index into `gta6rt.exe`'s `_tls_index`. Every thread the OS starts from then on has a fresh copy of +`gta6rt.exe`'s TLS at that index from its first instruction, so nothing has to run on a new thread first, including +code that runs in an earlier DLL's `DLL_THREAD_ATTACH`. Slot 0 then holds a block nothing reads, which the executable's +template copy replaces on the loading thread, on threads started later, and through `install_tls_for_thread()` on +older ones, exactly as a DLL's copy replaces a helper's; the OS frees both slots at thread exit. The move cannot be made +later: MSVC keeps the address of a TLS slot in a frame across calls (`zlib_inflate` in `shader_library.h` does), so +a thread that already runs gta6rt's code cannot be moved wherever it is stopped. The startup trace records the move at +the first executable (`tls_index0`). DLLs keep the helper indices and work next to the executable as before. + +When the executable does not get index 0 (the reservation failed, or another executable holds it), its `/GA` code +still reaches its static TLS directly at index 0 (`mov r64, gs:[58h]`), but the loader can only get that image an +index from the OS, and it need not be 0. Before the image's sections are protected and before any of its code runs, TLS callbacks included, the loader rewrites each such slot-0 read in an executable section to the same instruction reading `TEB->TlsSlots[slot]` instead (`patch_ga_tls_reads`), with one `TlsAlloc` slot per image; the rewrite is the same length, so nothing @@ -195,7 +225,19 @@ Current limits, by design: title's callback on, gets its copy from `load()` itself, the way Windows gives one to running threads for a DLL it loads: a block, no `DLL_THREAD_ATTACH`, `DLL_THREAD_DETACH` when it ends, and `~Loader` takes the block back. `install_tls_for_thread()` and `uninstall_tls_for_thread()` are no-ops on such a thread. Mapped DLLs' `DllMain` is not called with thread events. Destroy the `Loader` on the thread that - called `load()`. + called `load()`. As on Windows, a new thread gets every module's copy before any TLS callback runs, and the + executable's callbacks come after the DLLs' ones, for attach and for detach. +- One executable holds index 0 at a time, and only after `reserve_tls_index0()` has run at process start. An + executable mapped without it (the reservation failed, the `Loader` is used without it, or another executable + holds index 0) gets a helper index and a `[rt] loader: ... does not get module TLS index 0` line on stderr: its + `/GA` code would read and write the TLS in slot 0, which is `gta6rt.exe`'s own or the other executable's, so + `--run` and `--init` refuse it with an error and exit code 1, and a `Loader` user must not run its code. +- Threads that ran gta6rt's code before the reservation keep nothing of their TLS: they find a fresh copy at the new + index. In gta6rt only the main thread has run its code by then, and its TLS moves with it. +- The home clone stays loaded until the process ends (freeing it would free `gta6rt.exe`'s TLS blocks), and a mapped + image's file cannot be deleted, so its file stays in `%TEMP%` until the next run's clean-up of dead processes' + clones deletes it. The clones for mapped DLLs are deleted at exit as before. A `gta6rt.exe` whose TLS + outgrows the helper's 16 KiB array is refused the move. - The TOC of the game's RPF archives is encrypted and is not read here. The loader works on the PE files and on any images the caller passes it. @@ -226,7 +268,15 @@ Current limits, by design: Vulkan SDK and Python 3. The Vulkan device covers command submission, descriptor heaps, render-target and depth views, committed resources and copies (uploads, readbacks, BC textures), root signatures, graphics and compute pipeline states, draws, dispatches and `ExecuteIndirect`; see `docs/d3d12_vulkan.md` for what is - missing. + missing. `LEONIDA_DEVICE_FAULT=1` enables a stderr report with supported Vulkan fault information and queue + checkpoints on the first observed device loss. + +- `dstorage_xs.dll` / `xcrdapi.dll` / `dstorage.dll` — `DStorageGetFactory`: the console DirectStorage API + (`shims/dstorage.cpp`, declarations in `shims/dstorage_xs_abi.h`). Files open through the `GAME:` mapping and the + overlay; each queue reads file or memory ranges into memory in order on its own worker thread, inflating zlib + requests (RFC 1950, `src/shader_library.h`'s inflater), and reports through status arrays, `ID3D12Fence` signals + and events. BCPack, swizzle and physical-page requests are not done yet. + See [docs/directstorage.md](../docs/directstorage.md) for the ABI evidence and what is unverified. - `gameinput.dll` / `xgameruntime.dll` — `GameInputCreate`: the v0 GameInput API for gamepads on SDL3 (`shims/gameinput.cpp`), so any controller SDL supports works, with rumble, Xbox trigger rumble, force feedback @@ -246,12 +296,13 @@ document names. | variable | default | what it changes | |---|---|---| -| `LEONIDA_DEVICE_TYPE` | `7` | The `XSystemDeviceType` that `XSystemGetDeviceType` returns: `0` Unknown, `1` Pc, `2` XboxOne, `3` XboxOneS, `4` XboxOneX, `5` XboxOneXDevkit, `6` XboxScarlettLockhart (Series S), `7` XboxScarlettAnaconda (Series X), `8` XboxScarlettDevkit. A number outside 0..8 is ignored; text that is not a number counts as `0`. `6` also makes `XSystemGetAnalyticsInfo` report the form `Xbox Series S` instead of `Xbox Series X`. | +| `LEONIDA_DEVICE_TYPE` | `7` | The `XSystemDeviceType` that `XSystemGetDeviceType` returns: `0` Unknown, `1` Pc, `2` XboxOne, `3` XboxOneS, `4` XboxOneX, `5` XboxOneXDevkit, `6` XboxScarlettLockhart (Series S), `7` XboxScarlettAnaconda (Series X), `8` XboxScarlettDevkit. A number outside 0..8 is ignored; text that is not a number counts as `0`. `6` also makes `XSystemGetAnalyticsInfo` report the form `Xbox Series S` instead of `Xbox Series X`. The title's registry read of `HKLM\Software\Microsoft\Windows NT\CurrentVersion\OEM` `ConsoleMode` is answered from the same setting (`6` → `0x60`, `7` → `0x64`, `8` → `0x68`; the other types have no value, so the host registry is asked), so no registry key has to be written into a Wine prefix or a Windows machine (`docs/runtime_imports.md`, "Console identity in the registry"). | | `LEONIDA_ANALYTICS_FORM` | unset | The `form` string of `XSystemGetAnalyticsInfo`, in place of the one the device type gives (up to 63 characters). | | `LEONIDA_PACKAGE_ID` | `LeonidaPackageIdentifier00000000` | The identifier `XPackageGetCurrentProcessPackageIdentifier` returns (up to 32 characters). It is also the one identifier `XPackageMount` refuses with `E_ACCESSDENIED`, as the game's own package. | | `LEONIDA_CONTENT_PACKAGES` | unset | The content packages `XPackageMount` can mount: `id1=path1;id2=path2` (up to 1,023 characters). The mount path of a listed identifier is its path, as written; any other identifier is `ERROR_NOT_FOUND`, and a path longer than 259 characters is `ERROR_INSUFFICIENT_BUFFER`. | | `LEONIDA_PACKAGED` | `1` | `0`, or text that is not a number, makes `XPackageIsPackagedProcess` return false. Any other number keeps it true. | | `LEONIDA_TITLE_MEMORY_MB` | unset | Caps the title memory limit (in MiB, clamped to `2048..65536`) reported by both `XSystemGetAppMemoryUsageLimit` (`xgameruntime.cpp`) and `XMemGetWorkingSetStatistics` (`xmem.cpp`). Useful on 16 GB RAM / low-VRAM hosts to prevent oversized title pools; invalid or non-positive values are ignored and fall back to the host memory report. | +| `LEONIDA_STACKS` | unset | Comma-separated whole seconds after the title's entry point is called (e.g. `90,180`). At each time `--run` suspends every other thread in turn just long enough to copy its context and stack, then unwinds the copy (title frames through the unwind tables the loader registers) and prints to stderr `[rt] stacks t= thread ():` and up to 40 `#i module+0xRVA` frames, innermost first; a chain identical to an earlier thread's prints `same as thread `. | The two serializer functions and `D3D12XboxCreateDevice` are the only `d3d12_xs` imports used by the shipped DLLs (measured; see `docs/design.md` and `docs/d3d12_vulkan.md`). The game executable's own @@ -446,6 +497,7 @@ from the ANSI code page. | `kind` | When | Fields | |---|---|---| | `trace_open` | first line | `pid` | +| `tls_index0` | the first executable is mapped with module TLS index 0, which gta6rt freed at start (once per process) | `owner` (the image that held index 0, `gta6rt.exe`), `moved_to` (the index its block moved to) | | `map` | a module is mapped, bound and protected | `module`, `base`, `size`, `relocated` | | `tls_callback` | before each TLS callback the Loader runs (process attach and detach; thread events run under the Windows loader lock and are not traced) | `module`, `at` (module+RVA), `reason` | | `dllmain` | after `DllMain(DLL_PROCESS_ATTACH)` returns | `module`, `result` | diff --git a/runtime/cmake/translator_deps.cmake b/runtime/cmake/translator_deps.cmake index 42be0f0e2b..0cb1ecdf86 100644 --- a/runtime/cmake/translator_deps.cmake +++ b/runtime/cmake/translator_deps.cmake @@ -29,6 +29,7 @@ set(LEONIDA_TRANSLATOR_DEPS ${_leonida_repo}/tools/shader_stage_manifest.py ${_leonida_repo}/tools/spirv_asm.py ${_leonida_repo}/tools/spirv_asm_tables.py + ${_leonida_repo}/tools/spirv_loop_guard.py ${_leonida_repo}/tools/spirv_opt.py ${_leonida_repo}/tools/spirv_stubs.py ${_leonida_repo}/tools/vk_subgroup_info.py diff --git a/runtime/shims/chad.cpp b/runtime/shims/chad.cpp new file mode 100644 index 0000000000..011a34c4f2 --- /dev/null +++ b/runtime/shims/chad.cpp @@ -0,0 +1,220 @@ +// chad.dll: Custom Hardware Audio DSP. Hardware-accelerated convolution reverb, FFT and IFFT. +// +// On a PC there is no such DSP hardware. This shim accepts connections and activations, +// records the relevant parameters through the startup trace, and returns success for every +// call. Any submitted command is dropped; its "completion" is reported through the status +// buffer synchronously. +// +// The signatures below come from the public GDK reference (devdocs.xbox.com / docs.xbox.com): +// XDspAudio function reference, handles XDspClientHandle and XDspStreamHandle. +// +// ASSUMPTION: XDspClientHandle and XDspStreamHandle are opaque pointers returned by the +// connect and activate calls respectively. They are never dereferenced by the title +// (only passed back to XDSP functions). A plain heap allocation suffices. +// +// ASSUMPTION: XDspStatus is a structure the title reads to find the last processed command +// sequence. Without a hardware queue the status always reports every submitted command as +// processed. +// +// ASSUMPTION: XDspCommand carries input/output buffers and a frame count. The shim copies +// nothing and reports the command as completed immediately. + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "shims.h" +#include "startup_trace.h" + +namespace { + +// ---- Handle types (opaque) ---- + +struct XDspClient { + uint32_t refcount; + bool connected; + // The registered base buffer (the title's own memory, we just track it) + void* baseBuffer; + uint32_t baseBufferLength; + uint32_t aggregateImpulseResponseInSeconds; + uint32_t maxStreamCount; // set by XDspConnectWithMaximumStreamLimit + uint32_t maxChannelCount; // set by XDspConnectWithMaximumStreamLimit +}; +struct XDspStream {}; + +// ---- Global constants ---- + +constexpr uint32_t kMaxClients = 8; +constexpr uint32_t kMaxStreamsPerClient = 256; +constexpr uint32_t kMaxAggregateImpulseResponse = 128; // seconds + +// ---- Global state ---- + +std::mutex g_chad_mutex; +uint32_t g_client_count = 0; + +// ---- Startup trace helper ---- + +void trace_call(const char* api, const std::string& detail) { + if (!rt::startup_trace::enabled()) return; + static std::mutex mutex; + static std::set seen; + { + std::lock_guard lock(mutex); + if (!seen.insert(api + detail).second) return; + } + rt::startup_trace::event("chad", std::string("\"api\":\"") + api + "\"" + detail); +} + +// ---- XDspConnect ---- +// +// HRESULT XDspConnect(float* baseBuffer, uint32_t baseBufferLength, +// uint32_t aggregateImpulseResponseInSeconds, +// XDspClientHandle* handle) +// +// Not imported by the game (it uses XDspConnectWithMaximumStreamLimit), but provided +// for completeness. + +HRESULT __stdcall XDspConnect(void* baseBuffer, uint32_t baseBufferLength, + uint32_t aggregateImpulseResponseInSeconds, + void** handle) { + // Validate + if (!handle) return E_POINTER; + *handle = nullptr; + // The real title passes baseBufferLength=0 at a measured call site, so accept any size. + if (!baseBuffer || baseBufferLength > 500 * 1024 * 1024) + return E_INVALIDARG; + if (aggregateImpulseResponseInSeconds > kMaxAggregateImpulseResponse) + return 0x8004E402; // XDSP_E_MAX_AGGREGATE_IMPULSE_RESPONSE_EXCEEDED + + std::lock_guard lock(g_chad_mutex); + if (g_client_count >= kMaxClients) + return 0x8004E401; // XDSP_E_MAX_CLIENTS_EXCEEDED + + auto* client = new (std::nothrow) XDspClient{}; + if (!client) return E_OUTOFMEMORY; + client->refcount = 1; + client->connected = true; + client->baseBuffer = baseBuffer; + client->baseBufferLength = baseBufferLength; + client->aggregateImpulseResponseInSeconds = aggregateImpulseResponseInSeconds; + client->maxStreamCount = kMaxStreamsPerClient; + client->maxChannelCount = 2; + ++g_client_count; + *handle = client; + + trace_call("XDspConnect", + ",\"baseBufferLength\":" + std::to_string(baseBufferLength)); + return S_OK; +} + +// ---- XDspConnectWithMaximumStreamLimit ---- +// +// HRESULT XDspConnectWithMaximumStreamLimit(float* baseBuffer, uint32_t baseBufferLength, +// uint32_t aggregateImpulseResponseInSeconds, +// uint32_t maximumStreamCount, +// uint32_t maximumChannelCount, +// XDspClientHandle* handle) + +HRESULT __stdcall XDspConnectWithMaximumStreamLimit(void* baseBuffer, + uint32_t baseBufferLength, + uint32_t aggregateImpulseResponseInSeconds, + uint32_t maximumStreamCount, + uint32_t maximumChannelCount, + void** handle) { + if (!handle) return E_POINTER; + *handle = nullptr; + // A measured call site passes baseBufferLength=0, so accept any size. + if (!baseBuffer || baseBufferLength > 500 * 1024 * 1024) + return E_INVALIDARG; + if (maximumStreamCount == 0 || maximumStreamCount > kMaxStreamsPerClient) + return E_INVALIDARG; + if (maximumChannelCount != 1 && maximumChannelCount != 2) + return E_INVALIDARG; + if (aggregateImpulseResponseInSeconds > kMaxAggregateImpulseResponse) + return 0x8004E402; + + std::lock_guard lock(g_chad_mutex); + if (g_client_count >= kMaxClients) + return 0x8004E401; + + auto* client = new (std::nothrow) XDspClient{}; + if (!client) return E_OUTOFMEMORY; + client->refcount = 1; + client->connected = true; + client->baseBuffer = baseBuffer; + client->baseBufferLength = baseBufferLength; + client->aggregateImpulseResponseInSeconds = aggregateImpulseResponseInSeconds; + client->maxStreamCount = maximumStreamCount; + client->maxChannelCount = maximumChannelCount; + ++g_client_count; + *handle = client; + + trace_call("XDspConnectWithMaximumStreamLimit", + ",\"baseBufferLength\":" + std::to_string(baseBufferLength) + + ",\"maxStreams\":" + std::to_string(maximumStreamCount)); + return S_OK; +} + +// ---- XDspActivate ---- +// +// Measured: XDspActivate(void* handle, u64, u64, u64, u64) — 5 args (PR #6981). +// Success is a HRESULT of 0 (S_OK). The extra 4 values are activation parameters +// whose meaning is not read; we accept them and return success. + +HRESULT __stdcall XDspActivate(void* handle, uint64_t, uint64_t, uint64_t, uint64_t) { + trace_call("XDspActivate", ""); + return handle ? S_OK : E_INVALIDARG; +} + +// ---- XDspDeactivate ---- +// +// Measured: XDspDeactivate(void* handle, u64, u64, u64) — 4 args. + +HRESULT __stdcall XDspDeactivate(void* handle, uint64_t, uint64_t, uint64_t) { + trace_call("XDspDeactivate", ""); + return handle ? S_OK : E_INVALIDARG; +} + +// ---- XDspDisconnect ---- +// +// HRESULT XDspDisconnect(XDspClientHandle clientHandle) + +HRESULT __stdcall XDspDisconnect(void* clientHandle) { + if (!clientHandle) return E_INVALIDARG; + auto* client = static_cast(clientHandle); + { + std::lock_guard lock(g_chad_mutex); + if (g_client_count > 0) --g_client_count; + } + delete client; + trace_call("XDspDisconnect", ""); + return S_OK; +} + +// ---- XDspSubmitCommand ---- +// +// Measured: XDspSubmitCommand(void* a, void* b) — 2 args. Which of the two is +// the connection handle is not known (the measured wrapper swaps them). + +HRESULT __stdcall XDspSubmitCommand(void*, void*) { + trace_call("XDspSubmitCommand", ""); + return S_OK; +} + +} // namespace + +SHIM_TABLE(chad, + {"chad.dll", "XDspActivate", reinterpret_cast(&XDspActivate)}, + {"chad.dll", "XDspConnectWithMaximumStreamLimit", reinterpret_cast(&XDspConnectWithMaximumStreamLimit)}, + {"chad.dll", "XDspDeactivate", reinterpret_cast(&XDspDeactivate)}, + {"chad.dll", "XDspDisconnect", reinterpret_cast(&XDspDisconnect)}, + {"chad.dll", "XDspSubmitCommand", reinterpret_cast(&XDspSubmitCommand)}, +); diff --git a/runtime/shims/console_identity.h b/runtime/shims/console_identity.h new file mode 100644 index 0000000000..e6cdef0b25 --- /dev/null +++ b/runtime/shims/console_identity.h @@ -0,0 +1,49 @@ +// Which console the title is told it runs on: one setting, two answers. +// +// The title learns its console model two ways. Some code calls XSystemGetDeviceType; GTA VI's own code instead +// reads HKLM\Software\Microsoft\Windows NT\CurrentVersion\OEM, value ConsoleMode (a DWORD), and takes a missing +// value for a PC (docs/runtime_imports.md, "Console identity in the registry"). Both answers come from +// LEONIDA_DEVICE_TYPE through this header so they can never disagree. +// +// The ConsoleMode numbers (0x60 Series S, 0x64 Series X) are what VIctory's xsystem.rs maps (commit 2849477, +// GPL-3.0-or-later); 0x68 for the Scarlett devkit is the value xbox-emulator's xpal and gdk/hook.rs use (commit +// 0284e83, GPL-3.0). +#pragma once +#include + +#include +#include + +namespace rt::shims::console_identity { + +// XSystemDeviceType, in the order of the public documentation. +enum class DeviceType : uint32_t { + Unknown = 0, Pc = 1, XboxOne = 2, XboxOneS = 3, XboxOneX = 4, XboxOneXDevkit = 5, + XboxScarlettLockhart = 6, XboxScarlettAnaconda = 7, XboxScarlettDevkit = 8, +}; + +// The device type the title is told: LEONIDA_DEVICE_TYPE=<0..8>, read at every call so a test or a launcher change is +// seen at once. Text that is not a number counts as 0; a number outside 0..8 or an unset variable gives Series X, as +// XSystemGetDeviceType always did (the package is the Xbox Series build). +inline uint32_t configured_device_type() { + char s[16]; + const DWORD n = GetEnvironmentVariableA("LEONIDA_DEVICE_TYPE", s, sizeof(s)); + if (n > 0 && n < sizeof(s)) { + const int v = std::atoi(s); + if (v >= 0 && v <= 8) return static_cast(v); + } + return static_cast(DeviceType::XboxScarlettAnaconda); +} + +// The registry's ConsoleMode for a device type. False for the types that have none (Unknown, Pc and the Xbox One +// family): the title takes a missing value for a PC, so the registry shim leaves those to the host registry. +inline bool console_mode_for(uint32_t device_type, DWORD& mode) { + switch (static_cast(device_type)) { + case DeviceType::XboxScarlettLockhart: mode = 0x60; return true; + case DeviceType::XboxScarlettAnaconda: mode = 0x64; return true; + case DeviceType::XboxScarlettDevkit: mode = 0x68; return true; + default: return false; + } +} + +} // namespace rt::shims::console_identity diff --git a/runtime/shims/console_registry.cpp b/runtime/shims/console_registry.cpp new file mode 100644 index 0000000000..60633f43f6 --- /dev/null +++ b/runtime/shims/console_registry.cpp @@ -0,0 +1,160 @@ +// Registry shim: the console model the title reads from the registry. +// +// GTA VI does not only call XSystemGetDeviceType. Code linked into the executable (and into libHttpClient.GDK.dll +// and XCurl.dll, which carry the same statically linked GDK helper) opens +// HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\OEM +// with RegOpenKeyW / RegOpenKeyExW, reads the DWORD "ConsoleMode" with RegQueryValueExW (0x64 Series X, 0x60 Series +// S; a missing value means a PC, and a PC takes the PC memory and resolution budgets), and calls RegCloseKey. Under +// Proton the value could be written into the prefix, and on a Windows PC it needs administrator rights. Leonida +// answers it itself, from the same setting as XSystemGetDeviceType (LEONIDA_DEVICE_TYPE, console_identity.h). +// +// Only that one key and that one value are ours: a pseudo key stands for the key, and everything else (every other +// key, value, handle) goes to the host's advapi32 unchanged. For a device type that has no ConsoleMode (a PC, an +// Xbox One) the key is not ours either, so the host registry answers and a missing key stays missing. +// +// Bound for ADVAPI32.dll and for the registry API sets (XCurl.dll imports api-ms-win-core-registry-l1-1-0 and +// l2-1-0, measured with tools/pe_inspect.py); rt::shims::owns_dll keeps advapi32 and the api sets host modules. +// +// Ported with credit from VIctory crates/victory-hle/src/modules/xsystem.rs (mod device_type, commit 2849477, +// GPL-3.0-or-later): the pseudo-key design and the way a null buffer, the size and the type are answered. The +// hook in xbox-emulator crates/compat/compat-common/src/gdk/hook.rs (commit 0284e83, GPL-3.0) did the same with +// an import patch. Written here in C++ against the documented RegQueryValueExW contract. +#include + +#include +#include +#include + +#include "console_identity.h" +#include "console_registry.h" +#include "shims.h" + +namespace rt::shims::console_registry { +namespace { + +// HKEY_LOCAL_MACHINE as the title passes it: the predefined handle value (sign-extended 0x80000002). +const HKEY kLocalMachine = HKEY_LOCAL_MACHINE; +constexpr wchar_t kOemKey[] = L"Software\\Microsoft\\Windows NT\\CurrentVersion\\OEM"; +constexpr wchar_t kConsoleMode[] = L"ConsoleMode"; + +// The pseudo key's handle value: the address of a static, so it is never a kernel handle value. +char g_oem_key; + +std::atomic g_test_host{nullptr}; + +HostRegistry load_advapi32() { + HostRegistry h{}; + if (const HMODULE m = LoadLibraryExW(L"advapi32.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32)) { + h.open_key = reinterpret_cast(GetProcAddress(m, "RegOpenKeyW")); + h.open_key_ex = reinterpret_cast(GetProcAddress(m, "RegOpenKeyExW")); + h.query_value_ex = reinterpret_cast(GetProcAddress(m, "RegQueryValueExW")); + h.close_key = reinterpret_cast(GetProcAddress(m, "RegCloseKey")); + } + return h; +} + +const HostRegistry& host() { + if (const HostRegistry* t = g_test_host.load()) return *t; + static const HostRegistry real = load_advapi32(); // thread-safe; a failed load leaves null pointers + return real; +} + +bool equals_ignore_case(LPCWSTR a, const wchar_t* b) { + return a && CompareStringOrdinal(a, -1, b, -1, TRUE) == CSTR_EQUAL; +} + +// Whether the title asks for our key: HKLM and the OEM path (case-insensitive, as the registry is), and only while the +// configured device type has a ConsoleMode to give. +bool is_ours(HKEY key, LPCWSTR sub_key) { + DWORD mode; + return key == kLocalMachine && equals_ignore_case(sub_key, kOemKey) && + console_identity::console_mode_for(console_identity::configured_device_type(), mode); +} + +} // namespace + +HKEY pseudo_key() { return reinterpret_cast(&g_oem_key); } + +void set_host_registry_for_test(const HostRegistry* h) { g_test_host.store(h); } + +LSTATUS WINAPI reg_open_key_w(HKEY key, LPCWSTR sub_key, PHKEY result) { + if (key == pseudo_key()) { + // The OEM key has no subkeys; opening it with no subkey path gives the same key, as the registry does. + if (!result) return ERROR_INVALID_PARAMETER; + if (sub_key && *sub_key) return ERROR_FILE_NOT_FOUND; + *result = pseudo_key(); + return ERROR_SUCCESS; + } + if (result && is_ours(key, sub_key)) { + *result = pseudo_key(); + return ERROR_SUCCESS; + } + return host().open_key ? host().open_key(key, sub_key, result) : ERROR_CALL_NOT_IMPLEMENTED; +} + +LSTATUS WINAPI reg_open_key_ex_w(HKEY key, LPCWSTR sub_key, DWORD options, REGSAM desired, PHKEY result) { + if (key == pseudo_key()) { + if (!result) return ERROR_INVALID_PARAMETER; + if (sub_key && *sub_key) return ERROR_FILE_NOT_FOUND; + *result = pseudo_key(); + return ERROR_SUCCESS; + } + if (result && is_ours(key, sub_key)) { + *result = pseudo_key(); + return ERROR_SUCCESS; + } + return host().open_key_ex ? host().open_key_ex(key, sub_key, options, desired, result) + : ERROR_CALL_NOT_IMPLEMENTED; +} + +LSTATUS WINAPI reg_query_value_ex_w(HKEY key, LPCWSTR value_name, LPDWORD reserved, LPDWORD type, LPBYTE data, + LPDWORD size) { + if (key != pseudo_key()) + return host().query_value_ex ? host().query_value_ex(key, value_name, reserved, type, data, size) + : ERROR_CALL_NOT_IMPLEMENTED; + + // Our key holds one value. The default (unnamed) value and every other name do not exist. + DWORD mode; + if (!equals_ignore_case(value_name, kConsoleMode) || + !console_identity::console_mode_for(console_identity::configured_device_type(), mode)) + return ERROR_FILE_NOT_FOUND; + + if (data && !size) return ERROR_INVALID_PARAMETER; // a buffer with no size to say how big it is + if (type) *type = REG_DWORD; + if (!size) return ERROR_SUCCESS; // the caller wants only the type (or nothing) + + const DWORD room = *size; + *size = sizeof(DWORD); + if (!data) return ERROR_SUCCESS; // a size query + if (room < sizeof(DWORD)) return ERROR_MORE_DATA; + std::memcpy(data, &mode, sizeof(DWORD)); // the buffer may be unaligned + // Once per distinct answer, so a boot log shows what the title was told without a line per read. + static std::atomic logged{0}; + if (logged.exchange(mode) != mode) + std::fprintf(stderr, "[rt] registry: ConsoleMode answered 0x%x (LEONIDA_DEVICE_TYPE=%u)\n", + static_cast(mode), console_identity::configured_device_type()); + return ERROR_SUCCESS; +} + +LSTATUS WINAPI reg_close_key(HKEY key) { + if (key == pseudo_key()) return ERROR_SUCCESS; + return host().close_key ? host().close_key(key) : ERROR_CALL_NOT_IMPLEMENTED; +} + +} // namespace rt::shims::console_registry + +#define REG_ENTRIES(dll) \ + {dll, "RegOpenKeyW", reinterpret_cast(&rt::shims::console_registry::reg_open_key_w)}, \ + {dll, "RegOpenKeyExW", reinterpret_cast(&rt::shims::console_registry::reg_open_key_ex_w)}, \ + {dll, "RegQueryValueExW", reinterpret_cast(&rt::shims::console_registry::reg_query_value_ex_w)}, \ + {dll, "RegCloseKey", reinterpret_cast(&rt::shims::console_registry::reg_close_key)} + +// The classic import library and the API sets the registry functions live in. +SHIM_TABLE(console_registry, + REG_ENTRIES("advapi32.dll"), + REG_ENTRIES("api-ms-win-core-registry-l1-1-0.dll"), + REG_ENTRIES("api-ms-win-core-registry-l1-1-1.dll"), + REG_ENTRIES("api-ms-win-core-registry-l1-1-2.dll"), + REG_ENTRIES("api-ms-win-core-registry-l2-1-0.dll"), + REG_ENTRIES("api-ms-win-core-registry-l2-1-1.dll"), +); diff --git a/runtime/shims/console_registry.h b/runtime/shims/console_registry.h new file mode 100644 index 0000000000..6588c7baa5 --- /dev/null +++ b/runtime/shims/console_registry.h @@ -0,0 +1,27 @@ +// The registry answer for the console model: HKLM\Software\Microsoft\Windows NT\CurrentVersion\OEM, ConsoleMode. +// See console_registry.cpp. This header is the test seam; the title reaches the shim through rt::shims::find. +#pragma once +#include + +namespace rt::shims::console_registry { + +// The host registry functions every call that is not ours is forwarded to. The defaults are advapi32's, resolved on +// first use; a test replaces them to see what is forwarded. +struct HostRegistry { + LSTATUS(WINAPI* open_key)(HKEY, LPCWSTR, PHKEY); + LSTATUS(WINAPI* open_key_ex)(HKEY, LPCWSTR, DWORD, REGSAM, PHKEY); + LSTATUS(WINAPI* query_value_ex)(HKEY, LPCWSTR, LPDWORD, LPDWORD, LPBYTE, LPDWORD); + LSTATUS(WINAPI* close_key)(HKEY); +}; +void set_host_registry_for_test(const HostRegistry* host); // nullptr: advapi32 again + +// The pseudo key handed out for the OEM key. Never a host handle value. +HKEY pseudo_key(); + +LSTATUS WINAPI reg_open_key_w(HKEY key, LPCWSTR sub_key, PHKEY result); +LSTATUS WINAPI reg_open_key_ex_w(HKEY key, LPCWSTR sub_key, DWORD options, REGSAM desired, PHKEY result); +LSTATUS WINAPI reg_query_value_ex_w(HKEY key, LPCWSTR value_name, LPDWORD reserved, LPDWORD type, LPBYTE data, + LPDWORD size); +LSTATUS WINAPI reg_close_key(HKEY key); + +} // namespace rt::shims::console_registry diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 7c52441417..0fe0189428 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -6,20 +6,26 @@ #include "d3d12_trace.h" #include "d3d12_xs_device.h" #include "../src/gfx10_descriptors.h" +#include "../src/title_va_alias.h" +#include "../src/fsdraw_probe.h" // LOCAL DIAGNOSTIC #include #include #include #include +#include #include #include +#include #include #include #include #include #include #include +#include #include +#include #include #include #include @@ -198,6 +204,8 @@ class GraphicsCommandList final } const leonida::CommandList& commands() const { return list_; } + // The descriptor tables this recording binds (console VAs), for the scan before a submission. + const std::vector>& tables() const { return tables_; } // The pipeline states and root signatures the recording names (it holds a reference to each until Reset). const std::vector& pinned() const { return held_; } UINT front_stencil_ref() const { return front_stencil_ref_; } @@ -234,6 +242,7 @@ class GraphicsCommandList final record_into(command_allocator); invalid_ = false; calls_.clear(); + tables_.clear(); release_held(); // what the old recording used: it was replayed at ExecuteCommandLists reset_state(state); // Reset returns every list state to its default if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) set_initial_pipeline(state); // reset_state holds it @@ -509,7 +518,7 @@ class GraphicsCommandList final if (x > 65535 || y > 65535 || z > 65535 || std::uint64_t(x) * y * z > (1u << 22)) return check(false); if (!graphics_pipeline_ || !graphics_.layout) return check(false); if (!any_nonempty_viewport()) return; // as record_draw: nothing is rasterized - leonida::Draw draw{graphics_pipeline_, graphics_.data, draw_views(), depth_, {}, 0, viewport_, + leonida::Draw draw{graphics_pipeline_, graphics_user_data(), draw_views(), depth_, {}, 0, viewport_, scissor_, blend_factor_, front_stencil_ref_, back_stencil_ref_, false, x, y, z, 0, 0}; draw.mesh = true; draw.viewports = draw_viewports(); @@ -549,29 +558,49 @@ class GraphicsCommandList final switch (group[g].Type) { case D3D12_BARRIER_TYPE_GLOBAL: { const auto& b = group[g].pGlobalBarriers[i]; - check(list_.barrier(leonida::GlobalBarrier{u(b.SyncBefore), u(b.SyncAfter), u(b.AccessBefore), - u(b.AccessAfter)})); + if (!list_.barrier(leonida::GlobalBarrier{u(b.SyncBefore), u(b.SyncAfter), u(b.AccessBefore), + u(b.AccessAfter)}) && + reject()) + std::fprintf(stderr, "[rt] d3d12: global barrier sync 0x%x->0x%x access 0x%x->0x%x\n", + u(b.SyncBefore), u(b.SyncAfter), u(b.AccessBefore), u(b.AccessAfter)); break; } case D3D12_BARRIER_TYPE_BUFFER: { const auto& b = group[g].pBufferBarriers[i]; - check(list_.barrier(leonida::BufferBarrier{u(b.SyncBefore), u(b.SyncAfter), u(b.AccessBefore), - u(b.AccessAfter), resource_id(b.pResource)})); + if (!list_.barrier(leonida::BufferBarrier{u(b.SyncBefore), u(b.SyncAfter), u(b.AccessBefore), + u(b.AccessAfter), resource_id(b.pResource)}) && + reject()) { + std::fprintf(stderr, "[rt] d3d12: buffer barrier sync 0x%x->0x%x access 0x%x->0x%x offset " + "0x%llx size 0x%llx\n", + u(b.SyncBefore), u(b.SyncAfter), u(b.AccessBefore), u(b.AccessAfter), + static_cast(b.Offset), static_cast(b.Size)); + describe_barrier_resource(b.pResource); + } break; } case D3D12_BARRIER_TYPE_TEXTURE: { const auto& b = group[g].pTextureBarriers[i]; const auto& r = b.Subresources; - check(list_.barrier(leonida::TextureBarrier{ - u(b.SyncBefore), u(b.SyncAfter), u(b.AccessBefore), u(b.AccessAfter), u(b.LayoutBefore), - u(b.LayoutAfter), resource_id(b.pResource), - {r.IndexOrFirstMipLevel, r.NumMipLevels, r.FirstArraySlice, r.NumArraySlices, r.FirstPlane, - r.NumPlanes}, - u(b.Flags)})); + if (!list_.barrier(leonida::TextureBarrier{ + u(b.SyncBefore), u(b.SyncAfter), u(b.AccessBefore), u(b.AccessAfter), u(b.LayoutBefore), + u(b.LayoutAfter), resource_id(b.pResource), + {r.IndexOrFirstMipLevel, r.NumMipLevels, r.FirstArraySlice, r.NumArraySlices, + r.FirstPlane, r.NumPlanes}, + u(b.Flags)}) && + reject()) { + std::fprintf(stderr, + "[rt] d3d12: texture barrier sync 0x%x->0x%x access 0x%x->0x%x layout %u->%u " + "mips %u+%u layers %u+%u planes %u+%u flags 0x%x\n", + u(b.SyncBefore), u(b.SyncAfter), u(b.AccessBefore), u(b.AccessAfter), + u(b.LayoutBefore), u(b.LayoutAfter), r.IndexOrFirstMipLevel, r.NumMipLevels, + r.FirstArraySlice, r.NumArraySlices, r.FirstPlane, r.NumPlanes, u(b.Flags)); + describe_barrier_resource(b.pResource); + } break; } default: - check(false); + if (reject()) + std::fprintf(stderr, "[rt] d3d12: barrier group type %d\n", int(group[g].Type)); } } } @@ -639,7 +668,24 @@ class GraphicsCommandList final if (!dst || !src) return check(false); leonida::CopyTexture copy{location(*dst), x, y, z, location(*src), box != nullptr, {}}; if (box) copy.box = {box->left, box->top, box->front, box->right, box->bottom, box->back}; - check(list_.copy_texture(copy)); + if (!list_.copy_texture(copy) && reject()) { + for (const auto* l : {dst, src}) { + const char* side = l == dst ? "dst" : "src"; + if (l->Type != D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT) { + std::fprintf(stderr, "[rt] d3d12: %s type %d resource %p subresource %u\n", side, int(l->Type), + static_cast(l->pResource), l->SubresourceIndex); + continue; + } + const auto& f = l->PlacedFootprint; + std::fprintf(stderr, "[rt] d3d12: %s footprint resource %p offset 0x%llx format %d %ux%ux%u pitch %u\n", + side, static_cast(l->pResource), static_cast(f.Offset), + int(f.Footprint.Format), f.Footprint.Width, f.Footprint.Height, f.Footprint.Depth, + f.Footprint.RowPitch); + } + if (box) + std::fprintf(stderr, "[rt] d3d12: at %u,%u,%u box %u,%u,%u-%u,%u,%u\n", x, y, z, box->left, box->top, + box->front, box->right, box->bottom, box->back); + } } void STDMETHODCALLTYPE CopyResource(ID3D12Resource* dst, ID3D12Resource* src) override { @@ -721,6 +767,17 @@ class GraphicsCommandList final d3d12_trace::record("ID3D12GraphicsCommandList::ClearRenderTargetView"); if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); if (!view.ptr || !color) return check(false); + { // LOCAL DIAGNOSTIC: what the title clears, and with which colour + static std::atomic clears{0}; + const std::uint64_t n = ++clears; + if (n <= 6 || n % 600 == 0) { + const auto& t = *reinterpret_cast(view.ptr); + std::fprintf(stderr, "[rt] present-probe: ClearRenderTargetView #%llu resource 0x%llx mip %u layers %u+%u " + "colour %.3f %.3f %.3f %.3f rects %u\n", + static_cast(n), static_cast(t.resource), t.mip, + t.first_layer, t.layer_count, color[0], color[1], color[2], color[3], count); + } + } check(list_.clear_render_target(*reinterpret_cast(view.ptr), {color[0], color[1], color[2], color[3]}, to_rects(count, rects))); } @@ -898,7 +955,7 @@ class GraphicsCommandList final if (kind == leonida::IndirectKind::dispatch && max_command_count) { // the pipeline and root arguments a Dispatch would record if (!compute_pipeline_ || !compute_.layout) return check(false); cmd.pipeline = compute_pipeline_; - cmd.user_data = compute_.data; + cmd.user_data = compute_user_data(); } check(list_.execute_indirect(cmd)); } @@ -1056,8 +1113,35 @@ class GraphicsCommandList final return out; } - void check(bool ok) { - if (!ok) invalid_ = true; + // Records an invalid call: Close then returns E_INVALIDARG and ExecuteCommandLists refuses the list. The first + // rejection at each call site is logged with the method and line, so a failed Close names its cause; reject() + // returns true for that first one, when a caller may print the arguments too. + bool reject(std::source_location where = std::source_location::current()) { + invalid_ = true; + static std::array, 4096> seen{}; + const std::uint_least32_t line = where.line(); + if (line < seen.size() && seen[line].exchange(true, std::memory_order_relaxed)) return false; + std::string_view method = where.function_name(); + if (const auto at = method.find("GraphicsCommandList::"); at != std::string_view::npos) + method.remove_prefix(at); + if (const auto paren = method.find('('); paren != std::string_view::npos) method = method.substr(0, paren); + std::fprintf(stderr, "[rt] d3d12: %.*s rejected a call (d3d12_com.cpp:%u): the list's Close returns " + "E_INVALIDARG and ExecuteCommandLists refuses it\n", + int(method.size()), method.data(), unsigned(line)); + return true; + } + void check(bool ok, std::source_location where = std::source_location::current()) { + if (!ok) reject(where); + } + static void describe_barrier_resource(ID3D12Resource* resource) { + if (!resource) return void(std::fprintf(stderr, "[rt] d3d12: resource null\n")); + const D3D12_RESOURCE_DESC desc = resource->GetDesc(); + std::fprintf(stderr, + "[rt] d3d12: resource %p dimension %d format %d %llux%ux%u mips %u samples %u layout %d " + "flags 0x%x\n", + static_cast(resource), int(desc.Dimension), int(desc.Format), + static_cast(desc.Width), desc.Height, desc.DepthOrArraySize, desc.MipLevels, + desc.SampleDesc.Count, int(desc.Layout), unsigned(desc.Flags)); } void stop_recording() { @@ -1280,11 +1364,23 @@ class GraphicsCommandList final return; const RootArgumentLayout::Parameter* p = parameter(state, index, type); if (!p) return; + // A root view into the title's own memory (a slot-133 buffer, a constant ring) gets the console VA of a GPU + // copy of it, so the shader's heap_base + VA reaches it (src/title_va_alias.h). A descriptor table is in one + // of the layer's heaps: kept, and its buffer V#s are rewritten the same way before each submission. + // A table in a console descriptor heap is read from the heap's arena copy (console_descriptor_table_va). + if (type == rt::rootsig::ParamType::Descriptor) + va = leonida::title_va_aliases().resolve(va, kRootViewBytes, leonida::TitleVaAliases::root_view); + else + va = console_descriptor_table_va(va); + if (type != rt::rootsig::ParamType::Descriptor && va && p->table_descriptors && + (tables_.empty() || tables_.back().first != va)) + tables_.push_back({va, p->table_descriptors}); const std::uint32_t first = first_dword(state, *p); write(state, first, std::uint32_t(va)); - // In the compute layout a descriptor table is one dword, the 32-bit VA of its first descriptor (the heaps - // live below 4 GiB); a root view keeps both halves. The graphics layout gives every address two dwords. - if (!(is_compute(state) && type == rt::rootsig::ParamType::Table)) write(state, first + 1, std::uint32_t(va >> 32)); + // In the console layouts a descriptor table is one dword, the 32-bit VA of its first descriptor (the heaps + // live below 4 GiB); a root view keeps both halves. pack()'s graphics layout gives every address two dwords. + const bool console = is_compute(state) || state.layout->graphics_console; + if (!(console && type == rt::rootsig::ParamType::Table)) write(state, first + 1, std::uint32_t(va >> 32)); } D3D12_COMMAND_LIST_TYPE type_; @@ -1296,6 +1392,7 @@ class GraphicsCommandList final RootState compute_; RootState graphics_; std::uintptr_t compute_pipeline_ = 0; + bool unregistered_pipeline_ = false; // the bound PSO has no pipeline here (a stub): see set_pipeline std::uintptr_t graphics_pipeline_ = 0; ID3D12DescriptorHeap* cbv_srv_uav_heap_ = nullptr; ID3D12DescriptorHeap* sampler_heap_ = nullptr; @@ -1304,6 +1401,10 @@ class GraphicsCommandList final std::uint32_t topology_ = 0; // D3D_PRIMITIVE_TOPOLOGY_UNDEFINED std::array vertex_buffers_{}; leonida::IndexBufferView index_{}; + // SetGraphicsRootDescriptorTable / SetComputeRootDescriptorTable: VA, CBV/SRV/UAV slots the signature declares + std::vector> tables_; + // The span a root view may read: D3D12's largest constant buffer (4096 x 16 bytes). + static constexpr std::uint64_t kRootViewBytes = 65536; leonida::Viewport viewport_{}; leonida::Rect scissor_{}; std::array viewports_{}; @@ -1367,7 +1468,11 @@ class GraphicsCommandList final hold(state); compute_pipeline_ = compute_pipeline_id(state); graphics_pipeline_ = graphics_pipeline_id(state); - if (state && !compute_pipeline_ && !graphics_pipeline_) + // A pipeline this device never registered: a LEONIDA_STUB_PIPELINES stub (its translated shader is missing), + // or one from another device. Its draws resolve to nothing in replay; its dispatches are no-ops too + // (record_dispatch), so the list still closes. + unregistered_pipeline_ = state && !compute_pipeline_ && !graphics_pipeline_; + if (unregistered_pipeline_) stub("ID3D12GraphicsCommandList::SetPipelineState(pipeline from another device)"); } @@ -1391,13 +1496,13 @@ class GraphicsCommandList final if (!cbv_srv_uav_heap_) note_once("draw/dispatch uses CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED with no CBV/SRV/UAV heap bound"); else - note_once("CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED heap base tracked on list (SGPR slot open, section 3.4)"); + note_once("CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED heap base tracked on list"); } if (layout->flags & D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED) { if (!sampler_heap_) note_once("draw/dispatch uses SAMPLER_HEAP_DIRECTLY_INDEXED with no sampler heap bound"); else - note_once("SAMPLER_HEAP_DIRECTLY_INDEXED heap base tracked on list (SGPR slot open, section 3.4)"); + note_once("SAMPLER_HEAP_DIRECTLY_INDEXED heap base tracked on list"); } } @@ -1430,21 +1535,114 @@ class GraphicsCommandList final void set_vertex_buffers(UINT start, UINT count, const D3D12_VERTEX_BUFFER_VIEW* views) { if (count) draw_views_stale_ = true; - for (UINT i = 0; i < count; ++i) + for (UINT i = 0; i < count; ++i) { + if (views) leonida::title_va_aliases().note(views[i].BufferLocation, leonida::TitleVaAliases::vertex_view); + if (views) leonida::title_va_aliases().want_buffer(views[i].BufferLocation, views[i].SizeInBytes); vertex_buffers_[start + i] = views ? leonida::VertexBufferView{views[i].BufferLocation, views[i].SizeInBytes, views[i].StrideInBytes} : leonida::VertexBufferView{}; + } } void set_index_buffer(const D3D12_INDEX_BUFFER_VIEW* view) { + if (view) leonida::title_va_aliases().note(view->BufferLocation, leonida::TitleVaAliases::index_view); + if (view) leonida::title_va_aliases().want_buffer(view->BufferLocation, view->SizeInBytes); index_ = view ? leonida::IndexBufferView{view->BufferLocation, view->SizeInBytes, u(view->Format)} : leonida::IndexBufferView{}; } + // The compiled console ABI appends directly indexed heaps after the explicit root arguments: the resource heap's + // 32-bit shader VA, then the sampler heap's, each only when the signature has its flag. `slot` is the first + // dword after the arguments (RootArgumentLayout::*_arguments_end). The heaps are snapshotted for each command, + // so rebinding a heap cannot change a recorded draw or dispatch. + std::array with_direct_heaps(const RootState& state, + std::uint32_t slot) const { + auto data = state.data; + const auto flags = state.layout->flags; + if ((flags & D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED) && slot < data.size()) + data[slot++] = static_cast(cbv_srv_uav_base_); + if ((flags & D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED) && slot < data.size()) + data[slot] = static_cast(sampler_base_); + return data; + } + + static bool direct_heaps_enabled(const char* variable) { + const char* v = std::getenv(variable); + return !(v && std::string_view(v) == "0"); + } + + std::array compute_user_data() const { + static const bool enabled = direct_heaps_enabled("LEONIDA_COMPUTE_DIRECT_HEAPS"); + if (!enabled) return compute_.data; + return with_direct_heaps(compute_, compute_.layout->compute_arguments_end); + } + + // Graphics: vertex, pixel and geometry shaders share one user-data block and the s8 layout, so the heaps after + // the explicit arguments serve every one of those stages (a pixel shader of a signature whose arguments end at + // s11 reads the resource heap from s11). A mesh shader reads its arguments from s16, which is not modelled + // (RootArgumentLayout, D3D-448): its pixel shader gets the heaps, the mesh stage does not. + // LEONIDA_GRAPHICS_DIRECT_HEAPS=0 restores the previous arguments. + std::array graphics_user_data() const { + constexpr UINT direct = D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED | + D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED; + const RootArgumentLayout& layout = *graphics_.layout; + if (!(layout.flags & direct)) return graphics_.data; + static const bool enabled = direct_heaps_enabled("LEONIDA_GRAPHICS_DIRECT_HEAPS"); + if (!enabled) { + note_once("graphics direct heaps: off (LEONIDA_GRAPHICS_DIRECT_HEAPS=0), draws keep the explicit " + "arguments only"); + return graphics_.data; + } + const std::uint32_t end = layout.graphics_arguments_end; + if (end >= rt::rootsig::kMaxUserSgprs) { + note_once(layout.graphics_console + ? "graphics direct heaps: not supplied, the explicit arguments fill s8..s31" + : "graphics direct heaps: not supplied, the signature keeps the s0 graphics layout"); + return graphics_.data; + } + static std::atomic logged{false}; + if (!logged.exchange(true, std::memory_order_relaxed)) { + const bool resource = layout.flags & D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED; + const bool sampler = layout.flags & D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED; + char resource_at[48] = "none", sampler_at[48] = "none"; + if (resource) + std::snprintf(resource_at, sizeof resource_at, "0x%llx at s%u", + static_cast(std::uint32_t(cbv_srv_uav_base_)), end); + if (sampler && end + (resource ? 1u : 0u) < rt::rootsig::kMaxUserSgprs) + std::snprintf(sampler_at, sizeof sampler_at, "0x%llx at s%u", + static_cast(std::uint32_t(sampler_base_)), + end + (resource ? 1u : 0u)); + std::fprintf(stderr, + "[rt] d3d12: graphics direct heaps: resource heap %s, sampler heap %s, after %u dwords of " + "explicit arguments from s8 (first draw; LEONIDA_GRAPHICS_DIRECT_HEAPS=0 restores the " + "old arguments)\n", + resource_at, sampler_at, end - 8); + } + return with_direct_heaps(graphics_, end); + } + void record_dispatch(UINT x, UINT y, UINT z) { - if (!compute_pipeline_ || !compute_.layout) return check(false); + if (!compute_pipeline_ && unregistered_pipeline_) return; // a stub pipeline's dispatch: nothing to run + if (!compute_pipeline_) return check(false); // separate lines: the rejection log names which + if (!compute_.layout) return check(false); + static const bool probe = std::getenv("LEONIDA_COMPUTE_INPUTS") != nullptr; + if (probe) { + static std::mutex mutex; + static std::set> seen; + std::lock_guard lock(mutex); + if (seen.emplace(compute_pipeline_, compute_.layout, cbv_srv_uav_base_).second) { + std::fprintf(stderr, "[rt] compute-layout: pso=%p flags=%x bound-heap=0x%llx shader-heap=0x%llx", + reinterpret_cast(compute_pipeline_), compute_.layout->flags, + (unsigned long long)cbv_srv_uav_base_, + (unsigned long long)console_descriptor_table_va(cbv_srv_uav_base_)); + for (const auto& p : compute_.layout->parameters) + std::fprintf(stderr, " (s%u type=%u const=%u slots=%u)", p.compute_offset, + unsigned(p.type), p.constant_count, p.table_descriptors); + std::fputc('\n', stderr); + } + } note_direct_heap_indexing(compute_.layout); - check(list_.dispatch({compute_pipeline_, compute_.data, x, y, z})); + check(list_.dispatch({compute_pipeline_, compute_user_data(), x, y, z})); } // The views block a draw records. Rebuilt only when the render targets or the bound vertex buffers change. @@ -1486,8 +1684,87 @@ class GraphicsCommandList final note_direct_heap_indexing(graphics_.layout); // No viewport (never set, or unbound with RSSetViewports(0)) or every bound viewport empty: D3D12 rasterizes // nothing, and Vulkan forbids a 0x0 viewport, so the draw is not recorded. + { // LOCAL DIAGNOSTIC: the state each draw is recorded with + static std::atomic draws{0}, skipped{0}; + const bool skip = !any_nonempty_viewport(); + const std::uint64_t n = ++draws, k = skip ? ++skipped : skipped.load(); + if (n <= 8 || n % 1200 == 0) + std::fprintf(stderr, "[rt] present-probe: draw #%llu (%s; %llu skipped so far) pso %p rts %u rt0 0x%llx " + "mip %u viewport %.0fx%.0f at %.0f,%.0f scissor %d,%d-%d,%d count %u x%u\n", + static_cast(n), skip ? "SKIPPED: no viewport" : "recorded", + static_cast(k), reinterpret_cast(graphics_pipeline_), + render_target_count_, static_cast(render_targets_[0].resource), + render_targets_[0].mip, viewport_.width, viewport_.height, viewport_.x, viewport_.y, + scissor_.left, scissor_.top, scissor_.right, scissor_.bottom, count, instances); + // LOCAL DIAGNOSTIC (fsdraw): the first draw of each pipeline, and one frame's draws every ~300 frames, + // with the pipeline's description, the root data and what the bound descriptor tables hold. + static std::mutex seen_mutex; + static std::set seen; + bool first_seen; + { + std::lock_guard lock(seen_mutex); + first_seen = seen.insert(graphics_pipeline_).second; + } + const bool fullscreen = render_target_count_ >= 1 && count == 3 && viewport_.width >= 1000; + if (fullscreen) leonida::fsdraw::note_target(render_targets_[0].resource); + if (first_seen || (n - 1) % 600 < 2 || (n > 2 && n < 9)) { + std::fprintf(stderr, "[rt] fsdraw: draw #%llu pso %p%s rt0 0x%llx rts %u depth 0x%llx count %u x%u: %s\n", + static_cast(n), reinterpret_cast(graphics_pipeline_), + first_seen ? " (first use)" : "", static_cast(render_targets_[0].resource), + render_target_count_, static_cast(depth_.resource), count, instances, + leonida::fsdraw::pipeline(graphics_pipeline_).c_str()); + std::fprintf(stderr, "[rt] fsdraw: draw #%llu layout %p user data [%s] cbv heap %p base 0x%llx sampler " + "base 0x%llx tables %zu\n", + static_cast(n), static_cast(graphics_.layout), + leonida::fsdraw::hex_words(graphics_.data.data(), graphics_.data.size()).c_str(), + static_cast(cbv_srv_uav_heap_), + static_cast(cbv_srv_uav_base_), + static_cast(sampler_base_), tables_.size()); + for (std::size_t slot = 0; slot < 2; ++slot) { // the vertex buffers the blit's VS reads + const auto& vb = vertex_buffers_[slot]; + if (!vb.va) continue; + std::uint32_t words[12]{}; + bool read = false; + MEMORY_BASIC_INFORMATION mbi{}; + if (vb.va < leonida::fsdraw::arena_size()) { + read = leonida::fsdraw::arena_words(vb.va, words, 12); + } else if (VirtualQuery(reinterpret_cast(static_cast(vb.va)), &mbi, sizeof mbi) && + mbi.State == MEM_COMMIT && !(mbi.Protect & (PAGE_NOACCESS | PAGE_GUARD)) && mbi.Protect) { + std::memcpy(words, reinterpret_cast(static_cast(vb.va)), sizeof words); + read = true; + } + std::fprintf(stderr, "[rt] fsdraw: draw #%llu vb%zu va 0x%llx size %u stride %u: %s [%s]\n", + static_cast(n), slot, static_cast(vb.va), + unsigned(vb.size), unsigned(vb.stride), read ? "read" : "unreadable", + read ? leonida::fsdraw::hex_words(words, 12).c_str() : ""); + } + D3D12_DESCRIPTOR_HEAP_DESC heap_desc{}; + std::uintptr_t heap_cpu = 0; + if (cbv_srv_uav_heap_) { + heap_desc = cbv_srv_uav_heap_->GetDesc(); + heap_cpu = cbv_srv_uav_heap_->GetCPUDescriptorHandleForHeapStart().ptr; + } + char tag[48]; + std::snprintf(tag, sizeof tag, "draw #%llu", static_cast(n)); + for (const auto& [shader_va, slots] : tables_) { + const std::uint64_t va = leonida::fsdraw::table_origin(shader_va); + const std::uint64_t end = cbv_srv_uav_base_ + std::uint64_t(heap_desc.NumDescriptors) * 32; + const bool in_heap = heap_cpu && va >= cbv_srv_uav_base_ && va + 32 <= end; + const auto* cpu = in_heap ? reinterpret_cast(heap_cpu + (va - cbv_srv_uav_base_)) + : nullptr; + const bool console = heap_cpu == std::uintptr_t(cbv_srv_uav_base_); + if (shader_va != va) + std::fprintf(stderr, "[rt] fsdraw: %s table title va 0x%llx is shader va 0x%llx\n", tag, + static_cast(va), static_cast(shader_va)); + leonida::fsdraw::describe_table(tag, shader_va, slots, cpu, + !in_heap ? "none (not in the bound CBV/SRV/UAV heap)" + : console ? "console (CPU address = GPU VA, title memory)" + : "layer heap (arena)"); + } + } + } if (!any_nonempty_viewport()) return; - leonida::Draw draw{graphics_pipeline_, graphics_.data, draw_views(), depth_, index_, topology_, viewport_, + leonida::Draw draw{graphics_pipeline_, graphics_user_data(), draw_views(), depth_, index_, topology_, viewport_, scissor_, blend_factor_, front_stencil_ref_, back_stencil_ref_, indexed, count, instances, first, base_vertex, first_instance}; draw.viewports = draw_viewports(); @@ -1542,12 +1819,14 @@ class Fence final context_.enqueue_fence_callback(semaphore, queued, [context, semaphore, queued, value, held = held_] { std::uint64_t now = 0; bool signaled = false; - if (context->vk.vkGetSemaphoreCounterValue(context->device(), semaphore, &now) == VK_SUCCESS && + if (context->observe_result(context->vk.vkGetSemaphoreCounterValue(context->device(), semaphore, &now), + "vkGetSemaphoreCounterValue (fence callback)") == VK_SUCCESS && now >= queued && now < value) { VkSemaphoreSignalInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO}; info.semaphore = semaphore; info.value = value; - signaled = context->vk.vkSignalSemaphore(context->device(), &info) == VK_SUCCESS; + signaled = context->observe_result(context->vk.vkSignalSemaphore(context->device(), &info), + "vkSignalSemaphore (fence callback)") == VK_SUCCESS; } held->fetch_sub(1); if (signaled) { @@ -1717,6 +1996,42 @@ class CommandQueue final recorded.push_back(&list->commands()); graphics.push_back(list); } + // Buffer V#s the title wrote into a bound table itself may name its own memory: rewritten to a GPU copy's + // console VA before the copies are refreshed for this submission (src/title_va_alias.h). + { + std::map tables; // each table once, with the most slots it was bound with + for (const GraphicsCommandList* list : graphics) + for (const auto& [table, descriptors] : list->tables()) + tables[table] = std::max(tables[table], descriptors); + for (const auto& [table, descriptors] : tables) { // LOCAL DIAGNOSTIC (fsdraw): poke experiment + const std::uint64_t origin = leonida::fsdraw::table_origin(table); + if (origin != table) + leonida::fsdraw::poke_cb(reinterpret_cast(static_cast(origin))); + } + { // LOCAL DIAGNOSTIC (fsdraw): what the bound tables hold when the lists are submitted + static std::atomic submits{0}; + const std::uint64_t n = tables.empty() ? 0 : ++submits; + if (n && (n <= 6 || n % 300 == 0)) { + char tag[48]; + std::snprintf(tag, sizeof tag, "submit #%llu", static_cast(n)); + for (const auto& [table, descriptors] : tables) { + const std::uint64_t origin = leonida::fsdraw::table_origin(table); + const bool title = origin != table; + leonida::fsdraw::describe_table( + tag, table, descriptors, + title ? reinterpret_cast(static_cast(origin)) : nullptr, + title ? "title memory (CPU bytes read at the title VA the table was set with)" : "arena or unknown"); + } + } + } + if (!tables.empty()) { + const auto start = std::chrono::steady_clock::now(); + for (const auto& [table, descriptors] : tables) leonida::title_va_aliases().scan_table(table, descriptors); + leonida::title_va_aliases().note_scan(std::uint64_t( + std::chrono::duration_cast(std::chrono::steady_clock::now() - start) + .count())); + } + } last_result_ = queue_.execute(recorded, [&graphics] { return pin_lists(graphics); }); d3d12_trace::record(method, last_result_ == leonida::ReplayResult::success ? "ok" : "failed"); if (last_result_ != leonida::ReplayResult::success) @@ -1865,16 +2180,20 @@ class CommandQueue final LARGE_INTEGER before{}, after{}; { std::lock_guard submit_lock(context_.submit_mutex()); - if (vk.vkQueueWaitIdle(vk_queue_) != VK_SUCCESS) return E_FAIL; + if (context_.observe_result(vk.vkQueueWaitIdle(vk_queue_), "vkQueueWaitIdle (calibration)") != VK_SUCCESS) + return E_FAIL; QueryPerformanceCounter(&before); - if (vk.vkQueueSubmit(vk_queue_, 1, &submit, VK_NULL_HANDLE) != VK_SUCCESS || - vk.vkQueueWaitIdle(vk_queue_) != VK_SUCCESS) + if (context_.observe_result(vk.vkQueueSubmit(vk_queue_, 1, &submit, VK_NULL_HANDLE), + "vkQueueSubmit (calibration)") != VK_SUCCESS || + context_.observe_result(vk.vkQueueWaitIdle(vk_queue_), "vkQueueWaitIdle (calibration)") != VK_SUCCESS) return E_FAIL; QueryPerformanceCounter(&after); } std::uint64_t stamp = 0; - if (stamp_.get_query_pool_results(context_.device(), stamp_.queries, 0, 1, sizeof(stamp), &stamp, - sizeof(stamp), VK_QUERY_RESULT_64_BIT) != VK_SUCCESS) + if (context_.observe_result(stamp_.get_query_pool_results(context_.device(), stamp_.queries, 0, 1, + sizeof(stamp), &stamp, sizeof(stamp), + VK_QUERY_RESULT_64_BIT), + "vkGetQueryPoolResults (calibration)") != VK_SUCCESS) return E_FAIL; if (clock_.timestamp_valid_bits < 64) stamp &= (std::uint64_t(1) << clock_.timestamp_valid_bits) - 1; gpu = stamp; @@ -2094,7 +2413,8 @@ HRESULT set_event_on_multiple_fence_completion(leonida::VulkanContext& context, wait.semaphoreCount = count; wait.pSemaphores = semaphores.data(); wait.pValues = values; - const VkResult result = context.vk.vkWaitSemaphores(context.device(), &wait, UINT64_MAX); + const VkResult result = context.observe_result( + context.vk.vkWaitSemaphores(context.device(), &wait, UINT64_MAX), "vkWaitSemaphores (multiple fences)"); // Unlike a single fence's blocking SetEventOnCompletion, this path invokes Vulkan directly. // A lost device must wake its other registered fence waiters and reject later submissions. if (result == VK_ERROR_DEVICE_LOST) { diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index cf83f1f28a..f1ff60ebb6 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -86,6 +86,11 @@ struct VulkanDeviceInfo { std::uint32_t copy_family = UINT32_MAX; std::vector compute_queues; std::vector copy_queues; + bool pipeline_creation_feedback = false; + bool device_fault_diagnostics = false; + bool device_fault_info = false; + bool device_checkpoints = false; + bool device_diagnostics_config = false; bool separate_depth_stencil_layouts = true; bool depth_range_unrestricted = false; // VK_EXT_depth_range_unrestricted enabled on this device. std::uint32_t max_push_constants_size = 0; @@ -160,6 +165,9 @@ struct VulkanDeviceInfo { bool fragment_shader_barycentric = false; bool fragment_shader_interlock = false; bool maintenance8 = false; + // VK_KHR_maintenance5, enabled where its VK_FORMAT_A8_UNORM_KHR can be sampled and is a colour attachment the GPU + // can blend: A8_UNORM render targets are then stored in that format (other A8_UNORM textures stay R8_UNORM). + bool a8_render_target = false; // The instance enabled VK_EXT_debug_utils: SetMarker/BeginEvent/EndEvent become debug labels. Otherwise they // do nothing. bool debug_utils = false; @@ -242,6 +250,20 @@ VkImage vulkan_image(ID3D12Resource* resource); VkBuffer vulkan_buffer(ID3D12Resource* resource); // What a device from create_vulkan_device* was created with (enabled features included), or null. For tests. const VulkanDeviceInfo* vulkan_device_info(ID3D12Device* device); +// True when a slot-133 buffer is a shadow copied from the title's pages, false when they were imported. For tests. +bool title_shadow_buffer(ID3D12Resource* resource); +// VirtualQuery calls made by the title-buffer shadows in their latest refresh. For tests. +std::uint64_t title_shadow_refresh_queries(ID3D12Device* device); +// The trackers behind the title-buffer shadows and title windows (copies whose pages overlap or touch share one). +// For tests. +std::uint64_t title_shadow_trackers(ID3D12Device* device); +// What the title-buffer shadows' latest refresh did, summed over their trackers: GetWriteWatch calls, write-watched +// pages found written, the write faults taken since they were made, and the bytes of covered pages write-watched and +// hot (asked about rather than guarded). For tests. +struct TitleShadowWatch { + std::uint64_t asks = 0, written = 0, faults = 0, watched_bytes = 0, hot_bytes = 0; +}; +TitleShadowWatch title_shadow_watch(ID3D12Device* device); // True when `device` has VK_KHR_acceleration_structure + VK_KHR_ray_query enabled. bool device_supports_ray_tracing(ID3D12Device* device); @@ -348,6 +370,8 @@ class WindowPresenter { bool tear = false); // A black frame, nothing read (PresentX with no planes). HRESULT present_blank(UINT sync_interval); + // Show the shell image through startup clears, then hand off to the first non-black output. + bool present_splash(ID3D12Resource* image); // One or two planes composed (VulkanPresenter::present_planes); `planes` names the textures by ResourceId, so the // caller fills it with resource_id(). DXGI_ERROR_UNSUPPORTED for a source the compose pass cannot read. HRESULT present_planes(const leonida::PresentPlanes& planes, UINT sync_interval, bool tear = false); @@ -386,8 +410,12 @@ std::unique_ptr create_window_presenter(ID3D12Device* device, H // Where each root parameter's arguments go in the 32 user-data dwords the translated shaders read (docs section // 3.5). Built when a Vulkan device creates the root signature. A signature can be bound at either bind point, so it // carries both layouts: -// - graphics: rt::rootsig::pack() (from s0, two dwords per table; D3D-448 keeps it until per-stage user-data windows -// exist, because a mesh shader (s16) and a pixel shader (s8) share one push-constant block); +// - graphics: rt::rootsig::pack_stage(Stage::Pixel), the console layout of vertex, pixel and geometry shaders +// (from s8, one dword per table), which the game's own shaders read: VS_Blit/PS_BlitColour and the Scaleform +// VS load their table's first descriptor from s[8:9] with s9 forced to 0. A signature that would spill there +// (more than 24 dwords) keeps rt::rootsig::pack() (from s0, two dwords per table), logged: the graphics spill +// array is not modelled. A mesh shader reads from s16 and shares the block with its pixel shader (s8), so mesh +// pipelines still see their arguments 8 dwords early (D3D-448); // - compute: rt::rootsig::pack_stage(Stage::Compute), the measured console layout (from s4, one dword per table). // A layout that refuses the signature is marked unusable; binding the signature there invalidates the list. struct RootArgumentLayout { @@ -396,11 +424,21 @@ struct RootArgumentLayout { std::uint32_t user_offset; // graphics: first dword; unused for a parameter with no dwords std::uint32_t constant_count; // constants only std::uint32_t compute_offset = rt::rootsig::kNoSgpr; // compute: first user SGPR + // A table: the CBV/SRV/UAV slots its ranges declare (an unbounded range counts as 1024), for the scan of + // title-written V#s before a submission (src/title_va_alias.h). 0: a sampler table, or not a table. + std::uint32_t table_descriptors = 0; }; std::vector parameters; std::uint32_t flags = 0; // D3D12_ROOT_SIGNATURE_FLAGS from the serialized blob + // The graphics layout is the console's (pack_stage(Stage::Pixel)): a table takes one dword. False: pack()'s, two. + bool graphics_console = false; bool graphics_ok = true; bool compute_ok = true; + // One past the last user-data dword the explicit root arguments take at each bind point, where the console puts + // the directly indexed heaps (resource heap, then sampler heap). kNoSgpr: no such dword (the compute arguments + // spill, or graphics keeps pack()'s s0 layout). + std::uint32_t compute_arguments_end = rt::rootsig::kNoSgpr; + std::uint32_t graphics_arguments_end = rt::rootsig::kNoSgpr; }; // For the command list: the argument layout of a root signature from a Vulkan device, and the id it records for a @@ -416,6 +454,24 @@ const std::vector* pipeline_subgroup_requests(ID3D12Pi IUnknown* descriptor_heap_info(ID3D12DescriptorHeap* heap, D3D12_DESCRIPTOR_HEAP_DESC& desc, D3D12_GPU_VIRTUAL_ADDRESS& gpu_base); +// Xbox device slots 70/71: a buffer view of the title's own memory, with no resource object. `view` is a PC +// D3D12_SHADER_RESOURCE_VIEW_DESC (or, `unordered`, D3D12_UNORDERED_ACCESS_VIEW_DESC) of a buffer, `address` the +// memory's console VA and `width` its bytes. Writes the V# into `destination` and returns true; false when `device` +// is not this module's or the layer cannot write that view (the slot is left as it was). +bool write_placed_buffer_view(ID3D12Device* device, bool unordered, const void* view, std::uint64_t address, + std::uint64_t width, D3D12_CPU_DESCRIPTOR_HANDLE destination); + +// Xbox placed texture SRV (slot 70) or UAV (slot 71). The 56-byte console resource description includes the +// XG layout at +44. The PC SRV/UAV description and placement address select the view. A GPU-writable +// image must already exist for a UAV. False leaves the destination descriptor zeroed. +bool write_placed_texture_view(ID3D12Device* device, bool unordered, const std::uint32_t* resource_words, + const std::uint32_t* view_words, std::uint64_t address, + D3D12_CPU_DESCRIPTOR_HANDLE destination); + +// The VA shaders read a descriptor table at: for one inside a console descriptor heap (Xbox slot 14) whose arena copy +// lies elsewhere, the matching VA in that copy; any other VA unchanged. +D3D12_GPU_VIRTUAL_ADDRESS console_descriptor_table_va(D3D12_GPU_VIRTUAL_ADDRESS va); + // Reads the shader-visible descriptor heap GPU base addresses currently bound on `list` (0 when unbound). // Returns false when `list` is not one of this module's command lists. bool bound_descriptor_heap_bases(ID3D12GraphicsCommandList* list, D3D12_GPU_VIRTUAL_ADDRESS& cbv_srv_uav, diff --git a/runtime/shims/d3d12_compute_input_probe.h b/runtime/shims/d3d12_compute_input_probe.h new file mode 100644 index 0000000000..2b4c5e9ab3 --- /dev/null +++ b/runtime/shims/d3d12_compute_input_probe.h @@ -0,0 +1,299 @@ +#pragma once + +#include "../src/command_list.h" +#include "../src/fsdraw_probe.h" +#include "../src/title_va_alias.h" +#include "../src/title_page_watch.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace rt::compute_probe { +inline std::string_view filters() { + static const char* value = std::getenv("LEONIDA_COMPUTE_INPUTS"); + return value ? value : ""; +} +inline bool enabled() { return !filters().empty(); } +inline bool matches(const char* name) { + if (!name) return false; + auto parts = filters(); + while (!parts.empty()) { + const auto end = parts.find(','); + const auto part = parts.substr(0, end); + if (!part.empty() && std::string_view(name).find(part) != std::string_view::npos) return true; + if (end == parts.npos) break; + parts.remove_prefix(end + 1); + } + return false; +} + +// Each decimal pair selects a table root dword and a 32-byte descriptor index. +inline const auto& slots() { + static const auto pairs = [] { + std::vector> result; + const char* p = std::getenv("LEONIDA_COMPUTE_INPUT_SLOTS"); + if (!p) return result; + const char* end = p + std::strlen(p); + while (p != end && result.size() < 256) { + unsigned root{}, slot{}; + auto r = std::from_chars(p, end, root); + if (r.ec != std::errc{} || r.ptr == end || *r.ptr != '/') break; + auto s = std::from_chars(r.ptr + 1, end, slot); + if (s.ec != std::errc{} || (s.ptr != end && *s.ptr != ',')) break; + if (root < 32 && slot < (1u << 21)) result.emplace_back(root, slot); + p = s.ptr == end ? end : s.ptr + 1; + } + return result; + }(); + return pairs; +} + +inline constexpr const char* writers[] = {"unobserved", "CreateConstantBufferView", "CreateShaderResourceView", + "CreateUnorderedAccessView", "CopyDescriptors", "slot70", "slot71"}; +inline std::uint8_t writer_code(std::string_view name) { + for (std::uint8_t i = 1; i < std::size(writers); ++i) + if (name == writers[i]) return i; + return 0; +} + +inline bool read_cpu(std::uint64_t address, void* out, std::size_t size) { + SIZE_T read{}; + return address && ReadProcessMemory(GetCurrentProcess(), reinterpret_cast(address), + out, size, &read) && read == size; +} + +struct Backing { + const char* kind; + std::uint64_t title{}, host{}, available{}; +}; + +inline bool read_backing(Backing b, std::uint64_t offset, void* out, std::size_t size) { + if (!b.host || offset > b.available || size > b.available - offset) return false; + // The device owns the arena mapping for its lifetime. Linux cross-process reads can reject a + // device mapping even though the current process can read it directly. + if (std::string_view(b.kind) == "arena" || std::string_view(b.kind) == "arena-shadow" || + std::string_view(b.kind) == "window-shadow") { + std::memcpy(out, reinterpret_cast(b.host + offset), size); + return true; + } + return read_cpu(b.host + offset, out, size); +} + +template +Backing backing(State& state, std::uint64_t base) { + auto& aliases = leonida::title_va_aliases(); + std::uint64_t source{}, room{}; + const bool alias = aliases.source_of_vsharp(base, source, room); + if (base < state.arena.size) { + std::lock_guard lock(state.arena.mutex); + auto next = state.arena.free.upper_bound(base); + if (next != state.arena.free.begin()) { + const auto [at, size] = *std::prev(next); + if (base - at < size) return {"arena-free"}; + } + const auto end = next == state.arena.free.end() ? state.arena.size : next->first; + return {alias ? "arena-shadow" : "arena", source, reinterpret_cast(state.arena.mapped) + base, + alias ? std::min(room, end - base) : end - base}; + } + if (alias) { + std::uint64_t host{}, bytes{}; + { + std::lock_guard lock(state.title_window_mutex); + if (state.external_windows.lookup(state.arena.address + base, host, bytes)) + return {"window-shadow", source, host, std::min(room, bytes)}; + } + if (!state.context->diagnostic_buffer(source, host, bytes)) return {"alias-only", source}; + return {host == source ? "import" : host ? "external-shadow" : "external-buffer", source, host, + std::min(room, bytes)}; + } + std::uint64_t lo{}, hi{}; + if (state.geometry.cap()) { + std::uint64_t mapped{}, size{}, source{}; + bool populated{}; + if (state.geometry.lookup(state.arena.address + base, mapped, size, &source, &populated)) + return {populated ? "geometry" : "geometry-pending", source, mapped, size}; + } + if (aliases.title_memory(base, lo, hi)) return {"untranslated-title", base, 0, hi - base}; + const auto normalized = (base ^ (1ull << 47)) - (1ull << 47); + std::uint64_t host{}, bytes{}; + if (state.context->diagnostic_buffer(normalized, host, bytes)) return {"registered-buffer", 0, host, bytes}; + return {"unknown"}; +} + +template +Backing descriptor(State& state, std::uint64_t seq, std::size_t list, std::size_t cmd, + const std::array& roots, unsigned reg, unsigned slot) { + const auto at = std::uint64_t(roots[reg]) + std::uint32_t(slot * 32u); + std::array raw{}, gpu{}; + const char* origin = "no-heap"; + std::uint64_t index = 0, title_at = 0; + bool table = false, have_gpu = false; + { + std::lock_guard lock(state.probe_mutex); + for (const auto& heap : state.probes) { + const auto delta = at - heap->shader_va; + if (delta / 32 >= heap->slots || delta % 32) continue; + index = delta / 32; + title_at = heap->console_va + delta; + table = read_cpu(title_at, raw.data(), sizeof(raw)); + if (!table) break; + const auto h = State::probe_hash(reinterpret_cast(raw.data())); + origin = heap->api[index] == h && !heap->writer.empty() ? writers[heap->writer[index]] : + heap->api[index] ? "changed-since-API" : "no-API-write-recorded"; + if (heap->shadowed && at >= state.arena.size) { + gpu = raw; + have_gpu = true; + } + break; + } + } + if (state.geometry.cap() && table && at >= state.arena.size) { + std::lock_guard lock(state.console_heap_mutex); + for (const auto& heap : state.console_heaps) { + const auto delta = at - heap->shader_va; + if (heap->copy && delta <= heap->bytes && sizeof(gpu) <= heap->bytes - delta) { + std::memcpy(gpu.data(), heap->copy + delta, sizeof(gpu)); + have_gpu = true; + break; + } + } + } + if (!have_gpu) have_gpu = leonida::fsdraw::arena_words(at, gpu.data(), gpu.size()); + const auto prefix = "[rt] compute-input: execute=%llu list=%zu cmd=%zu s%u/%u "; + std::fprintf(stderr, prefix, (unsigned long long)seq, list, cmd, reg, slot); + if (!have_gpu) { + std::fprintf(stderr, "table=0x%llx no GPU-visible bytes\n", (unsigned long long)at); + return {"missing-table"}; + } + std::fprintf(stderr, "heap-slot=%llu table-title=0x%llx writer=%s words=[%s] ", + (unsigned long long)index, (unsigned long long)title_at, origin, + leonida::fsdraw::hex_words(gpu.data(), gpu.size()).c_str()); + if (table && raw != gpu) + std::fprintf(stderr, "title-words=[%s] ", leonida::fsdraw::hex_words(raw.data(), raw.size()).c_str()); + if (gpu[3] >> 30) { + std::fprintf(stderr, "texture key=%s\n", leonida::fsdraw::has_tsharp(gpu.data()) ? "registered" : "absent"); + return {"texture"}; + } + if (!(gpu[0] | gpu[1] | gpu[2] | gpu[3])) { std::fputs("null\n", stderr); return {"null"}; } + const auto base = std::uint64_t(gpu[0]) | (std::uint64_t(gpu[1] & 0xffff) << 32); + const auto stride = (gpu[1] >> 16) & 0x3fffu; + const auto span = std::uint64_t(gpu[2]) * (stride ? stride : 1); + auto b = backing(state, base); + const auto signed_base = (base ^ (1ull << 47)) - (1ull << 47); + std::fprintf(stderr, "V#=0x%llx bda=0x%llx stride=%u records=%u storage=%s title=0x%llx", + (unsigned long long)base, (unsigned long long)(state.arena.address + signed_base), stride, gpu[2], + b.kind, (unsigned long long)b.title); + std::array data{}; + const auto n = std::min({span, b.available, sizeof(data)}) / 4; + if (n && read_backing(b, 0, data.data(), 4 * n)) + std::fprintf(stderr, " cpu-sample=[%s]", leonida::fsdraw::hex_words(data.data(), n).c_str()); + if (std::string_view(b.kind) == "untranslated-title") { + std::uint64_t created_at{}; + const bool from_cbv = leonida::fsdraw::cbv_origin(base, created_at); + const auto source = leonida::title_gpu_views::to_cpu(base); + const auto aliased = leonida::title_va_aliases().shader_va(source); + MEMORY_BASIC_INFORMATION region{}; + VirtualQuery(reinterpret_cast(source), ®ion, sizeof(region)); + std::fprintf(stderr, " source=0x%llx source-alias=0x%llx state=0x%lx protect=0x%lx", + (unsigned long long)source, (unsigned long long)aliased, region.State, region.Protect); + if (from_cbv) std::fprintf(stderr, " recorded-CBV-location=0x%llx", (unsigned long long)created_at); + const auto size = std::min(span, sizeof(data)) / 4; + if (size && region.State == MEM_COMMIT && !(region.Protect & (PAGE_NOACCESS | PAGE_GUARD)) && + read_cpu(source, data.data(), size * 4)) + std::fprintf(stderr, " source-only=[%s]", leonida::fsdraw::hex_words(data.data(), size).c_str()); + } + std::fputc('\n', stderr); + b.available = std::min(b.available, span); + return b; +} + +// The two measured culling kernels share this record format. Read a bounded CPU snapshot +// of the actual int offsets for each dispatched group. A prior GPU writer can still be in flight. +template +void culling_records(State& state, std::uint64_t seq, std::size_t list, std::size_t cmd, + const std::array& roots, unsigned groups, Backing indices, Backing records) { + auto word = [](Backing b, std::uint64_t off, unsigned& out) { + return read_backing(b, off, &out, sizeof(out)); + }; + std::set indices_seen; + for (unsigned group = 0; group < std::min(groups, 256u); ++group) { + unsigned record{}; + if (!word(indices, 4ull * group, record)) break; + record &= ~3u; + unsigned branches[2]{}, vb{}, count{}; + const bool valid = word(records, record, branches[0]) && word(records, record + 4ull, branches[1]) && + word(records, record + 0x28ull, vb); + std::fprintf(stderr, "[rt] compute-record: execute=%llu cmd=%zu group=%u offset=0x%x accessible=%u", + (unsigned long long)seq, cmd, group, record, valid); + if (valid) { + std::fprintf(stderr, " vertex-slot=%u", vb); + unsigned byte_offset{}, first{}, count_instances{}; + if (word(records, record + 0x2cull, byte_offset) && word(records, record + 0x3cull, first) && + word(records, record + 0x40ull, count_instances)) + std::fprintf(stderr, " byte-offset=%u first=%u instances=%u", byte_offset, first, count_instances); + indices_seen.insert(vb); + for (unsigned branch : branches) { + std::uint64_t node = branch & ~3u; + unsigned indices_pair[2]{}; + if (word(records, node + 4, count)) std::fprintf(stderr, " node=0x%llx count4=%u", (unsigned long long)node, count); + if (word(records, node + 0x374, count)) std::fprintf(stderr, " count374=%u", count); + if (word(records, node + 0x39c, indices_pair[0]) && word(records, node + 0x3a0, indices_pair[1])) { + indices_seen.insert(indices_pair[0]); + indices_seen.insert(indices_pair[1]); + } + } + } + std::fputc('\n', stderr); + } + std::vector alternatives; + { + std::lock_guard lock(state.probe_mutex); + for (const auto& heap : state.probes) + if (heap->shadowed && heap->shader_va <= UINT32_MAX && roots[7] != heap->shader_va) + alternatives.push_back(static_cast(heap->shader_va)); + } + for (unsigned index : indices_seen) { + descriptor(state, seq, list, cmd, roots, 7, index); + for (auto heap : alternatives) { + std::fprintf(stderr, "[rt] compute-record: comparison only, heap=0x%x index=%u\n", heap, index); + auto expected = roots; + expected[7] = heap; + descriptor(state, seq, list, cmd, expected, 7, index); + } + } +} + +template +void inspect(State& state, std::span lists, std::uint64_t seq, const char* queue) { + for (std::size_t l = 0; l < lists.size(); ++l) { + const auto& cmds = lists[l]->commands(); + for (std::size_t i = 0; i < cmds.size(); ++i) { + const auto* d = std::get_if(&cmds[i]); + const auto* ind = std::get_if(&cmds[i]); + if (!d && (!ind || ind->kind != leonida::IndirectKind::dispatch)) continue; + const char* name = state.context->diagnostic_compute_name(d ? d->pipeline : ind->pipeline); + if (!matches(name)) continue; + const auto& roots = d ? d->user_data : ind->user_data; + std::fprintf(stderr, "[rt] compute-input: execute=%llu list=%zu cmd=%zu queue=%s name=%s pso=%p %s groups=%u,%u,%u " + "heap-base=0x%llx roots=[%s]\n", (unsigned long long)seq, l, i, queue, name, reinterpret_cast(d ? d->pipeline : ind->pipeline), + d ? "direct" : "indirect", d ? d->x : 0, d ? d->y : 0, d ? d->z : 0, + (unsigned long long)state.arena.address, leonida::fsdraw::hex_words(roots.data(), roots.size()).c_str()); + Backing indices{}, records{}; + for (const auto& [reg, slot] : slots()) { + const auto b = descriptor(state, seq, l, i, roots, reg, slot); + if (reg == 5 && slot == 0) indices = b; + if (reg == 4 && slot == 86) records = b; + } + if (d && (std::string_view(name).ends_with("lib_cs_01405") || std::string_view(name).ends_with("lib_cs_01410"))) + culling_records(state, seq, l, i, roots, d->x, indices, records); + } + } +} +} // namespace rt::compute_probe diff --git a/runtime/shims/d3d12_geometry_views.h b/runtime/shims/d3d12_geometry_views.h new file mode 100644 index 0000000000..ef7af22029 --- /dev/null +++ b/runtime/shims/d3d12_geometry_views.h @@ -0,0 +1,216 @@ +#pragma once + +#include "d3d12_title_buffer_windows.h" +#include "../src/title_geometry_watch.h" +#include +#include +#include +#include + +namespace rt::d3d12 { + +// One persistent device-local copy for each geometry extent. The console heap retains its original indices. +// Every CPU mapping of a source tile is watched; a physical remap changes which aliases must be watched. +enum class GeometryCopy { copied, unreadable, interrupted }; + +class GeometryViews { + using Address = std::uintptr_t; + static constexpr auto tile_size = leonida::geometry_writes::tile_size; + using Cell = leonida::geometry_writes::Cell; + struct View { + Address source; + std::size_t size; + std::uint8_t* dst; + VkDeviceSize va; + bool ready{}, zeroed{}; + }; + struct Tile { + Cell* primary{}; + std::uint64_t mapping{}, version{}; + std::vector> peers; + std::vector views; + bool retry = false; + }; + mutable std::mutex mutex_; + TitleBufferWindows pool_; + std::map, std::size_t> keys_; + std::vector views_; + std::map by_address_; + std::map tiles_; + static constexpr auto refused = SIZE_MAX; + std::uint64_t serial_{}, bytes_{}, cap_refusals_{}, allocation_failures_{}, ready_{}, uploads_{}, uploaded_{}; + std::uint64_t submissions_{}, dirty_refreshes_{}, refilled_{}; + std::chrono::steady_clock::duration refresh_time_{}; + std::uint64_t cleared_{}; + bool retry_{}; + + bool update(Address va, Tile& t) { + namespace watch = leonida::geometry_writes; + if (!t.primary) t.primary = watch::acquire(va); + auto version = t.primary->version.load(std::memory_order_acquire); + const auto mapping = t.primary->mapping.load(std::memory_order_acquire); + if (t.mapping != mapping) { + std::vector
others; + if (auto aliases = watch::aliases.load(std::memory_order_acquire)) aliases(va, others); + auto old = std::move(t.peers); + for (auto peer : others) t.peers.emplace_back(peer, watch::acquire(peer)); + for (auto [peer, cell] : old) watch::release(peer); + t.mapping = mapping; + } + for (auto [addr, peer] : t.peers) + version = (std::max)(version, peer->version.load(std::memory_order_acquire)); + if (version == t.version && !t.retry) return false; + t.retry = !watch::arm(va, *t.primary); + for (auto [addr, peer] : t.peers) + if (!watch::arm(addr, *peer)) t.retry = true; + t.version = version; + retry_ |= t.retry; + return !t.retry; + } + template + void fill(View& v, Copy& copy) { + const auto result = copy(v.dst, reinterpret_cast(v.source), v.size); + if (result == GeometryCopy::copied) { + if (!v.ready) ++ready_; + v.ready = true; + v.zeroed = false; + ++uploads_; + uploaded_ += v.size; + } else { + if (v.ready) --ready_; + v.ready = false; + if (!v.zeroed || result == GeometryCopy::interrupted) { + // A failing guarded copy may have written a prefix. A failed readability probe + // wrote nothing, so an already-zeroed view needs no second write across the BAR. + std::memset(v.dst, 0, v.size); + cleared_ += v.size; + v.zeroed = true; + } + } + } + +public: + static std::uint64_t cap() { + static const std::uint64_t value = []() -> std::uint64_t { + const char* opt = std::getenv("LEONIDA_GEOMETRY_MB"); + return opt ? (std::min)(std::strtoull(opt, nullptr, 10), 8192ull) << 20 : 0ull; + }(); + return value; + } + + std::uint64_t find(Address cpu, std::size_t bytes) const { + std::lock_guard lock(mutex_); + const auto it = keys_.find({cpu, bytes}); + return it == keys_.end() || it->second == refused ? 0 : views_[it->second].va; + } + + template + std::uint64_t resolve(Device& device, Address cpu, std::size_t bytes, Copy copy) { + if (!bytes || bytes > UINTPTR_MAX - cpu) return 0; + std::lock_guard lock(mutex_); + const auto key = std::make_pair(cpu, bytes); + if (const auto it = keys_.find(key); it != keys_.end()) + return it->second == refused ? 0 : views_[it->second].va; + std::uint8_t* mapped{}; + VkDeviceSize va{}; + bool at_cap = false; + if (bytes > cap() - bytes_ || !pool_.allocate(device, bytes, va, mapped, true, cap(), &at_cap)) { + if (at_cap || bytes > cap() - bytes_) { + keys_.emplace(key, refused); + if (++cap_refusals_ <= 4) + std::fprintf(stderr, "[rt] geometry buffer cap refused %zu bytes, %llu bytes already reserved\n", + bytes, static_cast(pool_.reserved())); + } else { + ++allocation_failures_; + } + return 0; + } + auto id = views_.size(); + keys_[key] = id; + by_address_.emplace(device.arena.address + va, id); + views_.push_back({cpu, bytes, mapped, va}); + bytes_ += bytes; + bool ready = true; + for (auto p = cpu & ~(tile_size - 1); p < cpu + bytes; p += tile_size) { + auto& tile = tiles_[p]; + // Previously watched tiles may have other dirty views waiting for refresh(). + if (!tile.primary) update(p, tile); + tile.views.push_back(id); + ready &= !tile.retry; + } + if (ready) fill(views_.back(), copy); + else { + std::memset(mapped, 0, bytes); + cleared_ += bytes; + views_.back().zeroed = true; + } + return va; + } + + template + void refresh(Copy copy) { + if (!cap()) return; + std::lock_guard lock(mutex_); + ++submissions_; + auto now = leonida::geometry_writes::state().serial.load(std::memory_order_acquire); + if (serial_ == now && !retry_) return; + const auto start = std::chrono::steady_clock::now(); + const auto before = uploaded_; + serial_ = now; + retry_ = false; + std::set changed; + for (auto& [va, tile] : tiles_) + if (update(va, tile)) changed.insert(tile.views.begin(), tile.views.end()); + for (auto id : changed) { + auto& view = views_[id]; + bool pinned = false; + for (auto p = view.source & ~(tile_size - 1); p < view.source + view.size; p += tile_size) + if (tiles_.at(p).retry) { pinned = true; break; } + if (!pinned) fill(view, copy); + } + if (uploaded_ != before) ++dirty_refreshes_; + refilled_ += uploaded_ - before; + refresh_time_ += std::chrono::steady_clock::now() - start; + } + + bool lookup(VkDeviceAddress bda, std::uint64_t& host, std::uint64_t& bytes, std::uint64_t* source = nullptr, + bool* populated = nullptr) const { + std::lock_guard lock(mutex_); + auto it = by_address_.upper_bound(bda); + if (it == by_address_.begin()) return false; + --it; + const auto offset = bda - it->first; + const auto& v = views_[it->second]; + if (offset >= v.size) return false; + bytes = v.size - offset; + host = reinterpret_cast
(v.dst) + offset; + if (source) *source = v.source + offset; + if (populated) *populated = v.ready; + return true; + } + void report() const { + if (!cap()) return; + std::lock_guard lock(mutex_); + std::fprintf(stderr, "[rt] geometry buffers: seen %zu, backed %zu (%llu bytes), populated %llu, cap %llu MiB, " + "cap refused %llu, allocation failures %llu, uploads %llu (%llu bytes), watched tiles %zu, reserved %llu bytes\n", + keys_.size(), views_.size(), (unsigned long long)bytes_, (unsigned long long)ready_, + (unsigned long long)(cap() >> 20), (unsigned long long)cap_refusals_, (unsigned long long)allocation_failures_, (unsigned long long)uploads_, + (unsigned long long)uploaded_, tiles_.size(), + static_cast(pool_.reserved())); + std::fprintf(stderr, "[rt] geometry refresh: %llu/%llu submissions uploaded dirty views, %llu bytes; " + "%.3f s checking and refreshing sources, %llu bytes cleared\n", + static_cast(dirty_refreshes_), static_cast(submissions_), + static_cast(refilled_), std::chrono::duration(refresh_time_).count(), + static_cast(cleared_)); + } + template + void release(Device& d) { + for (auto& [va, tile] : tiles_) { + for (auto [peer, cell] : tile.peers) leonida::geometry_writes::release(peer); + leonida::geometry_writes::release(va); + } + tiles_.clear(); + pool_.release(d); + } +}; +} // namespace rt::d3d12 diff --git a/runtime/shims/d3d12_pipeline_checkpoint.h b/runtime/shims/d3d12_pipeline_checkpoint.h new file mode 100644 index 0000000000..7756818a9b --- /dev/null +++ b/runtime/shims/d3d12_pipeline_checkpoint.h @@ -0,0 +1,97 @@ +// Win32 staging for a Vulkan session cache. Fill the mapped file directly so a +// checkpoint does not need a second, cache-sized private heap allocation. +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace rt::d3d12 { +struct CompileActivity { + std::atomic& count; + explicit CompileActivity(std::atomic& active) : count(active) { ++count; } + ~CompileActivity() { --count; } +}; + +inline bool direct_session_cache() { + static const bool enabled = [] { + wchar_t value[2]{}; + return !(GetEnvironmentVariableW(L"LEONIDA_DIRECT_SESSION_CACHE", value, 2) == 1 && value[0] == L'0'); + }(); + return enabled; +} + +// Both generations of staging filenames use two unsigned decimal components. +inline bool cache_temp_suffix(std::wstring_view suffix) { + const auto dot = suffix.find(L'.'); + return dot != suffix.npos && dot > 0 && dot + 1 < suffix.size() && + suffix.substr(0, dot).find_first_not_of(L"0123456789") == suffix.npos && + suffix.substr(dot + 1).find_first_not_of(L"0123456789") == suffix.npos; +} + +inline void clean_stale_cache_files(const std::filesystem::path& target) { + namespace fs = std::filesystem; + if (target.empty()) return; + const auto prefix = target.filename().wstring() + L".tmp."; + const auto cutoff = fs::file_time_type::clock::now() - std::chrono::minutes(10); + std::error_code ec; + for (fs::directory_iterator it(target.parent_path(), ec), end; !ec && it != end; it.increment(ec)) { + const auto name = it->path().filename().wstring(); + if (!name.starts_with(prefix) || !cache_temp_suffix(std::wstring_view(name).substr(prefix.size()))) continue; + std::error_code stat; + if (it->symlink_status(stat).type() != fs::file_type::regular || stat || + it->last_write_time(stat) >= cutoff || stat) continue; + // No sharing: an open writer/reader prevents cleanup, even after the age threshold. + HANDLE orphan = CreateFileW(it->path().c_str(), DELETE, 0, nullptr, OPEN_EXISTING, + FILE_FLAG_DELETE_ON_CLOSE | FILE_FLAG_OPEN_REPARSE_POINT, nullptr); + if (orphan != INVALID_HANDLE_VALUE) CloseHandle(orphan); + } +} + +class CacheStagingFile { +public: + void* data = nullptr; + + CacheStagingFile(const std::filesystem::path& destination, std::size_t bytes) { + static std::atomic sequence{0}; + temp_ = destination; + temp_ += L".tmp." + std::to_wstring(std::chrono::steady_clock::now().time_since_epoch().count()) + L"." + std::to_wstring(sequence++); + file_ = CreateFileW(temp_.c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, + CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr); + if (file_ == INVALID_HANDLE_VALUE) return; + const auto length = static_cast(bytes); + HANDLE mapping = CreateFileMappingW(file_, nullptr, PAGE_READWRITE, DWORD(length >> 32), DWORD(length), nullptr); + if (!mapping) return; + data = MapViewOfFile(mapping, FILE_MAP_WRITE, 0, 0, bytes); + CloseHandle(mapping); + } + CacheStagingFile(const CacheStagingFile&) = delete; + CacheStagingFile& operator=(const CacheStagingFile&) = delete; + ~CacheStagingFile() { + if (data) UnmapViewOfFile(data); + if (file_ != INVALID_HANDLE_VALUE) { + CloseHandle(file_); + DeleteFileW(temp_.c_str()); + } + } + + bool publish(const std::filesystem::path& destination, std::size_t written) { + if (!UnmapViewOfFile(data)) return false; + data = nullptr; + LARGE_INTEGER length{}; + length.QuadPart = static_cast(written); + if (!SetFilePointerEx(file_, length, nullptr, FILE_BEGIN) || !SetEndOfFile(file_)) return false; + CloseHandle(file_); + file_ = INVALID_HANDLE_VALUE; + if (MoveFileExW(temp_.c_str(), destination.c_str(), MOVEFILE_REPLACE_EXISTING)) return true; + DeleteFileW(temp_.c_str()); + return false; + } +private: + std::filesystem::path temp_; + HANDLE file_ = INVALID_HANDLE_VALUE; +}; +} // namespace rt::d3d12 diff --git a/runtime/shims/d3d12_pipeline_compile.h b/runtime/shims/d3d12_pipeline_compile.h new file mode 100644 index 0000000000..2ae78e24d7 --- /dev/null +++ b/runtime/shims/d3d12_pipeline_compile.h @@ -0,0 +1,128 @@ +// Timing and scheduling for Vulkan pipeline creation on the D3D12 device. +#pragma once + +#include "../src/vulkan_replay.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace rt::d3d12 { +inline bool trace_pipeline_compile() { + static const bool on = [] { + wchar_t v[2]{}; + return GetEnvironmentVariableW(L"LEONIDA_TRACE_PIPELINE_COMPILE", v, 2) == 1 && v[0] == L'1'; + }(); + return on; +} + +inline bool async_replay_compile() { + static const bool on = [] { + wchar_t v[2]{}; + return GetEnvironmentVariableW(L"LEONIDA_ASYNC_PIPELINES", v, 2) == 1 && v[0] == L'1'; + }(); + return on && !leonida::strict_replay(); +} + +// Absolute monotonic timestamps let trace readers distinguish time in the ICD from time queued for the worker. +using CompileClock = std::chrono::steady_clock; +inline long long compile_us() { + return std::chrono::duration_cast(CompileClock::now().time_since_epoch()).count(); +} + +inline long long compile_wall_ms() { + return std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()).count(); +} + +template VkPipeline replay_pipeline(const char* trigger, Build&& get) { + if (!trace_pipeline_compile()) return get(); + const auto start = compile_us(); + auto handle = get(); + auto elapsed = compile_us() - start; + if (elapsed >= 1000) + std::fprintf(stderr, "[rt] pipeline-use trigger=%s tid=%lu us=%lld ready=%d end_ms=%lld\n", + trigger, GetCurrentThreadId(), elapsed, int(handle != VK_NULL_HANDLE), compile_wall_ms()); + return handle; +} + +struct CompileTrace { + VkPipelineCreationFeedback feedback{}; + VkPipelineCreationFeedbackCreateInfo chain{VK_STRUCTURE_TYPE_PIPELINE_CREATION_FEEDBACK_CREATE_INFO, + nullptr, &feedback, 0, nullptr}; + long long started = 0; + const char* key = "-"; + + template void begin(Info& info, bool supported, const char* trigger, const char* shaders, + std::uint32_t variant, std::size_t bytes, const std::string& description_key) { + if (!trace_pipeline_compile()) return; + if (!description_key.empty()) key = description_key.c_str(); + if (supported) { + chain.pNext = info.pNext; + info.pNext = &chain; + } + std::fprintf(stderr, "[rt] pipeline-compile-begin trigger=%s tid=%lu bytes=%zu variant=%u begin_ms=%lld key=%s shaders=%s\n", + trigger, GetCurrentThreadId(), bytes, variant, compile_wall_ms(), key, shaders); + started = compile_us(); + } + + void end(const char* trigger, const char* shaders, std::uint32_t variant, std::size_t bytes, VkResult result) const { + if (!started) return; + const auto ended = compile_us(); + const int hit = !(feedback.flags & VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT) ? -1 : + int((feedback.flags & VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT) != 0); + std::fprintf(stderr, "[rt] pipeline-compile trigger=%s tid=%lu start_us=%lld us=%lld hit=%d bytes=%zu " + "variant=%u result=%d end_ms=%lld key=%s shaders=%s\n", trigger, GetCurrentThreadId(), started, + ended - started, hit, bytes, variant, int(result), compile_wall_ms(), key, shaders); + } +}; + + +// Demanded work has priority zero, speculative work is ordered by module size, and +// an idle checkpoint runs last. Jobs own their object until they finish. No Vulkan +// call runs with the queue lock held. The worker outlives individual D3D12 devices. +class PipelineCompiler { +public: + static PipelineCompiler& instance() { + static auto* pool = new PipelineCompiler; + return *pool; + } + void submit(std::size_t priority, std::function work) { + std::lock_guard lock(mutex_); + if (!started_) { + std::thread([this] { run(); }).detach(); + started_ = true; + } + jobs_.emplace(priority, std::move(work)); + wake_.notify_one(); + } + bool has_compile_waiter() { + std::lock_guard lock(mutex_); + return !jobs_.empty() && jobs_.begin()->first != SIZE_MAX; + } +private: + void run() { + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL); + for (;;) { + std::function job; + { + std::unique_lock wait(mutex_); + wake_.wait(wait, [this] { return !jobs_.empty(); }); + auto first = jobs_.begin(); + job = std::move(first->second); + jobs_.erase(first); + } + job(); + } + } + std::mutex mutex_; + std::condition_variable wake_; + std::multimap> jobs_; + bool started_ = false; +}; +} // namespace rt::d3d12 diff --git a/runtime/shims/d3d12_title_buffer_windows.h b/runtime/shims/d3d12_title_buffer_windows.h new file mode 100644 index 0000000000..5531d29a43 --- /dev/null +++ b/runtime/shims/d3d12_title_buffer_windows.h @@ -0,0 +1,119 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace rt::d3d12 { + +// Storage for shader-addressed mirrors when the main arena has no usable offset. +// A window lasts for the lifetime of the device, so these blocks only grow. +class TitleBufferWindows { + struct Block { + VkBuffer buffer{}; + VkDeviceMemory memory{}; + VkDeviceAddress address{}; + VkDeviceSize capacity{}, used{}; + std::uint8_t* mapped{}; + }; + std::vector blocks_; + VkDeviceSize reserved_{}; + +public: + VkDeviceSize reserved() const { return reserved_; } + + template + bool allocate(Device& d, VkDeviceSize bytes, VkDeviceSize& offset, std::uint8_t*& mapped, + bool device_local = false, VkDeviceSize cap = UINT64_MAX, bool* at_cap = nullptr) { + const VkDeviceSize alignment = device_local ? 16 : 65536; + constexpr VkDeviceSize block_size = 4ull << 20; + auto take = [&](Block& b) { + const auto start = (b.used + alignment - 1) & ~(alignment - 1); + if (start > b.capacity || bytes > b.capacity - start) return false; + mapped = b.mapped + start; + offset = b.address - d.arena.address + start; + b.used = start + bytes; + return true; + }; + if (!blocks_.empty() && take(blocks_.back())) return true; + // A large view may start a new slab while smaller views still fit earlier tails. + // Use those tails even after the budget can no longer accommodate another slab. + if (device_local && blocks_.size() > 1) + for (std::size_t i = blocks_.size() - 1; i != 0; --i) + if (take(blocks_[i - 1])) return true; + auto& vk = d.context->vk; + if (!vk.vkGetBufferDeviceAddress) return false; + Block b{}; + b.capacity = std::max(bytes, block_size); + if (b.capacity > cap - reserved_) { + if (at_cap) *at_cap = true; + return false; + } + VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; + info.size = b.capacity; + info.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; + d.share(info); + if (vk.vkCreateBuffer(d.info.device, &info, nullptr, &b.buffer) != VK_SUCCESS) return false; + VkMemoryRequirements req{}; + vk.vkGetBufferMemoryRequirements(d.info.device, b.buffer, &req); + if (req.size > cap - reserved_) { + if (at_cap) *at_cap = true; + vk.vkDestroyBuffer(d.info.device, b.buffer, nullptr); + return false; + } + b.memory = d.allocate(req, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | + (device_local ? VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT : 0), + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, nullptr, true); + void* host{}; + if (b.memory && vk.vkBindBufferMemory(d.info.device, b.buffer, b.memory, 0) == VK_SUCCESS && + vk.vkMapMemory(d.info.device, b.memory, 0, VK_WHOLE_SIZE, 0, &host) == VK_SUCCESS) { + VkBufferDeviceAddressInfo address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; + address.buffer = b.buffer; + b.address = vk.vkGetBufferDeviceAddress(d.info.device, &address); + const auto biased = b.address - d.arena.address; + // A positive 47-bit offset works with both generations of the translated V# decoder. + if (b.address && biased < (1ull << 47) && b.capacity <= (1ull << 47) - biased) { + b.mapped = static_cast(host); + blocks_.push_back(b); + reserved_ += req.size; + if (blocks_.size() == 1 || !(blocks_.size() & (blocks_.size() - 1))) + std::fprintf(stderr, "[rt] d3d12: title buffer shadows outside the arena: %zu blocks, " + "new block %llu KiB at shader VA 0x%llx\n", blocks_.size(), + static_cast(b.capacity >> 10), + static_cast(biased)); + return take(blocks_.back()); + } + vk.vkUnmapMemory(d.info.device, b.memory); + } + vk.vkDestroyBuffer(d.info.device, b.buffer, nullptr); + if (b.memory) vk.vkFreeMemory(d.info.device, b.memory, nullptr); + return false; + } + + bool lookup(VkDeviceAddress address, std::uint64_t& host, std::uint64_t& remaining) const { + for (const auto& b : blocks_) { + const auto delta = address - b.address; + if (delta < b.used) { + host = reinterpret_cast(b.mapped) + delta; + remaining = b.used - delta; + return true; + } + } + return false; + } + + // Device idle. No tracker writes into the blocks after this point. + template + void release(Device& d) { + for (auto& b : blocks_) { + d.context->vk.vkUnmapMemory(d.info.device, b.memory); + d.context->vk.vkDestroyBuffer(d.info.device, b.buffer, nullptr); + d.context->vk.vkFreeMemory(d.info.device, b.memory, nullptr); + } + blocks_.clear(); + reserved_ = 0; + } +}; +} // namespace rt::d3d12 diff --git a/runtime/shims/d3d12_title_image_census.h b/runtime/shims/d3d12_title_image_census.h new file mode 100644 index 0000000000..4d374fce85 --- /dev/null +++ b/runtime/shims/d3d12_title_image_census.h @@ -0,0 +1,85 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace rt::d3d12 { + +// Caller holds the registry lock. Counters describe current placements, excluding superseded GPU aliases. +template +void log_title_image_uses(const Registry& textures, std::size_t retired_count, std::uint64_t retired_bytes, std::uint64_t shared_bytes) { + std::size_t unbound = 0, unbound_placed = 0; + std::uint64_t unbound_bytes = 0, unbound_placed_bytes = 0; + // Two aliases of a stream-pool address resolve to the same CPU pages. Compare only live registry entries. + std::set placed_addresses; + std::uint64_t attachments = 0, duplicates = 0, gpu_written = 0, cpu_unfilled = 0; + std::size_t attachment_count = 0, duplicate_count = 0; + std::uint64_t cold = 0, cold_4k = 0, replayed = 0, shader_only = 0; + struct AllocationClass { std::uint64_t bytes = 0, unbound = 0, cold = 0; unsigned count = 0; }; + using Shape = std::tuple; + std::map classes; + for (const auto& [address, t] : textures) { + if (t->owned) { + unbound += t->unbound_bytes != 0; + unbound_bytes += t->unbound_bytes; + continue; + } + unbound_placed += t->unbound_bytes != 0; + unbound_placed_bytes += t->unbound_bytes; + placed_addresses.insert(t->cpu); + const auto& d = t->resource->desc(); + auto& c = classes[{d.Width, d.Height, unsigned(d.Format), unsigned(d.Flags), d.SampleDesc.Count}]; + ++c.count; + c.bytes += t->backing_bytes; + c.unbound += t->unbound_bytes; + if (t->resource->replay_seen()) replayed += t->backing_bytes; + else if (t->resource->shader_views()) shader_only += t->backing_bytes; + else if (!t->mapped && !t->fills) { + c.cold += t->backing_bytes; + cold += t->backing_bytes; + if (t->attachment_4k) cold_4k += t->backing_bytes; + } + if (t->attachment_4k) { + ++attachment_count; + attachments += t->backing_bytes; + } + if (t->gpu_written) gpu_written += t->backing_bytes; + else if (!t->fills) cpu_unfilled += t->backing_bytes; + } + for (const auto& [address, t] : textures) { + if (!t->owned || !placed_addresses.contains(t->cpu)) continue; + ++duplicate_count; + duplicates += t->backing_bytes; + } + constexpr double mib = 1.0 / 1048576.0; + std::fprintf(stderr, "[rt] mem-probe: %zu unbound slot-133 images, %.1f MiB backing deferred, %.1f MiB shared zero images\n", + unbound_placed, unbound_placed_bytes * mib, shared_bytes * mib); + std::fprintf(stderr, "[rt] mem-probe: slot-133 %.1f MiB referenced by replay/present, %.1f MiB with only " + "shader descriptors; %.1f MiB with no replay, shader descriptor, map or fill " + "(%.1f MiB 4K attachments)\n", replayed * mib, shader_only * mib, cold * mib, cold_4k * mib); + std::vector> ranked(classes.begin(), classes.end()); + std::sort(ranked.begin(), ranked.end(), [](const auto& a, const auto& b) { + return a.second.bytes + a.second.unbound > b.second.bytes + b.second.unbound; + }); + for (std::size_t i = 0; i < std::min(8, ranked.size()); ++i) { + const auto& [shape, c] = ranked[i]; + const auto& [w, h, fmt, flags, samples] = shape; + std::fprintf(stderr, "[rt] mem-probe: slot-133 %llux%u DXGI %u flags 0x%x samples %u: %u images %.1f MiB " + "backed, %.1f MiB deferred (%.1f MiB of backing untouched)\n", + (unsigned long long)w, h, fmt, flags, samples, c.count, c.bytes * mib, c.unbound * mib, c.cold * mib); + } + std::fprintf(stderr, "[rt] mem-probe: %zu unbound slot-70 images, %.1f MiB backing deferred; " + "%zu retired awaiting release %.1f MiB; %zu slot-70 images sharing slot-133 base %.1f MiB; " + "slot-133 GPU-writable %.1f MiB including %zu 4K attachments %.1f MiB; " + "CPU-fillable without a fill %.1f MiB\n", + unbound, unbound_bytes * mib, retired_count, retired_bytes * mib, + duplicate_count, duplicates * mib, gpu_written * mib, attachment_count, attachments * mib, + cpu_unfilled * mib); +} + +} // namespace rt::d3d12 diff --git a/runtime/shims/d3d12_title_image_upload.h b/runtime/shims/d3d12_title_image_upload.h new file mode 100644 index 0000000000..7b7dcb8e6e --- /dev/null +++ b/runtime/shims/d3d12_title_image_upload.h @@ -0,0 +1,201 @@ +#pragma once + +#include "xg_xs_layout.h" +#include "../src/vulkan_backend.h" + +namespace rt::d3d12 { + +// One upload buffer and command buffer per device, used under the title-texture registry lock. +// A whole image (including arrays and compressed mip tails) is detiled into the mapped buffer. +// The transfer never re-enters the D3D12 queue's pre-submit callbacks. +class TitleImageUpload { +public: + VkDeviceSize capacity() const { return capacity_; } + + template + void release(Device& d) { + auto& vk = d.context->vk; + release_buffer(d); + if (pool_) vk.vkDestroyCommandPool(d.info.device, pool_, nullptr); + if (ready_) vk.vkDestroySemaphore(d.info.device, ready_, nullptr); + pool_ = VK_NULL_HANDLE; + command_ = VK_NULL_HANDLE; + ready_ = VK_NULL_HANDLE; + } + + template + bool write(Device& d, leonida::ResourceId id, const leonida::ResourceBinding& image, + const xg_xs::Texture& layout, const std::uint8_t* tiled, std::vector& columns, + bool inspect, bool& nonzero) { + const auto block = leonida::copy_block_format(image, VK_IMAGE_ASPECT_COLOR_BIT); + const auto mips = layout.layout.mips; + const auto layers = layout.array; + if (!block.bytes || block.bytes != layout.format.bytes || !mips || mips > image.mip_levels || + !layers || layers > image.array_layers) return false; + + regions_.clear(); + VkDeviceSize bytes = 0; + for (unsigned layer = 0; layer < layers; ++layer) { + for (unsigned level = 0; level < mips; ++level) { + const auto& mip = layout.layout.plane[0].mips[level]; + VkBufferImageCopy copy{}; + copy.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, level, layer, 1}; + copy.imageExtent = {std::max(1u, image.width >> level), std::max(1u, image.height >> level), + image.volume ? std::max(1u, image.depth >> level) : 1u}; + if (mip.width_elements != (copy.imageExtent.width + block.block - 1) / block.block || + mip.height_elements != (copy.imageExtent.height + block.block - 1) / block.block || + (image.volume && mip.depth != copy.imageExtent.depth)) return false; + // Vulkan requires offsets aligned to four bytes and to the texel block size. + const auto align = 4u * block.bytes; + copy.bufferOffset = bytes + (align - bytes % align) % align; + const VkDeviceSize row = VkDeviceSize(mip.width_elements) * block.bytes; + const VkDeviceSize slice = row * mip.height_elements; + if (slice > UINT32_MAX || (UINT64_MAX - copy.bufferOffset) / copy.imageExtent.depth < slice) return false; + bytes = copy.bufferOffset + slice * copy.imageExtent.depth; + regions_.push_back(copy); + } + } + if (!prepare(d, bytes)) return false; + for (const auto& copy : regions_) { + const auto level = copy.imageSubresource.mipLevel; + const auto& mip = layout.layout.plane[0].mips[level]; + const auto row = mip.width_elements * block.bytes, slice = row * mip.height_elements; + auto* dst = mapped_ + copy.bufferOffset; + xg_xs::copy_elements(layout, level, copy.imageSubresource.baseArrayLayer, tiled, dst, row, slice, columns); + if (inspect && !nonzero) + nonzero = std::any_of(dst, dst + VkDeviceSize(slice) * copy.imageExtent.depth, + [](std::uint8_t c) { return c != 0; }); + } + + const VkImageSubresourceRange range{VK_IMAGE_ASPECT_COLOR_BIT, 0, mips, 0, layers}; + const auto result = d.context->write_staged_title_image(id, range, [&](const leonida::ReplayFunctions& replay, + const leonida::LayoutPieces& pieces) { + auto& vk = d.context->vk; + VkResult r = vk.vkResetCommandBuffer(command_, 0); + if (r != VK_SUCCESS) return r; + VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; + begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + if ((r = vk.vkBeginCommandBuffer(command_, &begin)) != VK_SUCCESS) return r; + // All texels of every mip/layer named in range are overwritten. Prior reads already finished. + leonida::detail::image_barrier(replay, command_, image, range, VK_IMAGE_LAYOUT_UNDEFINED, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 0, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, + VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); + vk.vkCmdCopyBufferToImage(command_, buffer_, image.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + static_cast(regions_.size()), regions_.data()); + for (const auto& piece : pieces) + leonida::detail::image_barrier(replay, command_, image, piece.range, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + piece.layout == VK_IMAGE_LAYOUT_UNDEFINED ? VK_IMAGE_LAYOUT_GENERAL : piece.layout, + VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); + if ((r = vk.vkEndCommandBuffer(command_)) != VK_SUCCESS) return r; + return submit(d); + }); + return result == VK_SUCCESS; + } + +private: + template + void release_buffer(Device& d) { + auto& vk = d.context->vk; + if (buffer_) vk.vkDestroyBuffer(d.info.device, buffer_, nullptr); + if (memory_) vk.vkFreeMemory(d.info.device, memory_, nullptr); + buffer_ = VK_NULL_HANDLE; + memory_ = VK_NULL_HANDLE; + mapped_ = nullptr; + capacity_ = 0; + } + + template + bool prepare(Device& d, VkDeviceSize size) { + auto& vk = d.context->vk; + const auto dev = d.info.device; + if (!pool_) { + VkCommandPoolCreateInfo pool{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; + pool.queueFamilyIndex = d.info.queue_family; + pool.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; + if (vk.vkCreateCommandPool(dev, &pool, nullptr, &pool_) != VK_SUCCESS) return false; + } + if (!command_) { + VkCommandBufferAllocateInfo alloc{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; + alloc.commandPool = pool_; + alloc.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; + alloc.commandBufferCount = 1; + if (vk.vkAllocateCommandBuffers(dev, &alloc, &command_) != VK_SUCCESS) return false; + } + if (!ready_) { + VkSemaphoreTypeCreateInfo timeline{VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO}; + timeline.semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE; + VkSemaphoreCreateInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, &timeline}; + if (vk.vkCreateSemaphore(dev, &info, nullptr, &ready_) != VK_SUCCESS) return false; + for (const auto* qs : {&d.info.command_queues, &d.info.compute_queues, &d.info.copy_queues}) + for (auto q : *qs) + if (q && q != d.info.queue && std::find(consumers_.begin(), consumers_.end(), q) == consumers_.end()) + consumers_.push_back(q); + } + if (size <= capacity_) return true; + release_buffer(d); + VkBufferCreateInfo buffer{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; + buffer.size = size; + buffer.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; + if (vk.vkCreateBuffer(dev, &buffer, nullptr, &buffer_) != VK_SUCCESS) return false; + VkMemoryRequirements req{}; + vk.vkGetBufferMemoryRequirements(dev, buffer_, &req); + memory_ = d.allocate(req, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, 0); + void* map = nullptr; + if (!memory_ || vk.vkBindBufferMemory(dev, buffer_, memory_, 0) != VK_SUCCESS || + vk.vkMapMemory(dev, memory_, 0, VK_WHOLE_SIZE, 0, &map) != VK_SUCCESS) { + release_buffer(d); + return false; + } + mapped_ = static_cast(map); + capacity_ = size; + return true; + } + + template + VkResult submit(Device& d) { + auto& vk = d.context->vk; + ++value_; + VkTimelineSemaphoreSubmitInfo timeline{VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO}; + timeline.signalSemaphoreValueCount = 1; + timeline.pSignalSemaphoreValues = &value_; + VkSubmitInfo transfer{VK_STRUCTURE_TYPE_SUBMIT_INFO, &timeline}; + transfer.commandBufferCount = 1; + transfer.pCommandBuffers = &command_; + transfer.signalSemaphoreCount = 1; + transfer.pSignalSemaphores = &ready_; + auto r = vk.vkQueueSubmit(d.info.queue, 1, &transfer, VK_NULL_HANDLE); + if (r != VK_SUCCESS) return r; + // The registry may reuse these mapped bytes or retire the image as soon as write() returns. + VkSemaphoreWaitInfo done{VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO}; + done.semaphoreCount = 1; + done.pSemaphores = &ready_; + done.pValues = &value_; + if ((r = vk.vkWaitSemaphores(d.info.device, &done, UINT64_MAX)) != VK_SUCCESS) return r; + // GPU writes become visible to later submissions on every other queue. The primary queue has the image barrier. + VkTimelineSemaphoreSubmitInfo acquire{VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO}; + acquire.waitSemaphoreValueCount = 1; + acquire.pWaitSemaphoreValues = &value_; + VkPipelineStageFlags stages = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; + VkSubmitInfo wait{VK_STRUCTURE_TYPE_SUBMIT_INFO, &acquire}; + wait.waitSemaphoreCount = 1; + wait.pWaitSemaphores = &ready_; + wait.pWaitDstStageMask = &stages; + for (auto q : consumers_) + if ((r = vk.vkQueueSubmit(q, 1, &wait, VK_NULL_HANDLE)) != VK_SUCCESS) return r; + return VK_SUCCESS; + } + + VkBuffer buffer_{}; + VkDeviceMemory memory_{}; + std::uint8_t* mapped_ = nullptr; + VkDeviceSize capacity_ = 0; + VkCommandPool pool_{}; + VkCommandBuffer command_{}; + VkSemaphore ready_{}; + std::uint64_t value_ = 0; + std::vector consumers_; + std::vector regions_; +}; + +} // namespace rt::d3d12 diff --git a/runtime/shims/d3d12_trace.h b/runtime/shims/d3d12_trace.h index 82432eb182..9c749b8b4f 100644 --- a/runtime/shims/d3d12_trace.h +++ b/runtime/shims/d3d12_trace.h @@ -9,6 +9,9 @@ namespace rt::d3d12_trace { inline std::atomic tracing{false}; +// Correlate an Xbox stream audit with its backend result, including concurrent creation jobs. +inline thread_local unsigned long long last_sequence = 0; +inline thread_local const char* stream_refusal = nullptr; inline void set_enabled(bool enable) noexcept { tracing.store(enable, std::memory_order_relaxed); @@ -24,7 +27,8 @@ inline void record(const char* method, const char* outcome = "called") noexcept static std::mutex mutex; static unsigned long long sequence = 0; const std::lock_guard lock(mutex); - std::fprintf(stderr, "[d3d12-trace] #%llu %s %s\n", ++sequence, method, outcome); + last_sequence = ++sequence; + std::fprintf(stderr, "[d3d12-trace] #%llu %s %s\n", last_sequence, method, outcome); std::fflush(stderr); } diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 8ff20b5a4c..d32ebed3d0 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -1,3 +1,4 @@ +#include "../src/shader_directory.h" // A Vulkan-backed ID3D12Device (PC ABI) for the Xbox-ABI device proxy (d3d12_xs_device.cpp) to forward to. // Implemented: queues, allocators, command lists, fences, descriptor heaps, render-target and depth-stencil views, // committed buffers and textures (1D, 1D arrays, 2D, multisampled 2D, 3D) and their 1/2/3 variants, allocation @@ -8,30 +9,51 @@ #define VK_USE_PLATFORM_WIN32_KHR #endif #include "d3d12_com.h" +#include "d3d12_pipeline_compile.h" +#include "d3d12_pipeline_checkpoint.h" #include "d3d12_feature_compat.h" #include "d3d12_stubs.h" // generated #include "d3d12_com_object.h" #include "d3d12_trace.h" #include "d3d12_xs_device.h" +#include "d3d12_xs_pso_stream.h" +#include "xg_xs_layout.h" +#include "d3d12_title_image_upload.h" +#include "d3d12_title_buffer_windows.h" +#include "d3d12_geometry_views.h" +#include "d3d12_title_image_census.h" #include "dxgi_com.h" #include "../src/arena_size.h" #include "../src/gfx10_descriptors.h" #include "../src/depth24_fragment.h" +#include "../src/rect_list_geometry.h" #include "../src/uav_clear.h" #include "../src/vulkan_bindless.h" #include "../src/vulkan_memory.h" #include "../src/vulkan_mesh_limits.h" #include "../src/resource_tiling.h" #include "../src/cached_pso.h" +#include "../src/pipeline_profile.h" +#include "../src/pipeline_cache_store.h" #include "../src/conservative_raster.h" #include "../src/resource_detile.h" #include "../src/shader_library.h" +#include "../src/dstorage_trace.h" +#include "../src/title_page_watch.h" +#include "../src/title_geometry_watch.h" +#include "../src/title_texture_memory.h" +#include "../src/title_texture_refresh.h" +#include "title_gpu_placements.h" #include "../src/spirv_f16_halves.h" #include "../src/spirv_stores.h" +#include "../src/title_va_alias.h" #include "../src/vulkan_present.h" #include "../src/vulkan_device_filter.h" #include "../src/vulkan13_features.h" +#include "d3d12_compute_input_probe.h" +#include "../src/fsdraw_probe.h" // LOCAL DIAGNOSTIC +#include "../src/mem_probe.h" // LOCAL DIAGNOSTIC #include #ifdef _MSC_VER @@ -40,8 +62,10 @@ #include #include +#include #include #include +#include #include #include #include @@ -51,10 +75,14 @@ #include #include #include +#include +#include #include +#include #include #include #include +#include #include namespace rt::d3d12 { @@ -65,8 +93,12 @@ namespace { constexpr UINT kDescriptorSize = descriptor_size; // The first 64 KiB of the GPU address arena are never handed out: VA 0 stays invalid, and the page is kept zero // for unbound vertex and index buffers to read (D3D12 reads zeros there). -constexpr VkDeviceSize kArenaReserved = 64 * 1024; +constexpr VkDeviceSize kZeroPage = 64 * 1024; // zeroed: what unbound vertex and index buffers read +constexpr std::uint32_t kQuadIndexCount = 64 * 1024; // 0, 1, 2, ... that non-indexed quad lists draw with (16384 quads) +constexpr VkDeviceSize kArenaReserved = kZeroPage + VkDeviceSize(kQuadIndexCount) * sizeof(std::uint32_t); static_assert(sizeof(leonida::TargetView) <= kDescriptorSize); +// pipeline_cache_store.h reads this layout without vulkan.h (D3D-704); remember the two. +static_assert(sizeof(VkPipelineCacheHeaderVersionOne) == leonida::pipeline_cache_store::header_bytes); // The shader model and root signature version this layer can honour. Nothing in the runtime compiles DXIL: the // game's shaders arrive as SPIR-V from the offline translator, and the only DXIL path (the BVH builder) is lowered @@ -78,11 +110,952 @@ constexpr D3D_ROOT_SIGNATURE_VERSION kHighestRootSignatureVersion = D3D_ROOT_SIG std::atomic g_global_realtime_privilege_override{-1}; -void log_once(const char* what, int value) { +bool first_diagnostic(const char* what, int value) { static std::mutex mutex; static std::set> seen; std::lock_guard lock(mutex); - if (seen.insert({what, value}).second) std::fprintf(stderr, "[rt] d3d12: %s %d\n", what, value); + return seen.insert({what, value}).second; +} + +enum class TitleImageOrigin { ordinary, placed, streamed, pending_stream }; + +void log_once(const char* what, int value) { + if (first_diagnostic(what, value)) std::fprintf(stderr, "[rt] d3d12: %s %d\n", what, value); +} + +// The base address a V# gets for a buffer address: in the title's own memory (a slot-133 buffer, a constant ring), +// the console VA of a GPU copy of it (src/title_va_alias.h, docs/d3d12_vulkan.md section 3.3); anything else +// unchanged. A V# keeps 48 address bits. An arena copy always fits; an imported buffer's address is its device +// address minus heap_base, which wraps when the driver put it below the arena: logged, and written as before. +std::uint64_t vsharp_address(std::uint64_t va, std::uint64_t bytes, + leonida::TitleVaAliases::Kind kind = leonida::TitleVaAliases::created_view) { + const std::uint64_t to = leonida::title_va_aliases().resolve(va, bytes, kind); + if (to != va && (to >> 48)) { + log_once("a V# names a title-placed buffer whose GPU copy lies below heap_base, out of a V#'s 48 bits; " + "address bits 48-63:", + int(to >> 48)); + // Which buffers: a shader that zero-extends the 48 bits reads such a V# 2^48 above the buffer (measured + // natively: garbage, or a lost device). Each distinct 64 KiB-aligned title address once, the first 32. + static std::mutex mutex; + static std::set seen; + std::lock_guard lock(mutex); + if (seen.size() < 32 && seen.insert(va >> 16).second) + std::fprintf(stderr, + "[rt] d3d12: wrapped V#: title address 0x%llx (%llu bytes, view kind %d) -> offset 0x%llx " + "from heap_base\n", + static_cast(va), static_cast(bytes), int(kind), + static_cast(to)); + } + return to; +} + +// The CBV/SRV/UAV slots a descriptor table declares: the end of its furthest range (D3D12 appends a range at +// D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND), an unbounded range counted as 1024. 0 for a sampler table or no table. +std::uint32_t table_view_descriptors(const rt::rootsig::RootParameter& param) { + if (param.type != rt::rootsig::ParamType::Table) return 0; + constexpr std::uint32_t kUnbounded = 1024; + std::uint64_t next = 0, end = 0; + for (const auto& range : param.ranges) { + const std::uint64_t start = range.offset_in_table == D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND ? next + : range.offset_in_table; + const std::uint64_t count = range.num_descriptors == UINT_MAX ? kUnbounded : range.num_descriptors; + next = start + count; + if (range.range_type != D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER) end = std::max(end, next); + } + return std::uint32_t(std::min(end, kUnbounded)); +} + +// memcpy that a page fault ends instead of killing the process: the title may decommit a page between the +// VirtualQuery that saw it committed and the read. No C++ objects here: it is a __try frame. +// `streaming` reads with MOVNTDQA, for write-combined pages: ordinary loads from them are not cached, and memcpy +// read 64 MiB of them in 253 ms on a Core i9-13900K (253 MiB/s), MOVNTDQA in 13 to 17 ms (4 to 5 GiB/s). Paid at every submission. +#if defined(__clang__) && defined(_M_X64) +__attribute__((target("sse4.1"))) +#endif +bool copy_guarded(std::uint8_t* to, const std::uint8_t* from, std::size_t bytes, bool streaming) { + __try { + if (streaming) { + const std::size_t head = std::min(bytes, (0 - reinterpret_cast(from)) & 63); + std::memcpy(to, from, head); + to += head, from += head, bytes -= head; + for (; bytes >= 64; to += 64, from += 64, bytes -= 64) { + const auto* in = reinterpret_cast(from); + const __m128i a = _mm_stream_load_si128(in), b = _mm_stream_load_si128(in + 1); + const __m128i c = _mm_stream_load_si128(in + 2), d = _mm_stream_load_si128(in + 3); + auto* out = reinterpret_cast<__m128i*>(to); + _mm_storeu_si128(out, a), _mm_storeu_si128(out + 1, b); + _mm_storeu_si128(out + 2, c), _mm_storeu_si128(out + 3, d); + } + } + std::memcpy(to, from, bytes); + return true; + } __except (EXCEPTION_EXECUTE_HANDLER) { + return false; + } +} + +// A 64-bit digest of the bytes of a texture the title keeps in its own memory, to tell whether they changed since its +// image was filled (TitleTextures). Up to 256 KiB every byte; above, 64 bytes at the start and 64 at the middle of +// every 4 KiB page plus the last 64 bytes, about 3% of them: the title's writes into texture memory are whole tiles +// (streaming, file reads, XG copies) or whole planes (video), never a few bytes inside a page. The same sampling as +// OpenScarlett's texture hash before submission (src/gpu/d3d12_xs/device_x.cpp, f8e24d4, MIT), with more samples. +// False when a page faults (the title unmapped it). No C++ objects here: it is a __try frame. +inline std::uint64_t mix_words(std::uint64_t h, const std::uint8_t* at, std::size_t n) { + for (std::size_t i = 0; i + 8 <= n; i += 8) { + std::uint64_t w; + std::memcpy(&w, at + i, 8); + h = (h ^ w) * 0x100000001b3ull; + h ^= h >> 29; + } + return h; +} +bool hash_guarded(const std::uint8_t* p, std::size_t bytes, std::uint64_t& out, bool every_byte = false) { + __try { + std::uint64_t h = 0x9e3779b97f4a7c15ull ^ bytes; + if (bytes <= (256u << 10) || every_byte) { + h = mix_words(h, p, bytes & ~std::size_t(7)); + for (std::size_t i = bytes & ~std::size_t(7); i < bytes; ++i) h = (h ^ p[i]) * 0x100000001b3ull; + } else { + for (std::size_t page = 0; page + 4096 <= bytes; page += 4096) { + h = mix_words(h, p + page, 64); + h = mix_words(h, p + page + 2048, 64); + } + h = mix_words(h, p + bytes - 64, 64); + } + out = h; + return true; + } __except (EXCEPTION_EXECUTE_HANDLER) { + return false; + } +} +inline std::uint64_t hashed_bytes(std::uint64_t bytes, bool every_byte = false) { + return bytes <= (256u << 10) || every_byte ? bytes : bytes / 32 + 64; +} + +// Set while this thread is inside the title-texture registry (it holds title_texture_mutex): a staged copy it makes +// submits through a queue, whose before-submission refresh must then not take the registry again. +thread_local bool t_in_title_textures = false; +struct InTitleTextures { + bool was = std::exchange(t_in_title_textures, true); + ~InTitleTextures() { t_in_title_textures = was; } +}; + +// Copies a run of the title's pages that VirtualQuery saw committed and readable. A page decommitted since then reads +// as zeros, and only that page: the run is redone page by page, so the rest of it keeps its bytes. +void copy_run(std::uint8_t* to, const std::uint8_t* from, std::size_t bytes, bool streaming) { + if (copy_guarded(to, from, bytes, streaming)) return; + for (std::size_t off = 0; off < bytes;) { + const std::size_t in_page = reinterpret_cast(from + off) & 4095; + const std::size_t n = std::min(bytes - off, 4096 - in_page); + if (!copy_guarded(to + off, from + off, n, streaming)) std::memset(to + off, 0, n); + off += n; + } +} + +// The title's pages behind slot-133 shadow buffers and title windows, and which of them the title wrote since the +// copies were last brought up to date. Nothing says which pages a title writes, so the pages say it themselves: once +// copied, a read-write page is made read-only (its cache attribute kept: PAGE_READONLY | PAGE_WRITECOMBINE for a +// write-combined one), and the title's next write to it faults. The fault handler (shadow_write_fault) makes the +// 64 KiB around it writable again and the write goes on; reopening the page clears its watched state. Each refresh() +// walks the range with VirtualQuery, passing over pages still known clean when the title memory map hasn't changed: +// - read-write pages were written (or newly committed, or newly mapped by xmem): made read-only, then copied. A +// write landing between the two faults again, so it reaches the next refresh at the latest; +// - pages this tracker made read-only weren't written: skipped; +// - other readable pages (read-only or copy-on-write pages of the title's own, pages another tracker protected) +// can't be watched: copied every time, as before; +// - pages not committed, or not readable, are zero in the copies (written once); +// - pages xmem reports mapped at another address too (title_page_watch.h) are copied every time: a write +// through the other address doesn't fault here; +// - pages a file shim pinned for a kernel write (ReadFile into title memory, which fails with ERROR_NOACCESS on a +// read-only page instead of faulting) are left writable and copied every time until the pin ends. +// If the protection can't be changed (VirtualProtect refuses, or the fault handler couldn't be installed), those +// pages stay read-write and are copied at every submission: the whole-range copy this replaces. +// +// One tracker serves every copy of the pages it covers (its targets). A page has one owner that may make it +// read-only, so copies of the same 4 KiB page must share a tracker: the title places many slot-133 buffers of a few +// KiB back to back, off page boundaries (measured on Windows 11: 3,172 of 3,267 placements shared a page with +// another), and with a tracker each every buffer but one found its shared pages read-only, not its own, and queried +// and copied them again at every submission (3,045 VirtualQuery calls, 57 of 62 ms per refresh). DeviceState:: +// add_shadow keeps one tracker per run of pages that overlap or touch, and a written page reaches every target over +// it. A page no target covers any more (its buffer went) is left writable and passed over. +// +// Pages xmem reserved with MEM_WRITE_WATCH (leonida::title_write_watch: the title's ordinary memory, not its +// physical-page views) start guarded like the rest. A write fault on one makes its 64 KiB block hot: never made +// read-only again, it is asked about instead. Each refresh first asks the kernel which hot pages were written since +// the last asking (GetWriteWatch, which clears its bits), through the journal that keeps the answer for every other +// tracker over the same pages; then those, and pages not known yet, are copied, and the rest passed over. A write +// after the asking is in the next one. No fault, no VirtualProtect, and a kernel write needs no opening: hot pages +// stay writable. A block not found written for kCool refreshes is guarded again. Asking costs about 3 ns per page per +// refresh and a fault about three orders more, so the pages written often are asked about and the rest wait for their +// write (measured natively: asking about all 242 MiB of write-watched pages at every submission cost 2.4 ms per +// refresh, against 0.14 ms for the guards with their faults). A file shim's pin still marks a hot page written +// (reopen_range) and keeps it copied until the pin ends: a device's write into locked pages need not set the kernel's +// bit. +// +// The fault handler waits for g_shadow_pages_lock and a tracker's lock_, and the faulting thread may hold the process +// heap's lock (the title's XMemAlloc memory is _aligned_malloc's, whose headers HeapAlloc and HeapFree write on pages a +// tracker may guard). So nothing that holds either lock, or a lock taken under them (title_page_aliases, +// kernel_writes' pins, title_write_watch's record and journal), touches the process heap: their containers allocate +// from leonida::host_heap, a heap of the runtime's own, and logging waits until the lock is released. +class ShadowPages { + template + using Vector = leonida::host_heap::vector; + +public: + static constexpr std::uintptr_t kPage = 0x1000; + static constexpr std::uintptr_t kBlock = 0x10000; // what one write fault makes writable again + + ShadowPages(const std::uint8_t* pages, std::uint8_t* shadow, std::size_t size, bool watch) : watch_(watch) { + begin_ = reinterpret_cast(pages); + end_ = begin_ + size; + first_ = begin_ & ~(kPage - 1); + last_ = (end_ + kPage - 1) & ~(kPage - 1); + state_.assign((last_ - first_) / kPage, 0); + idle_.assign(state_.size(), 0); + cover_.assign(state_.size(), 1); + targets_.push_back({begin_, end_, shadow}); + index_targets(); + } + ~ShadowPages() { + if (reader_) leonida::title_write_watch::close_reader(reader_); + } + // Every page made read-only here is read-write again: the title's pages outlive the buffer. + void reopen_all() { + AcquireSRWLockExclusive(&lock_); + if (std::any_of(state_.begin(), state_.end(), [](std::uint8_t s) { return s & kProtected; })) + reopen_locked(first_, last_); + ReleaseSRWLockExclusive(&lock_); + } + ShadowPages(const ShadowPages&) = delete; + ShadowPages& operator=(const ShadowPages&) = delete; + + // The bytes of all targets, and how many there are. + std::size_t size() const { return target_bytes_; } + std::size_t targets() const { return targets_.size(); } + // The pages covered: [first(), last()), 4 KiB aligned. + std::uintptr_t first() const { return first_; } + std::uintptr_t last() const { return last_; } + bool contains(std::uintptr_t address) const { return address >= first_ && address < last_; } + std::uint64_t faults() const { return faults_.load(std::memory_order_relaxed); } + std::uint64_t refresh_queries() const { return refresh_queries_; } + std::uint64_t refresh_protects() const { return refresh_protects_; } + bool refresh_walked_all() const { return refresh_walked_all_; } + // GetWriteWatch calls of the last refresh(), the write-watched pages it found written, and the bytes of the + // covered pages that are write-watched, and of those asked about (hot). + std::uint64_t refresh_asks() const { return refresh_asks_; } + std::uint64_t refresh_written() const { return refresh_written_; } + std::size_t watched_bytes() const { return watched_pages_ * kPage; } + std::size_t hot_bytes() const { return hot_pages_ * kPage; } + + // The ranges the last refresh() copied from the pages, as (offset from the first target's start, bytes). Pages it + // zeroed are not among them. Only between refreshes, under the lock that serializes them. For a tracker with one + // target (a console descriptor heap's), whose offsets are the buffer's. + template + void for_each_copied(F&& f) const { + for (const Job& job : jobs_) f(job.offset, job.bytes); + } + + // The ranges the last refresh() zeroed in the copies (pages no longer committed or readable), likewise. + template + void for_each_zeroed(F&& f) const { + for (const Job& job : zeroed_) f(job.offset, job.bytes); + } + + // Brings every target up to date with the pages. Returns the bytes copied into them. + std::size_t refresh() { + jobs_.clear(); + zeroed_.clear(); + std::uint64_t queries = 0; + const std::uint64_t generation = leonida::title_page_aliases::generation(); + // LEONIDA_SHADOW_FULL_WALK=1 queries every page at every refresh, as before the generation skip. + static const bool always_full_walk = [] { + char value[8] = {}; + std::size_t length = 0; + return getenv_s(&length, value, sizeof(value), "LEONIDA_SHADOW_FULL_WALK") == 0 && length > 1 && + value[0] != '0'; + }(); + AcquireSRWLockExclusive(&lock_); + const std::uint64_t map_generation = leonida::title_memory_map::generation(); + const bool full_walk = always_full_walk || map_generation != map_generation_; + refresh_walked_all_ = full_walk; + refresh_protects_ = 0; + if (generation != alias_generation_) { + alias_generation_ = generation; + for (std::uint8_t& s : state_) s &= ~kAliased; + leonida::title_page_aliases::for_each_in(first_, last_, [&](std::uintptr_t va) { + const std::uintptr_t from = std::max(va, first_), to = std::min(va + kBlock, last_); + for (std::uintptr_t p = from; p < to; p += kPage) state_[(p - first_) / kPage] |= kAliased; + }); + } + if (pinned_) { + for (std::uint8_t& s : state_) s &= ~kPinned; + pinned_ = false; + } + leonida::kernel_writes::for_each_pin(first_, last_, [&](std::uintptr_t from, std::uintptr_t to) { + for (std::uintptr_t p = from & ~(kPage - 1); p < to; p += kPage) state_[(p - first_) / kPage] |= kPinned; + pinned_ = true; + }); + // The write-watched pages written since the last asking are no longer clean: asked before the walk, so a write + // after this is in the next asking. + const std::uint64_t watch_generation = leonida::title_write_watch::generation(); + if (watch_generation != watch_generation_) { + watch_generation_ = watch_generation; + update_watched(); + } + if (runs_stale_) rebuild_watch_runs(); + refresh_asks_ = refresh_written_ = 0; + if (!watch_runs_.empty()) { + if (!reader_) { + reader_ = leonida::title_write_watch::open_reader(); + forget_clean(); + } + refresh_asks_ = watch_runs_.size(); + leonida::title_write_watch::ask( + reader_, watch_runs_, + [&](std::uintptr_t from, std::uintptr_t to) { + for (std::uintptr_t p = from; p < to; p += kPage) { + std::uint8_t& s = state_[(p - first_) / kPage]; + if (!(s & kHot)) continue; // asked over a gap between hot pages: guarded + refresh_written_ += (s & kClean) != 0; + s &= ~kClean; + warm(p); + } + }, + [&](std::uintptr_t from, std::uintptr_t to) { + // Not write-watched after all (released and reserved again): guarded from now on. + for (std::uintptr_t p = from; p < to; p += kPage) + state_[(p - first_) / kPage] &= ~(kWatched | kClean | kHot); + runs_stale_ = true; + }); + cool(); // a block it guards again leaves the runs at the next refresh + } + for (std::uintptr_t at = first_; at < last_;) { + const std::size_t i0 = (at - first_) / kPage; + if (!cover_[i0]) { // no copy reads it: left as the title set it + std::size_t i = i0 + 1; + while (i < state_.size() && !cover_[i]) ++i; + at = first_ + i * kPage; + continue; + } + if (!full_walk && unchanged(state_[i0])) { + std::size_t i = i0 + 1; + while (i < state_.size() && unchanged(state_[i])) ++i; + at = first_ + i * kPage; + continue; + } + MEMORY_BASIC_INFORMATION region{}; + std::uintptr_t next = at + kPage; + Kind kind = Kind::zero; + ++queries; + if (VirtualQuery(reinterpret_cast(at), ®ion, sizeof(region))) { + next = std::min(last_, reinterpret_cast(region.BaseAddress) + region.RegionSize); + kind = classify(region); + } + std::size_t i1 = (next - first_) / kPage; + for (std::size_t i = i0 + 1; i < i1; ++i) + if (!cover_[i]) { // the region goes on past the pages copies read: the rest is passed over above + i1 = i; + next = first_ + i * kPage; + break; + } + const bool streaming = (region.Protect & PAGE_WRITECOMBINE) != 0; + switch (kind) { + case Kind::zero: + for (std::size_t i = i0; i < i1; ++i) { + if (state_[i] & kZero) continue; + const auto [offset, bytes] = span_of(i, i + 1); + zero_targets(offset, bytes); + if (!zeroed_.empty() && zeroed_.back().offset + zeroed_.back().bytes == offset) + zeroed_.back().bytes += bytes; + else + zeroed_.push_back({offset, bytes, false}); + state_[i] = std::uint8_t(kZero | (state_[i] & (kAliased | kPinned | kWatched))); + } + break; + case Kind::writable: + case Kind::read_only: + for (std::size_t i = i0; i < i1;) { + const Watch how = watch_of(state_[i]); + std::size_t j = i + 1; + while (j < i1 && watch_of(state_[j]) == how) ++j; + switch (how) { + case Watch::clean: break; // write-watched, not written since it was copied + case Watch::written: // write-watched: written since, or not known yet + for (std::size_t k = i; k < j; ++k) + state_[k] = std::uint8_t((state_[k] & ~(kZero | kProtected)) | kClean); + add_job(i, j, streaming); + break; + case Watch::open: // write-watched, but pinned for a kernel write: copied until the pin ends + for (std::size_t k = i; k < j; ++k) state_[k] &= ~(kZero | kProtected | kClean); + add_job(i, j, streaming); + break; + case Watch::guard: + if (kind == Kind::writable) + guard_writable(i, j, region.Protect, streaming); + else + guard_read_only(i, j, streaming); + break; + } + i = j; + } + break; + case Kind::unwatched: + for (std::size_t i = i0; i < i1; ++i) state_[i] &= kAliased | kPinned | kWatched; + add_job(i0, i1, streaming); + break; + } + at = next; + } + // Remember the generation from before the walk, so a change during the walk triggers another one. + map_generation_ = map_generation; + const DWORD protect_error = std::exchange(protect_error_, 0); + ReleaseSRWLockExclusive(&lock_); + if (protect_error) + log_once("slot-133 shadow: VirtualProtect refused to watch the title's pages for writes, so they are " + "copied at every submission; error", + int(protect_error)); + // The copies run without the lock: a write that faults meanwhile is let through and copied next time. + std::size_t copied = 0; + for (const Job& job : jobs_) + for_each_target(begin_ + job.offset, begin_ + job.offset + job.bytes, + [&](const Target& t, std::uintptr_t from, std::uintptr_t to) { + copy_run(t.shadow + (from - t.begin), reinterpret_cast(from), + to - from, job.streaming); + copied += to - from; + }); + refresh_queries_ = queries; + return copied; + } + + // DeviceState::add_shadow, with every other tracker of its device held still (shadow_mutex) and the fault + // handler kept out (g_shadow_pages_lock exclusive). The pages [first, last) (4 KiB aligned) are covered from + // now on; the ones new here are unknown, so the next refresh queries them. + void extend(std::uintptr_t first, std::uintptr_t last) { + AcquireSRWLockExclusive(&lock_); + if (first < first_) { + const std::size_t n = (first_ - first) / kPage; + state_.insert(state_.begin(), n, std::uint8_t(0)); + idle_.insert(idle_.begin(), n, std::uint8_t(0)); + cover_.insert(cover_.begin(), n, 0u); + first_ = first; + } + if (last > last_) { + state_.resize((last - first_) / kPage, 0); + idle_.resize(state_.size(), 0); + cover_.resize(state_.size(), 0); + last_ = last; + } + alias_generation_ = ~std::uint64_t(0); // the new pages' alias marks + watch_generation_ = ~std::uint64_t(0); // and whether they are write-watched + ReleaseSRWLockExclusive(&lock_); + } + + // Likewise: takes over `other`'s targets, pages and what is known of them (inside this tracker's range, which + // never shares a page with it before). `other` is left with nothing to reopen: the caller unregisters and + // deletes it, and the pages it made read-only are this tracker's now. + void absorb(ShadowPages& other) { + AcquireSRWLockExclusive(&lock_); + AcquireSRWLockExclusive(&other.lock_); + const std::size_t at = (other.first_ - first_) / kPage; + for (std::size_t i = 0; i < other.state_.size(); ++i) { + state_[at + i] |= other.state_[i]; + cover_[at + i] += other.cover_[i]; + idle_[at + i] = other.idle_[i]; + } + targets_.insert(targets_.end(), other.targets_.begin(), other.targets_.end()); + if (other.map_generation_ != map_generation_) map_generation_ = ~std::uint64_t(0); + // Its clean write-watched pages are clean as of its last asking: this tracker asks from the older of the two. + if (other.reader_) { + if (!reader_) { + reader_ = leonida::title_write_watch::open_reader(); + forget_clean(); + } + leonida::title_write_watch::merge_reader(reader_, other.reader_); + } + watch_generation_ = ~std::uint64_t(0); + pinned_ |= other.pinned_; + watch_ = watch_ && other.watch_; + faults_.fetch_add(other.faults(), std::memory_order_relaxed); + std::fill(other.state_.begin(), other.state_.end(), std::uint8_t(0)); + other.targets_.clear(); + ReleaseSRWLockExclusive(&other.lock_); + index_targets(); + ReleaseSRWLockExclusive(&lock_); + } + + // Likewise: [begin, end), inside the covered pages, is copied to `shadow` from now on. fill() it next. + void add_target(std::uintptr_t begin, std::uintptr_t end, std::uint8_t* shadow) { + AcquireSRWLockExclusive(&lock_); + targets_.push_back({begin, end, shadow}); + for (std::uintptr_t p = begin & ~(kPage - 1); p < end; p += kPage) ++cover_[(p - first_) / kPage]; + index_targets(); + ReleaseSRWLockExclusive(&lock_); + } + + // A new target's first copy, of the pages as they are now; their watched state is not touched. A page this + // tracker keeps read-only is as the other targets have it; one written meanwhile is copied again at the next + // refresh, like any page that isn't read-only here. Under shadow_mutex, so no refresh runs meanwhile. + void fill(std::uintptr_t begin, std::uintptr_t end, std::uint8_t* shadow) { + for (std::uintptr_t at = begin & ~(kPage - 1); at < end;) { + MEMORY_BASIC_INFORMATION region{}; + std::uintptr_t next = at + kPage; + Kind kind = Kind::zero; + if (VirtualQuery(reinterpret_cast(at), ®ion, sizeof(region))) { + next = reinterpret_cast(region.BaseAddress) + region.RegionSize; + kind = classify(region); + } + const std::uintptr_t from = std::max(at, begin), to = std::min(next, end); + if (kind == Kind::zero) + std::memset(shadow + (from - begin), 0, to - from); + else + copy_run(shadow + (from - begin), reinterpret_cast(from), to - from, + (region.Protect & PAGE_WRITECOMBINE) != 0); + at = next; + } + } + + // Under shadow_mutex: `shadow` is no longer a target. Pages no other target covers are made writable again and + // passed over from now on. False when it isn't one of this tracker's. + bool remove_target(const std::uint8_t* shadow) { + const auto it = + std::find_if(targets_.begin(), targets_.end(), [shadow](const Target& t) { return t.shadow == shadow; }); + if (it == targets_.end()) return false; + AcquireSRWLockExclusive(&lock_); + const std::size_t i_end = (((it->end + kPage - 1) & ~(kPage - 1)) - first_) / kPage; + for (std::size_t i = ((it->begin & ~(kPage - 1)) - first_) / kPage; i < i_end;) { + if (--cover_[i]) { + ++i; + continue; + } + std::size_t j = i + 1; // [i, j): pages nothing covers now + for (; j < i_end && cover_[j] == 1; ++j) cover_[j] = 0; + reopen_locked(first_ + i * kPage, first_ + j * kPage); + for (std::size_t k = i; k < j; ++k) state_[k] &= kAliased | kPinned | kWatched; + i = j; + } + targets_.erase(it); + index_targets(); + watch_generation_ = ~std::uint64_t(0); // recounts the write-watched pages covered + ReleaseSRWLockExclusive(&lock_); + return true; + } + + // From a file shim, before the kernel writes [from, to): the pages there this tracker protected are writable again, + // and the write-watched ones count as written (a device writing into locked pages need not set the kernel's bit). + void reopen_range(std::uintptr_t from, std::uintptr_t to) { + from = std::max(from & ~(kPage - 1), first_); + to = std::min((to + kPage - 1) & ~(kPage - 1), last_); + if (from >= to) return; + AcquireSRWLockExclusive(&lock_); + bool guarded = false; + for (std::size_t i = (from - first_) / kPage, i1 = (to - first_) / kPage; i < i1; ++i) { + state_[i] &= ~kClean; + guarded |= (state_[i] & kProtected) != 0; + } + if (guarded) reopen_locked(from, to); + ReleaseSRWLockExclusive(&lock_); + } + + // From the fault handler: a write to `address`, inside this range, faulted. True when the write can be retried: + // the page is one this tracker made read-only, and the 64 KiB around it that it protected are read-write again; + // or the page is writable already, because another thread's fault reopened it after this write faulted. The + // second is asked here, under the lock, not by the handler afterwards: refresh() protects pages under the same + // lock, so by a later look the page can be read-only again (and this tracker's again), and the handler refused a + // write it should have retried, which ended the process (seen natively on Windows 11: threads writing one page + // across a submission). + bool reopen(std::uintptr_t address) { + AcquireSRWLockExclusive(&lock_); + const std::size_t index = (address - first_) / kPage; + bool retry = (state_[index] & kProtected) != 0; + if (retry) { + const std::uintptr_t block = address & ~(kBlock - 1); + const std::uintptr_t from = std::max(block, first_), to = std::min(block + kBlock, last_); + // A write-watched block written again: asked about from now on, not guarded (what reopen_locked left + // read-only stays guarded). No allocation in here: the faulting thread may hold the heap's lock. + bool watched[kBlock / kPage] = {}; + const std::size_t i0 = (from - first_) / kPage, i1 = (to - first_) / kPage; + for (std::size_t i = i0; i < i1; ++i) + watched[i - i0] = (state_[i] & (kWatched | kHot | kProtected)) == (kWatched | kProtected); + reopen_locked(from, to); + retry = !(state_[index] & kProtected); + faults_.fetch_add(1, std::memory_order_relaxed); + for (std::size_t i = i0; i < i1; ++i) { + if (!watched[i - i0] || (state_[i] & kProtected)) continue; + state_[i] = std::uint8_t((state_[i] | kHot) & ~kClean); + idle_[i] = 0; + runs_stale_ = true; + } + } else { + MEMORY_BASIC_INFORMATION region{}; + retry = VirtualQuery(reinterpret_cast(address), ®ion, sizeof(region)) && + classify(region) == Kind::writable; + } + ReleaseSRWLockExclusive(&lock_); + return retry; + } + +private: + enum : std::uint8_t { + kProtected = 1, // made read-only here: unchanged since it was copied + kZero = 2, // zero in the copies (not committed when last looked at) + kAliased = 4, // xmem maps its physical page at another address too + kPinned = 8, // a kernel write into it may be in flight (leonida::kernel_writes) + kWatched = 16, // in a write-watched reservation (leonida::title_write_watch) + kClean = 32, // hot, and not written since it was copied after an asking + kHot = 64, // write-watched and asked about at every refresh, never guarded + }; + // Refreshes a hot block may go without a write before it is guarded again. + static constexpr std::uint8_t kCool = 64; + // Hot runs this close in one reservation are asked about as one (a call costs about as much as 300 pages). + static constexpr std::uintptr_t kMergeGap = 0x40000; + enum class Kind { zero, writable, read_only, unwatched }; + // How a committed, readable page is watched: by the kernel (clean, written or, pinned or aliased, open) or by + // a guard. + enum class Watch { clean, written, open, guard }; + static Watch watch_of(std::uint8_t s) { + if ((s & (kWatched | kHot)) != (kWatched | kHot)) return Watch::guard; + if (s & (kAliased | kPinned)) return Watch::open; + return s & kClean ? Watch::clean : Watch::written; + } + // A page known unchanged since the last refresh, which one that doesn't walk everything passes over. + static bool unchanged(std::uint8_t s) { + return s == kProtected || s == (kWatched | kProtected) || s == (kWatched | kHot | kClean); + } + + // A hot page `p` was found written: its block is not idle. + void warm(std::uintptr_t p) { + const std::uintptr_t block = p & ~(kBlock - 1); + const std::size_t i0 = (std::max(block, first_) - first_) / kPage; + const std::size_t i1 = (std::min(block + kBlock, last_) - first_) / kPage; + for (std::size_t i = i0; i < i1; ++i) idle_[i] = 0; + } + + // After an asking: the hot pages not found written are one refresh idler, and those idle for kCool refreshes are + // guarded from now on (not clean: the walk copies them as it makes them read-only). + void cool() { + for (const auto& [from, to] : watch_runs_) + for (std::size_t i = (from - first_) / kPage, i1 = (to - first_) / kPage; i < i1; ++i) { + if (!(state_[i] & kHot)) continue; + if (idle_[i] < kCool) { + ++idle_[i]; + continue; + } + state_[i] &= ~(kHot | kClean); + idle_[i] = 0; + runs_stale_ = true; + } + } + + // Guarded pages [i, j) of a read-write region (protection `current`): written since the last refresh, or newly + // committed or mapped. Watched from now on, then copied. + void guard_writable(std::size_t i0, std::size_t i1, DWORD current, bool streaming) { + for (std::size_t i = i0; i < i1;) { + const bool unwatched = state_[i] & (kAliased | kPinned); + std::size_t j = i + 1; + while (j < i1 && bool(state_[j] & (kAliased | kPinned)) == unwatched) ++j; + for (std::size_t k = i; k < j; ++k) state_[k] &= ~(kZero | kProtected); + if (!unwatched && watch_) protect(i, j, current); + add_job(i, j, streaming); + i = j; + } + } + + // Guarded pages [i, j) of a read-only region: pages this tracker protected are as the last refresh left them; + // any other is copied again. + void guard_read_only(std::size_t i0, std::size_t i1, bool streaming) { + for (std::size_t i = i0; i < i1;) { + const bool clean = (state_[i] & (kProtected | kAliased | kPinned)) == kProtected; + std::size_t j = i + 1; + while (j < i1 && ((state_[j] & (kProtected | kAliased | kPinned)) == kProtected) == clean) ++j; + if (!clean) { + for (std::size_t k = i; k < j; ++k) state_[k] &= ~kZero; + add_job(i, j, streaming); + } + i = j; + } + } + + // With the lock held, when this tracker opens a new write-watch reader: no page is clean until that reader has + // asked and the walk has copied it. The runs may have closed (their reservation released) and come back over a + // reservation made at the same address since, which a page's watched mark alone doesn't tell (re-review of #61). + void forget_clean() { + for (std::uint8_t& page : state_) page &= std::uint8_t(~kClean); + } + + // With the lock held, after the write-watched reservations changed: which pages are write-watched now. A page + // that changes sides starts guarded: one this tracker keeps read-only stays so, and a hot one is not known any + // more (the next walk queries, guards and copies it). + void update_watched() { + // Pages [i, upto) are write-watched now, or not. Either way a page that changes sides is guarded now (a guard + // it has stays): only a hot one changes, to not known. + std::size_t i = 0; + const auto side = [&](std::size_t upto, bool watched) { + for (; i < upto; ++i) + if (bool(state_[i] & kWatched) != watched) + state_[i] = + std::uint8_t((state_[i] & ~(kWatched | kClean | kHot | kZero)) | (watched ? kWatched : 0)); + }; + leonida::title_write_watch::for_each_in(first_, last_, [&](std::uintptr_t from, std::uintptr_t to) { + side((from - first_) / kPage, false); + side((to - first_) / kPage, true); + }); + side(state_.size(), false); + rebuild_watch_runs(); + } + + // The runs of hot pages to ask about, each inside one reservation, from the pages' marks; runs less than kMergeGap + // apart are asked about as one. + void rebuild_watch_runs() { + runs_stale_ = false; + Vector>& runs = watch_runs_; + runs.clear(); + const auto hot = [&](std::uintptr_t p) { + return (state_[(p - first_) / kPage] & (kWatched | kHot)) == (kWatched | kHot); + }; + leonida::title_write_watch::for_each_in(first_, last_, [&](std::uintptr_t from, std::uintptr_t to) { + const std::size_t first_run = runs.size(); + for (std::uintptr_t p = from; p < to;) { + if (!hot(p)) { + p += kPage; + continue; + } + std::uintptr_t q = p + kPage; + while (q < to && hot(q)) q += kPage; + if (runs.size() > first_run && p - runs.back().second < kMergeGap) + runs.back().second = q; + else + runs.emplace_back(p, q); + p = q; + } + }); + watched_pages_ = hot_pages_ = 0; + for (std::size_t i = 0; i < state_.size(); ++i) { + watched_pages_ += (state_[i] & kWatched) && cover_[i]; + hot_pages_ += (state_[i] & kHot) && cover_[i]; + } + if (watch_runs_.empty() && reader_) { + leonida::title_write_watch::close_reader(reader_); + reader_ = 0; + } + } + struct Job { + std::size_t offset, bytes; // from begin_ + bool streaming; + }; + struct Target { + std::uintptr_t begin, end; // the title's bytes + std::uint8_t* shadow; // where begin's byte goes + }; + + static Kind classify(const MEMORY_BASIC_INFORMATION& region) { + if (region.State != MEM_COMMIT || (region.Protect & PAGE_GUARD)) return Kind::zero; + switch (region.Protect & 0xff) { + case PAGE_READWRITE: + case PAGE_EXECUTE_READWRITE: return Kind::writable; + case PAGE_READONLY: + case PAGE_EXECUTE_READ: return Kind::read_only; + case PAGE_WRITECOPY: + case PAGE_EXECUTE_WRITECOPY: return Kind::unwatched; + default: return Kind::zero; // PAGE_NOACCESS, PAGE_EXECUTE: not readable + } + } + + // Offset from begin_ and size of pages [i, j): the first and last pages may stick out of the targets. + std::pair span_of(std::size_t i, std::size_t j) const { + const std::uintptr_t from = std::max(first_ + i * kPage, begin_), to = std::min(first_ + j * kPage, end_); + return {from - begin_, to - from}; + } + + void add_job(std::size_t i, std::size_t j, bool streaming) { + const auto [offset, bytes] = span_of(i, j); + if (!jobs_.empty() && jobs_.back().streaming == streaming && + jobs_.back().offset + jobs_.back().bytes == offset) { + jobs_.back().bytes += bytes; + return; + } + jobs_.push_back({offset, bytes, streaming}); + } + + // The targets sorted by start, the bytes they hold, and reach_[k], the furthest end among targets_[0..k]: the + // targets over [from, to) are found from the first whose reach passes `from`. + void index_targets() { + std::sort(targets_.begin(), targets_.end(), [](const Target& a, const Target& b) { return a.begin < b.begin; }); + reach_.resize(targets_.size()); + target_bytes_ = 0; + std::uintptr_t reach = 0; + for (std::size_t k = 0; k < targets_.size(); ++k) { + reach = std::max(reach, targets_[k].end); + reach_[k] = reach; + target_bytes_ += targets_[k].end - targets_[k].begin; + } + if (!targets_.empty()) { + begin_ = targets_.front().begin; + end_ = reach; + } + } + + // f(target, from, to) for each target's part of the title's bytes [from, to). + template + void for_each_target(std::uintptr_t from, std::uintptr_t to, F&& f) const { + auto k = std::size_t(std::upper_bound(reach_.begin(), reach_.end(), from) - reach_.begin()); + for (; k < targets_.size() && targets_[k].begin < to; ++k) { + const Target& t = targets_[k]; + const std::uintptr_t a = std::max(from, t.begin), b = std::min(to, t.end); + if (a < b) f(t, a, b); + } + } + + void zero_targets(std::size_t offset, std::size_t bytes) { + for_each_target(begin_ + offset, begin_ + offset + bytes, [](const Target& t, std::uintptr_t a, std::uintptr_t b) { + std::memset(t.shadow + (a - t.begin), 0, b - a); + }); + } + + // Pages [i, j) of one region, read-write with protection `current`: read-only from now on, same cache attribute. + void protect(std::size_t i, std::size_t j, DWORD current) { + const DWORD base = current & 0xff; + const DWORD read_only = (current & ~DWORD(0xff)) | (base == PAGE_READWRITE ? PAGE_READONLY : PAGE_EXECUTE_READ); + DWORD old = 0; + if (!VirtualProtect(reinterpret_cast(first_ + i * kPage), (j - i) * kPage, read_only, &old)) { + protect_error_ = GetLastError(); // logged once the lock is released + return; + } + for (std::size_t k = i; k < j; ++k) state_[k] |= kProtected; + ++refresh_protects_; + } + + // With the lock held: the pages in [from, to) this tracker made read-only are read-write again. + void reopen_locked(std::uintptr_t from, std::uintptr_t to) { + for (std::uintptr_t at = from; at < to;) { + MEMORY_BASIC_INFORMATION region{}; + std::uintptr_t next = at + kPage; + DWORD base = 0; + if (VirtualQuery(reinterpret_cast(at), ®ion, sizeof(region))) { + next = std::min(to, reinterpret_cast(region.BaseAddress) + region.RegionSize); + if (region.State == MEM_COMMIT) base = region.Protect & 0xff; + } + const std::size_t i0 = (at - first_) / kPage, i1 = (next - first_) / kPage; + if (base != PAGE_READONLY && base != PAGE_EXECUTE_READ) { + // Not read-only any more (remapped, decommitted, opened by another thread): nothing to undo. + for (std::size_t i = i0; i < i1; ++i) state_[i] &= ~kProtected; + } else { + const DWORD writable = + (region.Protect & ~DWORD(0xff)) | (base == PAGE_READONLY ? PAGE_READWRITE : PAGE_EXECUTE_READWRITE); + for (std::size_t i = i0; i < i1;) { + const bool ours = state_[i] & kProtected; + std::size_t j = i + 1; + while (j < i1 && bool(state_[j] & kProtected) == ours) ++j; + DWORD old = 0; + if (ours && + VirtualProtect(reinterpret_cast(first_ + i * kPage), (j - i) * kPage, writable, &old)) + { + for (std::size_t k = i; k < j; ++k) state_[k] &= ~kProtected; + leonida::geometry_writes::notify(first_ + i * kPage, first_ + j * kPage, + leonida::geometry_writes::Event::write); + } + i = j; + } + } + at = next; + } + } + + bool watch_; + std::uintptr_t begin_ = 0, end_ = 0; // the targets' bytes: the first start and the furthest end + std::uintptr_t first_ = 0, last_ = 0; // the pages covered + SRWLOCK lock_ = SRWLOCK_INIT; // state_, cover_, the targets, and the protection of the pages + Vector state_; // per 4 KiB page + Vector cover_; // per 4 KiB page: the targets that read it + Vector targets_; // by start + Vector reach_; // see index_targets + std::size_t target_bytes_ = 0; + std::uint64_t alias_generation_ = ~std::uint64_t(0); + std::uint64_t map_generation_ = ~std::uint64_t(0); + bool pinned_ = false; // some page has kPinned + Vector jobs_; // refresh() only, which DeviceState::shadow_mutex serializes + Vector zeroed_; // likewise + DWORD protect_error_ = 0; // a VirtualProtect refusal of this refresh(), logged after it + std::uint64_t refresh_queries_ = 0; + std::uint64_t refresh_protects_ = 0; // VirtualProtect calls of the last refresh() + bool refresh_walked_all_ = false; // the last refresh() queried every page (the title memory map changed) + std::atomic faults_{0}; + // Write watching (leonida::title_write_watch): the reservations' generation the kWatched marks are from, the runs + // of hot pages, this tracker's reader of the journal (0: none yet) and what the last refresh() asked. + std::uint64_t watch_generation_ = ~std::uint64_t(0); + Vector> watch_runs_; + std::uint64_t reader_ = 0; + std::size_t watched_pages_ = 0, hot_pages_ = 0; // covered pages write-watched, and hot + Vector idle_; // per 4 KiB page: refreshes a hot page went without a write (kCool) + bool runs_stale_ = false; // a page became hot or cold: watch_runs_ is rebuilt at the next refresh + std::uint64_t refresh_asks_ = 0; + std::uint64_t refresh_written_ = 0; +}; + +// The live ShadowPages of every device, for the fault handler. Never freed: a fault can come at any time. In host_heap, +// like everything changed under g_shadow_pages_lock (see ShadowPages). +SRWLOCK g_shadow_pages_lock = SRWLOCK_INIT; +leonida::host_heap::vector& shadow_pages_list() { + static auto* list = new leonida::host_heap::vector; + return *list; +} + +// A write to a page a shadow made read-only: the page is made writable again and the write retried. First in the +// handler chain, so a startup trace doesn't log these as exceptions; any other access violation goes on down it. +LONG CALLBACK shadow_write_fault(EXCEPTION_POINTERS* info) { + const EXCEPTION_RECORD* record = info ? info->ExceptionRecord : nullptr; + if (!record || record->ExceptionCode != EXCEPTION_ACCESS_VIOLATION || record->NumberParameters < 2 || + record->ExceptionInformation[0] != 1) + return EXCEPTION_CONTINUE_SEARCH; + const auto address = static_cast(record->ExceptionInformation[1]); + bool retry = leonida::geometry_writes::notify(address, address + 1, leonida::geometry_writes::Event::fault); + AcquireSRWLockShared(&g_shadow_pages_lock); + for (ShadowPages* pages : shadow_pages_list()) + if (pages->contains(address)) retry |= pages->reopen(address); // reopened, or another thread's fault did + ReleaseSRWLockShared(&g_shadow_pages_lock); + return retry ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_CONTINUE_SEARCH; +} + +// leonida::kernel_writes' opener: a file shim is about to let the kernel write [from, to). +void open_shadow_pages(std::uintptr_t from, std::uintptr_t to) { + leonida::geometry_writes::notify(from, to, leonida::geometry_writes::Event::open); + AcquireSRWLockShared(&g_shadow_pages_lock); + for (ShadowPages* pages : shadow_pages_list()) pages->reopen_range(from, to); + ReleaseSRWLockShared(&g_shadow_pages_lock); +} + +// Installs the handler once. false: it couldn't be, and shadows copy every page at every submission. +bool watch_shadow_writes() { + static const bool installed = [] { + if (!AddVectoredExceptionHandler(1, &shadow_write_fault)) return false; + leonida::kernel_writes::set_opener(&open_shadow_pages); + return true; + }(); + return installed; +} + +// A ShadowPages the fault handler knows of for its whole life: registered before it protects anything, removed once +// its destructor has made every page writable again. +struct ShadowPagesDeleter { + void operator()(ShadowPages* pages) const { + pages->reopen_all(); + AcquireSRWLockExclusive(&g_shadow_pages_lock); + std::erase(shadow_pages_list(), pages); + ReleaseSRWLockExclusive(&g_shadow_pages_lock); + delete pages; + } +}; +using ShadowPagesPtr = std::unique_ptr; + +ShadowPagesPtr make_shadow_pages(const std::uint8_t* pages, std::uint8_t* shadow, std::size_t size) { + const bool watch = watch_shadow_writes(); + auto* tracker = new ShadowPages(pages, shadow, size, watch); + if (watch) { + shadow_pages_list(); // made (on the process heap) before the lock the fault handler waits for + AcquireSRWLockExclusive(&g_shadow_pages_lock); + shadow_pages_list().push_back(tracker); + ReleaseSRWLockExclusive(&g_shadow_pages_lock); + } + return ShadowPagesPtr(tracker); } // Two test settings that make the standalone device look like a GPU with fewer Vulkan queues, so the path where D3D12 @@ -126,7 +1099,18 @@ std::uint32_t max_queues_per_family(rt::d3d12::QueueTestSettings settings) { } // The pipelines build stage writes its cache beside gta6rt.exe, independently of the working directory. +// LEONIDA_PIPELINE_CACHE_DIR= keeps it there instead, so several builds of gta6rt share one warmed cache. std::filesystem::path pipeline_cache_path() { + { + std::wstring dir(32768, L'\0'); + const DWORD n = GetEnvironmentVariableW(L"LEONIDA_PIPELINE_CACHE_DIR", dir.data(), static_cast(dir.size())); + if (n > 0 && n < dir.size()) { + dir.resize(n); + std::error_code ec; + std::filesystem::create_directories(dir, ec); + return std::filesystem::path(dir) / L"pipeline_cache.bin"; + } + } std::wstring path(32768, L'\0'); const DWORD length = GetModuleFileNameW(nullptr, path.data(), static_cast(path.size())); if (!length || length >= path.size()) return {}; @@ -134,6 +1118,25 @@ std::filesystem::path pipeline_cache_path() { return std::filesystem::path(path).parent_path() / L"pipeline_cache.bin"; } +// What the runtime itself compiled, kept next to the offline seed and never written over it (D3D-704). +std::filesystem::path pipeline_cache_session_path() { + std::filesystem::path path = pipeline_cache_path(); + if (!path.empty()) path.replace_filename(L"pipeline_cache.session.bin"); + return path; +} + +// LEONIDA_PIPELINE_CACHE_BYTES, in bytes; 0 turns the session file off. One line for a value that is not a number. +std::size_t pipeline_cache_save_limit() { + char text[32] = {}; + size_t length = 0; + const bool present = getenv_s(&length, text, "LEONIDA_PIPELINE_CACHE_BYTES") == 0 && length > 1; + const auto limit = leonida::pipeline_cache_store::parse_save_limit(present ? text : ""); + if (!limit.valid) + std::fprintf(stderr, "[rt] d3d12: LEONIDA_PIPELINE_CACHE_BYTES=%s is not a byte count; using %zu\n", text, + limit.bytes); + return limit.bytes; +} + // A corpus cache may be several GiB. Keep the read-only view alive through vkCreatePipelineCache // and deny writers while the view is in use. class PipelineCacheSeed { @@ -166,13 +1169,7 @@ class PipelineCacheSeed { std::size_t size() const { return size_; } bool compatible(const leonida::cached_pso::Identity& identity) const { - static_assert(sizeof(VkPipelineCacheHeaderVersionOne) == 32); - VkPipelineCacheHeaderVersionOne header{}; - // The header is little-endian, like the host. The driver interprets the opaque payload. - std::memcpy(&header, data_, sizeof(header)); - return header.headerSize == sizeof(header) && header.headerVersion == VK_PIPELINE_CACHE_HEADER_VERSION_ONE && - header.vendorID == identity.vendor && header.deviceID == identity.device && - std::memcmp(header.pipelineCacheUUID, identity.cache_uuid, VK_UUID_SIZE) == 0; + return leonida::pipeline_cache_store::header_matches(data_, size_, identity); } private: @@ -182,27 +1179,167 @@ class PipelineCacheSeed { }; VkPipelineCache create_seeded_pipeline_cache(PFN_vkCreatePipelineCache create_cache, VkDevice device, - const leonida::cached_pso::Identity& identity) { - const PipelineCacheSeed seed(pipeline_cache_path()); + const leonida::cached_pso::Identity& identity, bool session = false) { + auto start = compile_us(); + const auto name = session ? "pipeline_cache.session.bin" : "pipeline_cache.bin"; + const PipelineCacheSeed seed(session ? pipeline_cache_session_path() : pipeline_cache_path()); if (!seed.data()) return VK_NULL_HANDLE; if (!seed.compatible(identity)) { - std::fprintf(stderr, "[rt] d3d12: pipeline_cache.bin does not match this Vulkan device\n"); + std::fprintf(stderr, "[rt] d3d12: %s does not match this Vulkan device\n", name); return VK_NULL_HANDLE; } const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, nullptr, 0, seed.size(), seed.data()}; VkPipelineCache cache = VK_NULL_HANDLE; + const auto mapped = compile_us(); if (create_cache(device, &create, nullptr, &cache) != VK_SUCCESS) { std::fprintf(stderr, "[rt] d3d12: Vulkan declined the pipeline cache seed\n"); return VK_NULL_HANDLE; } - std::fprintf(stderr, "[rt] d3d12: loaded %zu bytes from pipeline_cache.bin\n", seed.size()); + std::fprintf(stderr, "[rt] d3d12: loaded %zu bytes from %s\n", seed.size(), name); + if (trace_pipeline_compile()) + std::fprintf(stderr, "[rt] pipeline-cache op=load bytes=%zu map_us=%lld driver_us=%lld file=%s\n", + seed.size(), mapped-start, compile_us()-mapped, name); return cache; } +// D3D-704: merges what earlier launches compiled into the cache the pipelines are created against. The offline seed +// and the session file cannot be handed over as one VkPipelineCacheCreateInfo -- Vulkan reads a single blob -- so the +// session cache is created on its own and merged in. A missing, foreign or corrupt session file leaves the cache as +// it was, and so does a driver that does not expose vkMergePipelineCaches. +void merge_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDevice device, VkPipelineCache cache, + const leonida::cached_pso::Identity& identity) { + if (!cache || !vk.vkCreatePipelineCache || !vk.vkDestroyPipelineCache || !vk.vkMergePipelineCaches) return; + if (!pipeline_cache_save_limit()) return; // LEONIDA_PIPELINE_CACHE_BYTES=0 turns the session file off + const auto start = compile_us(); + const PipelineCacheSeed seed(pipeline_cache_session_path()); + if (!seed.data()) return; + if (!seed.compatible(identity)) { + std::fprintf(stderr, "[rt] d3d12: pipeline_cache.session.bin does not match this Vulkan device\n"); + return; + } + const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, nullptr, 0, seed.size(), + seed.data()}; + const auto mapped = compile_us(); + VkPipelineCache session = VK_NULL_HANDLE; + if (vk.vkCreatePipelineCache(device, &create, nullptr, &session) != VK_SUCCESS) { + std::fprintf(stderr, "[rt] d3d12: Vulkan declined pipeline_cache.session.bin\n"); + return; + } + const auto created = compile_us(); + const VkResult result = vk.vkMergePipelineCaches(device, cache, 1, &session); + const auto merged = compile_us(); + vk.vkDestroyPipelineCache(device, session, nullptr); + if (trace_pipeline_compile()) + std::fprintf(stderr, "[rt] pipeline-cache op=merge bytes=%zu map_us=%lld driver_us=%lld merge_us=%lld release_us=%lld result=%d\n", + seed.size(), mapped-start, created-mapped, merged-created, compile_us()-merged, int(result)); + if (result == VK_SUCCESS) + std::fprintf(stderr, "[rt] d3d12: merged %zu bytes from pipeline_cache.session.bin\n", seed.size()); + else + std::fprintf(stderr, "[rt] d3d12: vkMergePipelineCaches on pipeline_cache.session.bin returned %d; ignored\n", + static_cast(result)); +} + +// LEONIDA_SKIP_COMPUTE=[,...]: compute programs whose library name contains one of the parts are +// never built and every dispatch of theirs is dropped ("all" or "*": every compute program). For getting past a +// program that hangs the GPU, such as a translated loop that never ends on the input it is given here, while the +// program or its input is being fixed. What the program would have written keeps its previous contents. +bool skip_compute(const std::string& name) { + static const std::vector parts = [] { + std::vector out; + const DWORD need = GetEnvironmentVariableA("LEONIDA_SKIP_COMPUTE", nullptr, 0); // with the terminator + if (need == 0) return out; + std::string text(need, '\0'); + const DWORD n = GetEnvironmentVariableA("LEONIDA_SKIP_COMPUTE", text.data(), need); + if (n == 0 || n >= need) return out; + text.resize(n); + for (std::size_t at = 0; at <= text.size();) { + const std::size_t end = std::min(text.find(',', at), text.size()); + if (end > at) out.push_back(text.substr(at, end - at)); + at = end + 1; + } + return out; + }(); + for (const std::string& part : parts) + if (part == "all" || part == "*" || name.find(part) != std::string::npos) return true; + return false; +} + +// Graphics pipelines are built at their first draw, not at CreatePipelineState (LEONIDA_LAZY_PIPELINES=0: at +// creation, as before). The title creates ~50,000 graphics PSOs at startup and draws a small part of them; each live +// VkPipeline and its shader modules cost the driver ~90 KiB of host memory, ~4.5 GiB for the whole set. +bool lazy_graphics_pipelines() { + static const bool lazy = [] { + wchar_t value[2]{}; + return !(GetEnvironmentVariableW(L"LEONIDA_LAZY_PIPELINES", value, 2) == 1 && value[0] == L'0'); + }(); + return lazy; +} + +// Texture descriptions the console accepts and a PC GPU may not: an R9G9B9E5 render target (RDNA2 renders and +// stores to it; NVIDIA only samples it) and an sRGB RGBA8 or BGRA8 texture with unordered access. The title asks +// GetResourceAllocationInfo for them at boot and asserts when the answer is "invalid", so the device gives them a +// host format that can do the job (DeviceState::r9g9b9e5_target_stand_in, srgb_uav_emulated). +// LEONIDA_CONSOLE_FORMATS=0 refuses them, as a PC D3D12 runtime does. +bool console_format_stand_ins() { + static const bool on = [] { + wchar_t value[2]{}; + return !(GetEnvironmentVariableW(L"LEONIDA_CONSOLE_FORMATS", value, 2) == 1 && value[0] == L'0'); + }(); + return on; +} + +bool startup_cache_checkpoints_enabled() { + static const bool enabled = [] { + wchar_t value[2]{}; + return GetEnvironmentVariableW(L"LEONIDA_STARTUP_CACHE_CHECKPOINTS", value, 2) == 1 && value[0] == L'1'; + }(); + return enabled; +} + +// Writes the session cache at a startup checkpoint or during device teardown. The size cap applies to either write. +void save_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDevice device, VkPipelineCache cache, + bool checkpoint = false) { + if (!cache || !vk.vkGetPipelineCacheData) return; + auto limit = pipeline_cache_save_limit(); + // The output is an opaque Vulkan blob. A prefix is not an incremental cache. + if (checkpoint) limit = (std::min)(limit, std::size_t{512} << 20); + if (!limit) return; + const auto start = compile_us(); + std::size_t size = 0; + if (vk.vkGetPipelineCacheData(device, cache, &size, nullptr) != VK_SUCCESS || + size <= sizeof(VkPipelineCacheHeaderVersionOne)) return; + if (size > limit) { + std::fprintf(stderr, "[rt] d3d12: pipeline cache is %zu bytes, over the %zu-byte write limit\n", size, limit); + return; + } + const auto queried = compile_us(); + // A size query can itself serialize the driver cache. Let newly queued work run first. + if (checkpoint && PipelineCompiler::instance().has_compile_waiter()) return; + const auto path = pipeline_cache_session_path(); + if (path.empty()) return; + CacheStagingFile staging(path, size); + if (!staging.data) { + std::fprintf(stderr, "[rt] d3d12: could not map staging file for %zu pipeline cache bytes\n", size); + return; + } + auto written = size; + const auto result = vk.vkGetPipelineCacheData(device, cache, &written, staging.data); + const auto filled = compile_us(); + const bool ok = result == VK_SUCCESS && written >= sizeof(VkPipelineCacheHeaderVersionOne) && + written <= size && staging.publish(path, written); + if (trace_pipeline_compile()) + std::fprintf(stderr, "[rt] pipeline-cache op=%s bytes=%zu query_us=%lld fill_us=%lld publish_us=%lld ok=%d result=%d\n", + checkpoint ? "checkpoint" : "teardown", written, queried-start, filled-queried, + compile_us()-filled, int(ok), int(result)); + if (ok) std::fprintf(stderr, "[rt] d3d12: wrote %zu bytes to pipeline_cache.session.bin\n", written); + else std::fprintf(stderr, "[rt] d3d12: pipeline cache snapshot incomplete (%d); previous session retained\n", int(result)); +} + // A shader whose subgroup size cannot be had runs at the device's: inexact if it crosses the halves of a wave64 (or, -// for a wave32 shader on a 64-wide default, reads lanes that are not its own). Logged once per stage with the first -// shader's name, then again at 10, 100, 1000... of that stage so a whole corpus stays readable. +// for a wave32 shader on a 64-wide default, reads lanes that are not its own), unless the translator's +// partition-invariance tier says otherwise. Logged once per stage with the first shader's name, then again at 10, 100, +// 1000... of that stage so a whole corpus stays readable. void report_subgroup_unavailable(const leonida::ShaderEntry& entry, const leonida::SubgroupRequest& request, const leonida::SubgroupSizeCaps& caps) { static std::mutex mutex; @@ -216,6 +1353,18 @@ void report_subgroup_unavailable(const leonida::ShaderEntry& entry, const leonid const bool emulable = entry.stage == "cs" || entry.stage == "ms"; const std::string so_far = names.size() > 1 ? " (shaders of this stage so far: " + std::to_string(names.size()) + ")" : ""; + if (leonida::graphics_partition_invariant(entry)) { + // The translator proved this shader's results do not change when its wave is cut into two 32-lane halves + // (docs/design.md, "Wave64 graphics"), so neither a 64-wide subgroup nor emulation is needed. + std::fprintf(stderr, + "[rt] d3d12: %s (%s) is a 64-wide shader but this device cannot require that subgroup size for " + "the stage (device sizes %u..%u, default %u, subgroupSizeControl %s); it runs at the device's " + "size, which is exact for it: the translator's partition-invariance analysis puts it in tier " + "%s%s\n", + entry.name.c_str(), entry.stage.c_str(), caps.min_size, caps.max_size, caps.default_size, + caps.subgroup_size_control ? "on" : "off", entry.wave64_graphics.c_str(), so_far.c_str()); + return; + } std::fprintf(stderr, "[rt] d3d12: %s (%s) is a %u-wide shader but this device cannot require that subgroup size for the " "stage (device sizes %u..%u, default %u, subgroupSizeControl %s); it runs at the device's size and " @@ -231,6 +1380,14 @@ void report_subgroup_unavailable(const leonida::ShaderEntry& entry, const leonid "subgroup size)\n", entry.stage.c_str()); } +// VK_FORMAT_A8_UNORM_KHR where the Vulkan headers have VK_KHR_maintenance5. Older headers have no A8 render targets: +// VulkanDeviceInfo::a8_render_target is then never set, so this is never used as UNDEFINED. +#ifdef VK_KHR_MAINTENANCE_5_EXTENSION_NAME +constexpr VkFormat kA8UnormFormat = VK_FORMAT_A8_UNORM_KHR; +#else +constexpr VkFormat kA8UnormFormat = VK_FORMAT_UNDEFINED; +#endif + struct Format { VkFormat format = VK_FORMAT_UNDEFINED; VkImageAspectFlags aspects = 0; @@ -241,6 +1398,11 @@ struct Format { // for R9G9B9E5_SHAREDEXP, R16_UINT for B5G5R5A1_UNORM): the format its SRVs, RTVs and T#s use. Its storage view is // `format`, in the uint class; shaders write the packed bits. UNDEFINED for every other texture. VkFormat uint_backed = VK_FORMAT_UNDEFINED; + // An A8_UNORM render target stored as VK_FORMAT_A8_UNORM_KHR (VulkanDeviceInfo::a8_render_target): its RTVs render + // to the alpha channel and its SRVs view it in that format, whose one channel the T# names as X (gfx10's + // channels_a). Other A8_UNORM textures are R8_UNORM images. Vulkan puts A8 in a compatibility class of its own, + // so one image cannot be viewed both ways. + bool a8_as_alpha = false; // A 96-bit R32G32B32 format, held in the R32G32B32A32 image `format` names (ResourceBinding::rgb96). bool rgb96 = false; }; @@ -258,9 +1420,24 @@ constexpr Format rgb96_format(VkFormat wide, bool typeless = false) { // DXGI -> Vulkan for the formats render targets, depth buffers and common textures use. R32 and R16 typeless become // depth formats when the resource allows depth-stencil; R32G8X24 and R24G8 always do, as Vulkan has no colour format // with their layout. +// The console's own depth-stencil family, DXGI values past the PC list: D16_UNORM_S8_UINT (118) and its plane views +// R16_UNORM_X8_TYPELESS (119) and X16_TYPELESS_G8_UINT (120). The title sizes and creates its depth targets in it +// (and asserts when GetResourceAllocationInfo calls the description invalid). No D16S8 on the PC GPUs in reach, and +// the PC has no such DXGI format: they are the D24_UNORM_S8_UINT family here, whose planes are viewed the same way +// (depth as UNORM in X, stencil as UINT). Every entry point that takes a format from the title goes through this. +constexpr DXGI_FORMAT pc_format(DXGI_FORMAT format) { + switch (static_cast(format)) { + case 118: return DXGI_FORMAT_D24_UNORM_S8_UINT; + case 119: return DXGI_FORMAT_R24_UNORM_X8_TYPELESS; + case 120: return DXGI_FORMAT_X24_TYPELESS_G8_UINT; + default: return format; + } +} + Format vulkan_format(DXGI_FORMAT format, bool depth) { constexpr VkImageAspectFlags color = VK_IMAGE_ASPECT_COLOR_BIT, d = VK_IMAGE_ASPECT_DEPTH_BIT, ds = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; + format = pc_format(format); switch (format) { case DXGI_FORMAT_R32G32B32A32_TYPELESS: return {VK_FORMAT_R32G32B32A32_SFLOAT, color, true}; case DXGI_FORMAT_R32G32B32A32_FLOAT: return {VK_FORMAT_R32G32B32A32_SFLOAT, color}; @@ -533,28 +1710,64 @@ struct TextureCreateInfo { TextureCreateInfo& operator=(const TextureCreateInfo&) = delete; }; -// The folder make_game recorded in shader_path.txt at `config`, or empty without one. Throws when the path cannot be -// converted: MSVC's STL reports a Windows path that is not UTF-8 as std::system_error, libstdc++ as filesystem_error. -std::filesystem::path shader_directory_from_file(const std::filesystem::path& config) { - std::ifstream file(config, std::ios::binary); - if (!file) return {}; - const std::string text{std::istreambuf_iterator(file), std::istreambuf_iterator()}; - if (text.empty() || text.find('\0') != std::string::npos) return {}; - - // make_game records an absolute Unix path on Linux. Resolve it inside the running Wine prefix. - if (text.front() == '/') { - using WineDosPath = wchar_t* (CDECL*)(const char*); - const auto to_dos = std::bit_cast( - ::GetProcAddress(::GetModuleHandleW(L"kernel32.dll"), "wine_get_dos_file_name")); - if (!to_dos) return {}; - const auto release = [](wchar_t* path) { ::HeapFree(::GetProcessHeap(), 0, path); }; - const std::unique_ptr path(to_dos(text.c_str()), release); - if (path) return std::filesystem::path(path.get()); - return {}; +// The console descriptor heaps' ranges (Xbox slot 14): a descriptor table the title binds at a console VA inside one +// is read by shaders at the console VA of its copy in the GPU address arena (DeviceState::add_console_heap). Process +// wide, like the title's addresses; read by every SetGraphicsRootDescriptorTable / SetComputeRootDescriptorTable. +class ConsoleHeapRanges { +public: + void add(std::uint64_t console_va, std::uint64_t bytes, std::uint64_t shader_va) { + std::unique_lock lock(mutex_); + ranges_.push_back({console_va, bytes, shader_va}); + count_.store(ranges_.size(), std::memory_order_release); + } + void remove(std::uint64_t console_va) { + std::unique_lock lock(mutex_); + std::erase_if(ranges_, [console_va](const Range& r) { return r.console_va == console_va; }); + count_.store(ranges_.size(), std::memory_order_release); } - return std::filesystem::path(std::u8string(text.begin(), text.end())); + std::uint64_t shader_va(std::uint64_t va) const { + if (!count_.load(std::memory_order_acquire)) return va; + std::shared_lock lock(mutex_); + for (const Range& r : ranges_) + if (va >= r.console_va && va - r.console_va < r.bytes) return r.shader_va + (va - r.console_va); + return va; + } + +private: + struct Range { + std::uint64_t console_va, bytes, shader_va; + }; + mutable std::shared_mutex mutex_; + std::vector ranges_; + std::atomic count_{0}; +}; + +ConsoleHeapRanges& console_heap_ranges() { + static ConsoleHeapRanges ranges; + return ranges; } +// LEONIDA_CONSOLE_HEAP_SHADOW=0 keeps a console descriptor heap as it was before its arena copy existed: its bytes in +// the title's memory only, where no shader reads them (the comparison for a run that misbehaves with the copy). +bool console_heap_shadow_enabled() { + static const bool enabled = [] { + char text[4] = {}; + size_t length = 0; + return !(getenv_s(&length, text, "LEONIDA_CONSOLE_HEAP_SHADOW") == 0 && length > 1 && text[0] == '0'); + }(); + return enabled; +} + +// What a T# the title wrote itself into a console descriptor heap came to (bind_title_image, after Resource). +// not_tsharp: words with an image TYPE that do not decode as a T#: data, not a descriptor (the retail heap's last +// 27 MiB are also the slot-133 pool, whose buffers sit there; T14 in ref/GAP-ANALYSIS-2.md). +enum class TitleImage { known, bound, unknown, refused, not_tsharp }; +class Resource; +struct DeviceState; +// `why`, when given, says what refused a T#: the first refusals are logged with their words (scan_console_slots). +TitleImage bind_title_image(DeviceState& device, const leonida::gfx10::ImageWords& words, const char** why = nullptr); +struct TitleTexture; // a texture the title keeps in its own memory (TitleTexture, after Resource) + // What a device's children need from it, kept apart from the COM class so children can hold a plain pointer. struct DeviceState { VulkanDeviceInfo info; @@ -569,6 +1782,8 @@ struct DeviceState { } std::unique_ptr context; VkPhysicalDeviceMemoryProperties memory{}; + leonida::TitleImagePool title_image_pool; + PFN_vkGetImageMemoryRequirements2 bound_image_requirements = nullptr; // D3D-96: upload-heap buffers prefer DEVICE_LOCAL | HOST_VISIBLE memory, so the GPU reads them from VRAM. Only // with Resizable BAR (leonida::resizable_bar); LEONIDA_UPLOAD_SYSMEM=1 keeps them in system memory to compare. bool upload_in_vram = false; @@ -598,16 +1813,28 @@ struct DeviceState { leonida::cached_pso::Identity pso_identity; // what GetCachedBlob records and CachedPSO is checked against std::once_flag pipeline_cache_once; VkPipelineCache pipeline_cache_handle = VK_NULL_HANDLE; + std::atomic next_checkpoint{GetTickCount64() + 120000}; + std::atomic active_compiles{0}; VkPipelineCache pipeline_cache() { std::call_once(pipeline_cache_once, [this] { const auto& vk = context->vk; if (!vk.vkCreatePipelineCache || !vk.vkDestroyPipelineCache) return; + if (pipeline_cache_save_limit()) clean_stale_cache_files(pipeline_cache_session_path()); pipeline_cache_handle = create_seeded_pipeline_cache(vk.vkCreatePipelineCache, info.device, pso_identity); - if (pipeline_cache_handle) return; - const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO}; - if (vk.vkCreatePipelineCache(info.device, &create, nullptr, &pipeline_cache_handle) != VK_SUCCESS) - pipeline_cache_handle = VK_NULL_HANDLE; + if (pipeline_cache_handle) { + merge_session_pipeline_cache(vk, info.device, pipeline_cache_handle, pso_identity); + } else if (pipeline_cache_save_limit() && direct_session_cache()) { + // With no offline seed the session file can initialize the actual cache directly. + pipeline_cache_handle = create_seeded_pipeline_cache(vk.vkCreatePipelineCache, info.device, pso_identity, true); + } + if (!pipeline_cache_handle) { + const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO}; + if (vk.vkCreatePipelineCache(info.device, &create, nullptr, &pipeline_cache_handle) != VK_SUCCESS) + pipeline_cache_handle = VK_NULL_HANDLE; + else if (!direct_session_cache()) + merge_session_pipeline_cache(vk, info.device, pipeline_cache_handle, pso_identity); + } }); // Without EXTERNALLY_SYNCHRONIZED_BIT the driver synchronizes concurrent pipeline creation using this cache. return pipeline_cache_handle; @@ -620,10 +1847,21 @@ struct DeviceState { bool r9g9b9e5_uav_emulated = false; // The same for B5G5R5A1_UNORM: VK_FORMAT_A1R5G5B5_UNORM_PACK16 without STORAGE_IMAGE, backed by mutable R16_UINT. bool b5g5r5a1_uav_emulated = false; - // The same for the 8-bit sRGB formats: VK_FORMAT_R8G8B8A8_SRGB / B8G8R8A8_SRGB without STORAGE_IMAGE (as on most - // GPUs), backed by a mutable image of the UNORM format of the same order. The host runtime makes such textures. + // True when the GPU cannot render to VK_FORMAT_E5B9G9R9_UFLOAT_PACK32 but can render and store to + // VK_FORMAT_B10G11R11_UFLOAT_PACK32: an R9G9B9E5_SHAREDEXP texture that allows render targets is then an + // R11G11B10F image of the same texel size, viewed in that format by every RTV, SRV, UAV and T#, and pipelines + // that name R9G9B9E5 as a target format render in it (console_format_stand_ins). Its contents were rendered or + // stored, never uploaded, so the different bit layout is not visible to the title's shaders. + bool r9g9b9e5_target_stand_in = false; + // True when VK_FORMAT_R8G8B8A8_SRGB (B8G8R8A8_SRGB) has no STORAGE_IMAGE support but its UNORM twin does: an sRGB + // texture that allows unordered access is a mutable UNORM image (Format::uint_backed names the sRGB format its + // SRVs and RTVs use), and its storage views write the UNORM bits unconverted, as the console does. bool rgba8_srgb_uav_emulated = false; bool bgra8_srgb_uav_emulated = false; + // True when the GPU cannot render to VK_FORMAT_A4R4G4B4_UNORM_PACK16 (it need only sample it): a B4G4R4A4_UNORM + // texture that allows render targets (the title makes a 1280x720 one) is then a B8G8R8A8_UNORM image, which has + // the same channel order, viewed in that format by everything; pipelines naming B4G4R4A4 as a target render in it. + bool b4g4r4a4_target_stand_in = false; // Cached physical-device no-attachment sample counts for D3D12_OPTIONS19. UINT no_output_sample_counts = 0; @@ -642,8 +1880,324 @@ struct DeviceState { // VK_EXT_external_memory_host; null unless info.host_pointer_alignment is set and the entry point loaded. PFN_vkGetMemoryHostPointerPropertiesEXT get_host_pointer_properties = nullptr; + // The live shadow buffers of Xbox device slot 133 (Resource::create_shadow_buffer): title-placed buffers whose + // pages the driver would not import. Each is brought up to date from the title's pages before every submission + // of command lists (VulkanContext::set_before_execute), copying only what the title wrote since the last one + // (ShadowPages). The title windows below are refreshed with them. The first refresh is logged with what it cost, + // then the refreshes of every 5 seconds. + mutable std::mutex shadow_mutex; // nothing else is taken under it but the ShadowPages' own locks + std::vector shadows; + std::uint64_t shadow_submissions = 0; + std::uint64_t shadow_logged = 0; // shadow_submissions at the last log line + std::chrono::steady_clock::time_point shadow_log_time{}; + std::uint64_t shadow_bytes = 0; // copied since the last log line + std::uint64_t shadow_queries = 0; // VirtualQuery calls since the last log line + std::uint64_t shadow_protects = 0; // VirtualProtect calls since the last log line + std::uint64_t shadow_walks = 0; // trackers that queried every page (the title memory map changed), likewise + std::uint64_t shadow_asks = 0; // GetWriteWatch calls, likewise + std::uint64_t shadow_written = 0; // write-watched pages they found written, likewise + double shadow_ms = 0; // spent since the last log line + double shadow_max_ms = 0; // the longest refresh since the last log line + double heap_ms = 0; // spent in refresh_console_heaps since the last log line + std::uint64_t shadow_faults = 0; // the write faults counted at the last log line + + // A copy of the title's bytes [pages, pages + size) at `shadow`: filled now, then brought up to date before every + // submission. Copies whose pages overlap or touch share one tracker (ShadowPages: a page has one owner that may + // watch it), so a copy that reaches one or more trackers joins them into one. + void add_shadow(const std::uint8_t* pages, std::uint8_t* shadow, std::size_t size) { + constexpr std::uintptr_t kPage = ShadowPages::kPage; + const auto begin = reinterpret_cast(pages), end = begin + size; + const std::uintptr_t first = begin & ~(kPage - 1), last = (end + kPage - 1) & ~(kPage - 1); + std::lock_guard lock(shadow_mutex); + std::vector hits; // ascending + std::uintptr_t lo = first, hi = last; + for (std::size_t i = 0; i < shadows.size(); ++i) + if (shadows[i]->first() <= last && first <= shadows[i]->last()) { + hits.push_back(i); + lo = std::min(lo, shadows[i]->first()); + hi = std::max(hi, shadows[i]->last()); + } + if (hits.empty()) { + ShadowPagesPtr tracker = make_shadow_pages(pages, shadow, size); + tracker->refresh(); + shadows.push_back(std::move(tracker)); + return; + } + ShadowPages& keep = *shadows[hits.front()]; + // The fault handler is kept out while the pages change hands: it finds them in `keep` from then on, with + // what the others knew of them (the pages they made read-only stay so, now `keep`'s). + AcquireSRWLockExclusive(&g_shadow_pages_lock); + keep.extend(lo, hi); + for (std::size_t k = 1; k < hits.size(); ++k) { + ShadowPages* other = shadows[hits[k]].get(); + keep.absorb(*other); + std::erase(shadow_pages_list(), other); + } + keep.add_target(begin, end, shadow); + ReleaseSRWLockExclusive(&g_shadow_pages_lock); + for (std::size_t k = hits.size(); k-- > 1;) shadows.erase(shadows.begin() + std::ptrdiff_t(hits[k])); + keep.fill(begin, end, shadow); + } + void remove_shadow(const std::uint8_t* mapped) { + std::lock_guard lock(shadow_mutex); + for (auto it = shadows.begin(); it != shadows.end(); ++it) + if ((*it)->remove_target(mapped)) { + if (!(*it)->targets()) shadows.erase(it); + return; + } + } + void refresh_shadows() { + using clock = std::chrono::steady_clock; + // First, and without shadow_mutex: fixing a console heap's slots can make a title window (add_shadow). + const auto heaps_start = clock::now(); + refresh_console_heaps(); + heap_ms += std::chrono::duration(clock::now() - heaps_start).count(); + probe_census(); // LOCAL DIAGNOSTIC + std::lock_guard lock(shadow_mutex); + if (shadows.empty()) return; + const auto start = clock::now(); + std::uint64_t copied = 0; + for (const ShadowPagesPtr& s : shadows) { + copied += s->refresh(); + shadow_queries += s->refresh_queries(); + shadow_protects += s->refresh_protects(); + shadow_walks += s->refresh_walked_all(); + shadow_asks += s->refresh_asks(); + shadow_written += s->refresh_written(); + } + const auto now = clock::now(); + const double ms = std::chrono::duration(now - start).count(); + shadow_ms += ms; + shadow_max_ms = std::max(shadow_max_ms, ms); + shadow_bytes += copied; + ++shadow_submissions; + if (shadow_submissions != 1 && now - shadow_log_time < std::chrono::seconds(5)) return; + std::uint64_t size = 0, faults = 0, copies = 0, watched = 0, hot = 0; + for (const ShadowPagesPtr& s : shadows) + size += s->size(), faults += s->faults(), copies += s->targets(), watched += s->watched_bytes(), + hot += s->hot_bytes(); + const double count = double(shadow_submissions - shadow_logged); + std::fprintf(stderr, + "[rt] d3d12: slot-133 shadow buffers and title windows (%llu KiB in %llu copies, %zu trackers, " + "%zu title windows; %llu KiB of pages write-watched, %llu KiB hot): submissions %llu-%llu copied %.1f KiB each " + "from the title's pages in %.3f ms on average (%.3f max; console heaps %.3f ms), %.1f VirtualQuery, " + "%.1f VirtualProtect and %.1f GetWriteWatch calls (%.1f pages found written) and %.1f trackers " + "walked in full per refresh, %llu write faults\n", + static_cast(size / 1024), static_cast(copies), + shadows.size(), title_window_count.load(std::memory_order_relaxed), + static_cast(watched / 1024), static_cast(hot / 1024), + static_cast(shadow_logged + 1), + static_cast(shadow_submissions), double(shadow_bytes) / 1024.0 / count, + shadow_ms / count, shadow_max_ms, heap_ms / count, double(shadow_queries) / count, + double(shadow_protects) / count, double(shadow_asks) / count, double(shadow_written) / count, + double(shadow_walks) / count, + static_cast(faults >= shadow_faults ? faults - shadow_faults : faults)); + shadow_logged = shadow_submissions; + shadow_log_time = now; + shadow_bytes = shadow_queries = shadow_protects = shadow_walks = shadow_asks = shadow_written = 0; + shadow_ms = shadow_max_ms = heap_ms = 0; + shadow_faults = faults; + } + + // Textures the title keeps in its own memory, by the GPU address it names them by (Device:: + // write_placed_texture_view, register_title_texture, refresh_title_textures): the slot-133 textures and the + // images made for slot-70 views of memory no resource covers. title_texture_mutex is taken before + // descriptor_mutex. A slot-133 texture tells the registry when the title maps it and when it goes; both are + // defined after TitleTexture. + std::mutex title_texture_mutex; + std::map> title_textures; + void title_texture_mapped(const void* resource, std::uint64_t address); + void title_texture_unmapped(const void* resource, std::uint64_t address); // the title wrote texels + void title_texture_gone(const void* resource, std::uint64_t address); + + // Windows of the title's own memory in the GPU address arena (src/title_va_alias.h, docs/d3d12_vulkan.md + // section 3.3 "Title-chosen addresses"): a root view or buffer V# that names the title's memory outside any + // slot-133 buffer (a per-frame constant ring, #8862 section 3.5) gets a copy of the 64 KiB-aligned pages it + // covers, refreshed before every submission like a slot-133 shadow, and the address of that copy. Windows are + // kept until the device goes (the ring comes round to the same pages), up to LEONIDA_TITLE_WINDOWS_MB (64 MiB + // by default); past that, or with the arena full, the address is left as it was and counted. + struct TitleWindow { + std::uint64_t start; + std::uint64_t shader_va; + }; + static constexpr std::uint64_t kTitleWindowAlign = 65536; + static constexpr std::uint64_t kTitleWindowMax = 16ull << 20; // the most one address pulls in + std::mutex title_window_mutex; // taken before shadow_mutex, never under it + rt::d3d12::TitleBufferWindows external_windows; + std::vector title_windows; + std::atomic title_window_count{0}; // title_windows.size(), read without the mutex + std::uint64_t title_window_bytes = 0; + std::uint64_t title_window_cap = 64ull << 20; + + rt::d3d12::GeometryViews geometry; + static rt::d3d12::GeometryCopy copy_geometry(std::uint8_t* to, const std::uint8_t* from, std::size_t size) { + using Result = rt::d3d12::GeometryCopy; + if (!leonida::texture_memory_readable(reinterpret_cast(from), size)) return Result::unreadable; + return copy_guarded(to, from, size, false) ? Result::copied : Result::interrupted; + } + std::uint64_t geometry_va(std::uint64_t guest, std::uint64_t span, bool read_only) { + if (!geometry.cap() || !span || !guest || !watch_shadow_writes()) return 0; + const auto cpu = leonida::title_gpu_views::to_cpu(guest, span); + auto& aliases = leonida::title_va_aliases(); + const auto alias = aliases.shader_va(cpu, span); + if (alias != cpu) return alias; + if (cpu == guest) { + std::uint64_t lo{}, hi{}; + if (!aliases.title_memory(guest, lo, hi) || span > hi - guest || context->knows_buffer_va(guest)) + return 0; + if (!read_only && !leonida::title_gpu_views::other_view(cpu)) { + MEMORY_BASIC_INFORMATION region{}; + if (!VirtualQuery(reinterpret_cast(cpu), ®ion, sizeof region) || region.Type != MEM_MAPPED) + return geometry.find(cpu, span); + } + } + return geometry.resolve(*this, cpu, span, copy_geometry); + } + + // Called through title_va_aliases().resolve for an address with no copy yet. False: not the title's memory. + bool resolve_title_memory(std::uint64_t va, std::uint64_t bytes, std::uint64_t& out) { + out = va; + if (!arena.mapped || !context) return false; + static const bool stream_windows = [] { + const char* flag = std::getenv("LEONIDA_STREAM_BUFFER_WINDOWS"); + return !flag || std::string_view(flag) != "0"; + }(); + if (context->knows_buffer_va(va)) return false; // an upload or readback buffer's biased VA, say + if (va < arena.size) { + // Below the arena's size an address is an arena address unless the title's own memory is there (its + // heap is: arena_allocate keeps out of those ranges). + std::uint64_t lo = 0, hi = 0; + if (!leonida::title_va_aliases().title_memory(va, lo, hi)) return false; + } + auto& aliases = leonida::title_va_aliases(); + // Only the title's own memory gets a copy (xmem's ranges): an address anywhere else, the runtime's or a host + // DLL's memory included, is left as it was and counted. + std::uint64_t title_lo = 0, title_hi = 0; + if (!aliases.title_memory(va, title_lo, title_hi)) return true; + MEMORY_BASIC_INFORMATION mbi{}; + if (!VirtualQuery(reinterpret_cast(static_cast(va)), &mbi, sizeof(mbi)) || + mbi.State != MEM_COMMIT || !mbi.Protect || (mbi.Protect & (PAGE_NOACCESS | PAGE_GUARD))) + return true; + std::lock_guard lock(title_window_mutex); + if (const std::uint64_t made = aliases.shader_va(va); made != va) { // another thread made it meanwhile + out = made; + return true; + } + std::uint64_t lo = 0, hi = UINT64_MAX; + aliases.gap(va, lo, hi); // never over a slot-133 buffer's range or another window + lo = std::max(lo, title_lo); // nor past the title's range + hi = std::min(hi, title_hi); + const std::uint64_t want = std::clamp(bytes, 1, kTitleWindowMax); + const std::uint64_t start = std::max(va & ~(kTitleWindowAlign - 1), lo); + std::uint64_t end = va > UINT64_MAX - want - kTitleWindowAlign ? UINT64_MAX + : (va + want + kTitleWindowAlign - 1) & + ~(kTitleWindowAlign - 1); + end = std::min(end, hi); + if (end <= va) return true; + const std::uint64_t size = end - start; + if (title_window_bytes + size > title_window_cap) { + log_once("title memory named by a shader address is past LEONIDA_TITLE_WINDOWS_MB, left untranslated; " + "MiB copied so far:", + int(title_window_bytes >> 20)); + return true; + } + VkDeviceSize offset = 0; + std::uint8_t* mapped{}; + if (arena_allocate(size, kTitleWindowAlign, offset, arena_buffer)) { + mapped = arena.mapped + offset; + } else if (!stream_windows || !external_windows.allocate(*this, size, offset, mapped)) { + log_once("GPU address arena full (raise LEONIDA_ARENA_MB): title memory left untranslated; window KiB:", + int(std::min(size >> 10, INT_MAX))); + return true; + } + const auto* pages = reinterpret_cast(static_cast(start)); + // Filled now and refreshed before every submission with the slot-133 shadows, by the tracker of its pages. + add_shadow(pages, mapped, std::size_t(size)); + aliases.add(start, size, offset); + title_windows.push_back({start, offset}); + title_window_count.store(title_windows.size(), std::memory_order_relaxed); + title_window_bytes += size; + if (title_windows.size() <= 4 || !(title_windows.size() & (title_windows.size() - 1))) + std::fprintf(stderr, "[rt] d3d12: a %llu KiB window of the title's memory, named by a shader address, is " + "mirrored before every submission (%zu windows, %llu KiB)\n", + static_cast(size >> 10), title_windows.size(), + static_cast(title_window_bytes >> 10)); + out = offset + (va - start); + return true; + } + + // The shader-visible CBV/SRV/UAV heaps (arena offset -> end), for the scan of bound tables before a submission. + std::mutex cbv_heap_mutex; + std::map cbv_heaps; + static constexpr VkDeviceSize kTableScanDescriptors = 1024; // per table and submission + + // The buffer V#s of the table at `table_va` whose base is in the title's own memory get the address of a copy, + // written in place: the title wrote them itself (or copied them), so no Create*View saw them. Images (T#s) and + // null slots are skipped; so is a V# already in the arena, so a rewritten one is left alone next time. + void scan_title_table(std::uint64_t table_va, std::uint32_t descriptors) { + probe_table(table_va, descriptors); // LOCAL DIAGNOSTIC + VkDeviceSize end = 0; + { + std::lock_guard lock(cbv_heap_mutex); + auto it = cbv_heaps.upper_bound(table_va); + if (it == cbv_heaps.begin()) return; + --it; + if (table_va >= it->second) return; + end = std::min( + it->second, table_va + VkDeviceSize(std::min(descriptors, kTableScanDescriptors)) * + kDescriptorSize); + } + auto& aliases = leonida::title_va_aliases(); + // Slots the title wrote in its own backing of this heap, if it gave the heap one. + aliases.pull_descriptors(arena.mapped + table_va, std::size_t(end - table_va)); + for (VkDeviceSize at = table_va; at + 16 <= end; at += kDescriptorSize) + rebase_title_vsharp(reinterpret_cast(arena.mapped + at), aliases); + } + + // A buffer V# (its first four dwords at `w`) whose base is in the title's own memory gets the console VA of a GPU + // copy of that memory, in place. False for anything else: a null slot, an image, a V# already in the arena, or + // memory no copy could be made of. + bool rebase_title_vsharp(std::uint32_t* w, leonida::TitleVaAliases& aliases, bool make_window = true) { + const std::uint32_t w0 = w[0], w1 = w[1], w2 = w[2], w3 = w[3]; + if (!(w0 | w1 | w2 | w3) || (w3 >> 30)) return false; // null, or not a buffer V# (TYPE, dword 3 bits 30-31) + const std::uint64_t base = std::uint64_t(w0) | (std::uint64_t(w1 & 0xFFFFu) << 32); + std::uint64_t host{}, remaining{}; + if (base < arena.size || (geometry.cap() && geometry.lookup(arena.address + base, host, remaining))) return false; + const std::uint32_t stride = (w1 >> 16) & 0x3FFFu; + const std::uint64_t span = std::uint64_t(w2) * (stride ? stride : 1); + std::uint64_t to{}; + if (geometry.cap()) { + const leonida::gfx10::BufferWords words{w0, w1, w2, w3}; + leonida::gfx10::Buffer desc{}; + if (leonida::gfx10::decode(words, desc)) { + // Untyped heap slots can contain ordinary pointers or other data. Large extents with + // no format or fields outside our buffer encoding need independent evidence of a view. + // An explicit table or a placed SRV can still establish the backing for those words. + if (!make_window && span > kTitleWindowMax && + (!desc.format || leonida::gfx10::encode(desc) != words)) { + to = geometry.find(leonida::title_gpu_views::to_cpu(base, span), span); + if (!to) return false; + } else { + to = geometry_va(base, span, false); + } + } + } + + // A heap scan sees free-list links, raw data and inactive slots. Only explicit bindings may + // request general-purpose windows. The heap can reuse an existing one or make a geometry mirror. + if (!to) to = make_window ? aliases.resolve(base, span, leonida::TitleVaAliases::table_view) + : aliases.shader_va(base, span); + + if (to == base || (to >> 48)) return false; + w[0] = std::uint32_t(to); + w[1] = (w1 & 0xFFFF0000u) | std::uint32_t((to >> 32) & 0xFFFFu); + return true; + } + + // WriteToSubresource/ReadFromSubresource without host image copy: one staging copy at a time, submitted to // the device's VkQueue and waited for. Created on first use. + rt::d3d12::TitleImageUpload title_upload; // accessed with title_texture_mutex held std::mutex staging_mutex; std::unique_ptr staging_queue; @@ -703,8 +2257,15 @@ struct DeviceState { if (!bytes || bytes > arena.size) return false; std::lock_guard lock(arena.mutex); for (auto it = arena.free.begin(); it != arena.free.end(); ++it) { - const VkDeviceSize start = (it->first + alignment - 1) / alignment * alignment; + VkDeviceSize start = (it->first + alignment - 1) / alignment * alignment; const VkDeviceSize end = it->first + it->second; + // Not over a range of the title's own memory: the title's heap can lie below the arena's size, and a + // view that names an address there must mean the title's bytes (TitleVaAliases::want_buffer). + while (start < end && bytes <= end - start) { + const std::uint64_t title_end = leonida::title_va_aliases().title_overlap_end(start, start + bytes); + if (!title_end) break; + start = (title_end + alignment - 1) / alignment * alignment; + } if (start >= end || bytes > end - start) continue; const VkDeviceSize block = it->first; arena.free.erase(it); @@ -769,6 +2330,706 @@ struct DeviceState { } } + // Console descriptor heaps (Xbox slot 14, docs/d3d12_vulkan.md section 3.4). The title gives the heap's address + // itself: memory of its own, at a console VA the shaders would reach as heap_base + VA, past the arena. It fills + // the heap through Create*View and CopyDescriptors, and also by writing 32-byte descriptor records into that + // memory itself and copying them with its own memcpy, which no API call sees. So shaders must read the title's + // pages, not a copy the API keeps. Two ways, in this order: + // - import: the heap's pages are imported as host memory (VK_EXT_external_memory_host, as a slot-133 buffer + // on the title's pages is), so the GPU reads them as they are, with no copy. Shaders reach them at the + // import's device address minus heap_base, which must stay below 4 GiB: most shaders keep only 32 bits of a + // descriptor-table pointer (section 3.3). The title's own records are then read as written; T#s among them + // that no Create*View registered are found by a scan that walks a part of the heap before every submission; + // - copy: an arena range of the heap's size (at the console VA itself when the arena reaches that far), brought + // up to date before every submission from the pages the title wrote since the last one (ShadowPages, the + // slot-133 shadow's tracker); each slot copied is fixed up: a buffer V# whose base is the title's memory gets + // the console VA of a GPU copy (rebase_title_vsharp), and an unregistered T# is bound (bind_title_image). + // The tracker copies into a host mirror of the title's bytes, and only the slots whose bytes differ from what + // their arena slot was made from (a second host copy) are fixed and written there again; a T# that found no + // texture and a V# into title memory with no copy yet are tried at every submission until they do. Pages xmem + // maps at two addresses are copied at every submission, and fixing all their slots each time, reading the + // arena (uncached device memory) to do it, cost more than a frame (295 ms a submission for the 4 MiB of the + // retail heap in use, RTX 4070 Ti). + // A copy must not watch pages another import pins (a slot-133 buffer placed over the heap, as the retail + // title does): it is only the fallback. + // Descriptor tables bound at a console VA inside the heap, and the heap's base for SetDescriptorHeaps, are moved + // to where shaders read it (console_heap_ranges). The copy is one way, as for slot 133. + struct FreeConsoleScratch { + void operator()(std::uint8_t* p) const { VirtualFree(p, 0, MEM_RELEASE); } + }; + struct ConsoleHeap { + std::uint64_t console_va = 0; + VkDeviceSize bytes = 0; + std::uint64_t shader_va = 0; // where shaders read it + bool imported = false; + std::uint8_t* copy = nullptr; // writable GPU mirror of the console heap + // Keep large scratch allocations out of the low addresses the title can use for its heap. + std::unique_ptr scratch; + std::uint8_t* input{}; + std::uint8_t* previous{}; + // import + VkBuffer buffer = VK_NULL_HANDLE; + VkDeviceMemory memory = VK_NULL_HANDLE; + std::size_t scan_at = 0; // the next slot the T# scan reads + // copy + bool identity = false; + ShadowPagesPtr pages; + std::vector mirror; // the title's bytes as the tracker last copied them + std::vector made; // the title's bytes each arena slot was last made from + std::vector retry; // per slot: not settled yet (fix_console_slot), in `retries` + std::vector retries; + std::uint64_t refreshes = 0; + // Since the last log line. + std::uint64_t copied = 0, scanned = 0, vsharps = 0; + std::uint64_t images[5] = {}; // by TitleImage + double ms = 0; + }; + std::mutex console_heap_mutex; // taken before title_window_mutex, shadow_mutex and descriptor_mutex + std::vector> console_heaps; + static constexpr std::size_t kConsoleScanSlots = 65536; // per submission: 2 MiB, the whole retail heap in 19 + + // [start, start + bytes) of the arena, exactly. False when any of it is taken or past the arena. + bool arena_allocate_at(VkDeviceSize start, VkDeviceSize bytes, ArenaUse use) { + if (!bytes || start > arena.size || bytes > arena.size - start) return false; + std::lock_guard lock(arena.mutex); + auto it = arena.free.upper_bound(start); + if (it == arena.free.begin()) return false; + --it; + const VkDeviceSize block = it->first, end = it->first + it->second; + if (start + bytes > end) return false; + arena.free.erase(it); + if (start > block) arena.free[block] = start - block; + if (start + bytes < end) arena.free[start + bytes] = end - (start + bytes); + ++arena.allocations; + arena.in_use += bytes; + arena.peak_in_use = std::max(arena.peak_in_use, arena.in_use); + arena.peak_end = std::max(arena.peak_end, start + bytes); + arena.use_in_use[use] += bytes; + arena.use_peak[use] = std::max(arena.use_peak[use], arena.use_in_use[use]); + return true; + } + + // Slot `slot` of a heap copy, as the title wrote it, fixed up as described above. True when it is settled: not a + // T# whose texture is still to come, nor a V# into the title's memory that got no copy. + bool fix_console_slot(ConsoleHeap& heap, std::size_t slot, leonida::TitleVaAliases& aliases) { + std::uint32_t w[kDescriptorSize / 4]; + std::memcpy(w, heap.previous + slot * kDescriptorSize, kDescriptorSize); + bool settled = true; + if (!(w[0] | w[1] | w[2] | w[3])) { + } else if (!(w[3] >> 30)) { + if (rebase_title_vsharp(w, aliases, !heap.scratch)) { + ++heap.vsharps; + } else { + // The title's memory with no copy yet (a page not committed when it was looked at) is tried again. + const std::uint64_t base = std::uint64_t(w[0]) | (std::uint64_t(w[1] & 0xFFFFu) << 32); + std::uint64_t lo = 0, hi = 0; + settled = heap.scratch || base < arena.size || !aliases.title_memory(base, lo, hi) || + (geometry.cap() && geometry.lookup(arena.address + base, lo, hi)); + } + } else { + leonida::gfx10::ImageWords words; + std::memcpy(words.data(), w, sizeof(words)); + if (leonida::gfx10::is_image(words)) { + const TitleImage result = bind_title_image(*this, words); + ++heap.images[unsigned(result)]; + settled = result != TitleImage::unknown && result != TitleImage::refused; + } + } + std::memcpy(heap.copy + slot * kDescriptorSize, w, kDescriptorSize); + return settled; + } + + // The slots on [offset, offset + bytes) of a heap copy's mirror, just brought up to date: each that differs from + // what its arena slot was made from is written there and fixed up. + void fix_console_slots(ConsoleHeap& heap, std::size_t offset, std::size_t bytes) { + auto& aliases = leonida::title_va_aliases(); + const std::size_t end = std::min(offset + bytes, std::size_t(heap.bytes)); + for (std::size_t at = offset & ~std::size_t(kDescriptorSize - 1); at + kDescriptorSize <= end; + at += kDescriptorSize) { + const std::size_t slot = at / kDescriptorSize; + if (!std::memcmp(heap.previous + at, heap.input + at, kDescriptorSize)) continue; + std::memcpy(heap.previous + at, heap.input + at, kDescriptorSize); + if (fix_console_slot(heap, slot, aliases)) { + heap.retry[slot] = 0; + } else if (!heap.retry[slot]) { + heap.retry[slot] = 1; + heap.retries.push_back(std::uint32_t(slot)); + } + } + } + + // The slots of a heap copy not settled yet: fixed again, and kept while they are still not. + void retry_console_slots(ConsoleHeap& heap) { + auto& aliases = leonida::title_va_aliases(); + std::erase_if(heap.retries, [&](std::uint32_t slot) { + if (!heap.retry[slot]) return true; // rewritten or zeroed since + if (!fix_console_slot(heap, slot, aliases)) return false; + heap.retry[slot] = 0; + return true; + }); + } + + // An imported heap: the next kConsoleScanSlots slots, for T#s no Create*View registered. A V# is read as the + // title wrote it (its base cannot be rewritten in the title's own memory). + void scan_console_slots(ConsoleHeap& heap) { + const std::size_t slots = std::size_t(heap.bytes / kDescriptorSize); + const auto* base = reinterpret_cast(static_cast(heap.console_va)); + for (std::size_t n = 0; n < std::min(slots, kConsoleScanSlots); ++n) { + if (heap.scan_at >= slots) heap.scan_at = 0; + const auto* w = reinterpret_cast(base + heap.scan_at++ * kDescriptorSize); + if (leonida::gfx10::detail::get(w[3], 28, 4) < 8) continue; // not an image's TYPE + leonida::gfx10::ImageWords words; + std::memcpy(words.data(), w, sizeof(words)); + const char* why = nullptr; + const TitleImage result = bind_title_image(*this, words, &why); + ++heap.images[unsigned(result)]; + if (result == TitleImage::unknown) why = "names no registered texture"; + if (result == TitleImage::refused || result == TitleImage::unknown) + note_refused_tsharp(heap, (heap.scan_at - 1) * kDescriptorSize, words, why); + } + heap.scanned += std::min(slots, kConsoleScanSlots); + } + + // The first refused T#s of each reason, with where they sit in the heap and their words, and a count of the + // distinct slots refused (a slot is scanned again every pass over the heap). + void note_refused_tsharp(ConsoleHeap& heap, std::size_t offset, const leonida::gfx10::ImageWords& words, + const char* why) { + static std::mutex mutex; + static std::map logged; + static std::set slots; + std::lock_guard lock(mutex); + if (slots.size() >= 262144) return; // enough to say how many + const bool fresh = slots.insert(offset).second; + unsigned& n = logged[why ? why : "?"]; + if (!fresh || n >= 6) return; + ++n; + std::fprintf(stderr, + "[rt] d3d12: unbound T# in console heap 0x%llx at +0x%zx (%zu distinct slots so far): %s: " + "%08x %08x %08x %08x %08x %08x %08x %08x\n", + static_cast(heap.console_va), offset, slots.size(), why ? why : "?", words[0], + words[1], words[2], words[3], words[4], words[5], words[6], words[7]); + } + + void refresh_console_heap(ConsoleHeap& heap) { // console_heap_mutex held + if (heap.imported) return scan_console_slots(heap); + heap.copied += heap.pages->refresh(); + heap.pages->for_each_zeroed([&](std::size_t offset, std::size_t bytes) { + std::memset(heap.copy + offset, 0, bytes); + std::memset(heap.previous + offset, 0, bytes); + for (std::size_t slot = offset / kDescriptorSize; slot * kDescriptorSize < offset + bytes; ++slot) + heap.retry[slot] = 0; + }); + heap.pages->for_each_copied([&](std::size_t offset, std::size_t bytes) { fix_console_slots(heap, offset, bytes); }); + if (!heap.retries.empty()) retry_console_slots(heap); + } + + // Before every submission, ahead of the slot-133 shadows. + void refresh_console_heaps() { + constexpr std::uint64_t kLogEvery = 4096; + std::lock_guard lock(console_heap_mutex); + for (const auto& heap : console_heaps) { + const auto start = std::chrono::steady_clock::now(); + refresh_console_heap(*heap); + heap->ms += std::chrono::duration(std::chrono::steady_clock::now() - start).count(); + ++heap->refreshes; + if (heap->refreshes != 1 && heap->refreshes != 64 && heap->refreshes % kLogEvery) continue; + const double count = double(heap->refreshes == 1 ? 1 : heap->refreshes == 64 ? 63 : kLogEvery); + std::fprintf(stderr, + "[rt] d3d12: console descriptor heap 0x%llx (%s): submissions up to %llu %s %.1f KiB each " + "in %.3f ms on average, %llu write faults; %llu title V#s rebased, T#s %llu known, %llu " + "bound, %llu naming no texture, %llu refused, %llu words that are no T# (data)\n", + static_cast(heap->console_va), heap->imported ? "imported" : "copy", + static_cast(heap->refreshes), heap->imported ? "scanned" : "copied", + double(heap->imported ? heap->scanned * kDescriptorSize : heap->copied) / 1024.0 / count, + heap->ms / count, + static_cast(heap->pages ? heap->pages->faults() : 0), + static_cast(heap->vsharps), + static_cast(heap->images[unsigned(TitleImage::known)]), + static_cast(heap->images[unsigned(TitleImage::bound)]), + static_cast(heap->images[unsigned(TitleImage::unknown)]), + static_cast(heap->images[unsigned(TitleImage::refused)]), + static_cast(heap->images[unsigned(TitleImage::not_tsharp)])); + heap->copied = heap->scanned = heap->vsharps = 0; + for (auto& n : heap->images) n = 0; + heap->ms = 0; + } + } + + // The heap's pages imported as host memory (see above): true with `heap` filled in, false when they cannot be + // (no VK_EXT_external_memory_host, a page not committed or write-combined, a driver refusal, or a device address + // shaders could not reach with 32 bits). + bool import_console_heap(ConsoleHeap& heap, std::uintptr_t host_va) { + auto& vk = context->vk; + const VkDeviceSize alignment = info.host_pointer_alignment; + if (!get_host_pointer_properties || !alignment || !arena.address || (host_va % alignment) || + (heap.bytes % alignment)) + return false; + const auto* pages = reinterpret_cast(static_cast(host_va)); + for (VkDeviceSize at = 0; at < heap.bytes;) { + MEMORY_BASIC_INFORMATION region{}; + if (!VirtualQuery(pages + at, ®ion, sizeof(region)) || region.State != MEM_COMMIT || + (region.Protect & (PAGE_WRITECOMBINE | PAGE_NOCACHE | PAGE_GUARD))) + return false; + at = reinterpret_cast(region.BaseAddress) + region.RegionSize - host_va; + } + VkExternalMemoryBufferCreateInfo external{VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO}; + external.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT; + VkBufferCreateInfo create{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, &external}; + create.size = heap.bytes; + create.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | + VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | + VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; + share(create); + if (vk.vkCreateBuffer(info.device, &create, nullptr, &heap.buffer) != VK_SUCCESS) return false; + const auto fail = [&] { + if (heap.buffer) vk.vkDestroyBuffer(info.device, heap.buffer, nullptr); + if (heap.memory) vk.vkFreeMemory(info.device, heap.memory, nullptr); + heap.buffer = VK_NULL_HANDLE; + heap.memory = VK_NULL_HANDLE; + return false; + }; + VkMemoryRequirements requirements{}; + vk.vkGetBufferMemoryRequirements(info.device, heap.buffer, &requirements); + VkMemoryHostPointerPropertiesEXT host{VK_STRUCTURE_TYPE_MEMORY_HOST_POINTER_PROPERTIES_EXT}; + if (get_host_pointer_properties(info.device, VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT, + const_cast(pages), &host) != VK_SUCCESS) + return fail(); + const std::uint32_t types = host.memoryTypeBits & requirements.memoryTypeBits; + if (!types || heap.bytes < requirements.size) return fail(); + VkImportMemoryHostPointerInfoEXT import{VK_STRUCTURE_TYPE_IMPORT_MEMORY_HOST_POINTER_INFO_EXT}; + import.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT; + import.pHostPointer = const_cast(pages); + VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO, &import}; + flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; + for (const VkMemoryPropertyFlags want : + {VkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT), + VkMemoryPropertyFlags(0)}) { + for (std::uint32_t i = 0; i < memory.memoryTypeCount && !heap.memory; ++i) { + if (!(types & (1u << i)) || (memory.memoryTypes[i].propertyFlags & want) != want) continue; + VkMemoryAllocateInfo allocate{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, &flags}; + allocate.allocationSize = heap.bytes; + allocate.memoryTypeIndex = i; + if (vk.vkAllocateMemory(info.device, &allocate, nullptr, &heap.memory) != VK_SUCCESS) + heap.memory = VK_NULL_HANDLE; + } + if (heap.memory) break; + } + if (!heap.memory || vk.vkBindBufferMemory(info.device, heap.buffer, heap.memory, 0) != VK_SUCCESS) + return fail(); + VkBufferDeviceAddressInfo bda{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; + bda.buffer = heap.buffer; + const VkDeviceAddress address = vk.vkGetBufferDeviceAddress(info.device, &bda); + const std::uint64_t shader_va = address - arena.address; // mod 2^64, as for an imported slot-133 buffer + if (!address || shader_va > (std::uint64_t(1) << 32) - heap.bytes) { + std::fprintf(stderr, + "[rt] d3d12: console descriptor heap 0x%llx: its import lies at heap_base + 0x%llx, which " + "32-bit descriptor-table pointers cannot reach; copied instead\n", + static_cast(heap.console_va), static_cast(shader_va)); + return fail(); + } + heap.shader_va = shader_va; + heap.imported = true; + return true; + } + + // Gives the console heap at `console_va` a GPU view: `shader_va` is where shaders read it. False when there is + // none (the heap then stays where only the CPU sees it, as without this). + bool add_console_heap(std::uint64_t console_va, VkDeviceSize bytes, std::uint64_t& shader_va, bool resource_heap) { + if (!arena.mapped || !context || !bytes || console_va > UINTPTR_MAX - bytes) return false; + auto heap = std::make_unique(); + heap->console_va = console_va; + heap->bytes = bytes; + // Self-written V#s must be rebased without changing the title's descriptor bytes. + // A directly indexed heap can lie outside the main arena and still fit in a 32-bit shader offset. + if (resource_heap && geometry.cap()) { + if (bytes > SIZE_MAX / 3) return false; + heap->scratch.reset(static_cast(VirtualAlloc(nullptr, bytes * 3, MEM_TOP_DOWN | + MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE))); + if (heap->scratch) { + auto* backing = heap->scratch.get(); + if (import_console_heap(*heap, reinterpret_cast(backing))) heap->copy = backing; + heap->input = backing + bytes; + heap->previous = backing + 2 * bytes; + } + heap->imported = false; // the imported storage holds the rewritten descriptors + } else { + import_console_heap(*heap, console_va); + } + if (!heap->imported) { + if (!heap->copy) { + VkDeviceSize offset = 0; + heap->identity = arena_allocate_at(console_va, bytes, arena_descriptor_heap); + if (heap->identity) { + offset = console_va; + } else if (!arena_allocate(bytes, 65536, offset, arena_descriptor_heap)) { + log_once("GPU address arena full (raise LEONIDA_ARENA_MB): console descriptor heap left in title " + "memory only; KiB", + int(std::min(bytes >> 10, INT_MAX))); + return false; + } + heap->shader_va = offset; + heap->copy = arena.mapped + offset; + } + std::memset(heap->copy, 0, std::size_t(bytes)); + if (!heap->input) { + heap->mirror.assign(std::size_t(bytes), 0); + heap->made.assign(std::size_t(bytes), 0); + heap->input = heap->mirror.data(); + heap->previous = heap->made.data(); + } + heap->retry.assign(std::size_t(bytes / kDescriptorSize), 0); + heap->pages = make_shadow_pages(reinterpret_cast(static_cast(console_va)), + heap->input, std::size_t(bytes)); + } + shader_va = heap->shader_va; + if (shader_va != console_va) console_heap_ranges().add(console_va, bytes, shader_va); + const bool imported = heap->imported; + { + std::lock_guard lock(console_heap_mutex); + if (!imported) refresh_console_heap(*heap); + console_heaps.push_back(std::move(heap)); + } + std::fprintf(stderr, + "[rt] d3d12: console descriptor heap 0x%llx (%llu KiB): shaders read it at heap_base + 0x%llx, %s\n", + static_cast(console_va), static_cast(bytes >> 10), + static_cast(shader_va), + imported ? "the title's pages imported as host memory" + : "a descriptor copy brought up to date before every submission"); + return true; + } + + bool has_console_descriptor_copy(std::uintptr_t destination) { + std::lock_guard lock(console_heap_mutex); + for (const auto& heap : console_heaps) + if (heap->copy && destination - heap->console_va < heap->bytes) return true; + return false; + } + + void remove_console_heap(std::uint64_t console_va) { + std::unique_ptr heap; + { + std::lock_guard lock(console_heap_mutex); + const auto it = std::find_if(console_heaps.begin(), console_heaps.end(), + [console_va](const auto& h) { return h->console_va == console_va; }); + if (it == console_heaps.end()) return; + heap = std::move(*it); + console_heaps.erase(it); + } + console_heap_ranges().remove(console_va); + heap->pages.reset(); + if (heap->buffer) { + // As for an imported slot-133 buffer: the title may free its pages right after, so the memory goes once + // what was submitted retires, not through the deferred queue. + context->wait_retire_ticket(context->submitted_retire_ticket()); + context->vk.vkDestroyBuffer(info.device, heap->buffer, nullptr); + context->vk.vkFreeMemory(info.device, heap->memory, nullptr); + } else { + arena_release(heap->shader_va, heap->bytes, arena_descriptor_heap); + } + } + + // LOCAL DIAGNOSTIC (desc-probe): which console-heap slots our API wrote and which the title wrote itself, what + // the title's own records decode to, and whether the GPU can see them. Title data: the log stays local. + struct HeapProbe { + std::uint64_t console_va = 0, shader_va = 0; + std::size_t slots = 0; + bool shadowed = false; + std::vector api; // hash of what our API last wrote to the slot; 0: never + std::vector writer; // optional input-probe API origin by slot + std::vector seen; // hash at the last census + std::uint64_t api_writes = 0, censuses = 0; + int table_dumps = 0, census_dumps = 0; + bool told_table = false; + // bound tables, since the last census + std::uint64_t tables = 0, t_slots = 0, t_zero = 0, t_api = 0, t_title = 0, t_kind[8] = {}; + int table_logs = 0; + std::size_t recent[8] = {}; // the last bound slots, read again at each census + unsigned recent_count = 0; + }; + std::mutex probe_mutex; // never under console_heap_mutex' callees; takes descriptor_mutex inside + std::vector> probes; + std::uint64_t probe_submissions = 0; + static constexpr const char* kProbeKinds[8] = {"V# in arena", "V# title memory", "V# other", "T# key known", + "T# texture by address", "T# no texture", "other", + "free-list link (dword 0 only)"}; + std::atomic probe_view_logs{0}; + // Where a Create*View / CopyDescriptors* write landed, for the first ones. + void probe_view(const char* what, SIZE_T ptr, UINT count) { + if (probe_view_logs.fetch_add(1) >= 48) return; + std::lock_guard lock(probe_mutex); + for (const auto& p : probes) + if (ptr >= p->console_va && ptr < p->console_va + p->slots * kDescriptorSize) { + char text[512]; + probe_kind(reinterpret_cast(ptr), text, sizeof(text)); + std::fprintf(stderr, "[rt] desc-probe: %s x%u -> console heap slot %llu: %s\n", what, count, + static_cast((ptr - p->console_va) / kDescriptorSize), text); + return; + } + std::fprintf(stderr, "[rt] desc-probe: %s x%u -> 0x%llx, outside the console heaps\n", what, count, + static_cast(ptr)); + } + + static std::uint64_t probe_hash(const std::uint8_t* p) { + std::uint64_t h = 1469598103934665603ull; + for (unsigned i = 0; i < kDescriptorSize; ++i) h = (h ^ p[i]) * 1099511628211ull; + return h ? h : 1; + } + static bool probe_zero(const std::uint8_t* p) { + std::uint64_t q[4]; + std::memcpy(q, p, sizeof(q)); + return !(q[0] | q[1] | q[2] | q[3]); + } + void probe_add(std::uint64_t console_va, std::uint64_t shader_va, std::size_t slots, bool shadowed) { + auto probe = std::make_unique(); + probe->console_va = console_va; + probe->shader_va = shader_va; + probe->slots = slots; + probe->shadowed = shadowed; + probe->api.assign(slots, 0); + if (rt::compute_probe::enabled()) probe->writer.resize(slots); + probe->seen.assign(slots, 0); + std::lock_guard lock(probe_mutex); + probes.push_back(std::move(probe)); + std::fprintf(stderr, + "[rt] desc-probe: console heap 0x%llx, %zu slots, shaders read it at VA 0x%llx (%s); arena size " + "0x%llx: heap_base + VA is %s the arena\n", + static_cast(console_va), slots, static_cast(shader_va), + !shadowed ? "no GPU view" : shader_va + slots * kDescriptorSize <= arena.size ? "arena copy" : "import", + static_cast(arena.size), + shader_va + slots * kDescriptorSize <= arena.size ? "inside" : "PAST"); + } + void probe_remove(std::uint64_t console_va) { + std::lock_guard lock(probe_mutex); + std::erase_if(probes, [console_va](const std::unique_ptr& p) { return p->console_va == console_va; }); + } + void probe_api(SIZE_T ptr, UINT count, const char* what = "CopyDescriptors") { + if (!ptr || !count) return; + std::lock_guard lock(probe_mutex); + for (const auto& p : probes) { + if (ptr < p->console_va || ptr >= p->console_va + p->slots * kDescriptorSize) continue; + const std::size_t first = std::size_t((ptr - p->console_va) / kDescriptorSize); + for (std::size_t i = first; i < first + count && i < p->slots; ++i) { + p->api[i] = probe_hash(reinterpret_cast( + static_cast(p->console_va + i * kDescriptorSize))); + if (!p->writer.empty()) p->writer[i] = rt::compute_probe::writer_code(what); + ++p->api_writes; + } + } + } + // What a slot the title wrote holds (an index into kProbeKinds) and a line saying so. + int probe_kind(const std::uint8_t* bytes, char* text, std::size_t size) { + namespace g = leonida::gfx10; + std::uint32_t w[8]; + std::memcpy(w, bytes, sizeof(w)); + int n = std::snprintf(text, size, "%08x %08x %08x %08x %08x %08x %08x %08x |", w[0], w[1], w[2], w[3], w[4], + w[5], w[6], w[7]); + if (!(w[1] | w[2] | w[3] | w[4] | w[5] | w[6] | w[7]) && w[0] < 0x200000u) { + if (n > 0 && std::size_t(n) < size) std::snprintf(text + n, size - n, " free-list link to slot %u?", w[0]); + return 7; + } + if (n < 0) n = 0; + char* rest = text + std::min(std::size_t(n), size); + const std::size_t left = size - std::min(std::size_t(n), size); + if (!(w[3] >> 30)) { + g::BufferWords words{w[0], w[1], w[2], w[3]}; + g::Buffer b{}; + const bool ok = g::decode(words, b); + std::uint64_t lo = 0, hi = 0; + const bool title = leonida::title_va_aliases().title_memory(b.address, lo, hi); + const std::uint64_t to = leonida::title_va_aliases().shader_va(b.address); + const int kind = b.address < arena.size ? 0 : title ? 1 : 2; + std::snprintf(rest, left, + " V#%s base 0x%llx stride %u records %u fmt %u dst %u%u%u%u oob %u -> %s%s (upper 16 B %s)", + ok ? "" : "(bad dst)", static_cast(b.address), b.stride, b.num_records, + b.format, b.swizzle[0], b.swizzle[1], b.swizzle[2], b.swizzle[3], unsigned(b.oob_select), + kProbeKinds[kind], to != b.address ? " (has a GPU copy)" : "", + (w[4] | w[5] | w[6] | w[7]) ? "set" : "zero"); + return kind; + } + g::ImageWords words{w[0], w[1], w[2], w[3], w[4], w[5], w[6], w[7]}; + g::Image image{}; + if (!g::is_image(words) || !g::decode(words, image)) { + std::snprintf(rest, left, " neither V# nor valid T# (type %u)", w[3] >> 28); + return 6; + } + int kind = 5; + char what[96] = "no texture at that address"; + { + std::lock_guard lock(descriptor_mutex); + if (image_entries.count(words)) { + kind = 3; + std::snprintf(what, sizeof(what), "key registered"); + } else if (const auto it = images_by_address.find(image.address); it != images_by_address.end()) { + kind = 4; + std::snprintf(what, sizeof(what), "texture known, this key not registered"); + } + } + std::snprintf(rest, left, + " T# base 0x%llx fmt %u type %u %ux%u depth %u mips %u+%u of %u layers %u+%u samples %u dst " + "%u%u%u%u minlod %.2f -> %s", + static_cast(image.address), image.format, unsigned(image.type), image.width, + image.height, image.depth, image.first_mip, image.mip_count, image.resource_mips, + image.first_layer, image.layer_count, image.samples, image.swizzle[0], image.swizzle[1], + image.swizzle[2], image.swizzle[3], double(image.min_lod), what); + return kind; + } + // At a descriptor-table scan (ExecuteCommandLists): the slots a bound table in a console heap declares. + void probe_table(std::uint64_t table_va, std::uint32_t descriptors) { + std::lock_guard lock(probe_mutex); + for (const auto& p : probes) { + const std::uint64_t span = p->slots * kDescriptorSize; + std::uint64_t at = 0; + if (table_va >= p->shader_va && table_va - p->shader_va < span) at = table_va - p->shader_va; + else if (table_va >= p->console_va && table_va - p->console_va < span) at = table_va - p->console_va; + else continue; + const std::size_t first = std::size_t(at / kDescriptorSize); + const std::size_t count = std::min(std::min(descriptors, 1024), p->slots - first); + if (!p->told_table) { + p->told_table = true; + std::fprintf(stderr, + "[rt] desc-probe: first bound table in console heap 0x%llx: VA 0x%llx = slot %zu, %zu " + "slots declared; shaders load it at heap_base + 0x%llx, %s the arena (size 0x%llx)\n", + static_cast(p->console_va), static_cast(table_va), + first, count, static_cast(table_va), + table_va + count * kDescriptorSize <= arena.size ? "inside" : "PAST", + static_cast(arena.size)); + } + ++p->tables; + p->recent[p->recent_count++ % 8] = first; + if (p->table_logs < 40) { + ++p->table_logs; + char text[512] = ""; + probe_kind(reinterpret_cast( + static_cast(p->console_va + first * kDescriptorSize)), + text, sizeof(text)); + std::fprintf(stderr, "[rt] desc-probe: table %llu VA 0x%llx slot %zu (%zu declared) at execute: %s\n", + static_cast(p->tables), static_cast(table_va), + first, count, text); + } + for (std::size_t i = first; i < first + count; ++i) { + const auto* bytes = + reinterpret_cast(static_cast(p->console_va + i * kDescriptorSize)); + ++p->t_slots; + if (probe_zero(bytes)) { + ++p->t_zero; + continue; + } + if (p->api[i] && p->api[i] == probe_hash(bytes)) { + ++p->t_api; + continue; + } + ++p->t_title; + char text[512]; + const int kind = probe_kind(bytes, text, sizeof(text)); + ++p->t_kind[kind]; + if (p->table_dumps < 24) { + ++p->table_dumps; + std::fprintf(stderr, "[rt] desc-probe: table slot %zu (table VA 0x%llx +%zu) %s-written: %s\n", i, + static_cast(table_va), i - first, + p->api[i] ? "API-then-title" : "title", text); + } + } + } + } + // Before a submission, after the console heaps' copies are refreshed: the whole heap, now and then. + void probe_census() { + const std::uint64_t n = ++probe_submissions; + if (n != 1 && n != 64 && n != 512 && n != 2048 && n % 4096) return; + std::lock_guard lock(probe_mutex); + for (const auto& p : probes) { + ++p->censuses; + std::uint64_t zero = 0, api = 0, title_new = 0, title_over = 0, changed_no_api = 0, kinds[8] = {}; + std::uint64_t copy_differs = 0, copy_differs_unrebased = 0; + // A copy lies in the arena; an import never does (its device address is outside the arena's). + const std::uint8_t* copy = + p->shadowed && p->shader_va + p->slots * kDescriptorSize <= arena.size ? arena.mapped + p->shader_va + : nullptr; + for (std::size_t i = 0; i < p->slots; ++i) { + const auto* bytes = + reinterpret_cast(static_cast(p->console_va + i * kDescriptorSize)); + if (copy && std::memcmp(copy + i * kDescriptorSize, bytes, kDescriptorSize)) { + ++copy_differs; + // A rebased V# differs in its base only (dwords 0 and 1 low half). + std::uint32_t a[8], b[8]; + std::memcpy(a, bytes, 32); + std::memcpy(b, copy + i * kDescriptorSize, 32); + const bool rebased = !(a[3] >> 30) && a[2] == b[2] && a[3] == b[3] && + (a[1] & 0xFFFF0000u) == (b[1] & 0xFFFF0000u) && + !std::memcmp(a + 4, b + 4, 16); + copy_differs_unrebased += !rebased; + } + const bool is_zero = probe_zero(bytes); + const std::uint64_t h = is_zero ? 0 : probe_hash(bytes); + if (p->seen[i] != h && p->censuses > 1 && h != p->api[i]) ++changed_no_api; + p->seen[i] = h; + if (is_zero) { + ++zero; + continue; + } + if (p->api[i] == h) { + ++api; + continue; + } + ++(p->api[i] ? title_over : title_new); + char text[512]; + const int kind = probe_kind(bytes, text, sizeof(text)); + ++kinds[kind]; + if (p->census_dumps < 40 && kind != 7 && kind != 0) { + ++p->census_dumps; + std::fprintf(stderr, "[rt] desc-probe: census %llu slot %zu %s-written: %s\n", + static_cast(p->censuses), i, + p->api[i] ? "API-then-title" : "title", text); + } + } + std::fprintf(stderr, + "[rt] desc-probe: census %llu at submission %llu, heap 0x%llx (%zu slots, %llu API writes so " + "far): zero %llu, as our API wrote them %llu, title-written %llu (never API %llu, over an API " + "write %llu), changed since the last census with no API write %llu; title kinds: %s %llu, %s " + "%llu, %s %llu, %s %llu, %s %llu, %s %llu, %s %llu, %s %llu; arena copy differs %llu (not a rebased V# " + "%llu)\n", + static_cast(p->censuses), static_cast(n), + static_cast(p->console_va), p->slots, + static_cast(p->api_writes), static_cast(zero), + static_cast(api), static_cast(title_new + title_over), + static_cast(title_new), static_cast(title_over), + static_cast(changed_no_api), kProbeKinds[0], + static_cast(kinds[0]), kProbeKinds[1], + static_cast(kinds[1]), kProbeKinds[2], + static_cast(kinds[2]), kProbeKinds[3], + static_cast(kinds[3]), kProbeKinds[4], + static_cast(kinds[4]), kProbeKinds[5], + static_cast(kinds[5]), kProbeKinds[6], + static_cast(kinds[6]), kProbeKinds[7], + static_cast(kinds[7]), static_cast(copy_differs), + static_cast(copy_differs_unrebased)); + std::fprintf(stderr, + "[rt] desc-probe: bound tables since the last census: %llu tables, %llu slots: zero %llu, API " + "%llu, title-written %llu (%s %llu, %s %llu, %s %llu, %s %llu, %s %llu, %s %llu, %s %llu, %s %llu)\n", + static_cast(p->tables), static_cast(p->t_slots), + static_cast(p->t_zero), static_cast(p->t_api), + static_cast(p->t_title), kProbeKinds[0], + static_cast(p->t_kind[0]), kProbeKinds[1], + static_cast(p->t_kind[1]), kProbeKinds[2], + static_cast(p->t_kind[2]), kProbeKinds[3], + static_cast(p->t_kind[3]), kProbeKinds[4], + static_cast(p->t_kind[4]), kProbeKinds[5], + static_cast(p->t_kind[5]), kProbeKinds[6], + static_cast(p->t_kind[6]), kProbeKinds[7], + static_cast(p->t_kind[7])); + for (unsigned r = 0; r < std::min(p->recent_count, 8u); ++r) { + char text[512] = ""; + const std::size_t slot = p->recent[r]; + probe_kind(reinterpret_cast( + static_cast(p->console_va + slot * kDescriptorSize)), + text, sizeof(text)); + std::fprintf(stderr, "[rt] desc-probe: census %llu: recently bound slot %zu now: %s\n", + static_cast(p->censuses), slot, text); + } + p->tables = p->t_slots = p->t_zero = p->t_api = p->t_title = 0; + for (auto& k : p->t_kind) k = 0; + } + } + // The translator's output, loaded on first use. std::mutex library_mutex; bool library_tried = false; @@ -793,8 +3054,12 @@ struct DeviceState { std::fprintf(stderr, "[rt] d3d12: %s\n", error.c_str()); else { const auto path = shader_library.directory().u8string(); - std::fprintf(stderr, "[rt] d3d12: %zu translated shaders from %s\n", - shader_library.size(), reinterpret_cast(path.c_str())); + // fspx counts library/ too (shader_library.h, load()). + std::fprintf(stderr, "[rt] d3d12: %zu translated shaders (%zu fspx, %zu fspx_compute, " + "%zu fspx_gfx, %zu bvh, %zu exe) from %s\n", + shader_library.size(), shader_library.fspx_size(), shader_library.fspx_compute_size(), + shader_library.fspx_gfx_size(), shader_library.bvh_size(), shader_library.exe_size(), + reinterpret_cast(path.c_str())); } } catch (const std::exception& e) { std::fprintf(stderr, "[rt] d3d12: invalid translated shader path: %s\n", e.what()); @@ -953,16 +3218,38 @@ struct DeviceState { // The format a texture description is created with, D24S8 and R9G9B9E5 UAV fallbacks included. Format texture_format(const D3D12_RESOURCE_DESC& desc) const { if (!xr_bias_compatible(desc)) return {}; - if (desc.Format == DXGI_FORMAT_A8_UNORM && - (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || desc.SampleDesc.Count != 1 || - (desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | - D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)))) - return {}; + if (desc.Format == DXGI_FORMAT_A8_UNORM) { + // Sampled A8: an R8 image read through the alpha swizzle, in 1D, 2D or 3D as the host runtime makes + // them (d3d12_a8_dimensions_test); A8 render targets stay 2D. + if ((desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE1D && + desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D && + desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE3D) || + ((desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) && + desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) || + desc.SampleDesc.Count != 1 || + (desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS))) + return {}; + if (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) { + if (!info.a8_render_target) { + log_once("A8_UNORM render targets need VK_FORMAT_A8_UNORM_KHR (VK_KHR_maintenance5); format", + desc.Format); + return {}; + } + Format alpha{kA8UnormFormat, VK_IMAGE_ASPECT_COLOR_BIT}; + alpha.a8_as_alpha = true; + return alpha; + } + } if (desc.Format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP) { if ((desc.SampleDesc.Count != 1 && (!(desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) || (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS))) || (desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE))) return {}; + if ((desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) && r9g9b9e5_target_stand_in) { + log_once("R9G9B9E5_SHAREDEXP render target unavailable natively, using B10G11R11_UFLOAT; format", + desc.Format); + return Format{VK_FORMAT_B10G11R11_UFLOAT_PACK32, VK_IMAGE_ASPECT_COLOR_BIT}; + } if ((desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) && (!color_attachment_usable(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32) || ((desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) && @@ -1078,7 +3365,21 @@ struct DeviceState { std::atomic bindless_idle_waits{0}; bool bindless_legacy_idle = false; std::atomic bindless_cap_logged{false}; + std::size_t bindless_logged_table_bytes = 0; // descriptor_mutex: the table size last logged + bool bindless_host_logged = false; // descriptor_mutex std::map image_entries; + // A pending stream has a console descriptor immediately. Keep its keys (including aliases) + // until the first complete upload. A shader hash miss selects the existing fallback image. + struct PendingImage { + VkImage zero = VK_NULL_HANDLE; + std::map keys; + }; + std::unordered_map pending_image_keys; + using ZeroShape = std::tuple; + std::mutex zero_image_mutex; + std::map zero_images; + std::atomic zero_image_bytes{0}; + VkImage zero_sampled_image(const D3D12_RESOURCE_DESC&, const Format&, VkDeviceSize); std::multimap image_keys; // by the texture's address std::vector replaced_images; // kept until their texture goes: work in flight may still use them std::map sampler_entries; @@ -1155,7 +3456,20 @@ struct DeviceState { bool allow_channel_cast = false, VkFormat uint_backed = VK_FORMAT_UNDEFINED) { namespace g = leonida::gfx10; std::lock_guard lock(descriptor_mutex); + return bind_image_locked(words, image, vk_image, image_format, aspects, storage, allow_channel_cast, + uint_backed); + } + bool bind_image_locked(const leonida::gfx10::ImageWords& words, const leonida::gfx10::Image& image, + VkImage vk_image, VkFormat image_format, VkImageAspectFlags aspects, bool storage, + bool allow_channel_cast = false, VkFormat uint_backed = VK_FORMAT_UNDEFINED) { + namespace g = leonida::gfx10; if (!bindless) return false; + auto pending = pending_image_keys.find(vk_image); + if (pending != pending_image_keys.end()) { + pending->second.keys.try_emplace(words, image); + if (!pending->second.zero) return true; + vk_image = pending->second.zero; + } const auto existing = image_entries.find(words); if (existing != image_entries.end() && (existing->second.storage || !storage)) return true; @@ -1197,6 +3511,16 @@ struct DeviceState { view_format = rgb96_view_format(image_format, image.format); channels_format = rgb96_named_format(view_format); } + // A depth image can only be viewed in its own format, so a T# that names another format on it (the title's + // T# of a console D16S8 target says 16-bit UNORM; the image is D24S8 or D32S8) is its depth plane, read as a + // normalised value in X either way. + if (depth_or_stencil && !stencil && (aspects & VK_IMAGE_ASPECT_DEPTH_BIT) && + (view_format == VK_FORMAT_UNDEFINED || !g::is_depth_stencil_format(view_format))) { + log_once("a T# names another format on a depth image; viewed as its depth plane, GFX10 format", + int(image.format)); + view_format = image_format; + channels_format = image_format; + } if (view_format == VK_FORMAT_UNDEFINED || (depth_or_stencil && !g::is_depth_stencil_format(view_format))) { log_once("no Vulkan view format for the GFX10 format of a view:", int(image.format)); @@ -1213,7 +3537,9 @@ struct DeviceState { view_info.viewType = g::vulkan_view_type(image.type); view_info.format = view_format; VkImageViewUsageCreateInfo sampled_usage{VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO}; - if (uint_backed) { + // A sampled view only samples: a view in a cast format the image's storage usage does not support (an R32 + // target viewed as E5B9G9R9) stays valid (VUID-VkImageViewCreateInfo-usage-02274). + if (uint_backed || (view_format != image_format && view_format != VK_FORMAT_UNDEFINED)) { sampled_usage.usage = VK_IMAGE_USAGE_SAMPLED_BIT; view_info.pNext = &sampled_usage; } @@ -1269,7 +3595,25 @@ struct DeviceState { // Every state a shader can read or write the texture in is GENERAL (ResourceBinding::sampled_in_general). entry.index = bindless->add_image(dimension, entry.sampled, VK_IMAGE_LAYOUT_GENERAL, views, sampled_class); if (!entry.index) { - log_once("a bindless image array is full; dimension", int(dimension)); + if (first_diagnostic("a bindless image array is full; dimension", int(dimension))) { + // Whether the array holds live textures or stale views: the T#s it holds, the textures they name, + // and the most T#s of one texture (a texture whose T#s keep changing, a streamed mip clamp say, + // keeps an index for each until it goes). + std::size_t entries = 0, replaced = 0, most = 0; + std::map per_texture; + for (const auto& [key, held] : image_entries) + if (held.dimension == dimension) { + ++entries; + most = std::max(most, ++per_texture[held.address]); + } + for (const auto& held : replaced_images) replaced += held.dimension == dimension; + std::fprintf(stderr, + "[rt] d3d12: a bindless image array is full; dimension %d: %u indices, %zu T#s of %zu " + "textures (at most %zu T#s of one), %zu replaced views kept; further T#s of this " + "dimension read the fallback\n", + int(dimension), bindless->image_capacity(dimension), entries, per_texture.size(), most, + replaced); + } vk.vkDestroyImageView(info.device, entry.sampled, nullptr); if (entry.storage) vk.vkDestroyImageView(info.device, entry.storage, nullptr); return false; @@ -1282,12 +3626,33 @@ struct DeviceState { image_keys.emplace(image.address, words); } bindless->insert_key(words, entry.index); + leonida::fsdraw::note_tsharp(words.data()); // LOCAL DIAGNOSTIC return true; } + // Textures by the address their T#s name them by (Resource::image_address), for the T#s a title writes into a + // console descriptor heap itself (bind_title_image). Under descriptor_mutex: a texture leaves it in forget_image, + // before its image goes. + TitleGpuPlacements gpu_placements; // descriptor_mutex + std::map images_by_address; // a Resource + void note_image_address(std::uint64_t address, const void* resource) { + std::lock_guard lock(descriptor_mutex); + images_by_address[address] = resource; + } + // The texture registered at `address` (a title-placed texture's address can be taken over by a later one). + const void* image_owner(std::uint64_t address) { + std::lock_guard lock(descriptor_mutex); + const auto it = images_by_address.find(address); + return it == images_by_address.end() ? nullptr : it->second; + } + // The texture at `address` is gone: its views leave set 0 and its T#s the hash table. void forget_image(std::uint64_t address) { std::lock_guard lock(descriptor_mutex); + images_by_address.erase(address); + forget_image_views_locked(address); + } + void forget_image_views_locked(std::uint64_t address) { if (!bindless) return; const auto [first, last] = image_keys.equal_range(address); for (auto it = first; it != last; ++it) { @@ -1383,19 +3748,61 @@ struct DeviceState { // A memory type with `required`, preferring one that also has `preferred`, in a heap large enough for the // allocation (leonida::memory_type_order). `chosen`, when given, receives the property flags of the type the // memory came from. + // Held around every vkAllocateMemory of this device, host-pointer imports included (see allocate). + static std::mutex& memory_mutex() { + static std::mutex mutex; + return mutex; + } + VkDeviceMemory allocate(const VkMemoryRequirements& requirements, VkMemoryPropertyFlags required, VkMemoryPropertyFlags preferred, VkMemoryPropertyFlags* chosen = nullptr, - bool device_address = false, std::uint32_t* chosen_type = nullptr) const { + bool device_address = false, std::uint32_t* chosen_type = nullptr, + VkImage dedicated_image = VK_NULL_HANDLE) const { VkMemoryAllocateFlagsInfo flags_info{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO}; flags_info.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; for (const std::uint32_t i : leonida::memory_type_order(memory, requirements.memoryTypeBits, required, preferred, requirements.size)) { VkMemoryAllocateInfo allocate{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; if (device_address) allocate.pNext = &flags_info; + VkMemoryDedicatedAllocateInfo dedicated{VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO}; + if (dedicated_image) { + dedicated.image = dedicated_image; + dedicated.pNext = allocate.pNext; + allocate.pNext = &dedicated; + } allocate.allocationSize = requirements.size; allocate.memoryTypeIndex = i; VkDeviceMemory out = VK_NULL_HANDLE; - if (context->vk.vkAllocateMemory(info.device, &allocate, nullptr, &out) == VK_SUCCESS) { + // The NVIDIA driver (620.73 under Wine) answers VK_ERROR_OUT_OF_HOST_MEMORY for a few-KiB allocation now + // and then while other threads import host pointers that the kernel module cannot pin (journal: "Cannot + // map memory with base addr ..."), with gigabytes free. The title asserts on the texture it loses. So + // allocations and imports take turns (memory_mutex), and that answer is retried before it is believed. + VkResult allocated = VK_ERROR_OUT_OF_HOST_MEMORY; + for (int attempt = 0; attempt < 6 && allocated == VK_ERROR_OUT_OF_HOST_MEMORY; ++attempt) { + if (attempt) Sleep(attempt); + std::lock_guard serial(memory_mutex()); + allocated = context->vk.vkAllocateMemory(info.device, &allocate, nullptr, &out); + if (attempt && allocated == VK_SUCCESS) { + static std::atomic recovered{0}; + if (recovered.fetch_add(1, std::memory_order_relaxed) < 8) + std::fprintf(stderr, + "[rt] d3d12: vkAllocateMemory succeeded on retry %d after out-of-host-memory (%llu " + "bytes, type %u)\n", + attempt, static_cast(requirements.size), i); + } + } + if (allocated != VK_SUCCESS) { + static std::atomic logged{0}; + if (logged.fetch_add(1, std::memory_order_relaxed) < 16) + std::fprintf(stderr, + "[rt] d3d12: vkAllocateMemory failed (%d): %llu bytes, memory type %u (flags 0x%x, heap " + "%u of %llu MiB), device address %d\n", + int(allocated), static_cast(requirements.size), i, + unsigned(memory.memoryTypes[i].propertyFlags), memory.memoryTypes[i].heapIndex, + static_cast(memory.memoryHeaps[memory.memoryTypes[i].heapIndex].size >> 20), + int(device_address)); + } + if (allocated == VK_SUCCESS) { if (chosen) *chosen = memory.memoryTypes[i].propertyFlags; if (chosen_type) *chosen_type = i; if (leonida::spilled_to_host(required, preferred, memory.memoryTypes[i].propertyFlags)) @@ -1430,12 +3837,20 @@ Format texture_format(const DeviceState& device, const D3D12_RESOURCE_DESC& desc // path, D3D-90's placed one). Each format must map and be the same texel size as the resource's: the host PC // runtime refuses other sizes, and a size-mismatched VkImageFormatListCreateInfo is a Vulkan validation error // (VUID-VkImageCreateInfo-pNext-06722). A nonzero count with a null list is no list. E_INVALIDARG on a bad format. -HRESULT castable_view_formats(const Format& format, UINT32 count, const DXGI_FORMAT* castable, - std::vector& out) { +// An A8_UNORM texture's own format is always viewable (create_texture adds the image's format), so naming it is a +// no-op. An A8 render target's VK_FORMAT_A8_UNORM_KHR image (Format::a8_as_alpha) is in a class of its own: no +// other format can be a view format of it, so any other castable format is refused here, before Vulkan. +HRESULT castable_view_formats(const Format& format, DXGI_FORMAT resource_format, UINT32 count, + const DXGI_FORMAT* castable, std::vector& out) { if (!count || !castable) return S_OK; const bool depth = (format.aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) != 0; const leonida::BlockFormat own = leonida::block_format(format.format, format.aspects); for (UINT32 i = 0; i < count; ++i) { + if (resource_format == DXGI_FORMAT_A8_UNORM && castable[i] == DXGI_FORMAT_A8_UNORM) continue; + if (format.a8_as_alpha) { + log_once("castable format of an A8_UNORM render target not supported (only A8_UNORM is):", castable[i]); + return E_INVALIDARG; + } const Format cast = vulkan_format(castable[i], depth); if (cast.format == VK_FORMAT_UNDEFINED) { log_once("castable format not supported yet:", castable[i]); @@ -1488,7 +3903,8 @@ DXGI_FORMAT format_family(DXGI_FORMAT format) { // ALLOW_DEPTH_STENCIL: the host accepts every format of a family with a depth member (R32_FLOAT and R16_FLOAT // included) and nothing else. bool depth_stencil_family(DXGI_FORMAT format) { - const DXGI_FORMAT family = format_family(format); + // The console's own D16S8 family (DXGI 118-120) counts as the D24S8 family it is made of here (pc_format). + const DXGI_FORMAT family = format_family(pc_format(format)); return family == DXGI_FORMAT_R32_TYPELESS || family == DXGI_FORMAT_R16_TYPELESS || family == DXGI_FORMAT_R24G8_TYPELESS || family == DXGI_FORMAT_R32G8X24_TYPELESS; } @@ -1704,6 +4120,18 @@ const char* barrier_layout_refusal(const D3D12_RESOURCE_DESC& desc, D3D12_BARRIE // then address at +0x10 and size at +0x18. The title asserts GetCPUDescriptorHandleForHeapStart() == address. // Backing this range with title memory / section 3.3 aliasing is tracked separately; this path only satisfies the // observed ABI contract and must not be inferred from normal PC 16-byte CreateDescriptorHeap calls. +// LOCAL DIAGNOSTIC (desc-probe): records what a descriptor write through our API left in a console-heap slot. +struct ProbeApiWrite { + DeviceState& state; + SIZE_T ptr; + UINT count; + const char* what; + ~ProbeApiWrite() { + state.probe_api(ptr, count, what); + state.probe_view(what, ptr, count); + } +}; + struct ConsoleDescriptorHeapDesc { D3D12_DESCRIPTOR_HEAP_DESC desc{}; std::uint64_t address = 0; @@ -1728,11 +4156,21 @@ class DescriptorHeap final console_addressed_(console_address != 0) { const VkDeviceSize bytes = VkDeviceSize(desc_.NumDescriptors) * kDescriptorSize; if (console_addressed_) { - // The retail boot checks GetCPUDescriptorHandleForHeapStart() == address. Report the requested title VA - // now; backing this range with title memory / §3.3 aliasing is tracked separately. - log_once("descriptor heap uses console address/size (not backed by title memory)", int(desc_.Type)); + // The retail boot checks GetCPUDescriptorHandleForHeapStart() == address, so the CPU handles are the + // title's memory and the GPU handles its console VA. A shader-visible heap there is read by shaders from + // an arena copy the device keeps up to date (DeviceState::add_console_heap). cpu_ = reinterpret_cast(static_cast(console_address_)); in_arena_ = false; + if ((desc_.Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) && console_heap_shadow_enabled()) + shadowed_ = device.add_console_heap(console_address_, bytes, console_shader_va_, + desc_.Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + if (!shadowed_ && (desc_.Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE)) + log_once("descriptor heap uses console address/size, which no shader reads (no GPU view); type", + int(desc_.Type)); + if (desc_.Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV && // LOCAL DIAGNOSTIC + (desc_.Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE)) + device.probe_add(console_address_, shadowed_ ? console_shader_va_ : console_address_, + desc_.NumDescriptors, shadowed_); return; } if ((desc_.Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) && device.arena.mapped) { @@ -1744,6 +4182,10 @@ class DescriptorHeap final in_arena_ = true; cpu_ = device.arena.mapped + arena_offset_; std::memset(cpu_, 0, std::size_t(bytes)); + if (desc.Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) { + std::lock_guard lock(device.cbv_heap_mutex); + device.cbv_heaps[arena_offset_] = arena_offset_ + bytes; + } } else { storage_.reset(new std::byte[std::size_t(bytes)]()); cpu_ = reinterpret_cast(storage_.get()); @@ -1751,6 +4193,12 @@ class DescriptorHeap final } ~DescriptorHeap() override { + if (console_addressed_) device_.probe_remove(console_address_); // LOCAL DIAGNOSTIC + if (shadowed_) device_.remove_console_heap(console_address_); + if (in_arena_ && desc_.Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) { + std::lock_guard lock(device_.cbv_heap_mutex); + device_.cbv_heaps.erase(arena_offset_); + } if (in_arena_) device_.arena_release(arena_offset_, VkDeviceSize(desc_.NumDescriptors) * kDescriptorSize, DeviceState::arena_descriptor_heap); } @@ -1774,7 +4222,9 @@ class DescriptorHeap final } const D3D12_DESCRIPTOR_HEAP_DESC& raw_desc() const { return desc_; } + // Where shaders read the heap: its arena copy for a console heap that has one (SetDescriptorHeaps' base). D3D12_GPU_VIRTUAL_ADDRESS gpu_base() const { + if (shadowed_) return UINT64(console_shader_va_); if (console_addressed_) return static_cast(console_address_); return in_arena_ ? UINT64(arena_offset_) : 0; } @@ -1789,6 +4239,8 @@ class DescriptorHeap final std::uint64_t console_address_ = 0; std::uint64_t console_size_ = 0; bool console_addressed_ = false; + bool shadowed_ = false; // a console heap shaders read at console_shader_va_ (DeviceState::add_console_heap) + std::uint64_t console_shader_va_ = 0; }; class Resource final @@ -1808,13 +4260,21 @@ class Resource final : device_(device), desc_(desc), heap_(heap), heap_flags_(heap_flags), placed_(true), va_(placed_va) {} ~Resource() override { + if (title_texture_) device_.title_texture_gone(this, reinterpret_cast(title_address_)); + if (aliased_) leonida::title_va_aliases().remove(va_, title_alias_); if (accel_) { device_.context->unregister_acceleration_structure(gpu_va_); if (buffer_va_ && buffer_va_ != gpu_va_) device_.context->unregister_acceleration_structure(buffer_va_); device_.context->defer_destroy(leonida::DeferredDeletionQueue::Kind::acceleration_structure, accel_); } - if (image_address_) device_.forget_image(image_address_); + if (deferred_stream_) { + std::lock_guard lock(device_.descriptor_mutex); + device_.pending_image_keys.erase(image_); + } + if (image_address_ && device_.image_owner(image_address_) == this) device_.forget_image(image_address_); device_.context->remove_resource(id()); + // Before the memory goes to the deferred queue: no submission copies into it after this. + if (shadow_) device_.remove_shadow(shadow_); if (host_import_) { // VK_EXT_external_memory_host needs the caller's pages to stay valid for the imported memory's whole // lifetime, and a title may free them right after releasing the resource. So the memory is not left to @@ -1828,14 +4288,21 @@ class Resource final memory_ = VK_NULL_HANDLE; } if (in_arena_) device_.arena_release(arena_offset_, desc_.Width, DeviceState::arena_buffer); - if (image_ && !sparse_image_) + if (pooled_image_) + device_.context->defer_destroy(leonida::DeferredDeletionQueue::Kind::pooled_title_image, pooled_image_.release()); + else if (image_ && !sparse_image_) device_.context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image, image_); if (buffer_) device_.context->defer_destroy(leonida::DeferredDeletionQueue::Kind::buffer, buffer_); if (memory_) device_.context->defer_destroy(leonida::DeferredDeletionQueue::Kind::device_memory, memory_); } leonida::ResourceId id() const { return resource_id(this); } - VkImage image() const { return image_; } + VkImage image() const { return deferred_attachment_ && !deferred_attachment_->ensure() ? VK_NULL_HANDLE : image_; } + // A sampled placement can publish views of its shared, correctly sized zero image while its own image is unbound. + VkImage descriptor_image() const { return shared_zero_ ? image_ : image(); } + bool host_initialized_image() const { return host_transfer_; } + bool unbound_attachment() const { return deferred_attachment_ && !deferred_attachment_->bound(); } + VkDeviceSize image_backing_bytes() const { return unbound_attachment() ? 0 : image_backing_bytes_; } bool sparse_image() const { return sparse_image_; } VkBuffer buffer() const { return buffer_; } const D3D12_RESOURCE_DESC& desc() const { return desc_; } @@ -1855,11 +4322,49 @@ class Resource final } bool has_castable_formats() const { return !castable_formats_.empty(); } VkFormat uint_backed() const { return uint_backed_; } // Format::uint_backed + bool a8_as_alpha() const { return a8_as_alpha_; } VkImageAspectFlags aspects() const { return aspects_; } bool rgb96() const { return rgb96_; } // a 96-bit texture in an RGBA32 image std::uint64_t image_address() const { return image_address_; } // what a T# names the texture by - VkMemoryPropertyFlags memory_flags() const { return memory_flags_; } // of the memory type behind it + VkMemoryPropertyFlags memory_flags() const { return unbound_attachment() ? 0 : memory_flags_; } // of its backing + bool is_shadow() const { return shadow_ != nullptr; } // create_shadow_buffer: a copy of title pages const DeviceState& device_state() const { return device_; } + void* title_address() const { return title_address_; } // place_at_title_address, or null + HRESULT upload_title_subresource(UINT subresource, void* data, UINT row, UINT slice, bool allow_staging) { + static const bool ordered = [] { + const char* value = std::getenv("LEONIDA_ORDER_TEXTURE_UPLOADS"); + return !value || std::strcmp(value, "0"); + }(); + if (ordered && host_transfer_) { + Region r{}; + if (!region(subresource, nullptr, r) || row != r.row_bytes || slice != row * r.rows) return E_INVALIDARG; + const auto result = device_.context->write_host_texture(id(), subresource, [&] { return host_copy(true, r, data); }); + if (result == VK_SUCCESS) return S_OK; + if (result != VK_NOT_READY) return E_FAIL; + // Layout changed after the pass checked the subresources. Never submit recursively. + if (!allow_staging) return DXGI_ERROR_WAS_STILL_DRAWING; + return cpu_copy(true, subresource, nullptr, data, row, slice, false); + } + return WriteToSubresource(subresource, nullptr, data, row, slice); + } + + bool replay_seen() const { return replay_seen_.load(std::memory_order_relaxed); } + bool staged_title() const { return staged_title_; } + bool upload_staged_title(const rt::xg_xs::Texture& layout, const std::uint8_t* tiled, + std::vector& columns, bool inspect, bool& nonzero) { + return device_.title_upload.write(device_, id(), binding_, layout, tiled, columns, inspect, nonzero); + } + // Map and the destructor notify the registry for a slot-133 placement. + void mark_title_texture() { title_texture_ = true; } + void note_shader_view() const { shader_views_.fetch_add(1, std::memory_order_relaxed); } + std::uint32_t shader_views() const { return shader_views_.load(std::memory_order_relaxed); } + // The element a CPU copy moves (a 4x4 block for block-compressed formats), as WriteToSubresource takes it. + leonida::BlockFormat copy_element() const { return leonida::copy_block_format(binding_, VK_IMAGE_ASPECT_COLOR_BIT); } + // WriteToSubresource of this subresource is a host copy now (VK_EXT_host_image_copy, image in GENERAL), not a + // staged copy through a queue: the only kind a refresh before a submission may do. + bool host_copy_now(UINT subresource) const { + return host_transfer_ && device_.context->layout(id(), subresource) == VK_IMAGE_LAYOUT_GENERAL; + } // Default-heap buffers are ranges of the GPU address arena: console VA = offset, zeroed through the arena's host // mapping. Upload and readback buffers keep their own host memory; with buffer device addresses their console @@ -1991,8 +4496,9 @@ class Resource final // with VK_EXT_external_memory_host and the buffer bound to it at offset 0, so the CPU's writes there are the GPU's // reads with no copy. Its console VA is `address` itself, the VA the title chose, so vertex, index and immediate // writes the title names by that VA find this buffer (VulkanContext::buffer_at). A shader that adds heap_base to - // that VA does not reach it: the title's own V#s into these pages need the single address space of - // docs/d3d12_vulkan.md section 3.3, which this does not decide. The pages stay the caller's: nothing is zeroed. + // that VA would not reach it, so the root views and V#s the layer writes for it name its device address minus + // heap_base instead (alias_title_va, docs/d3d12_vulkan.md section 3.3 "Title-placed buffers"); V#s the title + // writes into memory itself keep its VA. The pages stay the caller's: nothing is zeroed. HRESULT create_host_buffer(void* address) { auto& vk = device_.context->vk; const VkDeviceSize alignment = device_.info.host_pointer_alignment; @@ -2022,8 +4528,11 @@ class Resource final bool importable = true; for (VkDeviceSize at = 0; at < bytes;) { MEMORY_BASIC_INFORMATION region{}; + // A page that is not writable right now (a shadow buffer's write watch on the same page, say) cannot be + // pinned for the GPU: the kernel module refuses it, loudly, and the shadow answers anyway. if (!VirtualQuery(static_cast(base_address) + at, ®ion, sizeof(region)) || - region.State != MEM_COMMIT || (region.Protect & (PAGE_WRITECOMBINE | PAGE_NOCACHE))) { + region.State != MEM_COMMIT || (region.Protect & (PAGE_WRITECOMBINE | PAGE_NOCACHE | PAGE_GUARD)) || + !(region.Protect & (PAGE_READWRITE | PAGE_EXECUTE_READWRITE))) { importable = false; break; } @@ -2070,6 +4579,7 @@ class Resource final need_bda ? static_cast(&flags) : &import}; allocate.allocationSize = bytes; allocate.memoryTypeIndex = i; + std::lock_guard serial(DeviceState::memory_mutex()); if (vk.vkAllocateMemory(device_.info.device, &allocate, nullptr, &memory_) == VK_SUCCESS) memory_flags_ = device_.memory.memoryTypes[i].propertyFlags; else @@ -2077,25 +4587,148 @@ class Resource final } if (memory_) break; } - if (!memory_) return E_OUTOFMEMORY; - if (vk.vkBindBufferMemory(device_.info.device, buffer_, memory_, offset) != VK_SUCCESS) return E_OUTOFMEMORY; + if (!memory_) return E_OUTOFMEMORY; + if (vk.vkBindBufferMemory(device_.info.device, buffer_, memory_, offset) != VK_SUCCESS) return E_OUTOFMEMORY; + if (need_bda && vk.vkGetBufferDeviceAddress) { + VkBufferDeviceAddressInfo bda{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; + bda.buffer = buffer_; + buffer_va_ = vk.vkGetBufferDeviceAddress(device_.info.device, &bda); + gpu_va_ = buffer_va_; + } + // An import the driver put below the arena cannot be named by a V#: the V# keeps 48 bits of (device address + // - heap_base), which is negative there, and the translated shaders zero-extend it, so they read 2^48 above + // the buffer (found natively by plaaasma-agent: garbage constants, or VK_ERROR_DEVICE_LOST; this machine + // logs the same wrap). Such an import is not used: the shadow buffer in the arena answers, as when the + // import is refused. LEONIDA_IMPORT_BELOW_ARENA=1 keeps the import (for a shader library whose programs + // sign-extend the address). + static const bool keep_low_imports = [] { + wchar_t value[2]{}; + return GetEnvironmentVariableW(L"LEONIDA_IMPORT_BELOW_ARENA", value, 2) == 1 && value[0] == L'1'; + }(); + if (buffer_va_ && buffer_va_ < device_.arena.address && !keep_low_imports) { + static std::atomic logged{0}; + if (logged.fetch_add(1, std::memory_order_relaxed) < 8) + std::fprintf(stderr, + "[rt] d3d12: an import of title memory at %p (%llu bytes) landed below the arena (device " + "address 0x%llx, arena 0x%llx): a shadow in the arena is used instead\n", + address, static_cast(desc_.Width), + static_cast(buffer_va_), + static_cast(device_.arena.address)); + buffer_va_ = 0; + gpu_va_ = 0; + return E_NOTIMPL; + } + mapped_ = address; + host_import_ = true; + va_ = start; + device_.log_va("title-placed buffer", va_, desc_.Width); + leonida::ResourceBinding binding{}; + binding.buffer = buffer_; + binding.size = desc_.Width; + binding.host = static_cast(address); + binding.host_readable = true; + binding.va = va_; + device_.context->add_resource(id(), binding); + // Shaders reach the imported pages by their device address (src/title_va_alias.h). + if (buffer_va_) alias_title_va(buffer_va_ - device_.arena.address); + return S_OK; + } + + // Registers [va_, va_ + width) as reached by shaders at `shader_va` (src/title_va_alias.h): the root views and + // buffer V#s the layer writes for an address in it get the matching address of the buffer's GPU copy. + void alias_title_va(std::uint64_t shader_va) { + if (!leonida::title_va_aliases().add(va_, desc_.Width, shader_va)) return; + title_alias_ = shader_va; + aliased_ = true; + } + + // The fallback of create_host_buffer, for pages the driver will not import: write-combined or uncached ones (in + // retail 74 MiB of the title's 182 MiB range), pages not committed yet, a device without + // VK_EXT_external_memory_host, or a driver past its import budget (an RTX 3070 Ti answers + // VK_ERROR_OUT_OF_DEVICE_MEMORY after about 64 MiB of imports). The buffer has its own host-visible memory, a + // shadow of the title's pages, but keeps the title's VA as its console VA, so the descriptors and views the title + // builds from that VA still find it (an ordinary buffer here had another VA and none of the data: slot 70 wrote + // a null SRV and the UI draws sampled nothing). It is filled from the pages now, and before every submission + // of command lists the pages the title wrote since are copied again (ShadowPages, DeviceState::refresh_shadows). + // One way only: what the GPU writes to the shadow is NOT copied back to the title's pages, and the next copy of + // a page overwrites it. A title that reads GPU output at `address` needs the import. + HRESULT create_shadow_buffer(void* address) { + auto& vk = device_.context->vk; + if (!address || !desc_.Width || desc_.Width > ~UINT64(0) - D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT) + return E_INVALIDARG; + const auto* pages = static_cast(address); + // The shadow is a range of the GPU address arena when it fits there (docs/d3d12_vulkan.md section 3.3). + // The title's VA is a user-mode Windows address far above 4 GiB, past the arena, so a shader's heap_base + VA would miss + // any buffer of the layer's; the root views and V#s the layer writes for that VA name the arena offset + // instead (src/title_va_alias.h), a VA below 4 GiB that a root view and a V#'s 48 bits both hold. The arena + // is host-visible, so the per-submission copy writes it in place. + if (device_.arena.mapped && device_.arena_allocate(desc_.Width, D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT, + arena_offset_, DeviceState::arena_buffer)) { + in_arena_ = true; + shadow_ = device_.arena.mapped + arena_offset_; + device_.add_shadow(pages, shadow_, std::size_t(desc_.Width)); + mapped_ = address; + va_ = reinterpret_cast(address); + buffer_va_ = gpu_va_ = device_.arena.address + arena_offset_; + device_.log_va("title-placed buffer (arena shadow)", va_, desc_.Width); + leonida::ResourceBinding binding{}; + binding.buffer = device_.arena.buffer; + binding.buffer_offset = arena_offset_; + binding.size = desc_.Width; + binding.host = shadow_; + binding.va = va_; + device_.context->add_resource(id(), binding); + alias_title_va(arena_offset_); + return S_OK; + } + log_once("a title-placed shadow buffer does not fit the GPU address arena (raise LEONIDA_ARENA_MB), so it " + "has its own memory; size in KiB:", + int(desc_.Width / 1024)); + const bool need_bda = device_.info.buffer_device_address || device_.arena.buffer != VK_NULL_HANDLE; + VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; + info.size = desc_.Width; + info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | + VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT | + VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | + VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT; + if (device_.info.conditional_rendering) info.usage |= VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT; + if (need_bda) info.usage |= VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; + device_.share(info); + if (vk.vkCreateBuffer(device_.info.device, &info, nullptr, &buffer_) != VK_SUCCESS) return E_OUTOFMEMORY; + VkMemoryRequirements requirements{}; + vk.vkGetBufferMemoryRequirements(device_.info.device, buffer_, &requirements); + // As an upload buffer (D3D-96): the CPU writes it at every submission and the GPU reads it, so VRAM through + // Resizable BAR where there is one, system memory otherwise. + memory_ = device_.allocate(requirements, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, + device_.upload_in_vram ? VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT : 0, &memory_flags_, + need_bda); + void* shadow = nullptr; + if (!memory_ || vk.vkBindBufferMemory(device_.info.device, buffer_, memory_, 0) != VK_SUCCESS || + vk.vkMapMemory(device_.info.device, memory_, 0, VK_WHOLE_SIZE, 0, &shadow) != VK_SUCCESS) + return E_OUTOFMEMORY; + shadow_ = static_cast(shadow); + device_.add_shadow(pages, shadow_, std::size_t(desc_.Width)); + // Map() answers the title's own pages, as the imported buffer does: a write to the shadow's memory would be + // overwritten by the next copy. mapped_ = address; - host_import_ = true; - va_ = start; + va_ = reinterpret_cast(address); if (need_bda && vk.vkGetBufferDeviceAddress) { VkBufferDeviceAddressInfo bda{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; bda.buffer = buffer_; buffer_va_ = vk.vkGetBufferDeviceAddress(device_.info.device, &bda); gpu_va_ = buffer_va_; } - device_.log_va("title-placed buffer", va_, desc_.Width); + device_.log_va("title-placed buffer (shadow)", va_, desc_.Width); leonida::ResourceBinding binding{}; binding.buffer = buffer_; binding.size = desc_.Width; - binding.host = static_cast(address); - binding.host_readable = true; + // CPU-side reads take the shadow, not the title's pages: it is as fresh as what the GPU reads and every byte + // of it can be read, which the pages do not promise. Not host_readable: GPU writes are not handed back. + binding.host = shadow_; binding.va = va_; device_.context->add_resource(id(), binding); + if (buffer_va_) alias_title_va(buffer_va_ - device_.arena.address); return S_OK; } @@ -2168,6 +4801,7 @@ class Resource final format_ = format.format; aspects_ = format.aspects; image_address_ = device_.next_image_address.fetch_add(256); + device_.note_image_address(image_address_, this); binding_.image = image_; binding_.format = format_; binding_.aspects = aspects_; @@ -2201,8 +4835,25 @@ class Resource final return S_OK; } - HRESULT create_texture(const Format& format, const std::vector& castable = {}) { + HRESULT create_texture(const Format& format, const std::vector& asked_castable = {}, + TitleImageOrigin origin = TitleImageOrigin::ordinary, bool allow_staged_title = true) { auto& vk = device_.context->vk; + // The console lets a typed RGBA8 or BGRA8 render target take a view in its UNORM/sRGB twin without a castable + // list: the title renders its movie frames through an R8G8B8A8_UNORM view of an R8G8B8A8_UNORM_SRGB target, + // and every such draw lost its target (9 of 9 sampled). Such a texture is created as if its list named the + // twin, so the view is legal in Vulkan (console_format_stand_ins). + std::vector castable = asked_castable; + if (castable.empty() && !format.uint_backed && !format.typeless && console_format_stand_ins() && + (desc_.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET)) { + const VkFormat twin = format.format == VK_FORMAT_R8G8B8A8_UNORM ? VK_FORMAT_R8G8B8A8_SRGB + : format.format == VK_FORMAT_R8G8B8A8_SRGB ? VK_FORMAT_R8G8B8A8_UNORM + : format.format == VK_FORMAT_B8G8R8A8_UNORM ? VK_FORMAT_B8G8R8A8_SRGB + : format.format == VK_FORMAT_B8G8R8A8_SRGB ? VK_FORMAT_B8G8R8A8_UNORM + : VK_FORMAT_UNDEFINED; + if (twin != VK_FORMAT_UNDEFINED && desc_.Format != DXGI_FORMAT_B8G8R8X8_UNORM && + desc_.Format != DXGI_FORMAT_B8G8R8X8_UNORM_SRGB) + castable = {format.format, twin}; + } const bool volume = desc_.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; const UINT depth = volume ? desc_.DepthOrArraySize : 1; const bool one_d = desc_.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D; @@ -2224,8 +4875,12 @@ class Resource final info.flags |= VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT; create.format_list.viewFormatCount = std::uint32_t(view_formats_.size()); create.format_list.pViewFormats = view_formats_.data(); - create.format_list.pNext = info.pNext; - info.pNext = &create.format_list; + // A uint-backed format already chained format_list in TextureCreateInfo: chaining it to itself would + // make the pNext chain cyclic (found in review). + if (info.pNext != &create.format_list) { + create.format_list.pNext = info.pNext; + info.pNext = &create.format_list; + } } const std::uint32_t samples = info.samples; // Textures the CPU reads and writes (WriteToSubresource/ReadFromSubresource) copy on the host when they can. @@ -2241,12 +4896,84 @@ class Resource final info.usage &= ~VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT; support = device_.check_image_support(info); } - if (FAILED(support)) return support; + if (FAILED(support)) { + std::fprintf(stderr, + "[rt] d3d12: texture refused by the GPU's image support query (hr 0x%08x): vk format %d " + "type %d %ux%ux%u mips %u layers %u samples %d usage 0x%x flags 0x%x (DXGI %d, D3D12 flags " + "0x%x)\n", + unsigned(support), int(info.format), int(info.imageType), info.extent.width, + info.extent.height, info.extent.depth, info.mipLevels, info.arrayLayers, int(info.samples), + unsigned(info.usage), unsigned(info.flags), int(desc_.Format), unsigned(desc_.Flags)); + return support; + } device_.share(info); + // A host-copyable sampled image can exclude the GPU's unmapped device-local memory. + // Compare identical creation parameters before dropping HOST_TRANSFER. Keep the fast + // host path on UMA and on devices where host copies allow the same device-local type. + static const bool stage_title = [] { + const char* value = std::getenv("LEONIDA_TITLE_IMAGE_STAGING"); + return !value || std::strcmp(value, "0"); + }(); + // Keep placed movie planes with a known linear CPU layout on the host-copy path. + // Map on a staged placement still returns the title's pages and participates in the refresh. + std::uint32_t xg_layout = 0; + const bool linear_placement = origin == TitleImageOrigin::placed && + (desc_.Layout == D3D12_TEXTURE_LAYOUT_ROW_MAJOR || + (leonida::title_xg_layouts::find({std::uint32_t(desc_.Dimension), std::uint32_t(desc_.Format), + desc_.Height, desc_.DepthOrArraySize, desc_.MipLevels, desc_.Width}, xg_layout) && xg_layout == 1)); + static const bool defer_placed = [] { + const char* value = std::getenv("LEONIDA_PLACED_IMAGE_DEFER"); + return !value || std::strcmp(value, "0"); + }(); + // Private BC copies start with the exact same zero blocks as the shared image. The host + // transition and clear complete before a private view is published, including during command prepare. + if (defer_placed && origin == TitleImageOrigin::placed && host_transfer_ && device_.bindless && + desc_.Flags == D3D12_RESOURCE_FLAG_NONE && desc_.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && + desc_.SampleDesc.Count == 1 && asked_castable.empty() && !format.typeless && + leonida::block_format(format.format, format.aspects).block > 1) { + VkMemoryRequirements footprint{}; + if (device_.memory_requirements(info, footprint)) + shared_zero_ = device_.zero_sampled_image(desc_, format, footprint.size); + } + std::uint32_t plain_bits = 0; + if (stage_title && !shared_zero_ && allow_staged_title && origin != TitleImageOrigin::ordinary && !linear_placement && + host_transfer_ && format.aspects == VK_IMAGE_ASPECT_COLOR_BIT && device_.image_requirements) { + for (std::uint32_t i = 0; i < device_.memory.memoryTypeCount; ++i) { + const auto flags = device_.memory.memoryTypes[i].propertyFlags; + if ((flags & (VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)) == + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) plain_bits |= 1u << i; + } + VkMemoryRequirements with{}, without{}; + auto staged = info; + staged.usage &= ~VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT; + if (plain_bits && device_.memory_requirements(info, with) && !(with.memoryTypeBits & plain_bits) && + device_.memory_requirements(staged, without) && (without.memoryTypeBits & plain_bits)) { + staged_title_ = true; + host_transfer_ = false; + info.usage = staged.usage; + } + } + auto retry_host = [&] { + if (image_) vk.vkDestroyImage(device_.info.device, image_, nullptr); + if (memory_) vk.vkFreeMemory(device_.info.device, memory_, nullptr); + image_ = VK_NULL_HANDLE; + memory_ = VK_NULL_HANDLE; + staged_title_ = false; + log_once("no room for a staged title image; retrying host-copyable backing, format", int(info.format)); + return create_texture(format, asked_castable, origin, false); + }; + bool retried = false; // retry_host made the whole resource again: nothing more to do here const auto create_image = [&]() -> HRESULT { const VkResult created = vk.vkCreateImage(device_.info.device, &info, nullptr, &image_); if (created == VK_SUCCESS) return S_OK; + std::fprintf(stderr, "[rt] d3d12: vkCreateImage failed (%d): vk format %d %ux%u usage 0x%x flags 0x%x\n", + int(created), int(info.format), info.extent.width, info.extent.height, unsigned(info.usage), + unsigned(info.flags)); image_ = VK_NULL_HANDLE; // undefined after a failed create; ~Resource destroys any non-null image_ + if (staged_title_) { + retried = true; + return retry_host(); + } if (created == VK_ERROR_OUT_OF_HOST_MEMORY || created == VK_ERROR_OUT_OF_DEVICE_MEMORY) return E_OUTOFMEMORY; if (!view_formats_.empty()) { @@ -2255,44 +4982,94 @@ class Resource final } return E_OUTOFMEMORY; }; - if (HRESULT hr = create_image(); FAILED(hr)) return hr; + if (HRESULT hr = create_image(); FAILED(hr) || retried) return hr; // Some drivers advertise VK_EXT_host_image_copy yet allow no memory type for a HOST_TRANSFER image // (NVIDIA Pascal / 582.78: memoryTypeBits == 0), or fail to allocate one. Staging copies do not need // that usage, so recreate the image without it and continue on that path, as for a refused format above. VkMemoryRequirements requirements{}; - for (;;) { + std::uint32_t type = UINT32_MAX; + const bool stream = origin == TitleImageOrigin::streamed || origin == TitleImageOrigin::pending_stream; + const auto allowed = staged_title_ ? plain_bits : UINT32_MAX; + const bool attachment = desc_.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | + D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + if (shared_zero_ || (defer_placed && origin == TitleImageOrigin::placed && attachment && !cpu_visible())) { vk.vkGetImageMemoryRequirements(device_.info.device, image_, &requirements); - // NVIDIA's Pascal driver (582.78 on a GTX 1050 Ti) reports HOST_IMAGE_TRANSFER for the format and creates - // the image, but then allows it no memory type at all. The image has not been bound or used, so it is - // made again without host-transfer usage and the CPU copies take the staging path. The test forces this - // branch on any GPU with force_host_transfer_retry. - bool retry = host_transfer_ && - (requirements.memoryTypeBits == 0 || device_.info.force_host_transfer_retry); - if (!retry) { - memory_ = device_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &memory_flags_); - if (memory_ && vk.vkBindImageMemory(device_.info.device, image_, memory_, 0) == VK_SUCCESS) break; - if (memory_) { vk.vkFreeMemory(device_.info.device, memory_, nullptr); memory_ = VK_NULL_HANDLE; } - retry = host_transfer_; // a failed allocation/bind retries on the staging path too - } - if (!retry) return E_OUTOFMEMORY; - log_once(requirements.memoryTypeBits == 0 || device_.info.force_host_transfer_retry - ? "host-transfer image has no memory type; using staging copies, format" - : "host-transfer image could not be bound; using staging copies, format", - int(info.format)); - vk.vkDestroyImage(device_.info.device, image_, nullptr); - image_ = VK_NULL_HANDLE; - host_transfer_ = false; - info.usage &= ~VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT; - if (HRESULT hr = device_.check_image_support(info); FAILED(hr)) return hr; - if (HRESULT hr = create_image(); FAILED(hr)) { - log_once("image refused after dropping host-transfer usage; format", int(info.format)); - return hr; + deferred_bytes_ = requirements.size; + deferred_types_ = allowed; + if (shared_zero_) { + deferred_stream_ = true; + std::lock_guard lock(device_.descriptor_mutex); + device_.pending_image_keys[image_].zero = shared_zero_; } + deferred_attachment_ = std::make_unique(this, [](void* owner) { + return static_cast(owner)->bind_placed_memory(); + }); + } else if (origin == TitleImageOrigin::pending_stream && (host_transfer_ || staged_title_)) { vk.vkGetImageMemoryRequirements(device_.info.device, image_, &requirements); - if (requirements.memoryTypeBits == 0) - log_once("image has no memory type even without host-transfer usage; format", int(info.format)); + deferred_bytes_ = requirements.size; + deferred_types_ = allowed; + deferred_stream_ = true; + std::lock_guard lock(device_.descriptor_mutex); + device_.pending_image_keys.try_emplace(image_); + } else { + for (;;) { + vk.vkGetImageMemoryRequirements(device_.info.device, image_, &requirements); + // NVIDIA's Pascal driver (582.78 on a GTX 1050 Ti) reports HOST_IMAGE_TRANSFER for the format and + // creates the image, but then allows it no memory type at all. The image has not been bound or used, + // so it is made again without host-transfer usage and the CPU copies take the staging path. The test + // forces this branch on any GPU with force_host_transfer_retry. + bool retry = host_transfer_ && + (requirements.memoryTypeBits == 0 || device_.info.force_host_transfer_retry); + if (!retry) { + if (bind_texture_memory(stream, allowed, requirements, type)) break; + retry = host_transfer_; // a failed allocation/bind retries on the staging path too + } + if (!retry) { + if (staged_title_) return retry_host(); + std::fprintf(stderr, + "[rt] d3d12: texture memory unavailable: %llu bytes, alignment %llu, type bits 0x%x " + "(vk format %d %ux%u)\n", + static_cast(requirements.size), + static_cast(requirements.alignment), + unsigned(requirements.memoryTypeBits), int(info.format), info.extent.width, + info.extent.height); + return E_OUTOFMEMORY; + } + log_once(requirements.memoryTypeBits == 0 || device_.info.force_host_transfer_retry + ? "host-transfer image has no memory type; using staging copies, format" + : "host-transfer image could not be bound; using staging copies, format", + int(info.format)); + vk.vkDestroyImage(device_.info.device, image_, nullptr); + image_ = VK_NULL_HANDLE; + host_transfer_ = false; + info.usage &= ~VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT; + if (HRESULT hr = device_.check_image_support(info); FAILED(hr)) return hr; + if (HRESULT hr = create_image(); FAILED(hr) || retried) { + if (FAILED(hr)) log_once("image refused after dropping host-transfer usage; format", int(info.format)); + return hr; + } + vk.vkGetImageMemoryRequirements(device_.info.device, image_, &requirements); + if (requirements.memoryTypeBits == 0) + log_once("image has no memory type even without host-transfer usage; format", int(info.format)); + } } + if (!deferred_stream_ && !deferred_attachment_ && origin != TitleImageOrigin::ordinary && leonida::mem_probe::interval_seconds()) { + char key[160]; + std::snprintf(key, sizeof(key), "image-class slot=%u format=%u dim=%u samples=%u flags=0x%x usage=0x%x bits=0x%x", + stream ? 70u : 133u, unsigned(info.format), + unsigned(info.imageType), unsigned(info.samples), unsigned(info.flags), + unsigned(info.usage), requirements.memoryTypeBits); + if (first_diagnostic(key, int(type))) { + VkImageCreateInfo staged = info; + staged.usage &= ~VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT; + VkMemoryRequirements without = requirements; + if (staged.usage != info.usage && !device_.memory_requirements(staged, without)) + without.memoryTypeBits = 0; + std::fprintf(stderr, "[rt] mem-probe: %s no-host-bits=0x%x type=%u\n", key, without.memoryTypeBits, type); + } + } leonida::ResourceBinding binding{}; binding.image = image_; binding.typeless = format.typeless && format.aspects == VK_IMAGE_ASPECT_COLOR_BIT; // views name their format @@ -2319,22 +5096,128 @@ class Resource final binding.sampled_in_general = device_.bindless != nullptr; format_ = format.format; uint_backed_ = format.uint_backed; + a8_as_alpha_ = format.a8_as_alpha; aspects_ = format.aspects; image_address_ = device_.next_image_address.fetch_add(256); + device_.note_image_address(image_address_, this); + binding.deferred_memory = deferred_attachment_.get(); + if (origin == TitleImageOrigin::placed && leonida::mem_probe::interval_seconds()) + binding.replay_seen = &replay_seen_; binding_ = binding; + if (shared_zero_) { + // All direct GPU commands resolve this binding in prepare(), before the descriptor table flush. + device_.context->add_resource(id(), binding_, host_transfer_ ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_UNDEFINED); + return S_OK; + } + return deferred_stream_ ? S_OK : register_bound_texture(); + } + + // Called with title_texture_mutex held, after a guarded read of the complete console texture. + bool back_streamed_texture() { + if (!deferred_bytes_) return true; + if (!image_backing_bytes_) { + VkMemoryRequirements requirements{}; + std::uint32_t type = UINT32_MAX; + if (!bind_texture_memory(true, deferred_types_, requirements, type) && + (deferred_types_ == UINT32_MAX || !(requirements.memoryTypeBits & ~deferred_types_) || + !bind_texture_memory(true, ~deferred_types_, requirements, type))) return false; + } + if (FAILED(register_bound_texture())) return false; + deferred_bytes_ = 0; + return true; + } + + void publish_streamed_texture() { + if (!deferred_stream_) return; + std::lock_guard lock(device_.descriptor_mutex); + auto pending = device_.pending_image_keys.extract(image_); + const auto owner = device_.images_by_address.find(image_address_); + if (!pending.empty() && owner != device_.images_by_address.end() && owner->second == this) { + if (pending.mapped().zero) device_.forget_image_views_locked(image_address_); + for (const auto& [words, image] : pending.mapped().keys) + device_.bind_image_locked(words, image, image_, format_, aspects_, false, has_view_format_list(), + uint_backed_); + } + deferred_stream_ = false; + } + + VkDeviceSize unbound_bytes() const { return image_backing_bytes() ? 0 : deferred_bytes_; } + +private: + bool bind_placed_memory() { + VkMemoryRequirements requirements{}; + std::uint32_t type = UINT32_MAX; + if (!image_backing_bytes_ && !bind_texture_memory(false, deferred_types_, requirements, type)) { + if (!(requirements.memoryTypeBits & ~deferred_types_) || + !bind_texture_memory(false, ~deferred_types_, requirements, type)) return false; + } + if (shared_zero_) { + if (host_transfer_ && !host_initialize()) return false; + publish_streamed_texture(); + } + return true; + } + + bool bind_texture_memory(bool stream, std::uint32_t allowed_types, VkMemoryRequirements& requirements, + std::uint32_t& type) { + auto& vk = device_.context->vk; + static const bool pool_images = [] { + wchar_t value[2]{}; + return !(GetEnvironmentVariableW(L"LEONIDA_TITLE_IMAGE_POOL", value, 2) == 1 && value[0] == L'0'); + }(); + VkMemoryDedicatedRequirements dedicated{VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS}; + if (stream && pool_images && device_.bound_image_requirements) { + VkImageMemoryRequirementsInfo2 query{VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2}; + query.image = image_; + VkMemoryRequirements2 result{VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2}; + result.pNext = &dedicated; + device_.bound_image_requirements(device_.info.device, &query, &result); + requirements = result.memoryRequirements; + if (!dedicated.requiresDedicatedAllocation) { + auto pool_requirements = requirements; + pool_requirements.memoryTypeBits &= allowed_types; + pooled_image_ = device_.title_image_pool.bind(device_.info.device, image_, pool_requirements, + vk.vkBindImageMemory, vk.vkDestroyImage, vk.vkFreeMemory, [&](VkDeviceSize size, std::uint32_t& type) { + auto page = pool_requirements; + page.size = size; + return device_.allocate(page, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, nullptr, false, &type); + }); + if (pooled_image_) memory_flags_ = device_.memory.memoryTypes[pooled_image_->page->type].propertyFlags; + } + } else { + vk.vkGetImageMemoryRequirements(device_.info.device, image_, &requirements); + } + type = pooled_image_ ? pooled_image_->page->type : UINT32_MAX; + if (!pooled_image_) { + auto selected = requirements; + selected.memoryTypeBits &= allowed_types; + memory_ = device_.allocate(selected, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &memory_flags_, false, + &type, dedicated.requiresDedicatedAllocation ? image_ : VK_NULL_HANDLE); + } + if (!pooled_image_ && (!memory_ || vk.vkBindImageMemory(device_.info.device, image_, memory_, 0) != VK_SUCCESS)) { + if (memory_) vk.vkFreeMemory(device_.info.device, memory_, nullptr); + memory_ = VK_NULL_HANDLE; + return false; + } + image_backing_bytes_ = requirements.size; + return true; + } + + HRESULT register_bound_texture() { if (host_transfer_) { // Moved to GENERAL and zero-filled on the host now, so the CPU can copy into it before any command // list has touched it (a first GPU use would otherwise zero-fill over what the CPU wrote). if (!host_initialize()) return E_OUTOFMEMORY; - device_.context->add_resource(id(), binding, VK_IMAGE_LAYOUT_GENERAL); + device_.context->add_resource(id(), binding_, VK_IMAGE_LAYOUT_GENERAL); return S_OK; } // Never used yet: the first command that touches a part zero-fills it and moves it to the layout of the // state that command expects (vulkan_replay.h, initialize), so no submission is needed here. - device_.context->add_resource(id(), binding, VK_IMAGE_LAYOUT_UNDEFINED); + device_.context->add_resource(id(), binding_, VK_IMAGE_LAYOUT_UNDEFINED); return S_OK; } +public: // D3D12 reports the placement alignment of a description that left it 0: 64 KiB, or 4 MiB for a multisampled // texture. One the description asked for is kept. Measured on the PC runtime and WARP (d3d12_resource_desc_test). D3D12_RESOURCE_DESC STDMETHODCALLTYPE GetDesc() override { @@ -2360,13 +5243,29 @@ class Resource final // runtime). // Buffers report their console VA into the GPU address arena; an acceleration structure reports its real device // address (instance descriptors and builds hand it to the driver). A texture the title placed at its own address - // through Xbox slot 133 reports that title address, as the console does: a title uses it as the CPU pointer it - // clears the texture through (docs/d3d12_vulkan.md 3.3). Any other texture answers 0, as on D3D12. - D3D12_GPU_VIRTUAL_ADDRESS STDMETHODCALLTYPE GetGPUVirtualAddress() override { return accel_ ? gpu_va_ : va_; } - // The title's own address for a texture Xbox slot 133 placed. The image is still the committed fallback, so its - // pixels do not alias the title's pages yet; the address is what GetGPUVirtualAddress answers (XCL PR #168's - // behavior, measured on a retail title). - void set_title_address(D3D12_GPU_VIRTUAL_ADDRESS address) { va_ = address; } + // through Xbox slot 133 reports that title address, as the console does (place_at_title_address; docs/d3d12_vulkan.md + // 3.3). Any other texture answers 0, as on D3D12. + D3D12_GPU_VIRTUAL_ADDRESS STDMETHODCALLTYPE GetGPUVirtualAddress() override { + if (image_ && title_address_) return reinterpret_cast(title_address_); + return accel_ ? gpu_va_ : va_; + } + + // A texture the title placed on its own memory (Xbox device slot 133, create_at_host_address). The console's + // texture IS that memory: Map and GetGPUVirtualAddress answer with the address (the title memsets and fills + // textures through the pointer Map gives it, and writes to address 0 when it gets none), and its T#s, the ones + // the title writes itself into a console descriptor heap included, name it by that address. The image is still + // ordinary GPU memory, filled from the title's bytes at the address by the title-texture registry + // (TitleTexture) unless the GPU writes it. + void place_at_title_address(void* address, bool separate_image_key = false) { + title_address_ = address; + const auto va = reinterpret_cast(address); + if (!image_ || !image_address_ || (va & 0xff)) return; // a T# keeps the address without its low 8 bits + if (separate_image_key) return; + device_.forget_image(image_address_); + device_.forget_image(va); // an earlier texture placed at this address, still alive: its views are stale + image_address_ = va; + device_.note_image_address(image_address_, this); + } // // The node masks read back as the one node of a single adapter (0 becomes 1), and the heap flags as the runtime @@ -2404,6 +5303,14 @@ class Resource final // no pointer to give (its layout is the driver's), so D3D12 only lets it be mapped with a null pointer, before // WriteToSubresource/ReadFromSubresource. HRESULT STDMETHODCALLTYPE Map(UINT subresource, const D3D12_RANGE* read, void** data) override { + if (image_ && title_address_) { // place_at_title_address: the console answers with the texture's memory + if (data) *data = title_address_; + // From now on the CPU may write its texels whenever it likes (video planes are mapped once): the + // registry checks this texture's bytes before submissions (Device::refresh_title_textures). + if (title_texture_ && !title_mapped_.exchange(true, std::memory_order_relaxed)) + device_.title_texture_mapped(this, reinterpret_cast(title_address_)); + return S_OK; + } if (image_) { VkImageSubresourceRange range{}; return !data && cpu_visible() && subresource != leonida::all_subresources && @@ -2416,7 +5323,12 @@ class Resource final if (data) *data = mapped_; return S_OK; } - void STDMETHODCALLTYPE Unmap(UINT, const D3D12_RANGE*) override {} + // A texture the title placed: Unmap ends its CPU writes (the title's lock passes the range it wrote), so its + // image is filled again before the next submission (TitleTexture). + void STDMETHODCALLTYPE Unmap(UINT, const D3D12_RANGE* written) override { + if (image_ && title_address_ && title_texture_ && (!written || written->End > written->Begin)) + device_.title_texture_unmapped(this, reinterpret_cast(title_address_)); + } // CPU copies into and out of a texture subresource. D3D12 completes them before returning and leaves it to // the application to keep the GPU off the subresource meanwhile, so a blocking copy is the whole contract. @@ -2473,11 +5385,12 @@ class Resource final } HRESULT cpu_copy(bool write, UINT subresource, const D3D12_BOX* box, void* data, UINT row_pitch, - UINT depth_pitch) { + UINT depth_pitch, bool allow_host = true) { if (!image_ || !data) return E_INVALIDARG; Region r{}; if (!region(subresource, box, r)) return E_INVALIDARG; if (!r.rows || !r.slices) return S_OK; // an empty box: nothing to copy + if (deferred_attachment_ && !deferred_attachment_->ensure()) return E_OUTOFMEMORY; // The pitches are not checked, as on the host runtime: rows or slices that overlap (a pitch smaller than a // row, or 0) are copied in order, row by row and slice by slice, so on a read the last one wins. if (!cpu_visible()) @@ -2501,7 +5414,7 @@ class Resource final // On the host only while the subresource is in GENERAL: it is from creation, and stays there until a // barrier moves it (D3D12's COMMON is GENERAL). Any other layout goes through the staging copy, which // moves it as a CopyTextureRegion would. - if (host_transfer_ && device_.context->layout(id(), subresource) == VK_IMAGE_LAYOUT_GENERAL) { + if (allow_host && host_transfer_ && device_.context->layout(id(), subresource) == VK_IMAGE_LAYOUT_GENERAL) { std::vector packed(r.row_bytes * r.rows * r.slices); if (write) pack(packed.data(), r.row_bytes); if (!host_copy(write, r, packed.data())) return E_FAIL; @@ -2660,22 +5573,39 @@ class Resource final VkBuffer buffer_ = VK_NULL_HANDLE; VkDeviceMemory memory_ = VK_NULL_HANDLE; VkMemoryPropertyFlags memory_flags_ = 0; + VkDeviceSize image_backing_bytes_ = 0; // Vulkan image memory requirement; excludes pool alignment/padding. + std::unique_ptr pooled_image_; VkAccelerationStructureKHR accel_ = VK_NULL_HANDLE; void* mapped_ = nullptr; VkFormat format_ = VK_FORMAT_UNDEFINED; std::vector view_formats_; // creation-time castable list; empty means no restriction std::vector castable_formats_; // the same list as the application gave it VkFormat uint_backed_ = VK_FORMAT_UNDEFINED; + bool a8_as_alpha_ = false; std::uint64_t image_address_ = 0; // what a T# names the texture by + void* title_address_ = nullptr; // where the title placed this texture (place_at_title_address), or null + bool title_texture_ = false; // mark_title_texture + mutable std::atomic shader_views_{0}; // T#s written for it (write_image_descriptor), for the census + std::atomic title_mapped_{false}; // Map told the registry bool rgb96_ = false; VkImageAspectFlags aspects_ = 0; std::uint64_t buffer_va_ = 0; std::uint64_t gpu_va_ = 0; bool host_import_ = false; // memory_ is the caller's pages (create_host_buffer): freed at once, not deferred + std::uint8_t* shadow_ = nullptr; // create_shadow_buffer: memory_ mapped, in DeviceState::shadows + bool aliased_ = false; // va_ is in leonida::title_va_aliases(), reached at title_alias_ + std::uint64_t title_alias_ = 0; bool reserved_ = false; bool sparse_image_ = false; bool placed_ = false; leonida::ResourceBinding binding_{}; // a texture's, as registered with the context + VkImage shared_zero_ = VK_NULL_HANDLE; // owned by the device + std::unique_ptr deferred_attachment_; + std::atomic replay_seen_{false}; + bool staged_title_ = false; + std::atomic deferred_stream_{false}; // keys stay unpublished until the whole first upload succeeds + VkDeviceSize deferred_bytes_ = 0; + std::uint32_t deferred_types_ = 0; bool host_transfer_ = false; // created with VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT D3D12_GPU_VIRTUAL_ADDRESS va_ = 0; // a buffer's console VA, or a slot-133 texture's title address VkDeviceSize arena_offset_ = 0; @@ -2685,6 +5615,30 @@ class Resource final std::shared_ptr heap_range_; }; +// One immutable, host-zeroed BC image per exact view shape. It has the right sampled format, extent, +// mip count and zero-block decoding even before the title first supplies data or copies into the placement. +VkImage DeviceState::zero_sampled_image(const D3D12_RESOURCE_DESC& d, const Format& format, VkDeviceSize bytes) { + if (!host_transfer_format(format.format)) return VK_NULL_HANDLE; + const ZeroShape key{d.Format, d.Width, d.Height, d.DepthOrArraySize, d.MipLevels}; + std::lock_guard lock(zero_image_mutex); + if (auto it = zero_images.find(key); it != zero_images.end()) return it->second ? it->second->image() : VK_NULL_HANDLE; + constexpr VkDeviceSize limit = 256ull << 20; + const auto used = zero_image_bytes.load(std::memory_order_relaxed); + if (used >= limit || bytes > limit - used) return VK_NULL_HANDLE; + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, D3D12_MEMORY_POOL_L0, 1, 1}; + auto* zero = new Resource(*this, d, heap, D3D12_HEAP_FLAG_NONE); + if (FAILED(zero->create_texture(format)) || !zero->host_initialized_image() || + zero->image_backing_bytes() > limit - used) { + zero->Release(); + zero_images.emplace(key, nullptr); + return VK_NULL_HANDLE; + } + zero_images.emplace(key, zero); + zero_image_bytes.fetch_add(zero->image_backing_bytes(), std::memory_order_relaxed); + return zero->image(); +} + + // DXGI -> Vulkan for vertex attributes, with each element's size for D3D12_APPEND_ALIGNED_ELEMENT. bool vertex_format(DXGI_FORMAT format, VkFormat& out, UINT& bytes) { struct Row { @@ -3171,7 +6125,35 @@ struct PipelineStream { bool has_graphics_stage = false; // VS, PS, DS, HS, GS, AS or MS }; -HRESULT parse_pipeline_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, PipelineStream& out) { +// Console stream retry adapted from Kokonotcu, ubiquitarianism/leonida #496 (GPL-3.0). +bool console_stream_enum_enabled() { + static const bool enabled = [] { + char value[8] = {}; + const DWORD n = GetEnvironmentVariableA("LEONIDA_XS_STREAM_ENUM", value, sizeof(value)); + return !(n == 1 && value[0] == '0') && + !(n == 2 && (value[0] == 'p' || value[0] == 'P') && (value[1] == 'c' || value[1] == 'C')); + }(); + return enabled; +} + +// The first DWORD in a DXIL program header holds the shader kind in its high 16 bits. +// Require a mesh program (kind 13) before changing the meaning of a stream that failed the PC parse. +bool is_mesh_container(const D3D12_SHADER_BYTECODE& code) { + if (!code.pShaderBytecode) return false; + const auto dxil = leonida::dxbc_part({static_cast(code.pShaderBytecode), + code.BytecodeLength}, "DXIL"); + return dxil.size() >= 4 && dxil[2] == 13 && dxil[3] == 0; +} + +HRESULT stream_unsupported(const char* reason, int type = 0) { + d3d12_trace::stream_refusal = reason; + log_once(reason, type); + return E_NOTIMPL; +} + +// The console numbering lacks the gap at 23 in the PC enumeration. +HRESULT parse_pipeline_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, PipelineStream& out, + bool console_enum = false) { if (!desc.pPipelineStateSubobjectStream || !desc.SizeInBytes) return E_INVALIDARG; D3D12_GRAPHICS_PIPELINE_STATE_DESC& g = out.graphics; for (auto& target : g.BlendState.RenderTarget) { @@ -3203,6 +6185,7 @@ HRESULT parse_pipeline_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, Pipe D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type; if (size - at < sizeof(type)) return E_INVALIDARG; std::memcpy(&type, base + at, sizeof(type)); + type = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE(d3d12_xs::pc_stream_type(unsigned(type), console_enum)); // The versioned depth-stencil and rasterizer subobjects describe the same state as their base type, so the // stream contract counts any two of one family as duplicates; the payload below still follows `type`. D3D12_PIPELINE_STATE_SUBOBJECT_TYPE family = type; @@ -3279,8 +6262,7 @@ HRESULT parse_pipeline_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, Pipe D3D12_DEPTH_STENCIL_DESC1 d{}; take(d); if (ok && d.DepthBoundsTestEnable) { - log_once("depth-bounds tests are not supported yet; stream subobject", int(type)); - return E_NOTIMPL; + return stream_unsupported("depth-bounds tests are not supported yet; stream subobject", int(type)); } g.DepthStencilState = {d.DepthEnable, d.DepthWriteMask, d.DepthFunc, d.StencilEnable, d.StencilReadMask, d.StencilWriteMask, d.FrontFace, d.BackFace}; @@ -3291,8 +6273,7 @@ HRESULT parse_pipeline_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, Pipe take(d); if (!ok) break; if (d.DepthBoundsTestEnable) { - log_once("depth-bounds tests are not supported yet; stream subobject", int(type)); - return E_NOTIMPL; + return stream_unsupported("depth-bounds tests are not supported yet; stream subobject", int(type)); } // Each face has its own read and write mask (OPTIONS14.IndependentFrontAndBackStencilRefMaskSupported): // the description takes the front face's, back_stencil the back face's. @@ -3333,8 +6314,7 @@ HRESULT parse_pipeline_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, Pipe D3D12_VIEW_INSTANCING_DESC d{}; take(d); if (ok && d.ViewInstanceCount) { - log_once("view instancing is not supported yet; views", int(d.ViewInstanceCount)); - return E_NOTIMPL; + return stream_unsupported("view instancing is not supported yet; stream subobject", int(type)); } break; } @@ -3445,36 +6425,70 @@ class PipelineState final // set from the list's state at each draw. // With `ms` (a pipeline state stream's MS subobject) it is an MS (+ PS) pipeline on VK_EXT_mesh_shader instead: // no VS, no vertex input or input assembly (the input layout, topology type and strip cut are ignored, as D3D12 - // does for mesh PSOs), drawn by DispatchMesh. An AS (amplification shader) is refused: the game has none. + // does for mesh PSOs), drawn by DispatchMesh. A nonempty PC AS still needs a task-stage translation. // `back_masks`, from a DEPTH_STENCIL2 subobject, are the back face's stencil masks; without it both faces take // the description's. + // LEONIDA_STUB_PIPELINES=1 (diagnostic): a pipeline whose translated shader is missing is created without a + // Vulkan pipeline. It is never registered, so SetPipelineState leaves no PSO bound and its draws and dispatches + // are recorded as no-ops (D3D-482). No game shader runs; the boot gets past a title that refuses to go on when + // pipeline creation fails. + static bool stub_pipelines() { + wchar_t v[8] = {}; + const DWORD n = GetEnvironmentVariableW(L"LEONIDA_STUB_PIPELINES", v, 8); + return n > 0 && n < 8 && v[0] != L'0'; + } + HRESULT stub_or(HRESULT hr, const char* what) { + if (!stub_pipelines()) return hr; + static std::atomic stubbed{0}; + const unsigned n = ++stubbed; + if (n == 1 || (n & (n - 1)) == 0) + std::fprintf(stderr, "[rt] d3d12: LEONIDA_STUB_PIPELINES: %s pipeline without a translated shader is a " + "no-op stub (%u so far)\n", what, n); + return S_OK; + } + + // LOCAL DIAGNOSTIC: one line per distinct graphics pipeline that uses a program translated from + // game_scarlett_master.exe (/exe), so the passes those inline containers serve can be read off a + // boot. LEONIDA_LOG_EXE_PIPELINES=1. + static void log_exe_pipeline(const leonida::ShaderEntry* vs, const leonida::ShaderEntry* ps, + const D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc) { + const auto from_exe = [](const leonida::ShaderEntry* e) { return e && e->name.rfind("exe/", 0) == 0; }; + if (!from_exe(vs) && !from_exe(ps)) return; + char line[512]; + std::snprintf(line, sizeof line, + "[rt] d3d12: exe pipeline vs=%s ps=%s rts=%u rt0=%d rt1=%d dsv=%d topo=%d samples=%u", + vs ? vs->fssm_sha256.c_str() : "-", ps ? ps->fssm_sha256.c_str() : "-", + unsigned(desc.NumRenderTargets), int(desc.RTVFormats[0]), int(desc.RTVFormats[1]), + int(desc.DSVFormat), int(desc.PrimitiveTopologyType), unsigned(desc.SampleDesc.Count)); + static std::mutex mutex; + static std::set seen; + std::lock_guard lock(mutex); + if (seen.insert(line).second) std::fprintf(stderr, "%s\n", line); + } HRESULT create_graphics(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc, const D3D12_SHADER_BYTECODE* ms = nullptr, const D3D12_SHADER_BYTECODE* as = nullptr, const StencilFaceMasks* back_masks = nullptr) { auto& vk = device_.context->vk; const VkDevice dev = device_.info.device; const bool mesh = ms && ms->pShaderBytecode && ms->BytecodeLength; if (as && as->pShaderBytecode && as->BytecodeLength) { - log_once("amplification shaders are not supported (the game has none); bytes", int(as->BytecodeLength)); - return E_NOTIMPL; + return stream_unsupported("amplification shaders are not supported; stream subobject", + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS); } if (mesh && (desc.VS.BytecodeLength || desc.HS.BytecodeLength || desc.DS.BytecodeLength || desc.GS.BytecodeLength || desc.StreamOutput.NumEntries)) return E_INVALIDARG; // D3D12: a mesh PSO has no vertex, tessellation or geometry stage if (!mesh && (!desc.VS.pShaderBytecode || !desc.VS.BytecodeLength)) return E_INVALIDARG; if (mesh && (!device_.info.mesh_shader || !vk.vkCmdDrawMeshTasksEXT)) { - log_once("mesh-shader PSOs need VK_EXT_mesh_shader, which the device has not enabled; stage", 1); - return E_NOTIMPL; + return stream_unsupported("mesh-shader PSOs need VK_EXT_mesh_shader, which the device has not enabled; stage", 1); } if (desc.NodeMask & ~1u) return E_INVALIDARG; if (static_cast(desc.Flags) & ~kKnownPipelineStateFlags) return E_INVALIDARG; if (!device_.arena.mapped) { - log_once("pipelines need the GPU address arena (bufferDeviceAddress); stage", 1); - return E_NOTIMPL; + return stream_unsupported("pipelines need the GPU address arena (bufferDeviceAddress); stage", 1); } - if (!push_constants_fit()) return E_NOTIMPL; + if (!push_constants_fit()) return stream_unsupported("graphics push-constant limit"); if (!vk.graphics_complete()) { - log_once("graphics pipelines need Vulkan 1.3 dynamic rendering and extended dynamic state; stage", 1); - return E_NOTIMPL; + return stream_unsupported("graphics pipelines need Vulkan 1.3 dynamic rendering and extended dynamic state; stage", 1); } if (desc.NumRenderTargets > D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT) return E_INVALIDARG; for (UINT i = desc.NumRenderTargets; i < D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT; ++i) @@ -3509,16 +6523,22 @@ class PipelineState final if (rt0.LogicOpEnable && unsigned(rt0.LogicOp) > D3D12_LOGIC_OP_OR_INVERTED) return E_INVALIDARG; } if (desc.HS.BytecodeLength || desc.DS.BytecodeLength || desc.StreamOutput.NumEntries) { - log_once("graphics pipeline stage not supported yet (hull/domain/stream output):", 0); - return E_NOTIMPL; + return stream_unsupported("graphics pipeline stage not supported yet (hull/domain/stream output):", 0); } // A geometry shader is the translator's Vulkan geometry stage (docs/design.md, "Geometry shaders"): it takes // triangles and emits a triangle strip. It needs the geometryShader feature, and the PSO's topology type must // be its input primitive, as D3D12 requires. const bool geometry = desc.GS.pShaderBytecode && desc.GS.BytecodeLength; if (geometry && !device_.info.features.geometryShader) { - log_once("geometry shaders need the Vulkan geometryShader feature; stage", 0); - return E_NOTIMPL; + return stream_unsupported("geometry shaders need the Vulkan geometryShader feature; stage", 0); + } + // The console's rectangle topology type (19) draws as triangles through a generated geometry stage that adds + // each rectangle's fourth corner (src/rect_list_geometry.h); it needs the same device feature, and no GS of + // the application's own. + const bool rect_list = !mesh && desc.PrimitiveTopologyType == leonida::topology_type_rect_list; + if (rect_list && (geometry || !device_.info.features.geometryShader)) { + log_once("a rectangle-list pipeline needs the geometryShader feature and no geometry shader; stage", 0); + return geometry ? E_INVALIDARG : E_NOTIMPL; } if (geometry && desc.PrimitiveTopologyType != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) { log_once("a translated geometry shader takes triangles; topology type", desc.PrimitiveTopologyType); @@ -3535,16 +6555,15 @@ class PipelineState final // is quality 0 here. The centre pattern puts every sample at the pixel centre, which needs custom sample // locations: refused with a log until those are set. if (desc.SampleDesc.Quality == DXGI_CENTER_MULTISAMPLE_QUALITY_PATTERN) { - log_once("D3D12_CENTER_MULTISAMPLE_PATTERN needs custom sample locations (not set yet); samples", + return stream_unsupported("D3D12_CENTER_MULTISAMPLE_PATTERN needs custom sample locations (not set yet); samples", int(samples)); - return E_NOTIMPL; } if (desc.SampleDesc.Quality != 0 && desc.SampleDesc.Quality != DXGI_STANDARD_MULTISAMPLE_QUALITY_PATTERN) { log_once("invalid graphics pipeline sample quality:", int(desc.SampleDesc.Quality)); return E_INVALIDARG; } const leonida::ShaderLibrary* library = device_.library(); - if (!library) return E_FAIL; + if (!library) return stub_or(E_FAIL, "graphics"); struct Stage { const char* name; @@ -3583,28 +6602,49 @@ class PipelineState final desc.RasterizerState.DepthBiasClamp}; for (Stage& stage : stages) { if (!stage.code.pShaderBytecode || !stage.code.BytecodeLength) continue; // no PS: depth only - stage.fssm = leonida::fssm_program( - {static_cast(stage.code.pShaderBytecode), stage.code.BytecodeLength}); - if (stage.fssm.empty()) { - log_once("shader bytecode holds no FSSM program; bytes", int(stage.code.BytecodeLength)); - return E_INVALIDARG; - } - const std::string hash = leonida::sha256_hex(stage.fssm); - // Containers with the same program can differ in their input signature or bindings: a VS must have its - // inputs fed by this input layout (else the layout check below reports it). + const std::span raw_bytes{ + static_cast(stage.code.pShaderBytecode), stage.code.BytecodeLength}; + stage.fssm = leonida::fssm_program(raw_bytes); const bool vertex = stage.bit == VK_SHADER_STAGE_VERTEX_BIT; - stage.entry = pick_entry(library->candidates(stage.name, hash), [&](const leonida::ShaderEntry& e) { - return !vertex || layout_feeds(e, desc.InputLayout); - }); - if (!stage.entry) { - std::fprintf(stderr, "[rt] d3d12: no translated %s for FSSM sha256 %s\n", stage.name, hash.c_str()); + if (!stage.fssm.empty()) { + const std::string hash = leonida::sha256_hex(stage.fssm); + // Containers with the same program can differ in their input signature or bindings: a VS must have its + // inputs fed by this input layout (else the layout check below reports it). + stage.entry = pick_entry(library->candidates(stage.name, hash), [&](const leonida::ShaderEntry& e) { + return !vertex || layout_feeds(e, desc.InputLayout); + }); + if (!stage.entry) { + std::fprintf(stderr, "[rt] d3d12: no translated %s for FSSM sha256 %s\n", stage.name, hash.c_str()); + if (d3d12_trace::enabled()) + std::fprintf(stderr, "[rt] d3d12: missing %s in graphics PSO %s (RTs %u, RT0 %d, DSV %d)\n", + stage.name, pipeline_key(desc).c_str(), desc.NumRenderTargets, + int(desc.RTVFormats[0]), int(desc.DSVFormat)); + return stub_or(E_INVALIDARG, "graphics"); + } + } else if (leonida::fspx_bare_program(raw_bytes)) { + // Slot 57 (DeserializeGraphicsPipelineStateX): bare RDNA2 program indexed by fspx_code_sha256 in + // /fspx_gfx/index.json. + const std::string hash = leonida::sha256_hex(raw_bytes); + stage.entry = pick_entry(library->fspx_candidates(stage.name, hash), [&](const leonida::ShaderEntry& e) { + return !vertex || layout_feeds(e, desc.InputLayout); + }); + if (!stage.entry) + stage.entry = pick_entry(library->fspx_candidates(stage.name, hash), + [](const leonida::ShaderEntry&) { return true; }); + if (!stage.entry) { + std::fprintf(stderr, "[rt] d3d12: no translated %s for FSPX code sha256 %s (%zu B)\n", + stage.name, hash.c_str(), raw_bytes.size()); + return stub_or(E_INVALIDARG, "graphics"); + } + } else { + log_once("shader bytecode holds no FSSM or FSPX program; bytes", int(stage.code.BytecodeLength)); return E_INVALIDARG; } if (stage.entry->binding_count) { if (!device_.bindless) { std::fprintf(stderr, "[rt] d3d12: %s uses set-0 bindings; the device has no bindless set 0\n", stage.entry->name.c_str()); - return E_NOTIMPL; + return stream_unsupported("graphics shader requires a bindless descriptor set"); } uses_bindless = true; register_literal_samplers(device_, *stage.entry); @@ -3616,13 +6656,12 @@ class PipelineState final if (const std::string refusal = leonida::mesh_limit_refusal(*stage.entry, device_.mesh_limits()); !refusal.empty()) { std::fprintf(stderr, "[rt] d3d12: %s\n", refusal.c_str()); - return E_NOTIMPL; + return stream_unsupported("mesh shader exceeds a device mesh limit"); } } if (stage.entry->uses_code_base) { if (code_stage) { - log_once("two stages read their code base; one push-constant slot holds one (question 14)", 0); - return E_NOTIMPL; + return stream_unsupported("two stages read their code base; one push-constant slot holds one (question 14)", 0); } code_stage = &stage; } @@ -3634,10 +6673,10 @@ class PipelineState final (stage.bit != VK_SHADER_STAGE_FRAGMENT_BIT || device_.conservative_raster_tier != D3D12_CONSERVATIVE_RASTERIZATION_TIER_3 || (inner.post_depth && !device_.conservative_post_depth_coverage))) { - log_once("FullyCoveredEXT needs an enabled Tier 3 shader ABI and device properties; stage", int(stage.bit)); - return E_NOTIMPL; + return stream_unsupported("FullyCoveredEXT needs an enabled Tier 3 shader ABI and device properties; stage", int(stage.bit)); } } + if (std::getenv("LEONIDA_LOG_EXE_PIPELINES")) log_exe_pipeline(stages[0].entry, stages[2].entry, desc); // --f16-interp-fallback (SHADER-378): align/synthesize VS decoded f16 halves for this (VS, PS) pair before // creating the shader modules so colliding PS and high-param producers link within MoltenVK's 30 locations. // stages[] is {vs, gs, ps} since geometry shaders joined graphics PSOs (#2109): the PS is stages[2], and with a @@ -3656,7 +6695,12 @@ class PipelineState final std::fprintf(stderr, "[rt] d3d12: %s\n", link_error.c_str()); return E_FAIL; } + f16_linked_ = true; } + // A lazy pipeline keeps where each stage's words come from, not the words or a module: build() makes them + // again, the same way, and drops them once the pipeline exists. + lazy_ = lazy_graphics_pipelines(); + depth24_bias_ = depth24_bias; // A stage that declares a storage image or buffer it may write needs a device feature outside compute // (src/spirv_stores.h). Without it the pipeline would be created all the same and break // VUID-RuntimeSpirv-NonWritable-06340 / -06341, so the PSO is refused here with the stage named. @@ -3671,7 +6715,7 @@ class PipelineState final "the device does not have it enabled, so the pipeline is refused\n", stage.entry->name.c_str(), stage.name, pixel ? "fragmentStoresAndAtomics" : "vertexPipelineStoresAndAtomics"); - return E_NOTIMPL; + return stream_unsupported("graphics shader requires an unavailable storesAndAtomics feature"); } for (Stage& stage : stages) { if (!stage.entry) continue; @@ -3687,12 +6731,22 @@ class PipelineState final stage.words = std::move(patched); } } - VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - module_info.codeSize = stage.words.size() * 4; - module_info.pCode = stage.words.data(); + if (trace_pipeline_compile()) { + if (!profile_shaders_.empty()) profile_shaders_ += ','; + profile_shaders_ += stage.entry->name; + stage_bytes_ += stage.words.size() * sizeof(std::uint32_t); + } VkShaderModule module = VK_NULL_HANDLE; - if (vk.vkCreateShaderModule(dev, &module_info, nullptr, &module) != VK_SUCCESS) return E_FAIL; - modules_.push_back(module); + if (lazy_) { + const bool patched = depth24_fragment && stage.bit == VK_SHADER_STAGE_FRAGMENT_BIT; + sources_.push_back({StageSource::library, std::uint8_t(&stage - stages), patched, stage.entry}); + } else { + VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + module_info.codeSize = stage.words.size() * 4; + module_info.pCode = stage.words.data(); + if (vk.vkCreateShaderModule(dev, &module_info, nullptr, &module) != VK_SUCCESS) return E_FAIL; + modules_.push_back(module); + } VkPipelineShaderStageCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; info.stage = stage.bit; info.module = module; @@ -3700,15 +6754,45 @@ class PipelineState final subgroup_size_for(*stage.entry, required_sizes[stage_infos.size()], info); stage_infos.push_back(info); } + if (rect_list) { // the stage that adds each rectangle's fourth corner, from the vertex shader's outputs + std::string why; + const std::vector words = leonida::rect_list_geometry(vs_stage.words, why); + if (words.empty()) { + std::fprintf(stderr, "[rt] d3d12: %s cannot be drawn as a rectangle list: %s\n", + vs_stage.entry->name.c_str(), why.c_str()); + return stream_unsupported("rectangle-list geometry shader generation failed"); + } + if (trace_pipeline_compile()) stage_bytes_ += words.size() * sizeof(std::uint32_t); + VkShaderModule module = VK_NULL_HANDLE; + if (lazy_) { + sources_.push_back({StageSource::rect_list}); + } else { + VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + module_info.codeSize = words.size() * 4; + module_info.pCode = words.data(); + if (vk.vkCreateShaderModule(dev, &module_info, nullptr, &module) != VK_SUCCESS) return E_FAIL; + modules_.push_back(module); + } + VkPipelineShaderStageCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; + info.stage = VK_SHADER_STAGE_GEOMETRY_BIT; + info.module = module; + info.pName = "main"; + stage_infos.push_back(info); + } if (depth24_fragment && !ps_stage.entry) { // no pixel shader: a built-in one writes the depth const std::vector words = leonida::depth24_depth_only_fragment(depth24_bias); - VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - module_info.codeSize = words.size() * 4; - module_info.pCode = words.data(); + if (words.empty()) return E_FAIL; + if (trace_pipeline_compile()) stage_bytes_ += words.size() * sizeof(std::uint32_t); VkShaderModule module = VK_NULL_HANDLE; - if (words.empty() || vk.vkCreateShaderModule(dev, &module_info, nullptr, &module) != VK_SUCCESS) - return E_FAIL; - modules_.push_back(module); + if (lazy_) { + sources_.push_back({StageSource::depth_only}); + } else { + VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + module_info.codeSize = words.size() * 4; + module_info.pCode = words.data(); + if (vk.vkCreateShaderModule(dev, &module_info, nullptr, &module) != VK_SUCCESS) return E_FAIL; + modules_.push_back(module); + } VkPipelineShaderStageCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; info.stage = VK_SHADER_STAGE_FRAGMENT_BIT; info.module = module; @@ -3748,9 +6832,8 @@ class PipelineState final if (instance && element.InstanceDataStepRate == 0) graphics_.zero_step_slots |= 1u << element.InputSlot; if (instance && element.InstanceDataStepRate > 1) { if (!device_.info.vertex_attribute_divisor) { - log_once("instance step rates above 1 need vertexAttributeInstanceRateDivisor; rate", + return stream_unsupported("instance step rates above 1 need vertexAttributeInstanceRateDivisor; rate", int(element.InstanceDataStepRate)); - return E_NOTIMPL; } if (!(divisor_slots & (1u << element.InputSlot))) { divisor_slots |= 1u << element.InputSlot; @@ -3774,7 +6857,8 @@ class PipelineState final } } VkPipelineInputAssemblyStateCreateInfo assembly{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO}; - switch (mesh ? D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE : desc.PrimitiveTopologyType) { // mesh: not used + // Type 19 is the console's rectangles, drawn as triangle lists through the geometry stage added above. + switch (mesh || rect_list ? D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE : desc.PrimitiveTopologyType) { // mesh: not used case D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT: assembly.topology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST; break; case D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE: assembly.topology = VK_PRIMITIVE_TOPOLOGY_LINE_LIST; break; case D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE: assembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; break; @@ -3803,7 +6887,8 @@ class PipelineState final if (r.FillMode != D3D12_FILL_MODE_SOLID || desc.PrimitiveTopologyType != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) return E_INVALIDARG; // Target-independent rasterization is a separate pipeline path; do not silently ignore its count. - if (r.ForcedSampleCount) return E_NOTIMPL; + if (r.ForcedSampleCount) + return stream_unsupported("target-independent rasterization; forced sample count", int(r.ForcedSampleCount)); } VkPipelineRasterizationStateCreateInfo raster{VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO}; raster.polygonMode = r.FillMode == D3D12_FILL_MODE_WIREFRAME ? VK_POLYGON_MODE_LINE : VK_POLYGON_MODE_FILL; @@ -3883,18 +6968,15 @@ class PipelineState final // State that needs a Vulkan feature the device did not enable (VulkanDeviceInfo::features) is refused, rather // than handed to the driver against the spec. const VkPhysicalDeviceFeatures& features = device_.info.features; - const auto refuse = [&](const char* what, int value) { - log_once(what, value); - return E_NOTIMPL; - }; + if (raster.polygonMode != VK_POLYGON_MODE_FILL && !features.fillModeNonSolid) - return refuse("wireframe fill needs fillModeNonSolid, which the device lacks; fill mode", r.FillMode); + return stream_unsupported("wireframe fill needs fillModeNonSolid, which the device lacks; fill mode", r.FillMode); if (raster.depthBiasEnable && raster.depthBiasClamp != 0.0f && !features.depthBiasClamp) - return refuse("a depth-bias clamp needs depthBiasClamp, which the device lacks; clamp x1000", + return stream_unsupported("a depth-bias clamp needs depthBiasClamp, which the device lacks; clamp x1000", int(raster.depthBiasClamp * 1000)); for (std::size_t i = 1; i < blends.size(); ++i) if (std::memcmp(&blends[i], &blends[0], sizeof(blends[0])) != 0 && !features.independentBlend) - return refuse("per-render-target blend state needs independentBlend, which the device lacks; target", + return stream_unsupported("per-render-target blend state needs independentBlend, which the device lacks; target", int(i)); const auto src1 = [](VkBlendFactor f) { return f == VK_BLEND_FACTOR_SRC1_COLOR || f == VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR || @@ -3904,12 +6986,12 @@ class PipelineState final if (b.blendEnable && !features.dualSrcBlend && (src1(b.srcColorBlendFactor) || src1(b.dstColorBlendFactor) || src1(b.srcAlphaBlendFactor) || src1(b.dstAlphaBlendFactor))) - return refuse("SRC1 blend factors need dualSrcBlend, which the device lacks; factor", + return stream_unsupported("SRC1 blend factors need dualSrcBlend, which the device lacks; factor", int(b.srcColorBlendFactor)); if (blend.logicOpEnable && !features.logicOp) - return refuse("logic ops need logicOp, which the device lacks; op", int(first.LogicOp)); + return stream_unsupported("logic ops need logicOp, which the device lacks; op", int(first.LogicOp)); if (raster.depthClampEnable && !features.depthClamp) - return refuse("DepthClipEnable = FALSE needs depthClamp, which the device lacks; flag", 0); + return stream_unsupported("DepthClipEnable = FALSE needs depthClamp, which the device lacks; flag", 0); graphics_.viewport_with_count = features.multiViewport && vk.vkCmdSetViewportWithCount && vk.vkCmdSetScissorWithCount; @@ -3917,7 +6999,12 @@ class PipelineState final graphics_.color_formats.assign(desc.NumRenderTargets, VK_FORMAT_UNDEFINED); for (UINT i = 0; i < desc.NumRenderTargets; ++i) { if (desc.RTVFormats[i] == DXGI_FORMAT_UNKNOWN) continue; - graphics_.color_formats[i] = vulkan_format(desc.RTVFormats[i], false).format; + graphics_.color_formats[i] = desc.RTVFormats[i] == DXGI_FORMAT_A8_UNORM && device_.info.a8_render_target + ? kA8UnormFormat + : desc.RTVFormats[i] == DXGI_FORMAT_R9G9B9E5_SHAREDEXP && + device_.r9g9b9e5_target_stand_in + ? VK_FORMAT_B10G11R11_UFLOAT_PACK32 // what such a target is made of + : vulkan_format(desc.RTVFormats[i], false).format; // B4G4R4A4 targets are RGBA8 images where no 4444 format renders (DeviceState's texture format choice). if (graphics_.color_formats[i] == VK_FORMAT_A4R4G4B4_UNORM_PACK16 && !device_.color_attachment_usable(VK_FORMAT_A4R4G4B4_UNORM_PACK16)) @@ -4018,9 +7105,16 @@ class PipelineState final recipe_.depth = depth; recipe_.blends = std::move(blends); recipe_.blend = blend; - graphics_.pipeline = build(0); - if (!graphics_.pipeline) return E_FAIL; - graphics_.variant = [this](std::uint32_t unbound) { return variant(unbound); }; + if (!lazy_) { + graphics_.pipeline = build(0, "graphics-create"); + if (!graphics_.pipeline) return E_FAIL; + } // lazy: graphics_.pipeline stays null and the first draw builds it as variant 0 + graphics_.async_build = async_replay_compile(); + graphics_.variant = [this](std::uint32_t unbound) { + return replay_pipeline("draw", [&] { + return graphics_.async_build ? queue_build(false, unbound) : variant(unbound, "draw"); + }); + }; if (code_stage) { VkDeviceSize offset = 0; @@ -4030,7 +7124,35 @@ class PipelineState final code_base_ = offset; graphics_.code_base = offset; } - device_.context->add_graphics_pipeline(id(), graphics_); + { // LOCAL DIAGNOSTIC: what this pipeline is, for the fsdraw probe's draw lines + const auto& rt0 = desc.BlendState.RenderTarget[0]; + char text[640]; + std::snprintf(text, sizeof text, + "vs %s (fssm %.16s) ps %s (fssm %.16s) rootsig %p rts %u fmt0 %d fmt1 %d dsv %d depth %d " + "blend0 en %d src %d dst %d op %d srcA %d dstA %d opA %d logic %d wm 0x%x alpha2cov %d " + "independent %d sample_mask 0x%x cull %d fill %d topo %d samples %u", + stages[0].entry ? stages[0].entry->name.c_str() : "-", + stages[0].entry ? stages[0].entry->fssm_sha256.c_str() : "-", + stages[2].entry ? stages[2].entry->name.c_str() : "-", + stages[2].entry ? stages[2].entry->fssm_sha256.c_str() : "-", + static_cast(desc.pRootSignature), desc.NumRenderTargets, int(desc.RTVFormats[0]), + int(desc.RTVFormats[1]), int(desc.DSVFormat), int(desc.DepthStencilState.DepthEnable), + int(rt0.BlendEnable), int(rt0.SrcBlend), int(rt0.DestBlend), int(rt0.BlendOp), + int(rt0.SrcBlendAlpha), int(rt0.DestBlendAlpha), int(rt0.BlendOpAlpha), int(rt0.LogicOpEnable), + unsigned(rt0.RenderTargetWriteMask), int(desc.BlendState.AlphaToCoverageEnable), + int(desc.BlendState.IndependentBlendEnable), unsigned(desc.SampleMask), + int(desc.RasterizerState.CullMode), int(desc.RasterizerState.FillMode), + int(desc.PrimitiveTopologyType), desc.SampleDesc.Count); + leonida::fsdraw::note_pipeline(id(), text); + } + if (device_.info.device_checkpoints) { + leonida::CheckpointShaders shaders{}; + for (std::size_t i = 0; i < std::size(stages); ++i) + if (stages[i].entry) shaders[i] = stages[i].entry->name.c_str(); + device_.context->add_graphics_pipeline(id(), graphics_, &shaders); + } else { + device_.context->add_graphics_pipeline(id(), graphics_); + } registered_ = true; is_graphics_ = true; return S_OK; @@ -4043,10 +7165,9 @@ class PipelineState final if (desc.NodeMask & ~1u) return E_INVALIDARG; if (static_cast(desc.Flags) & ~kKnownPipelineStateFlags) return E_INVALIDARG; if (!device_.arena.mapped) { - log_once("pipelines need the GPU address arena (bufferDeviceAddress); stage", 0); - return E_NOTIMPL; + return stream_unsupported("pipelines need the GPU address arena (bufferDeviceAddress); stage", 0); } - if (!push_constants_fit()) return E_NOTIMPL; + if (!push_constants_fit()) return stream_unsupported("compute push-constant limit"); // The game's FSSM program, or the FidelityFX DLL's FSPX kind-6 program: in a DXBC container's ACCC part at // slot 62, bare from a slot-67 description (docs/fspx.md, "Run-time lookup"). const leonida::ComputeProgram program = leonida::compute_program( @@ -4056,7 +7177,7 @@ class PipelineState final return E_INVALIDARG; } const leonida::ShaderLibrary* library = device_.library(); - if (!library) return E_FAIL; + if (!library) return stub_or(E_FAIL, "compute"); // A binding-free entry wins over one with bindings for the same program (pick_entry). // An FSPX program from a container is matched on its kind-0 state too; a bare kind-6 program whose // translations differ is ambiguous without that state and is refused (program_candidates). @@ -4065,21 +7186,23 @@ class PipelineState final [](const leonida::ShaderEntry&) { return true; }); if (!entry) { const bool fspx = program.kind == leonida::ComputeProgram::Kind::fspx; - if (ambiguous) + if (ambiguous) { + // Ambiguous is not missing: translations exist, so it is refused even with LEONIDA_STUB_PIPELINES. std::fprintf(stderr, "[rt] d3d12: FSPX kind-6 program sha256 %s is ambiguous without its kind-0 " "state: its translations differ\n", leonida::sha256_hex(program.bytes).c_str()); - else - std::fprintf(stderr, "[rt] d3d12: no translated compute shader for %s sha256 %s\n", - fspx ? (program.state.empty() ? "FSPX kind-6" : "FSPX kind-6 and kind-0") : "FSSM", - leonida::sha256_hex(program.bytes).c_str()); - return E_INVALIDARG; + return E_INVALIDARG; + } + std::fprintf(stderr, "[rt] d3d12: no translated compute shader for %s sha256 %s\n", + fspx ? (program.state.empty() ? "FSPX kind-6" : "FSPX kind-6 and kind-0") : "FSSM", + leonida::sha256_hex(program.bytes).c_str()); + return stub_or(E_INVALIDARG, "compute"); } // Set 0 (bindless images, samplers, the descriptor hash table): the device keeps it, and a pipeline whose // shader declares bindings has it in its layout and has it bound at every dispatch. if (entry->binding_count && !device_.bindless) { std::fprintf(stderr, "[rt] d3d12: %s uses set-0 bindings; the device has no bindless set 0\n", entry->name.c_str()); - return E_NOTIMPL; + return stream_unsupported("compute shader requires a bindless descriptor set"); } if (entry->binding_count) register_literal_samplers(device_, *entry); // SHADER-309: a module over the device's maxComputeSharedMemorySize is invalid usage that spirv-val accepts @@ -4097,20 +7220,15 @@ class PipelineState final "maxComputeSharedMemorySize %u\n", entry->name.c_str(), unsigned(entry->lds_bytes), unsigned(props.limits.maxComputeSharedMemorySize)); - return E_NOTIMPL; + return stream_unsupported("compute shader exceeds shared memory limit"); } } } - const std::vector words = library->spirv(*entry); - if (words.empty()) { - std::fprintf(stderr, "[rt] d3d12: %s.spv is missing or not SPIR-V\n", entry->name.c_str()); + const std::size_t spirv_bytes = library->spirv_bytes(*entry); + if (!spirv_bytes) { + std::fprintf(stderr, "[rt] d3d12: %s.spv is missing\n", entry->name.c_str()); return E_FAIL; } - - VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - module_info.codeSize = words.size() * 4; - module_info.pCode = words.data(); - if (vk.vkCreateShaderModule(dev, &module_info, nullptr, &module_) != VK_SUCCESS) return E_FAIL; const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(leonida::ShaderUserData)}; VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; layout_info.pushConstantRangeCount = 1; @@ -4123,33 +7241,211 @@ class PipelineState final pipeline_.bindless_set = device_.bindless->set(); } if (vk.vkCreatePipelineLayout(dev, &layout_info, nullptr, &pipeline_.layout) != VK_SUCCESS) return E_FAIL; + compute_entry_ = entry; + stage_bytes_ = spirv_bytes; + // The title creates hundreds of compute pipelines from job threads during startup and one of its init tasks + // waits for all of them; some modules (wave64-emulated ray-tracing resolves, 4 MiB of SPIR-V) take the driver + // minutes each. So the Vulkan pipeline is built on first use (build_compute): at the first dispatch that names + // it, or earlier by the warm-up thread. CreateComputePipelineState answers at once, as it does on the console + // where these are precompiled. LEONIDA_LAZY_COMPUTE=0: built here, as before. + static const bool lazy_compute = [] { + wchar_t v[2]{}; + return !(GetEnvironmentVariableW(L"LEONIDA_LAZY_COMPUTE", v, 2) == 1 && v[0] == L'0'); + }(); + if (skip_compute(entry->name)) { + // Never built. Replay drops each dispatch (ComputePipeline::skipped); the first one is logged, so a + // boot's log lists the skipped programs the title actually ran. + pipeline_.skipped = true; + pipeline_.build = [](void* self) -> VkPipeline { + auto* pso = static_cast(self); + if (!pso->skip_logged_.exchange(true)) + std::fprintf(stderr, "[rt] d3d12: compute program %s is skipped (LEONIDA_SKIP_COMPUTE): its " + "dispatches are dropped\n", pso->compute_entry_->name.c_str()); + return VK_NULL_HANDLE; + }; + pipeline_.build_context = this; + } else if (lazy_compute) { + pipeline_.async_build = async_replay_compile(); + pipeline_.build = [](void* self) { + auto* pso = static_cast(self); + return replay_pipeline("dispatch", [&] { + return pso->pipeline_.async_build ? pso->queue_build(true, 0) : pso->build_compute("dispatch"); + }); + }; + pipeline_.build_context = this; + } else if (!build_compute("compute-create")) { + return E_FAIL; + } + + // The code base: shaders read constant tables embedded in their own program through s_getpc_b64. The + // translator's code offsets are into the bytes the key hashes (the FSSM blob, or the kind-6 program). + if (entry->uses_code_base || !entry->code_base_known) { + const auto& code = program.bytes; + if (!device_.arena_allocate(code.size(), 256, code_base_, DeviceState::arena_shader)) return E_OUTOFMEMORY; + std::memcpy(device_.arena.mapped + code_base_, code.data(), code.size()); + code_bytes_ = code.size(); + pipeline_.code_base = code_base_; + } + device_.context->add_pipeline(id(), pipeline_, + device_.info.device_fault_diagnostics ? entry->name.c_str() : nullptr); + registered_ = true; + if (pipeline_.build && !pipeline_.skipped) warmup_enqueue(this, spirv_bytes); + return S_OK; + } + +private: + // The compute pipeline, built once: by create_compute (LEONIDA_LAZY_COMPUTE=0), by the first dispatch that names + // it (the replay layer calls ComputePipeline::build) or by the warm-up thread. Null when it cannot be built; the + // failure is logged and not retried. + VkPipeline build_compute(const char* trigger) { + CompileActivity activity(device_.active_compiles); + std::lock_guard lock(variants_mutex_); + if (pipeline_.pipeline || compute_failed_) return pipeline_.pipeline; + compute_failed_ = true; // until the pipeline exists + auto& vk = device_.context->vk; + const VkDevice dev = device_.info.device; + const leonida::ShaderLibrary* library = device_.library(); + const leonida::ShaderEntry* entry = compute_entry_; + if (!library || !entry) return VK_NULL_HANDLE; + // The driver's compiler needs hundreds of MiB per very large module; several at once exhausted host memory. + // Modules over 128 KiB compile one at a time (LEONIDA_SERIAL_BIG_COMPILES=0: as many as are asked for). + static const bool serial_big = [] { + wchar_t v[2]{}; + return !(GetEnvironmentVariableW(L"LEONIDA_SERIAL_BIG_COMPILES", v, 2) == 1 && v[0] == L'0'); + }(); + static std::mutex big_compile; + std::unique_lock big_lock(big_compile, std::defer_lock); + if (serial_big && stage_bytes_ > 128 * 1024) big_lock.lock(); + auto words = library->spirv(*entry); + if (words.empty()) { + std::fprintf(stderr, "[rt] d3d12: %s.spv is missing or not SPIR-V\n", entry->name.c_str()); + return VK_NULL_HANDLE; + } + VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + module_info.codeSize = words.size() * 4; + module_info.pCode = words.data(); + VkShaderModule module = VK_NULL_HANDLE; + if (vk.vkCreateShaderModule(dev, &module_info, nullptr, &module) != VK_SUCCESS) return VK_NULL_HANDLE; + const auto bytes = module_info.codeSize; + std::vector().swap(words); // vkCreateShaderModule consumed pCode VkComputePipelineCreateInfo pipeline_info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; pipeline_info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; pipeline_info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; - pipeline_info.stage.module = module_; + pipeline_info.stage.module = module; pipeline_info.stage.pName = "main"; VkPipelineShaderStageRequiredSubgroupSizeCreateInfo required_size{}; subgroup_size_for(*entry, required_size, pipeline_info.stage); pipeline_info.layout = pipeline_.layout; - if (vk.vkCreateComputePipelines(dev, device_.pipeline_cache(), 1, &pipeline_info, nullptr, &pipeline_.pipeline) != - VK_SUCCESS) - return E_FAIL; + const VkPipelineCache cache = device_.pipeline_cache(); + + const ULONGLONG started = GetTickCount64(); + VkPipeline built = VK_NULL_HANDLE; + CompileTrace trace; + trace.begin(pipeline_info, device_.info.pipeline_creation_feedback, trigger, entry->name.c_str(), 0, bytes, cache_key_); + const leonida::pipeline_profile::DriverCall profile("cs", trigger, entry->name.c_str()); + const VkResult created = vk.vkCreateComputePipelines(dev, cache, 1, &pipeline_info, nullptr, &built); + profile.finish(int(created)); + trace.end(trigger, entry->name.c_str(), 0, bytes, created); + if (big_lock.owns_lock()) big_lock.unlock(); + vk.vkDestroyShaderModule(dev, module, nullptr); // Vulkan lets a module go once the pipeline exists + const ULONGLONG took = GetTickCount64() - started; + if (created != VK_SUCCESS || !built) { + std::fprintf(stderr, "[rt] d3d12: compute pipeline %s could not be built (VkResult %d); its dispatches are " + "dropped\n", entry->name.c_str(), int(created)); + return VK_NULL_HANDLE; + } + if (took >= 2000) + std::fprintf(stderr, "[rt] d3d12: compute pipeline %s took %.1f s to build (%zu B SPIR-V)\n", + entry->name.c_str(), double(took) / 1000.0, bytes); + maybe_checkpoint(cache); + pipeline_.pipeline = built; + compute_failed_ = false; + return built; + } + + // Lazy compute pipelines are also built in the background, smallest module first, so most exist before their + // first dispatch. One low-priority thread; modules over LEONIDA_COMPUTE_WARMUP_MAX_BYTES of SPIR-V (default + // 1 MiB) are left to their first dispatch, since some take the driver minutes each. LEONIDA_COMPUTE_WARMUP=0 + // turns the thread off. A queued PSO is kept alive by a reference until it is built. + void maybe_checkpoint(VkPipelineCache cache) { + if (!cache || !startup_cache_checkpoints_enabled()) return; + auto now = GetTickCount64(); + auto next = device_.next_checkpoint.load(); + if (now < next || !device_.next_checkpoint.compare_exchange_strong(next, ULLONG_MAX)) return; + AddRef(); + try { + PipelineCompiler::instance().submit(SIZE_MAX, [this, cache] { + try { + if (!device_.active_compiles.load() && !PipelineCompiler::instance().has_compile_waiter()) + save_session_pipeline_cache(device_.context->vk, device_.info.device, cache, true); + } catch (const std::exception& e) { + std::fprintf(stderr, "[rt] pipeline cache checkpoint failed: %s\n", e.what()); + } + device_.next_checkpoint.store(GetTickCount64() + 120000); + Release(); + }); + } catch (...) { + device_.next_checkpoint.store(now + 120000); + Release(); + } + } + + VkPipeline queue_build(bool compute, std::uint32_t unbound, std::size_t warm_bytes = 0) { + static std::mutex publication; // ready handles only; no compiler call holds this lock + const bool warm = warm_bytes != 0; + std::lock_guard lock(publication); + if (!warm) { + if (!requested_) requested_ = std::make_unique(); + auto [it, inserted] = requested_->try_emplace(unbound); + if (!it->second.handle) ++it->second.skips; + if (!inserted) return it->second.handle; + } + AddRef(); + try { + PipelineCompiler::instance().submit(warm_bytes, [this, compute, warm, unbound] { + VkPipeline built{}; + try { + built = compute ? build_compute(warm ? "warmup" : "dispatch-worker") + : variant(unbound, "draw-worker"); + if (async_replay_compile()) { + unsigned long long skipped = 0; + { + std::lock_guard publish(publication); + if (!requested_) requested_ = std::make_unique(); + auto& entry = (*requested_)[unbound]; + if (!entry.handle) skipped = entry.skips; + entry.handle = built; + } + if (skipped && trace_pipeline_compile()) + std::fprintf(stderr, "[rt] pipeline-deferred type=%s skipped=%llu ready=%d\n", + compute ? "compute" : "graphics", skipped, int(built != VK_NULL_HANDLE)); + } + } catch (const std::exception& e) { + std::fprintf(stderr, "[rt] pipeline compile worker failed: %s\n", e.what()); + } + Release(); + }); + } catch (...) { + if (!warm) requested_->erase(unbound); + Release(); + } + return VK_NULL_HANDLE; + } - // The code base: shaders read constant tables embedded in their own program through s_getpc_b64. The - // translator's code offsets are into the bytes the key hashes (the FSSM blob, or the kind-6 program). - const std::vector& code = program.bytes; - VkDeviceSize offset = 0; - if (!device_.arena_allocate(code.size(), 256, offset, DeviceState::arena_shader)) return E_OUTOFMEMORY; - std::memcpy(device_.arena.mapped + offset, code.data(), code.size()); - code_bytes_ = code.size(); - code_base_ = offset; - pipeline_.code_base = offset; - device_.context->add_pipeline(id(), pipeline_); - registered_ = true; - return S_OK; + static void warmup_enqueue(PipelineState* pso, std::size_t bytes) { + static const std::size_t max_bytes = [] { + char text[32]{}; + const DWORD n = GetEnvironmentVariableA("LEONIDA_COMPUTE_WARMUP_MAX_BYTES", text, sizeof(text)); + const unsigned long long v = (n > 0 && n < sizeof(text)) ? std::strtoull(text, nullptr, 10) : 0; + return v ? static_cast(v) : std::size_t{1} << 20; + }(); + static const bool on = [] { + wchar_t v[2]{}; + return !(GetEnvironmentVariableW(L"LEONIDA_COMPUTE_WARMUP", v, 2) == 1 && v[0] == L'0'); + }(); + if (on && bytes && bytes <= max_bytes) pso->queue_build(true, 0, bytes); } -private: // What a graphics pipeline is made from, so variants can be built at draw time. struct Recipe { bool mesh = false; // no vertex input or input assembly state, and no dynamic topology or strides @@ -4170,7 +7466,8 @@ class PipelineState final }; // The graphics pipeline with the formats of the `unbound` slots (leonida::GraphicsPipeline::variant) undefined. - VkPipeline build(std::uint32_t unbound) const { + VkPipeline build(std::uint32_t unbound, const char* trigger) { + CompileActivity activity(device_.active_compiles); const Recipe& r = recipe_; std::vector colors = graphics_.color_formats; for (std::size_t slot = 0; slot < colors.size(); ++slot) @@ -4235,9 +7532,42 @@ class PipelineState final dynamic.dynamicStateCount = dyn_count; dynamic.pDynamicStates = dyn_list; + // A lazy pipeline's stages get their modules here, for this one call (Vulkan lets a module go once the + // pipeline exists), so the driver holds no SPIR-V for pipelines that are not drawn. + auto bytes = stage_bytes_; + std::vector stages; + std::vector made; + const auto drop_modules = [&] { + for (VkShaderModule module : made) device_.context->vk.vkDestroyShaderModule(device_.info.device, module, nullptr); + }; + if (lazy_) { + std::vector> words; + std::string why; + if (!stage_words(words, why) || words.size() != r.stages.size()) { + std::fprintf(stderr, "[rt] d3d12: a pipeline built at its first draw lost its SPIR-V: %s\n", + why.empty() ? "stage count" : why.c_str()); + return VK_NULL_HANDLE; + } + bytes = 0; + stages = r.stages; + for (std::size_t i = 0; i < stages.size(); ++i) { + VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + module_info.codeSize = words[i].size() * 4; + bytes += module_info.codeSize; + module_info.pCode = words[i].data(); + VkShaderModule module = VK_NULL_HANDLE; + if (device_.context->vk.vkCreateShaderModule(device_.info.device, &module_info, nullptr, &module) != + VK_SUCCESS) { + drop_modules(); + return VK_NULL_HANDLE; + } + made.push_back(module); + stages[i].module = module; + } + } VkGraphicsPipelineCreateInfo info{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, &rendering}; info.stageCount = std::uint32_t(r.stages.size()); - info.pStages = r.stages.data(); + info.pStages = lazy_ ? stages.data() : r.stages.data(); info.pVertexInputState = r.mesh ? nullptr : &vertex_input; // ignored with a mesh stage; null for clarity info.pInputAssemblyState = r.mesh ? nullptr : &r.assembly; info.pViewportState = &viewport; @@ -4248,18 +7578,85 @@ class PipelineState final info.pDynamicState = &dynamic; info.layout = graphics_.layout; VkPipeline pipeline = VK_NULL_HANDLE; - if (device_.context->vk.vkCreateGraphicsPipelines(device_.info.device, device_.pipeline_cache(), 1, - &info, nullptr, &pipeline) != VK_SUCCESS) - return VK_NULL_HANDLE; + const auto cache = device_.pipeline_cache(); + const char* program = "-", *fragment = "-"; + if (leonida::pipeline_profile::enabled()) { + for (const auto& source : sources_) { + if (!source.entry) continue; + if (source.slot == 0) program = source.entry->name.c_str(); + if (source.slot == 2) fragment = source.entry->name.c_str(); + } + } + CompileTrace trace; + trace.begin(info, device_.info.pipeline_creation_feedback, trigger, profile_shaders_.c_str(), unbound, bytes, cache_key_); + const leonida::pipeline_profile::DriverCall profile(r.mesh ? "ms" : "vs", lazy_ ? "lazy" : "eager", + program, fragment, unbound); + const auto result = device_.context->vk.vkCreateGraphicsPipelines(device_.info.device, cache, 1, &info, nullptr, &pipeline); + profile.finish(int(result)); + trace.end(trigger, profile_shaders_.c_str(), unbound, bytes, result); + if (result != VK_SUCCESS) + pipeline = VK_NULL_HANDLE; + drop_modules(); + if (pipeline) maybe_checkpoint(cache); return pipeline; } + // A lazy pipeline's SPIR-V, one module's words per recipe stage, made as create_graphics made them: the library + // stages (VS or MS, GS, PS) read again, the f16 halves linked, the D24 fragment patch, then the generated stages + // (the rectangle-list geometry stage from the vertex stage, the depth-only fragment stage). False with `why` when + // a file went missing since. + bool stage_words(std::vector>& words, std::string& why) const { + const leonida::ShaderLibrary* library = device_.library(); + if (!library) { + why = "no shader library"; + return false; + } + words.assign(sources_.size(), {}); + std::size_t vs = SIZE_MAX, ps = SIZE_MAX; + for (std::size_t i = 0; i < sources_.size(); ++i) { + const StageSource& source = sources_[i]; + if (source.kind != StageSource::library) continue; + words[i] = library->spirv(*source.entry); + if (words[i].empty()) { + why = source.entry->name + ".spv is missing or not SPIR-V"; + return false; + } + if (source.slot == 0) vs = i; + if (source.slot == 2) ps = i; + } + if (f16_linked_) { + if (vs == SIZE_MAX || ps == SIZE_MAX || + !leonida::link_f16_halves(words[vs], *sources_[vs].entry, words[ps], *sources_[ps].entry, &why)) + return false; + } + for (std::size_t i = 0; i < sources_.size(); ++i) { + if (!sources_[i].depth24) continue; + std::vector patched = leonida::depth24_patch_fragment(words[i], depth24_bias_, why); + if (patched.empty()) return false; + words[i] = std::move(patched); + } + for (std::size_t i = 0; i < sources_.size(); ++i) { + if (sources_[i].kind == StageSource::rect_list) { + if (vs == SIZE_MAX) return false; + words[i] = leonida::rect_list_geometry(words[vs], why); + } else if (sources_[i].kind == StageSource::depth_only) { + words[i] = leonida::depth24_depth_only_fragment(depth24_bias_); + } else { + continue; + } + if (words[i].empty()) return false; + } + return true; + } + // Built on first use and kept until the PSO is released (replay may call this from any queue). - VkPipeline variant(std::uint32_t unbound) { + VkPipeline variant(std::uint32_t unbound, const char* trigger) { std::lock_guard lock(variants_mutex_); if (const auto it = variants_.find(unbound); it != variants_.end()) return it->second; - const VkPipeline pipeline = build(unbound); + const VkPipeline pipeline = build(unbound, trigger); if (!pipeline) { + if (leonida::pipeline_profile::enabled()) + std::fprintf(stderr, "[rt] pso-variant failed stage=%s mask=%u\n", recipe_.mesh ? "ms" : "vs", unbound); log_once("a pipeline variant for unbound attachment slots could not be built; slots", int(unbound)); return VK_NULL_HANDLE; } @@ -4267,10 +7664,30 @@ class PipelineState final return pipeline; } + // Where a lazy graphics pipeline's stage modules come from, in recipe_.stages order (stage_words). + struct StageSource { + enum Kind : std::uint8_t { library, rect_list, depth_only } kind = library; + std::uint8_t slot = 0; // library: the create_graphics stage table entry (0 VS or MS, 1 GS, 2 PS) + bool depth24 = false; // library: the D24 fragment patch applies + const leonida::ShaderEntry* entry = nullptr; // library: the translated shader + }; + DeviceState& device_; leonida::ComputePipeline pipeline_; leonida::GraphicsPipeline graphics_; Recipe recipe_; + const leonida::ShaderEntry* compute_entry_ = nullptr; // compute: the translated shader build_compute reads + bool compute_failed_ = false; // compute: could not be built; not retried + std::atomic skip_logged_{false}; // compute: the skipped program's first dispatch was logged + bool lazy_ = false; // graphics: built at the first draw (lazy_graphics_pipelines) + bool f16_linked_ = false; // graphics: the VS and PS words had their f16 halves linked + leonida::Depth24Bias depth24_bias_{}; + std::vector sources_; + struct Request { VkPipeline handle{}; unsigned long long skips = 0; }; + using Requests = std::map; + std::unique_ptr requested_; + std::string profile_shaders_; // populated only with compile tracing enabled + std::size_t stage_bytes_ = 0; std::mutex variants_mutex_; std::map variants_; VkShaderModule module_ = VK_NULL_HANDLE; @@ -4730,9 +8147,205 @@ class ShaderCacheSession final std::shared_ptr store_; }; -// The T# of a view: what the shader gets to know about it, in the structure the console's shaders read. -// False (with a log) for a view set 0 cannot show yet. -bool image_descriptor(const Resource& resource, const TextureView& view, leonida::gfx10::Image& out) { +// A texture the title keeps in its own memory (gfxres notes, section 5): asset and UI textures it reads from its +// archives straight into that memory in the console's tiled layout and names only through device slot 70 views +// (resource words with the explicit XG Layout, view words, the address), and slot-133 textures it fills itself, +// through XG copies into the memory or the pointer Map gives it. The PC GPU cannot sample the console layout, so each +// has an image filled from the memory by detiling it with the layout of the slot-70 resource words (XG, +// xg_xs_layout.h), and filled again when the bytes change (Device::refresh_title_textures). Textures the GPU writes +// (render targets, depth, unordered access) are never filled from memory. The approach is five-star-recomp's +// (docs/gpu-resources.md "Textures", GpuTextures.cs / GpuTextureUploader.cs, GPL-3.0-or-later): a registry by +// address, refreshed at every slot-70 view and once a frame for textures the title maps. +struct TitleTexture { + std::uint64_t address = 0; // the GPU address the title names it by + std::uint64_t cpu = 0; // where the CPU reads its bytes (title_gpu_views::to_cpu) + std::array desc{}; // the console resource words the layout was built from + rt::xg_xs::Texture layout{}; // valid when layout_known + bool layout_known = false; + bool layout_guessed = false; // a slot-133 texture's own description (Layout 0), no slot-70 view yet + bool layout_from_xg = false; // the title's XG computer of its shape (title_xg_layout) + Resource* resource = nullptr; + // Snapshot at registration. A diagnostic census then need not fault in each Resource to count its image memory. + VkDeviceSize backing_bytes = 0, unbound_bytes = 0; + bool device_local = false; + void set_resource(Resource* r) { + resource = r; + backing_bytes = r->image_backing_bytes(); + unbound_bytes = r->unbound_bytes(); + device_local = (r->memory_flags() & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) != 0; + } + bool owned = false; // made here for slot-70 views (a reference is held); else slot 133's + bool attachment_4k = false; // slot 133: 3840x2160 color or depth attachment + bool gpu_written = false; // render target, depth or unordered access: never filled + bool mapped = false; // a slot-133 texture the title mapped: checked before submissions + bool stale = false; // changed bytes not uploaded yet (budget, or no host copy then) + leonida::TextureReadability memory; // protected by title_texture_mutex + std::vector formats; // owned: the image's format and castable view formats + std::uint64_t hash = 0; // hash_guarded (sampled) of the bytes the image was last filled from + bool hashed = false; + // A mapped texture up to 4 MiB is also hashed in full, every few passes: the title writes into it in small + // pieces (a glyph in a font cache, measured: Map once, many writes, no Unmap between them) that the sampling hash + // misses. Video planes, rewritten whole every frame, are caught by the sampled one first. + std::uint64_t full_hash = 0; + bool full_hashed = false; + bool every_byte() const { return mapped && layout.layout.size <= (4u << 20); } + std::uint64_t fills = 0; +}; + +// The layout of a slot-133 texture as the title's own XG computer for its shape says (title_xg_layouts): how the title +// lays out what it writes through Map. False when the title made none, or its layout does not fit the image. +bool title_xg_layout(const Resource& r, rt::xg_xs::Texture& out, std::array& words) { + const D3D12_RESOURCE_DESC& d = r.desc(); + std::uint32_t layout = 0; + if (!leonida::title_xg_layouts::find({std::uint32_t(d.Dimension), std::uint32_t(d.Format), d.Height, + d.DepthOrArraySize, d.MipLevels, d.Width}, + layout)) + return false; + rt::xg_xs::ResourceDesc x{}; + x.dimension = std::uint32_t(d.Dimension); + x.width = d.Width; + x.height = d.Height; + x.depth_or_array = d.DepthOrArraySize; + x.mips = d.MipLevels; + x.format = std::uint32_t(d.Format); + x.samples = 1; + x.layout = layout; + rt::xg_xs::Texture t; + if (!rt::xg_xs::build_texture(x, t) || t.layout.mips != d.MipLevels) return false; + const leonida::BlockFormat element = r.copy_element(); + if (element.bytes != t.format.bytes || element.block != t.format.side) return false; + out = t; + std::memcpy(words.data(), &x, sizeof(x)); + return true; +} + +void DeviceState::title_texture_mapped(const void* resource, std::uint64_t address) { + std::lock_guard lock(title_texture_mutex); + const auto it = title_textures.find(address); + if (it == title_textures.end() || it->second->resource != resource) return; + TitleTexture& t = *it->second; + t.mapped = true; + t.memory.retry(); + // The title computes the layout of what it writes right before it maps: take it when no view gave one. + if (!t.gpu_written && (t.layout_guessed || !t.layout_known) && + title_xg_layout(*static_cast(resource), t.layout, t.desc)) { + t.layout_known = true; + t.layout_guessed = false; + t.layout_from_xg = true; + t.hashed = false; + } + static std::atomic logged{0}; + if (logged.fetch_add(1, std::memory_order_relaxed) < 48) { + const auto& r = *static_cast(resource); + const D3D12_RESOURCE_DESC& d = r.desc(); + std::fprintf(stderr, + "[rt] d3d12: the title maps slot-133 texture 0x%llx (CPU 0x%llx): dimension %d %llux%ux%u mips %u " + "format %d flags 0x%x; layout %s, %s\n", + static_cast(address), static_cast(t.cpu), int(d.Dimension), + static_cast(d.Width), d.Height, unsigned(d.DepthOrArraySize), + unsigned(d.MipLevels), int(d.Format), unsigned(d.Flags), + t.gpu_written ? "none (GPU-written)" + : !t.layout_known ? "unknown" + : t.layout_guessed ? "guessed (no slot-70 view, no XG computer of its shape)" + : t.layout_from_xg ? (t.layout.mode == rt::xg_xs::kLinear ? "the title's XG computer's (linear)" + : "the title's XG computer's (swizzled)") + : "from a slot-70 view", + t.fills ? "filled before" : "not filled yet"); + } +} + +void DeviceState::title_texture_unmapped(const void* resource, std::uint64_t address) { + std::lock_guard lock(title_texture_mutex); + const auto it = title_textures.find(address); + if (it != title_textures.end() && it->second->resource == resource) { + it->second->stale = true; + it->second->memory.retry(); + } +} + +void DeviceState::title_texture_gone(const void* resource, std::uint64_t address) { + std::lock_guard lock(title_texture_mutex); + { + std::lock_guard descriptors(descriptor_mutex); + gpu_placements.remove(address, resource); + } + const auto it = title_textures.find(address); + if (it != title_textures.end() && it->second->resource == resource) title_textures.erase(it); +} + +// The T# of a view: what the shader gets to know about it, in the structure the console's shaders read. +// False (with a log) for a view set 0 cannot show yet. +// A T# the title wrote into a console descriptor heap itself (DeviceState::fix_console_slots). Translated shaders +// find an image by the T#'s exact eight dwords, so one that no Create*View wrote is decoded here, its texture looked +// up by the base address it names (Resource::image_address, the only texture addresses the title can know: it +// learns them from descriptors the layer wrote), and the image is given a view and a hash-table entry for exactly +// these words, as write_image_descriptor does. Every field the layer does not encode (tiling, compression, +// performance hints) only makes the key differ, so a title-built T# still finds its texture. Checked against the +// texture first: a view of mips, layers or a dimension it lacks would be an invalid Vulkan view. +TitleImage bind_title_image(DeviceState& device, const leonida::gfx10::ImageWords& words, const char** why) { + namespace g = leonida::gfx10; + const auto refuse = [why](const char* reason) { + if (why) *why = reason; + return TitleImage::refused; + }; + g::Image image{}; + if (!g::decode(words, image)) { + if (why) *why = "not a valid T# (swizzle, levels or layers)"; + return TitleImage::not_tsharp; + } + leonida::ResourceId sparse = 0; + { + std::lock_guard lock(device.descriptor_mutex); + if (!device.bindless) return refuse("no bindless set"); + if (device.image_entries.count(words)) return TitleImage::known; + auto found = device.images_by_address.find(image.address); + // Memory of the texture stream pool has two addresses, the CPU view's and the GPU-only alias the title hands + // to the GPU (title_gpu_views): a T# naming either finds a texture registered under the other. + if (found == device.images_by_address.end()) + if (const std::uint64_t other = leonida::title_gpu_views::other_view(image.address)) + found = device.images_by_address.find(other); + const Resource* owner = found == device.images_by_address.end() + ? nullptr : static_cast(found->second); + const auto matches = [&](const Resource& r) { return TitleGpuPlacements::matches(image, r.desc()); }; + if (!owner || !matches(*owner)) { + const auto alias = leonida::title_gpu_views::other_view(image.address); + if (auto* candidate = device.gpu_placements.find(image.address, alias, matches)) owner = candidate; + } + if (!owner) return TitleImage::unknown; + const Resource& r = *owner; + image.address = r.image_address(); // release this key with its actual owner + const D3D12_RESOURCE_DESC& d = r.desc(); + const bool volume = d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; + const bool line = d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D; + const bool msaa = d.SampleDesc.Count > 1; + const UINT layers = volume ? 1 : d.DepthOrArraySize; + const bool type_fits = image.type == g::ImageType::image_3d ? volume + : image.type == g::ImageType::image_1d ? line && image.layer_count == 1 + : g::multisampled(image.type) + ? msaa && !volume && !line && image.samples == d.SampleDesc.Count + : !volume && !line && !msaa; + if (!r.descriptor_image()) return refuse("the texture has no image"); + if (!type_fits) return refuse("T# type or samples do not fit the texture"); + if (!msaa && image.first_mip + image.mip_count > d.MipLevels) return refuse("T# names mips the texture lacks"); + if (!volume && image.first_layer + image.layer_count > layers) + return refuse("T# names layers the texture lacks"); + if (image.type == g::ImageType::cube && !(r.format() && image.layer_count >= 6)) + return refuse("cube T# on fewer than six layers"); + const bool storage = (d.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) && !msaa && + r.aspects() == VK_IMAGE_ASPECT_COLOR_BIT; + if (!device.bind_image_locked(words, image, r.descriptor_image(), r.format(), r.aspects(), storage, + r.has_view_format_list(), r.uint_backed())) + return refuse("no view for the T#'s format or range"); + r.note_shader_view(); // Include descriptors written directly into title heaps. + if (r.sparse_image()) sparse = r.id(); + } + if (sparse) device.context->note_shader_image(sparse); + return TitleImage::bound; +} + +bool image_descriptor(const Resource& resource, const TextureView& asked, leonida::gfx10::Image& out) { + TextureView view = asked; + view.format = pc_format(view.format); // the console's D16S8 plane views as D24S8's namespace g = leonida::gfx10; const D3D12_RESOURCE_DESC& desc = resource.desc(); // Plane 1 of a depth-stencil texture is its stencil, viewed as X24_TYPELESS_G8_UINT (D24S8) or @@ -4788,7 +8401,8 @@ bool image_descriptor(const Resource& resource, const TextureView& view, leonida const bool compatible = vulkan_format(desc.Format, false).typeless ? desc.Format == DXGI_FORMAT_R8G8B8A8_TYPELESS && (view.format == DXGI_FORMAT_R8G8B8A8_UNORM || view.format == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB) - : view.format == DXGI_FORMAT_UNKNOWN || view.format == desc.Format; + : view.format == DXGI_FORMAT_UNKNOWN || view.format == desc.Format || + (view.format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP && resource.lists_castable_format(view.format)); if (!compatible) { log_once("unsupported volume SRV format for this resource:", int(view.format)); return false; @@ -4830,11 +8444,15 @@ bool image_descriptor(const Resource& resource, const TextureView& view, leonida log_once("view format from another typeless family (B8G8R8X8 and B8G8R8A8):", int(view.format)); return false; } - if ((view.format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP) != (desc.Format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP)) { + // A 32-bit texture that lists R9G9B9E5 as castable (a slot-133 R32 unordered-access target the title packs + // E5 values into, create_at_host_address) is viewed as E5B9G9R9. + if ((view.format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP) != (desc.Format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP) && + !(view.format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP && resource.lists_castable_format(view.format))) { log_once("incompatible R9G9B9E5 view format:", int(view.format)); return false; } - named = texture_storage_format(view.format, false).format; + // An A8 render target is viewed in its own A8 format (Format::a8_as_alpha), other A8 textures through R8. + named = resource.a8_as_alpha() ? resource_format : texture_storage_format(view.format, false).format; if (g::is_depth_stencil_format(named)) { log_once("depth-stencil view format on a colour texture:", int(view.format)); return false; @@ -5125,6 +8743,19 @@ class Device final state_.probe_uint_backed_uav(VK_FORMAT_R8G8B8A8_SRGB, VK_FORMAT_R8G8B8A8_UNORM); state_.bgra8_srgb_uav_emulated = state_.probe_uint_backed_uav(VK_FORMAT_B8G8R8A8_SRGB, VK_FORMAT_B8G8R8A8_UNORM); + if (console_format_stand_ins()) { + state_.r9g9b9e5_target_stand_in = !state_.color_attachment_usable(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32) && + state_.color_attachment_usable(VK_FORMAT_B10G11R11_UFLOAT_PACK32) && + state_.storage_usable(VK_FORMAT_B10G11R11_UFLOAT_PACK32) && + state_.sampled_usable(VK_FORMAT_B10G11R11_UFLOAT_PACK32); + state_.b4g4r4a4_target_stand_in = !state_.color_attachment_usable(VK_FORMAT_A4R4G4B4_UNORM_PACK16) && + state_.color_attachment_usable(VK_FORMAT_B8G8R8A8_UNORM); + std::fprintf(stderr, + "[rt] d3d12: console format stand-ins: R9G9B9E5 target as R11G11B10F %d, B4G4R4A4 target as " + "BGRA8 %d, sRGB UAV as UNORM rgba %d bgra %d\n", + int(state_.r9g9b9e5_target_stand_in), int(state_.b4g4r4a4_target_stand_in), + int(state_.rgba8_srgb_uav_emulated), int(state_.bgra8_srgb_uav_emulated)); + } memory_properties(info.physical, &state_.memory); { char text[4] = {}; @@ -5136,6 +8767,9 @@ class Device final : sysmem ? "system memory (LEONIDA_UPLOAD_SYSMEM)" : "system memory (no Resizable BAR)"); } + if (get_device) + state_.bound_image_requirements = reinterpret_cast( + get_device(info.device, "vkGetImageMemoryRequirements2")); for (const char* name : {"vkGetDeviceImageMemoryRequirements", "vkGetDeviceImageMemoryRequirementsKHR"}) if (!state_.image_requirements) state_.image_requirements = @@ -5197,6 +8831,41 @@ class Device final info.buffer_device_address); state_.context->mesh_queries = info.mesh_shader_queries; state_.context->set_depth_range_unrestricted(info.depth_range_unrestricted); + if (info.device_fault_diagnostics) { + state_.context->configure_device_fault(get_device, + {info.device_fault_info, info.device_checkpoints, info.device_diagnostics_config}); + state_.context->add_diagnostic_queue(info.queue); + for (auto queue : info.command_queues) state_.context->add_diagnostic_queue(queue); + for (auto queue : info.compute_queues) state_.context->add_diagnostic_queue(queue); + for (auto queue : info.copy_queues) state_.context->add_diagnostic_queue(queue); + } + leonida::mem_probe::install(state_.context->vk); // LOCAL DIAGNOSTIC: before anything allocates + if (info.device_fault_diagnostics && rt::compute_probe::enabled()) + state_.context->set_input_probe([this](auto lists, auto sequence, auto queue) { + rt::compute_probe::inspect(state_, lists, sequence, queue); + }); + state_.context->set_before_execute([this] { + state_.refresh_shadows(); + state_.geometry.refresh(DeviceState::copy_geometry); + refresh_title_textures(); + }); + { + char text[16] = {}; + size_t length = 0; + if (getenv_s(&length, text, "LEONIDA_TITLE_WINDOWS_MB") == 0 && length > 1) + state_.title_window_cap = std::strtoull(text, nullptr, 10) << 20; + } + leonida::title_va_aliases().set_buffer_maker(this, [](void* device, std::uint64_t va, std::uint64_t bytes) { + static_cast*>(device)->make_title_buffer(va, bytes); + }); + leonida::title_va_aliases().set_hooks( + &state_, + [](void* device, std::uint64_t va, std::uint64_t bytes, std::uint64_t& out) { + return static_cast(device)->resolve_title_memory(va, bytes, out); + }, + [](void* device, std::uint64_t table, std::uint32_t descriptors) { + static_cast(device)->scan_title_table(table, descriptors); + }); if (info.physical && state_.format_properties) { state_.context->set_color_attachment_format( [physical = info.physical, get_props = state_.format_properties](VkFormat format) { @@ -5207,6 +8876,54 @@ class Device final } if (info.buffer_device_address && state_.context->loaded() && !create_arena()) std::fprintf(stderr, "[rt] d3d12: the GPU address arena could not be created\n"); + { // LOCAL DIAGNOSTIC: mem probe (LEONIDA_MEM_PROBE=) + leonida::mem_probe::DeviceFacts facts; + facts.memory = state_.memory; + facts.title_ranges = [] { return leonida::title_va_aliases().title_memory_ranges(); }; + facts.describe = [this] { + state_.geometry.report(); + DeviceState& d = state_; + // The driver serializes the whole cache to answer the size: only on request (LEONIDA_MEM_PROBE_CACHE=1). + std::size_t cache = 0; + static const bool ask_cache = [] { + wchar_t value[2]{}; + return GetEnvironmentVariableW(L"LEONIDA_MEM_PROBE_CACHE", value, 2) == 1 && value[0] == L'1'; + }(); + const VkPipelineCache handle = d.pipeline_cache_handle; + if (ask_cache && handle && d.context->vk.vkGetPipelineCacheData) + d.context->vk.vkGetPipelineCacheData(d.info.device, handle, &cache, nullptr); + std::uint64_t title = 0, title_ranges = 0; + for (const auto& [begin, end] : leonida::title_va_aliases().title_memory_ranges()) { + title += end - begin; + ++title_ranges; + } + std::uint64_t shadows = 0; + { + std::lock_guard lock(d.shadow_mutex); + shadows = d.shadows.size(); + } + VkDeviceSize in_use = 0, peak = 0, use[4] = {}; + { + std::lock_guard lock(d.arena.mutex); + in_use = d.arena.in_use; + peak = d.arena.peak_end; + for (int i = 0; i < 4; ++i) use[i] = d.arena.use_in_use[i]; + } + char text[512]; + std::snprintf(text, sizeof text, + "pipeline cache %.0f MiB; arena %.0f MiB (type %u), in use %.0f MiB (buffer %.0f, " + "descriptor heap %.0f, shader %.0f, heap %.0f), peak end %.0f MiB; title memory %llu " + "ranges %.0f MiB reserved/committed VA; shadows %llu; fsdraw pipeline notes %zu", + leonida::mem_probe::mib(cache), leonida::mem_probe::mib(d.arena.size), + d.arena.memory_type, leonida::mem_probe::mib(in_use), leonida::mem_probe::mib(use[0]), + leonida::mem_probe::mib(use[1]), leonida::mem_probe::mib(use[2]), + leonida::mem_probe::mib(use[3]), leonida::mem_probe::mib(peak), + (unsigned long long)title_ranges, leonida::mem_probe::mib(title), + (unsigned long long)shadows, leonida::fsdraw::pipeline_count()); + return std::string(text); + }; + leonida::mem_probe::start(std::move(facts)); + } if (info.conditional_rendering) { const auto properties = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties")); @@ -5337,6 +9054,32 @@ class Device final leonida::BindlessFeatures features{}; features.update_after_bind = true; // VulkanDeviceInfo::bindless promises it features.partially_bound = state_.info.bindless_partially_bound; + // The descriptor-table hash kind every shader of this device probes with, chosen once here, before the table's + // first key: each loaded module's index.json meta may say `descriptor_hash` (descriptor_table.h), and when the + // library mixes kinds the majority wins; LEONIDA_DESCRIPTOR_HASH overrides. The module index is read here + // rather than at the first pipeline so the choice is fixed before any descriptor can be registered. + leonida::DescriptorHashCensus hash_modules{}; + leonida::DescriptorHashKind descriptor_hash = leonida::DescriptorHashKind::fnv1a; + if (const leonida::ShaderLibrary* library = state_.library()) { + hash_modules = library->descriptor_hash_census(); + descriptor_hash = library->descriptor_hash_kind(); + } + leonida::DescriptorHashKind override_kind = descriptor_hash; + if (leonida::descriptor_hash_kind_from_env(std::getenv("LEONIDA_DESCRIPTOR_HASH"), &override_kind)) { + std::fprintf(stderr, + "[rt] d3d12: descriptor hash: %s (LEONIDA_DESCRIPTOR_HASH; %zu fnv1a_fmix32 / %zu fnv1a " + "modules)\n", + leonida::descriptor_hash_kind_name(override_kind), hash_modules.fnv1a_fmix32, + hash_modules.fnv1a); + descriptor_hash = override_kind; + } else if (hash_modules.fnv1a_fmix32 && hash_modules.fnv1a) { + std::fprintf(stderr, "[rt] d3d12: descriptor hash: %zu fnv1a_fmix32 / %zu fnv1a modules; using %s\n", + hash_modules.fnv1a_fmix32, hash_modules.fnv1a, + leonida::descriptor_hash_kind_name(descriptor_hash)); + } else { + std::fprintf(stderr, "[rt] d3d12: descriptor hash: %s (all %zu modules)\n", + leonida::descriptor_hash_kind_name(descriptor_hash), hash_modules.total()); + } const auto get_properties = reinterpret_cast( state_.info.get_instance_proc(state_.info.instance, "vkGetPhysicalDeviceProperties2")); if (get_properties) { @@ -5380,6 +9123,8 @@ class Device final features.counts[b::sampled_binding(leonida::ImageDimension::dim_3d)], features.counts[b::sampled_binding(leonida::ImageDimension::dim_1d)], features.counts[b::storage_binding(leonida::ImageDimension::dim_2d, 0)]); + std::fprintf(stderr, "[rt] d3d12: bindless table policy: spare generations, host-memory fallback, a degraded " + "flush instead of a refused submission\n"); // D3D12 promises a shader holds a full shader-visible sampler heap. Past this many distinct S#s, CreateSampler // logs that the array is full and a shader reads the fallback (clamping) sampler. if (features.counts[b::sampler_binding] < D3D12_MAX_SHADER_VISIBLE_SAMPLER_HEAP_SIZE + 1) @@ -5387,7 +9132,8 @@ class Device final "sampler heap (%u of %u besides the fallback): its limits or " "vkGetDescriptorSetLayoutSupport allow no more\n", features.counts[b::sampler_binding] - 1, unsigned(D3D12_MAX_SHADER_VISIBLE_SAMPLER_HEAP_SIZE)); - state_.bindless = std::make_unique(get_device, state_.info.device, state_.memory, features); + state_.bindless = std::make_unique(get_device, state_.info.device, state_.memory, features, + descriptor_hash); if (!state_.bindless->ok() || !state_.context->vk.vkCreateSampler) { state_.bindless.reset(); return false; @@ -5408,7 +9154,7 @@ class Device final // after it, so the generations flush() retires are free at once. { std::lock_guard submit(context.submit_mutex()); - context.vk.vkDeviceWaitIdle(state_.info.device); + context.observe_result(context.vk.vkDeviceWaitIdle(state_.info.device), "vkDeviceWaitIdle"); } state_.bindless_idle_waits.fetch_add(1, std::memory_order_relaxed); state_.bindless->release_retired(); @@ -5436,8 +9182,40 @@ class Device final // Under tracker_mutex_ (held from here to the submit) no other ExecuteCommandLists has recorded work that // is not yet submitted, so every submission that can have bound the set being replaced has a ticket up to // the one read here. - const bool flushed = state_.bindless->flush(command_buffer, context.submitted_retire_ticket()); - if (flushed && state_.bindless->last_flush_replaced()) context.note_bindless_upload(); + // A generation that cannot be made (VRAM full) does not fail the submission: the set frees what completed + // and retries, rewrites the table in place when nothing runs, or keeps the previous table (vulkan_bindless.h). + auto& set = *state_.bindless; + const std::uint64_t host_fallbacks = set.table_host_fallbacks(); + const bool flushed = set.flush(command_buffer, context.submitted_retire_ticket(), + [&context] { return context.completed_retire_ticket(); }); + if (flushed && set.last_flush_replaced()) context.note_bindless_upload(); + const auto table_state = [&] { + return std::to_string(set.table().size()) + " of " + std::to_string(set.table().capacity()) + + " slots used, " + std::to_string(set.table_buffer_bytes() / 1024) + " KiB in " + + (set.table_in_device_local_memory() ? "device-local" : "host") + " memory; " + + std::to_string(set.generations_made()) + " generations made, " + + std::to_string(set.retired_count()) + " retired, " + std::to_string(set.spare_count()) + + " spare, " + std::to_string(set.spares_reused()) + " reused"; + }; + if (set.table_buffer_bytes() != state_.bindless_logged_table_bytes) { + state_.bindless_logged_table_bytes = set.table_buffer_bytes(); + std::fprintf(stderr, "[rt] d3d12: bindless table: %s\n", table_state().c_str()); + } + if (set.table_host_fallbacks() != host_fallbacks && !state_.bindless_host_logged) { + state_.bindless_host_logged = true; + std::fprintf(stderr, "[rt] d3d12: bindless table buffer placed in host memory: device-local memory " + "is full (%s)\n", table_state().c_str()); + } + if (set.last_flush_degraded()) { + // Logged at the first and each power of two: how often it happens without flooding the log. + const std::uint64_t n = set.degraded_flushes(); + if ((n & (n - 1)) == 0) + std::fprintf(stderr, "[rt] d3d12: bindless table generation not made (%s: %d), %llu times: the " + "batch runs with the previous table, keys added since read the fallback " + "(%s)\n", + set.last_failure() ? set.last_failure() : "?", int(set.last_failure_result()), + static_cast(n), table_state().c_str()); + } return flushed; }); state_.context->set_bindless_current([this]() { @@ -5526,7 +9304,11 @@ class Device final return false; } arena.mapped = static_cast(mapped); - std::memset(arena.mapped, 0, kArenaReserved); // the zero page unbound vertex and index buffers read + std::memset(arena.mapped, 0, kZeroPage); // the zero page unbound vertex and index buffers read + { + auto* iota = reinterpret_cast(arena.mapped + kZeroPage); + for (std::uint32_t i = 0; i < kQuadIndexCount; ++i) iota[i] = i; + } VkBufferDeviceAddressInfo address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; address.buffer = arena.buffer; arena.address = vk.vkGetBufferDeviceAddress(state_.info.device, &address); @@ -5537,20 +9319,37 @@ class Device final length = 0; arena.log = getenv_s(&length, log, "LEONIDA_ARENA_LOG") == 0 && length > 1 && log[0] != '0'; state_.context->set_heap_base(arena.address); - state_.context->set_zero_page(arena.buffer, 0, kArenaReserved); + leonida::fsdraw::note_arena(arena.mapped, arena.size); // LOCAL DIAGNOSTIC + state_.context->set_zero_page(arena.buffer, 0, kZeroPage); + state_.context->set_quad_indices(arena.buffer, kZeroPage, kQuadIndexCount); return true; } ~Device() override { + leonida::title_va_aliases().clear_hooks(&state_); + { + std::lock_guard lock(state_.title_window_mutex); + for (const auto& window : state_.title_windows) + leonida::title_va_aliases().remove(window.start, window.shader_va); + state_.title_windows.clear(); + } + for (auto& [shape, image] : state_.zero_images) if (image) image->Release(); + state_.zero_images.clear(); if (state_.context) { { std::lock_guard lock(state_.context->submit_mutex()); - state_.context->vk.vkDeviceWaitIdle(state_.info.device); + state_.context->observe_result(state_.context->vk.vkDeviceWaitIdle(state_.info.device), + "vkDeviceWaitIdle"); } state_.context->drain_deleted_resources(UINT64_MAX); state_.context->set_bindless_release(nullptr, nullptr); state_.context->set_bindless_current(nullptr); // the retired generations go with state_.bindless below } + if (state_.context) { + state_.geometry.release(state_); + state_.external_windows.release(state_); + state_.title_upload.release(state_); + } state_.staging_queue.reset(); // it uses the context if (state_.context && state_.bindless) { // Every texture is gone by now (each held this device), and its views with it; samplers remain. @@ -5562,12 +9361,15 @@ class Device final } state_.report_arena(); if (state_.context && state_.arena.buffer) { + leonida::fsdraw::forget_arena(state_.arena.mapped); auto& vk = state_.context->vk; vk.vkDestroyBuffer(state_.info.device, state_.arena.buffer, nullptr); if (state_.arena.memory) vk.vkFreeMemory(state_.info.device, state_.arena.memory, nullptr); } - if (state_.pipeline_cache_handle) + if (state_.pipeline_cache_handle) { + save_session_pipeline_cache(state_.context->vk, state_.info.device, state_.pipeline_cache_handle); state_.context->vk.vkDestroyPipelineCache(state_.info.device, state_.pipeline_cache_handle, nullptr); + } state_.context.reset(); if (owned_.device) owned_.destroy_device(owned_.device, nullptr); if (owned_.instance) owned_.destroy_instance(owned_.instance, nullptr); @@ -5598,6 +9400,782 @@ class Device final return hand_out(heap, riid, out); } bool bind_sampler(const leonida::gfx10::SamplerWords& words) { return state_.bind_sampler(words); } + // Xbox device slots 70/71 (rt::d3d12::write_placed_buffer_view): the slot is zeroed first, as Create*View does. + bool write_placed_buffer_view(bool unordered, const void* view, std::uint64_t address, std::uint64_t width, + D3D12_CPU_DESCRIPTOR_HANDLE destination) { + struct PlacedWrite { + DeviceState& state; + SIZE_T ptr; + bool unordered; + ~PlacedWrite() { + if (rt::compute_probe::enabled()) state.probe_api(ptr, 1, unordered ? "slot71" : "slot70"); + } + } probe{state_, destination.ptr, unordered}; + std::memset(reinterpret_cast(destination.ptr), 0, kDescriptorSize); + if (unordered) { + D3D12_UNORDERED_ACCESS_VIEW_DESC desc{}; + std::memcpy(&desc, view, sizeof(desc)); + return write_buffer_uav_at(address, width, &desc, 0, destination); + } + D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; + std::memcpy(&desc, view, sizeof(desc)); + return desc.ViewDimension == D3D12_SRV_DIMENSION_BUFFER && write_buffer_srv(address, width, &desc, destination, true); + } + // ---- Textures the title keeps in its own memory (TitleTexture) ---- + + // Xbox device slot 70 with a texture description (rt::d3d12::write_placed_texture_view): the view's T#, of the + // slot-133 texture placed at `address` or of an image made for that memory and filled from it. False leaves the + // slot a null view (zeros); every reason is counted and logged once per format and layout. + bool write_placed_texture_view(const std::uint32_t* resource_words, const std::uint32_t* view_words, + std::uint64_t address, D3D12_CPU_DESCRIPTOR_HANDLE destination) { + std::memset(reinterpret_cast(destination.ptr), 0, kDescriptorSize); + rt::xg_xs::ResourceDesc d{}; + std::memcpy(&d, resource_words, sizeof(d)); + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + std::memcpy(&srv, view_words, sizeof(srv)); + if (!srv.Shader4ComponentMapping) srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + std::array words{}; + std::memcpy(words.data(), resource_words, sizeof(words)); + words[2] = words[3] = 0; // the alignment says nothing about the texels + bool written = false; + { + std::lock_guard lock(state_.title_texture_mutex); + const InTitleTextures inside; + TitleTextureStats& stats = title_stats_; + ++stats.views; + ++stats.asked[{d.format, d.layout, d.dimension, d.mips}]; + const std::uint64_t refusals = stats.refusals; + written = place_title_view(d, words, srv, address, destination); + if (texture_probe()) + std::fprintf(stderr, "[rt] texture-probe: SRV dest %llx va %llx %llux%ux%u fmt %u view %u mips %u ok %u\n", + (unsigned long long)destination.ptr, (unsigned long long)address, (unsigned long long)d.width, + d.height, unsigned(d.depth_or_array), d.format, unsigned(srv.Format), unsigned(d.mips), unsigned(written)); + if (!written && stats.refusals == refusals) refuse_title_view("no reason recorded", d, address); + if (!written) ++stats.null_views; + if (stats.views == 64 || !(stats.views % 2048)) log_title_census("slot-70 texture views"); + } + return written; + } + + // Slot 71 names GPU-writable memory. Its contents belong to the existing image. + bool write_placed_texture_uav(const std::uint32_t* words, const std::uint32_t* view, std::uint64_t address, + D3D12_CPU_DESCRIPTOR_HANDLE dest) { + static const bool enabled = [] { + const char* v = std::getenv("LEONIDA_PLACED_TEXTURE_UAV"); + return !v || std::strcmp(v, "0"); + }(); + std::memset(reinterpret_cast(dest.ptr), 0, kDescriptorSize); + if (!enabled || !address) return false; + rt::xg_xs::ResourceDesc d{}; + D3D12_UNORDERED_ACCESS_VIEW_DESC uav{}; + std::memcpy(&d, words, sizeof(d)); + std::memcpy(&uav, view, sizeof(uav)); + std::lock_guard lock(state_.title_texture_mutex); + auto it = state_.title_textures.find(address); + if (it == state_.title_textures.end()) + it = state_.title_textures.find(leonida::title_gpu_views::other_view(address)); + Resource* candidate = matching_gpu_placement(d, address, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + if (!candidate && it != state_.title_textures.end() && !it->second->owned) candidate = it->second->resource; + if (!candidate) return false; + Resource& r = *candidate; + const auto& rd = r.desc(); + if (!TitleGpuPlacements::matches(d, r) || !(rd.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) + return false; + if (uav.ViewDimension == D3D12_UAV_DIMENSION_TEXTURE3D) { + const auto& volume = uav.Texture3D; + if (rd.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE3D || volume.MipSlice >= rd.MipLevels) return false; + const UINT depth = std::max(1u, UINT(rd.DepthOrArraySize) >> volume.MipSlice); + if (volume.FirstWSlice || (volume.WSize != UINT_MAX && volume.WSize != depth)) return false; + TextureView v{}; + v.type = leonida::gfx10::ImageType::image_3d; + v.format = uav.Format; + v.first_mip = volume.MipSlice; + v.mip_count = 1; + write_image_descriptor(r, v, dest, true); + } else { + CreateUnorderedAccessView(&r, nullptr, &uav, dest); + } + leonida::gfx10::ImageWords result{}; + std::memcpy(result.data(), reinterpret_cast(dest.ptr), sizeof(result)); + if (!leonida::gfx10::is_image(result)) return false; + std::lock_guard descriptors(state_.descriptor_mutex); + if (!state_.bindless) return true; + const auto entry = state_.image_entries.find(result); + if (entry != state_.image_entries.end() && entry->second.storage) return true; + std::memset(reinterpret_cast(dest.ptr), 0, kDescriptorSize); + return false; + } + + // A slot-133 texture the title placed at `address` (create_at_host_address): slot-70 views at that address are + // of its image; unless the GPU writes it, the image is filled from the memory with the view's layout. + void register_title_texture(Resource* texture, std::uint64_t address) { + const D3D12_RESOURCE_DESC& desc = texture->desc(); + auto entry = std::make_shared(); + entry->address = address; + entry->cpu = leonida::title_gpu_views::to_cpu(address); + entry->set_resource(texture); + entry->attachment_4k = desc.Width == 3840 && desc.Height == 2160 && + (desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)); + entry->gpu_written = (desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | + D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) != 0 || + desc.SampleDesc.Count > 1; + if (!entry->gpu_written) { + // Until a slot-70 view says how it is laid out: the description's own (Layout 0, XG's default). + rt::xg_xs::ResourceDesc d{}; + d.dimension = std::uint32_t(desc.Dimension); + d.width = desc.Width; + d.height = desc.Height; + d.depth_or_array = desc.DepthOrArraySize; + d.mips = desc.MipLevels; + d.format = std::uint32_t(desc.Format); + d.samples = 1; + const char* why = nullptr; + if (title_xg_layout(*texture, entry->layout, entry->desc)) { + entry->layout_known = entry->layout_from_xg = true; + } else { + entry->layout_known = entry->layout_guessed = title_layout(d, entry->layout, why) && + title_layout_fits(entry->layout, d, *texture, why); + std::memcpy(entry->desc.data(), &d, sizeof(d)); + } + } + texture->mark_title_texture(); + { + std::lock_guard lock(state_.title_texture_mutex); + if (entry->gpu_written && !(address & 0xff) && texture->image_address() != address) { + std::lock_guard descriptors(state_.descriptor_mutex); + state_.gpu_placements.add(address, texture); + } + auto& slot = state_.title_textures[address]; + if (slot && slot->owned) retire_title_texture(*slot); + slot = std::move(entry); + ++title_stats_.registered; + } + } + + // Before every submission (VulkanContext::set_before_execute), at most once per LEONIDA_TITLE_TEXTURE_PERIOD_MS + // (16 by default, about a frame): the bytes of the textures filled from the title's memory are hashed, round + // robin, until LEONIDA_TITLE_TEXTURE_CHECK_KB have been read (4096 by default; all of a small texture, about 3% + // of a large one, hash_guarded), mapped slot-133 textures first and every pass; a texture whose bytes changed is + // filled again, up + // to LEONIDA_TITLE_TEXTURE_FILL_MB a pass (32 by default, OpenScarlett's batch cap), the rest at the next pass. + // Host copies and the private full-image uploader are safe here. Generic staging re-enters submission. No write + // watch on the title's pages: streaming memory would fault once a page. + void refresh_title_textures() { + if (t_in_title_textures) return; + using clock = std::chrono::steady_clock; + static const auto setting = [](const char* name, std::uint64_t fallback) { + char text[16] = {}; + size_t length = 0; + return getenv_s(&length, text, name) == 0 && length > 1 ? std::strtoull(text, nullptr, 10) : fallback; + }; + static const auto period = std::chrono::milliseconds(setting("LEONIDA_TITLE_TEXTURE_PERIOD_MS", 16)); + static const std::uint64_t check_budget = setting("LEONIDA_TITLE_TEXTURE_CHECK_KB", 4096) << 10; + static const std::uint64_t fill_budget = setting("LEONIDA_TITLE_TEXTURE_FILL_MB", 32) << 20; + // Stop the background sweep at a texture boundary. Zero keeps the byte budget alone. + static const std::uint64_t hash_budget_us = setting("LEONIDA_TEXTURE_HASH_BUDGET_US", 400); + // Residency checks and uploads also cost time. Limit background work between textures; + // mapped textures and notified writes have already been serviced when this timer starts. + static const auto sweep_budget_us = setting("LEONIDA_TEXTURE_SWEEP_BUDGET_US", 400); + const auto now = clock::now(); + const std::int64_t ticks = now.time_since_epoch().count(); + if (ticks - title_refreshed_.load(std::memory_order_relaxed) < + std::chrono::duration_cast(period).count()) + return; + std::unique_lock lock(state_.title_texture_mutex, std::try_to_lock); + if (!lock.owns_lock()) return; // a slot-70 view is filling one; next time + title_refreshed_.store(ticks, std::memory_order_relaxed); + const InTitleTextures inside; + TitleTextureStats& stats = title_stats_; + ++stats.passes; + std::uint64_t checked = 0, filled = 0; + const auto visit = [&](TitleTexture& t) { + // A slot-133 texture's guessed layout (no slot-70 view yet) is only used once the title maps it. + if (t.gpu_written || !t.layout_known || !t.resource || + ((t.layout_guessed || t.layout_from_xg) && !t.mapped && !t.stale)) + return; + const std::uint64_t span = t.layout.layout.size; + std::uint64_t hash = 0; + if (!title_texture_readable(t)) return; + checked += hashed_bytes(span); + ++stats.checked; + const auto* bytes = reinterpret_cast(static_cast(t.cpu)); + const auto timed_hash = [&](std::uint64_t& out, bool all = false) { + const auto start = clock::now(); + const bool ok = hash_guarded(bytes, std::size_t(span), out, all); + stats.hash_ns += std::chrono::duration_cast(clock::now() - start).count(); + return ok; + }; + if (!timed_hash(hash)) { + t.memory.defer(); + return; + } + if (t.hashed && hash == t.hash && !t.stale) { + if (!t.every_byte() || stats.passes % 6) return; + std::uint64_t full = 0; + checked += span; + if (!timed_hash(full, true)) { + t.memory.defer(); + return; + } + if (t.full_hashed && full == t.full_hash) return; + } + ++stats.changed; + if (!(t.mapped && refresh_mapped_pages()) && filled && filled + span > fill_budget) { + t.stale = true; + ++stats.deferred; + return; + } + filled += fill_title_texture(t, false); + }; + bool overflow = false; + auto written = leonida::title_texel_writes::take(overflow); + if (!written.empty() || overflow) { + stats.written_ranges += written.size(); + leonida::merge_title_writes(written); + for (auto& [address, t] : state_.title_textures) { + if (t->gpu_written || !t->layout_known) continue; + const std::uint64_t begin = t->cpu, end = t->cpu + t->layout.layout.size; + if (leonida::title_write_overlaps(written, begin, end)) { + t->memory.retry(); + t->stale = true; + } + if (overflow) { + t->memory.retry(); + t->hashed = false; + } + } + } + for (auto& [address, t] : state_.title_textures) + if (t->mapped || t->stale) visit(*t); + // The budget is the round robin's: mapped and stale textures above are checked every pass whatever it is. + const auto first_bytes = checked, first_hash_ns = stats.hash_ns; + if (check_budget) { + const auto sweep_start = clock::now(); + leonida::poll_title_textures(state_.title_textures, title_refresh_cursor_, visit, [&] { + if (checked - first_bytes >= check_budget || + (hash_budget_us && (stats.hash_ns - first_hash_ns) / 1000 >= hash_budget_us)) return true; + if (!sweep_budget_us) return false; + const auto elapsed = std::chrono::duration_cast(clock::now() - sweep_start); + return std::uint64_t(elapsed.count()) >= sweep_budget_us; + }); + } + stats.hashed += checked; + stats.filled_bytes += filled; + stats.max_pass_bytes = std::max(stats.max_pass_bytes, filled); + std::vector release; + std::erase_if(retired_title_textures_, [&](const auto& r) { + if (now - r.first < std::chrono::seconds(3)) return false; // descriptors may still be in flight + retired_backing_ -= r.second->image_backing_bytes(); + release.push_back(r.second); + return true; + }); + stats.refresh_ns += std::chrono::duration_cast(clock::now() - now).count(); + if (now - stats.last_log >= std::chrono::seconds(10)) { + stats.last_log = now; + log_title_census("refresh"); + } + lock.unlock(); + for (Resource* r : release) r->Release(); + } + +private: + struct TitleTextureStats { + // (format, Layout word, dimension, mips) of the slot-70 texture views -> views + std::map, std::uint64_t> asked; + std::map refused; // why a view is a null view -> views + std::uint64_t views = 0, null_views = 0, of_slot133 = 0, of_cache = 0, made = 0, retired = 0, registered = 0, + refusals = 0, written_ranges = 0, unmaps = 0, unreadable = 0, pending_views = 0; + std::uint64_t fills = 0, fill_bytes = 0, fill_failures = 0; + std::uint64_t staged_fills = 0, staged_ns = 0; + // refresh_title_textures, since the last log line + std::uint64_t passes = 0, checked = 0, hashed = 0, changed = 0, deferred = 0, filled_bytes = 0, + max_pass_bytes = 0, hash_ns = 0, refresh_ns = 0; + std::chrono::steady_clock::time_point last_log{}; + }; + TitleTextureStats title_stats_; // under title_texture_mutex + std::atomic title_refreshed_{0}; // steady_clock ticks of the last pass + std::uint64_t title_refresh_cursor_ = 0; // under title_texture_mutex + VkDeviceSize retired_backing_ = 0; + std::vector> retired_title_textures_; // likewise + std::vector title_tiled_, title_linear_; // scratch, under title_texture_mutex + std::vector title_columns_; + + // The rest under title_texture_mutex. + bool refuse_title_view(const char* why, const rt::xg_xs::ResourceDesc& d, std::uint64_t address) { + ++title_stats_.refusals; + std::uint64_t& n = title_stats_.refused[why]; + static std::set> logged; + if (!n++ || (logged.size() < 256 && logged.emplace(why, d.format, d.layout).second)) + std::fprintf(stderr, + "[rt] d3d12: slot-70 texture view is a null view (%s): dimension %u %llux%ux%u mips %u " + "format %u samples %u Layout 0x%x flags 0x%x at 0x%llx\n", + why, d.dimension, static_cast(d.width), d.height, + unsigned(d.depth_or_array), unsigned(d.mips), d.format, d.samples, d.layout, d.flags, + static_cast(address)); + return false; + } + + // The console layout of a description, as XG lays it out; false with the reason when this XG model lacks it. + static bool title_layout(const rt::xg_xs::ResourceDesc& d, rt::xg_xs::Texture& out, const char*& why) { + namespace xg = rt::xg_xs; + const std::uint32_t mode = xg::select_mode(d); + if (d.samples > 1) return why = "multisampled", false; + if (mode != xg::kLinear && mode != xg::k4kbS && mode != xg::k64kbS && mode != xg::k64kbD) + return why = "swizzle mode the XG model lacks", false; + if (!xg::format_info(d.format).bytes) return why = "format the XG model lacks", false; + xg::ResourceDesc plain = d; + plain.flags &= ~(xg::kRenderTarget | xg::kDepthStencil); + if (!xg::build_texture(plain, out)) return why = "description the XG model refuses", false; + return true; + } + + // The image a layout fills: the same extent, mips, layers and element (texel or 4x4 block) size. + static bool title_layout_fits(const rt::xg_xs::Texture& layout, const rt::xg_xs::ResourceDesc& d, + const Resource& r, const char*& why) { + const D3D12_RESOURCE_DESC& desc = r.desc(); + const leonida::BlockFormat element = r.copy_element(); + if (desc.Width != d.width || desc.Height != d.height || desc.DepthOrArraySize != d.depth_or_array || + desc.MipLevels != layout.layout.mips || UINT(desc.Dimension) != d.dimension) + return why = "texture of another extent, mips or layers at the address", false; + if (element.bytes != layout.format.bytes || element.block != layout.format.side) + return why = "image element differs from the console's", false; + return true; + } + + // Caller holds title_texture_mutex, which the registered resource takes before destruction. + Resource* matching_gpu_placement(const rt::xg_xs::ResourceDesc& d, std::uint64_t address, + D3D12_RESOURCE_FLAGS required = D3D12_RESOURCE_FLAG_NONE) { + std::lock_guard descriptors(state_.descriptor_mutex); + return state_.gpu_placements.find(address, leonida::title_gpu_views::other_view(address), [&](const Resource& r) { + return (r.desc().Flags & required) == required && TitleGpuPlacements::matches(d, r); + }); + } + + bool place_title_view(const rt::xg_xs::ResourceDesc& d, const std::array& words, + const D3D12_SHADER_RESOURCE_VIEW_DESC& srv, std::uint64_t address, + D3D12_CPU_DESCRIPTOR_HANDLE destination) { + if (!address) return refuse_title_view("no address", d, address); + const auto write = [&](const TitleTexture& t) { + const bool written = write_title_srv(*t.resource, srv, destination, d, address); + if (written && !t.gpu_written && t.memory.pending()) ++title_stats_.pending_views; + return written; + }; + auto& textures = state_.title_textures; + const auto it = textures.find(address); + TitleTexture* t = it == textures.end() ? nullptr : it->second.get(); + if (!t || !TitleGpuPlacements::matches(d, *t->resource)) { + if (Resource* gpu = matching_gpu_placement(d, address)) { + ++title_stats_.of_slot133; + return write_title_srv(*gpu, srv, destination, d, address); + } + } + if (t && !t->owned) { // the title's slot-133 texture + ++title_stats_.of_slot133; + if (!t->gpu_written && (t->layout_guessed || t->layout_from_xg || !t->layout_known || t->desc != words)) { + const char* why = nullptr; + rt::xg_xs::Texture layout; + if (title_layout(d, layout, why) && title_layout_fits(layout, d, *t->resource, why)) { + static std::atomic logged{0}; + if (t->mapped && logged.fetch_add(1, std::memory_order_relaxed) < 32) + std::fprintf(stderr, + "[rt] d3d12: a slot-70 view gives mapped slot-133 texture 0x%llx its layout: Layout " + "0x%x (XG mode %u; was %s)\n", + static_cast(address), d.layout, layout.mode, + t->layout_guessed ? "guessed" : "unknown"); + t->memory.retry(); + t->layout = layout; + t->desc = words; + t->layout_known = true; + t->layout_guessed = t->layout_from_xg = false; + t->hashed = false; + } else { + refuse_title_view(why, d, address); // counted; the view of its image is still written + } + } + if (!t->gpu_written && t->layout_known) refresh_title_texture(*t); + return write(*t); + } + if (t && !title_texture_matches(*t, words, srv)) { + std::vector formats = t->formats; + const bool same_shape = [&] { + auto a = t->desc, b = words; + a[8] = b[8] = 0; // the format + return a == b && rt::xg_xs::format_info(t->desc[8]).bytes == rt::xg_xs::format_info(words[8]).bytes && + rt::xg_xs::format_info(t->desc[8]).side == rt::xg_xs::format_info(words[8]).side; + }(); + retire_title_texture(*t); + textures.erase(address); + t = make_title_texture(d, words, srv, address, same_shape ? formats : std::vector{}); + } else if (t) { + ++title_stats_.of_cache; + refresh_title_texture(*t); + } else { + t = make_title_texture(d, words, srv, address, {}); + } + return t && write(*t); + } + + // An image made for slot-70 views serves another view when it has the description and the view's format. + static bool title_texture_matches(const TitleTexture& t, const std::array& words, + const D3D12_SHADER_RESOURCE_VIEW_DESC& srv) { + const auto has = [&](DXGI_FORMAT f) { return std::find(t.formats.begin(), t.formats.end(), f) != t.formats.end(); }; + return t.desc == words && (srv.Format == DXGI_FORMAT_UNKNOWN || has(srv.Format)); + } + + TitleTexture* make_title_texture(const rt::xg_xs::ResourceDesc& d, const std::array& words, + const D3D12_SHADER_RESOURCE_VIEW_DESC& srv, std::uint64_t address, + std::vector formats) { + namespace xg = rt::xg_xs; + if (d.flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) + return refuse_title_view("GPU-written texture with no slot-133 texture at its address", d, address), nullptr; + if (d.dimension < xg::kTexture1D || d.dimension > xg::kTexture3D) + return refuse_title_view("dimension", d, address), nullptr; + auto entry = std::make_shared(); + const char* why = nullptr; + if (!title_layout(d, entry->layout, why)) return refuse_title_view(why, d, address), nullptr; + const std::uint64_t span = entry->layout.layout.size; + entry->cpu = leonida::title_gpu_views::to_cpu(address); + // A streamed texture can have views before its pages arrive. Keep the descriptor stable across its first fill. + entry->memory.check(leonida::title_memory_map::generation(), check_pages_before_read(), + [&] { return leonida::texture_memory_readable(entry->cpu, span); }); + title_stats_.unreadable += entry->memory.pending(); + // The image takes the view's format too when the element is the same size (five-star-recomp does the same); + // views in other formats of the same description add theirs (place_title_view). + const auto add = [&](DXGI_FORMAT f) { + if (f != DXGI_FORMAT_UNKNOWN && std::find(formats.begin(), formats.end(), f) == formats.end()) + formats.push_back(f); + }; + add(DXGI_FORMAT(d.format)); + if (srv.Format != DXGI_FORMAT_UNKNOWN && srv.Format != DXGI_FORMAT(d.format)) { + const xg::Format a = xg::format_info(d.format), b = xg::format_info(srv.Format); + if (a.bytes != b.bytes || a.side != b.side) + return refuse_title_view("view format of another element size", d, address), nullptr; + add(srv.Format); + } + D3D12_RESOURCE_DESC pc{}; + pc.Dimension = D3D12_RESOURCE_DIMENSION(d.dimension); + pc.Width = d.width; + pc.Height = d.height; + pc.DepthOrArraySize = d.depth_or_array; + pc.MipLevels = UINT16(entry->layout.layout.mips); + pc.Format = formats.front(); + pc.SampleDesc = {1, 0}; + pc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; + pc.Flags = D3D12_RESOURCE_FLAG_NONE; + const Format host = state_.texture_format(pc); + if (host.format == VK_FORMAT_UNDEFINED) return refuse_title_view("format the layer lacks", d, address), nullptr; + if (host.aspects != VK_IMAGE_ASPECT_COLOR_BIT) + return refuse_title_view("depth or stencil format", d, address), nullptr; + // Keep CPU-copy semantics. Resource::create_texture selects host copies or staged uploads from Vulkan requirements. + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, + D3D12_MEMORY_POOL_L0, 1, 1}; + static const bool defer = [] { + const char* value = std::getenv("LEONIDA_TITLE_IMAGE_DEFER"); + return !value || std::strcmp(value, "0"); + }(); + const auto origin = defer && entry->memory.pending() ? TitleImageOrigin::pending_stream : TitleImageOrigin::streamed; + void* made = nullptr; + const HRESULT hr = create_committed(&heap, D3D12_HEAP_FLAG_NONE, &pc, D3D12_RESOURCE_STATE_COMMON, + formats.size() > 1 ? UINT32(formats.size()) : 0, formats.data(), + __uuidof(ID3D12Resource), &made, origin); + Resource* r = SUCCEEDED(hr) && made ? Resource::from(static_cast(made)) : nullptr; + if (!r) { + if (made) static_cast(made)->Release(); + log_once("an image for a slot-70 texture view could not be made; HRESULT", int(hr)); + return refuse_title_view("image not created", d, address), nullptr; + } + if (!title_layout_fits(entry->layout, d, *r, why)) { + r->Release(); + return refuse_title_view(why, d, address), nullptr; + } + r->place_at_title_address(reinterpret_cast(static_cast(address))); + entry->address = address; + entry->desc = words; + entry->layout_known = true; + entry->set_resource(r); + entry->owned = true; + entry->formats = std::move(formats); + if (!entry->memory.pending()) fill_title_texture(*entry, true); + ++title_stats_.made; + TitleTexture* t = entry.get(); + state_.title_textures[address] = std::move(entry); + return t; + } + + void retire_title_texture(TitleTexture& t) { + if (!t.owned || !t.resource) return; + // Its T#s leave the hash table now (a later texture at the address takes them over); the image itself goes + // a few seconds later, when no submission can still read it. + if (t.resource->image_address()) state_.forget_image(t.resource->image_address()); + retired_backing_ += t.resource->image_backing_bytes(); + retired_title_textures_.emplace_back(std::chrono::steady_clock::now(), t.resource); + t.resource = nullptr; + ++title_stats_.retired; + } + + static bool texture_probe() { + static const bool enabled = [] { + const char* v = std::getenv("LEONIDA_TEXTURE_PROBE"); + return v && std::strcmp(v, "0"); + }(); + return enabled; + } + + static bool check_pages_before_read() { + static const bool enabled = [] { + const char* v = std::getenv("LEONIDA_TEXTURE_PAGE_CHECK"); + return !v || std::strcmp(v, "0"); + }(); + return enabled; + } + + static bool refresh_mapped_pages() { + static const bool enabled = [] { + const char* value = std::getenv("LEONIDA_REFRESH_MAPPED_TEXTURES"); + return !value || std::strcmp(value, "0"); + }(); + return enabled; + } + + // A mapped texture can lose its pages between views or between refreshes. + static bool title_texture_readable(TitleTexture& t) { + const bool guard = check_pages_before_read(); + if (!guard && !t.memory.pending()) return true; + const bool mapped = t.mapped && refresh_mapped_pages(); + const auto commit = mapped ? leonida::kernel_writes::state().committer.load(std::memory_order_acquire) : nullptr; + return t.memory.check(leonida::title_memory_map::generation(), guard && !mapped, + [&] { return leonida::texture_memory_readable(t.cpu, t.layout.layout.size, commit); }); + } + + void refresh_title_texture(TitleTexture& t) { + std::uint64_t hash = 0; + if (!title_texture_readable(t)) return; + if (!hash_guarded(reinterpret_cast(static_cast(t.cpu)), + std::size_t(t.layout.layout.size), hash)) { + t.memory.defer(); + return; + } + if (!t.hashed || hash != t.hash || t.stale) fill_title_texture(t, true); + } + + // Snapshot the whole footprint before uploading any subresource. A concurrent unmap defers the fill. + // Private title staging bypasses the D3D12 submit callbacks. Generic staged copies require an outer fill. + std::uint64_t fill_title_texture(TitleTexture& t, bool staged) { + const rt::xg_xs::Texture& layout = t.layout; + const std::uint32_t mips = layout.layout.mips, slices = layout.array; + if (!staged && !t.unbound_bytes && !t.resource->staged_title()) + for (UINT sub = 0; sub < mips * slices; ++sub) + if (!t.resource->host_copy_now(sub)) { + t.stale = true; + return 0; + } + const std::uint64_t span = layout.layout.size; + if (!title_texture_readable(t)) return 0; + title_tiled_.resize(std::size_t(span)); + if (!copy_guarded(title_tiled_.data(), reinterpret_cast(t.cpu), std::size_t(span), + title_memory_write_combined(t.cpu))) { + // The section changed after VirtualQuery. Preserve the last complete upload and retry. + t.memory.defer(); + t.stale = true; + return 0; + } + if (!t.owned && t.unbound_bytes) { + if (!t.resource->image()) { + t.stale = true; + return 0; + } + t.set_resource(t.resource); + } + if (t.owned && t.unbound_bytes) { + if (!t.resource->back_streamed_texture()) { + t.stale = true; + return 0; + } + t.set_resource(t.resource); + } + std::uint64_t hash = 0; + hash_guarded(title_tiled_.data(), title_tiled_.size(), hash); + t.full_hashed = t.every_byte() && hash_guarded(title_tiled_.data(), title_tiled_.size(), t.full_hash, true); + const bool volume = layout.layout.dimension == rt::xg_xs::kTexture3D; + const bool trace_pool = leonida::dstorage::trace_enabled() && leonida::title_gpu_views::other_view(t.cpu); + bool nonzero = false; + bool ok = true; + if (t.resource->staged_title()) { + const auto start = std::chrono::steady_clock::now(); + ok = t.resource->upload_staged_title(layout, title_tiled_.data(), title_columns_, trace_pool, nonzero); + title_stats_.staged_ns += std::chrono::duration_cast( + std::chrono::steady_clock::now() - start).count(); + if (ok) ++title_stats_.staged_fills; + if (!ok) log_once("staged title texture upload failed, format", int(t.resource->format())); + } else { + for (std::uint32_t slice = 0; slice < slices && ok; ++slice) { + for (std::uint32_t level = 0; level < mips && ok; ++level) { + const auto& mip = layout.layout.plane[0].mips[level]; + const std::uint32_t row_pitch = mip.width_elements * layout.format.bytes; + const std::uint32_t slice_pitch = row_pitch * mip.height_elements; + title_linear_.resize(std::size_t(slice_pitch) * (volume ? mip.depth : 1)); + rt::xg_xs::copy_elements(layout, level, slice, title_tiled_.data(), title_linear_.data(), + row_pitch, slice_pitch, title_columns_); + if (trace_pool && !nonzero) + nonzero = std::any_of(title_linear_.begin(), title_linear_.end(), [](auto byte) { return byte != 0; }); + const HRESULT hr = + t.resource->upload_title_subresource(level + slice * mips, title_linear_.data(), row_pitch, + slice_pitch, staged); + if (FAILED(hr)) { + log_once("a title texture's subresource could not be filled; HRESULT", int(hr)); + ok = false; + } + } + } + } + if (!ok) { + ++title_stats_.fill_failures; + t.stale = true; + return 0; + } + if (trace_pool) + std::fprintf(stderr, "[rt] ds-pool-fill cpu=%llx size=%llu staged=%d nonzero=%d\n", + static_cast(t.cpu), static_cast(span), + int(staged), int(nonzero)); + if (t.owned && !t.fills) t.resource->publish_streamed_texture(); + t.hash = hash; + t.hashed = true; + t.stale = false; + ++t.fills; + ++title_stats_.fills; + title_stats_.fill_bytes += span; + return span; + } + + static bool title_memory_write_combined(std::uint64_t address) { + MEMORY_BASIC_INFORMATION region{}; + return VirtualQuery(reinterpret_cast(static_cast(address)), ®ion, + sizeof(region)) && + (region.Protect & PAGE_WRITECOMBINE); + } + + bool write_title_srv(Resource& r, const D3D12_SHADER_RESOURCE_VIEW_DESC& srv, D3D12_CPU_DESCRIPTOR_HANDLE dest, + const rt::xg_xs::ResourceDesc& d, std::uint64_t address) { + CreateShaderResourceView(static_cast(&r), &srv, dest); + const auto* w = reinterpret_cast(dest.ptr); + const auto written = [w] { return (w[0] | w[1] | w[2] | w[3] | w[4] | w[5] | w[6] | w[7]) != 0; }; + if (written()) return true; + // A slot-133 texture made in a stand-in format (an R9G9B9E5 target as R11G11B10F, console_format_stand_ins) + // has no view in the console format: the view in the texture's own format reads what it holds. + if (srv.Format != DXGI_FORMAT_UNKNOWN && srv.Format == r.desc().Format) { + D3D12_SHADER_RESOURCE_VIEW_DESC own = srv; + own.Format = DXGI_FORMAT_UNKNOWN; + CreateShaderResourceView(static_cast(&r), &own, dest); + if (written()) { + log_once("a slot-70 view in another format than its texture's reads it in the texture's own format; " + "view format", + int(srv.Format)); + return true; + } + } + static std::atomic logged{0}; + if (logged.fetch_add(1, std::memory_order_relaxed) < 16) + std::fprintf(stderr, + "[rt] d3d12: slot-70 view of a title texture at 0x%llx refused by the SRV checks: view format " + "%d dimension %d mapping 0x%x (texture format %d)\n", + static_cast(address), int(srv.Format), int(srv.ViewDimension), + unsigned(srv.Shader4ComponentMapping), int(r.desc().Format)); + return refuse_title_view("SRV refused for the texture", d, address); + } + + // One line of what slot 70 was asked for, and one of what the refresh did since the last line (NOTES: step 4). + void log_title_census(const char* when) { + TitleTextureStats& s = title_stats_; + std::vector>> asked; + for (const auto& [key, n] : s.asked) asked.emplace_back(n, key); + std::sort(asked.rbegin(), asked.rend()); + std::string census; + for (std::size_t i = 0; i < asked.size() && i < 24; ++i) { + char text[64]; + std::snprintf(text, sizeof(text), "%s%u/0x%x/%u/%u:%llu", i ? " " : "", asked[i].second[0], + asked[i].second[1], asked[i].second[2], asked[i].second[3], + static_cast(asked[i].first)); + census += text; + } + std::string refused; + for (const auto& [why, n] : s.refused) + refused += (refused.empty() ? "" : "; ") + why + " " + std::to_string(n); + std::size_t owned = 0, slot133 = 0, mapped = 0, filled = 0; + VkDeviceSize owned_bytes = 0, placed_bytes = 0, host_heap_bytes = 0; + for (const auto& [address, t] : state_.title_textures) { + (t->owned ? owned : slot133) += 1; + if (!t->owned && t->unbound_bytes) t->set_resource(t->resource); + mapped += t->mapped; + filled += t->fills > 0; + (t->owned ? owned_bytes : placed_bytes) += t->backing_bytes; + if (!t->device_local) host_heap_bytes += t->backing_bytes; + } + if (leonida::mem_probe::interval_seconds()) + log_title_image_uses(state_.title_textures, retired_title_textures_.size(), retired_backing_, state_.zero_image_bytes.load()); + if (leonida::mem_probe::interval_seconds()) + std::fprintf(stderr, "[rt] mem-probe: registered image backing: %.1f MiB from slot 70, %.1f MiB from slot " + "133, %.1f MiB total on non-device-local types; staged fills %llu, %.3f s, buffer %.1f MiB\n", + double(owned_bytes) / 1048576.0, double(placed_bytes) / 1048576.0, + double(host_heap_bytes) / 1048576.0, static_cast(s.staged_fills), + double(s.staged_ns) / 1e9, double(state_.title_upload.capacity()) / 1048576.0); + std::fprintf(stderr, + "[rt] d3d12: title textures (%s): %llu slot-70 texture views (%zu kinds), %llu of slot-133 textures, " + "%llu of images made for them (%llu made, %llu over memory not readable yet, %llu retired), %llu " + "null views; registry %zu images " + "(%zu made, %zu slot 133 of %llu registered, %zu mapped, %zu filled); %llu fills %.1f MiB, %llu " + "failed\n", + when, static_cast(s.views), s.asked.size(), + static_cast(s.of_slot133), static_cast(s.of_cache), + static_cast(s.made), static_cast(s.unreadable), + static_cast(s.retired), + static_cast(s.null_views), state_.title_textures.size(), owned, slot133, + static_cast(s.registered), mapped, filled, + static_cast(s.fills), double(s.fill_bytes) / 1048576.0, + static_cast(s.fill_failures)); + const auto host = state_.context->host_texture_stats(); + std::fprintf(stderr, "[rt] d3d12: ordered title host copies %llu, GPU waits %llu; " + "slot-70 views awaiting readable memory: %llu\n", + static_cast(host.copies), static_cast(host.waits), + static_cast(s.pending_views)); + std::fprintf(stderr, "[rt] d3d12: title textures census (format/Layout/dimension/mips:views): %s\n", + census.c_str()); + if (!refused.empty()) std::fprintf(stderr, "[rt] d3d12: title textures null views by reason: %s\n", refused.c_str()); + std::string maps; + std::size_t listed = 0; + for (const auto& [address, t] : state_.title_textures) { + if (!t->mapped || !t->resource || listed++ >= 16) continue; + const D3D12_RESOURCE_DESC& rd = t->resource->desc(); + char text[160]; + std::snprintf(text, sizeof(text), "%s0x%llx %llux%u fmt %d layout %s mode %u, %u T#s, %llu fills", maps.empty() ? "" : "; ", + static_cast(address), static_cast(rd.Width), rd.Height, + int(rd.Format), + t->layout_guessed ? "guessed" : t->layout_from_xg ? "XG" : t->layout_known ? "viewed" : "none", + t->layout.mode, t->resource->shader_views(), static_cast(t->fills)); + maps += text; + } + if (!maps.empty()) std::fprintf(stderr, "[rt] d3d12: title textures mapped: %s\n", maps.c_str()); + if (s.passes) { + std::fprintf(stderr, + "[rt] d3d12: title texture refresh: %llu passes, %llu XG-written ranges, %llu textures " + "checked (%.1f MiB read for hashes), %llu changed, %llu deferred, %.1f MiB filled (%.2f MiB a " + "pass on average, %.2f MiB at most)\n", + static_cast(s.passes), static_cast(s.written_ranges), + static_cast(s.checked), + double(s.hashed) / 1048576.0, static_cast(s.changed), + static_cast(s.deferred), double(s.filled_bytes) / 1048576.0, + double(s.filled_bytes) / 1048576.0 / double(s.passes), double(s.max_pass_bytes) / 1048576.0); + const double ms_per_ns_per_pass = 1e-6 / double(s.passes); + std::fprintf(stderr, "[rt] title texture hash time %.3f ms/pass; refresh total %.3f ms/pass\n", + double(s.hash_ns) * ms_per_ns_per_pass, double(s.refresh_ns) * ms_per_ns_per_pass); + s.passes = s.checked = s.hashed = s.changed = s.deferred = s.filled_bytes = s.max_pass_bytes = 0; + s.hash_ns = s.refresh_ns = 0; + s.written_ranges = 0; + } + } + +public: void own(const OwnedRuntime& owned) { owned_ = owned; } void set_outer(IUnknown* outer) { outer_ = outer; } @@ -6108,32 +10686,52 @@ class Device final std::fprintf(stderr, "[rt] d3d12: root signature not understood: %s\n", parsed.error.c_str()); return E_INVALIDARG; } - // Two layouts, one per bind point (RootArgumentLayout): graphics keeps pack(), compute takes the console - // layout pack_stage() measured (D3D-448). The signature is refused only when neither can place it. + // Two layouts, one per bind point (RootArgumentLayout): graphics takes the console layout of vertex and + // pixel shaders (s8, one dword per table) where it fits without a spill and keeps pack() otherwise, compute + // the console layout pack_stage() measured (D3D-448). The signature is refused only when neither can place it. const rt::rootsig::PackResult packed = rt::rootsig::pack(parsed.sig); + const rt::rootsig::StagePackResult pixel = rt::rootsig::pack_stage(parsed.sig, rt::rootsig::Stage::Pixel); const rt::rootsig::StagePackResult compute = rt::rootsig::pack_stage(parsed.sig, rt::rootsig::Stage::Compute); - if (!packed.ok && !compute.ok) { + if (!pixel.ok && packed.ok) { + static std::atomic kept{0}; + const unsigned n = ++kept; + if (n == 1 || (n & (n - 1)) == 0) + std::fprintf(stderr, "[rt] d3d12: root signature keeps the s0 graphics layout: %s (%u so far)\n", + pixel.error.c_str(), n); + } + const bool graphics_ok = pixel.ok || packed.ok; + if (!graphics_ok && !compute.ok) { std::fprintf(stderr, "[rt] d3d12: root signature refused: %s (compute: %s)\n", packed.error.c_str(), compute.error.c_str()); return E_INVALIDARG; } - if (!packed.ok) + if (!graphics_ok) std::fprintf(stderr, "[rt] d3d12: root signature usable for compute only: %s\n", packed.error.c_str()); if (!compute.ok) std::fprintf(stderr, "[rt] d3d12: root signature usable for graphics only: %s\n", compute.error.c_str()); RootArgumentLayout layout; layout.flags = parsed.sig.flags; - layout.graphics_ok = packed.ok; + layout.graphics_console = pixel.ok; + layout.graphics_ok = graphics_ok; layout.compute_ok = compute.ok; + if (compute.ok && !compute.spill_dwords) layout.compute_arguments_end = compute.end_sgpr; + // Vertex, pixel and geometry shaders share the s8 layout and one user-data block (a non-compute stage + // refuses a spill, so pixel.ok means every argument is inline). + if (pixel.ok) layout.graphics_arguments_end = pixel.end_sgpr; for (std::size_t i = 0; i < parsed.sig.params.size(); ++i) { std::uint32_t first = UINT32_MAX; - for (std::uint32_t d = 0; packed.ok && d < packed.dword_count; ++d) - if (packed.provenance[d].param_index == i) { - first = d; - break; - } + if (pixel.ok) { + first = pixel.first_sgpr[i]; + } else { + for (std::uint32_t d = 0; packed.ok && d < packed.dword_count; ++d) + if (packed.provenance[d].param_index == i) { + first = d; + break; + } + } layout.parameters.push_back({parsed.sig.params[i].type, first, parsed.sig.params[i].num_values, - compute.ok ? compute.first_sgpr[i] : rt::rootsig::kNoSgpr}); + compute.ok ? compute.first_sgpr[i] : rt::rootsig::kNoSgpr, + table_view_descriptors(parsed.sig.params[i])}); } register_static_samplers(parsed.sig); auto* signature = new RootSignature( @@ -6152,11 +10750,11 @@ class Device final if (const HRESULT hr = check_cached_pso(state_.pso_identity, key, desc->CachedPSO); FAILED(hr)) return hr; auto* pipeline = new PipelineState(state_); pipeline->attach_device(identity()); + pipeline->set_cache_key(std::move(key)); if (const HRESULT hr = pipeline->create_compute(*desc); FAILED(hr)) { pipeline->Release(); return hr; } - pipeline->set_cache_key(std::move(key)); return hand_out(pipeline, riid, out); } @@ -6169,11 +10767,11 @@ class Device final if (const HRESULT hr = check_cached_pso(state_.pso_identity, key, desc->CachedPSO); FAILED(hr)) return hr; auto* pipeline = new PipelineState(state_); pipeline->attach_device(identity()); + pipeline->set_cache_key(std::move(key)); if (const HRESULT hr = pipeline->create_graphics(*desc); FAILED(hr)) { pipeline->Release(); return hr; } - pipeline->set_cache_key(std::move(key)); return hand_out(pipeline, riid, out); } @@ -6259,11 +10857,39 @@ class Device final HRESULT STDMETHODCALLTYPE CreatePipelineState(const D3D12_PIPELINE_STATE_STREAM_DESC* desc, REFIID riid, void** out) override { constexpr const char* method = "ID3D12Device2::CreatePipelineState"; - if (!out) return d3d12_trace::result(method, E_POINTER); + d3d12_trace::stream_refusal = nullptr; + d3d12_xs::used_console_stream = false; + const auto finish = [&](HRESULT hr) { + if (hr == E_NOTIMPL) + d3d12_trace::record("PipelineStream::Refused", d3d12_trace::stream_refusal ? + d3d12_trace::stream_refusal : "other backend state"); + return d3d12_trace::result(method, hr); + }; + if (!out) return finish(E_POINTER); *out = nullptr; - if (!desc) return d3d12_trace::result(method, E_INVALIDARG); + if (!desc) return finish(E_INVALIDARG); PipelineStream stream; - if (const HRESULT hr = parse_pipeline_stream(*desc, stream); FAILED(hr)) return d3d12_trace::result(method, hr); + HRESULT parsed = parse_pipeline_stream(*desc, stream); + // A stream the PC reading refuses, or leaves with an AS and no MS (no valid PC stream), is read again with the + // console's numbering (parse_pipeline_stream), and that reading is taken when it holds a mesh shader (its 24) + // and no AS. A stream the PC reading accepts as valid is never read differently. LEONIDA_XS_STREAM_ENUM=pc + // keeps the PC reading alone (such PSOs are then refused, as before). + if ((FAILED(parsed) || (stream.as.pShaderBytecode && !stream.ms.pShaderBytecode)) && + console_stream_enum_enabled()) { + const char* pc_reason = d3d12_trace::stream_refusal; + PipelineStream console; + if (SUCCEEDED(parse_pipeline_stream(*desc, console, true)) && !console.as.pShaderBytecode && + is_mesh_container(console.ms)) { + log_once("console pipeline stream: type 24 contains a mesh shader; DXIL kind", 13); + d3d12_xs::used_console_stream = true; + d3d12_trace::stream_refusal = nullptr; + stream = console; + parsed = S_OK; + } else { + d3d12_trace::stream_refusal = pc_reason; + } + } + if (FAILED(parsed)) return finish(parsed); auto* pipeline = new PipelineState(state_); pipeline->attach_device(identity()); const HRESULT hr = stream.has_cs ? pipeline->create_compute(stream.compute) @@ -6271,9 +10897,11 @@ class Device final stream.back_masks ? &stream.back_stencil : nullptr); if (FAILED(hr)) { pipeline->Release(); - return d3d12_trace::result(method, hr); + return finish(hr); } - return d3d12_trace::result(method, hand_out(pipeline, riid, out)); + const HRESULT result = hand_out(pipeline, riid, out); + if (SUCCEEDED(result) && stream.ms.pShaderBytecode) d3d12_trace::record("PipelineStream::Mesh", "accepted"); + return finish(result); } UINT STDMETHODCALLTYPE GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE) override { @@ -6334,7 +10962,13 @@ class Device final const bool typed_bgra8_listed = r && !typed_rgba8 && rgba8_any_order(rd.Format) && r->has_castable_formats(); if (rd.Format == DXGI_FORMAT_A8_UNORM || (desc && desc->Format == DXGI_FORMAT_A8_UNORM)) { - view = {}; + // Only an A8 render target stored as VK_FORMAT_A8_UNORM_KHR takes an RTV, in its own format: the + // attachment view is the image's. + const bool plain_2d = !desc || desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2D || + desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2DARRAY; + if (!r || !r->a8_as_alpha() || rd.Format != DXGI_FORMAT_A8_UNORM || !plain_2d || + (desc && desc->Format != DXGI_FORMAT_UNKNOWN && desc->Format != DXGI_FORMAT_A8_UNORM)) + view = {}; } else if (r && r->uint_backed() == VK_FORMAT_A1R5G5B5_UNORM_PACK16) { // An R16_UINT-backed B5G5R5A1 UAV texture (Format::uint_backed) renders through an A1R5G5B5 view, in // its own format only. @@ -6342,13 +10976,17 @@ class Device final view = {}; else view.format = static_cast(VK_FORMAT_A1R5G5B5_UNORM_PACK16); - } else if (r && (r->uint_backed() == VK_FORMAT_R8G8B8A8_SRGB || r->uint_backed() == VK_FORMAT_B8G8R8A8_SRGB)) { - // A UNORM-backed 8-bit sRGB UAV texture renders through an sRGB view (encoding as the host does), in its - // own format only. - if (desc && desc->Format != DXGI_FORMAT_UNKNOWN && desc->Format != rd.Format) - view = {}; + } else if (r && (r->uint_backed() == VK_FORMAT_R8G8B8A8_SRGB || + r->uint_backed() == VK_FORMAT_B8G8R8A8_SRGB)) { + // A UNORM-backed sRGB UAV texture (texture_format) renders and clears through its sRGB view, or + // through the UNORM twin it is made of when the view asks for that (the console allows the cast). + const VkFormat wanted = desc && desc->Format != DXGI_FORMAT_UNKNOWN + ? vulkan_format(desc->Format, false).format + : r->uint_backed(); + if (wanted == r->uint_backed() || wanted == r->format()) + view.format = static_cast(wanted); else - view.format = static_cast(r->uint_backed()); + view = {}; } else if (rd.Format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP || (desc && desc->Format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP)) { if (rd.Format != DXGI_FORMAT_R9G9B9E5_SHAREDEXP || !(rd.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) || @@ -6364,7 +11002,8 @@ class Device final (r && r->has_view_format_list() && r->allows_view_format(vulkan_format(requested, false).format)); if (typeless_color || cast_listed || - (requested != rd.Format && listed && rd.Format == DXGI_FORMAT_R8G8B8A8_UNORM)) { + (requested != rd.Format && listed && + (rd.Format == DXGI_FORMAT_R8G8B8A8_UNORM || rd.Format == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB))) { const bool msaa = rd.SampleDesc.Count > 1; const bool plain_1d = !msaa && desc && desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE1D; const bool array_1d = !msaa && desc && desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE1DARRAY; @@ -6466,9 +11105,10 @@ class Device final ++s; s_at = 0; } else { - std::memmove(reinterpret_cast(destinations[d].ptr) + std::size_t(d_at++) * kDescriptorSize, + std::memmove(reinterpret_cast(destinations[d].ptr) + std::size_t(d_at) * kDescriptorSize, reinterpret_cast(sources[s].ptr) + std::size_t(s_at++) * kDescriptorSize, kDescriptorSize); + state_.probe_api(destinations[d].ptr + SIZE_T(d_at++) * kDescriptorSize, 1); // LOCAL DIAGNOSTIC } } } @@ -6479,6 +11119,8 @@ class Device final if (!destination.ptr || !source.ptr) return; std::memmove(reinterpret_cast(destination.ptr), reinterpret_cast(source.ptr), std::size_t(count) * kDescriptorSize); + state_.probe_api(destination.ptr, count); // LOCAL DIAGNOSTIC + state_.probe_view("CopyDescriptorsSimple", destination.ptr, count); } // A constant-buffer view is a 16-byte GFX10 raw buffer V# in the first half of the slot (zeros in the rest). @@ -6487,6 +11129,7 @@ class Device final D3D12_CPU_DESCRIPTOR_HANDLE destination) override { d3d12_trace::record("ID3D12Device::CreateConstantBufferView"); if (!destination.ptr) return; + ProbeApiWrite probe_note{state_, destination.ptr, 1, "CreateConstantBufferView"}; // LOCAL DIAGNOSTIC std::memset(reinterpret_cast(destination.ptr), 0, kDescriptorSize); if (!desc || !desc->BufferLocation || !desc->SizeInBytes) return; leonida::gfx10::Buffer buffer{}; @@ -6495,8 +11138,112 @@ class Device final buffer.num_records = desc->SizeInBytes; buffer.format = leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT); buffer.oob_select = leonida::gfx10::OobSelect::raw; + buffer.address = vsharp_address(buffer.address, desc->SizeInBytes); + leonida::gfx10::BufferWords words = leonida::gfx10::encode(buffer); + // The console's constant-buffer V# is a table of 16-byte rows: the title's own inline form of this descriptor + // (it writes one itself instead of calling here, depending on a device flag) is {base, stride 16, records + // (size + 15) / 16, fourth word 0x0002403C} (docs/re/notes/gfxgeom.md), and its shaders index rows through + // the stride: the batched Scaleform vertex shader reads its X and Y transform rows as base + index * stride. + // With the raw form (stride 0) both rows are the same 16 bytes and every batched triangle collapses onto the + // line x = y. LEONIDA_CBV_RAW=1 restores the raw form. + static const bool console_form = [] { + wchar_t value[2]{}; + return !(GetEnvironmentVariableW(L"LEONIDA_CBV_RAW", value, 2) == 1 && value[0] == L'1'); + }(); + if (console_form) { + words[1] = (words[1] & 0xFFFFu) | (16u << 16); + words[2] = (desc->SizeInBytes + 15) / 16; + words[3] = 0x0002403Cu; + } + std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); + { // LOCAL DIAGNOSTIC: the CBVs the title makes, where they go and what V# they get + static std::atomic made{0}; + const std::uint64_t n = ++made; + if (n <= 8 || n % 600 == 0 || n % 600 == 1) + std::fprintf(stderr, "[rt] fsdraw: CBV #%llu dest 0x%llx location 0x%llx size %u -> V# base 0x%llx [%s]\n", + static_cast(n), static_cast(destination.ptr), + static_cast(desc->BufferLocation), desc->SizeInBytes, + static_cast(buffer.address), + leonida::fsdraw::hex_words(words.data(), words.size()).c_str()); + } + leonida::fsdraw::note_cbv(buffer.address, desc->BufferLocation, desc->SizeInBytes); // LOCAL DIAGNOSTIC + } + + // A buffer shader-resource view of the `width` bytes at console VA `base_va`: a 16-byte GFX10 V# in the first + // half of the slot (raw, structured, or typed). False, the slot left as it was (zeros), for a view the layer + // cannot write. A resource's VA, or memory the title placed itself (Xbox device slot 70). + bool write_buffer_srv(UINT64 base_va, UINT64 width, const D3D12_SHADER_RESOURCE_VIEW_DESC* desc, + D3D12_CPU_DESCRIPTOR_HANDLE destination, bool placed = false) { + if (!base_va || !desc->Buffer.NumElements || (desc->Buffer.Flags & ~D3D12_BUFFER_SRV_FLAG_RAW)) return false; + leonida::gfx10::Buffer buffer{}; + if (desc->Buffer.Flags & D3D12_BUFFER_SRV_FLAG_RAW) { + if (desc->Format != DXGI_FORMAT_R32_TYPELESS || desc->Buffer.StructureByteStride != 0) return false; + if (desc->Buffer.FirstElement > width / 4) return false; + const UINT64 byte_off = desc->Buffer.FirstElement * 4; + const UINT64 byte_size = UINT64(desc->Buffer.NumElements) * 4; + if (byte_size > width - byte_off || byte_size > UINT32_MAX) return false; + buffer.address = base_va + byte_off; + buffer.stride = 0; + buffer.num_records = std::uint32_t(byte_size); + buffer.format = leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT); + buffer.oob_select = leonida::gfx10::OobSelect::raw; + } else if (desc->Buffer.StructureByteStride != 0) { + if (desc->Format != DXGI_FORMAT_UNKNOWN || desc->Buffer.StructureByteStride > 16383) return false; + const UINT64 stride = desc->Buffer.StructureByteStride; + if (desc->Buffer.FirstElement > width / stride) return false; + const UINT64 byte_off = desc->Buffer.FirstElement * stride; + const UINT64 byte_size = UINT64(desc->Buffer.NumElements) * stride; + if (byte_size > width - byte_off) return false; + buffer.address = base_va + byte_off; + buffer.stride = std::uint32_t(stride); + buffer.num_records = desc->Buffer.NumElements; + buffer.format = leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT); + // Check the field offset against the record stride, as for structured UAVs (five-star-recomp 3d287ab). + buffer.oob_select = leonida::gfx10::OobSelect::structured_with_offset; + } else { + const Format fmt = vulkan_format(desc->Format, false); + if (fmt.format == VK_FORMAT_UNDEFINED || fmt.typeless || !(fmt.aspects & VK_IMAGE_ASPECT_COLOR_BIT)) { + log_once("buffer SRV format not supported:", int(desc->Format)); + return false; + } + const VkFormat named = fmt.rgb96 ? rgb96_named_format(fmt.format) : fmt.format; + const std::uint32_t code = leonida::gfx10::format_from_vulkan(named); + const leonida::BlockFormat bf = footprint_block(fmt, VK_IMAGE_ASPECT_COLOR_BIT); + if (!code || bf.block != 1 || !bf.bytes || bf.bytes > 16383) { + log_once("buffer SRV format not supported:", int(desc->Format)); + return false; + } + const UINT64 stride = bf.bytes; + if (desc->Buffer.FirstElement > width / stride) return false; + const UINT64 byte_off = desc->Buffer.FirstElement * stride; + const UINT64 byte_size = UINT64(desc->Buffer.NumElements) * stride; + if (byte_size > width - byte_off) return false; + buffer.address = base_va + byte_off; + buffer.stride = std::uint32_t(stride); + buffer.num_records = desc->Buffer.NumElements; + buffer.format = code; + const leonida::gfx10::Swizzle channels = leonida::gfx10::format_swizzle(named); + for (unsigned i = 0; i < 4; ++i) { + const UINT from = D3D12_DECODE_SHADER_4_COMPONENT_MAPPING(i, desc->Shader4ComponentMapping); + buffer.swizzle[i] = from < 4 ? channels[from] + : from == D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_0 + ? leonida::gfx10::select_zero + : leonida::gfx10::select_one; + } + buffer.oob_select = leonida::gfx10::OobSelect::structured; + } + const auto bytes = std::uint64_t(buffer.num_records) * (buffer.stride ? buffer.stride : 1); + const auto copy = placed ? state_.geometry_va(buffer.address, bytes, true) : 0; + if (copy) { + // CPU readers and descriptor copies retain the guest address. The heap's shader mirror + // rewrites it at the original slot, just as it does for a descriptor written by the title. + if (!state_.has_console_descriptor_copy(destination.ptr)) buffer.address = copy; + } else { + buffer.address = vsharp_address(buffer.address, bytes); + } const leonida::gfx10::BufferWords words = leonida::gfx10::encode(buffer); std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); + return true; } // A shader-resource view of a texture is a T# in the slot (docs section 3.4): the shader loads those eight @@ -6508,6 +11255,7 @@ class Device final d3d12_trace::record("ID3D12Device::CreateShaderResourceView"); using leonida::gfx10::ImageType; if (!destination.ptr) return; + ProbeApiWrite probe_note{state_, destination.ptr, 1, "CreateShaderResourceView"}; // LOCAL DIAGNOSTIC std::memset(reinterpret_cast(destination.ptr), 0, kDescriptorSize); const Resource* r = Resource::from(resource); if (!r) { @@ -6518,7 +11266,7 @@ class Device final log_once("shader-resource view denied by resource flags; format", int(r->desc().Format)); return; } - if (!r->image()) { + if (!r->descriptor_image()) { if (!desc) { log_once("buffer SRV requires a description; width", int(r->desc().Width)); return; @@ -6527,67 +11275,7 @@ class Device final log_once("shader-resource view dimension not supported for buffer:", desc->ViewDimension); return; } - const UINT64 base_va = const_cast(r)->GetGPUVirtualAddress(); - const UINT64 width = r->desc().Width; - if (!base_va || !desc->Buffer.NumElements || (desc->Buffer.Flags & ~D3D12_BUFFER_SRV_FLAG_RAW)) return; - leonida::gfx10::Buffer buffer{}; - if (desc->Buffer.Flags & D3D12_BUFFER_SRV_FLAG_RAW) { - if (desc->Format != DXGI_FORMAT_R32_TYPELESS || desc->Buffer.StructureByteStride != 0) return; - if (desc->Buffer.FirstElement > width / 4) return; - const UINT64 byte_off = desc->Buffer.FirstElement * 4; - const UINT64 byte_size = UINT64(desc->Buffer.NumElements) * 4; - if (byte_size > width - byte_off || byte_size > UINT32_MAX) return; - buffer.address = base_va + byte_off; - buffer.stride = 0; - buffer.num_records = std::uint32_t(byte_size); - buffer.format = leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT); - buffer.oob_select = leonida::gfx10::OobSelect::raw; - } else if (desc->Buffer.StructureByteStride != 0) { - if (desc->Format != DXGI_FORMAT_UNKNOWN || desc->Buffer.StructureByteStride > 16383) return; - const UINT64 stride = desc->Buffer.StructureByteStride; - if (desc->Buffer.FirstElement > width / stride) return; - const UINT64 byte_off = desc->Buffer.FirstElement * stride; - const UINT64 byte_size = UINT64(desc->Buffer.NumElements) * stride; - if (byte_size > width - byte_off) return; - buffer.address = base_va + byte_off; - buffer.stride = std::uint32_t(stride); - buffer.num_records = desc->Buffer.NumElements; - buffer.format = leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT); - buffer.oob_select = leonida::gfx10::OobSelect::structured; - } else { - const Format fmt = vulkan_format(desc->Format, false); - if (fmt.format == VK_FORMAT_UNDEFINED || fmt.typeless || !(fmt.aspects & VK_IMAGE_ASPECT_COLOR_BIT)) { - log_once("buffer SRV format not supported:", int(desc->Format)); - return; - } - const VkFormat named = fmt.rgb96 ? rgb96_named_format(fmt.format) : fmt.format; - const std::uint32_t code = leonida::gfx10::format_from_vulkan(named); - const leonida::BlockFormat bf = footprint_block(fmt, VK_IMAGE_ASPECT_COLOR_BIT); - if (!code || bf.block != 1 || !bf.bytes || bf.bytes > 16383) { - log_once("buffer SRV format not supported:", int(desc->Format)); - return; - } - const UINT64 stride = bf.bytes; - if (desc->Buffer.FirstElement > width / stride) return; - const UINT64 byte_off = desc->Buffer.FirstElement * stride; - const UINT64 byte_size = UINT64(desc->Buffer.NumElements) * stride; - if (byte_size > width - byte_off) return; - buffer.address = base_va + byte_off; - buffer.stride = std::uint32_t(stride); - buffer.num_records = desc->Buffer.NumElements; - buffer.format = code; - const leonida::gfx10::Swizzle channels = leonida::gfx10::format_swizzle(named); - for (unsigned i = 0; i < 4; ++i) { - const UINT from = D3D12_DECODE_SHADER_4_COMPONENT_MAPPING(i, desc->Shader4ComponentMapping); - buffer.swizzle[i] = from < 4 ? channels[from] - : from == D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_0 - ? leonida::gfx10::select_zero - : leonida::gfx10::select_one; - } - buffer.oob_select = leonida::gfx10::OobSelect::structured; - } - const leonida::gfx10::BufferWords words = leonida::gfx10::encode(buffer); - std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); + write_buffer_srv(const_cast(r)->GetGPUVirtualAddress(), r->desc().Width, desc, destination); return; } TextureView view{}; @@ -6665,6 +11353,19 @@ class Device final } } write_image_descriptor(*r, view, destination, false); + { // LOCAL DIAGNOSTIC: the texture SRVs the title makes, where they go and the T# they get + static std::atomic made{0}; + const std::uint64_t n = ++made; + if (n <= 8 || n % 600 == 0 || n % 600 == 1) { + std::uint32_t w[8]; + std::memcpy(w, reinterpret_cast(destination.ptr), sizeof w); + std::fprintf(stderr, "[rt] fsdraw: SRV #%llu dest 0x%llx resource 0x%llx format %d dim %d -> [%s] bindless %s\n", + static_cast(n), static_cast(destination.ptr), + static_cast(r->id()), desc ? int(desc->Format) : -1, + desc ? int(desc->ViewDimension) : -1, leonida::fsdraw::hex_words(w, 8).c_str(), + leonida::fsdraw::has_tsharp(w) ? "yes" : "NO"); + } + } } // An unordered-access view of a buffer is a V# in the slot (docs section 3.4): the shader loads those four dwords @@ -6688,6 +11389,35 @@ class Device final desc ? int(desc->ViewDimension) : -1); return; } + // D3D12: a counter belongs to a structured view and sits in a buffer that allows unordered access, 4096-byte + // aligned with room for its 4 bytes; with no counter resource the offset is 0. + if (counter || desc->Buffer.CounterOffsetInBytes) { + const Resource* c = counter ? Resource::from(counter) : nullptr; + const bool valid = c && !c->image() && desc->Format == DXGI_FORMAT_UNKNOWN && + (c->desc().Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) && + !(desc->Buffer.CounterOffsetInBytes % D3D12_UAV_COUNTER_PLACEMENT_ALIGNMENT) && + UINT64(desc->Buffer.CounterOffsetInBytes) + 4 <= c->desc().Width; + if (!valid) { + log_once("unordered-access view counter refused (a structured view, a buffer that allows unordered " + "access, a 4096-aligned offset inside it); offset", + int(desc->Buffer.CounterOffsetInBytes)); + return; + } + } + const UINT64 va = resource->GetGPUVirtualAddress(); + const UINT64 counter_va = counter ? counter->GetGPUVirtualAddress() : 0; + if (!va || (counter && !counter_va)) return; + write_buffer_uav_at(va, rd.Width, desc, counter ? counter_va + desc->Buffer.CounterOffsetInBytes : 0, + destination); + } + + // A buffer unordered-access view of the `width` bytes at console VA `va` (a resource's, or memory the title + // placed itself: Xbox device slot 71), with its counter's V# when `counter_va` is not 0. False, the slot left as + // it was (zeros), for a view the layer cannot write. + bool write_buffer_uav_at(UINT64 va, UINT64 width, const D3D12_UNORDERED_ACCESS_VIEW_DESC* desc, UINT64 counter_va, + D3D12_CPU_DESCRIPTOR_HANDLE destination) { + namespace g = leonida::gfx10; + if (!va || !desc || desc->ViewDimension != D3D12_UAV_DIMENSION_BUFFER) return false; const D3D12_BUFFER_UAV& view = desc->Buffer; const bool structured = desc->Format == DXGI_FORMAT_UNKNOWN; const bool raw = desc->Format == DXGI_FORMAT_R32_TYPELESS && (view.Flags & D3D12_BUFFER_UAV_FLAG_RAW); @@ -6704,37 +11434,19 @@ class Device final format_code = layout ? g::format_from_vulkan(mapped.format) : 0; if (!format_code || format_code >= 128) { // the V#'s FORMAT is 7 bits log_once("typed buffer unordered-access view format not supported; format", int(desc->Format)); - return; + return false; } element_bytes = layout->bytes; channels = g::format_swizzle(mapped.format); } const UINT64 unit = structured ? view.StructureByteStride : typed ? element_bytes : 4; - if (!unit || unit > 0x3fff || view.FirstElement > rd.Width / unit || - (UINT64(view.FirstElement) + view.NumElements) > rd.Width / unit || + if (!unit || unit > 0x3fff || view.FirstElement > width / unit || + (UINT64(view.FirstElement) + view.NumElements) > width / unit || UINT64(view.NumElements) * (structured || typed ? 1 : 4) > ~0u) { log_once("unordered-access view of a buffer outside the resource or with a bad stride; elements", int(view.NumElements)); - return; - } - // D3D12: a counter belongs to a structured view and sits in a buffer that allows unordered access, 4096-byte - // aligned with room for its 4 bytes; with no counter resource the offset is 0. - if (counter || view.CounterOffsetInBytes) { - const Resource* c = counter ? Resource::from(counter) : nullptr; - const bool valid = c && !c->image() && structured && - (c->desc().Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) && - !(view.CounterOffsetInBytes % D3D12_UAV_COUNTER_PLACEMENT_ALIGNMENT) && - UINT64(view.CounterOffsetInBytes) + 4 <= c->desc().Width; - if (!valid) { - log_once("unordered-access view counter refused (a structured view, a buffer that allows unordered " - "access, a 4096-aligned offset inside it); offset", - int(view.CounterOffsetInBytes)); - return; - } + return false; } - const UINT64 va = resource->GetGPUVirtualAddress(); - const UINT64 counter_va = counter ? counter->GetGPUVirtualAddress() : 0; - if (!va || (counter && !counter_va)) return; g::Buffer buffer{}; buffer.address = va + view.FirstElement * unit; buffer.stride = structured || typed ? std::uint32_t(unit) : 0; @@ -6743,17 +11455,20 @@ class Device final buffer.swizzle = channels; buffer.oob_select = typed ? g::OobSelect::structured : structured ? g::OobSelect::structured_with_offset : g::OobSelect::raw; + buffer.address = vsharp_address(buffer.address, + std::uint64_t(buffer.num_records) * (buffer.stride ? buffer.stride : 1)); const g::BufferWords words = g::encode(buffer); std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); - if (counter) { + if (counter_va) { g::Buffer counter_buffer{}; - counter_buffer.address = counter_va + view.CounterOffsetInBytes; + counter_buffer.address = vsharp_address(counter_va, 4); counter_buffer.num_records = 4; counter_buffer.oob_select = g::OobSelect::raw; const g::BufferWords counter_words = g::encode(counter_buffer); std::memcpy(reinterpret_cast(destination.ptr) + sizeof(words), counter_words.data(), sizeof(counter_words)); } + return true; } // An unordered-access view of a texture is a T# too, of one mip; set 0 also holds it as a storage image. @@ -6762,6 +11477,7 @@ class Device final D3D12_CPU_DESCRIPTOR_HANDLE destination) override { d3d12_trace::record("ID3D12Device::CreateUnorderedAccessView"); if (!destination.ptr) return; + ProbeApiWrite probe_note{state_, destination.ptr, 1, "CreateUnorderedAccessView"}; // LOCAL DIAGNOSTIC std::memset(reinterpret_cast(destination.ptr), 0, kDescriptorSize); const Resource* r = Resource::from(resource); if (!r) { @@ -7218,18 +11934,92 @@ class Device final } } + // TitleVaAliases::want_buffer: a vertex or index view names `va` in the title's own memory and no buffer covers + // it. A buffer over the 64 KiB-aligned committed pages around it is made the way slot 133 makes one (the pages + // imported, or a shadow copied from them before every submission) and kept until the device goes, up to + // LEONIDA_TITLE_BUFFERS_MB (512 by default). + void make_title_buffer(std::uint64_t va, std::uint64_t bytes) { + if (!state_.context) return; + static const bool check_size = [] { + wchar_t flag[2]{}; + return !(GetEnvironmentVariableW(L"LEONIDA_TITLE_BUFFER_COVERAGE", flag, 2) == 1 && flag[0] == L'0'); + }(); + const auto covered = [&] { + return state_.context->knows_buffer_va(va, check_size ? bytes : 1); + }; + if (covered()) return; + std::uint64_t lo = 0, hi = 0; + if (!leonida::title_va_aliases().title_memory(va, lo, hi)) return; + std::lock_guard lock(title_buffer_mutex_); + if (covered()) return; + static const std::uint64_t cap = [] { + char text[16] = {}; + size_t length = 0; + const bool set = getenv_s(&length, text, "LEONIDA_TITLE_BUFFERS_MB") == 0 && length > 1; + return (set ? std::strtoull(text, nullptr, 10) : 512ull) << 20; + }(); + constexpr std::uint64_t align = 65536, most = 64ull << 20; + const std::uint64_t start = std::max(va & ~(align - 1), lo); + std::uint64_t end = std::min(hi, (va + std::clamp(bytes, 1, most) + align - 1) & ~(align - 1)); + for (std::uint64_t at = start; at < end;) { // the committed, readable part only + MEMORY_BASIC_INFORMATION region{}; + if (!VirtualQuery(reinterpret_cast(static_cast(at)), ®ion, sizeof(region)) || + region.State != MEM_COMMIT || !region.Protect || (region.Protect & (PAGE_NOACCESS | PAGE_GUARD))) { + end = at; + break; + } + at = reinterpret_cast(region.BaseAddress) + region.RegionSize; + } + // If the request runs into an uncommitted page or the size limit, reuse its backed prefix. + if (end <= va || (check_size && state_.context->knows_buffer_va(va, end - va))) return; + if (title_buffer_bytes_ + (end - start) > cap) { + log_once("vertex or index data in the title's memory is past LEONIDA_TITLE_BUFFERS_MB, left unresolved; MiB so far:", + int(title_buffer_bytes_ >> 20)); + return; + } + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = end - start; + desc.Height = 1; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + ID3D12Resource* made = nullptr; + const HRESULT hr = create_at_host_address(reinterpret_cast(static_cast(start)), desc, + 0xFFFFFFFFu, __uuidof(ID3D12Resource), + reinterpret_cast(&made)); + if (FAILED(hr) || !made) { + log_once("a buffer over the title's memory for a vertex or index view could not be made; HRESULT", int(hr)); + return; + } + title_buffers_.push_back(made); + title_buffer_bytes_ += end - start; + if (title_buffers_.size() <= 8 || !(title_buffers_.size() & (title_buffers_.size() - 1))) + std::fprintf(stderr, + "[rt] d3d12: a %llu KiB buffer over the title's memory at 0x%llx for a vertex or index view " + "at 0x%llx (%zu such buffers, %llu MiB)\n", + static_cast((end - start) >> 10), static_cast(start), + static_cast(va), title_buffers_.size(), + static_cast(title_buffer_bytes_ >> 20)); + } + std::mutex title_buffer_mutex_; + std::vector title_buffers_; // kept: the title's views name their addresses frame after frame + std::uint64_t title_buffer_bytes_ = 0; + HRESULT create_at_host_address(void* address, const D3D12_RESOURCE_DESC& desc, std::uint32_t layout, REFIID riid, void** out) { constexpr auto method = "Xbox CreatePlacedResourceX (device slot 133)"; if (desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) { - // A texture is not placed on the title's pages yet: it gets an ordinary committed DEFAULT texture of the - // same description, as slot 76 gives one, so the title has its resource instead of asserting (found in - // review). Its GPU VA is still the title's address: the console answers a placed texture's + // A texture cannot be placed on the title's pages (the PC GPU does not sample the console layout): it gets + // a committed texture of the same description, so the title has its resource instead of asserting (found + // in review). Its GPU VA is still the title's address: the console answers a placed texture's // GetGPUVirtualAddress with the address the title placed it at, and a title turns that into the CPU - // pointer it clears the texture through (docs/d3d12_vulkan.md 3.3). What the title writes at `address` - // does not reach the image yet. + // pointer it clears the texture through (docs/d3d12_vulkan.md 3.3). It is registered by that address + // (register_title_texture): slot-70 views of the address are of its image, which, unless the GPU writes + // it, is filled from the title's memory with the views' layout (TitleTexture). log_once("a title-placed texture (device slot 133) is a committed texture whose GPU VA is the title " - "address; its pixels do not alias the title's pages yet; dimension", + "address, filled from the title's pages unless the GPU writes it; dimension", int(desc.Dimension)); // The title's barrier layout (slot 133's third argument, measured by @dracbat) is checked against the // description as CreateCommittedResource checks a state; one it refuses (or UNDEFINED) gives COMMON, so @@ -7237,17 +12027,74 @@ class Device final // uses it moves it to that command's layout (vulkan_replay.h, initialize), as for every texture here. const D3D12_HEAP_PROPERTIES fallback{D3D12_HEAP_TYPE_DEFAULT}; const D3D12_RESOURCE_STATES initial = state_for_barrier_layout(layout); - HRESULT hr = create_committed_validated(nullptr, &fallback, D3D12_HEAP_FLAG_NONE, &desc, initial, nullptr, - 0, nullptr, riid, out); + // The console lets a depth-stencil target allow unordered access too; no PC GPU stores to a depth + // format, so the texture is made without it (as slot 25 and slot 76 size and make it). Its UAVs then + // write no descriptor. + D3D12_RESOURCE_DESC made = desc; + if ((made.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) && + (made.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { + made.Flags &= ~D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + log_once("a title-placed depth-stencil texture is made without unordered access; format", made.Format); + } + // A texture the GPU never writes holds what the title writes into its memory (XG copies, Map): its image + // is filled from there (TitleTexture), so it is made where host copies reach it (CUSTOM write-back: still + // device-local memory, created with host-transfer usage when the format allows). + const bool gpu_written = (made.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | + D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) || + made.SampleDesc.Count > 1; + const D3D12_HEAP_PROPERTIES host_copied{D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, + D3D12_MEMORY_POOL_L0, 1, 1}; + const D3D12_HEAP_PROPERTIES* heap = gpu_written ? &fallback : &host_copied; + // The title views 32-bit unordered-access targets as R9G9B9E5 (it packs E5 values into them from compute; + // seen in its slot-70 views): castable, so that view exists. Made without the list if Vulkan refuses it. + const bool r32 = made.Format == DXGI_FORMAT_R32_TYPELESS || made.Format == DXGI_FORMAT_R32_FLOAT || + made.Format == DXGI_FORMAT_R32_UINT || made.Format == DXGI_FORMAT_R32_SINT; + const DXGI_FORMAT castable[] = {made.Format, DXGI_FORMAT_R9G9B9E5_SHAREDEXP}; + const UINT32 cast_count = + r32 && (made.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) && made.SampleDesc.Count == 1 ? 2 : 0; + HRESULT hr = create_committed_validated(nullptr, heap, D3D12_HEAP_FLAG_NONE, &made, initial, nullptr, + cast_count, castable, riid, out, TitleImageOrigin::placed); + if (FAILED(hr) && cast_count) + hr = create_committed_validated(nullptr, heap, D3D12_HEAP_FLAG_NONE, &made, initial, nullptr, 0, + nullptr, riid, out, TitleImageOrigin::placed); if (FAILED(hr) && initial != D3D12_RESOURCE_STATE_COMMON) - hr = create_committed_validated(nullptr, &fallback, D3D12_HEAP_FLAG_NONE, &desc, - D3D12_RESOURCE_STATE_COMMON, nullptr, 0, nullptr, riid, out); + hr = create_committed_validated(nullptr, heap, D3D12_HEAP_FLAG_NONE, &made, + D3D12_RESOURCE_STATE_COMMON, nullptr, 0, nullptr, riid, out, TitleImageOrigin::placed); + if (FAILED(hr) && heap != &fallback) { + log_once("a title-placed texture the GPU does not write could not be made on a host-copied heap; " + "format", + made.Format); + hr = create_committed_validated(nullptr, &fallback, D3D12_HEAP_FLAG_NONE, &made, + D3D12_RESOURCE_STATE_COMMON, nullptr, 0, nullptr, riid, out, TitleImageOrigin::placed); + } if (SUCCEEDED(hr) && out && *out) { - // The console answers the texture's GetGPUVirtualAddress with the title's address; without it a - // title that clears the texture through that pointer writes at address 0 (XCL measured this on a - // retail title). The image stays the committed fallback above, so only the address is folded in. - if (auto* texture = Resource::from(static_cast(*out))) - texture->set_title_address(reinterpret_cast(address)); + // The interface handed out is the Resource itself (hand_out); ask it back and tell it its address. + ID3D12Resource* made = nullptr; + if (SUCCEEDED(static_cast(*out)->QueryInterface(__uuidof(ID3D12Resource), + reinterpret_cast(&made))) && made) { + if (auto* texture = Resource::from(made)) { + static const bool distinct = [] { + const char* v = std::getenv("LEONIDA_PLACED_IMAGE_KEYS"); + return !v || std::strcmp(v, "0"); + }(); + texture->place_at_title_address(address, distinct && gpu_written); + register_title_texture(texture, reinterpret_cast(address)); + } + made->Release(); + } + } + if (FAILED(hr)) { + // The title asserts when a texture it places cannot be made: say which one, in full. + static std::atomic logged{0}; + if (logged.fetch_add(1, std::memory_order_relaxed) < 32) + std::fprintf(stderr, + "[rt] d3d12: slot 133 texture not created (hr 0x%08x, layout %u): dim %d format %d " + "%llux%ux%u mips %u samples %u layout %d flags 0x%x at %p\n", + unsigned(hr), unsigned(layout), int(desc.Dimension), int(desc.Format), + static_cast(desc.Width), unsigned(desc.Height), + unsigned(desc.DepthOrArraySize), unsigned(desc.MipLevels), + unsigned(desc.SampleDesc.Count), int(desc.Layout), unsigned(desc.Flags), address); } return d3d12_trace::result(method, hr); } @@ -7265,13 +12112,26 @@ class Device final if (FAILED(hr)) { // The driver would not import these pages: RADV refuses a view of a pagefile-backed section, the form // xmem's physical pages take (found in review on an RX 9070 XT under Wine), and a device without - // VK_EXT_external_memory_host has no import at all. The boot goes on with an ordinary DEFAULT buffer - // of the same description, as #6915's stand-in did: the title gets a resource, but its writes at - // `address` do not reach it. + // VK_EXT_external_memory_host has no import at all; write-combined and uncommitted pages are not tried, + // and some drivers stop importing after a budget (create_shadow_buffer). The title then gets a shadow + // buffer at its VA, brought up to date from its pages before every submission. + resource->Release(); + resource = new Resource(state_, desc, heap, D3D12_HEAP_FLAG_NONE); + resource->attach_device(identity()); + const HRESULT shadow = resource->create_shadow_buffer(address); + if (SUCCEEDED(shadow)) { + log_once("a title-placed buffer (device slot 133) could not import its pages, so it is a shadow " + "copied from them before every submission; HRESULT", + int(hr)); + return d3d12_trace::result(method, hand_out(resource, riid, out)); + } + // No memory for the shadow either: the boot goes on with an ordinary DEFAULT buffer of the same + // description, as #6915's stand-in did. The title gets a resource, but neither its VA nor its writes at + // `address` reach it. resource->Release(); - log_once("a title-placed buffer (device slot 133) could not import its pages, so it is an ordinary buffer " - "the title's writes do not reach; HRESULT", - int(hr)); + log_once("a title-placed buffer (device slot 133) could neither import its pages nor get a shadow, so it " + "is an ordinary buffer the title's writes do not reach; HRESULT", + int(shadow)); const D3D12_HEAP_PROPERTIES fallback{D3D12_HEAP_TYPE_DEFAULT}; return d3d12_trace::result(method, create_committed(&fallback, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, 0, nullptr, riid, out)); @@ -7378,6 +12238,9 @@ class Device final if (out) *out = nullptr; auto* heap = Heap::from(heap_interface); if (!heap || !desc) return d3d12_trace::result(method, E_INVALIDARG); + D3D12_RESOURCE_DESC canonical = *desc; + canonical.Format = pc_format(canonical.Format); // the console's D16S8 family as D24S8 + desc = &canonical; if (heap->host_address()) { // An existing heap is not an arena range, and the placed path addresses resources by arena offset. log_once("a placed resource in an existing heap (OpenExistingHeapFromAddress) is not supported yet; " @@ -7476,7 +12339,7 @@ class Device final hr = E_INVALIDARG; } else { std::vector cast_formats; - hr = castable_view_formats(format, castable_count, castable, cast_formats); + hr = castable_view_formats(format, desc->Format, castable_count, castable, cast_formats); if (SUCCEEDED(hr)) hr = resource->create_texture(format, cast_formats); if (SUCCEEDED(hr)) resource->keep_castable_formats(castable_count, castable); } @@ -8024,7 +12887,8 @@ class Device final if (fs->Format == DXGI_FORMAT_A8_UNORM) { if (optimal & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) { - fs->Support1 = D3D12_FORMAT_SUPPORT1_TEXTURE2D | D3D12_FORMAT_SUPPORT1_TEXTURECUBE | + fs->Support1 = D3D12_FORMAT_SUPPORT1_TEXTURE1D | D3D12_FORMAT_SUPPORT1_TEXTURE2D | + D3D12_FORMAT_SUPPORT1_TEXTURE3D | D3D12_FORMAT_SUPPORT1_TEXTURECUBE | D3D12_FORMAT_SUPPORT1_SHADER_LOAD; if (optimal & VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT) fs->Support1 |= D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE | D3D12_FORMAT_SUPPORT1_SHADER_GATHER; @@ -8036,6 +12900,9 @@ class Device final VK_IMAGE_TILING_OPTIMAL, usage, 0, &limits) == VK_SUCCESS && limits.maxMipLevels > 1) fs->Support1 |= D3D12_FORMAT_SUPPORT1_MIP; + // Render targets are stored as VK_FORMAT_A8_UNORM_KHR, which the device checked can blend. + if (state_.info.a8_render_target) + fs->Support1 |= D3D12_FORMAT_SUPPORT1_RENDER_TARGET | D3D12_FORMAT_SUPPORT1_BLENDABLE; } return d3d12_trace::result(method, S_OK); } @@ -8387,6 +13254,7 @@ class Device final bool failed = count && !descs; for (UINT i = 0; i < count; ++i) { const D3D12_RESOURCE_ALLOCATION_INFO one = failed ? kInvalidAllocation : allocation(get(i)); + if (!failed && one.SizeInBytes == UINT64_MAX) log_refused_allocation(get(i)); failed = failed || one.SizeInBytes == UINT64_MAX; if (failed) { if (each) each[i] = {UINT64_MAX, one.Alignment, UINT64_MAX}; @@ -8401,8 +13269,33 @@ class Device final : D3D12_RESOURCE_ALLOCATION_INFO{align_up(total.SizeInBytes, total.Alignment), total.Alignment}; } + // A title that gets "invalid" for a description it believes in usually stops right there (GTA VI asserts on a + // size above 4 GiB), so every distinct refused description is logged in full. A small-alignment probe + // (Alignment 4096) the title retries without is expected, and marked as such. + static void log_refused_allocation(const D3D12_RESOURCE_DESC& desc) { + static std::mutex mutex; + static std::set seen; + char line[256]; + std::snprintf(line, sizeof line, + "dim %d format %d %llux%ux%u mips %u samples %u/%u layout %d flags 0x%x alignment %llu%s", + int(desc.Dimension), int(desc.Format), static_cast(desc.Width), + unsigned(desc.Height), unsigned(desc.DepthOrArraySize), unsigned(desc.MipLevels), + unsigned(desc.SampleDesc.Count), unsigned(desc.SampleDesc.Quality), int(desc.Layout), + unsigned(desc.Flags), static_cast(desc.Alignment), + desc.Alignment == D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT ? " (small-alignment probe)" : ""); + std::lock_guard lock(mutex); + if (seen.size() < 64 && seen.insert(line).second) + std::fprintf(stderr, "[rt] d3d12: GetResourceAllocationInfo refused: %s\n", line); + } + + D3D12_RESOURCE_ALLOCATION_INFO allocation(const D3D12_RESOURCE_DESC& asked) const { + D3D12_RESOURCE_DESC desc = asked; + desc.Format = pc_format(desc.Format); // the console's D16S8 family as D24S8 + return allocation_of(desc); + } + // One resource's size and alignment, or kInvalidAllocation for a description D3D12 (or this device) rejects. - D3D12_RESOURCE_ALLOCATION_INFO allocation(const D3D12_RESOURCE_DESC& desc) const { + D3D12_RESOURCE_ALLOCATION_INFO allocation_of(const D3D12_RESOURCE_DESC& desc) const { constexpr UINT64 align_4k = D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT, align_64k = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT, align_msaa_64k = D3D12_SMALL_MSAA_RESOURCE_PLACEMENT_ALIGNMENT, @@ -8559,12 +13452,13 @@ class Device final leonida::gfx10::Image image{}; if (!image_descriptor(resource, view, image)) return; const leonida::gfx10::ImageWords words = leonida::gfx10::encode(image); - const bool registered = state_.bind_image(words, image, resource.image(), resource.format(), + const bool registered = state_.bind_image(words, image, resource.descriptor_image(), resource.format(), resource.aspects(), storage, resource.has_view_format_list(), resource.uint_backed()); if (registered && resource.sparse_image()) state_.context->note_shader_image(resource.id()); if (leonida::gfx10::multisampled(image.type) && !registered) return; std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); + resource.note_shader_view(); } // Validation shared by CreateCommittedResource and CreateCommittedResource3; internal callers pass null `method` @@ -8572,7 +13466,8 @@ class Device final HRESULT create_committed_validated(const char* method, const D3D12_HEAP_PROPERTIES* heap, D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear, - UINT32 castable_count, const DXGI_FORMAT* castable, REFIID riid, void** out) { + UINT32 castable_count, const DXGI_FORMAT* castable, REFIID riid, void** out, + TitleImageOrigin origin = TitleImageOrigin::ordinary) { const auto finish = [&](HRESULT hr) { return method ? d3d12_trace::result(method, hr) : hr; }; if (out) *out = nullptr; if (!heap || !desc) return finish(E_INVALIDARG); @@ -8594,7 +13489,7 @@ class Device final int(desc->Dimension)); return finish(E_INVALIDARG); } - return finish(create_committed(heap, heap_flags, desc, state, castable_count, castable, riid, out)); + return finish(create_committed(heap, heap_flags, desc, state, castable_count, castable, riid, out, origin)); } // Shared by CreateCommittedResource, CreateCommittedResource3 and CreateReservedResource*. A castable-format list @@ -8603,9 +13498,13 @@ class Device final // runtime. HRESULT create_committed(const D3D12_HEAP_PROPERTIES* heap, D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES initial_state, - UINT32 castable_count, const DXGI_FORMAT* castable, REFIID riid, void** out) { + UINT32 castable_count, const DXGI_FORMAT* castable, REFIID riid, void** out, + TitleImageOrigin origin = TitleImageOrigin::ordinary) { if (out) *out = nullptr; if (!heap || !desc) return E_INVALIDARG; + D3D12_RESOURCE_DESC canonical = *desc; + canonical.Format = pc_format(canonical.Format); // the console's D16S8 family as D24S8 + desc = &canonical; if (castable_count && castable && desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { log_once("castable formats on a buffer are invalid; count", int(castable_count)); return E_INVALIDARG; @@ -8647,8 +13546,8 @@ class Device final hr = E_INVALIDARG; } else { std::vector cast_formats; - hr = castable_view_formats(format, castable_count, castable, cast_formats); - if (SUCCEEDED(hr)) hr = resource->create_texture(format, cast_formats); + hr = castable_view_formats(format, desc->Format, castable_count, castable, cast_formats); + if (SUCCEEDED(hr)) hr = resource->create_texture(format, cast_formats, origin); if (SUCCEEDED(hr)) resource->keep_castable_formats(castable_count, castable); } } @@ -8727,6 +13626,9 @@ class Device final REFIID riid, void** out) { if (out) *out = nullptr; if (!desc) return d3d12_trace::result(method, E_INVALIDARG); + D3D12_RESOURCE_DESC canonical = *desc; + canonical.Format = pc_format(canonical.Format); // the console's D16S8 family as D24S8 + desc = &canonical; if (castable_count && castable && desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { log_once("castable formats on a reserved buffer are invalid; count", int(castable_count)); return d3d12_trace::result(method, E_INVALIDARG); @@ -8960,6 +13862,26 @@ const std::vector* pipeline_subgroup_requests(ID3D12Pi return p && (p->compute() || p->graphics()) ? &p->subgroup_requests() : nullptr; } +bool write_placed_buffer_view(ID3D12Device* device, bool unordered, const void* view, std::uint64_t address, + std::uint64_t width, D3D12_CPU_DESCRIPTOR_HANDLE destination) { + Device* d = Device::from(device); + if (!d || !view || !destination.ptr) return false; + return d->write_placed_buffer_view(unordered, view, address, width, destination); +} + +bool write_placed_texture_view(ID3D12Device* device, bool unordered, const std::uint32_t* resource_words, + const std::uint32_t* view_words, std::uint64_t address, + D3D12_CPU_DESCRIPTOR_HANDLE destination) { + Device* d = Device::from(device); + if (!d || !resource_words || !view_words || !destination.ptr) return false; + if (unordered) return d->write_placed_texture_uav(resource_words, view_words, address, destination); + return d->write_placed_texture_view(resource_words, view_words, address, destination); +} + +D3D12_GPU_VIRTUAL_ADDRESS console_descriptor_table_va(D3D12_GPU_VIRTUAL_ADDRESS va) { + return console_heap_ranges().shader_va(va); +} + IUnknown* descriptor_heap_info(ID3D12DescriptorHeap* heap, D3D12_DESCRIPTOR_HEAP_DESC& desc, D3D12_GPU_VIRTUAL_ADDRESS& gpu_base) { if (!heap) return nullptr; @@ -8981,6 +13903,11 @@ VkMemoryPropertyFlags vulkan_memory_flags(ID3D12Resource* resource) { return r ? r->memory_flags() : 0; } +bool title_shadow_buffer(ID3D12Resource* resource) { + const Resource* r = Resource::from(resource); + return r && r->is_shadow(); +} + VkBuffer vulkan_buffer(ID3D12Resource* resource) { const Resource* r = Resource::from(resource); return r ? r->buffer() : VK_NULL_HANDLE; @@ -8993,6 +13920,39 @@ const VulkanDeviceInfo* vulkan_device_info(ID3D12Device* device) { return nullptr; } +std::uint64_t title_shadow_refresh_queries(ID3D12Device* device) { + auto* d = Device::from(device); + if (!d) return 0; + auto& state = d->state(); + std::lock_guard lock(state.shadow_mutex); + std::uint64_t queries = 0; + for (const auto& shadow : state.shadows) queries += shadow->refresh_queries(); + return queries; +} + +std::uint64_t title_shadow_trackers(ID3D12Device* device) { + auto* d = Device::from(device); + if (!d) return 0; + auto& state = d->state(); + std::lock_guard lock(state.shadow_mutex); + return state.shadows.size(); +} +TitleShadowWatch title_shadow_watch(ID3D12Device* device) { + TitleShadowWatch watch; + auto* d = Device::from(device); + if (!d) return watch; + auto& state = d->state(); + std::lock_guard lock(state.shadow_mutex); + for (const auto& shadow : state.shadows) { + watch.asks += shadow->refresh_asks(); + watch.written += shadow->refresh_written(); + watch.faults += shadow->faults(); + watch.watched_bytes += shadow->watched_bytes(); + watch.hot_bytes += shadow->hot_bytes(); + } + return watch; +} + HRESULT create_buffer_at_host_address(ID3D12Device* device, void* address, const D3D12_RESOURCE_DESC& desc, std::uint32_t layout, REFIID riid, void** out) { if (out) *out = nullptr; @@ -9189,6 +14149,13 @@ HRESULT WindowPresenter::present(ID3D12Resource* back_buffer, UINT sync_interval tear)); } +bool WindowPresenter::present_splash(ID3D12Resource* image) { + if (!image) return false; + image->AddRef(); + std::shared_ptr owner(image, [](ID3D12Resource* p) { p->Release(); }); + return presenter_->present_splash(resource_id(image), std::move(owner)); +} + bool WindowPresenter::tear_supported() const { return presenter_->tear_supported(); } bool WindowPresenter::last_present_tore() const { return presenter_->last_present_tore(); } std::uint64_t WindowPresenter::tear_presents() const { return presenter_->tear_presents(); } @@ -9481,6 +14448,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin LEONIDA_INSTANCE(vkGetPhysicalDeviceProperties); LEONIDA_INSTANCE(vkGetPhysicalDeviceQueueFamilyProperties); LEONIDA_INSTANCE(vkGetPhysicalDeviceFeatures2); + LEONIDA_INSTANCE(vkGetPhysicalDeviceFormatProperties); LEONIDA_INSTANCE(vkGetPhysicalDeviceProperties2); LEONIDA_INSTANCE(vkEnumerateDeviceExtensionProperties); LEONIDA_INSTANCE(vkCreateDevice); @@ -9857,6 +14825,27 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin } #endif +#ifdef VK_KHR_MAINTENANCE_5_EXTENSION_NAME + // VK_KHR_maintenance5 brings VK_FORMAT_A8_UNORM_KHR (VulkanDeviceInfo::a8_render_target). It is enabled only where + // that format can be sampled, copied (every texture is a transfer source and destination) and is a colour + // attachment the GPU can blend; nothing else here relies on it. + VkPhysicalDeviceMaintenance5FeaturesKHR maintenance5{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_5_FEATURES_KHR}; + if (has_device_extension(VK_KHR_MAINTENANCE_5_EXTENSION_NAME) && vkGetPhysicalDeviceFormatProperties) { + VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &maintenance5}; + vkGetPhysicalDeviceFeatures2(info.physical, &query); + VkFormatProperties a8{}; + vkGetPhysicalDeviceFormatProperties(info.physical, VK_FORMAT_A8_UNORM_KHR, &a8); + const VkFormatFeatureFlags needed = VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT | VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT | + VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT | + VK_FORMAT_FEATURE_TRANSFER_SRC_BIT | VK_FORMAT_FEATURE_TRANSFER_DST_BIT; + info.a8_render_target = maintenance5.maintenance5 == VK_TRUE && (a8.optimalTilingFeatures & needed) == needed; + if (info.a8_render_target) { + maintenance5.pNext = *v13.next(); + *v13.next() = &maintenance5; + } + } +#endif + #ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME // VK_KHR_shader_fma: OpFmaKHR is a single-rounding multiply-add in SPIR-V (GLSL.std.450 Fma may round twice). // Translated shaders built with `rdna2spirv.py --fma khr` need it (index capability FMAKHR, feature @@ -9998,6 +14987,9 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin std::vector device_extensions; v13.add_extensions(device_extensions); if (info.depth_range_unrestricted) device_extensions.push_back(VK_EXT_DEPTH_RANGE_UNRESTRICTED_EXTENSION_NAME); + info.pipeline_creation_feedback = v13.core || has_device_extension(VK_EXT_PIPELINE_CREATION_FEEDBACK_EXTENSION_NAME); + if (trace_pipeline_compile() && !v13.core && info.pipeline_creation_feedback) + device_extensions.push_back(VK_EXT_PIPELINE_CREATION_FEEDBACK_EXTENSION_NAME); if (info.conservative_rasterization) device_extensions.push_back(VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME); if (info.image_view_min_lod) device_extensions.push_back(VK_EXT_IMAGE_VIEW_MIN_LOD_EXTENSION_NAME); if (info.vertex_attribute_divisor) device_extensions.push_back(divisor_extension); @@ -10009,6 +15001,9 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin #ifdef VK_KHR_MAINTENANCE_8_EXTENSION_NAME if (info.maintenance8) device_extensions.push_back(VK_KHR_MAINTENANCE_8_EXTENSION_NAME); #endif +#ifdef VK_KHR_MAINTENANCE_5_EXTENSION_NAME + if (info.a8_render_target) device_extensions.push_back(VK_KHR_MAINTENANCE_5_EXTENSION_NAME); +#endif #ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME if (info.shader_fma) device_extensions.push_back(VK_KHR_SHADER_FMA_EXTENSION_NAME); #endif @@ -10028,6 +15023,17 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin info.swapchain_colorspace = info.presentation && swapchain_colorspace_enabled; if (info.custom_border_color) device_extensions.push_back(custom_border_name); if (info.host_pointer_alignment) device_extensions.push_back(VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME); + leonida::DeviceFaultFeatures fault_features; + char device_fault[2]{}; + if (GetEnvironmentVariableA("LEONIDA_DEVICE_FAULT", device_fault, sizeof(device_fault)) == 1 && + device_fault[0] == '1') { + info.device_fault_diagnostics = true; + const auto fault = fault_features.enable(info.physical, vkGetPhysicalDeviceFeatures2, extensions, + device_extensions, device_info); + info.device_fault_info = fault.fault; + info.device_checkpoints = fault.checkpoints; + info.device_diagnostics_config = fault.diagnostics_config; + } device_info.enabledExtensionCount = std::uint32_t(device_extensions.size()); device_info.ppEnabledExtensionNames = device_extensions.empty() ? nullptr : device_extensions.data(); if (vkCreateDevice(info.physical, &device_info, nullptr, &owned.device) != VK_SUCCESS) @@ -10129,26 +15135,7 @@ HRESULT create_console_descriptor_heap(ID3D12Device* device, const D3D12_DESCRIP } std::filesystem::path configured_shader_directory(std::string* error, const std::filesystem::path& config) { - try { - constexpr wchar_t env_name[] = L"LEONIDA_SHADERS"; - if (const DWORD size = ::GetEnvironmentVariableW(env_name, nullptr, 0)) { - std::wstring value(size, L'\0'); - const DWORD length = ::GetEnvironmentVariableW(env_name, value.data(), size); - if (length && length < size) { - value.resize(length); - return std::filesystem::path(value); - } - } - if (!config.empty()) return shader_directory_from_file(config); - std::wstring exe(32768, L'\0'); - const DWORD length = ::GetModuleFileNameW(nullptr, exe.data(), static_cast(exe.size())); - if (!length || length >= exe.size()) return {}; - exe.resize(length); - return shader_directory_from_file(std::filesystem::path(exe).parent_path() / L"shader_path.txt"); - } catch (const std::exception& e) { - if (error) *error = e.what(); - return {}; - } + return leonida::shader_paths::configured(error, config); } } // namespace rt::d3d12 diff --git a/runtime/shims/d3d12_xs.cpp b/runtime/shims/d3d12_xs.cpp index dfd16fd6ad..2201e84af0 100644 --- a/runtime/shims/d3d12_xs.cpp +++ b/runtime/shims/d3d12_xs.cpp @@ -187,6 +187,14 @@ HRESULT WINAPI D3D12XboxCreateDevice(IUnknown* adapter, const void* params, cons }); } + // A console title gets the console-shaped list the Xbox ABI calls. A guest compiled against the PC + // headers (the tiny fixtures, which call the list through PC vtable indices) asks for PC-shaped lists + // with LEONIDA_D3D12_LISTS=pc — the device, queue and friends stay console-shaped either way. + char lists_mode[8] = {}; + size_t lists_length = 0; + const bool pc_lists = getenv_s(&lists_length, lists_mode, "LEONIDA_D3D12_LISTS") == 0 && + std::strcmp(lists_mode, "pc") == 0; + #ifdef LEONIDA_VULKAN_DEVICE // Opt-in until the Vulkan device covers the first frame: LEONIDA_D3D12=vulkan puts the Vulkan-backed device // behind the same proxy instead of the host's D3D12 device. @@ -201,7 +209,7 @@ HRESULT WINAPI D3D12XboxCreateDevice(IUnknown* adapter, const void* params, cons static_cast(vhr)); return result(method, vhr); } - vhr = rt::d3d12_xs::create_device_proxy(vulkan, *riid, out); + vhr = rt::d3d12_xs::create_device_proxy(vulkan, *riid, out, /*console_lists=*/!pc_lists); if (FAILED(vhr)) { vulkan->Release(); std::fprintf(stderr, "[rt] d3d12_xs: D3D12XboxCreateDevice: proxy over the Vulkan device failed " @@ -227,7 +235,7 @@ HRESULT WINAPI D3D12XboxCreateDevice(IUnknown* adapter, const void* params, cons return result(method, hr); } - hr = rt::d3d12_xs::create_device_proxy(real, *riid, out); + hr = rt::d3d12_xs::create_device_proxy(real, *riid, out, /*console_lists=*/!pc_lists); if (FAILED(hr)) { // create_device_proxy keeps the caller's reference on failure. real->Release(); diff --git a/runtime/shims/d3d12_xs_alloc_size.h b/runtime/shims/d3d12_xs_alloc_size.h index 3321c4ec88..5dc3a2dc4e 100644 --- a/runtime/shims/d3d12_xs_alloc_size.h +++ b/runtime/shims/d3d12_xs_alloc_size.h @@ -16,6 +16,7 @@ #pragma once #include "../src/gfx10_tiling.h" +#include "xg_xs_layout.h" #include #include @@ -24,6 +25,7 @@ #include #include #include +#include namespace rt::d3d12_xs { @@ -105,6 +107,98 @@ inline UINT64 console_render_target_size(const D3D12_RESOURCE_DESC& desc) { return slice * slices; } +// The planes of a depth-stencil format as the console stores them, in bytes per element (0: no such plane), or +// {0, 0} for any other format. The console keeps depth and stencil in separate planes: 4 + 1 bytes for the 32-bit +// float depth formats and for D24S8, 2 + 1 for its own D16_UNORM_S8_UINT (DXGI 118), 4 or 2 alone for D32 and D16. +struct DepthPlanes { + std::size_t depth = 0, stencil = 0; +}; +inline DepthPlanes console_depth_planes(DXGI_FORMAT format) { + switch (static_cast(format)) { + case DXGI_FORMAT_R32G8X24_TYPELESS: case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: + case DXGI_FORMAT_R24G8_TYPELESS: case DXGI_FORMAT_D24_UNORM_S8_UINT: + return {4, 1}; + case 118: return {2, 1}; // the console's D16_UNORM_S8_UINT + case DXGI_FORMAT_R32_TYPELESS: case DXGI_FORMAT_D32_FLOAT: return {4, 0}; + case DXGI_FORMAT_R16_TYPELESS: case DXGI_FORMAT_D16_UNORM: return {2, 0}; + default: return {}; + } +} + +// The console's allocation size for a single-sampled 2D depth-stencil target: each plane laid out in 64 KiB tiles +// like a colour target of that element size, the planes added up. 0 when the rule does not apply. +// +// Why this one may be SMALLER than the PC answer, unlike the render-target rule: a PC driver stores D32_FLOAT_S8 as +// 8 bytes per texel (a 3840 x 2160 target is 63.75 MiB on NVIDIA; the console's two planes are 40.3 MiB), and the +// title checks the peak of its transient render-target pool, 4752 x 64 KiB on a Series S, against these sizes and +// stops on an int3 when it does not fit (measured: peak 320.0 MiB against 297 MiB with the PC sizes, two such +// targets alive at the peak; docs/re/answers.md). The title never writes a depth target's memory with the CPU and +// this runtime does not keep the texture in the title's allocation, so the smaller number is only its bookkeeping. +// No HiZ/HTile memory is added: whether the console counts it in the allocation is not measured. +inline UINT64 console_depth_stencil_size(const D3D12_RESOURCE_DESC& desc) { + if (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) return 0; + if (!(desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) return 0; + if (desc.SampleDesc.Count > 1 || !desc.Width || !desc.Height || !desc.DepthOrArraySize) return 0; + const DepthPlanes planes = console_depth_planes(desc.Format); + if (!planes.depth) return 0; + const UINT full_chain = static_cast(std::bit_width(std::max(desc.Width, desc.Height))); + const UINT mips = desc.MipLevels ? std::min(desc.MipLevels, full_chain) : full_chain; + UINT64 slice = 0; + for (const std::size_t element_bytes : {planes.depth, planes.stencil}) { + if (!element_bytes) continue; + bool tail = false; + for (UINT mip = 0; mip < mips; ++mip) { + const UINT64 width = std::max((desc.Width + (UINT64{1} << mip) - 1) >> mip, 1); + const UINT64 height = std::max((UINT64{desc.Height} + (UINT64{1} << mip) - 1) >> mip, 1); + leonida::gfx10::TiledSurface2D surface; + if (width > UINT32_MAX || + !leonida::gfx10::TiledSurface2D::make(leonida::gfx10::TileMode::sw_64kb_d, element_bytes, + static_cast(width), + static_cast(height), surface)) + return 0; + if (width <= surface.tile_width() / 2 && height <= surface.tile_height()) { + tail = true; + break; + } + slice += surface.tiled_size(); + } + if (tail) slice += kConsoleTileBytes; + } + const UINT64 slices = desc.DepthOrArraySize; + if (!slice || slice > UINT64_MAX / slices) return 0; + return slice * slices; +} + +// The console's size and alignment of a texture nothing renders or stores to (no render-target, depth-stencil or +// unordered-access flag): XG's layout of the description (xg_xs_layout.h; the default swizzle mode when the layout +// word names none). False when XG's model does not take the description: the PC answer then stands. +// +// Why exact: the title keeps this size in its streaming tables and reads exactly that many bytes of the texture +// from its archives through DirectStorage; a compressed chunk must be read whole, and the title stops on an int3 +// when the size it was given is smaller than the chunk. Measured with a debugger at that int3: a +// request of 0x2000 bytes for a chunk that spans 0x4000, the PC answer for the texture being half the console's. +inline bool console_texture_layout(const D3D12_RESOURCE_DESC& desc, UINT64& size, UINT64& alignment) { + constexpr UINT gpu_written = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + if (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE1D && desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D && + desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE3D) + return false; + if ((desc.Flags & gpu_written) || desc.SampleDesc.Count != 1) return false; + static_assert(sizeof(rt::xg_xs::ResourceDesc) == sizeof(D3D12_RESOURCE_DESC)); + rt::xg_xs::ResourceDesc xg{}; + std::memcpy(&xg, &desc, sizeof(xg)); + xg.alignment = 0; + xg.quality = 0; + xg.flags = 0; + if (xg.layout != 1 && (xg.layout & ~0x1fu) != rt::xg_xs::kSwizzled) xg.layout = 0; // XG's default mode + static thread_local rt::xg_xs::Texture texture; // 7 KiB: not on a title thread's stack + texture = {}; + if (!rt::xg_xs::build_texture(xg, texture) || !texture.layout.size || !texture.layout.alignment) return false; + size = texture.layout.size; + alignment = texture.layout.alignment; + return true; +} + // Rounds up to a multiple of `to`, stopping at the last multiple below 2^64 instead of wrapping (as the PC device's // totals do). inline UINT64 align_up_saturating(UINT64 value, UINT64 to) { @@ -125,7 +219,11 @@ bool console_placement(const D3D12_RESOURCE_DESC* descs, UINT count, PcOne pc_on D3D12_RESOURCE_ALLOCATION_INFO& total, D3D12_RESOURCE_ALLOCATION_INFO1* each) { if (!descs) return false; bool any_target = false; - for (UINT i = 0; i < count && !any_target; ++i) any_target = console_render_target_size(descs[i]) != 0; + for (UINT i = 0; i < count && !any_target; ++i) { + UINT64 xg_size = 0, xg_alignment = 0; + any_target = console_render_target_size(descs[i]) != 0 || console_depth_stencil_size(descs[i]) != 0 || + console_texture_layout(descs[i], xg_size, xg_alignment); + } if (!any_target) return false; // Two passes when `each` is wanted: the first decides, the second writes, so a refusal or a list that does not // grow leaves the array as the PC device filled it. @@ -134,14 +232,28 @@ bool console_placement(const D3D12_RESOURCE_DESC* descs, UINT count, PcOne pc_on bool grows = false; UINT64 end = 0, alignment = 1; for (UINT i = 0; i < count; ++i) { - const D3D12_RESOURCE_ALLOCATION_INFO one = pc_one(i); + D3D12_RESOURCE_ALLOCATION_INFO one = pc_one(i); if (one.SizeInBytes == UINT64_MAX || !one.Alignment) return false; UINT64 size = one.SizeInBytes; + // A texture only the CPU fills takes XG's size and alignment, whichever way they differ. + if (UINT64 xg_size = 0, xg_alignment = 0; console_texture_layout(descs[i], xg_size, xg_alignment)) { + if (xg_size != size || xg_alignment != one.Alignment) grows = true; + size = xg_size; + one.Alignment = xg_alignment; + } const UINT64 console = console_render_target_size(descs[i]); if (console > size) { size = align_up_saturating(console, one.Alignment); grows = true; } + // A depth-stencil target takes its console size whichever way it differs (console_depth_stencil_size). + if (const UINT64 depth = console_depth_stencil_size(descs[i])) { + const UINT64 planes = align_up_saturating(depth, one.Alignment); + if (planes != size) { + size = planes; + grows = true; + } + } const UINT64 offset = align_up_saturating(end, one.Alignment); if (write) each[i] = {offset, one.Alignment, size}; end = size > UINT64_MAX - offset ? UINT64_MAX : offset + size; diff --git a/runtime/shims/d3d12_xs_desc_clean.h b/runtime/shims/d3d12_xs_desc_clean.h index ba51184a4d..5b44484628 100644 --- a/runtime/shims/d3d12_xs_desc_clean.h +++ b/runtime/shims/d3d12_xs_desc_clean.h @@ -1,9 +1,10 @@ // The PC form of a resource description the retail title builds for the console, for the Xbox-ABI device proxy. // // The title's D3D12_RESOURCE_DESC carries console values the PC device cannot take: the layout word is 0x101 (tiled) -// or 0x1 (row-major buffer), and the flags have bits above the PC ones set (docs/retail_boot_chain.md, #6982). Slot 76 -// replaces the layout word the same way before it forwards to CreateCommittedResource; slot 25 and the slot 127 -// stand-in need the same cleaning. The title's own description is never written: a caller gets a copy. +// or another console layout word, and the flags have bits above the PC ones set (docs/retail_boot_chain.md, #6982). +// Slot 76 replaces the layout word the same way before it forwards to CreateCommittedResource; slot 25 (for a +// console-form call or a 0x101 layout) and the slot 127 stand-in need the same cleaning. The title's own description +// is never written: a caller gets a copy. #pragma once #include @@ -24,14 +25,53 @@ constexpr std::uint32_t kPcResourceFlagsMask = // Not constexpr: 0x101 is outside the unfixed enum's value range, which clang-cl rejects in a constant expression. inline const auto kXboxTiledResourceLayout = static_cast(0x101); -// Strip Xbox-only flags and translate the Xbox tiled layout. Preserve all other layouts so the host can validate them. +// The console allows a depth-stencil texture to allow unordered access too (measured locally at a title's call sites: +// a 2D R32G8X24_TYPELESS texture with ALLOW_DEPTH_STENCIL | ALLOW_UNORDERED_ACCESS, sized through slot 25), but the PC +// runtime refuses that pair, and Vulkan has no depth format with storage support to make it with. Stand-in: such a +// texture is a depth-stencil texture without unordered access (slot 76 through this; slot 25 through +// pc_resource_desc). Its unordered-access views write no descriptor (the PC layer refuses a UAV of a texture without +// the flag), so what a shader writes through them goes nowhere and their reads see whatever the descriptor held. +inline std::uint32_t without_depth_stencil_uav(D3D12_RESOURCE_DIMENSION dimension, std::uint32_t flags) { + if (dimension != D3D12_RESOURCE_DIMENSION_BUFFER && (flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) + flags &= ~static_cast(D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + return flags; +} + +inline bool is_depth_resource_format(DXGI_FORMAT format) { + switch (format) { + case DXGI_FORMAT_D16_UNORM: + case DXGI_FORMAT_D24_UNORM_S8_UINT: + case DXGI_FORMAT_D32_FLOAT: + case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: + case DXGI_FORMAT_R16_TYPELESS: + case DXGI_FORMAT_R24G8_TYPELESS: + case DXGI_FORMAT_R32_TYPELESS: + case DXGI_FORMAT_R32G8X24_TYPELESS: + case static_cast(118): // the console's D16_UNORM_S8_UINT + return true; + default: + return false; + } +} + +// Strip Xbox-only flags and preserve the three supported PC layouts. In addition to 0x101, zebraso measured +// layout words 0x102 and 0x105 reaching slot 25 during a retail boot. inline D3D12_RESOURCE_DESC pc_resource_desc(const D3D12_RESOURCE_DESC& xbox) { D3D12_RESOURCE_DESC pc = xbox; - if (pc.Layout == kXboxTiledResourceLayout) { + if (pc.Layout != D3D12_TEXTURE_LAYOUT_UNKNOWN && + pc.Layout != D3D12_TEXTURE_LAYOUT_ROW_MAJOR && + pc.Layout != D3D12_TEXTURE_LAYOUT_64KB_STANDARD_SWIZZLE) { pc.Layout = pc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER ? D3D12_TEXTURE_LAYOUT_ROW_MAJOR : D3D12_TEXTURE_LAYOUT_UNKNOWN; } - pc.Flags = static_cast(static_cast(xbox.Flags) & kPcResourceFlagsMask); + std::uint32_t flags = static_cast(xbox.Flags) & kPcResourceFlagsMask; + // zebraso measured slot 25 rejecting B5G5R5A1 render targets with UAV on an RTX 5080 without + // storage-image support for that format. Depth-stencil resources also cannot be UAVs on PC. + if (pc.Format == DXGI_FORMAT_B5G5R5A1_UNORM || + ((flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) && is_depth_resource_format(pc.Format))) { + flags &= ~static_cast(D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + } + pc.Flags = static_cast(flags); return pc; } diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 0b8c8dc880..e4546ce680 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -24,10 +24,26 @@ // for a trace that disagrees. The frame-event calls answer from a per-device token counter: there is no vblank source // behind the device before a presenter exists, so WaitFrameEventX returns at once with a fresh non-zero token. #include "d3d12_xs_device.h" +#ifdef LEONIDA_VULKAN_DEVICE +#include "d3d12_com.h" // rt::d3d12::create_console_descriptor_heap for slot 14 +#endif #include "d3d12_trace.h" #include "d3d12_xs_alloc_size.h" #include "d3d12_xs_desc_clean.h" +#include "../src/frame_pacer.h" +#include "d3d12_xs_pso_stream.h" #include "../src/shader_library.h" // leonida::fspx_payload_from_parts for slot 67 +#include "../src/title_page_watch.h" // leonida::kernel_writes for slot 14 + +#ifdef LEONIDA_VULKAN_DEVICE +// PresentX wiring: the queue's console slots land on the Xbox presentation core, which needs the Vulkan layer's +// WindowPresenter. Other builds of this file (mock and COM tests) keep the refused-slot behaviour. +#include "xbox_present.h" +#include "title_window.h" +#include "package_splash.h" +#include "startup_trace.h" +#include +#endif #include #include @@ -43,12 +59,17 @@ #include #include #include +#include +#include +#include +#include #include #include #include #include #include + namespace rt::d3d12_xs { namespace { @@ -59,6 +80,9 @@ static_assert(kMaxSlots > 133, "the proxy table must cover the slots the retail // Set by the Vulkan device behind the proxy; slot 14 uses it for a console-extended CreateDescriptorHeap. std::atomic g_console_descriptor_heap{nullptr}; +// Commits the title's pages before slot 133 imports them or slot 14 checks them (set_placed_at_va_pages_hook; gta6rt +// registers xmem's commit_physical_range, which leaves memory other than mapped physical pages alone). +std::atomic g_placed_at_va_pages{nullptr}; static_assert(kMaxSlots > 83, "the proxy table must cover ID3D12Device14 (83 slots)"); static_assert(sizeof(void*) == 8, "the Xbox-ABI proxy is x64-only"); static_assert(sizeof(D3D12_CPU_DESCRIPTOR_HANDLE) == 8, @@ -71,6 +95,20 @@ struct DeviceProxy { void** real_vtable; unsigned slot_count; // number of valid entries in real_vtable std::atomic refs; + // The PresentX state (window, presenter, XboxPresentation) the first queue PresentX builds on this device, + // under LEONIDA_VULKAN_DEVICE; always null elsewhere. Opaque: PresentState is defined with the queue proxy. + void* present_state = nullptr; + std::mutex present_state_mutex; + // The upload-memory arena console list slot 148 (AllocateUploadMemory) carves from; always null until the + // first call. Opaque: UploadArena is defined with the list proxy. Atomic: lists record on several threads + // at once, so the first AllocateUploadMemory installs the arena by compare-exchange. + std::atomic upload_state{nullptr}; + // The console runtime layout this title was built against (docs/d3d12_xs_console_abi.md §4): the queue proxy + // writes it on detection and every object shares it — the queue/list slot tails shift +2 under the newer one. + std::atomic console_layout{0}; // 0 unknown, 1 older, 2 newer + // Set by create_device_proxy: false hands real (PC-shaped) lists back from CreateCommandList for callers + // compiled against the PC headers. + bool console_lists = true; // The device's IDXGIDevice1 (see "IDXGIDevice1 on the device" below): a title's IDXGIDevice1* points here. void** dxgi_vtable; DxgiAdapterProvider adapter_provider; @@ -82,7 +120,7 @@ struct DeviceProxy { std::atomic frame_interval_us{0}; std::atomic frame_latency{1}; std::atomic frame_event_scheduled{false}; - std::atomic frame_next_token{1}; + std::shared_ptr frame_tokens = std::make_shared(); // Optional presentation wiring attached via set_presentation_handler (guarded by presentation_lock). SRWLOCK presentation_lock = SRWLOCK_INIT; PresentationHandler presentation{}; @@ -102,6 +140,10 @@ bool call_presentation(DeviceProxy* self, F&& f) { return handled; } +// Freed in proxy_release; defined where the states are complete. +void destroy_present_state(void* present_state); +void destroy_upload_state(void* upload_state); + constexpr unsigned kHeapSlots = 11; // IUnknown + ID3D12Object + DeviceChild + Pageable + GetDesc + 2 handles struct HeapProxy { @@ -244,8 +286,8 @@ const char* slot_name(unsigned slot) { case 23: return "CopyDescriptors (CPU handles translated)"; case 24: return "CopyDescriptorsSimple (CPU handles translated)"; case 25: return "GetResourceAllocationInfo (C or PC form)"; - case 26: return "GetCustomHeapProperties"; - case 27: return "CreateCommittedResource (PC slot 27)"; + case 26: return "GetCustomHeapProperties (C or PC form)"; + case 27: return "CreateCommittedResource (initial state mapped)"; case 31: return "CreateSharedHandle (proxies unwrapped)"; case 32: return "OpenSharedHandle (a fence comes back wrapped)"; case 34: return "MakeResident (proxies unwrapped)"; @@ -255,14 +297,16 @@ const char* slot_name(unsigned slot) { case 43: return "GetAdapterLuid"; case 45: return "SetEventOnMultipleFenceCompletion (fence proxies unwrapped)"; case 46: return "SetResidencyPriority (proxies unwrapped)"; - case 48: return "Xbox CreateCommandQueueX -> queue proxy"; + case 48: return "Xbox CreateCommandQueueX (32-byte desc) -> queue proxy"; case 50: return "EnqueueMakeResident (proxies unwrapped)"; + case 53: return "CreateCommittedResource1 (initial state mapped)"; case 56: return "GetResourceAllocationInfo1 (C or PC form)"; case 61: return "Xbox CreateSamplerX -> PC CreateSampler (a host caller gets PC CreateMetaCommand)"; case 62: return "Xbox CreateComputePipelineState"; case 67: return "Xbox DeserializeComputePipelineStateX"; - case 70: return "Xbox shader-resource view from raw words"; - case 73: return "Xbox CreateCommandListX -> PC CreateCommandList"; + case 70: return "Xbox shader-resource view of placed memory"; + case 71: return "Xbox unordered-access view of placed memory"; + case 73: return "Xbox CreateCommandListX -> console list proxy"; case 74: return "Xbox (pointer, u32, pointer) stand-in"; case 75: return "CreateCommandQueue1 -> queue proxy"; case 76: return "Xbox resource creation"; @@ -270,10 +314,11 @@ const char* slot_name(unsigned slot) { case 78: return "Xbox SetFrameIntervalX"; case 79: return "Xbox ScheduleFrameEventX"; case 80: return "Xbox WaitFrameEventX"; + case 55: return "Xbox CreateDerivedPipelineState -> PC CreatePipelineState of the patched stream (slot 47)"; case 86: return "Xbox CreatePipelineState -> PC CreatePipelineState (slot 47)"; case 101: return "Xbox CreateStateObject -> PC CreateStateObject (slot 62)"; case 108: return "Xbox GetResourceAllocationInfo2 -> PC GetResourceAllocationInfo2 (slot 68)"; - case 133: return "Xbox CreatePlacedResourceX (a buffer on the title's pages)"; + case 133: return "Xbox CreatePlacedResourceX (a buffer on the title's pages, else committed)"; default: return "forwarded"; } } @@ -407,6 +452,8 @@ unsigned long proxy_release(DeviceProxy* self) { note_slot(2); const unsigned long refs = self->refs.fetch_sub(1, std::memory_order_acq_rel) - 1; if (refs == 0) { + destroy_present_state(self->present_state); + destroy_upload_state(self->upload_state.load(std::memory_order_relaxed)); ID3D12Device* real = self->real; delete self; if (real) real->Release(); @@ -778,10 +825,17 @@ HRESULT create_heap_proxy(ID3D12DescriptorHeap* real, DeviceProxy* device, REFII // // Device slots 8 (CreateCommandQueue), 75 (CreateCommandQueue1), 36 (CreateFence) and 32 (OpenSharedHandle, for a // fence) wrap what they create, so a title never holds a PC or Vulkan-layer queue or fence. The proxies forward -// the public chain in PC order, exactly like the device proxy, and a slot past the PC vtable is logged and refused -// with E_NOTIMPL. PresentX, SuspendX and ResumeX are queue methods past the public chain -// (docs/d3d12_command_objects.md §5.3). Their slots are not known and nothing is guessed: the first run of the -// executable names them in the log. +// the public chain in PC order, exactly like the device proxy; on a fence a slot past the PC vtable is logged and +// refused with E_NOTIMPL. The one exception is fence slot 12, which returns the address of the completed value (its +// section below). PresentX, SuspendX and ResumeX are queue methods past the public chain +// (docs/d3d12_command_objects.md §5.3). A sibling layer measured two queue layouts on retail titles +// (docs/d3d12_xs_console_abi.md §4, unverified here): the older has Signal 14, Wait 15, +// GetTimestampFrequency 16, GetClockCalibration 17, GetDesc 18, SignalX 23, PresentX 30; a newer game +// OS inserts two methods before Signal, shifting to Signal 16, Wait 17, frequency 18, SignalX 25, +// PresentX 32 — a fence passed to slot 16 or 17 marks the newer layout, and the detection is shared +// across queues through the device. PresentX is wired to the Vulkan layer's Xbox presentation, +// SignalX forwards as Signal, and the unmodelled console-only slots answer S_OK (the PresentX +// section below); the first run of the executable confirms which layout. // // Slot numbers are those of the Windows SDK 10.0.26100 d3d12.h: ID3D12CommandQueue has 19, ID3D12Fence 11 and // ID3D12Fence1 12. That the console keeps these public slots, and keeps device slots 8/32/36/75, is an assumption @@ -799,11 +853,10 @@ HRESULT create_heap_proxy(ID3D12DescriptorHeap* real, DeviceProxy* device, REFII // passed there: queue Signal/Wait (14/15) take a fence; device CreateSharedHandle (31) a device child, // MakeResident/Evict (34/35), SetResidencyPriority (46) and EnqueueMakeResident (50) pageables, and // SetEventOnMultipleFenceCompletion (45) and EnqueueMakeResident fences. The heap proxies of slot 14 are pageables -// and device children too and are unwrapped in the same places. Command lists are not wrapped yet, so -// ExecuteCommandLists passes them through, and a heap proxy still reaches the real runtime through the list's -// SetDescriptorHeaps. A command-list proxy (docs/d3d12_command_objects.md §3.5a) adds its vtable to -// proxy_real_object, which every unwrap goes through, and a queue slot 10 branch in child_slot that unwraps the list -// array (UnwrappedArray) before forwarding, and unwraps heap proxies in its own SetDescriptorHeaps. +// and device children too and are unwrapped in the same places. Command lists from device slot 12 come back +// console-shaped (the list proxy below): queue ExecuteCommandLists (10) unwraps the list array, the list's own +// Reset and ExecuteBundle unwrap allocator and bundle proxies, and its SetDescriptorHeaps unwraps heap proxies — +// all through proxy_real_object, so any object kind added later unwraps in every place at once. // // QueryInterface answers only the interfaces the proxy models (the base chain and its own interface, Fence1 when // the real fence has it), like the device and heap proxies, so the COM identity holds and no real object leaks to @@ -834,6 +887,13 @@ static_assert(kQueueSlots * sizeof(void*) <= 4096 && kFenceSlots * sizeof(void*) constexpr unsigned kQueueExecuteCommandLists = 10; // (UINT, ID3D12CommandList* const*) constexpr unsigned kQueueSignal = 14, kQueueWait = 15; // (ID3D12Fence*, UINT64) +constexpr unsigned kFenceSignal = 10; // ID3D12Fence::Signal(UINT64), from the CPU +constexpr unsigned kFenceCompletedValueSlot = 12; // one past ID3D12Fence1: the completed value's address +static_assert(kFenceCompletedValueSlot >= kFence1PublicSlots && kFenceCompletedValueSlot < kFenceSlots, + "fence slot 12 is past the public chain and inside the table"); + +struct FenceMirror; + constexpr unsigned kQueueExecuteCommandListsX = 35; // console ExecuteCommandLists(count, lists) variant static_assert(kQueueExecuteCommandLists < kQueuePublicSlots && kQueueExecuteCommandListsX < kQueueSlots, "queue execution slots must stay within their respective tables"); @@ -845,6 +905,18 @@ struct ChildProxy { void** real_vtable; unsigned slot_count; // public slots the real object implements; the rest of the table is refused std::atomic refs; + // Queues only: the console runtime layout this title was built against (docs/d3d12_xs_console_abi.md §4), + // detected by a fence reaching slot 16/17 or SignalX slot 25. Unused on fences and allocators. A queue is + // used from many threads, so the cache of the device's shared detection is atomic like the shared flag + // itself. + static constexpr unsigned char kQueueLayoutUnknown = 0; + static constexpr unsigned char kQueueLayoutOlder = 1; // PC order; PresentX 30, SignalX 23 + static constexpr unsigned char kQueueLayoutNewer = 2; // +2 shift; PresentX 32, SignalX 25 + std::atomic queue_layout{kQueueLayoutUnknown}; + // Allocators only: callback and context recorded by console slot 9 (SetAllocatorCallbackX). + std::atomic allocator_callback{0}; + std::atomic allocator_callback_context{0}; + std::atomic mirror{nullptr}; // fence: slot 12's completed value, made on its first call }; template @@ -882,6 +954,7 @@ const char* child_public_name(unsigned slot) { if (slot < kFence1PublicSlots) return fence[slot - 8]; } else { if (slot == 8) return "Reset"; + if (slot == 9) return "SetAllocatorCallbackX"; } return nullptr; } @@ -937,12 +1010,132 @@ void reset_child_stats() { S::overruns.store(0, std::memory_order_relaxed); } -// Frees a proxy whose last reference is gone, with the real object and the device reference it held. +// ---- Fence slot 12: the completed value at an address ---- +// +// Measured on the retail executable (a run past the PC chain, #6982): fence slot 12, one past ID3D12Fence1, is called +// as (value, descriptor, flags), where the descriptor is four words whose second is a code pointer, and the title +// reads the return as a pointer to the fence's 64-bit completed value. It compares that value with ~0 (device +// removed) and subtracts the value it waits for. Refused with E_NOTIMPL, the title dereferences 0x80004001. +// +// A console fence keeps that value in memory the GPU writes. Here each fence gets a mirror that stays live without +// the title calling anything. A thread-pool wait refreshes on a completion event or a timeout. A timeout can +// observe a rewind and subsequent values below the outstanding event's threshold. It does not add another +// completion event. Slot 12 and CPU Signal refresh synchronously. After device removal the callback stops waiting. +// +// The descriptor's code pointer is not called: the measured run goes on without it, and its contract (when it runs, +// on which thread, with what) is not known. The first call is logged with its arguments. +struct FenceMirror { + alignas(8) volatile std::uint64_t completed = 0; // what the title reads through slot 12's pointer + ID3D12Fence* fence = nullptr; // the real fence; the proxy holds the reference + SRWLOCK lock = SRWLOCK_INIT; // orders refreshes + HANDLE event = nullptr; // auto-reset; the real fence sets it at the armed value + PTP_WAIT wait = nullptr; // the thread-pool wait on the completion event + bool stopping = false; // guarded by lock + std::atomic arm_failed{false}; +}; + +std::uint64_t refresh_mirror(FenceMirror* m) { + AcquireSRWLockExclusive(&m->lock); + const std::uint64_t value = m->fence->GetCompletedValue(); + if (m->completed != value) m->completed = value; + ReleaseSRWLockExclusive(&m->lock); + return value; +} + +void wait_for_fence_progress(FenceMirror* mirror) { + constexpr LONGLONG kRewindPollInterval = -10 * 10'000; // 10 ms in relative 100 ns units + ULARGE_INTEGER due{}; + due.QuadPart = static_cast(kRewindPollInterval); + FILETIME timeout{due.LowPart, due.HighPart}; + SetThreadpoolWait(mirror->wait, mirror->event, &timeout); +} + +VOID CALLBACK on_fence_progress(PTP_CALLBACK_INSTANCE, PVOID context, PTP_WAIT, TP_WAIT_RESULT result) { + auto* mirror = static_cast(context); + const std::uint64_t value = refresh_mirror(mirror); + if (value == ~std::uint64_t{0}) return; + if (result == WAIT_OBJECT_0) { + const HRESULT hr = mirror->fence->SetEventOnCompletion(value + 1, mirror->event); + if (FAILED(hr) && !mirror->arm_failed.exchange(true, std::memory_order_relaxed)) + std::fprintf(stderr, "[rt] d3d12_xs: fence slot 12: SetEventOnCompletion failed (0x%08lX); the completed " + "value at the returned address now uses periodic refresh\n", + static_cast(hr)); + } + AcquireSRWLockExclusive(&mirror->lock); + if (!mirror->stopping) wait_for_fence_progress(mirror); + ReleaseSRWLockExclusive(&mirror->lock); +} + +// The fence's mirror, made on the first slot 12 call. Null only when it cannot be allocated. +FenceMirror* fence_mirror(ChildProxy* self) { + if (FenceMirror* m = self->mirror.load(std::memory_order_acquire)) return m; + static SRWLOCK create_lock = SRWLOCK_INIT; + AcquireSRWLockExclusive(&create_lock); + FenceMirror* m = self->mirror.load(std::memory_order_relaxed); + if (!m && (m = new (std::nothrow) FenceMirror)) { + m->fence = reinterpret_cast(self->real); + refresh_mirror(m); + m->event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + if (m->event) m->wait = CreateThreadpoolWait(on_fence_progress, m, nullptr); + if (m->wait) { + wait_for_fence_progress(m); + SetEvent(m->event); // the callback makes the first SetEventOnCompletion + } else { + std::fprintf(stderr, "[rt] d3d12_xs: fence slot 12: no wait for the completed value (error %lu); it " + "moves only on slot 12 and Signal\n", GetLastError()); + if (m->event) CloseHandle(m->event); + m->event = nullptr; + m->wait = nullptr; + } + self->mirror.store(m, std::memory_order_release); + } + ReleaseSRWLockExclusive(&create_lock); + return m; +} + +// Fence slot 12 (value, descriptor, flags): the address of the fence's completed value, refreshed now. +std::uint64_t fence_completed_value_address(ChildProxy* self, std::uint64_t value, std::uint64_t descriptor, + std::uint64_t flags) { + static std::atomic logged{false}; + if (!logged.exchange(true, std::memory_order_relaxed)) + std::fprintf(stderr, "[rt] d3d12_xs: fence slot 12 (value %llu, descriptor 0x%llx, flags 0x%llx): returns " + "the address of the fence's completed value, kept live; the descriptor is not used\n", + static_cast(value), static_cast(descriptor), + static_cast(flags)); + FenceMirror* m = fence_mirror(self); + if (!m) { + std::fprintf(stderr, "[rt] d3d12_xs: fence slot 12: out of memory for the completed value\n"); + return 0; + } + refresh_mirror(m); + return reinterpret_cast(&m->completed); +} + +// Frees a proxy whose last reference is gone, with the real object and the device reference it held. A fence's +// mirror wait is unregistered first, waiting for a callback in flight, so none runs on a released fence. +// +// The mirror's last SetEventOnCompletion can still be pending on the real fence, and nothing cancels one: only the +// fence's destruction drops it. So the event is closed only when this release destroyed the fence. When another +// reference keeps the fence alive, the event stays open (one handle per such fence) and a later completion sets +// that event, not a closed or reused handle. void destroy_child(ChildProxy* self) { IUnknown* real = self->real; DeviceProxy* device = self->device; + FenceMirror* mirror = self->mirror.load(std::memory_order_acquire); + if (mirror && mirror->wait) { + AcquireSRWLockExclusive(&mirror->lock); + mirror->stopping = true; + SetThreadpoolWait(mirror->wait, nullptr, nullptr); + ReleaseSRWLockExclusive(&mirror->lock); + WaitForThreadpoolWaitCallbacks(mirror->wait, TRUE); + CloseThreadpoolWait(mirror->wait); + } delete self; - if (real) real->Release(); + const unsigned long left = real ? real->Release() : 0; + if (mirror) { + if (mirror->event && left == 0) CloseHandle(mirror->event); + delete mirror; + } if (device) proxy_release(device); } @@ -1042,35 +1235,15 @@ void** get_list_vtable(); template void** get_child_vtable(); +// The command-list proxy's helpers (defined with the list proxy below): proxy_real_object checks lists through +// list_real_or_null, since the ListProxy type is complete only there. +IUnknown* list_real_or_null(const void* object); + template bool is_child_proxy(const void* object) { return object && *reinterpret_cast(object) == reinterpret_cast(get_child_vtable()); } -constexpr unsigned kListSlots = 160; -constexpr unsigned kConsoleSetDescriptorHeaps = 32; -constexpr unsigned kConsoleExecuteBundle = 31; -constexpr unsigned kConsoleBarrier = 146; - -struct ListProxy { - void** vtable; // +0x00 - ID3D12GraphicsCommandList* real; // +0x08 - DeviceProxy* device; // +0x10: keeps the Xbox-ABI device alive; GetDevice returns it - // +0x18..: the console object body a title's inline writers read. +0x18 holds the write cursor, +0x28 and - // +0x30 the record limits; the rest is room for the measured flags, header table and pipeline record. - alignas(8) std::uint8_t console_fields[0x600]; - std::atomic refs; // past the console body - unsigned pc_slot_count; // slots the real list implements; mapped slots past it are refused - - void pin_cursor_at_limit() { - const std::uint64_t at_limit = static_cast( - reinterpret_cast(this) + 0x18 + 0x500); - for (const size_t offset : {0x18, 0x28, 0x30}) - std::memcpy(reinterpret_cast(this) + offset, &at_limit, sizeof(at_limit)); - } -}; -static_assert(offsetof(ListProxy, console_fields) == 0x18, "the console fields start at +0x18"); - // The real object behind a heap, queue, fence or list proxy, or null when `object` is none of them. IUnknown* proxy_real_object(const void* object) { if (!object) return nullptr; @@ -1080,8 +1253,7 @@ IUnknown* proxy_real_object(const void* object) { vtable == reinterpret_cast(get_child_vtable()) || vtable == reinterpret_cast(get_child_vtable())) return static_cast(object)->real; - if (vtable == reinterpret_cast(get_list_vtable())) - return static_cast(object)->real; + if (IUnknown* real = list_real_or_null(object)) return real; return nullptr; } @@ -1120,198 +1292,6 @@ class UnwrappedArray { std::uint64_t* data_ = nullptr; }; -struct ListStats { - static inline std::atomic hits[kListSlots]; - static inline std::atomic first[kListSlots]; -}; - -inline void note_list_slot(unsigned slot, std::uint64_t a1 = 0, std::uint64_t a2 = 0, std::uint64_t a3 = 0, std::uint64_t a4 = 0) { - if (slot >= kListSlots) return; - ListStats::hits[slot].fetch_add(1, std::memory_order_relaxed); - bool expected = false; - if (ListStats::first[slot].compare_exchange_strong(expected, true, std::memory_order_relaxed)) - std::fprintf(stderr, "[rt] d3d12_xs: list slot %u first call (args 0x%llx 0x%llx 0x%llx 0x%llx)\n", slot, - static_cast(a1), static_cast(a2), - static_cast(a3), static_cast(a4)); -} - -// Measured Xbox ID3D12GraphicsCommandListX IID passed to device slot 73 (CreateCommandListX). -constexpr IID kXboxGraphicsCommandListXIid = { - 0xc3827890, 0x4024, 0x474c, {0x98, 0xcf, 0x64, 0x5b, 0x51, 0xdc, 0x48, 0x74}}; - -inline bool is_list_iid(const IID& iid) { - return IsEqualIID(iid, __uuidof(IUnknown)) || IsEqualIID(iid, __uuidof(ID3D12Object)) || - IsEqualIID(iid, __uuidof(ID3D12DeviceChild)) || IsEqualIID(iid, __uuidof(ID3D12CommandList)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList1)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList2)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList3)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList4)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList5)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList6)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList7)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList8)) || - IsEqualIID(iid, kXboxGraphicsCommandListXIid); -} - -inline unsigned long list_add_ref(ListProxy* self) { return self->refs.fetch_add(1, std::memory_order_relaxed) + 1; } - -inline void destroy_list(ListProxy* self) { - IUnknown* real = self->real; - DeviceProxy* device = self->device; - delete self; - if (real) real->Release(); - if (device) proxy_release(device); -} - -inline unsigned long list_release(ListProxy* self) { - const unsigned long refs = self->refs.fetch_sub(1, std::memory_order_acq_rel) - 1; - if (refs == 0) destroy_list(self); - return refs; -} - -inline HRESULT list_query_interface(ListProxy* self, const IID* riid, void** out) { - note_list_slot(0, reinterpret_cast(riid), reinterpret_cast(out), 0, 0); - if (!out) return E_POINTER; - *out = nullptr; - if (!riid) return E_POINTER; - if (!is_list_iid(*riid)) { - if (supports_iid(self->real, *riid)) log_refused_iid("list", *riid); - return E_NOINTERFACE; - } - const IID real_iid = IsEqualIID(*riid, kXboxGraphicsCommandListXIid) - ? __uuidof(ID3D12GraphicsCommandList) - : *riid; - if (!supports_iid(self->real, real_iid)) return E_NOINTERFACE; - *out = self; - list_add_ref(self); - return S_OK; -} - -inline unsigned detect_list_slot_count(IUnknown* real) { - if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList8))) return 82; - if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList7))) return 81; - if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList6))) return 80; - if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList5))) return 79; - if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList4))) return 77; - if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList3))) return 68; - if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList2))) return 67; - if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList1))) return 66; - if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList))) return 60; - return 9; -} - -template -std::uint64_t WINAPI list_slot(ListProxy* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, - std::uint64_t a4, std::uint64_t a5, std::uint64_t a6, std::uint64_t a7, - std::uint64_t a8, std::uint64_t a9, std::uint64_t a10, std::uint64_t a11, - std::uint64_t a12, std::uint64_t a13, std::uint64_t a14) { - if constexpr (Slot == 0) { - return hr_to_u64(list_query_interface(self, reinterpret_cast(a1), - reinterpret_cast(a2))); - } else if constexpr (Slot == 1) { - return list_add_ref(self); - } else if constexpr (Slot == 2) { - return list_release(self); - } else if constexpr (Slot == 7) { // GetDevice - note_list_slot(7, a1, a2, 0, 0); - if (a2) *reinterpret_cast(a2) = nullptr; - if (!a1) return hr_to_u64(E_POINTER); - if (!a2) { - using Fn = HRESULT(WINAPI*)(IUnknown*, const IID*, void**); - return hr_to_u64(reinterpret_cast((*reinterpret_cast(self->real))[7])( - self->real, reinterpret_cast(a1), nullptr)); - } - return hr_to_u64(proxy_query_interface(self->device, reinterpret_cast(a1), - reinterpret_cast(a2))); - } else { - note_list_slot(Slot, a1, a2, a3, a4); - constexpr unsigned pc = console_to_pc_list_slot(Slot); - if constexpr (pc == kListNotForwarded) { - if constexpr (Slot == 148) { - static std::atomic logged{false}; - if (!logged.exchange(true, std::memory_order_relaxed)) - std::fprintf(stderr, - "[rt] d3d12_xs: console list slot 148 AllocateUploadMemory stub called (size %llu, align %llu)\n", - static_cast(a1), static_cast(a2)); - } - return 0; - } else { - if (pc >= self->pc_slot_count) { - static std::atomic beyond_warned[kListSlots]; - bool expected = false; - if (beyond_warned[Slot].compare_exchange_strong(expected, true, std::memory_order_relaxed)) - std::fprintf(stderr, - "[rt] d3d12_xs: list slot %u maps to PC slot %u, beyond the real list's %u " - "slots; returning E_NOTIMPL\n", - Slot, pc, self->pc_slot_count); - return hr_to_u64(E_NOTIMPL); - } - using ForwardFn = std::uint64_t(WINAPI*)(void*, std::uint64_t, std::uint64_t, std::uint64_t, - std::uint64_t, std::uint64_t, std::uint64_t, - std::uint64_t, std::uint64_t, std::uint64_t, - std::uint64_t, std::uint64_t, std::uint64_t, - std::uint64_t, std::uint64_t); - auto** const real_vtable = *reinterpret_cast(self->real); - UnwrappedArray heaps; - if constexpr (Slot == 10) { - a1 = unwrap_object(a1); - self->pin_cursor_at_limit(); - } else if constexpr (Slot == kConsoleExecuteBundle) { - a1 = unwrap_object(a1); - } else if constexpr (Slot == kConsoleSetDescriptorHeaps) { - if (!heaps.fill(a2, a1)) return 0; - if (heaps.data()) a2 = heaps.data(); - } - return reinterpret_cast(real_vtable[pc])(self->real, a1, a2, a3, a4, a5, a6, a7, a8, a9, - a10, a11, a12, a13, a14); - } - } -} - -template -void fill_list_vtable(void** vtable, std::index_sequence) { - ((vtable[I] = reinterpret_cast(&list_slot(I)>)), ...); -} - -void** get_list_vtable() { - static void** vtable = [] { - static void* storage[kListSlots]; - fill_list_vtable(storage, std::make_index_sequence{}); - return storage; - }(); - return vtable; -} - -HRESULT wrap_list(IUnknown* created, DeviceProxy* device, const IID* riid, void** out) { - if (out) *out = nullptr; - if (!created) return E_FAIL; - auto* proxy = new (std::nothrow) ListProxy(); - if (!proxy) { - created->Release(); - return E_OUTOFMEMORY; - } - proxy->vtable = get_list_vtable(); - proxy->real = static_cast(created); - proxy->device = device; - proxy->refs.store(1, std::memory_order_relaxed); - proxy->pc_slot_count = detect_list_slot_count(created); - proxy->pin_cursor_at_limit(); - proxy_add_ref(device); - - const HRESULT hr = list_query_interface(proxy, riid, out); - if (FAILED(hr)) { - destroy_list(proxy); - return hr; - } - static std::atomic logged{false}; - if (!d3d12_trace::enabled() && (!logged.exchange(true, std::memory_order_relaxed) || trace_enabled())) - std::fprintf(stderr, "[rt] d3d12_xs: list proxy %p wraps %p (%u PC vtable slots)\n", - static_cast(proxy), static_cast(created), proxy->pc_slot_count); - proxy->refs.fetch_sub(1, std::memory_order_relaxed); - return S_OK; -} - // The vtable read for a slot past a table faults in the reservation behind it; name the slot. Only reads the // exception record and writes with WriteFile, so it is safe whatever the faulting thread holds. template @@ -1402,31 +1382,237 @@ const XboxQueueSlotRoutes& xbox_queue_slot_routes() { return routes; } -template -std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, - std::uint64_t a4, std::uint64_t a5, std::uint64_t a6, std::uint64_t a7, - std::uint64_t a8, std::uint64_t a9, std::uint64_t a10, std::uint64_t a11, - std::uint64_t a12, std::uint64_t a13, std::uint64_t a14) { - if constexpr (Slot == 0) { - d3d12_trace::record(child_trace_name(Slot)); - return hr_to_u64(child_query_interface(self, reinterpret_cast(a1), - reinterpret_cast(a2))); - } else if constexpr (Slot == 1) { - return child_add_ref(self); - } else if constexpr (Slot == 2) { - return child_release(self); - } else if constexpr (Slot == 7) { - d3d12_trace::record(child_trace_name(Slot)); - return hr_to_u64(child_get_device(self, reinterpret_cast(a1), - reinterpret_cast(a2))); +// ---- PresentX on the queue (LEONIDA_VULKAN_DEVICE) --------------------------------------------------------- +// +// The measured console queue slots (docs/d3d12_xs_console_abi.md §4): the older runtime keeps the PC order — +// Signal 14, Wait 15, frequency 16, calibration 17, GetDesc 18 — and presents at slot 30, with SignalX at 23. A +// newer game OS inserts two methods before Signal: Signal 16, Wait 17, frequency 18, calibration 19, GetDesc 20, +// SignalX 25, PresentX 32. The layout is detected once, by a fence object reaching slot 16 or 17 (the older +// layout's frequency and calibration getters take no object argument) or by a fence reaching SignalX slot 25 — +// a title that signals only through SignalX would otherwise stay undetected and lose every signal. +// +// Every other console-only queue method answers S_OK (sibling layer: title frame pacing flows through them, and a +// refusal wedges the present loop), still recorded by note_child_slot. Slot 148's AllocateUploadMemory is a list +// method, not a queue method, so it is not part of this table. + +#ifdef LEONIDA_VULKAN_DEVICE + +struct PresentState { + ~PresentState() { + // The fallback window belongs to its own thread (fallback_window_thread): that thread destroys it. + if (window) PostMessageW(window, WM_APP + 1, 0, 0); + } + HWND window = nullptr; // the runtime's own fallback window, when the title has no window to present in + std::unique_ptr xbox; +}; + +void destroy_present_state(void* present_state) { + delete static_cast(present_state); +} + +LRESULT CALLBACK present_window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) { + switch (message) { + case WM_APP + 1: // ~PresentState + DestroyWindow(window); + return 0; + case WM_CLOSE: // the user closed the only window the run has: the run ends with it + TerminateProcess(GetCurrentProcess(), 0); + return 0; + case WM_DESTROY: + PostQuitMessage(0); + return 0; + case WM_ERASEBKGND: + return 1; // the frames cover the client area; nothing to erase + default: + return DefWindowProcW(window, message, wparam, lparam); + } +} + +// The runtime's own window, for a title that has made none by its first PresentX. It is shown, and it lives on a +// thread of its own that reads its messages: a visible window whose thread never does is "not responding" to the +// window manager. LEONIDA_PRESENT_WINDOW=hidden keeps it hidden (frames are still rendered and captured). +struct FallbackWindowStart { + HANDLE ready = nullptr; + HWND window = nullptr; + bool show = true; +}; + +DWORD WINAPI fallback_window_thread(LPVOID parameter) { + auto* start = static_cast(parameter); + WNDCLASSW window_class{}; + window_class.lpfnWndProc = present_window_proc; + window_class.hInstance = GetModuleHandleW(nullptr); + window_class.lpszClassName = L"LeonidaPresentX"; + window_class.hCursor = LoadCursorW(nullptr, reinterpret_cast(IDC_ARROW)); + HWND window = nullptr; + if (!RegisterClassW(&window_class) && GetLastError() != ERROR_CLASS_ALREADY_EXISTS) { + std::fprintf(stderr, "[rt] d3d12_xs: PresentX window class failed (error %lu)\n", GetLastError()); } else { - note_child_slot(Slot); - if constexpr (K == ChildKind::queue && Slot == kQueueExecuteCommandListsX) { + // A 1920x1080 client area where the desktop has room for it; the window manager may still size it. + RECT frame{0, 0, 1920, 1080}; + AdjustWindowRect(&frame, WS_OVERLAPPEDWINDOW, FALSE); + window = CreateWindowExW(0, window_class.lpszClassName, L"Leonida", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, + CW_USEDEFAULT, frame.right - frame.left, frame.bottom - frame.top, nullptr, nullptr, + window_class.hInstance, nullptr); + if (!window) std::fprintf(stderr, "[rt] d3d12_xs: PresentX window failed (error %lu)\n", GetLastError()); + } + if (window && start->show) ShowWindow(window, SW_SHOWNOACTIVATE); + start->window = window; + SetEvent(start->ready); // `start` belongs to the creator again from here on + if (!window) return 0; + MSG message{}; + while (GetMessageW(&message, nullptr, 0, 0) > 0) { + TranslateMessage(&message); + DispatchMessageW(&message); + } + return 0; +} + +HWND create_fallback_window(bool show) { + FallbackWindowStart start; + start.show = show; + start.ready = CreateEventW(nullptr, TRUE, FALSE, nullptr); + if (!start.ready) return nullptr; + HANDLE thread = CreateThread(nullptr, 0, fallback_window_thread, &start, 0, nullptr); + if (thread) { + WaitForSingleObject(start.ready, INFINITE); + CloseHandle(thread); + } + CloseHandle(start.ready); + return thread ? start.window : nullptr; +} + +// Lazily builds the window, presenter and XboxPresentation a console PresentX needs, once per device. Returns the +// state even when `xbox` stays null (no presentation support): the failure is logged once, not retried. +// +// Where the frames go (LEONIDA_PRESENT_WINDOW): by default the title's own top-level window when it has one by now +// (title_window.h: a GDKX title makes one and shows it, and with nothing presented in it the user sees an empty white +// window), else a window of the runtime's own, shown. "own" always uses the runtime's window; "hidden" uses the +// runtime's window and never shows it, which is what every build before this one did. +PresentState* present_state_for(DeviceProxy* device, bool splash_only = false) { + std::lock_guard lock(device->present_state_mutex); + if (auto* state = static_cast(device->present_state)) return state; + char mode[16] = {}; + std::size_t mode_length = 0; + if (getenv_s(&mode_length, mode, sizeof(mode), "LEONIDA_PRESENT_WINDOW") != 0) mode[0] = '\0'; + const bool hidden = std::strcmp(mode, "hidden") == 0; + const bool own = hidden || std::strcmp(mode, "own") == 0; + HWND target = own ? nullptr : rt::d3d12::find_title_window(GetCurrentProcessId()); + RECT client{}; + if (target && (!GetClientRect(target, &client) || client.right <= client.left || client.bottom <= client.top)) + target = nullptr; // minimised or zero-sized: nothing to present in + Microsoft::WRL::ComPtr splash; + if (splash_only) { + const auto* info = rt::d3d12::vulkan_device_info(device->real); + if (!target || !info || !info->presentation) return nullptr; + splash.Attach(rt::package_splash::create_texture(device->real, UINT(client.right), UINT(client.bottom))); + if (!splash) return nullptr; + } + std::unique_ptr pending(new (std::nothrow) PresentState); + if (!pending) return nullptr; + PresentState* state = pending.get(); + if (!splash_only) device->present_state = pending.release(); + const bool titles = target != nullptr; + if (!target) { + state->window = create_fallback_window(!hidden); + target = state->window; + if (!target) return state; + GetClientRect(target, &client); + } + auto presenter = rt::d3d12::create_window_presenter(device->real, target); + if (!presenter) { + if (splash_only) return nullptr; // ordinary PresentX will still try + std::fprintf(stderr, "[rt] d3d12_xs: no window presenter on this device; PresentX is a no-op\n"); + return state; + } + if (splash_only) { + // Show the shell frame before the title starts creating its pipelines. Use the same swapchain for PresentX. + if (!presenter->present_splash(splash.Get())) return nullptr; + rt::startup_trace::event("package_splash_present"); + } + // The title takes its frame tokens from device slot 80 (WaitFrameEventX), which numbers them from the device's + // FrameTokenSource. The pacer refuses a token above the ones its source issued, so it must count from the same + // source: with a pacer-owned one every PresentX after the first wait is refused with E_INVALIDARG (#7496, #7685). + state->xbox = std::make_unique(std::move(presenter), nullptr, device->frame_tokens); + if (splash_only) device->present_state = pending.release(); + std::fprintf(stderr, "[rt] d3d12_xs: PresentX ready (window %p: %s, client area %ldx%ld)\n", + static_cast(target), + titles ? "the title's own window" : hidden ? "the runtime's window, hidden" : "the runtime's window", + static_cast(client.right - client.left), static_cast(client.bottom - client.top)); + return state; +} + +std::uint64_t queue_present_x(ChildProxy* self, std::uint64_t plane_count, std::uint64_t planes, + std::uint64_t params) { + PresentState* state = self->device ? present_state_for(self->device) : nullptr; + if (!state || !state->xbox) return hr_to_u64(S_OK); // a title still runs with nothing presented + return hr_to_u64(state->xbox->PresentX( + static_cast(plane_count), + reinterpret_cast(planes), + reinterpret_cast(params))); +} + +#else // !LEONIDA_VULKAN_DEVICE: this translation unit stands alone (mock and COM tests) + +void destroy_present_state(void*) {} + +std::uint64_t queue_present_x(ChildProxy*, std::uint64_t, std::uint64_t, std::uint64_t) { + return hr_to_u64(S_OK); +} + +#endif + +template +std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, + std::uint64_t a4, std::uint64_t a5, std::uint64_t a6, std::uint64_t a7, + std::uint64_t a8, std::uint64_t a9, std::uint64_t a10, std::uint64_t a11, + std::uint64_t a12, std::uint64_t a13, std::uint64_t a14) { + if constexpr (Slot == 0) { + d3d12_trace::record(child_trace_name(Slot)); + return hr_to_u64(child_query_interface(self, reinterpret_cast(a1), + reinterpret_cast(a2))); + } else if constexpr (Slot == 1) { + return child_add_ref(self); + } else if constexpr (Slot == 2) { + return child_release(self); + } else if constexpr (Slot == 7) { + d3d12_trace::record(child_trace_name(Slot)); + return hr_to_u64(child_get_device(self, reinterpret_cast(a1), + reinterpret_cast(a2))); + } else if constexpr (K == ChildKind::fence && Slot == kFenceCompletedValueSlot) { + // Past ID3D12Fence1, so whether the real fence has Fence1 does not matter here. + note_child_slot(Slot); + d3d12_trace::record(child_trace_name(Slot)); + return fence_completed_value_address(self, a1, a2, a3); + } else { + note_child_slot(Slot); + if constexpr (K == ChildKind::queue && Slot == kQueueExecuteCommandListsX) { d3d12_trace::record(child_trace_name(Slot)); return queue_execute_command_lists(self, a1, a2); } - if (Slot >= self->slot_count) { - if constexpr (K == ChildKind::queue) { + if constexpr (K == ChildKind::allocator && Slot == 9) { + // Console-only ID3D12CommandAllocator::SetAllocatorCallbackX(callback, context, ...), observed past the + // 9-slot PC chain on the retail executable (call shape: function pointer, context, plus trailing words). + // The PC/Vulkan layer manages command-buffer backing directly without invoking a title allocator callback, + // so record the callback and context on the proxy and return S_OK while leaving slots 10+ refused. + self->allocator_callback.store(static_cast(a1), std::memory_order_relaxed); + self->allocator_callback_context.store(static_cast(a2), std::memory_order_relaxed); + static std::atomic logged{false}; + if (!logged.exchange(true, std::memory_order_relaxed)) { + std::fprintf(stderr, + "[rt] d3d12_xs: allocator slot 9 (SetAllocatorCallbackX) recorded " + "(callback=0x%llx context=0x%llx a3=0x%llx a4=0x%llx)\n", + static_cast(a1), static_cast(a2), + static_cast(a3), static_cast(a4)); + } + d3d12_trace::record(child_trace_name(Slot)); + return hr_to_u64(S_OK); + } + if constexpr (K == ChildKind::queue) { + // A presenter attached with set_presentation_handler (rt::d3d12::attach_xbox_presentation) answers the + // slots routed to it (PresentX at 30 or LEONIDA_XS_PRESENT_X_SLOT, SuspendX and ResumeX when their + // variables are set) before the built-in console queue methods below. + if (Slot >= self->slot_count) { const XboxQueueSlotRoutes& qroutes = xbox_queue_slot_routes(); HRESULT hr = S_OK; if (call_presentation(self->device, [&](const PresentationHandler& p) { @@ -1447,6 +1633,102 @@ std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_ })) return hr_to_u64(hr); } + } + if constexpr (K == ChildKind::queue) { + // Layout detection (the comment at the PresentX section): a fence reaching slot 16 or 17 is the newer + // layout's Signal/Wait; anything else there is the older layout's frequency/calibration getter. A + // fence at slot 14 or 15 is the older Signal/Wait; a non-fence argument there is one of the newer + // layout's two inserted console methods. + // A queue made after another one detected the layout inherits it from the device; undetected queues + // assume the older layout, whose unshifted slots are also the PC chain. A fence reaching SignalX + // slot 25 while the layout is still unknown is itself the newer-layout evidence: a title that + // signals only through SignalX never reaches Signal/Wait at 16/17, and an unanswered SignalX + // returns S_OK having signalled nothing, leaving a waiter on that fence value hanging. + const bool newer = [&] { + const unsigned char own = self->queue_layout.load(std::memory_order_relaxed); + if (own == ChildProxy::kQueueLayoutNewer) return true; + const unsigned char shared = + self->device->console_layout.load(std::memory_order_relaxed); + return own == ChildProxy::kQueueLayoutUnknown && shared == ChildProxy::kQueueLayoutNewer; + }(); + if (Slot == 16 || Slot == 17) { + if (IUnknown* fence = proxy_real_object(reinterpret_cast(a1))) { + self->queue_layout.store(ChildProxy::kQueueLayoutNewer, std::memory_order_relaxed); + self->device->console_layout.store(ChildProxy::kQueueLayoutNewer, + std::memory_order_relaxed); + using Fn = HRESULT(WINAPI*)(IUnknown*, IUnknown*, UINT64); + return hr_to_u64(reinterpret_cast(self->real_vtable[kQueueSignal + (Slot - 16)])( + self->real, fence, a2)); + } + if (newer) return hr_to_u64(S_OK); // proven newer: a non-fence Signal/Wait arg is malformed, + // not evidence of the older layout — do not downgrade the shared detection on it + if (self->queue_layout.load(std::memory_order_relaxed) == + ChildProxy::kQueueLayoutUnknown) { + self->queue_layout.store(ChildProxy::kQueueLayoutOlder, std::memory_order_relaxed); + self->device->console_layout.store(ChildProxy::kQueueLayoutOlder, + std::memory_order_relaxed); + } + } else if ((Slot == 14 || Slot == 15) && !proxy_real_object(reinterpret_cast(a1)) && + newer) { + return hr_to_u64(S_OK); // the newer layout's two inserted console methods, unmeasured + } + if (newer && Slot >= 18 && Slot <= 20) { + // Newer layout: frequency 18, calibration 19, GetDesc 20 are the PC slots 16-18 shifted. + d3d12_trace::record(child_trace_name(Slot)); + using ForwardFn = std::uint64_t(WINAPI*)(void*, std::uint64_t, std::uint64_t, std::uint64_t, + std::uint64_t, std::uint64_t, std::uint64_t, + std::uint64_t, std::uint64_t, std::uint64_t, + std::uint64_t, std::uint64_t, std::uint64_t, + std::uint64_t, std::uint64_t); + auto fn = reinterpret_cast(self->real_vtable[Slot - 2]); + return fn(self->real, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14); + } + // Slot 18 while the layout is still unknown is ambiguous: the older GetDesc (a struct-return + // write of a whole desc) or the newer frequency getter (an 8-byte out). Answering it as GetDesc + // writes far past the 8 bytes a frequency caller passes, so the call goes to the frequency + // getter — the only interpretation that cannot overrun its argument, and a title often queries + // the frequency before its first fence call. A proven-older queue keeps the generic GetDesc + // path below; slots 19 and 20 stay no-ops, since their newer interpretations write through + // caller pointers an unmodelled older method might not supply. + if (Slot == 18 && !newer && self->queue_layout == ChildProxy::kQueueLayoutUnknown && + self->device->console_layout.load(std::memory_order_relaxed) != + ChildProxy::kQueueLayoutOlder) { + d3d12_trace::record(child_trace_name(Slot)); + using Fn = HRESULT(WINAPI*)(IUnknown*, UINT64*); + return hr_to_u64(reinterpret_cast(self->real_vtable[16])( + self->real, reinterpret_cast(a1))); + } + if (Slot == (newer ? 25u : 23u) || + (Slot == 25u && self->queue_layout.load(std::memory_order_relaxed) == + ChildProxy::kQueueLayoutUnknown && + self->device->console_layout.load(std::memory_order_relaxed) == + ChildProxy::kQueueLayoutUnknown)) { + // SignalX: console Signal (older 23, newer 25); the extra X word is dropped. The slot-25 + // alternative is the fence itself carrying the layout evidence, per the comment above; a + // proven-older queue still leaves slot 25 to the console-only no-op, since its fence-taking + // methods sit at 14/15/23 there. + if (IUnknown* fence = proxy_real_object(reinterpret_cast(a1))) { + if (Slot == 25u && !newer) { + self->queue_layout.store(ChildProxy::kQueueLayoutNewer, + std::memory_order_relaxed); + self->device->console_layout.store(ChildProxy::kQueueLayoutNewer, + std::memory_order_relaxed); + } + static std::atomic logged{false}; + if (!logged.exchange(true, std::memory_order_relaxed)) + std::fprintf(stderr, "[rt] d3d12_xs: SignalX (queue slot %u) forwarded as Signal\n", Slot); + using Fn = HRESULT(WINAPI*)(IUnknown*, IUnknown*, UINT64); + return hr_to_u64(reinterpret_cast(self->real_vtable[kQueueSignal])(self->real, fence, a2)); + } + return hr_to_u64(S_OK); + } + if (Slot == (newer ? 32u : 30u)) return queue_present_x(self, a1, a2, a3); // PresentX + if (Slot >= self->slot_count || (newer && (Slot == 14 || Slot == 15))) { + d3d12_trace::record(child_trace_name(Slot), "console-only"); + return hr_to_u64(S_OK); // unmodelled console queue methods: frame pacing flows through them + } + } + if (Slot >= self->slot_count) { bool expected = false; if (ChildStats::beyond_warned[Slot].compare_exchange_strong(expected, true, std::memory_order_relaxed)) { @@ -1478,6 +1760,11 @@ std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_ std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t); auto fn = reinterpret_cast(self->real_vtable[Slot]); + if constexpr (K == ChildKind::fence && Slot == kFenceSignal) { + const std::uint64_t result = fn(self->real, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14); + if (FenceMirror* m = self->mirror.load(std::memory_order_acquire)) refresh_mirror(m); + return result; + } return fn(self->real, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14); } } @@ -1535,43 +1822,624 @@ void** get_child_vtable() { // Wraps `created` (one reference, owned by the proxy on success, released on failure) and returns `riid` from the // proxy through `out`. -template -HRESULT wrap_child(IUnknown* created, DeviceProxy* device, const IID* riid, void** out) { +template +HRESULT wrap_child(IUnknown* created, DeviceProxy* device, const IID* riid, void** out) { + if (!created) return E_FAIL; + ChildProxy* proxy = new (std::nothrow) ChildProxy; + if (!proxy) { + created->Release(); + return E_OUTOFMEMORY; + } + proxy->vtable = get_child_vtable(); + proxy->real = created; + proxy->device = device; + proxy->real_vtable = *reinterpret_cast(created); + if constexpr (K == ChildKind::queue) { + proxy->slot_count = kQueuePublicSlots; + } else if constexpr (K == ChildKind::fence) { + proxy->slot_count = supports_iid(created, __uuidof(ID3D12Fence1)) ? kFence1PublicSlots : kFencePublicSlots; + } else { + proxy->slot_count = kAllocatorPublicSlots; + } + proxy->refs.store(1, std::memory_order_relaxed); + proxy_add_ref(device); // the object keeps its Xbox-ABI device alive for GetDevice + + const HRESULT hr = child_query_interface(proxy, riid, out); + if (FAILED(hr)) { + destroy_child(proxy); // no reference escaped + return hr; + } + // Titles create fences at run time: the first proxy of each kind is logged, every one only with XS_TRACE. + static std::atomic logged{false}; + if (!d3d12_trace::enabled() && (!logged.exchange(true, std::memory_order_relaxed) || trace_enabled())) + std::fprintf(stderr, "[rt] d3d12_xs: %s proxy %p wraps %p (device proxy %p, %u public slots)\n", + child_kind_name(), static_cast(proxy), static_cast(created), + static_cast(device), proxy->slot_count); + proxy->refs.fetch_sub(1, std::memory_order_relaxed); // drop the creation reference; `out` holds the caller's + return S_OK; +} + +// ---- Command list proxy --------------------------------------------------------------------------------- +// +// Device slot 12 (CreateCommandList) hands the title a console-shaped command list: the console vtable order, a +// 160-slot table, and the object fields the console SDK's inline writers touch (docs/d3d12_xs_console_abi.md +// §5). The write cursor (+0x18) is pinned at both limits (+0x28, +0x30), so a title always finds the record +// buffer full and takes the vtable path for every command — the proxy never has to interpret inline records. +// The flag bytes (+0x140..+0x143), the root-parameter header table (+0x344) and the pipeline record (+0x544) +// stay zeroed: they are only read while writing a record, which never happens at the limit. +// +// The console slot order keeps the PC order through slot 26 (measured: 9, 10, 12-17, 19, 20, 25, 26), places +// four console-only methods at 27-30, then the PC chain resumes shifted +4 — confirmed at console 32->PC 28 +// (SetDescriptorHeaps), 33->29, 41->37, 43->39, 45->41, 48->44, 51->47 and 53->49, and the same shift fills the +// block through console 59 -> PC 55. The console has no PIX markers: console 60 is EndEvent (PC 58) and 61 is +// ExecuteIndirect (PC 59, package-measured). Console 146 is the enhanced Barrier taking one D3D12_BARRIER_GROUP +// (package-confirmed; PC equivalent is GCL7 slot 80). Console-only slots — the 27-30 extras, AllocateUploadMemory +// (148), the disputed tail past 61 and the newer-layout +2 tail — are recorded with their first argument words +// and return 0 without a PC call: a wrong forward is worse than a clean refusal. + +constexpr unsigned kListSlots = 160; +// ---- Upload memory (console list slot 148, AllocateUploadMemory) ---- +// +// On the console the CPU and GPU share one address space: the pointer AllocateUploadMemory(size, alignment) +// returns is written by the CPU and handed to the GPU unchanged — the package measures it going straight into a +// root SRV (docs/d3d12_xs_console_abi.md §5.3, d3d12_command_objects.md §3.3a). A PC has two address spaces, so +// each arena chunk is a persistently-mapped UPLOAD-heap buffer: the title gets the CPU pointer and writes the +// very memory the GPU samples, and the root-descriptor setters translate a chunk address to the buffer's device +// address (the same backing memory) before forwarding. Translation covers the six root VA setters (console +// 41-46); VAs inside view structs (IASetVertexBuffers/IASetIndexBuffer) and ExecuteIndirect arguments are not +// rewritten yet and stay title addresses. + +struct UploadChunk { + UploadChunk* next; + ID3D12Resource* resource; // the mapped buffer; released with the chunk + std::uint8_t* cpu_base; + D3D12_GPU_VIRTUAL_ADDRESS gpu_base; + std::size_t size; + std::size_t used; +}; + +struct UploadArena { + UploadChunk* chunks = nullptr; + std::mutex lock; +}; + +constexpr std::size_t kUploadChunkMin = 8 << 20; // one chunk serves a title's whole frame of uploads + +UploadChunk* upload_chunk_new(DeviceProxy* device, std::size_t size) { + auto* chunk = new (std::nothrow) UploadChunk{}; + if (!chunk) return nullptr; + chunk->size = size; + + D3D12_HEAP_PROPERTIES heap = {}; + heap.Type = D3D12_HEAP_TYPE_UPLOAD; + D3D12_RESOURCE_DESC desc = {}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = size; + desc.Height = 1; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + ID3D12Resource* resource = nullptr; + const HRESULT hr = device->real->CreateCommittedResource( + &heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + __uuidof(ID3D12Resource), reinterpret_cast(&resource)); + void* cpu = nullptr; + if (SUCCEEDED(hr) && resource && SUCCEEDED(resource->Map(0, nullptr, &cpu)) && cpu && + resource->GetGPUVirtualAddress() != 0) { + chunk->resource = resource; + chunk->cpu_base = static_cast(cpu); + chunk->gpu_base = resource->GetGPUVirtualAddress(); + return chunk; + } + if (resource) resource->Release(); + // A device that cannot hand out a mapped buffer (a mock, or an older layer without buffer device + // addresses) still gets memory to write; upload_translate leaves its addresses alone. + auto* cpu_fallback = static_cast( + VirtualAlloc(nullptr, size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); + if (!cpu_fallback) { + delete chunk; + return nullptr; + } + chunk->cpu_base = cpu_fallback; + chunk->gpu_base = reinterpret_cast(cpu_fallback); + return chunk; +} + +std::uint64_t upload_alloc(DeviceProxy* device, std::uint64_t size, std::uint64_t alignment) { + if (!device || !size) return 0; + alignment = alignment < 16 ? 16 : alignment; // every measured call asked for 16 + // Refuse what cannot be served before any arithmetic runs: only power-of-two alignments are measured, + // chunks map at 64K granularity at best, and a size too big to add the alignment to would wrap the + // checks below — one such call returned a pointer and left the cursor so the next request re-handed + // the same range (daemosofchaos's report on #2490). + if ((alignment & (alignment - 1)) != 0 || alignment > (64 << 10) || + size > ~static_cast(0) - alignment) { + std::fprintf(stderr, "[rt] d3d12_xs: AllocateUploadMemory(%llu, %llu) refused\n", + static_cast(size), static_cast(alignment)); + return 0; + } + auto* arena = static_cast(device->upload_state.load(std::memory_order_acquire)); + if (!arena) { + auto* fresh = new (std::nothrow) UploadArena; + if (!fresh) return 0; + void* expected = nullptr; // a concurrent first call loses its arena but keeps the winner's chunks + if (device->upload_state.compare_exchange_strong(expected, fresh, std::memory_order_acq_rel)) + arena = fresh; + else { + delete fresh; + arena = static_cast(expected); + } + } + std::lock_guard lock(arena->lock); + const std::size_t need = static_cast(size); + for (UploadChunk* chunk = arena->chunks; chunk; chunk = chunk->next) { + const std::size_t aligned = (chunk->used + (alignment - 1)) & ~(static_cast(alignment) - 1); + if (aligned >= chunk->used && aligned <= chunk->size && need <= chunk->size - aligned) { + chunk->used = aligned + need; + return reinterpret_cast(chunk->cpu_base + aligned); + } + } + const std::size_t chunk_size = need + alignment > kUploadChunkMin ? need + alignment : kUploadChunkMin; + UploadChunk* chunk = upload_chunk_new(device, chunk_size); + if (!chunk) { + std::fprintf(stderr, "[rt] d3d12_xs: AllocateUploadMemory(%llu, %llu) failed\n", + static_cast(size), static_cast(alignment)); + return 0; + } + chunk->next = arena->chunks; + arena->chunks = chunk; + const std::size_t aligned = (alignment - 1) & ~(static_cast(alignment) - 1); // 0-based + chunk->used = aligned + need; + return reinterpret_cast(chunk->cpu_base + aligned); +} + +// An address inside an upload chunk becomes the chunk's device address plus the offset; anything else — a +// real resource VA the title already holds — passes through. +std::uint64_t upload_translate(DeviceProxy* device, std::uint64_t va) { + auto* arena = static_cast( + device ? device->upload_state.load(std::memory_order_acquire) : nullptr); + if (!arena) return va; + std::lock_guard lock(arena->lock); + for (UploadChunk* chunk = arena->chunks; chunk; chunk = chunk->next) { + const std::uint64_t base = reinterpret_cast(chunk->cpu_base); + if (va >= base && va < base + chunk->size) return chunk->gpu_base + (va - base); + } + return va; +} + +void destroy_upload_state(void* upload_state) { + auto* arena = static_cast(upload_state); + if (!arena) return; + for (UploadChunk* chunk = arena->chunks; chunk;) { + UploadChunk* next = chunk->next; + if (chunk->resource) { + chunk->resource->Unmap(0, nullptr); + chunk->resource->Release(); + } else { + VirtualFree(chunk->cpu_base, 0, MEM_RELEASE); + } + delete chunk; + chunk = next; + } + delete arena; +} + +constexpr unsigned kConsoleSetDescriptorHeaps = 32; +constexpr unsigned kConsoleExecuteBundle = 31; +constexpr unsigned kConsoleOMSetRenderTargets = 50; +constexpr unsigned kConsoleClearDepthStencilView = 51; +constexpr unsigned kConsoleClearRenderTargetView = 52; +constexpr unsigned kConsoleClearUavUint = 53; +constexpr unsigned kConsoleClearUavFloat = 54; +constexpr unsigned kConsoleReset = 139; +constexpr unsigned kConsoleBarrier = 146; +constexpr unsigned kConsoleAllocateUpload = 148; + +// console_to_pc_list_slot and kListNotForwarded are in d3d12_xs_device.h (the mock tests check the table). +static_assert(console_to_pc_list_slot(kConsoleReset) == 10 && console_to_pc_list_slot(kConsoleBarrier) == 80, + "the console list table names Reset and Barrier"); + +struct ListProxy { + void** vtable; // +0x00 + ID3D12GraphicsCommandList* real; // +0x08 + DeviceProxy* device; // +0x10: keeps the Xbox-ABI device alive; GetDevice returns it + // +0x18..: the console object body a title's inline writers read. +0x18 holds the write cursor, +0x28 and + // +0x30 the record limits; the rest is room for the measured flags, header table and pipeline record. + alignas(8) std::uint8_t console_fields[0x600]; + std::atomic refs; // past the console body + unsigned pc_slot_count; // slots the real list implements; mapped slots past it are refused + std::vector vb_scratch; // slot-48 views with their VAs translated + std::vector so_scratch; // slot-49 views, same treatment + + void pin_cursor_at_limit() { + const std::uint64_t at_limit = static_cast( + reinterpret_cast(this) + 0x18 + 0x500); + for (const size_t offset : {0x18, 0x28, 0x30}) + std::memcpy(reinterpret_cast(this) + offset, &at_limit, sizeof(at_limit)); + } +}; +static_assert(offsetof(ListProxy, console_fields) == 0x18, "the console fields start at +0x18"); + +struct ListStats { + static inline std::atomic hits[kListSlots]; + static inline std::atomic first[kListSlots]; +}; + +// The list tail (D3D-445). From CopyTextureRegionX on, the newer console layout sits two slots later than the older +// one (docs/d3d12_xs_console_abi.md 5.3). The table is keyed by the older-layout slot. Only CopyTextureRegionX has a +// measured name; the other measured pairs are named by their older slot, so that both layouts print the same text +// for the same method. +struct ListTailName { + unsigned older_slot; + const char* name; +}; +constexpr ListTailName kListTailNames[] = { + {83, "CopyTextureRegionX"}, {84, "tail method, older slot 84"}, {85, "tail method, older slot 85"}, + {88, "tail method, older slot 88"}, {89, "tail method, older slot 89"}, {90, "tail method, older slot 90"}, + {93, "tail method, older slot 93"}, {94, "tail method, older slot 94"}, +}; +constexpr unsigned kListTailShift = 2; +static_assert(kConsoleLayoutOlder == ChildProxy::kQueueLayoutOlder && + kConsoleLayoutNewer == ChildProxy::kQueueLayoutNewer, + "the list tail names use the queue proxy's layout values"); + +// Null while the layout is unknown, and for a slot that is not a measured tail slot of that layout: a slot number +// never gets the other layout's name. +const char* list_tail_name(unsigned slot, unsigned char console_layout) { + if (console_layout != kConsoleLayoutOlder && console_layout != kConsoleLayoutNewer) return nullptr; + const unsigned shift = console_layout == kConsoleLayoutNewer ? kListTailShift : 0; + if (slot < shift) return nullptr; + for (const ListTailName& entry : kListTailNames) + if (entry.older_slot == slot - shift) return entry.name; + return nullptr; +} + +void note_list_slot(unsigned slot, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, std::uint64_t a4, + unsigned char console_layout = 0) { + if (slot >= kListSlots) return; + ListStats::hits[slot].fetch_add(1, std::memory_order_relaxed); + bool expected = false; + if (ListStats::first[slot].compare_exchange_strong(expected, true, std::memory_order_relaxed)) { + const char* name = list_tail_name(slot, console_layout); + std::fprintf(stderr, "[rt] d3d12_xs: list slot %u%s%s%s first call (args 0x%llx 0x%llx 0x%llx 0x%llx)\n", slot, + name ? " (" : "", name ? name : "", name ? ")" : "", static_cast(a1), + static_cast(a2), static_cast(a3), + static_cast(a4)); + } +} + +// Measured Xbox ID3D12GraphicsCommandListX IID passed to device slot 73 (CreateCommandListX). +constexpr IID kXboxGraphicsCommandListXIid = { + 0xc3827890, 0x4024, 0x474c, {0x98, 0xcf, 0x64, 0x5b, 0x51, 0xdc, 0x48, 0x74}}; + +// The interfaces the console list answers: the base chain, ID3D12CommandList and every graphics-command-list +// interface the real list implements — on the console the list is a single object, so any of them returns the +// proxy. +bool is_list_iid(const IID& iid) { + return IsEqualIID(iid, __uuidof(IUnknown)) || IsEqualIID(iid, __uuidof(ID3D12Object)) || + IsEqualIID(iid, __uuidof(ID3D12DeviceChild)) || IsEqualIID(iid, __uuidof(ID3D12CommandList)) || + IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList)) || + IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList1)) || + IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList2)) || + IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList3)) || + IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList4)) || + IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList5)) || + IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList6)) || + IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList7)) || + IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList8)) || + IsEqualIID(iid, kXboxGraphicsCommandListXIid); +} + +unsigned long list_add_ref(ListProxy* self) { return self->refs.fetch_add(1, std::memory_order_relaxed) + 1; } + +void destroy_list(ListProxy* self) { + IUnknown* real = self->real; + DeviceProxy* device = self->device; + delete self; + if (real) real->Release(); + if (device) proxy_release(device); +} + +unsigned long list_release(ListProxy* self) { + const unsigned long refs = self->refs.fetch_sub(1, std::memory_order_acq_rel) - 1; + if (refs == 0) destroy_list(self); + return refs; +} + +HRESULT list_query_interface(ListProxy* self, const IID* riid, void** out) { + note_list_slot(0, reinterpret_cast(riid), reinterpret_cast(out), 0, 0); + if (!out) return E_POINTER; + *out = nullptr; + if (!riid) return E_POINTER; + if (!is_list_iid(*riid)) { + if (supports_iid(self->real, *riid)) log_refused_iid("list", *riid); + return E_NOINTERFACE; + } + // The console command-list IID (device slot 73 passes it) is answered as ID3D12GraphicsCommandList. + const IID real_iid = IsEqualIID(*riid, kXboxGraphicsCommandListXIid) + ? __uuidof(ID3D12GraphicsCommandList) + : *riid; + if (!supports_iid(self->real, real_iid)) return E_NOINTERFACE; + *out = self; + list_add_ref(self); + return S_OK; +} + +// Highest list interface the real object implements; its cumulative slot count bounds mapped forwards +// (ID3D12GraphicsCommandList8 ends at slot 81, OMSetFrontAndBackStencilRef). +unsigned detect_list_slot_count(IUnknown* real) { + if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList8))) return 82; + if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList7))) return 81; + if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList6))) return 80; + if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList5))) return 79; + if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList4))) return 77; + if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList3))) return 68; + if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList2))) return 67; + if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList1))) return 66; + if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList))) return 60; + return 9; +} + +template +std::uint64_t WINAPI list_slot(ListProxy* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, + std::uint64_t a4, std::uint64_t a5, std::uint64_t a6, std::uint64_t a7, + std::uint64_t a8, std::uint64_t a9, std::uint64_t a10, std::uint64_t a11, + std::uint64_t a12, std::uint64_t a13, std::uint64_t a14) { + if constexpr (Slot == 0) { + return hr_to_u64(list_query_interface(self, reinterpret_cast(a1), + reinterpret_cast(a2))); + } else if constexpr (Slot == 1) { + return list_add_ref(self); + } else if constexpr (Slot == 2) { + return list_release(self); + } else if constexpr (Slot == 7) { // GetDevice: the Xbox-ABI device, as on the other proxies + note_list_slot(7, a1, a2, 0, 0); + if (a2) *reinterpret_cast(a2) = nullptr; + if (!a1) return hr_to_u64(E_POINTER); + if (!a2) { // no output: the real object's own answer + using Fn = HRESULT(WINAPI*)(IUnknown*, const IID*, void**); + return hr_to_u64(reinterpret_cast((*reinterpret_cast(self->real))[7])( + self->real, reinterpret_cast(a1), nullptr)); + } + return hr_to_u64(proxy_query_interface(self->device, reinterpret_cast(a1), + reinterpret_cast(a2))); + } else { + note_list_slot(Slot, a1, a2, a3, a4, self->device->console_layout.load(std::memory_order_relaxed)); + constexpr unsigned pc = console_to_pc_list_slot(Slot); + if constexpr (pc == kListNotForwarded) { + if constexpr (Slot == kConsoleAllocateUpload) { + return upload_alloc(self->device, a1, a2); // (size, alignment); the comment at UploadChunk + } + return 0; // unmodelled console slot: recorded above, never a PC call + } else { + if (pc >= self->pc_slot_count) { + static std::atomic beyond_warned[kListSlots]; + bool expected = false; + if (beyond_warned[Slot].compare_exchange_strong(expected, true, std::memory_order_relaxed)) + std::fprintf(stderr, + "[rt] d3d12_xs: list slot %u maps to PC slot %u, beyond the real list's %u " + "slots; returning E_NOTIMPL\n", + Slot, pc, self->pc_slot_count); + return hr_to_u64(E_NOTIMPL); + } + using ForwardFn = std::uint64_t(WINAPI*)(void*, std::uint64_t, std::uint64_t, std::uint64_t, + std::uint64_t, std::uint64_t, std::uint64_t, + std::uint64_t, std::uint64_t, std::uint64_t, + std::uint64_t, std::uint64_t, std::uint64_t, + std::uint64_t, std::uint64_t); + auto** const real_vtable = *reinterpret_cast(self->real); + if constexpr (pc == 10) { + // Reset(allocator, pso) — console 10, and 139 as the retail title calls it: the title hands its + // allocator proxy; the real list takes the real one (and a wrapped pipeline state, if that ever + // exists, the same way). + a1 = unwrap_object(a1); + a2 = unwrap_object(a2); + self->pin_cursor_at_limit(); // a reset list starts its records again: keep the title on the API path + } else if constexpr (Slot == kConsoleExecuteBundle) { + a1 = unwrap_object(a1); // the bundle is a list proxy too + } else if constexpr (Slot >= 41 && Slot <= 46) { + // The six root descriptor setters (index, GPU VA): an upload-arena CPU pointer becomes the + // chunk's device address (d3d12_xs_console_abi.md §5.3 measures slots 41/43/45 for the compute + // side; the graphics setters interleave on even slots). + a2 = upload_translate(self->device, a2); + } else if constexpr (Slot == 47) { + // IASetIndexBuffer(pView): the view's BufferLocation is a GPU VA; translate in a copy so the + // title's struct is not written. + if (a1) { + auto view = *reinterpret_cast(a1); + view.BufferLocation = upload_translate(self->device, view.BufferLocation); + return reinterpret_cast(real_vtable[pc])( + self->real, reinterpret_cast(&view), a2, a3, a4, a5, a6, a7, a8, a9, + a10, a11, a12, a13, a14); + } + } else if constexpr (Slot == 48) { + // IASetVertexBuffers(start, count, views): each view's BufferLocation is a GPU VA. The views are + // translated in the proxy's scratch array for the same reason as the index view. + if (a3 && a2) { + const auto* in = reinterpret_cast(a3); + self->vb_scratch.assign(in, in + a2); + for (auto& view : self->vb_scratch) + view.BufferLocation = upload_translate(self->device, view.BufferLocation); + return reinterpret_cast(real_vtable[pc])( + self->real, a1, a2, reinterpret_cast(self->vb_scratch.data()), a4, a5, + a6, a7, a8, a9, a10, a11, a12, a13, a14); + } + } else if constexpr (Slot == 49) { + // SOSetTargets(start, count, views): BufferLocation and BufferFilledSizeLocation are both VAs. + if (a3 && a2) { + const auto* in = reinterpret_cast(a3); + self->so_scratch.assign(in, in + a2); + for (auto& view : self->so_scratch) { + view.BufferLocation = upload_translate(self->device, view.BufferLocation); + view.BufferFilledSizeLocation = + upload_translate(self->device, view.BufferFilledSizeLocation); + } + return reinterpret_cast(real_vtable[pc])( + self->real, a1, a2, reinterpret_cast(self->so_scratch.data()), a4, a5, + a6, a7, a8, a9, a10, a11, a12, a13, a14); + } + } else if constexpr (Slot == kConsoleSetDescriptorHeaps) { + UnwrappedArray heaps; + if (!heaps.fill(a2, a1)) return 0; // void on the PC side; the call simply does not happen + const std::uint64_t real_heaps = heaps.data() ? heaps.data() : a2; + return reinterpret_cast(real_vtable[pc])(self->real, a1, real_heaps, a3, a4, a5, a6, + a7, a8, a9, a10, a11, a12, a13, a14); + } else if constexpr (Slot == kConsoleOMSetRenderTargets) { + // OMSetRenderTargets(NumRenderTargetDescriptors, pRenderTargetDescriptors, + // RTsSingleHandleToDescriptorRange, pDepthStencilDescriptor): + // translate title-owned CPU descriptor handles into local copies without mutating caller buffers. + const UINT count = static_cast(a1); + const auto* in_rtvs = reinterpret_cast(a2); + const BOOL single_range = static_cast(a3); + const auto* in_dsv = reinterpret_cast(a4); + D3D12_CPU_DESCRIPTOR_HANDLE rtvs[D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT]{}; + const D3D12_CPU_DESCRIPTOR_HANDLE* out_rtvs = in_rtvs; + if (in_rtvs && count > 0) { + if (single_range) { + rtvs[0] = translate_cpu_handle(self->device, in_rtvs[0]); + out_rtvs = rtvs; + } else if (count <= D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT) { + for (UINT i = 0; i < count; ++i) rtvs[i] = translate_cpu_handle(self->device, in_rtvs[i]); + out_rtvs = rtvs; + } + } + D3D12_CPU_DESCRIPTOR_HANDLE dsv{}; + const D3D12_CPU_DESCRIPTOR_HANDLE* out_dsv = in_dsv; + if (in_dsv) { + dsv = translate_cpu_handle(self->device, *in_dsv); + out_dsv = &dsv; + } + return reinterpret_cast(real_vtable[pc])( + self->real, a1, reinterpret_cast(out_rtvs), a3, + reinterpret_cast(out_dsv), a5, a6, a7, a8, a9, a10, a11, a12, a13, a14); + } else if constexpr (Slot == kConsoleClearRenderTargetView) { + // ClearRenderTargetView(RenderTargetView, ColorRGBA, NumRects, pRects): translate the RTV handle. + a1 = static_cast( + translate_cpu_handle(self->device, D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(a1)}).ptr); + } else if constexpr (Slot == kConsoleClearUavUint || Slot == kConsoleClearUavFloat) { + // ClearUnorderedAccessViewUint/Float(ViewGPUHandle, ViewCPUHandle, pResource, Values, NumRects, + // pRects): keep GPU handle, translate CPU handle. + a2 = static_cast( + translate_cpu_handle(self->device, D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(a2)}).ptr); + } + return reinterpret_cast(real_vtable[pc])(self->real, a1, a2, a3, a4, a5, a6, a7, a8, a9, + a10, a11, a12, a13, a14); + } + } +} + +// ClearDepthStencilView (console slot 51 -> PC slot 47) takes FLOAT Depth as its fourth argument (XMM3 on Windows +// x64 ABI). The all-uint64_t list_slot thunk would read R9 instead of XMM3 and clobber Depth, so this slot gets a +// typed thunk that preserves Depth and translates the title-owned CPU descriptor handle. +void WINAPI list_clear_depth_stencil_view(ListProxy* self, D3D12_CPU_DESCRIPTOR_HANDLE dsv, + D3D12_CLEAR_FLAGS flags, FLOAT depth, UINT8 stencil, UINT num_rects, + const D3D12_RECT* rects) { + std::uint32_t depth_bits = 0; + std::memcpy(&depth_bits, &depth, sizeof(depth_bits)); + note_list_slot(kConsoleClearDepthStencilView, static_cast(dsv.ptr), + static_cast(flags), depth_bits, stencil, + self->device->console_layout.load(std::memory_order_relaxed)); + constexpr unsigned pc = console_to_pc_list_slot(kConsoleClearDepthStencilView); + if (pc >= self->pc_slot_count) { + static std::atomic beyond_warned{false}; + bool expected = false; + if (beyond_warned.compare_exchange_strong(expected, true, std::memory_order_relaxed)) + std::fprintf(stderr, + "[rt] d3d12_xs: list slot %u maps to PC slot %u, beyond the real list's %u slots\n", + kConsoleClearDepthStencilView, pc, self->pc_slot_count); + return; + } + const D3D12_CPU_DESCRIPTOR_HANDLE translated = translate_cpu_handle(self->device, dsv); + using ClearDsvFn = void(WINAPI*)(ID3D12GraphicsCommandList*, D3D12_CPU_DESCRIPTOR_HANDLE, D3D12_CLEAR_FLAGS, + FLOAT, UINT8, UINT, const D3D12_RECT*); + auto** const real_vtable = *reinterpret_cast(self->real); + reinterpret_cast(real_vtable[pc])(self->real, translated, flags, depth, stencil, num_rects, rects); +} + +template +void fill_list_vtable(void** vtable, std::index_sequence) { + ((vtable[I] = reinterpret_cast(&list_slot(I)>) ), ...); + vtable[kConsoleClearDepthStencilView] = reinterpret_cast(&list_clear_depth_stencil_view); +} + +void** get_list_vtable() { + static void** vtable = [] { + static void* storage[kListSlots]; + fill_list_vtable(storage, std::make_index_sequence{}); + return storage; + }(); + return vtable; +} + +bool is_list_proxy_impl(const void* list) { + return list && *reinterpret_cast(list) == reinterpret_cast(get_list_vtable()); +} + +IUnknown* list_real_or_null(const void* object) { + return is_list_proxy_impl(object) ? static_cast(static_cast(object)->real) + : nullptr; +} + +// Wraps `created` (one reference, owned by the proxy on success, released on failure) and returns `riid` from the +// proxy through `out`. +HRESULT wrap_list(IUnknown* created, DeviceProxy* device, const IID* riid, void** out) { if (!created) return E_FAIL; - ChildProxy* proxy = new (std::nothrow) ChildProxy; + ListProxy* proxy = new (std::nothrow) ListProxy(); // (): the console body starts zeroed if (!proxy) { created->Release(); return E_OUTOFMEMORY; } - proxy->vtable = get_child_vtable(); - proxy->real = created; + proxy->vtable = get_list_vtable(); + proxy->real = static_cast(created); proxy->device = device; - proxy->real_vtable = *reinterpret_cast(created); - if constexpr (K == ChildKind::queue) { - proxy->slot_count = kQueuePublicSlots; - } else if constexpr (K == ChildKind::fence) { - proxy->slot_count = supports_iid(created, __uuidof(ID3D12Fence1)) ? kFence1PublicSlots : kFencePublicSlots; - } else { - proxy->slot_count = kAllocatorPublicSlots; - } proxy->refs.store(1, std::memory_order_relaxed); - proxy_add_ref(device); // the object keeps its Xbox-ABI device alive for GetDevice + proxy->pc_slot_count = detect_list_slot_count(created); + proxy->pin_cursor_at_limit(); + proxy_add_ref(device); // the list keeps its Xbox-ABI device alive for GetDevice - const HRESULT hr = child_query_interface(proxy, riid, out); + const HRESULT hr = list_query_interface(proxy, riid, out); if (FAILED(hr)) { - destroy_child(proxy); // no reference escaped + destroy_list(proxy); // no reference escaped return hr; } - // Titles create fences at run time: the first proxy of each kind is logged, every one only with XS_TRACE. static std::atomic logged{false}; if (!d3d12_trace::enabled() && (!logged.exchange(true, std::memory_order_relaxed) || trace_enabled())) - std::fprintf(stderr, "[rt] d3d12_xs: %s proxy %p wraps %p (device proxy %p, %u public slots)\n", - child_kind_name(), static_cast(proxy), static_cast(created), - static_cast(device), proxy->slot_count); + std::fprintf(stderr, "[rt] d3d12_xs: list proxy %p wraps %p (%u PC vtable slots)\n", + static_cast(proxy), static_cast(created), proxy->pc_slot_count); proxy->refs.fetch_sub(1, std::memory_order_relaxed); // drop the creation reference; `out` holds the caller's return S_OK; } +// Device slot 12: CreateCommandList(node_mask, type, allocator, initial_pso, riid, out). The title hands its +// allocator proxy, which the real device unwraps to the real allocator; the created list goes back console-shaped. +HRESULT proxy_create_command_list(DeviceProxy* self, std::uint64_t node_mask, std::uint64_t type, + std::uint64_t allocator, std::uint64_t pso, const IID* riid, void** out) { + note_slot(12); + if (out) *out = nullptr; // as slot 8 + if (!riid) return E_POINTER; + if (!out) return self->real->CreateCommandList(static_cast(node_mask), + static_cast(type), + reinterpret_cast(unwrap_object(allocator)), + reinterpret_cast(pso), *riid, nullptr); + if (!self->console_lists) { + // PC caller (create_device_proxy's console_lists=false): the real list answers every PC slot, and the + // console-only pieces (slot 148, the shifted tail) are simply not there for this caller to reach. + return self->real->CreateCommandList(static_cast(node_mask), + static_cast(type), + reinterpret_cast(unwrap_object(allocator)), + reinterpret_cast(pso), *riid, out); + } + void* created = nullptr; + const HRESULT hr = self->real->CreateCommandList( + static_cast(node_mask), static_cast(type), + reinterpret_cast(unwrap_object(allocator)), + reinterpret_cast(pso), __uuidof(ID3D12GraphicsCommandList), &created); + if (FAILED(hr)) return hr; + if (!created) return E_FAIL; + return wrap_list(static_cast(created), self, riid, out); +} + // Calls the real device's slot `Slot` with these five words in the positions the thunk received them (see "A thunk // declares 14 argument words" at the top: no word may move to another stack position on the way). template @@ -1608,7 +2476,31 @@ HRESULT proxy_create_command_queue(DeviceProxy* self, const D3D12_COMMAND_QUEUE_ void* created = nullptr; const HRESULT hr = self->real->CreateCommandQueue(desc, __uuidof(ID3D12CommandQueue), &created); if (FAILED(hr)) return hr; - return wrap_child(static_cast(created), self, riid, out); + const HRESULT wrapped = wrap_child(static_cast(created), self, riid, out); +#ifdef LEONIDA_VULKAN_DEVICE + if (SUCCEEDED(wrapped) && desc && desc->Type == D3D12_COMMAND_LIST_TYPE_DIRECT && rt::package_splash::configured()) + present_state_for(self, true); +#endif + return wrapped; +} + +// Device slot 48, measured on the retail title: (desc, riid, out) with riid = IID_ID3D12CommandQueue. On the PC the +// slot is OpenExistingHeapFromAddress, so forwarding it by number fails. desc is a PC D3D12_COMMAND_QUEUE_DESC +// (16 bytes) followed by four more 32-bit Xbox words of unknown meaning, logged once. Only the PC prefix is used and +// only the flag the PC knows is kept; the rest is the slot 8 path. +HRESULT proxy_create_command_queue_xbox(DeviceProxy* self, const std::uint32_t* desc, const IID* riid, void** out) { + if (out) *out = nullptr; + if (!desc) return E_INVALIDARG; + static_assert(sizeof(D3D12_COMMAND_QUEUE_DESC) == 16, "the PC prefix of the Xbox description is 16 bytes"); + D3D12_COMMAND_QUEUE_DESC pc{}; + std::memcpy(&pc, desc, sizeof(pc)); + pc.Flags &= D3D12_COMMAND_QUEUE_FLAG_DISABLE_GPU_TIMEOUT; + static std::atomic logged{false}; + if (!logged.exchange(true, std::memory_order_relaxed)) + std::fprintf(stderr, + "[rt] d3d12_xs: slot 48 queue: flags=0x%x extra words=0x%x 0x%x 0x%x 0x%x\n", + static_cast(desc[2]), desc[4], desc[5], desc[6], desc[7]); + return proxy_create_command_queue(self, &pc, riid, out); } // Xbox device slot 78 (public HLE): SetFrameIntervalX(output, interval_us, latency, flags). The output and flags are @@ -1658,9 +2550,7 @@ HRESULT proxy_wait_frame_event_x(DeviceProxy* self, std::uint64_t event, std::ui })) return hr; if (!token) return E_POINTER; - std::uint64_t value = self->frame_next_token.fetch_add(1, std::memory_order_relaxed); - if (value == 0) value = self->frame_next_token.fetch_add(1, std::memory_order_relaxed); // skip the null token - *token = value; + *token = self->frame_tokens->issue(); return S_OK; } @@ -1702,43 +2592,97 @@ HRESULT proxy_create_command_list_x(DeviceProxy* self, std::uint64_t desc_word, return wrap_list(static_cast(created), self, riid, out); } -// Device slot 48, measured on the retail title: (desc, riid, out) with riid = IID_ID3D12CommandQueue. On the PC the -// slot is OpenExistingHeapFromAddress, so forwarding it by number fails. desc is a PC D3D12_COMMAND_QUEUE_DESC -// (16 bytes) followed by four more 32-bit Xbox words of unknown meaning, logged once. Only the PC prefix is used and -// only the flag the PC knows is kept; the rest is the slot 8 path. -HRESULT proxy_create_command_queue_xbox(DeviceProxy* self, const std::uint32_t* desc, const IID* riid, void** out) { - if (out) *out = nullptr; - if (!desc) return E_INVALIDARG; - static_assert(sizeof(D3D12_COMMAND_QUEUE_DESC) == 16, "the PC prefix of the Xbox description is 16 bytes"); - D3D12_COMMAND_QUEUE_DESC pc{}; - std::memcpy(&pc, desc, sizeof(pc)); - pc.Flags &= D3D12_COMMAND_QUEUE_FLAG_DISABLE_GPU_TIMEOUT; - static std::atomic logged{false}; - if (!logged.exchange(true, std::memory_order_relaxed)) - std::fprintf(stderr, - "[rt] d3d12_xs: slot 48 queue: flags=0x%x extra words=0x%x 0x%x 0x%x 0x%x\n", - static_cast(desc[2]), desc[4], desc[5], desc[6], desc[7]); - return proxy_create_command_queue(self, &pc, riid, out); -} +// Xbox device slots 70 and 71: (resource words, view words, destination), no return value. The retail title's +// shader-resource (70) and unordered-access (71) views of memory it placed itself, with no resource object +// (docs/retail_boot_chain.md, stop 14). The PC slots are CreatePlacedResource1 and CreateSamplerFeedbackUnordered- +// AccessView. The layout is VIctory's measurement for this title (crates/victory-gpu/src/descriptor.rs and +// descriptor/host.rs, "device methods 0x230 and 0x238", GPL-3.0-or-later): +// - resource words: 14 dwords in the shape of a PC D3D12_RESOURCE_DESC: dword 0 the dimension (1 a buffer), +// dwords 4-5 the width in bytes; +// - view words: 16 dwords: 0-9 the PC D3D12_SHADER_RESOURCE_VIEW_DESC (slot 70) or D3D12_UNORDERED_ACCESS_VIEW_DESC +// (slot 71), 10-11 the 64-bit address of the memory, 12-15 console fields (not read). +// A buffer view gets its V# on that address (vsharp_address gives title memory a GPU copy). A texture view gets the +// T# of the slot-133 texture placed at the address, or of an image made for that memory, filled from it with its +// console layout (XG) and filled again when the bytes change (rt::d3d12::write_placed_texture_view); what that +// cannot show gets a null descriptor. UAVs require a live, matching GPU-writable texture at the placement. +// SRVs over pending streams are filled once their pages arrive. The first calls and every 4096th are logged. +#ifdef LEONIDA_VULKAN_DEVICE +static bool accessible_range(const void* ptr, std::size_t bytes, bool writable); +#endif -// Xbox device slot 70: (texture_words, view_desc, destination), no return value. The retail executable's SRV writer -// makes a view from raw descriptions and a GPU address with no resource object (docs/retail_boot_chain.md, stop 14, -// measured by call shape only). The PC slot 70 is ID3D12Device8::CreatePlacedResource1, which would take the -// destination handle for a resource description and write through it. The layout of the raw words is not measured, -// so nothing reads them: the destination gets the PC's null shader-resource view, which a shader reads as zeros, and -// the call returns. A view that reaches the GPU address needs that layout. -void proxy_create_srv_from_raw_x(DeviceProxy* self, std::uint64_t texture_words, std::uint64_t view_desc, - std::uint64_t destination) { - note_slot(70); - log_xbox_route_once(70, "CreateShaderResourceView from raw words (null view)", texture_words, view_desc, - destination, 0, 0); +struct PlacedViewCounts { + std::atomic calls{0}, buffers{0}, textures{0}, refused{0}, texture_views{0}; +}; +PlacedViewCounts g_placed_views[2]; // SRV, UAV + +void proxy_create_placed_view_x(DeviceProxy* self, bool unordered, std::uint64_t resource_words, + std::uint64_t view_words, std::uint64_t destination) { + const unsigned slot = unordered ? 71 : 70; + note_slot(slot); + log_xbox_route_once(slot, unordered ? "CreateUnorderedAccessView of placed memory" + : "CreateShaderResourceView of placed memory", + resource_words, view_words, destination, 0, 0); if (!destination) return; + const D3D12_CPU_DESCRIPTOR_HANDLE dest = translate_cpu_handle(self, D3D12_CPU_DESCRIPTOR_HANDLE{destination}); + PlacedViewCounts& counts = g_placed_views[unordered ? 1 : 0]; + const std::uint64_t n = counts.calls.fetch_add(1, std::memory_order_relaxed) + 1; + std::uint32_t resource[14] = {}, view[16] = {}; + bool read = false; +#ifdef LEONIDA_VULKAN_DEVICE + read = resource_words && view_words && + accessible_range(reinterpret_cast(resource_words), sizeof(resource), false) && + accessible_range(reinterpret_cast(view_words), sizeof(view), false); +#endif + if (read) { + std::memcpy(resource, reinterpret_cast(resource_words), sizeof(resource)); + std::memcpy(view, reinterpret_cast(view_words), sizeof(view)); + } + const std::uint64_t address = std::uint64_t(view[10]) | (std::uint64_t(view[11]) << 32); + const std::uint64_t width = std::uint64_t(resource[4]) | (std::uint64_t(resource[5]) << 32); + const bool buffer = read && resource[0] == std::uint32_t(D3D12_RESOURCE_DIMENSION_BUFFER); + bool written = false, texture_written = false; +#ifdef LEONIDA_VULKAN_DEVICE + if (buffer) written = rt::d3d12::write_placed_buffer_view(self->real, unordered, view, address, width, dest); + // A texture view: the T# of an image filled from the title's memory at the address (TitleTexture in + // d3d12_vulkan_device.cpp), or a null view with the reason logged there. + if (read && !buffer) + texture_written = rt::d3d12::write_placed_texture_view(self->real, unordered, resource, view, address, dest); +#endif + (written ? counts.buffers : buffer ? counts.refused : texture_written ? counts.texture_views : counts.textures) + .fetch_add(1, std::memory_order_relaxed); + if (n <= 8 || !(n % 4096)) + std::fprintf(stderr, + "[rt] d3d12_xs: slot %u call %llu: %s of placed memory 0x%llx (%llu bytes), dimension %u, view " + "format %u dimension %u -> %s (so far: %llu buffer views, %llu refused, %llu texture views, " + "%llu textures as null views)\n", + slot, static_cast(n), unordered ? "UAV" : "SRV", + static_cast(address), static_cast(width), resource[0], + view[0], view[1], + written ? "a buffer V#" + : texture_written ? "a texture T#" + : !read ? "unreadable words, null view" + : buffer ? "refused, null view" + : "texture, null view", + static_cast(counts.buffers.load()), + static_cast(counts.refused.load()), + static_cast(counts.texture_views.load()), + static_cast(counts.textures.load())); + if (written || texture_written) return; + if (unordered) { + // A null UAV of the view's kind: a buffer, or a 2D texture for anything else. + D3D12_UNORDERED_ACCESS_VIEW_DESC null_view{}; + null_view.Format = DXGI_FORMAT_R32_UINT; + null_view.ViewDimension = buffer ? D3D12_UAV_DIMENSION_BUFFER : D3D12_UAV_DIMENSION_TEXTURE2D; + self->real->CreateUnorderedAccessView(nullptr, nullptr, &null_view, dest); + return; + } D3D12_SHADER_RESOURCE_VIEW_DESC null_view{}; null_view.Format = DXGI_FORMAT_R8G8B8A8_UNORM; null_view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; null_view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; null_view.Texture2D.MipLevels = 1; - self->real->CreateShaderResourceView(nullptr, &null_view, D3D12_CPU_DESCRIPTOR_HANDLE{destination}); + // The destination can be a handle inside a heap backed by the title's XMem hook (slot 14): translated as slots 17-24. + self->real->CreateShaderResourceView(nullptr, &null_view, dest); } // Device slot 75: ID3D12Device9::CreateCommandQueue1(desc, creator_id, riid, out), called by slot index. @@ -1872,7 +2816,7 @@ static bool console_heap_range_plausible(const D3D12_DESCRIPTOR_HEAP_DESC* desc, return true; } -static bool readable_range(const void* ptr, std::size_t bytes) { +static bool accessible_range(const void* ptr, std::size_t bytes, bool writable) { if (!ptr || !bytes) return false; const auto* p = static_cast(ptr); std::size_t remaining = bytes; @@ -1880,7 +2824,9 @@ static bool readable_range(const void* ptr, std::size_t bytes) { MEMORY_BASIC_INFORMATION mbi{}; if (!VirtualQuery(p, &mbi, sizeof(mbi)) || mbi.State != MEM_COMMIT) return false; const DWORD protect = mbi.Protect & 0xffu; - if (protect == PAGE_NOACCESS || protect == PAGE_GUARD || protect == PAGE_EXECUTE) return false; + if ((mbi.Protect & PAGE_GUARD) || protect == PAGE_NOACCESS || protect == PAGE_EXECUTE) return false; + if (writable && protect != PAGE_READWRITE && protect != PAGE_WRITECOPY && + protect != PAGE_EXECUTE_READWRITE && protect != PAGE_EXECUTE_WRITECOPY) return false; const auto base = reinterpret_cast(mbi.BaseAddress); const auto addr = reinterpret_cast(p); const std::size_t avail = static_cast(base + mbi.RegionSize - addr); @@ -1891,6 +2837,7 @@ static bool readable_range(const void* ptr, std::size_t bytes) { return true; } + HRESULT proxy_create_descriptor_heap(DeviceProxy* self, const D3D12_DESCRIPTOR_HEAP_DESC* desc, const IID* riid, void** out) { note_slot(14); @@ -1902,31 +2849,71 @@ HRESULT proxy_create_descriptor_heap(DeviceProxy* self, const D3D12_DESCRIPTOR_H void* created = nullptr; HRESULT hr = E_INVALIDARG; bool console_extended = false; - if (desc && desc->Type <= D3D12_DESCRIPTOR_HEAP_TYPE_DSV && + // Console-extended slot 14 (issue #313): the address and size of the title's own descriptor memory follow the PC + // description. The device behind the proxy registers the handler that interprets them + // (set_console_descriptor_heap_handler); on the Vulkan layer only its own devices take the path (a PC device + // behind the proxy gets the PC call). + const ConsoleDescriptorHeapHandler handler = g_console_descriptor_heap.load(std::memory_order_acquire); +#ifdef LEONIDA_VULKAN_DEVICE + const bool console_capable = handler && rt::d3d12::vulkan_device_info(self->real); +#else + const bool console_capable = handler != nullptr; +#endif + if (desc && console_capable && desc->Type <= D3D12_DESCRIPTOR_HEAP_TYPE_DSV && (desc->Flags & ~D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) == 0) { const auto* bytes = reinterpret_cast(desc); const void* tail = bytes + sizeof(D3D12_DESCRIPTOR_HEAP_DESC); - if (readable_range(tail, sizeof(std::uint64_t) * 2)) { + if (accessible_range(tail, sizeof(std::uint64_t) * 2, false)) { std::uint64_t address = 0; std::uint64_t size = 0; std::memcpy(&address, tail, sizeof(address)); std::memcpy(&size, bytes + sizeof(D3D12_DESCRIPTOR_HEAP_DESC) + sizeof(address), sizeof(size)); - // Console-extended slot 14 (issue #313): address/size follow the PC desc. A non-zero word is not evidence - // of that layout - the bytes after a PC desc are whatever the caller holds next, and they are almost - // always readable and non-zero. The size has to agree with the descriptor count for the path to be taken. - if (console_heap_range_plausible(desc, address, size)) { - const ConsoleDescriptorHeapHandler handler = - g_console_descriptor_heap.load(std::memory_order_acquire); - if (handler) { - console_extended = true; - hr = handler(self->real, desc, static_cast(address), size, - __uuidof(ID3D12DescriptorHeap), &created); - } + const auto stride = self->real->GetDescriptorHandleIncrementSize(desc->Type); + { // LOCAL DIAGNOSTIC: what the title passes on slot 14, and whether the console path takes it + static std::atomic logged{0}; + if (logged.fetch_add(1) < 32) + std::fprintf(stderr, "[rt] heap-probe: slot 14 type %d num %u flags 0x%x console va 0x%llx size %llu " + "(num*stride %llu, our stride %u, size/num %.2f) writable %d\n", + int(desc->Type), desc->NumDescriptors, unsigned(desc->Flags), + static_cast(address), static_cast(size), + static_cast(std::uint64_t(desc->NumDescriptors) * stride), stride, + desc->NumDescriptors ? double(size) / desc->NumDescriptors : 0.0, + address && size ? int(accessible_range(reinterpret_cast(address), size, true)) : -1); + } + // A non-zero word is not evidence of that layout - the bytes after a PC desc are whatever the caller holds + // next, and they are almost always readable and non-zero. The size has to agree with the descriptor count + // (32 bytes each, the console's and this layer's stride), and the range has to be the title's writable + // memory; otherwise the PC heap stands (a read-only or mismatched range falls back). Physical pages are + // committed on first touch (xmem), so the range's pages are committed first, as slot 133 does: a range the + // title mapped but has not written yet is still reserved and would read as not writable. + // The range may also lie under a slot-133 shadow or a title window whose write watch made its pages + // read-only (the title places a buffer over the memory it carves the heap from); those pages are the + // title's writable memory all the same, so they are pinned writable while the range is checked. + const bool plausible = console_heap_range_plausible(desc, address, size) && address <= UINTPTR_MAX - size; + std::uint64_t pin = 0; + if (plausible) { + if (const PlacedAtVaPagesHook pages = g_placed_at_va_pages.load(std::memory_order_acquire)) + pages(reinterpret_cast(address), static_cast(size)); + pin = leonida::kernel_writes::begin_write(reinterpret_cast(address), + static_cast(size), nullptr); + } + const bool writable = plausible && accessible_range(reinterpret_cast(address), size, true); + leonida::kernel_writes::end_write(pin, false); + if (writable && size == std::uint64_t(desc->NumDescriptors) * stride) { + console_extended = true; + hr = handler(self->real, desc, static_cast(address), size, + __uuidof(ID3D12DescriptorHeap), &created); } } } if (!console_extended) hr = self->real->CreateDescriptorHeap(desc, __uuidof(ID3D12DescriptorHeap), &created); + { // LOCAL DIAGNOSTIC + static std::atomic logged{0}; + if (logged.fetch_add(1) < 32) + std::fprintf(stderr, "[rt] heap-probe: slot 14 -> %s heap, hr 0x%08lx\n", console_extended ? "CONSOLE" : "pc", + static_cast(hr)); + } if (FAILED(hr) || !created) return FAILED(hr) ? hr : E_FAIL; ID3D12DescriptorHeap* heap = static_cast(created); @@ -1953,6 +2940,30 @@ HRESULT proxy_create_descriptor_heap(DeviceProxy* self, const D3D12_DESCRIPTOR_H custom_cpu_start = addr; custom_byte_size = byte_size; real_cpu_start = raw_heap_get_cpu_handle(heap, *reinterpret_cast(heap)).ptr; +#ifdef LEONIDA_VULKAN_DEVICE + // A CPU-only heap of the Vulkan device keeps its descriptors in the backing itself: the title + // makes views there through the API and then moves the 32-byte records into its shader-visible + // heap with its own memcpy (no CopyDescriptors call), so the records must be in the memory its + // handles name. Without this the device wrote its own heap and the title copied the untouched + // backing (zeros or stale bytes; found by the fsdraw forensics on the console path). + if (!console_extended && !(desc->Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) && + rt::d3d12::vulkan_device_info(self->real)) { + void* in_backing = nullptr; + if (SUCCEEDED(rt::d3d12::create_console_descriptor_heap( + self->real, desc, static_cast(addr), byte_size, + __uuidof(ID3D12DescriptorHeap), &in_backing)) && + in_backing) { + heap->Release(); + heap = static_cast(in_backing); + real_cpu_start = addr; + static std::atomic logged{false}; + if (first_call(logged)) + std::fprintf(stderr, "[rt] d3d12_xs: CPU-only descriptor heaps keep their descriptors " + "in the title's XMem backing (first: type %d, %u slots at %p)\n", + int(desc->Type), desc->NumDescriptors, backing); + } + } +#endif } else if (free_fn) { free_fn(backing, kXmemDescriptorHeapAttributes); } @@ -1962,6 +2973,19 @@ HRESULT proxy_create_descriptor_heap(DeviceProxy* self, const D3D12_DESCRIPTOR_H hr = create_heap_proxy(heap, self, *riid, out, custom_cpu_start, custom_byte_size, real_cpu_start, custom_cpu_start ? free_fn : nullptr); + { // LOCAL DIAGNOSTIC (fsdraw): which CPU start the title gets for this heap + static std::atomic logged{0}; + if (logged.fetch_add(1) < 32) + std::fprintf(stderr, "[rt] fsdraw: heap type %d num %u flags 0x%x console %d: title CPU start 0x%llx (custom " + "backing %s), real CPU start 0x%llx, hr 0x%08lx\n", + desc ? int(desc->Type) : -1, desc ? desc->NumDescriptors : 0u, desc ? unsigned(desc->Flags) : 0u, + int(console_extended), + static_cast(custom_cpu_start ? custom_cpu_start + : raw_heap_get_cpu_handle(heap, *reinterpret_cast(heap)).ptr), + custom_cpu_start ? "yes" : "no", + static_cast(raw_heap_get_cpu_handle(heap, *reinterpret_cast(heap)).ptr), + static_cast(hr)); + } if (FAILED(hr)) { heap->Release(); if (custom_cpu_start && free_fn) @@ -2051,8 +3075,24 @@ void proxy_copy_descriptors(DeviceProxy* self, UINT num_dest, const D3D12_CPU_DE void proxy_copy_descriptors_simple(DeviceProxy* self, UINT num_descriptors, D3D12_CPU_DESCRIPTOR_HANDLE dest_start, D3D12_CPU_DESCRIPTOR_HANDLE src_start, D3D12_DESCRIPTOR_HEAP_TYPE type) { note_slot(24); - self->real->CopyDescriptorsSimple(num_descriptors, translate_cpu_handle(self, dest_start), - translate_cpu_handle(self, src_start), type); + const D3D12_CPU_DESCRIPTOR_HANDLE dest = translate_cpu_handle(self, dest_start); + const D3D12_CPU_DESCRIPTOR_HANDLE src = translate_cpu_handle(self, src_start); + self->real->CopyDescriptorsSimple(num_descriptors, dest, src, type); + { // LOCAL DIAGNOSTIC (fsdraw): where the title copies its descriptors, and what lands there + static std::atomic copies{0}; + const std::uint64_t n = ++copies; + if (n <= 24 || n % 600 == 0 || n % 600 == 1) { + std::uint32_t w[8]{}; + if (dest.ptr && num_descriptors && accessible_range(reinterpret_cast(dest.ptr), sizeof w, false)) + std::memcpy(w, reinterpret_cast(dest.ptr), sizeof w); // a handle need not be CPU memory (mocks) + std::fprintf(stderr, "[rt] fsdraw: CopyDescriptorsSimple #%llu n %u type %d dest 0x%llx -> 0x%llx src 0x%llx -> " + "0x%llx first slot now [%08x %08x %08x %08x %08x %08x %08x %08x]\n", + static_cast(n), num_descriptors, int(type), + static_cast(dest_start.ptr), static_cast(dest.ptr), + static_cast(src_start.ptr), static_cast(src.ptr), w[0], + w[1], w[2], w[3], w[4], w[5], w[6], w[7]); + } + } } // The Xbox slot 62 takes two more words between the description and the IID: (desc, w2, w3, riid, out). Measured @@ -2236,6 +3276,8 @@ HRESULT proxy_create_compute_pipeline_from_native_code(DeviceProxy* self, const static_cast(xbox_desc->kind1_size), static_cast(xbox_desc->kind6_size), static_cast(xbox_desc->kind7_size)); + else if (d3d12_trace::enabled()) + std::fprintf(stderr, "[d3d12-trace] slot 67 call %llu ok\n", static_cast(call)); return hr; } @@ -2247,8 +3289,11 @@ HRESULT proxy_create_compute_pipeline_from_native_code(DeviceProxy* self, const // created on the PC never allocated through the hooks, so the whole range was left and the assert fired. Each committed // resource made by slots 76 and 127 therefore allocates its size through the hooks as a lease: the resource holds it // (SetPrivateDataInterface) and the hooks' free runs when the resource is destroyed. The bytes are not used for the -// resource; the PC device owns its memory. The size is the one slot 25 answers for the same description -// (lease_size), the figure the title budgets with. +// resource; the PC device owns its memory. The size is the console's (lease_size): for a render target of a listed +// shape, its whole SW_64KB_D tiles (console_render_target_size), never the PC size. The title's budget is sized for +// exactly those (two 3840 x 2160 RGBA8 targets are 2 x 510 tiles of a 64 MiB range), and a PC driver may answer more: +// AMD's Windows driver gives 513 x 64 KiB for that target, and leasing that overran the range (an int3 in the title's +// hook, @controldebils on #7240). Anything else leases the PC size. // HYPOTHESIS: the attribute word, allocator ID 0x80 (eXALLOCAllocatorId_D3D) with page-size field 2 and object type 0. // Of it the measured matcher reads only the page-size field; a title hook that matches on other fields may not take // these leases for the console's allocations. @@ -2330,6 +3375,365 @@ void lease_title_resource_memory(DeviceProxy* self, void* created, const D3D12_R static_cast(size)); } +// The console creates its render-target and depth textures with initial state 0x6; the PC runtime refuses that state +// for a texture (reported by rafaelpssz from a retail exe integration run). A texture whose flags name the use gets +// that use's state: ALLOW_RENDER_TARGET -> RENDER_TARGET, ALLOW_DEPTH_STENCIL -> DEPTH_WRITE. Every other state and +// every buffer goes on unchanged. The description is only read; the title's words are never written. +constexpr std::uint32_t kConsoleTextureInitialState = 0x6; + +std::uint64_t pc_initial_state_word(std::uint64_t desc_word, std::uint64_t state_word) { + if (static_cast(state_word) != kConsoleTextureInitialState || !desc_word) return state_word; + const auto* desc = reinterpret_cast(desc_word); + if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) return state_word; + if (desc->Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) return D3D12_RESOURCE_STATE_RENDER_TARGET; + if (desc->Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) return D3D12_RESOURCE_STATE_DEPTH_WRITE; + return state_word; +} + +D3D12_RESOURCE_STATES pc_initial_state(const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state) { + return static_cast(static_cast( + pc_initial_state_word(reinterpret_cast(desc), static_cast(state)))); +} + +// Device slots 27 CreateCommittedResource(props, heap_flags, desc, state, clear, riid, out) and 53 +// CreateCommittedResource1 (a protected session before riid): the PC call with the initial state mapped above. The PC +// method is called by its table entry with the caller's words, so a null riid or output reaches the real device as it did. +template +std::uint64_t proxy_create_committed_resource(DeviceProxy* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, + std::uint64_t a4, std::uint64_t a5, std::uint64_t a6, std::uint64_t a7, + std::uint64_t a8) { + const std::uint64_t state = pc_initial_state_word(a3, a4); + if constexpr (Slot == 27) { + using Fn = std::uint64_t(WINAPI*)(void*, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, + std::uint64_t, std::uint64_t, std::uint64_t); + return reinterpret_cast(self->real_vtable[27])(self->real, a1, a2, a3, state, a5, a6, a7); + } else { + using Fn = std::uint64_t(WINAPI*)(void*, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, + std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t); + return reinterpret_cast(self->real_vtable[53])(self->real, a1, a2, a3, state, a5, a6, a7, a8); + } +} + +// Xbox slot 57 (+0x1c8): DeserializeGraphicsPipelineStateX(const XboxNativeGraphicsPipelineStateDesc* desc, +// REFIID riid, void** ppPipelineState). +struct XboxNativeGraphicsPipelineStateDesc { + ID3D12RootSignature* root_signature; // +0x00 + const void* state_blob; // +0x08: 380..404 B state blob (magic 0x4005d800 / 0x4005d808 / 0x4005d810) + std::uint64_t state_blob_size; // +0x10 + const void* pipeline_blob; // +0x18: 80..224 B pipeline / input-layout blob (188 B in boot PSOs 1..3) + std::uint64_t pipeline_blob_size; // +0x20 + const void* prog_a; // +0x28: native RDNA2 program #1 (or nullptr/0 if absent, as in boot PSO 3) + std::uint64_t prog_a_size; // +0x30 + const void* stage_a; // +0x38: stage blob #1 (kind-2, e.g. 208 B, or nullptr/0 if absent) + std::uint64_t stage_a_size; // +0x40 + const void* prog_b; // +0x48: native RDNA2 program #2 (e.g. 320..384 B) + std::uint64_t prog_b_size; // +0x50 + const void* stage_b; // +0x58: stage blob #2 (kind-2, e.g. 752 B) + std::uint64_t stage_b_size; // +0x60 +}; + +// Measured offsets in the 380..388 B state blob across the 24,797 graphics records of the pipeline library. +// None is confirmed as a specific D3D12 state field yet; each offset is logged once with its observed u32 word. +struct MeasuredStateBlobField { + std::uint32_t offset; + const char* note; +}; + +constexpr MeasuredStateBlobField kMeasuredStateBlobFields[] = { + {0x000, "version/type tag (0x4005d800 / 0x4005d808 / 0x4005d810)"}, + {0x004, "PSO family (4 or 6)"}, + {0x00c, "per-PSO state word"}, + {0x028, "per-PSO state word"}, + {0x02c, "constant 2"}, + {0x038, "per-PSO state word"}, + {0x03c, "small counter"}, + {0x040, "mask (0xfffe or 0)"}, + {0x044, "mask (0xfffffffe or 0xffff0000)"}, + {0x04c, "boot-PSO diff word"}, + {0x050, "small counter"}, + {0x054, "boot-PSO diff word"}, + {0x058, "boot-PSO diff word"}, + {0x05c, "boot-PSO diff word"}, + {0x064, "per-PSO state word"}, + {0x068, "boot-PSO diff word"}, + {0x06c, "boot-PSO diff word"}, + {0x070, "boot-PSO diff word"}, + {0x074, "per-PSO state word (0x060201bc or 0x80)"}, + {0x07c, "per-PSO state word (0xcc0010 / 0 / 0xcc0011)"}, + {0x084, "boot-PSO diff word"}, + {0x0a0, "per-PSO state word"}, + {0x0a8, "per-PSO state word (0x1000 or 0x8004)"}, + {0x0b8, "boot-PSO diff word"}, + {0x0f0, "per-PSO state word"}, + {0x0f4, "constant 5"}, + {0x0f8, "constant 1"}, + {0x0fc, "0x33333333 (float 0.1)"}, + {0x100, "repeated 0x00060006 slot 0"}, + {0x104, "repeated 0x00060006 slot 1"}, + {0x108, "repeated 0x00060006 slot 2"}, + {0x10c, "repeated 0x00060006 slot 3"}, + {0x110, "repeated 0x00060006 slot 4"}, + {0x114, "repeated 0x00060006 slot 5"}, + {0x118, "repeated 0x00060006 slot 6"}, + {0x11c, "repeated 0x00060006 slot 7"}, + {0x128, "boot-PSO diff word"}, + {0x144, "mask (0 or 0xffffffff)"}, + {0x150, "constant 0x40"}, + {0x158, "constant 0xffffffff"}, + {0x174, "per-PSO state word"}, + {0x17c, "constant 0x10000a00 (present when size >= 384)"}, +}; + +std::atomic g_state_blob_field_logged[std::size(kMeasuredStateBlobFields)]{}; + +void log_measured_state_blob_fields(const void* blob, std::size_t blob_size) { + if (!blob || blob_size < 4) return; + const auto* bytes = static_cast(blob); + for (std::size_t i = 0; i < std::size(kMeasuredStateBlobFields); ++i) { + const std::uint32_t off = kMeasuredStateBlobFields[i].offset; + if (static_cast(off) + 4 > blob_size) continue; + bool expected = false; + if (g_state_blob_field_logged[i].compare_exchange_strong(expected, true, std::memory_order_relaxed)) { + std::uint32_t val = 0; + std::memcpy(&val, bytes + off, 4); + std::fprintf(stderr, "[rt] d3d12_xs: state blob: campo sin identificar en 0x%03x = 0x%08x\n", + static_cast(off), static_cast(val)); + } + } +} + +bool parse_xbox_pipeline_blob_input_layout_impl(const void* blob, std::size_t blob_size, + std::vector& out_elements) { + out_elements.clear(); + if (!blob || blob_size < 0x54) return false; + const auto* bytes = static_cast(blob); + const auto read_u32 = [&](std::size_t off, std::uint32_t& v) -> bool { + if (off + 4 > blob_size) return false; + std::memcpy(&v, bytes + off, 4); + return true; + }; + std::uint32_t magic_const = 0; + std::uint32_t field_block_size = 0; + std::uint32_t tag_3c = 0; + std::uint32_t num_elements = 0; + if (!read_u32(0x04, magic_const) || !read_u32(0x10, field_block_size) || + !read_u32(0x3c, tag_3c) || !read_u32(0x4c, num_elements)) + return false; + if (num_elements == 0 || num_elements > D3D12_IA_VERTEX_INPUT_STRUCTURE_ELEMENT_COUNT) return true; + // Measured at +0x10: 0x1c (28 bytes = 7 u32) in PSOs 1 and 2, 0 in PSO 3 where the element stride is still 28 B. + const std::size_t stride_after_name = (field_block_size >= 16 && field_block_size <= 64) ? field_block_size : 28u; + std::size_t pos = 0x54; + for (std::uint32_t idx = 0; idx < num_elements && pos + 4 <= blob_size; ++idx) { + const void* nul = std::memchr(bytes + pos, 0, blob_size - pos); + if (!nul) break; + const std::size_t name_len = static_cast(nul) - (bytes + pos); + if (name_len == 0) break; + const std::size_t fields_pos = pos + name_len + 1; + // Need at least the first 4 u32s (+0x00 slot, +0x04 DXGI_FORMAT, +0x08 SemanticIndex, +0x0c AlignedByteOffset) + // inside blob_size; never read past blob_size even when the last 1..4 bytes of the 28-byte block are truncated. + if (fields_pos + 16 > blob_size) break; + std::uint32_t slot = 0, fmt = 0, sem_idx = 0, byte_off = 0; + read_u32(fields_pos + 0x00, slot); + read_u32(fields_pos + 0x04, fmt); + read_u32(fields_pos + 0x08, sem_idx); + read_u32(fields_pos + 0x0c, byte_off); + XboxPipelineInputElement elem; + elem.semantic_name.assign(reinterpret_cast(bytes + pos), name_len); + elem.semantic_index = sem_idx; + elem.format = static_cast(fmt); + elem.input_slot = slot < D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT ? slot : 0; + elem.aligned_byte_offset = byte_off; + out_elements.push_back(std::move(elem)); + pos = fields_pos + stride_after_name; + } + return true; +} + +SRWLOCK g_fspx_stage_lock = SRWLOCK_INIT; +leonida::ShaderLibrary* g_fspx_stage_lib = nullptr; +std::wstring* g_fspx_stage_dir = nullptr; + +std::wstring current_shaders_env_dir() { + wchar_t buf[32768]{}; + const DWORD n = GetEnvironmentVariableW(L"LEONIDA_SHADERS", buf, static_cast(std::size(buf))); + if (n == 0 || n >= std::size(buf)) return {}; + return std::wstring(buf, n); +} + +std::string lookup_xbox_fspx_program_stage_impl(const void* program_bytes, std::size_t program_size) { + if (!program_bytes || !program_size || program_size > leonida::kFspxPartLimit) return {}; + const std::span code{static_cast(program_bytes), program_size}; + if (!leonida::fspx_bare_program(code)) return {}; + const std::string hash = leonida::sha256_hex(code); + const std::wstring dir = current_shaders_env_dir(); + if (dir.empty()) return {}; + AcquireSRWLockExclusive(&g_fspx_stage_lock); + if (!g_fspx_stage_lib) g_fspx_stage_lib = new (std::nothrow) leonida::ShaderLibrary(); + if (!g_fspx_stage_dir) g_fspx_stage_dir = new (std::nothrow) std::wstring(); + if (g_fspx_stage_lib && g_fspx_stage_dir && *g_fspx_stage_dir != dir) { + *g_fspx_stage_dir = dir; + g_fspx_stage_lib->load_fspx_only(std::filesystem::path(dir)); + } + const leonida::ShaderEntry* entry = g_fspx_stage_lib ? g_fspx_stage_lib->find_fspx_by_code(hash) : nullptr; + const std::string stage = entry ? entry->stage : std::string{}; + ReleaseSRWLockExclusive(&g_fspx_stage_lock); + return stage; +} + +std::atomic g_slot57_calls{0}; + +HRESULT proxy_create_graphics_pipeline_from_native_code(DeviceProxy* self, const void* desc, + const IID* riid, void** out) { + if (!out) return E_POINTER; + *out = nullptr; + if (!desc) return E_INVALIDARG; + if (!riid) return E_POINTER; + + const auto* xbox_desc = static_cast(desc); + const std::uint64_t call = g_slot57_calls.fetch_add(1, std::memory_order_relaxed) + 1; + + // 1. Inspect and log measured state-blob fields once per offset (no unmeasured offsets). + if (xbox_desc->state_blob && xbox_desc->state_blob_size) { + if (xbox_desc->state_blob_size > leonida::kFspxPartLimit) return E_INVALIDARG; + log_measured_state_blob_fields(xbox_desc->state_blob, static_cast(xbox_desc->state_blob_size)); + } + + // 2. Defensively decode input layout from the pipeline blob (+0x18 / +0x20). + std::vector parsed_inputs; + if (xbox_desc->pipeline_blob && xbox_desc->pipeline_blob_size) { + if (xbox_desc->pipeline_blob_size > leonida::kFspxPartLimit) return E_INVALIDARG; + parse_xbox_pipeline_blob_input_layout_impl( + xbox_desc->pipeline_blob, static_cast(xbox_desc->pipeline_blob_size), parsed_inputs); + } + std::vector input_descs; + input_descs.reserve(parsed_inputs.size()); + for (const auto& elem : parsed_inputs) { + D3D12_INPUT_ELEMENT_DESC d{}; + d.SemanticName = elem.semantic_name.c_str(); + d.SemanticIndex = elem.semantic_index; + d.Format = elem.format; + d.InputSlot = elem.input_slot; + d.AlignedByteOffset = elem.aligned_byte_offset; + d.InputSlotClass = D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA; + d.InstanceDataStepRate = 0; + input_descs.push_back(d); + } + + // 3. Resolve each present RDNA2 program (+0x28/+0x30 and +0x48/+0x50) by sha256(program bytes) and assign its + // stage from the index entry ("vs", "ps", "ms", "gs"), never from its position in the description. + D3D12_GRAPHICS_PIPELINE_STATE_DESC pc_desc{}; + pc_desc.pRootSignature = xbox_desc->root_signature; + pc_desc.InputLayout.pInputElementDescs = input_descs.empty() ? nullptr : input_descs.data(); + pc_desc.InputLayout.NumElements = static_cast(input_descs.size()); + + struct ProgPair { + const void* data; + std::uint64_t size; + }; + const ProgPair pairs[2] = {{xbox_desc->prog_a, xbox_desc->prog_a_size}, + {xbox_desc->prog_b, xbox_desc->prog_b_size}}; + for (const ProgPair& p : pairs) { + if (!p.data && !p.size) continue; + if (!p.data || !p.size || p.size > leonida::kFspxPartLimit) return E_INVALIDARG; + const std::span code{static_cast(p.data), + static_cast(p.size)}; + if (!leonida::fspx_bare_program(code)) { + static std::atomic bad_prog_log{0}; + if (bad_prog_log.fetch_add(1, std::memory_order_relaxed) < 8) + std::fprintf(stderr, "[rt] d3d12_xs: slot 57 call %llu: non-RDNA2 program blob (%llu B)\n", + static_cast(call), static_cast(p.size)); + return E_INVALIDARG; + } + const std::string stage = lookup_xbox_fspx_program_stage_impl(p.data, static_cast(p.size)); + if (stage == "vs") { + pc_desc.VS = {p.data, static_cast(p.size)}; + } else if (stage == "ps") { + pc_desc.PS = {p.data, static_cast(p.size)}; + } else if (stage == "gs") { + pc_desc.GS = {p.data, static_cast(p.size)}; + } else { + static std::atomic miss_log{0}; + if (miss_log.fetch_add(1, std::memory_order_relaxed) < 16) { + const std::string hash = leonida::sha256_hex(code); + std::fprintf(stderr, + "[rt] d3d12_xs: slot 57 call %llu: no translated graphics stage in fspx_gfx for kind-6 " + "sha256 %s (%llu B)\n", + static_cast(call), hash.c_str(), + static_cast(p.size)); + } + return E_INVALIDARG; + } + } + + // 4. Safe default fixed-function state (blend disabled, depth test on/LESS, cull none, triangle list, 1x sample). + pc_desc.BlendState.AlphaToCoverageEnable = FALSE; + pc_desc.BlendState.IndependentBlendEnable = FALSE; + for (auto& rt : pc_desc.BlendState.RenderTarget) { + rt.BlendEnable = FALSE; + rt.LogicOpEnable = FALSE; + rt.SrcBlend = D3D12_BLEND_ONE; + rt.DestBlend = D3D12_BLEND_ZERO; + rt.BlendOp = D3D12_BLEND_OP_ADD; + rt.SrcBlendAlpha = D3D12_BLEND_ONE; + rt.DestBlendAlpha = D3D12_BLEND_ZERO; + rt.BlendOpAlpha = D3D12_BLEND_OP_ADD; + rt.LogicOp = D3D12_LOGIC_OP_NOOP; + rt.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + } + pc_desc.SampleMask = UINT_MAX; + pc_desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + pc_desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + pc_desc.RasterizerState.FrontCounterClockwise = FALSE; + pc_desc.RasterizerState.DepthBias = D3D12_DEFAULT_DEPTH_BIAS; + pc_desc.RasterizerState.DepthBiasClamp = D3D12_DEFAULT_DEPTH_BIAS_CLAMP; + pc_desc.RasterizerState.SlopeScaledDepthBias = D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS; + pc_desc.RasterizerState.DepthClipEnable = TRUE; + pc_desc.RasterizerState.MultisampleEnable = FALSE; + pc_desc.RasterizerState.AntialiasedLineEnable = FALSE; + pc_desc.RasterizerState.ForcedSampleCount = 0; + pc_desc.RasterizerState.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF; + + pc_desc.DepthStencilState.DepthEnable = TRUE; + pc_desc.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; + pc_desc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_LESS; + pc_desc.DepthStencilState.StencilEnable = FALSE; + pc_desc.DepthStencilState.StencilReadMask = D3D12_DEFAULT_STENCIL_READ_MASK; + pc_desc.DepthStencilState.StencilWriteMask = D3D12_DEFAULT_STENCIL_WRITE_MASK; + const D3D12_DEPTH_STENCILOP_DESC default_stencil_op = { + D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_COMPARISON_FUNC_ALWAYS}; + pc_desc.DepthStencilState.FrontFace = default_stencil_op; + pc_desc.DepthStencilState.BackFace = default_stencil_op; + + pc_desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + if (pc_desc.PS.pShaderBytecode && pc_desc.PS.BytecodeLength) { + pc_desc.NumRenderTargets = 1; + pc_desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + } else { + pc_desc.NumRenderTargets = 0; + } + pc_desc.DSVFormat = DXGI_FORMAT_D32_FLOAT; + pc_desc.SampleDesc.Count = 1; + pc_desc.SampleDesc.Quality = 0; + pc_desc.NodeMask = 0; + pc_desc.CachedPSO = {nullptr, 0}; + pc_desc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE; + + const HRESULT hr = self->real->CreateGraphicsPipelineState(&pc_desc, *riid, out); + if (FAILED(hr)) { + static std::atomic fail_log{0}; + if (fail_log.fetch_add(1, std::memory_order_relaxed) < 16) + std::fprintf(stderr, + "[rt] d3d12_xs: slot 57 call %llu failed with 0x%08lx (state %llu B, pipe %llu B, progA %llu B, " + "progB %llu B)\n", + static_cast(call), static_cast(hr), + static_cast(xbox_desc->state_blob_size), + static_cast(xbox_desc->pipeline_blob_size), + static_cast(xbox_desc->prog_a_size), + static_cast(xbox_desc->prog_b_size)); + } + return hr; +} + HRESULT proxy_create_resource(DeviceProxy* self, const D3D12_HEAP_PROPERTIES* heap_properties, D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC* xbox_desc, D3D12_RESOURCE_STATES initial_state, const D3D12_CLEAR_VALUE* clear_value, @@ -2347,6 +3751,10 @@ HRESULT proxy_create_resource(DeviceProxy* self, const D3D12_HEAP_PROPERTIES* he const auto xbox_layout = static_cast(pc_desc.Layout); pc_desc.Layout = pc_desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER ? D3D12_TEXTURE_LAYOUT_ROW_MAJOR : D3D12_TEXTURE_LAYOUT_UNKNOWN; + // A console depth-stencil texture may allow unordered access; the PC one may not (without_depth_stencil_uav, the + // slot 25 stand-in). Only that bit is dropped here: the other flag bits go on as they came. + pc_desc.Flags = static_cast( + without_depth_stencil_uav(pc_desc.Dimension, static_cast(pc_desc.Flags))); static std::atomic logged{false}; if (!logged.exchange(true, std::memory_order_relaxed)) { @@ -2354,8 +3762,9 @@ HRESULT proxy_create_resource(DeviceProxy* self, const D3D12_HEAP_PROPERTIES* he "[rt] d3d12_xs: slot 76 resource: dimension=%d xbox layout=0x%x -> PC layout=0x%x\n", static_cast(pc_desc.Dimension), xbox_layout, static_cast(pc_desc.Layout)); } - const HRESULT hr = self->real->CreateCommittedResource(heap_properties, heap_flags, &pc_desc, initial_state, - clear_value, *riid, out); + const HRESULT hr = self->real->CreateCommittedResource(heap_properties, heap_flags, &pc_desc, + pc_initial_state(&pc_desc, initial_state), clear_value, + *riid, out); if (SUCCEEDED(hr)) lease_title_resource_memory(self, *out, pc_desc); return hr; } @@ -2367,11 +3776,9 @@ HRESULT proxy_create_resource(DeviceProxy* self, const D3D12_HEAP_PROPERTIES* he // device behind the proxy registered (set_placed_at_va_handler), with the PC flags kept and the layout made // ROW_MAJOR, as slot 76 does. std::atomic g_placed_at_va{nullptr}; -std::atomic g_placed_at_va_pages{nullptr}; -HRESULT proxy_create_placed_resource_x(DeviceProxy* self, void* va, const D3D12_RESOURCE_DESC* xbox_desc, - std::uint32_t state, const IID* riid, void** out) { - note_slot(133); +HRESULT proxy_create_buffer_at_va(DeviceProxy* self, void* va, const D3D12_RESOURCE_DESC* xbox_desc, + std::uint32_t state, const IID* riid, void** out) { if (out) *out = nullptr; // Without a handler (a PC device behind the proxy, or none registered) the slot refuses like any slot past the // PC vtable, whatever its arguments. @@ -2453,7 +3860,7 @@ HRESULT proxy_create_committed_resource3_x(DeviceProxy* self, std::uint64_t heap if (out) *out = nullptr; // _COM_Outptr_: NULL on every failure, as slots 14/62/76 const auto* const xbox_desc = reinterpret_cast(desc_word); const auto* const riid = reinterpret_cast(riid_word); - if (!out || !xbox_desc || !riid) return E_POINTER; + if (!out || !heap_word || !xbox_desc || !riid) return E_POINTER; if (self->slot_count <= kPcCreateCommittedResource3) { // the PC device predates ID3D12Device10 static std::atomic warned{false}; if (first_call(warned)) @@ -2562,6 +3969,73 @@ bool route_xbox_device_slot(DeviceProxy* self, unsigned slot, std::uint64_t a1, return true; } +// Device slot 133 places a resource at a virtual address: (va, desc, initial_state, clear_value, riid, out), the +// shape of the console's CreatePlacedResourceX. Measured locally at a title's call sites: riid is ID3D12Resource, va is +// the start of a range the title has just reserved for physical pages, desc is a 56-byte D3D12_RESOURCE_DESC with +// Xbox bits in Flags above the PC flags, and initial_state is all ones, which is no PC state. The PC has no call that +// puts a resource at a caller's address, so this creates a committed DEFAULT-heap resource from the cleaned +// description: the PC flags only, slot 76's layout rule, COMMON for a buffer or an all-ones state, and the clear value +// only for a render target or depth texture. The resource is not backed by the memory at va: what the title writes +// there does not reach it. Backing it needs the physical-page mapper; until then this gets the title past the call. +constexpr std::uint32_t kPcResourceFlags = 0x3FF; // D3D12_RESOURCE_FLAG_* up to USE_TIGHT_ALIGNMENT (0x200) + +HRESULT proxy_create_placed_resource_x(DeviceProxy* self, std::uint64_t va, const D3D12_RESOURCE_DESC* xbox_desc, + std::uint32_t initial_state, const D3D12_CLEAR_VALUE* clear_value, + const IID* riid, void** out) { + note_slot(133); + if (out) *out = nullptr; + if (!xbox_desc) return E_INVALIDARG; + if (!riid || !out) return E_POINTER; + + D3D12_RESOURCE_DESC pc_desc = *xbox_desc; + const auto xbox_flags = static_cast(pc_desc.Flags); + pc_desc.Flags = static_cast(xbox_flags & kPcResourceFlags); + const bool buffer = pc_desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER; + pc_desc.Layout = buffer ? D3D12_TEXTURE_LAYOUT_ROW_MAJOR : D3D12_TEXTURE_LAYOUT_UNKNOWN; + const auto state = (buffer || initial_state == 0xFFFFFFFFu) ? D3D12_RESOURCE_STATE_COMMON + : static_cast(initial_state); + const bool clearable = + !buffer && (pc_desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)); + + static std::atomic logged{false}; + if (first_call(logged)) + std::fprintf(stderr, + "[rt] d3d12_xs: slot 133 places a resource at a VA: dimension=%d flags=0x%x -> 0x%x, state=0x%x; " + "created committed, not backed by the VA\n", + static_cast(pc_desc.Dimension), xbox_flags, static_cast(pc_desc.Flags), + initial_state); + (void)va; + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT, D3D12_CPU_PAGE_PROPERTY_UNKNOWN, + D3D12_MEMORY_POOL_UNKNOWN, 0, 0}; + return self->real->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &pc_desc, state, + clearable ? clear_value : nullptr, *riid, out); +} + +// Slot 133 with both of its paths. The buffer on the title's own pages (proxy_create_buffer_at_va) is tried first: it +// is the only one whose memory is the memory at `va`. Where it cannot be made (no handler registered, a PC device +// behind the proxy, a texture, no VK_EXT_external_memory_host, or a range the import refuses), the committed DEFAULT +// stand-in (proxy_create_placed_resource_x) answers, so the title still gets a resource and does not assert; that +// one is not backed by the VA and its first-call log line says so. +HRESULT proxy_create_placed_resource_slot133(DeviceProxy* self, std::uint64_t va, + const D3D12_RESOURCE_DESC* xbox_desc, std::uint32_t state, + const D3D12_CLEAR_VALUE* clear_value, const IID* riid, void** out) { + if (out && xbox_desc && riid) { + const HRESULT hr = proxy_create_buffer_at_va(self, reinterpret_cast(va), xbox_desc, state, riid, out); + if (SUCCEEDED(hr)) { + note_slot(133); + return hr; + } + *out = nullptr; + static std::atomic logged{false}; + if (hr != E_NOTIMPL && !logged.exchange(true, std::memory_order_relaxed)) + std::fprintf(stderr, + "[rt] d3d12_xs: slot 133: no buffer on the title's pages at %p (hr=0x%08x); creating the " + "committed stand-in\n", + reinterpret_cast(va), static_cast(hr)); + } + return proxy_create_placed_resource_x(self, va, xbox_desc, state, clear_value, riid, out); +} + // Slot 74: the retail title calls it once with (pointer, u32, pointer) (kapitche, issue 7231). The PC slot 74 is // ID3D12Device9::ShaderCacheControl(kinds, control), which reads the first word as a flags value and returns // E_INVALIDARG, and the title then stops on an int3. The words are not measured: nothing is written through the @@ -2577,14 +4051,79 @@ std::uint64_t proxy_slot74(std::uint64_t a1, std::uint64_t a2, std::uint64_t a3) return hr_to_u64(S_OK); } +// Keeps a copy of the stream a PSO was created from, on the PSO, so slot 55 can derive from it. A stream the module +// does not model is logged once: the PSO is still returned, and slot 55 refuses it as a base. +void keep_pso_stream(IUnknown* pso, const D3D12_PIPELINE_STATE_STREAM_DESC& desc) { + ID3D12Object* object = nullptr; + if (FAILED(pso->QueryInterface(__uuidof(ID3D12Object), reinterpret_cast(&object))) || !object) return; + auto record = PsoStreamRecord::capture(desc, used_console_stream); + static std::atomic logged{false}; + if (!record || !attach_pso_record(object, std::move(record))) { + if (!logged.exchange(true, std::memory_order_relaxed)) + std::fprintf(stderr, "[rt] d3d12_xs: a pipeline state stream is not kept for derivation (unmodelled subobject or allocation failure); slot 55 refuses that PSO as a base\n"); + } + object->Release(); +} + +// The PC CreatePipelineState (PC slot 47) that slots 86 and 55 share: on success the stream is kept on the PSO. +HRESULT create_pso_from_stream(DeviceProxy* self, const D3D12_PIPELINE_STATE_STREAM_DESC* desc, const IID* riid, + void** out) { + if (!riid) return E_POINTER; + using Fn = HRESULT(WINAPI*)(ID3D12Device*, const D3D12_PIPELINE_STATE_STREAM_DESC*, const IID*, void**); + used_console_stream = false; + d3d12_trace::stream_refusal = nullptr; + const HRESULT hr = reinterpret_cast(self->real_vtable[47])(self->real, desc, riid, out); + static const bool audit = [] { + char value[2]{}; + return GetEnvironmentVariableA("LEONIDA_PSO_STREAM_AUDIT", value, sizeof(value)) == 1 && value[0] == '1'; + }(); + if (audit && desc && (hr == E_NOTIMPL || hr == E_FAIL)) { + try { + audit_pso_stream(*desc, hr, used_console_stream); + } catch (const std::bad_alloc&) {} + } + if (SUCCEEDED(hr) && out && *out && desc) keep_pso_stream(static_cast(*out), *desc); + return hr; +} + // Xbox slot 86: CreatePipelineState(desc, riid, out), forwarded to PC ID3D12Device2::CreatePipelineState (PC slot 47). HRESULT proxy_create_pipeline_state(DeviceProxy* self, const D3D12_PIPELINE_STATE_STREAM_DESC* desc, const IID* riid, void** out) { if (out) *out = nullptr; if (self->slot_count <= 47) return refuse_beyond_device(86, self->slot_count); // predates ID3D12Device2 - if (!riid) return E_POINTER; - using Fn = HRESULT(WINAPI*)(ID3D12Device*, const D3D12_PIPELINE_STATE_STREAM_DESC*, const IID*, void**); - return reinterpret_cast(self->real_vtable[47])(self->real, desc, riid, out); + return create_pso_from_stream(self, desc, riid, out); +} + +// Logs a slot 55 refusal once per reason, and returns the HRESULT. +HRESULT refuse_derived(unsigned reason, const char* why, HRESULT hr) { + static std::atomic logged[4]{}; + if (!logged[reason].exchange(true, std::memory_order_relaxed)) + std::fprintf(stderr, "[rt] d3d12_xs: derived pipeline state (device slot 55) refused: %s\n", why); + return hr; +} + +// Xbox slot 55: CreateDerivedPipelineState(pBasePSO, n, pRecords, riid, ppv). The base must be a PSO that slot 86 or +// slot 55 created with a kept stream; n is 1..4 records of 0x14c bytes (d3d12_xs_pso_stream.h). The patched stream +// goes through the slot 86 path. Every refusal leaves *ppv null and returns a failure, never a fake success. +HRESULT proxy_create_derived_pso(DeviceProxy* self, ID3D12PipelineState* base, std::uint32_t count, + const unsigned char* records, const IID* riid, void** out) { + note_slot(55); + if (out) *out = nullptr; + if (self->slot_count <= 47) return refuse_beyond_device(55, self->slot_count); // predates ID3D12Device2 + if (!out || !riid || !records) return E_POINTER; + const PsoStreamRecord* base_record = base ? find_pso_record(base) : nullptr; + if (!base_record) return refuse_derived(0, "base PSO has no kept stream", E_FAIL); + std::vector patched; + switch (derive_stream(*base_record, records, count, patched)) { + case DeriveStatus::ok: break; + case DeriveStatus::unknown_tag: return refuse_derived(1, "record tag not known", E_INVALIDARG); + case DeriveStatus::missing_state: return refuse_derived(2, "base has no subobject for a record", E_INVALIDARG); + case DeriveStatus::malformed: return refuse_derived(3, "record count or base stream malformed", E_INVALIDARG); + } + D3D12_PIPELINE_STATE_STREAM_DESC desc{}; + desc.SizeInBytes = patched.size(); + desc.pPipelineStateSubobjectStream = patched.data(); + return create_pso_from_stream(self, &desc, riid, out); } // Xbox slot 101: CreateStateObject(desc, riid, out), forwarded to PC ID3D12Device5::CreateStateObject (PC slot 62, @@ -2687,17 +4226,8 @@ std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64 return hr_to_u64(proxy_create_command_allocator(self, a1, reinterpret_cast(a2), reinterpret_cast(a3))); } else if constexpr (Slot == 12) { - note_slot(12); - a3 = unwrap_object(a3); - if (Slot >= self->slot_count) return hr_to_u64(refuse_beyond_device(12, self->slot_count)); - using CreateListFn = HRESULT(WINAPI*)(ID3D12Device*, UINT, D3D12_COMMAND_LIST_TYPE, ID3D12CommandAllocator*, - ID3D12PipelineState*, const IID*, void**); - auto fn = reinterpret_cast(self->real_vtable[12]); - return hr_to_u64(fn(self->real, static_cast(a1), static_cast(a2), - reinterpret_cast(a3), - reinterpret_cast(a4), - reinterpret_cast(a5), - reinterpret_cast(a6))); + return hr_to_u64(proxy_create_command_list(self, a1, a2, a3, a4, reinterpret_cast(a5), + reinterpret_cast(a6))); } else if constexpr (Slot == 36) { return hr_to_u64(proxy_create_fence(self, a1, a2, reinterpret_cast(a3), reinterpret_cast(a4))); @@ -2768,6 +4298,26 @@ std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64 D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(a3)}, static_cast(static_cast(a4))); return 0; + } else if constexpr (Slot == 57) { + // Xbox slot 57 is DeserializeGraphicsPipelineStateX(desc, riid, out), whereas PC slot 57 is + // ID3D12Device4::CreateProtectedResourceSession(desc, riid, out). Both pass `riid` in `a2`; when `riid` + // is IID_ID3D12PipelineState (or `a2` is null so the slot-57 null-IID path is tested), route to graphics + // PSO deserialization. When `riid` is IID_ID3D12ProtectedResourceSession*, forward to the PC device. + const IID* riid = reinterpret_cast(a2); + if (!riid || *riid == __uuidof(ID3D12PipelineState)) { + note_slot(57); + log_xbox_route_once(57, "DeserializeGraphicsPipelineStateX", a1, a2, a3, a4, a5); + return hr_to_u64(proxy_create_graphics_pipeline_from_native_code( + self, reinterpret_cast(a1), riid, reinterpret_cast(a3))); + } + note_slot(57); + if (57 >= self->slot_count) return hr_to_u64(refuse_beyond_device(57, self->slot_count)); + using ForwardFn = std::uint64_t(WINAPI*)(void*, std::uint64_t, std::uint64_t, std::uint64_t, + std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, + std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, + std::uint64_t, std::uint64_t, std::uint64_t); + auto fn = reinterpret_cast(self->real_vtable[57]); + return fn(self->real, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14); } else if constexpr (Slot == 62) { return hr_to_u64(proxy_create_compute_pipeline_state( self, reinterpret_cast(a1), a2, a3, @@ -2795,12 +4345,19 @@ std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64 self, reinterpret_cast(a1), reinterpret_cast(a2), reinterpret_cast(a3))); } else if constexpr (Slot == 133) { - return hr_to_u64(proxy_create_placed_resource_x(self, reinterpret_cast(a1), - reinterpret_cast(a2), - static_cast(a3), reinterpret_cast(a5), - reinterpret_cast(a6))); + return hr_to_u64(proxy_create_placed_resource_slot133( + self, a1, reinterpret_cast(a2), static_cast(a3), + reinterpret_cast(a4), reinterpret_cast(a5), + reinterpret_cast(a6))); } else if constexpr (Slot == 70) { - proxy_create_srv_from_raw_x(self, a1, a2, a3); + std::uint64_t routed = 0; + if (route_xbox_device_slot(self, Slot, a1, a2, a3, a4, a5, routed)) return routed; // an override moved a route here + proxy_create_placed_view_x(self, false, a1, a2, a3); + return 0; + } else if constexpr (Slot == 71) { + std::uint64_t routed = 0; + if (route_xbox_device_slot(self, Slot, a1, a2, a3, a4, a5, routed)) return routed; // an override moved a route here + proxy_create_placed_view_x(self, true, a1, a2, a3); return 0; } else if constexpr (Slot == 76) { return hr_to_u64(proxy_create_resource( @@ -2810,6 +4367,11 @@ std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64 static_cast(static_cast(a4)), reinterpret_cast(a5), reinterpret_cast(a6), reinterpret_cast(a7))); + } else if constexpr (Slot == 55) { + return hr_to_u64(proxy_create_derived_pso( + self, reinterpret_cast(a1), static_cast(a2), + reinterpret_cast(a3), reinterpret_cast(a4), + reinterpret_cast(a5))); } else if constexpr (Slot == kCreateCommittedResource3X) { return hr_to_u64(proxy_create_committed_resource3_x(self, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10)); } else { @@ -2837,6 +4399,9 @@ std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64 reinterpret_cast(a2), reinterpret_cast(a3))); } else if constexpr (Slot == 108) { return proxy_get_resource_allocation_info2(self, a1, a2, a3, a4, a5); + } else if constexpr (Slot == 27 || Slot == 53) { + if (Slot >= self->slot_count) return hr_to_u64(refuse_beyond_device(Slot, self->slot_count)); + return proxy_create_committed_resource(self, a1, a2, a3, a4, a5, a6, a7, a8); } else { if (Slot >= self->slot_count) return hr_to_u64(refuse_beyond_device(Slot, self->slot_count)); @@ -2909,7 +4474,13 @@ void apply_console_placement(const D3D12_RESOURCE_DESC* descs, UINT count, D3D12 "description(s)\n", slot, static_cast(console.SizeInBytes), static_cast(info.SizeInBytes), static_cast(count)); - if (console.SizeInBytes >= info.SizeInBytes) info = console; + // A list with a depth-stencil target may come out smaller than the PC answer (console_depth_stencil_size). + bool depth = false; + for (UINT i = 0; descs && i < count && !depth; ++i) { + UINT64 xg_size = 0, xg_alignment = 0; + depth = console_depth_stencil_size(descs[i]) != 0 || console_texture_layout(descs[i], xg_size, xg_alignment); + } + if (depth || console.SizeInBytes >= info.SizeInBytes) info = console; } void* WINAPI proxy_get_resource_allocation_info(std::uint64_t a0, std::uint64_t a1, std::uint64_t visible_mask, @@ -2920,6 +4491,7 @@ void* WINAPI proxy_get_resource_allocation_info(std::uint64_t a0, std::uint64_t // Normalize console descriptors in a copy. PC calls can also pass the Xbox tiled layout explicitly. Otherwise // their flags and layout reach the host unchanged so the host can validate them. const UINT desc_count = static_cast(count); + const D3D12_RESOURCE_DESC* const title_descs = descs; std::unique_ptr clean; if (descs && desc_count) { clean.reset(new (std::nothrow) D3D12_RESOURCE_DESC[desc_count]); @@ -2930,16 +4502,64 @@ void* WINAPI proxy_get_resource_allocation_info(std::uint64_t a0, std::uint64_t for (UINT i = 0; i < desc_count; ++i) { const auto& desc = descs[i]; clean[i] = call.console_abi || desc.Layout == kXboxTiledResourceLayout ? pc_resource_desc(desc) : desc; + static std::atomic uav_dropped{false}; + if (((static_cast(desc.Flags) & ~static_cast(clean[i].Flags)) & + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) && + first_call(uav_dropped)) + std::fprintf(stderr, + "[rt] d3d12_xs: slot 25: depth-stencil texture (format %d) sized without unordered " + "access, which the PC refuses with it (stand-in)\n", + static_cast(desc.Format)); } descs = clean.get(); } const UINT mask = static_cast(visible_mask); D3D12_RESOURCE_ALLOCATION_INFO info = real->GetResourceAllocationInfo(mask, desc_count, descs); + // The title asserts that the size fits in 32 bits, so a description the PC refuses (UINT64_MAX) stops the boot. + // Each refused description is logged once per (dimension, format, flags) so the next stand-in can be found. + if (info.SizeInBytes == UINT64_MAX && descs) { + static std::mutex mutex; + static std::set seen; + for (UINT i = 0; i < desc_count; ++i) { + const D3D12_RESOURCE_DESC& d = descs[i]; + const std::uint64_t key = (std::uint64_t(d.Dimension) << 56) | (std::uint64_t(d.Format) << 40) | + static_cast(d.Flags); + { + const std::lock_guard lock(mutex); + if (!seen.insert(key).second) continue; + } + std::fprintf(stderr, + "[rt] d3d12_xs: slot 25: the PC refuses to size a description: dimension=%d format=%d " + "%llux%ux%u mips=%u samples=%u/%u layout=0x%x flags=0x%x (console flags 0x%x)\n", + static_cast(d.Dimension), static_cast(d.Format), + static_cast(d.Width), d.Height, d.DepthOrArraySize, d.MipLevels, + d.SampleDesc.Count, d.SampleDesc.Quality, static_cast(d.Layout), + static_cast(d.Flags), static_cast(title_descs[i].Flags)); + } + } + const UINT64 pc_size = info.SizeInBytes; // The console tile sizes are the title's: a call in the console form gets them. A PC-form caller (the runtime's // own code and tests, which compare with the PC device) gets the PC device's answer unchanged. if (call.console_abi) apply_console_placement(descs, desc_count, info, nullptr, [&](UINT i) { return real->GetResourceAllocationInfo(mask, 1, &descs[i]); }, 25); + // LEONIDA_LOG_ALLOCINFO=1: every call, with the calling thread (the title sums a batch of these against a fixed + // pool and asserts when the batch does not fit). + static const bool log_all = [] { + wchar_t value[2]{}; + return GetEnvironmentVariableW(L"LEONIDA_LOG_ALLOCINFO", value, 2) == 1 && value[0] == L'1'; + }(); + if (log_all && descs && desc_count) + std::fprintf(stderr, + "[rt] d3d12_xs: slot 25 tid %lx n %u: dim %d fmt %d %llux%ux%u mips %u samples %u flags 0x%x -> %llu B " + "(pc %llu) align %llu\n", + static_cast(GetCurrentThreadId()), static_cast(desc_count), + static_cast(descs[0].Dimension), static_cast(descs[0].Format), + static_cast(descs[0].Width), static_cast(descs[0].Height), + static_cast(descs[0].DepthOrArraySize), static_cast(descs[0].MipLevels), + static_cast(descs[0].SampleDesc.Count), static_cast(descs[0].Flags), + static_cast(info.SizeInBytes), static_cast(pc_size), + static_cast(info.Alignment)); *static_cast(call.ret) = info; return call.ret; } @@ -2958,6 +4578,17 @@ void* WINAPI proxy_get_resource_allocation_info1(std::uint64_t a0, std::uint64_t } using Fn = void*(WINAPI*)(void*, void*, UINT, UINT, const D3D12_RESOURCE_DESC*, D3D12_RESOURCE_ALLOCATION_INFO1*); const UINT n = static_cast(count); + // The per-resource array is optional (_Out_writes_opt_). The console total must not depend on whether the + // caller asked for it, so without one the host's per-resource answers go to a local array (found by Alpha325). + std::vector local; + if (!each && descs && n) { + try { + local.resize(n); + each = local.data(); + } catch (const std::bad_alloc&) { + each = nullptr; // the host total stands + } + } void* const returned = reinterpret_cast(self->real_vtable[56])( self->real, call.ret, static_cast(visible_mask), n, descs, each); if (each && call.console_abi) { // console sizes for the console form only, as slot 25 @@ -3022,7 +4653,9 @@ unsigned detect_slot_count(ID3D12Device* real) { } // namespace -HRESULT create_device_proxy(ID3D12Device* real, REFIID riid, void** out) { +IUnknown* real_object_behind_proxy(const void* object) { return proxy_real_object(object); } + +HRESULT create_device_proxy(ID3D12Device* real, REFIID riid, void** out, bool console_lists) { if (!real) return E_POINTER; if (!out) return E_POINTER; *out = nullptr; @@ -3033,6 +4666,7 @@ HRESULT create_device_proxy(ID3D12Device* real, REFIID riid, void** out) { proxy->real = real; proxy->real_vtable = *reinterpret_cast(real); proxy->slot_count = detect_slot_count(real); + proxy->console_lists = console_lists; proxy->refs.store(1, std::memory_order_relaxed); proxy->dxgi_vtable = get_dxgi_vtable(); proxy->adapter_provider = nullptr; @@ -3165,10 +4799,17 @@ ID3D12Device* device_proxy_real_device(const void* device) { return static_cast(device)->real; } +std::shared_ptr device_frame_tokens(const void* device) { + if (!is_device_proxy(device)) return nullptr; + return static_cast(device)->frame_tokens; +} + bool device_slot_overridden(unsigned slot) { - if (slot <= 2 || slot == 8 || slot == 9 || slot == 14 || (slot >= 17 && slot <= 24) || slot == 25 || slot == 26 || slot == 31 || slot == 32 || slot == 34 || slot == 35 || - slot == 36 || slot == 41 || slot == 45 || slot == 46 || slot == 50 || slot == 56 || slot == 61 || slot == 74 || slot == 62 || slot == 67 || - slot == 70 || slot == 75 || slot == 76 || slot == 133 || slot == kCreateCommittedResource3X || slot == 86 || slot == 101 || slot == 108) + if (slot <= 2 || slot == 8 || slot == 9 || slot == 12 || slot == 14 || (slot >= 17 && slot <= 27) || slot == 31 || + slot == 32 || slot == 34 || slot == 35 || slot == 36 || slot == 41 || slot == 45 || slot == 46 || slot == 50 || + slot == 53 || slot == 55 || slot == 56 || slot == 61 || slot == 62 || slot == 67 || slot == 70 || slot == 74 || slot == 75 || + slot == 76 || + slot == 86 || slot == 101 || slot == 108 || slot == kCreateCommittedResource3X || slot == 133) return true; const XboxDeviceSlotRoutes& routes = xbox_device_slot_routes(); return slot == routes.frame_interval || slot == routes.schedule_event || slot == routes.wait_event || @@ -3176,6 +4817,17 @@ bool device_slot_overridden(unsigned slot) { } bool is_queue_proxy(const void* queue) { return is_child_proxy(queue); } + +bool is_list_proxy(const void* list) { return is_list_proxy_impl(list); } + +ID3D12CommandList* list_proxy_real_list(const void* list) { + if (!is_list_proxy_impl(list)) return nullptr; + return static_cast(list)->real; +} + +const char* list_tail_slot_name(unsigned slot, unsigned char console_layout) { + return list_tail_name(slot, console_layout); +} bool is_fence_proxy(const void* fence) { return is_child_proxy(fence); } bool is_allocator_proxy(const void* allocator) { return is_child_proxy(allocator); } @@ -3214,6 +4866,18 @@ unsigned allocator_proxy_slot_count(const void* allocator) { return is_allocator_proxy(allocator) ? static_cast(allocator)->slot_count : 0; } +std::uintptr_t allocator_proxy_callback(const void* allocator) { + return is_allocator_proxy(allocator) + ? static_cast(allocator)->allocator_callback.load(std::memory_order_relaxed) + : 0; +} + +std::uintptr_t allocator_proxy_callback_context(const void* allocator) { + return is_allocator_proxy(allocator) + ? static_cast(allocator)->allocator_callback_context.load(std::memory_order_relaxed) + : 0; +} + unsigned long command_object_proxy_ref_count(const void* object) { if (!is_queue_proxy(object) && !is_fence_proxy(object) && !is_allocator_proxy(object)) return 0; return static_cast(object)->refs.load(std::memory_order_relaxed); @@ -3344,4 +5008,13 @@ void reset_device_proxy_stats() { reset_child_stats(); } +bool parse_xbox_pipeline_blob_input_layout(const void* blob, std::size_t blob_size, + std::vector& out_elements) { + return parse_xbox_pipeline_blob_input_layout_impl(blob, blob_size, out_elements); +} + +std::string lookup_xbox_fspx_program_stage(const void* program_bytes, std::size_t program_size) { + return lookup_xbox_fspx_program_stage_impl(program_bytes, program_size); +} + } // namespace rt::d3d12_xs diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h index d796b919f1..a4c03dca2f 100644 --- a/runtime/shims/d3d12_xs_device.h +++ b/runtime/shims/d3d12_xs_device.h @@ -10,29 +10,48 @@ // from the retail title's call sites) is created as D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH. // slot 61 CreateSamplerX(desc, dest) -> PC CreateSampler (slot 22); the description's PC // D3D12_SAMPLER_DESC prefix is passed. The PC slot 61 is CreateMetaCommand. Measured on the retail title's boot. +// slot 57 DeserializeGraphicsPipelineStateX(desc, iid, out): converts the Xbox 0x68-byte native graphics PSO +// description (+0x00 root signature, +0x08/+0x10 state blob, +0x18/+0x20 pipeline input-layout blob, +// +0x28/+0x30 and +0x48/+0x50 bare RDNA2 programs, +0x38/+0x40 and +0x58/+0x60 kind-2 stage blobs) to +// D3D12_GRAPHICS_PIPELINE_STATE_DESC and forwards to PC CreateGraphicsPipelineState (slot 10). When the +// second argument's IID is not IID_ID3D12PipelineState, forwards to PC CreateProtectedResourceSession. // slot 62 CreateComputePipelineState(desc, w2, w3, iid, out): two words (0 from XboxBvhBuilder, meaning unknown) // before the IID. The PC slot 62 is CreateStateObject. // slot 67 CreateComputePipelineState from native code (desc, iid, out): converts the Xbox native-code desc // (+0x00 root signature, +0x28 code, +0x30 size) to D3D12_COMPUTE_PIPELINE_STATE_DESC and forwards // to PC CreateComputePipelineState (slot 11). The PC slot 67 is CreateProtectedResourceSession1. -// slot 70 (texture words, view desc, destination handle), no return value: a shader-resource view from raw words -// and a GPU address, with no resource (retail boot chain stop 14). The PC slot 70 is CreatePlacedResource1. -// The words are not measured, so the destination gets the PC null view (PC CreateShaderResourceView -// with no resource) and the call returns. +// slot 70 (resource words, view words, destination handle), no return value: a shader-resource view of memory the +// title placed itself, with no resource (retail boot chain stop 14). The PC slot 70 is CreatePlacedResource1. +// Layout per VIctory: 14 resource dwords shaped as D3D12_RESOURCE_DESC, 16 view dwords whose first 10 are +// the PC view description and 10-11 the memory's address. A buffer view gets its V#; a texture the PC +// null view (no texture exists for the title's memory yet). +// slot 71 the same for an unordered-access view. The PC slot 71 is CreateSamplerFeedbackUnorderedAccessView. // slot 74 (pointer, u32, pointer): not measured, returns S_OK. The PC slot 74 is ShaderCacheControl(kinds, control), // which reads the first word as flags and returns E_INVALIDARG. Nothing is written, the PC device is not called. // slot 76 resource creation -> PC CreateCommittedResource (PC slot 27), with the Xbox layout word ignored. // slot 127 CreateCommittedResource3 (heap, flags, desc1, layout, clear, session, castable count/list, riid, out) -> // PC ID3D12Device10::CreateCommittedResource3 (PC slot 76), with the Xbox layout word replaced and the // Xbox flag bits dropped (RT-5 stop 15, docs/retail_boot_chain.md). E_NOTIMPL when the PC device lacks it. -// slot 48 CreateCommandQueueX(desc, riid, out) -> the same queue proxy as slot 8. The Xbox desc's first fields are -// D3D12_COMMAND_QUEUE_DESC's (public HLE). -// slot 73 CreateCommandListX(desc, allocator, initialState, riid, out) -> PC CreateCommandList(0, type, allocator, -// initialState, riid, out). The type is the first word of the Xbox desc; there is no node-mask argument -// in the console call (public HLE; the PC six-argument form differs). -// slots 78/79/80 SetFrameIntervalX, ScheduleFrameEventX, WaitFrameEventX. A per-device token state machine answers -// them before the PC vtable is indexed; WaitFrameEventX returns at once with a fresh non-zero token. -// Slot 80 is outside a PC ID3D12Device11 table, so it is checked before the beyond-table refusal. +// slot 26 GetCustomHeapProperties, called by the retail title with the C ABI: return buffer in RCX, the device +// in RDX (the PC form is `this` in RCX, return buffer in RDX). Slot 25 (GetResourceAllocationInfo, also a +// struct wider than 8 bytes) takes the same form by the same rule. Both accept either form. +// slot 133 CreatePlacedResourceX(va, desc, state, clear, riid, out) -> a buffer on the title's pages at va, made by +// the handler of set_placed_at_va_handler (below). Where that cannot be made, PC CreateCommittedResource +// on a DEFAULT heap, with the Xbox flag bits dropped and an all-ones state as COMMON: not backed by the +// memory at va. +// slot 48 CreateCommandQueueX(desc, riid, out) -> the same queue proxy as slot 8. The 32-byte Xbox desc starts with +// a D3D12_COMMAND_QUEUE_DESC; only that prefix is passed on, with the console-only flag bits cleared +// (DISABLE_GPU_TIMEOUT is kept). The four extra words are logged once. +// slot 73 CreateCommandListX(desc, allocator, initialState, riid, out) -> the slot 12 console list proxy over PC +// CreateCommandList(0, type, allocator, initialState). The type is the first word of the Xbox desc; there +// is no node-mask argument in the console call (public HLE; the PC six-argument form differs). An riid the +// proxy does not answer (the console's own list IID) is answered with the proxy. +// slots 78/79/80/81 SetFrameIntervalX, ScheduleFrameEventX, WaitFrameEventX, GetFrameStatisticsX. A per-device +// token state machine answers them before the PC vtable is indexed (or the presenter attached with +// set_presentation_handler); WaitFrameEventX returns at once with a fresh non-zero token from the +// device's FrameTokenSource, and GetFrameStatisticsX reports no statistics yet (S_FALSE, count 0). +// Slots 80/81 are outside a PC ID3D12Device11 table, so they are checked before the beyond-table +// refusal. // slot 86 CreatePipelineState(desc, riid, out) -> PC ID3D12Device2::CreatePipelineState (PC slot 47). // slot 101 CreateStateObject(desc, riid, out) -> PC ID3D12Device5::CreateStateObject (PC slot 62, displaced on // Xbox by compute-PSO slot 62). @@ -43,10 +62,8 @@ // flag bits normalized on the copy. // The slots 48/73/78/79/80 are the public HLE Freminet/ScarlettX's observation, not Microsoft documentation, and can // be moved with LEONIDA_XS_QUEUE_X_SLOT, LEONIDA_XS_LIST_X_SLOT, LEONIDA_XS_FRAME_INTERVAL_SLOT, -// LEONIDA_XS_SCHEDULE_EVENT_SLOT and LEONIDA_XS_WAIT_EVENT_SLOT (3..127; anything else is logged once and ignored). -// slot 26 GetCustomHeapProperties, called by the retail title with the C ABI: return buffer in RCX, the device -// in RDX (the PC form is `this` in RCX, return buffer in RDX). Slot 25 (GetResourceAllocationInfo, also a -// struct wider than 8 bytes) takes the same form by the same rule. Both accept either form. +// LEONIDA_XS_SCHEDULE_EVENT_SLOT, LEONIDA_XS_WAIT_EVENT_SLOT and LEONIDA_XS_FRAME_STATISTICS_SLOT (3..127; anything +// else is logged once and ignored). // The measured slots 9/10 (GetCPU/GPUDescriptorHandleForHeapStart) are ID3D12DescriptorHeap methods, not device // methods: the PC device's 9/10 are CreateCommandAllocator/CreateGraphicsPipelineState and are forwarded unchanged. // On the PC heap those getters use the hidden return pointer in RDX; the Xbox ABI returns the 8-byte handle in @@ -64,16 +81,28 @@ // // Command queues and fences (device slots 8, 75, 36, and 32 for a shared fence) come back wrapped in queue and fence // proxies of the same kind: the public chain (19 queue slots, 11 or 12 fence slots in SDK 10.0.26100) is forwarded -// in PC order. Queue slot 35 is the console ExecuteCommandLists(count, lists) variant and forwards to PC slot 10; -// every other slot past the public chain, up to the end of the proxy's table (128 queue, 64 fence slots), is logged -// with its first four argument words and refused with E_NOTIMPL. A slot past the table faults on the vtable read inside a -// reserved, never-committed region, and the fault is logged with the slot. PresentX, SuspendX and ResumeX slots past -// the public chain remain refused until measured and implemented, and that the console keeps the public slots is an -// assumption (docs/d3d12_command_objects.md §5.2). Heap, queue and fence proxies are +// in PC order, and a slot past it, up to the end of the proxy's table (128 queue, 64 fence slots), is logged with its +// first four argument words and answered S_OK on a queue or refused with E_NOTIMPL on a fence or allocator. Fence +// slot 12 is served instead: the retail executable reads its return as the address of the fence's 64-bit completed +// value, so it returns a per-fence mirror that a wait on the real fence keeps current (d3d12_xs_device.cpp, "Fence +// slot 12"). Queue slot 35 is the console ExecuteCommandLists(count, lists) variant and is served like PC slot 10, list +// proxies unwrapped. A slot past the table faults on the vtable read inside a +// reserved, never-committed region, and the fault is logged with the slot. That is where the console's queue methods +// (PresentX, SuspendX, ResumeX) will show up; the sibling-layer measurement puts PresentX at queue slot 30 or 32 +// and SignalX at 23 or 25 by runtime layout (docs/d3d12_xs_console_abi.md §4, unverified here). The proxy detects +// the layout from a fence reaching slot 16/17, forwards SignalX as PC Signal, routes PresentX to the presentation +// core under LEONIDA_VULKAN_DEVICE (a presenter attached with set_presentation_handler answers its routed +// slots first, below) and answers the remaining console-only queue methods S_OK (frame pacing flows +// through them) without forwarding, and that +// the console keeps the public slots is an assumption (docs/d3d12_command_objects.md §5.2). Heap, queue and fence proxies are // unwrapped wherever a device or queue method hands them to the real runtime: queue Signal/Wait (14/15), device // CreateSharedHandle (31), MakeResident/Evict (34/35), SetEventOnMultipleFenceCompletion (45), SetResidencyPriority -// (46) and EnqueueMakeResident (50). Command lists are not wrapped, so ExecuteCommandLists passes them through and a -// heap proxy given to a list's SetDescriptorHeaps reaches the real list as it is. QueryInterface answers only the +// (46) and EnqueueMakeResident (50). Command lists come back from device slot 12 behind a console-shaped list +// proxy: console vtable order (PC order through slot 26, four console-only extras at 27-30, the PC chain shifted +// +4 through console 59, measured tail slots at 60/61/146), the write cursor pinned at the record limits so a +// title's inline writers always take the vtable path, unmodelled slots recorded and refused. Queue +// ExecuteCommandLists unwraps the list array; the list's own Reset, ExecuteBundle and SetDescriptorHeaps unwrap +// allocator, list and heap proxies. QueryInterface answers only the // modelled interfaces; one the real object has but the proxy does not model is logged once and refused. #pragma once @@ -81,13 +110,24 @@ #include #include +#include +#include +#include + +namespace leonida { +class FrameTokenSource; +} namespace rt::d3d12_xs { // Wraps `real` and returns the requested device interface through `out`. Takes ownership of one reference to // `real` on success; on failure the caller keeps its reference. Returns E_NOINTERFACE if `riid` is not a D3D12 // device interface the PC device implements. -HRESULT create_device_proxy(ID3D12Device* real, REFIID riid, void** out); +// `console_lists` shapes the command lists CreateCommandList returns: true (the title path) gives the +// console-shaped object the Xbox ABI calls; false hands the real list back for callers compiled against +// the PC headers (the GPU test harnesses), whose vtable indices past slot 26 do not exist in console order. +// D3D12XboxCreateDevice opts in; the default is PC-shaped so direct callers keep the old behaviour. +HRESULT create_device_proxy(ID3D12Device* real, REFIID riid, void** out, bool console_lists = false); // True when `device` points at a proxy created by create_device_proxy. Used by the tests. bool is_device_proxy(const void* device); @@ -146,10 +186,14 @@ unsigned device_proxy_slot_count(const void* device); // The PC device behind a proxy. Null when `device` is not a proxy. ID3D12Device* device_proxy_real_device(const void* device); +// The real object behind any of the child proxies (heap, queue, fence, allocator, and a kind added later, such as a +// console command-list proxy, which joins proxy_real_object), or null when `object` is none of them. For code outside +// this file that is handed a title's object, like the XboxBvhBuilder shim's command lists. +IUnknown* real_object_behind_proxy(const void* object); // Device slot 133 (the console's CreatePlacedResourceX) makes a buffer on the title's pages at `va`. The proxy does // not create it itself: the device behind it does, through this handler, which the Vulkan layer registers -// (rt::d3d12::create_buffer_at_host_address). With none registered, or a PC device behind the proxy, the slot -// answers E_NOTIMPL. +// (rt::d3d12::create_buffer_at_host_address). With none registered, a PC device behind the proxy, or a handler +// that fails (a texture, a range the import refuses), the slot creates the committed stand-in described at the top. // `layout` is the title's third argument, a D3D12_BARRIER_LAYOUT (0xFFFFFFFF = UNDEFINED), measured on a retail // boot: 0x6 SHADER_RESOURCE, 0x3 UNORDERED_ACCESS, as PC CreatePlacedResource2 takes it. using PlacedAtVaHandler = HRESULT (*)(ID3D12Device* real, void* va, const D3D12_RESOURCE_DESC& desc, @@ -191,13 +235,16 @@ struct PresentationHandler { }; bool set_presentation_handler(void* device, const PresentationHandler* handler); +// The device proxy's frame-token source (PresentX paces with the token source the device hands out), or null for +// an object that is not a device proxy. +std::shared_ptr device_frame_tokens(const void* device); + // True for slots the proxy handles itself rather than forwarding verbatim: IUnknown (0-2), 8 and 75 (queue // proxies), 9 (allocator proxies), 14 (descriptor heap proxy), 17-24 (CPU descriptor handle translation), 26 (the -// console's struct-return form), -// 31/34/35/45/46/50 (proxies unwrapped), 32 and 36 (fence proxies), 48/73 and -// 78/79/80 (the Xbox slots above, at their configured indices), 62, 67, 70, 74, 76, 86, 101, 108 and 127. Slot 10 is intentionally false: the -// measured 9/10 handle conversion is on the heap proxy, and device slot 9 is CreateCommandAllocator, which the proxy -// handles for the allocator proxy. +// console's struct-return form), 31/34/35/45/46/50 (proxies unwrapped), +// 32 and 36 (fence proxies), 48/73 and 78/79/80/81 (the Xbox slots above, at their configured indices), 55, 62, 67, 70, +// 74, 76, 86, 101, 108 and 127. Slot 10 is intentionally false: the measured 9/10 handle conversion is on the heap +// proxy, and device slot 9 is CreateCommandAllocator, which the proxy handles for the allocator proxy. bool device_slot_overridden(unsigned slot); // Whether a return address is in an image the guest loader mapped, i.e. the call comes from the title. Device slot 61 @@ -234,10 +281,11 @@ std::uint64_t fence_table_overruns(); // or the fault logger failed). bool command_object_tables_guarded(); -// Command allocator proxies (device slot 9): the public chain (9 slots: the base chain and Reset) is forwarded, a -// slot past it up to the end of the table (64 slots) is logged and refused with E_NOTIMPL, and a read past the -// table faults in a guard region, as for queues and fences. The console allocator's extra methods are not -// measured and not guessed. Slot 9 wraps only an allocator that answers kLeonidaCommandAllocatorTag, Leonida's +// Command allocator proxies (device slot 9): the public chain (9 slots: the base chain and Reset) is forwarded, +// slot 9 (console SetAllocatorCallbackX(callback, context, ...)) records the callback and context on the proxy and +// returns S_OK without invoking the callback on the PC/Vulkan path, slots 10..63 are logged and refused with +// E_NOTIMPL, and a read past the table faults in a guard region, as for queues and fences. Slot 9 wraps only an +// allocator that answers kLeonidaCommandAllocatorTag, Leonida's // own Vulkan-layer allocator: its command lists resolve the proxy (CreateCommandList, Reset). A PC runtime // allocator goes back unchanged, because the PC runtime's lists would take a proxy for their own allocator; a // command-list proxy that unwraps at Reset is what lets the host backend wrap allocators too. @@ -245,10 +293,27 @@ bool command_object_tables_guarded(); inline constexpr GUID kLeonidaCommandAllocatorTag{ 0x7d0e6b51, 0x34a2, 0x4f0c, {0x9a, 0x61, 0x0c, 0x5b, 0x2e, 0x8f, 0x4a, 0x10}}; bool is_allocator_proxy(const void* allocator); +// Command-list proxies (device slot 12): the console-shaped object. is_list_proxy / list_proxy_real_list give the +// same access as the queue, fence and allocator helpers; list_slot_hits counts calls per console slot. +bool is_list_proxy(const void* list); +ID3D12CommandList* list_proxy_real_list(const void* list); +std::uint64_t list_slot_hits(unsigned slot); +// The diagnostic name of a command-list slot on the list tail, where the newer console layout sits two slots later +// than the older one from CopyTextureRegionX on (docs/d3d12_xs_console_abi.md 5.3: newer->older pairs 85->83, +// 86->84, 87->85, 90->88, 91->89, 92->90, 95->93, 96->94). `console_layout` is the device-wide layout the queue +// proxy detects (kConsoleLayoutOlder or kConsoleLayoutNewer). Null when the layout is not known yet or the slot is +// not a measured tail slot of that layout, so that a slot number is never given the other layout's name. Naming +// only: no slot is forwarded because of it. +inline constexpr unsigned char kConsoleLayoutOlder = 1; +inline constexpr unsigned char kConsoleLayoutNewer = 2; +const char* list_tail_slot_name(unsigned slot, unsigned char console_layout); // The wrapped allocator (no reference added), or null when `allocator` is not an allocator proxy. ID3D12CommandAllocator* allocator_proxy_real_allocator(const void* allocator); unsigned allocator_proxy_slot_count(const void* allocator); unsigned allocator_proxy_table_size(); +// Callback and context recorded by console allocator slot 9 (SetAllocatorCallbackX), or 0 if unset / not a proxy. +std::uintptr_t allocator_proxy_callback(const void* allocator); +std::uintptr_t allocator_proxy_callback_context(const void* allocator); std::uint64_t allocator_slot_hits(unsigned slot); bool allocator_slot_first_call_seen(unsigned slot); std::uint64_t allocator_table_overruns(); @@ -270,8 +335,11 @@ inline constexpr unsigned console_to_pc_list_slot(unsigned slot) { if (slot <= 59) return slot - 4; // PC chain, shifted +4 if (slot == 60) return 58; // EndEvent (no console SetMarker/BeginEvent) if (slot == 61) return 59; // ExecuteIndirect (Package) - if (slot == 85) return 16; // CopyTextureRegionX -> CopyTextureRegion + // CopyTextureRegionX -> CopyTextureRegion. In the newer console layout; in the older one the tail sits two slots + // earlier (list_tail_slot_name), and 85 is another method. The retail title has not been seen calling 85. + if (slot == 85) return 16; if (slot == 146) return 80; // D3D12_BARRIER_GROUP (Package; PC GCL7) + if (slot == 139) return 10; // Reset(allocator, pso): measured on the retail title (Pipodi) return kListNotForwarded; } @@ -291,4 +359,23 @@ std::uint64_t heap_slot_hits(unsigned slot); bool heap_slot_first_call_seen(unsigned slot); void reset_device_proxy_stats(); +// Decoded input element from an Xbox slot-57 pipeline blob (188 B in the first 3 boot graphics PSOs). +struct XboxPipelineInputElement { + std::string semantic_name; + UINT semantic_index = 0; + DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN; + UINT input_slot = 0; + UINT aligned_byte_offset = 0; +}; + +// Defensively parses the input-layout elements from an Xbox slot-57 pipeline blob (+0x4c element count, +0x54 array +// of NUL-terminated ASCII semantic name + 7 u32s). Stops cleanly before reading out of bounds when the last 1..4 B +// of the trailing 28-byte block are truncated at `blob_size`. Returns true when the header is valid. +bool parse_xbox_pipeline_blob_input_layout(const void* blob, std::size_t blob_size, + std::vector& out_elements); + +// Looks up the stage ("vs", "ps", "ms", "gs") of a bare RDNA2 program by its SHA-256 (`fspx_code_sha256`) in the +// configured shader library (`LEONIDA_SHADERS`, including `fspx_gfx/index.json`). Returns an empty string on miss. +std::string lookup_xbox_fspx_program_stage(const void* program_bytes, std::size_t program_size); + } // namespace rt::d3d12_xs diff --git a/runtime/shims/d3d12_xs_pso_stream.cpp b/runtime/shims/d3d12_xs_pso_stream.cpp new file mode 100644 index 0000000000..1b59bf3eaf --- /dev/null +++ b/runtime/shims/d3d12_xs_pso_stream.cpp @@ -0,0 +1,381 @@ +#include "d3d12_xs_pso_stream.h" +#include "d3d12_trace.h" + +#include "../src/shader_library.h" + +#include +#include +#include + +namespace rt::d3d12_xs { +namespace { + +// Tag 5 and the DEPTH_STENCIL offsets of its two stencil mask bytes (StencilReadMask, StencilWriteMask). +constexpr std::uint32_t kStencilMaskTag = 5; +constexpr std::size_t kStencilReadMaskOffset = 0x10; +constexpr std::size_t kStencilWriteMaskOffset = 0x11; + +// Streams beyond this are refused: a title's PSO stream is a few kilobytes. +constexpr std::size_t kMaxStreamBytes = 64 * 1024; + +// Private-data GUIDs (random, fixed for this shim). The record pointer is found by GetPrivateData; the owner is an +// IUnknown the object releases when it is destroyed, which frees the record with it. +constexpr GUID kRecordPointerGuid{0x3c1f9a2e, 0x5b7d, 0x4e08, {0x8f, 0x12, 0x6a, 0x4d, 0x9c, 0x2b, 0x71, 0xe3}}; +constexpr GUID kRecordOwnerGuid{0x9e4b2d17, 0x0a6c, 0x4f35, {0xb1, 0x8d, 0x23, 0x7e, 0x5f, 0xc9, 0x40, 0x6a}}; + +struct Layout { + std::size_t size; + std::size_t align; +}; + +// Size and alignment of each subobject payload this module walks (the SDK's D3D12_PIPELINE_STATE_SUBOBJECT_TYPE). +// VIEW_INSTANCING and unknown types are not modelled: a stream with one is not captured. +bool layout_of(unsigned type, Layout& out) { + switch (type) { + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE: out = {8, 8}; return true; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DS: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_HS: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS: + out = {sizeof(D3D12_SHADER_BYTECODE), 8}; + return true; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_STREAM_OUTPUT: out = {sizeof(D3D12_STREAM_OUTPUT_DESC), 8}; return true; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND: out = {sizeof(D3D12_BLEND_DESC), 4}; return true; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK: out = {4, 4}; return true; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER: out = {sizeof(D3D12_RASTERIZER_DESC), 4}; return true; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL: out = {sizeof(D3D12_DEPTH_STENCIL_DESC), 4}; return true; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT: out = {sizeof(D3D12_INPUT_LAYOUT_DESC), 8}; return true; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_NODE_MASK: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS: + out = {4, 4}; + return true; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS: + out = {sizeof(D3D12_RT_FORMAT_ARRAY), 4}; + return true; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC: out = {sizeof(DXGI_SAMPLE_DESC), 4}; return true; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO: out = {sizeof(D3D12_CACHED_PIPELINE_STATE), 8}; return true; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1: out = {sizeof(D3D12_DEPTH_STENCIL_DESC1), 4}; return true; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL2: out = {sizeof(D3D12_DEPTH_STENCIL_DESC2), 4}; return true; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER1: out = {sizeof(D3D12_RASTERIZER_DESC1), 4}; return true; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER2: out = {sizeof(D3D12_RASTERIZER_DESC2), 4}; return true; + default: return false; + } +} + +std::size_t align_up(std::size_t value, std::size_t align) { return (value + align - 1) / align * align; } + +struct Subobject { + unsigned type; + std::size_t tag_offset; + std::size_t payload; // offset of the payload in the stream + std::size_t size; +}; + +// Walks a stream laid out as the console does: u32 type, payload at its natural alignment, next entry 8-aligned +// (the measured console offsets: BLEND payload +0x8c, DEPTH_STENCIL1 entry at +0x210). False when a type is unknown +// or the entries do not end exactly at `size`. +bool walk(const unsigned char* stream, std::size_t size, std::vector& out, bool console = false) { + out.clear(); + std::size_t off = 0; + while (off < size) { + if (size - off < 4) return false; + unsigned type; + std::memcpy(&type, stream + off, 4); + type = pc_stream_type(type, console); + Layout layout{}; + if (!layout_of(type, layout)) return false; + const std::size_t payload = align_up(off + 4, layout.align); + if (payload > size || layout.size > size - payload) return false; + out.push_back({type, off, payload, layout.size}); + off = align_up(payload + layout.size, 8); + } + return off == size; +} + +// Copies `count` bytes into a new owned blob and returns its address (stable: the blob's buffer does not move). +const unsigned char* own_blob(std::vector>& blobs, const void* bytes, std::size_t count) { + const auto* src = static_cast(bytes); + blobs.emplace_back(src, src + count); + return blobs.back().data(); +} + +// Holds a PsoStreamRecord as an IUnknown: the object keeps one reference, the creation code drops its own. +class RecordOwner final : public IUnknown { +public: + explicit RecordOwner(std::unique_ptr record) : record_(std::move(record)) {} + + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override { + if (!out) return E_POINTER; + if (riid == __uuidof(IUnknown)) { + *out = static_cast(this); + AddRef(); + return S_OK; + } + *out = nullptr; + return E_NOINTERFACE; + } + ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; } + ULONG STDMETHODCALLTYPE Release() override { + const ULONG left = --refs_; + if (left == 0) delete this; + return left; + } + PsoStreamRecord* record() { return record_.get(); } + +private: + ~RecordOwner() = default; + std::atomic refs_{1}; + std::unique_ptr record_; +}; + +// A record's target: the subobject it patches, a fallback subobject type (0 for none), and the payload bytes it carries. +struct Target { + unsigned primary_type; + unsigned fallback_type; + std::size_t bytes; +}; + +bool target_of_tag(std::uint32_t tag, Target& out) { + switch (tag) { + case 0: // D3D12_DEPTH_STENCIL_DESC: DEPTH_STENCIL, or the prefix of DEPTH_STENCIL1 + out = {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1, + sizeof(D3D12_DEPTH_STENCIL_DESC)}; + return true; + case 1: // D3D12_RASTERIZER_DESC + out = {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, 0, sizeof(D3D12_RASTERIZER_DESC)}; + return true; + case 2: // D3D12_BLEND_DESC + out = {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, 0, sizeof(D3D12_BLEND_DESC)}; + return true; + case 3: // sample mask (UINT) + out = {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, 0, sizeof(UINT)}; + return true; + default: return false; + } +} + +const Subobject* find_subobject(const std::vector& subs, const Target& target); + +// Tag 5: the two stencil mask bytes of the record overwrite the base's DEPTH_STENCIL (or DEPTH_STENCIL1) masks; the +// rest of the record's zeros are not applied. False when the base has no depth-stencil subobject. +bool overlay_stencil_masks(const std::vector& subs, const unsigned char* record, + std::vector& out) { + const Target depth{D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1, 0}; + const Subobject* sub = find_subobject(subs, depth); + if (!sub) return false; + for (std::size_t field : {kStencilReadMaskOffset, kStencilWriteMaskOffset}) + out[sub->payload + field] = record[kDerivedRecordPayload + field]; + return true; +} + +const Subobject* find_subobject(const std::vector& subs, const Target& target) { + for (const Subobject& sub : subs) + if (sub.type == target.primary_type) return ⊂ + if (target.fallback_type) + for (const Subobject& sub : subs) + if (sub.type == target.fallback_type) return ⊂ + return nullptr; +} + +D3D12_SHADER_BYTECODE bytecode(const unsigned char* src, const Subobject& sub) { + D3D12_SHADER_BYTECODE code{}; + std::memcpy(&code, src + sub.payload, sizeof(code)); + return code; +} + +int dxil_kind(std::span code) { + const auto dxil = leonida::dxbc_part(code, "DXIL"); + return dxil.size() >= 4 ? dxil[2] | (dxil[3] << 8) : -1; +} + +} // namespace + +void audit_pso_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, HRESULT hr, bool normalized) { + const auto* src = static_cast(desc.pPipelineStateSubobjectStream); + std::vector subs; + if (!src || !desc.SizeInBytes || desc.SizeInBytes > kMaxStreamBytes || + !walk(src, desc.SizeInBytes, subs, normalized)) { + std::fprintf(stderr, "[rt] pso-stream call=%llu normalized=%d hr=%08lx types=unwalked reason=%s\n", + d3d12_trace::last_sequence, int(normalized), static_cast(hr), + d3d12_trace::stream_refusal ? d3d12_trace::stream_refusal : "-"); + return; + } + bool depth_bounds = false; + std::string types, shaders; + for (const auto& sub : subs) { + unsigned raw; + std::memcpy(&raw, src + sub.tag_offset, sizeof(raw)); + if (!types.empty()) types += ','; + types += std::to_string(raw); + if (sub.type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1 || + sub.type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL2) { + BOOL enabled; + const auto offset = sub.type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1 + ? offsetof(D3D12_DEPTH_STENCIL_DESC1, DepthBoundsTestEnable) + : offsetof(D3D12_DEPTH_STENCIL_DESC2, DepthBoundsTestEnable); + std::memcpy(&enabled, src + sub.payload + offset, sizeof(enabled)); + depth_bounds |= enabled != FALSE; + } + if (!(sub.type >= 1 && sub.type <= 6) && sub.type != D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS && + sub.type != D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS) continue; + const auto code = bytecode(src, sub); + if (!code.pShaderBytecode || !code.BytecodeLength) continue; + const std::span bytes{static_cast(code.pShaderBytecode), code.BytecodeLength}; + const auto program = leonida::compute_program(bytes); + shaders += " " + std::to_string(raw) + "/" + std::to_string(dxil_kind(bytes)) + "=" + + (program.bytes.empty() ? "unknown" : leonida::sha256_hex(program.bytes)); + if (FAILED(hr) && hr != E_NOTIMPL) + shaders += " container=" + leonida::sha256_hex(bytes) + " bytes=" + std::to_string(bytes.size()); + } + std::fprintf(stderr, "[rt] pso-stream call=%llu normalized=%d hr=%08lx bounds=%d types=%s%s reason=%s\n", + d3d12_trace::last_sequence, int(normalized), static_cast(hr), int(depth_bounds), + types.c_str(), shaders.c_str(), d3d12_trace::stream_refusal ? d3d12_trace::stream_refusal : "-"); +} + +PsoStreamRecord::~PsoStreamRecord() { + for (ID3D12RootSignature* root : roots_) + if (root) root->Release(); +} + +std::unique_ptr PsoStreamRecord::capture(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, bool console) { + if (!desc.pPipelineStateSubobjectStream || desc.SizeInBytes == 0 || desc.SizeInBytes > kMaxStreamBytes) + return nullptr; + const auto* source = static_cast(desc.pPipelineStateSubobjectStream); + std::vector subs; + if (!walk(source, desc.SizeInBytes, subs, console)) return nullptr; + + std::unique_ptr record(new PsoStreamRecord()); + record->bytes_.assign(source, source + desc.SizeInBytes); + for (const Subobject& sub : subs) { + if (console) std::memcpy(record->bytes_.data() + sub.tag_offset, &sub.type, sizeof(sub.type)); + if (!record->copy_pointed_data(sub.type, sub.payload)) return nullptr; + } + return record; +} + +// Replaces the pointers in one subobject's payload with copies of what they point to. +bool PsoStreamRecord::copy_pointed_data(std::size_t type, std::size_t payload_offset) { + unsigned char* payload = bytes_.data() + payload_offset; + switch (type) { + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE: { + ID3D12RootSignature* root = nullptr; + std::memcpy(&root, payload, sizeof(root)); + if (root) { + root->AddRef(); + roots_.push_back(root); + } + return true; + } + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DS: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_HS: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS: { + D3D12_SHADER_BYTECODE code{}; + std::memcpy(&code, payload, sizeof(code)); + if (code.pShaderBytecode && code.BytecodeLength) { + code.pShaderBytecode = own_blob(blobs_, code.pShaderBytecode, code.BytecodeLength); + std::memcpy(payload, &code, sizeof(code)); + } + return true; + } + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_STREAM_OUTPUT: { + D3D12_STREAM_OUTPUT_DESC so{}; + std::memcpy(&so, payload, sizeof(so)); + if (so.pSODeclaration && so.NumEntries) + so.pSODeclaration = reinterpret_cast( + own_blob(blobs_, so.pSODeclaration, so.NumEntries * sizeof(D3D12_SO_DECLARATION_ENTRY))); + if (so.pBufferStrides && so.NumStrides) + so.pBufferStrides = reinterpret_cast( + own_blob(blobs_, so.pBufferStrides, so.NumStrides * sizeof(UINT))); + std::memcpy(payload, &so, sizeof(so)); + return true; + } + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT: { + D3D12_INPUT_LAYOUT_DESC layout{}; + std::memcpy(&layout, payload, sizeof(layout)); + if (!layout.pInputElementDescs || !layout.NumElements) return true; + const std::size_t bytes = layout.NumElements * sizeof(D3D12_INPUT_ELEMENT_DESC); + auto* elements = reinterpret_cast( + const_cast(own_blob(blobs_, layout.pInputElementDescs, bytes))); + for (UINT i = 0; i < layout.NumElements; ++i) { + if (!elements[i].SemanticName) continue; + const std::size_t len = std::strlen(elements[i].SemanticName) + 1; + elements[i].SemanticName = + reinterpret_cast(own_blob(blobs_, elements[i].SemanticName, len)); + } + layout.pInputElementDescs = elements; + std::memcpy(payload, &layout, sizeof(layout)); + return true; + } + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO: { + D3D12_CACHED_PIPELINE_STATE cached{}; + std::memcpy(&cached, payload, sizeof(cached)); + if (cached.pCachedBlob && cached.CachedBlobSizeInBytes) { + cached.pCachedBlob = own_blob(blobs_, cached.pCachedBlob, cached.CachedBlobSizeInBytes); + std::memcpy(payload, &cached, sizeof(cached)); + } + return true; + } + default: return true; // no pointers in this payload + } +} + +DeriveStatus derive_stream(const PsoStreamRecord& base, const unsigned char* records, unsigned count, + std::vector& out) { + if (!records || count == 0 || count > kDerivedMaxRecords) return DeriveStatus::malformed; + out = base.bytes(); + std::vector subs; + if (!walk(out.data(), out.size(), subs)) return DeriveStatus::malformed; + + for (unsigned i = 0; i < count; ++i) { + const unsigned char* record = records + i * kDerivedRecordSize; + std::uint32_t tag; + std::memcpy(&tag, record, sizeof(tag)); + if (tag == kStencilMaskTag) { + if (!overlay_stencil_masks(subs, record, out)) return DeriveStatus::missing_state; + continue; + } + Target target{}; + if (!target_of_tag(tag, target)) return DeriveStatus::unknown_tag; + const Subobject* sub = find_subobject(subs, target); + if (!sub) return DeriveStatus::missing_state; + std::memcpy(out.data() + sub->payload, record + kDerivedRecordPayload, target.bytes); + } + return DeriveStatus::ok; +} + +bool attach_pso_record(ID3D12Object* object, std::unique_ptr record) { + if (!object || !record) return false; + RecordOwner* owner = new RecordOwner(std::move(record)); // one reference: ours + if (FAILED(object->SetPrivateDataInterface(kRecordOwnerGuid, owner))) { + owner->Release(); + return false; + } + // The object holds its own reference now; drop ours. The pointer below is for lookups only. + owner->Release(); + RecordOwner* pointer = owner; + return SUCCEEDED(object->SetPrivateData(kRecordPointerGuid, sizeof(pointer), &pointer)); +} + +const PsoStreamRecord* find_pso_record(ID3D12Object* object) { + if (!object) return nullptr; + UINT size = sizeof(RecordOwner*); + RecordOwner* owner = nullptr; + if (FAILED(object->GetPrivateData(kRecordPointerGuid, &size, &owner)) || size != sizeof(RecordOwner*) || !owner) + return nullptr; + return owner->record(); +} + +} // namespace rt::d3d12_xs diff --git a/runtime/shims/d3d12_xs_pso_stream.h b/runtime/shims/d3d12_xs_pso_stream.h new file mode 100644 index 0000000000..7f0ca31b73 --- /dev/null +++ b/runtime/shims/d3d12_xs_pso_stream.h @@ -0,0 +1,82 @@ +// Xbox derived pipeline states (device slot 55) over PC pipeline state streams. +// +// Slot 86 creates a PSO from a D3D12_PIPELINE_STATE_STREAM_DESC. The proxy keeps a deep copy of that stream on the +// PSO it returns (ID3D12Object private data, so the copy is freed with the PSO). Slot 55 takes a base PSO and up to +// three state records; it patches a copy of the base stream and creates the new PSO through the same path. +// +// Record layout (TomBox's create_derived_pso_x, GPL-3.0): 0x14c bytes, a u32 tag, then the state payload at +4. +// tag 0: D3D12_DEPTH_STENCIL_DESC (0x34) -> the DEPTH_STENCIL or DEPTH_STENCIL1 subobject (first 0x34 bytes) +// tag 1: D3D12_RASTERIZER_DESC (0x2c) +// tag 2: D3D12_BLEND_DESC (0x148) +// tag 3: sample mask (u32) +// tag 5: the StencilReadMask and StencilWriteMask bytes (payload +0x10, +0x11) overwrite those two bytes of the base's +// DEPTH_STENCIL / DEPTH_STENCIL1; the title writes no other byte of it (read from the retail build's record writes) +// Any other tag is refused: its meaning is not known. +#pragma once + +#include + +#include +#include +#include +#include + +namespace rt::d3d12_xs { + +// The Vulkan parser selects the layout. Slot 55 keeps its canonical tags for subsequent derivation. +inline thread_local bool used_console_stream = false; +constexpr unsigned pc_stream_type(unsigned raw, bool console) { + return console && raw >= 23 && raw < 63 ? raw + 1 : raw; +} + +void audit_pso_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, HRESULT hr, bool console); + +inline constexpr std::size_t kDerivedRecordSize = 0x14c; +inline constexpr std::size_t kDerivedRecordPayload = 4; +// The console passes the count of records it built: raster, depth-stencil, the tag-5 record and blend can all be +// present, so the count reaches 4 (measured from the title's record writes, see the notes in docs/d3d12_vulkan.md). +inline constexpr unsigned kDerivedMaxRecords = 4; + +// An owned deep copy of one pipeline state stream. The root signature references are held until destruction; shader +// bytecode, stream-output and input-layout arrays and strings, and cached blobs are copied, and their pointers in the +// copy point at the copies. +class PsoStreamRecord { +public: + // Null when the stream is malformed, holds a subobject type this module does not walk, or is too large. + static std::unique_ptr capture(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, bool console = false); + ~PsoStreamRecord(); + PsoStreamRecord(const PsoStreamRecord&) = delete; + PsoStreamRecord& operator=(const PsoStreamRecord&) = delete; + + // The stream bytes. Its pointers refer to this record's copies, so the record must outlive any use of the desc. + const std::vector& bytes() const { return bytes_; } + // The PC runtime reads the stream and never writes it; the const_cast only meets the desc's void* member. + D3D12_PIPELINE_STATE_STREAM_DESC desc() const { + D3D12_PIPELINE_STATE_STREAM_DESC d{}; + d.SizeInBytes = bytes_.size(); + d.pPipelineStateSubobjectStream = const_cast(bytes_.data()); + return d; + } + +private: + PsoStreamRecord() = default; + bool copy_pointed_data(std::size_t type, std::size_t payload_offset); + + std::vector bytes_; + std::vector> blobs_; // owned copies; their buffers do not move when this grows + std::vector roots_; // AddRef'd +}; + +enum class DeriveStatus { ok, unknown_tag, missing_state, malformed }; + +// Writes the base stream with `count` records applied (count 1..kDerivedMaxRecords; `records` holds count records). +// The result's pointers still refer to the base record's copies. +DeriveStatus derive_stream(const PsoStreamRecord& base, const unsigned char* records, unsigned count, + std::vector& out); + +// Keeps `record` on `object` (lifetime follows the object) and finds it again. attach returns false on failure, and +// then the record is dropped. find returns null when no record was attached to that object. +bool attach_pso_record(ID3D12Object* object, std::unique_ptr record); +const PsoStreamRecord* find_pso_record(ID3D12Object* object); + +} // namespace rt::d3d12_xs diff --git a/runtime/shims/dstorage.cpp b/runtime/shims/dstorage.cpp index 0f83456894..7f4cef9d94 100644 --- a/runtime/shims/dstorage.cpp +++ b/runtime/shims/dstorage.cpp @@ -5,20 +5,19 @@ // for those names, the console ABI and what each method does here. In short: // - OpenFile resolves kernel32.dll!CreateFileW through the shim registry, so a GAME: path goes through the // runtime's console path mapping and write overlay (file_system.cpp) exactly as the title's own CreateFileW. -// - Each queue has one worker thread that runs its submitted entries in order: a request reads a file range or +// - Each queue publishes its submitted entries in order: a request reads a file range or // copies a memory range into the destination, a status entry, fence signal or event runs when every entry before // it has. Completion is therefore in queue order, as the API guarantees. -// - A zlib request (ZlibDecompress alone) reads its source into a staging buffer, inflates it on the worker with -// the runtime's RFC 1950 inflater (leonida::zlib_inflate, src/shader_library.h) and copies the result to the -// destination only when it is exactly DestinationSize bytes; a stream that fails leaves the destination as it was. -// - BCPack, swizzle and physical-page requests fail with E_NOTIMPL for now (later PRs: they become stages between -// the read and the destination write, BCPack after the inflate). +// - Compressed requests stage RFC 1950 inflate, BCPack BC block reconstruction and DirectStorage +// macro-unshuffle before publishing the destination. Physical page numbers resolve in xmem at execution. // Nothing here goes online or touches the GPU. #include #include #include #include +#include +#include #include #include #include @@ -33,7 +32,15 @@ #include #include "../src/shader_library.h" // leonida::zlib_inflate +#include "../src/title_page_watch.h" // title_gpu_views, title_texel_writes, kernel_writes +#include "../src/bcpack.h" +#include "../src/shader_directory.h" +#include "../src/dstorage_swizzle.h" +#include "../src/dstorage_trace.h" #include "dstorage_xs_abi.h" +#include "dstorage_staging.h" +#include "startup_trace.h" +#include "xmem.h" #include "shims.h" using namespace dsx; @@ -431,8 +438,66 @@ HRESULT read_error(DWORD error) { } } -// Reads exactly "size" bytes at "offset" of a synchronous handle into "destination". -HRESULT read_file_range(HANDLE handle, uint64_t offset, void* destination, uint32_t size) { +bool extended_enabled() { + static const bool enabled = [] { + char value[2]{}; + return GetEnvironmentVariableA("LEONIDA_DSTORAGE_EXTENDED", value, sizeof value) != 1 || value[0] != '0'; + }(); + return enabled; +} + +// Calibrated predictor values stay in a local sidecar. Absent or invalid files retain the built-in codec policy. +const leonida::bcpack::Calibration* bcpack_history() { + static const auto profile = []() -> std::unique_ptr { + std::wstring explicit_path(32768, L'\0'); + const DWORD n = GetEnvironmentVariableW(L"LEONIDA_DSTORAGE_HISTORY", explicit_path.data(), DWORD(explicit_path.size())); + if (n >= explicit_path.size()) return {}; + std::filesystem::path path; + if (n) { + explicit_path.resize(n); + if (explicit_path == L"0") return {}; + path = explicit_path; + } else { + auto shaders = leonida::shader_paths::configured(); + if (shaders.empty()) return {}; + if (!shaders.has_filename()) shaders = shaders.parent_path(); + path = shaders.parent_path() / "bcpack" / "history.bcph"; + } + FILE* raw = nullptr; + if (_wfopen_s(&raw, path.c_str(), L"rb") || !raw) { + log_once("history-open", "could not open the local BCPack predictor profile"); + return {}; + } + std::unique_ptr file(raw, &std::fclose); + auto table = std::make_unique(); + char magic[8]; + if (std::fread(magic, 1, sizeof magic, raw) != sizeof magic || std::memcmp(magic, "BCPHIST1", 8) || + std::fread(table.get(), 1, sizeof *table, raw) != sizeof *table || std::fgetc(raw) != EOF || std::ferror(raw)) { + log_once("history-format", "invalid local BCPack predictor profile"); + return {}; + } + unsigned bc6_ep = 0, bc6_ix = 0, bc7_ep = 0, bc7_ix = 0; + for (const auto& row : table->bc6) { + bc6_ep += row.ep_class != 0; + bc6_ix += row.ix_class != 0; + } + for (const auto& row : table->bc7) { + bc7_ep += unsigned(std::count_if(row.ep_bits.begin(), row.ep_bits.end(), [](auto v) {return v != 0;})); + bc7_ix += unsigned(std::count_if(row.ix_bits.begin(), row.ix_bits.end(), [](auto v) {return v != 0;})); + } + log_once("history-ok", std::string("loaded ") + (n ? "explicit" : "default") + " BCPack profile; BC6H endpoint/index rows " + + std::to_string(bc6_ep) + "/256 " + std::to_string(bc6_ix) + "/256; BC7 endpoint/index fields " + + std::to_string(bc7_ep) + "/6144 " + std::to_string(bc7_ix) + "/8192"); + return table; + }(); + return profile.get(); +} + +// Reads exactly "size" bytes at "offset" of a synchronous handle into "destination". Through kernel_writes, as the +// title's own reads: the destination is title memory, which a kernel write cannot fault in (pages the D3D12 layer +// keeps read-only, xmem pages that wait for their first touch), title_page_watch.h. +enum class ReadTarget { Title, Staging }; +HRESULT read_file_range(HANDLE handle, uint64_t offset, void* destination, uint32_t size, ReadTarget target) { LARGE_INTEGER length{}; if (!GetFileSizeEx(handle, &length)) return HRESULT_FROM_WIN32(GetLastError()); const uint64_t file_size = static_cast(length.QuadPart); @@ -445,7 +510,13 @@ HRESULT read_file_range(HANDLE handle, uint64_t offset, void* destination, uint3 at.Offset = static_cast(position); at.OffsetHigh = static_cast(position >> 32); DWORD got = 0; - if (!ReadFile(handle, out + done, size - done, &got, &at)) { + // A private vector cannot be mapped or write-protected by the title. + const auto read = [&] { + return target == ReadTarget::Title + ? leonida::kernel_writes::read_file(handle, out + done, size - done, &got, &at) + : ::ReadFile(handle, out + done, size - done, &got, &at); + }; + if (!read()) { const DWORD error = GetLastError(); if (error != ERROR_NOACCESS) return read_error(error); // Destination pages not committed yet (see touch_pages): commit them from user mode and read again once. @@ -453,7 +524,7 @@ HRESULT read_file_range(HANDLE handle, uint64_t offset, void* destination, uint3 at = OVERLAPPED{}; at.Offset = static_cast(position); at.OffsetHigh = static_cast(position >> 32); - if (!ReadFile(handle, out + done, size - done, &got, &at)) return read_error(GetLastError()); + if (!read()) return read_error(GetLastError()); } if (got == 0) return E_DSTORAGE_END_OF_FILE; // the file shrank since the size check done += got; @@ -463,7 +534,21 @@ HRESULT read_file_range(HANDLE handle, uint64_t offset, void* destination, uint3 // ---- Queues ------------------------------------------------------------------------------------------------------- +// Only sampled when request tracing is enabled. Times include work done by the file/decode worker. +struct Timing { + using Clock = std::chrono::steady_clock; + long long read{}, inflate{}, bcpack{}, copy{}, unshuffle{}; + static Clock::time_point start() { + return leonida::dstorage::trace_enabled() ? Clock::now() : Clock::time_point{}; + } + static long long elapsed(Clock::time_point begin) { + return leonida::dstorage::trace_enabled() + ? std::chrono::duration_cast(Clock::now() - begin).count() : 0; + } +}; struct Entry { + Timing timing; + const char* reason = "none"; enum class Type { Request, Status, Signal, Event } type = Type::Request; DSTORAGE_REQUEST request{}; File* file = nullptr; // a reference, for a file request naming a live file @@ -494,6 +579,10 @@ class Queue final : public IDStorageQueueX2 { // Separate from the constructor so a failure to start the thread can be reported. bool start() { if (!error_event_) return false; + wchar_t workers[4]{}; + const DWORD n = GetEnvironmentVariableW(L"LEONIDA_DSTORAGE_WORKERS", workers, 4); + if (!(n == 1 && (workers[0] == L'1' || workers[0] == L'0'))) + preparation_work_ = CreateThreadpoolWork(prepare_in_background, this, nullptr); try { worker_ = std::thread([this] { run(); }); } catch (...) { @@ -503,6 +592,7 @@ class Queue final : public IDStorageQueueX2 { } ~Queue() { Close(); + if (preparation_work_) CloseThreadpoolWork(preparation_work_); if (error_event_) CloseHandle(error_event_); std::lock_guard lock(stats().mutex); --priority_stats(stats().s, desc_.Priority).CurrentQueueCount; @@ -679,7 +769,7 @@ class Queue final : public IDStorageQueueX2 { size_t usable() const { return desc_.Capacity - 1u; } size_t half() const { return desc_.Capacity / 2u; } bool auto_submit() const { return !desc_.Options.AutoSubmitDisabled; } - size_t used_locked() const { return entries_.size() + (in_flight_ ? 1 : 0); } + size_t used_locked() const { return entries_.size() + in_flight_; } void enqueue(Entry&& e) { { @@ -726,23 +816,67 @@ class Queue final : public IDStorageQueueX2 { } } + struct Prepared { + Entry& entry; + HRESULT result = S_OK; + std::vector bytes; + }; + // Each queue publishes in order. Only an adjacent pair of file transforms can + // overlap. Memory inputs, direct reads, page resolution and notifications remain barriers. + static bool can_prepare(const Entry& e) { + const auto& r = e.request; + const auto o = r.Options.AsUINT64; + constexpr uint64_t budget = 16ull << 20; + return e.type == Entry::Type::Request && !e.cancelled && SUCCEEDED(e.enqueue_error) && e.file && + (options::zlib(o) || options::bcpack(o) || options::swizzle(o)) && + leonida::dstorage::staging_bytes(r) <= budget; + } + + static void CALLBACK prepare_in_background(PTP_CALLBACK_INSTANCE, void* context, PTP_WORK) { + auto& q = *static_cast(context); + q.set_pending(+1); + auto& job = *q.helper_job_; + job.result = q.validate_request(job.entry); + if (SUCCEEDED(job.result)) job.result = q.prepare(job.entry, job.bytes); + else job.entry.reason = "request-validation"; + } + void run() { for (;;) { - Entry e; + Entry head, next; + leonida::dstorage::StagingPool::Lease reservation(leonida::dstorage::staging_pool()); + Prepared prepared{next, S_OK, {}}; + bool paired = false; { std::unique_lock lock(mutex_); work_.wait(lock, [&] { return submitted_ > 0 || closed_; }); - if (submitted_ == 0) return; // closed and drained - e = std::move(entries_.front()); + if (submitted_ == 0) return; + head = std::move(entries_.front()); entries_.pop_front(); --submitted_; - in_flight_ = true; + paired = preparation_work_ && submitted_ && can_prepare(head) && can_prepare(entries_.front()) && + reservation.try_pair(leonida::dstorage::staging_bytes(head.request) + + leonida::dstorage::staging_bytes(entries_.front().request)); + if (paired) { + next = std::move(entries_.front()); + entries_.pop_front(); + --submitted_; + helper_job_ = &prepared; + SubmitThreadpoolWork(preparation_work_); + } + in_flight_ = paired ? 2 : 1; + } + process(head, nullptr, paired); + release_references(head); + if (paired) { + WaitForThreadpoolWorkCallbacks(preparation_work_, FALSE); + process(next, &prepared); + release_references(next); + helper_job_ = nullptr; } - process(e); - release_references(e); { std::lock_guard lock(mutex_); - in_flight_ = false; + in_flight_ = 0; space_.notify_all(); if (entries_.empty()) idle_.notify_all(); } @@ -751,8 +885,11 @@ class Queue final : public IDStorageQueueX2 { // Runs on the worker. since_notify_ is the first failure since the last status entry or fence signal: the // HRESULT a status entry reports. - void process(Entry& e) { + void process(Entry& e, Prepared* prepared, bool pair_reserved = false) { HRESULT hr = e.enqueue_error; + if (FAILED(hr)) e.reason = "enqueue"; + const auto begin = Timing::start(); + long long notify_us = 0; switch (e.type) { case Entry::Type::Request: // A cancelled request is a success whatever else is wrong with it (the GDK: not counted as a failure). @@ -760,27 +897,85 @@ class Queue final : public IDStorageQueueX2 { hr = S_OK; } else if (SUCCEEDED(hr)) { // Pending: processing has started and not completed (DSTORAGE_PRIORITY_STATS). - set_pending(+1); - hr = execute_request(e); + if (prepared) { + hr = prepared->result; + if (SUCCEEDED(hr)) hr = publish(e, prepared->bytes); + } else { + set_pending(+1); + hr = execute_request(e, pair_reserved); + } set_pending(-1); } + if (FAILED(hr) || leonida::dstorage::trace_enabled()) { + const auto& r = e.request; + const auto o = r.Options.AsUINT64; + const bool pages = (o & options::kDestinationPages) != 0; + std::fprintf(stderr, "[rt] ds-request queue=%p options=%llx zlib=%d bc=%llu sw=%llu " + "dest=%s address=%p file=%ls offset=%llu src=%u mid=%u dst=%u cancelled=%d hr=%08lx " + "tick_ms=%llu page_offset=%u read_us=%lld inflate_us=%lld bc_us=%lld copy_us=%lld sw_us=%lld paired=%d reason=%s priority=%d\n", + static_cast(this), o, int(options::zlib(o)), options::bcpack(o), + options::swizzle(o), pages ? "pages" : "buffer", r.Destination, + e.file ? e.file->path().c_str() : L"-", e.file ? r.FileOffset : 0ull, + r.SourceSize, r.IntermediateSize, r.DestinationSize, int(e.cancelled), + static_cast(hr), GetTickCount64(), + pages ? unsigned(r.DestinationPageOffset) : 0u, e.timing.read, e.timing.inflate, + e.timing.bcpack, e.timing.copy, e.timing.unshuffle, int(prepared != nullptr), e.reason, int(desc_.Priority)); + if (hr == E_DSTORAGE_ACCESS_VIOLATION) { + const void* cpu = pages ? r.DestinationPageArray : cpu_destination(r); + MEMORY_BASIC_INFORMATION info{}; + VirtualQuery(cpu, &info, sizeof(info)); + std::fprintf(stderr, "[rt] ds-access queue=%p dest=%p cpu=%p paired=%llx base=%p " + "region=%zu state=%lx protect=%lx type=%lx\n", static_cast(this), + r.Destination, cpu, static_cast(pages ? 0 : + leonida::title_gpu_views::other_view(reinterpret_cast(cpu))), + info.BaseAddress, info.RegionSize, info.State, info.Protect, info.Type); + } + // Put failures on the same clock as title faults, even if another queue is active. + if (FAILED(hr) && rt::startup_trace::enabled()) { + rt::startup_trace::event("dstorage_failure", + "\"queue\":" + rt::startup_trace::quote(rt::startup_trace::hex(reinterpret_cast(this))) + + ",\"hr\":" + rt::startup_trace::quote(hr_text(hr)) + + ",\"options\":" + rt::startup_trace::quote(rt::startup_trace::hex(o)) + + ",\"offset\":" + std::to_string(e.file ? r.FileOffset : 0ull) + + ",\"source_size\":" + std::to_string(r.SourceSize) + + ",\"destination_size\":" + std::to_string(r.DestinationSize)); + } + } if (e.file && e.file_counted) e.file->finish_pending(); if (FAILED(hr) && SUCCEEDED(since_notify_)) since_notify_ = hr; break; - case Entry::Type::Status: + case Entry::Type::Status: { + const auto result = FAILED(hr) ? hr : since_notify_; if (SUCCEEDED(hr)) { - e.status->complete(e.index, since_notify_); + e.status->complete(e.index, result); since_notify_ = S_OK; } + notify_us = Timing::elapsed(begin); + if (leonida::dstorage::trace_enabled()) + std::fprintf(stderr, "[rt] ds-status queue=%p array=%p slot=%u hr=%08lx\n", + static_cast(this), static_cast(e.status), e.index, + static_cast(result)); break; + } case Entry::Type::Signal: if (SUCCEEDED(hr)) hr = e.fence->Signal(e.value); + notify_us = Timing::elapsed(begin); + if (leonida::dstorage::trace_enabled()) + std::fprintf(stderr, "[rt] ds-signal queue=%p value=%llu hr=%08lx\n", static_cast(this), + e.value, static_cast(hr)); since_notify_ = S_OK; break; case Entry::Type::Event: if (SUCCEEDED(hr) && !SetEvent(e.event)) hr = HRESULT_FROM_WIN32(GetLastError()); + notify_us = Timing::elapsed(begin); + if (leonida::dstorage::trace_enabled()) + std::fprintf(stderr, "[rt] ds-event queue=%p hr=%08lx\n", static_cast(this), + static_cast(hr)); break; } + if (e.type != Entry::Type::Request && leonida::dstorage::trace_enabled()) + std::fprintf(stderr, "[rt] ds-notify queue=%p type=%u us=%lld\n", static_cast(this), + static_cast(e.type), notify_us); if (FAILED(hr)) { DSTORAGE_ERROR_FIRST_FAILURE f{}; f.HResult = hr; @@ -789,38 +984,36 @@ class Queue final : public IDStorageQueueX2 { } } - HRESULT execute_request(const Entry& e) { + HRESULT validate_request(const Entry& e) const { const DSTORAGE_REQUEST& r = e.request; const uint64_t o = r.Options.AsUINT64; if (o & options::kReservedMask) return E_DSTORAGE_RESERVED_FIELDS; if (options::source_type(o) != desc_.SourceType) return E_DSTORAGE_INVALID_SOURCE_TYPE; if (options::bcpack(o) > DSTORAGE_BCPACK_MODE_BC7) return E_DSTORAGE_INVALID_BCPACK_MODE; if (options::swizzle(o) > DSTORAGE_SWIZZLE_MODE_4K_12K_4K_12K) return E_DSTORAGE_INVALID_SWIZZLE_MODE; - if (options::bcpack(o) != 0 || options::swizzle(o) != 0) { - log_once("decompress", "BCPack and swizzle requests are not implemented yet (E_NOTIMPL)"); - return E_NOTIMPL; - } - if (o & (options::kDestinationPages | options::kSourcePages)) { - log_once("pages", "physical-page requests are not implemented yet (E_NOTIMPL)"); + const unsigned bc = unsigned(options::bcpack(o)), sw = unsigned(options::swizzle(o)); + const bool pages = o & (options::kDestinationPages | options::kSourcePages); + if ((bc || sw || pages) && !extended_enabled()) return E_NOTIMPL; + if (bc == DSTORAGE_BCPACK_MODE_BC2) { + log_once("bc2", "BC2 has no known BCPack block decoder (E_NOTIMPL)"); return E_NOTIMPL; } const bool zlib = options::zlib(o); - // IntermediateSize is the BCPack data's size between the inflate and the BCPack decode (DSTORAGE_REQUEST), so - // it is 0 for every request that gets here (BCPack is refused above). - if (r.IntermediateSize != 0) return E_DSTORAGE_INVALID_INTERMEDIATE_SIZE; - // E_DSTORAGE_INVALID_DESTINATION_SIZE: without decompression DestinationSize must equal the source's length, - // with it it must be larger (dstorageerr.h's description; DSTORAGE_REQUEST says the same of DestinationSize). - if (zlib ? r.DestinationSize <= r.SourceSize : r.DestinationSize != r.SourceSize) - return E_DSTORAGE_INVALID_DESTINATION_SIZE; + if ((zlib && bc) != (r.IntermediateSize != 0) || r.IntermediateSize > kMaxRequestBytes) + return E_DSTORAGE_INVALID_INTERMEDIATE_SIZE; + if (zlib || bc) { + if (r.DestinationSize <= r.SourceSize) return E_DSTORAGE_INVALID_DESTINATION_SIZE; + } else if (r.DestinationSize != r.SourceSize) return E_DSTORAGE_INVALID_DESTINATION_SIZE; + if (bc && r.DestinationSize % ((bc == 1 || bc == 4) ? 8 : 16)) return E_DSTORAGE_INVALID_DESTINATION_SIZE; + if (sw && r.DestinationSize % leonida::dstorage::group_size(sw)) return E_DSTORAGE_INVALID_DESTINATION_SIZE; const bool memory = desc_.SourceType == DSTORAGE_REQUEST_SOURCE_MEMORY; + if (!memory && (o & options::kSourcePages)) return E_DSTORAGE_INVALID_SOURCE_TYPE; const uint64_t total = static_cast(r.DestinationSize) + (memory ? r.SourceSize : 0u); - if (total > kMaxRequestBytes) return E_DSTORAGE_REQUEST_TOO_LARGE; - // DSTORAGE_REQUEST: a buffer over 32 MiB is allowed only with 64 KiB or 2 MiB pages, which are not implemented - // yet (refused above). The source is never larger than the destination here (the same size without zlib, - // smaller with it), so this covers both buffers, and bounds the staging buffers of a zlib request too. - if (r.DestinationSize > kMax4kPageDestinationSize) return E_DSTORAGE_REQUEST_TOO_LARGE; - // DSTORAGE_REQUEST: with ZlibDecompress the file offset must be 16-byte aligned. - if (zlib && !memory && r.FileOffset % 16 != 0) return E_DSTORAGE_INVALID_FILE_OFFSET; + if (total > kMaxRequestBytes || + (r.DestinationSize > kMax4kPageDestinationSize && !(o & options::kDestinationPages)) || + (memory && r.SourceSize > kMax4kPageDestinationSize && !(o & options::kSourcePages))) + return E_DSTORAGE_REQUEST_TOO_LARGE; + if ((zlib || bc) && !memory && r.FileOffset % 16 != 0) return E_DSTORAGE_INVALID_FILE_OFFSET; if (!r.Destination) return E_INVALIDARG; if (memory) { if (!r.Source) return E_INVALIDARG; @@ -828,68 +1021,192 @@ class Queue final : public IDStorageQueueX2 { if (!r.File) return E_INVALIDARG; if (!e.file_counted) return E_DSTORAGE_FILE_NOT_OPEN; } - if (zlib) return inflate_request(e, memory); + return S_OK; + } + + HRESULT execute_request(Entry& e, bool pair_reserved) { + const HRESULT valid = validate_request(e); + if (FAILED(valid)) { e.reason = "request-validation"; return valid; } + const auto& r = e.request; + const auto o = r.Options.AsUINT64; + const bool memory = desc_.SourceType == DSTORAGE_REQUEST_SOURCE_MEMORY; + if ((o & (options::kDestinationPages | options::kSourcePages)) || options::zlib(o) || + options::bcpack(o) || options::swizzle(o)) { + leonida::dstorage::StagingPool::Lease reservation(leonida::dstorage::staging_pool()); + if (!pair_reserved) reservation.acquire(leonida::dstorage::staging_bytes(r)); + std::vector data; + const auto hr = prepare(e, data); + return FAILED(hr) ? hr : publish(e, data); + } if (r.SourceSize == 0) return S_OK; // nothing to move; the reference does not say this fails - if (memory) return guarded_move(r.Destination, r.Source, r.SourceSize) ? S_OK : E_DSTORAGE_ACCESS_VIOLATION; - return read_file_range(e.file->handle(), r.FileOffset, r.Destination, r.SourceSize); - } - - // A zlib request whose checks have passed: the source (SourceSize bytes of the file or of memory) goes into a - // staging buffer, inflates there, and only a result of exactly DestinationSize bytes is copied to the destination. - // So a failed stream leaves the destination as it was, and a memory source that overlaps its destination is safe. - // Both buffers are at most 32 MiB (execute_request). The stream is RFC 1950: the two header bytes, the deflate - // data, the Adler-32 of the result; bytes after the Adler-32 are not read. A failure is the matching - // dstorageerr.h code: a bad header (not deflate, a window over 32 KiB, a bad check value or a preset dictionary) - // E_DSTORAGE_ZLIB_BAD_HEADER, bad or truncated deflate data E_DSTORAGE_ZLIB_BAD_DATA, an Adler-32 mismatch - // E_DSTORAGE_ZLIB_PARITY_FAIL, and a stream that inflates to more or fewer bytes than DestinationSize - // E_DSTORAGE_DECOMPRESSION_ERROR (no code names a size mismatch; this is the header's generic one). - HRESULT inflate_request(const Entry& e, bool memory) { - const DSTORAGE_REQUEST& r = e.request; - std::vector source, result; - try { - source.resize(r.SourceSize); - result.reserve(r.DestinationSize); - } catch (const std::bad_alloc&) { - return E_OUTOFMEMORY; + void* const destination = cpu_destination(r); + if (memory) { + const auto begin = Timing::start(); + const auto hr = written(r, guarded_move(destination, r.Source, r.SourceSize) ? S_OK : E_DSTORAGE_ACCESS_VIOLATION); + e.timing.copy = Timing::elapsed(begin); + if (FAILED(hr)) e.reason = "copy"; + return hr; + } + if (extended_enabled() && !rt::xmem::commit_physical_range(destination, r.DestinationSize)) { + e.reason = "destination-commit"; + return E_DSTORAGE_ACCESS_VIOLATION; + } + const auto begin = Timing::start(); + const auto hr = read_file_range(e.file->handle(), r.FileOffset, destination, r.SourceSize, ReadTarget::Title); + e.timing.read = Timing::elapsed(begin); + if (FAILED(hr)) e.reason = "file-read"; + return written(r, hr); + } + + // Where the CPU writes a request's destination: the title hands its stream pool's GPU-only alias range as the + // destination of streamed texture data (gfxgeom notes, section 2), which only the GPU maps; its CPU view holds the + // same pages (src/title_page_watch.h, title_gpu_views). + static void* cpu_destination(const DSTORAGE_REQUEST& r) { + return reinterpret_cast(leonida::title_gpu_views::to_cpu(reinterpret_cast(r.Destination))); + } + // A request that wrote its destination tells the D3D12 layer, whose images of textures in that memory are filled + // from it (title_texel_writes). + static HRESULT written(const DSTORAGE_REQUEST& r, HRESULT hr) { + if (SUCCEEDED(hr)) leonida::title_texel_writes::note(cpu_destination(r), r.DestinationSize); + return hr; + } + + // The caller may populate or remap the physical page list between enqueue and Submit. + // Snapshot page numbers on the worker before taking xmem's allocation/map lock. + static HRESULT page_transfer(const ULONG_PTR* pages, uint16_t offset, std::span buffer, bool write) { + if (buffer.empty()) return S_OK; + std::vector numbers(1 + (buffer.size() - 1 + offset) / 65536); + if (!guarded_move(numbers.data(), pages, numbers.size() * sizeof(numbers[0]))) + return E_DSTORAGE_ACCESS_VIOLATION; + if (rt::xmem::transfer_physical(numbers, offset, buffer, write)) return S_OK; + return HRESULT_FROM_WIN32(GetLastError()); + } + + static HRESULT inflate(const std::vector& src, std::vector& out, size_t size) { + leonida::ZlibError why{}; + static const bool bulk = [] { + wchar_t value[2]{}; + return GetEnvironmentVariableW(L"LEONIDA_DSTORAGE_FAST_INFLATE", value, 2) != 1 || value[0] != L'0'; + }(); + out.reserve(size); + if (leonida::zlib_inflate(src, out, size, &why, bulk)) + return out.size() == size ? S_OK : E_DSTORAGE_DECOMPRESSION_ERROR; + switch (why) { + case leonida::ZlibError::header: return E_DSTORAGE_ZLIB_BAD_HEADER; + case leonida::ZlibError::checksum: return E_DSTORAGE_ZLIB_PARITY_FAIL; + case leonida::ZlibError::limit: return E_DSTORAGE_DECOMPRESSION_ERROR; + default: return E_DSTORAGE_ZLIB_BAD_DATA; + } + } + + static HRESULT decode_stages(Entry& e, unsigned bc, unsigned sw, std::vector& data) { + const auto& r = e.request; + if (options::zlib(r.Options.AsUINT64)) { + std::vector scratch; + static const bool reported = (log_once("zlib", "zlib requests use CPU inflate (RFC 1950)"), true); + (void)reported; + const auto begin = Timing::start(); + const auto hr = inflate(data, scratch, bc ? r.IntermediateSize : r.DestinationSize); + e.timing.inflate = Timing::elapsed(begin); + if (FAILED(hr)) { e.reason = "inflate"; return hr; } + data = std::move(scratch); } - if (r.SourceSize != 0) { - if (memory) { - if (!guarded_move(source.data(), r.Source, r.SourceSize)) return E_DSTORAGE_ACCESS_VIOLATION; - } else if (const HRESULT hr = read_file_range(e.file->handle(), r.FileOffset, source.data(), r.SourceSize); - FAILED(hr)) { + if (bc) { + std::vector scratch(r.DestinationSize); + static const bool allow_fitted = [] { + char value[2]{}; + return GetEnvironmentVariableA("LEONIDA_DSTORAGE_FITTED", value, sizeof value) != 1 || value[0] != '0'; + }(); + const auto begin = Timing::start(); + static const bool fast_entropy = [] { + char value[2]{}; + return GetEnvironmentVariableA("LEONIDA_DSTORAGE_FAST_BCPACK", value, sizeof value) != 1 || value[0] != '0'; + }(); + const char* failure = nullptr; + const auto quality = leonida::bcpack::decode(bc, data, scratch, allow_fitted, bc >= 6 ? bcpack_history() : nullptr, &failure, fast_entropy); + e.timing.bcpack = Timing::elapsed(begin); + if (quality == leonida::bcpack::Quality::failed) { e.reason = failure; return E_DSTORAGE_DECOMPRESSION_ERROR; } + if (quality == leonida::bcpack::Quality::fitted) { + static const bool reported = (log_once("fitted", "using fitted BCPack predictors"), true); + (void)reported; + if (leonida::dstorage::trace_enabled()) + std::fprintf(stderr, "[rt] ds-fitted bc=%u bytes=%u\n", bc, r.DestinationSize); + } + data = std::move(scratch); + } + if (sw) { + std::vector scratch(r.DestinationSize); + const auto begin = Timing::start(); + if (!leonida::dstorage::unshuffle(sw, data, scratch)) return E_DSTORAGE_INVALID_DESTINATION_SIZE; + e.timing.unshuffle = Timing::elapsed(begin); + data = std::move(scratch); + } + return S_OK; + } + + HRESULT prepare(Entry& e, std::vector& data) try { + const auto& r = e.request; + const auto o = r.Options.AsUINT64; + const bool memory = desc_.SourceType == DSTORAGE_REQUEST_SOURCE_MEMORY; + const auto bc = unsigned(options::bcpack(o)), sw = unsigned(options::swizzle(o)); + data.resize(r.SourceSize); + HRESULT hr = S_OK; + const auto read_begin = Timing::start(); + if (!memory) hr = read_file_range(e.file->handle(), r.FileOffset, data.data(), r.SourceSize, ReadTarget::Staging); + else if (o & options::kSourcePages) hr = page_transfer(r.SourcePageArray, r.SourcePageOffset, data, false); + else if (!data.empty() && !guarded_move(data.data(), r.Source, data.size())) hr = E_DSTORAGE_ACCESS_VIOLATION; + e.timing.read = Timing::elapsed(read_begin); + if (FAILED(hr)) { e.reason = "read"; return hr; } + if (bc || sw || options::zlib(o)) { + set_decompression_pending(+1); + try { + hr = decode_stages(e, bc, sw, data); + } catch (const std::bad_alloc&) { + hr = E_OUTOFMEMORY; + } + set_decompression_pending(-1); + if (FAILED(hr)) { + std::lock_guard lock(stats().mutex); + ++stats().s.DecompressionErrors; return hr; } } - log_once("zlib", "zlib requests are inflated on the CPU (RFC 1950, leonida::zlib_inflate)"); - set_decompression_pending(+1); - leonida::ZlibError why = leonida::ZlibError::none; - const bool inflated = leonida::zlib_inflate(source, result, r.DestinationSize, &why); - set_decompression_pending(-1); + return S_OK; + } catch (const std::bad_alloc&) { return E_OUTOFMEMORY; } + + HRESULT publish(Entry& e, std::vector& data) try { + const auto& r = e.request; + const auto o = r.Options.AsUINT64; + const auto bc = options::bcpack(o), sw = options::swizzle(o); HRESULT hr = S_OK; - if (!inflated) { - switch (why) { - case leonida::ZlibError::header: hr = E_DSTORAGE_ZLIB_BAD_HEADER; break; - case leonida::ZlibError::checksum: hr = E_DSTORAGE_ZLIB_PARITY_FAIL; break; - case leonida::ZlibError::limit: hr = E_DSTORAGE_DECOMPRESSION_ERROR; break; // longer than the destination - default: hr = E_DSTORAGE_ZLIB_BAD_DATA; break; + const auto copy_begin = Timing::start(); + if (o & options::kDestinationPages) hr = page_transfer(r.DestinationPageArray, r.DestinationPageOffset, data, true); + else if (!data.empty()) { + void* const dest = cpu_destination(r); + if (extended_enabled() && !rt::xmem::commit_physical_range(dest, data.size())) { + e.reason = "destination-commit"; + return E_DSTORAGE_ACCESS_VIOLATION; } - } else if (result.size() != r.DestinationSize) { - hr = E_DSTORAGE_DECOMPRESSION_ERROR; // shorter than the destination + hr = written(r, guarded_move(dest, data.data(), data.size()) ? S_OK : E_DSTORAGE_ACCESS_VIOLATION); } - if (FAILED(hr)) { - std::lock_guard lock(stats().mutex); - ++stats().s.DecompressionErrors; - return hr; + e.timing.copy = Timing::elapsed(copy_begin); + if (FAILED(hr)) e.reason = "publish"; + if (leonida::dstorage::trace_enabled() && SUCCEEDED(hr) && (bc || sw || (o & options::kDestinationPages) || + leonida::title_gpu_views::other_view(reinterpret_cast(r.Destination)))) { + std::fprintf(stderr, "[rt] ds-write queue=%p dest=%p cpu=%p options=%llx bytes=%zu nonzero=%d\n", + static_cast(this), r.Destination, (o & options::kDestinationPages) ? nullptr : cpu_destination(r), + o, data.size(), + int(std::any_of(data.begin(), data.end(), [](uint8_t byte) { return byte != 0; }))); } - return guarded_move(r.Destination, result.data(), result.size()) ? S_OK : E_DSTORAGE_ACCESS_VIOLATION; - } + return hr; + } catch (const std::bad_alloc&) { return E_OUTOFMEMORY; } void set_pending(int delta) { std::lock_guard lock(stats().mutex); priority_stats(stats().s, desc_.Priority).PendingRequestCount += static_cast(delta); } - // PendingDecompressionRequestCount is the zlib requests being inflated; TotalDecompressionRequestCount counts each + // PendingDecompressionRequestCount covers the current decode pipeline; TotalDecompressionRequestCount counts each // one that reached its inflate (its source was read), DecompressionErrors those whose stream then failed. static void set_decompression_pending(int delta) { std::lock_guard lock(stats().mutex); @@ -943,9 +1260,16 @@ class Queue final : public IDStorageQueueX2 { if (record_.FailureCount++ == 0) record_.FirstFailure = f; if (error_event_) SetEvent(error_event_); } - log_once("fail" + hr_text(f.HResult) + std::to_string(f.CommandType), - "an entry failed with " + hr_text(f.HResult) + " (command type " + std::to_string(f.CommandType) + - "; logged once per code)"); + static auto* counts = new std::map; + std::lock_guard lock(log_mutex()); + const auto count = ++(*counts)[f.HResult]; + // The boot digest groups identical lines. Keep one invariant line per HRESULT and + // report the cumulative value separately so a truncated run is still countable. + std::fprintf(stderr, "[rt] dstorage: an entry failed with 0x%08lx (facility=%lx code=%lx)\n" + "[rt] ds-error-count hr=%08lx count=%llu command=%u\n", + static_cast(f.HResult), static_cast(HRESULT_FACILITY(f.HResult)), + static_cast(HRESULT_CODE(f.HResult)), static_cast(f.HResult), + static_cast(count), unsigned(f.CommandType)); } void clear_record_locked() { @@ -971,10 +1295,12 @@ class Queue final : public IDStorageQueueX2 { std::condition_variable work_, space_, idle_; std::deque entries_; size_t submitted_ = 0; // the first submitted_ entries are submitted - bool in_flight_ = false; + size_t in_flight_ = 0; bool closing_ = false; bool closed_ = false; std::thread worker_; + PTP_WORK preparation_work_ = nullptr; + Prepared* helper_job_ = nullptr; // Lives on the publisher stack through the callback and ordered write. HRESULT since_notify_ = S_OK; // worker only std::mutex error_mutex_; DSTORAGE_ERROR_RECORD record_{}; diff --git a/runtime/shims/dstorage_staging.h b/runtime/shims/dstorage_staging.h new file mode 100644 index 0000000000..a989f69acb --- /dev/null +++ b/runtime/shims/dstorage_staging.h @@ -0,0 +1,104 @@ +// Temporary payloads across all DirectStorage queues. A pair reserves both requests +// together so its ordered publisher never waits for space held by its own helper. +#pragma once + +#include "dstorage_xs_abi.h" +#include "../src/dstorage_trace.h" +#include +#include +#include +#include +#include + +namespace leonida::dstorage { + +inline uint64_t staging_bytes(const dsx::DSTORAGE_REQUEST& r) { + using namespace dsx; + const auto o = r.Options.AsUINT64; + const bool bc = options::bcpack(o) != 0; + uint64_t input = r.SourceSize, peak = 0; + const auto pages = [](uint64_t size, unsigned offset) { + return size ? size + sizeof(uint64_t) * (1 + (size - 1 + offset) / 65536) : 0; + }; + if (o & options::kSourcePages) peak = pages(input, r.SourcePageOffset); + const auto stage = [&](uint64_t output) { + peak = (std::max)(peak, input + output); + input = output; + }; + if (options::zlib(o)) stage(bc ? r.IntermediateSize : r.DestinationSize); + if (bc) stage(r.DestinationSize); + if (options::swizzle(o)) stage(r.DestinationSize); + if (o & options::kDestinationPages) peak = (std::max)(peak, pages(input, r.DestinationPageOffset)); + return peak; // Raw buffer reads/copies allocate no private payload. +} + +class StagingPool { +public: + static constexpr uint64_t limit = 64ull << 20; + // Requests above the shared window run alone. The validated ABI sizes bound + // one transform to two 1 GiB buffers. No payload is allocated by the pool itself. + class Lease { + public: + explicit Lease(StagingPool& pool) : pool_(pool) {} + Lease(const Lease&) = delete; + Lease& operator=(const Lease&) = delete; + + bool try_pair(uint64_t bytes) { + std::lock_guard lock(pool_.mutex_); + if (pool_.helpers_ >= 2 || pool_.next_ != pool_.serving_ || + bytes > limit || pool_.used_ > limit - bytes) return false; + ++pool_.helpers_; + pair_ = true; + take(bytes); + return true; + } + void acquire(uint64_t bytes) { + if (!bytes) return; + std::unique_lock lock(pool_.mutex_); + const uint64_t ticket = pool_.next_++; + pool_.changed_.wait(lock, [&] { + return ticket == pool_.serving_ && (!pool_.used_ || + (bytes <= limit && pool_.used_ <= limit - bytes)); + }); + take(bytes); + ++pool_.serving_; + if (pool_.next_ != pool_.serving_) pool_.changed_.notify_all(); + } + ~Lease() { + if (!bytes_ && !pair_) return; + std::lock_guard lock(pool_.mutex_); + pool_.used_ -= bytes_; + if (pair_) --pool_.helpers_; + if (!pool_.used_ && pool_.drained_ < pool_.peak_) { + pool_.drained_ = pool_.peak_; + if (trace_enabled()) std::fprintf(stderr, "[rt] ds-staging idle_bytes=0 peak_bytes=%llu\n", pool_.peak_); + } + if (pool_.next_ != pool_.serving_) pool_.changed_.notify_all(); + } + private: + void take(uint64_t bytes) { + bytes_ = bytes; + pool_.used_ += bytes; + if (pool_.used_ > pool_.peak_) { + pool_.peak_ = pool_.used_; + if (trace_enabled()) std::fprintf(stderr, "[rt] ds-staging peak_bytes=%llu limit_bytes=%llu\n", pool_.peak_, limit); + } + } + StagingPool& pool_; + uint64_t bytes_{}; + bool pair_{}; + }; + +private: + std::mutex mutex_; + std::condition_variable changed_; + unsigned helpers_{}; + uint64_t used_{}, peak_{}, drained_{}, next_{}, serving_{}; +}; + +inline StagingPool& staging_pool() { + static auto* pool = new StagingPool; + return *pool; +} + +} // namespace leonida::dstorage diff --git a/runtime/shims/dxgi_com.cpp b/runtime/shims/dxgi_com.cpp index 71b9d8261b..04ed1c68e6 100644 --- a/runtime/shims/dxgi_com.cpp +++ b/runtime/shims/dxgi_com.cpp @@ -212,7 +212,8 @@ class SwapChain final : public IDXGISwapChain3 { : parent_(parent), device_(device), context_(context), - swapchain_(gipa, instance, physical, gdpa, context.device(), queue, queue_family, context.submit_mutex()) { + swapchain_(gipa, instance, physical, gdpa, context.device(), queue, queue_family, context.submit_mutex(), + context.device_fault()) { if (parent_) parent_->AddRef(); if (device_) device_->AddRef(); } @@ -221,6 +222,7 @@ class SwapChain final : public IDXGISwapChain3 { unregister_buffers(); if (restrict_to_output_) restrict_to_output_->Release(); if (waitable_) CloseHandle(waitable_); + swapchain_.close(); if (device_) device_->Release(); if (parent_) parent_->Release(); } diff --git a/runtime/shims/dxgi_swapchain.h b/runtime/shims/dxgi_swapchain.h index 3dadfcef5d..ebe3bc0279 100644 --- a/runtime/shims/dxgi_swapchain.h +++ b/runtime/shims/dxgi_swapchain.h @@ -15,11 +15,14 @@ #include #include +#include "../src/vulkan_device_fault.h" + #include "../src/vulkan_backend.h" #include #include #include +#include #include namespace leonida { @@ -108,9 +111,9 @@ class VulkanSwapchain { public: VulkanSwapchain(PFN_vkGetInstanceProcAddr gipa, VkInstance instance, VkPhysicalDevice physical, PFN_vkGetDeviceProcAddr gdpa, VkDevice device, VkQueue queue, std::uint32_t queue_family, - std::mutex& submit_mutex) + std::mutex& submit_mutex, DeviceFaultDiagnostics* diagnostics) : instance_(instance), physical_(physical), device_(device), queue_(queue), queue_family_(queue_family), - submit_mutex_(submit_mutex) { + submit_mutex_(submit_mutex), diagnostics_(diagnostics) { loaded_ = fn_.load(gipa, instance, gdpa, device); if (loaded_) { VkFenceCreateInfo fi{VK_STRUCTURE_TYPE_FENCE_CREATE_INFO}; @@ -129,12 +132,15 @@ class VulkanSwapchain { } } - ~VulkanSwapchain() { + ~VulkanSwapchain() { close(); } + + // The COM owner calls this before releasing its reference to the D3D12 queue and device. + void close() { destroy_swapchain(); - if (blit_pool_) fn_.destroy_cmd_pool(device_, blit_pool_, nullptr); - if (surface_) fn_.destroy_surface(instance_, surface_, nullptr); - if (acquire_fence_) fn_.destroy_fence(device_, acquire_fence_, nullptr); - if (blit_fence_) fn_.destroy_fence(device_, blit_fence_, nullptr); + if (blit_pool_) fn_.destroy_cmd_pool(device_, std::exchange(blit_pool_, VK_NULL_HANDLE), nullptr); + if (surface_) fn_.destroy_surface(instance_, std::exchange(surface_, VK_NULL_HANDLE), nullptr); + if (acquire_fence_) fn_.destroy_fence(device_, std::exchange(acquire_fence_, VK_NULL_HANDLE), nullptr); + if (blit_fence_) fn_.destroy_fence(device_, std::exchange(blit_fence_, VK_NULL_HANDLE), nullptr); } VulkanSwapchain(const VulkanSwapchain&) = delete; @@ -162,7 +168,7 @@ class VulkanSwapchain { if (!loaded_ || !surface_) return false; { std::lock_guard lock(submit_mutex_); - fn_.device_wait_idle(device_); + observe(fn_.device_wait_idle(device_), "vkDeviceWaitIdle (DXGI)"); } allow_tearing_ = allow_tearing; const VkFormat fmt = (preferred_format != VK_FORMAT_UNDEFINED) ? preferred_format : format_; @@ -173,10 +179,12 @@ class VulkanSwapchain { bool acquire_next_image(std::uint32_t& out_index, std::uint64_t timeout_ns = UINT64_MAX) { if (!swapchain_ || !acquire_fence_) return false; if (fn_.reset_fences(device_, 1, &acquire_fence_) != VK_SUCCESS) return false; - const VkResult r = fn_.acquire_next_image(device_, swapchain_, timeout_ns, VK_NULL_HANDLE, acquire_fence_, - &out_index); + const VkResult r = observe( + fn_.acquire_next_image(device_, swapchain_, timeout_ns, VK_NULL_HANDLE, acquire_fence_, &out_index), + "vkAcquireNextImageKHR (DXGI)"); if (r != VK_SUCCESS && r != VK_SUBOPTIMAL_KHR) return false; - if (fn_.wait_for_fences(device_, 1, &acquire_fence_, VK_TRUE, timeout_ns) != VK_SUCCESS) return false; + if (observe(fn_.wait_for_fences(device_, 1, &acquire_fence_, VK_TRUE, timeout_ns), + "vkWaitForFences (DXGI acquire)") != VK_SUCCESS) return false; acquired_index_ = out_index; if (is_offscreen()) { // The native image count may differ from the DXGI BufferCount (Vulkan is free to return more @@ -212,7 +220,7 @@ class VulkanSwapchain { pi.pSwapchains = &swapchain_; pi.pImageIndices = &image_index; std::lock_guard lock(submit_mutex_); - const VkResult r = fn_.queue_present(queue_, &pi); + const VkResult r = observe(fn_.queue_present(queue_, &pi), "vkQueuePresentKHR (DXGI)"); return r == VK_SUCCESS || r == VK_SUBOPTIMAL_KHR; } @@ -246,6 +254,10 @@ class VulkanSwapchain { } private: + VkResult observe(VkResult result, const char* operation) const noexcept { + return DeviceFaultDiagnostics::observe(diagnostics_, result, operation); + } + bool transition_image_layout(VkImage img, VkImageLayout old_layout, VkImageLayout new_layout) { if (!blit_cmd_ || !blit_fence_ || !img) return false; std::lock_guard lock(submit_mutex_); @@ -271,8 +283,7 @@ class VulkanSwapchain { VkSubmitInfo si{VK_STRUCTURE_TYPE_SUBMIT_INFO}; si.commandBufferCount = 1; si.pCommandBuffers = &blit_cmd_; - return fn_.queue_submit(queue_, 1, &si, blit_fence_) == VK_SUCCESS && - fn_.wait_for_fences(device_, 1, &blit_fence_, VK_TRUE, UINT64_MAX) == VK_SUCCESS; + return submit_blit_and_wait(si); } void destroy_offscreen() { @@ -287,7 +298,7 @@ class VulkanSwapchain { void destroy_swapchain() { if (swapchain_ || !offscreen_images_.empty()) { std::lock_guard lock(submit_mutex_); - fn_.device_wait_idle(device_); + observe(fn_.device_wait_idle(device_), "vkDeviceWaitIdle (DXGI)"); destroy_offscreen(); if (swapchain_) { fn_.destroy_swapchain(device_, swapchain_, nullptr); @@ -471,8 +482,13 @@ class VulkanSwapchain { VkSubmitInfo si{VK_STRUCTURE_TYPE_SUBMIT_INFO}; si.commandBufferCount = 1; si.pCommandBuffers = &blit_cmd_; - if (fn_.queue_submit(queue_, 1, &si, blit_fence_) != VK_SUCCESS) return false; - return fn_.wait_for_fences(device_, 1, &blit_fence_, VK_TRUE, UINT64_MAX) == VK_SUCCESS; + return submit_blit_and_wait(si); + } + + bool submit_blit_and_wait(const VkSubmitInfo& submit) { + return observe(fn_.queue_submit(queue_, 1, &submit, blit_fence_), "vkQueueSubmit (DXGI)") == VK_SUCCESS && + observe(fn_.wait_for_fences(device_, 1, &blit_fence_, VK_TRUE, UINT64_MAX), + "vkWaitForFences (DXGI blit)") == VK_SUCCESS; } bool rebuild(std::uint32_t width, std::uint32_t height, VkFormat preferred_format, std::uint32_t buffer_count) { @@ -540,7 +556,8 @@ class VulkanSwapchain { ci.oldSwapchain = swapchain_; VkSwapchainKHR next = VK_NULL_HANDLE; - if (fn_.create_swapchain(device_, &ci, nullptr, &next) != VK_SUCCESS) return false; + if (observe(fn_.create_swapchain(device_, &ci, nullptr, &next), "vkCreateSwapchainKHR (DXGI)") != VK_SUCCESS) + return false; if (swapchain_) fn_.destroy_swapchain(device_, swapchain_, nullptr); destroy_offscreen(); swapchain_ = next; @@ -579,6 +596,7 @@ class VulkanSwapchain { VkQueue queue_ = VK_NULL_HANDLE; std::uint32_t queue_family_ = 0; std::mutex& submit_mutex_; + DeviceFaultDiagnostics* diagnostics_; VkSurfaceKHR surface_ = VK_NULL_HANDLE; VkSwapchainKHR swapchain_ = VK_NULL_HANDLE; VkFence acquire_fence_ = VK_NULL_HANDLE; diff --git a/runtime/shims/file_system.cpp b/runtime/shims/file_system.cpp index f6934c5ed0..8208cc5ecf 100644 --- a/runtime/shims/file_system.cpp +++ b/runtime/shims/file_system.cpp @@ -41,6 +41,7 @@ #include "file_system.h" #include "shims.h" #include "startup_trace.h" +#include "../src/title_page_watch.h" namespace rt::fs { namespace { @@ -725,19 +726,22 @@ bool touch_pages(void* buffer, DWORD size) { return all; } -// ReadFile with one retry for a destination the kernel cannot write yet. The retail title reads into title memory -// that xmem maps from physical pages committed on first touch; the kernel's write raises no user-mode fault, so -// ReadFile fails with ERROR_NOACCESS (998), and the title's read loop sleeps 1 ms and retries forever (measured on -// 1.0.2.1, native Windows). Touching the pages from user mode commits them; the read is then retried once. -BOOL WINAPI read_file(HANDLE file, LPVOID buffer, DWORD size, LPDWORD read, LPOVERLAPPED overlapped) { - if (ReadFile(file, buffer, size, read, overlapped)) return TRUE; - if (GetLastError() != ERROR_NOACCESS || !buffer || !size) return FALSE; - static std::atomic logged{false}; - if (!logged.exchange(true)) - std::fprintf(stderr, "[rt] fs: ReadFile into uncommitted title memory (ERROR_NOACCESS): committing the " - "destination pages and retrying (logged once)\n"); - touch_pages(buffer, size); - return ReadFile(file, buffer, size, read, overlapped); +// LOCAL DIAGNOSTIC: gta6rt --trace FILE also records the first 600 successful opens ("file_open": path, access, +// caller), so the startup trace shows which file the title was working on when it stopped making progress. +void note_open(const char* api, LPCWSTR name, DWORD access, const void* caller) { + if (!rt::startup_trace::enabled()) return; + static std::atomic left{600}; + if (left.fetch_sub(1, std::memory_order_relaxed) <= 0) return; + std::string utf8; + if (const int n = WideCharToMultiByte(CP_UTF8, 0, name, -1, nullptr, 0, nullptr, nullptr); n > 1) { + utf8.resize(static_cast(n) - 1); + WideCharToMultiByte(CP_UTF8, 0, name, -1, utf8.data(), n, nullptr, nullptr); + } + rt::startup_trace::event( + "file_open", + std::string("\"api\":\"") + api + "\",\"path\":" + rt::startup_trace::quote(utf8) + ",\"access\":" + + std::to_string(access) + ",\"caller\":" + + rt::startup_trace::quote(rt::startup_trace::where(reinterpret_cast(caller)))); } HANDLE WINAPI create_file_w(LPCWSTR name, DWORD access, DWORD share, LPSECURITY_ATTRIBUTES attributes, @@ -757,6 +761,8 @@ HANDLE WINAPI create_file_w(LPCWSTR name, DWORD access, DWORD share, LPSECURITY_ const DWORD error = GetLastError(); note_open_failure("CreateFileW", name, error, _ReturnAddress()); SetLastError(error); + } else { + note_open("CreateFileW", name, access, _ReturnAddress()); } return h; } @@ -788,6 +794,8 @@ HANDLE WINAPI create_file2(LPCWSTR name, DWORD access, DWORD share, DWORD dispos const DWORD error = GetLastError(); note_open_failure("CreateFile2", name, error, _ReturnAddress()); SetLastError(error); + } else { + note_open("CreateFile2", name, access, _ReturnAddress()); } return h; } @@ -1434,9 +1442,36 @@ BOOL WINAPI set_file_attributes_a(LPCSTR name, DWORD attributes) { namespace { using namespace rt::fs; +// Reads into title memory. The D3D12 layer keeps some of the title's pages read-only between submissions to see +// which ones the title writes (slot-133 shadow buffers); the kernel fails a read into such a page with +// ERROR_NOACCESS instead of faulting, so the destination is pinned and opened first (title_page_watch.h). +// +// If the read still fails with ERROR_NOACCESS (no committer or opener set), the destination may be xmem physical +// pages committed on first touch: the kernel's write raises no user-mode fault, and the title's read loop sleeps +// 1 ms and retries forever (measured on 1.0.2.1, native Windows). Touching the pages from user mode commits them; +// the read is then retried once. +BOOL WINAPI read_file(HANDLE file, LPVOID buffer, DWORD bytes, LPDWORD read, LPOVERLAPPED overlapped) { + if (leonida::kernel_writes::read_file(file, buffer, bytes, read, overlapped)) return TRUE; + if (GetLastError() != ERROR_NOACCESS || !buffer || !bytes) return FALSE; + static std::atomic logged{false}; + if (!logged.exchange(true)) + std::fprintf(stderr, "[rt] fs: ReadFile into uncommitted title memory (ERROR_NOACCESS): committing the " + "destination pages and retrying (logged once)\n"); + rt::fs::touch_pages(buffer, bytes); + return leonida::kernel_writes::read_file(file, buffer, bytes, read, overlapped); +} +BOOL WINAPI read_file_ex(HANDLE file, LPVOID buffer, DWORD bytes, LPOVERLAPPED overlapped, + LPOVERLAPPED_COMPLETION_ROUTINE routine) { + return leonida::kernel_writes::read_file_ex(file, buffer, bytes, overlapped, routine); +} +BOOL WINAPI read_file_scatter(HANDLE file, FILE_SEGMENT_ELEMENT segments[], DWORD bytes, LPDWORD reserved, + LPOVERLAPPED overlapped) { + return leonida::kernel_writes::read_file_scatter(file, segments, bytes, reserved, overlapped); +} + // CreateFile, the FindFirstFile family, the attribute queries and DeleteFile arrive through kernel32/kernelbase // imports and through the api sets a GDK title is linked against (file-l1-1-0 for the find and attribute calls, -// file-l1-2-0 and file-l2-1-0 for CreateFile). +// file-l1-2-0 and file-l2-1-0 for CreateFile; ReadFile and its variants are in file-l1-1-0). #define FILE_API(dll) \ {dll, "CreateFileA", reinterpret_cast(&create_file_a)}, \ {dll, "CreateFileW", reinterpret_cast(&create_file_w)}, \ @@ -1471,7 +1506,10 @@ using namespace rt::fs; {dll, "CopyFileExW", reinterpret_cast(©_file_ex_w)}, \ {dll, "CopyFile2", reinterpret_cast(©_file2)}, \ {dll, "SetFileAttributesA", reinterpret_cast(&set_file_attributes_a)}, \ - {dll, "SetFileAttributesW", reinterpret_cast(&set_file_attributes_w)} + {dll, "SetFileAttributesW", reinterpret_cast(&set_file_attributes_w)}, \ + {dll, "ReadFile", reinterpret_cast(&read_file)}, \ + {dll, "ReadFileEx", reinterpret_cast(&read_file_ex)}, \ + {dll, "ReadFileScatter", reinterpret_cast(&read_file_scatter)} } // namespace SHIM_TABLE(file_system, diff --git a/runtime/shims/gameinput.cpp b/runtime/shims/gameinput.cpp index 7650b361ff..83511f939d 100644 --- a/runtime/shims/gameinput.cpp +++ b/runtime/shims/gameinput.cpp @@ -1895,10 +1895,14 @@ void update_keyboard_pad() { } clip_cursor(active && g_raw_ready && g_cursor_pos.load() == system_cursor_pos && foreground_is_ours()); for (const auto& b : kKeyBindings) SDL_SetJoystickVirtualButton(g_keyboard.js, b.sdl_button, down[b.sdl_button]); - // Timed presses on the keyboard pad, in seconds since its first update. Each press lasts 300 ms. + // LEONIDA_INPUT_SCRIPT="a@70,a@85,start@120" (with LEONIDA_KEYBOARD_PAD=always): timed presses on the keyboard + // pad, in seconds since its first update, each held 300 ms. Buttons: a b x y start back lb rb up down left right. + // The rsup and rsdown entries throw the right stick up or down for the same 300 ms. + int right_y = g_keyboard.right_y; struct ScriptedPress { SDL_GamepadButton button; double at; + int right_y = 0; }; static const std::vector script = [] { std::vector out; @@ -1925,6 +1929,11 @@ void update_keyboard_pad() { const double seconds = std::strtod(time, &tail); if (tail == time || !std::isfinite(seconds) || seconds < 0 || item.find_first_not_of(whitespace, tail - item.c_str()) != std::string::npos) continue; + if (item.compare(first, sep - first, "rsup") == 0 || item.compare(first, sep - first, "rsdown") == 0) { + const bool up = item.compare(first, sep - first, "rsup") == 0; + out.push_back({SDL_GAMEPAD_BUTTON_INVALID, seconds, up ? -kStickFull : kStickFull}); + continue; + } for (const auto& [name, button] : names) { if (item.compare(first, sep - first, name) == 0) { out.push_back({button, seconds}); @@ -1944,8 +1953,13 @@ void update_keyboard_pad() { bool scripted[SDL_GAMEPAD_BUTTON_COUNT] = {}; bool named[SDL_GAMEPAD_BUTTON_COUNT] = {}; for (const auto& press : script) { - named[press.button] = true; - if (now >= press.at && now < press.at + 0.3) scripted[press.button] = true; + const bool held = now >= press.at && now < press.at + 0.3; + if (press.right_y) { + if (held) right_y = press.right_y; + } else { + named[press.button] = true; + scripted[press.button] |= held; + } } for (int button = 0; button < SDL_GAMEPAD_BUTTON_COUNT; ++button) { if (!named[button]) continue; @@ -1961,7 +1975,7 @@ void update_keyboard_pad() { SDL_SetJoystickVirtualAxis(g_keyboard.js, SDL_GAMEPAD_AXIS_LEFTX, static_cast(lx * reach)); SDL_SetJoystickVirtualAxis(g_keyboard.js, SDL_GAMEPAD_AXIS_LEFTY, static_cast(ly * reach)); SDL_SetJoystickVirtualAxis(g_keyboard.js, SDL_GAMEPAD_AXIS_RIGHTX, static_cast(g_keyboard.right_x)); - SDL_SetJoystickVirtualAxis(g_keyboard.js, SDL_GAMEPAD_AXIS_RIGHTY, static_cast(g_keyboard.right_y)); + SDL_SetJoystickVirtualAxis(g_keyboard.js, SDL_GAMEPAD_AXIS_RIGHTY, static_cast(right_y)); // SDL maps a full-range virtual axis to the trigger, so -32768 is released, 0 half pulled, 32767 full. SDL_SetJoystickVirtualAxis(g_keyboard.js, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, aim ? 32767 : -32768); SDL_SetJoystickVirtualAxis(g_keyboard.js, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, fire ? 32767 : -32768); @@ -2032,6 +2046,33 @@ void poll_once() { read_raw(d, &snap); const bool guide_changed = d->last_snap.guide != snap.guide; const bool changed = !(d->last_snap == snap); + // Every press is logged in LEONIDA_INPUT_SCRIPT's own form (name@seconds), so a session played by hand can + // be replayed unattended: join the logged items with commas. The right stick's vertical throws (what scrolls + // a page) are logged as rsup/rsdown. LEONIDA_INPUT_LOG=0 turns the lines off. + { + static const bool log_presses = env("LEONIDA_INPUT_LOG") != "0"; + static const ULONGLONG log_origin = GetTickCount64(); + if (log_presses) { + static const std::pair kNames[] = { + {GameInputGamepadA, "a"}, {GameInputGamepadB, "b"}, + {GameInputGamepadX, "x"}, {GameInputGamepadY, "y"}, + {GameInputGamepadMenu, "start"}, {GameInputGamepadView, "back"}, + {GameInputGamepadLeftShoulder, "lb"}, {GameInputGamepadRightShoulder, "rb"}, + {GameInputGamepadDPadUp, "up"}, {GameInputGamepadDPadDown, "down"}, + {GameInputGamepadDPadLeft, "left"}, {GameInputGamepadDPadRight, "right"}}; + const double at = (GetTickCount64() - log_origin) / 1000.0; + const uint32_t pressed = snap.gamepad.buttons & ~d->last_snap.gamepad.buttons; + for (const auto& n : kNames) + if (pressed & n.first) + std::fprintf(stderr, "[rt] gameinput: press %s@%.1f (%s)\n", n.second, at, d->name.c_str()); + const auto throw_of = [](float y) { return y > 0.6f ? 1 : y < -0.6f ? -1 : 0; }; + const int was = throw_of(d->last_snap.gamepad.rightThumbstickY); + const int is = throw_of(snap.gamepad.rightThumbstickY); + if (is != was && is != 0) + std::fprintf(stderr, "[rt] gameinput: press %s@%.1f (%s)\n", is > 0 ? "rsup" : "rsdown", at, + d->name.c_str()); + } + } d->last_snap = snap; // A newly opened pad's first sample here is its baseline (active_input.h), so connecting a pad with a button // held changes nothing. diff --git a/runtime/shims/gameinput_no_sdl.cpp b/runtime/shims/gameinput_no_sdl.cpp new file mode 100644 index 0000000000..ab190d2505 --- /dev/null +++ b/runtime/shims/gameinput_no_sdl.cpp @@ -0,0 +1,86 @@ +// gameinput.dll: GameInputCreate without SDL3. +// +// runtime/shims/gameinput.cpp serves the real thing through SDL3 and is only compiled when SDL3 is available. A build +// without SDL3 therefore left gameinput.dll unserved, the loader fell through to the host's gameinput.dll (wine ships +// one), and that host answers GameInputCreate with a null interface while the title ignores the HRESULT: the title's +// lazy singleton stores the null and calls AddRef/Release through it, which is a page fault at address 0. +// +// This file keeps the object identity honest without any input backend: one static object, slot 0/1/2 as +// QueryInterface/AddRef/Release, E_NOTIMPL for every other slot, so a caller that only holds and releases the +// interface survives and one that asks for devices gets a clean refusal instead of a null dereference. +#include + +#include +#include +#include +#include +#include + +#include "shims.h" + +namespace { + +constexpr size_t kSlots = 64; // comfortably covers the public v0 IGameInput vtable + +struct GameInputStub { + const void* const* vtable; +}; + +std::atomic g_refs{1}; + +HRESULT __stdcall stub_qi(GameInputStub* self, const IID& riid, void** out); +ULONG __stdcall stub_add_ref(GameInputStub*); +ULONG __stdcall stub_release(GameInputStub*); + +template +HRESULT __stdcall stub_method(GameInputStub*) { + static std::atomic warned{false}; + if (!warned.exchange(true, std::memory_order_relaxed)) + std::fprintf(stderr, "[rt] gameinput: slot %zu is not served without SDL3; E_NOTIMPL (logged once)\n", Slot); + return E_NOTIMPL; +} + +template +constexpr auto make_vtable(std::index_sequence) { + return std::array{ + (Slot == 0 ? reinterpret_cast(&stub_qi) + : Slot == 1 ? reinterpret_cast(&stub_add_ref) + : Slot == 2 ? reinterpret_cast(&stub_release) + : reinterpret_cast(&stub_method))...}; +} + +const auto kVtable = make_vtable(std::make_index_sequence{}); +GameInputStub g_gameinput{kVtable.data()}; + +HRESULT __stdcall stub_qi(GameInputStub*, const IID& riid, void** out) { + if (!out) return E_POINTER; + // An interface pointer is handed back for any IID: the measured call site holds this object only to AddRef and + // Release it, and the other v0 interfaces answer E_NOTIMPL on their slots rather than faulting on a null. + (void)riid; + *out = &g_gameinput; + g_refs.fetch_add(1); + return S_OK; +} + +ULONG __stdcall stub_add_ref(GameInputStub*) { return g_refs.fetch_add(1) + 1; } + +ULONG __stdcall stub_release(GameInputStub*) { return g_refs.fetch_sub(1) - 1; } + +HRESULT WINAPI GameInputCreate(void** out) { + if (!out) return E_POINTER; + g_refs.fetch_add(1); + *out = &g_gameinput; + static std::atomic warned{false}; + if (!warned.exchange(true, std::memory_order_relaxed)) + std::fprintf(stderr, "[rt] gameinput: served without SDL3 (no devices; E_NOTIMPL for every other slot)\n"); + return S_OK; +} + +} // namespace + +SHIM_TABLE(gameinput_no_sdl, + {"gameinput.dll", "GameInputCreate", reinterpret_cast(&GameInputCreate)}, + // The retail executable imports this one by ordinal, so the registry key is "#1"; without the alias the loader + // fell through to the host's gameinput.dll, which handed the title a null interface. + {"gameinput.dll", "#1", reinterpret_cast(&GameInputCreate)}, +); diff --git a/runtime/shims/library_loader.cpp b/runtime/shims/library_loader.cpp index 250fe0209f..3a96092df1 100644 --- a/runtime/shims/library_loader.cpp +++ b/runtime/shims/library_loader.cpp @@ -2,9 +2,10 @@ // // GDK code does not always import the console runtime. The package's libHttpClient.GDK.dll and XCurl.dll have no // import entry for xgameruntime.dll at all: their statically linked xgameruntime.lib thunks hold the wide string -// "xgameruntime.dll" and the names InitializeApiImpl, InitializeApiImplEx, InitializeApiImplEx2, QueryApiImpl and -// UninitializeApiImpl, and look them up at run time (docs/runtime_imports.md, "Run-time loaded modules"). Bound to the -// host, that LoadLibraryW would load the PC's Gaming Services runtime or fail, and never reach the offline shims. +// "xgameruntime.dll" and the names InitializeApiImpl, InitializeApiImplEx, InitializeApiImplEx2, QueryApiImpl, +// UninitializeApiImpl and XErrorReport, and look them up at run time (docs/runtime_imports.md, "Run-time loaded +// modules"). Bound to the host, that LoadLibraryW would load the PC's Gaming Services runtime or fail, and never reach +// the offline shims. // // So for a module the shim registry owns (rt::shims::owns_dll: xgameruntime.dll, d3d12_xs.dll, xmem.dll, ...), these // return a pseudo-handle, and GetProcAddress on it resolves names (and "#ordinal") through rt::shims::find. A name the diff --git a/runtime/shims/package_splash.cpp b/runtime/shims/package_splash.cpp new file mode 100644 index 0000000000..f21967519a --- /dev/null +++ b/runtime/shims/package_splash.cpp @@ -0,0 +1,159 @@ +#include "package_splash.h" +#include "title_window.h" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace rt::package_splash { +namespace { +using Microsoft::WRL::ComPtr; +std::filesystem::path image_path; + +std::filesystem::path declared_image(const std::filesystem::path& package, const wchar_t* manifest, + const wchar_t* element, const wchar_t* attribute) { + ComPtr stream; + ComPtr reader; + const auto config = package / manifest; + if (FAILED(SHCreateStreamOnFileEx(config.c_str(), STGM_READ | STGM_SHARE_DENY_NONE, 0, FALSE, nullptr, &stream)) || + FAILED(CreateXmlReader(IID_PPV_ARGS(&reader), nullptr)) || FAILED(reader->SetInput(stream.Get()))) + return {}; + XmlNodeType type{}; + while (reader->Read(&type) == S_OK) { + const wchar_t* name = nullptr; + const wchar_t* value = nullptr; + if (type != XmlNodeType_Element || FAILED(reader->GetLocalName(&name, nullptr)) || + std::wstring_view(name) != element || + reader->MoveToAttributeByName(attribute, nullptr) != S_OK || + FAILED(reader->GetValue(&value, nullptr)) || !*value) + continue; + const std::filesystem::path asset(value); + if (asset.has_root_path() || asset.native().find(L':') != std::wstring::npos) return {}; + for (const auto& part : asset) + if (part == L"..") return {}; + std::error_code ec; + const auto root = std::filesystem::canonical(package, ec); + if (ec) return {}; + const auto file = std::filesystem::canonical(root / asset, ec); + if (ec) return {}; + const auto relative = file.lexically_relative(root); + if (relative.empty() || *relative.begin() == L".." || !std::filesystem::is_regular_file(file, ec)) return {}; + return file; + } + return {}; +} + +std::vector decode(UINT width, UINT height) { + ComPtr factory; + ComPtr decoder; + ComPtr frame; + UINT w = 0, h = 0; + if (FAILED(CoCreateInstance(CLSID_WICImagingFactory, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&factory))) || + FAILED(factory->CreateDecoderFromFilename(image_path.c_str(), nullptr, GENERIC_READ, WICDecodeMetadataCacheOnDemand, &decoder)) || + FAILED(decoder->GetFrame(0, &frame)) || FAILED(frame->GetSize(&w, &h)) || !w || !h) + return {}; + + // Centre the package art at its original aspect ratio in the actual client area. + const UINT draw_w = UINT(std::clamp(std::uint64_t(height) * w / h, 1, width)); + const UINT draw_h = UINT(std::clamp(std::uint64_t(width) * h / w, 1, height)); + ComPtr scaler; + ComPtr converter; + if (FAILED(factory->CreateBitmapScaler(&scaler)) || + FAILED(scaler->Initialize(frame.Get(), draw_w, draw_h, WICBitmapInterpolationModeFant)) || + FAILED(factory->CreateFormatConverter(&converter)) || + FAILED(converter->Initialize(scaler.Get(), GUID_WICPixelFormat32bppPBGRA, WICBitmapDitherTypeNone, nullptr, 0, + WICBitmapPaletteTypeCustom))) + return {}; + const UINT pitch = width * 4; + const UINT bytes = pitch * height; + const UINT offset = (height - draw_h) / 2 * pitch + (width - draw_w) / 2 * 4; + std::vector pixels(bytes); + if (FAILED(converter->CopyPixels(nullptr, pitch, bytes - offset, pixels.data() + offset))) return {}; + + return pixels; +} + +std::vector load_pixels(UINT width, UINT height) { + if (image_path.empty() || !width || !height || std::uint64_t(width) * height > (64u << 20)) return {}; + const HRESULT apartment = CoInitializeEx(nullptr, COINIT_MULTITHREADED); + if (FAILED(apartment) && apartment != RPC_E_CHANGED_MODE) return {}; + std::vector pixels; + try { + pixels = decode(width, height); + } catch (const std::bad_alloc&) { + // Optional startup art must leave the first title frame available on low-memory hosts. + } + if (SUCCEEDED(apartment)) CoUninitialize(); + return pixels; +} + +} // namespace + +void configure(const std::filesystem::path& package) { + image_path.clear(); + wchar_t value[4]{}; + if (GetEnvironmentVariableW(L"LEONIDA_PACKAGE_SPLASH", value, 4) == 1 && value[0] == L'0') return; + wchar_t window_mode[16]{}; + const DWORD length = GetEnvironmentVariableW(L"LEONIDA_PRESENT_WINDOW", window_mode, 16); + if (length && length < 16 && (std::wstring_view(window_mode) == L"own" || std::wstring_view(window_mode) == L"hidden")) + return; + image_path = declared_image(package, L"MicrosoftGame.Config", L"ShellVisuals", L"SplashScreenImage"); + if (image_path.empty()) image_path = declared_image(package, L"appxmanifest.xml", L"SplashScreen", L"Image"); +} + +bool configured() { return !image_path.empty(); } + +bool paint_window(HWND window) { + static std::atomic painted{false}; + if (painted.load() || !configured() || !window || rt::d3d12::find_title_window(GetCurrentProcessId()) != window) + return false; + RECT client{}; + if (!GetClientRect(window, &client) || client.right <= 0 || client.bottom <= 0 || painted.exchange(true)) + return false; + auto pixels = load_pixels(UINT(client.right), UINT(client.bottom)); + if (pixels.empty()) return false; + BITMAPINFO bitmap{}; + bitmap.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); + bitmap.bmiHeader.biWidth = client.right; + bitmap.bmiHeader.biHeight = -client.bottom; + bitmap.bmiHeader.biPlanes = 1; + bitmap.bmiHeader.biBitCount = 32; + bitmap.bmiHeader.biCompression = BI_RGB; + if (GetWindowThreadProcessId(window, nullptr) == GetCurrentThreadId()) UpdateWindow(window); + HDC dc = GetDC(window); + if (!dc) return false; + int lines = SetDIBitsToDevice(dc, 0, 0, client.right, client.bottom, 0, 0, 0, client.bottom, + pixels.data(), &bitmap, DIB_RGB_COLORS); + ReleaseDC(window, dc); + return lines > 0; +} + +ID3D12Resource* create_texture(ID3D12Device* device, UINT width, UINT height) { + if (!device) return nullptr; + const auto pixels = load_pixels(width, height); + if (pixels.empty()) return nullptr; + const UINT pitch = width * 4; + const UINT bytes = pitch * height; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = width; + desc.Height = height; + desc.DepthOrArraySize = desc.MipLevels = 1; + desc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; + desc.SampleDesc.Count = 1; + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, D3D12_MEMORY_POOL_L0, 1, 1}; + ComPtr texture; + if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, + nullptr, IID_PPV_ARGS(&texture))) || + FAILED(texture->WriteToSubresource(0, nullptr, pixels.data(), pitch, bytes))) + return nullptr; + return texture.Detach(); +} +} // namespace rt::package_splash diff --git a/runtime/shims/package_splash.h b/runtime/shims/package_splash.h new file mode 100644 index 0000000000..b15e72dfb2 --- /dev/null +++ b/runtime/shims/package_splash.h @@ -0,0 +1,14 @@ +#pragma once + +#include +#include + +namespace rt::package_splash { + +// Called before the title starts. An absent or disabled shell visual leaves presentation to the title. +void configure(const std::filesystem::path& package); +bool configured(); +bool paint_window(HWND window); +ID3D12Resource* create_texture(ID3D12Device* device, UINT width, UINT height); + +} // namespace rt::package_splash diff --git a/runtime/shims/registry.cpp b/runtime/shims/registry.cpp index d2a78eb6bf..59f1da1066 100644 --- a/runtime/shims/registry.cpp +++ b/runtime/shims/registry.cpp @@ -100,6 +100,25 @@ const char* const kNotHResult[] = { }; const char* const kXFamilies[] = {"XAsync", "XTaskQueue", "XUser", "XStore", "XGameSave", "XPackage", "XGameUi"}; +static bool is_audio_hal_hresult(const std::string& dll, const std::string& name) { + if (dll == "chad.dll") { + // All five XDsp* functions return HRESULT (GDK XDspAudio reference). + if (starts_with(name, "XDsp")) return true; + } else if (dll == "xapu.dll") { + // XApuConnect/DequeueResult/Disconnect/EnqueueCommand return HRESULT; + // XApuGetResultCount returns uint32_t. + if (name != "XApuGetResultCount" && starts_with(name, "XApu")) return true; + } else if (dll == "acphal.dll") { + // AcpHalAllocateShapeContexts, AcpHalCreate, AcpHalReleaseShapeContexts, + // ApuAlloc, ApuCreateHeap return HRESULT. ApuFree, ApuIsVirtualAddressValid, + // ApuMapApuAddress and ApuMapVirtualAddress return other types. + if (name == "AcpHalAllocateShapeContexts" || name == "AcpHalCreate" || + name == "AcpHalReleaseShapeContexts" || name == "ApuAlloc" || + name == "ApuCreateHeap") return true; + } + return false; +} + ReturnClass classify(const std::string& dll, const std::string& name) { if (dll == "d3d12.dll" || dll == "d3d12_xs.dll") { if (starts_with(name, "D3D12Create") || starts_with(name, "D3D12Serialize") || @@ -116,11 +135,8 @@ ReturnClass classify(const std::string& dll, const std::string& name) { if (name == "GameInputCreate") return ReturnClass::HResult; } else if (dll == "dstorage.dll" || dll == "dstorage_xs.dll" || dll == "xcrdapi.dll") { if (name == "DStorageGetFactory") return ReturnClass::HResult; - } else if (dll == "acphal.dll") { - if (name == "AcpHalAllocateShapeContexts" || name == "AcpHalCreate" || - name == "AcpHalReleaseShapeContexts" || name == "ApuAlloc" || - name == "ApuCreateHeap") - return ReturnClass::HResult; + } else if (is_audio_hal_hresult(dll, name)) { + return ReturnClass::HResult; } else if (dll == "xgameruntime.dll") { if (name == "XGameRuntimeInitialize" || name == "XGameEventWrite") return ReturnClass::HResult; for (const char* n : kNotHResult) @@ -534,7 +550,7 @@ void* find(const std::string& dll_lower, const std::string& name) { bool owns_dll(const std::string& dll_lower) { static const char* const host[] = {"kernel32.dll", "kernelbase.dll", "msvcrt.dll", "ucrtbase.dll", "ucrtbased.dll", "vulkan-1.dll", "ntdll.dll", "user32.dll", "ws2_32.dll", - "wsock32.dll"}; + "wsock32.dll", "advapi32.dll"}; if (starts_with(dll_lower, "api-ms-") || starts_with(dll_lower, "ext-ms-")) return false; for (const char* h : host) if (dll_lower == h) return false; diff --git a/runtime/shims/startup_trace.h b/runtime/shims/startup_trace.h index 7b47d993ae..2d404eaff6 100644 --- a/runtime/shims/startup_trace.h +++ b/runtime/shims/startup_trace.h @@ -3,14 +3,16 @@ // One JSON object per line, flushed per event so the file survives a crash. Off by default; every entry point is a // single relaxed load when it is off. Events: // {"seq":1,"t":0.000,"kind":"trace_open"} -// {"seq":2,"t":0.001,"kind":"map","module":"a.dll","base":"0x...","size":"0x2000","relocated":false} -// {"seq":3,"t":0.002,"kind":"tls_callback","module":"a.dll","at":"a.dll+0x1200","reason":1} -// {"seq":4,"t":0.002,"kind":"dllmain","module":"a.dll","result":1} -// {"seq":5,"t":0.010,"kind":"unimplemented_call","import":"x.dll!Foo","caller":"a.dll+0x3f10"} (first call only) -// {"seq":6,"t":0.011,"kind":"debug_string","text":"..."} -// {"seq":7,"t":0.020,"kind":"exception","code":"0xc0000005","at":"a.dll+0x4a00","access":"read","address":"0x0", -// "stack":["a.dll+0x4a00","a.dll+0x2210"]} -// {"seq":8,"t":0.030,"kind":"exit","code":0} +// {"seq":2,"t":0.001,"kind":"tls_index0","owner":"gta6rt.exe","moved_to":4} (first executable mapped, once) +// {"seq":3,"t":0.001,"kind":"map","module":"a.dll","base":"0x...","size":"0x2000","relocated":false} +// {"seq":4,"t":0.002,"kind":"tls_callback","module":"a.dll","at":"a.dll+0x1200","reason":1} +// {"seq":5,"t":0.002,"kind":"dllmain","module":"a.dll","result":1} +// {"seq":6,"t":0.010,"kind":"unimplemented_call","import":"x.dll!Foo","caller":"a.dll+0x3f10"} (first call only) +// {"seq":7,"t":0.011,"kind":"debug_string","text":"..."} +// {"seq":8,"t":0.020,"kind":"exception","code":"0xc0000005","at":"a.dll+0x4a00","access":"read","address":"0x0", +// "region":{"base":"0x0","allocation_base":"0x0","size":"0x7ffe0000","state":"0x10000","protect":"0x1", +// "type":"0x0"},"regs":{...},"stack":["a.dll+0x4a00","a.dll+0x2210"]} +// {"seq":9,"t":0.030,"kind":"exit","code":0} // // The exception handler is vectored, logs and returns EXCEPTION_CONTINUE_SEARCH: it never changes what the process // does (except LEONIDA_SKIP_INT3, below). @@ -163,9 +165,53 @@ inline std::string debug_text(const EXCEPTION_RECORD& r) { return utf8_from_ansi(a, static_cast(n ? n - 1 : strlen(a))); } +// LOCAL DIAGNOSTIC for one of the title's asserts (docs/re/answers.md, "transient pool"): at that assert's int3 +// the title has just computed the peak of a list of resources with lifetimes against a fixed pool. The int3's +// location is measured locally and not kept here: LEONIDA_POOL_DIAG_AT names it as the trace prints it +// (`+0x`), and the dump is off without it. +// rdi = the list (24-byte records: entry pointer, u32 size rounded to 64 KiB), r13 = the count, rax = the peak, +// rcx = the pool size. An entry is {record pointer, ..., u32 first pass at +16, u32 last pass at +20}; a record has +// its usage word at +14, kind word at +16 and, for a texture, width/height/depth words at +56/+58/+60, the dimension +// and DXGI format bytes at +62/+63 and the mip count at +66. Printed once, to stderr; every read is checked. +inline void dump_transient_pool(const CONTEXT& c) { + static std::atomic done{false}; + if (done.exchange(true)) return; + const auto read = [](uint64_t at, void* out, size_t n) { + SIZE_T got = 0; + return ReadProcessMemory(GetCurrentProcess(), reinterpret_cast(at), out, n, &got) && got == n; + }; + std::fprintf(stderr, "[rt] pool-diag: peak %llu B, pool %llu B, %llu entries (i size first last usage kind fmt WxHxD mips)\n", + static_cast(c.Rax), static_cast(c.Rcx), + static_cast(c.R13)); + for (uint64_t i = 0; i < c.R13 && i < 4096; ++i) { + uint64_t entry = 0, record = 0; + uint32_t size = 0, passes[2]{}; + uint8_t desc[16]{}; + uint16_t words[2]{}; + if (!read(c.Rdi + i * 24, &entry, 8) || !read(c.Rdi + i * 24 + 8, &size, 4) || !read(entry, &record, 8) || + !read(entry + 16, passes, 8) || !read(record + 14, words, 4) || !read(record + 56, desc, 16)) + break; + uint16_t w, h, d; + std::memcpy(&w, desc, 2); + std::memcpy(&h, desc + 2, 2); + std::memcpy(&d, desc + 4, 2); + std::fprintf(stderr, "[rt] pool-diag: %llu %u %u %u 0x%x 0x%x %u %ux%ux%u %u\n", + static_cast(i), size, passes[0], passes[1], words[0], words[1], + unsigned(desc[7]), unsigned(w), unsigned(h), unsigned(d), unsigned(desc[10])); + } +} + inline void log_exception(const EXCEPTION_POINTERS& info) { const EXCEPTION_RECORD& r = *info.ExceptionRecord; try { + static const std::string pool_diag_at = [] { + char at[128]{}; + const DWORD n = GetEnvironmentVariableA("LEONIDA_POOL_DIAG_AT", at, sizeof(at)); + return n && n < sizeof(at) ? std::string(at, n) : std::string(); + }(); + if (r.ExceptionCode == EXCEPTION_BREAKPOINT && info.ContextRecord && !pool_diag_at.empty() && + where(reinterpret_cast(r.ExceptionAddress)).ends_with(pool_diag_at)) + dump_transient_pool(*info.ContextRecord); if (r.ExceptionCode == kDbgPrint || r.ExceptionCode == kDbgPrintWide) { const ULONG_PTR fallback = wide_fallback; const bool wide = r.ExceptionCode == kDbgPrintWide; @@ -181,8 +227,27 @@ inline void log_exception(const EXCEPTION_POINTERS& info) { const auto op = r.ExceptionInformation[0]; f += ",\"access\":" + quote(op == 0 ? "read" : op == 1 ? "write" : "execute") + ",\"address\":" + quote(hex(r.ExceptionInformation[1])); + // The faulting page's region: committed or not, its protection, private or a mapped view. + MEMORY_BASIC_INFORMATION m{}; + if (VirtualQuery(reinterpret_cast(r.ExceptionInformation[1]), &m, sizeof(m))) + f += ",\"region\":{\"base\":" + quote(hex(reinterpret_cast(m.BaseAddress))) + + ",\"allocation_base\":" + quote(hex(reinterpret_cast(m.AllocationBase))) + + ",\"size\":" + quote(hex(m.RegionSize)) + ",\"state\":" + quote(hex(m.State)) + + ",\"protect\":" + quote(hex(m.Protect)) + ",\"type\":" + quote(hex(m.Type)) + "}"; } if (r.ExceptionCode == kCppException) f += ",\"cpp\":true"; + if (info.ContextRecord) { + // The registers at the fault: what an analyst needs to read a title assert (which value, which list). + const CONTEXT& c = *info.ContextRecord; + const std::pair regs[] = { + {"rax", c.Rax}, {"rcx", c.Rcx}, {"rdx", c.Rdx}, {"rbx", c.Rbx}, {"rsi", c.Rsi}, {"rdi", c.Rdi}, + {"r8", c.R8}, {"r9", c.R9}, {"r10", c.R10}, {"r11", c.R11}, {"r12", c.R12}, {"r13", c.R13}, + {"r14", c.R14}, {"r15", c.R15}, {"rbp", c.Rbp}, {"rsp", c.Rsp}}; + f += ",\"regs\":{"; + for (size_t i = 0; i < std::size(regs); ++i) + f += std::string(i ? "," : "") + "\"" + regs[i].first + "\":" + quote(hex(regs[i].second)); + f += "}"; + } if (info.ContextRecord) f += ",\"stack\":" + stack_from(*info.ContextRecord); event("exception", f); } diff --git a/runtime/shims/title_gpu_placements.h b/runtime/shims/title_gpu_placements.h new file mode 100644 index 0000000000..f3734a66e6 --- /dev/null +++ b/runtime/shims/title_gpu_placements.h @@ -0,0 +1,65 @@ +#pragma once + +#include "xg_xs_layout.h" +#include "../src/gfx10_descriptors.h" +#include +#include + +namespace rt::d3d12 { + +// GPU resources can have overlapping lifetimes at one placement VA. Resource references are +// held by the D3D12 caller. The device serializes this index with descriptor registration. +template +class TitleGpuPlacements { +public: + void add(std::uint64_t address, Resource* resource) { resources_.emplace(address, resource); } + + void remove(std::uint64_t address, const void* owner) { + auto [it, end] = resources_.equal_range(address); + for (; it != end; ++it) { + if (it->second == owner) { + resources_.erase(it); + return; + } + } + } + + template + Resource* find(std::uint64_t va, std::uint64_t alias, Matches matches) const { + for (const auto address : {va, alias}) { + if (!address) continue; + auto [first, end] = resources_.equal_range(address); + while (first != end) { + Resource* r = (--end)->second; + if (matches(*r)) return r; + } + } + return nullptr; + } + + static bool matches(const rt::xg_xs::ResourceDesc& d, const Resource& resource) { + const auto& r = resource.desc(); + return UINT(r.Dimension) == d.dimension && r.Width == d.width && r.Height == d.height && + r.DepthOrArraySize == d.depth_or_array && (!d.mips || r.MipLevels == d.mips) && + r.SampleDesc.Count == d.samples && + (UINT(r.Format) == d.format || resource.lists_castable_format(DXGI_FORMAT(d.format))); + } + + static bool matches(const leonida::gfx10::Image& image, const D3D12_RESOURCE_DESC& d) { + namespace g = leonida::gfx10; + if (d.Width != image.width || d.Height != image.height) return false; + if (g::multisampled(image.type) != (d.SampleDesc.Count > 1)) return false; + if (d.SampleDesc.Count > 1 && d.SampleDesc.Count != image.samples) return false; + if (image.first_mip + image.mip_count > d.MipLevels) return false; + if (image.type == g::ImageType::image_3d) + return d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D && image.depth == d.DepthOrArraySize; + const auto dimension = image.type == g::ImageType::image_1d + ? D3D12_RESOURCE_DIMENSION_TEXTURE1D : D3D12_RESOURCE_DIMENSION_TEXTURE2D; + return d.Dimension == dimension && image.first_layer + image.layer_count <= d.DepthOrArraySize; + } + +private: + std::multimap resources_; +}; + +} // namespace rt::d3d12 diff --git a/runtime/shims/title_window.h b/runtime/shims/title_window.h new file mode 100644 index 0000000000..f2564f6563 --- /dev/null +++ b/runtime/shims/title_window.h @@ -0,0 +1,52 @@ +#pragma once + +// The window a GDKX title shows its frames in, for PresentX. +// +// On the console PresentX puts a frame on the display: it names no window. A GDKX title still makes its own top-level +// Win32 window (CreateWindowExW with its own class, a message loop on its own thread) before it presents, so on the PC +// that window is where the frames belong. Measured on a retail executable: by its first PresentX the title has one +// visible, unowned top-level window on a thread of its own; the other windows of the process at that point are hidden +// (the IME windows Windows adds, a driver's dummy window). +// +// The lookup sends no message to any window. The present thread is not the title's window thread, and that thread can +// be busy (or waiting on the present thread) when the first PresentX comes: GetWindowTextW, or any call that sends a +// message across threads, would block the present thread there. Measured: a lookup that read the window titles with +// GetWindowTextW stopped the retail title at its first PresentX. EnumWindows, GetWindowThreadProcessId, IsWindowVisible, +// GetWindow(GW_OWNER), GetWindowLongPtrW and GetClientRect read the window manager's own state and send nothing. + +#include + +namespace rt::d3d12 { + +// The visible, unowned, non-tool top-level window of `process_id` with the largest client area, `exclude` aside (the +// runtime's own fallback window); null when the process has none. Ties keep the first one in Z order (the topmost). +inline HWND find_title_window(DWORD process_id, HWND exclude = nullptr) { + struct Search { + DWORD process_id; + HWND exclude; + HWND best; + LONGLONG best_area; + } search{process_id, exclude, nullptr, -1}; + EnumWindows( + [](HWND window, LPARAM context) -> BOOL { + auto& s = *reinterpret_cast(context); + DWORD owner_process = 0; + if (window == s.exclude || !GetWindowThreadProcessId(window, &owner_process) || + owner_process != s.process_id) + return TRUE; + if (!IsWindowVisible(window) || GetWindow(window, GW_OWNER)) return TRUE; + if (GetWindowLongPtrW(window, GWL_EXSTYLE) & WS_EX_TOOLWINDOW) return TRUE; + RECT client{}; + const LONGLONG area = + GetClientRect(window, &client) ? LONGLONG(client.right - client.left) * (client.bottom - client.top) : 0; + if (area > s.best_area) { + s.best = window; + s.best_area = area; + } + return TRUE; + }, + reinterpret_cast(&search)); + return search.best; +} + +} // namespace rt::d3d12 diff --git a/runtime/shims/xapu.cpp b/runtime/shims/xapu.cpp new file mode 100644 index 0000000000..a7a612c5c7 --- /dev/null +++ b/runtime/shims/xapu.cpp @@ -0,0 +1,142 @@ +// xapu.dll: Audio Processing Unit (XAPU). Hardware-accelerated Opus decoding and +// sample-rate conversion on Xbox Series. +// +// On a PC there is no such hardware. This shim accepts connections and commands, +// and reports results as if they completed immediately with silence/identity. +// +// Measured from the call sites in the executable, read statically (shapes and +// argument counts only; see docs/audio_hal_exe_calls.md and PR #6981): +// XApuConnect(void* out24, void* out16, void** handle) 3 args +// XApuEnqueueCommand(void* handle, const uint32_t* cmd, u64) 3 args +// XApuGetResultCount(void* handle, u64) 2 args +// XApuDequeueResult(void* handle, void* out) 2 args +// XApuDisconnect(void* handle) 1 arg +// +// The 24-byte output is zeroed, the 16-byte output holds {base, size} of a +// shared buffer (0x14000 + 128 * 0x1E00 bytes), commands are accepted and +// dropped, the result queue stays empty. + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "shims.h" +#include "startup_trace.h" + +namespace { + +constexpr size_t kApuBufferSize = 0x14000 + 128 * 0x1E00; +constexpr HRESULT XAPU_E_PENDING_RESULTS = 0x8004E801; + +// ---- Opaque handle ---- + +struct XApuClient { + void* buffer; +}; + +// ---- Startup trace helper ---- + +void trace_call(const char* api, const std::string& detail) { + if (!rt::startup_trace::enabled()) return; + static std::mutex mutex; + static std::set seen; + { + std::lock_guard lock(mutex); + if (!seen.insert(std::string(api) + detail).second) return; + } + rt::startup_trace::event("xapu", + std::string("\"api\":\"") + api + "\"" + detail); +} + +// ---- XApuConnect ---- +// +// Measured: XApuConnect(void* out24, void* out16, void** handle) +// out24[0..23] is zeroed. out16[0..1] = {buffer_base, buffer_size}. +// The handle is an opaque pointer. +// Success is SUCCEEDED(hr). + +HRESULT __stdcall XApuConnect(void* out24, void* out16, void** handle) { + trace_call("XApuConnect", ""); + if (!handle) return E_INVALIDARG; + *handle = nullptr; + + void* buffer = VirtualAlloc(nullptr, kApuBufferSize, + MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + if (!buffer) return E_OUTOFMEMORY; + + if (out24) std::memset(out24, 0, 24); + if (out16) { + const uint64_t info[2] = {reinterpret_cast(buffer), kApuBufferSize}; + std::memcpy(out16, info, sizeof(info)); + } + + *handle = new XApuClient{buffer}; + return S_OK; +} + +// ---- XApuDequeueResult ---- +// +// Measured: XApuDequeueResult(void* handle, void* result) +// Without hardware there are no results. Return a negative HRESULT that the +// caller handles (it stops the dequeue loop). + +HRESULT __stdcall XApuDequeueResult(void* handle, void* commandResult) { + (void)handle; + (void)commandResult; + return XAPU_E_PENDING_RESULTS; +} + +// ---- XApuDisconnect ---- +// +// Measured: XApuDisconnect(void* handle) + +HRESULT __stdcall XApuDisconnect(void* handle) { + trace_call("XApuDisconnect", ""); + if (!handle) return E_INVALIDARG; + auto* client = static_cast(handle); + VirtualFree(client->buffer, 0, MEM_RELEASE); + delete client; + return S_OK; +} + +// ---- XApuEnqueueCommand ---- +// +// Measured: XApuEnqueueCommand(void* handle, const uint32_t* command, uint64_t flags) +// The return value is never read. The command's first dword is a type (1, 2, 3 seen), +// the second a stream slot. The 3rd argument is a flags word (always 0 at the call sites). + +HRESULT __stdcall XApuEnqueueCommand(void* handle, const uint32_t* command, + uint64_t flags) { + (void)flags; + trace_call("XApuEnqueueCommand", + ",\"type\":" + std::to_string(command ? command[0] : ~0u)); + return handle && command ? S_OK : E_INVALIDARG; +} + +// ---- XApuGetResultCount ---- +// +// Measured: XApuGetResultCount(void* handle, uint64_t flags) +// Returns uint32_t: 0 means no results ready. + +uint32_t __stdcall XApuGetResultCount(void* handle, uint64_t flags) { + (void)handle; + (void)flags; + return 0; +} + +} // namespace + +SHIM_TABLE(xapu, + {"xapu.dll", "XApuConnect", reinterpret_cast(&XApuConnect)}, + {"xapu.dll", "XApuDequeueResult", reinterpret_cast(&XApuDequeueResult)}, + {"xapu.dll", "XApuDisconnect", reinterpret_cast(&XApuDisconnect)}, + {"xapu.dll", "XApuEnqueueCommand", reinterpret_cast(&XApuEnqueueCommand)}, + {"xapu.dll", "XApuGetResultCount", reinterpret_cast(&XApuGetResultCount)}, +); \ No newline at end of file diff --git a/runtime/shims/xbox_bvh_builder.cpp b/runtime/shims/xbox_bvh_builder.cpp new file mode 100644 index 0000000000..8c80419e2e --- /dev/null +++ b/runtime/shims/xbox_bvh_builder.cpp @@ -0,0 +1,285 @@ +// XboxBvhBuilder.dll served by the layer's own acceleration-structure builder (RT-5, boot stop 18). +// +// The package's XboxBvhBuilder.dll builds the game's ray-tracing structures with 52 console compute programs that +// its constructor creates as pipelines on the title's thread. Translated, they take 25-60 s to compile on a cold +// driver cache (31.2 s for one of them on an RTX 4080, 59.5 s for all 52 on an RX 9070 XT, measured in #7231 and +// #7049), longer than the title's startup watchdog (about 30 s), so a first boot ends at the builder. The layer +// already builds XDXR BVH4 structures itself (BuildRaytracingAccelerationStructure on the Vulkan device, D3D-178, +// src/xdxr_build.*), in the node format the game's translated traversal shaders read, and its one pipeline compiles +// in well under a second. So this file serves the DLL's exports with the layer's builder and the DLL is never +// loaded: the loader binds an import to a shim before a bundled module (pe_loader.cpp, Loader::resolve). +// +// The exports, as the executable imports them (7 of the DLL's 12, measured statically on 1.0.2.1: names and call +// counts only). Member functions: `this` comes first (rcx), then the arguments, as for a free function on x64. +// ??0 XboxBvhBuilder(ID3D12Device11*, bool) 1 call site +// ??1 ~XboxBvhBuilder() 1 +// Set64BitMortonCodes(bool) 8 +// GetRaytracingAccelerationStructurePrebuildInfo(const INPUTS*, const XDXR_STREAM_DESC*, PREBUILD_INFO*) 3 +// BuildRaytracingAccelerationStructureBatched2X(GCL6*, UINT, const BATCHED_DESC2*) 6 +// CopyRaytracingAccelerationStructure(GCL4*, UINT64 dest, UINT64 source, COPY_MODE) 2 +// RehydrateRaytracingAccelerationStructureBatched2X(GCL8*, UINT, const BUILD_DESC*, const UINT64*) -> HRESULT 4 +// The Xbox descriptions are the measured layouts of src/xdxr_descs.h (docs/xdxr.md). +// +// What differs from the console builder, on purpose: +// - No programs are created: the constructor only remembers the device. +// - The XDXR stream records (docs/xdxr.md §3) tune the console builder's own heuristics. The layer's builder has +// none of those settings, so a non-empty stream is logged once and otherwise ignored; the structure is still a +// valid BVH of the same geometry. Set64BitMortonCodes is recorded and ignored for the same reason. +// - The DLL throws its validation errors as C++ exceptions (docs/xdxr.md, "Errors are thrown, not returned"). A +// shim must not throw into the title, so an element the DLL would reject is logged and skipped instead. The one +// rule a correct title meets every time is kept: the offline-statistics postbuild type (0x10) is never written. +// - Rehydration is not implemented yet: RehydrateRaytracingAccelerationStructureBatched2X logs once and returns +// E_NOTIMPL. (Planned: rebuild each structure from the source geometry its description carries.) +// +// The builder object belongs to the title, which allocates it with a size this file doesn't know, so nothing is +// written into it: what the shim keeps (the device, the Morton option) lives in a table keyed by its address. +// +// LEONIDA_BVH_BUILDER=console turns the shim off, so the imports bind to the bundled DLL as before (for work on the +// console programs themselves, #5680 and #7318). The variable is read once, when the shim registers. +#include + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "d3d12_xs_device.h" +#include "shims.h" +#include "../src/xdxr_descs.h" + +namespace { + +namespace xdxr = leonida::xdxr; + +struct BuilderState { + ID3D12Device5* device = nullptr; // a reference held for the builder's lifetime; null if it has no DXR methods + bool morton64 = false; +}; + +std::mutex g_mutex; +std::unordered_map g_builders; + +void log_once(std::atomic& flag, const char* text) { + if (!flag.exchange(true)) std::fprintf(stderr, "[rt] XboxBvhBuilder shim: %s\n", text); +} + +// The PC device behind what the title passed: the real device behind a d3d12_xs device proxy, or the pointer +// itself when it is already a device (a test, or a backend that hands out unwrapped devices). +ID3D12Device5* device5_of(void* device) { + if (!device) return nullptr; + IUnknown* base = rt::d3d12_xs::device_proxy_real_device(device); + if (!base) base = static_cast(device); + ID3D12Device5* out = nullptr; + if (FAILED(base->QueryInterface(IID_PPV_ARGS(&out)))) return nullptr; + return out; +} + +// The command list a title passes, as the backend's own list: a d3d12_xs proxy is unwrapped first, so the PC +// interfaces below are asked of the real list and never of a console-shaped proxy (whose vtable is not the PC one; +// docs/d3d12_command_objects.md §3.5a). Lists aren't wrapped on main yet; a console list proxy joins +// proxy_real_object, which real_object_behind_proxy follows. +IUnknown* real_list(void* list) { + if (!list) return nullptr; + IUnknown* real = rt::d3d12_xs::real_object_behind_proxy(list); + return real ? real : static_cast(list); +} + +ID3D12GraphicsCommandList4* list4_of(void* list) { + IUnknown* real = real_list(list); + if (!real) return nullptr; + ID3D12GraphicsCommandList4* out = nullptr; + if (FAILED(real->QueryInterface(IID_PPV_ARGS(&out)))) return nullptr; + return out; +} + +// ??0XboxBvhBuilder@@QEAA@PEAUID3D12Device11@@_N@Z: XboxBvhBuilder(ID3D12Device11* device, bool). +// Returns `this`, as an MSVC constructor does. The bool's meaning is not measured; it is not needed here. +void* builder_construct(void* self, void* device, bool) { + ID3D12Device5* device5 = device5_of(device); + if (!device5) { + static std::atomic s_logged{false}; + log_once(s_logged, "the device has no ID3D12Device5 (DXR) interface; builds will be skipped"); + } + std::lock_guard lock(g_mutex); + BuilderState& state = g_builders[self]; + if (state.device) state.device->Release(); // the same storage constructed twice without a destructor + state = BuilderState{device5, false}; + return self; +} + +// ??1XboxBvhBuilder@@QEAA@XZ: ~XboxBvhBuilder(). +void builder_destruct(void* self) { + std::lock_guard lock(g_mutex); + auto it = g_builders.find(self); + if (it == g_builders.end()) return; + if (it->second.device) it->second.device->Release(); + g_builders.erase(it); +} + +// ?Set64BitMortonCodes@XboxBvhBuilder@@QEAAX_N@Z: a console-builder option (64-bit Morton keys for its sort). +void builder_set_64bit_morton_codes(void* self, bool enable) { + std::lock_guard lock(g_mutex); + auto it = g_builders.find(self); + if (it != g_builders.end()) it->second.morton64 = enable; +} + +// The builder's device with a reference of the caller's own, taken under the lock, so a destructor on another +// thread can't release it during the call. The caller releases it. +ID3D12Device5* builder_device(void* self) { + std::lock_guard lock(g_mutex); + auto it = g_builders.find(self); + if (it == g_builders.end() || !it->second.device) return nullptr; + it->second.device->AddRef(); + return it->second.device; +} + +void note_stream(const xdxr::StreamDesc& stream) { + if (stream.size_in_bytes == 0 || !stream.stream) return; + static std::atomic s_logged{false}; + log_once(s_logged, "XDXR stream records (console builder settings) are ignored by the layer's builder"); +} + +// ?GetRaytracingAccelerationStructurePrebuildInfo@XboxBvhBuilder@@QEAAXPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_ +// STRUCTURE_INPUTS@@PEBUD3D12XBOX_XDXR_STREAM_DESC@@PEAUD3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO@@@Z +// The sizes the layer's own builder needs, which are the sizes the layer's build will use. +void builder_prebuild_info(void* self, const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS* inputs, + const xdxr::StreamDesc* stream, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO* info) { + if (!info) return; + *info = {}; + if (!inputs) return; + if (stream) note_stream(*stream); + ID3D12Device5* device = builder_device(self); + if (!device) { + static std::atomic s_logged{false}; + log_once(s_logged, "GetRaytracingAccelerationStructurePrebuildInfo on a builder without a DXR device; sizes are 0"); + return; + } + device->GetRaytracingAccelerationStructurePrebuildInfo(inputs, info); + device->Release(); +} + +// ?BuildRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList6@@IPEBUD3D12XBOX_ +// BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2@@@Z +// Each element is a public build description followed by its postbuild descriptions and a stream (xdxr_descs.h), so +// it is one BuildRaytracingAccelerationStructure on the list. +void builder_build_batched2x(void*, void* list, UINT count, const xdxr::BatchedDesc2* descs) { + static_assert(sizeof(D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC) == 0x30, "the BATCHED_DESC2 prefix"); + static_assert(sizeof(D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC) == sizeof(xdxr::PostbuildInfoDesc), + "postbuild descriptions are the public ones"); + if (count == 0) return; + if (!descs) return; + ID3D12GraphicsCommandList4* list4 = list4_of(list); + if (!list4) { + static std::atomic s_logged{false}; + log_once(s_logged, "BuildRaytracingAccelerationStructureBatched2X: the list has no ID3D12GraphicsCommandList4"); + return; + } + for (UINT i = 0; i < count; ++i) { + const xdxr::BatchedDesc2& element = descs[i]; + note_stream(element.stream); + D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC build; + std::memcpy(&build, &element, sizeof(build)); + // The postbuild descriptions, without the offline-statistics type the DLL refuses (docs/xdxr.md §4). + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC kept[16]; + UINT n_kept = 0; + bool skipped_statistics = false; + const auto* post = reinterpret_cast( + element.postbuild_info_descs); + for (UINT p = 0; post && p < element.num_postbuild_info_descs; ++p) { + if (static_cast(post[p].InfoType) == xdxr::kPostbuildInfoOfflineStatistics) { + skipped_statistics = true; + continue; + } + if (n_kept == 16) { + static std::atomic s_logged{false}; + log_once(s_logged, "more than 16 postbuild descriptions in one element; the rest are dropped"); + break; + } + kept[n_kept++] = post[p]; + } + if (skipped_statistics) { + // The DLL throws E_INVALIDARG for this element before any work; the shim skips it the same way. + static std::atomic s_logged{false}; + log_once(s_logged, "an element asked for offline statistics (0x10), which the DLL refuses; element skipped"); + continue; + } + list4->BuildRaytracingAccelerationStructure(&build, n_kept, n_kept ? kept : nullptr); + } + list4->Release(); +} + +// ?CopyRaytracingAccelerationStructure@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@_K1W4D3D12_RAYTRACING_ +// ACCELERATION_STRUCTURE_COPY_MODE@@@Z +void builder_copy(void*, void* list, UINT64 dest, UINT64 source, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE mode) { + ID3D12GraphicsCommandList4* list4 = list4_of(list); + if (!list4) { + static std::atomic s_logged{false}; + log_once(s_logged, "CopyRaytracingAccelerationStructure: the list has no ID3D12GraphicsCommandList4"); + return; + } + list4->CopyRaytracingAccelerationStructure(dest, source, mode); + list4->Release(); +} + +// ?RehydrateRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAJPEAUID3D12GraphicsCommandList8@@IPEBUD3D12_ +// BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@PEB_K@Z -> HRESULT. Not implemented yet (see the header comment). +HRESULT builder_rehydrate_batched2x(void*, void*, UINT, const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC*, + const UINT64*) { + static std::atomic s_logged{false}; + log_once(s_logged, "RehydrateRaytracingAccelerationStructureBatched2X is not implemented yet; E_NOTIMPL"); + return E_NOTIMPL; +} + +constexpr const char kDll[] = "xboxbvhbuilder.dll"; + +const rt::shims::Entry kEntries[] = { + {kDll, "??0XboxBvhBuilder@@QEAA@PEAUID3D12Device11@@_N@Z", reinterpret_cast(&builder_construct)}, + {kDll, "??1XboxBvhBuilder@@QEAA@XZ", reinterpret_cast(&builder_destruct)}, + {kDll, "?Set64BitMortonCodes@XboxBvhBuilder@@QEAAX_N@Z", reinterpret_cast(&builder_set_64bit_morton_codes)}, + {kDll, + "?GetRaytracingAccelerationStructurePrebuildInfo@XboxBvhBuilder@@QEAAXPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_" + "STRUCTURE_INPUTS@@PEBUD3D12XBOX_XDXR_STREAM_DESC@@PEAUD3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO@@@Z", + reinterpret_cast(&builder_prebuild_info)}, + {kDll, + "?BuildRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList6@@IPEBUD3D12" + "XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2@@@Z", + reinterpret_cast(&builder_build_batched2x)}, + {kDll, + "?CopyRaytracingAccelerationStructure@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@_K1W4D3D12_" + "RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE@@@Z", + reinterpret_cast(&builder_copy)}, + {kDll, + "?RehydrateRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAJPEAUID3D12GraphicsCommandList8@@IPEBU" + "D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@PEB_K@Z", + reinterpret_cast(&builder_rehydrate_batched2x)}, +}; + +bool shim_enabled() { + char value[16] = {}; + size_t length = 0; + if (getenv_s(&length, value, "LEONIDA_BVH_BUILDER") != 0 || length <= 1) return true; + return _stricmp(value, "console") != 0; +} + +// Registers the table unless LEONIDA_BVH_BUILDER=console asks for the bundled DLL. +struct Registration { + Registration() { + if (!shim_enabled()) return; + static rt::shims::Table table(kEntries, sizeof(kEntries) / sizeof(kEntries[0])); + } +} g_registration; + +} // namespace + +namespace rt::shims { +// For tests: the builders constructed and not destroyed. +size_t xbox_bvh_builder_live_count() { + std::lock_guard lock(g_mutex); + return g_builders.size(); +} +} // namespace rt::shims diff --git a/runtime/shims/xbox_present.cpp b/runtime/shims/xbox_present.cpp index f8791e1bf2..a5f1d86abc 100644 --- a/runtime/shims/xbox_present.cpp +++ b/runtime/shims/xbox_present.cpp @@ -5,6 +5,7 @@ #include "../src/vulkan_present.h" +#include #include #include #include @@ -29,10 +30,11 @@ void log_once(bool& done, const char* text) { } // namespace -XboxPresentation::XboxPresentation(std::unique_ptr presenter, leonida::FrameClock* clock) +XboxPresentation::XboxPresentation(std::unique_ptr presenter, leonida::FrameClock* clock, + std::shared_ptr tokens) : presenter_(std::move(presenter)), own_clock_(clock ? nullptr : std::make_unique()), - pacer_(clock ? *clock : *own_clock_) { + pacer_(clock ? *clock : *own_clock_, std::move(tokens)) { // A present waiting for a swapchain image gives up once SuspendX has been called. presenter_->set_abort([this] { return pacer_.suspended(); }); // LEONIDA_SDR_EOTF=gamma22 (or 2.2, any case) decodes SDR with a pure power of 2.2 instead of piecewise sRGB; "srgb" or @@ -148,11 +150,31 @@ HRESULT XboxPresentation::PresentX(UINT plane_count, const XboxPresentPlaneParam return d3d12_trace::result("XboxPresentation::PresentX", present_x(plane_count, planes, params)); } +// LOCAL DIAGNOSTIC (not for upstream): which check refuses PresentX, with its HRESULT. +static HRESULT present_diag(int line, HRESULT hr) { + static std::atomic logged{0}; + if (FAILED(hr) && logged.fetch_add(1) < 40) + std::fprintf(stderr, "[rt] PresentX diag: refused at line %d hr 0x%08lx\n", line, static_cast(hr)); + return hr; +} + HRESULT XboxPresentation::present_x(UINT plane_count, const XboxPresentPlaneParameters* planes, const XboxPresentParameters* params) { std::lock_guard serialise(present_mutex_); - if (plane_count > 2 || (plane_count && !planes)) return E_INVALIDARG; - if (pacer_.suspended()) return from_pacer(hr::invalid_state); + { + static std::atomic dumped{0}; + if (dumped.fetch_add(1) < 6) { + std::fprintf(stderr, "[rt] PresentX diag: planes %u params %p suspended %d registered %d\n", plane_count, + static_cast(params), int(pacer_.suspended()), int(pacer_.registered())); + for (UINT i = 0; planes && i < plane_count && i < 2; ++i) + std::fprintf(stderr, "[rt] PresentX diag: plane %u token 0x%llx count %u res %p res0 %p\n", i, + static_cast(planes[i].Token), planes[i].ResourceCount, + static_cast(planes[i].ppResources), + planes[i].ppResources ? static_cast(planes[i].ppResources[0]) : nullptr); + } + } + if (plane_count > 2 || (plane_count && !planes)) return present_diag(117, E_INVALIDARG); + if (pacer_.suspended()) return present_diag(118, from_pacer(hr::invalid_state)); // A zero, negative or NaN threshold never tears; an uncapped frame is never late for anything either. const float threshold = params ? params->ImmediateThresholdPercent : 0.0f; const bool wants_tear = threshold > 0.0f && !pacer_.uncapped(); @@ -171,7 +193,7 @@ HRESULT XboxPresentation::present_x(UINT plane_count, const XboxPresentPlanePara pacer_.note_untokened_present(); ++presents_; } - return result; + return present_diag(__LINE__, result); } // All planes carry the token of one frame. @@ -179,20 +201,20 @@ HRESULT XboxPresentation::present_x(UINT plane_count, const XboxPresentPlanePara for (UINT i = 0; i < plane_count; ++i) { const XboxPresentPlaneParameters& plane = planes[i]; if (plane.Token != token || plane.ResourceCount == 0 || !plane.ppResources || !plane.ppResources[0]) - return E_INVALIDARG; + return present_diag(145, E_INVALIDARG); // Both paths read ppResources[0] only: a plane with several resources would silently lose the others and could show // the wrong frame, so it is refused (before anything is presented) until it is modelled. What the console does // with ResourceCount above 1 (views? stereo?) is unmeasured. if (plane.ResourceCount != 1) { log_once(logged_resource_count_, "PresentX plane with ResourceCount other than 1: not implemented, refused"); - return DXGI_ERROR_UNSUPPORTED; + return present_diag(__LINE__, DXGI_ERROR_UNSUPPORTED); } } // Only a token that was never handed out is refused. Null, stale and repeated tokens are presented anyway (what the // console does with them is unmeasured, and a title that does it must not freeze); each kind is logged once. FramePacer::TokenIssue issue{}; if (const std::int32_t checked = pacer_.check_present_token(token, &issue); checked != hr::ok) - return from_pacer(checked); + return present_diag(158, from_pacer(checked)); switch (issue) { case FramePacer::TokenIssue::null_token: log_once(logged_null_token_, "PresentX with the null token: presented anyway (real behaviour unmeasured)"); @@ -239,10 +261,21 @@ HRESULT XboxPresentation::present_x(UINT plane_count, const XboxPresentPlanePara // Plane 1 is composed over plane 0 only when flagged an overlay (hypothesis). Otherwise it is not shown, as before: in // the public HDR sample it is the GameDVR copy of the frame, and blending a plane we cannot tell apart from it risks // drawing the frame twice with an alpha that was never meant to be blended. - const bool overlay = plane_count == 2 && (planes[1].Flags & xbox_plane_flag_overlay) != 0; + // The retail title (GTA VI) presents two planes with Flags 0 on both: plane 0 is the scene, plane 1 is the target + // its front end draws on (loading screen, prompts, UI), cleared to transparent every frame, and its own + // UI-over-scene composite is skipped in that mode, so the display blends plane 1 over plane 0 (read from the + // title's code: docs/re/notes/firstframe.md, F14). So a second plane is composed over the first whether or + // not it carries the overlay flag. LEONIDA_PRESENT_PLANE1=0 shows plane 0 alone, as before. + static const bool plane1_always = [] { + wchar_t value[2]{}; + return !(GetEnvironmentVariableW(L"LEONIDA_PRESENT_PLANE1", value, 2) == 1 && value[0] == L'0'); + }(); + const bool overlay = plane_count == 2 && (plane1_always || (planes[1].Flags & xbox_plane_flag_overlay) != 0); if (plane_count == 2 && !overlay) log_once(logged_planes_, "PresentX with 2 planes and no overlay flag on plane 1: only plane 0 is shown (plane 1 is taken " "as the GameDVR copy of the frame)"); + else if (plane_count == 2) + log_once(logged_planes_, "PresentX with 2 planes: plane 1 is blended over plane 0"); const bool compose = hdr0 || placement(planes[0]) || filter_of(planes[0]) != xbox_scale_filter_default || overlay; if (compose) { @@ -256,12 +289,12 @@ HRESULT XboxPresentation::present_x(UINT plane_count, const XboxPresentPlanePara const XboxPresentPlaneParameters& p = planes[i]; ID3D12Resource* source = p.ppResources[0]; const D3D12_RESOURCE_DESC source_desc = source->GetDesc(); - if (source_desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) return E_INVALIDARG; + if (source_desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) return present_diag(222, E_INVALIDARG); const D3D12_RECT* source_rect = p.pSrcViewRects; if (source_rect && (source_rect->left < 0 || source_rect->top < 0 || source_rect->left >= source_rect->right || source_rect->top >= source_rect->bottom || UINT64(source_rect->right) > source_desc.Width || UINT(source_rect->bottom) > source_desc.Height)) - return E_INVALIDARG; + return present_diag(227, E_INVALIDARG); const XboxViewRect* place = placement(p); leonida::PresentPlane& out = composed.plane[i]; out.source = resource_id(source); @@ -285,7 +318,7 @@ HRESULT XboxPresentation::present_x(UINT plane_count, const XboxPresentPlanePara tear = leonida::decide_present_sync(timing.late_us, timing.period_us, threshold) == leonida::PresentSync::immediate; } const HRESULT result = presenter_->present_planes(composed, sync_interval, tear); - if (FAILED(result)) return pacer_.suspended() ? from_pacer(hr::invalid_state) : result; + if (FAILED(result)) return present_diag(251, pacer_.suspended() ? from_pacer(hr::invalid_state) : result); pacer_.commit_present_token(token, plane_count, tear && presenter_->last_present_tore() ? leonida::PresentSync::immediate : leonida::PresentSync::vblank); @@ -296,7 +329,7 @@ HRESULT XboxPresentation::present_x(UINT plane_count, const XboxPresentPlanePara const XboxPresentPlaneParameters& plane = planes[0]; ID3D12Resource* resource = plane.ppResources[0]; const D3D12_RESOURCE_DESC desc = resource->GetDesc(); - if (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) return E_INVALIDARG; + if (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) return present_diag(262, E_INVALIDARG); D3D12_HEAP_PROPERTIES heap{}; D3D12_HEAP_FLAGS heap_flags = D3D12_HEAP_FLAG_NONE; if (SUCCEEDED(resource->GetHeapProperties(&heap, &heap_flags)) && !(heap_flags & D3D12_HEAP_FLAG_ALLOW_DISPLAY)) @@ -305,7 +338,7 @@ HRESULT XboxPresentation::present_x(UINT plane_count, const XboxPresentPlanePara const D3D12_RECT* rect = plane.pSrcViewRects; if (rect && (rect->left < 0 || rect->top < 0 || rect->left >= rect->right || rect->top >= rect->bottom || UINT64(rect->right) > desc.Width || UINT(rect->bottom) > desc.Height)) - return E_INVALIDARG; + return present_diag(271, E_INVALIDARG); // How late the frame is, now that everything that can refuse it has: past the vblank it was due at, by what part of // the interval the scan has moved on. The presenter says whether it really queued it as a tear. @@ -316,7 +349,7 @@ HRESULT XboxPresentation::present_x(UINT plane_count, const XboxPresentPlanePara tear = leonida::decide_present_sync(timing.late_us, timing.period_us, threshold) == leonida::PresentSync::immediate; } const HRESULT result = presenter_->present(resource, sync_interval, rect, tear); - if (FAILED(result)) return pacer_.suspended() ? from_pacer(hr::invalid_state) : result; + if (FAILED(result)) return present_diag(282, pacer_.suspended() ? from_pacer(hr::invalid_state) : result); pacer_.commit_present_token(token, plane_count, tear && presenter_->last_present_tore() ? leonida::PresentSync::immediate : leonida::PresentSync::vblank); diff --git a/runtime/shims/xbox_present.h b/runtime/shims/xbox_present.h index 6230d82eae..4f56db3d80 100644 --- a/runtime/shims/xbox_present.h +++ b/runtime/shims/xbox_present.h @@ -100,7 +100,8 @@ class XboxPresentation { public: // `clock` null: real time (a steady high-resolution timer). Tests pass a leonida::ManualFrameClock, which must // outlive this object. `presenter` is what create_window_presenter returned. - explicit XboxPresentation(std::unique_ptr presenter, leonida::FrameClock* clock = nullptr); + explicit XboxPresentation(std::unique_ptr presenter, leonida::FrameClock* clock = nullptr, + std::shared_ptr tokens = nullptr); ~XboxPresentation(); XboxPresentation(const XboxPresentation&) = delete; XboxPresentation& operator=(const XboxPresentation&) = delete; diff --git a/runtime/shims/xg_xs.cpp b/runtime/shims/xg_xs.cpp index b45fbf689a..8b6b816a7e 100644 --- a/runtime/shims/xg_xs.cpp +++ b/runtime/shims/xg_xs.cpp @@ -1,90 +1,309 @@ -// xg_xs.dll: the console's texture layout library. The game executable (1.0.2.1) imports two functions from it. -// -// Measured from the call sites in the executable, read statically (shapes and checks only): -// HRESULT XGSuggestSwizzleMode(const desc*, 0, uint32_t* mode) -// 2 call sites, both in the game's helper that fills a texture description before XGCreateTextureComputer. The -// out pointer is a 32-bit field of that description, which the helper first sets to 0 and, when the mode is -// known, writes itself as 0x100 | mode. The HRESULT is only passed back up; no caller branches on it. -// HRESULT XGCreateTextureComputer(const desc*, computer** out) -// 4 call sites. Two test the HRESULT and take their failure path when it is negative; two ignore it and call -// through *out at once. On the computer the callers use vtable slot 1 after they are done (3 sites, read as -// Release; no site calls slot 0, read as AddRef, nor QueryInterface), slot 2 with one out pointer to a large -// stack structure (2 sites), slot 8 with six arguments in a loop over subresources (1 site) and slot 10 with -// seven arguments (1 site). No site reads the return value of slots 2, 8 or 10. -// -// The runtime has no model of the console's resource layout (runtime/src/gfx10_tiling.h covers two swizzle modes of -// one 2D level, without mips or the layout structure slot 2 fills), so nothing here computes a layout: -// - XGSuggestSwizzleMode returns E_NOTIMPL and writes nothing, so the field keeps the 0 the caller put there. -// - XGCreateTextureComputer returns E_NOTIMPL, but still stores a computer in *out. The two checking callers then -// fail cleanly; the two that do not check would otherwise call through a null pointer. COM says *out is null on -// failure; this breaks that on purpose, because the measured callers need it. -// - Slot 0 and slot 1 count nothing (the computer is one static object). Every other slot, up to kSlots, prints its -// index and caller once and returns E_NOTIMPL without writing its arguments, so a caller's own zero-filled outputs -// stay zero and a stack structure the caller did not fill stays as it was. -// Hypothesis, not measured: slots 0 and 1 being AddRef and Release; the meaning of slots 2, 8 and 10; that callers -// reach no slot above kSlots - 1 (the computer is also stored in an object at one site and may be called later). +// xg_xs.dll: Xbox Series texture layout and CPU copies. The object has an +// Xbox vtable (AddRef and Release first, with no QueryInterface). #include #include #include #include +#include #include #include +#include +#include +#include #include #include "shims.h" +#include "xg_xs_layout.h" +#include "../src/title_page_watch.h" namespace { -constexpr HRESULT kNotImpl = static_cast(rt::shims::kENotImpl); +using namespace rt::xg_xs; constexpr size_t kSlots = 32; -// Prints once per entry point; `slot` is the vtable index for a computer method, or -1 for an export. -void warn_once(std::atomic& warned, const char* what, int slot, const void* caller) { - if (warned.exchange(true, std::memory_order_relaxed)) return; - char name[64]; - if (slot < 0) std::snprintf(name, sizeof(name), "%s", what); - else std::snprintf(name, sizeof(name), "%s%d", what, slot); - std::fprintf(stderr, "[rt] xg_xs: %s: no console texture layout on the PC; E_NOTIMPL (caller %s, logged once)\n", - name, rt::shims::module_offset(reinterpret_cast(caller)).c_str()); +struct Computer { + const void* const* vtable; + std::atomic refs{1}; + Texture texture; +}; + +void trace(std::atomic& calls, const char* name, const void* caller, const char* format, ...) { + static const bool enabled = [] { + char value[2]{}; + return GetEnvironmentVariableA("LEONIDA_XG_TRACE", value, sizeof(value)) == 1 && value[0] == '1'; + }(); + if (!enabled) return; + const unsigned call = calls.fetch_add(1, std::memory_order_relaxed) + 1; + if (call > 1024) return; + char details[512]; + va_list args; + va_start(args, format); + std::vsnprintf(details, sizeof(details), format, args); + va_end(args); + std::fprintf(stderr, "[rt] xg_xs: LOCAL DIAGNOSTIC: %s #%u caller=%s %s\n", + name, call, rt::shims::module_offset(reinterpret_cast(caller)).c_str(), details); } -ULONG __stdcall computer_add_ref(void*) { return 1; } -ULONG __stdcall computer_release(void*) { return 1; } +void trace_desc(std::atomic& calls, const char* name, const void* caller, + const ResourceDesc* desc, const void* out, uint32_t options, + HRESULT hr, uint32_t mode, uint64_t bytes) { + if (!desc) { + trace(calls, name, caller, "desc=null out=%p options=%#x hr=0x%08x", out, options, uint32_t(hr)); + return; + } + trace(calls, name, caller, + "dim=%u %llux%ux%u mips=%u fmt=%u samples=%u quality=%u align=%llu layout=%#x flags=%#x " + "options=%#x out=%p hr=0x%08x mode=%#x bytes=%llu", + desc->dimension, static_cast(desc->width), desc->height, unsigned(desc->depth_or_array), + unsigned(desc->mips), desc->format, desc->samples, desc->quality, static_cast(desc->alignment), + desc->layout, desc->flags, options, out, uint32_t(hr), mode, static_cast(bytes)); +} -template -HRESULT __stdcall computer_slot(void*) { - static std::atomic warned{false}; - warn_once(warned, "texture computer slot ", static_cast(Slot), _ReturnAddress()); - return kNotImpl; +ULONG __stdcall add_ref(Computer* self) { + static std::atomic calls{0}; + const ULONG refs = self->texture.layout.planes ? self->refs.fetch_add(1, std::memory_order_relaxed) + 1 : 1; + trace(calls, "slot 0", _ReturnAddress(), "this=%p refs=%lu", self, refs); + return refs; } -template -constexpr auto make_vtable(std::index_sequence) { - return std::array{ - (Slot == 0 ? reinterpret_cast(&computer_add_ref) - : Slot == 1 ? reinterpret_cast(&computer_release) - : reinterpret_cast(&computer_slot))...}; +ULONG __stdcall release(Computer* self) { + static std::atomic calls{0}; + const ULONG refs = self->texture.layout.planes ? self->refs.fetch_sub(1, std::memory_order_acq_rel) - 1 : 1; + trace(calls, "slot 1", _ReturnAddress(), "this=%p refs=%lu", self, refs); + if (!refs) delete self; + return refs; } -const auto kVtable = make_vtable(std::make_index_sequence{}); -struct Computer { - const void* const* vtable; +HRESULT __stdcall get_layout(Computer* self, ResourceLayout* out) { + static std::atomic calls{0}; + const auto& layout = self->texture.layout; + const HRESULT hr = !layout.planes ? E_NOTIMPL : !out ? E_POINTER : S_OK; + trace(calls, "slot 2", _ReturnAddress(), "this=%p out=%p hr=0x%08x bytes=%llu align=%llu mips=%u planes=%u", + self, out, uint32_t(hr), static_cast(layout.size), + static_cast(layout.alignment), layout.mips, layout.planes); + if (SUCCEEDED(hr)) { + *out = {layout.size, layout.alignment, layout.mips, layout.planes, {layout.plane[0]}, layout.dimension, 0}; + } + return hr; +} + +uint64_t __stdcall get_size(Computer* self) { + static std::atomic calls{0}; + const uint64_t bytes = self->texture.layout.size; + trace(calls, "slot 3", _ReturnAddress(), "this=%p bytes=%llu", self, static_cast(bytes)); + return bytes; +} + +uint64_t __stdcall get_alignment(Computer* self) { + static std::atomic calls{0}; + const uint64_t bytes = self->texture.layout.alignment; + trace(calls, "slot 4", _ReturnAddress(), "this=%p bytes=%llu", self, static_cast(bytes)); + return bytes; +} + +uint64_t __stdcall get_mip_offset(Computer* self, uint32_t plane, uint32_t level) { + static std::atomic calls{0}; + const auto& layout = self->texture.layout; + const uint64_t offset = plane < layout.planes && level < layout.mips ? layout.plane[plane].mips[level].offset : 0; + trace(calls, "slot 5", _ReturnAddress(), "this=%p plane=%u mip=%u offset=%llu", + self, plane, level, static_cast(offset)); + return offset; +} + +uint64_t __stdcall get_element_offset(Computer* self, uint32_t plane, uint32_t level, + uint64_t x, uint32_t y, uint32_t z, uint32_t sample, uint32_t* bit) { + static std::atomic calls{0}; + const auto& t = self->texture; + uint64_t offset = 0; + if (bit) *bit = 0; + if (plane < t.layout.planes && level < t.layout.mips && sample == 0) { + const auto& mip = t.layout.plane[plane].mips[level]; + if (x < mip.width_elements && y < mip.height_elements && z < mip.depth) { + const ElementAddress address(t); + offset = address.offset(mip, address.tail_origin(mip), uint32_t(x), y, z); + } + } + trace(calls, "slot 6", _ReturnAddress(), "this=%p plane=%u mip=%u x=%llu y=%u z=%u sample=%u bit=%p offset=%llu", + self, plane, level, static_cast(x), y, z, sample, bit, + static_cast(offset)); + return offset; +} + +template +HRESULT copy_subresource(const Texture& t, uint32_t plane, uint32_t subresource, uint32_t sample, + const void* src, void* dst, uint32_t row_pitch, uint32_t slice_pitch) { + const auto& layout = t.layout; + if (!layout.planes) return E_NOTIMPL; + if (!src || !dst) return E_POINTER; + if (plane >= layout.planes || subresource >= layout.mips * t.array || sample) return E_INVALIDARG; + const auto& mip = layout.plane[plane].mips[subresource % layout.mips]; + const uint32_t slice = subresource / layout.mips; + const uint32_t row_bytes = mip.width_elements * t.format.bytes; + if (row_pitch < row_bytes) return E_INVALIDARG; + const uint32_t depth = t.layout.dimension == kTexture3D ? mip.depth : 1; + const uint64_t one_slice = uint64_t(row_pitch) * (mip.height_elements - 1) + row_bytes; + if (depth > 1 && slice_pitch < one_slice) return E_INVALIDARG; + const uint64_t linear_size = uint64_t(slice_pitch) * (depth - 1) + one_slice; + const auto source = static_cast(src); + auto destination = static_cast(dst); + if (leonida::gfx10::tiling_detail::overlap( + {source, Into ? linear_size : layout.size}, {destination, Into ? layout.size : linear_size})) + return E_INVALIDARG; + std::vector columns; + copy_elements(t, subresource % layout.mips, slice, source, destination, row_pitch, slice_pitch, columns); + return S_OK; +} + +HRESULT __stdcall copy_into(Computer* self, void* dst, uint32_t plane, uint32_t sub, const void* src, + uint32_t row, uint32_t slice) { + static std::atomic calls{0}; + const HRESULT hr = copy_subresource(self->texture, plane, sub, 0, src, dst, row, slice); + // The texture's image on the PC GPU is filled from this memory: tell the D3D12 layer it changed. + if (SUCCEEDED(hr)) leonida::title_texel_writes::note(dst, size_t(self->texture.layout.size)); + trace(calls, "slot 8", _ReturnAddress(), "this=%p dst=%p plane=%u sub=%u src=%p row=%u slice=%u hr=0x%08x", + self, dst, plane, sub, src, row, slice, uint32_t(hr)); + return hr; +} + +HRESULT __stdcall copy_from(Computer* self, void* dst, uint32_t plane, uint32_t sub, uint32_t sample, + const void* src, uint32_t row, uint32_t slice) { + static std::atomic calls{0}; + const HRESULT hr = copy_subresource(self->texture, plane, sub, sample, src, dst, row, slice); + trace(calls, "slot 9", _ReturnAddress(), "this=%p dst=%p plane=%u sub=%u sample=%u src=%p row=%u slice=%u hr=0x%08x", + self, dst, plane, sub, sample, src, row, slice, uint32_t(hr)); + return hr; +} + +struct PackedMips { + uint8_t standard, packed; + uint16_t reserved; + uint32_t tiles, start; }; -Computer g_computer{kVtable.data()}; +struct TileShape { uint32_t width, height, depth; }; +struct SubresourceTiling { uint32_t width; uint16_t height, depth; uint32_t start; }; +static_assert(sizeof(PackedMips) == 12 && sizeof(TileShape) == 12 && sizeof(SubresourceTiling) == 12); + +HRESULT __stdcall get_tiling(Computer* self, uint32_t* total_tiles, PackedMips* packed, TileShape* shape, + uint32_t* count, uint32_t first, SubresourceTiling* tilings) { + static std::atomic calls{0}; + const auto& t = self->texture; + const auto& layout = t.layout; + const auto& p = layout.plane[0]; + const unsigned requested = count ? *count : 0; + const bool supported = layout.alignment == kTileBytes && layout.dimension == kTexture2D; + const HRESULT hr = !layout.planes ? E_NOTIMPL : !supported ? E_FAIL : S_OK; + const uint32_t tiles = supported ? uint32_t(layout.size / kTileBytes) : 0; + unsigned written = 0; + if (SUCCEEDED(hr)) { + if (total_tiles) *total_tiles = tiles; + if (packed) *packed = {uint8_t(p.standard_mips), uint8_t(p.tail_mips), 0, p.tail_mips ? 1u : 0u, 0}; + if (shape) *shape = {t.tile_width * t.format.side, t.tile_height * t.format.side, 1}; + const uint32_t total_subresources = t.array * layout.mips; + if (count && first < total_subresources) { + const uint32_t end = std::min(requested, total_subresources - first); + for (uint32_t i = 0; i < end; ++i) { + const uint32_t sub = first + i; + const uint32_t level = sub % layout.mips; + if (level >= p.standard_mips) continue; + ++written; + if (!tilings) continue; + const auto& mip = p.mips[level]; + const uint64_t start_bytes = (sub / layout.mips) * p.slice_bytes + mip.offset; + tilings[i] = {mip.padded_width / t.tile_width, uint16_t(mip.padded_height / t.tile_height), 1, + uint32_t(start_bytes / kTileBytes)}; + } + } + if (count) *count = written; + } + trace(calls, "slot 10", _ReturnAddress(), + "this=%p total=%p packed=%p shape=%p count=%p first=%u out=%p requested=%u written=%u " + "hr=0x%08x tiles=%u standard=%u tail=%u tile=%ux%u", + self, total_tiles, packed, shape, count, first, tilings, requested, written, uint32_t(hr), + tiles, p.standard_mips, p.tail_mips, t.tile_width * t.format.side, t.tile_height * t.format.side); + return hr; +} + +template +HRESULT __stdcall unimplemented_slot(Computer* self) { + static std::atomic calls{0}; + trace(calls, "unknown slot", _ReturnAddress(), "this=%p slot=%zu hr=0x80004001", self, Slot); + return E_NOTIMPL; +} + +template +auto make_vtable(std::index_sequence) { + std::array vtable{reinterpret_cast(&unimplemented_slot)...}; + vtable[0] = reinterpret_cast(&add_ref); + vtable[1] = reinterpret_cast(&release); + vtable[2] = reinterpret_cast(&get_layout); + vtable[3] = reinterpret_cast(&get_size); + vtable[4] = reinterpret_cast(&get_alignment); + vtable[5] = reinterpret_cast(&get_mip_offset); + vtable[6] = reinterpret_cast(&get_element_offset); + vtable[8] = reinterpret_cast(©_into); + vtable[9] = reinterpret_cast(©_from); + vtable[10] = reinterpret_cast(&get_tiling); + return vtable; +} +const auto kVtable = make_vtable(std::make_index_sequence{}); +Computer unavailable{kVtable.data(), {1}, {}}; -HRESULT __stdcall XGCreateTextureComputer(const void* /*desc*/, void** out) { - static std::atomic warned{false}; - warn_once(warned, "XGCreateTextureComputer", -1, _ReturnAddress()); - if (!out) return E_POINTER; - *out = &g_computer; // see the top of the file: two measured callers use *out without checking the HRESULT - return kNotImpl; +HRESULT __stdcall XGCreateTextureComputer(const void* desc, void** out) { + static std::atomic calls{0}; + ResourceDesc d{}; + if (desc) std::memcpy(&d, desc, sizeof(d)); + Texture t; + HRESULT hr = E_NOTIMPL; + if (!out) hr = E_POINTER; + else { + // Two measured callers dereference the computer even after a failed creation. + *out = &unavailable; + if (!desc) hr = E_INVALIDARG; + else if (build_texture(d, t)) { + auto* computer = new (std::nothrow) Computer{kVtable.data(), {1}, t}; + hr = computer ? S_OK : E_OUTOFMEMORY; + if (computer) *out = computer; + // How the title lays out a texture of this shape (title_xg_layouts): what its CPU writes use. + leonida::title_xg_layouts::note({d.dimension, d.format, d.height, d.depth_or_array, d.mips, d.width}, + d.layout); + } + } + trace_desc(calls, "create", _ReturnAddress(), desc ? &d : nullptr, out, 0, hr, t.mode, t.layout.size); + // LOCAL DIAGNOSTIC: LEONIDA_XG_TRACE_FORMAT= logs the first 256 computers of that format whatever + // LEONIDA_XG_TRACE's cap, with the layout the title asked for (which tiling its CPU writes use). + static const uint32_t only = [] { + char value[8]{}; + return GetEnvironmentVariableA("LEONIDA_XG_TRACE_FORMAT", value, sizeof(value)) ? uint32_t(atoi(value)) : 0u; + }(); + static std::atomic only_logged{0}; + if (only && desc && d.format == only && only_logged.fetch_add(1, std::memory_order_relaxed) < 256) + std::fprintf(stderr, + "[rt] xg_xs: LOCAL DIAGNOSTIC: computer for format %u: dim=%u %llux%ux%u mips=%u layout=%#x " + "flags=%#x -> mode %u, %llu bytes, hr 0x%08x, caller %s\n", + d.format, d.dimension, static_cast(d.width), d.height, + unsigned(d.depth_or_array), unsigned(d.mips), d.layout, d.flags, t.mode, + static_cast(t.layout.size), uint32_t(hr), + rt::shims::module_offset(reinterpret_cast(_ReturnAddress())).c_str()); + return hr; } -HRESULT __stdcall XGSuggestSwizzleMode(const void* /*desc*/, uint32_t /*flags*/, uint32_t* /*mode*/) { - static std::atomic warned{false}; - warn_once(warned, "XGSuggestSwizzleMode", -1, _ReturnAddress()); - return kNotImpl; +HRESULT __stdcall XGSuggestSwizzleMode(const void* desc, uint32_t options, uint32_t* out) { + static std::atomic calls{0}; + ResourceDesc d{}; + if (desc) std::memcpy(&d, desc, sizeof(d)); + HRESULT hr = E_INVALIDARG; + uint32_t mode = 0; + if (desc && out && d.dimension >= kTexture1D && d.dimension <= kTexture3D && d.width) { + hr = E_NOTIMPL; + if (!options) { + mode = kSwizzled | select_mode(d); + *out = mode; + hr = S_OK; + } + } + trace_desc(calls, "suggest", _ReturnAddress(), desc ? &d : nullptr, out, options, hr, mode, 0); + return hr; } } // namespace diff --git a/runtime/shims/xg_xs_THIRD_PARTY.md b/runtime/shims/xg_xs_THIRD_PARTY.md new file mode 100644 index 0000000000..c0dfc9e174 --- /dev/null +++ b/runtime/shims/xg_xs_THIRD_PARTY.md @@ -0,0 +1,50 @@ +# XG texture layout references + +The thin surface size, mip order and packed mip tail rules in +`xg_xs_layout.h` use AMD addrlib's GFX10 implementation. The +`k64kbStandard` and `k4kbStandard3D` equations come from AMD's RB+ tables. +The source pin is [Mesa 26.2.0 addrlib][amd], in +`src/gfx10/gfx10addrlib.cpp` and `src/gfx10/gfx10SwizzlePattern.h`. +The existing Leonida detiler supplies the 2D 4 KiB standard and 64 KiB +display equations. + +The Series descriptor and texture computer ABI and the BC7 fixture +were cross-checked with [VIctory, commit 2849477][victory], GPL-3.0-or-later, +in `crates/victory-hle/src/modules/xg.rs`. The output structure sizes were +also checked against [xbox-emulator, commit 410e01f][xbox-emulator], +GPL-3.0, in `crates/compat/xg_xs/src/{computer,layout}.rs`. + +xcl (GPL-2.0-only) provided evidence about GFX10 mip ordering, compressed +block units and the slot 10 contract. TuxBox (unlicensed) provided +published differential coverage for tile shapes and mode selection. +Both were references for behavior. The swizzle equations used here +come from the original MIT-licensed AMD sources. + +[amd]: https://gitlab.freedesktop.org/mesa/mesa/-/tree/mesa-26.2.0/src/amd/addrlib +[victory]: https://github.com/Marvisak/VIctory/tree/2849477 +[xbox-emulator]: https://github.com/omonkeyz/xbox-emulator/tree/410e01f + +## AMD addrlib + +Copyright (C) 2007-2026 Advanced Micro Devices, Inc. All rights reserved. +Copyright (C) 2007-2024 Advanced Micro Devices, Inc. All rights reserved. + +SPDX-License-Identifier: MIT + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/runtime/shims/xg_xs_layout.h b/runtime/shims/xg_xs_layout.h new file mode 100644 index 0000000000..57492f9337 --- /dev/null +++ b/runtime/shims/xg_xs_layout.h @@ -0,0 +1,410 @@ +#pragma once + +#include "../src/gfx10_tiling.h" + +// AMD addrlib equations and license: see xg_xs_THIRD_PARTY.md. + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace rt::xg_xs { + +// D3D12_RESOURCE_DESC ABI, with the Xbox layout encoding in the layout field. +struct ResourceDesc { + uint32_t dimension; + uint64_t alignment, width; + uint32_t height; + uint16_t depth_or_array, mips; + uint32_t format, samples, quality, layout, flags; +}; +static_assert(sizeof(ResourceDesc) == 0x38 && offsetof(ResourceDesc, layout) == 0x2c); + +constexpr uint32_t kSwizzled = 0x100; +constexpr uint32_t kLinear = 0, k4kbS = 5, k64kbS = 9, k64kbD = 10, k64kbZX = 24, k64kbRX = 27; +constexpr uint32_t kTexture1D = 2, kTexture2D = 3, kTexture3D = 4; +constexpr uint32_t kTextureDisplay = 0x08000000; +constexpr uint32_t kRenderTarget = 1, kDepthStencil = 2; +constexpr unsigned kMaxMips = 15; +constexpr uint32_t kTileBytes = 65536; + +inline uint32_t select_mode(const ResourceDesc& desc) { + if (desc.layout == 1) return kLinear; + if ((desc.layout & ~0x1fu) == kSwizzled) return desc.layout & 0x1f; + if (desc.flags & kDepthStencil) return k64kbZX; + if (desc.flags & kTextureDisplay) return k64kbD; + if (desc.flags & kRenderTarget) return k64kbRX; + return desc.dimension >= kTexture2D ? k4kbS : kLinear; +} + +struct Format { + uint32_t bytes = 0; + uint32_t side = 1; +}; + +inline Format format_info(uint32_t f) { + // DXGI's typed and typeless variants occupy consecutive values within a storage family. + if (f >= DXGI_FORMAT_R32G32B32A32_TYPELESS && f <= DXGI_FORMAT_R32G32B32A32_SINT) return {16, 1}; + if (f >= DXGI_FORMAT_R16G16B16A16_TYPELESS && f <= DXGI_FORMAT_R32G32_SINT) return {8, 1}; + if (f >= DXGI_FORMAT_R10G10B10A2_TYPELESS && f <= DXGI_FORMAT_R32_SINT) return {4, 1}; + if (f >= DXGI_FORMAT_R8G8_TYPELESS && f <= DXGI_FORMAT_R16_SINT) return {2, 1}; + if (f >= DXGI_FORMAT_R8_TYPELESS && f <= DXGI_FORMAT_A8_UNORM) return {1, 1}; + if (f == DXGI_FORMAT_R9G9B9E5_SHAREDEXP) return {4, 1}; + if (f >= DXGI_FORMAT_BC1_TYPELESS && f <= DXGI_FORMAT_BC1_UNORM_SRGB) return {8, 4}; + if (f >= DXGI_FORMAT_BC2_TYPELESS && f <= DXGI_FORMAT_BC3_UNORM_SRGB) return {16, 4}; + if (f >= DXGI_FORMAT_BC4_TYPELESS && f <= DXGI_FORMAT_BC4_SNORM) return {8, 4}; + if (f >= DXGI_FORMAT_BC5_TYPELESS && f <= DXGI_FORMAT_BC5_SNORM) return {16, 4}; + if (f == DXGI_FORMAT_B5G6R5_UNORM || f == DXGI_FORMAT_B5G5R5A1_UNORM || + f == DXGI_FORMAT_B4G4R4A4_UNORM) return {2, 1}; + if (f >= DXGI_FORMAT_B8G8R8A8_UNORM && f <= DXGI_FORMAT_B8G8R8X8_UNORM_SRGB) return {4, 1}; + if (f >= DXGI_FORMAT_BC6H_TYPELESS && f <= DXGI_FORMAT_BC7_UNORM_SRGB) return {16, 4}; + return {}; +} + +// Xbox Series slot 2 output. The unused planes are zero-filled. +struct MipLayout { + uint64_t size, offset, slice_bytes; + uint32_t pitch_texels, pitch_bytes, alignment; + uint32_t padded_width, padded_height, padded_depth; + uint32_t width_elements, height_elements, width_texels, height_texels; + uint32_t depth, samples, swizzle, reserved0; + uint64_t bank_rotation[2]; + uint32_t tile_depth, in_tail, tail_position, reserved1; +}; +struct PlaneLayout { + uint32_t usage, reserved0; + uint64_t size, slice_bytes, offset, alignment; + uint32_t element_bytes, standard_mips, tail_mips, reserved1; + std::array mips; +}; +template +struct TextureLayout { + uint64_t size, alignment; + uint32_t mips, planes; + std::array plane; + uint32_t dimension, reserved; +}; +using ResourceLayout = TextureLayout<4>; // Slot 2 output ABI. +static_assert(sizeof(MipLayout) == 0x70 && offsetof(MipLayout, bank_rotation) == 0x50); +static_assert(sizeof(PlaneLayout) == 0x6c8 && offsetof(PlaneLayout, mips) == 0x38); +static_assert(sizeof(ResourceLayout) == 0x1b40 && offsetof(ResourceLayout, dimension) == 0x1b38); + +struct Texture { + // build_texture supports single-plane formats. Expand to the ABI layout only in get_layout. + TextureLayout<1> layout{}; + // GFX10 thick blocks interleave mip chains by slabs of tile_depth slices. + struct VolumeMip { uint64_t macro_offset = 0; uint32_t tail_x = 0, tail_y = 0; }; + std::array volume_mips{}; + uint64_t slab_bytes = 0; + Format format; + uint32_t mode = 0, tile_width = 0, tile_height = 0, tile_depth = 1, array = 0; +}; + +inline uint32_t align_up(uint32_t value, uint32_t alignment) { + return (value + alignment - 1) & ~(alignment - 1); +} + +// Thin surface allocation from AMD addrlib's GFX10 rules. The logical size +// contracts by floor division, while physical pitch/height use ShiftCeil on +// the base extent in elements. A slice stores the tail block, then its +// unpacked mips from smallest to largest. +inline bool build_texture(const ResourceDesc& desc, Texture& texture) { + if (desc.dimension < kTexture1D || desc.dimension > kTexture3D || + desc.width == 0 || desc.width > 16384 || desc.height == 0 || desc.height > 16384 || + (desc.dimension == kTexture1D && desc.height != 1) || + desc.depth_or_array == 0 || desc.depth_or_array > 2048 || desc.samples != 1 || desc.quality || + (desc.flags & (kRenderTarget | kDepthStencil)) || + (desc.layout > 1 && (desc.layout & ~0x1fu) != kSwizzled)) + return false; + + const Format format = format_info(desc.format); + if (!format.bytes || (desc.dimension == kTexture1D && format.side != 1)) return false; + const unsigned full_mips = std::bit_width(std::max({uint32_t(desc.width), desc.height, + desc.dimension == kTexture3D ? unsigned(desc.depth_or_array) : 1u})); + const unsigned mips = desc.mips ? desc.mips : full_mips; + if (mips > full_mips) return false; + + const uint32_t mode = select_mode(desc); + unsigned tile_bits; + switch (mode) { + case kLinear: tile_bits = 8; break; + case k4kbS: tile_bits = 12; break; + case k64kbS: case k64kbD: tile_bits = 16; break; + default: return false; + } + const bool volume = desc.dimension == kTexture3D; + if (volume && mode != k4kbS) return false; + if (volume && (mips != 1 || format.side != 1)) { + static const bool enabled = [] { + const char* value = std::getenv("LEONIDA_VOLUME_MIPS"); + return !value || std::strcmp(value, "0") != 0; + }(); + if (!enabled) return false; + } + if (mode != kLinear && desc.dimension == kTexture1D) return false; + + const uint32_t alignment = 1u << tile_bits; + const unsigned element_bits = std::countr_zero(format.bytes); + const unsigned tile_elements = tile_bits - element_bits; + uint32_t tw = mode == kLinear ? alignment / format.bytes : 1u << ((tile_elements + 1) / 2); + uint32_t th = mode == kLinear ? 1 : 1u << (tile_elements / 2); + const uint32_t base_width = align_up(uint32_t(desc.width), format.side) / format.side; + const uint32_t base_height = align_up(desc.height, format.side) / format.side; + + texture = {}; + texture.format = format; + texture.mode = mode; + texture.tile_width = tw; + texture.tile_height = th; + texture.array = volume ? 1u : desc.depth_or_array; + if (volume) { + // Dimensions in elements (4x4 blocks for BC formats). + constexpr uint32_t blocks[5][3] = {{16, 16, 16}, {8, 16, 16}, {8, 16, 8}, {8, 8, 8}, {4, 8, 8}}; + texture.tile_width = tw = blocks[element_bits][0]; + texture.tile_height = th = blocks[element_bits][1]; + texture.tile_depth = blocks[element_bits][2]; + } + + auto& layout = texture.layout; + layout.alignment = alignment; + layout.dimension = desc.dimension; + layout.mips = mips; + layout.planes = 1; + auto& plane = layout.plane[0]; + plane.usage = 1; // data plane + plane.alignment = alignment; + plane.element_bytes = format.bytes; + plane.standard_mips = mips; + // AMD addrlib Gfx10Lib::ComputeSurfaceInfoMacroTiled and Lib::GetMipTailDim. + // A 4 KiB thick block has five tail levels and halves height. BC extents are in blocks. + const unsigned max_tail = volume ? 5u : tile_bits - 4; + uint32_t tail_w = volume ? tw : tw / 2, tail_h = volume ? th / 2 : th; + constexpr uint32_t micro3d[5][3] = {{8,4,8}, {4,4,8}, {4,4,4}, {4,2,4}, {2,2,4}}; + const uint32_t micro_w = volume ? micro3d[element_bits][0] : 1u << ((8 - element_bits + 1) / 2); + const uint32_t micro_h = volume ? micro3d[element_bits][1] : 256 / (format.bytes * micro_w); + uint32_t tail_depth = 0; + + uint64_t chain_bytes = 0; + for (unsigned i = 0; i < mips; ++i) { + auto& mip = plane.mips[i]; + mip.width_texels = std::max(1u, uint32_t(desc.width) >> i); + mip.height_texels = std::max(1u, desc.height >> i); + mip.width_elements = align_up(mip.width_texels, format.side) / format.side; + mip.height_elements = align_up(mip.height_texels, format.side) / format.side; + const uint32_t round = (1u << i) - 1; + const uint32_t physical_w = (base_width + round) >> i; + const uint32_t physical_h = (base_height + round) >> i; + if (mode != kLinear && mips > 1 && plane.standard_mips == mips && + mips - i <= max_tail && physical_w <= tail_w && physical_h <= tail_h) { + plane.standard_mips = i; + plane.tail_mips = mips - i; + chain_bytes = alignment; + tail_depth = (uint32_t(desc.depth_or_array) + round) >> i; + } + + mip.depth = volume ? std::max(1u, uint32_t(desc.depth_or_array) >> i) : desc.depth_or_array; + mip.padded_depth = volume ? align_up((uint32_t(desc.depth_or_array) + round) >> i, texture.tile_depth) : mip.depth; + mip.samples = 1; + mip.tile_depth = texture.tile_depth; + mip.in_tail = i >= plane.standard_mips; + if (mip.in_tail) { + const unsigned index = max_tail - 1 - (i - plane.standard_mips); + mip.offset = index > 6 ? 16u << index : index * 256u; + if (volume) { + texture.volume_mips[i].tail_x = ((index >> 1) & 1u) * micro_w; + texture.volume_mips[i].tail_y = ((index & 1u) | ((index >> 1) & 2u)) * micro_h; + mip.offset *= align_up(tail_depth, micro3d[element_bits][2]) / micro3d[element_bits][2]; + } + mip.alignment = 256; + mip.swizzle = mode == k64kbD ? 2 : 1; // 256 B microtile of the same family + mip.padded_width = tail_w; + mip.padded_height = tail_h; + tail_w = std::max(tail_w / 2, micro_w); + tail_h = std::max(tail_h / 2, micro_h); + } else { + mip.alignment = alignment; + mip.swizzle = mode; + mip.padded_width = align_up(physical_w, tw); + mip.padded_height = align_up(physical_h, th); + } + mip.pitch_texels = mip.padded_width * format.side; + mip.pitch_bytes = mip.padded_width * format.bytes; + mip.slice_bytes = uint64_t(mip.pitch_bytes) * mip.padded_height; + mip.size = mip.slice_bytes * (volume ? mip.padded_depth : 1u); + } + if (volume) { + uint64_t macro = chain_bytes; + chain_bytes *= align_up(tail_depth, texture.tile_depth) / texture.tile_depth; + for (unsigned i = plane.standard_mips; i > 0; --i) { + auto& mip = plane.mips[i - 1]; + texture.volume_mips[i - 1].macro_offset = macro; + mip.offset = chain_bytes; + macro += mip.slice_bytes * texture.tile_depth; + chain_bytes += mip.size; + } + texture.slab_bytes = macro; + plane.size = layout.size = macro * (align_up(desc.depth_or_array, texture.tile_depth) / texture.tile_depth); + plane.slice_bytes = mips == 1 ? plane.size : macro / texture.tile_depth; + return true; + } + for (unsigned i = plane.standard_mips; i > 0; --i) { + auto& mip = plane.mips[i - 1]; + mip.offset = chain_bytes; + chain_bytes += mip.size; + } + plane.slice_bytes = chain_bytes; + plane.size = layout.size = chain_bytes * texture.array; + return true; +} + + +// These RB+ equation rows come directly from AMD addrlib. The other two +// non-XOR modes already have equations in Leonida's GFX10 detiler. +inline constexpr int k64kbStandard[5][16] = { + {1, 2, 3, 4, -1, -2, -3, -4, -5, 5, -6, 6, -7, 7, -8, 8}, + {0, 1, 2, 3, -1, -2, -3, 4, -4, 5, -5, 6, -6, 7, -7, 8}, + {0, 0, 1, 2, -1, -2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7}, + {0, 0, 0, 1, -1, -2, 2, 3, -3, 4, -4, 5, -5, 6, -6, 7}, + {0, 0, 0, 0, -1, -2, 1, 2, -3, 3, -4, 4, -5, 5, -6, 6}, +}; +inline constexpr int k4kbStandard3D[5][12] = { + {1, 2, 17, -1, 18, -2, 3, 19, -3, 4, 20, -4}, + {0, 1, 17, -1, 18, -2, 2, 19, -3, 3, 20, -4}, + {0, 0, 1, -1, 17, -2, 2, 18, -3, 3, 19, -4}, + {0, 0, 0, 1, 17, -1, 2, 18, -2, 3, 19, -3}, + {0, 0, 0, 0, 17, -1, 1, 18, -2, 2, 19, -3}, +}; + +struct ElementAddress { + explicit ElementAddress(const Texture& texture) : texture(texture) { + const unsigned i = std::countr_zero(texture.format.bytes); + switch (texture.mode) { + case k4kbS: + pattern = texture.tile_depth == 1 ? leonida::gfx10::tiling_detail::patterns_4k[i] : k4kbStandard3D[i]; + break; + case k64kbS: pattern = k64kbStandard[i]; break; + case k64kbD: pattern = leonida::gfx10::tiling_detail::patterns_64k[i]; break; + default: return; + } + bits = std::countr_zero(texture.layout.alignment); + const uint32_t dims[] = {texture.tile_width, texture.tile_height, texture.tile_depth}; + for (unsigned b = 0; b < bits; ++b) { + if (!pattern[b]) continue; + const auto [axis, shift] = coordinate(pattern[b]); + for (uint32_t c = 0; c < dims[axis]; ++c) + axis_offset[axis][c] |= ((c >> shift) & 1) << b; + } + } + + std::array tail_origin(const MipLayout& mip) const { + std::array coords{}; + if (mip.in_tail && texture.slab_bytes) { + const auto& sub = texture.volume_mips[&mip - texture.layout.plane[0].mips.data()]; + return {sub.tail_x, sub.tail_y, 0}; + } + if (mip.in_tail && pattern) { + for (unsigned b = 0; b < bits; ++b) { + if (!pattern[b] || !(mip.offset & (1u << b))) continue; + const auto [axis, shift] = coordinate(pattern[b]); + coords[axis] |= 1u << shift; + } + } + return coords; + } + + uint64_t offset(const MipLayout& mip, const std::array& tail, + uint32_t x, uint32_t y, uint32_t z) const { + if (texture.slab_bytes) return volume_row(mip, tail, y, z) + column(mip, tail, x); + const uint64_t slice = z * texture.layout.plane[0].slice_bytes; + if (texture.mode == kLinear) return slice + mip.offset + uint64_t(y) * mip.pitch_bytes + x * texture.format.bytes; + + const uint32_t w = texture.tile_width, h = texture.tile_height; + if (mip.in_tail) { + return slice + axis_offset[0][x + tail[0]] + axis_offset[1][y + tail[1]]; + } + + // Whole blocks are row-major, then the equation selects a byte inside it. + const uint64_t block = uint64_t(y / h) * (mip.padded_width / w) + x / w; + return slice + mip.offset + (block << bits) + axis_offset[0][x & (w - 1)] + axis_offset[1][y & (h - 1)]; + } + + // offset() split into a part that depends only on the row (y, z) and one that depends only on x, so a whole + // row is addressed with one table lookup per element: offset(mip, tail, x, y, z) == row(mip, tail, y, z) + + // column(mip, tail, x). + uint64_t row(const MipLayout& mip, const std::array& tail, uint32_t y, uint32_t z) const { + if (texture.slab_bytes) return volume_row(mip, tail, y, z); + const uint64_t slice = z * texture.layout.plane[0].slice_bytes; + if (texture.mode == kLinear) return slice + mip.offset + uint64_t(y) * mip.pitch_bytes; + if (mip.in_tail) return slice + axis_offset[1][y + tail[1]]; + const uint32_t w = texture.tile_width, h = texture.tile_height; + const uint64_t blocks = uint64_t(y / h) * (mip.padded_width / w); + return slice + mip.offset + (blocks << bits) + axis_offset[1][y & (h - 1)]; + } + uint64_t column(const MipLayout& mip, const std::array& tail, uint32_t x) const { + if (texture.mode == kLinear) return uint64_t(x) * texture.format.bytes; + if (mip.in_tail) return axis_offset[0][x + tail[0]]; + const uint32_t w = texture.tile_width; + return (uint64_t(x / w) << bits) + axis_offset[0][x & (w - 1)]; + } + +private: + uint64_t volume_row(const MipLayout& mip, const std::array& tail, uint32_t y, uint32_t z) const { + const auto& sub = texture.volume_mips[&mip - texture.layout.plane[0].mips.data()]; + const uint64_t block_row = uint64_t(y / texture.tile_height) * (mip.padded_width / texture.tile_width); + return (z / texture.tile_depth) * texture.slab_bytes + sub.macro_offset + (block_row << bits) + + axis_offset[1][(y + tail[1]) % texture.tile_height] + axis_offset[2][z % texture.tile_depth]; + } + + static std::pair coordinate(int bit) { + // Positive 1..16 are X, negative are Y, 17 and above are Z. + if (bit < 0) return {1, unsigned(-bit - 1)}; + if (bit >= 17) return {2, unsigned(bit - 17)}; + return {0, unsigned(bit - 1)}; + } + + const Texture& texture; + const int* pattern = nullptr; + unsigned bits = 0; + uint32_t axis_offset[3][256]{}; +}; + +// The element copy behind XG's CopyIntoSubresource / CopyFromSubresource (xg_xs.cpp) and the D3D12 layer's fill of +// textures the title keeps in its own memory (d3d12_vulkan_device.cpp, TitleTextures): one mip of one array slice +// between the console layout (`tiled`, from the texture's base) and linear rows of elements `row_pitch` bytes apart, +// 3D slices `slice_pitch` apart. Into: linear -> tiled. The callers check the arguments and the buffer sizes +// (`tiled` holds layout.size bytes; linear holds the mip's rows). `columns` is scratch. +template +inline void copy_elements(const Texture& t, uint32_t level, uint32_t slice, const Byte* source, Byte* destination, + uint32_t row_pitch, uint32_t slice_pitch, std::vector& columns) { + const auto& mip = t.layout.plane[0].mips[level]; + const uint32_t bytes = t.format.bytes; + const uint32_t row_bytes = mip.width_elements * bytes; + const uint32_t depth = t.layout.dimension == kTexture3D ? mip.depth : 1; + const ElementAddress address(t); + const auto tail = address.tail_origin(mip); + columns.resize(mip.width_elements); + for (uint32_t x = 0; x < mip.width_elements; ++x) columns[x] = address.column(mip, tail, x); + for (uint32_t z = 0; z < depth; ++z) { + for (uint32_t y = 0; y < mip.height_elements; ++y) { + const uint64_t linear = uint64_t(z) * slice_pitch + uint64_t(y) * row_pitch; + const uint64_t tiled = address.row(mip, tail, y, slice + z); + if (t.mode == kLinear) { + std::memcpy(destination + (Into ? tiled : linear), source + (Into ? linear : tiled), row_bytes); + continue; + } + for (uint32_t x = 0; x < mip.width_elements; ++x) { + const uint64_t at = tiled + columns[x]; + const uint64_t to = linear + uint64_t(x) * bytes; + std::memcpy(destination + (Into ? at : to), source + (Into ? to : at), bytes); + } + } + } +} + +} // namespace rt::xg_xs diff --git a/runtime/shims/xgameruntime.cpp b/runtime/shims/xgameruntime.cpp index 07cccc8d79..741b7d55b7 100644 --- a/runtime/shims/xgameruntime.cpp +++ b/runtime/shims/xgameruntime.cpp @@ -29,12 +29,14 @@ #include #include #include +#include #include #include #include #include +#include "console_identity.h" #include "file_system.h" #include "shims.h" @@ -63,6 +65,8 @@ std::atomic g_runtime_refs{0}; // (no caller in the shipped DLLs to measure), and the classes of the other xgameruntime_*.cpp files through their // query functions; for any other class QueryApiImpl logs the class and interface id and refuses it, so the first boot // with the executable lists the interfaces to implement next. +// +// The thunks look up a sixth name, XErrorReport (served below GetApiVersionImpl), and refuse the runtime without it. struct ApiImplOptions { // InitializeApiImplEx2's fourth argument uint32_t unknown; // documented as always 1 @@ -678,16 +682,9 @@ enum class XSystemDeviceType : uint32_t { }; // XSystemDeviceType XSystemGetDeviceType(). The package is the Xbox Series build, so report Series X (Anaconda). -// LEONIDA_DEVICE_TYPE=<0..8> overrides it, for trying other code paths on day one. -uint32_t __stdcall XSystemGetDeviceType() { - char s[16]; - const DWORD n = GetEnvironmentVariableA("LEONIDA_DEVICE_TYPE", s, sizeof(s)); - if (n > 0 && n < sizeof(s)) { - int v = std::atoi(s); - if (v >= 0 && v <= 8) return static_cast(v); - } - return static_cast(XSystemDeviceType::XboxScarlettAnaconda); -} +// LEONIDA_DEVICE_TYPE=<0..8> overrides it, for trying other code paths on day one. The title's registry read of +// ConsoleMode (console_registry.cpp) is answered from the same setting (console_identity.h), so the two agree. +uint32_t __stdcall XSystemGetDeviceType() { return rt::shims::console_identity::configured_device_type(); } // HRESULT XSystemGetConsoleId(size_t consoleIdSize, char* consoleId, size_t* consoleIdUsed). // XSystemConsoleIdBytes is 39 (including the terminator). An offline PC has no console id, so this returns a @@ -1005,21 +1002,27 @@ bool __stdcall XPackageIsPackagedProcess() { return true; } -// ---- XPackageImpl (asked for as IXPackageImpl3), offline ---- +// ---- XPackageImpl (asked for as IXPackageImpl3 and IXPackageImpl4), offline ---- // // libHttpClient.GDK.dll asks QueryApiImpl for XPackageImpl with IXPackageImpl3's id through 30 thunks (slots 3-19, // 22, 24-27, 30, 32-34, 37-40), each in the argument shape of the method at that position of xgameruntime-docs' // IXPackageImpl (slots 3-34), IXPackageImpl2 (35-38) and IXPackageImpl3 (39-40) lists (docs/runtime_imports.md). +// The retail executable asks with IXPackageImpl4's id (tools/gdk_runtime_calls.py: 18 thunks, slots 3-7, 9, 12, 14, +// 16-19, 25, 26, 34, 37-39; VIctory's xpackage.rs serves the same id), which adds slot 41, XPackageGetPackageKind. // The slots with an offline answer forward to the XPackage functions above (the package identifier, whether the -// process is packaged, the mount path and its size, the user's locale); every other slot logs its number once and -// returns E_NOTIMPL, so the first boot shows which ones the title needs. +// process is packaged, the mount path and its size, the user's locale) or answer for the fully installed package +// (slots 5-19, the installation monitor and the chunks; 39, no content packages to enumerate) or mount a mapped +// content package (37-38); every other slot logs its number once and returns E_NOTIMPL, so the first boot shows which +// ones the title needs. constexpr GUID kPackageClass = {0xaf406016, 0xe850, 0x4aa8, {0xa8, 0x8d, 0x2f, 0x3d, 0xcb, 0x9d, 0xac, 0x7e}}; -// IXPackageImpl3 : IXPackageImpl2 : IXPackageImpl (xgameruntime include/xpackage.idl); the class id is its own. +// IXPackageImpl4 : IXPackageImpl3 : IXPackageImpl2 : IXPackageImpl (xgameruntime include/xpackage.idl; IXPackageImpl4 +// per tools/gdk_runtime_classes.json); the class id is its own. constexpr GUID kPackage1 = {0x3720de07, 0xe8e4, 0x44a3, {0xad, 0x32, 0xb3, 0x59, 0xe8, 0xad, 0xbe, 0x55}}; constexpr GUID kPackage2 = {0xf92d8712, 0x2b27, 0x4d8a, {0xbf, 0x01, 0x11, 0xa6, 0xf8, 0xe3, 0xeb, 0x42}}; constexpr GUID kPackage3 = {0xe2a4734b, 0x2f4a, 0x456d, {0xaa, 0x8f, 0xd0, 0x65, 0xe0, 0x4f, 0xb2, 0x09}}; -const GUID* const kPackageIids[] = {&kPackage1, &kPackage2, &kPackage3, nullptr}; +constexpr GUID kPackage4 = {0x0b9d556e, 0xab70, 0x43f4, {0xba, 0xa0, 0x99, 0x99, 0xac, 0x4c, 0xb0, 0x40}}; +const GUID* const kPackageIids[] = {&kPackage1, &kPackage2, &kPackage3, &kPackage4, nullptr}; template HRESULT STDMETHODCALLTYPE package_not_implemented(void*) { static std::atomic s_logged{false}; @@ -1031,13 +1034,17 @@ HRESULT STDMETHODCALLTYPE pkg_identifier(void*, size_t size, char* buffer) { return XPackageGetCurrentProcessPackageIdentifier(size, buffer); } bool STDMETHODCALLTYPE pkg_is_packaged(void*) { return XPackageIsPackagedProcess(); } -// The package's MicrosoftGame.Config as text, from the game folder (LEONIDA_GAME_DIR, else --game-dir); empty when -// there is no folder or no config. Wide on purpose: a game folder named outside the ANSI code page must reach the file -// intact. -std::string package_config() { +// The package's folder, the game folder (LEONIDA_GAME_DIR, else --game-dir); empty when neither is set. Wide on +// purpose: a game folder named outside the ANSI code page must reach its files intact. +std::filesystem::path package_dir() { wchar_t env[MAX_PATH] = {}; const DWORD n = GetEnvironmentVariableW(L"LEONIDA_GAME_DIR", env, MAX_PATH); - const std::filesystem::path dir = (n > 0 && n < MAX_PATH) ? std::filesystem::path(env) : rt::fs::game_dir(); + return (n > 0 && n < MAX_PATH) ? std::filesystem::path(env) : rt::fs::game_dir(); +} + +// The package's MicrosoftGame.Config as text, from the package folder; empty when there is no folder or no config. +std::string package_config() { + const std::filesystem::path dir = package_dir(); if (dir.empty()) return {}; std::ifstream f(dir / L"MicrosoftGame.Config", std::ios::binary); if (!f) return {}; @@ -1130,39 +1137,446 @@ HRESULT STDMETHODCALLTYPE pkg_mount_path(void*, XPackageMountHandle mount, size_ } void STDMETHODCALLTYPE pkg_close_mount(void*, XPackageMountHandle mount) { XPackageCloseMountHandle(mount); } +// ---- Slots 5-19: the installation monitor and the package's chunks ---- +// +// Offline the title's own package is fully installed: every chunk is present, nothing is pending, nothing needs a +// download. The title reads a failure from any of these as "chunk not installed" (its chunk check, its chunk manager +// and its monitor setup all take the failure path), so each one answers for the installed package. The answers are +// ported from VIctory's crates/victory-hle/src/modules/xpackage.rs (Marvisak/VIctory, GPL-3.0-or-later, commit +// 2849477), which runs this title into its world with them; slots 13 and 15, which VIctory leaves out, follow the same +// rule. Signatures are Microsoft's public XPackage reference pages: each slot takes the function's arguments after +// `this`, as slots 3-4, 7-8, 11 and 23-26 do. A package identifier other than the process's own (or a content package +// LEONIDA_CONTENT_PACKAGES maps) is E_GAMEPACKAGE_NO_PACKAGE_IDENTIFIER, as VIctory answers it. Each slot writes one +// "[rt] xgameruntime: XPackage first call" line, with its arguments and answer, so a boot log shows which ones +// the title uses. + +// E_GAMEPACKAGE_NO_PACKAGE_IDENTIFIER: no installed package has the identifier (VIctory's value). +constexpr HRESULT kNoPackage = static_cast(0x89245208); + +// XPackageChunkSelector: XPackageChunkSelectorType (Language 0, Tag 1, Chunk 2, Feature 3), then a union of the +// language, tag or feature string and the u32 chunk id. +struct ChunkSelector { + uint32_t type; + union { + const char* text; + uint32_t chunk_id; + }; +}; +static_assert(sizeof(ChunkSelector) == 16, "XPackageChunkSelector layout"); +constexpr uint32_t kSelectorLanguage = 0, kSelectorChunk = 2, kSelectorFeature = 3; + +// XPackageChunkAvailability: Ready 0, Pending 1, Installable 2, Unavailable 3. +constexpr uint32_t kChunkReady = 0; + +const char* text_or_null(const char* s) { return s ? s : "(null)"; } + +// `package "id", 2 selectors: chunk 1000, tag "x"`, the first four selectors at most, for the first-call lines. +std::string describe_request(const char* id, uint32_t count, const ChunkSelector* selectors) { + std::string out = std::string("package \"") + text_or_null(id) + "\", "; + if (!count) return out + "no selectors (the whole package)"; + out += std::to_string(count) + (count == 1 ? " selector" : " selectors"); + if (!selectors) return out + " (null array)"; + static const char* const kTypes[] = {"language", "tag", "chunk", "feature"}; + const uint32_t shown = (std::min)(count, 4u); + for (uint32_t i = 0; i < shown; ++i) { + const ChunkSelector& s = selectors[i]; + out += i ? ", " : ": "; + if (s.type == kSelectorChunk) out += "chunk " + std::to_string(s.chunk_id); + else if (s.type <= kSelectorFeature) out += std::string(kTypes[s.type]) + " \"" + text_or_null(s.text) + "\""; + else out += "type " + std::to_string(s.type); + } + if (count > shown) out += ", ..."; + return out; +} + +// S_OK when `id` names an installed package: the process's own (XPackageGetCurrentProcessPackageIdentifier) or a +// content package LEONIDA_CONTENT_PACKAGES maps. +HRESULT check_package(const char* id) { + if (!id) return E_INVALIDARG; + char own[XPACKAGE_IDENTIFIER_MAX_LENGTH] = {}; + if (SUCCEEDED(XPackageGetCurrentProcessPackageIdentifier(sizeof(own), own)) && std::strcmp(id, own) == 0) + return S_OK; + HRESULT found = S_OK; + const std::string path = resolve_package_path(id, found); // main's form: the path, and the HRESULT through `found` + return SUCCEEDED(found) && !path.empty() ? S_OK : kNoPackage; +} + +// Bytes in the package folder, counted once (VIctory counts its package folder the same way). 1 when there is no +// folder, so the total is never zero and installed == total still reads as a finished installation. +uint64_t package_bytes() { + static const uint64_t bytes = [] { + namespace fs = std::filesystem; + uint64_t sum = 0; + const fs::path dir = package_dir(); + std::error_code ec; + if (!dir.empty()) + for (fs::recursive_directory_iterator it(dir, fs::directory_options::skip_permission_denied, ec), end; + !ec && it != end; it.increment(ec)) { + std::error_code file_ec; + if (!it->is_regular_file(file_ec)) continue; + const uintmax_t size = it->file_size(file_ec); + if (!file_ec) sum += size; + } + return sum ? sum : uint64_t{1}; + }(); + return bytes; +} + +// XPackageInstallationMonitorHandle: a small heap object the title holds until slot 6 closes it. Every monitor watches +// the same finished installation, so it carries only a serial number for the log. The open ones are kept in a set, so +// closing a handle that is not ours (or closing one twice) frees nothing. +struct InstallationMonitor { + uint64_t serial; +}; +std::mutex g_monitor_mu; +std::unordered_set g_monitors; +std::atomic g_monitor_serials{0}; +std::atomic g_progress_tokens{0}; + +InstallationMonitor* open_monitor() { + auto* monitor = new InstallationMonitor{g_monitor_serials.fetch_add(1) + 1}; + std::lock_guard lock(g_monitor_mu); + g_monitors.insert(monitor); + return monitor; +} + +const char* hr_name(HRESULT hr) { + switch (hr) { + case S_OK: return "S_OK"; + case E_INVALIDARG: return "E_INVALIDARG"; + case E_POINTER: return "E_POINTER"; + case E_PENDING: return "E_PENDING"; + case kNoPackage: return "E_GAMEPACKAGE_NO_PACKAGE_IDENTIFIER"; + default: return "failure"; + } +} + +// Slot 5: HRESULT XPackageCreateInstallationMonitor(const char* packageIdentifier, uint32_t selectorCount, +// XPackageChunkSelector* selectors, uint32_t minimumUpdateIntervalMs, XTaskQueueHandle queue, +// XPackageInstallationMonitorHandle* installationMonitor). A monitor of the finished installation. +HRESULT STDMETHODCALLTYPE pkg_create_monitor(void*, const char* id, uint32_t count, const ChunkSelector* selectors, + uint32_t interval_ms, XTaskQueueHandle, void** monitor) { + HRESULT hr = monitor ? check_package(id) : E_POINTER; + if (monitor) *monitor = SUCCEEDED(hr) ? open_monitor() : nullptr; + static std::atomic s_logged{false}; + if (!s_logged.exchange(true)) + std::fprintf(stderr, "[rt] xgameruntime: XPackage CreateInstallationMonitor first call: %s, interval %u ms -> %s (0x%08lx), monitor %p\n", + describe_request(id, count, selectors).c_str(), interval_ms, hr_name(hr), + static_cast(hr), monitor ? *monitor : nullptr); + return hr; +} + +// Slot 6: void XPackageCloseInstallationMonitorHandle(XPackageInstallationMonitorHandle installationMonitor). +void STDMETHODCALLTYPE pkg_close_monitor(void*, void* handle) { + auto* monitor = static_cast(handle); + bool ours = false; + { + std::lock_guard lock(g_monitor_mu); + ours = monitor && g_monitors.erase(monitor) == 1; + } + static std::atomic s_logged{false}; + if (!s_logged.exchange(true)) + std::fprintf(stderr, "[rt] xgameruntime: XPackage CloseInstallationMonitorHandle first call: monitor %p (%s)\n", + handle, ours ? "closed" : "not an open monitor, nothing freed"); + if (ours) delete monitor; +} + // XPackageInstallationProgress: totalBytes, installedBytes, launchBytes (u64), launchable, completed (bool). struct InstallationProgress { uint64_t total_bytes, installed_bytes, launch_bytes; bool launchable, completed; }; static_assert(sizeof(InstallationProgress) == 32, "XPackageInstallationProgress layout"); -// void XPackageGetInstallationProgress(monitor, XPackageInstallationProgress*): an offline package is installed, -// launchable and completed, every byte present. -void STDMETHODCALLTYPE pkg_installation_progress(void*, void*, InstallationProgress* progress) { - if (progress) *progress = {0, 0, 0, true, true}; +// Slot 7: void XPackageGetInstallationProgress(monitor, XPackageInstallationProgress*): an offline package is +// installed, launchable and completed, every byte of the package folder present (as VIctory reports it). +void STDMETHODCALLTYPE pkg_installation_progress(void*, void* monitor, InstallationProgress* progress) { + const uint64_t bytes = package_bytes(); + if (progress) *progress = {bytes, bytes, bytes, true, true}; + static std::atomic s_logged{false}; + if (!s_logged.exchange(true)) + std::fprintf(stderr, "[rt] xgameruntime: XPackage GetInstallationProgress first call: monitor %p -> %llu of " + "%llu bytes installed, launchable, completed\n", + monitor, static_cast(bytes), static_cast(bytes)); } // The bool methods with no offline work, as Microsoft documents them: XPackageUpdateInstallationMonitor is false // (nothing changed), the two Unregister* calls are true (nothing pending), XPackageUninstallPackage is false (not // uninstalled). A generic E_NOTIMPL stub would read as true in al. -bool STDMETHODCALLTYPE pkg_update_monitor(void*, void*) { return false; } -bool STDMETHODCALLTYPE pkg_unregister_progress(void*, void*, XTaskQueueRegistrationToken, bool) { return true; } +bool STDMETHODCALLTYPE pkg_update_monitor(void*, void* monitor) { + static std::atomic s_logged{false}; + if (!s_logged.exchange(true)) + std::fprintf(stderr, "[rt] xgameruntime: XPackage UpdateInstallationMonitor first call: monitor %p -> false " + "(no change)\n", monitor); + return false; +} + +// Slot 9: HRESULT XPackageRegisterInstallationProgressChanged(XPackageInstallationMonitorHandle installationMonitor, +// void* context, XPackageInstallationProgressCallback* callback, XTaskQueueRegistrationToken* token). The installation +// is finished, so progress never changes and the callback is never called (as in VIctory); the token is a fresh +// non-zero number that slot 10 accepts. +HRESULT STDMETHODCALLTYPE pkg_register_progress(void*, void* monitor, void*, void* callback, + XTaskQueueRegistrationToken* token) { + HRESULT hr = S_OK; + if (!token) hr = E_POINTER; + else if (!callback) hr = E_INVALIDARG; + if (token) token->token = SUCCEEDED(hr) ? g_progress_tokens.fetch_add(1) + 1 : 0; + static std::atomic s_logged{false}; + if (!s_logged.exchange(true)) + std::fprintf(stderr, "[rt] xgameruntime: XPackage RegisterInstallationProgressChanged first call: monitor %p " + "-> %s (0x%08lx), token %llu, callback never called (installation complete)\n", + monitor, hr_name(hr), static_cast(hr), + static_cast(token ? token->token : 0)); + return hr; +} +bool STDMETHODCALLTYPE pkg_unregister_progress(void*, void* monitor, XTaskQueueRegistrationToken token, bool) { + static std::atomic s_logged{false}; + if (!s_logged.exchange(true)) + std::fprintf(stderr, "[rt] xgameruntime: XPackage UnregisterInstallationProgressChanged first call: monitor %p, " + "token %llu -> true\n", monitor, static_cast(token.token)); + return true; +} bool STDMETHODCALLTYPE pkg_unregister_installed(void*, XTaskQueueRegistrationToken, bool) { return true; } bool STDMETHODCALLTYPE pkg_uninstall_package(void*, const char*) { return false; } +// Slot 39 (IXPackageImpl3): HRESULT XPackageEnumeratePackages(XPackageKind kind, XPackageEnumerationScope scope, +// void* context, XPackageEnumerationCallback* callback), the callback a `bool CALLBACK (void* context, const +// XPackageDetails* details)` that is called once per package. The title enumerates content packages (kind 1) and the +// offline install has none to list, so this is S_OK without a callback, as VIctory's xpackage.rs answers the same slot +// (0x138) for this title. Shortcut: a console would also list this installation for kind 0 (Game); no caller seen asks +// for it. A content package LEONIDA_CONTENT_PACKAGES maps is mounted by its identifier (slots 23, 37), not listed here. +HRESULT STDMETHODCALLTYPE pkg_enumerate_packages(void*, uint32_t kind, uint32_t scope, void* context, void* callback) { + const HRESULT hr = callback ? S_OK : E_INVALIDARG; + static std::atomic s_logged{false}; + if (!s_logged.exchange(true)) + std::fprintf(stderr, "[rt] xgameruntime: XPackage EnumeratePackages first call: kind %u, scope %u, context %p " + "-> %s (0x%08lx), no packages listed\n", + kind, scope, context, hr_name(hr), static_cast(hr)); + return hr; +} + +// Slot 12: HRESULT XPackageFindChunkAvailability(const char* packageIdentifier, uint32_t selectorCount, +// XPackageChunkSelector* selectors, XPackageChunkAvailability* availability). Ready for every selector of an installed +// package. Like VIctory this does not check that the selectors name chunks the package's layout has (the console would +// answer an unknown one with E_GAMEPACKAGE_INVALID_SELECTOR); the title asks only about its own chunks. +HRESULT STDMETHODCALLTYPE pkg_find_chunk_availability(void*, const char* id, uint32_t count, + const ChunkSelector* selectors, uint32_t* availability) { + const HRESULT hr = availability ? check_package(id) : E_POINTER; + if (SUCCEEDED(hr)) *availability = kChunkReady; + static std::atomic s_logged{false}; + if (!s_logged.exchange(true)) + std::fprintf(stderr, "[rt] xgameruntime: XPackage FindChunkAvailability first call: %s -> %s (0x%08lx)%s\n", + describe_request(id, count, selectors).c_str(), hr_name(hr), static_cast(hr), + SUCCEEDED(hr) ? ", Ready" : ""); + return hr; +} + +// Slot 13: HRESULT XPackageEnumerateChunkAvailability(const char* packageIdentifier, XPackageChunkSelectorType type, +// void* context, XPackageChunkAvailabilityCallback* callback), the callback being +// bool (void* context, const XPackageChunkSelector* selector, XPackageChunkAvailability availability), true to go on. +// Nothing is pending: every reported selector is Ready. Languages are the ones MicrosoftGame.Config declares; tags, +// chunk ids and features come from the package's layout, which is not read offline, so none are reported. +using ChunkAvailabilityCallback = bool(CALLBACK*)(void* context, const ChunkSelector* selector, uint32_t availability); +HRESULT STDMETHODCALLTYPE pkg_enumerate_chunk_availability(void*, const char* id, uint32_t type, void* context, + ChunkAvailabilityCallback callback) { + HRESULT hr = callback ? check_package(id) : E_INVALIDARG; + if (SUCCEEDED(hr) && type > kSelectorFeature) hr = E_INVALIDARG; + size_t reported = 0; + if (SUCCEEDED(hr) && type == kSelectorLanguage) { + const std::vector locales = package_locales(); + for (const std::string& locale : locales) { + ChunkSelector selector{}; + selector.type = kSelectorLanguage; + selector.text = locale.c_str(); + ++reported; + if (!callback(context, &selector, kChunkReady)) break; + } + } + static std::atomic s_logged{false}; + if (!s_logged.exchange(true)) + std::fprintf(stderr, "[rt] xgameruntime: XPackage EnumerateChunkAvailability first call: package \"%s\", " + "selector type %u -> %s (0x%08lx), %zu selectors reported Ready\n", + text_or_null(id), type, hr_name(hr), static_cast(hr), reported); + return hr; +} + +// Slot 14: HRESULT XPackageChangeChunkInstallOrder(const char* packageIdentifier, uint32_t selectorCount, +// XPackageChunkSelector* selectors). Nothing is queued, so any order is the order. +HRESULT STDMETHODCALLTYPE pkg_change_chunk_install_order(void*, const char* id, uint32_t count, + const ChunkSelector* selectors) { + const HRESULT hr = check_package(id); + static std::atomic s_logged{false}; + if (!s_logged.exchange(true)) + std::fprintf(stderr, "[rt] xgameruntime: XPackage ChangeChunkInstallOrder first call: %s -> %s (0x%08lx)\n", + describe_request(id, count, selectors).c_str(), hr_name(hr), static_cast(hr)); + return hr; +} + +// Slot 15: HRESULT XPackageInstallChunks(const char* packageIdentifier, uint32_t selectorCount, +// XPackageChunkSelector* selectors, uint32_t minimumUpdateIntervalMs, bool suppressUserConfirmation, +// XTaskQueueHandle queue, XPackageInstallationMonitorHandle* installationMonitor). Everything is installed already: +// S_OK and a monitor of the finished installation. +HRESULT STDMETHODCALLTYPE pkg_install_chunks(void*, const char* id, uint32_t count, const ChunkSelector* selectors, + uint32_t, bool, XTaskQueueHandle, void** monitor) { + const HRESULT hr = monitor ? check_package(id) : E_POINTER; + if (monitor) *monitor = SUCCEEDED(hr) ? open_monitor() : nullptr; + static std::atomic s_logged{false}; + if (!s_logged.exchange(true)) + std::fprintf(stderr, "[rt] xgameruntime: XPackage InstallChunks first call: %s -> %s (0x%08lx), already " + "installed, monitor %p\n", + describe_request(id, count, selectors).c_str(), hr_name(hr), static_cast(hr), + monitor ? *monitor : nullptr); + return hr; +} + +// Slot 16: HRESULT XPackageInstallChunksAsync(const char* packageIdentifier, uint32_t selectorCount, +// XPackageChunkSelector* selectors, uint32_t minimumUpdateIntervalMs, bool suppressUserConfirmation, +// XAsyncBlock* asyncBlock). Everything is installed already: the block completes on its queue straight away, through +// XAsyncRun like the other offline *Async slots, with S_OK (E_GAMEPACKAGE_NO_PACKAGE_IDENTIFIER for a package that is +// not installed, as VIctory completes it). +HRESULT STDMETHODCALLTYPE pkg_install_chunks_async(void*, const char* id, uint32_t count, + const ChunkSelector* selectors, uint32_t, bool, XAsyncBlock* async) { + const HRESULT package = check_package(id); + HRESULT hr = S_OK; + if (!async) hr = E_POINTER; + else if (package == E_INVALIDARG) hr = E_INVALIDARG; + else if (SUCCEEDED(package)) hr = XAsyncRun(async, [](XAsyncBlock*) -> HRESULT { return S_OK; }); + else hr = XAsyncRun(async, [](XAsyncBlock*) -> HRESULT { return kNoPackage; }); + static std::atomic s_logged{false}; + if (!s_logged.exchange(true)) + std::fprintf(stderr, "[rt] xgameruntime: XPackage InstallChunksAsync first call: %s -> %s (0x%08lx), " + "completes with %s\n", + describe_request(id, count, selectors).c_str(), hr_name(hr), static_cast(hr), + FAILED(hr) ? "nothing (not started)" : hr_name(package)); + return hr; +} + +// Slot 17: HRESULT XPackageInstallChunksResult(XAsyncBlock* asyncBlock, +// XPackageInstallationMonitorHandle* installationMonitor). The block's status, and on success a monitor of the +// finished installation. +HRESULT STDMETHODCALLTYPE pkg_install_chunks_result(void*, XAsyncBlock* async, void** monitor) { + HRESULT hr = (async && monitor) ? XAsyncGetStatus(async, false) : E_POINTER; + if (monitor) *monitor = SUCCEEDED(hr) ? open_monitor() : nullptr; + static std::atomic s_logged{false}; + if (!s_logged.exchange(true)) + std::fprintf(stderr, "[rt] xgameruntime: XPackage InstallChunksResult first call: block %p -> %s (0x%08lx), " + "monitor %p\n", + static_cast(async), hr_name(hr), static_cast(hr), + monitor ? *monitor : nullptr); + return hr; +} + +// Slot 18: HRESULT XPackageEstimateDownloadSize(const char* packageIdentifier, uint32_t selectorCount, +// XPackageChunkSelector* selectors, uint64_t* downloadSize, bool* shouldPresentUserConfirmation). Nothing to download, +// so nothing to confirm. +HRESULT STDMETHODCALLTYPE pkg_estimate_download_size(void*, const char* id, uint32_t count, + const ChunkSelector* selectors, uint64_t* download_size, + bool* confirm) { + const HRESULT hr = download_size ? check_package(id) : E_POINTER; + if (SUCCEEDED(hr)) { + *download_size = 0; + if (confirm) *confirm = false; + } + static std::atomic s_logged{false}; + if (!s_logged.exchange(true)) + std::fprintf(stderr, "[rt] xgameruntime: XPackage EstimateDownloadSize first call: %s -> %s (0x%08lx)%s\n", + describe_request(id, count, selectors).c_str(), hr_name(hr), static_cast(hr), + SUCCEEDED(hr) ? ", 0 bytes, no user confirmation" : ""); + return hr; +} + +// Slot 19: HRESULT XPackageUninstallChunks(const char* packageIdentifier, uint32_t selectorCount, +// XPackageChunkSelector* selectors). Accepted, but nothing is removed (the package folder is the user's), so the +// chunks stay Ready, as in VIctory. +HRESULT STDMETHODCALLTYPE pkg_uninstall_chunks(void*, const char* id, uint32_t count, const ChunkSelector* selectors) { + const HRESULT hr = check_package(id); + static std::atomic s_logged{false}; + if (!s_logged.exchange(true)) + std::fprintf(stderr, "[rt] xgameruntime: XPackage UninstallChunks first call: %s -> %s (0x%08lx), nothing " + "removed\n", + describe_request(id, count, selectors).c_str(), hr_name(hr), static_cast(hr)); + return hr; +} + +// Slots 37/38: HRESULT XPackageMountWithUiAsync(const char* packageIdentifier, XAsyncBlock* async) and +// HRESULT XPackageMountWithUiResult(XAsyncBlock* async, XPackageMountHandle* mount). The retail executable calls both +// once IXPackageImpl4 is served. A content package LEONIDA_CONTENT_PACKAGES maps is mounted as slot 23 mounts it and +// the result hands out its handle; any other identifier completes with E_GAMEPACKAGE_NO_PACKAGE_IDENTIFIER, as +// VIctory's mount_async answers (no content package is installed). The block completes through XAsyncRun. +std::mutex g_ui_mount_mu; +std::unordered_map g_ui_mounts; // a finished mount's handle until its result is read + +HRESULT STDMETHODCALLTYPE pkg_mount_with_ui_async(void*, const char* id, XAsyncBlock* async) { + HRESULT hr = S_OK; + HRESULT mounted = kNoPackage; + if (!async) hr = E_POINTER; + else if (!id) hr = E_INVALIDARG; + else { + XPackageMountHandle mount{}; + mounted = SUCCEEDED(XPackageMount(id, &mount)) ? S_OK : kNoPackage; + if (SUCCEEDED(mounted)) { + std::lock_guard lock(g_ui_mount_mu); + g_ui_mounts[async] = mount.handle; + } + hr = SUCCEEDED(mounted) ? XAsyncRun(async, [](XAsyncBlock*) -> HRESULT { return S_OK; }) + : XAsyncRun(async, [](XAsyncBlock*) -> HRESULT { return kNoPackage; }); + if (FAILED(hr) && SUCCEEDED(mounted)) { + std::lock_guard lock(g_ui_mount_mu); + g_ui_mounts.erase(async); + XPackageCloseMountHandle(mount); + } + } + static std::atomic s_logged{false}; + if (!s_logged.exchange(true)) + std::fprintf(stderr, "[rt] xgameruntime: XPackage MountWithUiAsync first call: package \"%s\" -> %s (0x%08lx), " + "completes with %s\n", + text_or_null(id), hr_name(hr), static_cast(hr), + FAILED(hr) ? "nothing (not started)" : hr_name(mounted)); + return hr; +} + +HRESULT STDMETHODCALLTYPE pkg_mount_with_ui_result(void*, XAsyncBlock* async, XPackageMountHandle* mount) { + HRESULT hr = (async && mount) ? XAsyncGetStatus(async, false) : E_POINTER; + if (mount) mount->handle = 0; + if (async && mount && hr != E_PENDING) { + std::lock_guard lock(g_ui_mount_mu); + const auto it = g_ui_mounts.find(async); + if (it != g_ui_mounts.end()) { + if (SUCCEEDED(hr)) mount->handle = it->second; + else XPackageCloseMountHandle(XPackageMountHandle{it->second}); + g_ui_mounts.erase(it); + } else if (SUCCEEDED(hr)) { + hr = E_UNEXPECTED; // the result was read already + } + } + static std::atomic s_logged{false}; + if (!s_logged.exchange(true)) + std::fprintf(stderr, "[rt] xgameruntime: XPackage MountWithUiResult first call: block %p -> %s (0x%08lx), " + "mount %llu\n", + static_cast(async), hr_name(hr), static_cast(hr), + static_cast(mount ? mount->handle : 0)); + return hr; +} + #define PN(n) reinterpret_cast(&package_not_implemented) const void* const kPackageVtable[] = { reinterpret_cast(&object_query_interface), reinterpret_cast(&object_add_ref), reinterpret_cast(&object_release), reinterpret_cast(&pkg_identifier), // 3 XPackageGetCurrentProcessPackageIdentifier reinterpret_cast(&pkg_is_packaged), // 4 XPackageIsPackagedProcess - PN(5), PN(6), // 5-6 installation monitor: create, close + reinterpret_cast(&pkg_create_monitor), // 5 XPackageCreateInstallationMonitor + reinterpret_cast(&pkg_close_monitor), // 6 XPackageCloseInstallationMonitorHandle (void) reinterpret_cast(&pkg_installation_progress), // 7 XPackageGetInstallationProgress (void, writes) reinterpret_cast(&pkg_update_monitor), // 8 XPackageUpdateInstallationMonitor (bool) - PN(9), // 9 XPackageRegisterInstallationProgressChanged + reinterpret_cast(&pkg_register_progress), // 9 XPackageRegisterInstallationProgressChanged reinterpret_cast(&pkg_unregister_progress), // 10 ...UnregisterInstallationProgressChanged (bool) reinterpret_cast(&pkg_user_locale), // 11 XPackageGetUserLocale - PN(12), PN(13), PN(14), PN(15), PN(16), PN(17), // 12-19 chunks: find / enumerate availability, change order, - PN(18), PN(19), // install (+ async, result), estimate size, uninstall + reinterpret_cast(&pkg_find_chunk_availability), // 12 XPackageFindChunkAvailability + reinterpret_cast(&pkg_enumerate_chunk_availability), // 13 XPackageEnumerateChunkAvailability + reinterpret_cast(&pkg_change_chunk_install_order), // 14 XPackageChangeChunkInstallOrder + reinterpret_cast(&pkg_install_chunks), // 15 XPackageInstallChunks + reinterpret_cast(&pkg_install_chunks_async), // 16 XPackageInstallChunksAsync + reinterpret_cast(&pkg_install_chunks_result), // 17 XPackageInstallChunksResult + reinterpret_cast(&pkg_estimate_download_size), // 18 XPackageEstimateDownloadSize + reinterpret_cast(&pkg_uninstall_chunks), // 19 XPackageUninstallChunks PN(20), PN(21), // 20-21 _unknown_ (older enumerate / register installed) reinterpret_cast(&pkg_unregister_installed), // 22 XPackageUnregisterPackageInstalled (bool) reinterpret_cast(&pkg_mount), // 23 XPackageMount @@ -1173,12 +1587,16 @@ const void* const kPackageVtable[] = { // 30 GetWriteStats, 31 _unknown_ PN(32), PN(33), // 32 UninstallUWPInstance, 33 EnumerateFeatures reinterpret_cast(&pkg_uninstall_package), // 34 XPackageUninstallPackage (bool) - PN(35), PN(36), PN(37), PN(38), // IXPackageImpl2: EnumeratePackages, RegisterPackageInstalled, - // MountWithUiAsync, MountWithUiResult - PN(39), PN(40), // IXPackageImpl3: EnumeratePackages, RegisterPackageInstalled + PN(35), PN(36), // IXPackageImpl2: EnumeratePackages, RegisterPackageInstalled, + reinterpret_cast(&pkg_mount_with_ui_async), // 37 XPackageMountWithUiAsync + reinterpret_cast(&pkg_mount_with_ui_result), // 38 XPackageMountWithUiResult + reinterpret_cast(&pkg_enumerate_packages), // 39 XPackageEnumeratePackages (IXPackageImpl3) + PN(40), // 40 RegisterPackageInstalled (IXPackageImpl3) + PN(41), // IXPackageImpl4: XPackageGetPackageKind }; #undef PN -static_assert(std::size(kPackageVtable) == 41, "IUnknown + IXPackageImpl's 32 + IXPackageImpl2's 4 + IXPackageImpl3's 2"); +static_assert(std::size(kPackageVtable) == 42, + "IUnknown + IXPackageImpl's 32 + IXPackageImpl2's 4 + IXPackageImpl3's 2 + IXPackageImpl4's 1"); RuntimeObject& package_object() { static RuntimeObject object{kPackageVtable, &kPackageClass, kPackageIids}; @@ -1384,7 +1802,7 @@ SHIM_TABLE(xgameruntime, XGR(InitializeApiImplEx2), XGR(UninitializeApiImpl), XGR(QueryApiImpl), - XGR(XErrorReport), + XGR(XErrorReport), // looked up with the five above; without it the thunks refuse the runtime // the same runtime through gameplatformservices.dll, which XCurl.dll loads from System32 (GetApiVersionImpl above) {"gameplatformservices.dll", "QueryApiImpl", reinterpret_cast(&QueryApiImpl)}, {"gameplatformservices.dll", "GetApiVersionImpl", reinterpret_cast(&GetApiVersionImpl)}, diff --git a/runtime/shims/xgameruntime_user.cpp b/runtime/shims/xgameruntime_user.cpp index e323956463..d4f991995e 100644 --- a/runtime/shims/xgameruntime_user.cpp +++ b/runtime/shims/xgameruntime_user.cpp @@ -15,6 +15,10 @@ // The executable links thunks for IXUserImpl slots 3-5, 7-14, 19-25 and 33-34 and IXUserGamertagImpl slot 3 // (tools/gdk_runtime_calls.py, from the file alone; docs/runtime_imports.md). None of them is a private or PC-only // slot; those still log once when called. +// +// Every served slot writes one "[rt] xgameruntime: XUser first call: ..." line with its arguments and answer +// (XUserGetGamertag one per component), so a boot log shows how far the title got with its user: the player-select +// prompt needs a signed-in user and its gamertag (docs/re/notes/firstframe.md). Later calls are silent. #include #include @@ -105,40 +109,57 @@ bool valid(XUserHandle h) { return g_handles.count(h) != 0; } +// The slot's one first-call line (see the top of the file); the format string is a literal. +#define USER_FIRST_CALL(...) \ + do { \ + static std::atomic s_logged{false}; \ + if (!s_logged.exchange(true)) std::fprintf(stderr, "[rt] xgameruntime: XUser " __VA_ARGS__); \ + } while (0) +unsigned long hex(HRESULT hr) { return static_cast(hr); } + // ---- IXUserImpl (slots 3-36) ---- // 3: HRESULT XUserDuplicateHandle(XUserHandle handle, XUserHandle* duplicatedHandle) HRESULT STDMETHODCALLTYPE user_duplicate(void*, XUserHandle handle, XUserHandle* dup) { - if (!dup) return E_POINTER; - *dup = nullptr; - if (!valid(handle)) return E_INVALIDARG; - *dup = new_handle(); - return S_OK; + const HRESULT hr = [&]() -> HRESULT { + if (!dup) return E_POINTER; + *dup = nullptr; + if (!valid(handle)) return E_INVALIDARG; + *dup = new_handle(); + return S_OK; + }(); + USER_FIRST_CALL("DuplicateHandle first call: handle %p -> 0x%08lx, new handle %p\n", static_cast(handle), + hex(hr), dup ? static_cast(*dup) : nullptr); + return hr; } // 4: void XUserCloseHandle(XUserHandle user) void STDMETHODCALLTYPE user_close(void*, XUserHandle user) { + bool ours = false; { std::lock_guard lock(g_handles_mutex); - if (!user || g_handles.erase(user) == 0) return; // closed already, or not ours + ours = user && g_handles.erase(user) != 0; // false: closed already, or not ours } - delete user; + USER_FIRST_CALL("CloseHandle first call: handle %p (%s)\n", static_cast(user), + ours ? "closed" : "not open; ignored"); + if (ours) delete user; } // 5: int32_t XUserCompare(XUserHandle user1, XUserHandle user2): 0 when both name the same user. Every valid handle // names the one local user. int32_t STDMETHODCALLTYPE user_compare(void*, XUserHandle a, XUserHandle b) { const bool va = valid(a), vb = valid(b); - if (va && vb) return 0; - if (va != vb) return va ? 1 : -1; - return a == b ? 0 : (a < b ? -1 : 1); + const int32_t order = va && vb ? 0 : va != vb ? (va ? 1 : -1) : a == b ? 0 : (a < b ? -1 : 1); + USER_FIRST_CALL("Compare first call: handles %p, %p -> %d\n", static_cast(a), static_cast(b), order); + return order; } // 6: HRESULT XUserGetMaxUsers(uint32_t* maxUsers). One local user offline. HRESULT STDMETHODCALLTYPE user_get_max_users(void*, uint32_t* max_users) { - if (!max_users) return E_POINTER; - *max_users = 1; - return S_OK; + const HRESULT hr = max_users ? S_OK : E_POINTER; + if (max_users) *max_users = 1; + USER_FIRST_CALL("GetMaxUsers first call: -> 0x%08lx, 1 user\n", hex(hr)); + return hr; } // XAsync providers. The result of an add is a new handle, created when the title collects it, so a result the @@ -194,69 +215,91 @@ HRESULT CALLBACK resolve_provider(XAsyncOp op, const XAsyncProviderData* data) { // refused, as documented ("A guest cannot be the default user"). Without a silent option the console would show the // account picker; offline the one user is the answer either way. HRESULT STDMETHODCALLTYPE user_add_async(void*, XUserAddOptions options, XAsyncBlock* async) { - if (!async) return E_POINTER; const auto bits = static_cast(options); - if ((bits & static_cast(XUserAddOptions::AddDefaultUserSilently)) && - (bits & static_cast(XUserAddOptions::AllowGuests))) - return E_INVALIDARG; - return XAsyncBegin(async, nullptr, &kAddIdentity, "XUserAddAsync", add_provider); + const HRESULT hr = [&]() -> HRESULT { + if (!async) return E_POINTER; + if ((bits & static_cast(XUserAddOptions::AddDefaultUserSilently)) && + (bits & static_cast(XUserAddOptions::AllowGuests))) + return E_INVALIDARG; + return XAsyncBegin(async, nullptr, &kAddIdentity, "XUserAddAsync", add_provider); + }(); + USER_FIRST_CALL("AddAsync first call: options 0x%x, block %p -> 0x%08lx (the offline user \"%s\")\n", bits, + static_cast(async), hex(hr), gamertag()); + return hr; } // 8: HRESULT XUserAddResult(XAsyncBlock* async, XUserHandle* newUser) HRESULT STDMETHODCALLTYPE user_add_result(void*, XAsyncBlock* async, XUserHandle* user) { - if (!user) return E_POINTER; - *user = nullptr; - return XAsyncGetResult(async, &kAddIdentity, sizeof(*user), user, nullptr); + const HRESULT hr = [&]() -> HRESULT { + if (!user) return E_POINTER; + *user = nullptr; + return XAsyncGetResult(async, &kAddIdentity, sizeof(*user), user, nullptr); + }(); + USER_FIRST_CALL("AddResult first call: block %p -> 0x%08lx, handle %p\n", static_cast(async), hex(hr), + user ? static_cast(*user) : nullptr); + return hr; } // 9: HRESULT XUserGetLocalId(XUserHandle user, XUserLocalId* userLocalId) HRESULT STDMETHODCALLTYPE user_get_local_id(void*, XUserHandle user, XUserLocalId* id) { - if (!id) return E_POINTER; - if (!valid(user)) return E_INVALIDARG; - id->value = kOfflineLocalId; - return S_OK; + const HRESULT hr = !id ? E_POINTER : !valid(user) ? E_INVALIDARG : S_OK; + if (hr == S_OK) id->value = kOfflineLocalId; + USER_FIRST_CALL("GetLocalId first call: handle %p -> 0x%08lx, local id %llu\n", static_cast(user), hex(hr), + static_cast(hr == S_OK ? kOfflineLocalId : 0)); + return hr; } // 10: HRESULT XUserFindUserByLocalId(XUserLocalId userLocalId, XUserHandle* handle) HRESULT STDMETHODCALLTYPE user_find_by_local_id(void*, XUserLocalId id, XUserHandle* handle) { - if (!handle) return E_POINTER; - *handle = nullptr; - if (id.value != kOfflineLocalId) return E_GAMEUSER_USER_NOT_FOUND; - *handle = new_handle(); - return S_OK; + const HRESULT hr = [&]() -> HRESULT { + if (!handle) return E_POINTER; + *handle = nullptr; + if (id.value != kOfflineLocalId) return E_GAMEUSER_USER_NOT_FOUND; + *handle = new_handle(); + return S_OK; + }(); + USER_FIRST_CALL("FindUserByLocalId first call: local id %llu -> 0x%08lx, handle %p\n", + static_cast(id.value), hex(hr), handle ? static_cast(*handle) : nullptr); + return hr; } // 11: HRESULT XUserGetId(XUserHandle user, uint64_t* userId) HRESULT STDMETHODCALLTYPE user_get_id(void*, XUserHandle user, uint64_t* id) { - if (!id) return E_POINTER; - if (!valid(user)) return E_INVALIDARG; - *id = kOfflineXuid; - return S_OK; + const HRESULT hr = !id ? E_POINTER : !valid(user) ? E_INVALIDARG : S_OK; + if (hr == S_OK) *id = kOfflineXuid; + USER_FIRST_CALL("GetId first call: handle %p -> 0x%08lx, user id 0x%016llx\n", static_cast(user), hex(hr), + static_cast(hr == S_OK ? kOfflineXuid : 0)); + return hr; } // 12: HRESULT XUserFindUserById(uint64_t userId, XUserHandle* handle) HRESULT STDMETHODCALLTYPE user_find_by_id(void*, uint64_t id, XUserHandle* handle) { - if (!handle) return E_POINTER; - *handle = nullptr; - if (id != kOfflineXuid) return E_GAMEUSER_USER_NOT_FOUND; - *handle = new_handle(); - return S_OK; + const HRESULT hr = [&]() -> HRESULT { + if (!handle) return E_POINTER; + *handle = nullptr; + if (id != kOfflineXuid) return E_GAMEUSER_USER_NOT_FOUND; + *handle = new_handle(); + return S_OK; + }(); + USER_FIRST_CALL("FindUserById first call: user id 0x%016llx -> 0x%08lx, handle %p\n", + static_cast(id), hex(hr), handle ? static_cast(*handle) : nullptr); + return hr; } // 13: HRESULT XUserGetIsGuest(XUserHandle user, bool* isGuest) HRESULT STDMETHODCALLTYPE user_get_is_guest(void*, XUserHandle user, bool* guest) { - if (!guest) return E_POINTER; - if (!valid(user)) return E_INVALIDARG; - *guest = false; - return S_OK; + const HRESULT hr = !guest ? E_POINTER : !valid(user) ? E_INVALIDARG : S_OK; + if (hr == S_OK) *guest = false; + USER_FIRST_CALL("GetIsGuest first call: handle %p -> 0x%08lx, not a guest\n", static_cast(user), hex(hr)); + return hr; } // 14: HRESULT XUserGetState(XUserHandle user, XUserState* state) HRESULT STDMETHODCALLTYPE user_get_state(void*, XUserHandle user, XUserState* state) { - if (!state) return E_POINTER; - if (!valid(user)) return E_INVALIDARG; - *state = XUserState::SignedIn; - return S_OK; + const HRESULT hr = !state ? E_POINTER : !valid(user) ? E_INVALIDARG : S_OK; + if (hr == S_OK) *state = XUserState::SignedIn; + USER_FIRST_CALL("GetState first call: handle %p -> 0x%08lx, SignedIn (0)\n", static_cast(user), hex(hr)); + return hr; } // A slot with no public signature, logged once. Slot 15 (the docs' "unknown") answers E_NOTIMPL, so a caller fails @@ -288,35 +331,45 @@ template HRESULT STDMETHODCALLTYPE offline_failure(voi // 19: HRESULT XUserGetAgeGroup(XUserHandle user, XUserAgeGroup* ageGroup) HRESULT STDMETHODCALLTYPE user_get_age_group(void*, XUserHandle user, XUserAgeGroup* group) { - if (!group) return E_POINTER; - if (!valid(user)) return E_INVALIDARG; - *group = XUserAgeGroup::Adult; - return S_OK; + const HRESULT hr = !group ? E_POINTER : !valid(user) ? E_INVALIDARG : S_OK; + if (hr == S_OK) *group = XUserAgeGroup::Adult; + USER_FIRST_CALL("GetAgeGroup first call: handle %p -> 0x%08lx, Adult (3)\n", static_cast(user), hex(hr)); + return hr; } // 20: HRESULT XUserCheckPrivilege(XUserHandle user, XUserPrivilegeOptions options, XUserPrivilege privilege, // bool* hasPrivilege, XUserPrivilegeDenyReason* reason). Everything is allowed offline // (multiplayer and the like then fail at the network, as on a console without one). -HRESULT STDMETHODCALLTYPE user_check_privilege(void*, XUserHandle user, uint32_t, uint32_t, bool* has, +HRESULT STDMETHODCALLTYPE user_check_privilege(void*, XUserHandle user, uint32_t options, uint32_t privilege, bool* has, XUserPrivilegeDenyReason* reason) { - if (!has) return E_POINTER; - if (!valid(user)) return E_INVALIDARG; - *has = true; - if (reason) *reason = XUserPrivilegeDenyReason::None; - return S_OK; + const HRESULT hr = !has ? E_POINTER : !valid(user) ? E_INVALIDARG : S_OK; + if (hr == S_OK) { + *has = true; + if (reason) *reason = XUserPrivilegeDenyReason::None; + } + USER_FIRST_CALL("CheckPrivilege first call: handle %p, options %u, privilege %u -> 0x%08lx, granted\n", + static_cast(user), options, privilege, hex(hr)); + return hr; } // 21: HRESULT XUserResolvePrivilegeWithUiAsync(XUserHandle user, XUserPrivilegeOptions options, XUserPrivilege privilege, // XAsyncBlock* async) -HRESULT STDMETHODCALLTYPE user_resolve_privilege_async(void*, XUserHandle user, uint32_t, uint32_t, XAsyncBlock* async) { - if (!async) return E_POINTER; - if (!valid(user)) return E_INVALIDARG; - return XAsyncBegin(async, nullptr, &kResolveIdentity, "XUserResolvePrivilegeWithUiAsync", resolve_provider); +HRESULT STDMETHODCALLTYPE user_resolve_privilege_async(void*, XUserHandle user, uint32_t, uint32_t privilege, + XAsyncBlock* async) { + const HRESULT hr = !async ? E_POINTER + : !valid(user) ? E_INVALIDARG + : XAsyncBegin(async, nullptr, &kResolveIdentity, "XUserResolvePrivilegeWithUiAsync", + resolve_provider); + USER_FIRST_CALL("ResolvePrivilegeWithUiAsync first call: handle %p, privilege %u -> 0x%08lx (nothing to resolve)\n", + static_cast(user), privilege, hex(hr)); + return hr; } // 22: HRESULT XUserResolvePrivilegeWithUiResult(XAsyncBlock* async) HRESULT STDMETHODCALLTYPE user_resolve_privilege_result(void*, XAsyncBlock* async) { - return XAsyncGetResult(async, &kResolveIdentity, 0, nullptr, nullptr); + const HRESULT hr = XAsyncGetResult(async, &kResolveIdentity, 0, nullptr, nullptr); + USER_FIRST_CALL("ResolvePrivilegeWithUiResult first call: block %p -> 0x%08lx\n", static_cast(async), hex(hr)); + return hr; } // 33: HRESULT XUserRegisterForChangeEvent(XTaskQueueHandle queue, void* context, XUserChangeEventCallback* callback, @@ -329,19 +382,27 @@ uint64_t g_next_token = 1; HRESULT STDMETHODCALLTYPE user_register_change(void*, XTaskQueueHandle, void*, XUserChangeEventCallback callback, XTaskQueueRegistrationToken* token) { - if (!callback || !token) return E_POINTER; - std::lock_guard lock(g_tokens_mutex); - token->token = g_next_token++; - g_tokens.insert(token->token); - return S_OK; + const HRESULT hr = callback && token ? S_OK : E_POINTER; + if (hr == S_OK) { + std::lock_guard lock(g_tokens_mutex); + token->token = g_next_token++; + g_tokens.insert(token->token); + } + USER_FIRST_CALL("RegisterForChangeEvent first call: -> 0x%08lx, token %llu (never called: the user never changes)\n", + hex(hr), static_cast(hr == S_OK ? token->token : 0)); + return hr; } // false means "wait was false and the unregistration is still pending"; nothing is ever pending offline, so it is // true for every token, including one already unregistered or never handed out (a title polling with wait = false // would otherwise spin). bool STDMETHODCALLTYPE user_unregister_change(void*, XTaskQueueRegistrationToken token, bool) { - std::lock_guard lock(g_tokens_mutex); - g_tokens.erase(token.token); + { + std::lock_guard lock(g_tokens_mutex); + g_tokens.erase(token.token); + } + USER_FIRST_CALL("UnregisterForChangeEvent first call: token %llu -> true\n", + static_cast(token.token)); return true; } @@ -349,6 +410,8 @@ bool STDMETHODCALLTYPE user_unregister_change(void*, XTaskQueueRegistrationToken // no sign-out to defer (the documented E_GAMEUSER_DEFERRAL_NOT_AVAILABLE). HRESULT STDMETHODCALLTYPE user_get_signout_deferral(void*, XUserSignOutDeferralHandle* deferral) { if (deferral) *deferral = nullptr; + USER_FIRST_CALL("GetSignOutDeferral first call: -> 0x%08lx (nothing signs out offline)\n", + hex(E_GAMEUSER_DEFERRAL_NOT_AVAILABLE)); return E_GAMEUSER_DEFERRAL_NOT_AVAILABLE; } @@ -359,34 +422,45 @@ void STDMETHODCALLTYPE user_close_signout_deferral(void*, XUserSignOutDeferralHa // 37: HRESULT XUserAddByIdWithUiAsync(uint64_t userId, XAsyncBlock* async) HRESULT STDMETHODCALLTYPE user_add_by_id_async(void*, uint64_t id, XAsyncBlock* async) { - if (!async) return E_POINTER; - return XAsyncBegin(async, reinterpret_cast(static_cast(id)), &kAddByIdIdentity, - "XUserAddByIdWithUiAsync", add_by_id_provider); + const HRESULT hr = !async ? E_POINTER + : XAsyncBegin(async, reinterpret_cast(static_cast(id)), + &kAddByIdIdentity, "XUserAddByIdWithUiAsync", add_by_id_provider); + USER_FIRST_CALL("AddByIdWithUiAsync first call: user id 0x%016llx -> 0x%08lx\n", static_cast(id), + hex(hr)); + return hr; } // 38: HRESULT XUserAddByIdWithUiResult(XAsyncBlock* async, XUserHandle* newUser) HRESULT STDMETHODCALLTYPE user_add_by_id_result(void*, XAsyncBlock* async, XUserHandle* user) { - if (!user) return E_POINTER; - *user = nullptr; - return XAsyncGetResult(async, &kAddByIdIdentity, sizeof(*user), user, nullptr); + const HRESULT hr = [&]() -> HRESULT { + if (!user) return E_POINTER; + *user = nullptr; + return XAsyncGetResult(async, &kAddByIdIdentity, sizeof(*user), user, nullptr); + }(); + USER_FIRST_CALL("AddByIdWithUiResult first call: block %p -> 0x%08lx, handle %p\n", static_cast(async), + hex(hr), user ? static_cast(*user) : nullptr); + return hr; } // ---- IXUserImpl4 (42) ---- // 42: bool XUserIsStoreUser(XUserHandle user): the handle is _In_opt_, and the GDK reference says the function // always returns true on console. -bool STDMETHODCALLTYPE user_is_store_user(void*, XUserHandle) { return true; } +bool STDMETHODCALLTYPE user_is_store_user(void*, XUserHandle user) { + USER_FIRST_CALL("IsStoreUser first call: handle %p -> true\n", static_cast(user)); + return true; +} // ---- IXUserGamertagImpl (its slot 3) ---- // HRESULT XUserGetGamertag(XUserHandle user, XUserGamertagComponent component, size_t gamertagSize, char* gamertag, // size_t* gamertagUsed). The offline user has a classic gamertag: Modern and UniqueModern are // the same text (a classic tag has no '#' and no suffix) and ModernSuffix is empty. gamertagUsed counts the -// terminator. +// terminator. This is what the title's player-select prompt shows as " (A)"; the first call for each +// component is logged with its answer. HRESULT STDMETHODCALLTYPE user_get_gamertag(void*, XUserHandle user, XUserGamertagComponent component, size_t size, char* out, size_t* used) { if (used) *used = 0; - if (!valid(user)) return E_INVALIDARG; const char* text = nullptr; switch (component) { case XUserGamertagComponent::Classic: @@ -398,13 +472,24 @@ HRESULT STDMETHODCALLTYPE user_get_gamertag(void*, XUserHandle user, XUserGamert text = ""; break; default: - return E_INVALIDARG; + break; } - const size_t need = std::strlen(text) + 1; - if (!out || size < need) return kInsufficientBuffer; - std::memcpy(out, text, need); - if (used) *used = need; - return S_OK; + const size_t need = text ? std::strlen(text) + 1 : 0; + const HRESULT hr = !valid(user) || !text ? E_INVALIDARG : !out || size < need ? kInsufficientBuffer : S_OK; + if (hr == S_OK) { + std::memcpy(out, text, need); + if (used) *used = need; + } + static const char* const kNames[] = {"Classic", "Modern", "ModernSuffix", "UniqueModern", "unknown component"}; + static std::atomic s_logged[std::size(kNames)]; + const uint32_t c = static_cast(component); + const size_t index = c < 4 ? c : 4; + if (!s_logged[index].exchange(true)) + std::fprintf(stderr, "[rt] xgameruntime: XUser GetGamertag first call: %s (%u), handle %p, buffer %zu bytes -> " + "0x%08lx, \"%s\" (%zu bytes used)\n", + kNames[index], c, static_cast(user), size, hex(hr), hr == S_OK ? text : "", + hr == S_OK ? need : 0); + return hr; } // ---- The object: one vtable for the IXUserImpl..IXUserImpl6 chain, one for IXUserGamertagImpl ---- @@ -450,6 +535,7 @@ HRESULT query(REFIID iid, void** out) { // A process-wide singleton, as the other runtime classes: AddRef and Release don't free. HRESULT STDMETHODCALLTYPE object_query_interface(void*, REFIID iid, void** out) { return query(iid, out); } +#undef USER_FIRST_CALL ULONG STDMETHODCALLTYPE object_add_ref(void*) { return 2; } ULONG STDMETHODCALLTYPE object_release(void*) { return 1; } diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp index e5c5c4469d..82d8142d0f 100644 --- a/runtime/shims/xmem.cpp +++ b/runtime/shims/xmem.cpp @@ -18,6 +18,7 @@ #include #include +#include #include #include #include @@ -38,6 +39,10 @@ #include "shims.h" #include "startup_trace.h" #include "xmem.h" +#include "../src/dstorage_trace.h" +#include "../src/title_page_watch.h" +#include "../src/title_geometry_watch.h" +#include "../src/title_va_alias.h" namespace { @@ -69,14 +74,29 @@ void note_attributes(const char* api, uint64_t attributes, size_t size, const vo void* allocate_block(size_t size) { return _aligned_malloc(size ? size : 1, kAlign); } +// Every block and range the title gets here is recorded as the title's memory (src/title_va_alias.h): a shader +// address into it can be given a GPU copy, and an address anywhere else cannot. +void* title_block(size_t size) { + void* p = allocate_block(size); + if (p) leonida::title_memory_map::changed(); + leonida::title_va_aliases().add_title_memory(reinterpret_cast(p), size ? size : 1); + return p; +} + +void free_title_block(void* p) { + if (p) leonida::title_va_aliases().remove_title_memory(reinterpret_cast(p)); + _aligned_free(p); + if (p) leonida::title_memory_map::changed(); +} + void* __stdcall XMemAlloc(size_t size, uint64_t attributes) { note_attributes("XMemAlloc", attributes, size, _ReturnAddress()); - return allocate_block(size); + return title_block(size); } void __stdcall XMemFree(void* p, uint64_t attributes) { note_attributes("XMemFree", attributes, kNoSize, _ReturnAddress()); - _aligned_free(p); + free_title_block(p); } // XMemAllocDefault / XMemFreeDefault: the GDK's own allocator behind XMemAlloc and XMemFree, which a title that hooks @@ -85,12 +105,12 @@ void __stdcall XMemFree(void* p, uint64_t attributes) { // released by either free. void* __stdcall XMemAllocDefault(size_t size, uint64_t attributes) { note_attributes("XMemAllocDefault", attributes, size, _ReturnAddress()); - return allocate_block(size); + return title_block(size); } void __stdcall XMemFreeDefault(void* p, uint64_t attributes) { note_attributes("XMemFreeDefault", attributes, kNoSize, _ReturnAddress()); - _aligned_free(p); + free_title_block(p); } // BOOL XMemIsToolsMemAvailable(void). The measured title calls it from one helper, which six out-of-memory paths reach @@ -281,13 +301,25 @@ std::map g_windows; // base -> window std::unordered_map g_pages; // page number -> backing std::vector g_free_slots; uint64_t g_next_slot = 1; -struct MappedPage { - uint64_t page; - std::shared_ptr
section; - uint64_t offset; +// A mapped run: `count` pages of one section at consecutive offsets, mapped as one view at its base. One view per run +// rather than per page: under Wine each view costs a placeholder split and a section map whose time grows with the +// number of views, and the retail title maps about 100,000 pages in one call. +struct View { + uint64_t count; + std::shared_ptr
section; // kept for remapping part of the run after its pages are freed + uint64_t offset; // section offset of the first page + DWORD protect; }; - -std::unordered_map g_mapped; +leonida::host_heap::map g_views; // view base -> view; host_heap: see g_fault_lock + +// The views (g_views) as the fault handler reads them, which is all it reads: physical_page_fault takes it shared at +// every access violation in the process, xmem's own or not, and so does commit_physical_range. A title thread can +// take an access violation while it holds the process heap's lock (XMemAlloc is _aligned_malloc, so HeapAlloc and +// HeapFree write block headers on the title's pages: a page waiting for its first touch, or one a D3D12 shadow +// guards), and then waits here. So a thread that holds it exclusively must never wait for the process heap: it would +// wait for the faulting thread, which waits for it. Everything allocated or freed under it comes from +// leonida::host_heap (g_views, g_mapped, g_page_addresses, the sections, title_page_aliases), nothing under it logs, +// and nothing under it reads title memory, which could fault into the handler on the same thread. SRWLOCK g_fault_lock = SRWLOCK_INIT; struct FaultLockExclusive { @@ -302,10 +334,41 @@ struct FaultLockShared { ~FaultLockShared() { ReleaseSRWLockShared(&g_fault_lock); } FaultLockShared(const FaultLockShared&) = delete; FaultLockShared& operator=(const FaultLockShared&) = delete; + }; -// With g_phys_mutex held. A window replaces every window it overlaps: the title released those regions (with -// kernel32!VirtualFree, which the shim does not see) before the host could hand the addresses out again. +// With g_phys_mutex held; changed under g_fault_lock too (unmap_range), so they allocate from host_heap. +template +using HostUnorderedMap = + std::unordered_map, std::equal_to, leonida::host_heap::Allocator>>; +using AddressSet = std::set, leonida::host_heap::Allocator>; +HostUnorderedMap g_mapped; // mapped 64 KiB address -> page number +HostUnorderedMap g_page_addresses; // page number -> the addresses it is mapped at + +// With g_phys_mutex held. Keeps leonida::title_page_aliases in step: a page mapped at two or more addresses is +// aliased at each of them (the D3D12 layer's slot-133 shadows copy those pages at every submission instead of +// waiting for a write fault, which a write through another address doesn't raise). +void note_mapping(uint64_t page, uintptr_t address, bool mapped) { + auto& addresses = g_page_addresses[page]; + if (mapped) { + addresses.insert(address); + } else { + addresses.erase(address); + leonida::title_page_aliases::set(address, false); + } + using namespace leonida::geometry_writes; + if (state().count.load(std::memory_order_acquire)) { + notify(address, address + kPhysicalPageSize, Event::mapping); + for (auto other : addresses) + if (other != address) notify(other, other + kPhysicalPageSize, Event::mapping); + } + const bool aliased = addresses.size() > 1; + for (const uintptr_t at : addresses) leonida::title_page_aliases::set(at, aliased); + if (addresses.empty()) g_page_addresses.erase(page); +} + +// With g_phys_mutex held. A window replaces every window it overlaps: the title released those regions before +// the host could hand the addresses out again. void record_window(void* base, SIZE_T size, DWORD protect) { const uintptr_t start = reinterpret_cast(base); const uintptr_t end = start + size; @@ -337,7 +400,9 @@ bool isolate_placeholder(void* address, SIZE_T size) { return false; } if (info.AllocationBase == address && info.RegionSize == size) return true; - return VirtualFree(address, size, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER) != FALSE; + if (!VirtualFree(address, size, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)) return false; + leonida::title_memory_map::changed(); + return true; } PVOID reserve_placeholder(void* address, SIZE_T size, SIZE_T alignment) { @@ -354,6 +419,43 @@ PVOID reserve_placeholder(void* address, SIZE_T size, SIZE_T alignment) { PAGE_NOACCESS, parameter_count ? ¶meter : nullptr, parameter_count); } +// A new ordinary reservation of the title's (MEM_RESERVE, not a placeholder, not physical, not large pages) is made +// with MEM_WRITE_WATCH and recorded (leonida::title_write_watch): the D3D12 layer's shadows of these pages then ask the +// kernel which pages were written instead of making them read-only and taking a fault at the title's first write. +// `allocate(type)` makes the call. A host that refuses the flag gets the call without it, and the pages are guarded +// as before; so are they with LEONIDA_WRITE_WATCH=0. A reservation the title asked to be write-watched itself is not +// recorded: its bits are the title's (XMemGetWriteWatch). +template +void* reserve_watched(DWORD type, const void* address, SIZE_T size, Allocate&& allocate) { + constexpr DWORD kNotWatchable = MEM_WRITE_WATCH | MEM_PHYSICAL | MEM_LARGE_PAGES | MEM_RESERVE_PLACEHOLDER | + MEM_REPLACE_PLACEHOLDER | MEM_RESET | MEM_RESET_UNDO; + // A commit at no given address reserves too. + const bool reserves = (type & MEM_RESERVE) || (!address && (type & MEM_COMMIT)); + const bool watch = reserves && !(type & kNotWatchable) && leonida::title_write_watch::enabled(); + void* result = allocate(watch ? type | MEM_RESERVE | MEM_WRITE_WATCH : type); + if (!watch) return result; + if (!result) return allocate(type); + // The reservation is [result, end of the requested range): VirtualAlloc rounds a given address down to 64 KiB. + const uintptr_t base = reinterpret_cast(result); + const uintptr_t end = (address ? reinterpret_cast(address) : base) + size; + leonida::title_write_watch::add(base, end - base); + return result; +} + +// After a successful call that changes pages of an existing reservation without a write the kernel would see (a +// commit, which may bring back decommitted pages as zeros; MEM_RESET; a decommit with `decommit`): if it is +// write-watched, the shadows take [address, address + size) as written (size 0: to the reservation's end). +void note_unwatched_change(const void* address, SIZE_T size, DWORD type, bool decommit) { + if (!address || !(decommit || (type & (MEM_COMMIT | MEM_RESET | MEM_RESET_UNDO))) || (type & MEM_RESERVE)) return; + const auto from = reinterpret_cast(address); + const uintptr_t to = size ? from + size : leonida::title_write_watch::end_of(from); + if (to > from) { + leonida::title_write_watch::mark(from, to); + leonida::geometry_writes::notify(from, to, decommit ? leonida::geometry_writes::Event::replaced + : leonida::geometry_writes::Event::mapping); + } +} + // PVOID XMemVirtualAlloc(address, size, allocationType, attributes, protect). All 23 calls of the measured title pass a // nonzero attribute word; its bits are not decoded and nothing on the host depends on them, so it is accepted and only // recorded (xmem_attributes). Its types cover committed 2 MiB and 64 KiB pages, reserve-only 64 KiB windows for physical pages, one @@ -361,8 +463,39 @@ PVOID reserve_placeholder(void* address, SIZE_T size, SIZE_T alignment) { // XMemMapPhysicalPages. The guest page size sets the alignment and rounding of the region; the host's own pages stay // 4 KiB (host large pages need SeLockMemoryPrivilege). A 2 MiB region the host places is reserved 2 MiB-aligned through // VirtualAlloc2. +void* xmem_virtual_alloc(void* address, SIZE_T size, DWORD allocation_type, ULONGLONG attributes, DWORD protect); + void* WINAPI XMemVirtualAlloc(void* address, SIZE_T size, DWORD allocation_type, ULONGLONG attributes, DWORD protect) { note_attributes("XMemVirtualAlloc", attributes, size, _ReturnAddress()); + void* result = xmem_virtual_alloc(address, size, allocation_type, attributes, protect); + // The title's memory (src/title_va_alias.h). Never forgotten: a released range is no longer committed, which + // the copy also checks. + if (result) { + leonida::title_memory_map::changed(); + leonida::title_va_aliases().add_title_memory(reinterpret_cast(result), size); + note_unwatched_change(address, size, allocation_type, false); + if (allocation_type & MEM_RESERVE) { + const auto from = reinterpret_cast(result); + leonida::geometry_writes::notify(from, from + size, leonida::geometry_writes::Event::replaced); + } + } + // A reservation: a GPU-only one (no CPU access, PAGE_GRAPHICS_* bits) is paired with the CPU-mappable one of the + // same size made just before it (src/title_page_watch.h, title_gpu_views). + const DWORD host_type = allocation_type & kXmemHostAllocationTypeMask; + if (result && host_type && !(host_type & MEM_COMMIT)) { + const bool gpu_only = (protect & kPageGraphicsMask) && host_protect(protect) == PAGE_NOACCESS; + if (leonida::title_gpu_views::note_reservation(reinterpret_cast(result), size, gpu_only)) + std::fprintf(stderr, "[rt] xmem: GPU-only view %p (%llu MiB, protect 0x%lx) reads at the CPU view %p\n", + result, static_cast(size >> 20), static_cast(protect), + reinterpret_cast(leonida::title_gpu_views::to_cpu(reinterpret_cast(result)))); + else if (gpu_only && size >= (64u << 20)) + std::fprintf(stderr, "[rt] xmem: GPU-only reservation %p (%llu MiB, protect 0x%lx) has no CPU view\n", result, + static_cast(size >> 20), static_cast(protect)); + } + return result; +} + +void* xmem_virtual_alloc(void* address, SIZE_T size, DWORD allocation_type, ULONGLONG attributes, DWORD protect) { if (size == 0) { SetLastError(ERROR_INVALID_PARAMETER); return nullptr; @@ -460,25 +593,96 @@ void* WINAPI XMemVirtualAlloc(void* address, SIZE_T size, DWORD allocation_type, MEM_EXTENDED_PARAMETER parameter{}; parameter.Type = MemExtendedParameterAddressRequirements; parameter.Pointer = &requirements; - return placeholder_api().virtual_alloc2(GetCurrentProcess(), nullptr, size, host_type | MEM_RESERVE, host_prot, - ¶meter, 1); + return reserve_watched(host_type | MEM_RESERVE, nullptr, size, [&](DWORD type) { + return placeholder_api().virtual_alloc2(GetCurrentProcess(), nullptr, size, type, host_prot, ¶meter, 1); + }); } - return VirtualAlloc(address, size, host_type, host_prot); + return reserve_watched(host_type, address, size, + [&](DWORD type) { return VirtualAlloc(address, size, type, host_prot); }); } -// With g_phys_mutex held. Unmaps the page at `address` if one is mapped there; the address becomes a placeholder again. -bool unmap_page(uintptr_t address) { - const FaultLockExclusive lock; - const auto it = g_mapped.find(address); - if (it == g_mapped.end()) return true; - if (!placeholder_api().unmap_view2(GetCurrentProcess(), reinterpret_cast(address), - MEM_PRESERVE_PLACEHOLDER)) { - return false; +// With g_phys_mutex held. Maps `view` at the 64 KiB-aligned `address`, which holds no mapped page. MEM_REPLACE_PLACEHOLDER +// needs the view to fill one placeholder exactly, and earlier partial unmaps can leave several host placeholders in one +// run, so the run is mapped as one view per placeholder it spans. Views are capped at kMaxViewPages so that unmapping a +// page inside a long run only remaps the rest of one capped view, not the whole run. +constexpr uint64_t kMaxViewPages = 1024; // 64 MiB + + +bool map_view(uintptr_t address, const View& view) { + for (uint64_t mapped = 0; mapped < view.count;) { + const uintptr_t base = address + mapped * kPhysicalPageSize; + void* const target = reinterpret_cast(base); + MEMORY_BASIC_INFORMATION info{}; + if (!VirtualQuery(target, &info, sizeof(info)) || info.State != MEM_RESERVE || + info.RegionSize < kPhysicalPageSize) { + SetLastError(ERROR_INVALID_ADDRESS); + return false; + } + const uint64_t available = info.RegionSize / kPhysicalPageSize; + const uint64_t remaining = view.count - mapped; + const uint64_t count = (std::min)({available, remaining, kMaxViewPages}); + const SIZE_T size = static_cast(count * kPhysicalPageSize); + const uint64_t offset = view.offset + mapped * kPhysicalPageSize; + if (!isolate_placeholder(target, size)) return false; + if (!placeholder_api().map_view3(view.section->handle, GetCurrentProcess(), target, offset, size, + MEM_REPLACE_PLACEHOLDER, view.protect, nullptr, 0)) { + return false; + } + leonida::title_memory_map::changed(); + g_views.emplace(base, View{count, view.section, offset, view.protect}); + mapped += count; + } + return true; +} + +// With g_phys_mutex held. Unmaps every page in [start, end); the addresses become placeholders again. A view that +// reaches outside the range is unmapped whole, and its pages outside the range are mapped again, so neighbours keep +// their pages. +// There is no rollback: if mapping a remainder again fails, those neighbouring pages stay unmapped and the caller only +// sees the failure. +bool unmap_range(uintptr_t start, uintptr_t end) { + const FaultLockExclusive lock; // faults on neighbouring pages wait through the split and remap + auto it = g_views.upper_bound(start); + if (it != g_views.begin()) { + const auto prev = std::prev(it); + if (prev->first + prev->second.count * kPhysicalPageSize > start) it = prev; + } + while (it != g_views.end() && it->first < end) { + const uintptr_t base = it->first; + const View view = it->second; + const uintptr_t view_end = base + view.count * kPhysicalPageSize; + if (!placeholder_api().unmap_view2(GetCurrentProcess(), reinterpret_cast(base), + MEM_PRESERVE_PLACEHOLDER)) { + return false; + } + leonida::title_memory_map::changed(); + leonida::geometry_writes::notify(base, view_end, leonida::geometry_writes::Event::replaced); + it = g_views.erase(it); + // The pages of [start, end) this view held are unmapped now; the ones outside it are mapped again below. + for (uintptr_t at = (std::max)(base, start); at < (std::min)(view_end, end); at += kPhysicalPageSize) { + if (const auto mapped = g_mapped.find(at); mapped != g_mapped.end()) { + note_mapping(mapped->second, at, false); + g_mapped.erase(mapped); + } + } + if (base < start) { + View left = view; + left.count = (start - base) / kPhysicalPageSize; + if (!map_view(base, left)) return false; + } + if (view_end > end) { + const uint64_t skipped = (end - base) / kPhysicalPageSize; + View right = view; + right.count = view.count - skipped; + right.offset += skipped * kPhysicalPageSize; + return map_view(end, right); // the last view the range touches + } } - g_mapped.erase(it); return true; } +bool unmap_page(uintptr_t address) { return unmap_range(address, address + kPhysicalPageSize); } + // With g_phys_mutex held. Maps physical page `page` (0: unmap) at the 64 KiB-aligned `address`, replacing what was // mapped there. The caller has found the window. bool map_page(uintptr_t address, uint64_t page, DWORD protect) { @@ -489,22 +693,23 @@ bool map_page(uintptr_t address, uint64_t page, DWORD protect) { SetLastError(ERROR_INVALID_PARAMETER); return false; } - void* const target = reinterpret_cast(address); - if (!isolate_placeholder(target, kPhysicalPageSize)) return false; - const FaultLockExclusive lock; - void* const view = placeholder_api().map_view3(it->second.section->handle, GetCurrentProcess(), target, - it->second.offset, kPhysicalPageSize, MEM_REPLACE_PLACEHOLDER, - protect, nullptr, 0); - if (!view) return false; - g_mapped[address] = MappedPage{page, it->second.section, it->second.offset}; + { + const FaultLockExclusive lock; + if (!map_view(address, View{1, it->second.section, it->second.offset, protect})) return false; + } + g_mapped[address] = page; + note_mapping(page, address, true); return true; } enum class PageCommit { not_ours, committed_before, committed_now, failed }; PageCommit commit_mapped_page(uintptr_t address, uintptr_t accessed, DWORD& protect) { - const auto it = g_mapped.find(address); - if (it == g_mapped.end() || !it->second.section->scratch) return PageCommit::not_ours; + auto it = g_views.upper_bound(address); + if (it == g_views.begin()) return PageCommit::not_ours; + --it; + const uintptr_t within = address - it->first; + if (within / kPhysicalPageSize >= it->second.count || !it->second.section->scratch) return PageCommit::not_ours; MEMORY_BASIC_INFORMATION info{}; if (!VirtualQuery(reinterpret_cast(accessed), &info, sizeof(info)) || info.Type != MEM_MAPPED) { return PageCommit::not_ours; @@ -513,9 +718,11 @@ PageCommit commit_mapped_page(uintptr_t address, uintptr_t accessed, DWORD& prot protect = info.Protect; return PageCommit::committed_before; } - void* const backing = static_cast(it->second.section->scratch) + it->second.offset; - return VirtualAlloc(backing, kPhysicalPageSize, MEM_COMMIT, PAGE_READWRITE) ? PageCommit::committed_now - : PageCommit::failed; + void* const backing = static_cast(it->second.section->scratch) + it->second.offset + within; + if (!VirtualAlloc(backing, kPhysicalPageSize, MEM_COMMIT, PAGE_READWRITE)) return PageCommit::failed; + leonida::geometry_writes::notify(address, address + kPhysicalPageSize, leonida::geometry_writes::Event::mapping); + leonida::title_memory_map::changed(); + return PageCommit::committed_now; } bool access_allowed(DWORD protect, ULONG_PTR access) { @@ -632,7 +839,8 @@ BOOL WINAPI XMemAllocatePhysicalPages(uint64_t attributes, uint64_t* page_count, *page_count = 0; return FALSE; } - const auto section = std::make_shared
(handle); + // From host_heap: the unmap that drops the last reference frees it under g_fault_lock. + const auto section = std::allocate_shared
(leonida::host_heap::Allocator
{}, handle); if (!section->scratch) { *page_count = 0; return FALSE; @@ -665,12 +873,14 @@ BOOL WINAPI XMemFreePhysicalPages(uint64_t page_count, const uint64_t* page_arra for (uint64_t i = 0; i < page_count; ++i) { const auto it = g_pages.find(page_array[i]); if (it == g_pages.end()) { + if (i != 0) leonida::title_memory_map::changed(); SetLastError(ERROR_INVALID_PARAMETER); return FALSE; } g_pages.erase(it); g_free_slots.push_back(page_array[i] / kFramesPerPage); } + if (page_count != 0) leonida::title_memory_map::changed(); return TRUE; } @@ -679,8 +889,9 @@ BOOL WINAPI XMemFreePhysicalPages(uint64_t page_count, const uint64_t* page_arra // or null to unmap that many (four calls at shutdown). Callers test the 64-bit result for zero, so it is the address on // success. A page number of 0 in the array unmaps that one page. // -// Each page is its own view (MapViewOfFile3 into a 64 KiB placeholder), so any page can be remapped or unmapped later -// without touching its neighbours. A failure part-way leaves the pages before it mapped. +// Consecutive pages of one allocation are mapped as one view (MapViewOfFile3 into a placeholder of their size); a +// page remapped or unmapped later splits its view, and its neighbours stay mapped. The range is unmapped first, so a +// page number that is not a live page fails with the pages before it mapped and the rest of the range unmapped. void* WINAPI XMemMapPhysicalPages(void* address, uint64_t page_count, const uint64_t* page_array) { const uintptr_t start = reinterpret_cast(address); if (!aligned_page_address(start) || page_count > (std::numeric_limits::max)() / kPhysicalPageSize || @@ -693,20 +904,46 @@ void* WINAPI XMemMapPhysicalPages(void* address, uint64_t page_count, const uint return nullptr; } const std::lock_guard lock(g_phys_mutex); - if (!page_array) { - for (uint64_t i = 0; i < page_count; ++i) { - if (!unmap_page(start + i * kPhysicalPageSize)) return nullptr; - } - return address; - } + const uintptr_t end = start + page_count * kPhysicalPageSize; + if (!page_array) return unmap_range(start, end) ? address : nullptr; const Window* const window = find_window(start, page_count * kPhysicalPageSize); if (!window) { SetLastError(ERROR_INVALID_ADDRESS); return nullptr; } const DWORD protect = view_protect(*window); - for (uint64_t i = 0; i < page_count; ++i) { - if (!map_page(start + i * kPhysicalPageSize, page_array[i], protect)) return nullptr; + if (!unmap_range(start, end)) return nullptr; + for (uint64_t i = 0; i < page_count;) { + if (page_array[i] == 0) { + ++i; + continue; + } + const auto it = g_pages.find(page_array[i]); + if (it == g_pages.end()) { + SetLastError(ERROR_INVALID_PARAMETER); + return nullptr; + } + View view{1, it->second.section, it->second.offset, protect}; + while (i + view.count < page_count) { + const auto next = g_pages.find(page_array[i + view.count]); + if (next == g_pages.end() || next->second.section != view.section || + next->second.offset != view.offset + view.count * kPhysicalPageSize) { + break; + } + ++view.count; + } + { + const FaultLockExclusive view_lock; + if (!map_view(start + i * kPhysicalPageSize, view)) return nullptr; + } + // After the fault lock: page_array is the title's memory, and a read of it that faults would wait for the + // lock on this thread. g_mapped and the aliases are g_phys_mutex's; the fault handler reads neither. + for (uint64_t k = 0; k < view.count; ++k) { + const uintptr_t at = start + (i + k) * kPhysicalPageSize; + g_mapped[at] = page_array[i + k]; + note_mapping(page_array[i + k], at, true); + } + i += view.count; } return address; } @@ -746,12 +983,24 @@ BOOL WINAPI XMemMapPhysicalPagesScatter(void* const* addresses, uint32_t page_co return TRUE; } +// The title's write watching, on reservations it made with MEM_WRITE_WATCH. One xmem write-watched for the shadows +// (reserve_watched) is refused as the host refuses a region that is not write-watched ((UINT)-1, +// ERROR_INVALID_PARAMETER), as the console would: it isn't write-watched there, and a reset here would clear the bits +// the shadows ask about. +bool shadows_write_watch(const void* base_address) { + if (!leonida::title_write_watch::contains(reinterpret_cast(base_address))) return false; + SetLastError(ERROR_INVALID_PARAMETER); + return true; +} + UINT WINAPI XMemGetWriteWatch(DWORD flags, void* base_address, SIZE_T region_size, void** addresses, ULONG_PTR* count, ULONG* granularity) { + if (shadows_write_watch(base_address)) return UINT(-1); return GetWriteWatch(flags, base_address, region_size, addresses, count, granularity); } UINT WINAPI XMemResetWriteWatch(void* base_address, SIZE_T region_size) { + if (shadows_write_watch(base_address)) return UINT(-1); return ResetWriteWatch(base_address, region_size); } @@ -811,14 +1060,56 @@ BOOL WINAPI XMemTransferMemory(uint32_t type, SIZE_T size) { constexpr DWORD kMemGraphics = 0x10000000; constexpr DWORD kMemTitle = 0x40000000; +// A new reservation is write-watched for the D3D12 layer's shadows (reserve_watched). LPVOID WINAPI TitleVirtualAlloc(LPVOID address, SIZE_T size, DWORD allocation_type, DWORD protect) { - return VirtualAlloc(address, size, allocation_type & ~(kMemGraphics | kMemTitle), host_protect(protect)); + const DWORD type = allocation_type & ~(kMemGraphics | kMemTitle); + const DWORD host_prot = host_protect(protect); + LPVOID result = + reserve_watched(type, address, size, [&](DWORD t) { return VirtualAlloc(address, size, t, host_prot); }); + if (result) { + leonida::title_memory_map::changed(); + leonida::title_va_aliases().add_title_memory(reinterpret_cast(result), size); + note_unwatched_change(address, size, type, false); + if (type & MEM_RESERVE) { + const auto from = reinterpret_cast(result); + leonida::geometry_writes::notify(from, from + size, leonida::geometry_writes::Event::replaced); + } + } + return result; +} + +BOOL WINAPI TitleVirtualFree(LPVOID address, SIZE_T size, DWORD free_type) { + const BOOL result = VirtualFree(address, size, free_type); + if (result) leonida::title_memory_map::changed(); + if (result && (free_type & MEM_DECOMMIT)) note_unwatched_change(address, size, 0, true); + if (result && (free_type & MEM_RELEASE) && !(free_type & MEM_PRESERVE_PLACEHOLDER)) + leonida::title_write_watch::remove(reinterpret_cast(address)); + return result; +} + +BOOL WINAPI TitleVirtualProtect(LPVOID address, SIZE_T size, DWORD protect, PDWORD old) { + const BOOL result = VirtualProtect(address, size, protect, old); + if (result) { + leonida::title_memory_map::changed(); + const auto start = reinterpret_cast(address); + leonida::geometry_writes::notify(start, start + size, leonida::geometry_writes::Event::replaced); + } + return result; } } // namespace namespace rt::xmem { +void geometry_aliases(std::uintptr_t va, std::vector& addresses) { + std::lock_guard lock(g_phys_mutex); + const auto mapped = g_mapped.find(va); + if (mapped == g_mapped.end()) return; + const auto peers = g_page_addresses.find(mapped->second); + if (peers != g_page_addresses.end()) + for (auto other : peers->second) if (other != va) addresses.push_back(other); +} + bool commit_physical_range(const void* address, size_t size) { if (size == 0) return true; const uintptr_t start = reinterpret_cast(address); @@ -838,13 +1129,12 @@ bool commit_physical_range(const void* address, size_t size) { return true; } -bool commit_physical_pages(const uint64_t* page_array, size_t count) { +static bool commit_pages_locked(const uint64_t* page_array, size_t count) { if (count == 0) return true; if (!page_array) { SetLastError(ERROR_INVALID_PARAMETER); return false; } - const std::lock_guard lock(g_phys_mutex); size_t first = 0; while (first < count) { const auto it = g_pages.find(page_array[first]); @@ -863,26 +1153,68 @@ bool commit_physical_pages(const uint64_t* page_array, size_t count) { } void* const backing = static_cast(it->second.section->scratch) + it->second.offset; if (!VirtualAlloc(backing, (last - first) * kPhysicalPageSize, MEM_COMMIT, PAGE_READWRITE)) return false; + leonida::title_memory_map::changed(); first = last; } return true; } +bool commit_physical_pages(const uint64_t* page_array, size_t count) { + const std::lock_guard lock(g_phys_mutex); + return commit_pages_locked(page_array, count); +} + +bool transfer_physical(std::span pages, uint16_t offset, std::span staging, bool write) { + if (staging.empty()) return true; + if (pages.size() != 1 + (staging.size() - 1 + offset) / kPhysicalPageSize) { + SetLastError(ERROR_INVALID_PARAMETER); + return false; + } + const std::lock_guard lock(g_phys_mutex); + if (!commit_pages_locked(pages.data(), pages.size())) return false; + for (const auto page : pages) { + const auto& backing = g_pages.at(page); + auto* ptr = static_cast(backing.section->scratch) + backing.offset + offset; + const size_t bytes = (std::min)(staging.size(), size_t(kPhysicalPageSize - offset)); + if (write) { + std::memcpy(ptr, staging.data(), bytes); + if (auto mapped = g_page_addresses.find(page); mapped != g_page_addresses.end()) { + for (uintptr_t address : mapped->second) { + leonida::geometry_writes::notify(address + offset, address + offset + bytes, leonida::geometry_writes::Event::write); + leonida::title_texel_writes::note(reinterpret_cast(address + offset), bytes); + if (leonida::dstorage::trace_enabled()) + std::fprintf(stderr, "[rt] ds-scatter cpu=%llx bytes=%zu page=%llu\n", + static_cast(address + offset), bytes, + static_cast(page)); + } + } + } else { + std::memcpy(staging.data(), ptr, bytes); + } + staging = staging.subspan(bytes); + offset = 0; + } + return true; +} + } -#define TITLE_VIRTUAL_ALLOC(dll) {dll, "VirtualAlloc", reinterpret_cast(&TitleVirtualAlloc)} +#define TITLE_VIRTUAL_MEMORY(dll) \ + {dll, "VirtualAlloc", reinterpret_cast(&TitleVirtualAlloc)}, \ + {dll, "VirtualFree", reinterpret_cast(&TitleVirtualFree)}, \ + {dll, "VirtualProtect", reinterpret_cast(&TitleVirtualProtect)} // The classic libraries and the memory api sets a title's imports name. SHIM_TABLE(title_memory, - TITLE_VIRTUAL_ALLOC("kernel32.dll"), - TITLE_VIRTUAL_ALLOC("kernelbase.dll"), - TITLE_VIRTUAL_ALLOC("api-ms-win-core-memory-l1-1-0.dll"), - TITLE_VIRTUAL_ALLOC("api-ms-win-core-memory-l1-1-1.dll"), - TITLE_VIRTUAL_ALLOC("api-ms-win-core-memory-l1-1-2.dll"), - TITLE_VIRTUAL_ALLOC("api-ms-win-core-memory-l1-1-3.dll"), - TITLE_VIRTUAL_ALLOC("api-ms-win-core-memory-l1-1-4.dll"), - TITLE_VIRTUAL_ALLOC("api-ms-win-core-memory-l1-1-5.dll"), - TITLE_VIRTUAL_ALLOC("api-ms-win-core-memory-l1-1-6.dll"), + TITLE_VIRTUAL_MEMORY("kernel32.dll"), + TITLE_VIRTUAL_MEMORY("kernelbase.dll"), + TITLE_VIRTUAL_MEMORY("api-ms-win-core-memory-l1-1-0.dll"), + TITLE_VIRTUAL_MEMORY("api-ms-win-core-memory-l1-1-1.dll"), + TITLE_VIRTUAL_MEMORY("api-ms-win-core-memory-l1-1-2.dll"), + TITLE_VIRTUAL_MEMORY("api-ms-win-core-memory-l1-1-3.dll"), + TITLE_VIRTUAL_MEMORY("api-ms-win-core-memory-l1-1-4.dll"), + TITLE_VIRTUAL_MEMORY("api-ms-win-core-memory-l1-1-5.dll"), + TITLE_VIRTUAL_MEMORY("api-ms-win-core-memory-l1-1-6.dll"), ); SHIM_TABLE(xmem, diff --git a/runtime/shims/xmem.h b/runtime/shims/xmem.h index beef935e65..c60ccf5d30 100644 --- a/runtime/shims/xmem.h +++ b/runtime/shims/xmem.h @@ -2,10 +2,18 @@ #include #include +#include +#include namespace rt::xmem { +void geometry_aliases(std::uintptr_t va, std::vector& addresses); bool commit_physical_range(const void* address, std::size_t size); bool commit_physical_pages(const std::uint64_t* page_array, std::size_t count); +// Copy a validated DirectStorage staging buffer through the page table. The page list has +// one frame number per 64 KiB page. All pages are resolved before a write starts. +bool transfer_physical(std::span pages, std::uint16_t offset, + std::span staging, bool write); + } diff --git a/runtime/src/bcpack.cpp b/runtime/src/bcpack.cpp new file mode 100644 index 0000000000..bb4646787e --- /dev/null +++ b/runtime/src/bcpack.cpp @@ -0,0 +1,423 @@ +// C++ port of tools/bcpack.py. The build derives the model and BCn format +// constants from that same reference. +#include "bcpack.h" +#include "bcpack_stream.h" +#include +#include +#include +#include + +namespace leonida::bcpack { +namespace { +using namespace detail; + +void color(uint8_t *dst, const int *e, int a, int b, int c, int d) { + for (int i = 0; i < 2; ++i, e += 3) { + const int rgb = (e[0] << 11) | (e[1] << 5) | e[2]; + dst[i * 2] = uint8_t(rgb); + dst[i * 2 + 1] = uint8_t(rgb >> 8); + } + dst[4] = uint8_t((a & 15) | (b << 4)); + dst[5] = uint8_t((a >> 4) | (b & 240)); + dst[6] = uint8_t((c & 15) | (d << 4)); + dst[7] = uint8_t((c >> 4) | (d & 240)); +} + +struct Endpoints { + int v[8]{}; +}; + +bool rebuild_classic(unsigned codec, size_t i, const Symbols &a, + const Symbols &b, array &past, + uint8_t *dst, bool allow_fitted, Quality &quality) { + const bool single = codec == 1 || codec == 4; + if (a[1] || b[1]) + return false; + const unsigned distance = unzig(single ? a[0] : interleave(a[0], b[0])) & 255; + Endpoints e; + const int count = codec == 1 ? 6 : codec == 3 ? 8 : codec == 4 ? 2 : 4; + if (!distance) { + if (codec != 1) + fill_n(e.v, codec == 5 ? 4 : 2, 128); + } else if (distance <= i) { + e = past[(i - distance) & 255]; + } else { + const unsigned slot = (i - distance) & 255; + const Seed &seed = codec == 1 ? history1[slot] + : codec == 3 ? history3[slot] + : codec == 4 ? history4[slot] + : history5[slot]; + if (seed.values[0] < 0 || (seed.fitted && !allow_fitted)) + return false; + if (seed.fitted) + quality = Quality::fitted; + copy_n(seed.values, count, e.v); + } + const int alpha = codec == 1 ? 0 : codec == 5 ? 4 : 2; + for (int k = 0; k < count; ++k) { + const int coord = k - alpha; + const int mask = coord < 0 ? 255 : coord % 3 == 1 ? 63 : 31; + const int symbol = single ? a[2 + k] + : coord < 0 ? (k % 2 ? b : a)[2 + k / 2] + : (coord < 3 ? a : b)[7 + coord % 3]; + e.v[k] = (e.v[k] + unzig(symbol)) & mask; + } + past[i & 255] = e; + for (int ch = 0; ch < alpha / 2; ++ch) { + const auto *pairs = codec == 3 ? pair3 : codec == 4 ? pair4 : pair5; + uint64_t bits = 0; + for (int row = 0; row < 4; ++row) { + const int lane = + codec == 4 ? 4 + 2 * row : (codec == 3 ? 3 : 4 + 4 * ch) + row; + const int right = single ? a[lane + 1] : b[lane]; + bits |= uint64_t(pairs[a[lane]] | (pairs[right] << 6)) << (12 * row); + } + *dst++ = uint8_t(e.v[ch * 2]); + *dst++ = uint8_t(e.v[ch * 2 + 1]); + for (int j = 0; j < 6; ++j) + *dst++ = uint8_t(bits >> (8 * j)); + } + if (codec == 1) + color(dst, e.v, quad1[a[8]], quad1[a[9]], quad1[a[10]], quad1[a[11]]); + if (codec == 3) + color(dst, e.v + 2, quad3[a[10]], quad3[b[10]], quad3[a[11]], quad3[b[11]]); + return true; +} + +struct BitWriter { + uint8_t *dst; + int pos{}, violations{}; + void put(int value, int bits) { + while (bits > 0) { + const int n = min(bits, 8 - pos % 8); + dst[pos / 8] |= uint8_t((value & ((1 << n) - 1)) << (pos % 8)); + value >>= n; + bits -= n; + pos += n; + } + } +}; + +// Endpoints and indices have independent predictors, with distances limited to +// eight bits. +struct BptcState { + array ep{}; + array ix{}; + int ep_root = -1, ix_root = -1; +}; +int mod_bits(int v, int n) { return v & ((1 << n) - 1); } + +void index_row(int a, int b, int row, int bits, const int *ref, int *value, + int *history) { + for (int x = 0; x < 4; ++x) { + const int s = (x < 2 ? a : b) >> ((x % 2) ^ (row < 3)); + const int delta = + (s & 1) | ((s >> 1) & 2) | ((s >> 2) & 4) | ((s >> 3) & 8); + const int p = 4 * row + x; + value[p] = mod_bits((ref[p] >> (4 - bits)) + unzig(delta), bits); + history[p] = value[p] << (4 - bits); + } +} + +bool put_indices(BitWriter &writer, const int *values, int bits, + int anchor1 = -1, int anchor2 = -1) { + for (int p = 0; p < 16; ++p) { + const int n = bits - (p == 0 || p == anchor1 || p == anchor2); + if (values[p] >> n) + ++writer.violations; + writer.put(values[p], n); + } + return true; +} + +bool bc6(const Symbols &a, const Symbols &b, const BptcState &ep, + const BptcState &ix, BptcState &next, BitWriter &writer) { + if (a[15] >= 14) + return false; + const auto &m = bc6Modes[a[15]]; + const int partition = min(b[15], 31), base_shift = 16 - m.base; + int fields[3][4]{}; + for (int c = 0; c < 3; ++c) { + const int n = m.delta[c], shift = max(0, 6 - n); + const auto *ref = &ep.ep[c * 4]; + const int w = mod_bits((ref[0] >> base_shift) + + unzig(interleave(a[2 + c], b[2 + c], 8)), + m.base); + const int x = mod_bits( + (ref[1] >> (10 - n)) + unzig(interleave(a[5 + c], b[5 + c], 5)), n); + const int y = mod_bits((ref[2] >> shift) + unzig(a[8 + c]), n); + const int z = mod_bits((ref[3] >> shift) + unzig(b[8 + c]), n); + auto *state = &next.ep[c * 4]; + state[0] = w << base_shift; + state[1] = x << (10 - n); + if (m.regions == 2) { + state[2] = y << shift; + state[3] = z << shift; + } else { + const int v = mod_bits(w, n) ^ (m.transformed << (n - 1)); + state[2] = n >= 6 ? v >> (n - 6) : v << shift; + state[3] = state[1] >> 4; + } + fields[c][0] = w; + if (a[15] >= 12) { + fields[c][0] &= 1023; + for (int bit = 10; bit < m.base; ++bit) + fields[c][0] |= ((w >> bit) & 1) << (m.base + 9 - bit); + } + fields[c][1] = x; + fields[c][2] = y; + fields[c][3] = z; + } + writer.put(m.code, m.code < 2 ? 2 : 5); + for (int j = 0; j < m.count; ++j) { + const auto &f = bc6Plan[m.first + j]; + writer.put((f[0] < 0 ? partition : fields[f[0]][f[1]]) >> f[2], 1); + } + int values[16]; + const int bits = m.regions == 2 ? 3 : 4; + for (int y = 0; y < 4; ++y) + index_row(a[11 + y], b[11 + y], y, bits, ix.ix.data(), values, + next.ix.data()); + return put_indices(writer, values, bits, + m.regions == 2 ? anchor2[partition] : -1); +} + +bool bc7(const Symbols &a, const Symbols &b, const BptcState &ep, + const BptcState &ix, BptcState &next, BitWriter &writer) { + if (a[15] >= 32 || b[15] >= 16) + return false; + const auto &cfg = bc7Config[a[15] * 16 + b[15]]; + const auto [tag, part, rot, isel] = cfg; + const int mode = tag & 127; + if (mode > 7 || part >= 64) + return false; + const auto &f = bc7_formats[mode]; + int widths[4] = {f.color, f.color, f.color, f.alpha}; + if (rot) + swap(widths[rot - 1], widths[3]); + constexpr int lane[3][4] = {{2, 3, 4, 5}, {6, 7, 8, 9}, {10, 5, 9, -1}}; + int v[3][2][4]{}; + for (int sub = 0; sub < f.subsets; ++sub) { + for (int end = 0; end < 2; ++end) { + for (int c = 0; c < 4; ++c) { + if (!widths[c] || lane[sub][c] < 0) + continue; + const int n = widths[c] + (f.pbits && c == 0); + const int k = 8 * sub + 4 * end + c; + v[sub][end][c] = mod_bits( + (ep.ep[k] >> (8 - n)) + unzig((end ? b : a)[lane[sub][c]]), n); + next.ep[k] = v[sub][end][c] << (8 - n); + } + } + if (f.pbits == 2 && ((v[sub][0][0] ^ v[sub][1][0]) & 1)) + ++writer.violations; + } + for (int sub = f.subsets; sub < 3; ++sub) + copy_n(next.ep.begin(), 8, next.ep.begin() + 8 * sub); + int primary[16], secondary[16]; + constexpr int second_rows[] = {6, 7, 8, 10}; + const bool two = mode == 4 || mode == 5; + for (int y = 0; y < 4; ++y) { + index_row(a[11 + y], b[11 + y], y, f.index, ix.ix.data(), primary, + next.ix.data()); + if (two) + index_row(a[second_rows[y]], b[second_rows[y]], y, 2, ix.ix.data() + 16, + secondary, next.ix.data() + 16); + } + if (mode == 0 && part == 0 && + ranges::all_of(next.ep, [](int v) { return !v; }) && + ranges::all_of(primary, [](int v) { return !v; })) + return true; + + writer.put(1 << mode, mode + 1); + writer.put(part, f.partition); + if (two) + writer.put(rot, 2); + if (mode == 4) + writer.put(isel, 1); + for (int c = 0; c < 4; ++c) { + const int src = rot && c == rot - 1 ? 3 : rot && c == 3 ? rot - 1 : c; + for (int sub = 0; sub < f.subsets; ++sub) + for (int end = 0; end < 2; ++end) + writer.put(v[sub][end][src] >> (f.pbits && src == 0), + c == 3 ? f.alpha : f.color); + } + if (f.pbits) { + for (int sub = 0; sub < f.subsets; ++sub) + for (int end = 0; end < (f.pbits == 1 ? 2 : 1); ++end) + writer.put(v[sub][end][0], 1); + } + const int anc1 = f.subsets == 2 ? anchor2[part] + : f.subsets == 3 ? anchor3a[part] + : -1; + const int anc2 = f.subsets == 3 ? anchor3b[part] : -1; + if (mode == 4) + return put_indices(writer, secondary, 2) && + put_indices(writer, primary, f.index); + return put_indices(writer, primary, f.index, anc1, anc2) && + (!two || put_indices(writer, secondary, 2)); +} + +// A predictor can influence later blocks through either independent reference +// chain. A bit-depth gap discovered during the first 256 blocks also affects +// earlier uses of the slot. +struct Coverage { + array missing_ep{}, missing_ix{}; + size_t lost{}, inconsistent{}, limit{}; + bool lost_endpoints{}, lost_indices{}; + void note_missing(const BptcState &block) { + const bool ep = block.ep_root >= 0 && missing_ep[block.ep_root]; + const bool ix = block.ix_root >= 0 && missing_ix[block.ix_root]; + lost += ep || ix; + lost_endpoints |= ep; + lost_indices |= ix; + } +}; + +bool rebuild_bptc(unsigned codec, size_t i, size_t blocks, const Symbols &a, + const Symbols &b, array &past, uint8_t *dest, + const Calibration *history, bool allow_fitted, + Quality &quality, Coverage &coverage, const char*& reason) { + const unsigned di = interleave(a[1], b[1]); + const unsigned de = (di + unzig(interleave(a[0], b[0]))) & 255; + if ((di > i || de > i) && !history) { + reason = "missing-profile"; + return false; + } + const int islot = di > i ? int(256 + i - di) : -1; + const int eslot = de > i ? int(256 + i - de) : -1; + bool fitted = false; + BptcState zero{}; + if (codec == 6) { + for (int c = 0; c < 3; ++c) { + zero.ep[4 * c] = 32768; + zero.ep[4 * c + 1] = 512; + zero.ep[4 * c + 2] = zero.ep[4 * c + 3] = 32; + } + zero.ix.fill(8); + } + if (codec == 6) { + if (a[15] >= 14) + return false; + const auto &m = bc6Modes[a[15]]; + if (eslot >= 0) { + const auto &row = history->bc6[eslot]; + for (int c = 0; c < 3; ++c) { + const int needs[] = {m.base, m.delta[c], + m.regions == 2 ? m.delta[c] : 0, + m.regions == 2 ? m.delta[c] : 0}; + for (int k = 0; k < 4; ++k) { + const int j = 4 * c + k; + zero.ep[j] = row.ep[2 * j] | (row.ep[2 * j + 1] << 8); + fitted |= row.ep_confirmed[j] < needs[k]; + } + } + fitted |= row.ep_class != 3; + coverage.missing_ep[eslot] |= !row.ep_class; + } + if (islot >= 0) { + const auto &row = history->bc6[islot]; + copy(row.ix.begin(), row.ix.end(), zero.ix.begin()); + fitted |= + row.ix_class != 3 || ranges::any_of(row.ix_confirmed, [&](int n) { + return n < (m.regions == 2 ? 3 : 4); + }); + coverage.missing_ix[islot] |= !row.ix_class; + } + } else { + if (a[15] >= 32 || b[15] >= 16) + return false; + const auto &cfg = bc7Config[a[15] * 16 + b[15]]; + const unsigned mode = cfg[0] & 127; + if (mode >= 8 || cfg[1] >= 64) + return false; + if (cfg[0] & 128) + fitted = true; + const auto &format = bc7_formats[mode]; + if (eslot >= 0) { + const auto &row = history->bc7[eslot]; + copy(row.ep.begin(), row.ep.end(), zero.ep.begin()); + int width[] = {format.color, format.color, format.color, format.alpha}; + if (cfg[2]) + swap(width[3], width[cfg[2] - 1]); + width[0] += format.pbits != 0; + for (int j = 0; j < 8 * format.subsets; ++j) { + const int need = width[j % 4]; + fitted |= row.ep_confirmed[j] < need || row.ep_bits[j] < need; + coverage.missing_ep[eslot] |= row.ep_bits[j] < min(need, 4); + } + } + if (islot >= 0) { + const auto &row = history->bc7[islot]; + copy(row.ix.begin(), row.ix.end(), zero.ix.begin()); + for (int j = 0; j < (mode == 4 || mode == 5 ? 32 : 16); ++j) { + int need = j < 16 ? format.index : 2; + fitted |= row.ix_confirmed[j] < need || row.ix_bits[j] < need; + coverage.missing_ix[islot] |= row.ix_bits[j] < need; + } + } + } + if (fitted) { + if (!allow_fitted) { + reason = "unconfirmed-predictor"; + return false; + } + quality = Quality::fitted; + } + const auto &ep = de && eslot < 0 ? past[(i - de) & 255] : zero; + const auto &ix = di && islot < 0 ? past[(i - di) & 255] : zero; + auto &next = past[i & 255]; + next = {}; + next.ep_root = eslot >= 0 ? eslot : ep.ep_root; + next.ix_root = islot >= 0 ? islot : ix.ix_root; + fill_n(dest, 16, 0); + BitWriter writer{dest}; + const bool valid = codec == 6 ? bc6(a, b, ep, ix, next, writer) + : bc7(a, b, ep, ix, next, writer); + coverage.inconsistent += + codec == 6 ? writer.violations : int(writer.violations != 0); + if (i + 1 == min(256, blocks)) { + for (size_t k = 0; k <= i; ++k) + coverage.note_missing(past[k]); + } else if (i >= 256) + coverage.note_missing(next); + if (!valid) return false; + if (coverage.lost > coverage.limit) { + reason = coverage.lost_endpoints && coverage.lost_indices ? "missing-endpoint-and-index" : + coverage.lost_endpoints ? "missing-endpoint" : "missing-index"; + return false; + } + if (coverage.inconsistent > coverage.limit) { reason = "anchor-or-pbit"; return false; } + return true; +} +} // namespace + +Quality decode(unsigned codec, std::span source, + std::span output, bool allow_fitted, + const Calibration *history, const char** failure, bool fast_entropy) { + const char* reason = "bcpack-stream"; + if (failure) *failure = reason; + Quality quality = Quality::confirmed; + if (!codec || codec == 2 || codec > 7) + return Quality::failed; + const bool single = codec == 1 || codec == 4; + const unsigned block_size = single ? 8 : 16; + if (output.size() % block_size) + return Quality::failed; + array classic{}; + array bptc{}; + Coverage coverage{}; + coverage.limit = allow_fitted && history + ? max(2, output.size() / block_size / 1024) + : 0; + const bool valid = visit_blocks(codec, source, output.size(), [&](size_t i, const Symbols &first, const Symbols &tuple) { + auto *dst = output.data() + i * block_size; + if (codec >= 6) + return rebuild_bptc(codec, i, output.size() / block_size, first, tuple, bptc, dst, history, allow_fitted, quality, coverage, reason); + return rebuild_classic(codec, i, first, tuple, classic, dst, allow_fitted, quality); + }, fast_entropy); + if (valid && (!coverage.inconsistent || quality == Quality::fitted)) return quality; + if (failure) *failure = coverage.inconsistent && valid ? "anchor-or-pbit" : reason; + return Quality::failed; +} +} // namespace leonida::bcpack diff --git a/runtime/src/bcpack.h b/runtime/src/bcpack.h new file mode 100644 index 0000000000..9c34a074ba --- /dev/null +++ b/runtime/src/bcpack.h @@ -0,0 +1,33 @@ +// C++ BCPack decoder. Publish the caller's staged output only on success. +#pragma once +#include +#include +#include + +namespace leonida::bcpack { +enum class Quality { failed, confirmed, fitted }; + +// Fixed-size little-endian sidecar produced by +// tools/gen_bcpack_runtime_tables.py --profile. All fields are bytes: BC6H's 12 +// endpoint quantities are stored as little-endian uint16 pairs. +struct Calibration { + struct BC6 { + std::array ep; + std::array ix; + std::array ep_confirmed; + std::array ix_confirmed; + std::uint8_t ep_class, ix_class; + }; + struct BC7 { + std::array ep, ep_bits, ep_confirmed; + std::array ix, ix_bits, ix_confirmed; + }; + std::array bc6; + std::array bc7; +}; +static_assert(sizeof(Calibration) == 256 * (70 + 168)); +Quality decode(unsigned codec, std::span source, + std::span output, bool allow_fitted = false, + const Calibration *history = nullptr, const char** failure = nullptr, + bool fast_entropy = true); +} // namespace leonida::bcpack diff --git a/runtime/src/bcpack_stream.h b/runtime/src/bcpack_stream.h new file mode 100644 index 0000000000..7876869291 --- /dev/null +++ b/runtime/src/bcpack_stream.h @@ -0,0 +1,222 @@ +// Shared rANS block stream used by the runtime decoder and the offline history fitter. +#pragma once +#include +#include +#include +#include +#include + +namespace leonida::bcpack::detail { +using namespace std; +struct Seed { + int16_t values[8]; + bool fitted; +}; +struct BC6Mode { + int code, transformed, base, delta[3], regions, first, count; +}; +#include "bcpack_tables.inc" + +using Symbols = array; +constexpr uint32_t home = 1u << 24; + +struct Model { + uint32_t base[11]{}; + const uint32_t *frequency{}; + int width{}; + array first{}; + uint64_t reciprocal[9]{}; + void init(int w, int q) { + width = w; + frequency = freq[w][q]; + for (int p = 1; p <= w; ++p) { + base[p] = base[p - 1] + (frequency[p - 1] << max(0, p - 2)); + reciprocal[p] = ((uint64_t{1} << 32) + frequency[p] - 1) / frequency[p]; + } + unsigned p = 0; + for (unsigned window = 0; window < first.size(); ++window) { + while (p < unsigned(width) && base[p + 1] <= (window << 8)) ++p; + first[window] = uint8_t(p); + } + } + int symbol(uint32_t state, bool fast) const { + const uint32_t cf = state & 65535; + if (fast) { + unsigned p = first[cf >> 8]; + while (p < unsigned(width) && cf >= base[p + 1]) ++p; + if (!p) return 0; + const auto quotient = uint32_t(((cf - base[p]) * reciprocal[p]) >> 32); + return int((1u << (p - 1)) + quotient); + } + int p = width; + while (p && cf < base[p]) --p; + return p ? (1 << (p - 1)) + (cf - base[p]) / frequency[p] : 0; + } + uint32_t advance(uint32_t state, unsigned sym) const { + const int p = bit_width(sym); + uint32_t f = frequency[p], + c = base[p] + f * (sym - (p ? 1u << (p - 1) : 0u)); + if (!c) { + --f; + ++c; + } + return f * (state >> 16) + (state & 65535) - c; + } +}; + +// VIctory's GPL-3.0 BCPack decoder uses the high slot byte to locate a bucket. +// Build this accelerator solely from Leonida's own rANS frequencies. +inline const Model& model_for(int w, int q) { + static const auto models = [] { + array, 8> result{}; + for (int width = 1; width <= 8; ++width) + for (int quality = 0; quality < 16; ++quality) + result[width - 1][quality].init(width, quality); + return result; + }(); + return models[w - 1][q]; +} + +enum class Phase { header, length, long_length, symbols }; +struct Lane { + Phase phase{Phase::header}; + const Model* model{}; + uint32_t state{}; + int bytes{}, byte{}, zeros{}, symbol{}, slot{}; + size_t remaining{}; + bool flush{}, extended{}, buffered{}, held{}, full{}, done{}; + + bool step(int width, span &input, int &budget, bool fast) { + if (done || (held && full)) + return true; + if (!buffered && (phase != Phase::symbols || bytes)) { + if (!budget) + return true; + if (input.empty()) + return false; + --budget; + byte = input.front(); + input = input.subspan(1); + buffered = true; + } + if (held) { + state = model->advance(state, symbol); + slot = symbol; + full = true; + held = false; + } + if (phase == Phase::header) { + model = &model_for(width - (byte >> 6), byte & 15); + flush = (byte & 16) != 0; + extended = (byte & 32) != 0; + zeros = 0; + buffered = false; + phase = Phase::length; + } else if (phase == Phase::length || phase == Phase::long_length) { + if (phase == Phase::long_length) { + bytes += (byte << 8) + 257; + phase = Phase::symbols; + } else { + bytes = byte + !extended; + phase = extended ? Phase::long_length : Phase::symbols; + } + buffered = false; + } else { + if (state < home) { + if (bytes) { + state = (state << 8) | byte; + buffered = false; + --bytes; + } else if (!flush) { + done = remaining == 0; + phase = Phase::header; + return true; + } + if (!bytes && flush && state < home) { + if (!state || zeros >= 8) + return false; + while (state < home && zeros < 8) { + state <<= 8; + ++zeros; + } + } + } + held = state > home && remaining; + if (held) { + symbol = model->symbol(state, fast); + if (symbol >= (1 << model->width)) + return false; + --remaining; + } + if (!bytes && flush && state == home) { + done = !remaining; + phase = Phase::header; + state = 0; + } else if (!bytes && !flush && !remaining && !held) { + done = true; + } else if (state == home || (state > home && !held)) { + return false; + } + } + return true; + } +}; + +inline int unzig(int value) { return value & 1 ? -((value + 1) >> 1) : value >> 1; } +inline int interleave(int a, int b, int bits = 4) { + int v = 0; + for (int k = 0; k < bits; ++k) + v |= (((a >> k) & 1) | (((b >> k) & 1) << 1)) << (2 * k); + return v; +} + +struct BC7Format { + int subsets, color, alpha, pbits, index, partition; +}; +constexpr BC7Format bc7_formats[] = {{3, 4, 0, 1, 3, 4}, {2, 6, 0, 2, 3, 6}, + {3, 5, 0, 0, 2, 6}, {2, 7, 0, 1, 2, 6}, + {1, 5, 6, 0, 3, 0}, {1, 7, 8, 0, 2, 0}, + {1, 7, 7, 1, 4, 0}, {2, 5, 5, 1, 2, 6}}; + + +template +bool visit_blocks(unsigned codec, span source, size_t size, Block block, bool fast = true) { + const bool single = codec == 1 || codec == 4; + const unsigned count = codec >= 6 ? 16 : 12; + const size_t elements = size / 8; + array lanes{}; + for (auto &lane : lanes) lane.remaining = elements; + Symbols first{}; + size_t emitted = 0; + while (elements) { + bool ready = true, done = true; + int budget = 8; + for (unsigned l = 0; l < count; ++l) { + auto &lane = lanes[l]; + if (!lane.step(widths[codec][l], source, budget, fast)) + return false; + ready &= lane.full; + done &= lane.done; + } + if (ready) { + if (emitted == elements) + return false; + Symbols tuple{}; + for (unsigned l = 0; l < count; ++l) { + tuple[l] = uint16_t(lanes[l].slot); + lanes[l].full = false; + } + if (single || emitted % 2) { + const size_t i = single ? emitted : emitted / 2; + if (!block(i, single ? tuple : first, tuple)) return false; + } else { + first = tuple; + } + ++emitted; + } + if (done) + break; + } + return emitted == elements && ranges::all_of(source, [](uint8_t v) { return v == 0; }); +} +} // namespace leonida::bcpack::detail diff --git a/runtime/src/buffer_va_index.h b/runtime/src/buffer_va_index.h index 2ea0f9380f..6fbba5b05c 100644 --- a/runtime/src/buffer_va_index.h +++ b/runtime/src/buffer_va_index.h @@ -83,6 +83,12 @@ class BufferVaIndex { return found; } + // find() can return a shorter alias. Only a complete range can serve the view without new backing. + bool covers(std::uint64_t va, std::uint64_t bytes) const { + Hit hit{}; + return find(va, hit, bytes) && bytes <= hit.size - (va - hit.start); + } + std::size_t size() const { return ranges_.size(); } std::uint64_t longest() const { return longest_; } diff --git a/runtime/src/clzero_patch.h b/runtime/src/clzero_patch.h new file mode 100644 index 0000000000..7ab90e3036 --- /dev/null +++ b/runtime/src/clzero_patch.h @@ -0,0 +1,200 @@ +// Moves the title's CLZERO loops off the #UD path on a CPU without CLZERO (docs/cpu_features.md). +// +// The executable's 10 CLZERO sites are one leaf routine that zeroes buffers a 64-byte line at a time. Emulated on #UD +// (cpu_emulation.h), every line costs an exception dispatch and two VirtualQuery calls: measured on an i9-13900K, +// the routine took ~99% of one thread for the whole boot and the title presented at ~3 frames a second. Each site sits +// in one of two loop shapes, which are matched exactly (register forms only, nothing that refers to RIP): +// +// A (12 bytes) clzero; add rax, 40h; cmp rax, END; jb A (END: rdx or r8-r15) +// B (15 bytes) mov rax, CUR; add CUR, 40h; clzero; cmp CUR, END; jb B (CUR, END: rdx or r8-r15) +// +// The loop's first instruction becomes a `jmp rel32` to a copy of the loop in a stub page within 2 GiB of the image, +// and the rest of the loop becomes int3 (nothing branches into a loop's middle: its jb targets its first byte). In the +// copy, CLZERO is eight 8-byte stores of zero to the line rAX points into, with RCX saved around them; the loop's own +// instructions are copied unchanged, so the registers and flags the loop leaves are the ones the original leaves. The +// copy ends with a jmp to the instruction after the original jb. A line the title cannot write faults in the stub, as +// the original would fault at its CLZERO; the stub page is logged so such an address can be placed. +// +// Run before any of the image's code and before its sections are protected. LEONIDA_CLZERO_PATCH=0 keeps the #UD path. +#pragma once + +#ifdef _WIN32 +#include + +#include +#include +#include +#include +#include +#include + +namespace rt::clzero_patch { + +struct Site { + uint32_t head; // offset of the loop's first byte from the scanned code's start + uint32_t length; // 12 (shape A) or 15 (shape B) + uint32_t clzero; // offset of the CLZERO within the loop +}; + +// `cmp r/m64, r64` (REX.W 39 /r, register form) or `mov`/`add` with the given register as ModRM r/m, for rdx or +// r8-r15: the registers the routine uses. rcx is excluded because the stub saves it around its stores. +inline bool is_cmp_rr(const uint8_t* p) { + return (p[0] == 0x48 || p[0] == 0x49 || p[0] == 0x4C || p[0] == 0x4D) && p[1] == 0x39 && (p[2] & 0xC0) == 0xC0; +} + +inline bool clzero_at(const uint8_t* p) { return p[0] == 0x0F && p[1] == 0x01 && p[2] == 0xFC; } + +// Register number (0-15) of ModRM.rm / ModRM.reg with REX. +inline unsigned rm_reg(uint8_t rex, uint8_t modrm) { return (modrm & 7) | ((rex & 1) << 3); } +inline unsigned reg_reg(uint8_t rex, uint8_t modrm) { return ((modrm >> 3) & 7) | ((rex & 4) << 1); } + +// Finds the loops in `code[0, size)`. A CLZERO that is in neither shape is left to the #UD path. +inline std::vector find(const uint8_t* code, size_t size) { + std::vector sites; + for (size_t k = 0; k + 3 <= size; ++k) { + if (!clzero_at(code + k)) continue; + // Shape A: the CLZERO is the loop's first instruction. + if (k + 12 <= size) { + const uint8_t* p = code + k; + const bool add = p[3] == 0x48 && p[4] == 0x83 && p[5] == 0xC0 && p[6] == 0x40; // add rax, 40h + // cmp rax, END: REX.W (+R for r8-r15) 39 /r with rm = rax. + const bool cmp = is_cmp_rr(p + 7) && rm_reg(p[7], p[9]) == 0 && (p[7] & 1) == 0; + const unsigned end = cmp ? reg_reg(p[7], p[9]) : 0; + const bool jb = p[10] == 0x72 && int8_t(p[11]) == -12; + if (add && cmp && jb && end != 0 && end != 1 && end != 4) { + sites.push_back({uint32_t(k), 12, 0}); + k += 2; + continue; + } + } + // Shape B: mov rax, CUR; add CUR, 40h before the CLZERO; cmp CUR, END; jb after it. + if (k >= 7 && k + 8 <= size) { + const uint8_t* p = code + k - 7; + // mov rax, CUR: REX.W(+R) 89 /r, rm = rax, reg = CUR. + const bool mov = (p[0] == 0x48 || p[0] == 0x4C) && p[1] == 0x89 && (p[2] & 0xC7) == 0xC0; + const unsigned cur = mov ? reg_reg(p[0], p[2]) : 0; + // add CUR, 40h: REX.W(+B) 83 /0 ib with rm = CUR. + const bool add = (p[3] == 0x48 || p[3] == 0x49) && p[4] == 0x83 && (p[5] & 0xF8) == 0xC0 && + rm_reg(p[3], p[5]) == cur && p[6] == 0x40; + // cmp CUR, END: REX.W 39 /r with rm = CUR, reg = END. + const bool cmp = is_cmp_rr(p + 10) && rm_reg(p[10], p[12]) == cur; + const unsigned end = cmp ? reg_reg(p[10], p[12]) : 0; + const bool jb = p[13] == 0x72 && int8_t(p[14]) == -15; + const auto ok = [](unsigned r) { return r == 2 || r >= 8; }; + if (mov && add && cmp && jb && ok(cur) && ok(end) && cur != end) { + sites.push_back({uint32_t(k - 7), 15, 7}); + k += 7; + continue; + } + } + } + return sites; +} + +// The stub for one loop: its instructions before the CLZERO, the zeroing block, its instructions after the CLZERO up +// to the jb, a jb back to the stub's start, then a jmp to `resume` (the instruction after the original jb). +inline std::vector stub(const uint8_t* loop, const Site& s, uint64_t stub_at, uint64_t resume) { + std::vector out(loop, loop + s.clzero); // shape B: mov rax, CUR; add CUR, 40h + const uint8_t zero_line[] = { + 0x51, // push rcx + 0x48, 0x89, 0xC1, // mov rcx, rax + 0x48, 0x83, 0xE1, 0xC0, // and rcx, -64 + 0x48, 0xC7, 0x01, 0, 0, 0, 0, // mov qword [rcx], 0 + 0x48, 0xC7, 0x41, 0x08, 0, 0, 0, 0, // mov qword [rcx+8], 0 + 0x48, 0xC7, 0x41, 0x10, 0, 0, 0, 0, + 0x48, 0xC7, 0x41, 0x18, 0, 0, 0, 0, + 0x48, 0xC7, 0x41, 0x20, 0, 0, 0, 0, + 0x48, 0xC7, 0x41, 0x28, 0, 0, 0, 0, + 0x48, 0xC7, 0x41, 0x30, 0, 0, 0, 0, + 0x48, 0xC7, 0x41, 0x38, 0, 0, 0, 0, + 0x59, // pop rcx + }; + out.insert(out.end(), std::begin(zero_line), std::end(zero_line)); + // The instructions between the CLZERO and the jb (shape A: add rax, 40h; cmp; shape B: cmp). + out.insert(out.end(), loop + s.clzero + 3, loop + s.length - 2); + const int back = -int(out.size() + 2); + out.push_back(0x72); + out.push_back(uint8_t(int8_t(back))); + out.push_back(0xE9); + const int64_t rel = int64_t(resume) - int64_t(stub_at + out.size() + 4); + const int32_t rel32 = int32_t(rel); + const auto* b = reinterpret_cast(&rel32); + out.insert(out.end(), b, b + 4); + return out; +} + +// Reserves a page within 2 GiB above or below [lo, hi) for the stubs (the image does not move after this). +inline uint8_t* stub_page(uint64_t lo, uint64_t hi, size_t size) { + SYSTEM_INFO si; + GetSystemInfo(&si); + const uint64_t gran = si.dwAllocationGranularity; + const uint64_t limit = uint64_t(1) << 31; + for (uint64_t at = (hi + gran - 1) & ~(gran - 1); at + size < lo + limit - 0x1000; at += gran) { + if (void* p = VirtualAlloc(reinterpret_cast(at), size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)) + return static_cast(p); + } + for (uint64_t at = (lo - size) & ~(gran - 1); at > gran && hi - at < limit - 0x1000; at -= gran) { + if (void* p = VirtualAlloc(reinterpret_cast(at), size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)) + return static_cast(p); + } + return nullptr; +} + +inline bool enabled() { + char v[8] = {}; + size_t n = 0; + return !(getenv_s(&n, v, "LEONIDA_CLZERO_PATCH") == 0 && n == 2 && v[0] == '0'); +} + +struct Result { + size_t sites = 0; + uint8_t* stubs = nullptr; + size_t stub_bytes = 0; +}; + +// Patches every loop found in the executable ranges `ranges` (pairs of start address and size, all inside +// [image_lo, image_hi)). The ranges must be writable. On any failure nothing is patched. +inline Result patch(const std::vector>& ranges, uint64_t image_lo, uint64_t image_hi) { + Result r; + std::vector> all; + for (const auto& [code, size] : ranges) + for (const Site& s : find(code, size)) all.push_back({code, s}); + if (all.empty()) return r; + const size_t page = 0x10000; + uint8_t* const stubs = stub_page(image_lo, image_hi, page); + if (!stubs) return r; + size_t used = 0; + std::vector> bodies; + for (const auto& [code, s] : all) { + uint8_t* const loop = code + s.head; + const uint64_t at = uint64_t(stubs + used); + bodies.push_back(stub(loop, s, at, uint64_t(loop + s.length))); + used += (bodies.back().size() + 15) & ~size_t(15); + if (used > page) { + VirtualFree(stubs, 0, MEM_RELEASE); + return r; + } + } + used = 0; + for (size_t i = 0; i < all.size(); ++i) { + const auto& [code, s] = all[i]; + uint8_t* const loop = code + s.head; + uint8_t* const at = stubs + used; + std::memcpy(at, bodies[i].data(), bodies[i].size()); + used += (bodies[i].size() + 15) & ~size_t(15); + const int32_t rel = int32_t(int64_t(at) - int64_t(loop + 5)); + loop[0] = 0xE9; + std::memcpy(loop + 1, &rel, 4); + std::memset(loop + 5, 0xCC, s.length - 5); + } + DWORD old = 0; + VirtualProtect(stubs, page, PAGE_EXECUTE_READ, &old); + FlushInstructionCache(GetCurrentProcess(), stubs, page); + r.sites = all.size(); + r.stubs = stubs; + r.stub_bytes = used; + return r; +} + +} // namespace rt::clzero_patch +#endif diff --git a/runtime/src/d3d12_xs_frame_events.h b/runtime/src/d3d12_xs_frame_events.h new file mode 100644 index 0000000000..b4a128fb9d --- /dev/null +++ b/runtime/src/d3d12_xs_frame_events.h @@ -0,0 +1,47 @@ +#pragma once + +// Portable Xbox Series D3D12 device slot 81 (GetFrameEventsX) ABI model (no Windows or Vulkan dependency). +// +// Observed call shape (static ABI inspection, offsets and stride only): +// HRESULT GetFrameEventsX(uint64_t frameToken, uint32_t flags, uint32_t* pNumEvents, XboxFrameEvent* pEvents) +// +// Each output event record has stride 0x38 bytes: +// +0x00: uint32_t event_type +// +0x08: uint8_t status (0 = ok) +// +0x18: uint64_t timestamp + +#include +#include + +namespace leonida::d3d12_xs { + +// Device slot 81 (GetFrameEventsX) output event record (exact stride 0x38 bytes). +struct XboxFrameEvent { + std::uint32_t event_type = 0; // +0x00 + std::uint32_t reserved0 = 0; // +0x04 + std::uint8_t status = 0; // +0x08 (0 = ok) + std::uint8_t pad[15] = {}; // +0x09..+0x17 + std::uint64_t timestamp = 0; // +0x18 + std::uint64_t reserved1[3] = {}; // +0x20..+0x37 +}; +static_assert(sizeof(XboxFrameEvent) == 0x38); +static_assert(offsetof(XboxFrameEvent, event_type) == 0x00); +static_assert(offsetof(XboxFrameEvent, status) == 0x08); +static_assert(offsetof(XboxFrameEvent, timestamp) == 0x18); + +enum class FrameEventQueryStatus : std::uint32_t { + ok = 0, + null_count = 1, + null_buffer = 2, +}; + +// Validates GetFrameEventsX output parameters and reports zero pending frame events. +// With no hardware flip-event history yet, reporting *num_events = 0 is cleanly handled by callers. +inline FrameEventQueryStatus query_frame_events_empty(std::uint32_t* num_events, XboxFrameEvent* events) { + if (!num_events) return FrameEventQueryStatus::null_count; + if (*num_events > 0 && !events) return FrameEventQueryStatus::null_buffer; + *num_events = 0; + return FrameEventQueryStatus::ok; +} + +} // namespace leonida::d3d12_xs diff --git a/runtime/src/deferred_image_binding.h b/runtime/src/deferred_image_binding.h new file mode 100644 index 0000000000..668cf593db --- /dev/null +++ b/runtime/src/deferred_image_binding.h @@ -0,0 +1,31 @@ +#pragma once + +#include +#include + +namespace leonida { + +// A placed image can be named concurrently by command replay and descriptor creation. +// Vulkan permits one successful bind for the lifetime of an ordinary image. +class DeferredImageBinding { +public: + using Bind = bool (*)(void*); + DeferredImageBinding(void* owner, Bind bind) : owner_(owner), bind_(bind) {} + bool bound() const { return bound_.load(std::memory_order_acquire); } + bool ensure() { + if (bound()) return true; + std::lock_guard lock(mutex_); + if (bound()) return true; + if (!bind_(owner_)) return false; + bound_.store(true, std::memory_order_release); + return true; + } + +private: + void* owner_; + Bind bind_; + std::mutex mutex_; + std::atomic bound_{false}; +}; + +} // namespace leonida diff --git a/runtime/src/descriptor_table.h b/runtime/src/descriptor_table.h index 69857c4c60..a0d80968a8 100644 --- a/runtime/src/descriptor_table.h +++ b/runtime/src/descriptor_table.h @@ -26,7 +26,19 @@ inline constexpr std::uint32_t kSlotOccupiedMarker = 0xA11CA7EDu; // S# key is 4 dwords followed by 4x 0xFFFFFFFF. using DescriptorKey = std::array; -inline std::uint32_t hash_descriptor_key(const std::uint32_t key[8]) { +// Which hash the table, and every module it serves, probe with. Both run the same FNV-1a loop over the key's dwords; +// fnv1a_fmix32 then finalizes it with MurmurHash3's fmix32, which spreads keys whose low FNV-1a bits cluster (the T#s +// that differ only in a high nibble of dword 0 all land in one slot today). A translated index.json declares its +// modules' kind in the per-module meta (`descriptor_hash`); the runtime picks one kind for its table before the first +// insert and uses it for every insert, lookup, relocation and rehash. +enum class DescriptorHashKind : std::uint8_t { fnv1a = 0, fnv1a_fmix32 = 1 }; + +inline constexpr const char* descriptor_hash_kind_name(DescriptorHashKind kind) { + return kind == DescriptorHashKind::fnv1a_fmix32 ? "fnv1a_fmix32" : "fnv1a"; +} + +// The bare FNV-1a loop: the hash every module has probed with until the marker says otherwise. +inline std::uint32_t hash_descriptor_key_fnv1a(const std::uint32_t key[8]) { std::uint32_t h = kFnvOffsetBasis; for (int i = 0; i < 8; ++i) { h = (h ^ key[i]) * kFnvPrime; @@ -34,6 +46,30 @@ inline std::uint32_t hash_descriptor_key(const std::uint32_t key[8]) { return h; } +// MurmurHash3's fmix32 finalizer (logical shifts, arithmetic mod 2^32): what fnv1a_fmix32 applies after the FNV loop. +inline std::uint32_t finalize_descriptor_hash(std::uint32_t h) { + h ^= h >> 16; + h *= 0x85EBCA6Bu; + h ^= h >> 13; + h *= 0xC2B2AE35u; + h ^= h >> 16; + return h; +} + +inline std::uint32_t hash_descriptor_key(const std::uint32_t key[8], DescriptorHashKind kind) { + const std::uint32_t h = hash_descriptor_key_fnv1a(key); + return kind == DescriptorHashKind::fnv1a_fmix32 ? finalize_descriptor_hash(h) : h; +} + +inline std::uint32_t hash_descriptor_key(const DescriptorKey& key, DescriptorHashKind kind) { + return hash_descriptor_key(key.data(), kind); +} + +// The old default, so a table or a test that does not name a kind keeps probing with bare FNV-1a. +inline std::uint32_t hash_descriptor_key(const std::uint32_t key[8]) { + return hash_descriptor_key(key, DescriptorHashKind::fnv1a); +} + inline std::uint32_t hash_descriptor_key(const DescriptorKey& key) { return hash_descriptor_key(key.data()); } @@ -69,7 +105,12 @@ class DescriptorTable { public: enum class InsertResult { added, unchanged, replaced, added_with_relocation }; - explicit DescriptorTable(std::uint32_t initial_capacity = 16) { + // `hash_kind` is the finalizer every insert, lookup, relocation and rehash of this table uses. It is fixed here, + // before the first insert: one table serves all the device's shaders, which all probe with the kind the device + // chose from their indexes (or LEONIDA_DESCRIPTOR_HASH). The default is the old bare FNV-1a. + explicit DescriptorTable(std::uint32_t initial_capacity = 16, + DescriptorHashKind hash_kind = DescriptorHashKind::fnv1a) + : hash_kind_(hash_kind) { // Slots use nonnegative int indices internally. Larger powers also wrap the capacity counter. if (initial_capacity > max_capacity) throw std::length_error("Descriptor table capacity exceeds slot range"); std::uint32_t cap = 16; @@ -78,6 +119,9 @@ class DescriptorTable { entries_.resize(cap); } + // The kind this table places and finds keys with (immutable after construction). + DescriptorHashKind hash_kind() const { return hash_kind_; } + // Inserts or updates a key -> index mapping. // If the key already exists in one of the 8 probe slots, its index is updated. // Try one bounded relocation before growing. Load never exceeds 50%. @@ -99,7 +143,7 @@ class DescriptorTable { // Queries the index associated with key. Returns 0 if not found. std::uint32_t lookup(const std::uint32_t key[8]) const { std::lock_guard lock(mutex_); - const std::uint32_t h = hash_descriptor_key(key); + const std::uint32_t h = hash_descriptor_key(key, hash_kind_); for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) { const std::uint32_t slot = (h + k) & mask_; const auto& entry = entries_[slot]; @@ -116,7 +160,7 @@ class DescriptorTable { bool contains(const std::uint32_t key[8]) const { std::lock_guard lock(mutex_); - const std::uint32_t h = hash_descriptor_key(key); + const std::uint32_t h = hash_descriptor_key(key, hash_kind_); for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) { const std::uint32_t slot = (h + k) & mask_; const auto& entry = entries_[slot]; @@ -249,7 +293,7 @@ class DescriptorTable { // to the first empty slot beyond that window, within its own eight probes. // A later hole is farther from every resident, so failure here is final for a single move. // `moved_to` receives the hole the resident moved into, so the caller can mark that slot changed too. - static int make_probe_slot(std::vector& entries, std::uint32_t hash, + static int make_probe_slot(std::vector& entries, std::uint32_t hash, DescriptorHashKind kind, std::uint32_t* moved_to = nullptr) { const auto mask = static_cast(entries.size() - 1); for (auto offset = kDescriptorProbes; offset < 2 * kDescriptorProbes - 1; ++offset) { @@ -257,7 +301,7 @@ class DescriptorTable { if (entries[hole].pad == kSlotOccupiedMarker) continue; for (auto k = kDescriptorProbes; k > 0; --k) { const auto slot = (hash + k - 1) & mask; - const auto home = hash_descriptor_key(entries[slot].key); + const auto home = hash_descriptor_key(entries[slot].key, kind); if (((hole - home) & mask) < kDescriptorProbes) { entries[hole] = entries[slot]; if (moved_to) *moved_to = hole; @@ -271,7 +315,7 @@ class DescriptorTable { InsertResult insert_locked(const std::uint32_t key[8], std::uint32_t index) { while (true) { - const std::uint32_t h = hash_descriptor_key(key); + const std::uint32_t h = hash_descriptor_key(key, hash_kind_); int empty_slot = -1; for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) { @@ -300,14 +344,14 @@ class DescriptorTable { std::uint32_t same_hash = 0; for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) { const auto& entry = entries_[(h + k) & mask_]; - if (hash_descriptor_key(entry.key) == h) ++same_hash; + if (hash_descriptor_key(entry.key, hash_kind_) == h) ++same_hash; } if (same_hash == kDescriptorProbes) throw std::length_error("Descriptor hash collision exceeds shader probe limit"); } const bool relocate = empty_slot < 0; std::uint32_t moved_to = 0; - if (relocate) empty_slot = make_probe_slot(entries_, h, &moved_to); + if (relocate) empty_slot = make_probe_slot(entries_, h, hash_kind_, &moved_to); if (empty_slot >= 0) { auto& entry = entries_[empty_slot]; std::memcpy(entry.key, key, sizeof(entry.key)); @@ -324,7 +368,7 @@ class DescriptorTable { } bool erase_locked(const std::uint32_t key[8]) { - const std::uint32_t h = hash_descriptor_key(key); + const std::uint32_t h = hash_descriptor_key(key, hash_kind_); std::uint32_t found_slot = 0; bool found = false; for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) { @@ -355,7 +399,7 @@ class DescriptorTable { for (const auto& old : entries_) { if (old.pad != kSlotOccupiedMarker) continue; - const std::uint32_t h = hash_descriptor_key(old.key); + const std::uint32_t h = hash_descriptor_key(old.key, hash_kind_); int slot = -1; for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) { const std::uint32_t s = (h + k) & new_mask; @@ -364,7 +408,7 @@ class DescriptorTable { break; } } - if (slot < 0) slot = make_probe_slot(new_entries, h); + if (slot < 0) slot = make_probe_slot(new_entries, h, hash_kind_); if (slot < 0) { rehash_ok = false; break; @@ -386,6 +430,7 @@ class DescriptorTable { static constexpr std::uint32_t max_capacity = std::uint32_t{1} << 31; mutable std::mutex mutex_; + const DescriptorHashKind hash_kind_; std::uint32_t mask_ = 15; std::vector entries_; std::size_t occupied_count_ = 0; diff --git a/runtime/src/dstorage_swizzle.h b/runtime/src/dstorage_swizzle.h new file mode 100644 index 0000000000..45186fcf81 --- /dev/null +++ b/runtime/src/dstorage_swizzle.h @@ -0,0 +1,29 @@ +#pragma once +#include +#include +#include + +namespace leonida::dstorage { +// The public Xbox-GDK-Samples DirectStorageTextureShuffling example stores each BC component +// plane across the whole request. The MDU interleaves a stripe of each plane per group. The +// sample's compute shader does the remaining intra-group shuffle; surface tiling is already baked in. +inline constexpr unsigned stripes[][5] = {{}, {1, 1, 2}, {1, 1, 6}, {1, 3, 1, 1, 2}, {1, 3, 1, 3}}; + +inline size_t group_size(unsigned mode) { return mode == 1 ? 16384 : 32768; } + +inline bool unshuffle(unsigned mode, std::span input, std::span out) { + if (!mode || mode > 4 || input.size() != out.size() || input.size() % group_size(mode)) return false; + const size_t group = group_size(mode), groups = input.size() / group; + size_t source = 0, offset = 0; + for (unsigned pages : stripes[mode]) { + if (!pages) break; + const size_t bytes = pages * 4096; + for (size_t i = 0; i < groups; ++i) { + std::memcpy(out.data() + i * group + offset, input.data() + source, bytes); + source += bytes; + } + offset += bytes; + } + return true; +} +} // namespace leonida::dstorage diff --git a/runtime/src/dstorage_trace.h b/runtime/src/dstorage_trace.h new file mode 100644 index 0000000000..3c2eda2171 --- /dev/null +++ b/runtime/src/dstorage_trace.h @@ -0,0 +1,12 @@ +#pragma once +#include + +namespace leonida::dstorage { +inline bool trace_enabled() { + static const bool enabled = [] { + char value[2]{}; + return GetEnvironmentVariableA("LEONIDA_DSTORAGE_TRACE", value, sizeof value) == 1 && value[0] == '1'; + }(); + return enabled; +} +} // namespace leonida::dstorage diff --git a/runtime/src/frame_pacer.h b/runtime/src/frame_pacer.h index afeaf191e3..34fd38fc76 100644 --- a/runtime/src/frame_pacer.h +++ b/runtime/src/frame_pacer.h @@ -39,8 +39,10 @@ #include #include #include +#include #include #include +#include namespace leonida { @@ -171,9 +173,19 @@ struct FramePacingSummary { std::uint64_t latency_p99_us = 0; // nearest-rank 99th percentile origin-to-present latency in us }; +class FrameTokenSource { +public: + std::uint64_t issue() { return last_.fetch_add(1, std::memory_order_acq_rel) + 1; } + std::uint64_t issued() const { return last_.load(std::memory_order_acquire); } + +private: + std::atomic last_{0}; +}; + class FramePacer { public: - explicit FramePacer(FrameClock& clock) : clock_(clock) { + explicit FramePacer(FrameClock& clock, std::shared_ptr tokens = nullptr) + : clock_(clock), tokens_(tokens ? std::move(tokens) : std::make_shared()) { clock_.set_wake([this] { { std::lock_guard guard(mutex_); } cv_.notify_all(); @@ -295,7 +307,7 @@ class FramePacer { std::lock_guard guard(mutex_); if (issue) *issue = TokenIssue::none; if (suspended_) return pacer_hr::invalid_state; - if (token > issued_) return pacer_hr::invalid_arg; + if (token > tokens_->issued()) return pacer_hr::invalid_arg; if (issue) { if (token == 0) *issue = TokenIssue::null_token; else if (token == last_presented_) *issue = TokenIssue::repeated; @@ -394,7 +406,8 @@ class FramePacer { } bool suspended() const { std::lock_guard guard(mutex_); return suspended_; } - std::uint64_t tokens_issued() const { std::lock_guard guard(mutex_); return issued_; } + std::uint64_t tokens_issued() const { return tokens_->issued(); } + const std::shared_ptr& token_source() const { return tokens_; } std::uint32_t frames_in_flight() { std::lock_guard guard(mutex_); retire_locked(clock_.now_us()); @@ -505,7 +518,7 @@ class FramePacer { } std::uint64_t issue_token_locked(std::uint64_t origin_us, std::uint64_t due_us) { - const std::uint64_t tok = ++issued_; + const std::uint64_t tok = tokens_->issue(); // the shared token source (the device proxy and PresentX pace with it) Record record; record.token = tok; record.origin_us = origin_us; @@ -580,7 +593,7 @@ class FramePacer { std::uint32_t event_offset_us_[frame_event_count] = {0, 0, 0}; std::uint64_t epoch_us_ = 0; std::int64_t last_event_tick_[frame_event_count] = {0, 0, 0}; // tick 0 is the epoch itself, which has passed - std::uint64_t issued_ = 0; + std::shared_ptr tokens_; std::uint64_t last_presented_ = 0; std::uint64_t immediate_presents_ = 0; std::uint64_t presents_recorded_ = 0; diff --git a/runtime/src/fsdraw_probe.h b/runtime/src/fsdraw_probe.h new file mode 100644 index 0000000000..38c0ca58cd --- /dev/null +++ b/runtime/src/fsdraw_probe.h @@ -0,0 +1,236 @@ +#pragma once + +// LOCAL DIAGNOSTIC (not for upstream): fsdraw probe. Follows the title's fullscreen draws back from the backbuffer: +// what each pipeline is (shaders, target formats, blend, write mask), what the draw's descriptor tables hold on the +// CPU and what the GPU address arena holds at the same VA (the shader's heap_base + VA), which T#s have a bindless +// entry, and which render targets the present-probe should read back as well. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace leonida::fsdraw { + +struct State { + std::mutex mutex; + std::unordered_map pipelines; // graphics PSO id -> description + std::set> tsharps; // T#s that have a bindless entry + const std::uint8_t* arena = nullptr; // the GPU address arena's host mapping + std::uint64_t arena_size = 0; + std::vector readback; // render targets of fullscreen draws (besides the presented source) + std::uint64_t presented_source = 0; + std::unordered_map table_origin; // translated table VA -> title VA + std::unordered_map> cbv_origin; // V# base -> location, size +}; + +inline State& state() { + static State s; + return s; +} + +inline void note_pipeline(std::uintptr_t id, std::string text) { + std::lock_guard lock(state().mutex); + state().pipelines[id] = std::move(text); +} + +inline std::size_t pipeline_count() { // LOCAL DIAGNOSTIC (mem probe) + std::lock_guard lock(state().mutex); + return state().pipelines.size(); +} + +inline std::string pipeline(std::uintptr_t id) { + std::lock_guard lock(state().mutex); + const auto it = state().pipelines.find(id); + return it == state().pipelines.end() ? std::string("(not registered)") : it->second; +} + +inline void note_tsharp(const std::uint32_t* words) { + std::array key{}; + std::memcpy(key.data(), words, sizeof(key)); + std::lock_guard lock(state().mutex); + state().tsharps.insert(key); +} + +inline bool has_tsharp(const std::uint32_t* words) { + std::array key{}; + std::memcpy(key.data(), words, sizeof(key)); + std::lock_guard lock(state().mutex); + return state().tsharps.count(key) != 0; +} + +inline void note_arena(const std::uint8_t* mapped, std::uint64_t size) { + std::lock_guard lock(state().mutex); + state().arena = mapped; + state().arena_size = size; +} + +// A test or application may create multiple devices. Never inspect a released +// mapping; destroying an older device must leave the current mapping alone. +inline void forget_arena(const std::uint8_t* mapped) { + std::lock_guard lock(state().mutex); + if (state().arena == mapped) { + state().arena = nullptr; + state().arena_size = 0; + } +} + +// A render target a fullscreen draw wrote: the present-probe reads it back with the source (at most 4 kept). +inline void note_target(std::uint64_t id) { + if (!id) return; + std::lock_guard lock(state().mutex); + auto& r = state().readback; + for (const std::uint64_t x : r) + if (x == id) return; + if (r.size() < 4) r.push_back(id); +} + +inline std::vector targets() { + std::lock_guard lock(state().mutex); + return state().readback; +} + +inline void note_table(std::uint64_t translated, std::uint64_t original) { + std::lock_guard lock(state().mutex); + auto& m = state().table_origin; + if (m.size() > 8192) m.clear(); + m[translated] = original; +} + +inline std::uint64_t table_origin(std::uint64_t va) { + std::lock_guard lock(state().mutex); + const auto it = state().table_origin.find(va); + return it == state().table_origin.end() ? va : it->second; +} + +inline void note_cbv(std::uint64_t base, std::uint64_t location, std::uint32_t size) { + std::lock_guard lock(state().mutex); + auto& m = state().cbv_origin; + if (m.size() > 8192) m.clear(); + m[base] = {location, size}; +} + +inline bool cbv_origin(std::uint64_t base, std::uint64_t& location) { + std::lock_guard lock(state().mutex); + const auto it = state().cbv_origin.find(base); + if (it == state().cbv_origin.end()) return false; + location = it->second.first; + return true; +} + +inline std::string hex_words(const std::uint32_t* w, std::size_t n) { + std::string s; + char b[16]; + for (std::size_t i = 0; i < n; ++i) { + std::snprintf(b, sizeof b, i ? " %08x" : "%08x", w[i]); + s += b; + } + return s; +} + +// The 8 dwords at arena offset `va`, if the arena holds them. +inline bool arena_words(std::uint64_t va, std::uint32_t* out, std::size_t n) { + std::lock_guard lock(state().mutex); + const State& s = state(); + if (!s.arena || va + n * 4 > s.arena_size || va + n * 4 < va) return false; + std::memcpy(out, s.arena + va, n * 4); + return true; +} + +inline std::uint64_t arena_size() { + std::lock_guard lock(state().mutex); + return state().arena_size; +} + +// Logs one descriptor table: `cpu` is the layer's host view of the slot at `va` (null when no heap holds `va`). +// For each slot: the CPU bytes, the arena bytes at the same VA (what a shader's heap_base + VA loads), and what the +// CPU bytes are (null, V# with its base, or T# with whether it has a bindless entry). A V# whose base is inside the +// arena has its first 16 dwords printed from the arena. +inline void describe_table(const char* tag, std::uint64_t va, std::uint32_t slots, const std::uint8_t* cpu, + const char* heap_kind) { + const std::uint32_t shown = slots < 4 ? slots : 4; + std::fprintf(stderr, "[rt] fsdraw: %s table va 0x%llx slots %u heap %s (arena size 0x%llx)\n", tag, + static_cast(va), slots, heap_kind, static_cast(arena_size())); + for (std::uint32_t i = 0; i < shown; ++i) { + const std::uint64_t at = va + std::uint64_t(i) * 32; + std::uint32_t c[8]{}, g[8]{}; + const bool have_cpu = cpu != nullptr; + if (have_cpu) std::memcpy(c, cpu + std::size_t(i) * 32, sizeof c); + const bool have_gpu = arena_words(at, g, 8); + const bool same = have_cpu && have_gpu && std::memcmp(c, g, sizeof c) == 0; + std::fprintf(stderr, "[rt] fsdraw: %s slot %u cpu [%s] gpu [%s]%s\n", tag, i, + have_cpu ? hex_words(c, 8).c_str() : "no heap", have_gpu ? hex_words(g, 8).c_str() : "OUT OF ARENA", + have_cpu && have_gpu ? (same ? " (same)" : " (DIFFER)") : ""); + const std::uint32_t* w = have_cpu ? c : have_gpu ? g : nullptr; + if (!w) continue; + if (!(w[0] | w[1] | w[2] | w[3] | w[4] | w[5] | w[6] | w[7])) { + std::fprintf(stderr, "[rt] fsdraw: %s slot %u is null\n", tag, i); + continue; + } + if (!(w[3] >> 30)) { // buffer V# (TYPE in dword 3 bits 30-31 is 0) + const std::uint64_t base = std::uint64_t(w[0]) | (std::uint64_t(w[1] & 0xFFFFu) << 32); + const std::uint32_t stride = (w[1] >> 16) & 0x3FFFu; + std::uint32_t data[16]{}; + const bool in_arena = arena_words(base, data, 16); + std::size_t nonzero = 0; + if (in_arena) { + std::vector all(std::min(w[2] ? w[2] : 256, 4096) / 4); + if (!all.empty() && arena_words(base, all.data(), all.size())) + for (const std::uint32_t x : all) nonzero += x != 0; + } + std::uint64_t location = 0; + const bool made = cbv_origin(base, location); + std::fprintf(stderr, "[rt] fsdraw: %s slot %u V# base 0x%llx stride %u records %u -> %s [%s] nonzero dwords " + "%zu%s\n", + tag, i, static_cast(base), stride, w[2], + in_arena ? "arena" : "outside the arena buffer", in_arena ? hex_words(data, 16).c_str() : "", + nonzero, made ? "" : " (no CreateConstantBufferView made this V#)"); + if (made && !in_arena && location) { // the CB as the title wrote it (title memory, CPU view) + std::uint32_t cb[16]{}; + std::memcpy(cb, reinterpret_cast(static_cast(location)), sizeof cb); + std::fprintf(stderr, "[rt] fsdraw: %s slot %u CB at title 0x%llx: [%s]\n", tag, i, + static_cast(location), hex_words(cb, 16).c_str()); + } + } else { + std::fprintf(stderr, "[rt] fsdraw: %s slot %u T# bindless entry %s\n", tag, i, + has_tsharp(w) ? "yes" : "NO (a lookup misses: index 0, zeros)"); + } + } +} + +// LEONIDA_FSDRAW_POKE_CB=1 (experiment): before a submission, the CB that a bound table's slot-0 V# names gets a +// known colour in dwords 8..11 (what PS_BlitColour multiplies the vertex colour by), written into the title's own +// copy. A non-zero render target afterwards proves table -> V# -> CB -> pixel shader -> target works on the GPU. +inline bool poke_enabled() { + static const bool on = [] { + const char* v = std::getenv("LEONIDA_FSDRAW_POKE_CB"); + return v && *v && *v != '0'; + }(); + return on; +} + +inline void poke_cb(const std::uint8_t* table_cpu) { + if (!table_cpu || !poke_enabled()) return; + std::uint32_t w[4]; + std::memcpy(w, table_cpu, sizeof w); + if (!(w[0] | w[1] | w[2] | w[3]) || (w[3] >> 30) || w[2] < 48) return; + const std::uint64_t base = std::uint64_t(w[0]) | (std::uint64_t(w[1] & 0xFFFFu) << 32); + std::uint64_t location = 0; + if (!cbv_origin(base, location) || !location) return; + const float colour[4] = {1.0f, 0.5f, 0.25f, 1.0f}; + std::memcpy(reinterpret_cast(static_cast(location + 32)), colour, sizeof colour); + static std::atomic poked{0}; + const std::uint64_t n = ++poked; + if (n <= 4 || n % 600 == 0) + std::fprintf(stderr, "[rt] fsdraw: POKE #%llu: CB at title 0x%llx dwords 8..11 = 1.0 0.5 0.25 1.0\n", + static_cast(n), static_cast(location)); +} + +} // namespace leonida::fsdraw diff --git a/runtime/src/gfx10_descriptors.h b/runtime/src/gfx10_descriptors.h index a4a9b44481..10cea81f46 100644 --- a/runtime/src/gfx10_descriptors.h +++ b/runtime/src/gfx10_descriptors.h @@ -218,6 +218,7 @@ struct FormatRow { }; inline constexpr Swizzle channels_r{select_x, select_zero, select_zero, select_one}; +inline constexpr Swizzle channels_a{select_zero, select_zero, select_zero, select_x}; inline constexpr Swizzle channels_rg{select_x, select_y, select_zero, select_one}; inline constexpr Swizzle channels_rgb{select_x, select_y, select_z, select_one}; inline constexpr Swizzle channels_rgba = identity_swizzle; @@ -227,6 +228,9 @@ inline constexpr Swizzle channels_abgr{select_w, select_z, select_y, select_x}; inline constexpr FormatRow format_table[] = { {1, VK_FORMAT_R8_UNORM, channels_r}, // GFX10_FORMAT_8_UNORM +#ifdef VK_KHR_MAINTENANCE_5_EXTENSION_NAME + {1, VK_FORMAT_A8_UNORM_KHR, channels_a}, // GFX10_FORMAT_8_UNORM (an A8 render target) +#endif {2, VK_FORMAT_R8_SNORM, channels_r}, // GFX10_FORMAT_8_SNORM {3, VK_FORMAT_R8_USCALED, channels_r}, // GFX10_FORMAT_8_USCALED {4, VK_FORMAT_R8_SSCALED, channels_r}, // GFX10_FORMAT_8_SSCALED @@ -379,6 +383,13 @@ inline constexpr VkFormat vulkan_view_format(VkFormat image_format, std::uint32_ if (!image) return VK_FORMAT_UNDEFINED; if (image->gfx10 == gfx10_format) return image_format; if (is_depth_stencil_format(image_format)) return VK_FORMAT_UNDEFINED; + // An R9G9B9E5 render target on a GPU that cannot render to E5B9G9R9 is an R11G11B10F image (the D3D12 device's + // r9g9b9e5_target_stand_in): a T# that names 5_9_9_9 views it in the image's own format. The image is not + // mutable, and the two formats have the same channels, so the swizzle is unchanged. + if (image_format == VK_FORMAT_B10G11R11_UFLOAT_PACK32 && gfx10_format == 132) return image_format; + // The same for a B4G4R4A4 render target stored as BGRA8 (b4g4r4a4_target_stand_in): 4_4_4_4 names its channels + // in the order BGRA8 has them. + if (image_format == VK_FORMAT_B8G8R8A8_UNORM && gfx10_format == 136) return image_format; const FormatRow* fallback = nullptr; for (const FormatRow& row : format_table) { if (row.gfx10 != gfx10_format || is_depth_stencil_format(row.vulkan)) continue; diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp index 098a8ee400..ddf23d7264 100644 --- a/runtime/src/main.cpp +++ b/runtime/src/main.cpp @@ -18,6 +18,7 @@ // (--overlay, default /overlay) so the package is never modified (shims/file_system.cpp). #include +#include #include #include #include @@ -27,15 +28,127 @@ #include #include +#include + +namespace { + +// The retail title runs a hang watchdog thread: when the game's main loop has not set its "kick" byte for 30 +// one-second ticks, it calls a crash callback and then writes to address 0 (`movl $0, 0`). Under the runtime the +// game thread can legitimately stall for longer than that, e.g. while the driver compiles pipelines against a cold +// cache (first boot after a driver update), and the title then kills itself. The two places are measured locally +// and not kept in the repository: LEONIDA_TITLE_WATCHDOG_KICK="," (hex) names them, and only +// when that exact trap instruction sits at the first one does a runtime thread set the byte at the second twice a +// second, so the title's watchdog never fires. Unset (or LEONIDA_TITLE_WATCHDOG=1), the watchdog stays armed. +constexpr unsigned char kWatchdogTrap[] = {0xC7, 0x04, 0x25, 0, 0, 0, 0, 0, 0, 0, 0}; // movl $0, 0x0 + +bool watchdog_rvas(std::uint32_t& trap_rva, std::uint32_t& kick_rva) { + char value[64]{}; + const DWORD n = GetEnvironmentVariableA("LEONIDA_TITLE_WATCHDOG_KICK", value, sizeof(value)); + if (!n || n >= sizeof(value)) return false; + char* rest = nullptr; + const unsigned long long trap = std::strtoull(value, &rest, 16); + if (!rest || *rest != ',') return false; + const unsigned long long kick = std::strtoull(rest + 1, &rest, 16); + if (!rest || *rest || !trap || !kick || trap > 0xFFFFFFFFull || kick > 0xFFFFFFFFull) return false; + trap_rva = static_cast(trap); + kick_rva = static_cast(kick); + return true; +} + +void keep_title_watchdog_kicked(std::uint8_t* base) { + char keep[4]{}; + if (GetEnvironmentVariableA("LEONIDA_TITLE_WATCHDOG", keep, sizeof(keep)) == 1 && keep[0] == '1') return; + std::uint32_t kWatchdogTrapRva = 0, kWatchdogKickRva = 0; + if (!watchdog_rvas(kWatchdogTrapRva, kWatchdogKickRva)) return; + MEMORY_BASIC_INFORMATION trap{}, kick{}; + if (!VirtualQuery(base + kWatchdogTrapRva, &trap, sizeof(trap)) || trap.State != MEM_COMMIT || + std::memcmp(base + kWatchdogTrapRva, kWatchdogTrap, sizeof(kWatchdogTrap)) != 0) + return; // not the trap the RVAs name: leave the title's watchdog alone + const DWORD writable = PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY; + if (!VirtualQuery(base + kWatchdogKickRva, &kick, sizeof(kick)) || kick.State != MEM_COMMIT || + !(kick.Protect & writable)) + return; + volatile std::uint8_t* const byte = base + kWatchdogKickRva; + const HANDLE thread = CreateThread( + nullptr, 0, + [](LPVOID p) -> DWORD { + auto* b = static_cast(p); + for (;;) { + *b = 1; + Sleep(500); + } + }, + const_cast(byte), 0, nullptr); + if (thread) { + CloseHandle(thread); + std::fprintf(stderr, "[rt] loader: keeping the title's hang watchdog kicked (LEONIDA_TITLE_WATCHDOG_KICK)\n"); + } +} + +// LEONIDA_PEEK=":3,," (diagnostic): a thread prints the 8-byte values at these RVAs of the +// title's image (":n" = n consecutive values) every LEONIDA_PEEK_SECONDS (default 10). For answering "what does this +// global hold at run time" without a debugger: the reverse-engineering notes (docs/re/requests.md) ask for exactly +// that. Reads are checked; nothing is written. +void start_title_peek(std::uint8_t* base) { + static char spec[1024]; + const DWORD n = GetEnvironmentVariableA("LEONIDA_PEEK", spec, sizeof(spec)); + if (!n || n >= sizeof(spec)) return; + static std::uint8_t* image = base; + const HANDLE thread = CreateThread( + nullptr, 0, + [](LPVOID) -> DWORD { + char seconds[16]{}; + DWORD period = 10; + if (GetEnvironmentVariableA("LEONIDA_PEEK_SECONDS", seconds, sizeof(seconds)) > 0) + period = std::max(1, static_cast(std::strtoul(seconds, nullptr, 10))); + for (unsigned tick = 0;; ++tick) { + std::string line = "[rt] peek t=" + std::to_string(tick * period) + "s:"; + for (const char* at = spec; *at;) { + char* end = nullptr; + const std::uint64_t rva = std::strtoull(at, &end, 16); + if (end == at) break; + unsigned count = 1; + if (*end == ':') count = static_cast(std::strtoul(end + 1, &end, 10)); + char text[40]; + std::snprintf(text, sizeof(text), " 0x%llx=", static_cast(rva)); + line += text; + for (unsigned i = 0; i < count && i < 16; ++i) { + std::uint64_t value = 0; + SIZE_T got = 0; + const bool ok = ReadProcessMemory(GetCurrentProcess(), image + rva + 8ull * i, &value, + sizeof(value), &got) && got == sizeof(value); + std::snprintf(text, sizeof(text), ok ? "%s%llx" : "%s?", i ? "," : "", + static_cast(value)); + line += text; + } + at = *end == ',' ? end + 1 : end; + if (at == end && *end) break; + } + std::fprintf(stderr, "%s\n", line.c_str()); + Sleep(period * 1000); + } + }, + nullptr, 0, nullptr); + if (thread) CloseHandle(thread); +} + +} // namespace + #include "base_reservation.h" #include "code_hooks.h" #include "cpu_emulation.h" #include "host_cpu.h" #include "mods.h" #include "pe_loader.h" +#include "thread_stacks.h" +#include "title_page_watch.h" +#include "title_geometry_watch.h" #include "../shims/d3d12_trace.h" #include "../shims/d3d12_xs_device.h" #include "../shims/file_system.h" +#ifdef LEONIDA_VULKAN_DEVICE +#include "../shims/package_splash.h" +#endif #include "../shims/process_shim.h" #include "../shims/shims.h" #include "../shims/startup_trace.h" @@ -52,6 +165,16 @@ const char* binding_name(rt::Binding b) { } } +// Module TLS index 0 for the game's executable (rt::reserve_tls_index0), from the CRT's initializer table: .CRT$XCT +// runs after the C runtime is set up and before every C++ dynamic initializer of gta6rt (.CRT$XCU), so before any of +// gta6rt's code can have started a thread. The frames above it (wmainCRTStartup, __scrt_common_main_seh, _initterm) +// hold no TLS slot address. The result is read again where an image is run. +void __cdecl reserve_tls_index0_at_start() { rt::reserve_tls_index0(); } +#pragma section(".CRT$XCT", read) +extern "C" __declspec(allocate(".CRT$XCT")) void(__cdecl* const gta6rt_reserve_tls_index0)() = + reserve_tls_index0_at_start; +#pragma comment(linker, "/INCLUDE:gta6rt_reserve_tls_index0") + int usage() { std::fprintf(stderr, "usage: gta6rt --dry-run [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace FILE]\n" @@ -62,6 +185,17 @@ int usage() { } // namespace +#ifdef LEONIDA_VULKAN_DEVICE +static BOOL WINAPI show_package_window(HWND window, int command) { + const BOOL previous = ShowWindow(window, command); + const DWORD error = GetLastError(); + if (command != SW_HIDE && rt::package_splash::paint_window(window)) + rt::startup_trace::event("package_splash_window"); + SetLastError(error); + return previous; +} +#endif + int wmain(int argc, wchar_t** argv) { std::filesystem::path image, game_dir, overlay_dir, mods_dir; uint32_t archetype_lookup_rva = 0; // --archetype-lookup RVA[,ARG]: the game's archetype lookup by hash @@ -120,6 +254,15 @@ int wmain(int argc, wchar_t** argv) { return ec ? p : a; }; game_dir = game_dir.empty() ? absolute_or_same(image).parent_path() : absolute_or_same(game_dir); + // An unattended run can select a fresh write root even when its launcher supplies --overlay. + if (const DWORD size = GetEnvironmentVariableW(L"LEONIDA_WRITE_DIR", nullptr, 0)) { + std::wstring dir(size, 0); + const DWORD n = GetEnvironmentVariableW(L"LEONIDA_WRITE_DIR", dir.data(), size); + if (n && n < size) { + dir.resize(n); + overlay_dir = dir; + } + } if (!overlay_dir.empty()) overlay_dir = absolute_or_same(overlay_dir); // LEONIDA_SHADERS too: the D3D12 device reads it at the title's first pipeline state, after it may have moved. if (const DWORD size = GetEnvironmentVariableW(L"LEONIDA_SHADERS", nullptr, 0)) { @@ -137,6 +280,18 @@ int wmain(int argc, wchar_t** argv) { // GAME: paths read under --game-dir; whatever a title writes lands in the overlay, never in the package. if (overlay_dir.empty()) overlay_dir = game_dir / "overlay"; rt::fs::configure(game_dir, overlay_dir); +#ifdef LEONIDA_VULKAN_DEVICE + if (run) { + rt::package_splash::configure(game_dir); + if (rt::package_splash::configured()) { + const rt::shims::Entry window_imports[] = { + {"ext-ms-win-rtcore-ntuser-window-l1-1-0.dll", "ShowWindow", reinterpret_cast(&show_package_window)}, + {"user32.dll", "ShowWindow", reinterpret_cast(&show_package_window)}, + }; + rt::shims::Table{window_imports, std::size(window_imports)}; + } + } +#endif // Mods (docs/modding.md): \mods unless --mods names another. Loaded and reported here; // the archetype swaps take effect once the game's archetype lookup is hooked for this executable version. if (mods_dir.empty()) { @@ -168,6 +323,9 @@ int wmain(int argc, wchar_t** argv) { rt::d3d12_trace::set_enabled(trace_d3d12); // Slot 133 imports the title's pages; xmem commits them on first touch, so they are committed first. rt::d3d12_xs::set_placed_at_va_pages_hook(&rt::xmem::commit_physical_range); + // So do the file shims' reads, whose kernel writes do not fault them in: on ERROR_NOACCESS (title_page_watch.h). + leonida::geometry_writes::aliases.store(&rt::xmem::geometry_aliases); + leonida::kernel_writes::set_committer(&rt::xmem::commit_physical_range); if (int trace_error = 0; !trace_file.empty() && !rt::startup_trace::open(trace_file.c_str(), &trace_error)) { std::fprintf(stderr, trace_error == EEXIST ? "error: the trace file already exists; --trace only creates a new file\n" : "error: cannot create the trace file\n"); @@ -186,6 +344,20 @@ int wmain(int argc, wchar_t** argv) { try { rt::Loader loader(game_dir); rt::Module& main_module = loader.load(image); // maps, binds and installs TLS; runs no image code + // An executable with TLS that did not get index 0: its /GA code would read and write the TLS in slot 0, which + // is gta6rt's own (or another executable's), so no code of it may run. + const auto* main_nt = reinterpret_cast( + main_module.base + reinterpret_cast(main_module.base)->e_lfanew); + const bool main_is_exe = (main_nt->FileHeader.Characteristics & IMAGE_FILE_DLL) == 0; + if ((init || run) && main_is_exe && main_module.tls_slot != rt::kNoTlsIndex && main_module.tls_index != 0) { + std::string why; + if (rt::reserve_tls_index0(&why)) why = "another mapped executable holds it"; + std::fprintf(stderr, + "error: %s cannot have module TLS index 0 (%s); code built with /GA would read and write " + "another module's TLS through slot 0, so it is not run\n", + main_module.name.c_str(), why.c_str()); + return 1; + } // The mods' archetype swaps (docs/modding.md): hooked here, before any image code runs, when the lookup's RVA // for this executable is given. The count of redirected calls shows whether the RVA is the real lookup. if (view_mode_getter_rva) { @@ -272,7 +444,13 @@ int wmain(int argc, wchar_t** argv) { } std::printf("running %s\n", main_module.name.c_str()); std::fflush(stdout); - const int code = rt::process::run_entry(main_module.base + main_module.entry_rva); + keep_title_watchdog_kicked(main_module.base); + start_title_peek(main_module.base); + int code; + { + auto stacks = rt::start_thread_stacks(); + code = rt::process::run_entry(main_module.base + main_module.entry_rva); + } std::fflush(stdout); std::printf("game exited with code %d\n", code); rt::shims::report_called_unimplemented(); diff --git a/runtime/src/mem_probe.h b/runtime/src/mem_probe.h new file mode 100644 index 0000000000..a36d38bfe3 --- /dev/null +++ b/runtime/src/mem_probe.h @@ -0,0 +1,570 @@ +#pragma once + +// LOCAL DIAGNOSTIC (not for upstream): mem probe. Where the game process's memory goes. +// LEONIDA_MEM_PROBE= turns it on (absent or 0: off, and nothing below is installed). Every it logs +// [rt] mem-probe t=...: the live Vulkan objects the runtime made (pipelines by kind, shader modules and their SPIR-V +// bytes, VkDeviceMemory per memory type, split into allocated and imported), what the device +// adds (pipeline cache bytes, arena, title memory), and +// [rt] mem-probe smaps: /proc/self/smaps of the Wine process, Rss and Swap per kind of mapping: title memory, +// other PE private memory (runtime + title heaps), PE images, PE sections, memory the Vulkan +// driver mapped for us, /dev/nvidia* mappings, other native (Unix-side) anonymous memory +// (driver heaps, glibc arenas), and files. +// The Vulkan counts come from wrapping the runtime's own function table (install()); helpers that load their own +// pointers (depth24, predicate, xdxr, swapchain) are not counted: they create a handful of objects. + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace leonida::mem_probe { + +struct Allocation { + std::uint32_t type = 0; + std::uint64_t bytes = 0; + bool imported = false; + std::uintptr_t mapped = 0; + std::uint64_t mapped_bytes = 0; +}; + +struct State { + PFN_vkAllocateMemory allocate = nullptr; + PFN_vkFreeMemory free = nullptr; + PFN_vkMapMemory map = nullptr; + PFN_vkUnmapMemory unmap = nullptr; + PFN_vkCreateShaderModule create_module = nullptr; + PFN_vkDestroyShaderModule destroy_module = nullptr; + PFN_vkCreateGraphicsPipelines create_graphics = nullptr; + PFN_vkCreateComputePipelines create_compute = nullptr; + PFN_vkDestroyPipeline destroy_pipeline = nullptr; + + std::mutex mutex; + std::unordered_map allocations; + std::unordered_map modules; + std::unordered_map pipelines; // 0 graphics, 1 compute + std::uint64_t module_bytes = 0, modules_made = 0, module_bytes_made = 0; + std::uint64_t graphics_live = 0, compute_live = 0, graphics_made = 0, compute_made = 0; + std::uint64_t graphics_ns = 0, compute_ns = 0; // time inside vkCreate*Pipelines + std::uint64_t installed = 0; + ULONGLONG started = 0; +}; + +inline State& state() { + static State s; + return s; +} + +inline unsigned interval_seconds() { + static const unsigned seconds = [] { + char text[16] = {}; + DWORD n = GetEnvironmentVariableA("LEONIDA_MEM_PROBE", text, sizeof text); + if (!n || n >= sizeof text) return 0u; + return unsigned(std::strtoul(text, nullptr, 10)); + }(); + return seconds; +} + +inline bool imported_memory(const VkMemoryAllocateInfo* info) { + for (auto* p = static_cast(info->pNext); p; p = p->pNext) + if (p->sType == VK_STRUCTURE_TYPE_IMPORT_MEMORY_HOST_POINTER_INFO_EXT || + p->sType == VK_STRUCTURE_TYPE_IMPORT_MEMORY_WIN32_HANDLE_INFO_KHR || + p->sType == VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR) + return true; + return false; +} + +inline VKAPI_ATTR VkResult VKAPI_CALL allocate_memory(VkDevice device, const VkMemoryAllocateInfo* info, + const VkAllocationCallbacks* callbacks, VkDeviceMemory* out) { + State& s = state(); + const VkResult result = s.allocate(device, info, callbacks, out); + if (result == VK_SUCCESS && out && *out) { + std::lock_guard lock(s.mutex); + s.allocations[*out] = {info->memoryTypeIndex, info->allocationSize, imported_memory(info), 0, 0}; + } + return result; +} + +inline VKAPI_ATTR void VKAPI_CALL free_memory(VkDevice device, VkDeviceMemory memory, + const VkAllocationCallbacks* callbacks) { + State& s = state(); + if (memory) { + std::lock_guard lock(s.mutex); + s.allocations.erase(memory); + } + s.free(device, memory, callbacks); +} + +inline VKAPI_ATTR VkResult VKAPI_CALL map_memory(VkDevice device, VkDeviceMemory memory, VkDeviceSize offset, + VkDeviceSize size, VkMemoryMapFlags flags, void** data) { + State& s = state(); + const VkResult result = s.map(device, memory, offset, size, flags, data); + if (result == VK_SUCCESS && data && *data) { + std::lock_guard lock(s.mutex); + if (auto it = s.allocations.find(memory); it != s.allocations.end()) { + it->second.mapped = reinterpret_cast(*data); + it->second.mapped_bytes = size == VK_WHOLE_SIZE ? it->second.bytes - offset : size; + } + } + return result; +} + +inline VKAPI_ATTR void VKAPI_CALL unmap_memory(VkDevice device, VkDeviceMemory memory) { + State& s = state(); + { + std::lock_guard lock(s.mutex); + if (auto it = s.allocations.find(memory); it != s.allocations.end()) it->second.mapped = 0; + } + s.unmap(device, memory); +} + +inline VKAPI_ATTR VkResult VKAPI_CALL create_shader_module(VkDevice device, const VkShaderModuleCreateInfo* info, + const VkAllocationCallbacks* callbacks, + VkShaderModule* out) { + State& s = state(); + const VkResult result = s.create_module(device, info, callbacks, out); + if (result == VK_SUCCESS && out && *out) { + std::lock_guard lock(s.mutex); + s.modules[*out] = info->codeSize; + s.module_bytes += info->codeSize; + ++s.modules_made; + s.module_bytes_made += info->codeSize; + } + return result; +} + +inline VKAPI_ATTR void VKAPI_CALL destroy_shader_module(VkDevice device, VkShaderModule module, + const VkAllocationCallbacks* callbacks) { + State& s = state(); + if (module) { + std::lock_guard lock(s.mutex); + if (auto it = s.modules.find(module); it != s.modules.end()) { + s.module_bytes -= it->second; + s.modules.erase(it); + } + } + s.destroy_module(device, module, callbacks); +} + +inline std::uint64_t now_ns() { + return std::uint64_t( + std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()) + .count()); +} + +inline void note_pipelines(std::uint8_t kind, std::uint32_t count, const VkPipeline* made, std::uint64_t ns) { + State& s = state(); + std::lock_guard lock(s.mutex); + (kind ? s.compute_ns : s.graphics_ns) += ns; + for (std::uint32_t i = 0; i < count; ++i) { + if (!made[i]) continue; + s.pipelines[made[i]] = kind; + ++(kind ? s.compute_live : s.graphics_live); + ++(kind ? s.compute_made : s.graphics_made); + } +} + +inline double mib(std::uint64_t bytes) { return double(bytes) / 1048576.0; } + +// One line per pipeline call that takes 1 s or more: how long, and how big its SPIR-V was. +inline void note_slow(const char* kind, std::uint64_t ns, std::uint64_t spirv_bytes, std::uint32_t stages) { + if (ns < 1000000000ull) return; + std::fprintf(stderr, "[rt] mem-probe slow %s pipeline: %.1f s, %u stages, %.1f MiB SPIR-V\n", kind, + double(ns) / 1e9, stages, mib(spirv_bytes)); +} + +inline std::uint64_t module_size(VkShaderModule module) { + State& s = state(); + std::lock_guard lock(s.mutex); + const auto it = s.modules.find(module); + return it == s.modules.end() ? 0 : it->second; +} + +inline VKAPI_ATTR VkResult VKAPI_CALL create_graphics_pipelines(VkDevice device, VkPipelineCache cache, + std::uint32_t count, + const VkGraphicsPipelineCreateInfo* infos, + const VkAllocationCallbacks* callbacks, + VkPipeline* out) { + const std::uint64_t t0 = now_ns(); + const VkResult result = state().create_graphics(device, cache, count, infos, callbacks, out); + const std::uint64_t ns = now_ns() - t0; + if (result >= 0 && out) note_pipelines(0, count, out, ns); + if (ns >= 1000000000ull && count == 1) { + std::uint64_t bytes = 0; + for (std::uint32_t i = 0; i < infos[0].stageCount; ++i) bytes += module_size(infos[0].pStages[i].module); + note_slow("graphics", ns, bytes, infos[0].stageCount); + } + return result; +} + +inline VKAPI_ATTR VkResult VKAPI_CALL create_compute_pipelines(VkDevice device, VkPipelineCache cache, + std::uint32_t count, + const VkComputePipelineCreateInfo* infos, + const VkAllocationCallbacks* callbacks, + VkPipeline* out) { + const std::uint64_t t0 = now_ns(); + const VkResult result = state().create_compute(device, cache, count, infos, callbacks, out); + const std::uint64_t ns = now_ns() - t0; + if (result >= 0 && out) note_pipelines(1, count, out, ns); + if (ns >= 1000000000ull && count == 1) note_slow("compute", ns, module_size(infos[0].stage.module), 1); + return result; +} + +inline VKAPI_ATTR void VKAPI_CALL destroy_pipeline(VkDevice device, VkPipeline pipeline, + const VkAllocationCallbacks* callbacks) { + State& s = state(); + if (pipeline) { + std::lock_guard lock(s.mutex); + if (auto it = s.pipelines.find(pipeline); it != s.pipelines.end()) { + --(it->second ? s.compute_live : s.graphics_live); + s.pipelines.erase(it); + } + } + s.destroy_pipeline(device, pipeline, callbacks); +} + +// Wraps the runtime's function table (leonida::VulkanDeviceFunctions). Once per process: the first device wins. +template +void install(Functions& vk) { + if (!interval_seconds()) return; + State& s = state(); + std::lock_guard lock(s.mutex); + if (s.installed++) return; + if (!vk.vkAllocateMemory || !vk.vkFreeMemory || !vk.vkMapMemory || !vk.vkUnmapMemory || + !vk.vkCreateShaderModule || !vk.vkDestroyShaderModule || !vk.vkCreateGraphicsPipelines || + !vk.vkCreateComputePipelines || !vk.vkDestroyPipeline) + return; + s.started = GetTickCount64(); + s.allocate = vk.vkAllocateMemory, vk.vkAllocateMemory = allocate_memory; + s.free = vk.vkFreeMemory, vk.vkFreeMemory = free_memory; + s.map = vk.vkMapMemory, vk.vkMapMemory = map_memory; + s.unmap = vk.vkUnmapMemory, vk.vkUnmapMemory = unmap_memory; + s.create_module = vk.vkCreateShaderModule, vk.vkCreateShaderModule = create_shader_module; + s.destroy_module = vk.vkDestroyShaderModule, vk.vkDestroyShaderModule = destroy_shader_module; + s.create_graphics = vk.vkCreateGraphicsPipelines, vk.vkCreateGraphicsPipelines = create_graphics_pipelines; + s.create_compute = vk.vkCreateComputePipelines, vk.vkCreateComputePipelines = create_compute_pipelines; + s.destroy_pipeline = vk.vkDestroyPipeline, vk.vkDestroyPipeline = destroy_pipeline; + std::fprintf(stderr, "[rt] mem-probe: installed, every %u s\n", interval_seconds()); +} + +// ---- /proc/self/smaps, classified ---- +enum Bucket { + b_title, // the title's memory (XMem / title VirtualAlloc ranges) + b_pe_private, // other PE private memory: the runtime's and the title's heaps, stacks + b_pe_high, // PE private memory at 0x7f0000000000 and above (where native mmaps land: a check on Wine views) + b_pe_image, // PE images (exe/dll) + b_pe_mapped, // PE sections (file mappings, pagefile-backed sections) + b_vk_mapped, // memory the Vulkan driver mapped for vkMapMemory + b_nvidia, // other /dev/nvidia* mappings + b_native_anon, // native anonymous memory Wine does not know: driver heaps, glibc arenas, [heap], [stack] + b_file, // native file mappings (.so, ...) + b_count +}; +inline const char* bucket_name(int b) { + static const char* names[b_count] = {"title", "pe-private", "pe-private@7f", "pe-image", "pe-section", + "vk-mapped", "nvidia-dev", "native-anon", "native-file"}; + return names[b]; +} + +struct Usage { + std::uint64_t rss = 0, anon = 0, swap = 0, vmas = 0; +}; + +using Ranges = std::vector>; // [begin, end), sorted + +inline bool in_ranges(const Ranges& ranges, std::uint64_t va) { + auto it = std::upper_bound(ranges.begin(), ranges.end(), std::make_pair(va, UINT64_MAX)); + if (it == ranges.begin()) return false; + --it; + return va >= it->first && va < it->second; +} + +inline std::string read_small(const std::string& path) { + HANDLE file = CreateFileA(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, + nullptr); + if (file == INVALID_HANDLE_VALUE) return {}; + std::string text; + std::vector buffer(16384); + DWORD got = 0; + while (ReadFile(file, buffer.data(), DWORD(buffer.size()), &got, nullptr) && got) text.append(buffer.data(), got); + CloseHandle(file); + return text; +} + +// The Unix process of this Wine process. Wine opens files in wineserver, so Z:\proc\self is the server: the game is +// the /proc entry whose command line names gta6rt and whose address space is the largest (one boot at a time). +inline std::string proc_dir() { + static std::string found; + if (!found.empty()) return found; + WIN32_FIND_DATAA data{}; + HANDLE find = FindFirstFileA("Z:\\proc\\*", &data); + if (find == INVALID_HANDLE_VALUE) return {}; + std::uint64_t best = 0; + do { + if (data.cFileName[0] < '1' || data.cFileName[0] > '9') continue; + const std::string dir = std::string("Z:\\proc\\") + data.cFileName; + std::string cmdline = read_small(dir + "\\cmdline"); + for (char& c : cmdline) c = char(std::tolower(static_cast(c))); + if (cmdline.find("gta6rt") == std::string::npos) continue; + const std::string status = read_small(dir + "\\status"); + const std::size_t at = status.find("VmSize:"); + const std::uint64_t vm = at == std::string::npos ? 0 : std::strtoull(status.c_str() + at + 7, nullptr, 10); + if (vm > best) { + best = vm; + found = dir; + } + } while (FindNextFileA(find, &data)); + FindClose(find); + if (!found.empty()) std::fprintf(stderr, "[rt] mem-probe: this process is %s (VmSize %llu kB)\n", found.c_str(), + (unsigned long long)best); + return found; +} + +// Parses /proc//smaps (Wine reaches the Unix /proc through Z:). Classifies each VMA by its start address. +inline bool read_smaps(const Ranges& title, const Ranges& vk_mapped, Usage (&usage)[b_count], std::string& top_files, + std::string& error) { + const std::string dir = proc_dir(); + if (dir.empty()) { + error = "no /proc entry names gta6rt"; + return false; + } + HANDLE file = CreateFileA((dir + "\\smaps").c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, + OPEN_EXISTING, 0, nullptr); + if (file == INVALID_HANDLE_VALUE) { + error = "open failed " + std::to_string(GetLastError()); + return false; + } + std::vector buffer(1 << 20); + std::string carry; + int bucket = -1; + std::string path; + std::map files; + const auto field = [](const char* line, const char* name, std::uint64_t& out) { + const std::size_t n = std::strlen(name); + if (std::strncmp(line, name, n) != 0) return false; + out = std::strtoull(line + n, nullptr, 10) * 1024; + return true; + }; + const auto header = [&](const char* line) { + // 7f0000000000-7f0000001000 rw-p 00000000 00:00 0 [path] + char* end = nullptr; + const std::uint64_t begin = std::strtoull(line, &end, 16); + if (!end || *end != '-') return false; + const char* p = line; + for (int fields = 0; fields < 5 && *p; ++fields) { // skip range perms offset dev inode + while (*p && *p != ' ') ++p; + while (*p == ' ') ++p; + } + path = p; + while (!path.empty() && (path.back() == '\n' || path.back() == '\r' || path.back() == ' ')) path.pop_back(); + if (in_ranges(title, begin)) { + bucket = b_title; + } else if (in_ranges(vk_mapped, begin)) { + bucket = b_vk_mapped; + } else if (path.rfind("/dev/nvidia", 0) == 0) { + bucket = b_nvidia; + } else { + MEMORY_BASIC_INFORMATION region{}; + const bool known = VirtualQuery(reinterpret_cast(begin), ®ion, sizeof region) && + region.State == MEM_COMMIT; + if (known && region.Type == MEM_IMAGE) bucket = b_pe_image; + else if (known && region.Type == MEM_MAPPED) bucket = b_pe_mapped; + else if (known && region.Type == MEM_PRIVATE) bucket = begin >= 0x7f0000000000ull ? b_pe_high : b_pe_private; + else if (!path.empty() && path[0] == '/' ) bucket = b_file; + else bucket = b_native_anon; + } + ++usage[bucket].vmas; + return true; + }; + const auto line_of = [&](const char* line) { + std::uint64_t value = 0; + if ((line[0] >= '0' && line[0] <= '9') || (line[0] >= 'a' && line[0] <= 'f')) { + if (header(line)) return; + } + if (bucket < 0) return; + if (field(line, "Rss:", value)) { + usage[bucket].rss += value; + if (bucket == b_file || bucket == b_pe_image || bucket == b_pe_mapped) files[path].rss += value; + } else if (field(line, "Anonymous:", value)) { + usage[bucket].anon += value; + } else if (field(line, "Swap:", value)) { + usage[bucket].swap += value; + if (bucket == b_file || bucket == b_pe_image || bucket == b_pe_mapped) files[path].swap += value; + } + }; + DWORD got = 0; + while (ReadFile(file, buffer.data(), DWORD(buffer.size()), &got, nullptr) && got) { + carry.append(buffer.data(), got); + std::size_t start = 0; + for (std::size_t nl; (nl = carry.find('\n', start)) != std::string::npos; start = nl + 1) { + carry[nl] = 0; + line_of(carry.c_str() + start); + } + carry.erase(0, start); + } + CloseHandle(file); + std::vector> ranked; + for (auto& [name, u] : files) ranked.push_back({u.rss + u.swap, name}); + std::sort(ranked.rbegin(), ranked.rend()); + char text[256]; + for (std::size_t i = 0; i < ranked.size() && i < 4; ++i) { + std::string name = ranked[i].second.empty() ? "(none)" : ranked[i].second; + if (name.size() > 60) name = "..." + name.substr(name.size() - 57); + std::snprintf(text, sizeof text, "%s%s %.0f", i ? ", " : "", name.c_str(), mib(ranked[i].first)); + top_files += text; + } + return true; +} + +// Sums the Linux-side totals the kernel keeps (/proc//smaps_rollup), for a check of the buckets. +inline std::string read_rollup() { + const std::string dir = proc_dir(); + const std::string text = dir.empty() ? std::string() : read_small(dir + "\\smaps_rollup"); + if (text.empty()) return "rollup: open failed"; + std::string out = "rollup MiB:"; + for (const char* name : {"Rss:", "Anonymous:", "Swap:", "Pss_File:", "Pss_Shmem:"}) { + const std::size_t at = text.find(std::string("\n") + name); + if (at == std::string::npos) continue; + const std::uint64_t kb = std::strtoull(text.c_str() + at + 1 + std::strlen(name), nullptr, 10); + char item[64]; + std::snprintf(item, sizeof item, " %.*s %.0f", int(std::strlen(name) - 1), name, double(kb) / 1024.0); + out += item; + } + return out; +} + +// What the device adds to the line: pipeline cache bytes, arena use, title memory ranges. +struct DeviceFacts { + std::function describe; // one text fragment + std::function title_ranges; // the title's memory + VkPhysicalDeviceMemoryProperties memory{}; +}; + +inline std::string type_flags(VkMemoryPropertyFlags f) { + std::string s; + if (f & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) s += "DL"; + if (f & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) s += s.empty() ? "HV" : "+HV"; + if (f & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) s += "+HC"; + if (f & VK_MEMORY_PROPERTY_HOST_CACHED_BIT) s += "+HCa"; + return s.empty() ? "none" : s; +} + +inline std::string wall_clock() { + SYSTEMTIME now{}; + GetLocalTime(&now); + char text[16]; + std::snprintf(text, sizeof text, "%02u:%02u:%02u", now.wHour, now.wMinute, now.wSecond); + return text; +} + +inline void sample(const DeviceFacts& facts) { + State& s = state(); + const double t = double(GetTickCount64() - s.started) / 1000.0; + std::uint64_t type_count[VK_MAX_MEMORY_TYPES] = {}, type_bytes[VK_MAX_MEMORY_TYPES] = {}; + std::uint64_t import_count[VK_MAX_MEMORY_TYPES] = {}, import_bytes[VK_MAX_MEMORY_TYPES] = {}; + Ranges vk_mapped; + std::uint64_t modules = 0, module_bytes = 0, modules_made = 0, module_bytes_made = 0; + std::uint64_t graphics = 0, compute = 0, graphics_made = 0, compute_made = 0, graphics_ns = 0, compute_ns = 0; + { + std::lock_guard lock(s.mutex); + for (const auto& [memory, a] : s.allocations) { + const std::uint32_t i = a.type < VK_MAX_MEMORY_TYPES ? a.type : 0; + if (a.imported) { + ++import_count[i]; + import_bytes[i] += a.bytes; + } else { + ++type_count[i]; + type_bytes[i] += a.bytes; + } + if (a.mapped && !a.imported) vk_mapped.push_back({a.mapped, a.mapped + a.mapped_bytes}); + } + modules = s.modules.size(); + module_bytes = s.module_bytes; + modules_made = s.modules_made; + module_bytes_made = s.module_bytes_made; + graphics = s.graphics_live; + compute = s.compute_live; + graphics_made = s.graphics_made; + compute_made = s.compute_made; + graphics_ns = s.graphics_ns; + compute_ns = s.compute_ns; + } + std::sort(vk_mapped.begin(), vk_mapped.end()); + std::string memory_text; + char item[256]; + for (std::uint32_t i = 0; i < facts.memory.memoryTypeCount && i < VK_MAX_MEMORY_TYPES; ++i) { + if (!type_count[i] && !import_count[i]) continue; + std::snprintf(item, sizeof item, " type %u %s heap %u: %llu x %.0f MiB", i, + type_flags(facts.memory.memoryTypes[i].propertyFlags).c_str(), + facts.memory.memoryTypes[i].heapIndex, (unsigned long long)type_count[i], mib(type_bytes[i])); + memory_text += item; + if (import_count[i]) { + std::snprintf(item, sizeof item, " (+%llu imported, %.0f MiB)", (unsigned long long)import_count[i], + mib(import_bytes[i])); + memory_text += item; + } + memory_text += ';'; + } + std::fprintf(stderr, + "[rt] mem-probe t=%.0fs (%s): pipelines live graphics %llu compute %llu (made %llu / %llu, %.1f s / %.1f s " + "in vkCreate*Pipelines); shader modules live %llu, %.0f MiB SPIR-V (made %llu, %.0f MiB); " + "vk memory:%s %s\n", + t, wall_clock().c_str(), (unsigned long long)graphics, (unsigned long long)compute, (unsigned long long)graphics_made, + (unsigned long long)compute_made, double(graphics_ns) / 1e9, double(compute_ns) / 1e9, + (unsigned long long)modules, mib(module_bytes), (unsigned long long)modules_made, + mib(module_bytes_made), memory_text.c_str(), facts.describe ? facts.describe().c_str() : ""); + Ranges title = facts.title_ranges ? facts.title_ranges() : Ranges{}; + std::sort(title.begin(), title.end()); + Usage usage[b_count]; + std::string top_files, error; + const std::uint64_t t0 = now_ns(); + if (!read_smaps(title, vk_mapped, usage, top_files, error)) { + std::fprintf(stderr, "[rt] mem-probe smaps t=%.0fs: %s\n", t, error.c_str()); + return; + } + std::string text; + std::uint64_t rss = 0, swap = 0; + for (int b = 0; b < b_count; ++b) { + rss += usage[b].rss; + swap += usage[b].swap; + std::snprintf(item, sizeof item, " %s %.0f+%.0f (anon %.0f, %llu vmas);", bucket_name(b), mib(usage[b].rss), + mib(usage[b].swap), mib(usage[b].anon), (unsigned long long)usage[b].vmas); + text += item; + } + std::fprintf(stderr, + "[rt] mem-probe smaps t=%.0fs (%.0f ms): total rss %.0f + swap %.0f MiB; rss+swap per kind:%s top " + "files: %s; %s\n", + t, double(now_ns() - t0) / 1e6, mib(rss), mib(swap), text.c_str(), top_files.c_str(), + read_rollup().c_str()); +} + +// Starts the sampling thread (once). The thread runs until the process ends. +inline void start(DeviceFacts facts) { + const unsigned seconds = interval_seconds(); + if (!seconds) return; + static std::once_flag once; + std::call_once(once, [&] { + std::thread([facts = std::move(facts), seconds] { + for (;;) { + Sleep(seconds * 1000); + sample(facts); + } + }).detach(); + }); +} + +} // namespace leonida::mem_probe diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index cc4ae88aab..3558cffb58 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -19,6 +19,8 @@ #include "../shims/shims.h" #include "../shims/startup_trace.h" #include "base_reservation.h" +#include "clzero_patch.h" +#include "cpu_emulation.h" namespace rt { @@ -126,8 +128,29 @@ IMAGE_TLS_DIRECTORY64* tls_directory(Module& m) { // reuses that index for the mapped image. When more than one manually mapped module uses static TLS at once, the loader // clones gta6rt_tls_host.dll to a per-process temporary path on demand and loads it, so the OS assigns an independent // module TLS index for each simultaneous module (up to kMaxMappedTlsModules). +// +// A mapped executable is different: MSVC code built with /GA (an EXE-only optimisation) skips _tls_index and reads +// TEB->ThreadLocalStoragePointer[0] directly (mov rax, gs:[58h]; mov rax, [rax]), because Windows always gives the +// process executable module TLS index 0. Measured with a `thread_local int v = 42;` EXE built /O2 /GA /MD: natively +// tls_index=0 value=42; mapped with a helper index (6) the code still read slot 0 and printed value=0. Index 0 +// belongs to the runtime's own EXE (gta6rt.exe: a 1398-byte template when measured, no TLS callbacks; so does each +// test EXE that links this file), and every TLS read in its disassembly goes through _tls_index (the only direct +// gs:[58h] read is module_tls_slots below, which wants the array itself). reserve_tls_index0 therefore moves the owner +// off index 0, once, at process start: it loads the home clone (make_home_clone_image), whose TLS template is a copy of +// the owner's, and on the calling thread swaps slots 0 and home and writes home into the owner's _tls_index. From then on every thread the OS +// starts has a fresh copy of the owner's template at home, which is where the owner looks, from its first instruction: +// nothing has to run on a new thread first. Slot 0 holds a block nobody reads, which the mapped executable's copy +// replaces (kMainImageSlot) exactly as a DLL's copy replaces a helper's, and the OS frees both slots at thread exit. +// It has to happen before any other thread has run the owner's code: MSVC keeps &ThreadLocalStoragePointer[_tls_index] +// across calls (zlib_inflate in shader_library.h saves it at [rbp-80h] across memset, push_back and inflate_codes, then +// reads _Init_thread_epoch through it), so a running thread cannot be moved safely, wherever it is stopped. Such a +// thread's TLS would also stay where it was, at index 0. constexpr DWORD kMaxModuleTlsSlots = 64; constexpr size_t kMaxMappedTlsModules = 16; +// The slot for a mapped executable, which reads module TLS index 0 (see above). Only one at a time; a second +// executable mapped while one is live gets an ordinary helper slot. kTlsSlotCount sizes the per-slot tables. +constexpr size_t kMainImageSlot = kMaxMappedTlsModules; +constexpr size_t kTlsSlotCount = kMaxMappedTlsModules + 1; void** module_tls_slots() { return reinterpret_cast(__readgsqword(0x58)); } void __cdecl on_host_thread_event(DWORD reason); @@ -135,6 +158,7 @@ void __cdecl on_host_thread_event(DWORD reason); struct TlsHostModule { HMODULE module = nullptr; DWORD index = TLS_OUT_OF_INDEXES; + bool hooked = false; // its DllMain reports thread events to on_host_thread_event }; std::filesystem::path tls_host_base_path() { @@ -167,20 +191,39 @@ struct TlsCloneRecord { std::mutex g_tls_alloc_mutex; std::array g_tls_hosts{}; -std::array, kMaxMappedTlsModules> g_tls_slot_owners{}; -std::array, kMaxMappedTlsModules> g_tls_slot_generations{}; +std::array, kTlsSlotCount> g_tls_slot_owners{}; +std::array, kTlsSlotCount> g_tls_slot_generations{}; std::atomic g_next_tls_generation{1}; -std::vector g_tls_clones; +// Allocated with the first clone and never destroyed: cleanup_tls_clones_at_exit runs from the atexit table, and a +// static vector's destructor (registered when its dynamic initializer ran) could run before it. Under +// g_tls_alloc_mutex, as are its records. +std::vector* g_tls_clones = nullptr; + +// The move of module TLS index 0 (see kMainImageSlot): done at most once, by reserve_tls_index0 under +// g_tls_alloc_mutex. `why` is the reason it was not done, for the executable that then maps with a helper index. +// Constant-initialized only (no std::string): gta6rt reserves from a CRT initializer that runs before the dynamic +// initializers of this file, which would otherwise reset what it wrote. +struct Index0Move { + bool moved = false; + bool traced = false; // the startup trace opens after the move; the first executable map reports it + TlsHostModule home; // the clone whose index holds the owner's TLS from now on; never freed + char owner[260] = {}; // UTF-8 file name of the image that held index 0 + char why[160] = "reserve_tls_index0 was not called at process start"; +}; +Index0Move g_index0; -// Frees every TLS helper clone this process loaded and deletes its files. load() registers the wrapper with atexit; -// the --run path in main() must also call this directly before ExitProcess, which skips the atexit table. Call it -// only when no mapped code can run again: it unmaps the helper images. +// Frees every TLS helper clone recorded for a mapped DLL's slot and deletes its files. ensure_tls_host registers the +// wrapper with atexit when it records the first clone; the --run path in main() must also call this directly before +// ExitProcess, which skips the atexit table. Call it only when no mapped code can run again: it unmaps the helper +// images. The home clone is not recorded (reserve_index0): it stays loaded, so its file outlives the process and the +// next run's sweep deletes it. void cleanup_tls_clones_internal() { - for (const auto& rec : g_tls_clones) { + if (!g_tls_clones) return; + for (const auto& rec : *g_tls_clones) { if (rec.module) FreeLibrary(rec.module); if (!rec.path.empty()) DeleteFileW(rec.path.c_str()); } - g_tls_clones.clear(); + g_tls_clones->clear(); } void cleanup_tls_clones_at_exit() { cleanup_tls_clones_internal(); } @@ -204,10 +247,14 @@ DWORD clone_owner_pid(const wchar_t* name) { bool process_alive(DWORD pid) { // PROCESS_QUERY_LIMITED_INFORMATION needs no handle rights a normal process could deny; a failure means the // process is gone. A still-mapped or still-open file is caught by the checks below even for a misjudged PID. + // OpenProcess also succeeds on a process that has ended while another process still holds a handle to it (a + // parent waiting on its exit code, as CMake's execute_process does), so the exit code decides. HANDLE p = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid); if (!p) return false; + DWORD code = 0; + const bool alive = !GetExitCodeProcess(p, &code) || code == STILL_ACTIVE; CloseHandle(p); - return true; + return alive; } // Deletes clones left behind by processes that have exited. Deletion is scoped to files whose owner is gone: a @@ -262,45 +309,66 @@ TlsHostModule load_tls_host_image(const std::filesystem::path& path, bool hook_t if (hook_thread_events) { // Only the primary helper reports thread attach/detach events; on_host_thread_event iterates all active slots. using SetThreadEvent = void(__cdecl*)(void(__cdecl*)(DWORD)); - if (auto set = reinterpret_cast(GetProcAddress(host.module, "gta6rt_tls_host_set_thread_event"))) + auto set = reinterpret_cast(GetProcAddress(host.module, "gta6rt_tls_host_set_thread_event")); + if (set) { set(&on_host_thread_event); + host.hooked = true; + } } return host; } -// Must be called with g_tls_alloc_mutex held and WITHOUT g_tls_lock held (LoadLibraryExW takes the Windows loader lock). -TlsHostModule ensure_tls_host(size_t slot) { - if (slot >= kMaxMappedTlsModules) return {}; - if (g_tls_hosts[slot].index != TLS_OUT_OF_INDEXES) return g_tls_hosts[slot]; - +// The primary helper: slot 0's index, and the only helper whose DllMain reports thread events (on_host_thread_event +// covers every slot). Must be called with g_tls_alloc_mutex held and WITHOUT g_tls_lock held (LoadLibraryExW takes the +// Windows loader lock). +// A helper without the thread-event export is refused: no thread started later would get its copies. +bool ensure_primary_tls_host() { + if (g_tls_hosts[0].index != TLS_OUT_OF_INDEXES) return true; const std::filesystem::path primary = tls_host_base_path(); - if (primary.empty()) return {}; - - if (slot == 0) { - g_tls_hosts[0] = load_tls_host_image(primary, true); - return g_tls_hosts[0]; - } - - // Ensure slot 0 is loaded first so thread attach/detach events are hooked. - if (g_tls_hosts[0].index == TLS_OUT_OF_INDEXES) { - g_tls_hosts[0] = load_tls_host_image(primary, true); - if (g_tls_hosts[0].index == TLS_OUT_OF_INDEXES) return {}; + if (primary.empty()) return false; + TlsHostModule host = load_tls_host_image(primary, true); + if (host.index != TLS_OUT_OF_INDEXES && !host.hooked) { + FreeLibrary(host.module); + return false; } + g_tls_hosts[0] = host; + return host.index != TLS_OUT_OF_INDEXES; +} +// Copies gta6rt_tls_host.dll (or writes `image`, a changed copy of it) to "leonida_tls_host__.dll" in the +// clone directory and loads it, so the OS gives the copy an index of its own. On failure the file is gone again and +// the result has no index. The caller records the clone (g_tls_clones) if it is to be freed at exit. Same locking rule +// as ensure_primary_tls_host. +TlsHostModule load_tls_host_clone(const std::wstring& tag, std::filesystem::path& clone_path, + const std::vector* image = nullptr) { + const std::filesystem::path primary = tls_host_base_path(); + if (primary.empty()) return {}; // Clone gta6rt_tls_host.dll to a distinct path using CopyFileW (Wine 9 lacks CopyFile2 used by std::filesystem). const std::filesystem::path dir = tls_host_clone_dir(); static bool swept = false; if (!swept) { swept = true; sweep_stale_tls_clones(dir); - std::atexit(&cleanup_tls_clones_at_exit); } - const std::wstring name = - L"leonida_tls_host_" + std::to_wstring(GetCurrentProcessId()) + L"_" + std::to_wstring(slot) + L".dll"; - const std::filesystem::path clone_path = dir / name; + const std::wstring name = L"leonida_tls_host_" + std::to_wstring(GetCurrentProcessId()) + L"_" + tag + L".dll"; + clone_path = dir / name; // The staging name must not match the sweep pattern, which only covers final clone names ending in .dll. const std::filesystem::path staging = clone_path.wstring() + L".new"; - if (!CopyFileW(primary.c_str(), staging.c_str(), FALSE)) return {}; + if (image) { + HANDLE out = + CreateFileW(staging.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + if (out == INVALID_HANDLE_VALUE) return {}; + DWORD written = 0; + const bool ok = WriteFile(out, image->data(), static_cast(image->size()), &written, nullptr) && + written == image->size(); + CloseHandle(out); + if (!ok) { + DeleteFileW(staging.c_str()); + return {}; + } + } else if (!CopyFileW(primary.c_str(), staging.c_str(), FALSE)) { + return {}; + } // Open the guard before the clone exists under its final name and hold it across LoadLibraryExW: the rename // below needs DELETE access, which the handle's FILE_SHARE_DELETE grants, and no purge can remove the clone @@ -320,18 +388,34 @@ TlsHostModule ensure_tls_host(size_t slot) { TlsHostModule loaded = load_tls_host_image(clone_path, false); CloseHandle(guard); - if (loaded.index == TLS_OUT_OF_INDEXES) { + if (loaded.index == TLS_OUT_OF_INDEXES) DeleteFileW(clone_path.c_str()); + return loaded; +} + +// Must be called with g_tls_alloc_mutex held and WITHOUT g_tls_lock held (LoadLibraryExW takes the Windows loader lock). +TlsHostModule ensure_tls_host(size_t slot) { + if (slot >= kMaxMappedTlsModules) return {}; + if (g_tls_hosts[slot].index != TLS_OUT_OF_INDEXES) return g_tls_hosts[slot]; + // Slot 0 is the primary helper; it is loaded first in any case so thread attach/detach events are hooked. + if (!ensure_primary_tls_host()) return {}; + if (slot == 0) return g_tls_hosts[0]; + + std::filesystem::path clone_path; + TlsHostModule loaded = load_tls_host_clone(std::to_wstring(slot), clone_path); + if (loaded.index == TLS_OUT_OF_INDEXES) return {}; + // Index 0 is the runtime EXE's, and after the move the home clone's index holds that EXE's TLS. + bool taken = loaded.index == 0 || loaded.index == g_index0.home.index; + for (size_t i = 0; i < kMaxMappedTlsModules; ++i) taken |= i != slot && g_tls_hosts[i].index == loaded.index; + if (taken) { + FreeLibrary(loaded.module); DeleteFileW(clone_path.c_str()); return {}; } - for (size_t i = 0; i < kMaxMappedTlsModules; ++i) { - if (i != slot && g_tls_hosts[i].index == loaded.index) { - FreeLibrary(loaded.module); - DeleteFileW(clone_path.c_str()); - return {}; - } + if (!g_tls_clones) { + g_tls_clones = new std::vector; + std::atexit(&cleanup_tls_clones_at_exit); } - g_tls_clones.push_back({loaded.module, clone_path}); + g_tls_clones->push_back({loaded.module, clone_path}); g_tls_hosts[slot] = loaded; return g_tls_hosts[slot]; } @@ -347,7 +431,7 @@ struct ThreadTlsSlot { }; // Per-thread installation state for each reserved TLS slot. -thread_local std::array g_thread_tls_slots{}; +thread_local std::array g_thread_tls_slots{}; // Orders the TLS owners' publication, their `initialised` flags and their retirement against the thread events. Shared // in on_host_thread_event, exclusive only for those short writes (no allocation and no call that takes the Windows @@ -366,10 +450,185 @@ struct ExclusiveTlsLock { ExclusiveTlsLock& operator=(const ExclusiveTlsLock&) = delete; }; +// gta6rt_tls_host.dll's exports that the home clone's TLS directory is pointed at (tls_host.cpp): a zero array in its +// .rdata and that array's size. +constexpr char kHomeTemplateExport[] = "gta6rt_tls_home_template"; +constexpr char kHomeTemplateSizeExport[] = "gta6rt_tls_home_template_size"; + +// File offset of `len` bytes at `rva` in an image file held in memory, or SIZE_MAX when they are not all inside one +// section's raw data. +size_t file_offset(const std::vector& file, const IMAGE_NT_HEADERS64* nt, uint64_t rva, uint64_t len) { + const auto* sec = IMAGE_FIRST_SECTION(nt); + for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) { + if (reinterpret_cast(sec + 1) > file.data() + file.size()) break; + if (rva < sec->VirtualAddress || rva + len > static_cast(sec->VirtualAddress) + sec->SizeOfRawData) + continue; + const uint64_t off = sec->PointerToRawData + (rva - sec->VirtualAddress); + return off + len <= file.size() ? static_cast(off) : SIZE_MAX; + } + return SIZE_MAX; +} + +// The RVA of a named export in an image file held in memory, 0 when it has none. +uint32_t file_export(const std::vector& file, const IMAGE_NT_HEADERS64* nt, const char* wanted) { + const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_EXPORT); + const size_t ed_off = file_offset(file, nt, dir.VirtualAddress, sizeof(IMAGE_EXPORT_DIRECTORY)); + if (!dir.Size || ed_off == SIZE_MAX) return 0; + const auto* ed = reinterpret_cast(file.data() + ed_off); + const size_t names = file_offset(file, nt, ed->AddressOfNames, uint64_t{4} * ed->NumberOfNames); + const size_t ords = file_offset(file, nt, ed->AddressOfNameOrdinals, uint64_t{2} * ed->NumberOfNames); + const size_t funcs = file_offset(file, nt, ed->AddressOfFunctions, uint64_t{4} * ed->NumberOfFunctions); + if (names == SIZE_MAX || ords == SIZE_MAX || funcs == SIZE_MAX) return 0; + const size_t wanted_len = std::strlen(wanted) + 1; + for (uint32_t i = 0; i < ed->NumberOfNames; ++i) { + uint32_t name_rva, func_rva; + uint16_t ord; + std::memcpy(&name_rva, file.data() + names + 4 * i, 4); + std::memcpy(&ord, file.data() + ords + 2 * i, 2); + const size_t name = file_offset(file, nt, name_rva, wanted_len); + if (name == SIZE_MAX || std::memcmp(file.data() + name, wanted, wanted_len) != 0) continue; + if (ord >= ed->NumberOfFunctions) return 0; + std::memcpy(&func_rva, file.data() + funcs + 4 * ord, 4); + return func_rva; + } + return 0; +} + +// Turns gta6rt_tls_host.dll's bytes into the home clone: its TLS directory now covers gta6rt_tls_home_template, which +// starts with a copy of the owner's template (taken from the mapped owner, so its pointers are already relocated; the +// array itself has no relocations), and takes the owner's alignment. The OS then gives every thread, at the home +// index, a block that is a fresh copy of the owner's TLS. The zero fill goes into the covered range too: +// LdrpAllocateTls allocates and copies End - Start only (Windows 11 26300) and ignores SizeOfZeroFill. The directory's +// Start and End have base relocations, so they follow the clone wherever it loads. Empty on success, else why not. +std::string make_home_clone_image(std::vector& file, const IMAGE_TLS_DIRECTORY64& owner) { + if (file.size() < sizeof(IMAGE_DOS_HEADER)) return "gta6rt_tls_host.dll is truncated"; + const auto* dos = reinterpret_cast(file.data()); + if (dos->e_magic != IMAGE_DOS_SIGNATURE || dos->e_lfanew < 0 || + static_cast(dos->e_lfanew) + sizeof(IMAGE_NT_HEADERS64) > file.size()) + return "gta6rt_tls_host.dll has no PE header"; + auto* nt = reinterpret_cast(file.data() + dos->e_lfanew); + if (nt->Signature != IMAGE_NT_SIGNATURE || nt->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC) + return "gta6rt_tls_host.dll is not a 64-bit image"; + const uint32_t array_rva = file_export(file, nt, kHomeTemplateExport); + const uint32_t size_rva = file_export(file, nt, kHomeTemplateSizeExport); + const size_t size_off = file_offset(file, nt, size_rva, sizeof(uint32_t)); + if (!array_rva || !size_rva || size_off == SIZE_MAX) + return "gta6rt_tls_host.dll has no gta6rt_tls_home_template"; + uint32_t capacity; + std::memcpy(&capacity, file.data() + size_off, sizeof(capacity)); + const uint64_t raw = owner.EndAddressOfRawData - owner.StartAddressOfRawData; + const uint64_t total = raw + owner.SizeOfZeroFill; + if (owner.EndAddressOfRawData < owner.StartAddressOfRawData || total > capacity) + return "the owner's TLS (" + std::to_string(total) + " bytes) does not fit gta6rt_tls_home_template (" + + std::to_string(capacity) + " bytes)"; + const size_t array_off = file_offset(file, nt, array_rva, capacity); + const auto tls_dir = directory(nt, IMAGE_DIRECTORY_ENTRY_TLS); + const size_t tls_off = file_offset(file, nt, tls_dir.VirtualAddress, sizeof(IMAGE_TLS_DIRECTORY64)); + if (array_off == SIZE_MAX || !tls_dir.Size || tls_off == SIZE_MAX) + return "gta6rt_tls_host.dll's TLS directory or home template lies outside its file"; + std::memcpy(file.data() + array_off, reinterpret_cast(owner.StartAddressOfRawData), raw); + std::memset(file.data() + array_off + raw, 0, capacity - raw); + auto* tls = reinterpret_cast(file.data() + tls_off); + tls->StartAddressOfRawData = nt->OptionalHeader.ImageBase + array_rva; + tls->EndAddressOfRawData = tls->StartAddressOfRawData + total; + tls->SizeOfZeroFill = 0; + tls->Characteristics = + (tls->Characteristics & ~IMAGE_SCN_ALIGN_MASK) | (owner.Characteristics & IMAGE_SCN_ALIGN_MASK); + return {}; +} + +std::string module_file_name(HMODULE module) { + wchar_t path[MAX_PATH]; + const DWORD n = GetModuleFileNameW(module, path, MAX_PATH); + if (!n || n >= MAX_PATH) return "?"; + const wchar_t* name = path; + for (const wchar_t* p = path; *p; ++p) + if (*p == L'\\' || *p == L'/') name = p + 1; + const int bytes = WideCharToMultiByte(CP_UTF8, 0, name, -1, nullptr, 0, nullptr, nullptr); + if (bytes <= 1) return "?"; + std::string out(static_cast(bytes - 1), '\0'); + WideCharToMultiByte(CP_UTF8, 0, name, -1, out.data(), bytes, nullptr, nullptr); + return out; +} + +// The move on the calling thread, kept apart so that no frame of reserve_index0 holds a slot address across it. After +// it the owner's live block is at `home` and slot 0 holds the home clone's fresh copy, which nothing reads. +__declspec(noinline) void move_index0_on_this_thread(DWORD* owner_index, DWORD home) { + void** slots = module_tls_slots(); + std::swap(slots[0], slots[home]); + *owner_index = home; +} + +// See reserve_tls_index0. Empty on success, else why not; nothing has changed then. g_tls_alloc_mutex held. It reads +// no thread_local data and runs no code that does, before or after the move. +std::string reserve_index0() { + // Windows gives index 0 to the process executable when it has TLS; a DLL can only hold it in a process whose EXE + // has none, and a DLL that is still loading or was loaded without its references resolved shows 0 too. + const HMODULE exe = GetModuleHandleW(nullptr); + auto* base = reinterpret_cast(exe); + auto* nt = at(base, reinterpret_cast(base)->e_lfanew); + const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_TLS); + if (!dir.Size || !dir.VirtualAddress) return "the process executable has no TLS, so index 0 is not its"; + const IMAGE_TLS_DIRECTORY64 owner = *at(base, dir.VirtualAddress); + auto* owner_index = reinterpret_cast(owner.AddressOfIndex); + if (!owner_index) return "the process executable's TLS directory has no index"; + if (*owner_index != 0) return "the process executable's _tls_index is " + std::to_string(*owner_index) + ", not 0"; + if (!module_tls_slots()) return "this thread has no TLS array"; + if (!ensure_primary_tls_host()) + return "gta6rt_tls_host.dll is missing, has no module TLS index or lacks gta6rt_tls_host_set_thread_event"; + + std::vector image; + try { + image = read_file(tls_host_base_path()); + } catch (const std::exception& e) { + return e.what(); + } + if (std::string why = make_home_clone_image(image, owner); !why.empty()) return why; + std::filesystem::path path; + const TlsHostModule home = load_tls_host_clone(L"home", path, &image); + if (home.index == TLS_OUT_OF_INDEXES) return "the home clone of gta6rt_tls_host.dll cannot be loaded"; + auto drop = [&](std::string why) { + FreeLibrary(home.module); // safe until the move below: nothing lives at its index yet + DeleteFileW(path.c_str()); + return why; + }; + bool taken = home.index == 0 || home.index >= kMaxModuleTlsSlots; + for (const auto& host : g_tls_hosts) taken |= host.index == home.index; + if (taken) return drop("the home clone got an unusable module TLS index"); + // The OS must have taken the changed directory: the mapped clone's template is the owner's, at full size. + auto* home_base = reinterpret_cast(home.module); + auto* home_nt = at(home_base, reinterpret_cast(home_base)->e_lfanew); + const auto* home_tls = + at(home_base, directory(home_nt, IMAGE_DIRECTORY_ENTRY_TLS).VirtualAddress); + const uint64_t raw = owner.EndAddressOfRawData - owner.StartAddressOfRawData; + if (home_tls->EndAddressOfRawData - home_tls->StartAddressOfRawData != raw + owner.SizeOfZeroFill || + std::memcmp(reinterpret_cast(home_tls->StartAddressOfRawData), + reinterpret_cast(owner.StartAddressOfRawData), raw) != 0) + return drop("the home clone's mapped TLS template is not the owner's"); + + // Everything that can throw comes first: past the move this records the result and nothing more. + const std::string name = module_file_name(exe); + // _tls_index sits in .data; made writable first in case a linker merged it into a read-only section. + DWORD old_protect = 0; + if (!VirtualProtect(owner_index, sizeof(DWORD), PAGE_READWRITE, &old_protect)) + return drop("the owner's _tls_index cannot be written"); + move_index0_on_this_thread(owner_index, home.index); + VirtualProtect(owner_index, sizeof(DWORD), old_protect, &old_protect); + + // Kept loaded for the process lifetime: FreeLibrary would make the OS free every thread's block at its index, the + // owner's from now on. Not in g_tls_clones for that reason. Its file cannot be deleted while it is mapped + // (DeleteFileW and a POSIX-semantics delete both fail with ERROR_ACCESS_DENIED on Windows 11), so it stays until + // a later run's sweep. + g_index0.home = home; + std::snprintf(g_index0.owner, sizeof(g_index0.owner), "%s", name.c_str()); + g_index0.moved = true; + return {}; +} + // Puts the helper DLL's own block back in this thread's slot and frees the copy that replaced it. Uses only this // thread's record, so it also works after the module that installed the copy is gone. void release_thread_slot(size_t slot) { - if (slot >= kMaxMappedTlsModules) return; + if (slot >= kTlsSlotCount) return; ThreadTlsSlot& entry = g_thread_tls_slots[slot]; if (!entry.module && !entry.block) return; if (entry.ga_view) { @@ -438,7 +697,7 @@ void** make_ga_view(const Module& m, void* block) { } void install_thread_block(Module& m) { - if (m.tls_slot >= kMaxMappedTlsModules) return; + if (m.tls_slot >= kTlsSlotCount) return; const size_t slot = m.tls_slot; ThreadTlsSlot& entry = g_thread_tls_slots[slot]; if (entry.module == &m && entry.generation == m.tls_generation) return; @@ -530,7 +789,7 @@ bool ga_tls_patch_enabled() { } void uninstall_thread_block(Module& m) { - if (m.tls_slot >= kMaxMappedTlsModules) return; + if (m.tls_slot >= kTlsSlotCount) return; const size_t slot = m.tls_slot; ThreadTlsSlot& entry = g_thread_tls_slots[slot]; if (entry.module != &m || entry.generation != m.tls_generation) return; @@ -697,7 +956,7 @@ constexpr size_t kMaxEndedThreads = 1024; // load(): every other running thread gets its own copy of m's template. Not fatal where it cannot be done. void install_on_existing_threads(Module& m) { const uint64_t total = static_cast(m.tls_raw_size) + m.tls_zero_fill; - if (!total || m.tls_index >= kMaxModuleTlsSlots || m.tls_slot >= kMaxMappedTlsModules) return; + if (!total || m.tls_index >= kMaxModuleTlsSlots || m.tls_slot >= kTlsSlotCount) return; // Stays ahead of the TLS lock: the first call resolves the function with GetModuleHandle and GetProcAddress, which // take the Windows loader lock, and a thread inside its attach event holds that lock while it waits for ours. if (!query_thread_fn()) return; @@ -882,7 +1141,11 @@ void release_existing_blocks_of_this_thread() { // Runs in gta6rt_tls_host.dll's DllMain for each thread the process starts or ends once the helper is loaded, under // the Windows loader lock, on that thread. A new thread gets its own copy of each active TLS owner's template; an // ending one gives each helper's block back before the Windows loader frees it. TLS callbacks get the thread events -// only after the module's DLL_PROCESS_ATTACH (initialise()), as the Windows loader orders them. +// only after the module's DLL_PROCESS_ATTACH (initialise()), as the Windows loader orders them. Windows allocates +// every module's block before the first DllMain of a new thread, and runs an EXE's TLS callbacks after every DllMain, +// for attach and for detach (measured on Windows 11 26300). So attach installs all copies first and then runs the +// callbacks, the DLL slots in order and the executable's last; detach runs the DLL slots in reverse and then the +// executable's slot, each releasing its copy after its callbacks. void __cdecl on_host_thread_event(DWORD reason) { SharedTlsLock lock; // The try/catch is per slot: a throw from one module's install or callbacks must not take the thread events @@ -893,14 +1156,25 @@ void __cdecl on_host_thread_event(DWORD reason) { } catch (const std::exception& e) { std::fprintf(stderr, "[rt] loader: thread attach: %s\n", e.what()); } - for (size_t slot = 0; slot < kMaxMappedTlsModules; ++slot) { + std::array installed{}; + for (size_t slot = 0; slot < kTlsSlotCount; ++slot) { Module* m = g_tls_slot_owners[slot].load(); if (!m) continue; try { install_thread_block(*m); - if (m->initialised) run_callbacks(*m, DLL_THREAD_ATTACH); + installed[slot] = m; + } catch (const std::exception& e) { + // The thread runs on without this module's TLS (and its callbacks); later slots still get theirs. + std::fprintf(stderr, "[rt] loader: thread attach, slot %zu (%s): %s\n", slot, m->name.c_str(), + e.what()); + } + } + for (size_t slot = 0; slot < kTlsSlotCount; ++slot) { + Module* m = installed[slot]; + if (!m || !m->initialised) continue; + try { + run_callbacks(*m, DLL_THREAD_ATTACH); } catch (const std::exception& e) { - // The thread runs on without this module's TLS; later slots still get theirs. std::fprintf(stderr, "[rt] loader: thread attach, slot %zu (%s): %s\n", slot, m->name.c_str(), e.what()); } @@ -913,7 +1187,8 @@ void __cdecl on_host_thread_event(DWORD reason) { } catch (const std::exception& e) { std::fprintf(stderr, "[rt] loader: thread detach: %s\n", e.what()); } - for (size_t i = kMaxMappedTlsModules; i-- > 0;) { + for (size_t step = 0; step < kTlsSlotCount; ++step) { + const size_t i = step < kMaxMappedTlsModules ? kMaxMappedTlsModules - 1 - step : kMainImageSlot; Module* m = g_tls_slot_owners[i].load(); if (m && g_thread_tls_slots[i].module == m && g_thread_tls_slots[i].generation == m->tls_generation) { @@ -1017,6 +1292,26 @@ void redirect_pc_to_file_header_at(const void* resolved) { // Declared in pe_loader.h; the body needs the internal clone registry above. void cleanup_tls_clones() { cleanup_tls_clones_internal(); } +bool reserve_tls_index0(std::string* why) { + std::lock_guard alloc_lock(g_tls_alloc_mutex); + static bool attempted = false; // once: a later attempt could meet threads that already run this EXE's code + if (!attempted) { + attempted = true; + // A throw (std::filesystem::temp_directory_path when GetTempPathW fails, an allocation) is a failed + // reservation like any other: gta6rt calls this before main, where an exception would end it with no message. + try { + const std::string reason = reserve_index0(); + std::snprintf(g_index0.why, sizeof(g_index0.why), "%s", reason.c_str()); + } catch (const std::exception& e) { + std::snprintf(g_index0.why, sizeof(g_index0.why), "%s", e.what()); + } catch (...) { + std::snprintf(g_index0.why, sizeof(g_index0.why), "an unknown error while reserving it"); + } + } + if (why) *why = g_index0.moved ? std::string() : std::string(g_index0.why); + return g_index0.moved; +} + namespace { bool lookup_in_loader(void* ctx, uint64_t address, std::string& module, uint32_t& rva) { return static_cast(ctx)->find_address(address, module, rva); @@ -1099,7 +1394,7 @@ Loader::~Loader() { shims::remove_module_lookup(this); for (auto* m : order_) { // TLS state must go away before the image and its TLS block are unmapped. - if (m->tls_index != kNoTlsIndex && m->tls_slot < kMaxMappedTlsModules) { + if (m->tls_index != kNoTlsIndex && m->tls_slot < kTlsSlotCount) { // Retired first, under the lock: no thread event installs it or runs its callbacks after this, and a // thread that still holds a copy frees it when it ends (on_host_thread_event). { @@ -1514,7 +1809,7 @@ Module& Loader::map_image(const std::filesystem::path& path, const std::string& // Only the OS loader can allocate that module index, so the loader reuses the index the OS assigned to // gta6rt_tls_host.dll and maps a fresh clone of the helper for every additional simultaneous TLS module, each clone // getting its own index. All kMaxMappedTlsModules slots can be live at once; a further module is rejected rather than -// silently sharing (and corrupting) a slot. +// silently sharing (and corrupting) a slot. An executable takes index 0 instead (kMainImageSlot), as on Windows. void Loader::initialize_tls(Module& m) { auto* tls = tls_directory(m); if (!tls) return; @@ -1543,26 +1838,51 @@ void Loader::initialize_tls(Module& m) { if (!module_tls_slots()) throw std::runtime_error(m.name + ": this thread has no TLS array"); - size_t slot = kMaxMappedTlsModules; + auto* nt = at(m.base, reinterpret_cast(m.base)->e_lfanew); + const bool executable = (nt->FileHeader.Characteristics & IMAGE_FILE_DLL) == 0; + + size_t slot = kTlsSlotCount; DWORD index = TLS_OUT_OF_INDEXES; { std::lock_guard alloc_lock(g_tls_alloc_mutex); - for (size_t i = 0; i < kMaxMappedTlsModules; ++i) { - if (g_tls_slot_owners[i].load() == nullptr) { - slot = i; - break; + if (executable) { + if (g_index0.moved && g_tls_slot_owners[kMainImageSlot].load() == nullptr) { + slot = kMainImageSlot; + index = 0; + if (!g_index0.traced && startup_trace::enabled()) { + g_index0.traced = true; + startup_trace::event("tls_index0", "\"owner\":" + startup_trace::quote(g_index0.owner) + + ",\"moved_to\":" + std::to_string(g_index0.home.index)); + } + } else { + // Mapped on as a DLL is: its code that reads _tls_index works, but its /GA code would read and write + // the block in slot 0, which is the runtime's own TLS or the other executable's. gta6rt refuses to + // run such an image (main.cpp); a Loader user must not run its code either. + std::fprintf(stderr, + "[rt] loader: %s does not get module TLS index 0 (%s); its code built with /GA would use " + "another module's TLS\n", + m.name.c_str(), g_index0.moved ? "another mapped executable holds it" : g_index0.why); } } - if (slot >= kMaxMappedTlsModules) - throw std::runtime_error(m.name + ": all " + std::to_string(kMaxMappedTlsModules) + - " manually mapped static TLS slots are in use"); - - // Load/clone gta6rt_tls_host.dll OUTSIDE ExclusiveTlsLock so LoadLibraryExW cannot deadlock with - // on_host_thread_event (which runs under the Windows loader lock and takes SharedTlsLock). - index = ensure_tls_host(slot).index; - if (index == TLS_OUT_OF_INDEXES) - throw std::runtime_error(m.name + ": gta6rt_tls_host.dll is missing or has no module TLS index"); - if (index >= kMaxModuleTlsSlots) throw std::runtime_error(m.name + ": reserved TLS index is out of range"); + if (slot == kTlsSlotCount) { + for (size_t i = 0; i < kMaxMappedTlsModules; ++i) { + if (g_tls_slot_owners[i].load() == nullptr) { + slot = i; + break; + } + } + if (slot >= kMaxMappedTlsModules) + throw std::runtime_error(m.name + ": all " + std::to_string(kMaxMappedTlsModules) + + " manually mapped static TLS slots are in use"); + + // Load/clone gta6rt_tls_host.dll OUTSIDE ExclusiveTlsLock so LoadLibraryExW cannot deadlock with + // on_host_thread_event (which runs under the Windows loader lock and takes SharedTlsLock). + index = ensure_tls_host(slot).index; + if (index == TLS_OUT_OF_INDEXES) + throw std::runtime_error(m.name + ": gta6rt_tls_host.dll is missing or has no module TLS index"); + if (index >= kMaxModuleTlsSlots) + throw std::runtime_error(m.name + ": reserved TLS index is out of range"); + } // The fields are complete before a thread event can see the owner. ExclusiveTlsLock lock; @@ -1864,6 +2184,24 @@ void Loader::bind_imports(Module& m) { void Loader::protect_sections(Module& m) { auto* nt = at(m.base, reinterpret_cast(m.base)->e_lfanew); DWORD old; + // On a CPU without CLZERO, the image's CLZERO loops run from stubs instead of taking a #UD per cache line + // (clzero_patch.h). The sections are still writable here, and none of the image's code has run. + static const bool clzero_missing = !rt::cpu_emulation::detect_host().clzero; + if (clzero_missing && rt::clzero_patch::enabled()) { + std::vector> code; + const IMAGE_SECTION_HEADER* cs = IMAGE_FIRST_SECTION(nt); + for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++cs) { + if (!(cs->Characteristics & IMAGE_SCN_MEM_EXECUTE) || cs->VirtualAddress >= m.size) continue; + const uint64_t size = std::min(std::min(cs->Misc.VirtualSize, cs->SizeOfRawData), + m.size - cs->VirtualAddress); + if (size) code.push_back({m.base + cs->VirtualAddress, static_cast(size)}); + } + const auto patched = rt::clzero_patch::patch(code, uint64_t(m.base), uint64_t(m.base) + m.size); + if (patched.sites) + std::fprintf(stderr, + "[rt] loader: %s: %zu CLZERO loops run from stubs at %p (%zu bytes), not as a #UD per line\n", + m.name.c_str(), patched.sites, static_cast(patched.stubs), patched.stub_bytes); + } VirtualProtect(m.base, nt->OptionalHeader.SizeOfHeaders, PAGE_READONLY, &old); auto* sec = IMAGE_FIRST_SECTION(nt); for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) { diff --git a/runtime/src/pe_loader.h b/runtime/src/pe_loader.h index fda9244401..f75426e416 100644 --- a/runtime/src/pe_loader.h +++ b/runtime/src/pe_loader.h @@ -54,11 +54,15 @@ struct Module { // the image's _tls_index. tls_index names TEB->ThreadLocalStoragePointer[tls_index], the array // __declspec(thread) reads; it is not a TlsAlloc slot. The loader reserves distinct indices by loading // gta6rt_tls_host.dll (and cloning it on demand for additional simultaneous TLS modules, up to 16 at a time). + // An executable gets index 0, as Windows gives the process EXE, because code built with /GA reads slot 0 without + // _tls_index. That needs reserve_tls_index0() at process start; without it, and for a second executable mapped + // while one holds index 0, the executable gets a helper index and a note on stderr, and its /GA code would use + // another module's TLS, so its code must not run (gta6rt refuses). // Every thread started after load() gets its own copy through the helper's DLL_THREAD_ATTACH, and gives it back // at DLL_THREAD_DETACH. A thread that was already running gets its copy from load() itself, as it would from // Windows for a DLL Windows loads: a block, no DLL_THREAD_ATTACH, and DLL_THREAD_DETACH when it ends. uint32_t tls_index = kNoTlsIndex; - uint32_t tls_slot = kNoTlsIndex; // index into the loader's reserved TLS-host slot pool + uint32_t tls_slot = kNoTlsIndex; // index into the loader's reserved TLS-host slot pool ; 16 is index 0, an executable's uint64_t tls_generation = 0; // unique token per TLS initialisation, distinguishing reused slots/addresses void* tls_block = nullptr; // calling thread's copy of the image's template void* tls_saved_block = nullptr; // helper DLL block replaced in that thread, restored by ~Loader @@ -182,6 +186,14 @@ class Loader { // skips the atexit table. Call it when no mapped code can run again: it unmaps the helper images. void cleanup_tls_clones(); +// Moves the runtime's own EXE off module TLS index 0, which Windows gave it, so that a mapped executable can have it +// (Module::tls_index): its TLS moves to the index of one more helper clone, whose template is a copy of the EXE's. +// Call it once at process start, before any other thread has run this EXE's code (gta6rt does it from a CRT +// initializer): MSVC code keeps the address of its TLS slot across calls, so a thread that is already running cannot +// be moved, and its TLS would stay at index 0. Returns false, with the reason in *why, when it cannot; later calls +// return the first result. +bool reserve_tls_index0(std::string* why = nullptr); + std::string lower(std::string s); } // namespace rt diff --git a/runtime/test/pipeline_cache_file.h b/runtime/src/pipeline_cache_file.h similarity index 93% rename from runtime/test/pipeline_cache_file.h rename to runtime/src/pipeline_cache_file.h index 400138ef7d..96e16f9ccc 100644 --- a/runtime/test/pipeline_cache_file.h +++ b/runtime/src/pipeline_cache_file.h @@ -1,4 +1,7 @@ // Publish a checkpoint only after every byte has reached a closed, same-directory staging file. +// +// Used by vk_pipeline_check for its offline corpus checkpoints. The runtime fills a mapped session staging file +// directly (d3d12_pipeline_checkpoint.h). #pragma once #include diff --git a/runtime/src/pipeline_cache_store.h b/runtime/src/pipeline_cache_store.h new file mode 100644 index 0000000000..6d519d99b1 --- /dev/null +++ b/runtime/src/pipeline_cache_store.h @@ -0,0 +1,69 @@ +// Persisting the runtime's VkPipelineCache across launches (D3D-704). +// +// Two files sit beside gta6rt.exe, and they are not interchangeable: +// +// pipeline_cache.bin the offline corpus seed the `pipelines` build stage writes (#367). Read only. +// pipeline_cache.session.bin what the runtime compiled last time. Written on device teardown. +// +// Keeping them apart means a run can never replace the multi-GB corpus cache with the handful of pipelines it +// happened to compile. On the next launch both are loaded and merged, so the offline entries and the previous +// session's entries are available together. +// +// This header is pure stdlib on purpose (it does not include vulkan.h): pipeline_cache_store_test builds on hosts +// where CMake has no Vulkan headers. The byte layout below is VkPipelineCacheHeaderVersionOne, whose 32 bytes are +// part of Vulkan's ABI, not something a driver chooses. +#pragma once + +#include +#include +#include +#include + +#include "cached_pso.h" + +namespace leonida::pipeline_cache_store { + +// A session cache normally holds what one boot compiled (a few MB to a few hundred MB). The cap is what keeps a +// cache seeded from the multi-GB corpus file -- whose data comes back as the whole union -- from being rewritten +// at every exit. Past it the previous session file is left alone; raise the limit with +// LEONIDA_PIPELINE_CACHE_BYTES when a session really compiles that much. +inline constexpr std::size_t default_save_limit = std::size_t{256} << 20; // 256 MiB + +struct SaveLimit { + std::size_t bytes = default_save_limit; + bool valid = true; // false when the text was not a byte count; bytes then stays at the default +}; + +// LEONIDA_PIPELINE_CACHE_BYTES: a decimal byte count, 0 turning the session file off entirely. Empty or absent +// means the default; stray text, a sign or an overflow is reported by the caller and the default is used. +inline SaveLimit parse_save_limit(const char* text) { + if (!text || !*text) return {}; + std::size_t value = 0; + for (const char* p = text; *p; ++p) { + if (*p < '0' || *p > '9') return {default_save_limit, false}; + const std::size_t digit = static_cast(*p - '0'); + if (value > (std::numeric_limits::max() - digit) / 10) return {default_save_limit, false}; + value = value * 10 + digit; + } + return {value, true}; +} + +inline constexpr std::size_t header_bytes = 32; +inline constexpr std::uint32_t header_version_one = 1; + +inline std::uint32_t read_u32(const std::uint8_t* p) { + return std::uint32_t(p[0]) | (std::uint32_t(p[1]) << 8) | (std::uint32_t(p[2]) << 16) | + (std::uint32_t(p[3]) << 24); +} + +// True when the blob's header names this physical device and pipeline-cache UUID, which is what a driver requires +// before it will read the opaque payload. The header is little-endian, like the host. +inline bool header_matches(const void* data, std::size_t size, const cached_pso::Identity& identity) { + if (!data || size < header_bytes) return false; + const auto* bytes = static_cast(data); + return read_u32(bytes) == header_bytes && read_u32(bytes + 4) == header_version_one && + read_u32(bytes + 8) == identity.vendor && read_u32(bytes + 12) == identity.device && + std::memcmp(bytes + 16, identity.cache_uuid, sizeof(identity.cache_uuid)) == 0; +} + +} // namespace leonida::pipeline_cache_store diff --git a/runtime/src/pipeline_profile.h b/runtime/src/pipeline_profile.h new file mode 100644 index 0000000000..f81c00c7de --- /dev/null +++ b/runtime/src/pipeline_profile.h @@ -0,0 +1,70 @@ +// Optional driver-call timing. Match begin/end by id even when startup warmup and replay overlap. +#pragma once + +#include +#include +#include +#include +#include +#ifdef _WIN32 +#include +#endif + +namespace leonida::pipeline_profile { + +inline bool enabled() { + static const bool enable = [] { + const char* value = std::getenv("LEONIDA_PSO_PROFILE"); + return value && std::strcmp(value, "1") == 0; + }(); + return enable; +} + +inline long long unix_ms() { + return std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()).count(); +} + +// CPU charged to the calling thread distinguishes synchronous compilation from time waiting in the driver. +inline long long thread_cpu_us() { +#ifdef _WIN32 + FILETIME creation{}, exit{}, kernel{}, user{}; + if (GetThreadTimes(GetCurrentThread(), &creation, &exit, &kernel, &user)) { + const auto ticks = [](FILETIME t) { + return (static_cast(t.dwHighDateTime) << 32) | t.dwLowDateTime; + }; + return static_cast((ticks(kernel) + ticks(user)) / 10); + } +#endif + return -1; +} + +class DriverCall { +public: + DriverCall(const char* stage, const char* origin, const char* program, const char* fragment = "-", + unsigned unbound = 0) { + if (!enabled()) return; + static std::atomic sequence{0}; + id_ = sequence.fetch_add(1, std::memory_order_relaxed) + 1; + start_ = std::chrono::steady_clock::now(); + cpu_start_ = thread_cpu_us(); + std::fprintf(stderr, "[rt] pso-driver begin id=%llu unix_ms=%lld stage=%s origin=%s program=%s ps=%s mask=%u\n", + id_, unix_ms(), stage, origin, program, fragment, unbound); + } + + void finish(int result) const { + if (!id_) return; + const auto us = std::chrono::duration_cast( + std::chrono::steady_clock::now() - start_).count(); + const long long cpu = thread_cpu_us(); + std::fprintf(stderr, "[rt] pso-driver end id=%llu unix_ms=%lld us=%lld cpu_us=%lld result=%d\n", + id_, unix_ms(), static_cast(us), cpu >= 0 && cpu_start_ >= 0 ? cpu - cpu_start_ : -1, + result); + } +private: + unsigned long long id_ = 0; + long long cpu_start_ = -1; + std::chrono::steady_clock::time_point start_{}; +}; + +} // namespace leonida::pipeline_profile diff --git a/runtime/src/rect_list_geometry.h b/runtime/src/rect_list_geometry.h new file mode 100644 index 0000000000..c6e47b0c08 --- /dev/null +++ b/runtime/src/rect_list_geometry.h @@ -0,0 +1,258 @@ +#pragma once + +// Console rectangle lists on Vulkan, which has no such primitive. +// +// A rectangle is three corners (v1, v2, v3) of a screen-aligned rectangle and the hardware makes the fourth, for the +// position and for every interpolant, after the vertex stage. A list topology of rectangles (D3D_PRIMITIVE_TOPOLOGY +// 17) and a pipeline whose topology type is 19 are console-only. The fact comes from xvalkyrie (GPL-3.0, commit +// 53af7df77c10, notes in its backlog); no code is taken from it. The corner between the other two (the right angle) +// is not always v1: the title's own full-screen blit (VS_Blit_6e5520d1) gives (-1, 1) (-1, -1) (1, -1), the corner +// at v2, and xcl's notes say the same of a retail title's full-screen pass and list v1, v2 and v3 as possible +// (learned from its docs and tests, GPL-2.0-only, no code taken). Taking v1 there made the parallelogram +// v2 + v3 - v1 = (1, -3), of which only the lower-left half of the screen is on screen. +// +// The fourth vertex depends on what the vertex stage wrote, not on what it read, so the expansion has to sit after +// the vertex stage: a pre-pass over the vertex buffers is wrong for any shader that is not linear in its inputs (and +// the translated vertex shaders fetch by V# themselves, so there is no vertex buffer to expand). The pipeline gets a +// small geometry stage instead, built here from the vertex shader's own SPIR-V: it takes the triangle (v1, v2, v3) +// the list draws, finds the corner between the other two as the one opposite the longest side (from the positions' +// x and y; a degenerate triangle takes v1), makes the fourth corner v4 = the other two's sum minus that corner, and +// emits the rectangle as two triangles with the winding of (v1, v2, v3) that both start at v1, so a flat input +// (taken from a triangle's first vertex) is v1's over the whole rectangle: +// corner v1: (v1, v2, v4) (v1, v4, v3); corner v2: (v1, v2, v3) (v1, v3, v4); corner v3: (v1, v2, v3) (v1, v4, v2). Every Location output of the vertex stage is a vec4 float in the translator's output (rdna2spirv.py), +// and so is the stage's Position; the generated stage reads and writes exactly those. +// +// Not covered, and refused with a reason: a vertex stage that writes ClipDistance, CullDistance, Layer or +// ViewportIndex, or a Location output that is not a vec4 float. +// +// Plain word editing, standard library only. + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace leonida { + +// D3D_PRIMITIVE_TOPOLOGY values and the PSO topology type of the console's rectangle and quad lists. +constexpr std::uint32_t topology_rect_list = 17; +constexpr std::uint32_t topology_quad_list = 19; +constexpr std::uint32_t topology_type_rect_list = 19; + +// The geometry stage for `vertex_words`' outputs; empty, with `why` set, when the vertex stage cannot be expanded. +inline std::vector rect_list_geometry(const std::vector& vertex_words, std::string& why) { + enum : std::uint32_t { + op_entry_point = 15, op_type_void = 19, op_type_int = 21, op_type_float = 22, + op_type_vector = 23, op_type_array = 28, op_type_pointer = 32, op_type_function = 33, op_constant = 43, + op_type_bool = 20, op_composite_construct = 80, op_composite_extract = 81, op_fmul = 133, + op_logical_and = 167, op_logical_not = 168, op_select = 169, op_ford_greater_than_equal = 190, + op_function = 54, op_function_end = 56, op_variable = 59, op_load = 61, op_store = 62, op_access_chain = 65, + op_decorate = 71, op_fadd = 129, op_fsub = 131, op_emit_vertex = 218, op_end_primitive = 219, op_label = 248, op_return = 253, + op_capability = 17, op_memory_model = 14, op_execution_mode = 16, + deco_builtin = 11, deco_location = 30, builtin_position = 0, builtin_point_size = 1, + storage_input = 1, storage_output = 3 + }; + why.clear(); + if (vertex_words.size() < 6 || vertex_words[0] != 0x07230203u) { + why = "the vertex shader is not a SPIR-V module"; + return {}; + } + // What the vertex stage declares: types, Output variables, and the decorations that name them. + struct Type { std::uint32_t op = 0, component = 0, count = 0, width = 0; }; + std::map types; + std::map variable_type; // Output variable -> its pointer type + std::map location, builtin; // variable id -> value + std::set outputs; + for (std::size_t i = 5; i < vertex_words.size();) { + const std::uint32_t op = vertex_words[i] & 0xffffu, n = vertex_words[i] >> 16; + if (!n || i + n > vertex_words.size()) { + why = "the vertex shader's SPIR-V is cut short"; + return {}; + } + const std::uint32_t* w = &vertex_words[i]; + if (op == op_type_float && n >= 3) types[w[1]] = {op, 0, 0, w[2]}; + else if (op == op_type_vector && n >= 4) types[w[1]] = {op, w[2], w[3], 0}; + else if (op == op_type_pointer && n >= 4) types[w[1]] = {op, w[3], w[2], 0}; + else if (op == op_variable && n >= 4 && w[3] == storage_output) outputs.insert(w[2]), variable_type[w[2]] = w[1]; + else if (op == op_decorate && n >= 4 && w[2] == deco_location) location[w[1]] = w[3]; + else if (op == op_decorate && n >= 4 && w[2] == deco_builtin) builtin[w[1]] = w[3]; + i += n; + } + std::uint32_t position = 0; + std::vector params; // Location values, ascending + for (std::uint32_t id : outputs) { + const auto b = builtin.find(id); + if (b != builtin.end()) { + if (b->second == builtin_position) position = id; + else if (b->second != builtin_point_size) { + why = "the vertex shader writes ClipDistance, CullDistance, Layer or ViewportIndex"; + return {}; + } + continue; + } + const auto l = location.find(id); + if (l == location.end()) continue; + const Type& ptr = types[variable_type[id]]; + const Type& vec = types[ptr.component]; + const Type& scalar = types[vec.component]; + if (vec.op != op_type_vector || vec.count != 4 || scalar.op != op_type_float || scalar.width != 32) { + why = "a vertex output is not a vec4 float"; + return {}; + } + params.push_back(l->second); + } + if (!position) { + why = "the vertex shader writes no Position"; + return {}; + } + std::sort(params.begin(), params.end()); + params.erase(std::unique(params.begin(), params.end()), params.end()); + + // The module: a fixed prelude, then per variable ids, then the body. Ids count up from 1. + std::uint32_t next = 1; + const auto id = [&] { return next++; }; + std::vector head, annotations, globals, body; + const auto emit = [](std::vector& to, std::uint32_t op, std::initializer_list args) { + to.push_back((std::uint32_t(args.size()) + 1) << 16 | op); + to.insert(to.end(), args.begin(), args.end()); + }; + const std::uint32_t t_void = id(), t_fn = id(), t_uint = id(), t_float = id(), t_v4 = id(), + c3 = id(), t_arr = id(), t_pin_arr = id(), t_pin_v4 = id(), + t_pout_v4 = id(), c0 = id(), c1 = id(), c2 = id(); + emit(globals, op_type_void, {t_void}); + emit(globals, op_type_function, {t_fn, t_void}); + emit(globals, op_type_int, {t_uint, 32, 0}); + emit(globals, op_type_float, {t_float, 32}); + emit(globals, op_type_vector, {t_v4, t_float, 4}); + emit(globals, op_constant, {t_uint, c3, 3}); + emit(globals, op_constant, {t_uint, c0, 0}); + emit(globals, op_constant, {t_uint, c1, 1}); + emit(globals, op_constant, {t_uint, c2, 2}); + emit(globals, op_type_array, {t_arr, t_v4, c3}); + emit(globals, op_type_pointer, {t_pin_arr, storage_input, t_arr}); + emit(globals, op_type_pointer, {t_pin_v4, storage_input, t_v4}); + emit(globals, op_type_pointer, {t_pout_v4, storage_output, t_v4}); + + struct Var { std::uint32_t in, out; bool is_position; }; + std::vector vars; + vars.push_back({id(), id(), true}); + for (std::size_t i = 0; i < params.size(); ++i) vars.push_back({id(), id(), false}); + std::vector io_vars; + emit(annotations, op_decorate, {vars[0].in, deco_builtin, builtin_position}); + emit(annotations, op_decorate, {vars[0].out, deco_builtin, builtin_position}); + for (std::size_t i = 0; i < params.size(); ++i) { + emit(annotations, op_decorate, {vars[i + 1].in, deco_location, params[i]}); + emit(annotations, op_decorate, {vars[i + 1].out, deco_location, params[i]}); + } + for (const Var& v : vars) { + emit(globals, op_variable, {t_pin_arr, v.in, storage_input}); + emit(globals, op_variable, {t_pout_v4, v.out, storage_output}); + io_vars.push_back(v.in); + io_vars.push_back(v.out); + } + + const std::uint32_t main_fn = id(), entry_label = id(); + emit(body, op_function, {t_void, main_fn, 0, t_fn}); + emit(body, op_label, {entry_label}); + // Per variable: the three corners. + struct Corners { std::uint32_t v[3]; }; + std::vector corners; + const std::uint32_t cs[3] = {c0, c1, c2}; + for (const Var& v : vars) { + Corners c{}; + for (int k = 0; k < 3; ++k) { + const std::uint32_t ptr = id(); + c.v[k] = id(); + emit(body, op_access_chain, {t_pin_v4, ptr, v.in, cs[k]}); + emit(body, op_load, {t_v4, c.v[k], ptr}); + } + corners.push_back(c); + } + // The corner between the other two, opposite the longest side: squared lengths from the positions' x and y. + const std::uint32_t t_bool = id(), t_bv4 = id(); + emit(globals, op_type_bool, {t_bool}); + emit(globals, op_type_vector, {t_bv4, t_bool, 4}); + const auto extract = [&](std::uint32_t vector, std::uint32_t component) { + const std::uint32_t r = id(); + emit(body, op_composite_extract, {t_float, r, vector, component}); + return r; + }; + const auto length2 = [&](std::uint32_t a, std::uint32_t b) { + const std::uint32_t d = id(), xx = id(), yy = id(), sum = id(); + emit(body, op_fsub, {t_v4, d, a, b}); + const std::uint32_t x = extract(d, 0), y = extract(d, 1); + emit(body, op_fmul, {t_float, xx, x, x}); + emit(body, op_fmul, {t_float, yy, y, y}); + emit(body, op_fadd, {t_float, sum, xx, yy}); + return sum; + }; + const auto at_least = [&](std::uint32_t a, std::uint32_t b) { + const std::uint32_t r = id(); + emit(body, op_ford_greater_than_equal, {t_bool, r, a, b}); + return r; + }; + const auto both = [&](std::uint32_t a, std::uint32_t b) { + const std::uint32_t r = id(); + emit(body, op_logical_and, {t_bool, r, a, b}); + return r; + }; + const auto splat = [&](std::uint32_t b) { // OpSelect on vectors takes a vector condition before SPIR-V 1.4 + const std::uint32_t r = id(); + emit(body, op_composite_construct, {t_bv4, r, b, b, b, b}); + return r; + }; + const std::uint32_t* p = corners[0].v; // vars[0] is the Position + const std::uint32_t l12 = length2(p[0], p[1]), l23 = length2(p[1], p[2]), l31 = length2(p[2], p[0]); + const std::uint32_t at_v1 = both(at_least(l23, l12), at_least(l23, l31)), not_v1 = id(); + emit(body, op_logical_not, {t_bool, not_v1, at_v1}); + const std::uint32_t at_v2 = both(not_v1, at_least(l31, l12)); + const std::uint32_t c_v1 = splat(at_v1), c_v2 = splat(at_v2); + const auto pick = [&](std::uint32_t condition, std::uint32_t yes, std::uint32_t no) { + const std::uint32_t r = id(); + emit(body, op_select, {t_v4, r, condition, yes, no}); + return r; + }; + // Per variable: the fourth corner, v1 + v2 + v3 - 2 * corner, and the six vertices of the two triangles. + std::vector> emitted; + for (const Corners& c : corners) { + const std::uint32_t corner = pick(c_v1, c.v[0], pick(c_v2, c.v[1], c.v[2])); + const std::uint32_t s12 = id(), s123 = id(), less = id(), fourth = id(); + emit(body, op_fadd, {t_v4, s12, c.v[0], c.v[1]}); + emit(body, op_fadd, {t_v4, s123, s12, c.v[2]}); + emit(body, op_fsub, {t_v4, less, s123, corner}); + emit(body, op_fsub, {t_v4, fourth, less, corner}); + emitted.push_back({c.v[0], c.v[1], pick(c_v1, fourth, c.v[2]), + c.v[0], pick(c_v2, c.v[2], fourth), pick(c_v1, c.v[2], pick(c_v2, fourth, c.v[1]))}); + } + for (int triangle = 0; triangle < 2; ++triangle) { + for (int k = 0; k < 3; ++k) { + for (std::size_t i = 0; i < vars.size(); ++i) emit(body, op_store, {vars[i].out, emitted[i][triangle * 3 + k]}); + emit(body, op_emit_vertex, {}); + } + emit(body, op_end_primitive, {}); + } + emit(body, op_return, {}); + emit(body, op_function_end, {}); + + std::vector out{0x07230203u, 0x00010000u, 0, next, 0}; + emit(out, op_capability, {2}); // Geometry + emit(out, op_memory_model, {0, 1}); // Logical, GLSL450 + std::vector entry{3, main_fn, 0x6e69616du, 0}; // Geometry, %main, "main" + entry.insert(entry.end(), io_vars.begin(), io_vars.end()); + out.push_back((std::uint32_t(entry.size()) + 1) << 16 | op_entry_point); + out.insert(out.end(), entry.begin(), entry.end()); + emit(out, op_execution_mode, {main_fn, 22}); // Triangles + emit(out, op_execution_mode, {main_fn, 0, 1}); // Invocations 1 + emit(out, op_execution_mode, {main_fn, 29}); // OutputTriangleStrip + emit(out, op_execution_mode, {main_fn, 26, 6}); // OutputVertices 6 + out.insert(out.end(), annotations.begin(), annotations.end()); + out.insert(out.end(), globals.begin(), globals.end()); + out.insert(out.end(), body.begin(), body.end()); + return out; +} + +} // namespace leonida diff --git a/runtime/src/root_signature.cpp b/runtime/src/root_signature.cpp index a0eb96cced..10dd1e02c7 100644 --- a/runtime/src/root_signature.cpp +++ b/runtime/src/root_signature.cpp @@ -59,10 +59,18 @@ StagePackResult pack_stage(const RootSignature& sig, Stage stage) { } uint64_t cost = 0; // 64-bit, as in pack() uint64_t next = out.base; + uint64_t spill_next = 0; + bool spilling = false; std::vector first; + std::vector spill; first.reserve(sig.params.size()); + spill.reserve(sig.params.size()); for (size_t i = 0; i < sig.params.size(); ++i) { const RootParameter& p = sig.params[i]; + if (p.type != ParamType::Constants && p.type != ParamType::Descriptor && p.type != ParamType::Table) { + out.error = "unknown root parameter type"; + return out; + } if (p.type == ParamType::Constants && p.num_values == 0) { out.error = "root constant parameter needs at least 1 dword"; return out; @@ -73,18 +81,27 @@ StagePackResult pack_stage(const RootSignature& sig, Stage stage) { return out; } const uint64_t dwords = stage_dwords(p.type, p.num_values); - if (next + dwords > kMaxUserSgprs) { - // The console moves this parameter and every later one to the spill array behind s[0:1]; that array's - // layout is not modelled here, so refuse rather than drop arguments. + if (!spilling && next + dwords <= kMaxUserSgprs) { + first.push_back(static_cast(next)); + spill.push_back(kNoSpill); + next += dwords; + } else if (stage == Stage::Compute) { + // Compute packs this parameter and every later one contiguously into the spill array behind s[0:1] + // (docs/d3d12_vulkan.md §3.5 & §7). Total spill stays bounded by kMaxD3d12Cost (<= 64 dwords). + spilling = true; + first.push_back(kNoSgpr); + spill.push_back(static_cast(spill_next)); + spill_next += dwords; + } else { out.error = "root parameter " + std::to_string(i) + " does not fit in the user SGPRs from s" + std::to_string(out.base) + " (spill array not modelled)"; return out; } - first.push_back(static_cast(next)); - next += dwords; } out.first_sgpr = std::move(first); + out.spill_dword = std::move(spill); out.end_sgpr = static_cast(next); + out.spill_dwords = static_cast(spill_next); out.d3d12_cost = static_cast(cost); out.ok = true; return out; diff --git a/runtime/src/root_signature.h b/runtime/src/root_signature.h index 3769629400..60b0d56327 100644 --- a/runtime/src/root_signature.h +++ b/runtime/src/root_signature.h @@ -132,7 +132,9 @@ constexpr uint32_t kMaxD3d12Cost = 64; // - vertex/pixel/geometry s8 and mesh s16: a hypothesis from the corpus census only (lowest pointer SGPR per stage); // no signature confirms them, and visibility is not modelled (every parameter takes its place in every stage). // A parameter that does not fit goes to the console's spill array behind s[0:1] (compute, section 7) together with -// every parameter after it; that array is not modelled, so such a signature is refused, never truncated. +// every parameter after it. For compute that packed spill array (1 dword per 32-bit constant, 2 per root descriptor, +// 1 per descriptor table, no alignment padding) is modelled in StagePackResult; non-compute stages still refuse spills +// because their spill pointer SGPR is unmeasured. enum class Stage : uint32_t { Vertex = 0, Pixel = 1, Geometry = 2, Compute = 3, Mesh = 4 }; [[nodiscard]] constexpr uint32_t stage_base(Stage stage) noexcept { @@ -163,19 +165,23 @@ enum class Stage : uint32_t { Vertex = 0, Pixel = 1, Geometry = 2, Compute = 3, } constexpr uint32_t kNoSgpr = 0xFFFFFFFFu; +constexpr uint32_t kNoSpill = 0xFFFFFFFFu; struct StagePackResult { bool ok = false; - std::string error; // set when !ok; names the refusing parameter + std::string error; // set when !ok; names the refusing parameter Stage stage = Stage::Compute; - uint32_t base = 0; // stage_base(stage) - std::vector first_sgpr; // per parameter: its first user SGPR (kNoSgpr when the signature is refused) - uint32_t end_sgpr = 0; // one past the last SGPR used: the RSRC2 USER_SGPR count the layout implies - uint32_t d3d12_cost = 0; // cost against the 64-dword D3D12 limit + uint32_t base = 0; // stage_base(stage) + std::vector first_sgpr; // per parameter: its first user SGPR (kNoSgpr when spilled or refused) + std::vector spill_dword; // per parameter: dword offset in s[0:1] spill array (kNoSpill when inline) + uint32_t end_sgpr = 0; // one past the last inline SGPR used: the RSRC2 USER_SGPR count + uint32_t spill_dwords = 0; // total dwords in the packed spill array (0 when nothing spills) + uint32_t d3d12_cost = 0; // cost against the 64-dword D3D12 limit }; -// Lays the parameters out for `stage` in the console layout. Fails like pack() on more than 64 parameters, a -// constant parameter of 0 values or the 64-dword cost limit, and on any parameter that would spill. +// Lays the parameters out for `stage` in the console layout. Fails like pack() on more than 64 parameters, an +// unknown parameter type, a constant parameter of 0 values, or the 64-dword cost limit. Compute spills any trailing +// parameters from the first one that does not fit whole into spill_dword; non-compute stages refuse any spill. [[nodiscard]] StagePackResult pack_stage(const RootSignature& sig, Stage stage); // D3D12 cost of one parameter against the 64-dword limit. diff --git a/runtime/src/shader_directory.h b/runtime/src/shader_directory.h new file mode 100644 index 0000000000..ed7412898b --- /dev/null +++ b/runtime/src/shader_directory.h @@ -0,0 +1,56 @@ +// Shared shader-library location for the Vulkan and DirectStorage runtimes. +#pragma once +#include +#include +#include +#include +#include +#include +#include + +namespace leonida::shader_paths { +// The folder make_game recorded in shader_path.txt at `config`, or empty without one. Throws when the path cannot be +// converted: MSVC's STL reports a Windows path that is not UTF-8 as std::system_error, libstdc++ as filesystem_error. +inline std::filesystem::path shader_directory_from_file(const std::filesystem::path& config) { + std::ifstream file(config, std::ios::binary); + if (!file) return {}; + const std::string text{std::istreambuf_iterator(file), std::istreambuf_iterator()}; + if (text.empty() || text.find('\0') != std::string::npos) return {}; + + // make_game records an absolute Unix path on Linux. Resolve it inside the running Wine prefix. + if (text.front() == '/') { + using WineDosPath = wchar_t* (CDECL*)(const char*); + const auto to_dos = std::bit_cast( + ::GetProcAddress(::GetModuleHandleW(L"kernel32.dll"), "wine_get_dos_file_name")); + if (!to_dos) return {}; + const auto release = [](wchar_t* path) { ::HeapFree(::GetProcessHeap(), 0, path); }; + const std::unique_ptr path(to_dos(text.c_str()), release); + if (path) return std::filesystem::path(path.get()); + return {}; + } + return std::filesystem::path(std::u8string(text.begin(), text.end())); +} + +inline std::filesystem::path configured(std::string* error = nullptr, const std::filesystem::path& config = {}) { + try { + constexpr wchar_t env_name[] = L"LEONIDA_SHADERS"; + if (const DWORD size = ::GetEnvironmentVariableW(env_name, nullptr, 0)) { + std::wstring value(size, L'\0'); + const DWORD length = ::GetEnvironmentVariableW(env_name, value.data(), size); + if (length && length < size) { + value.resize(length); + return std::filesystem::path(value); + } + } + if (!config.empty()) return shader_directory_from_file(config); + std::wstring exe(32768, L'\0'); + const DWORD length = ::GetModuleFileNameW(nullptr, exe.data(), static_cast(exe.size())); + if (!length || length >= exe.size()) return {}; + exe.resize(length); + return shader_directory_from_file(std::filesystem::path(exe).parent_path() / L"shader_path.txt"); + } catch (const std::exception& e) { + if (error) *error = e.what(); + return {}; + } +} +} // namespace leonida::shader_paths diff --git a/runtime/src/shader_library.h b/runtime/src/shader_library.h index 596ad0ae92..4fc439c349 100644 --- a/runtime/src/shader_library.h +++ b/runtime/src/shader_library.h @@ -8,6 +8,7 @@ // writes into `spirv/index.json`, next to `.spv`. This header needs no Windows, Vulkan or third-party code: // it carries its own inflate (RFC 1950/1951), SHA-256 (FIPS 180-4) and a minimal JSON reader. +#include "descriptor_table.h" #include "spirv_words.h" #include @@ -220,7 +221,7 @@ inline int decode(BitReader& in, const Huffman& h) { } inline ZlibError inflate_codes(BitReader& in, std::vector& out, const Huffman& lengths, - const Huffman& distances, std::size_t limit) { + const Huffman& distances, std::size_t limit, bool bulk = false) { static constexpr std::int16_t length_base[29] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258}; static constexpr std::int16_t length_extra[29] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, @@ -248,7 +249,25 @@ inline ZlibError inflate_codes(BitReader& in, std::vector& out, co if (in.failed() || distance > out.size()) return ZlibError::data; if (out.size() > limit || length > limit - out.size()) return ZlibError::limit; const std::size_t from = out.size() - distance; - for (std::size_t i = 0; i < length; ++i) out.push_back(out[from + i]); + if (!bulk) { + for (std::size_t i = 0; i < length; ++i) out.push_back(out[from + i]); + continue; + } + const auto end = out.size(); + out.resize(end + length); + auto* dest = out.data() + end; + if (distance == 1) { + std::memset(dest, out[from], length); + } else { + // Copy one period, then double the completed prefix. Each memcpy is disjoint. + auto copied = (std::min)(distance, length); + std::memcpy(dest, out.data() + from, copied); + while (copied < length) { + const auto n = (std::min)(copied, length - copied); + std::memcpy(dest + copied, dest, n); + copied += n; + } + } } } @@ -260,7 +279,7 @@ inline ZlibError inflate_codes(BitReader& in, std::vector& out, co // dictionary), `data` for the deflate data or a missing trailer, `checksum` for an Adler-32 mismatch, `limit` for // output beyond `limit`. Bytes after the Adler-32 trailer are not read. inline bool zlib_inflate(std::span in, std::vector& out, - std::size_t limit = std::size_t(1) << 30, ZlibError* why = nullptr) { + std::size_t limit = std::size_t(1) << 30, ZlibError* why = nullptr, bool bulk = false) { out.clear(); const auto fail = [why](ZlibError reason) { if (why) *why = reason; @@ -303,7 +322,7 @@ inline bool zlib_inflate(std::span in, std::vector in, std::vector in, std::vector in.size() || in.size() - at < 4) return fail(ZlibError::data); std::uint32_t a = 1, b = 0; - for (const std::uint8_t x : out) { - a = (a + x) % 65521; - b = (b + a) % 65521; + if (bulk) { + // Worst-case sums of 5552 bytes fit in uint32_t between modulo operations. + for (size_t pos = 0; pos < out.size();) { + const auto end = pos + (std::min)(size_t(5552), out.size() - pos); + while (pos < end) { a += out[pos++]; b += a; } + a %= 65521; + b %= 65521; + } + } else { + for (const std::uint8_t x : out) { + a = (a + x) % 65521; + b = (b + a) % 65521; + } } const std::uint32_t expected = (std::uint32_t(in[at]) << 24) | (std::uint32_t(in[at + 1]) << 16) | (std::uint32_t(in[at + 2]) << 8) | in[at + 3]; @@ -808,7 +837,8 @@ struct SignatureElement { struct ShaderEntry { std::string name; - std::string stage; // "vs", "ps", "cs", "ms", "gs" + std::string spv_file; // optional "" filename when the index key is a hash + std::string stage; // "vs", "ps", "cs", "ms", "gs" std::string fssm_sha256; std::string fspx_code_sha256; // an FSPX program (docs/fspx.md): the SHA-256 of its kind-6 bytes std::string fspx_state_sha256; // and of its kind-0 entry (dispatch state) @@ -819,6 +849,7 @@ struct ShaderEntry { // pipeline needs it at or under the device's maxComputeSharedMemorySize (32768 on some drivers). std::uint32_t lds_bytes = 0; bool uses_code_base = false; + bool code_base_known = false; bool wave64 = false; // The subgroup size the translator assumed (64 for a wave64 shader, 32 otherwise); 0 when the entry says null, // as one translated with --wave64-emulate does, or has none. @@ -826,6 +857,10 @@ struct ShaderEntry { // "workgroup" for a shader translated with --wave64-emulate: it uses no subgroup operation and is exact on any // subgroup size. Empty for a native translation. std::string wave64_exchange; + // Wave64 VS/PS/GS only: the translator's partition-invariance tier (index.json `wave64_graphics`; docs/design.md, + // "Wave64 graphics"). A and B are exact when the wave is cut into two 32-lane halves, C is not. Empty for other + // stages or an index written without the analysis. + std::string wave64_graphics; bool emulated() const { return wave64_exchange == "workgroup"; } std::vector input_signature; // vertex shaders: what the input layout must feed std::vector inputs; // pixel shaders: input locations declared @@ -841,18 +876,55 @@ struct ShaderEntry { std::uint32_t max_primitives = 0; }; +// Which descriptor-table hash finalizer the loaded modules probe with (descriptor_table.h). Each module's index.json +// meta may carry `"descriptor_hash": "fnv1a_fmix32"`; an absent key means the old bare `"fnv1a"`. The runtime has one +// table for all shaders, so it counts the kinds over every loaded module (the root index and each sub-index) and picks +// the majority; a mixed library still works, because the minority's lookups simply miss to index 0. +struct DescriptorHashCensus { + std::size_t fnv1a = 0; + std::size_t fnv1a_fmix32 = 0; + std::size_t total() const { return fnv1a + fnv1a_fmix32; } +}; + +// The kind most modules declare. A tie (or no modules) is fnv1a, the behaviour before the marker existed. +inline DescriptorHashKind majority_descriptor_hash_kind(const DescriptorHashCensus& census) { + return census.fnv1a_fmix32 > census.fnv1a ? DescriptorHashKind::fnv1a_fmix32 : DescriptorHashKind::fnv1a; +} + +// LEONIDA_DESCRIPTOR_HASH=fnv1a|fnv1a_fmix32 overrides the modules' majority. False when `value` is null, empty or not +// one of the two kinds (an unrecognised value is ignored rather than failing startup). +inline bool descriptor_hash_kind_from_env(const char* value, DescriptorHashKind* kind) { + if (!value || !*value) return false; + if (std::strcmp(value, "fnv1a_fmix32") == 0) { + if (kind) *kind = DescriptorHashKind::fnv1a_fmix32; + return true; + } + if (std::strcmp(value, "fnv1a") == 0) { + if (kind) *kind = DescriptorHashKind::fnv1a; + return true; + } + return false; +} + class ShaderLibrary { public: - // Reads /index.json, then the indexes of the programs make_game.py translates from the package's DLLs, each - // when it is there: + // Reads /index.json, then the indexes of the programs make_game.py translates from the package's DLLs and the + // game executable, each when it is there: // - /fspx/index.json, the FidelityFX DLL's FSPX programs, entries named "fspx/" (docs/fspx.md); + // - /fspx_compute/index.json, the compute programs from shaders.rpf's pipeline library; + // - /fspx_gfx/index.json, the graphics programs from the same library; // - /bvh/index.json, XboxBvhBuilder.dll's FSSM programs, entries named "bvh/" and found by // fssm_sha256 like the game's own shaders (docs/embedded_shaders.md); + // - /exe/index.json, game_scarlett_master.exe's own DXBC containers, entries named "exe/" and found + // the same way (docs/embedded_shaders.md, "Retail executable"); // - /library/index.json, the compute programs of the pipeline library in shaders.rpf, which the executable // creates with slot 67; entries named "library/" and found by fspx_code_sha256 and fspx_state_sha256 // like the FSPX ones (docs/shader_library.md). - // Entries with neither fssm_sha256 nor fspx_code_sha256 cannot be found by content and are skipped. Both folders - // are optional: a missing or unreadable index there leaves the main one, and the other folder's, loaded. + // fspx_compute/ and library/ are two builds of the same slot-67 programs (make_game.py's library_shaders() writes + // library/; fspx_compute/ is the set translated from every console-path miss): both go into the same FSPX lookup + // by kind-6 and kind-0 SHA-256, and fspx_compute/ is read first, so its entry is the one found when both hold a + // program. Entries with neither fssm_sha256 nor fspx_code_sha256 cannot be found by content and are skipped. The + // sub-indexes are optional: a missing or unreadable index there leaves the main one and the other folders loaded. bool load(const std::filesystem::path& dir, std::string* error = nullptr) { const auto fail = [&](const std::string& why) { if (error) *error = why; @@ -870,7 +942,7 @@ class ShaderLibrary { } catch (...) { return fail("index.json could not be read"); } - for (const char* sub_folder : {"fspx", "bvh", "library"}) { + for (const char* sub_folder : {"fspx", "fspx_compute", "fspx_gfx", "bvh", "exe", "library"}) { try { const auto ignore = [](const std::string&) { return false; }; const std::filesystem::path sub = folder / sub_folder; @@ -882,17 +954,53 @@ class ShaderLibrary { return true; } + // Loads only the optional FSPX sub-indexes (/fspx/index.json and /fspx_gfx/index.json) without parsing + // the 26,565-entry main index.json, for fast stage/hash lookups in the Xbox device proxy. + bool load_fspx_only(const std::filesystem::path& dir) { + dir_ = dir; + entries_.clear(); + fspx_entries_.clear(); + count_ = 0; + fspx_count_ = 0; + fspx_compute_count_ = 0; + fspx_gfx_count_ = 0; + bvh_count_ = 0; + exe_count_ = 0; + descriptor_hash_census_ = {}; + for (const char* folder : {"fspx", "fspx_gfx"}) { + try { + const auto ignore = [](const std::string&) { return false; }; + const std::filesystem::path sub = dir / folder; + if (std::ifstream(sub / "index.json", std::ios::binary)) + load_index(sub, std::string(folder) + "/", ignore); + } catch (...) { + } + } + return (fspx_count_ + fspx_gfx_count_) > 0; + } + bool loaded() const { return !dir_.empty(); } // The folder load() read, made absolute; empty before. const std::filesystem::path& directory() const { return dir_; } std::size_t size() const { return count_; } + // The descriptor-hash kinds the loaded modules declare, and the kind the majority of them probe with (fnv1a when + // they tie or none declares one). The device takes this once, before its descriptor table's first insert, unless + // LEONIDA_DESCRIPTOR_HASH names a kind. + const DescriptorHashCensus& descriptor_hash_census() const { return descriptor_hash_census_; } + DescriptorHashKind descriptor_hash_kind() const { return majority_descriptor_hash_kind(descriptor_hash_census_); } // Entries loaded from /fspx/index.json and /library/index.json. A corpus of RPF containers never // reaches these: their programs come from FidelityFX DLLs and the pipeline library, so callers comparing reached // entries with size() must leave them out. std::size_t fspx_size() const { return fspx_count_; } + std::size_t fspx_compute_size() const { return fspx_compute_count_; } + // Entries loaded from /fspx_gfx/index.json (graphics FSPX programs from shaders.rpf's pipeline library). + std::size_t fspx_gfx_size() const { return fspx_gfx_count_; } // Entries loaded from /bvh/index.json. No RPF container reaches these either: XboxBvhBuilder.dll passes // their containers itself. std::size_t bvh_size() const { return bvh_count_; } + // Entries loaded from /exe/index.json: game_scarlett_master.exe's inline containers, which no shader + // archive holds. + std::size_t exe_size() const { return exe_count_; } // The first entry for this program. Two containers can hold the same FSSM program with different input // signatures; `candidates` returns all of them. @@ -910,6 +1018,15 @@ class ShaderLibrary { return lookup(fspx_entries_, stage, fspx_code_sha256); } + // Finds an FSPX program by its kind-6 SHA-256 across all stages so the stage comes from the index entry itself. + const ShaderEntry* find_fspx_by_code(std::string_view fspx_code_sha256) const { + for (std::string_view st : {"vs", "ps", "ms", "gs", "cs"}) { + const auto all = fspx_candidates(st, fspx_code_sha256); + if (!all.empty()) return all.front(); + } + return nullptr; + } + // The entries for a program compute_program() found, by the key of its kind (docs/fspx.md, "Build and run-time // lookup"): // - FSSM: by fssm_sha256, as before; @@ -946,11 +1063,30 @@ class ShaderLibrary { return all; } + // The size of the module's file in bytes, or 0 when it is missing: what spirv() would read, without reading it. + std::size_t spirv_bytes(const ShaderEntry& entry) const { + std::error_code ec; + auto path = dir_; + path += "/" + entry.name + ".spv"; + auto size = std::filesystem::file_size(path, ec); + if (ec && !entry.spv_file.empty()) { + auto alt = dir_; + alt += "/" + entry.spv_file; + size = std::filesystem::file_size(alt, ec); + } + return ec ? 0 : static_cast(size); + } + // The module's words, or empty when /.spv is missing or not SPIR-V. std::vector spirv(const ShaderEntry& entry) const { auto path = dir_; path += "/" + entry.name + ".spv"; std::ifstream file(path, std::ios::binary | std::ios::ate); + if (!file && !entry.spv_file.empty()) { + auto alt = dir_; + alt += "/" + entry.spv_file; + file.open(alt, std::ios::binary | std::ios::ate); + } return read_spirv_words(file, file.tellg()); } @@ -999,7 +1135,11 @@ class ShaderLibrary { fspx_entries_.clear(); count_ = 0; fspx_count_ = 0; + fspx_compute_count_ = 0; + fspx_gfx_count_ = 0; bvh_count_ = 0; + exe_count_ = 0; + descriptor_hash_census_ = {}; } for (const auto& [name, meta] : root.object) { const Json* hash = meta.find("fssm_sha256"); @@ -1010,6 +1150,8 @@ class ShaderLibrary { if ((!by_fssm && !by_fspx) || !stage || stage->kind != Json::Kind::string) continue; ShaderEntry e; e.name = prefix + name; + if (const Json* spv = meta.find("spv"); spv && spv->kind == Json::Kind::string && !spv->string.empty()) + e.spv_file = prefix + spv->string; e.stage = stage->string; if (by_fssm) e.fssm_sha256 = hash->string; if (by_fspx) e.fspx_code_sha256 = code_hash->string; @@ -1020,12 +1162,20 @@ class ShaderLibrary { e.lds_bytes = u32(meta.find("lds_bytes")); if (const Json* l = meta.find("local_size"); l && l->kind == Json::Kind::array) for (std::size_t i = 0; i < l->array.size() && i < 3; ++i) e.local_size[i] = u32(&l->array[i]); - if (const Json* c = meta.find("uses_code_base"); c && c->kind == Json::Kind::boolean) e.uses_code_base = c->boolean; + // The paired FSPX translator emits uses_code_base only when true. Older + // key-only indexes have no such contract; retain their program bytes. + e.code_base_known = !e.fspx_state_sha256.empty(); + if (const Json* c = meta.find("uses_code_base"); c && c->kind == Json::Kind::boolean) { + e.uses_code_base = c->boolean; + e.code_base_known = true; + } if (const Json* w = meta.find("wave64"); w && w->kind == Json::Kind::boolean) e.wave64 = w->boolean; if (const Json* g = meta.find("subgroup_size"); g && g->kind == Json::Kind::number) e.subgroup_size = u32(g); if (const Json* x = meta.find("wave64_exchange"); x && x->kind == Json::Kind::string) e.wave64_exchange = x->string; + if (const Json* wg = meta.find("wave64_graphics"); wg && wg->kind == Json::Kind::string) + e.wave64_graphics = wg->string; if (const Json* s = meta.find("input_signature"); s && s->kind == Json::Kind::array) { for (const Json& item : s->array) { SignatureElement element; @@ -1072,10 +1222,20 @@ class ShaderLibrary { } e.max_vertices = u32(meta.find("max_vertices")); e.max_primitives = u32(meta.find("max_primitives")); + // Which finalizer this module's shader probes the descriptor table with (descriptor_table.h). Absent, or not + // a kind this runtime knows, is the old bare FNV-1a. + if (const Json* dh = meta.find("descriptor_hash"); + dh && dh->kind == Json::Kind::string && dh->string == "fnv1a_fmix32") + ++descriptor_hash_census_.fnv1a_fmix32; + else + ++descriptor_hash_census_.fnv1a; if (by_fspx) fspx_entries_[{e.stage, e.fspx_code_sha256}].push_back(e); if (by_fssm) entries_[{e.stage, e.fssm_sha256}].push_back(std::move(e)); if (by_fspx && (prefix == "fspx/" || prefix == "library/")) ++fspx_count_; + if (by_fspx && prefix == "fspx_compute/") ++fspx_compute_count_; + if (by_fspx && prefix == "fspx_gfx/") ++fspx_gfx_count_; if (prefix == "bvh/") ++bvh_count_; + if (prefix == "exe/") ++exe_count_; ++count_; } return true; @@ -1084,10 +1244,14 @@ class ShaderLibrary { std::filesystem::path dir_; std::size_t count_ = 0; std::size_t fspx_count_ = 0; + std::size_t fspx_compute_count_ = 0; + std::size_t fspx_gfx_count_ = 0; std::size_t bvh_count_ = 0; + std::size_t exe_count_ = 0; // Entries by (stage, fssm_sha256) and by (stage, fspx_code_sha256), in index order. Entries entries_; Entries fspx_entries_; + DescriptorHashCensus descriptor_hash_census_; }; } // namespace leonida diff --git a/runtime/src/subgroup_size.h b/runtime/src/subgroup_size.h index c391b7e63d..0241c4db8e 100644 --- a/runtime/src/subgroup_size.h +++ b/runtime/src/subgroup_size.h @@ -61,6 +61,14 @@ inline VkShaderStageFlagBits subgroup_stage_bit(std::string_view stage) { return VkShaderStageFlagBits(0); } +// A wave64 VS/PS/GS that the translator's partition-invariance analysis (index.json `wave64_graphics`; docs/design.md, +// "Wave64 graphics") puts in tier A or B: observable results do not change when the GPU cuts the wave into two 32-lane +// halves, so the device's 32-wide size is exact for it. Tier C and entries without the analysis stay conservative. +inline bool graphics_partition_invariant(const ShaderEntry& entry) { + if (entry.stage != "vs" && entry.stage != "ps" && entry.stage != "gs") return false; + return entry.wave64 && (entry.wave64_graphics == "A" || entry.wave64_graphics == "B"); +} + enum class SubgroupOutcome { emulated, // --wave64-emulate: exact on any size, nothing is required required, // the stage asks for `size` diff --git a/runtime/src/thread_stacks.cpp b/runtime/src/thread_stacks.cpp new file mode 100644 index 0000000000..67188d9086 --- /dev/null +++ b/runtime/src/thread_stacks.cpp @@ -0,0 +1,237 @@ +#include "thread_stacks.h" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../shims/shims.h" +#include "../shims/startup_trace.h" + +namespace rt { +namespace { + +using Clock = std::chrono::steady_clock; +using GetDescription = HRESULT(WINAPI*)(HANDLE, PWSTR*); +using QueryThread = LONG(NTAPI*)(HANDLE, int, void*, ULONG, ULONG*); + +struct CopiedStack { + DWORD64 copy = 0; // Where the bytes are now. + DWORD64 original = 0; // Where they were in the thread: [original, original + size). + size_t size = 0; +}; + +// Suspended section: system calls and a copy only. +bool copy_context_and_stack(HANDLE thread, CONTEXT& context, std::byte* buffer, CopiedStack& stack) { + if (SuspendThread(thread) == DWORD(-1)) return false; + context.ContextFlags = CONTEXT_FULL; + MEMORY_BASIC_INFORMATION region{}; + bool copied = false; + if (GetThreadContext(thread, &context) && + VirtualQuery(reinterpret_cast(context.Rsp), ®ion, sizeof(region)) && + region.State == MEM_COMMIT && !(region.Protect & (PAGE_GUARD | PAGE_NOACCESS))) { + // From RSP (rounded down to keep the 16-byte alignment the copy buffer also has) to the top of the committed + // run of stack pages, at most kMaxStackBytes. + stack.original = context.Rsp & ~DWORD64(15); + const DWORD64 top = reinterpret_cast(region.BaseAddress) + region.RegionSize; + stack.size = static_cast(std::min(StackSampler::kMaxStackBytes, top - stack.original)); + SIZE_T read = 0; + copied = ReadProcessMemory(GetCurrentProcess(), reinterpret_cast(stack.original), buffer, stack.size, + &read) && read == stack.size; + } + ResumeThread(thread); + stack.copy = reinterpret_cast(buffer); + return copied; +} + +// A frame's code can be unloaded after its thread resumes and a damaged stack can hand the unwinder a bad pointer: +// both are access violations here, and end the walk. +bool unwind_frame(CONTEXT& context) { + __try { + DWORD64 image_base = 0; + if (const auto* entry = RtlLookupFunctionEntry(context.Rip, &image_base, nullptr)) { + void* handler_data = nullptr; + DWORD64 establisher = 0; + RtlVirtualUnwind(UNW_FLAG_NHANDLER, image_base, context.Rip, const_cast(entry), + &context, &handler_data, &establisher, nullptr); + } else { + // No function entry: a leaf (or a thunk without unwind data) that has not moved RSP. + context.Rip = *reinterpret_cast(context.Rsp); + context.Rsp += sizeof(DWORD64); + } + } __except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION || GetExceptionCode() == EXCEPTION_IN_PAGE_ERROR + ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + return false; + } + return true; +} + +size_t walk_copy(CONTEXT& context, const CopiedStack& stack, std::uint64_t* frames) { + // An address in the copied range now names the same word in the copy. + const auto rebase = [&](DWORD64& address) { + if (address >= stack.original && address - stack.original < stack.size) address += stack.copy - stack.original; + }; + const auto in_copy = [&](DWORD64 address) { + return address >= stack.copy && address - stack.copy + sizeof(DWORD64) <= stack.size; + }; + size_t count = 0; + rebase(context.Rsp); + while (context.Rip && count < StackSampler::kMaxFrames) { + frames[count++] = context.Rip; + if (!in_copy(context.Rsp)) break; + const DWORD64 rsp = context.Rsp; + // Any nonvolatile register can be a frame pointer, including one just restored from the copy's bytes. + for (DWORD64* reg : {&context.Rbx, &context.Rbp, &context.Rsi, &context.Rdi, + &context.R12, &context.R13, &context.R14, &context.R15}) + rebase(*reg); + if (!unwind_frame(context)) break; + rebase(context.Rsp); // A machine frame restores RSP from the copy as well. + if (context.Rsp <= rsp) break; + } + return count; +} + +std::string thread_label(HANDLE thread, GetDescription describe, QueryThread query) { + if (describe) { + PWSTR description = nullptr; + if (SUCCEEDED(describe(thread, &description)) && description) { + std::string name = startup_trace::detail::utf8_from_wide(description, static_cast(wcslen(description))); + LocalFree(description); + if (!name.empty()) return name; + } + } + constexpr int kWin32StartAddress = 9; // ThreadQuerySetWin32StartAddress + DWORD64 start = 0; + if (query && query(thread, kWin32StartAddress, &start, sizeof(start), nullptr) >= 0 && start) + return "start " + shims::module_offset(start); + return "start unknown"; +} + +struct ThreadTrace { + DWORD tid = 0; + std::string label; + std::array frames{}; + size_t count = 0; +}; + +void print_traces(unsigned at, const std::vector& traces) { + std::string out = "[rt] stacks t=" + std::to_string(at) + ": " + std::to_string(traces.size()) + " threads\n"; + for (auto it = traces.begin(); it != traces.end(); ++it) { + out += "[rt] stacks t=" + std::to_string(at) + " thread " + std::to_string(it->tid) + " (" + it->label + "):\n"; + const auto same = std::find_if(traces.begin(), it, [&](const ThreadTrace& earlier) { + return it->count && it->count == earlier.count && + std::equal(it->frames.begin(), it->frames.begin() + it->count, earlier.frames.begin()); + }); + if (same != it) { + out += " same as thread " + std::to_string(same->tid) + "\n"; + } else if (!it->count) { + out += " stack unavailable\n"; + } else { + for (size_t i = 0; i < it->count; ++i) + out += " #" + std::to_string(i) + " " + shims::module_offset(it->frames[i]) + "\n"; + } + } + std::fputs(out.c_str(), stderr); + std::fflush(stderr); +} + +void snapshot_threads(unsigned at, StackSampler& sampler, GetDescription describe, QueryThread query) { + const HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); + if (snapshot == INVALID_HANDLE_VALUE) { + std::fprintf(stderr, "[rt] stacks t=%u: thread list failed (error %lu)\n", at, GetLastError()); + return; + } + std::vector traces; + traces.reserve(512); + const DWORD pid = GetCurrentProcessId(); + const DWORD self = GetCurrentThreadId(); + THREADENTRY32 entry{}; + entry.dwSize = sizeof(entry); + for (BOOL ok = Thread32First(snapshot, &entry); ok; ok = Thread32Next(snapshot, &entry)) { + entry.dwSize = sizeof(entry); + if (entry.th32OwnerProcessID != pid || entry.th32ThreadID == self) continue; + const HANDLE thread = OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, + FALSE, entry.th32ThreadID); + if (!thread) continue; + if (GetProcessIdOfThread(thread) == pid) { // The listed thread may have exited and its ID been reused. + ThreadTrace& trace = traces.emplace_back(); + trace.tid = entry.th32ThreadID; + trace.label = thread_label(thread, describe, query); // Before sampling: it allocates. + trace.count = sampler.sample(thread, trace.frames.data()); + } + CloseHandle(thread); + } + CloseHandle(snapshot); + print_traces(at, traces); +} + +} // namespace + +StackSampler::StackSampler() : stack_(std::make_unique_for_overwrite(kMaxStackBytes)) {} + +std::size_t StackSampler::sample(void* thread, std::uint64_t* frames) { + CONTEXT context{}; + CopiedStack stack; + if (!copy_context_and_stack(static_cast(thread), context, stack_.get(), stack)) { + if (!context.Rip) return 0; + frames[0] = context.Rip; // The context without its stack: the innermost frame only. + return 1; + } + return walk_copy(context, stack, frames); +} + +bool parse_stack_times(std::string_view text, std::vector& seconds) { + seconds.clear(); + for (;;) { + const auto comma = text.find(','); + const auto token = text.substr(0, comma); + unsigned value = 0; + const auto [end, error] = std::from_chars(token.data(), token.data() + token.size(), value); + if (token.empty() || error != std::errc{} || end != token.data() + token.size()) { + seconds.clear(); + return false; + } + seconds.push_back(value); + if (comma == std::string_view::npos) break; + text.remove_prefix(comma + 1); + } + std::sort(seconds.begin(), seconds.end()); + seconds.erase(std::unique(seconds.begin(), seconds.end()), seconds.end()); + return true; +} + +std::jthread start_thread_stacks() { + const auto start = Clock::now(); + char spec[1024]; + const DWORD length = GetEnvironmentVariableA("LEONIDA_STACKS", spec, sizeof(spec)); + if (!length) return {}; + std::vector times; + if (length >= sizeof(spec) || !parse_stack_times(std::string_view(spec, length), times)) { + std::fprintf(stderr, "[rt] LEONIDA_STACKS: expected comma-separated whole seconds\n"); + return {}; + } + return std::jthread([start, times = std::move(times)](std::stop_token stop) { + const auto describe = reinterpret_cast(reinterpret_cast( + GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "GetThreadDescription"))); + const auto query = reinterpret_cast(reinterpret_cast( + GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "NtQueryInformationThread"))); + StackSampler sampler; + std::condition_variable_any wake; + std::mutex mutex; + std::unique_lock lock(mutex); + for (const unsigned at : times) { + wake.wait_until(lock, stop, start + std::chrono::seconds(at), [] { return false; }); + if (stop.stop_requested()) break; + snapshot_threads(at, sampler, describe, query); + } + }); +} + +} // namespace rt diff --git a/runtime/src/thread_stacks.h b/runtime/src/thread_stacks.h new file mode 100644 index 0000000000..523c7b2663 --- /dev/null +++ b/runtime/src/thread_stacks.h @@ -0,0 +1,38 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace rt { + +// One thread's call chain, taken without stopping the thread for longer than a context and stack copy. +class StackSampler { +public: + static constexpr std::size_t kMaxFrames = 40; + static constexpr std::size_t kMaxStackBytes = 8 * 1024 * 1024; + + StackSampler(); // Allocates the stack copy once, so sample() allocates nothing. + + // `thread` needs THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT. While it is suspended this makes system calls only + // (GetThreadContext, VirtualQuery, ReadProcessMemory): no heap, stdio or user-mode locks, which the suspended + // thread may hold. After ResumeThread it unwinds the copy with RtlLookupFunctionEntry/RtlVirtualUnwind, reading + // stack words from the copy rather than the live stack, which has moved on. Writes up to kMaxFrames addresses + // (the instruction pointer, then return addresses) and returns how many; 0 if the thread could not be sampled. + std::size_t sample(void* thread, std::uint64_t* frames); + +private: + std::unique_ptr stack_; +}; + +// Parses LEONIDA_STACKS: comma-separated whole seconds. Returns false (and leaves `seconds` empty) on bad text. +bool parse_stack_times(std::string_view text, std::vector& seconds); + +// LEONIDA_STACKS: snapshots of every thread at the listed times since this call, printed to stderr. Destroy the +// sampler before unmapping the title image. +std::jthread start_thread_stacks(); + +} // namespace rt diff --git a/runtime/src/title_geometry_watch.h b/runtime/src/title_geometry_watch.h new file mode 100644 index 0000000000..ddc21d218f --- /dev/null +++ b/runtime/src/title_geometry_watch.h @@ -0,0 +1,123 @@ +#pragma once + +#include "title_page_watch.h" +#include +#include + +namespace leonida::geometry_writes { + +constexpr std::uintptr_t tile_size = 65536, page_size = 4096; +using Aliases = void (*)(std::uintptr_t, std::vector&); +inline std::atomic aliases{}; + +struct Cell { + std::atomic version{1}, mapping{1}; + std::array restore{}; + unsigned refs = 0; +}; +struct State { + std::mutex mutex; + host_heap::map cells; + std::atomic serial{1}; + std::atomic count{0}; +}; +inline State& state() { static State s; return s; } + +inline Cell* acquire(std::uintptr_t va) { + auto& s = state(); + std::lock_guard lock(s.mutex); + auto& c = s.cells[va]; + ++c.refs; + s.count.store(s.cells.size(), std::memory_order_release); + return &c; +} + +// Restore only protections this watch installed. A guest remap or explicit new protection supersedes them. +inline DWORD read_only(DWORD protection) { + switch (protection & 255u) { + case PAGE_READWRITE: case PAGE_WRITECOPY: return (protection & ~255u) | PAGE_READONLY; + case PAGE_EXECUTE_READWRITE: case PAGE_EXECUTE_WRITECOPY: return (protection & ~255u) | PAGE_EXECUTE_READ; + default: return 0; + } +} +inline void reopen(std::uintptr_t va, Cell& c) { + for (std::size_t i = 0; i < c.restore.size(); ++i) { + if (!c.restore[i]) continue; + void* p = reinterpret_cast(va + i * page_size); + MEMORY_BASIC_INFORMATION m{}; + DWORD old{}; + if (!VirtualQuery(p, &m, sizeof m)) continue; + if (m.State == MEM_COMMIT && m.Protect == read_only(c.restore[i]) && + !VirtualProtect(p, page_size, c.restore[i], &old)) continue; + c.restore[i] = 0; + } +} +inline void release(std::uintptr_t va) { + auto& s = state(); + std::lock_guard lock(s.mutex); + auto it = s.cells.find(va); + if (it != s.cells.end() && !--it->second.refs) { + reopen(va, it->second); + s.cells.erase(it); + s.count.store(s.cells.size(), std::memory_order_release); + } +} +enum class Event { write, open, fault, mapping, replaced }; +inline bool notify(std::uintptr_t begin, std::uintptr_t end, Event event) { + auto& s = state(); + if (!s.count.load(std::memory_order_acquire) || end <= begin) return false; + std::lock_guard lock(s.mutex); + auto it = s.cells.lower_bound(begin & ~(tile_size - 1)); + if (it == s.cells.end() || it->first >= end) return false; + const auto version = s.serial.load(std::memory_order_relaxed) + 1; + bool opened = false; + for (; it != s.cells.end() && it->first < end; ++it) { + auto& cell = it->second; + if (event == Event::open || event == Event::fault) { + reopen(it->first, cell); + if (event == Event::fault) { + MEMORY_BASIC_INFORMATION m{}; + opened = VirtualQuery(reinterpret_cast(begin), &m, sizeof m) && + m.State == MEM_COMMIT && !(m.Protect & PAGE_GUARD) && read_only(m.Protect); + } + } + if (event == Event::replaced) { + for (unsigned i = 0; i < cell.restore.size(); ++i) { + auto p = it->first + i * page_size; + if (p < end && p + page_size > begin) cell.restore[i] = 0; + } + } + if (event == Event::mapping || event == Event::replaced) cell.mapping.store(version, std::memory_order_release); + cell.version.store(version, std::memory_order_release); + } + s.serial.store(version, std::memory_order_release); + return opened; +} + +// Arm under the same lock as the write-fault path. A kernel destination may only be guarded again after its pin ends. +inline bool arm(std::uintptr_t va, Cell& c) { + auto& s = state(); + // Querying an OVERLAPPED can fault into xmem. Never do it with the watch lock held. + const auto version = c.version.load(std::memory_order_acquire); + bool pinned = false; + kernel_writes::for_each_pin(va, va + tile_size, [&](auto, auto) { pinned = true; }); + std::lock_guard lock(s.mutex); + if (pinned || version != c.version.load(std::memory_order_relaxed)) return false; + for (std::size_t i = 0; i < c.restore.size();) { + auto p = va + i * page_size; + MEMORY_BASIC_INFORMATION m{}; + if (!VirtualQuery(reinterpret_cast(p), &m, sizeof m)) return false; + const auto end = (std::min)(va + tile_size, reinterpret_cast(m.BaseAddress) + m.RegionSize); + if (end <= p) return false; + const auto next = (end - va) / page_size; + const DWORD guarded = read_only(m.Protect); + if (m.State == MEM_COMMIT && !(m.Protect & PAGE_GUARD) && guarded) { + DWORD old{}; + if (!VirtualProtect(reinterpret_cast(p), end - p, guarded, &old)) return false; + for (auto j = i; j < next; ++j) c.restore[j] = old; + } + i = next; + } + return true; +} +} // namespace leonida::geometry_writes diff --git a/runtime/src/title_page_watch.h b/runtime/src/title_page_watch.h new file mode 100644 index 0000000000..b83e71b7b9 --- /dev/null +++ b/runtime/src/title_page_watch.h @@ -0,0 +1,700 @@ +#pragma once +// What the D3D12 layer's slot-133 shadow buffers (ShadowPages in d3d12_vulkan_device.cpp) need from the rest of the +// runtime to see every write to the title's pages. +// +// A shadow notices the title's writes by asking the kernel which pages were written, where xmem reserved them with +// MEM_WRITE_WATCH (title_write_watch, below), and elsewhere by making the buffer's pages read-only between +// submissions: a write faults, the layer's handler makes the page writable again and the page is copied at the next +// submission. Two kinds of write don't fault there, and are reported here instead: +// +// 1. Aliases (title_page_aliases). xmem maps one physical page at as many VAs as the title asks +// (XMemMapPhysicalPages): a write through one VA changes what the others read without touching them. xmem +// reports each 64 KiB page mapped at more than one address; a shadow copies those at every submission. +// +// 2. Kernel writes (kernel_writes). A read-only page makes ReadFile fail with ERROR_NOACCESS instead of faulting +// into a user-mode handler. The file shims (read_file and the rest, below) pin the destination before the kernel +// writes it: the layer makes its pages writable and doesn't protect them again until the pin ends, when the +// call returns or, for an overlapped read, once its OVERLAPPED says it completed. A read that still fails with +// ERROR_NOACCESS is retried once after the destination is opened again and xmem has committed the physical pages +// mapped there that wait for their first touch (they are reserved until then, and a kernel write does not fault +// them in either: measured on Windows 11, the title's 258 MiB effect-database read failed this way forever). +// +// Any other host code that has the kernel write title memory (a DirectStorage queue that ReadFiles straight into +// a request's destination, for one) does the same: kernel_writes::read_file instead of ::ReadFile, or +// begin_write(destination, bytes, overlapped) before the call and end_write(id, pending) after it. A user-mode +// copy into title memory needs nothing: it faults like the title's own writes. +// +// Successful title memory map changes also invalidate the shadows' cached protection state. The shadows' own +// protection changes stay local to their trackers. +// +// The shadows themselves are brought up to date in one place, DeviceState::refresh_shadows in +// d3d12_vulkan_device.cpp, which VulkanQueue::execute_now calls (VulkanContext::set_before_execute) before every +// submission of command lists. +// +// Header-only, so the D3D12 layer, xmem and the file shims share one state in a process without linking each other. +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// The runtime's own heap (host_heap) for the state the D3D12 layer's write-fault handler waits behind. A thread can take +// a write fault on a guarded title page while it holds the process heap's lock: XMemAlloc is _aligned_malloc, so +// HeapAlloc and HeapFree write block headers on the title's pages. Its handler then waits for the tracker's lock +// (ShadowPages::reopen) and the list of trackers (g_shadow_pages_lock). So a thread that holds either of those, or any +// lock such a thread waits for (the record and journal of title_write_watch, title_page_aliases, kernel_writes' pins), +// must never wait for the process heap: it would wait for the faulting thread, which waits for it. Their containers +// allocate here instead, from a heap the title never touches and on whose lock no thread faults. +namespace leonida::host_heap { + +inline HANDLE handle() { + static const HANDLE heap = [] { + const HANDLE created = HeapCreate(0, 0, 0); + if (!created) // the process heap brings back the deadlock this heap avoids: write watching stays off + std::fprintf(stderr, "[rt] host heap: HeapCreate failed (%lu); write watching is off\n", GetLastError()); + return created ? created : GetProcessHeap(); + }(); + return heap; +} + +template +struct Allocator { + using value_type = T; + Allocator() noexcept { handle(); } // created before any lock is taken + template + Allocator(const Allocator&) noexcept {} + T* allocate(std::size_t n) { + if (n > std::size_t(-1) / sizeof(T)) throw std::bad_array_new_length(); + if (void* p = HeapAlloc(handle(), 0, n * sizeof(T))) return static_cast(p); + throw std::bad_alloc(); + } + void deallocate(T* p, std::size_t) noexcept { HeapFree(handle(), 0, p); } + template + bool operator==(const Allocator&) const noexcept { + return true; + } +}; + +template +using vector = std::vector>; +template +using map = std::map, Allocator>>; + +} // namespace leonida::host_heap + +namespace leonida::title_memory_map { + +inline std::atomic map_generation{0}; + +inline std::uint64_t generation() { return map_generation.load(std::memory_order_acquire); } +inline void changed() { map_generation.fetch_add(1, std::memory_order_release); } + +} // namespace leonida::title_memory_map + +namespace leonida::title_page_aliases { + +constexpr std::uintptr_t kPageSize = 0x10000; + +struct State { + std::shared_mutex mutex; + // 64 KiB-aligned VAs + std::unordered_set, std::equal_to, + host_heap::Allocator> + aliased; + std::atomic generation{0}; +}; + +inline State& state() { + static State s; + return s; +} + +// The 64 KiB page at `va` (rounded down) shows a page that is also mapped elsewhere (true), or no longer does. +inline void set(std::uintptr_t va, bool aliased) { + State& s = state(); + va &= ~(kPageSize - 1); + std::unique_lock lock(s.mutex); + const bool changed = aliased ? s.aliased.insert(va).second : s.aliased.erase(va) != 0; + if (changed) s.generation.fetch_add(1, std::memory_order_release); +} + +// Bumped by every change of set(). +inline std::uint64_t generation() { return state().generation.load(std::memory_order_acquire); } + +// Calls `f(va)` for each aliased 64 KiB page overlapping [begin, end). +template +void for_each_in(std::uintptr_t begin, std::uintptr_t end, F&& f) { + State& s = state(); + std::shared_lock lock(s.mutex); + if (s.aliased.empty()) return; + for (std::uintptr_t va = begin & ~(kPageSize - 1); va < end; va += kPageSize) + if (s.aliased.count(va)) f(va); +} + +} // namespace leonida::title_page_aliases + +// 3. GPU-only views (title_gpu_views). The title reserves some memory twice: a range the CPU maps physical pages into +// and a GPU-only range of the same size (PAGE_NOACCESS | PAGE_GRAPHICS_NOACCESS) that the console's GPU page +// tables map to the same pages, and it hands the GPU-only address to the GPU (the texture stream pool: slot-133 +// placements, slot-70 views, DirectStorage destinations; gfxres notes section 5). Nothing maps the GPU-only range +// for the host CPU, so the D3D12 layer reads such memory at the CPU range's address: to_cpu. xmem pairs each +// GPU-only reservation with the CPU-mappable reservation of the same size made just before it, as +// five-star-recomp does (docs/gpu-resources.md "Addresses", XMemReservation.CpuView; GPL-3.0-or-later). +namespace leonida::title_gpu_views { + +struct View { + std::uintptr_t gpu, cpu, size; +}; + +struct State { + std::shared_mutex mutex; + std::vector views; + std::atomic count{0}; + std::uintptr_t last_cpu = 0, last_cpu_size = 0; // the last CPU-mappable reservation +}; + +inline State& state() { + static State s; + return s; +} + +// xmem: a reservation the title made, GPU-only or not. Returns true when it paired a GPU-only one. +inline bool note_reservation(std::uintptr_t base, std::uintptr_t size, bool gpu_only) { + State& s = state(); + std::unique_lock lock(s.mutex); + if (!gpu_only) { + s.last_cpu = base; + s.last_cpu_size = size; + return false; + } + if (!s.last_cpu || s.last_cpu_size != size) return false; + s.views.push_back({base, s.last_cpu, size}); + s.count.store(s.views.size(), std::memory_order_release); + s.last_cpu = s.last_cpu_size = 0; + return true; +} + +// Where the CPU reads the memory a GPU address names: the paired CPU range for a GPU-only view, else the address. +inline std::uintptr_t to_cpu(std::uintptr_t va, std::uintptr_t bytes = 1) { + State& s = state(); + if (!s.count.load(std::memory_order_acquire)) return va; + std::shared_lock lock(s.mutex); + for (const View& v : s.views) + if (va >= v.gpu && va - v.gpu < v.size && bytes <= v.size - (va - v.gpu)) return va - v.gpu + v.cpu; + return va; +} + +// The other address of memory in a paired range: the CPU view's address for a GPU-only one and the GPU-only +// address for a CPU view's; 0 outside every pair. +inline std::uintptr_t other_view(std::uintptr_t va) { + State& s = state(); + if (!s.count.load(std::memory_order_acquire)) return 0; + std::shared_lock lock(s.mutex); + for (const View& v : s.views) { + if (va >= v.gpu && va - v.gpu < v.size) return va - v.gpu + v.cpu; + if (va >= v.cpu && va - v.cpu < v.size) return va - v.cpu + v.gpu; + } + return 0; +} + +} // namespace leonida::title_gpu_views + +// 4. Texel writes (title_texel_writes). The title writes texels into its own texture memory through XG's +// CopyIntoSubresource (xg_xs.cpp) and through the pointer Map gives it; the D3D12 layer fills a texture's image +// from that memory again when told (Device::refresh_title_textures drains these ranges before a submission), so a +// small update (a glyph in a font cache) is not left to a hash that samples the bytes. +namespace leonida::title_texel_writes { + +struct State { + std::mutex mutex; + std::vector> ranges; // [begin, end) + bool overflow = false; // too many to keep: check everything + std::atomic pending{false}; +}; + +inline State& state() { + static State s; + return s; +} + +inline void note(const void* begin, std::size_t bytes) { + if (!begin || !bytes) return; + State& s = state(); + std::lock_guard lock(s.mutex); + const auto at = reinterpret_cast(begin); + if (s.ranges.size() < 4096) s.ranges.emplace_back(at, at + bytes); + else s.overflow = true; + s.pending.store(true, std::memory_order_release); +} + +// The ranges noted since the last call; `overflow` says some were dropped. +inline std::vector> take(bool& overflow) { + State& s = state(); + overflow = false; + if (!s.pending.load(std::memory_order_acquire)) return {}; + std::lock_guard lock(s.mutex); + overflow = std::exchange(s.overflow, false); + s.pending.store(false, std::memory_order_relaxed); + return std::exchange(s.ranges, {}); +} + +} // namespace leonida::title_texel_writes + +// 5. XG layouts by shape (title_xg_layouts). A texture the title locks and writes with the CPU through Map is laid out +// as the XG computer the title made for it says (its lock computes the layout with XGCreateTextureComputer right +// before it maps, gfxres notes section 5), which a slot-133 description (Layout 0) does not tell: measured, the +// 2048x2048 and 1024x1024 A8 glyph caches are LINEAR (0x100) while XG's default for that description is 4KB_S. +// xg_xs records the Layout word of every computer by the texture's shape; the D3D12 layer takes the latest one of +// a mapped texture's shape when no slot-70 view has given it a layout. +namespace leonida::title_xg_layouts { + +struct Shape { + std::uint32_t dimension, format, height, depth, mips; + std::uint64_t width; + bool operator<(const Shape& o) const { + return std::tie(dimension, format, width, height, depth, mips) < + std::tie(o.dimension, o.format, o.width, o.height, o.depth, o.mips); + } +}; + +struct State { + std::mutex mutex; + std::map layouts; +}; + +inline State& state() { + static State s; + return s; +} + +inline void note(const Shape& shape, std::uint32_t layout) { + State& s = state(); + std::lock_guard lock(s.mutex); + if (s.layouts.size() < 65536 || s.layouts.count(shape)) s.layouts[shape] = layout; +} + +// The Layout word of the latest computer of this shape, or false. +inline bool find(const Shape& shape, std::uint32_t& layout) { + State& s = state(); + std::lock_guard lock(s.mutex); + const auto it = s.layouts.find(shape); + if (it == s.layouts.end()) return false; + layout = it->second; + return true; +} + +} // namespace leonida::title_xg_layouts + +// 6. Write-watched title memory (title_write_watch). xmem reserves the title's ordinary memory (the XMemVirtualAlloc +// and VirtualAlloc reservations that are not placeholders or physical-page windows) with MEM_WRITE_WATCH, and the +// kernel keeps a dirty bit per 4 KiB page there: GetWriteWatch with WRITE_WATCH_FLAG_RESET returns the pages +// written since and clears them. A shadow over such pages asks the kernel instead of making them read-only: no +// write fault, no VirtualProtect, and a kernel write (ReadFile) into them neither fails nor needs opening first. +// Sections (xmem's physical-page views) can't be write-watched, and keep the read-only guard. +// +// Several shadows can cover one page (a console descriptor heap's mirror next to a slot-133 buffer, two devices), +// and one asking clears the kernel's bits for all of them. So what each asking found is kept in a journal: per +// page, the number of the last asking that found it written. A reader (a shadow's tracker) was written to since its +// own last asking where a page's number is above it. As VIctory does (crates/victory-gpu/src/watch.rs, +// GPL-3.0-or-later). A reservation is numbered the same way when it is recorded: a reader whose last asking is +// older takes all of its pages as written. A reservation the title releases and reserves again at the same address +// is then new to the shadows, though its pages are write-watched both before and after and the new one's kernel +// bits are clear (what the old one's pages held is gone: they read as zeros now). +// +// LEONIDA_WRITE_WATCH=0 reserves without MEM_WRITE_WATCH: every shadow keeps the read-only guard, as before. Under +// Wine that is the default (=1 turns write watching on). +namespace leonida::title_write_watch { + +constexpr std::uintptr_t kPage = 0x1000; // the kernel's unit +// The journal is pruned of what every reader has seen once it doubles. Past kMaxPages it forgets askings more than +// kKeep old even if a reader hasn't seen them: that reader then takes all of its pages as written, once. +constexpr std::size_t kMaxPages = std::size_t(1) << 18; +constexpr std::uint64_t kKeep = std::uint64_t(1) << 16; + +// On by default on Windows; off under Wine, whose write watching was not measured here (LEONIDA_WRITE_WATCH=1 turns it +// on there). Off with LEONIDA_WRITE_WATCH=0. +inline bool enabled() { + static const bool on = [] { + char value[8] = {}; + std::size_t length = 0; + if (host_heap::handle() == GetProcessHeap()) return false; // no private heap: see host_heap + if (getenv_s(&length, value, sizeof(value), "LEONIDA_WRITE_WATCH") == 0 && length > 1) return value[0] != '0'; + const HMODULE ntdll = GetModuleHandleW(L"ntdll.dll"); + return !(ntdll && GetProcAddress(ntdll, "wine_get_version")); + }(); + return on; +} + +// A reservation made with MEM_WRITE_WATCH: its end, and the number it was recorded with (an asking's, see ask). +struct Region { + std::uintptr_t end; + std::uint64_t born; +}; + +// The containers allocate from host_heap: the D3D12 layer takes these locks while it holds a tracker's lock, which its +// write-fault handler waits for, and a faulting thread may hold the process heap's lock. +struct State { + std::shared_mutex mutex; // regions + host_heap::map regions; // base -> the reservation at base + std::atomic generation{0}; // bumped by every change of regions + std::atomic count{0}; // regions.size(), read without the lock + + // The last number given to an asking (or to a recorded reservation, which takes one without the journal's lock). + std::atomic asked{0}; + std::mutex journal; // everything below + std::uint64_t floor = 0; // askings up to this one were forgotten before every reader saw them + host_heap::map written; // page address -> the last asking that found it written + std::size_t pruned_size = 0; // written.size() after the last pruning + std::uint64_t pruned_at = 0; // the asking of the last pruning + host_heap::map readers; // reader -> its last asking + std::uint64_t next_reader = 1; + host_heap::vector found; // room for the kernel's answer + host_heap::vector refusals; // per run of an asking: the kernel refused it +}; + +inline State& state() { + static State s; + return s; +} + +// xmem: [base, base + size) was reserved with MEM_WRITE_WATCH for the shadows. A reservation the title asked to be +// write-watched itself is not added: its bits are the title's. Every reader takes its pages as written at its next +// asking (they are not the pages it copied, even at the same address). +inline void add(std::uintptr_t base, std::uintptr_t size) { + if (!size) return; + State& s = state(); + const std::uintptr_t end = base + ((size + kPage - 1) & ~(kPage - 1)); + std::unique_lock lock(s.mutex); + // A reservation released without remove() overlapping the new one is gone. + auto it = s.regions.lower_bound(base); + if (it != s.regions.begin() && std::prev(it)->second.end > base) --it; + while (it != s.regions.end() && it->first < end) it = s.regions.erase(it); + // Numbered under the lock: an asking that finds the reservation took its own number later (see ask). + s.regions[base] = Region{end, s.asked.fetch_add(1, std::memory_order_acq_rel) + 1}; + s.count.store(s.regions.size(), std::memory_order_release); + s.generation.fetch_add(1, std::memory_order_release); +} + +// xmem: the reservation holding `address` was released. +inline void remove(std::uintptr_t address) { + State& s = state(); + if (!s.count.load(std::memory_order_acquire)) return; + std::unique_lock lock(s.mutex); + auto it = s.regions.upper_bound(address); + if (it == s.regions.begin() || (--it)->second.end <= address) return; + s.regions.erase(it); + s.count.store(s.regions.size(), std::memory_order_release); + s.generation.fetch_add(1, std::memory_order_release); +} + +inline std::uint64_t generation() { return state().generation.load(std::memory_order_acquire); } + +// Whether `address` is in a write-watched reservation. +inline bool contains(std::uintptr_t address) { + State& s = state(); + if (!s.count.load(std::memory_order_acquire)) return false; + std::shared_lock lock(s.mutex); + auto it = s.regions.upper_bound(address); + return it != s.regions.begin() && (--it)->second.end > address; +} + +// The end of the write-watched reservation holding `address`, or 0. +inline std::uintptr_t end_of(std::uintptr_t address) { + State& s = state(); + if (!s.count.load(std::memory_order_acquire)) return 0; + std::shared_lock lock(s.mutex); + auto it = s.regions.upper_bound(address); + return it != s.regions.begin() && (--it)->second.end > address ? it->second.end : 0; +} + +// Calls `f(from, to)` for each write-watched part of [begin, end): each inside one reservation. +template +void for_each_in(std::uintptr_t begin, std::uintptr_t end, F&& f) { + State& s = state(); + if (!s.count.load(std::memory_order_acquire)) return; + std::shared_lock lock(s.mutex); + auto it = s.regions.upper_bound(begin); + if (it != s.regions.begin() && std::prev(it)->second.end > begin) --it; + for (; it != s.regions.end() && it->first < end; ++it) { + const std::uintptr_t from = (std::max)(it->first, begin), to = (std::min)(it->second.end, end); + if (from < to) f(from, to); + } +} + +// xmem: [from, to) of a write-watched reservation changed with no write the kernel sees (decommitted, committed again, +// reset): every reader takes its pages as written at its next asking. Past kKeep pages, every reader takes all of its +// write-watched pages as written instead. +inline void mark(std::uintptr_t from, std::uintptr_t to) { + from &= ~(kPage - 1); + to = (to + kPage - 1) & ~(kPage - 1); + if (from >= to || !contains(from)) return; + State& s = state(); + std::lock_guard lock(s.journal); + const std::uint64_t now = s.asked.fetch_add(1, std::memory_order_acq_rel) + 1; + if ((to - from) / kPage > kKeep) { + s.floor = now; + return; + } + for (std::uintptr_t p = from; p < to; p += kPage) s.written[p] = now; +} + +// A new reader, which has seen everything asked so far (its pages are not known yet: it copies them all first). +inline std::uint64_t open_reader() { + State& s = state(); + std::lock_guard lock(s.journal); + const std::uint64_t id = s.next_reader++; + s.readers[id] = s.asked.load(std::memory_order_acquire); + return id; +} + +inline void close_reader(std::uint64_t reader) { + State& s = state(); + std::lock_guard lock(s.journal); + s.readers.erase(reader); +} + +// `reader` takes over what `other` has not seen yet (a tracker absorbing another's pages). +inline void merge_reader(std::uint64_t reader, std::uint64_t other) { + State& s = state(); + std::lock_guard lock(s.journal); + const auto a = s.readers.find(reader), b = s.readers.find(other); + if (a != s.readers.end() && b != s.readers.end()) a->second = (std::min)(a->second, b->second); +} + +// When the reservation holding `address` was recorded (see ask), or 0 when no recorded one holds it. +inline std::uint64_t born(std::uintptr_t address) { + State& s = state(); + if (!s.count.load(std::memory_order_acquire)) return 0; + std::shared_lock lock(s.mutex); + auto it = s.regions.upper_bound(address); + return it != s.regions.begin() && (--it)->second.end > address ? it->second.born : 0; +} + +// One asking for `reader`: the kernel's written pages of each run (4 KiB aligned, each inside one reservation from +// for_each_in) are taken and cleared, then `dirty(from, to)` gets the pages of the runs written since the reader's +// last asking, the kernel's answer now and the earlier askings of other readers alike, and all of a run whose +// reservation was recorded since then (or is not recorded: reserved again, not added yet). `refused(from, to)` gets +// a run the kernel refused (no longer write-watched: released), for which dirty is not called. Returns the asking's +// number. `runs` is a vector of (from, to) pairs. +template +std::uint64_t ask(std::uint64_t reader, const Runs& runs, Dirty&& dirty, Refused&& refused) { + State& s = state(); + std::lock_guard lock(s.journal); + const auto me = s.readers.find(reader); + const std::uint64_t since = me != s.readers.end() ? me->second : 0; + const std::uint64_t now = s.asked.fetch_add(1, std::memory_order_acq_rel) + 1; + s.refusals.assign(runs.size(), 0); + for (std::size_t r = 0; r < runs.size(); ++r) { + const auto [from, to] = runs[r]; + ULONG_PTR count = (to - from) / kPage; + if (s.found.size() < count) s.found.resize(count); + ULONG granularity = 0; + if (GetWriteWatch(WRITE_WATCH_FLAG_RESET, reinterpret_cast(from), to - from, s.found.data(), &count, + &granularity) != 0) { + s.refusals[r] = 1; + continue; + } + for (ULONG_PTR k = 0; k < count; ++k) + s.written[reinterpret_cast(s.found[k]) & ~(kPage - 1)] = now; + } + for (std::size_t r = 0; r < runs.size(); ++r) { + const auto [from, to] = runs[r]; + if (s.refusals[r]) { + refused(from, to); + continue; + } + // Forgotten before this reader saw it, or a reservation new to it: all of it. Looked up after `now` was + // taken, so a reservation recorded later has a higher number and is all written at the next asking too. + const std::uint64_t reserved = born(from); + if (since < s.floor || !reserved || reserved > since) { + dirty(from, to); + continue; + } + std::uintptr_t run_from = 0, run_to = 0; + for (auto it = s.written.lower_bound(from); it != s.written.end() && it->first < to; ++it) { + if (it->second <= since) continue; + if (it->first != run_to) { + if (run_from != run_to) dirty(run_from, run_to); + run_from = it->first; + } + run_to = it->first + kPage; + } + if (run_from != run_to) dirty(run_from, run_to); + } + if (me != s.readers.end()) me->second = now; + // What every reader has seen goes, once the journal doubled or every kPruneEvery askings (a pruning that dropped + // little, readers being behind then, must not stop the next); past kMaxPages, what is more than kKeep askings old + // goes too. + constexpr std::uint64_t kPruneEvery = 256; + if (s.written.size() > 4096 && (s.written.size() > 2 * s.pruned_size || now - s.pruned_at >= kPruneEvery)) { + s.pruned_at = now; + std::uint64_t seen = now; + for (const auto& [id, last] : s.readers) seen = (std::min)(seen, last); + if (s.written.size() > kMaxPages && now > kKeep && seen < now - kKeep) { + seen = now - kKeep; + s.floor = (std::max)(s.floor, seen); + } + std::erase_if(s.written, [seen](const auto& entry) { return entry.second <= seen; }); + s.pruned_size = s.written.size(); + } + return now; +} + +} // namespace leonida::title_write_watch + +namespace leonida::kernel_writes { + +// The layer's side: makes every watched page in [begin, end) writable. Set once the first shadow exists. +using Opener = void (*)(std::uintptr_t begin, std::uintptr_t end); + +// xmem's side: commits the physical pages mapped in [address, address + bytes) that are still waiting for their first +// touch (rt::xmem::commit_physical_range; pages xmem does not map are left as they are). gta6rt sets it at start. +using Committer = bool (*)(const void* address, std::size_t bytes); + +struct Pin { + std::uintptr_t begin, end; + const OVERLAPPED* overlapped; // null: ends when the call returns + std::uint64_t id; +}; + +struct State { + std::atomic opener{nullptr}; + std::atomic committer{nullptr}; + std::mutex mutex; + host_heap::vector pins; // host_heap: see there + std::uint64_t next_id = 1; + std::atomic count{0}; // pins.size(), read without the lock +}; + +inline State& state() { + static State s; + return s; +} + +inline void set_opener(Opener opener) { state().opener.store(opener, std::memory_order_release); } +inline void set_committer(Committer committer) { state().committer.store(committer, std::memory_order_release); } + +// Whether an overlapped request is still in flight. Its OVERLAPPED is the title's and may be gone by now: a read that +// faults counts as completed (the title doesn't free an OVERLAPPED it is still waiting on). +inline bool overlapped_pending(const OVERLAPPED* overlapped) { + __try { + return overlapped->Internal == static_cast(STATUS_PENDING); + } __except (EXCEPTION_EXECUTE_HANDLER) { + return false; + } +} + +// The pinned ranges overlapping [begin, end), for the layer's refresh. Overlapped pins whose request completed are +// dropped first. +template +void for_each_pin(std::uintptr_t begin, std::uintptr_t end, F&& f) { + State& s = state(); + if (!s.count.load(std::memory_order_acquire)) return; + std::lock_guard lock(s.mutex); + std::erase_if(s.pins, [](const Pin& pin) { return pin.overlapped && !overlapped_pending(pin.overlapped); }); + s.count.store(s.pins.size(), std::memory_order_release); + for (const Pin& pin : s.pins) + if (pin.begin < end && begin < pin.end) f((std::max)(pin.begin, begin), (std::min)(pin.end, end)); +} + +// Before the kernel writes [buffer, buffer + bytes): pins the range (until end_write(), or until `overlapped` completes +// when it is not null) and opens it. Returns the pin's id, 0 when nothing was pinned. +inline std::uint64_t begin_write(const void* buffer, std::size_t bytes, const OVERLAPPED* overlapped) { + State& s = state(); + const Opener opener = s.opener.load(std::memory_order_acquire); + if (!opener || !buffer || !bytes) return 0; + const auto begin = reinterpret_cast(buffer); + std::uint64_t id = 0; + { + std::lock_guard lock(s.mutex); + id = s.next_id++; + s.pins.push_back({begin, begin + bytes, overlapped, id}); + s.count.store(s.pins.size(), std::memory_order_release); + } + // After the pin: a refresh that runs from here on leaves the range writable. + opener(begin, begin + bytes); + return id; +} + +// The call is over: a synchronous pin ends. An overlapped pin whose request is still pending stays until it completes. +inline void end_write(std::uint64_t id, bool pending) { + if (!id) return; + State& s = state(); + std::lock_guard lock(s.mutex); + std::erase_if(s.pins, [id, pending](const Pin& pin) { return pin.id == id && !(pending && pin.overlapped); }); + s.count.store(s.pins.size(), std::memory_order_release); +} + +// Readies [buffer, buffer + bytes) for a retry after ERROR_NOACCESS: commits xmem's pages that wait for their first +// touch (the kernel's write does not fault them in) and opens watched pages again. false: neither side is set. +inline bool reopen(const void* buffer, std::size_t bytes) { + if (!buffer || !bytes) return false; + const State& s = state(); + const Committer committer = s.committer.load(std::memory_order_acquire); + const Opener opener = s.opener.load(std::memory_order_acquire); + if (committer) committer(buffer, bytes); + if (opener) { + const auto begin = reinterpret_cast(buffer); + opener(begin, begin + bytes); + } + return committer || opener; +} + +// The file shims' reads into title memory (file_system.cpp): ReadFile, ReadFileEx and ReadFileScatter with their +// destination pinned and opened first, and retried once if it fails with ERROR_NOACCESS anyway (after committing +// first-touch pages: the title retries such a read forever, `0x314200`, so the retry has to change something). +inline BOOL read_file(HANDLE file, LPVOID buffer, DWORD bytes, LPDWORD read, LPOVERLAPPED overlapped) { + const std::uint64_t pin = begin_write(buffer, bytes, overlapped); + BOOL ok = ::ReadFile(file, buffer, bytes, read, overlapped); + if (!ok && GetLastError() == ERROR_NOACCESS && reopen(buffer, bytes)) + ok = ::ReadFile(file, buffer, bytes, read, overlapped); + const DWORD error = GetLastError(); + end_write(pin, !ok && error == ERROR_IO_PENDING); + SetLastError(error); + return ok; +} + +inline BOOL read_file_ex(HANDLE file, LPVOID buffer, DWORD bytes, LPOVERLAPPED overlapped, + LPOVERLAPPED_COMPLETION_ROUTINE routine) { + const std::uint64_t pin = begin_write(buffer, bytes, overlapped); + BOOL ok = ::ReadFileEx(file, buffer, bytes, overlapped, routine); + if (!ok && GetLastError() == ERROR_NOACCESS && reopen(buffer, bytes)) + ok = ::ReadFileEx(file, buffer, bytes, overlapped, routine); + const DWORD error = GetLastError(); + end_write(pin, bool(ok)); // queued: pending until the OVERLAPPED says otherwise + SetLastError(error); + return ok; +} + +// Each segment is one system page. +inline BOOL read_file_scatter(HANDLE file, FILE_SEGMENT_ELEMENT segments[], DWORD bytes, LPDWORD reserved, + LPOVERLAPPED overlapped) { + SYSTEM_INFO info{}; + GetSystemInfo(&info); + std::vector pins; + const DWORD count = segments ? (bytes + info.dwPageSize - 1) / info.dwPageSize : 0; + for (DWORD i = 0; i < count; ++i) + pins.push_back(begin_write(segments[i].Buffer, info.dwPageSize, overlapped)); + BOOL ok = ::ReadFileScatter(file, segments, bytes, reserved, overlapped); + if (!ok && GetLastError() == ERROR_NOACCESS && count) { + for (DWORD i = 0; i < count; ++i) reopen(segments[i].Buffer, info.dwPageSize); + ok = ::ReadFileScatter(file, segments, bytes, reserved, overlapped); + } + const DWORD error = GetLastError(); + for (const std::uint64_t pin : pins) end_write(pin, bool(ok) || error == ERROR_IO_PENDING); + SetLastError(error); + return ok; +} + +} // namespace leonida::kernel_writes diff --git a/runtime/src/title_texture_memory.h b/runtime/src/title_texture_memory.h new file mode 100644 index 0000000000..d592029c25 --- /dev/null +++ b/runtime/src/title_texture_memory.h @@ -0,0 +1,58 @@ +#pragma once +#include +#include +#include +#include + +namespace leonida { + +// Keep negative probes until the title changes the map or a writer reports this footprint. +class TextureReadability { +public: + template + bool check(std::uint64_t generation, bool cache_failure, Probe probe) { + if (cache_failure && pending_ && !retry_ && generation_ == generation) return false; + generation_ = generation; // snapshot before the probe so a concurrent map change is noticed + retry_ = false; + pending_ = !probe(); + return !pending_; + } + void defer() { pending_ = true; } // mapping disappeared between the probe and the read + void retry() { retry_ = true; } + bool pending() const { return pending_; } +private: + std::uint64_t generation_ = 0; + bool pending_ = false, retry_ = false; +}; + +using TexturePageCommitter = bool (*)(const void*, std::size_t); + +// Check the whole footprint. A committed first page says nothing about a streamed mip farther on. +inline bool texture_memory_readable(std::uintptr_t base, std::uint64_t size, TexturePageCommitter commit = nullptr) { + if (!base || !size || size > (std::numeric_limits::max)() - base) return false; + const auto end = base + size; + for (auto at = base; at < end;) { + MEMORY_BASIC_INFORMATION region{}; + const auto* address = reinterpret_cast(at); + if (!VirtualQuery(address, ®ion, sizeof(region))) return false; + // A persistent Map can name an xmem section whose physical pages commit on first touch. + // Only xmem may commit them. A bare reservation or an inaccessible page must still defer. + if (commit && region.State == MEM_RESERVE && region.Type == MEM_MAPPED) { + if (!commit(address, end - at) || !VirtualQuery(address, ®ion, sizeof(region))) return false; + } + if (region.State != MEM_COMMIT || (region.Protect & PAGE_GUARD)) return false; + switch (region.Protect & 0xff) { + case PAGE_READONLY: case PAGE_READWRITE: case PAGE_WRITECOPY: + case PAGE_EXECUTE_READ: case PAGE_EXECUTE_READWRITE: case PAGE_EXECUTE_WRITECOPY: break; + default: return false; + } + const auto start = reinterpret_cast(region.BaseAddress); + if (at < start || at - start >= region.RegionSize) return false; + const auto available = region.RegionSize - (at - start); + if (available >= end - at) return true; + at += available; + } + return true; +} + +} // namespace leonida diff --git a/runtime/src/title_texture_refresh.h b/runtime/src/title_texture_refresh.h new file mode 100644 index 0000000000..21a88d2796 --- /dev/null +++ b/runtime/src/title_texture_refresh.h @@ -0,0 +1,45 @@ +#pragma once +#include +#include +#include +#include + +namespace leonida { + +using TitleWriteRanges = std::vector>; + +// Sorted, disjoint half-open intervals let each texture find its first possible writer by end address. +inline void merge_title_writes(TitleWriteRanges& writes) { + std::sort(writes.begin(), writes.end()); + std::size_t count = 0; + for (const auto [begin, end] : writes) { + if (begin >= end) continue; + if (count && begin <= writes[count - 1].second) + writes[count - 1].second = std::max(writes[count - 1].second, end); + else + writes[count++] = {begin, end}; + } + writes.resize(count); +} + +inline bool title_write_overlaps(const TitleWriteRanges& writes, std::uintptr_t begin, std::uintptr_t end) { + const auto it = std::upper_bound(writes.begin(), writes.end(), begin, + [](auto address, const auto& range) { return address < range.second; }); + return begin < end && it != writes.end() && it->first < end; +} + +// Poll unmarked textures in placement order. A time or byte limit resumes the next pass at +// the following address. The cursor also survives insertion or removal between passes. +template +void poll_title_textures(Registry& textures, std::uint64_t& cursor, Visit visit, Exhausted exhausted) { + auto it = textures.lower_bound(cursor); + for (auto left = textures.size(); left; --left) { + if (it == textures.end()) it = textures.begin(); + auto& [address, texture] = *it++; + cursor = address + 1; + if (!texture->mapped && !texture->stale) visit(*texture); + if (exhausted()) break; // advance at least one registry entry even if a deadline already passed + } +} + +} // namespace leonida diff --git a/runtime/src/title_va_alias.h b/runtime/src/title_va_alias.h new file mode 100644 index 0000000000..6082681190 --- /dev/null +++ b/runtime/src/title_va_alias.h @@ -0,0 +1,314 @@ +#pragma once +// Buffer addresses in the title's own memory and the console VA a translated shader reaches them by +// (docs/d3d12_vulkan.md section 3.3, "Title-chosen addresses"). +// +// A translated shader computes heap_base + console_va, with heap_base the GPU address arena's device address. The +// layer chooses every console VA it hands out, so they all land in the arena. The title does not always use them: +// - device slot 133 places a buffer at the CPU address of the title's own pages (a user-mode Windows address, far above 4 GiB); +// - the title points V#s and root views at its own memory (a per-frame constant ring, #8862 section 3.5). +// Both are far past the arena, so heap_base + VA reads nothing the layer made. An address inside such a range is +// therefore replaced, wherever the layer can see it, by the console VA of a GPU copy of that range: its arena offset +// when the copy is an arena range (a slot-133 shadow, or a window of the title's pages copied before every +// submission), or its device address minus heap_base (mod 2^64) when it has its own memory (an imported slot-133 +// buffer). Addresses that are not in the title's memory are passed through unchanged. +// +// The table is process-wide, like the title's address space. The device behind it registers two hooks: a resolver +// that makes a GPU copy for an address in the title's memory that has none yet, and a scanner that rewrites the +// buffer V#s of a bound descriptor table before a submission. Without hooks the table only translates what was +// added to it, so it is tested without a GPU (title_va_alias_test). +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace leonida { + +class TitleVaAliases { +public: + // Where the layer saw the address, for the counters. + enum Kind : unsigned { root_view, created_view, table_view, vertex_view, index_view, kind_count }; + static constexpr const char* kKindNames[kind_count] = {"root view", "created view", "table V#", "vertex view", + "index view"}; + + // An address in the title's memory: true, with `shader_va` what a shader must be given (the address itself when + // no copy could be made). False: not the title's memory (an arena VA, a buffer of the layer's). + using Resolver = bool (*)(void* context, std::uint64_t va, std::uint64_t bytes, std::uint64_t& shader_va); + using TableScanner = void (*)(void* context, std::uint64_t table_va, std::uint32_t descriptors); + + // [title_va, title_va + bytes) is reached as [shader_va, shader_va + bytes). A range that overlaps a live one + // replaces it (the title has placed a new buffer over pages it released). False for an empty or wrapping range. + bool add(std::uint64_t title_va, std::uint64_t bytes, std::uint64_t shader_va) { + if (!bytes || title_va > UINT64_MAX - bytes) return false; + std::unique_lock lock(mutex_); + erase_overlapping(title_va, title_va + bytes); + ranges_[title_va] = {title_va + bytes, shader_va}; + count_.store(ranges_.size(), std::memory_order_release); + return true; + } + + // Forgets the range that starts at title_va, if it still maps to shader_va (a newer range at the same VA keeps + // its own entry). + void remove(std::uint64_t title_va, std::uint64_t shader_va) { + std::unique_lock lock(mutex_); + const auto it = ranges_.find(title_va); + if (it != ranges_.end() && it->second.shader_va == shader_va) ranges_.erase(it); + count_.store(ranges_.size(), std::memory_order_release); + } + + // The address a shader must be given for `va` from the ranges added so far: translated inside one, unchanged + // elsewhere. No copy is made here. + std::uint64_t shader_va(std::uint64_t va, std::uint64_t bytes = 1) const { + if (!count_.load(std::memory_order_acquire)) return va; // the common case: no title range at all + std::shared_lock lock(mutex_); + auto it = ranges_.upper_bound(va); + if (it == ranges_.begin()) return va; + --it; + if (va >= it->second.end || bytes > it->second.end - va) return va; + return it->second.shader_va + (va - it->first); + } + + // Debug-only inverse lookup. V#s retain 48 bits, so an import below heap_base wraps. + bool source_of_vsharp(std::uint64_t base, std::uint64_t& title, std::uint64_t& available) const { + constexpr std::uint64_t mask = (1ull << 48) - 1; + std::shared_lock lock(mutex_); + for (const auto& [start, range] : ranges_) { + const auto delta = (base - range.shader_va) & mask; + if (delta >= range.end - start) continue; + title = start + delta; + available = range.end - title; + return true; + } + return false; + } + + // The free span around `va` (not in any range): [lo, hi). A copy made for `va` must stay inside it, so it never + // replaces a range another buffer still uses. + void gap(std::uint64_t va, std::uint64_t& lo, std::uint64_t& hi) const { + std::shared_lock lock(mutex_); + lo = 0; + hi = UINT64_MAX; + auto it = ranges_.upper_bound(va); + if (it != ranges_.end()) hi = it->first; + if (it != ranges_.begin()) lo = std::prev(it)->second.end; + } + + // shader_va, and when `va` is in the title's memory with no copy yet, a copy made by the device's resolver. + // Counted by kind: translated, or in the title's memory and left as it was. + std::uint64_t resolve(std::uint64_t va, std::uint64_t bytes, Kind kind) { + if (!va) return va; + std::uint64_t to = shader_va(va); + if (to != va) { + translated_[kind].fetch_add(1, std::memory_order_relaxed); + return to; + } + Resolver resolver; + void* context; + { + std::lock_guard lock(hook_mutex_); + resolver = resolver_; + context = hook_context_; + } + if (!resolver || !resolver(context, va, bytes, to)) return va; + (to != va ? translated_ : untranslated_)[kind].fetch_add(1, std::memory_order_relaxed); + return to; + } + + // Counts an address that the layer resolves through its buffer index instead (vertex and index views): only + // whether it is in a title range. + void note(std::uint64_t va, Kind kind) { + if (va && shader_va(va) != va) untranslated_[kind].fetch_add(1, std::memory_order_relaxed); + } + + // Before a submission: the device rewrites the buffer V#s of the `descriptors` slots the root signature declares + // for the table at `table_va` (a console VA in one of its shader-visible CBV/SRV/UAV heaps). + void scan_table(std::uint64_t table_va, std::uint32_t descriptors) { + TableScanner scanner; + void* context; + { + std::lock_guard lock(hook_mutex_); + scanner = scanner_; + context = hook_context_; + } + if (scanner) scanner(context, table_va, descriptors); + } + + // The scan's cost, per ExecuteCommandLists that had tables to scan. + void note_scan(std::uint64_t nanoseconds) { + scans_.fetch_add(1, std::memory_order_relaxed); + scan_ns_.fetch_add(nanoseconds, std::memory_order_relaxed); + std::uint64_t seen = scan_max_ns_.load(std::memory_order_relaxed); + while (nanoseconds > seen && !scan_max_ns_.compare_exchange_weak(seen, nanoseconds)) { + } + } + std::uint64_t scans() const { return scans_.load(std::memory_order_relaxed); } + std::uint64_t scan_ns() const { return scan_ns_.load(std::memory_order_relaxed); } + std::uint64_t scan_max_ns() const { return scan_max_ns_.load(std::memory_order_relaxed); } + + // The title's own memory, as the xmem shims hand it out (XMemAlloc, XMemVirtualAlloc, the title's VirtualAlloc): + // only an address in one of these ranges gets a copy. A base anywhere else (the runtime's own heap, a host DLL) + // is left as it was and counted. + void add_title_memory(std::uint64_t base, std::uint64_t bytes) { + if (!base || !bytes || base > UINT64_MAX - bytes) return; + std::uint64_t begin = base, end = base + bytes; + std::unique_lock lock(memory_mutex_); + // A commit inside a reserved range, or two that overlap, are one range. + auto it = memory_.upper_bound(begin); + if (it != memory_.begin() && std::prev(it)->second > begin) --it; + while (it != memory_.end() && it->first < end) { + begin = std::min(begin, it->first); + end = std::max(end, it->second); + it = memory_.erase(it); + } + memory_[begin] = end; + } + void remove_title_memory(std::uint64_t base) { + std::unique_lock lock(memory_mutex_); + memory_.erase(base); + } + // LOCAL DIAGNOSTIC (mem probe): every title range, [begin, end), in address order. + std::vector> title_memory_ranges() const { + std::shared_lock lock(memory_mutex_); + return {memory_.begin(), memory_.end()}; + } + // The title range that holds `va`: [lo, hi). False when none does. + bool title_memory(std::uint64_t va, std::uint64_t& lo, std::uint64_t& hi) const { + std::shared_lock lock(memory_mutex_); + auto it = memory_.upper_bound(va); + if (it == memory_.begin()) return false; + --it; + if (va >= it->second) return false; + lo = it->first; + hi = it->second; + return true; + } + + // A title that gives a descriptor heap its own backing memory (__XMemAllocationHooks__) writes descriptors there + // itself, while shaders read the layer's heap. The layer that keeps that mapping registers a source: before a + // bound table is scanned, it copies the slots the title wrote in its own memory over the layer's copy + // ([real, real + bytes) is the layer heap's CPU memory). Returns how many slots it copied. + using DescriptorSource = std::uint64_t (*)(void* context, std::uint8_t* real, std::size_t bytes); + void set_descriptor_source(void* context, DescriptorSource source) { + std::lock_guard lock(hook_mutex_); + source_context_ = context; + source_ = source; + } + void pull_descriptors(std::uint8_t* real, std::size_t bytes) { + DescriptorSource source; + void* context; + { + std::lock_guard lock(hook_mutex_); + source = source_; + context = source_context_; + } + if (source) pulled_.fetch_add(source(context, real, bytes), std::memory_order_relaxed); + } + std::uint64_t pulled() const { return pulled_.load(std::memory_order_relaxed); } + + // The end of the first title range that overlaps [lo, hi), or 0 when none does. The GPU address arena keeps its + // own allocations out of these ranges, so one number is never both an arena address and a title address. + std::uint64_t title_overlap_end(std::uint64_t lo, std::uint64_t hi) const { + std::shared_lock lock(memory_mutex_); + auto it = memory_.upper_bound(lo); + if (it != memory_.begin() && std::prev(it)->second > lo) return std::prev(it)->second; + if (it != memory_.end() && it->first < hi) return it->second; + return 0; + } + + // A vertex or index buffer view at `va`. On the console every page of the title's memory is GPU memory, so a view + // may name any address: the retail title binds vertex data that lives in its own CPU heap, with no D3D12 resource + // over it. When `va` is in the title's memory the device's maker makes sure a buffer covers it (found with a + // debugger: the address a draw could not resolve was a field of a vertex-buffer object in the title's heap, + // docs/re/answers.md). + using BufferMaker = void (*)(void* context, std::uint64_t va, std::uint64_t bytes); + void set_buffer_maker(void* context, BufferMaker maker) { + std::lock_guard lock(hook_mutex_); + maker_context_ = context; + maker_ = maker; + } + void clear_buffer_maker(void* context) { + std::lock_guard lock(hook_mutex_); + if (maker_context_ != context) return; + maker_context_ = nullptr; + maker_ = nullptr; + } + void want_buffer(std::uint64_t va, std::uint64_t bytes) { + if (!va) return; + std::uint64_t lo = 0, hi = 0; + if (!title_memory(va, lo, hi)) return; + BufferMaker maker; + void* context; + { + std::lock_guard lock(hook_mutex_); + maker = maker_; + context = maker_context_; + } + if (maker) maker(context, va, bytes); + } + + // The first device to register keeps the hooks until it clears them. + void set_hooks(void* context, Resolver resolver, TableScanner scanner) { + std::lock_guard lock(hook_mutex_); + if (hook_context_) return; + hook_context_ = context; + resolver_ = resolver; + scanner_ = scanner; + } + void clear_hooks(void* context) { + std::lock_guard lock(hook_mutex_); + if (hook_context_ != context) return; + hook_context_ = nullptr; + resolver_ = nullptr; + scanner_ = nullptr; + } + + std::size_t size() const { return count_.load(std::memory_order_acquire); } + std::uint64_t translated(Kind kind) const { return translated_[kind].load(std::memory_order_relaxed); } + std::uint64_t untranslated(Kind kind) const { return untranslated_[kind].load(std::memory_order_relaxed); } + +private: + struct Range { + std::uint64_t end; // exclusive + std::uint64_t shader_va; // what the range's first byte becomes + }; + + void erase_overlapping(std::uint64_t begin, std::uint64_t end) { + auto it = ranges_.lower_bound(begin); + if (it != ranges_.begin()) { + auto previous = std::prev(it); + if (previous->second.end > begin) it = previous; + } + while (it != ranges_.end() && it->first < end) it = ranges_.erase(it); + } + + mutable std::shared_mutex mutex_; + std::map ranges_; // by title VA + std::atomic count_{0}; + std::mutex hook_mutex_; + void* hook_context_ = nullptr; + void* maker_context_ = nullptr; + BufferMaker maker_ = nullptr; + Resolver resolver_ = nullptr; + TableScanner scanner_ = nullptr; + void* source_context_ = nullptr; + DescriptorSource source_ = nullptr; + std::atomic pulled_{0}; + std::array, kind_count> translated_{}; + std::array, kind_count> untranslated_{}; + std::atomic scans_{0}, scan_ns_{0}, scan_max_ns_{0}; + mutable std::shared_mutex memory_mutex_; + std::map memory_; // the title's memory: base -> end +}; + +// The process's table: the device's title ranges and hooks, read by the command lists and descriptor writers. +inline TitleVaAliases& title_va_aliases() { + static TitleVaAliases aliases; + return aliases; +} + +} // namespace leonida diff --git a/runtime/src/tls_host.cpp b/runtime/src/tls_host.cpp index ab234cbd97..6cf5e70ae4 100644 --- a/runtime/src/tls_host.cpp +++ b/runtime/src/tls_host.cpp @@ -5,6 +5,12 @@ // __declspec(thread) access in mapped code reads a valid TEB slot. The anchor itself is never used; the loader saves // and restores the helper's own block, so the helper's CRT TLS state is not disturbed. // +// One more clone, leonida_tls_host__home.dll, is made at process start by reserve_tls_index0: its TLS directory +// is pointed at gta6rt_tls_home_template below, filled with a copy of the runtime EXE's template, and the runtime EXE +// moves its TLS from index 0 (which Windows gave it) to that clone's index, so a mapped executable can take index 0. +// That clone stays loaded until the process ends, and its slot then holds the runtime's live TLS, so nothing in this +// DLL may read or write its own TLS (gta6rt_tls_host_keep is never called). +// // The Windows loader also calls this DLL's DllMain with DLL_THREAD_ATTACH on every new thread (after it has built that // thread's TLS array) and with DLL_THREAD_DETACH when a thread exits (before it frees the array). The loader registers // a callback here so it can give each new thread its own copy of the mapped image's TLS, and put this DLL's block back @@ -26,6 +32,13 @@ void* volatile g_thread_event = nullptr; // the linker without making DllMain touch TLS during thread attach/detach. extern "C" __declspec(dllexport) void gta6rt_tls_host_keep() { g_tls_host_anchor = 1; } +// The home clone's TLS template (pe_loader.cpp, make_home_clone_image): zeros here, the runtime EXE's template in the +// clone's file. 16 KiB: gta6rt.exe's own TLS template was 1398 bytes when measured; the loader refuses the move when +// the EXE's TLS does not fit. Each thread gets a block of the EXE's size, not of this array's. Clones of this DLL for +// mapped DLLs keep the 514-byte TLS directory and do not use the array. +extern "C" __declspec(dllexport) const unsigned char gta6rt_tls_home_template[16384] = {}; +extern "C" __declspec(dllexport) const unsigned int gta6rt_tls_home_template_size = sizeof(gta6rt_tls_home_template); + // Called by the loader. `fn` runs inside DllMain (under the Windows loader lock) for DLL_THREAD_ATTACH and // DLL_THREAD_DETACH; nullptr stops the calls. extern "C" __declspec(dllexport) void gta6rt_tls_host_set_thread_event(ThreadEventFn fn) { diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index ab6786a518..2230732353 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -17,11 +17,13 @@ #include "statistics_sum_spirv.h" #include "vulkan13_features.h" #include "vulkan_depth24.h" +#include "vulkan_title_image_pool.h" #include "vulkan_indirect_dispatch_count.h" #include "vulkan_scratch.h" #include "vulkan_replay.h" #include "queue_families.h" #include "resource_tiling.h" +#include "pipeline_profile.h" #include "xdxr_build.h" #include @@ -46,6 +48,15 @@ namespace leonida { +// Which check of the queue's replay refused a batch ("ExecuteCommandLists failed: unsupported"), by source line, +// the first time each one does. The batch is then not submitted at all. +inline ReplayResult queue_unsupported(int line) { + static std::atomic seen[4096]; + if (line < 0 || line >= 4096 || !seen[line].exchange(true, std::memory_order_relaxed)) + std::fprintf(stderr, "[rt] d3d12: queue replay refused a batch at vulkan_backend.h:%d\n", line); + return ReplayResult::unsupported; +} + // A CPU-written Vulkan-address instance pointer array, kept until the submission that builds with it completes. // Completed stages are pooled per queue and reused, so a per-frame TLAS build does not allocate memory each frame. struct KhrInstanceStage { @@ -105,7 +116,7 @@ struct VulkanDeviceFunctions { X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) \ X(vkCmdSetBlendConstants) X(vkCmdDraw) \ X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) X(vkGetImageSparseMemoryRequirements) \ - X(vkCreatePipelineCache) X(vkDestroyPipelineCache) \ + X(vkCreatePipelineCache) X(vkDestroyPipelineCache) X(vkGetPipelineCacheData) X(vkMergePipelineCaches) \ X(vkCreateEvent) X(vkDestroyEvent) X(vkResetEvent) X(vkCmdSetEvent) X(vkCmdWaitEvents) X(vkCmdDrawMeshTasksEXT) \ X(vkCreateRenderPass2) X(vkDestroyRenderPass) X(vkCreateFramebuffer) X(vkDestroyFramebuffer) \ X(vkCmdBeginRenderPass) X(vkCmdEndRenderPass) @@ -435,6 +446,7 @@ class DeferredDeletionQueue { image_view, image, sparse_resource, + pooled_title_image, buffer, device_memory, acceleration_structure, @@ -512,6 +524,9 @@ class DeferredDeletionQueue { case Kind::image: vk.vkDestroyImage(device, reinterpret_cast(item.handle), nullptr); break; + case Kind::pooled_title_image: + delete reinterpret_cast(item.handle); + break; case Kind::sparse_resource: // Releases the resource and its page backing together after outstanding submissions. delete reinterpret_cast*>(item.handle); @@ -601,6 +616,8 @@ class FenceWaitDispatcher { FenceWaitDispatcher(const FenceWaitDispatcher&) = delete; FenceWaitDispatcher& operator=(const FenceWaitDispatcher&) = delete; + void set_device_fault(DeviceFaultDiagnostics* diagnostics) { diagnostics_ = diagnostics; } + void set_signal_event_fn(SignalEventFn fn) { std::lock_guard lock(mutex_); signal_event_ = fn; @@ -777,7 +794,8 @@ class FenceWaitDispatcher { VkSemaphoreSignalInfo si{VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO}; si.semaphore = wakeup_sem_; si.value = next; - vk_.vkSignalSemaphore(device_, &si); + DeviceFaultDiagnostics::observe(diagnostics_, vk_.vkSignalSemaphore(device_, &si), + "vkSignalSemaphore (fence wakeup)"); } void run() { @@ -814,7 +832,8 @@ class FenceWaitDispatcher { // is pending (d3d12_queue_wait_timeout's _Exit, or quitting with a fence outstanding) never finishes // exiting, and TerminateProcess cannot end it either. A timeout returns here and the loop re-arms the // same wait; completions still wake it at once through the ANY wait. - const VkResult res = vk_.vkWaitSemaphores(device_, &wi, kWaitSliceNs); + const VkResult res = DeviceFaultDiagnostics::observe( + diagnostics_, vk_.vkWaitSemaphores(device_, &wi, kWaitSliceNs), "vkWaitSemaphores (fence dispatcher)"); lock.lock(); waiting_ = false; @@ -835,7 +854,9 @@ class FenceWaitDispatcher { std::size_t write = 0; for (std::size_t i = 0; i < pending_.size(); ++i) { std::uint64_t done = 0; - const VkResult cr = vk_.vkGetSemaphoreCounterValue(device_, pending_[i].semaphore, &done); + const VkResult cr = DeviceFaultDiagnostics::observe( + diagnostics_, vk_.vkGetSemaphoreCounterValue(device_, pending_[i].semaphore, &done), + "vkGetSemaphoreCounterValue (fence dispatcher)"); if (cr == VK_ERROR_DEVICE_LOST) { lost = true; for (std::size_t j = i; j < pending_.size(); ++j) ready.push_back(std::move(pending_[j])); @@ -867,6 +888,7 @@ class FenceWaitDispatcher { VkDevice device_; const VulkanDeviceFunctions& vk_; std::atomic& device_lost_; + DeviceFaultDiagnostics* diagnostics_ = nullptr; // configured before the dispatcher starts SignalEventFn signal_event_ = nullptr; VkSemaphore wakeup_sem_ = VK_NULL_HANDLE; std::uint64_t wakeup_val_ = 0; @@ -1106,6 +1128,7 @@ class VulkanContext { } ~VulkanContext() { + progress_watch_ = {}; // stop before queues, timelines or diagnostic state go away fence_dispatcher_.reset(); deletion_queue_.drain(UINT64_MAX, device_, vk); for (const auto& [key, framebuffer] : resolve_framebuffers_) @@ -1118,6 +1141,22 @@ class VulkanContext { VulkanContext& operator=(const VulkanContext&) = delete; bool loaded() const { return loaded_; } + + void configure_device_fault(PFN_vkGetDeviceProcAddr get, DeviceFaultExtensions enabled) { + device_fault_ = std::make_unique(get, device_, enabled); + if (fence_dispatcher_) fence_dispatcher_->set_device_fault(device_fault_.get()); + if (loaded_) progress_watch_ = std::jthread([this](std::stop_token stop) { watch_queue_progress(stop); }); + } + + void add_diagnostic_queue(VkQueue queue) { + if (device_fault_) device_fault_->add_queue(queue); + } + + DeviceFaultDiagnostics* device_fault() const { return device_fault_.get(); } + + VkResult observe_result(VkResult result, const char* operation) const noexcept { + return DeviceFaultDiagnostics::observe(device_fault_.get(), result, operation); + } void configure_predication(PFN_vkGetDeviceProcAddr get, const VkPhysicalDeviceMemoryProperties& memory, VkDeviceSize max_range, std::uint32_t family) { std::unique_lock lock(resource_mutex_); @@ -1155,6 +1194,11 @@ class VulkanContext { std::unique_lock lock(resource_mutex_); set_resource_locked(id, binding); } + // Whether `va` is in a buffer this context knows by VA (the index buffer_at searches). + bool knows_buffer_va(std::uint64_t va, std::uint64_t bytes = 1) { + std::shared_lock lock(resource_mutex_); + return buffer_vas_.covers(va, bytes); + } void add_resource(ResourceId id, const ResourceBinding& binding, VkImageLayout current_layout) { std::unique_lock rlock(resource_mutex_); set_resource_locked(id, binding); @@ -1293,6 +1337,14 @@ class VulkanContext { replay_.depth_range_unrestricted = enabled; } + // 0, 1, 2, ... as 32-bit indices, for non-indexed quad lists (ReplayFunctions::quad_indices). + void set_quad_indices(VkBuffer buffer, VkDeviceSize offset, std::uint32_t count) { + std::unique_lock lock(resource_mutex_); + replay_.quad_indices = buffer; + replay_.quad_indices_offset = offset; + replay_.quad_index_count = count; + } + // Physical-device COLOR_ATTACHMENT format check for reinterpreted UAV clears. void set_color_attachment_format(std::function check) { std::unique_lock lock(resource_mutex_); @@ -1304,24 +1356,77 @@ class VulkanContext { } // Pipelines are registered by an opaque id (the PSO object) for as long as the PSO lives. - void add_pipeline(std::uintptr_t id, const ComputePipeline& pipeline) { + void add_pipeline(std::uintptr_t id, const ComputePipeline& pipeline, const char* shader = nullptr) { std::unique_lock lock(resource_mutex_); pipelines_[id] = pipeline; + if (shader && device_fault_) device_fault_->pipeline_names[id] = {shader}; } void remove_pipeline(std::uintptr_t id) { std::unique_lock lock(resource_mutex_); pipelines_.erase(id); graphics_pipelines_.erase(id); + if (device_fault_) device_fault_->pipeline_names.erase(id); } - void add_graphics_pipeline(std::uintptr_t id, const GraphicsPipeline& pipeline) { + void add_graphics_pipeline(std::uintptr_t id, const GraphicsPipeline& pipeline, + const CheckpointShaders* shaders = nullptr) { std::unique_lock lock(resource_mutex_); graphics_pipelines_[id] = pipeline; + if (shaders && device_fault_) device_fault_->pipeline_names[id] = *shaders; } // Configure before queue creation, when the selected queue family supports compute. void set_occlusion_resolve_memory(const VkPhysicalDeviceMemoryProperties& memory) { occlusion_resolve_memory_ = memory; } + struct HostTextureStats { std::uint64_t copies = 0, waits = 0; }; + HostTextureStats host_texture_stats() { + std::lock_guard lock(submit_mutex_); + return host_texture_stats_; + } + + // CPU writes to a title texture have no application fence. Prevent another queue from + // claiming a new layout or submitting work between the completion check and the host copy. + // An unsatisfied console Wait lives in QueueHolds, outside the Vulkan queues. + template + VkResult write_host_texture(ResourceId id, std::uint32_t subresource, Copy&& copy) { + std::lock_guard layout_lock(tracker_mutex_); + std::lock_guard queue_lock(submit_mutex_); + if (tracker_.layout(id, subresource) != VK_IMAGE_LAYOUT_GENERAL) return VK_NOT_READY; + if (image_work_pending_) { + ++host_texture_stats_.waits; + const auto result = observe_result(vk.vkDeviceWaitIdle(device_), "vkDeviceWaitIdle (title texture upload)"); + if (result != VK_SUCCESS) return result; + image_work_pending_ = false; + } + if (!copy()) return VK_ERROR_UNKNOWN; + ++host_texture_stats_.copies; + return VK_SUCCESS; + } + + // A complete CPU-side replacement of these color subresources. Serialize with replay and + // present while recording the old layouts, finishing prior reads and publishing the copy. + template + VkResult write_staged_title_image(ResourceId id, const VkImageSubresourceRange& range, Copy&& copy) { + std::lock_guard layout_lock(tracker_mutex_); + std::lock_guard queue_lock(submit_mutex_); + LayoutPieces pieces; + if (!tracker_.pieces(id, range, pieces) || pieces.empty()) return VK_ERROR_UNKNOWN; + if (image_work_pending_) { + const auto r = observe_result(vk.vkDeviceWaitIdle(device_), "vkDeviceWaitIdle (title staging)"); + if (r != VK_SUCCESS) return r; + image_work_pending_ = false; + } + const auto r = observe_result(copy(replay_, pieces), "title staging upload"); + if (r == VK_SUCCESS) { + for (const auto& p : pieces) + if (p.layout == VK_IMAGE_LAYOUT_UNDEFINED) tracker_.set(id, p.range, VK_IMAGE_LAYOUT_GENERAL); + } + return r; + } + + // Present and probe submissions have their own fences, outside the queue retirement timelines. + void note_image_work_locked() { image_work_pending_ = true; } + // For tests and traces. VkImageLayout layout(ResourceId id, std::uint32_t subresource) { std::lock_guard lock(tracker_mutex_); @@ -1408,6 +1513,30 @@ class VulkanContext { // and records what the set needs first. When it fails, nothing of that call is executed. void set_transfer_only_family(std::uint32_t family) { transfer_only_family_ = family; } + // `before` is called at the start of every submission of command lists (a held batch: when it is released), + // before any lock here is taken: the device re-copies its slot-133 shadow buffers from the title's pages there. + // Set once, before the first queue exists. + using InputProbe = std::function, std::uint64_t, const char*)>; + void set_input_probe(InputProbe probe) { input_probe_ = std::move(probe); } + bool diagnostic_buffer(std::uint64_t va, std::uint64_t& host, std::uint64_t& room) { + std::shared_lock lock(resource_mutex_); + BufferVaIndex::Hit hit{}; + if (!buffer_vas_.find(va, hit)) return false; + const auto* b = resolve(hit.id); + if (!b || va - b->va >= b->size) return false; + const auto offset = va - b->va; + host = b->host ? reinterpret_cast(b->host + offset) : 0; + room = b->size - offset; + return true; + } + const char* diagnostic_compute_name(std::uintptr_t id) { + std::shared_lock lock(resource_mutex_); + if (!device_fault_) return nullptr; + const auto it = device_fault_->pipeline_names.find(id); + return it == device_fault_->pipeline_names.end() ? nullptr : it->second[0]; + } + void set_before_execute(std::function before) { before_execute_ = std::move(before); } + void set_bindless_prepare(std::function prepare) { std::unique_lock lock(resource_mutex_); bindless_prepare_ = std::move(prepare); @@ -1418,7 +1547,8 @@ class VulkanContext { void enable_depth24(PFN_vkGetDeviceProcAddr get, Depth24Converter::Allocate allocate, std::uint64_t max_storage_range = 1u << 27) { std::unique_lock lock(resource_mutex_); - depth24_ = std::make_unique(get, device_, std::move(allocate), max_storage_range); + depth24_ = std::make_unique(get, device_, std::move(allocate), max_storage_range, + device_fault_.get()); if (!depth24_->loaded()) { depth24_.reset(); return; @@ -1433,7 +1563,7 @@ class VulkanContext { // `allocate`. Without this such a copy is refused as unsupported. void enable_copy_scratch(PFN_vkGetDeviceProcAddr get, ScratchBuffers::Allocate allocate) { std::unique_lock lock(resource_mutex_); - scratch_ = std::make_unique(get, device_, std::move(allocate)); + scratch_ = std::make_unique(get, device_, std::move(allocate), device_fault_.get()); if (!scratch_->loaded()) scratch_.reset(); } @@ -1497,7 +1627,8 @@ class VulkanContext { wait.semaphoreCount = std::uint32_t(semaphores.size()); wait.pSemaphores = semaphores.data(); wait.pValues = values.data(); - vk.vkWaitSemaphores(device_, &wait, UINT64_MAX); // outside submit_mutex_: a signal may need it + // Outside submit_mutex_: a signal may need it. + observe_result(vk.vkWaitSemaphores(device_, &wait, UINT64_MAX), "vkWaitSemaphores (retirement)"); } return completed_retire_ticket(); } @@ -1515,7 +1646,8 @@ class VulkanContext { if (is_device_lost()) return 0; ticket = retire_tickets_.completed([this, &lost](VkSemaphore semaphore, std::uint64_t value) { std::uint64_t done = 0; - const VkResult result = vk.vkGetSemaphoreCounterValue(device_, semaphore, &done); + const VkResult result = observe_result(vk.vkGetSemaphoreCounterValue(device_, semaphore, &done), + "vkGetSemaphoreCounterValue (retirement)"); if (result == VK_ERROR_DEVICE_LOST) lost = true; return result == VK_SUCCESS && done >= value; }); @@ -1536,6 +1668,7 @@ class VulkanContext { void record_submit_locked(VkSemaphore progress, std::uint64_t value) { const auto ticket = submitted_ticket_.fetch_add(1, std::memory_order_acq_rel) + 1; retire_tickets_.record(ticket, progress, value); + note_image_work_locked(); } void retire_queue_idle_locked(VkSemaphore progress) { retire_tickets_.queue_idle(progress); @@ -1605,7 +1738,11 @@ class VulkanContext { const ResourceBinding* resolve(ResourceId id) const { const auto it = resources_.find(id); - return it == resources_.end() ? nullptr : &it->second; + if (it == resources_.end()) return nullptr; + if (auto* memory = it->second.deferred_memory; memory && !memory->ensure()) return nullptr; + if (auto* seen = it->second.replay_seen; seen && !seen->load(std::memory_order_relaxed)) + seen->store(true, std::memory_order_relaxed); + return &it->second; } // Called from prepare; protected by views_mutex_ so concurrent shared_lock readers are safe. @@ -1693,6 +1830,52 @@ class VulkanContext { return framebuffer; } + std::uint64_t poll_retirement_locked(VkResult& result) { + return retire_tickets_.completed([&](VkSemaphore semaphore, std::uint64_t value) { + std::uint64_t done = 0; + result = observe_result(vk.vkGetSemaphoreCounterValue(device_, semaphore, &done), + "vkGetSemaphoreCounterValue (retirement)"); + return result == VK_SUCCESS && done >= value; + }); + } + + void watch_queue_progress(std::stop_token stop) { + using Watch = SubmissionProgressWatch; + Watch watch; + std::uint64_t retired = 0; + std::mutex timer_mutex; + std::condition_variable_any timer; + std::unique_lock timer_lock(timer_mutex); + while (!stop.stop_requested()) { + timer.wait_for(timer_lock, stop, std::chrono::seconds(1), [] { return false; }); + if (stop.stop_requested() || is_device_lost()) break; + auto state = Watch::State::submit_lock_busy; + VkResult result = VK_SUCCESS; + std::uint64_t submitted; + { + // Keep queue timelines alive as in completed_retire_ticket(). A submit or idle wait + // blocked inside the driver can hold this mutex indefinitely. + std::unique_lock lock(submit_mutex_, std::try_to_lock); + submitted = submitted_retire_ticket(); + if (lock.owns_lock()) { + if (is_device_lost()) break; + retired = poll_retirement_locked(result); + state = retired < submitted ? Watch::State::pending : Watch::State::idle; + } + } + if (result == VK_ERROR_DEVICE_LOST) { + mark_device_lost(); + break; + } + // A failed counter query does not measure GPU progress. + if (result != VK_SUCCESS) state = Watch::State::idle; + if (watch.sample(state, retired, Watch::Clock::now())) + device_fault_->report_stall(state == Watch::State::pending ? "queue retirement has not advanced" + : "could not sample the submit lock", + submitted, retired); + } + } + VkDevice device_; bool loaded_ = false; bool ray_tracing_ = false; @@ -1702,9 +1885,13 @@ class VulkanContext { alignas(64) std::mutex tracker_mutex_; alignas(64) std::mutex views_mutex_; alignas(64) std::mutex submit_mutex_; + bool image_work_pending_ = false; // under submit_mutex_ + HostTextureStats host_texture_stats_; // under submit_mutex_ RetireTickets retire_tickets_; std::atomic submitted_ticket_{0}; DeferredDeletionQueue deletion_queue_; + std::unique_ptr device_fault_; + std::jthread progress_watch_; std::unique_ptr fence_dispatcher_; QueueHolds holds_; std::unordered_map resources_; @@ -1732,6 +1919,8 @@ class VulkanContext { std::map, VkRenderPass> resolve_passes_; std::map, VkFramebuffer> resolve_framebuffers_; + std::function before_execute_; + InputProbe input_probe_; std::function bindless_prepare_; std::function bindless_current_; bool bindless_upload_pending_ = false; // tracker_mutex_ @@ -1784,7 +1973,8 @@ class VulkanFence { std::uint64_t completed() const { if (context_.is_device_lost()) return UINT64_MAX; std::uint64_t value = 0; - const VkResult result = context_.vk.vkGetSemaphoreCounterValue(context_.device(), semaphore_, &value); + const VkResult result = context_.observe_result( + context_.vk.vkGetSemaphoreCounterValue(context_.device(), semaphore_, &value), "vkGetSemaphoreCounterValue"); if (result == VK_ERROR_DEVICE_LOST) { context_.mark_device_lost(); return UINT64_MAX; @@ -1800,13 +1990,15 @@ class VulkanFence { // it marks the context lost on a query error and prevents the dispatcher from waking. if (context_.is_device_lost()) return false; std::uint64_t current = 0; - if (context_.vk.vkGetSemaphoreCounterValue(context_.device(), semaphore_, ¤t) == VK_SUCCESS && + if (context_.observe_result(context_.vk.vkGetSemaphoreCounterValue(context_.device(), semaphore_, ¤t), + "vkGetSemaphoreCounterValue") == VK_SUCCESS && value <= current) return false; VkSemaphoreSignalInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO}; info.semaphore = semaphore_; info.value = value; - const VkResult result = context_.vk.vkSignalSemaphore(context_.device(), &info); + const VkResult result = context_.observe_result(context_.vk.vkSignalSemaphore(context_.device(), &info), + "vkSignalSemaphore"); if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost(); if (result != VK_SUCCESS) return false; context_.holds().signaled(semaphore_, value); // queues that held a batch for this value run it now @@ -1820,7 +2012,8 @@ class VulkanFence { info.semaphoreCount = 1; info.pSemaphores = &semaphore_; info.pValues = &value; - const VkResult result = context_.vk.vkWaitSemaphores(context_.device(), &info, timeout_ns); + const VkResult result = context_.observe_result( + context_.vk.vkWaitSemaphores(context_.device(), &info, timeout_ns), "vkWaitSemaphores"); if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost(); return result == VK_SUCCESS; } @@ -1893,7 +2086,7 @@ class VulkanQueue : private QueueHolds::Holder { if (queue_) { std::lock_guard lock(context_.submit_mutex()); for (; open_labels_; --open_labels_) context_.labels_.queue_end(queue_); - const VkResult idle_result = vk.vkQueueWaitIdle(queue_); + const VkResult idle_result = context_.observe_result(vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle"); if (idle_result == VK_SUCCESS) { if (progress_) context_.retire_queue_idle_locked(progress_); } else { @@ -2014,18 +2207,21 @@ class VulkanQueue : private QueueHolds::Holder { using PinFn = std::function()>; ReplayResult execute(std::span lists, const PinFn& pin = {}) { + auto* diagnostics = context_.device_fault(); + const auto execute_call = diagnostics ? diagnostics->next_execute_call() : 0; ReplayResult result = ReplayResult::success; bool held = false; std::vector> retired; // destroyed after state_mutex_ is released { std::lock_guard state(state_mutex_); if (!must_hold()) { - result = execute_now(lists); + result = execute_now(lists, execute_call); } else if (context_.is_device_lost()) { - result = ReplayResult::unsupported; + result = queue_unsupported(__LINE__); } else { Deferred op; op.kind = Deferred::Kind::batch; + op.execute_call = execute_call; op.lists.reserve(lists.size()); for (const CommandList* list : lists) op.lists.push_back(*list); if (pin) op.pins.push_back(pin()); @@ -2104,7 +2300,7 @@ class VulkanQueue : private QueueHolds::Holder { bool idle() { std::lock_guard lock(context_.submit_mutex()); - return context_.vk.vkQueueWaitIdle(queue_) == VK_SUCCESS; + return context_.observe_result(context_.vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle") == VK_SUCCESS; } private: @@ -2190,11 +2386,11 @@ class VulkanQueue : private QueueHolds::Holder { !funcs.vkAllocateMemory || !funcs.vkFreeMemory || !funcs.vkBindBufferMemory || !funcs.vkMapMemory || !funcs.vkUnmapMemory || !funcs.vkGetBufferDeviceAddress || !vk.host_at || !vk.buffer_at || !build.instance_count) - return ReplayResult::unsupported; + return queue_unsupported(__LINE__); const std::uint64_t bytes = 8ull * build.instance_count; const std::uint8_t* guest = nullptr; const HostReadStatus status = vk.host_at(build.instances_va, bytes, guest); - if (status == HostReadStatus::not_cpu_written) return ReplayResult::unsupported; + if (status == HostReadStatus::not_cpu_written) return queue_unsupported(__LINE__); if (status != HostReadStatus::ok) return ReplayResult::invalid_copy; KhrInstanceStage stage{}; @@ -2217,7 +2413,7 @@ class VulkanQueue : private QueueHolds::Holder { info.usage = VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR; if (funcs.vkCreateBuffer(context_.device(), &info, nullptr, &stage.buffer) != VK_SUCCESS) - return ReplayResult::unsupported; + return queue_unsupported(__LINE__); VkMemoryRequirements requirements{}; funcs.vkGetBufferMemoryRequirements(context_.device(), stage.buffer, &requirements); const auto& memory = context_.occlusion_resolve_memory_; @@ -2233,7 +2429,7 @@ class VulkanQueue : private QueueHolds::Holder { } if (type == memory.memoryTypeCount) { discard(); - return ReplayResult::unsupported; + return queue_unsupported(__LINE__); } VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO}; flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; @@ -2243,7 +2439,7 @@ class VulkanQueue : private QueueHolds::Holder { if (funcs.vkAllocateMemory(context_.device(), &allocation, nullptr, &stage.memory) != VK_SUCCESS || funcs.vkBindBufferMemory(context_.device(), stage.buffer, stage.memory, 0) != VK_SUCCESS) { discard(); - return ReplayResult::unsupported; + return queue_unsupported(__LINE__); } stage.size = bytes; } @@ -2251,7 +2447,7 @@ class VulkanQueue : private QueueHolds::Holder { void* mapped = nullptr; if (funcs.vkMapMemory(context_.device(), stage.memory, 0, bytes, 0, &mapped) != VK_SUCCESS) { discard(); - return ReplayResult::unsupported; + return queue_unsupported(__LINE__); } // Validate and translate in one pass straight into the staging buffer; no second vector of addresses. for (std::uint32_t i = 0; i < build.instance_count; ++i) { @@ -2277,21 +2473,25 @@ class VulkanQueue : private QueueHolds::Holder { stage.address = funcs.vkGetBufferDeviceAddress(context_.device(), &device_address); if (!stage.address) { discard(); - return ReplayResult::unsupported; + return queue_unsupported(__LINE__); } stages.push_back(std::move(stage)); address = stages.back().address; return ReplayResult::success; } - ReplayResult execute_now(std::span lists) { - if (context_.is_device_lost() || !wait_for_room()) return ReplayResult::unsupported; + ReplayResult execute_now(std::span lists, std::uint64_t execute_call) { + if (context_.is_device_lost() || !wait_for_room()) return queue_unsupported(__LINE__); + if (context_.before_execute_) context_.before_execute_(); + if (context_.input_probe_) + context_.input_probe_(lists, execute_call, kind_ == QueueKind::direct ? "direct" : + kind_ == QueueKind::compute ? "compute" : "copy"); if (kind_ != QueueKind::direct) for (const auto* list : lists) for (const auto& command : list->commands()) if (std::holds_alternative(command) || std::holds_alternative(command)) - return ReplayResult::unsupported; + return queue_unsupported(__LINE__); VkCommandBuffer command_buffer = VK_NULL_HANDLE; struct KhrGuard { VulkanQueue* queue; @@ -2337,6 +2537,8 @@ class VulkanQueue : private QueueHolds::Holder { // use only the first lists.size() entries, so stale entries are never prepared, queried or emitted. if (prepared.size() < lists.size()) prepared.resize(lists.size()); ReplayFunctions replay = context_.replay_; + unsigned mesh_draws = 0; + if (pipeline_profile::enabled()) replay.mesh_draw_count = &mesh_draws; replay.queue_stages = kind_ == QueueKind::copy ? detail::queue_stages_copy : kind_ == QueueKind::compute ? detail::queue_stages_compute : 0; @@ -2359,12 +2561,12 @@ class VulkanQueue : private QueueHolds::Holder { std::unique_ptr counted_batch; if (captures) { if (kind_ == QueueKind::copy || !context_.predicate_reducer_ || family_ != context_.predicate_family_) - return ReplayResult::unsupported; + return queue_unsupported(__LINE__); // The helper's lazy pipeline is shared by queues. Serialize preparation with the tracker lock, // retaining main's resource -> tracker -> submit lock order through emit and submission. if (!tracker_lock.owns_lock()) tracker_lock.lock(); batch = context_.predicate_reducer_->batch(captures); - if (!batch) return ReplayResult::unsupported; + if (!batch) return queue_unsupported(__LINE__); replay.prepare_predicate = [&](VkBuffer buffer, VkDeviceSize offset, PredicateCapture& out) { return batch->prepare(buffer, offset, out); }; @@ -2449,7 +2651,7 @@ class VulkanQueue : private QueueHolds::Holder { if (result != ReplayResult::success) return result; if (prepared[i].segment_count > UINT32_MAX - segments || prepared[i].statistics_segment_count > UINT32_MAX - statistics_segments) - return ReplayResult::unsupported; + return queue_unsupported(__LINE__); segments += prepared[i].segment_count; statistics_segments += prepared[i].statistics_segment_count; has_queries = has_queries || !prepared[i].queries.empty(); @@ -2469,12 +2671,12 @@ class VulkanQueue : private QueueHolds::Holder { return vk.vkCreateQueryPool(out->device, &info, nullptr, &out->pool) == VK_SUCCESS; }; std::shared_ptr physical, statistics; - if (segments && !segment_pool(VK_QUERY_TYPE_OCCLUSION, segments, physical)) return ReplayResult::unsupported; + if (segments && !segment_pool(VK_QUERY_TYPE_OCCLUSION, segments, physical)) return queue_unsupported(__LINE__); // Without the compute helper a split query could not be summed: leave statistics queries whole, as before // (QueryReplay::plan refuses a list whose statistics query holds a mesh draw then). if (statistics_segments && can_resolve_occlusion) { if (!segment_pool(VK_QUERY_TYPE_PIPELINE_STATISTICS, statistics_segments, statistics)) - return ReplayResult::unsupported; + return queue_unsupported(__LINE__); for (const auto& list : prepared) statistics->mesh.insert(statistics->mesh.end(), list.statistics_mesh.begin(), list.statistics_mesh.end()); @@ -2489,7 +2691,7 @@ class VulkanQueue : private QueueHolds::Holder { info.pipelineStatistics = kMeshStatisticsFlags; if (context_.vk.vkCreateQueryPool(statistics->device, &info, nullptr, &statistics->mesh_pool) != VK_SUCCESS) - return ReplayResult::unsupported; + return queue_unsupported(__LINE__); // The mesh-primitives count of a mesh segment (D3D-MESH-CLIPPING-COUNTER): a query of its own type, // which the pipeline-statistics pool cannot hold. The device needs the meshShaderQueries feature, // or the clipping field of a mesh segment stays 0. @@ -2499,7 +2701,7 @@ class VulkanQueue : private QueueHolds::Holder { primitives.queryCount = statistics_segments; if (context_.vk.vkCreateQueryPool(statistics->device, &primitives, nullptr, &statistics->primitives_pool) != VK_SUCCESS) - return ReplayResult::unsupported; + return queue_unsupported(__LINE__); } } } @@ -2519,16 +2721,16 @@ class VulkanQueue : private QueueHolds::Holder { if (queries.needs_sum || queries.needs_binary || queries.needs_statistics_sum || queries.needs_sum_binary) { if (!occlusion_resolve_) { auto helper = std::make_unique(context_.vk, context_.device()); - if (!helper->initialize(occlusion_memory)) return ReplayResult::unsupported; + if (!helper->initialize(occlusion_memory)) return queue_unsupported(__LINE__); occlusion_resolve_ = std::move(helper); } if (!occlusion_resolve_->prepare(queries.needs_sum, queries.needs_binary, queries.needs_statistics_sum, queries.needs_sum_binary)) - return ReplayResult::unsupported; + return queue_unsupported(__LINE__); } CommandSlot* slot = acquire(); - if (!slot) return ReplayResult::unsupported; + if (!slot) return queue_unsupported(__LINE__); slot->khr_instances = std::move(khr_guard.stages); // freed when this slot is reused khr_guard.stages.clear(); slot->khr_as_queries = std::move(khr_guard.as_queries); @@ -2557,9 +2759,10 @@ class VulkanQueue : private QueueHolds::Holder { }; VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; - if (context_.vk.vkBeginCommandBuffer(command_buffer, &begin) != VK_SUCCESS) { + if (context_.observe_result(context_.vk.vkBeginCommandBuffer(command_buffer, &begin), + "vkBeginCommandBuffer") != VK_SUCCESS) { discard(); - return ReplayResult::unsupported; + return queue_unsupported(__LINE__); } // D3D12 ends every ExecuteCommandLists with all its work done and its writes visible to the next one on the // queue (implicit state decay relies on it), and a list may then touch the same memory without a barrier: @@ -2575,7 +2778,8 @@ class VulkanQueue : private QueueHolds::Holder { } if (!tracker_lock.owns_lock()) tracker_lock.lock(); if (!transfer_only && context_.bindless_prepare_ && !context_.bindless_prepare_(command_buffer)) { - const bool ended = context_.vk.vkEndCommandBuffer(command_buffer) == VK_SUCCESS; + const bool ended = context_.observe_result(context_.vk.vkEndCommandBuffer(command_buffer), + "vkEndCommandBuffer") == VK_SUCCESS; resource_lock.unlock(); const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0); if (!submitted) discard(); @@ -2589,7 +2793,7 @@ class VulkanQueue : private QueueHolds::Holder { } if (bindless_commit) bindless_commit(submitted); tracker_lock.unlock(); - return ReplayResult::unsupported; + return queue_unsupported(__LINE__); } replay.bindless_set = context_.bindless_current_ ? context_.bindless_current_() : VK_NULL_HANDLE; const bool bindless_uploaded = std::exchange(context_.bindless_upload_pending_, false); @@ -2644,9 +2848,23 @@ class VulkanQueue : private QueueHolds::Holder { bool wrote_readback = false; VkPipelineStageFlags2 readback_stages = 0; std::uint32_t open_labels = 0; // events may span the lists of one ExecuteCommandLists + CheckpointSubmission diagnostics; + PFN_vkCmdSetCheckpointNV checkpoint = nullptr; + if (execute_call) { + auto& fault = *context_.device_fault(); + checkpoint = fault.checkpoint_command(); + const char* queue_kind = kind_ == QueueKind::direct ? "direct" : + kind_ == QueueKind::compute ? "compute" : "copy"; + diagnostics = fault.begin_submission(execute_call, queue_, queue_kind, lists.size()); + } for (std::size_t i = 0; i < lists.size(); ++i) { const auto& list = prepared[i]; - emit(list, command_buffer, replay, &next_tracker, &open_labels); + if (execute_call && i < diagnostics.lists.size()) { + const CheckpointRecorder recorder{checkpoint, diagnostics, context_.device_fault()->pipeline_names, i}; + emit_commands(list, command_buffer, replay, &next_tracker, &open_labels, &recorder); + } else { + emit(list, command_buffer, replay, &next_tracker, &open_labels); + } wrote_readback |= list.wrote_readback; readback_stages |= list.readback_src_stages; } @@ -2681,14 +2899,19 @@ class VulkanQueue : private QueueHolds::Holder { 0, 1, &host, 0, nullptr, 0, nullptr); } } - const bool ended = context_.vk.vkEndCommandBuffer(command_buffer) == VK_SUCCESS; + const bool ended = context_.observe_result(context_.vk.vkEndCommandBuffer(command_buffer), + "vkEndCommandBuffer") == VK_SUCCESS; resource_lock.unlock(); // release resource_mutex_ before vkQueueSubmit while keeping tracker_lock held const bool wait_previous = ordered_timestamps && submitted_; if (wait_previous) { waits_.push_back(progress_); wait_values_.push_back(submitted_); } - const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0); + const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0, + execute_call ? &diagnostics : nullptr); + if (mesh_draws) + std::fprintf(stderr, "[rt] pso-mesh unix_ms=%lld draws=%u submitted=%d\n", + pipeline_profile::unix_ms(), mesh_draws, int(submitted)); if (!submitted && (!storage_images.empty() || !zero_buffers.empty())) { // not initialized after all: try again with the next submission std::lock_guard lock(context_.storage_mutex_); @@ -2735,7 +2958,7 @@ class VulkanQueue : private QueueHolds::Holder { // the queue (it keeps a single upload obligation). if (bindless_commit) bindless_commit(submitted); tracker_lock.unlock(); - return submitted ? ReplayResult::success : ReplayResult::unsupported; + return submitted ? ReplayResult::success : queue_unsupported(__LINE__); } void marker_now(DebugMarker::Kind kind, const char* label) { @@ -2763,6 +2986,7 @@ class VulkanQueue : private QueueHolds::Holder { enum class Kind : std::uint8_t { batch, signal, marker }; Kind kind = Kind::batch; std::uint64_t seq = 0; // QueueHolds::next_seq(): the order operations were held in, across queues + std::uint64_t execute_call = 0; // original ExecuteCommandLists call for a held batch std::vector waits; std::vector wait_values; std::vector lists; // batch: copies, so the application may Reset its lists after the call @@ -2847,7 +3071,7 @@ class VulkanQueue : private QueueHolds::Holder { for (const CommandList& list : op.lists) lists.push_back(&list); // The pipeline states and root signatures of the lists are in op.pins (see execute()): they live until // the batch has been recorded and then, with the fences, until its submission has completed (below). - const ReplayResult result = execute_now(lists); + const ReplayResult result = execute_now(lists, op.execute_call); if (result != ReplayResult::success) { int none = static_cast(ReplayResult::success); held_failure_.compare_exchange_strong(none, static_cast(result)); @@ -3071,7 +3295,8 @@ class VulkanQueue : private QueueHolds::Holder { pending_bindings_.push_back(std::move(pending)); { std::lock_guard lock(context_.submit_mutex()); - const auto result = vk.vkQueueBindSparse(queue_, 1, &info, VK_NULL_HANDLE); + const auto result = context_.observe_result(vk.vkQueueBindSparse(queue_, 1, &info, VK_NULL_HANDLE), + "vkQueueBindSparse"); if (result != VK_SUCCESS) { if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost(); pending_bindings_.pop_back(); @@ -3093,7 +3318,8 @@ class VulkanQueue : private QueueHolds::Holder { std::uint64_t completed() const { if (context_.is_device_lost()) return 0; std::uint64_t done = 0; - const VkResult result = context_.vk.vkGetSemaphoreCounterValue(context_.device(), progress_, &done); + const VkResult result = context_.observe_result( + context_.vk.vkGetSemaphoreCounterValue(context_.device(), progress_, &done), "vkGetSemaphoreCounterValue"); if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost(); // A failed timeline query cannot be used as a resource-retirement or command-buffer reuse ticket. return result == VK_SUCCESS ? done : 0; @@ -3161,7 +3387,8 @@ class VulkanQueue : private QueueHolds::Holder { info.semaphoreCount = 1; info.pSemaphores = &progress_; info.pValues = &oldest; - return context_.vk.vkWaitSemaphores(context_.device(), &info, kQueuedWaitNs); + return context_.observe_result(context_.vk.vkWaitSemaphores(context_.device(), &info, kQueuedWaitNs), + "vkWaitSemaphores (queue progress)"); } CommandSlot* acquire() { @@ -3201,7 +3428,8 @@ class VulkanQueue : private QueueHolds::Holder { return event; } - bool submit(VkCommandBuffer command_buffer, VkSemaphore fence, std::uint64_t value) { + bool submit(VkCommandBuffer command_buffer, VkSemaphore fence, std::uint64_t value, + CheckpointSubmission* diagnostics = nullptr) { if (context_.is_device_lost()) return false; const std::uint64_t ticket = submitted_ + 1; if (last_sparse_) { @@ -3250,7 +3478,10 @@ class VulkanQueue : private QueueHolds::Holder { submit.pCommandBuffers = &command_buffer; submit.signalSemaphoreCount = signal_count; submit.pSignalSemaphores = signals; - res = context_.vk.vkQueueSubmit(queue_, 1, &submit, VK_NULL_HANDLE); + // Publish before the driver can execute a marker or a concurrent fence wait can see the loss. + if (diagnostics) context_.device_fault()->publish(std::move(*diagnostics)); + res = context_.observe_result(context_.vk.vkQueueSubmit(queue_, 1, &submit, VK_NULL_HANDLE), + "vkQueueSubmit"); if (res == VK_SUCCESS) { context_.record_submit_locked(progress_, ticket); if (signals_fence) context_.holds().signaled(fence, value); diff --git a/runtime/src/vulkan_bindless.h b/runtime/src/vulkan_bindless.h index cb5b61f655..179ba12e9c 100644 --- a/runtime/src/vulkan_bindless.h +++ b/runtime/src/vulkan_bindless.h @@ -11,8 +11,9 @@ // dimension: 0 = 2D, 1 = 2D array, 2 = 3D, 3 = 1D (the translator's STORE_DIMS); class: 0 = float, 1 = uint, 2 = sint. // bindings 20/21: sampled multisample 2D images / 2D arrays, 256 each (runtime SRVs). // bindings 22/23 and 24/25 are their UINT and SINT equivalents on devices supporting those classes. -// These are the default counts (BindlessFeatures::counts). size_bindings() sizes the 2D, sampler and storage arrays -// from the device's limits instead; the shaders declare runtime arrays, so any count works for them. +// These are the default counts (BindlessFeatures::counts). size_bindings() sizes the sampled arrays of every +// single-sample dimension, the samplers and the storage arrays from the device's limits instead; the shaders declare +// runtime arrays, so any count works for them. // // A shader turns a T# or S# into an index through the hash table (descriptor_table.h) and uses that index in // whichever binding the instruction calls for: the sampled array of the image's dimension, or one of its storage @@ -37,6 +38,15 @@ // flush() takes the command buffer that will use the set: it uploads only the slots that changed, from a mapped // staging buffer, and barriers the copy before the draws. The table at creation is empty until that first flush. // +// When device-local memory runs out (a title that fills VRAM), a new generation's table goes to HOST_VISIBLE memory +// instead: slower lookups beat no table. Released generations are kept as spares (at most max_spares) and reused, +// pool and buffers, by the next replacing flush, so steady churn allocates nothing. If a generation still cannot be +// made, flush() rewrites the current table in place when every submission that could read it is done, and otherwise +// degrades: the descriptors are written, the table keeps its last uploaded contents (keys added since find the +// fallback, index 0; keys rebound since keep their previous index, whose views stay alive; removed indices are not +// given out again meanwhile) and the change waits for a later flush. A flush never fails the submission for want of +// memory (last_flush_degraded(), degraded_flushes()). +// // Not thread-safe: the owner serialises calls. #ifndef VK_NO_PROTOTYPES @@ -196,8 +206,13 @@ struct SetLayout { }; // What size_bindings() grows to where the device's limits allow. At 32-64 bytes a descriptor the whole set is then -// 3-6 MiB (93793 descriptors on an RTX 5070). +// 5-10 MiB (about 160000 descriptors on an RTX 5070). inline constexpr std::uint32_t max_2d_images = 65536; +// The other single-sample dimensions: a title streams far more cube maps and texture arrays (and 1D lookup +// textures) than the 1024 and 256 of the defaults, each distinct T# of one taking its own index. +inline constexpr std::uint32_t max_2d_array_images = 16384; +inline constexpr std::uint32_t max_3d_images = 4096; +inline constexpr std::uint32_t max_1d_images = 4096; inline constexpr std::uint32_t max_storage_indices = 4096; // in each storage array, at most its dimension's images // A full D3D12 shader-visible sampler heap (2048) and room for literal and static S#s, within what the device can // create (maxSamplerAllocationCount, at least 4000) less the samplers that are not in the set. @@ -212,8 +227,9 @@ inline constexpr std::uint32_t growth_headroom = 64; // standalone samplers do not, though they count in an update-after-bind pool. // 1. The default counts, or as much of them as the device holds: samplers, then storage, then 2D images. // 2. The MS pairs that fit beside them (limit_ms_bindings, which may turn classes off). -// 3. Growth towards the maximums above, in the same order, within maxPerSetDescriptors. That limit only says -// what is sure to work (vkGetDescriptorSetLayoutSupport may allow more), so it never shrinks step 1. +// 3. Growth towards the maximums above, in the same order, then the 2D-array, 3D and 1D images, within +// maxPerSetDescriptors. That limit only says what is sure to work (vkGetDescriptorSetLayoutSupport may allow +// more), so it never shrinks step 1. // A storage array holds the smaller of the storage count and its dimension's images: add_image never gives a // storage view an index past the sampled array. The other bindings keep their default counts. // layout_supported, when given, answers vkGetDescriptorSetLayoutSupport for set 0 at the counts in its argument: @@ -243,10 +259,16 @@ inline bool size_bindings(BindlessFeatures& features, const VkPhysicalDeviceLimi auto& counts = features.counts; counts = default_counts(); std::uint32_t images = 1, samplers = 1, storage = 1; + std::uint32_t arrays = counts[sampled_binding(ImageDimension::dim_2d_array)]; + std::uint32_t volumes = counts[sampled_binding(ImageDimension::dim_3d)]; + std::uint32_t lines = counts[sampled_binding(ImageDimension::dim_1d)]; // Until the end the 2D storage arrays are not capped by the 2D images, which grow after them: capping can only // take descriptors away. const auto apply = [&](bool final) { counts[sampled_binding(ImageDimension::dim_2d)] = images; + counts[sampled_binding(ImageDimension::dim_2d_array)] = arrays; + counts[sampled_binding(ImageDimension::dim_3d)] = volumes; + counts[sampled_binding(ImageDimension::dim_1d)] = lines; counts[sampler_binding] = samplers; for (std::uint32_t d = 0; d < 4; ++d) { const auto dimension = ImageDimension(d); @@ -305,6 +327,9 @@ inline bool size_bindings(BindlessFeatures& features, const VkPhysicalDeviceLimi grow(samplers, std::max(samplers, std::min(max_samplers, creatable)), growth_headroom, set_limit); grow(images, std::max(images, max_2d_images), growth_headroom, set_limit); grow(storage, std::max(storage, max_storage_indices), growth_headroom, set_limit); + grow(arrays, std::max(arrays, max_2d_array_images), growth_headroom, set_limit); + grow(volumes, std::max(volumes, max_3d_images), growth_headroom, set_limit); + grow(lines, std::max(lines, max_1d_images), growth_headroom, set_limit); apply(true); return full; } @@ -313,14 +338,18 @@ inline bool size_bindings(BindlessFeatures& features, const VkPhysicalDeviceLimi class BindlessSet { public: + // `descriptor_hash` is the finalizer the shaders of this device probe the table with (descriptor_table.h); it is + // handed to the table before its first key is inserted, so every insert, lookup and rehash agrees with them. BindlessSet(PFN_vkGetDeviceProcAddr get, VkDevice device, const VkPhysicalDeviceMemoryProperties& memory, - BindlessFeatures features = {}) - : device_(device), memory_(memory), features_(features) { + BindlessFeatures features = {}, DescriptorHashKind descriptor_hash = DescriptorHashKind::fnv1a) + : device_(device), memory_(memory), features_(features), table_(64, descriptor_hash) { ok_ = vk_.load(get, device) && create_layout() && create_fallbacks() && create_table_buffers() && fill(); } ~BindlessSet() { release_retired(); + for (Generation& spare : spares_) destroy(spare); + spares_.clear(); destroy(table_buffers_); if (fallback_sampler_) vk_.vkDestroySampler(device_, fallback_sampler_, nullptr); for (const VkImageView view : fallback_views_) vk_.vkDestroyImageView(device_, view, nullptr); @@ -414,16 +443,20 @@ class BindlessSet { void update_image(ImageDimension dimension, std::uint32_t index, VkImageView sampled, VkImageLayout sampled_layout, const StorageViews& storage = {}, std::uint32_t sampled_class = 0) { const auto& used = image_used_[std::uint32_t(dimension)]; - if (index && index < used.size() && used[index]) + if (index && index < used.size() && used[index] == in_use) write_image(dimension, index, sampled, sampled_layout, storage, sampled_class); } // Returns the index to the fallback and frees it. The caller removes the image's keys with erase_key() first. + // While the table has changes the GPU's copy lacks (an erased key may still name the index there), the index is + // held until a flush has brought the table up to date (one that did not degrade), so that no new image answers + // that key; otherwise it is free at once. void remove_image(ImageDimension dimension, std::uint32_t index) { auto& used = image_used_[std::uint32_t(dimension)]; - if (!index || index >= used.size() || !used[index]) return; + if (!index || index >= used.size() || used[index] != in_use) return; write_image(dimension, index, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_GENERAL, {}, 0); - used[index] = 0; + used[index] = table_dirty_ ? held : 0; + if (table_dirty_) held_images_.push_back({dimension, index}); } // 0 when the sampler array is full. @@ -434,9 +467,10 @@ class BindlessSet { } void remove_sampler(std::uint32_t index) { - if (!index || index >= sampler_used_.size() || !sampler_used_[index]) return; + if (!index || index >= sampler_used_.size() || sampler_used_[index] != in_use) return; write_sampler(index, fallback_sampler_); - sampler_used_[index] = 0; + sampler_used_[index] = table_dirty_ ? held : 0; + if (table_dirty_) held_samplers_.push_back(index); } // T# and S# keys to the indices above: the table of binding 2 (descriptor_table.h). Changes reach the shaders @@ -479,7 +513,10 @@ class BindlessSet { void table_upload_result(bool submitted) { if (!upload_in_flight_) return; upload_in_flight_ = false; - if (submitted) return; + if (submitted) { + table_on_gpu_ = true; // the current buffers hold a table the GPU was given + return; + } table_dirty_ = true; force_full_upload_ = true; } @@ -488,17 +525,42 @@ class BindlessSet { // the set are recorded after it. When flush_replaces_table() was true this starts a new generation (table // buffers, descriptor set, binding 2 and every descriptor written so far) and puts the previous one on the retire // list, stamped `retire_ticket`: the owner's number for "every submission made so far", which release_retired() - // compares with what has completed. False when the new generation cannot be made: the set then still has the - // table as of the last flush. - bool flush(VkCommandBuffer command_buffer, std::uint64_t retire_ticket = 0) { + // compares with what has completed. + // When the new generation cannot be made (no memory for its buffers or descriptor pool) and `completed_ticket` is + // given, it is asked what has completed: the generations retired up to there are released (to the spares) and + // the generation is tried again; when everything up to `retire_ticket` is done, nothing reads the current table + // and it is rewritten in place if it is large enough. Failing both, the flush degrades instead of failing: the + // descriptors are written in place, as on a flush that does not replace the table (add_image writes new indices, + // which no key of the GPU's table reaches; remove_image writes the fallback, and the index stays held until a + // flush that does not degrade), the table keeps what it had, and its changes wait for a later flush + // (last_flush_degraded()). False only without a command buffer, when nothing can be recorded. + bool flush(VkCommandBuffer command_buffer, std::uint64_t retire_ticket = 0, + const std::function& completed_ticket = {}) { + if (!command_buffer) return false; bool replaced = false; bool written = true; const bool must_replace = flush_replaces_table(); + last_flush_degraded_ = false; if (table_dirty_ || !table_uploaded_) written = upload_table(command_buffer, retire_ticket, replaced); + if (!written && must_replace && completed_ticket) { + const std::uint64_t completed = completed_ticket(); + if (!retired_.empty()) { + release_retired(completed); + written = upload_table(command_buffer, retire_ticket, replaced); + } + if (!written && completed >= retire_ticket) written = rewrite_table_in_place(command_buffer); + } last_flush_replaced_ = replaced; - // The new generation could not be made: the current set is the one running work reads, so its descriptors are - // not written in place either. The pending writes and the table's changes stay for the next flush. - if (!written && must_replace) return false; + // Degrading keeps what the current buffers hold, so only once they hold a table that reached the queue: a + // first flush under full memory, or one after a failed submission of the only upload, has nothing on the GPU + // (word 0 is the probe mask) and refuses as before (review of #64). + if (!written && must_replace && !table_on_gpu_) return false; + if (!written && must_replace) { + // The current set is the one running work reads, and the table's changes may move or rebind live keys: + // they stay for a later flush, and keys added since find the fallback until then. + ++degraded_flushes_; + last_flush_degraded_ = true; + } for (const Pending& pending : pending_) { if (pending.binding >= shadow_.size() || pending.index >= shadow_[pending.binding].size()) continue; shadow_[pending.binding][pending.index] = pending.info; @@ -521,17 +583,29 @@ class BindlessSet { } pending_.clear(); pending_slots_.clear(); - return written; + if (!last_flush_degraded_) { + // The table this flush leaves on the GPU names no removed index any more: they can be given out again. + for (const auto& [dimension, index] : held_images_) image_used_[std::uint32_t(dimension)][index] = 0; + for (const std::uint32_t index : held_samplers_) sampler_used_[index] = 0; + held_images_.clear(); + held_samplers_.clear(); + } + return true; } - // Frees the generations (table buffers and descriptor set) that flush() retired with a ticket up to `completed`. - // The default frees all of them: when nothing submitted before the last flush() still runs. + // Releases the generations (table buffers and descriptor set) that flush() retired with a ticket up to + // `completed`: up to max_spares of them, large enough for the table, are kept for the next replacing flush to + // reuse; the others are freed. The default releases all of them: when nothing submitted before the last flush() + // still runs. void release_retired(std::uint64_t completed = UINT64_MAX) { std::size_t kept = 0; for (auto& generation : retired_) { if (generation.ticket <= completed) { - destroy(generation.buffers); - if (generation.pool) vk_.vkDestroyDescriptorPool(device_, generation.pool, nullptr); + if (spares_.size() < max_spares && generation.pool && generation.buffers.staging.mapped && + generation.buffers.table.size >= table_.size_bytes()) + spares_.push_back(generation); + else + destroy(generation); } else { retired_[kept++] = generation; } @@ -548,11 +622,32 @@ class BindlessSet { std::uint64_t generations_made() const { return generations_made_; } std::size_t retired_count() const { return retired_.size(); } + // Released generations kept for reuse, and how many replacing flushes reused one instead of allocating. One: the + // current generation and a spare are the two a replacing flush has at its peak anyway (the new one, and the one + // retired until its work completes), and a grown table can be large (64 MiB at a million slots). + static constexpr std::size_t max_spares = 1; + std::size_t spare_count() const { return spares_.size(); } + std::uint64_t spares_reused() const { return spares_reused_; } + // Flushes that could not make the generation they needed and kept the previous table (see flush()), and whether + // the last one did; flushes that rewrote the table in place instead, every submission being done. + std::uint64_t degraded_flushes() const { return degraded_flushes_; } + bool last_flush_degraded() const { return last_flush_degraded_; } + std::uint64_t in_place_rewrites() const { return in_place_rewrites_; } + // Table buffers placed in HOST_VISIBLE memory because the DEVICE_LOCAL allocation failed. + std::uint64_t table_host_fallbacks() const { return table_host_fallbacks_; } + // What the last generation that could not be made failed to get: "table buffer", "staging buffer" or + // "descriptor set" (nullptr before any failure), and the Vulkan result of that call. + const char* last_failure() const { return last_failure_; } + VkResult last_failure_result() const { return last_failure_result_; } + // Bytes of the current table buffer (the table grows by doubling its slots: size_bytes() of table()). + std::size_t table_buffer_bytes() const { return table_buffers_.table.size; } + private: struct Functions { #define LEONIDA_BINDLESS_FUNCTIONS(X) \ X(vkCreateDescriptorSetLayout) X(vkDestroyDescriptorSetLayout) X(vkCreateDescriptorPool) \ - X(vkDestroyDescriptorPool) X(vkAllocateDescriptorSets) X(vkUpdateDescriptorSets) X(vkCreateBuffer) \ + X(vkDestroyDescriptorPool) X(vkResetDescriptorPool) X(vkAllocateDescriptorSets) X(vkUpdateDescriptorSets) \ + X(vkCreateBuffer) \ X(vkDestroyBuffer) X(vkGetBufferMemoryRequirements) X(vkBindBufferMemory) X(vkAllocateMemory) \ X(vkFreeMemory) X(vkMapMemory) X(vkCreateImage) X(vkDestroyImage) X(vkGetImageMemoryRequirements) \ X(vkBindImageMemory) X(vkCreateImageView) X(vkDestroyImageView) X(vkCreateSampler) X(vkDestroySampler) \ @@ -583,6 +678,7 @@ class BindlessSet { VkDeviceMemory memory = VK_NULL_HANDLE; void* mapped = nullptr; std::size_t size = 0; + bool device_local = false; // the memory is DEVICE_LOCAL }; // The table and the mapped staging copy the CPU writes before vkCmdCopyBuffer moves the changes. @@ -591,6 +687,13 @@ class BindlessSet { TableBuffer staging; // HOST_VISIBLE | HOST_COHERENT }; + struct Generation { // what a replaced table leaves for release_retired() + TableBuffers buffers; + VkDescriptorPool pool = VK_NULL_HANDLE; // owns the descriptor set + VkDescriptorSet set = VK_NULL_HANDLE; + std::uint64_t ticket = 0; + }; + struct Pending { std::uint32_t binding; std::uint32_t index; @@ -598,6 +701,9 @@ class BindlessSet { }; static constexpr std::uint32_t dimensions = 6, classes = 3; + // image_used_ and sampler_used_: 0 free, in_use, or held (removed while the table was dirty: free after the next + // flush that does not degrade). + static constexpr std::uint8_t in_use = 1, held = 2; // The first free index in [begin, end), marked used; 0 when there is none. static std::uint32_t allocate(std::vector& used, std::uint32_t begin, std::uint32_t end) { @@ -645,21 +751,35 @@ class BindlessSet { pool_info.maxSets = 1; pool_info.poolSizeCount = pool_size_count_; pool_info.pPoolSizes = pool_sizes_.data(); - if (vk_.vkCreateDescriptorPool(device_, &pool_info, nullptr, &pool) != VK_SUCCESS) { + if (const VkResult result = vk_.vkCreateDescriptorPool(device_, &pool_info, nullptr, &pool); + result != VK_SUCCESS) { pool = VK_NULL_HANDLE; + note_failure("descriptor set", result); return false; } + if (allocate_set(pool, set)) return true; + vk_.vkDestroyDescriptorPool(device_, pool, nullptr); + pool = VK_NULL_HANDLE; + return false; + } + + bool allocate_set(VkDescriptorPool pool, VkDescriptorSet& set) const { VkDescriptorSetAllocateInfo set_info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; set_info.descriptorPool = pool; set_info.descriptorSetCount = 1; set_info.pSetLayouts = &layout_; - if (vk_.vkAllocateDescriptorSets(device_, &set_info, &set) == VK_SUCCESS) return true; - vk_.vkDestroyDescriptorPool(device_, pool, nullptr); - pool = VK_NULL_HANDLE; + const VkResult result = vk_.vkAllocateDescriptorSets(device_, &set_info, &set); + if (result == VK_SUCCESS) return true; set = VK_NULL_HANDLE; + note_failure("descriptor set", result); return false; } + void note_failure(const char* what, VkResult result) const { + last_failure_ = what; + last_failure_result_ = result; + } + // Writes every descriptor written so far (the shadow) into the current set, one update per run of written // elements: the set was just made, and unwritten elements stay unwritten, as partially_bound allows. void write_shadow() const { @@ -753,36 +873,53 @@ class BindlessSet { return vk_.vkCreateSampler(device_, &sampler, nullptr, &fallback_sampler_) == VK_SUCCESS; } - bool create(TableBuffer& out, std::size_t bytes, bool device_local, bool* got_device_local = nullptr) const { + // device_local: the table (DEVICE_LOCAL, else HOST_VISIBLE when the device has no such type or that heap is out + // of memory); otherwise the mapped staging buffer (HOST_VISIBLE | HOST_COHERENT). + bool create(TableBuffer& out, std::size_t bytes, bool device_local) { + constexpr VkMemoryPropertyFlags host = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; + const char* what = device_local ? "table buffer" : "staging buffer"; VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; info.size = bytes; info.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | (device_local ? VK_BUFFER_USAGE_TRANSFER_DST_BIT : VK_BUFFER_USAGE_TRANSFER_SRC_BIT); TableBuffer made; made.size = bytes; - if (vk_.vkCreateBuffer(device_, &info, nullptr, &made.buffer) != VK_SUCCESS) return false; + if (const VkResult result = vk_.vkCreateBuffer(device_, &info, nullptr, &made.buffer); result != VK_SUCCESS) { + made.buffer = VK_NULL_HANDLE; + note_failure(what, result); + return false; + } VkMemoryRequirements requirements{}; vk_.vkGetBufferMemoryRequirements(device_, made.buffer, &requirements); VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; allocation.allocationSize = requirements.size; - allocation.memoryTypeIndex = - device_local ? memory_type(requirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) - : memory_type(requirements.memoryTypeBits, - VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); - if (device_local && allocation.memoryTypeIndex == 0xffffffffu) - allocation.memoryTypeIndex = memory_type(requirements.memoryTypeBits, - VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | - VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); - if (got_device_local) - *got_device_local = allocation.memoryTypeIndex != 0xffffffffu && - (memory_.memoryTypes[allocation.memoryTypeIndex].propertyFlags & + const auto allocate = [&](std::uint32_t type) { + if (type == 0xffffffffu) return VK_ERROR_OUT_OF_DEVICE_MEMORY; + allocation.memoryTypeIndex = type; + const VkResult result = vk_.vkAllocateMemory(device_, &allocation, nullptr, &made.memory); + if (result != VK_SUCCESS) made.memory = VK_NULL_HANDLE; + return result; + }; + const std::uint32_t local = device_local + ? memory_type(requirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) + : 0xffffffffu; + VkResult result = device_local ? allocate(local) : allocate(memory_type(requirements.memoryTypeBits, host)); + if (result != VK_SUCCESS && device_local) { + const std::uint32_t fallback = memory_type(requirements.memoryTypeBits, host); + if (fallback != local) { + result = allocate(fallback); + if (result == VK_SUCCESS && local != 0xffffffffu) ++table_host_fallbacks_; + } + } + if (result == VK_SUCCESS) { + made.device_local = (memory_.memoryTypes[allocation.memoryTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) != 0; - bool ready = allocation.memoryTypeIndex != 0xffffffffu && - vk_.vkAllocateMemory(device_, &allocation, nullptr, &made.memory) == VK_SUCCESS && - vk_.vkBindBufferMemory(device_, made.buffer, made.memory, 0) == VK_SUCCESS; - if (ready && !device_local) - ready = vk_.vkMapMemory(device_, made.memory, 0, VK_WHOLE_SIZE, 0, &made.mapped) == VK_SUCCESS; - if (!ready) { + result = vk_.vkBindBufferMemory(device_, made.buffer, made.memory, 0); + } + if (result == VK_SUCCESS && !device_local) + result = vk_.vkMapMemory(device_, made.memory, 0, VK_WHOLE_SIZE, 0, &made.mapped); + if (result != VK_SUCCESS) { + note_failure(what, result); destroy(made); return false; } @@ -801,17 +938,55 @@ class BindlessSet { destroy(buffers.table); } + void destroy(Generation& generation) const { + destroy(generation.buffers); + if (generation.pool) vk_.vkDestroyDescriptorPool(device_, generation.pool, nullptr); // frees the set + generation.pool = VK_NULL_HANDLE; + generation.set = VK_NULL_HANDLE; + } + + // A generation for a table of `bytes`: a spare when one is large enough (its pool reset for a fresh set), else + // new buffers and a new pool. Spares too small for the table are freed: the table never shrinks. + bool make_generation(std::size_t bytes, TableBuffers& buffers, VkDescriptorPool& pool, VkDescriptorSet& set) { + std::size_t kept = 0; + bool found = false; + for (Generation& spare : spares_) { + if (spare.buffers.table.size < bytes || spare.buffers.staging.size < bytes) { + destroy(spare); + continue; + } + if (!found && vk_.vkResetDescriptorPool(device_, spare.pool, 0) == VK_SUCCESS && + allocate_set(spare.pool, set)) { + buffers = spare.buffers; + pool = spare.pool; + found = true; + ++spares_reused_; + continue; + } + spares_[kept++] = spare; + } + spares_.resize(kept); + if (found) return true; + TableBuffers made; + if (!create(made.table, bytes, true) || !create(made.staging, bytes, false) || !make_set(pool, set)) { + destroy(made); + return false; + } + buffers = made; + return true; + } + bool create_table_buffers() { const std::size_t bytes = table_.size_bytes(); TableBuffers made; - bool device_local = false; - if (!create(made.table, bytes, true, &device_local) || !create(made.staging, bytes, false)) { + if (!create(made.table, bytes, true) || !create(made.staging, bytes, false)) { destroy(made); return false; } table_buffers_ = made; - table_device_local_ = device_local; + table_device_local_ = made.table.device_local; table_uploaded_ = false; // the first flush() uploads it, in the command buffer that will use it + table_on_gpu_ = false; table_dirty_ = existing_entries_changed_ = false; return true; } @@ -829,15 +1004,11 @@ class BindlessSet { TableBuffers larger; VkDescriptorPool pool = VK_NULL_HANDLE; VkDescriptorSet set = VK_NULL_HANDLE; - bool device_local = false; - if (!create(larger.table, bytes, true, &device_local) || !create(larger.staging, bytes, false) || - !make_set(pool, set)) { - destroy(larger); - return false; - } - table_device_local_ = device_local; + if (!make_generation(bytes, larger, pool, set)) return false; + table_device_local_ = larger.table.device_local; retired_.push_back({table_buffers_, pool_, set_, retire_ticket}); table_buffers_ = larger; + table_on_gpu_ = false; // until this generation's upload is submitted (table_upload_result) pool_ = pool; set_ = set; write_table_binding(table_buffers_.table.buffer); @@ -893,6 +1064,25 @@ class BindlessSet { return true; } + // The whole table into the current generation's buffers, for a flush whose new generation could not be made, + // once every submission that could read the current table is done (flush()). False when the table outgrew them. + bool rewrite_table_in_place(VkCommandBuffer command_buffer) { + const std::size_t bytes = table_.size_bytes(); + if (bytes > table_buffers_.table.size || bytes > table_buffers_.staging.size || !table_buffers_.staging.mapped) + return false; + table_.take_changes(); // all of it goes + // Nothing still runs that copies from the staging buffer or reads the table. + table_.write_to_buffer(table_buffers_.staging.mapped); + copy_table_range(command_buffer, 0, bytes); + record_table_barrier(command_buffer); + upload_in_flight_ = true; + table_dirty_ = existing_entries_changed_ = false; + table_uploaded_ = true; + force_full_upload_ = false; + ++in_place_rewrites_; + return true; + } + // Copies the data into the command buffer while recording (64 KiB per call, the Vulkan limit), so no staging // buffer is read at execution: a later flush can rewrite its own staging without racing a pending copy. void update_table_range(VkCommandBuffer command_buffer, VkDeviceSize offset, const void* data, @@ -1026,25 +1216,30 @@ class BindlessSet { bool fallbacks_ready_ = false; std::array, dimensions> image_used_; std::vector sampler_used_; + std::vector> held_images_; // removed, not yet free (remove_image) + std::vector held_samplers_; std::vector pending_; std::unordered_map pending_slots_; // binding and index -> place in pending_ - DescriptorTable table_{64}; + DescriptorTable table_; // 64 slots, and the device's hash kind, from the constructor TableBuffers table_buffers_; bool table_uploaded_ = false; // the table's current contents are in table_buffers_.table + bool table_on_gpu_ = false; // an upload into the current table buffers reached the queue (degrading is safe) bool table_device_local_ = false; bool table_dirty_ = false; // the table differs from the buffer bool existing_entries_changed_ = false; // ... and not only by entries added bool upload_in_flight_ = false; // a copy is recorded, not yet known to have reached the queue bool force_full_upload_ = false; // the last submit failed: rebuild the whole table on the next flush - struct Generation { // what a replaced table leaves for release_retired() - TableBuffers buffers; - VkDescriptorPool pool = VK_NULL_HANDLE; // owns the descriptor set - VkDescriptorSet set = VK_NULL_HANDLE; - std::uint64_t ticket = 0; - }; std::vector retired_; + std::vector spares_; // released generations kept for reuse (release_retired) std::uint64_t generations_made_ = 0; bool last_flush_replaced_ = false; + bool last_flush_degraded_ = false; + std::uint64_t spares_reused_ = 0; + std::uint64_t degraded_flushes_ = 0; + std::uint64_t in_place_rewrites_ = 0; + std::uint64_t table_host_fallbacks_ = 0; + mutable const char* last_failure_ = nullptr; + mutable VkResult last_failure_result_ = VK_SUCCESS; std::array pool_sizes_{}; std::uint32_t pool_size_count_ = 0; // Every descriptor written to the set (the table's binding aside), to fill the next generation's set. diff --git a/runtime/src/vulkan_depth24.h b/runtime/src/vulkan_depth24.h index 988b79d9f1..a46177dd4d 100644 --- a/runtime/src/vulkan_depth24.h +++ b/runtime/src/vulkan_depth24.h @@ -12,6 +12,8 @@ #endif #include +#include "vulkan_device_fault.h" + #include #include #include @@ -29,14 +31,15 @@ class Depth24Converter { using Allocate = std::function; // `max_range`: the device's maxStorageBufferRange; a copy is split into dispatches that stay inside it. - Depth24Converter(PFN_vkGetDeviceProcAddr get, VkDevice device, Allocate allocate, std::uint64_t max_range = 1u << 27) - : device_(device), allocate_(std::move(allocate)), max_range_(max_range) { + Depth24Converter(PFN_vkGetDeviceProcAddr get, VkDevice device, Allocate allocate, + std::uint64_t max_range = 1u << 27, DeviceFaultDiagnostics* diagnostics = nullptr) + : device_(device), diagnostics_(diagnostics), allocate_(std::move(allocate)), max_range_(max_range) { loaded_ = vk_.load(get, device); } ~Depth24Converter() { if (!loaded_) return; - vk_.vkDeviceWaitIdle(device_); + DeviceFaultDiagnostics::observe(diagnostics_, vk_.vkDeviceWaitIdle(device_), "vkDeviceWaitIdle"); release(current_); for (auto& batch : retired_) release(batch); for (auto& chunk : spare_) destroy(chunk); @@ -146,7 +149,9 @@ class Depth24Converter { if (retired_[i].ticket != 0) { std::uint64_t done = 0; if (!retired_[i].timeline || - vk_.vkGetSemaphoreCounterValue(device_, retired_[i].timeline, &done) != VK_SUCCESS || + DeviceFaultDiagnostics::observe(diagnostics_, + vk_.vkGetSemaphoreCounterValue(device_, retired_[i].timeline, &done), + "vkGetSemaphoreCounterValue (scratch)") != VK_SUCCESS || done < retired_[i].ticket) { ++i; continue; @@ -354,6 +359,7 @@ class Depth24Converter { } VkDevice device_; + DeviceFaultDiagnostics* diagnostics_; Allocate allocate_; std::uint64_t max_range_; Functions vk_; diff --git a/runtime/src/vulkan_device_fault.h b/runtime/src/vulkan_device_fault.h new file mode 100644 index 0000000000..f51edb360b --- /dev/null +++ b/runtime/src/vulkan_device_fault.h @@ -0,0 +1,429 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace leonida { + +struct DeviceFaultExtensions { + bool fault = false; + bool checkpoints = false; + bool diagnostics_config = false; +}; + +// Owns the feature structures until vkCreateDevice returns. +struct DeviceFaultFeatures { + VkPhysicalDeviceFaultFeaturesEXT fault{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FAULT_FEATURES_EXT}; + VkPhysicalDeviceDiagnosticsConfigFeaturesNV diagnostics{ + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DIAGNOSTICS_CONFIG_FEATURES_NV}; + VkDeviceDiagnosticsConfigCreateInfoNV config{VK_STRUCTURE_TYPE_DEVICE_DIAGNOSTICS_CONFIG_CREATE_INFO_NV}; + + DeviceFaultExtensions enable(VkPhysicalDevice physical, PFN_vkGetPhysicalDeviceFeatures2 query, + std::span advertised, + std::vector& extensions, VkDeviceCreateInfo& device) { + const auto has = [&](const char* name) { + return std::any_of(advertised.begin(), advertised.end(), [name](const auto& ext) { + return std::strcmp(ext.extensionName, name) == 0; + }); + }; + const bool has_fault = has(VK_EXT_DEVICE_FAULT_EXTENSION_NAME); + const bool has_config = has(VK_NV_DEVICE_DIAGNOSTICS_CONFIG_EXTENSION_NAME); + if (has_fault || has_config) { + diagnostics.pNext = nullptr; + fault.pNext = has_config ? &diagnostics : nullptr; + VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; + features.pNext = has_fault ? static_cast(&fault) : static_cast(&diagnostics); + query(physical, &features); + } + const DeviceFaultExtensions enabled{has_fault && fault.deviceFault == VK_TRUE, + has(VK_NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME), + has_config && diagnostics.diagnosticsConfig == VK_TRUE}; + if (enabled.fault) { + extensions.push_back(VK_EXT_DEVICE_FAULT_EXTENSION_NAME); + fault.pNext = const_cast(device.pNext); + device.pNext = &fault; + } + if (enabled.checkpoints) extensions.push_back(VK_NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME); + if (enabled.diagnostics_config) { + extensions.push_back(VK_NV_DEVICE_DIAGNOSTICS_CONFIG_EXTENSION_NAME); + diagnostics.pNext = const_cast(device.pNext); + config.pNext = &diagnostics; + config.flags = VK_DEVICE_DIAGNOSTICS_CONFIG_ENABLE_SHADER_DEBUG_INFO_BIT_NV | + VK_DEVICE_DIAGNOSTICS_CONFIG_ENABLE_RESOURCE_TRACKING_BIT_NV | + VK_DEVICE_DIAGNOSTICS_CONFIG_ENABLE_AUTOMATIC_CHECKPOINTS_BIT_NV; + device.pNext = &config; + } + return enabled; + } +}; + +enum class CheckpointKind : std::uint8_t { draw = 1, dispatch, copy, resolve, clear }; + +struct CheckpointMarker { + static constexpr std::uint32_t max_list = 0xff; + static constexpr std::uint32_t max_command = 0x1ffff; + static constexpr std::uint64_t tag = 0xa; + + std::uint32_t submission = 0; + std::uint32_t list = 0; + std::uint32_t command = 0; + CheckpointKind kind{}; + + // Vulkan treats the value as an opaque pointer. The runtime never dereferences it. + static constexpr std::uintptr_t encode(std::uint32_t submission, std::size_t list, std::size_t command, + CheckpointKind kind) { + if (sizeof(void*) < 8 || !submission || list > max_list || command > max_command) return 0; + return static_cast((tag << 60) | (std::uint64_t{submission} << 28) | + (std::uint64_t{list} << 20) | (std::uint64_t{command} << 3) | + static_cast(kind)); + } + + static constexpr CheckpointMarker decode(std::uintptr_t marker) { + const std::uint64_t bits = marker; + const auto kind = static_cast(bits & 7); + if ((bits >> 60) != tag || kind < CheckpointKind::draw || kind > CheckpointKind::clear) return {}; + return {static_cast(bits >> 28), static_cast((bits >> 20) & max_list), + static_cast((bits >> 3) & max_command), kind}; + } + + const char* kind_name() const { + switch (kind) { + case CheckpointKind::draw: return "draw"; + case CheckpointKind::dispatch: return "dispatch"; + case CheckpointKind::copy: return "copy"; + case CheckpointKind::resolve: return "resolve"; + case CheckpointKind::clear: return "clear"; + default: return "unknown"; + } + } +}; + +using CheckpointShaders = std::array; // Immutable ShaderLibrary names, valid until context teardown. + +struct CheckpointPipeline { + VkPipeline handle = VK_NULL_HANDLE; + std::uintptr_t id = 0; + CheckpointShaders shaders{}; +}; + +struct CheckpointList { + struct ShaderChange { + std::uint32_t command; + CheckpointPipeline pipeline; + }; + std::vector shaders; +}; + +// CPU record of work handed to vkQueueSubmit. A driver checkpoint can identify which +// entry it reached; on drivers without checkpoints these remain submitted candidates. +struct CheckpointDispatch { + std::uint64_t execute_call; + VkQueue queue; + const char* queue_kind; + std::size_t list, command; + const char* shader; + std::array groups; + std::uintptr_t argument_buffer, count_buffer; + std::uint64_t argument_offset, count_offset; + std::uint32_t max_count, stride; + std::array roots; + bool indirect; +}; + +struct CheckpointSubmission { + std::uint32_t sequence = 0; + std::uint64_t execute_call = 0; + VkQueue queue = VK_NULL_HANDLE; + const char* queue_kind = nullptr; + std::size_t list_count = 0; + std::vector lists; + std::vector dispatches; + std::size_t dispatch_count = 0; + static constexpr std::size_t dispatch_limit = 64; + + void append_dispatch(CheckpointDispatch d) { + if (dispatches.size() < dispatch_limit) dispatches.push_back(d); + else dispatches[dispatch_count % dispatch_limit] = d; + ++dispatch_count; + } +}; + +struct CheckpointRecorder { + PFN_vkCmdSetCheckpointNV set; + CheckpointSubmission& submission; + const std::unordered_map& pipeline_names; + std::size_t list; + + void record(VkCommandBuffer buffer, std::size_t command, CheckpointKind kind, + VkPipeline pipeline = VK_NULL_HANDLE, std::uintptr_t id = 0) const { + if (!set) return; + const auto marker = CheckpointMarker::encode(submission.sequence, list, command, kind); + if (!marker) return; + if (kind == CheckpointKind::draw || kind == CheckpointKind::dispatch) { + auto& shaders = submission.lists[list].shaders; + if (shaders.empty() || shaders.back().pipeline.handle != pipeline || shaders.back().pipeline.id != id) { + const auto names = pipeline_names.find(id); + shaders.push_back({static_cast(command), + {pipeline, id, names != pipeline_names.end() ? names->second : CheckpointShaders{}}}); + } + } + set(buffer, reinterpret_cast(marker)); + } + + void dispatch(VkCommandBuffer buffer, std::size_t command, VkPipeline pipeline, std::uintptr_t id, + const std::array& roots, std::array groups, + bool indirect = false, std::uintptr_t args = 0, std::uint64_t offset = 0, + std::uintptr_t count = 0, std::uint64_t count_offset = 0, + std::uint32_t max_count = 0, std::uint32_t stride = 0) const { + const auto names = pipeline_names.find(id); + submission.append_dispatch({submission.execute_call, submission.queue, submission.queue_kind, list, command, + names != pipeline_names.end() ? names->second[0] : nullptr, groups, args, count, + offset, count_offset, max_count, stride, roots, indirect}); + record(buffer, command, CheckpointKind::dispatch, pipeline, id); + } +}; + +// A D3D fence may stay unsignalled by design. Only queue retirement tickets represent +// work that actually reached vkQueueSubmit. +class SubmissionProgressWatch { +public: + using Clock = std::chrono::steady_clock; + enum class State { idle, pending, submit_lock_busy }; + + bool sample(State state, std::uint64_t retired, Clock::time_point now) { + if (state == State::idle || state != state_ || retired != retired_) { + state_ = state; + retired_ = retired; + since_ = now; + reported_ = false; + return false; + } + if (reported_ || now - since_ < std::chrono::seconds(15)) return false; + reported_ = true; + return true; + } + +private: + State state_ = State::idle; + std::uint64_t retired_ = 0; + Clock::time_point since_{}; + bool reported_ = false; +}; + +class DeviceFaultDiagnostics { +public: + DeviceFaultDiagnostics(PFN_vkGetDeviceProcAddr get, VkDevice device, DeviceFaultExtensions enabled) + : device_(device) { +#define LEONIDA_FAULT_LOAD(name) name = reinterpret_cast(get(device, #name)) + if (enabled.fault) LEONIDA_FAULT_LOAD(vkGetDeviceFaultInfoEXT); + if (enabled.checkpoints) { + LEONIDA_FAULT_LOAD(vkCmdSetCheckpointNV); + LEONIDA_FAULT_LOAD(vkGetQueueCheckpointDataNV); + } +#undef LEONIDA_FAULT_LOAD + std::fprintf(stderr, "[rt] device-fault: enabled (fault info %s, checkpoints %s, NVIDIA diagnostics config %s)\n", + vkGetDeviceFaultInfoEXT ? "on" : "unavailable", checkpoint_command() ? "on" : "unavailable", + enabled.diagnostics_config ? "on" : "unavailable"); + } + + PFN_vkCmdSetCheckpointNV checkpoint_command() const { + return sizeof(void*) >= 8 && vkGetQueueCheckpointDataNV ? vkCmdSetCheckpointNV : nullptr; + } + + void add_queue(VkQueue queue) { + if (!queue || !vkGetQueueCheckpointDataNV) return; + std::lock_guard lock(mutex_); + if (std::find(queues_.begin(), queues_.end(), queue) == queues_.end()) queues_.push_back(queue); + } + + std::uint64_t next_execute_call() { return ++execute_calls_; } + + // Accessed under the context's resource lock. Reports read the names copied into the ring instead. + std::unordered_map pipeline_names; + + // Called under the context's tracker lock, in replay order. + CheckpointSubmission begin_submission(std::uint64_t call, VkQueue queue, const char* kind, std::size_t lists) { + if (!++sequence_) ++sequence_; // 0 is reserved for invalid markers + return {sequence_, call, queue, kind, lists, + std::vector(std::min(lists, std::size_t{CheckpointMarker::max_list} + 1))}; + } + + void publish(CheckpointSubmission&& submission) { + std::lock_guard lock(mutex_); + for (std::size_t i = submission.dispatch_count - submission.dispatches.size(); i < submission.dispatch_count; ++i) + dispatches_[dispatch_count_++ % dispatches_.size()] = submission.dispatches[i % submission.dispatch_limit]; + submission.dispatches.clear(); + recent_[submission.sequence % recent_.size()] = std::move(submission); + } + + static VkResult observe(DeviceFaultDiagnostics* diagnostics, VkResult result, const char* operation) noexcept { + if (result == VK_ERROR_DEVICE_LOST && diagnostics) diagnostics->report(operation); + return result; + } + + void report_stall(const char* reason, std::uint64_t submitted, std::uint64_t retired) { + std::fprintf(stderr, "[rt] device-stall: %s for 15 s; submitted ticket %" PRIu64 + ", last observed retired ticket %" PRIu64 "\n", reason, submitted, retired); + // NV checkpoints and EXT fault data require a lost device. The CPU ring is valid at any time. + dump_dispatches(); + } + +private: + void dump_dispatches() { + std::lock_guard lock(mutex_); + const auto n = std::min(dispatch_count_, dispatches_.size()); + for (std::size_t i = dispatch_count_ - n; i < dispatch_count_; ++i) { + const auto& d = dispatches_[i % dispatches_.size()]; + std::fprintf(stderr, "[rt] device-fault: submitted dispatch seq=%zu execute=%" PRIu64 + " queue=%p (%s) list=%zu command=%zu shader=%s ", i + 1, d.execute_call, + static_cast(d.queue), d.queue_kind, d.list, d.command, d.shader ? d.shader : "-"); + if (d.indirect) + std::fprintf(stderr, "indirect args=0x%" PRIxPTR "+0x%" PRIx64 " count=0x%" PRIxPTR + "+0x%" PRIx64 " max=%u stride=%u", d.argument_buffer, d.argument_offset, + d.count_buffer, d.count_offset, d.max_count, d.stride); + else std::fprintf(stderr, "groups=%u,%u,%u", d.groups[0], d.groups[1], d.groups[2]); + if (include_roots_) { + std::fputs(" roots=", stderr); + for (auto word : d.roots) std::fprintf(stderr, "%08x ", word); + } + std::fputc('\n', stderr); + } + } + + void report(const char* operation) noexcept { + if (reported_.exchange(true, std::memory_order_relaxed)) return; + std::fprintf(stderr, "[rt] device-fault: VK_ERROR_DEVICE_LOST from %s\n", operation); + dump_dispatches(); + try { + if (vkGetDeviceFaultInfoEXT) report_fault(); + } catch (...) { + std::fprintf(stderr, "[rt] device-fault: fault info collection failed\n"); + } + try { + std::lock_guard lock(mutex_); + for (VkQueue queue : queues_) report_queue(queue); + } catch (...) { + std::fprintf(stderr, "[rt] device-fault: checkpoint collection failed\n"); + } + } + + void report_fault() const { + VkDeviceFaultCountsEXT counts{VK_STRUCTURE_TYPE_DEVICE_FAULT_COUNTS_EXT}; + VkResult result = vkGetDeviceFaultInfoEXT(device_, &counts, nullptr); + if (result != VK_SUCCESS) { + std::fprintf(stderr, "[rt] device-fault: vkGetDeviceFaultInfoEXT counts failed (%d)\n", int(result)); + return; + } + std::fprintf(stderr, "[rt] device-fault: vendor binary size %" PRIu64 " bytes\n", counts.vendorBinarySize); + std::vector addresses(counts.addressInfoCount); + std::vector vendors(counts.vendorInfoCount); + std::vector binary; + // Keep collecting addresses and vendor records if the crash binary cannot be allocated. + try { + if (counts.vendorBinarySize <= binary.max_size()) + binary.resize(static_cast(counts.vendorBinarySize)); + } catch (...) { + } + counts.vendorBinarySize = binary.size(); + VkDeviceFaultInfoEXT fault{VK_STRUCTURE_TYPE_DEVICE_FAULT_INFO_EXT}; + fault.pAddressInfos = addresses.data(); + fault.pVendorInfos = vendors.data(); + fault.pVendorBinaryData = binary.data(); + result = vkGetDeviceFaultInfoEXT(device_, &counts, &fault); + if (result != VK_SUCCESS && result != VK_INCOMPLETE) { + std::fprintf(stderr, "[rt] device-fault: vkGetDeviceFaultInfoEXT data failed (%d)\n", int(result)); + return; + } + std::fprintf(stderr, "[rt] device-fault: description: %.*s%s\n", int(sizeof(fault.description)), + fault.description, result == VK_INCOMPLETE ? " (partial report)" : ""); + for (std::size_t i = 0; i < counts.addressInfoCount; ++i) { + const auto& address = addresses[i]; + std::fprintf(stderr, "[rt] device-fault: address[%zu] type=%d address=0x%" PRIx64 + " precision=%" PRIu64 "\n", + i, int(address.addressType), address.reportedAddress, address.addressPrecision); + } + for (std::size_t i = 0; i < counts.vendorInfoCount; ++i) { + const auto& vendor = vendors[i]; + std::fprintf(stderr, "[rt] device-fault: vendor[%zu] %.*s code=0x%" PRIx64 " data=0x%" PRIx64 "\n", + i, int(sizeof(vendor.description)), vendor.description, vendor.vendorFaultCode, + vendor.vendorFaultData); + } + } + + void report_queue(VkQueue queue) const { + std::uint32_t count = 0; + vkGetQueueCheckpointDataNV(queue, &count, nullptr); + std::vector data(count, {VK_STRUCTURE_TYPE_CHECKPOINT_DATA_NV}); + if (count) vkGetQueueCheckpointDataNV(queue, &count, data.data()); + std::fprintf(stderr, "[rt] device-fault: queue %p checkpoints=%u\n", static_cast(queue), count); + for (std::uint32_t i = 0; i < count; ++i) { + const auto& checkpoint = data[i]; + const auto stage = static_cast(checkpoint.stage); + const auto marker = CheckpointMarker::decode(reinterpret_cast(checkpoint.pCheckpointMarker)); + if (!marker.submission) { + std::fprintf(stderr, "[rt] device-fault: stage=0x%" PRIx64 " marker=%p (unrecognized)\n", + stage, checkpoint.pCheckpointMarker); + continue; + } + std::fprintf(stderr, "[rt] device-fault: stage=0x%" PRIx64 " submission=%u list=%u command=%u kind=%s\n", + stage, marker.submission, marker.list, marker.command, marker.kind_name()); + const auto& entry = recent_[marker.submission % recent_.size()]; + if (entry.sequence != marker.submission || entry.queue != queue || marker.list >= entry.lists.size()) { + std::fprintf(stderr, "[rt] device-fault: submission metadata unavailable\n"); + continue; + } + std::fprintf(stderr, "[rt] device-fault: ExecuteCommandLists #%" PRIu64 " queue=%p (%s) lists=%zu\n", + entry.execute_call, static_cast(entry.queue), entry.queue_kind, entry.list_count); + const auto& shaders = entry.lists[marker.list].shaders; + const auto next = std::upper_bound(shaders.begin(), shaders.end(), marker.command, + [](auto command, const auto& change) { return command < change.command; }); + if (next != shaders.begin()) { + const auto& pipeline = (next - 1)->pipeline; + std::fprintf(stderr, "[rt] device-fault: last shader pipeline=0x%" PRIx64 " shaders=%s %s %s\n", + pipeline_handle(pipeline.handle), pipeline.shaders[0] ? pipeline.shaders[0] : "-", + pipeline.shaders[1] ? pipeline.shaders[1] : "-", + pipeline.shaders[2] ? pipeline.shaders[2] : "-"); + } + } + } + + template + static std::uint64_t pipeline_handle(Handle handle) { + if constexpr (VK_USE_64_BIT_PTR_DEFINES) return reinterpret_cast(handle); + else return handle; + } + + VkDevice device_; + PFN_vkGetDeviceFaultInfoEXT vkGetDeviceFaultInfoEXT = nullptr; + PFN_vkCmdSetCheckpointNV vkCmdSetCheckpointNV = nullptr; + PFN_vkGetQueueCheckpointDataNV vkGetQueueCheckpointDataNV = nullptr; + std::atomic reported_{false}; + std::atomic execute_calls_{0}; + std::uint32_t sequence_ = 0; + std::mutex mutex_; // leaf lock, guards queues_ and recent_ + std::vector queues_; + const bool include_roots_ = [] { + const char* value = std::getenv("LEONIDA_DEVICE_FAULT_ROOTS"); + return value && !std::strcmp(value, "1"); + }(); + std::array dispatches_{}; + std::size_t dispatch_count_ = 0; + std::array recent_; +}; + +} // namespace leonida diff --git a/runtime/src/vulkan_present.h b/runtime/src/vulkan_present.h index 97c365b5f8..6e75d1c545 100644 --- a/runtime/src/vulkan_present.h +++ b/runtime/src/vulkan_present.h @@ -27,6 +27,7 @@ #include "vulkan_backend.h" #include "vulkan_present_compose.h" +#include "fsdraw_probe.h" // LOCAL DIAGNOSTIC // Use the original EXT spellings. They are aliases of the promoted KHR types and are available in older headers. #if defined(VK_EXT_SWAPCHAIN_MAINTENANCE_1_EXTENSION_NAME) && defined(VK_EXT_SURFACE_MAINTENANCE_1_EXTENSION_NAME) @@ -185,6 +186,11 @@ class VulkanPresenter { if (const char* limit = std::getenv("LEONIDA_CAPTURE_LIMIT")) capture_limit_ = std::max(1, std::atoi(limit)); std::fprintf(stderr, "[rt] present: capture on: every %d presented frame(s), at most %d, into %s\n", capture_every_, capture_limit_, capture_dir_.c_str()); + // LOCAL DIAGNOSTIC: LEONIDA_CAPTURE_SOURCE=1 also reads back the presented source texture itself. + if (const char* source = std::getenv("LEONIDA_CAPTURE_SOURCE"); source && *source && *source != '0') { + probe_source_ = true; + std::fprintf(stderr, "[rt] present-probe: source capture on\n"); + } } ok_ = recreate(true, false); if (!ok_ && capture_to_disk_) { @@ -204,7 +210,7 @@ class VulkanPresenter { const VkDevice device = context_.device(); { std::lock_guard lock(context_.submit_mutex()); - vk.vkQueueWaitIdle(queue_); + context_.observe_result(vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle (present)"); // A WSI layer may perform a device-wide idle while destroying the swapchain. // Keep that implicit idle serialized with submits from every context queue. release(swapchain_); @@ -219,6 +225,7 @@ class VulkanPresenter { if (frame.done) vkDestroyFence_(device, frame.done, nullptr); if (frame.acquired) vk.vkDestroySemaphore(device, frame.acquired, nullptr); } + if (probe_fence_) vkDestroyFence_(device, probe_fence_, nullptr); // LOCAL DIAGNOSTIC if (pool_) vk.vkDestroyCommandPool(device, pool_, nullptr); if (surface_ && vkDestroySurfaceKHR_) vkDestroySurfaceKHR_(instance_, surface_, nullptr); } @@ -340,6 +347,7 @@ class VulkanPresenter { bool enable_capture() { std::lock_guard lock(present_mutex_); if (!ok_) return false; + splash_capture_only_ = false; capture_ = true; stale_ = true; if (!recreate(vsync_, swapchain_srgb_, swapchain_hdr_req_) || (swapchain_ && !capture_buffer_)) { @@ -349,6 +357,9 @@ class VulkanPresenter { return true; } + // Present the shell image immediately. Keep it on screen until the window has a non-black title frame. + bool present_splash(ResourceId source, std::shared_ptr owner); + // The last presented frame as the swapchain stores it (4 bytes a texel, rows tightly packed, format() order). // Waits for the frame to finish. False when nothing was presented since enable_capture(), after a present // that was skipped because the window is minimised (it returned VK_SUCCESS but showed nothing), until the next @@ -357,7 +368,8 @@ class VulkanPresenter { std::lock_guard lock(present_mutex_); if (!capture_ || !capture_ptr_ || !captured_) return false; const Frame& frame = frames_[(frame_index_ + frames_.size() - 1) % frames_.size()]; - if (vkWaitForFences_(context_.device(), 1, &frame.done, VK_TRUE, UINT64_MAX) != VK_SUCCESS) + if (context_.observe_result(vkWaitForFences_(context_.device(), 1, &frame.done, VK_TRUE, UINT64_MAX), + "vkWaitForFences (present readback)") != VK_SUCCESS) return false; pixels.assign(capture_ptr_, capture_ptr_ + std::size_t(captured_extent_.width) * captured_extent_.height * 4); if (extent) *extent = captured_extent_; @@ -393,6 +405,9 @@ class VulkanPresenter { if (source_rect) pending.rect = *source_rect; if (planes) pending.planes = *planes; deferred_.push_back(pending); + if (const std::uint64_t n = ++probe_deferred_; n <= 8 || n % 600 == 0) // LOCAL DIAGNOSTIC + std::fprintf(stderr, "[rt] present-probe: present #%llu queued behind held work (%zu queued)\n", + static_cast(n), deferred_.size()); last_tore_ = false; context_.holds().after_held(this, [this] { run_deferred(); }); return VK_SUCCESS; @@ -455,6 +470,7 @@ class VulkanPresenter { VkResult submit_now(const ResourceBinding* binding, ResourceId source, bool vsync, const PresentRect* source_rect, bool srgb, bool tear = false, const PresentPlanes* planes = nullptr) { last_tore_ = false; + probe_path(binding, source, planes); // LOCAL DIAGNOSTIC if (!ok_) return VK_ERROR_INITIALIZATION_FAILED; if (surface_lost_) { // the window's display went away under a presented swapchain // Try to make a new surface for the same window (the hwnd is retained by the factory's callback). @@ -478,7 +494,7 @@ class VulkanPresenter { if (vsync != vsync_ || stale_ || srgb != swapchain_srgb_ || want_hdr != swapchain_hdr_req_) { // The swapchain's colour encoding is only recorded once the new swapchain exists, so a failed // recreate is tried again at the next present. - if (!recreate(vsync, srgb, want_hdr)) return VK_ERROR_OUT_OF_DATE_KHR; + if (!recreate_for_present(vsync, srgb, want_hdr)) return VK_ERROR_OUT_OF_DATE_KHR; } if (!swapchain_) { // minimised: try again next frame stale_ = true; @@ -492,7 +508,9 @@ class VulkanPresenter { auto& vk = context_.vk; const VkDevice device = context_.device(); Frame& frame = frames_[frame_index_ % frames_.size()]; - if (const VkResult waited = vkWaitForFences_(device, 1, &frame.done, VK_TRUE, UINT64_MAX); waited != VK_SUCCESS) + if (const VkResult waited = context_.observe_result( + vkWaitForFences_(device, 1, &frame.done, VK_TRUE, UINT64_MAX), "vkWaitForFences (present)"); + waited != VK_SUCCESS) return stop(waited); // Every submit copies into the same mapped buffer, even if its frame is outside the disk capture stride. if (const VkResult r = finish_pending_capture(); r != VK_SUCCESS) return stop(r); @@ -500,7 +518,7 @@ class VulkanPresenter { std::uint32_t image = 0; VkResult acquired = acquire(frame.acquired, &image); if (acquired == VK_ERROR_OUT_OF_DATE_KHR) { - if (!recreate(vsync, swapchain_srgb_, swapchain_hdr_req_)) return acquired; + if (!recreate_for_present(vsync, swapchain_srgb_, swapchain_hdr_req_)) return acquired; if (!swapchain_) { // minimised since the last present: skipped, as above captured_ = false; return VK_SUCCESS; @@ -571,7 +589,8 @@ class VulkanPresenter { plane_rollbacks[i].layout); }; if (!recorded) return give_back(frame, VK_ERROR_UNKNOWN); // released by another thread since presentable() - if (const VkResult reset = vkResetFences_(device, 1, &frame.done); reset != VK_SUCCESS) { + if (const VkResult reset = context_.observe_result(vkResetFences_(device, 1, &frame.done), + "vkResetFences (present)"); reset != VK_SUCCESS) { rollback(); return stop(reset); } @@ -603,15 +622,34 @@ class VulkanPresenter { const bool tearing = false; (void)tear; #endif + const bool inspect = splash_owner_ && capture_ptr_; + bool show_title = false; + if (inspect) { + submit_info.signalSemaphoreCount = 0; // signal ready only after choosing the image the window will show + if (!tracker_lock.owns_lock()) tracker_lock.lock(); + } VkResult submitted, result = VK_SUCCESS; { std::lock_guard lock(context_.submit_mutex()); - submitted = vk.vkQueueSubmit(queue_, 1, &submit_info, frame.done); + submitted = context_.observe_result(vk.vkQueueSubmit(queue_, 1, &submit_info, frame.done), + "vkQueueSubmit (present)"); + if (submitted == VK_SUCCESS) context_.note_image_work_locked(); if (submitted != VK_SUCCESS) rollback(); - // Commit/rollback happened before releasing tracker_mutex_ inside submit_mutex(), preserving submission - // order without holding tracker_mutex_ across vkQueuePresentKHR. + if (submitted == VK_SUCCESS && inspect) { + result = finish_startup_frame(frame, image, show_title); + if (result != VK_SUCCESS) return stop(result); + } if (tracker_lock.owns_lock()) tracker_lock.unlock(); - if (submitted == VK_SUCCESS) result = vkQueuePresentKHR_(queue_, &present); + if (submitted == VK_SUCCESS) + result = context_.observe_result(vkQueuePresentKHR_(queue_, &present), "vkQueuePresentKHR"); + } + if (show_title && (result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR)) { + splash_owner_.reset(); + if (splash_capture_only_) { + splash_capture_only_ = false; + capture_ = false; + release_capture(); + } } if (submitted != VK_SUCCESS) return give_back(frame, submitted); ++frame_index_; @@ -648,6 +686,310 @@ class VulkanPresenter { } private: + // ---- LOCAL DIAGNOSTIC (not for upstream): which path each present takes, and the source texture's contents ---- + bool probe_source_ = false; + std::uint64_t probe_calls_ = 0, probe_blit_ = 0, probe_compose_ = 0, probe_blank_ = 0, probe_unresolved_ = 0; + std::atomic probe_deferred_{0}; + int probe_written_ = 0; + VkCommandBuffer probe_commands_ = VK_NULL_HANDLE; + VkFence probe_fence_ = VK_NULL_HANDLE; + + static float probe_half(std::uint16_t h) { + const std::uint32_t sign = (h >> 15) & 1, exponent = (h >> 10) & 0x1f, mantissa = h & 0x3ff; + float v; + if (exponent == 0) v = std::ldexp(float(mantissa), -24); + else if (exponent == 31) v = mantissa ? 0.0f : 65504.0f; // NaN reads as 0, inf as the largest half + else v = std::ldexp(float(mantissa | 0x400), int(exponent) - 25); + return sign ? -v : v; + } + static float probe_uf11(std::uint32_t bits, int mantissa_bits) { // B10G11R11 channels (5-bit exponent) + const std::uint32_t exponent = (bits >> mantissa_bits) & 0x1f, mantissa = bits & ((1u << mantissa_bits) - 1); + if (exponent == 0) return std::ldexp(float(mantissa), -14 - mantissa_bits); + if (exponent == 31) return 65504.0f; + return std::ldexp(float(mantissa | (1u << mantissa_bits)), int(exponent) - 15 - mantissa_bits); + } + // RGB in 0..1 (float formats unclamped) of one texel; false for a format this probe does not decode. + static bool probe_decode(VkFormat format, const std::uint8_t* t, float rgb[3]) { + switch (format) { + case VK_FORMAT_B8G8R8A8_UNORM: case VK_FORMAT_B8G8R8A8_SRGB: + rgb[0] = t[2] / 255.0f; rgb[1] = t[1] / 255.0f; rgb[2] = t[0] / 255.0f; return true; + case VK_FORMAT_R8G8B8A8_UNORM: case VK_FORMAT_R8G8B8A8_SRGB: + rgb[0] = t[0] / 255.0f; rgb[1] = t[1] / 255.0f; rgb[2] = t[2] / 255.0f; return true; + case VK_FORMAT_A2B10G10R10_UNORM_PACK32: case VK_FORMAT_A2R10G10B10_UNORM_PACK32: { + std::uint32_t w; std::memcpy(&w, t, 4); + const float lo = (w & 0x3ff) / 1023.0f, mid = ((w >> 10) & 0x3ff) / 1023.0f, hi = ((w >> 20) & 0x3ff) / 1023.0f; + const bool bgra = format == VK_FORMAT_A2R10G10B10_UNORM_PACK32; + rgb[0] = bgra ? hi : lo; rgb[1] = mid; rgb[2] = bgra ? lo : hi; return true; + } + case VK_FORMAT_R16G16B16A16_SFLOAT: { + std::uint16_t h[3]; std::memcpy(h, t, 6); + for (int i = 0; i < 3; ++i) rgb[i] = probe_half(h[i]); + return true; + } + case VK_FORMAT_R16G16B16A16_UNORM: { + std::uint16_t h[3]; std::memcpy(h, t, 6); + for (int i = 0; i < 3; ++i) rgb[i] = h[i] / 65535.0f; + return true; + } + case VK_FORMAT_B10G11R11_UFLOAT_PACK32: { + std::uint32_t w; std::memcpy(&w, t, 4); + rgb[0] = probe_uf11(w & 0x7ff, 6); rgb[1] = probe_uf11((w >> 11) & 0x7ff, 6); rgb[2] = probe_uf11(w >> 22, 5); + return true; + } + case VK_FORMAT_R32G32B32A32_SFLOAT: + std::memcpy(rgb, t, 12); return true; + default: + return false; + } + } + + // Called at the top of submit_now(), so after any held work it was queued behind. + void probe_path(const ResourceBinding* binding, ResourceId source, const PresentPlanes* planes) { + const std::uint64_t n = ++probe_calls_; + const char* path = planes ? "present_planes(compose)" : binding ? "present(blit)" : "present_blank"; + (planes ? probe_compose_ : binding ? probe_blit_ : probe_blank_)++; + const ResourceId id = planes ? planes->plane[0].source : binding ? source : ResourceId{}; + ResourceBinding found{}; + bool resolved = false; + if (id) { + std::shared_lock lock(context_.resource_mutex_); + if (const ResourceBinding* b = context_.resolve(id)) { + found = *b; + resolved = true; + } + } + if (id && !resolved) ++probe_unresolved_; + if (n <= 6 || n % 600 == 0) + std::fprintf(stderr, + "[rt] present-probe: submit #%llu path %s source 0x%llx resolved %d image %p format %d %ux%u " + "mips %u layers %u samples %u sampled %d (blit %llu compose %llu blank %llu unresolved %llu)\n", + static_cast(n), path, static_cast(id), int(resolved), + reinterpret_cast(found.image), int(found.format), found.width, found.height, + found.mip_levels, found.array_layers, found.samples, int(found.sampled), + static_cast(probe_blit_), static_cast(probe_compose_), + static_cast(probe_blank_), static_cast(probe_unresolved_)); + // The same frames the swapchain capture takes: the one presented_ becomes when this present is shown. + if (probe_source_ && resolved && found.image && probe_written_ < capture_limit_ && + presented_ % std::uint64_t(capture_every_) == 0) + { + probe_read_source(id, presented_ + 1, path); + // LOCAL DIAGNOSTIC (fsdraw): the render targets of the frame's fullscreen draws, read back with it. + for (const std::uint64_t target : fsdraw::targets()) + if (target != id) probe_read_source(target, presented_ + 1, "fullscreen-draw target", "target"); + } + } + + // Copies mip 0, layer 0 of `id` to host memory on the presenter's queue (waited for), logs and writes it. + void probe_read_source(ResourceId id, std::uint64_t number, const char* path, const char* prefix = "source") { + const bool is_source = std::strcmp(prefix, "source") == 0; + auto& vk = context_.vk; + const VkDevice device = context_.device(); + const ReplayFunctions& fn = context_.replay_; + if (!probe_commands_) { + VkCommandBufferAllocateInfo allocate{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; + allocate.commandPool = pool_; + allocate.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; + allocate.commandBufferCount = 1; + VkFenceCreateInfo fence{VK_STRUCTURE_TYPE_FENCE_CREATE_INFO}; + if (vk.vkAllocateCommandBuffers(device, &allocate, &probe_commands_) != VK_SUCCESS || + vkCreateFence_(device, &fence, nullptr, &probe_fence_) != VK_SUCCESS) { + std::fprintf(stderr, "[rt] present-probe: cannot make the readback command buffer\n"); + probe_source_ = false; + return; + } + } + std::shared_lock resource_lock(context_.resource_mutex_); + const ResourceBinding* found = context_.resolve(id); + if (!found || !found->image) return; + const ResourceBinding binding = *found; + const BlockFormat bf = block_format(binding.format, VK_IMAGE_ASPECT_COLOR_BIT); + // Held only while the copy is recorded (fsdraw: holding them through the wait, the slow host reads and the + // file write stalled every resource creation and the boot ran out of memory). + std::unique_lock tracker_lock(context_.tracker_mutex_); + const bool tracked = context_.tracker_.tracked(id); + const VkImageSubresourceRange range{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + const VkImageLayout common = image_layout(binding, VK_IMAGE_LAYOUT_GENERAL); + LayoutPieces pieces = detail::current(&context_.tracker_, id, range, common); + const VkImageLayout layout = pieces.empty() ? VK_IMAGE_LAYOUT_UNDEFINED : pieces[0].layout; + std::fprintf(stderr, + "[rt] present-probe: %s frame %llu via %s: id 0x%llx format %d %ux%u mips %u layers %u samples %u " + "texel bytes %u tracked %d layout %d\n", + prefix, static_cast(number), path, static_cast(id), + int(binding.format), binding.width, binding.height, binding.mip_levels, binding.array_layers, + binding.samples, bf.bytes, int(tracked), int(layout)); + if (layout == VK_IMAGE_LAYOUT_UNDEFINED) { + std::fprintf(stderr, "[rt] present-probe: %s frame %llu is UNDEFINED in the tracker: no tracked GPU " + "operation ever wrote it (the present zero-fills it)\n", + prefix, static_cast(number)); + if (is_source) ++probe_written_; + return; + } + if (binding.samples > 1 || bf.block != 1 || !bf.bytes) { + std::fprintf(stderr, "[rt] present-probe: %s format %d not read back\n", prefix, int(binding.format)); + return; + } + const VkDeviceSize size = VkDeviceSize(binding.width) * binding.height * bf.bytes; + VkBuffer buffer = VK_NULL_HANDLE; + VkDeviceMemory memory = VK_NULL_HANDLE; + void* mapped = nullptr; + VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; + info.size = size; + info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT; + if (vk.vkCreateBuffer(device, &info, nullptr, &buffer) != VK_SUCCESS) return; + VkMemoryRequirements requirements{}; + vk.vkGetBufferMemoryRequirements(device, buffer, &requirements); + VkPhysicalDeviceMemoryProperties props{}; + vkGetPhysicalDeviceMemoryProperties_(physical_, &props); + constexpr VkMemoryPropertyFlags wanted = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; + std::uint32_t type = UINT32_MAX; + // Host-cached system memory first (fsdraw): a resizable-BAR type is uncached for host reads. + for (int pass = 0; pass < 2 && type == UINT32_MAX; ++pass) + for (std::uint32_t i = 0; i < props.memoryTypeCount; ++i) { + const VkMemoryPropertyFlags f = props.memoryTypes[i].propertyFlags; + const bool cached = (f & VK_MEMORY_PROPERTY_HOST_CACHED_BIT) && !(f & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); + if ((requirements.memoryTypeBits & (1u << i)) && (f & wanted) == wanted && (pass || cached)) { + type = i; + break; + } + } + VkMemoryAllocateInfo allocate{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; + allocate.allocationSize = requirements.size; + allocate.memoryTypeIndex = type; + const auto cleanup = [&] { + if (memory) vk.vkFreeMemory(device, memory, nullptr); + if (buffer) vk.vkDestroyBuffer(device, buffer, nullptr); + }; + if (type == UINT32_MAX || vk.vkAllocateMemory(device, &allocate, nullptr, &memory) != VK_SUCCESS || + vk.vkBindBufferMemory(device, buffer, memory, 0) != VK_SUCCESS || + vk.vkMapMemory(device, memory, 0, VK_WHOLE_SIZE, 0, &mapped) != VK_SUCCESS) { + cleanup(); + return; + } + VkCommandBuffer commands = probe_commands_; + vk.vkResetCommandBuffer(commands, 0); + VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; + begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + vk.vkBeginCommandBuffer(commands, &begin); + constexpr VkAccessFlags any = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; + for (const auto& piece : pieces) + detail::image_barrier(fn, commands, binding, piece.range, piece.layout, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, + any, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_TRANSFER_READ_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT); + VkBufferImageCopy copy{}; + copy.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; + copy.imageExtent = {binding.width, binding.height, 1}; + fn.copy_image_to_buffer(commands, binding.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, buffer, 1, ©); + for (const auto& piece : pieces) + detail::image_barrier(fn, commands, binding, piece.range, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, piece.layout, + VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, any, + VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); + VkBufferMemoryBarrier to_host{VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER}; + to_host.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + to_host.dstAccessMask = VK_ACCESS_HOST_READ_BIT; + to_host.srcQueueFamilyIndex = to_host.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + to_host.buffer = buffer; + to_host.size = VK_WHOLE_SIZE; + fn.pipeline_barrier(commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, 0, nullptr, 1, + &to_host, 0, nullptr); + vk.vkEndCommandBuffer(commands); + tracker_lock.unlock(); + resource_lock.unlock(); + vkResetFences_(device, 1, &probe_fence_); + VkSubmitInfo submit_info{VK_STRUCTURE_TYPE_SUBMIT_INFO}; + submit_info.commandBufferCount = 1; + submit_info.pCommandBuffers = &commands; + VkResult submitted; + { + std::lock_guard lock(context_.submit_mutex()); + submitted = context_.observe_result(vk.vkQueueSubmit(queue_, 1, &submit_info, probe_fence_), + "vkQueueSubmit (present probe)"); + if (submitted == VK_SUCCESS) context_.note_image_work_locked(); + } + if (submitted != VK_SUCCESS || + context_.observe_result(vkWaitForFences_(device, 1, &probe_fence_, VK_TRUE, 5'000'000'000ull), + "vkWaitForFences (present probe)") != VK_SUCCESS) { + std::fprintf(stderr, "[rt] present-probe: readback submit/wait failed (%d)\n", int(submitted)); + cleanup(); + return; + } + const std::size_t texels = std::size_t(binding.width) * binding.height; + const auto* bytes = static_cast(mapped); + std::vector rgb(texels * 3); + double sum[3] = {0, 0, 0}; + float peak = 0.0f; + std::size_t nonzero = 0; + bool decoded = true; + for (std::size_t i = 0; i < texels && decoded; ++i) { + float c[3]; + if (!probe_decode(binding.format, bytes + i * bf.bytes, c)) { + decoded = false; + break; + } + bool any_set = false; + for (int k = 0; k < 3; ++k) { + sum[k] += c[k]; + peak = std::max(peak, c[k]); + if (c[k] != 0.0f) any_set = true; + rgb[i * 3 + k] = std::uint8_t(std::clamp(c[k], 0.0f, 1.0f) * 255.0f + 0.5f); + } + nonzero += any_set; + } + // Raw bytes too: a format the probe cannot decode still says whether anything was written. + std::size_t raw_nonzero = 0; + std::size_t first_nonzero = SIZE_MAX; + for (std::size_t i = 0; i < std::size_t(size); ++i) + if (bytes[i]) { + if (first_nonzero == SIZE_MAX) first_nonzero = i; + ++raw_nonzero; + } + { // LOCAL DIAGNOSTIC (fsdraw): raw texels at the centre and at the first non-zero byte + const std::size_t centre = (std::size_t(binding.height / 2) * binding.width + binding.width / 2) * bf.bytes; + std::string c, f; + char b[8]; + for (std::uint32_t k = 0; k < bf.bytes && k < 16; ++k) { + std::snprintf(b, sizeof b, "%02x", bytes[centre + k]); + c += b; + } + if (first_nonzero != SIZE_MAX) { + const std::size_t t = first_nonzero / bf.bytes * bf.bytes; + for (std::uint32_t k = 0; k < bf.bytes && k < 16; ++k) { + std::snprintf(b, sizeof b, "%02x", bytes[t + k]); + f += b; + } + } + std::fprintf(stderr, "[rt] present-probe: %s frame %llu raw centre texel %s first non-zero texel %lld (%s)\n", + prefix, static_cast(number), c.c_str(), + first_nonzero == SIZE_MAX ? -1ll : static_cast(first_nonzero / bf.bytes), f.c_str()); + } + cleanup(); + const double scale = 255.0 / double(texels); + std::fprintf(stderr, + "[rt] present-probe: %s frame %llu mean rgb %.2f %.2f %.2f (0..255 scale) peak %.3f nonzero " + "texels %zu of %zu, nonzero bytes %zu of %llu%s\n", + prefix, static_cast(number), sum[0] * scale, sum[1] * scale, sum[2] * scale, peak, + nonzero, texels, raw_nonzero, static_cast(size), + decoded ? "" : " (format not decoded)"); + std::string dir = capture_dir_; + if (dir.back() != '/' && dir.back() != '\\') dir += '/'; + if (decoded && (is_source || nonzero)) { + char name[64]; + std::snprintf(name, sizeof name, "%s_%05llu.ppm", prefix, static_cast(number)); + std::ofstream file(dir + name, std::ios::binary | std::ios::trunc); + if (file) { + file << "P6\n" << binding.width << ' ' << binding.height << "\n255\n"; + file.write(reinterpret_cast(rgb.data()), std::streamsize(rgb.size())); + } + } + std::ofstream index(dir + "source_index.txt", std::ios::app); + if (index) + index << prefix << " frame " << number << " id 0x" << std::hex << id << std::dec << " path " << path << " format " << int(binding.format) << " extent " + << binding.width << 'x' << binding.height << " layout " << int(layout) << " mean rgb " << std::fixed + << std::setprecision(2) << sum[0] * scale << ' ' << sum[1] * scale << ' ' << sum[2] * scale + << " nonzero texels " << nonzero << " nonzero bytes " << raw_nonzero << '\n'; + if (is_source) ++probe_written_; + } + // ---- end LOCAL DIAGNOSTIC ---- + struct Frame { VkCommandBuffer commands = VK_NULL_HANDLE; VkFence done = VK_NULL_HANDLE; @@ -655,6 +997,9 @@ class VulkanPresenter { std::array views{}; // the plane views of the last composed present, until the frame is reused }; + bool recreate_for_present(bool vsync, bool srgb, bool hdr); + VkResult finish_startup_frame(Frame& frame, std::uint32_t image, bool& show_title); + // Whether `source` is a colour texture the device knows, so present() can refuse it before acquiring an image. bool presentable(ResourceId source) { std::shared_lock lock(context_.resource_mutex_); // the resource table (vulkan_backend.h) @@ -667,7 +1012,8 @@ class VulkanPresenter { // present, which gives back the image that was never presented. Returns `failure`, the error to report. VkResult give_back(Frame& frame, VkResult failure) { const VkDevice device = context_.device(); - if (vkResetFences_(device, 1, &frame.done) != VK_SUCCESS) return stop(failure); + if (context_.observe_result(vkResetFences_(device, 1, &frame.done), "vkResetFences (present)") != VK_SUCCESS) + return stop(failure); const VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; VkSubmitInfo submit_info{VK_STRUCTURE_TYPE_SUBMIT_INFO}; submit_info.waitSemaphoreCount = 1; @@ -676,7 +1022,8 @@ class VulkanPresenter { VkResult submitted; { std::lock_guard lock(context_.submit_mutex()); - submitted = context_.vk.vkQueueSubmit(queue_, 1, &submit_info, frame.done); + submitted = context_.observe_result(context_.vk.vkQueueSubmit(queue_, 1, &submit_info, frame.done), + "vkQueueSubmit (return present image)"); } if (submitted != VK_SUCCESS) return stop(failure); stale_ = true; @@ -707,7 +1054,8 @@ class VulkanPresenter { const VkDevice device = context_.device(); { std::lock_guard lock(context_.submit_mutex()); - vk.vkQueueWaitIdle(queue_); // the old swapchain's images and semaphores may still be in use + // The old swapchain's images and semaphores may still be in use. + context_.observe_result(vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle (present)"); release(swapchain_); } swapchain_ = VK_NULL_HANDLE; @@ -796,7 +1144,8 @@ class VulkanPresenter { return true; { std::lock_guard lock(context_.submit_mutex()); - context_.vk.vkQueueWaitIdle(queue_); // the old target may still be in use + // The old target may still be in use. + context_.observe_result(context_.vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle (present)"); } bool changed = false; return composer_->ensure_target(extent_, changed); @@ -921,8 +1270,9 @@ class VulkanPresenter { VkResult acquire(VkSemaphore semaphore, std::uint32_t* image) { for (;;) { - const VkResult result = vkAcquireNextImageKHR_(context_.device(), swapchain_, 50'000'000, semaphore, - VK_NULL_HANDLE, image); + const VkResult result = context_.observe_result( + vkAcquireNextImageKHR_(context_.device(), swapchain_, 50'000'000, semaphore, VK_NULL_HANDLE, image), + "vkAcquireNextImageKHR"); if (result != VK_TIMEOUT && result != VK_NOT_READY) return result; if (should_abort()) return VK_NOT_READY; } @@ -1050,7 +1400,8 @@ class VulkanPresenter { VkResult finish_pending_capture() { if (!pending_capture_) return VK_SUCCESS; - const VkResult waited = vkWaitForFences_(context_.device(), 1, &pending_capture_, VK_TRUE, UINT64_MAX); + const VkResult waited = context_.observe_result( + vkWaitForFences_(context_.device(), 1, &pending_capture_, VK_TRUE, UINT64_MAX), "vkWaitForFences (capture)"); pending_capture_ = VK_NULL_HANDLE; if (waited == VK_SUCCESS) write_capture(); return waited; @@ -1145,7 +1496,8 @@ class VulkanPresenter { const VkDevice device = context_.device(); { std::lock_guard lock(context_.submit_mutex()); - vk.vkQueueWaitIdle(queue_); // the old swapchain's images and semaphores may still be in use + // The old swapchain's images and semaphores may still be in use. + context_.observe_result(vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle (present)"); } if (finish_pending_capture() != VK_SUCCESS) return false; stale_ = true; // until this succeeds @@ -1288,7 +1640,8 @@ class VulkanPresenter { swapchain_ = VK_NULL_HANDLE; info.oldSwapchain = old; VkSwapchainKHR fresh = VK_NULL_HANDLE; - const VkResult created = vkCreateSwapchainKHR_(device, &info, nullptr, &fresh); + const VkResult created = context_.observe_result(vkCreateSwapchainKHR_(device, &info, nullptr, &fresh), + "vkCreateSwapchainKHR"); { std::lock_guard lock(context_.submit_mutex()); release(old); // retired by the creation attempt, whether or not it succeeded @@ -1440,6 +1793,10 @@ class VulkanPresenter { bool surface_lost_ = false; // set by mark_surface_lost(); cleared once a new surface was created std::map features_; bool warned_srgb_ = false; + std::shared_ptr splash_owner_; + ResourceBinding splash_binding_{}; + ResourceId splash_source_{}; + bool splash_capture_only_ = false; bool capture_ = false; VkBuffer capture_buffer_ = VK_NULL_HANDLE; VkDeviceMemory capture_memory_ = VK_NULL_HANDLE; @@ -1479,3 +1836,5 @@ class VulkanPresenter { }; } // namespace leonida + +#include "vulkan_present_splash.h" diff --git a/runtime/src/vulkan_present_splash.h b/runtime/src/vulkan_present_splash.h new file mode 100644 index 0000000000..9dd94a313e --- /dev/null +++ b/runtime/src/vulkan_present_splash.h @@ -0,0 +1,63 @@ +#pragma once + +#include "vulkan_present.h" + +namespace leonida { + +inline bool VulkanPresenter::present_splash(ResourceId source, std::shared_ptr owner) { + std::lock_guard lock(present_mutex_); + if (!deferred_.empty() || context_.holds().any_held()) return false; + { + std::shared_lock resources(context_.resource_mutex_); + const auto* binding = context_.resolve(source); + if (!binding || !binding->image) return false; + splash_binding_ = *binding; + } + if (!capture_) splash_capture_only_ = enable_capture(); + const auto before = presented(); + if (present(source, true) != VK_SUCCESS || presented() == before) return false; + const Frame& frame = frames_[(frame_index_ - 1) % frames_.size()]; + if (vkWaitForFences_(context_.device(), 1, &frame.done, VK_TRUE, UINT64_MAX) != VK_SUCCESS || + finish_pending_capture() != VK_SUCCESS) return false; + if (capture_ptr_) { + splash_source_ = source; + splash_owner_ = std::move(owner); + } + return true; +} + +// A changed surface or colour format may not support readback. Keep the title able to present on it. +inline bool VulkanPresenter::recreate_for_present(bool vsync, bool srgb, bool hdr) { + if (recreate(vsync, srgb, hdr)) return true; + if (!splash_capture_only_) return false; + splash_owner_.reset(); + splash_capture_only_ = false; + capture_ = false; + return recreate(vsync, srgb, hdr); +} + +// Called only during the launch handoff, with the tracker and queue locked. Check the composed pixels so a +// transparent overlay or a clear with nonzero alpha cannot dismiss the splash. Later black frames are genuine. +inline VkResult VulkanPresenter::finish_startup_frame(Frame& frame, std::uint32_t image, bool& show_title) { + const VkDevice device = context_.device(); + VkResult result = vkWaitForFences_(device, 1, &frame.done, VK_TRUE, UINT64_MAX); + if (result != VK_SUCCESS) return result; + const bool ten_bit = format_ == VK_FORMAT_A2B10G10R10_UNORM_PACK32 || format_ == VK_FORMAT_A2R10G10B10_UNORM_PACK32; + const std::uint32_t rgb = ten_bit ? 0x3fffffffu : 0xffffffu; + const auto* pixels = reinterpret_cast(capture_ptr_); + const auto count = std::size_t(extent_.width) * extent_.height; + show_title = std::any_of(pixels, pixels + count, [rgb](auto pixel) { return (pixel & rgb) != 0; }); + VkSubmitInfo ready{VK_STRUCTURE_TYPE_SUBMIT_INFO}; + ready.signalSemaphoreCount = 1; + ready.pSignalSemaphores = &ready_[image]; + if (show_title) return context_.vk.vkQueueSubmit(queue_, 1, &ready, VK_NULL_HANDLE); + // The acquire was consumed and the title commands finished. Overwrite the same image before presenting it. + record(frame.commands, splash_binding_, splash_source_, image, nullptr); + result = vkResetFences_(device, 1, &frame.done); + if (result != VK_SUCCESS) return result; + ready.commandBufferCount = 1; + ready.pCommandBuffers = &frame.commands; + return context_.vk.vkQueueSubmit(queue_, 1, &ready, frame.done); +} + +} // namespace leonida diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 7dcc7e2c0a..ce345e023b 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -1,4 +1,6 @@ #pragma once +#include +#include #include "resource_tiling.h" @@ -31,7 +33,10 @@ // A list that needs a missing function fails with ReplayResult::unsupported before anything is written. #include "command_list.h" +#include "deferred_image_binding.h" +#include "vulkan_device_fault.h" #include "depth24.h" +#include "rect_list_geometry.h" #include "uav_clear.h" #include @@ -41,8 +46,10 @@ #include #include +#include #include #include +#include #include #include #include @@ -97,6 +104,8 @@ struct ResourceBinding { bool sampled = false; // has SAMPLED usage (no DENY_SHADER_RESOURCE): the present compose pass reads it bool host_readable = false; // D3D12_HEAP_TYPE_READBACK (or CUSTOM write-back): needs host-read flush bool sparse_buffer = false; + DeferredImageBinding* deferred_memory = nullptr; // Owned by the placed resource until it leaves the context. + std::atomic* replay_seen = nullptr; // Optional census of placed image use under the resource lock. }; struct VulkanAccess { @@ -469,7 +478,11 @@ inline BlockFormat block_format(VkFormat format, VkImageAspectFlags aspect) { case VK_FORMAT_R8_UNORM: case VK_FORMAT_R8_SNORM: case VK_FORMAT_R8_UINT: - case VK_FORMAT_R8_SINT: return {1, 1}; + case VK_FORMAT_R8_SINT: +#ifdef VK_KHR_MAINTENANCE_5_EXTENSION_NAME + case VK_FORMAT_A8_UNORM_KHR: // an A8_UNORM render target (VulkanDeviceInfo::a8_render_target) +#endif + return {1, 1}; case VK_FORMAT_BC1_RGBA_UNORM_BLOCK: case VK_FORMAT_BC1_RGBA_SRGB_BLOCK: case VK_FORMAT_BC4_UNORM_BLOCK: @@ -759,6 +772,12 @@ struct ComputePipeline { VkPipelineLayout layout = VK_NULL_HANDLE; std::uint64_t code_base = 0; VkDescriptorSet bindless_set = VK_NULL_HANDLE; // set 0 of the layout, bound at every dispatch; null: none + // A pipeline built on first use: with `pipeline` null, `build(build_context)` returns the handle (building it if + // nobody has yet), or null when it cannot be built. Null `build`: `pipeline` is final. + VkPipeline (*build)(void*) = nullptr; + void* build_context = nullptr; + bool async_build = false; // a null handle may be waiting for the compile worker + bool skipped = false; // never built on request (LEONIDA_SKIP_COMPUTE): its dispatches are dropped }; // A graphics pipeline as replay needs it: the formats its attachments must have and which vertex-input slots it @@ -783,6 +802,7 @@ struct GraphicsPipeline { static constexpr std::uint32_t unbound_depth = 1u << 8; std::function variant; std::uint32_t samples = 1; // rasterizationSamples; every bound attachment must have this count + bool async_build = false; }; // The 144-byte push-constant block every translated shader declares: s0..s31, heap base, code base. @@ -811,6 +831,61 @@ enum class ReplayResult { unsupported }; +// LOCAL DIAGNOSTIC: which check called a resource unresolved, by source line, logged at the 1st, 2nd, 4th, 8th... +// time it fires (a list that fails this way is not submitted at all, so the first lines name what stops rendering). +// LEONIDA_STRICT_REPLAY=1: an unresolvable draw or dispatch fails its list again instead of being dropped. Read with +// the C runtime, not the Win32 API: this header is built into tests without windows.h too. +inline bool strict_replay() { + static const bool strict = [] { +#ifdef _WIN32 + char value[2]{}; + std::size_t length = 0; + return getenv_s(&length, value, sizeof value, "LEONIDA_STRICT_REPLAY") == 0 && length == 2 && value[0] == '1'; +#else + const char* value = std::getenv("LEONIDA_STRICT_REPLAY"); + return value && value[0] == '1' && !value[1]; +#endif + }(); + return strict; +} + +inline bool order_buffer_copies() { + static const bool enabled = [] { +#ifdef _WIN32 + char value[2]{}; + std::size_t length = 0; + return getenv_s(&length, value, sizeof value, "LEONIDA_ORDER_BUFFER_COPIES") != 0 || length != 2 || value[0] != '0'; +#else + const char* value = std::getenv("LEONIDA_ORDER_BUFFER_COPIES"); + return !value || value[0] != '0' || value[1]; +#endif + }(); + return enabled; +} + +inline ReplayResult unresolved_at(int line) { + static std::atomic seen[8192]; + if (line >= 0 && line < 8192) { + const unsigned count = seen[line].fetch_add(1, std::memory_order_relaxed) + 1; + if ((count & (count - 1)) == 0) + std::fprintf(stderr, "[rt] replay: unresolved resource at vulkan_replay.h:%d (x%u)\n", line, count); + } + return ReplayResult::unresolved_resource; +} + +// LOCAL DIAGNOSTIC, as unresolved_at: which check called a command list unsupported (the whole list is then not +// submitted: "ExecuteCommandLists failed: unsupported"), by source line, at the 1st, 2nd, 4th, 8th... time. +inline ReplayResult unsupported_at(int line) { + static std::atomic seen[8192]; + if (line >= 0 && line < 8192) { + const unsigned count = seen[line].fetch_add(1, std::memory_order_relaxed) + 1; + if ((count & (count - 1)) == 0) + std::fprintf(stderr, "[rt] replay: unsupported at vulkan_replay.h:%d (x%u)\n", line, count); + } + return ReplayResult::unsupported; +} + + struct ReplayFunctions { // Set 0 for the pipelines that declare one (their own `bindless_set` is only the marker): the device's current // generation of it, which a flush may have replaced since the pipeline was made. Null: the pipeline's. @@ -866,6 +941,7 @@ struct ReplayFunctions { PFN_vkCmdSetStencilReference set_stencil_reference = nullptr; PFN_vkCmdSetBlendConstants set_blend_constants = nullptr; PFN_vkCmdDraw draw = nullptr; + unsigned* mesh_draw_count = nullptr; // opt-in count for this submission PFN_vkCmdDrawMeshTasksEXT draw_mesh_tasks = nullptr; // VK_EXT_mesh_shader; null: mesh draws are unsupported PFN_vkCmdDrawIndexed draw_indexed = nullptr; std::function graphics_pipeline; @@ -880,6 +956,10 @@ struct ReplayFunctions { VkBuffer zero_buffer = VK_NULL_HANDLE; VkDeviceSize zero_offset = 0; VkDeviceSize zero_size = 0; + // 0, 1, 2, ... as 32-bit indices: what a non-indexed quad list is drawn with (quad_index_count of them). + VkBuffer quad_indices = VK_NULL_HANDLE; + VkDeviceSize quad_indices_offset = 0; + std::uint32_t quad_index_count = 0; std::uint64_t heap_base = 0; // device address of the GPU address arena (push-constant dwords 32-33) // Resolves available binary-occlusion queries to 64-bit 0/1 values, outside conditional rendering. std::function 4 && bytes % 4) { - return ReplayResult::unsupported; + return unsupported_at(__LINE__); } p.fills.push_back({offset, bytes}); return ReplayResult::success; @@ -1824,7 +1911,7 @@ inline ReplayResult prepare_texture_copy(const CopyTexture& copy, Prepared& p) { const BlockFormat format = copy_block_format(image, range.aspectMask); // A 12-byte texel does not divide D3D12's 256-byte pitches; an rgb96 copy hands Vulkan the scratch buffer of // the repack, never this pitch, and the pass reads the footprint in words. - if (!format.bytes || placed.row_pitch % (image.rgb96 ? 4 : format.bytes)) return ReplayResult::unsupported; + if (!format.bytes || placed.row_pitch % (image.rgb96 ? 4 : format.bytes)) return unsupported_at(__LINE__); const VkExtent2D mip = mip_extent(image, range.baseMipLevel); const auto mip_depth = std::max(1u, image.depth >> range.baseMipLevel); // The box is in the source's coordinates: the footprint for an upload, the texture for a readback. @@ -1857,7 +1944,7 @@ inline ReplayResult prepare_texture_copy(const CopyTexture& copy, Prepared& p) { // Vulkan wants a buffer offset that is a multiple of the texel size (VUID-vkCmdCopyBufferToImage-dstImage-07975), // which D3D12's 512-byte placement does not give a 12-byte texel: one more reason an rgb96 copy is repacked. const std::uint32_t alignment = (range.aspectMask & depth_stencil_aspects) || image.rgb96 ? 4 : format.bytes; - if (offset % alignment && !copy.tile_footprint) return ReplayResult::unsupported; + if (offset % alignment && !copy.tile_footprint) return unsupported_at(__LINE__); const std::uint64_t rows = (std::uint64_t(h) + format.block - 1) / format.block; const std::uint64_t row_bytes = (std::uint64_t(w) + format.block - 1) / format.block * format.bytes; if (!rows || !row_bytes || !within(std::uint64_t(placed_x / format.block) * format.bytes, row_bytes, placed.row_pitch) || @@ -1866,7 +1953,7 @@ inline ReplayResult prepare_texture_copy(const CopyTexture& copy, Prepared& p) { return ReplayResult::invalid_copy; if (buffer.size > UINT64_MAX - buffer.buffer_offset) return ReplayResult::invalid_copy; const VkDeviceSize backing_offset = buffer.buffer_offset + offset; - if (backing_offset % alignment && !copy.tile_footprint) return ReplayResult::unsupported; + if (backing_offset % alignment && !copy.tile_footprint) return unsupported_at(__LINE__); VkBufferImageCopy region{}; region.bufferOffset = backing_offset; region.bufferRowLength = placed.row_pitch / format.bytes * format.block; @@ -1875,7 +1962,7 @@ inline ReplayResult prepare_texture_copy(const CopyTexture& copy, Prepared& p) { region.imageOffset = {std::int32_t(texture_x), std::int32_t(texture_y), std::int32_t(texture_z)}; region.imageExtent = {w, h, depth}; if (image.rgb96) { // the repack's scratch replaces this buffer in the copy; these are for the pass - if (placed.row_pitch / 4 > UINT32_MAX || slice_pitch / 4 > UINT32_MAX) return ReplayResult::unsupported; + if (placed.row_pitch / 4 > UINT32_MAX || slice_pitch / 4 > UINT32_MAX) return unsupported_at(__LINE__); p.rgb96_row_words = std::uint32_t(placed.row_pitch / 4); p.rgb96_slice_words = std::uint32_t(slice_pitch / 4); region.bufferRowLength = 0; @@ -2006,15 +2093,15 @@ inline ReplayResult prepare_resolve(const ResolveSubresource& resolve, Prepared& } else if (from.width != to.width || from.height != to.height) { return ReplayResult::invalid_copy; } - if (src.aspectMask != dst.aspectMask || p.source.format != p.binding.format) return ReplayResult::unsupported; + if (src.aspectMask != dst.aspectMask || p.source.format != p.binding.format) return unsupported_at(__LINE__); const auto& region = resolve.region; if (src.aspectMask == VK_IMAGE_ASPECT_COLOR_BIT) { - if (region && region->mode != d3d12_resolve_mode::average) return ReplayResult::unsupported; + if (region && region->mode != d3d12_resolve_mode::average) return unsupported_at(__LINE__); } else { // A rendering scope resolves each pixel in place, so the destination offset must be the source's. if (!region || dst_offset.x != src_offset.x || dst_offset.y != src_offset.y || (region->mode == d3d12_resolve_mode::average && src.aspectMask != VK_IMAGE_ASPECT_DEPTH_BIT)) - return ReplayResult::unsupported; + return unsupported_at(__LINE__); p.resolve_mode = region->mode == d3d12_resolve_mode::minimum ? VK_RESOLVE_MODE_MIN_BIT : region->mode == d3d12_resolve_mode::maximum ? VK_RESOLVE_MODE_MAX_BIT : VK_RESOLVE_MODE_AVERAGE_BIT; @@ -2058,7 +2145,7 @@ inline ReplayResult keep_around_resolve(const ReplayFunctions& vk, Prepared& p) VkDeviceSize base = 0; if (!texel || !vk.copy_image_to_buffer || !vk.copy_buffer_to_image || !vk.copy_scratch || !vk.copy_scratch(total, p.staged, base)) - return ReplayResult::unsupported; + return unsupported_at(__LINE__); for (VkBufferImageCopy& region : p.staged_reads) region.bufferOffset += base; return ReplayResult::success; } @@ -2136,15 +2223,16 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct !vk.set_primitive_topology || !vk.set_primitive_restart_enable || !vk.set_stencil_reference || !vk.set_blend_constants || !vk.draw || !vk.draw_indexed || !vk.bind_pipeline || !vk.push_constants) - return ReplayResult::unsupported; + return unsupported_at(__LINE__); const GraphicsPipeline* pipeline = vk.graphics_pipeline(draw.pipeline); - if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; + // A null pipeline with a variant builder is one built at its first draw: variant 0 (all slots bound). + if (!pipeline || (!pipeline->pipeline && !pipeline->variant)) return unresolved_at(__LINE__); if (pipeline->mesh != draw.mesh) return ReplayResult::invalid_draw; - if (draw.mesh && !vk.draw_mesh_tasks) return ReplayResult::unsupported; + if (draw.mesh && !vk.draw_mesh_tasks) return unsupported_at(__LINE__); if (pipeline->viewport_with_count && (!vk.set_viewport_with_count || !vk.set_scissor_with_count)) - return ReplayResult::unsupported; - if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; - if (pipeline->color_formats.size() > max_render_targets) return ReplayResult::unsupported; + return unsupported_at(__LINE__); + if (pipeline->bindless_set && !vk.bind_descriptor_sets) return unsupported_at(__LINE__); + if (pipeline->color_formats.size() > max_render_targets) return unsupported_at(__LINE__); p.graphics = pipeline; p.pipeline = pipeline->pipeline; p.area = {UINT32_MAX, UINT32_MAX}; @@ -2161,7 +2249,7 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct const TargetView& target = draw.views->render_targets[slot]; if (!target.resource) continue; const ResourceBinding* binding = resolve(target.resource); - if (!binding) return ReplayResult::unresolved_resource; + if (!binding) return unresolved_at(__LINE__); auto& a = p.colors[slot]; a.binding = *binding; a.id = target.resource; @@ -2173,12 +2261,12 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct ResourceBinding viewed = a.binding; if (pipeline->color_formats[slot] != VK_FORMAT_UNDEFINED) viewed.format = pipeline->color_formats[slot]; a.view = vk.image_view(viewed, a.range); - if (!a.view) return ReplayResult::unsupported; + if (!a.view) return unsupported_at(__LINE__); shrink(a.binding, target, a.range); } if (draw.depth.resource && pipeline->depth_format != VK_FORMAT_UNDEFINED) { const ResourceBinding* binding = resolve(draw.depth.resource); - if (!binding) return ReplayResult::unresolved_resource; + if (!binding) return unresolved_at(__LINE__); auto& a = p.depth; a.binding = *binding; a.id = draw.depth.resource; @@ -2188,7 +2276,7 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct ResourceBinding viewed = a.binding; viewed.format = pipeline->depth_format; a.view = vk.image_view(viewed, a.range); - if (!a.view) return ReplayResult::unsupported; + if (!a.view) return unsupported_at(__LINE__); shrink(a.binding, draw.depth, a.range); } if (p.area.width == UINT32_MAX) { // no attachment: the viewports bound the rendering @@ -2211,9 +2299,13 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct for (std::size_t slot = 0; slot < p.colors.size(); ++slot) if (pipeline->color_formats[slot] != VK_FORMAT_UNDEFINED && !p.colors[slot].id) unbound |= 1u << slot; if (pipeline->depth_format != VK_FORMAT_UNDEFINED && !p.depth.id) unbound |= GraphicsPipeline::unbound_depth; - if (unbound) { + if (unbound || !p.pipeline) { p.pipeline = pipeline->variant ? pipeline->variant(unbound) : VK_NULL_HANDLE; - if (!p.pipeline) return ReplayResult::unsupported; + if (!p.pipeline && pipeline->async_build && !strict_replay()) { + p.skipped = true; + return ReplayResult::success; + } + if (!p.pipeline) return unsupported_at(__LINE__); } // An unbound vertex-buffer slot reads zeros, as in D3D12: the zero page with stride 0. Per-instance slots with @@ -2227,7 +2319,7 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct const bool bound = draw.views && slot < draw.views->vertex_buffers.size() && draw.views->vertex_buffers[slot].va; if (!bound) { - if (!vk.zero_buffer) return ReplayResult::unresolved_resource; + if (!vk.zero_buffer) return unresolved_at(__LINE__); p.vertex_buffers[slot] = vk.zero_buffer; p.vertex_offsets[slot] = vk.zero_offset; p.vertex_sizes[slot] = vk.zero_size; @@ -2236,23 +2328,38 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct } const VertexBufferView& view = draw.views->vertex_buffers[slot]; std::uint64_t size = view.size; - if (!vk.buffer_at(view.va, size, p.vertex_buffers[slot], p.vertex_offsets[slot])) - return ReplayResult::unresolved_resource; + if (!vk.buffer_at(view.va, size, p.vertex_buffers[slot], p.vertex_offsets[slot])) { + static std::atomic logged{0}; // LOCAL DIAGNOSTIC: where the unresolved vertex data lives + if (logged.fetch_add(1, std::memory_order_relaxed) < 24) + std::fprintf(stderr, "[rt] replay: vertex buffer slot %u va 0x%llx size %llu stride %u names no buffer\n", + slot, static_cast(view.va), + static_cast(view.size), unsigned(view.stride)); + return unresolved_at(__LINE__); + } p.vertex_sizes[slot] = size; p.vertex_strides[slot] = (pipeline->zero_step_slots & (1u << slot)) ? 0 : view.stride; } + // A non-indexed quad list is drawn from the shared 0, 1, 2, ... index buffer (emit). + if (!draw.indexed && !draw.mesh && draw.topology == topology_quad_list && !vk.quad_indices) + return unresolved_at(__LINE__); if (draw.indexed) { if (draw.index.format == 57) p.index_type = VK_INDEX_TYPE_UINT16; else if (draw.index.format == 42) p.index_type = VK_INDEX_TYPE_UINT32; - else if (draw.index.va) return ReplayResult::unsupported; + else if (draw.index.va) return unsupported_at(__LINE__); if (!draw.index.va) { // no index buffer: every index reads 0 - if (!vk.zero_buffer) return ReplayResult::unresolved_resource; + if (!vk.zero_buffer) return unresolved_at(__LINE__); p.index_buffer = vk.zero_buffer; p.index_offset = vk.zero_offset; } else { std::uint64_t size = draw.index.size; - if (!vk.buffer_at(draw.index.va, size, p.index_buffer, p.index_offset)) - return ReplayResult::unresolved_resource; + if (!vk.buffer_at(draw.index.va, size, p.index_buffer, p.index_offset)) { + static std::atomic logged{0}; // LOCAL DIAGNOSTIC + if (logged.fetch_add(1, std::memory_order_relaxed) < 24) + std::fprintf(stderr, "[rt] replay: index buffer va 0x%llx size %llu names no buffer\n", + static_cast(draw.index.va), + static_cast(draw.index.size)); + return unresolved_at(__LINE__); + } } } return ReplayResult::success; @@ -2275,6 +2382,11 @@ inline VkPrimitiveTopology vulkan_topology(std::uint32_t topology) { case 11: return VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY; case 12: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY; case 13: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY; + // The console's lists (rect_list_geometry.h). A rectangle list is drawn as the triangle list of its three + // corners, the pipeline's geometry stage adds the fourth. A quad (v0 v1 v2 v3) is the fan (v0 v1 v2) (v0 v2 v3), + // which is the index pattern 0 1 2, 0 2 3; the draw below issues one fan per quad. + case topology_rect_list: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; + case topology_quad_list: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN; default: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; } } @@ -2667,7 +2779,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun }; const auto rect_view = [&](std::span rects, const TargetView& target, VkImageAspectFlags view_aspects) { if (rects.empty()) return ReplayResult::success; - if (!rendering) return ReplayResult::unsupported; + if (!rendering) return unsupported_at(__LINE__); detail::clip(rects, detail::mip_extent(p.binding, target.mip), target.layer_count, p.rects); if (p.rects.empty()) { p.skip = true; @@ -2687,7 +2799,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun }; if (const auto* transition = std::get_if(&command)) { - if (!bind(transition->resource)) return ReplayResult::unresolved_resource; + if (!bind(transition->resource)) return unresolved_at(__LINE__); if (p.binding.image == VK_NULL_HANDLE) { if (transition->subresource != 0 && transition->subresource != all_subresources) return ReplayResult::invalid_subresource; @@ -2695,16 +2807,16 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun return ReplayResult::invalid_subresource; } } else if (std::holds_alternative(command) || std::holds_alternative(command)) { - if (!vk.pipeline_barrier2) return ReplayResult::unsupported; + if (!vk.pipeline_barrier2) return unsupported_at(__LINE__); if (const auto* buffer_barrier = std::get_if(&command)) - if (!bind(buffer_barrier->resource)) return ReplayResult::unresolved_resource; + if (!bind(buffer_barrier->resource)) return unresolved_at(__LINE__); } else if (const auto* texture = std::get_if(&command)) { - if (!vk.pipeline_barrier2) return ReplayResult::unsupported; - if (!bind(texture->resource)) return ReplayResult::unresolved_resource; + if (!vk.pipeline_barrier2) return unsupported_at(__LINE__); + if (!bind(texture->resource)) return unresolved_at(__LINE__); if (!p.binding.image || !barrier_range(p.binding, texture->range, p.range)) return ReplayResult::invalid_subresource; } else if (const auto* color_clear = std::get_if(&command)) { - if (!bind(color_clear->target.resource)) return ReplayResult::unresolved_resource; + if (!bind(color_clear->target.resource)) return unresolved_at(__LINE__); if (!p.binding.image || p.binding.aspects != VK_IMAGE_ASPECT_COLOR_BIT) return ReplayResult::invalid_clear; if (!detail::view_range(p.binding, color_clear->target, VK_IMAGE_ASPECT_COLOR_BIT, p.range)) return ReplayResult::invalid_subresource; @@ -2724,9 +2836,9 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun VK_IMAGE_ASPECT_COLOR_BIT); r != ReplayResult::success) return r; } else if (const auto r = rect_view(clear_rects(color_clear->rects), color_clear->target, VK_IMAGE_ASPECT_COLOR_BIT); r != ReplayResult::success) return r; - if (!p.skip && p.rects.empty() && !vk.clear_color_image) return ReplayResult::unsupported; + if (!p.skip && p.rects.empty() && !vk.clear_color_image) return unsupported_at(__LINE__); } else if (const auto* depth_clear = std::get_if(&command)) { - if (!bind(depth_clear->target.resource)) return ReplayResult::unresolved_resource; + if (!bind(depth_clear->target.resource)) return unresolved_at(__LINE__); VkImageAspectFlags aspects = 0; if (depth_clear->flags & clear_depth) aspects |= VK_IMAGE_ASPECT_DEPTH_BIT; if (depth_clear->flags & clear_stencil) aspects |= VK_IMAGE_ASPECT_STENCIL_BIT; @@ -2743,12 +2855,12 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (const auto r = rect_view(clear_rects(depth_clear->rects), depth_clear->target, p.binding.aspects); r != ReplayResult::success) return r; - if (!p.skip && p.rects.empty() && !vk.clear_depth_stencil_image) return ReplayResult::unsupported; + if (!p.skip && p.rects.empty() && !vk.clear_depth_stencil_image) return unsupported_at(__LINE__); } else if (const auto* uav = std::get_if(&command)) { const UavView& view = uav->view; - if (!bind(view.resource)) return ReplayResult::unresolved_resource; + if (!bind(view.resource)) return unresolved_at(__LINE__); if (view.buffer) { - if (!vk.fill_buffer || !vk.update_buffer || !vk.copy_buffer) return ReplayResult::unsupported; + if (!vk.fill_buffer || !vk.update_buffer || !vk.copy_buffer) return unsupported_at(__LINE__); if (predicated) ++out.unpredicated_copies; // fills and copies are transfer commands if (const auto r = detail::prepare_buffer_uav_clear(*uav, p); r != ReplayResult::success) return r; const bool short_fill = std::any_of(p.fills.begin(), p.fills.end(), [&](const auto& fill) { @@ -2757,7 +2869,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (short_fill && (!vk.copy_scratch || !vk.copy_scratch(8, p.fill_scratch, p.fill_scratch_offset) || !p.fill_scratch || p.fill_scratch_offset % 4 || p.fill_scratch_offset > UINT64_MAX - 8)) - return ReplayResult::unsupported; + return unsupported_at(__LINE__); if (!p.skip && !p.fills.empty() && p.binding.host_readable) { out.wrote_readback = true; out.readback_src_stages |= VK_PIPELINE_STAGE_2_TRANSFER_BIT; @@ -2776,10 +2888,10 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun // bit-exact R32_UINT backing path. const VkFormat view_format = view.format ? VkFormat(view.format) : p.binding.format; if (!uav_clear::encode(view_format, uav->is_float, uav->values, p.element)) - return ReplayResult::unsupported; + return unsupported_at(__LINE__); const auto* image_layout = uav_clear::layout(p.binding.format); if (!image_layout || image_layout->bytes != p.element.size) - return ReplayResult::unsupported; + return unsupported_at(__LINE__); const bool attachment = p.binding.color_attachment && !p.binding.volume; const bool view_attachable = vk.color_attachment_format ? vk.color_attachment_format(view_format) @@ -2787,10 +2899,10 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun const bool reinterpret = view_format != p.binding.format && attachment && view_attachable; const VkFormat clear_format = reinterpret ? view_format : p.binding.format; if (!uav_clear::decode(clear_format, p.element, p.clear_color)) - return ReplayResult::unsupported; + return unsupported_at(__LINE__); if (reinterpret) p.clear_format = view_format; if (!uav->rects.empty() && !attachment) - return ReplayResult::unsupported; + return unsupported_at(__LINE__); // Under a predicate a whole view is cleared as one rectangle where the image can be an attachment, as // render targets are; otherwise vkCmdClearColorImage runs unconditionally and is counted. if (predicated && uav->rects.empty() && !attachment) ++out.unpredicated_copies; @@ -2799,14 +2911,14 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun : attachment ? clear_rects(uav->rects) : std::span(uav->rects); if (const auto r = rect_view(rects, target, VK_IMAGE_ASPECT_COLOR_BIT); r != ReplayResult::success) return r; - if (!p.skip && p.rects.empty() && !vk.clear_color_image) return ReplayResult::unsupported; + if (!p.skip && p.rects.empty() && !vk.clear_color_image) return unsupported_at(__LINE__); } else if (std::holds_alternative(command) || std::holds_alternative(command) || std::holds_alternative(command)) { - if (!copies) return ReplayResult::unsupported; + if (!copies) return unsupported_at(__LINE__); if (predicated && !std::holds_alternative(command)) ++out.unpredicated_copies; const auto [dst_id, src_id] = copy_ids(command); const ResourceBinding* source = resolve(src_id); - if (!bind(dst_id) || !source) return ReplayResult::unresolved_resource; + if (!bind(dst_id) || !source) return unresolved_at(__LINE__); p.source = *source; ReplayResult result = ReplayResult::success; if (const auto* buffer_copy = std::get_if(&command)) { @@ -2830,7 +2942,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (predicated) { if ((statistics_active && !statistics_helpers) || !vk.prepare_predicated_copy || !vk.emit_predicated_copy || !vk.prepare_predicated_copy(p.source.buffer, p.binding.buffer, src, dst, buffer_copy->size, p.predicated_copy)) - return ReplayResult::unsupported; + return unsupported_at(__LINE__); } else p.buffer_copies.push_back({src, dst, buffer_copy->size}); } else if (const auto* texture_copy = std::get_if(&command)) { result = detail::prepare_texture_copy(*texture_copy, p); @@ -2858,7 +2970,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun (region.imageSubresource.aspectMask & depth_stencil_aspects) || image.rgb96 ? 4 : fmt.bytes; if (alignment > 1 && region.bufferOffset % alignment && !detail::stage_unaligned_tile(vk, p, image, fmt, upload)) - return ReplayResult::unsupported; + return unsupported_at(__LINE__); } const bool depth24_footprint = result == ReplayResult::success && image.depth24_as_float && !p.buffer_image_copies.empty() && @@ -2866,7 +2978,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun const bool rgb96_footprint = result == ReplayResult::success && image.rgb96 && !p.buffer_image_copies.empty(); // Without a segment pool, refuse before allocating conversion scratch/descriptors. - if (statistics_active && !statistics_helpers && (depth24_footprint || rgb96_footprint)) return ReplayResult::unsupported; + if (statistics_active && !statistics_helpers && (depth24_footprint || rgb96_footprint)) return unsupported_at(__LINE__); if (depth24_footprint) { const VkBufferImageCopy& region = p.buffer_image_copies[0]; const ResourceBinding& buffer = upload ? p.source : p.binding; @@ -2880,7 +2992,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun job.slices = region.imageExtent.depth; job.app_row_words = region.bufferRowLength ? region.bufferRowLength : job.width; job.app_slice_words = job.app_row_words * (region.bufferImageHeight ? region.bufferImageHeight : job.height); - if (!vk.depth24_prepare || !vk.depth24_run || !vk.depth24_prepare(job, p.depth24_parts)) return ReplayResult::unsupported; + if (!vk.depth24_prepare || !vk.depth24_run || !vk.depth24_prepare(job, p.depth24_parts)) return unsupported_at(__LINE__); p.has_depth24 = true; } else if (rgb96_footprint) { // A footprint of a 96-bit texture: 12-byte texels, 16 in the image. The same pass and scratch. @@ -2897,7 +3009,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun job.slices = region.imageExtent.depth; job.app_row_words = p.rgb96_row_words; job.app_slice_words = p.rgb96_slice_words; - if (!vk.depth24_prepare || !vk.depth24_run || !vk.depth24_prepare(job, p.depth24_parts)) return ReplayResult::unsupported; + if (!vk.depth24_prepare || !vk.depth24_run || !vk.depth24_prepare(job, p.depth24_parts)) return unsupported_at(__LINE__); p.has_depth24 = true; } } else { @@ -2918,7 +3030,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun } VkDeviceSize base = 0; if (!texel || !vk.copy_scratch || !vk.copy_scratch(total, p.staged, base)) - return ReplayResult::unsupported; + return unsupported_at(__LINE__); for (std::size_t r = 0; r < p.image_copies.size(); ++r) { const VkImageCopy& c = p.image_copies[r]; VkBufferImageCopy region{}; @@ -2942,18 +3054,18 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun ? VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT : VK_PIPELINE_STAGE_2_COPY_BIT; } } else if (const auto* resolve_command = std::get_if(&command)) { - if (!vk.resolve_image) return ReplayResult::unsupported; + if (!vk.resolve_image) return unsupported_at(__LINE__); if (predicated) ++out.unpredicated_copies; // a transfer command, like the copies const ResourceBinding* source = resolve(resolve_command->src); - if (!bind(resolve_command->dst) || !source) return ReplayResult::unresolved_resource; + if (!bind(resolve_command->dst) || !source) return unresolved_at(__LINE__); p.source = *source; if (const auto result = detail::prepare_resolve(*resolve_command, p); result != ReplayResult::success) return result; if (p.resolve_mode != VK_RESOLVE_MODE_NONE) { - if (!vk.begin_rendering || !vk.end_rendering || !vk.image_view) return ReplayResult::unsupported; + if (!vk.begin_rendering || !vk.end_rendering || !vk.image_view) return unsupported_at(__LINE__); p.view = vk.image_view(p.source, p.source_range); p.resolve_view = vk.image_view(p.binding, p.range); - if (!p.view || !p.resolve_view) return ReplayResult::unsupported; + if (!p.view || !p.resolve_view) return unsupported_at(__LINE__); if (const auto result = detail::keep_around_resolve(vk, p); result != ReplayResult::success) return result; // D3D-417, a driver workaround: AMD's Windows driver (32.0.21042.62, Radeon RDNA2 iGPU) resolves a @@ -2971,12 +3083,12 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun p.binding, p.resolve_view, image_layout(p.binding, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL), p.resolve_mode, {std::min(from.width, to.width), std::min(from.height, to.height)}, p.resolve_pass); - if (!p.resolve_framebuffer) return ReplayResult::unsupported; + if (!p.resolve_framebuffer) return unsupported_at(__LINE__); } } } else if (const auto* discard = std::get_if(&command)) { // Buffers and partial (rectangle) discards keep their contents, which "undefined" allows. - if (!bind(discard->resource)) return ReplayResult::unresolved_resource; + if (!bind(discard->resource)) return unresolved_at(__LINE__); const std::uint64_t end = std::uint64_t(discard->first_subresource) + discard->count; if (!p.binding.image) { if (!discard->whole && end > 1) return ReplayResult::invalid_subresource; @@ -2993,26 +3105,26 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun } } } else if (const auto* write = std::get_if(&command)) { - if (!vk.update_buffer || !vk.buffer_at) return ReplayResult::unsupported; + if (!vk.update_buffer || !vk.buffer_at) return unsupported_at(__LINE__); std::uint64_t bytes = 4; if (!vk.buffer_at(write->address, bytes, p.write_buffer, p.write_offset) || bytes < 4) - return ReplayResult::unresolved_resource; + return unresolved_at(__LINE__); if (p.write_offset % 4) return ReplayResult::invalid_copy; // WriteBufferImmediate resolves by VA and may target a readback buffer in COPY_DEST. out.wrote_readback = true; out.readback_src_stages |= VK_PIPELINE_STAGE_2_TRANSFER_BIT; } else if (const auto* atomic = std::get_if(&command)) { - if (!vk.copy_buffer) return ReplayResult::unsupported; + if (!vk.copy_buffer) return unsupported_at(__LINE__); if (predicated) ++out.unpredicated_copies; // a transfer command, like the copies const ResourceBinding* source = resolve(atomic->src); - if (!bind(atomic->dst) || !source) return ReplayResult::unresolved_resource; + if (!bind(atomic->dst) || !source) return unresolved_at(__LINE__); p.source = *source; if (!p.binding.buffer || !p.source.buffer || !detail::within(atomic->dst_offset, atomic->bytes, p.binding.size) || !detail::within(atomic->src_offset, atomic->bytes, p.source.size)) return ReplayResult::invalid_copy; for (const auto& d : atomic->dependencies) { const ResourceBinding* dependent = resolve(d.resource); - if (!dependent) return ReplayResult::unresolved_resource; + if (!dependent) return unresolved_at(__LINE__); if (!dependent->image) { const std::uint64_t end = d.end == UINT64_MAX ? dependent->size : d.end; if (d.subresource != 0 || d.begin >= end || end > dependent->size) @@ -3028,26 +3140,26 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun } else if (const auto* predication = std::get_if(&command)) { predicated = predication->buffer != 0; if (!predicated) continue; - if (!conditional) return ReplayResult::unsupported; + if (!conditional) return unsupported_at(__LINE__); // Without physical segments the capture dispatch would pollute CSInvocations. - if (statistics_active && !statistics_helpers) return ReplayResult::unsupported; - if (!bind(predication->buffer)) return ReplayResult::unresolved_resource; + if (statistics_active && !statistics_helpers) return unsupported_at(__LINE__); + if (!bind(predication->buffer)) return unresolved_at(__LINE__); if (!p.binding.buffer || !detail::within(predication->offset, 8, p.binding.size) || predication->offset > UINT64_MAX - p.binding.buffer_offset) return ReplayResult::invalid_predication; if (!vk.prepare_predicate || !vk.capture_predicate || !vk.prepare_predicate(p.binding.buffer, p.binding.buffer_offset + predication->offset, p.predicate)) - return ReplayResult::unsupported; + return unsupported_at(__LINE__); } else if (const QueryRange range = query_range(command); range.count) { // BeginQuery, EndQuery and ResolveQueryData are not among D3D12's predicated calls, so a predicate does // not suppress them (emit_query suspends conditional rendering around ResolveQueryData). - if (!queries) return ReplayResult::unsupported; + if (!queries) return unsupported_at(__LINE__); QueryPool* heap = vk.query_pool(range.heap); - if (!heap) return ReplayResult::unresolved_resource; + if (!heap) return unresolved_at(__LINE__); if (!query_fits_heap(heap->heap_type, range.type)) return ReplayResult::invalid_query; if (range.first >= heap->count || range.count > heap->count - range.first) return ReplayResult::invalid_query; - if (!query_result_size(range.type)) return ReplayResult::unsupported; + if (!query_result_size(range.type)) return unsupported_at(__LINE__); if (range.type != d3d12_query::timestamp && !std::holds_alternative(command)) { const bool begin = std::holds_alternative(command); if (range.type == d3d12_query::occlusion) { @@ -3066,7 +3178,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun } if (const auto* resolve_queries = std::get_if(&command)) { // The destination is a buffer, as D3D12 requires, large enough for every result. - if (!bind(resolve_queries->dst)) return ReplayResult::unresolved_resource; + if (!bind(resolve_queries->dst)) return unresolved_at(__LINE__); const std::uint64_t bytes = std::uint64_t(range.count) * query_result_size(range.type); if (!p.binding.buffer || p.binding.buffer_offset % 8 || !detail::within(resolve_queries->offset, bytes, p.binding.size) || @@ -3076,7 +3188,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun // Inside a pipeline-statistics query, QueryReplay::plan checks that the helper dispatch is kept out // of the application's counters. if (range.type == d3d12_query::binary_occlusion && !vk.resolve_binary_occlusion) - return ReplayResult::unsupported; + return unsupported_at(__LINE__); if (p.binding.host_readable) { out.wrote_readback = true; out.readback_src_stages |= VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_TRANSFER_BIT; @@ -3084,7 +3196,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun } out.queries.push_back({i, heap, statistics_active}); } else if (const auto* ind = std::get_if(&command)) { - if (!bind(ind->argument_buffer) || !p.binding.buffer) return ReplayResult::unresolved_resource; + if (!bind(ind->argument_buffer) || !p.binding.buffer) return unresolved_at(__LINE__); const VkDeviceSize record_size = detail::indirect_record_size(ind->kind); if (!record_size || ind->stride < record_size || ind->stride % sizeof(std::uint32_t)) return ReplayResult::invalid_indirect_arguments; @@ -3098,7 +3210,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun return ReplayResult::invalid_indirect_arguments; if (ind->count_buffer) { const ResourceBinding* cnt = resolve(ind->count_buffer); - if (!cnt || !cnt->buffer) return ReplayResult::unresolved_resource; + if (!cnt || !cnt->buffer) return unresolved_at(__LINE__); if (!detail::indirect_range(*cnt, ind->count_offset, sizeof(std::uint32_t))) return ReplayResult::invalid_indirect_arguments; p.source = *cnt; @@ -3110,57 +3222,61 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun !vk.prepare_counted_dispatch(p.binding.buffer, p.binding.buffer_offset + ind->argument_offset, p.source.buffer, p.source.buffer_offset + ind->count_offset, ind->stride, ind->max_count, p.counted_dispatch)) - return ReplayResult::unsupported; + return unsupported_at(__LINE__); } else if ((ind->kind == IndirectKind::draw && !vk.draw_indirect_count) || (ind->kind == IndirectKind::draw_indexed && !vk.draw_indexed_indirect_count)) { - return ReplayResult::unsupported; + return unsupported_at(__LINE__); } } else { if ((ind->kind == IndirectKind::draw && !vk.draw_indirect) || (ind->kind == IndirectKind::draw_indexed && !vk.draw_indexed_indirect) || (ind->kind == IndirectKind::dispatch && !vk.dispatch_indirect)) - return ReplayResult::unsupported; + return unsupported_at(__LINE__); } if (ind->kind == IndirectKind::dispatch && ind->pipeline) { // the pipeline and root arguments it was recorded - if (!vk.bind_pipeline || !vk.push_constants || !vk.compute_pipeline) return ReplayResult::unsupported; + if (!vk.bind_pipeline || !vk.push_constants || !vk.compute_pipeline) return unsupported_at(__LINE__); const ComputePipeline* pipeline = vk.compute_pipeline(ind->pipeline); - if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; - if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; + if (!pipeline) return unresolved_at(__LINE__); p.pipeline = *pipeline; + if (!p.pipeline.pipeline && p.pipeline.build) p.pipeline.pipeline = p.pipeline.build(p.pipeline.build_context); + if (!p.pipeline.pipeline && p.pipeline.skipped) continue; // dropped on request, strict or not + if (!p.pipeline.pipeline && p.pipeline.async_build && !strict_replay()) continue; + if (!p.pipeline.pipeline) return unresolved_at(__LINE__); + if (pipeline->bindless_set && !vk.bind_descriptor_sets) return unsupported_at(__LINE__); } } else if (const auto* build = std::get_if(&command)) { p.khr_instances = 0; if (vk.xdxr_check) { - if (!vk.xdxr_check(*build)) return ReplayResult::unsupported; + if (!vk.xdxr_check(*build)) return unsupported_at(__LINE__); } else { if (!vk.build_acceleration_structures || !vk.resolve_acceleration_structure) - return ReplayResult::unsupported; + return unsupported_at(__LINE__); p.accel_dst = vk.resolve_acceleration_structure(build->dst_va); - if (!p.accel_dst) return ReplayResult::unresolved_resource; + if (!p.accel_dst) return unresolved_at(__LINE__); if (build->update && build->src_va) { p.accel_src = vk.resolve_acceleration_structure(build->src_va); - if (!p.accel_src) return ReplayResult::unresolved_resource; + if (!p.accel_src) return unresolved_at(__LINE__); } if (build->is_tlas && build->instance_pointers && build->instance_count) { - if (!vk.prepare_khr_instances || !vk.host_at || !vk.buffer_at) return ReplayResult::unsupported; + if (!vk.prepare_khr_instances || !vk.host_at || !vk.buffer_at) return unsupported_at(__LINE__); return vk.prepare_khr_instances(*build, p.khr_instances); } } } else if (const auto* copy = std::get_if(&command)) { if (vk.xdxr_copy) { // XDXR structures: the destination's room bounds the copy, as the size is only known to the GPU. - if (!vk.buffer_at || copy->mode > 1) return ReplayResult::unsupported; + if (!vk.buffer_at || copy->mode > 1) return unsupported_at(__LINE__); std::uint64_t room = ~std::uint64_t(0); VkBuffer buffer = VK_NULL_HANDLE; VkDeviceSize offset = 0; - if (!vk.buffer_at(copy->dst_va, room, buffer, offset)) return ReplayResult::unresolved_resource; + if (!vk.buffer_at(copy->dst_va, room, buffer, offset)) return unresolved_at(__LINE__); std::uint64_t source = ~std::uint64_t(0); - if (!vk.buffer_at(copy->src_va, source, buffer, offset)) return ReplayResult::unresolved_resource; + if (!vk.buffer_at(copy->src_va, source, buffer, offset)) return unresolved_at(__LINE__); p.xdxr_bytes = std::min(room, source); } else { if (vk.queue_stages == detail::queue_stages_copy || !vk.copy_acceleration_structure || !vk.resolve_acceleration_structure || copy->mode > 1) - return ReplayResult::unsupported; + return unsupported_at(__LINE__); p.accel_dst = vk.resolve_acceleration_structure(copy->dst_va); p.accel_src = vk.resolve_acceleration_structure(copy->src_va); if (!p.accel_dst || !p.accel_src) return ReplayResult::unresolved_resource; @@ -3169,11 +3285,11 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun } } else if (const auto* info = std::get_if(&command)) { if (vk.xdxr_postbuild) { - if (!vk.buffer_at || (info->type != 0 && info->type != 3)) return ReplayResult::unsupported; + if (!vk.buffer_at || (info->type != 0 && info->type != 3)) return unsupported_at(__LINE__); std::uint64_t room = 8 * info->sources.size(); VkBuffer buffer = VK_NULL_HANDLE; VkDeviceSize offset = 0; - if (!vk.buffer_at(info->dest_va, room, buffer, offset)) return ReplayResult::unresolved_resource; + if (!vk.buffer_at(info->dest_va, room, buffer, offset)) return unresolved_at(__LINE__); if (room < 8 * info->sources.size()) return ReplayResult::invalid_copy; if (!info->sources.empty()) { // dest_va is resolved by VA and may target a host-readable buffer; XDXR postbuild writes from compute. @@ -3185,7 +3301,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun vk.pipeline_barrier && vk.buffer_at && vk.prepare_khr_postbuild) { if (vk.queue_stages == detail::queue_stages_copy || info->sources.empty() || info->sources.size() > std::numeric_limits::max() / 8u) - return ReplayResult::unsupported; + return unsupported_at(__LINE__); const std::uint64_t need = 8ull * info->sources.size(); std::uint64_t room = need; detail::PreparedKhrPostbuild pb; @@ -3203,7 +3319,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (!vk.prepare_khr_postbuild(static_cast(pb.sources.size()), pb.query_pool, pb.first_query) || !pb.query_pool) - return ReplayResult::unsupported; + return unsupported_at(__LINE__); p.khr_postbuild = static_cast(out.khr_postbuilds.size()); out.khr_postbuilds.push_back(std::move(pb)); // dest_va is resolved by VA and may target a host-readable buffer in COPY_DEST. @@ -3215,18 +3331,39 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun } } else if (const auto* dispatch = std::get_if(&command)) { if (!vk.bind_pipeline || !vk.push_constants || !vk.dispatch || !vk.compute_pipeline) - return ReplayResult::unsupported; + return unsupported_at(__LINE__); const ComputePipeline* pipeline = vk.compute_pipeline(dispatch->pipeline); - if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; - if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; + // A dispatch or draw this runtime cannot resolve (a pipeline it could not make: an untranslated + // program, an amplification shader; a vertex or index buffer address that names memory it has no + // buffer for) is dropped, logged by unresolved_at, and the rest of the list is submitted. Failing the + // list instead loses every other draw of the frame: the retail title's lists mix such draws in. + // LEONIDA_STRICT_REPLAY=1 restores the failure. + const bool strict = strict_replay(); + if (!pipeline) { + if (strict) return unresolved_at(__LINE__); + unresolved_at(__LINE__); + p.pipeline = {}; + continue; + } p.pipeline = *pipeline; + if (!p.pipeline.pipeline && p.pipeline.build) p.pipeline.pipeline = p.pipeline.build(p.pipeline.build_context); + if (!p.pipeline.pipeline && p.pipeline.skipped) continue; // dropped on request, strict or not + if (!p.pipeline.pipeline) { + if (strict) return unresolved_at(__LINE__); + if (!p.pipeline.async_build) unresolved_at(__LINE__); + continue; + } + if (pipeline->bindless_set && !vk.bind_descriptor_sets) return unsupported_at(__LINE__); } else if (const auto* draw = std::get_if(&command)) { if (out.draw_count == out.draws.size()) out.draws.emplace_back(); auto& prepared_draw = out.draws[out.draw_count]; prepared_draw.reset(); p.draw = std::uint32_t(out.draw_count++); - if (const auto r = detail::prepare_draw(*draw, resolve, vk, prepared_draw); r != ReplayResult::success) - return r; + if (const auto r = detail::prepare_draw(*draw, resolve, vk, prepared_draw); r != ReplayResult::success) { + const bool strict = strict_replay(); + if (r != ReplayResult::unresolved_resource || strict) return r; + prepared_draw.skipped = true; // dropped at emit (see the dispatch branch above) + } } } if (ordinary_active || binary_active) return ReplayResult::invalid_query; @@ -3239,7 +3376,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun } if (overlaps) { if (!vk.sum_occlusion || out.queries.size() >= detail::PreparedQuery::no_segment) - return ReplayResult::unsupported; + return unsupported_at(__LINE__); return plan_occlusion_segments(out); } return ReplayResult::success; @@ -3256,7 +3393,7 @@ class QueryReplay { const std::shared_ptr& statistics_pool = {}, std::uint32_t statistics_base = 0) { if (list.segment_count) { - if (!pool) return ReplayResult::unsupported; + if (!pool) return unsupported_at(__LINE__); retain(pool); list.segment_pool = pool->pool; list.segment_base = base; @@ -3272,14 +3409,14 @@ class QueryReplay { list.statistics_base = statistics_base; } else if (mesh) { // Unsplit, the query would be active around a mesh draw with counters Vulkan forbids there. - return ReplayResult::unsupported; + return unsupported_at(__LINE__); } else if (list.statistics_overlaps) { // Whole queries on the heap pool would keep two pipeline-statistics queries active at once. - return ReplayResult::unsupported; + return unsupported_at(__LINE__); } else { for (const auto& command : list.commands) if (command.statistics_end != detail::PreparedQuery::no_segment) - return ReplayResult::unsupported; + return unsupported_at(__LINE__); for (auto& query : list.queries) { query.statistics_end = query.statistics_begin = detail::PreparedQuery::no_segment; query.statistics_count = 0; @@ -3311,7 +3448,7 @@ class QueryReplay { for (std::uint32_t i = 0; i < resolve.count; ++i) { const auto index = resolve.first + i; const auto value = lookup(*query.heap, index); - if (binary && value.ended && !uncounted) return ReplayResult::unsupported; + if (binary && value.ended && !uncounted) return unsupported_at(__LINE__); needs_binary |= binary && value.ended; detail::QueryResolveRun run{value.ended ? query.heap->pool : VK_NULL_HANDLE, index, 1, offset + VkDeviceSize(i) * size}; @@ -3328,7 +3465,7 @@ class QueryReplay { saved.count > 1 || any_mesh, saved.segments->mesh_pool, saved.segments->primitives_pool, kinds}; if (any_mesh && !statistics) return ReplayResult::invalid_query; - if (!can_sum || (run.sum && !uncounted)) return ReplayResult::unsupported; + if (!can_sum || (run.sum && !uncounted)) return unsupported_at(__LINE__); if (statistics) needs_statistics_sum |= run.sum; else if (binary) (run.sum ? needs_sum_binary : needs_binary) = true; else needs_sum |= run.sum; @@ -3497,8 +3634,9 @@ inline void close_labels(VkCommandBuffer command_buffer, const ReplayFunctions& // `open_labels` counts the debug labels begun and not yet ended in this command buffer: an EndEvent with none open // is dropped (Vulkan requires a matching begin), and the caller ends what is still open before it ends the buffer // (close_labels). Without it, the list's own events are balanced at its end. -inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, const ReplayFunctions& vk, - LayoutTracker* tracker = nullptr, std::uint32_t* open_labels = nullptr) { +template +inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_buffer, const ReplayFunctions& vk, + LayoutTracker* tracker, std::uint32_t* open_labels, const CheckpointRecorder* checkpoints) { std::uint32_t own_labels = 0; std::uint32_t& labels = open_labels ? *open_labels : own_labels; const auto commands = prepared.list->commands(); @@ -3520,6 +3658,9 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c const auto& command = commands[i]; const auto& p = prepared.commands[i]; if (next_query < prepared.queries.size() && prepared.queries[next_query].command == i) { + if constexpr (Checkpoints) + if (std::holds_alternative(command)) + checkpoints->record(command_buffer, i, CheckpointKind::resolve); emit_query(prepared, prepared.queries[next_query++], command_buffer, vk, predicate); continue; } @@ -3677,6 +3818,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c if (tracker && !release) tracker->set(id, range, new_layout); } else if (const auto* color_clear = std::get_if(&command)) { if (p.skip) continue; + if constexpr (Checkpoints) checkpoints->record(command_buffer, i, CheckpointKind::clear); const VulkanAccess state = vulkan_access(d3d12_state::render_target, false); auto pieces = detail::current(tracker, id, p.range, image_layout(p.binding, state.layout)); detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker); @@ -3710,6 +3852,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c }); } else if (const auto* depth_clear = std::get_if(&command)) { if (p.skip) continue; + if constexpr (Checkpoints) checkpoints->record(command_buffer, i, CheckpointKind::clear); // With separate layouts only the cleared planes move; otherwise both do. const auto range = detail::planes_for_layout(p.binding, p.range, separate); const VulkanAccess state = vulkan_access(d3d12_state::depth_write, false); @@ -3752,6 +3895,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c }); } else if (const auto* uav = std::get_if(&command)) { if (p.skip) continue; + if constexpr (Checkpoints) checkpoints->record(command_buffer, i, CheckpointKind::clear); // The UAV state, widened to transfers: a later barrier from SYNC_CLEAR_UNORDERED_ACCESS_VIEW names the // clear stage, which is a transfer stage in the legacy masks. VulkanAccess state = vulkan_access(d3d12_state::unordered_access, false); @@ -3804,12 +3948,21 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c }); } else if (std::holds_alternative(command) || std::holds_alternative(command) || std::holds_alternative(command)) { + if constexpr (Checkpoints) checkpoints->record(command_buffer, i, CheckpointKind::copy); const auto [dst_id, src_id] = copy_ids(command); if (!p.predicated_copy.empty()) { end_statistics(); vk.emit_predicated_copy(command_buffer, p.predicated_copy); begin_statistics(); } else if (!p.buffer_copies.empty()) { + // Transfer dependency from natterman12, ubiquitarianism/leonida PR #354 (GPL-3.0). + // D3D12 orders buffer copies even across lists on one queue. A previous transfer write can + // overlap this copy's source or destination without an application barrier. + if (order_buffer_copies()) { + detail::memory_barrier(vk, command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT); + } vk.copy_buffer(command_buffer, p.source.buffer, p.binding.buffer, std::uint32_t(p.buffer_copies.size()), p.buffer_copies.data()); } else if (p.staged) { @@ -3927,6 +4080,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c } } } else if (std::holds_alternative(command)) { + if constexpr (Checkpoints) checkpoints->record(command_buffer, i, CheckpointKind::resolve); // resolve_source and resolve_dest are the transfer layouts, as copy_source and copy_dest are. const auto [dst_id, src_id] = copy_ids(command); if (p.resolve_mode != VK_RESOLVE_MODE_NONE) { @@ -4065,6 +4219,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c vk.update_buffer(command_buffer, p.write_buffer, p.write_offset, 4, &write->value); if (predicate.buffer) vk.begin_conditional_rendering(command_buffer, &predicate); } else if (std::holds_alternative(command)) { + if constexpr (Checkpoints) checkpoints->record(command_buffer, i, CheckpointKind::copy); // Every earlier write, to the dependent resources among others, finishes and is visible before the copy. // Vulkan promises no atomicity for a transfer; that a naturally aligned 4- or 8-byte copy is one write // is an assumption about the hardware (docs/d3d12_vulkan.md, section 4.2). @@ -4073,6 +4228,17 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c VK_PIPELINE_STAGE_TRANSFER_BIT); vk.copy_buffer(command_buffer, p.source.buffer, p.binding.buffer, 1, p.buffer_copies.data()); } else if (const auto* ind = std::get_if(&command)) { + if (ind->kind == IndirectKind::dispatch && ind->pipeline && !p.pipeline.pipeline && + (p.pipeline.async_build || p.pipeline.skipped)) + continue; + if constexpr (Checkpoints) { + if (ind->kind == IndirectKind::dispatch) + checkpoints->dispatch(command_buffer, i, p.pipeline.pipeline, ind->pipeline, ind->user_data, {}, true, + ind->argument_buffer, ind->argument_offset, ind->count_buffer, + ind->count_offset, ind->max_count, ind->stride); + else + checkpoints->record(command_buffer, i, CheckpointKind::draw); + } const VkDeviceSize arguments = p.binding.buffer_offset + ind->argument_offset; if (ind->count_buffer && ind->kind != IndirectKind::dispatch) { const VkDeviceSize count = p.source.buffer_offset + ind->count_offset; @@ -4121,6 +4287,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c xdxr_build && vk.xdxr_record) { vk.xdxr_record(command_buffer, *xdxr_build); } else if (const auto* copy = std::get_if(&command)) { + if constexpr (Checkpoints) checkpoints->record(command_buffer, i, CheckpointKind::copy); if (vk.xdxr_copy) { vk.xdxr_copy(command_buffer, copy->src_va, copy->dst_va, p.xdxr_bytes); } else { @@ -4216,6 +4383,10 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c const VkAccelerationStructureBuildRangeInfoKHR* range_ptr = ranges.data(); vk.build_acceleration_structures(command_buffer, 1, &info, &range_ptr); } else if (const auto* dispatch = std::get_if(&command)) { + if (!p.pipeline.pipeline) continue; // could not be resolved in prepare: dropped + if constexpr (Checkpoints) + checkpoints->dispatch(command_buffer, i, p.pipeline.pipeline, dispatch->pipeline, dispatch->user_data, + {dispatch->x, dispatch->y, dispatch->z}); ShaderUserData data{}; std::copy(dispatch->user_data.begin(), dispatch->user_data.end(), data.s); data.heap_base = vk.heap_base; @@ -4230,6 +4401,10 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c vk.dispatch(command_buffer, dispatch->x, dispatch->y, dispatch->z); } else if (const auto* draw = std::get_if(&command)) { const detail::PreparedDraw& d = prepared.draws[p.draw]; + if (d.skipped) continue; // could not be resolved in prepare: dropped + if constexpr (Checkpoints) + checkpoints->record(command_buffer, i, CheckpointKind::draw, + d.pipeline, draw->pipeline); constexpr VkAccessFlags color_access = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; constexpr VkAccessFlags depth_access = @@ -4342,6 +4517,31 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c } if (draw->mesh) { vk.draw_mesh_tasks(command_buffer, draw->count, draw->instances, draw->first); + if (vk.mesh_draw_count) ++*vk.mesh_draw_count; + } else if (draw->topology == topology_quad_list) { + // One four-vertex fan per quad. The translated vertex shaders take their vertex id from the index + // value (VertexIndex - BaseVertex), so a fan must be drawn with the index values 4q..4q+3: an + // indexed draw reads them from the application's index buffer, a non-indexed one from the + // shared 0, 1, 2, ... buffer (quad_indices), with the draw's first vertex as the vertex offset, as + // VertexIndex is first + i for a plain draw. + const bool generated = !draw->indexed; // prepare() has checked that quad_indices is there + if (generated) + vk.bind_index_buffer(command_buffer, vk.quad_indices, vk.quad_indices_offset, VK_INDEX_TYPE_UINT32); + else + vk.bind_index_buffer(command_buffer, d.index_buffer, d.index_offset, d.index_type); + // The shared buffer holds quad_index_count / 4 quads: more are cut off here and said so. + const std::uint32_t wanted = draw->count / 4, room = generated ? vk.quad_index_count / 4 : UINT32_MAX; + const std::uint32_t quads = std::min(wanted, room); + if (quads < wanted) + std::fprintf(stderr, "[rt] d3d12: a non-indexed quad list of %u quads draws only the first %u\n", + wanted, quads); + const std::int32_t vertex_offset = generated ? std::int32_t(draw->first) : draw->base_vertex; + // All the instances of a quad are drawn together (a split by instance would zero the translated + // instance id, InstanceIndex - BaseInstance), so with several instances the primitive order is quad + // by quad, not instance by instance: only overlapping blended instances can tell. + for (std::uint32_t quad = 0; quad < quads; ++quad) + vk.draw_indexed(command_buffer, 4, draw->instances, (generated ? 0 : draw->first) + 4 * quad, + vertex_offset, draw->first_instance); } else if (draw->indexed) { vk.bind_index_buffer(command_buffer, d.index_buffer, d.index_offset, d.index_type); vk.draw_indexed(command_buffer, draw->count, draw->instances, draw->first, draw->base_vertex, @@ -4357,6 +4557,11 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c if (!open_labels) close_labels(command_buffer, vk, own_labels); } +inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, const ReplayFunctions& vk, + LayoutTracker* tracker = nullptr, std::uint32_t* open_labels = nullptr) { + emit_commands(prepared, command_buffer, vk, tracker, open_labels, nullptr); +} + // prepare + emit for one list. A failed replay leaves the command buffer and the tracker untouched. // With `keep` and vk.create_segment_pool (and the sum helpers) set, overlapping occlusion or statistics queries get // segment pools as in the batched path; the caller holds `keep` until the command buffer has completed. @@ -4365,20 +4570,20 @@ ReplayResult replay(const CommandList& list, VkCommandBuffer command_buffer, Res const ReplayFunctions& vk, LayoutTracker* tracker = nullptr, std::vector>* keep = nullptr) { if (tracker && tracker->separate_depth_stencil_layouts() != vk.separate_depth_stencil_layouts) - return ReplayResult::unsupported; + return unsupported_at(__LINE__); const bool pools = keep && vk.create_segment_pool && vk.sum_occlusion && vk.resolve_binary_occlusion && vk.sum_statistics && vk.sum_binary_occlusion; PreparedList prepared; if (const auto result = prepare(list, resolve, vk, prepared, pools); result != ReplayResult::success) return result; - if (tracker && zero_clear_unavailable(prepared, vk, *tracker)) return ReplayResult::unsupported; + if (tracker && zero_clear_unavailable(prepared, vk, *tracker)) return unsupported_at(__LINE__); std::shared_ptr physical, statistics; if (pools && prepared.segment_count && !(physical = vk.create_segment_pool(VK_QUERY_TYPE_OCCLUSION, prepared.segment_count))) - return ReplayResult::unsupported; + return unsupported_at(__LINE__); if (pools && prepared.statistics_segment_count && !(statistics = vk.create_segment_pool(VK_QUERY_TYPE_PIPELINE_STATISTICS, prepared.statistics_segment_count))) - return ReplayResult::unsupported; + return unsupported_at(__LINE__); QueryReplay queries; if (const auto result = queries.plan(prepared, physical, 0, pools, statistics, 0); result != ReplayResult::success) return result; diff --git a/runtime/src/vulkan_scratch.h b/runtime/src/vulkan_scratch.h index 33d84bf72f..23626d8b16 100644 --- a/runtime/src/vulkan_scratch.h +++ b/runtime/src/vulkan_scratch.h @@ -10,6 +10,8 @@ #endif #include +#include "vulkan_device_fault.h" + #include #include #include @@ -23,14 +25,15 @@ class ScratchBuffers { // A device-local allocation for a chunk; null on failure. using Allocate = std::function; - ScratchBuffers(PFN_vkGetDeviceProcAddr get, VkDevice device, Allocate allocate) - : device_(device), allocate_(std::move(allocate)) { + ScratchBuffers(PFN_vkGetDeviceProcAddr get, VkDevice device, Allocate allocate, + DeviceFaultDiagnostics* diagnostics = nullptr) + : device_(device), diagnostics_(diagnostics), allocate_(std::move(allocate)) { loaded_ = vk_.load(get, device); } ~ScratchBuffers() { if (!loaded_) return; - vk_.vkDeviceWaitIdle(device_); + DeviceFaultDiagnostics::observe(diagnostics_, vk_.vkDeviceWaitIdle(device_), "vkDeviceWaitIdle"); release(current_); for (auto& batch : retired_) release(batch); for (auto& chunk : spare_) destroy(chunk); @@ -101,7 +104,9 @@ class ScratchBuffers { if (retired_[i].ticket != 0) { std::uint64_t done = 0; if (!retired_[i].timeline || - vk_.vkGetSemaphoreCounterValue(device_, retired_[i].timeline, &done) != VK_SUCCESS || + DeviceFaultDiagnostics::observe(diagnostics_, + vk_.vkGetSemaphoreCounterValue(device_, retired_[i].timeline, &done), + "vkGetSemaphoreCounterValue (scratch)") != VK_SUCCESS || done < retired_[i].ticket) { ++i; continue; @@ -175,6 +180,7 @@ class ScratchBuffers { } VkDevice device_; + DeviceFaultDiagnostics* diagnostics_; Allocate allocate_; Functions vk_; bool loaded_ = false; diff --git a/runtime/src/vulkan_title_image_pool.h b/runtime/src/vulkan_title_image_pool.h new file mode 100644 index 0000000000..94308f6871 --- /dev/null +++ b/runtime/src/vulkan_title_image_pool.h @@ -0,0 +1,113 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace leonida { + +// Only optimal-tiled, non-sparse images go in a page. A slot is returned after the owning +// image is destroyed by the device's normal GPU retirement queue. +struct TitleImagePage { + VkDevice device{}; + VkDeviceMemory memory{}; + PFN_vkFreeMemory free_memory{}; + std::uint32_t type = 0, capacity = 0, allocated = 0; + std::mutex mutex; + std::vector returned; + + ~TitleImagePage() { + if (memory) free_memory(device, memory, nullptr); + } + + bool take(std::uint32_t& slot) { + std::lock_guard lock(mutex); + if (!returned.empty()) { + slot = returned.back(); + returned.pop_back(); + } else if (allocated < capacity) { + slot = allocated++; + } else { + return false; + } + return true; + } + + void release(std::uint32_t slot) { + std::lock_guard lock(mutex); + returned.push_back(slot); // the page reserves capacity at creation + } +}; + +struct PooledTitleImage { + PooledTitleImage() = default; + PooledTitleImage(const PooledTitleImage&) = delete; + PooledTitleImage& operator=(const PooledTitleImage&) = delete; + + std::shared_ptr page; + std::uint32_t slot = 0; + VkImage image{}; + PFN_vkDestroyImage destroy_image{}; + + ~PooledTitleImage() { + if (image) destroy_image(page->device, image, nullptr); + if (page) page->release(slot); + } +}; + +class TitleImagePool { +public: + // The caller has already excluded dedicated-only images. All allocations in one page have + // identical stride, compatible memory types and non-overlapping, individually aligned ranges. + template + std::unique_ptr bind(VkDevice device, VkImage image, const VkMemoryRequirements& req, + PFN_vkBindImageMemory bind_image, PFN_vkDestroyImage destroy_image, + PFN_vkFreeMemory free_memory, Allocate allocate) { + constexpr VkDeviceSize largest_slot = VkDeviceSize{2} << 20; + const VkDeviceSize needed = std::max(req.size, req.alignment); + if (!needed || needed > largest_slot || !req.memoryTypeBits) return {}; + // Eight size classes per power of two keep padding below one eighth (besides required alignment). + const VkDeviceSize quantum = std::max(req.alignment, std::max(VkDeviceSize{1}, std::bit_floor(needed) / 8)); + const VkDeviceSize stride = (needed + quantum - 1) & ~(quantum - 1); + const VkDeviceSize page_size = std::min(VkDeviceSize{8} << 20, 256 * stride); + auto allocation = std::make_unique(); + std::lock_guard lock(mutex_); + auto& pages = classes_[stride]; + std::erase_if(pages, [](const auto& page) { return page.expired(); }); + for (const auto& weak : pages) { + auto page = weak.lock(); + if (page && (req.memoryTypeBits & (1u << page->type)) && page->take(allocation->slot)) { + allocation->page = std::move(page); + break; + } + } + if (!allocation->page) { + auto page = std::make_shared(); + page->device = device; + page->free_memory = free_memory; + page->capacity = static_cast(page_size / stride); + page->returned.reserve(page->capacity); + page->memory = allocate(page_size, page->type); + if (!page->memory) return {}; + pages.push_back(page); + page->take(allocation->slot); + allocation->page = std::move(page); + } + if (bind_image(device, image, allocation->page->memory, stride * allocation->slot) != VK_SUCCESS) return {}; + allocation->destroy_image = destroy_image; + allocation->image = image; + return allocation; + } + +private: + std::mutex mutex_; + std::map>> classes_; +}; + +} // namespace leonida diff --git a/runtime/test/allocator_proxy_test.cpp b/runtime/test/allocator_proxy_test.cpp index 5f89366f54..b48b224b72 100644 --- a/runtime/test/allocator_proxy_test.cpp +++ b/runtime/test/allocator_proxy_test.cpp @@ -58,11 +58,13 @@ using SlotFn = std::uint64_t(WINAPI*)(void*, std::uint64_t, std::uint64_t, std:: std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t); -// A call through slot `slot` with all words zero, the way a title calls a console method the PC interface lacks. -HRESULT call_slot(void* object, unsigned slot) { +// A call through slot `slot` with up to four explicit words (rest zero), the way a title calls a console method the PC +// interface lacks. +HRESULT call_slot(void* object, unsigned slot, std::uint64_t a1 = 0, std::uint64_t a2 = 0, std::uint64_t a3 = 0, + std::uint64_t a4 = 0) { void** vtable = *reinterpret_cast(object); return static_cast(static_cast( - reinterpret_cast(vtable[slot])(object, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))); + reinterpret_cast(vtable[slot])(object, a1, a2, a3, a4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))); } ULONG_PTR g_fault_address = 0; @@ -182,10 +184,24 @@ int check_proxy(const Backend& b, ID3D12CommandAllocator* allocator) { back->Release(); EXPECT(SUCCEEDED(allocator->SetPrivateDataInterface(key, nullptr))); - // The refused tail: every slot past the public chain, up to the table end, is E_NOTIMPL and counted. + // Console slot 9 (SetAllocatorCallbackX): records callback/context on the proxy and returns S_OK. const unsigned table = xs::allocator_proxy_table_size(); EXPECT(table == 64); - for (unsigned slot = 9; slot < table; ++slot) { + { + EXPECT(xs::allocator_proxy_callback(allocator) == 0 && xs::allocator_proxy_callback_context(allocator) == 0); + constexpr std::uintptr_t fake_cb = 0x11223344u; + constexpr std::uintptr_t fake_ctx = 0x55667788u; + const std::uint64_t before = xs::allocator_slot_hits(9); + EXPECT(call_slot(allocator, 9, fake_cb, fake_ctx, 0, 0x99aabbccu) == S_OK); + EXPECT(xs::allocator_slot_hits(9) == before + 1 && xs::allocator_slot_first_call_seen(9)); + EXPECT(xs::allocator_proxy_callback(allocator) == fake_cb && + xs::allocator_proxy_callback_context(allocator) == fake_ctx); + EXPECT(call_slot(allocator, 9, 0, 0) == S_OK); + EXPECT(xs::allocator_proxy_callback(allocator) == 0 && xs::allocator_proxy_callback_context(allocator) == 0); + } + + // The refused tail: every slot past slot 9, up to the table end, is E_NOTIMPL and counted. + for (unsigned slot = 10; slot < table; ++slot) { const std::uint64_t before = xs::allocator_slot_hits(slot); EXPECT(call_slot(allocator, slot) == E_NOTIMPL); EXPECT(xs::allocator_slot_hits(slot) == before + 1 && xs::allocator_slot_first_call_seen(slot)); @@ -201,8 +217,9 @@ int check_proxy(const Backend& b, ID3D12CommandAllocator* allocator) { EXPECT(g_fault_address == reinterpret_cast(&vtable[slot])); EXPECT(xs::allocator_table_overruns() == before + 1); } - std::printf("%s: allocator proxy: 9 public slots forwarded, slots 9-%u refused, the guard region names a read " - "past the table; QueryInterface/GetDevice/private data keep the proxy identity\n", label, table - 1); + std::printf("%s: allocator proxy: 9 public slots forwarded, slot 9 SetAllocatorCallbackX handled, slots 10-%u " + "refused, the guard region names a read past the table; QueryInterface/GetDevice/private data keep " + "the proxy identity\n", label, table - 1); return 0; } diff --git a/runtime/test/bindless_sizing_test.cpp b/runtime/test/bindless_sizing_test.cpp index 4553f25b60..2ceecf76f0 100644 --- a/runtime/test/bindless_sizing_test.cpp +++ b/runtime/test/bindless_sizing_test.cpp @@ -1,6 +1,6 @@ // bindless::size_bindings with synthetic device limits: no GPU. The counts of set 0 come from the device's descriptor -// limits (vulkan_bindless.h): today's sizes where a device is at them, larger 2D, sampler and storage arrays where it -// has room, and less where it is below them. +// limits (vulkan_bindless.h): today's sizes where a device is at them, larger image, sampler and storage arrays where +// it has room, and less where it is below them. #ifndef VK_NO_PROTOTYPES #define VK_NO_PROTOTYPES #endif @@ -103,8 +103,13 @@ int main() { EXPECT(f.counts[bindless::sampler_binding] == 4000 - bindless::reserved_samplers); EXPECT(f.counts[bindless::sampler_binding] > 2048); // a full sampler heap and the fallback EXPECT(storage(f, D::dim_2d) == bindless::max_storage_indices); - EXPECT(storage(f, D::dim_2d_array) == 1024 && storage(f, D::dim_3d) == 256 && storage(f, D::dim_1d) == 256); - EXPECT(count(f, D::dim_2d_array) == 1024 && count(f, D::dim_3d) == 256 && count(f, D::dim_1d) == 256); + // The other dimensions grow too (a title's cube maps, texture arrays and 1D lookups outnumber the defaults); + // their storage arrays hold as many indices as the 2D one. + EXPECT(count(f, D::dim_2d_array) == bindless::max_2d_array_images && + count(f, D::dim_3d) == bindless::max_3d_images && count(f, D::dim_1d) == bindless::max_1d_images); + EXPECT(storage(f, D::dim_2d_array) == bindless::max_storage_indices && + storage(f, D::dim_3d) == bindless::max_storage_indices && + storage(f, D::dim_1d) == bindless::max_storage_indices); EXPECT(f.ms_samples[0] == VK_SAMPLE_COUNT_4_BIT && f.ms_samples[2] == VK_SAMPLE_COUNT_4_BIT); EXPECT(storage_consistent(f)); if (update_after_bind) diff --git a/runtime/test/buffer_va_index_test.cpp b/runtime/test/buffer_va_index_test.cpp index 8abf4462db..79890c3103 100644 --- a/runtime/test/buffer_va_index_test.cpp +++ b/runtime/test/buffer_va_index_test.cpp @@ -73,6 +73,14 @@ void fixed_cases() { index.insert(0x3000, 0, 4); check(index.size() == 2 && at(index, 0) == 0 && at(index, 0x3000) == 0, "a null VA or an empty range is not indexed"); + // The padding of an old title window can contain the next index view's start. + // Replay needs one backing from that start through the last index, even when the view grows. + Index windows; + windows.insert(0x10000, 0x10000, 1); + check(windows.covers(0x1fff0, 16) && !windows.covers(0x1fff0, 18), "whole view must fit in its window"); + windows.insert(0x10000, 0x20000, 2); + check(windows.covers(0x1fff0, 18) && !windows.covers(0x1fff0, UINT64_MAX), "grown window and an oversized view"); + // Aliasing placed buffers: a long one with two short ones inside it. The nearest start that holds the VA wins. Index alias; alias.insert(0x10000, 0x10000, 10); // [0x10000, 0x20000) diff --git a/runtime/test/chad_test.cpp b/runtime/test/chad_test.cpp new file mode 100644 index 0000000000..21dc2a1ba5 --- /dev/null +++ b/runtime/test/chad_test.cpp @@ -0,0 +1,90 @@ +// Checks the registered chad.dll shim against the measured call shapes +// (docs/audio_hal_exe_calls.md, PR #6981). +// +// Every export is resolved through rt::shims::find so the test exercises +// the same shim table the runtime installs. The measured call shapes: +// XDspConnectWithMaximumStreamLimit(buffer, u32, u32, max_streams, flags, handle**), +// XDspActivate(handle, ...), XDspSubmitCommand(a, b), XDspDeactivate(handle, ...), +// XDspDisconnect(handle). +#include + +#include +#include +#include + +#include "shims.h" + +namespace { + +using XDspConnectFn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t, uint32_t, uint32_t, void**); +using XDspActivateFn = HRESULT(__stdcall*)(void*, uint64_t, uint64_t, uint64_t, uint64_t); +using XDspDeactivateFn = HRESULT(__stdcall*)(void*, uint64_t, uint64_t, uint64_t); +using XDspDisconnectFn = HRESULT(__stdcall*)(void*); +using XDspSubmitFn = HRESULT(__stdcall*)(void*, void*); + +int g_checks = 0; +int g_failures = 0; + +void check(bool condition, const char* what) { + ++g_checks; + std::printf("%s %s\n", condition ? "PASS" : "FAIL", what); + if (!condition) ++g_failures; +} + +} // namespace + +int main() { + std::printf("chad_test: registered chad.dll shim\n"); + + const auto dsp_connect = reinterpret_cast( + rt::shims::find("chad.dll", "XDspConnectWithMaximumStreamLimit")); + const auto dsp_activate = reinterpret_cast( + rt::shims::find("chad.dll", "XDspActivate")); + const auto dsp_deactivate = reinterpret_cast( + rt::shims::find("chad.dll", "XDspDeactivate")); + const auto dsp_disconnect = reinterpret_cast( + rt::shims::find("chad.dll", "XDspDisconnect")); + const auto dsp_submit = reinterpret_cast( + rt::shims::find("chad.dll", "XDspSubmitCommand")); + + check(dsp_connect != nullptr, "XDspConnectWithMaximumStreamLimit is registered"); + check(dsp_activate != nullptr, "XDspActivate is registered"); + check(dsp_deactivate != nullptr, "XDspDeactivate is registered"); + check(dsp_disconnect != nullptr, "XDspDisconnect is registered"); + check(dsp_submit != nullptr, "XDspSubmitCommand is registered"); + check(rt::shims::owns_dll("chad.dll"), "the registry owns chad.dll"); + if (!dsp_connect || !dsp_activate || !dsp_deactivate || !dsp_disconnect || !dsp_submit) return 1; + + // XDspConnectWithMaximumStreamLimit: measured 6 args + // (buffer, baseBufferLength, aggImpulseResp, max_streams, max_channels, handle**). + // The shim validates baseBufferLength >= 0x10000, max_streams >= 1, etc. + // The title passes 0x80 (128) streams and 1 channel. + alignas(64) static uint8_t buffer[0x10000]; + void* handle = nullptr; + const HRESULT cr = dsp_connect(buffer, 0x10000, 0, 0x80, 1, &handle); + check(cr == S_OK && handle != nullptr, + "XDspConnectWithMaximumStreamLimit returns S_OK and a handle"); + + // XDspActivate(handle, ...): 5 args, success is a return of 0. + check(dsp_activate(handle, 0, 0, 0, 0) == S_OK, + "XDspActivate returns S_OK"); + + // XDspSubmitCommand(a, b): 2 args, which of the two is the connection is unknown. + check(dsp_submit(handle, buffer) == S_OK, + "XDspSubmitCommand returns S_OK"); + + // XDspDeactivate(handle, ...): 4 args, success is a return of 0. + check(dsp_deactivate(handle, 0, 0, 0) == S_OK, + "XDspDeactivate returns S_OK"); + + // XDspDisconnect(handle): 1 arg, success is a return of 0. + check(dsp_disconnect(handle) == S_OK, + "XDspDisconnect returns S_OK"); + + // Null handle returns E_POINTER. + check(dsp_connect(buffer, 0x10000, 0, 0x80, 1, nullptr) == E_POINTER, + "XDspConnectWithMaximumStreamLimit(nullptr handle) returns E_POINTER"); + + std::printf("%d checks, %d failures\n", g_checks, g_failures); + return g_failures ? 1 : 0; +} \ No newline at end of file diff --git a/runtime/test/check_tiny_frame.py b/runtime/test/check_tiny_frame.py index 2a734e43e4..b67e468d7c 100644 --- a/runtime/test/check_tiny_frame.py +++ b/runtime/test/check_tiny_frame.py @@ -124,7 +124,10 @@ def main(): print("SKIP: no usable Vulkan device (the probe test skipped)") return SKIP - environment = dict(os.environ, LEONIDA_D3D12="vulkan") + # The fixture is compiled against the PC headers, so it calls the command list through PC vtable + # indices; LEONIDA_D3D12_LISTS=pc asks the proxy for PC-shaped lists. The console-shaped device, + # queue, heap and fence it checks stay console-shaped. + environment = dict(os.environ, LEONIDA_D3D12="vulkan", LEONIDA_D3D12_LISTS="pc") if options.queue_test_settings: environment.update(QUEUE_TEST_SETTINGS) run = subprocess.run([*options.runner, options.loader, "--run", os.path.basename(options.guest), "--trace-d3d12"], diff --git a/runtime/test/check_tls_clone_cleanup.cmake b/runtime/test/check_tls_clone_cleanup.cmake new file mode 100644 index 0000000000..21130ce328 --- /dev/null +++ b/runtime/test/check_tls_clone_cleanup.cmake @@ -0,0 +1,40 @@ +# gta6rt --dry-run, --init and --dry-run again with tiny_tls_clones.exe, which maps three TLS modules and so makes a +# helper clone for one of its DLLs. After each run no clone file of that run's process may remain in the temporary +# folder but its home clone (leonida_tls_host__home.dll), which is mapped until the process ends and cannot be +# deleted before; the next run's sweep must delete that one. The process ID comes from the trace's first line. A gta6rt +# running beside this test may sweep the home clone first, so its absence is fine. +if(DEFINED ENV{TMP}) + set(temp "$ENV{TMP}") +else() + set(temp "$ENV{TEMP}") +endif() +file(TO_CMAKE_PATH "${temp}" temp) +set(previous "") +foreach(mode dry-run init dry-run) + set(trace "${TRACE_DIR}/tls_clone_cleanup.jsonl") + file(REMOVE "${trace}") # --trace only creates a new file + execute_process( + COMMAND ${RUNNER} "${LOADER}" --${mode} "${GUEST}" --trace "${trace}" + TIMEOUT 90 + RESULT_VARIABLE code OUTPUT_VARIABLE output ERROR_VARIABLE error) + if(NOT code STREQUAL "0" OR NOT output MATCHES "3 module\\(s\\) mapped") + message(FATAL_ERROR "--${mode} returned ${code}\n${output}\n${error}") + endif() + file(STRINGS "${trace}" first LIMIT_COUNT 1) + file(REMOVE "${trace}") + if(NOT first MATCHES "\"pid\":([0-9]+)") + message(FATAL_ERROR "--${mode}: no pid in the trace: ${first}") + endif() + set(pid "${CMAKE_MATCH_1}") + file(GLOB left "${temp}/leonida_tls_host_${pid}_*.dll") + if(left AND NOT left STREQUAL "${temp}/leonida_tls_host_${pid}_home.dll") + message(FATAL_ERROR "--${mode} (pid ${pid}) left clone files other than its home clone: ${left}") + endif() + if(previous) + file(GLOB swept "${temp}/leonida_tls_host_${previous}_*.dll") + if(swept) + message(FATAL_ERROR "the run after pid ${previous} did not delete its clone files: ${swept}") + endif() + endif() + set(previous "${pid}") +endforeach() diff --git a/runtime/test/check_tls_index0.cmake b/runtime/test/check_tls_index0.cmake new file mode 100644 index 0000000000..a1ca31b8ff --- /dev/null +++ b/runtime/test/check_tls_index0.cmake @@ -0,0 +1,46 @@ +# gta6rt --run and --init with tiny_tls_ga.exe, an executable built /GA whose thread_local reads go straight to +# ThreadLocalStoragePointer[0]. --run: the game thread and a second thread both read the template value 42 and +# _tls_index is 0. Both modes: the startup trace names gta6rt.exe as the image that held module TLS index 0 and the +# index its block moved to. Then, with TMP and TEMP naming a missing folder, the home clone cannot be written and the +# reservation fails before main: --run and --init refuse the image with that reason and run none of its code, and +# --dry-run maps it with the note. (A TMP longer than MAX_PATH does not get this far: GetTempPathW then skips it.) +foreach(mode run init) + set(trace "${TRACE_DIR}/tls_index0_${mode}.jsonl") + file(REMOVE "${trace}") # --trace only creates a new file + execute_process( + COMMAND ${RUNNER} "${LOADER}" --${mode} "${GUEST}" --trace "${trace}" + TIMEOUT 90 + RESULT_VARIABLE code OUTPUT_VARIABLE output ERROR_VARIABLE error) + if(NOT code STREQUAL "0") + message(FATAL_ERROR "--${mode} returned ${code}\n${output}\n${error}") + endif() + if(mode STREQUAL "run" AND (NOT output MATCHES "tiny_tls_ga: tls_index=0 main=42 thread=42 OK" + OR NOT output MATCHES "game exited with code 0")) + message(FATAL_ERROR "--run did not read the TLS from slot 0\n${output}\n${error}") + endif() + if(error MATCHES "does not get module TLS index 0") + message(FATAL_ERROR "--${mode}: the executable was not given index 0\n${error}") + endif() + file(READ "${trace}" lines) + if(NOT lines MATCHES "\"kind\":\"tls_index0\",\"owner\":\"gta6rt.exe\",\"moved_to\":[1-9][0-9]*}") + message(FATAL_ERROR "--${mode}: no tls_index0 event naming gta6rt.exe in the trace\n${lines}") + endif() + file(REMOVE "${trace}") +endforeach() + +set(missing "${TRACE_DIR}/leonida_no_such_temp") +file(REMOVE_RECURSE "${missing}") +foreach(mode run init dry-run) + execute_process( + COMMAND ${CMAKE_COMMAND} -E env "TMP=${missing}" "TEMP=${missing}" ${RUNNER} "${LOADER}" --${mode} "${GUEST}" + TIMEOUT 90 + RESULT_VARIABLE code OUTPUT_VARIABLE output ERROR_VARIABLE error) + set(reason "module TLS index 0 \\(the home clone of gta6rt_tls_host.dll cannot be loaded") + if(mode STREQUAL "dry-run") + if(NOT code STREQUAL "0" OR NOT error MATCHES "does not get ${reason}") + message(FATAL_ERROR "--dry-run without the reservation returned ${code}\n${output}\n${error}") + endif() + elseif(NOT code STREQUAL "1" OR NOT error MATCHES "cannot have ${reason}" OR output MATCHES "running ") + message(FATAL_ERROR "--${mode} without the reservation returned ${code}\n${output}\n${error}") + endif() +endforeach() diff --git a/runtime/test/clzero_patch_test.cpp b/runtime/test/clzero_patch_test.cpp new file mode 100644 index 0000000000..dc34de8f8f --- /dev/null +++ b/runtime/test/clzero_patch_test.cpp @@ -0,0 +1,116 @@ +// clzero_patch.h: the two CLZERO loop shapes the title uses are found, rewritten to jump to stubs, and the stubs +// zero exactly the lines the loops would zero and leave the registers the loops leave. The loops are hand-assembled +// here (no game code), and only the patched copies run, so the test runs on any x86-64 CPU. +#include + +#include +#include +#include +#include + +#include "clzero_patch.h" + +namespace { + +int failures = 0; +int checks = 0; + +void check(bool ok, const char* what) { + ++checks; + if (!ok) ++failures; + std::printf("%s %s\n", ok ? "PASS" : "FAIL", what); +} + +// uint64_t f(void* begin, void* end): shape A over [begin, end), returns rax at the loop's exit. +const uint8_t kShapeA[] = { + 0x48, 0x89, 0xC8, // mov rax, rcx + 0x49, 0x89, 0xD2, // mov r10, rdx + 0x0F, 0x01, 0xFC, // L: clzero + 0x48, 0x83, 0xC0, 0x40, // add rax, 40h + 0x4C, 0x39, 0xD0, // cmp rax, r10 + 0x72, 0xF4, // jb L + 0xC3, // ret +}; + +// uint64_t f(void* begin, void* end): shape B over [begin, end), returns the counter at the loop's exit. +const uint8_t kShapeB[] = { + 0x49, 0x89, 0xCA, // mov r10, rcx + 0x49, 0x89, 0xD3, // mov r11, rdx + 0x4C, 0x89, 0xD0, // L: mov rax, r10 + 0x49, 0x83, 0xC2, 0x40, // add r10, 40h + 0x0F, 0x01, 0xFC, // clzero + 0x4D, 0x39, 0xDA, // cmp r10, r11 + 0x72, 0xF1, // jb L + 0x4C, 0x89, 0xD0, // mov rax, r10 + 0xC3, // ret +}; + +// Shape A with cmp rax, rcx: rcx is the register the stub saves, so this loop is left alone. +const uint8_t kShapeAWithRcx[] = { + 0x0F, 0x01, 0xFC, // clzero + 0x48, 0x83, 0xC0, 0x40, // add rax, 40h + 0x48, 0x39, 0xC8, // cmp rax, rcx + 0x72, 0xF4, // jb + 0xC3, +}; + +using Loop = uint64_t (*)(void*, void*); + +// Fills a buffer, runs `loop` over [buf + first, buf + last) and checks which bytes changed. +bool zeroes_exactly(Loop loop, size_t first, size_t last, uint64_t& returned) { + alignas(64) static uint8_t buf[4096]; + std::memset(buf, 0xAB, sizeof buf); + returned = loop(buf + first, buf + last); + for (size_t i = 0; i < sizeof buf; ++i) { + const bool inside = i >= (first & ~size_t(63)) && i < last; + if (buf[i] != (inside ? 0 : 0xAB)) return false; + } + return returned == reinterpret_cast(buf + last); +} + +} // namespace + +int main() { + namespace cz = rt::clzero_patch; + { + const auto a = cz::find(kShapeA, sizeof kShapeA); + check(a.size() == 1 && a[0].head == 6 && a[0].length == 12 && a[0].clzero == 0, "shape A is found at its CLZERO"); + const auto b = cz::find(kShapeB, sizeof kShapeB); + check(b.size() == 1 && b[0].head == 6 && b[0].length == 15 && b[0].clzero == 7, + "shape B is found at its mov rax, CUR"); + check(cz::find(kShapeAWithRcx, sizeof kShapeAWithRcx).empty(), "a loop that compares against rcx is left alone"); + const uint8_t lone[] = {0x0F, 0x01, 0xFC, 0xC3}; + check(cz::find(lone, sizeof lone).empty(), "a CLZERO outside both loop shapes is left alone"); + } + + auto* code = static_cast(VirtualAlloc(nullptr, 0x1000, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE)); + check(code != nullptr, "code page"); + if (!code) return 1; + std::memcpy(code, kShapeA, sizeof kShapeA); + std::memcpy(code + 0x100, kShapeB, sizeof kShapeB); + const auto r = cz::patch({{code, 0x1000}}, uint64_t(code), uint64_t(code) + 0x1000); + check(r.sites == 2 && r.stubs != nullptr, "both loops are patched"); + check(code[6] == 0xE9 && code[0x106] == 0xE9, "each loop starts with a jmp rel32 to its stub"); + const int64_t distance = int64_t(r.stubs) - int64_t(code); + check(distance > -(int64_t(1) << 31) && distance < (int64_t(1) << 31), "the stubs are within 2 GiB of the code"); + FlushInstructionCache(GetCurrentProcess(), code, 0x1000); + + const auto shape_a = reinterpret_cast(code); + const auto shape_b = reinterpret_cast(code + 0x100); + uint64_t ret = 0; + check(zeroes_exactly(shape_a, 64, 64 + 1024, ret), "shape A zeroes its 16 lines and returns rax = end"); + check(zeroes_exactly(shape_a, 128, 192, ret), "shape A runs once for a one-line range"); + check(zeroes_exactly(shape_b, 256, 256 + 0x380, ret), "shape B zeroes its 14 lines and leaves CUR = end"); + { + // An unaligned start: CLZERO zeroes the whole line rAX points into, and the loop steps by 64 from rAX. + alignas(64) static uint8_t buf[512]; + std::memset(buf, 0xAB, sizeof buf); + shape_a(buf + 64 + 8, buf + 64 + 8 + 128); + bool ok = true; + for (size_t i = 0; i < sizeof buf; ++i) ok &= buf[i] == ((i >= 64 && i < 64 + 128) ? 0 : 0xAB); + check(ok, "an unaligned start zeroes the lines rAX points into"); + } + + std::printf("clzero_patch_test: %s (%d checks)\n", failures ? "FAILED" : "OK", checks); + return failures ? 1 : 0; +} diff --git a/runtime/test/console_registry_test.cpp b/runtime/test/console_registry_test.cpp new file mode 100644 index 0000000000..21335d4c7a --- /dev/null +++ b/runtime/test/console_registry_test.cpp @@ -0,0 +1,340 @@ +// Tests for runtime/shims/console_registry.cpp: the title's registry read of the console model. +// The shim is reached the way the loader reaches it, through rt::shims::find, under every DLL name the title's +// modules import the registry functions from. +#include + +#include +#include +#include + +#include "console_identity.h" +#include "console_registry.h" +#include "shims.h" + +namespace { + +using namespace rt::shims; + +int g_checks = 0; +int g_failures = 0; + +void check(bool condition, const char* what) { + ++g_checks; + std::printf("%s %s\n", condition ? "PASS" : "FAIL", what); + if (!condition) ++g_failures; +} + +using OpenFn = LSTATUS(WINAPI*)(HKEY, LPCWSTR, PHKEY); +using OpenExFn = LSTATUS(WINAPI*)(HKEY, LPCWSTR, DWORD, REGSAM, PHKEY); +using QueryFn = LSTATUS(WINAPI*)(HKEY, LPCWSTR, LPDWORD, LPDWORD, LPBYTE, LPDWORD); +using CloseFn = LSTATUS(WINAPI*)(HKEY); + +const wchar_t kOem[] = L"Software\\Microsoft\\Windows NT\\CurrentVersion\\OEM"; +const wchar_t kCurrentVersion[] = L"Software\\Microsoft\\Windows NT\\CurrentVersion"; + +// What the title's import binds to: the shim registered for advapi32.dll. +OpenFn open_w() { return reinterpret_cast(find("advapi32.dll", "RegOpenKeyW")); } +OpenExFn open_ex_w() { return reinterpret_cast(find("advapi32.dll", "RegOpenKeyExW")); } +QueryFn query_w() { return reinterpret_cast(find("advapi32.dll", "RegQueryValueExW")); } +CloseFn close_k() { return reinterpret_cast(find("advapi32.dll", "RegCloseKey")); } + +void set_device_type(const char* text) { SetEnvironmentVariableA("LEONIDA_DEVICE_TYPE", text); } + +// Opens our key the way the title does and reads ConsoleMode into `mode`; returns the query's status. +LSTATUS read_console_mode(DWORD& mode) { + HKEY key = nullptr; + if (open_w()(HKEY_LOCAL_MACHINE, kOem, &key) != ERROR_SUCCESS) return ERROR_PATH_NOT_FOUND; + DWORD type = 0, size = sizeof(mode); + mode = 0; + const LSTATUS r = query_w()(key, L"ConsoleMode", nullptr, &type, reinterpret_cast(&mode), &size); + close_k()(key); + return r == ERROR_SUCCESS && (type != REG_DWORD || size != sizeof(DWORD)) ? ERROR_BAD_FORMAT : r; +} + +// A host registry that records what it was asked and answers a status no real registry returns. +constexpr LSTATUS kFromHost = 0x5A5A; +struct Calls { + int open = 0, open_ex = 0, query = 0, close = 0; + HKEY last_key = nullptr; + LPCWSTR last_sub = nullptr; + LPCWSTR last_name = nullptr; + DWORD last_options = 0, last_desired = 0; + LPBYTE last_data = nullptr; + LPDWORD last_size = nullptr; +} g_calls; + +LSTATUS WINAPI fake_open(HKEY k, LPCWSTR sub, PHKEY) { + ++g_calls.open; + g_calls.last_key = k; + g_calls.last_sub = sub; + return kFromHost; +} +LSTATUS WINAPI fake_open_ex(HKEY k, LPCWSTR sub, DWORD options, REGSAM desired, PHKEY) { + ++g_calls.open_ex; + g_calls.last_key = k; + g_calls.last_sub = sub; + g_calls.last_options = options; + g_calls.last_desired = desired; + return kFromHost; +} +LSTATUS WINAPI fake_query(HKEY k, LPCWSTR name, LPDWORD, LPDWORD, LPBYTE data, LPDWORD size) { + ++g_calls.query; + g_calls.last_key = k; + g_calls.last_name = name; + g_calls.last_data = data; + g_calls.last_size = size; + return kFromHost; +} +LSTATUS WINAPI fake_close(HKEY k) { + ++g_calls.close; + g_calls.last_key = k; + return kFromHost; +} +const console_registry::HostRegistry kFakeHost{fake_open, fake_open_ex, fake_query, fake_close}; + +void test_registered_under_every_name() { + const char* const dlls[] = {"advapi32.dll", + "api-ms-win-core-registry-l1-1-0.dll", "api-ms-win-core-registry-l1-1-1.dll", + "api-ms-win-core-registry-l1-1-2.dll", "api-ms-win-core-registry-l2-1-0.dll", + "api-ms-win-core-registry-l2-1-1.dll"}; + const char* const names[] = {"RegOpenKeyW", "RegOpenKeyExW", "RegQueryValueExW", "RegCloseKey"}; + bool all = true; + for (const char* d : dlls) + for (const char* n : names) all = all && find(d, n) != nullptr; + check(all, "the four registry functions resolve under advapi32 and the registry API sets"); + check(find("advapi32.dll", "RegOpenKeyW") == find("api-ms-win-core-registry-l2-1-0.dll", "RegOpenKeyW"), + "an API set and advapi32 bind the same shim"); + check(find("advapi32.dll", "RegSetValueExW") == nullptr, "other advapi32 functions are not shimmed"); + check(!owns_dll("advapi32.dll") && !owns_dll("api-ms-win-core-registry-l1-1-0.dll"), + "advapi32 and the API sets stay host modules (no pseudo-handle for LoadLibrary)"); +} + +void test_our_key_for_each_device_type() { + struct Case { const char* env; DWORD mode; const char* what; } cases[] = { + {"6", 0x60, "device type 6 (Series S) -> ConsoleMode 0x60"}, + {"7", 0x64, "device type 7 (Series X) -> ConsoleMode 0x64"}, + {"8", 0x68, "device type 8 (devkit) -> ConsoleMode 0x68"}, + {nullptr, 0x64, "no setting -> Series X, ConsoleMode 0x64 (as XSystemGetDeviceType)"}, + {"99", 0x64, "a device type out of range is ignored -> 0x64"}, + }; + for (const auto& c : cases) { + set_device_type(c.env); + DWORD mode = 0; + const LSTATUS r = read_console_mode(mode); + check(r == ERROR_SUCCESS && mode == c.mode, c.what); + } + // The same setting drives XSystemGetDeviceType: ConsoleMode for 6 and 7 is the one the device type names. + for (uint32_t t = 0; t <= 8; ++t) { + char text[4]; + std::snprintf(text, sizeof text, "%u", t); + set_device_type(text); + DWORD mode = 0; + const bool has = console_identity::console_mode_for(console_identity::configured_device_type(), mode); + check(console_identity::configured_device_type() == t && has == (t >= 6), + "configured_device_type follows LEONIDA_DEVICE_TYPE; only the Series types have a ConsoleMode"); + } + set_device_type(nullptr); +} + +void test_pc_and_xbox_one_are_not_ours() { + console_registry::set_host_registry_for_test(&kFakeHost); + for (const char* env : {"0", "1", "2", "5"}) { + set_device_type(env); + g_calls = {}; + HKEY key = nullptr; + const LSTATUS r = open_w()(HKEY_LOCAL_MACHINE, kOem, &key); + check(r == kFromHost && g_calls.open == 1 && key == nullptr, + "a device type without a ConsoleMode leaves the OEM key to the host registry"); + } + set_device_type(nullptr); + console_registry::set_host_registry_for_test(nullptr); +} + +void test_size_query_and_type() { + set_device_type("7"); + HKEY key = nullptr; + check(open_ex_w()(HKEY_LOCAL_MACHINE, kOem, 0, KEY_READ, &key) == ERROR_SUCCESS && + key == console_registry::pseudo_key(), + "RegOpenKeyExW hands out the pseudo key"); + + DWORD type = 0, size = 0; + check(query_w()(key, L"ConsoleMode", nullptr, &type, nullptr, &size) == ERROR_SUCCESS && type == REG_DWORD && + size == sizeof(DWORD), + "a size query (null data) reports 4 bytes and REG_DWORD"); + + size = 0xFFFF; // the size query ignores what was in there + check(query_w()(key, L"ConsoleMode", nullptr, nullptr, nullptr, &size) == ERROR_SUCCESS && size == 4, + "a size query with no type pointer works"); + + type = 0; + check(query_w()(key, L"ConsoleMode", nullptr, &type, nullptr, nullptr) == ERROR_SUCCESS && type == REG_DWORD, + "null data and null size report just the type"); + check(query_w()(key, L"ConsoleMode", nullptr, nullptr, nullptr, nullptr) == ERROR_SUCCESS, + "everything null is a plain existence check"); + + // Room for more than a DWORD: the size comes back as 4. + uint8_t big[8]; + std::memset(big, 0xEE, sizeof big); + size = sizeof big; + check(query_w()(key, L"ConsoleMode", nullptr, &type, big, &size) == ERROR_SUCCESS && size == 4 && + big[0] == 0x64 && big[1] == 0 && big[2] == 0 && big[3] == 0 && big[4] == 0xEE, + "a larger buffer gets exactly 4 bytes and the size comes back as 4"); + + // An unaligned buffer. + uint8_t raw[8] = {}; + size = 4; + check(query_w()(key, L"ConsoleMode", nullptr, &type, raw + 1, &size) == ERROR_SUCCESS && raw[1] == 0x64 && + raw[0] == 0 && raw[5] == 0, + "an unaligned buffer is written byte-wise"); + + check(close_k()(key) == ERROR_SUCCESS, "RegCloseKey on the pseudo key succeeds"); + set_device_type(nullptr); +} + +void test_more_data() { + set_device_type("6"); + HKEY key = nullptr; + check(open_w()(HKEY_LOCAL_MACHINE, kOem, &key) == ERROR_SUCCESS, "open the OEM key (Series S)"); + for (DWORD room : {0u, 1u, 2u, 3u}) { + uint8_t buf[4] = {0xEE, 0xEE, 0xEE, 0xEE}; + DWORD size = room, type = 0; + const LSTATUS r = query_w()(key, L"ConsoleMode", nullptr, &type, buf, &size); + check(r == ERROR_MORE_DATA && size == 4 && type == REG_DWORD && buf[0] == 0xEE && buf[1] == 0xEE && + buf[2] == 0xEE && buf[3] == 0xEE, + "a short buffer returns ERROR_MORE_DATA, the needed size and the type, and writes nothing"); + } + uint8_t buf[4] = {}; + DWORD size = 4; + check(query_w()(key, L"ConsoleMode", nullptr, nullptr, buf, &size) == ERROR_SUCCESS && buf[0] == 0x60, + "a buffer of exactly 4 bytes is enough (and Series S gives 0x60)"); + close_k()(key); + set_device_type(nullptr); +} + +void test_bad_arguments_and_names() { + set_device_type("7"); + HKEY key = nullptr; + open_w()(HKEY_LOCAL_MACHINE, kOem, &key); + uint8_t buf[4]; + DWORD type = 0; + check(query_w()(key, L"ConsoleMode", nullptr, &type, buf, nullptr) == ERROR_INVALID_PARAMETER, + "a data buffer with no size pointer is ERROR_INVALID_PARAMETER"); + DWORD size = 4; + check(query_w()(key, L"consolemode", nullptr, &type, buf, &size) == ERROR_SUCCESS && buf[0] == 0x64, + "the value name is case-insensitive"); + size = 4; + check(query_w()(key, L"Other", nullptr, &type, buf, &size) == ERROR_FILE_NOT_FOUND, "another value does not exist"); + check(query_w()(key, nullptr, nullptr, &type, buf, &size) == ERROR_FILE_NOT_FOUND, + "the default value does not exist"); + check(query_w()(key, L"", nullptr, &type, buf, &size) == ERROR_FILE_NOT_FOUND, "an empty value name does not exist"); + + HKEY sub = nullptr; + check(open_w()(key, L"Sub", &sub) == ERROR_FILE_NOT_FOUND && open_ex_w()(key, L"Sub", 0, KEY_READ, &sub) == + ERROR_FILE_NOT_FOUND, + "the pseudo key has no subkeys"); + check(open_w()(key, nullptr, &sub) == ERROR_SUCCESS && sub == console_registry::pseudo_key(), + "opening the pseudo key with no subkey path gives the key again"); + + HKEY again = nullptr; + const wchar_t mixed[] = L"software\\MICROSOFT\\windows nt\\CurrentVersion\\oem"; + check(open_w()(HKEY_LOCAL_MACHINE, mixed, &again) == ERROR_SUCCESS && again == console_registry::pseudo_key(), + "the key path is case-insensitive"); + check(close_k()(key) == ERROR_SUCCESS && close_k()(key) == ERROR_SUCCESS, "closing the pseudo key twice is harmless"); + set_device_type(nullptr); +} + +void test_other_keys_fall_through() { + set_device_type("7"); + console_registry::set_host_registry_for_test(&kFakeHost); + HKEY key = nullptr; + + g_calls = {}; + check(open_w()(HKEY_LOCAL_MACHINE, kCurrentVersion, &key) == kFromHost && g_calls.open == 1 && + g_calls.last_key == HKEY_LOCAL_MACHINE && g_calls.last_sub == kCurrentVersion, + "RegOpenKeyW of another HKLM key reaches the host with its arguments"); + g_calls = {}; + check(open_w()(HKEY_CURRENT_USER, kOem, &key) == kFromHost && g_calls.open == 1 && + g_calls.last_key == HKEY_CURRENT_USER, + "the OEM path under HKCU is not ours"); + g_calls = {}; + check(open_w()(HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows NT\\CurrentVersion\\OEM\\Sub", &key) == kFromHost, + "a subkey of the OEM path is not ours"); + check(open_w()(HKEY_LOCAL_MACHINE, nullptr, &key) == kFromHost, "HKLM with no subkey is not ours"); + g_calls = {}; + check(open_ex_w()(HKEY_LOCAL_MACHINE, kCurrentVersion, 3, KEY_QUERY_VALUE | KEY_WOW64_64KEY, &key) == kFromHost && + g_calls.open_ex == 1 && g_calls.last_options == 3 && + g_calls.last_desired == (KEY_QUERY_VALUE | KEY_WOW64_64KEY) && g_calls.last_sub == kCurrentVersion, + "RegOpenKeyExW of another key reaches the host with options and access"); + check(open_w()(HKEY_LOCAL_MACHINE, kOem, nullptr) == kFromHost, + "the OEM key with a null result pointer is left to the host to reject"); + + // A value query on a host key, even for the name ConsoleMode: forwarded unchanged. + HKEY host_key = reinterpret_cast(static_cast(0x1234)); + uint8_t buf[4]; + DWORD size = 4, type = 0; + g_calls = {}; + check(query_w()(host_key, L"ConsoleMode", nullptr, &type, buf, &size) == kFromHost && g_calls.query == 1 && + g_calls.last_key == host_key && g_calls.last_data == buf && g_calls.last_size == &size, + "RegQueryValueExW on a host key is forwarded, even for the name ConsoleMode"); + g_calls = {}; + check(close_k()(host_key) == kFromHost && g_calls.close == 1 && g_calls.last_key == host_key, + "RegCloseKey on a host key is forwarded"); + g_calls = {}; + check(close_k()(HKEY_LOCAL_MACHINE) == kFromHost && g_calls.close == 1, "a predefined key is closed by the host"); + + // Our own calls never reach the host. + g_calls = {}; + HKEY ours = nullptr; + DWORD mode = 0; + size = 4; + check(open_w()(HKEY_LOCAL_MACHINE, kOem, &ours) == ERROR_SUCCESS && + query_w()(ours, L"ConsoleMode", nullptr, &type, reinterpret_cast(&mode), &size) == ERROR_SUCCESS && + close_k()(ours) == ERROR_SUCCESS && mode == 0x64 && + g_calls.open + g_calls.open_ex + g_calls.query + g_calls.close == 0, + "the OEM key's open, query and close never reach the host"); + + console_registry::set_host_registry_for_test(nullptr); + set_device_type(nullptr); +} + +// The real advapi32 behind the shim (a Windows host, Wine): another key opens, reads and closes as it does directly. +void test_real_registry_behind_the_shim() { + set_device_type("7"); + HKEY key = nullptr; + const LSTATUS r = open_w()(HKEY_LOCAL_MACHINE, kCurrentVersion, &key); + check(r == ERROR_SUCCESS && key != nullptr && key != console_registry::pseudo_key(), + "the real HKLM\\...\\CurrentVersion opens through the shim as a host key"); + if (r == ERROR_SUCCESS) { + DWORD size = 0, type = 0; + const LSTATUS shim = query_w()(key, L"ProductName", nullptr, &type, nullptr, &size); + DWORD size2 = 0, type2 = 0; + const LSTATUS real = RegQueryValueExW(key, L"ProductName", nullptr, &type2, nullptr, &size2); + check(shim == real && size == size2 && type == type2, "a value of a host key reads the same through the shim"); + check(close_k()(key) == ERROR_SUCCESS, "the host key closes through the shim"); + } + + // The OEM key of a PC-class device type: whatever the host registry says, byte for byte. + set_device_type("1"); + HKEY a = nullptr, b = nullptr; + const LSTATUS shim = open_ex_w()(HKEY_LOCAL_MACHINE, kOem, 0, KEY_READ, &a); + const LSTATUS real = RegOpenKeyExW(HKEY_LOCAL_MACHINE, kOem, 0, KEY_READ, &b); + check(shim == real, "with a PC device type the OEM key is the host's: same status as a direct call"); + if (shim == ERROR_SUCCESS) close_k()(a); + if (real == ERROR_SUCCESS) RegCloseKey(b); + set_device_type(nullptr); +} + +} // namespace + +int main() { + test_registered_under_every_name(); + test_our_key_for_each_device_type(); + test_pc_and_xbox_one_are_not_ours(); + test_size_query_and_type(); + test_more_data(); + test_bad_arguments_and_names(); + test_other_keys_fall_through(); + test_real_registry_behind_the_shim(); + std::printf("%d check(s), %d failure(s)\n", g_checks, g_failures); + return g_failures ? 1 : 0; +} diff --git a/runtime/test/d3d12_a8_dimensions_test.cpp b/runtime/test/d3d12_a8_dimensions_test.cpp new file mode 100644 index 0000000000..82978cd0c1 --- /dev/null +++ b/runtime/test/d3d12_a8_dimensions_test.cpp @@ -0,0 +1,294 @@ +// A8_UNORM textures in every dimension: 1D, 2D and 3D, compared with Windows D3D12. The host adapter and WARP both +// report TEXTURE1D, TEXTURE2D and TEXTURE3D support for A8_UNORM, size those textures and create them; the layer must +// too (it holds them as R8 images read through the alpha swizzle, the same for every dimension). A byte pattern copied +// into each texture and back out must come back unchanged. Render targets, depth and UAVs stay refused. +// No game data or shaders. Run explicitly (needs Vulkan hardware); LEONIDA_VK_VALIDATION=1 checks Vulkan usage. +#include "vk_test_device.h" +#include "host_adapter.h" +#include "host_wine.h" +#include "../shims/d3d12_com.h" +#include +#include +#include +#include +#define CHECK(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return false; } \ +} while (0) + +namespace { +template +struct Ref { + T* p = nullptr; + ~Ref() { if (p) p->Release(); } + T* operator->() const { return p; } +}; +struct Event { + HANDLE handle = CreateEventW(nullptr, FALSE, FALSE, nullptr); + ~Event() { if (handle) CloseHandle(handle); } +}; + +struct Shape { + const char* name; + D3D12_RESOURCE_DIMENSION dimension; + UINT64 width; + UINT height; + UINT16 depth; + UINT16 mips; +}; + +// The 1D shape is the one the retail title sizes through device slot 25 (128 texels, one mip). +constexpr Shape kShapes[] = { + {"1D 128", D3D12_RESOURCE_DIMENSION_TEXTURE1D, 128, 1, 1, 1}, + {"1D 300, 3 mips", D3D12_RESOURCE_DIMENSION_TEXTURE1D, 300, 1, 1, 3}, + {"1D array 64 x4", D3D12_RESOURCE_DIMENSION_TEXTURE1D, 64, 1, 4, 1}, + {"2D 13x7", D3D12_RESOURCE_DIMENSION_TEXTURE2D, 13, 7, 1, 1}, + {"3D 16x8x4, 2 mips", D3D12_RESOURCE_DIMENSION_TEXTURE3D, 16, 8, 4, 2}, + {"3D 5x3x7", D3D12_RESOURCE_DIMENSION_TEXTURE3D, 5, 3, 7, 1}, +}; + +D3D12_RESOURCE_DESC describe(const Shape& shape, UINT64 alignment, D3D12_RESOURCE_FLAGS flags) { + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = shape.dimension; + desc.Alignment = alignment; + desc.Width = shape.width; + desc.Height = shape.height; + desc.DepthOrArraySize = shape.depth; + desc.MipLevels = shape.mips; + desc.Format = DXGI_FORMAT_A8_UNORM; + desc.SampleDesc.Count = 1; + desc.Flags = flags; + return desc; +} + +HRESULT create(ID3D12Device* device, const D3D12_RESOURCE_DESC& desc, D3D12_RESOURCE_STATES state, + ID3D12Resource** out) { + // A null `out` only asks whether the description is valid, as the D3D12 documentation allows. + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + return device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, + __uuidof(ID3D12Resource), reinterpret_cast(out)); +} + +D3D12_RESOURCE_BARRIER transition(ID3D12Resource* resource, D3D12_RESOURCE_STATES before, + D3D12_RESOURCE_STATES after) { + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Transition.pResource = resource; + barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + barrier.Transition.StateBefore = before; + barrier.Transition.StateAfter = after; + return barrier; +} + +// Copies a byte pattern into every subresource of the texture, copies it back out into a readback buffer and compares +// every texel of every row and slice. +bool round_trip(ID3D12Device* device, const D3D12_RESOURCE_DESC& desc, unsigned& texels) { + Ref texture; + CHECK(SUCCEEDED(create(device, desc, D3D12_RESOURCE_STATE_COPY_DEST, &texture.p))); + const UINT subresources = desc.MipLevels * + (desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D ? 1u : desc.DepthOrArraySize); + D3D12_PLACED_SUBRESOURCE_FOOTPRINT layouts[16]{}; + UINT rows[16]{}; + UINT64 row_bytes[16]{}, total = 0; + CHECK(subresources <= 16); + device->GetCopyableFootprints(&desc, 0, subresources, 0, layouts, rows, row_bytes, &total); + CHECK(total != 0 && total != UINT64_MAX); + + D3D12_RESOURCE_DESC buffer{}; + buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buffer.Width = total; + buffer.Height = 1; + buffer.DepthOrArraySize = 1; + buffer.MipLevels = 1; + buffer.SampleDesc.Count = 1; + buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}, readback_heap{D3D12_HEAP_TYPE_READBACK}; + Ref upload, readback; + CHECK(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &buffer, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + IID_PPV_ARGS(&upload.p)))); + CHECK(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &buffer, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback.p)))); + auto pattern = [](UINT s, UINT z, UINT y, UINT x) { return std::uint8_t(7 + 13 * s + 5 * z + 3 * y + x); }; + std::uint8_t* bytes = nullptr; + CHECK(SUCCEEDED(upload->Map(0, nullptr, reinterpret_cast(&bytes)))); + std::memset(bytes, 0, static_cast(total)); + for (UINT s = 0; s < subresources; ++s) + for (UINT z = 0; z < layouts[s].Footprint.Depth; ++z) + for (UINT y = 0; y < rows[s]; ++y) + for (UINT x = 0; x < row_bytes[s]; ++x) + bytes[layouts[s].Offset + (z * rows[s] + y) * layouts[s].Footprint.RowPitch + x] = pattern(s, z, y, x); + upload->Unmap(0, nullptr); + + Ref queue; + Ref allocator; + Ref list; + Ref fence; + const D3D12_COMMAND_QUEUE_DESC queue_desc{}; + CHECK(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + CHECK(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + CHECK(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, + IID_PPV_ARGS(&list.p)))); + CHECK(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + for (UINT s = 0; s < subresources; ++s) { + D3D12_TEXTURE_COPY_LOCATION to{texture.p, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + to.SubresourceIndex = s; + D3D12_TEXTURE_COPY_LOCATION from{upload.p, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + from.PlacedFootprint = layouts[s]; + list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); + } + const auto to_source = transition(texture.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &to_source); + for (UINT s = 0; s < subresources; ++s) { + D3D12_TEXTURE_COPY_LOCATION to{readback.p, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + to.PlacedFootprint = layouts[s]; + D3D12_TEXTURE_COPY_LOCATION from{texture.p, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + from.SubresourceIndex = s; + list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); + } + CHECK(SUCCEEDED(list->Close())); + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + Event done; + CHECK(SUCCEEDED(queue->Signal(fence.p, 1))); + CHECK(SUCCEEDED(fence->SetEventOnCompletion(1, done.handle))); + CHECK(WaitForSingleObject(done.handle, 10000) == WAIT_OBJECT_0); + + CHECK(SUCCEEDED(readback->Map(0, nullptr, reinterpret_cast(&bytes)))); + bool same = true; + for (UINT s = 0; s < subresources; ++s) + for (UINT z = 0; z < layouts[s].Footprint.Depth; ++z) + for (UINT y = 0; y < rows[s]; ++y) + for (UINT x = 0; x < row_bytes[s]; ++x, ++texels) { + const std::uint8_t got = + bytes[layouts[s].Offset + (z * rows[s] + y) * layouts[s].Footprint.RowPitch + x]; + if (got != pattern(s, z, y, x) && same) { + std::fprintf(stderr, "subresource %u texel (%u, %u, %u): %u, expected %u\n", s, x, y, z, + unsigned(got), unsigned(pattern(s, z, y, x))); + same = false; + } + } + readback->Unmap(0, nullptr); + return same; +} +} // namespace + +int main() { + vktest::Device vk; + const auto device_status = vk.initialize(); + if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips + if (device_status != vktest::DeviceStatus::ready) return 1; + unsigned failures = 0, references = 0, sized = 0, texels = 0; + { + Ref ours; + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = vk.instance_proc; + info.instance = vk.instance; + info.physical = vk.physical; + info.device = vk.device; + info.queue = vk.queue; + info.queue_family = vk.family; + info.conditional_rendering = vk.conditional_rendering; + info.storage_buffer_8bit = vk.storage_buffer_8bit; + info.buffer_device_address = vk.buffer_device_address; + if (FAILED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&ours.p)))) return 1; + if (hostwine::host_is_wine()) return 77; // every check is a comparison with Windows D3D12 + Ref factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p)))) { + std::fprintf(stderr, "no DXGI factory\n"); + return 1; + } + Ref hosts[2]; // the layer's own adapter, then WARP + std::string names[2]; + for (int warp = 0; warp < 2; ++warp) { + Ref adapter; + if (!hostadapter::reference(factory.p, vk, warp == 1, &adapter.p, names[warp])) continue; + if (FAILED(D3D12CreateDevice(adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&hosts[warp].p)))) + hosts[warp].p = nullptr; + else + ++references; + } + if (!hosts[1].p) { + std::fprintf(stderr, "WARP reference unavailable\n"); + return 1; + } + + // Format support: the dimension bits match every reference. + constexpr UINT dimension_bits = + D3D12_FORMAT_SUPPORT1_TEXTURE1D | D3D12_FORMAT_SUPPORT1_TEXTURE2D | D3D12_FORMAT_SUPPORT1_TEXTURE3D; + D3D12_FEATURE_DATA_FORMAT_SUPPORT ours_support{DXGI_FORMAT_A8_UNORM}; + if (FAILED(ours->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &ours_support, sizeof(ours_support)))) { + std::fprintf(stderr, "A8_UNORM format support query failed\n"); + ++failures; + } + for (int h = 0; h < 2; ++h) { + if (!hosts[h].p) continue; + D3D12_FEATURE_DATA_FORMAT_SUPPORT host_support{DXGI_FORMAT_A8_UNORM}; + hosts[h]->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &host_support, sizeof(host_support)); + if ((UINT(ours_support.Support1) & dimension_bits) != (UINT(host_support.Support1) & dimension_bits)) { + std::fprintf(stderr, "A8_UNORM dimension support 0x%x, %s reports 0x%x\n", + UINT(ours_support.Support1) & dimension_bits, names[h].c_str(), + UINT(host_support.Support1) & dimension_bits); + ++failures; + } + } + + // Sizing and creation: where every reference sizes and creates the texture, the layer must too, with the + // reference's alignment (64 KiB, or 4 KiB when the description asks for it and qualifies). + for (const Shape& shape : kShapes) { + for (UINT64 alignment : {UINT64(0), UINT64(D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT)}) { + const D3D12_RESOURCE_DESC desc = describe(shape, alignment, D3D12_RESOURCE_FLAG_NONE); + bool every_host = true; + UINT64 host_alignment = 0; + for (int h = 0; h < 2; ++h) { + if (!hosts[h].p) continue; + const D3D12_RESOURCE_ALLOCATION_INFO host = hosts[h]->GetResourceAllocationInfo(0, 1, &desc); + D3D12_RESOURCE_DESC created = desc; + created.Alignment = 0; + if (host.SizeInBytes == UINT64_MAX || + FAILED(create(hosts[h].p, created, D3D12_RESOURCE_STATE_COMMON, nullptr))) + every_host = false; + else if (h == 1) + host_alignment = host.Alignment; + } + if (!every_host) { + std::printf("%s, alignment %llu: a reference refuses it; skipped\n", shape.name, + static_cast(alignment)); + continue; + } + const D3D12_RESOURCE_ALLOCATION_INFO mine = ours->GetResourceAllocationInfo(0, 1, &desc); + if (mine.SizeInBytes == UINT64_MAX || mine.Alignment != host_alignment) { + std::fprintf(stderr, "%s, alignment %llu: size %llu alignment %llu, WARP alignment %llu\n", + shape.name, static_cast(alignment), + static_cast(mine.SizeInBytes), + static_cast(mine.Alignment), + static_cast(host_alignment)); + ++failures; + continue; + } + ++sized; + if (alignment) continue; // creation ignores the alignment; one round trip per shape + if (!round_trip(ours.p, desc, texels)) { + std::fprintf(stderr, "%s: the round trip failed\n", shape.name); + ++failures; + } + } + } + + // Render targets, depth and unordered access stay refused, in every dimension. + for (const Shape& shape : kShapes) { + for (auto flag : {D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS}) { + const D3D12_RESOURCE_DESC desc = describe(shape, 0, flag); + if (ours->GetResourceAllocationInfo(0, 1, &desc).SizeInBytes != UINT64_MAX || + SUCCEEDED(create(ours.p, desc, D3D12_RESOURCE_STATE_COMMON, nullptr))) { + std::fprintf(stderr, "%s with flag 0x%x: accepted\n", shape.name, unsigned(flag)); + ++failures; + } + } + } + } + std::printf("A8_UNORM dimensions: %u references, %u descriptions sized, %u texels round-tripped, %u failures\n", + references, sized, texels, failures); + return failures ? 1 : 0; +} diff --git a/runtime/test/d3d12_buffer_uav_test.cpp b/runtime/test/d3d12_buffer_uav_test.cpp index a2fa903302..c2ea4fb37a 100644 --- a/runtime/test/d3d12_buffer_uav_test.cpp +++ b/runtime/test/d3d12_buffer_uav_test.cpp @@ -161,7 +161,7 @@ int run_shaders(vktest::Device& d, const std::filesystem::path& root_dir, unsign EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); + reinterpret_cast(&device.p), /*console_lists=*/false))); rt::d3d12::set_device_outer(inner, device.p); EXPECT(rt::d3d12::bindless_set(device.p) != VK_NULL_HANDLE); diff --git a/runtime/test/d3d12_clear_formats_test.cpp b/runtime/test/d3d12_clear_formats_test.cpp index 33088abeec..f8b594a487 100644 --- a/runtime/test/d3d12_clear_formats_test.cpp +++ b/runtime/test/d3d12_clear_formats_test.cpp @@ -234,6 +234,7 @@ const std::vector kSint = {{-1, -2, -128, 127}, {-1.5f, -2.5f, 2.5f, 3.5f const ColorCase kColorCases[] = { {"UNORM", "R8_UNORM", DXGI_FORMAT_R8_UNORM, 1, &kUnorm}, + {"UNORM", "A8_UNORM", DXGI_FORMAT_A8_UNORM, 1, &kUnorm}, // the alpha component only {"UNORM", "R8G8_UNORM", DXGI_FORMAT_R8G8_UNORM, 2, &kUnorm}, {"UNORM", "R8G8B8A8_UNORM", DXGI_FORMAT_R8G8B8A8_UNORM, 4, &kUnorm}, {"UNORM", "B8G8R8A8_UNORM", DXGI_FORMAT_B8G8R8A8_UNORM, 4, &kUnorm}, @@ -336,6 +337,7 @@ int main() { info.device = vk.device; info.queue = vk.queue; info.queue_family = vk.family; + info.a8_render_target = vk.a8_render_target; if (FAILED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&ours.p)))) return 1; Ref factory; Ref warp; diff --git a/runtime/test/d3d12_compute_test.cpp b/runtime/test/d3d12_compute_test.cpp index 5ba3ded525..9faebb7c59 100644 --- a/runtime/test/d3d12_compute_test.cpp +++ b/runtime/test/d3d12_compute_test.cpp @@ -321,7 +321,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); + reinterpret_cast(&device.p), /*console_lists=*/false))); rt::d3d12::set_device_outer(inner, device.p); // Root signature: [0] two constants (s4, s5), [1] a root UAV (s6:s7), [2] a one-CBV table (s8, its 32-bit VA): @@ -559,6 +559,88 @@ int main() { IID_PPV_ARGS(&list.p)))); EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + // Direct and indirect compute commands snapshot the bound shader heaps after s4..s8. + // Rebinding just the resource heap clears the sampler for the later command. + { + auto direct_desc = root_desc; + direct_desc.Desc_1_0.Flags = D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED | + D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED; + const auto direct_blob = serialize(direct_desc); + Ref direct_root; + EXPECT(SUCCEEDED(device->CreateRootSignature(0, direct_blob.data(), direct_blob.size(), IID_PPV_ARGS(&direct_root.p)))); + auto pipeline_desc = pso_desc; + pipeline_desc.pRootSignature = direct_root.p; + Ref direct_pso; + EXPECT(SUCCEEDED(device->CreateComputePipelineState(&pipeline_desc, IID_PPV_ARGS(&direct_pso.p)))); + Ref sampler; + auto sampler_desc = heap_desc; + sampler_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&sampler_desc, IID_PPV_ARGS(&sampler.p)))); + const auto smp = reinterpret_cast(slot(sampler.p, 10))(sampler.p); + const D3D12_INDIRECT_ARGUMENT_DESC arg{D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH}; + const D3D12_COMMAND_SIGNATURE_DESC signature_desc{12, 1, &arg, 0}; + Ref signature; + EXPECT(SUCCEEDED(device->CreateCommandSignature(&signature_desc, nullptr, IID_PPV_ARGS(&signature.p)))); + list->SetPipelineState(direct_pso.p); + list->SetComputeRootSignature(direct_root.p); + ID3D12DescriptorHeap* both[] = {sampler.p, heap.p}; + list->SetDescriptorHeaps(2, both); + list->SetComputeRootDescriptorTable(2, {gpu + 32}); + list->Dispatch(1, 1, 1); + list->SetDescriptorHeaps(1, &heap.p); + list->ExecuteIndirect(signature.p, 1, out_a.p, 0, nullptr, 0); + EXPECT(SUCCEEDED(list->Close())); + std::vector commands; + EXPECT(rt::d3d12::recorded_commands(list.p, commands) && commands.size() == 2); + const auto& before = std::get(commands[0]).user_data; + const auto& after = std::get(commands[1]).user_data; + EXPECT(before[8] == gpu + 32 && before[9] == gpu && before[10] == smp); + EXPECT(after[8] == gpu + 32 && after[9] == gpu && after[10] == 0); + EXPECT(SUCCEEDED(list->Reset(allocator.p, nullptr))); + // The shader follows the V# at the heap index in s4. Slot 1 and the unrelated explicit table are null. + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = DXGI_FORMAT_R32_TYPELESS; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + srv.Buffer.NumElements = 4; + srv.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + device->CreateShaderResourceView(nullptr, &srv, {cpu + 32}); + device->CreateShaderResourceView(constants.p, &srv, {cpu + 2 * 32}); + list->SetComputeRootSignature(direct_root.p); + list->SetPipelineState(direct_pso.p); + list->SetDescriptorHeaps(2, both); + list->SetComputeRootDescriptorTable(2, {gpu + 32}); + list->SetComputeRootUnorderedAccessView(1, va_a); + for (UINT index = 1; index <= 2; ++index) { + const UINT inputs[] = {index, 0xfffffffcu}; + list->SetComputeRoot32BitConstants(0, 2, inputs, 0); + list->Dispatch(1, 1, 1); + const auto copy = transition(out_a.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, ©); + list->CopyBufferRegion(readback.p, (index - 1) * bytes, out_a.p, 0, bytes); + const auto resume = transition(out_a.p, D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + list->ResourceBarrier(1, &resume); + } + EXPECT(SUCCEEDED(list->Close())); + ID3D12CommandList* submitted[] = {list.p}; + queue->ExecuteCommandLists(1, submitted); + Ref done; + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&done.p)))); + EXPECT(SUCCEEDED(queue->Signal(done.p, 1)) && SUCCEEDED(done->SetEventOnCompletion(1, nullptr))); + void* results{}; + EXPECT(SUCCEEDED(readback->Map(0, nullptr, &results))); + const auto* values = static_cast(results); + for (UINT i = 0; i < elements; ++i) { + EXPECT(values[i] == 0); + EXPECT(values[elements + i] == table_values[i % 4]); + } + readback->Unmap(0, nullptr); + std::puts("directly indexed compute heap: 64 buffer reads and 64 null controls matched"); + EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, nullptr))); + } + // Misuse is reported by Close: a dispatch without a pipeline, a root view set on a constants parameter. list->Dispatch(1, 1, 1); EXPECT(list->Close() == E_INVALIDARG); @@ -683,6 +765,8 @@ int main() { device->CreateConstantBufferView(&cbv_a, slot_cpu(1)); device->CreateConstantBufferView(&cbv_b, slot_cpu(2)); + wchar_t raw_env[2]{}; + const bool raw_cbv = GetEnvironmentVariableW(L"LEONIDA_CBV_RAW", raw_env, 2) == 1 && raw_env[0] == L'1'; // Decode the written V# in slots 1 and 2 and verify every field + zeroed trailing 16 bytes. for (const auto& [slot_idx, expected_va] : {std::pair{1u, std::uint64_t(cb_va)}, std::pair{2u, std::uint64_t(cb_va + 256)}}) { @@ -691,11 +775,16 @@ int main() { leonida::gfx10::Buffer decoded{}; EXPECT(leonida::gfx10::decode(raw, decoded)); EXPECT(decoded.address == expected_va); - EXPECT(decoded.stride == 0); - EXPECT(decoded.num_records == 256); - EXPECT(decoded.format == leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT)); - EXPECT(decoded.swizzle == leonida::gfx10::identity_swizzle); - EXPECT(decoded.oob_select == leonida::gfx10::OobSelect::raw); + if (raw_cbv) { + EXPECT(decoded.stride == 0 && decoded.num_records == 256); + EXPECT(decoded.format == leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT)); + EXPECT(decoded.swizzle == leonida::gfx10::identity_swizzle); + EXPECT(decoded.oob_select == leonida::gfx10::OobSelect::raw); + } else { + EXPECT(decoded.stride == 16 && decoded.num_records == 16); + EXPECT(decoded.oob_select == leonida::gfx10::OobSelect::structured_with_offset); + EXPECT(raw[3] == 0x0002403Cu); + } EXPECT(std::memcmp(reinterpret_cast(slot_cpu(slot_idx).ptr) + 16, zeros, 16) == 0); } @@ -772,7 +861,7 @@ int main() { EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &deny_buf_desc, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&srv_deny.p)))); - const auto srv_rb_desc = buffer_desc(6 * bytes, D3D12_RESOURCE_FLAG_NONE); + const auto srv_rb_desc = buffer_desc(8 * bytes, D3D12_RESOURCE_FLAG_NONE); EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &srv_rb_desc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&srv_readback.p)))); @@ -848,10 +937,10 @@ int main() { EXPECT(decode_slot(3, d3)); EXPECT(d3.address == srv_va && d3.stride == 16 && d3.num_records == 32 && d3.format == leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT) && - d3.oob_select == leonida::gfx10::OobSelect::structured); + d3.oob_select == leonida::gfx10::OobSelect::structured_with_offset); EXPECT(decode_slot(4, d4)); EXPECT(d4.address == srv_va + 256 && d4.stride == 16 && d4.num_records == 32 && - d4.oob_select == leonida::gfx10::OobSelect::structured); + d4.oob_select == leonida::gfx10::OobSelect::structured_with_offset); EXPECT(decode_slot(5, d5)); const leonida::gfx10::Swizzle want_swz = {leonida::gfx10::select_z, leonida::gfx10::select_y, leonida::gfx10::select_x, leonida::gfx10::select_one}; @@ -887,7 +976,7 @@ int main() { EXPECT(expect_zero_srv(srv_default.p, &bad)); // out of bounds (70 * 16 > 1024) EXPECT(expect_zero_srv(nullptr, &raw_a)); // null resource -> null V# - // Upload buffer contents to arena and dispatch 6 GPU passes through the shader-visible descriptor table. + // Upload buffer contents to arena and dispatch 8 GPU passes through the shader-visible descriptor table. // out_a is already in D3D12_RESOURCE_STATE_UNORDERED_ACCESS at the end of the CBV pass. EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, pso.p))); list->CopyBufferRegion(srv_default.p, 0, srv_upload.p, 0, buf_bytes); @@ -901,6 +990,7 @@ int main() { const struct SrvDispatch { UINT slot_idx; UINT readback_offset; + UINT field_offset = 0; } srv_dispatches[] = { {1, 0 * bytes}, {2, 1 * bytes}, @@ -908,10 +998,12 @@ int main() { {4, 3 * bytes}, {5, 4 * bytes}, {7, 5 * bytes}, + {3, 6 * bytes, 16}, // first dword past the structured record + {5, 7 * bytes, 16}, // same offset with the typed index-only check }; - const std::uint32_t srv_mode[2] = {0u, 0xFFFFFFFFu}; // s1 == 0xFFFFFFFF selects buffer SRV V# mode - list->SetComputeRoot32BitConstants(0, 2, srv_mode, 0); for (const auto& cfg : srv_dispatches) { + const std::uint32_t args[2] = {cfg.field_offset, 0xFFFFFFFFu}; + list->SetComputeRoot32BitConstants(0, 2, args, 0); list->SetComputeRootDescriptorTable(2, slot_gpu(cfg.slot_idx)); list->Dispatch(1, 1, 1); const auto to_src = @@ -937,6 +1029,11 @@ int main() { std::memcpy(srv_struct_b.data(), rb + 3 * bytes, bytes); std::memcpy(srv_typed.data(), rb + 4 * bytes, bytes); std::memcpy(srv_null.data(), rb + 5 * bytes, bytes); + const auto* cross_record = static_cast(srv_res) + 6 * elements; + for (UINT i = 0; i < elements; ++i) { + EXPECT(cross_record[i] == 0u); + EXPECT(cross_record[elements + i] == (i < 24 ? 0x50000u + (9u + i) * 4u : 0u)); + } } for (auto* r : {&out_a, &out_b, &out_c, &constants, &readback}) r->reset(); diff --git a/runtime/test/d3d12_console_descriptor_heap_test.cpp b/runtime/test/d3d12_console_descriptor_heap_test.cpp index ed2d901f40..471c6a35ac 100644 --- a/runtime/test/d3d12_console_descriptor_heap_test.cpp +++ b/runtime/test/d3d12_console_descriptor_heap_test.cpp @@ -6,12 +6,22 @@ #include "vk_test_device.h" #include "../shims/d3d12_com.h" #include "../shims/d3d12_xs_device.h" +#include "../src/title_page_watch.h" #include #include namespace { +// The pages a test write watch made read-only, and its opener: the D3D12 layer's slot-133 shadows protect the title's +// pages the same way and give them back through leonida::kernel_writes. +std::uintptr_t g_watched_begin = 0, g_watched_end = 0; +void open_watched(std::uintptr_t from, std::uintptr_t to) { + DWORD old = 0; + if (from < g_watched_end && to > g_watched_begin) + VirtualProtect(reinterpret_cast(g_watched_begin), g_watched_end - g_watched_begin, PAGE_READWRITE, &old); +} + template struct Ref { T* p = nullptr; @@ -64,14 +74,17 @@ bool check_console_addressed_heap(ID3D12Device* device) { return true; } -bool check_xs_proxy_slot14(ID3D12Device* real_device) { - Ref proxy; - real_device->AddRef(); // create_device_proxy takes ownership of one reference on success - if (FAILED(rt::d3d12_xs::create_device_proxy(real_device, IID_PPV_ARGS(&proxy.p))) || !proxy.p) { - real_device->Release(); // the caller keeps its reference on failure +bool check_xs_proxy_slot14(ID3D12Device* real_device, bool expect_console) { + void* proxy_raw = nullptr; + // The proxy takes one reference to the device on success; the caller's Ref keeps its own. + real_device->AddRef(); + if (FAILED(rt::d3d12_xs::create_device_proxy(real_device, __uuidof(ID3D12Device), &proxy_raw)) || !proxy_raw) { + real_device->Release(); std::fprintf(stderr, "create_device_proxy failed\n"); return false; } + Ref proxy; + proxy.p = static_cast(proxy_raw); struct ConsoleDescriptorHeapDesc { D3D12_DESCRIPTOR_HEAP_DESC desc{}; @@ -81,31 +94,59 @@ bool check_xs_proxy_slot14(ID3D12Device* real_device) { console.desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; console.desc.NumDescriptors = 4; console.desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE; - console.address = 0x556677880000ull; - console.size = 4ull * 32ull; + alignas(64) unsigned char storage[4096]{}; + console.address = reinterpret_cast(storage); + console.size = console.desc.NumDescriptors * real_device->GetDescriptorHandleIncrementSize(console.desc.Type); + if (console.size > sizeof(storage)) return false; + D3D12_DESCRIPTOR_HEAP_DESC ordinary = console.desc; + Ref ordinary_heap; + if (FAILED(proxy->CreateDescriptorHeap(&ordinary, IID_PPV_ARGS(ordinary_heap.put())))) return false; - Ref heap; - const HRESULT hr = proxy->CreateDescriptorHeap(&console.desc, IID_PPV_ARGS(heap.put())); - if (FAILED(hr) || !heap.get()) { - std::fprintf(stderr, "proxy CreateDescriptorHeap(console) failed: 0x%08lx\n", - static_cast(hr)); - return false; - } - // The proxy's own GetCPUDescriptorHandleForHeapStart answers the console (RAX) convention; this test is a PC - // caller, so read the wrapped heap's PC method. The address proves slot 14 passed the console VA through. - ID3D12DescriptorHeap* real = rt::d3d12_xs::heap_proxy_real_heap(heap.p); - if (!real) { - std::fprintf(stderr, "heap proxy has no real heap\n"); - return false; - } - const auto cpu = real->GetCPUDescriptorHandleForHeapStart(); - if (cpu.ptr != static_cast(console.address)) { - std::fprintf(stderr, "proxy CPU heap start mismatch: got 0x%llx want 0x%llx\n", - static_cast(cpu.ptr), - static_cast(console.address)); - return false; - } - return true; + auto check_start = [&](const char* label, bool uses_console_address) { + Ref heap; + const HRESULT hr = proxy->CreateDescriptorHeap(&console.desc, IID_PPV_ARGS(heap.put())); + if (FAILED(hr) || !heap.get()) { + std::fprintf(stderr, "%s: CreateDescriptorHeap failed: 0x%08lx\n", label, static_cast(hr)); + return false; + } + // Xbox heap slot 9 returns the handle in RAX rather than through a hidden PC return pointer. + using GetCpuHandleFn = D3D12_CPU_DESCRIPTOR_HANDLE(WINAPI*)(ID3D12DescriptorHeap*); + void** const vtbl = *reinterpret_cast(heap.get()); + const auto cpu = reinterpret_cast(vtbl[9])(heap.get()); + if (!cpu.ptr || (cpu.ptr == console.address) != uses_console_address) { + std::fprintf(stderr, "%s: expected %s handle, got 0x%llx (console address 0x%llx)\n", + label, uses_console_address ? "console" : "ordinary", + static_cast(cpu.ptr), static_cast(console.address)); + return false; + } + return true; + }; + if (!expect_console) return check_start("host device", false); + if (!check_start("writable backing", true)) return false; + ++console.size; + if (!check_start("size mismatch", false)) return false; + --console.size; + + void* read_only = VirtualAlloc(nullptr, console.size, MEM_RESERVE | MEM_COMMIT, PAGE_READONLY); + if (!read_only) return false; + console.address = reinterpret_cast(read_only); + const bool ok = check_start("read-only backing", false); + VirtualFree(read_only, 0, MEM_RELEASE); + if (!ok) return false; + + // Writable memory a write watch has made read-only (the retail title places a slot-133 buffer over the memory it + // carves its heap from, and that buffer's shadow watches it) is still the title's writable memory. + void* watched = VirtualAlloc(nullptr, console.size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + DWORD old = 0; + if (!watched || !VirtualProtect(watched, console.size, PAGE_READONLY, &old)) return false; + g_watched_begin = reinterpret_cast(watched); + g_watched_end = g_watched_begin + console.size; + leonida::kernel_writes::set_opener(&open_watched); + console.address = g_watched_begin; + const bool watched_ok = check_start("watched backing", true); + leonida::kernel_writes::set_opener(nullptr); + VirtualFree(watched, 0, MEM_RELEASE); + return watched_ok; } bool check_normal_heap_unchanged(ID3D12Device* device) { @@ -150,7 +191,10 @@ int main() { if (!check_normal_heap_unchanged(device.get())) return 1; if (!check_console_addressed_heap(device.get())) return 1; - if (!check_xs_proxy_slot14(device.get())) return 1; + Ref host; + if (FAILED(D3D12CreateDevice(nullptr, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(host.put())))) return 1; + if (!check_xs_proxy_slot14(host.get(), false)) return 1; + if (!check_xs_proxy_slot14(device.get(), true)) return 1; std::fprintf(stderr, "ok\n"); return 0; } diff --git a/runtime/test/d3d12_debug_markers_test.cpp b/runtime/test/d3d12_debug_markers_test.cpp index a87fd030f7..b5d1a00344 100644 --- a/runtime/test/d3d12_debug_markers_test.cpp +++ b/runtime/test/d3d12_debug_markers_test.cpp @@ -100,7 +100,9 @@ HRESULT make_device(const vktest::Device& d, bool debug_utils, ID3D12Device** ou ID3D12Device* inner = nullptr; HRESULT hr = rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)); if (FAILED(hr)) return hr; - hr = rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), reinterpret_cast(out)); + // PC-shaped lists: this test calls the marker methods the console ABI does not have. + hr = rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), reinterpret_cast(out), + /*console_lists=*/false); if (FAILED(hr)) { inner->Release(); return hr; @@ -135,6 +137,9 @@ int run_markers(ID3D12Device* device) { const char ansi[] = "ansi pass and more"; const wchar_t spans[] = L"spans two lists"; const std::uint64_t blob[2] = {0x1234, 0x5678}; + // make_device passes console_lists=false, so first/second are the real PC-shaped lists — the console + // ABI has no SetMarker or BeginEvent, and its one marker slot (EndEvent at console 60) would land here + // on a shifted index. ExecuteCommandLists still unwraps the proxies below. first->SetMarker(0, frame, sizeof(frame)); first->SetMarker(0, nullptr, 0); first->BeginEvent(1, ansi, 9); // "ansi pass" diff --git a/runtime/test/d3d12_depth24_draw_test.cpp b/runtime/test/d3d12_depth24_draw_test.cpp index 436336e024..9ff50b059d 100644 --- a/runtime/test/d3d12_depth24_draw_test.cpp +++ b/runtime/test/d3d12_depth24_draw_test.cpp @@ -74,7 +74,7 @@ struct Pass { D3D12_COMPARISON_FUNC func = D3D12_COMPARISON_FUNC_ALWAYS; bool write = true; float clear = 1.0f; - float z = 0.5f, dz = 0.0f, shader_z = 0.0f; // s0, s1 (vs_depth.vert), s2 (ps_depth_write.frag) + float z = 0.5f, dz = 0.0f, shader_z = 0.0f; // s8, s9 (vs_depth.vert), s10 (ps_depth_write.frag) }; struct Result { @@ -263,7 +263,8 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); + reinterpret_cast(&device.p), + /*console_lists=*/false))); rt::d3d12::set_device_outer(inner, device.p); D3D12_ROOT_PARAMETER param{}; diff --git a/runtime/test/d3d12_depth_resolve_test.cpp b/runtime/test/d3d12_depth_resolve_test.cpp index fd210c3aa4..35d4259fe7 100644 --- a/runtime/test/d3d12_depth_resolve_test.cpp +++ b/runtime/test/d3d12_depth_resolve_test.cpp @@ -1,4 +1,4 @@ -// Compare depth/stencil ResolveSubresourceRegion with Windows D3D12 on the layer's own adapter and on WARP, through +// Compare depth/stencil ResolveSubresourceRegion with Windows D3D12 on the layer's own adapter and on WARP, through // clears, resolves, copies and Map on both sides: MIN and MAX of either plane, named by the depth format or the // plane's own format, and AVERAGE of the depth plane by its own format (R32_FLOAT, R24_UNORM_X8_TYPELESS). // Clears write whole pixels, so all samples of a pixel are equal and every mode returns that value: these cases @@ -88,10 +88,9 @@ struct Planes { std::vector depth, stencil; }; -// Clears a 4x target with three overlapping values and the 1x destination to values none of them have, resolves -// `c` and reads every plane of the destination back. The resolve is its own list, so a refused one (run only when -// `run_invalid`) can't take the clears and read-back with it: the layer refuses a failed list's whole batch. -bool resolve_and_read(ID3D12Device* device, const Case& c, Planes& out, bool run_invalid, +// Clear a 4x source and 1x destination, resolve c, then read back every destination plane. For a layer refusal, +// submit the setup and readback independently: ExecuteCommandLists rejects the entire list that failed Close. +bool resolve_and_read(ID3D12Device* device, const Case& c, Planes& out, bool check_refusal, const EdgeDraw* edge = nullptr) { Ref queue; Ref allocator; @@ -104,6 +103,7 @@ bool resolve_and_read(ID3D12Device* device, const Case& c, Planes& out, bool run CHECK(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, IID_PPV_ARGS(&list.p)))); CHECK(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + const auto execute = [&](ID3D12CommandList* commands) { queue->ExecuteCommandLists(1, &commands); }; D3D12_HEAP_PROPERTIES heap_properties{}; heap_properties.Type = D3D12_HEAP_TYPE_DEFAULT; @@ -197,24 +197,33 @@ bool resolve_and_read(ID3D12Device* device, const Case& c, Planes& out, bool run barriers[1].Transition.pResource = target.p; barriers[1].Transition.StateAfter = D3D12_RESOURCE_STATE_RESOLVE_DEST; list->ResourceBarrier(2, barriers); - CHECK(SUCCEEDED(list->Close())); - - CHECK(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, - IID_PPV_ARGS(&resolve_list.p)))); - CHECK(SUCCEEDED(resolve_list->QueryInterface(IID_PPV_ARGS(&list1.p)))); + if (check_refusal) { + CHECK(SUCCEEDED(list->Close())); + execute(list.p); + CHECK(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); + CHECK(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, + IID_PPV_ARGS(&list1.p)))); + } else { + CHECK(SUCCEEDED(list->QueryInterface(IID_PPV_ARGS(&list1.p)))); + } D3D12_RECT rect = source_rect; const UINT x = c.dst_x >= 0 ? UINT(c.dst_x) : c.rect ? UINT(rect.left) : 0; const UINT y = c.dst_y >= 0 ? UINT(c.dst_y) : c.rect ? UINT(rect.top) : 0; list1->ResolveSubresourceRegion(target.p, c.plane, x, y, source.p, c.plane, c.rect ? &rect : nullptr, c.format, c.mode); - out.close = resolve_list->Close(); - if (FAILED(out.close) && !run_invalid) return true; - - CHECK(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, - IID_PPV_ARGS(©_list.p)))); + Ref readback_list; + if (check_refusal) { + out.close = list1->Close(); + if (SUCCEEDED(out.close)) return true; // The caller will report the unexpected success. + execute(list1.p); + CHECK(rt::d3d12::last_execute_result(queue.p) != leonida::ReplayResult::success); + CHECK(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, + IID_PPV_ARGS(&readback_list.p)))); + } + auto* copy = check_refusal ? readback_list.p : list.p; barriers[1].Transition.StateBefore = D3D12_RESOURCE_STATE_RESOLVE_DEST; barriers[1].Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE; - copy_list->ResourceBarrier(1, &barriers[1]); + copy->ResourceBarrier(1, &barriers[1]); for (UINT i = 0; i < planes; ++i) { D3D12_TEXTURE_COPY_LOCATION src{}, dst{}; src.pResource = target.p; @@ -223,14 +232,17 @@ bool resolve_and_read(ID3D12Device* device, const Case& c, Planes& out, bool run dst.pResource = readback.p; dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; dst.PlacedFootprint = placed[i]; - copy_list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + copy->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); } - CHECK(SUCCEEDED(copy_list->Close())); - - for (ID3D12CommandList* one : {static_cast(list.p), - static_cast(resolve_list.p), - static_cast(copy_list.p)}) - queue->ExecuteCommandLists(1, &one); + const HRESULT close = copy->Close(); + if (check_refusal) { + CHECK(SUCCEEDED(close)); + } else { + out.close = close; + if (FAILED(close) || c.host_refuses) return true; + } + execute(copy); + if (check_refusal) CHECK(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); CHECK(SUCCEEDED(queue->Signal(fence.p, 1))); Event event; CHECK(event.handle); @@ -238,6 +250,7 @@ bool resolve_and_read(ID3D12Device* device, const Case& c, Planes& out, bool run // 30 s, not 5 s: under `ctest -j 6` other GPU tests share the device, and a fence can take longer // than this test's idle runtime to signal (TEST-514 flake). Sibling tests already wait 15-60 s. CHECK(WaitForSingleObject(event.handle, 30000) == WAIT_OBJECT_0); + CHECK(fence->GetCompletedValue() == 1); void* mapped = nullptr; const D3D12_RANGE range{0, SIZE_T(total)}; CHECK(SUCCEEDED(readback->Map(0, &range, &mapped)) && mapped); @@ -441,12 +454,11 @@ int main() { ++edge_skipped; continue; } - if (!resolve_and_read(ours.p, c, results[i], true, &ours_edge)) return 1; - // A mode the device lacks is refused like the cases below. An edge case has no CPU model of its - // coverage: only its Close is checked here, and its planes against the host below. + if (!resolve_and_read(ours.p, c, results[i], !can, &ours_edge)) return 1; + // Successful edge resolves have no CPU coverage model and are compared with the host below. const Planes expected = expected_planes(c, can); if (results[i].close != (can ? S_OK : E_INVALIDARG) || - (!c.edge && !same_planes(results[i], expected, false, c.plane))) { + ((!c.edge || !can) && !same_planes(results[i], expected, false, c.plane))) { std::fprintf(stderr, "%s %s rect %d: Close 0x%08lx, destination %s the clears\n", c.name, mode_name(c.mode), int(c.rect), results[i].close, same_planes(results[i], expected, false, c.plane) ? "matches" : "differs from"); @@ -492,14 +504,32 @@ int main() { std::fprintf(stderr, "no DXGI factory\n"); return 1; } + bool use_warp_for_d24_stencil = false; for (const bool warp : {false, true}) { if (hostwine::host_is_wine()) break; // checked against the clears above Ref adapter; Ref host; std::string adapter_name; - if (!hostadapter::reference(factory.p, vk, warp, &adapter.p, adapter_name)) continue; - if (FAILED(D3D12CreateDevice(adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) continue; + if (!hostadapter::reference(factory.p, vk, warp, &adapter.p, adapter_name) || + FAILED(D3D12CreateDevice(adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) { + if (warp && use_warp_for_d24_stencil) { + std::fprintf(stderr, "WARP is required for the D24S8 stencil reference on this driver\n"); + return 1; + } + continue; + } const char* name = adapter_name.c_str(); + // RTX 4070 Ti (630.20): a D24S8 stencil MIN resolve with either format closes successfully but + // hangs the device on submission. Use WARP for this plane, and keep the hardware's other comparisons. + DXGI_ADAPTER_DESC adapter_desc{}; + LARGE_INTEGER driver{}; + if (!warp && adapter.p && SUCCEEDED(adapter->GetDesc(&adapter_desc)) && + adapter_desc.VendorId == 0x10de && adapter_desc.DeviceId == 0x2782 && + SUCCEEDED(adapter->CheckInterfaceSupport(__uuidof(IDXGIDevice), &driver)) && + driver.QuadPart == 0x0020'0000'0010'0bccLL) { // 32.0.16.3020 + use_warp_for_d24_stencil = true; + std::printf("D24S8 stencil reference on %s (630.20): using WARP\n", name); + } unsigned same = 0, compared = 0, refused_alike = 0, quirks = 0; std::vector quirks_seen; // cases without the edge where this host differs from the clears const auto quirky = [&](const Case& e) { @@ -509,8 +539,12 @@ int main() { }; for (std::size_t i = 0; i < cases.size(); ++i) { const Case& c = cases[i]; + const bool warp_stencil = use_warp_for_d24_stencil && c.plane == 1 && + (c.format == d24 || c.format == g8); // See the top of the file; D32S8 by its own format is kept off WARP for the same reason. - if (results[i].depth.empty() || (warp && (c.format == d32 || c.format == d32s8))) continue; + if (results[i].depth.empty() || (warp && (c.format == d32 || c.format == d32s8)) || + (!warp && warp_stencil)) + continue; Planes expected; if (!resolve_and_read(host.p, c, expected, false, &host_edge)) return 1; ++compared; @@ -518,9 +552,8 @@ int main() { // host quirk, not a layer bug: report, don't fail. Which D24S8 resolves is the driver's: with stencil // MIN/MAX on both, an RTX 3070 (NVIDIA 610.74) adds "stencil as X24_G8" and "depth as R24_X8" AVERAGE, // a Ryzen 7 9700X iGPU (AMD 32.0.21042.62) depth MIN/MAX; whole subresources and rectangles alike. - // Edge cases have no clear model: on WARP, or where the host had a quirk on the same case without the - // edge, a difference from the layer is only reported. - if (c.edge && (warp || quirky(c))) { + // Only report edge differences if a clear comparison found a quirk, or if WARP is a second reference. + if (c.edge && ((warp && !warp_stencil) || quirky(c))) { if (FAILED(expected.close) || !same_planes(expected, results[i], true, c.plane)) std::printf("edge %s %s rect %d: %s differs from the layer (information)\n", c.name, mode_name(c.mode), int(c.rect), name); diff --git a/runtime/test/d3d12_descriptor_test.cpp b/runtime/test/d3d12_descriptor_test.cpp index 9d4cf0fbae..2172c6311b 100644 --- a/runtime/test/d3d12_descriptor_test.cpp +++ b/runtime/test/d3d12_descriptor_test.cpp @@ -333,6 +333,7 @@ int main() { info.device = d.device; info.queue = d.queue; info.queue_family = d.family; + info.a8_render_target = d.a8_render_target; info.texture_compression_bc = d.bc; info.bindless = d.bindless; info.bindless_partially_bound = d.partially_bound; @@ -344,7 +345,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); + reinterpret_cast(&device.p), /*console_lists=*/false))); rt::d3d12::set_device_outer(inner, device.p); // the proxy now owns `inner` D3D12_FEATURE_DATA_D3D12_OPTIONS8 options8{}; @@ -491,8 +492,10 @@ int main() { EXPECT((support.Support1 & D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE) != 0); EXPECT((support.Support1 & D3D12_FORMAT_SUPPORT1_SHADER_GATHER) != 0); EXPECT((support.Support1 & D3D12_FORMAT_SUPPORT1_MIP) != 0); - EXPECT(!(support.Support1 & (D3D12_FORMAT_SUPPORT1_RENDER_TARGET | D3D12_FORMAT_SUPPORT1_BLENDABLE | - D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW)) && !support.Support2); + // Render targets where the device has VK_FORMAT_A8_UNORM_KHR (they are then blendable too); never UAVs. + const bool a8_render_target = (support.Support1 & D3D12_FORMAT_SUPPORT1_RENDER_TARGET) != 0; + EXPECT(a8_render_target == ((support.Support1 & D3D12_FORMAT_SUPPORT1_BLENDABLE) != 0)); + EXPECT(!(support.Support1 & D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW) && !support.Support2); for (UINT count : {1u, 4u}) { D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS quality_levels{DXGI_FORMAT_A8_UNORM, count}; EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS, &quality_levels, @@ -504,10 +507,12 @@ int main() { auto desc = texture_desc; desc.Format = DXGI_FORMAT_A8_UNORM; desc.Flags = flag; - EXPECT(FAILED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc, - D3D12_RESOURCE_STATE_COMMON, nullptr, - __uuidof(ID3D12Resource), nullptr))); - EXPECT(device->GetResourceAllocationInfo(0, 1, &desc).SizeInBytes == UINT64_MAX); + const bool allowed = flag == D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET && a8_render_target; + // With no output, a valid description is S_FALSE. + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, + __uuidof(ID3D12Resource), nullptr)) == allowed); + EXPECT((device->GetResourceAllocationInfo(0, 1, &desc).SizeInBytes == UINT64_MAX) == !allowed); } Ref byte_textures[2]; D3D12_PLACED_SUBRESOURCE_FOOTPRINT byte_placed[2]{}, a8_mip_placed{}; @@ -526,6 +531,17 @@ int main() { } EXPECT(byte_placed[0].Offset == byte_placed[1].Offset && byte_placed[0].Footprint.RowPitch == byte_placed[1].Footprint.RowPitch); + // An A8 render target (VK_FORMAT_A8_UNORM_KHR where the device has it) gets the same bytes, and its SRVs must + // read them as the R8-backed A8 texture's do. Without render-target support, slots 5 and 6 view that one. + Ref a8_target; + if (a8_render_target) { + auto desc = texture_desc; + desc.Format = DXGI_FORMAT_A8_UNORM; + desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&a8_target.p)))); + } for (UINT y = 0; y < size; ++y) { auto* row = static_cast(mapped) + byte_placed[0].Offset + y * byte_placed[0].Footprint.RowPitch; for (UINT x = 0; x < size; ++x) row[x] = std::uint8_t(1 + 3 * (y * size + x)); @@ -1194,7 +1210,7 @@ int main() { } } - constexpr UINT a8_mip_slot = 4, byte_view_count = a8_mip_slot + 1; + constexpr UINT a8_mip_slot = 4, a8_target_slot = 5, byte_view_count = a8_target_slot + 2; D3D12_DESCRIPTOR_HEAP_DESC byte_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, byte_view_count, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; Ref byte_heap; @@ -1224,6 +1240,18 @@ int main() { byte_view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; byte_view.Texture2D.MostDetailedMip = 1; device->CreateShaderResourceView(byte_textures[0].p, &byte_view, byte_slot(a8_mip_slot)); + { + // The A8 render target: a default view (null description) and the remapped one of slot 1. + ID3D12Resource* const a8_source = a8_target.p ? a8_target.p : byte_textures[0].p; + device->CreateShaderResourceView(a8_source, nullptr, byte_slot(a8_target_slot)); + D3D12_SHADER_RESOURCE_VIEW_DESC remapped = byte_view; + remapped.Texture2D.MostDetailedMip = 0; + remapped.Shader4ComponentMapping = D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING( + D3D12_SHADER_COMPONENT_MAPPING_FROM_MEMORY_COMPONENT_3, + D3D12_SHADER_COMPONENT_MAPPING_FROM_MEMORY_COMPONENT_0, D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_1, + D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_0); + device->CreateShaderResourceView(a8_source, &remapped, byte_slot(a8_target_slot + 1)); + } // D3D-75: plane 1 of a depth-stencil texture is its stencil. The T# is 8_UINT at the texture's own address, // with the eight bits read as G and R, B, A as 0, 0, 1 (D3D12's X24_TYPELESS_G8_UINT / X32_..._G8X24_UINT). @@ -1487,6 +1515,18 @@ int main() { D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); list->ResourceBarrier(1, &ready); } + if (a8_target.p) { + D3D12_TEXTURE_COPY_LOCATION to{}, from{}; + to.pResource = a8_target.p; + to.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + from.pResource = upload.p; + from.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + from.PlacedFootprint = byte_placed[0]; + list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); + const auto ready = transition(a8_target.p, D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + list->ResourceBarrier(1, &ready); + } EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); // Upload, then the texture into a shader-resource state. Executing the list also brings set 0 up to date. @@ -1976,12 +2016,17 @@ int main() { {value, 0, 0, 255}, {255, value, 255, 0}}; for (UINT k = 0; k < 4; ++k) EXPECT(std::memcmp(byte_results.data() + k * bytes + 4 * i, expected[k], 4) == 0); + // The A8 render target's default and remapped views read as the A8 texture's (slots 0 and 1). + EXPECT(std::memcmp(byte_results.data() + a8_target_slot * bytes + 4 * i, expected[0], 4) == 0); + EXPECT(std::memcmp(byte_results.data() + (a8_target_slot + 1) * bytes + 4 * i, expected[1], 4) == 0); const UINT mip_texel = (i / size / 2) * mip_size + (i % size) / 2; const std::uint8_t mip_expected[] = {0, 0, 0, std::uint8_t(208 + mip_texel)}; EXPECT(std::memcmp(byte_results.data() + a8_mip_slot * bytes + 4 * i, mip_expected, 4) == 0); } std::printf("A8 mip 1: %u samples matched across %u texels\n", texels, mip_size * mip_size); std::printf("A8 and R8 default and remapped views: %u texels matched each\n", texels); + std::printf("A8 render target (%s) default and remapped views: %u texels matched each\n", + a8_target.p ? "VK_FORMAT_A8_UNORM_KHR" : "not supported: the R8-backed texture", texels); // A gather across the center of each 2x2 block uses the A8 view's R-to-A swizzle. // The remapped view of the same image forces alpha to zero. @@ -2887,6 +2932,7 @@ int main() { typeless_heap.reset(); uint_texture.reset(); for (auto& resource : byte_textures) resource.reset(); + a8_target.reset(); byte_heap.reset(); ms_texture.reset(); ms_array.reset(); diff --git a/runtime/test/d3d12_draw_test.cpp b/runtime/test/d3d12_draw_test.cpp index 36e2f6e37a..ea6b3a76b1 100644 --- a/runtime/test/d3d12_draw_test.cpp +++ b/runtime/test/d3d12_draw_test.cpp @@ -10,6 +10,8 @@ // checks the viewport flip (D3D clip space is y-up) and the front-face winding; // - full-screen blends that read destination alpha into B8G8R8X8 and B8G8R8A8 targets cleared with alpha 0.25: // B8G8R8X8 has no alpha, so destination alpha reads 1 there, as on WARP and AMD's D3D12 driver; +// - an A8_UNORM render target where the device has VK_FORMAT_A8_UNORM_KHR: a draw and two alpha blends, also on +// one created with A8_UNORM as its castable list (an R8_UNORM list is refused); // - draws through RTVs in a format the texture's castable list names, in the other channel order (RGBA8 and BGRA8) // or across B8G8R8X8 and B8G8R8A8: the bytes land in the view's order and encoding. // The shaders are GLSL written to the translator's contract (test/glsl/vs_draw.vert, ps_draw.frag). No game data. @@ -21,12 +23,14 @@ #include "../shims/d3d12_com.h" #include "../shims/d3d12_xs_device.h" #include "../src/shader_library.h" +#include "../src/title_va_alias.h" #include #include #include #include #include +#include #if !defined(LEONIDA_TEST_VS_SPV) || !defined(LEONIDA_TEST_PS_SPV) || !defined(LEONIDA_TEST_VS_INT_SPV) || \ !defined(LEONIDA_TEST_PS_UINT_SPV) @@ -55,7 +59,10 @@ static_assert(offsetof(Vertex, wrong_color) == 16); } // namespace -int main() { +int main(int argc, char** argv) { + const bool title_index = argc == 2 && std::strcmp(argv[1], "--title-index-window") == 0; + const bool title_vertex = argc == 2 && std::strcmp(argv[1], "--title-vertex-window") == 0; + const bool title_window = title_index || title_vertex; vktest::Device d; const auto device_status = d.initialize(); if (device_status == vktest::DeviceStatus::unavailable) { @@ -111,6 +118,19 @@ int main() { std::vector step2_pixels(size * 256), step1_pixels(size * 256); const bool logic_op = d.enabled.logicOp == VK_TRUE; const bool has_divisor = d.vertex_attribute_divisor; + constexpr UINT title_bytes = 2 * 65536; + auto& aliases = leonida::title_va_aliases(); + const auto release_title = [&](std::uint8_t* pages) { + aliases.remove_title_memory(reinterpret_cast(pages)); + VirtualFree(pages, 0, MEM_RELEASE); + }; + std::unique_ptr title_pages(title_window ? static_cast( + VirtualAlloc(nullptr, title_bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)) : nullptr, release_title); + const auto title_va = reinterpret_cast(title_pages.get()); + if (title_window) { + EXPECT(title_pages); + aliases.add_title_memory(title_va, title_bytes); + } { rt::d3d12::VulkanDeviceInfo info{}; info.get_instance_proc = d.instance_proc; @@ -119,6 +139,7 @@ int main() { info.device = d.device; info.queue = d.queue; info.queue_family = d.family; + info.a8_render_target = d.a8_render_target; info.buffer_device_address = true; info.subgroup = d.subgroup; info.shader_dir = library.string(); @@ -129,7 +150,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); + reinterpret_cast(&device.p), /*console_lists=*/false))); rt::d3d12::set_device_outer(inner, device.p); // Root signature: [0] two constants (s0, s1: offset), [1] a root CBV (s2:s3: tint). @@ -372,16 +393,35 @@ int main() { transition(vertex_buffer.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER), transition(target.p, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_RENDER_TARGET)}; list->ResourceBarrier(2, barriers); - const FLOAT blue[4] = {0, 0, 1, 1}; + const FLOAT blue[4] = {0, 0, 1, title_window ? 0.f : 1.f}; list->ClearRenderTargetView(rtv, blue, 0, nullptr); // State for the draws; the pipeline came with CreateCommandList. list->SetGraphicsRootSignature(root.p); list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); const D3D12_VERTEX_BUFFER_VIEW vbv{vertex_buffer->GetGPUVirtualAddress(), sizeof(vertices), sizeof(Vertex)}; - list->IASetVertexBuffers(0, 1, &vbv); + constexpr UINT vertex_after_window = (65536 + sizeof(Vertex) - 1) / sizeof(Vertex); + if (title_vertex) { + std::memcpy(title_pages.get() + vertex_after_window * sizeof(Vertex), vertices, sizeof(vertices)); + const D3D12_VERTEX_BUFFER_VIEW small_view{title_va, sizeof(vertices), sizeof(Vertex)}; + const D3D12_VERTEX_BUFFER_VIEW large_view{title_va, title_bytes, sizeof(Vertex)}; + list->IASetVertexBuffers(0, 1, &small_view); + list->IASetVertexBuffers(0, 1, &large_view); + } else { + list->IASetVertexBuffers(0, 1, &vbv); + } const D3D12_INDEX_BUFFER_VIEW ibv{upload_va + 256, sizeof(indices), DXGI_FORMAT_R16_UINT}; - list->IASetIndexBuffer(&ibv); + if (title_index) { + // First binding creates a 64 KiB window. A later view at the same VA + // needs indices in the second 64 KiB. + const D3D12_INDEX_BUFFER_VIEW small_title_ib{title_va, sizeof(indices), DXGI_FORMAT_R16_UINT}; + const D3D12_INDEX_BUFFER_VIEW large_title_ib{title_va, title_bytes, DXGI_FORMAT_R16_UINT}; + std::memcpy(title_pages.get() + 65536, indices, sizeof(indices)); + list->IASetIndexBuffer(&small_title_ib); + list->IASetIndexBuffer(&large_title_ib); + } else { + list->IASetIndexBuffer(&ibv); + } const D3D12_VIEWPORT viewport{0, 0, float(size), float(size), 0, 1}; const D3D12_RECT scissor{0, 0, LONG(size), LONG(size)}; list->RSSetViewports(1, &viewport); @@ -394,7 +434,14 @@ int main() { list->SetPipelineState(mrt.p); list->SetGraphicsRoot32BitConstants(0, 2, origin, 0); list->SetGraphicsRootConstantBufferView(1, upload_va + 512); - list->DrawIndexedInstanced(6, 1, 0, 0, 0); + list->DrawIndexedInstanced(6, 1, title_index ? 65536 / sizeof(indices[0]) : 0, + title_vertex ? vertex_after_window : 0, 0); + if (title_window) { + // Only draw 1 contributes to the coverage check. + const D3D12_RECT empty{}; + list->RSSetScissorRects(1, &empty); + list->IASetIndexBuffer(&ibv); + } // Draw 2: offset (1, -1), green tint -> bottom-right quadrant green. The root signature is set again after // the arguments; it is the same one, so they stay bound (else the quad would land top-left, untinted). list->SetPipelineState(pso.p); @@ -443,6 +490,25 @@ int main() { void* mapped = nullptr; EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); std::memcpy(pixels.data(), mapped, pixels.size()); + if (title_window) { + unsigned painted = 0, wrong = 0; + for (unsigned y = 0; y < size; ++y) { + for (unsigned x = 0; x < size; ++x) { + const bool inside = x < size / 2 && y < size / 2; + const auto alpha = pixels[y * 256 + x * 4 + 3]; + painted += alpha == 255; + wrong += alpha != (inside ? 255 : 0); + } + } + std::printf("title %s window: %u/%u pixels painted; %u differences from expected coverage\n", + title_vertex ? "vertex" : "index", painted, size * size / 4, wrong); + EXPECT(wrong == 0); + EXPECT(aliases.shader_va(title_va + 65536) == aliases.shader_va(title_va) + 65536); + EXPECT(aliases.shader_va(title_va + 65536) != title_va + 65536); + readback->Unmap(0, nullptr); + EXPECT(d.validation_errors() == 0); + return 0; + } // Second pass on the same target, cleared blue again: the full-screen triangle (yellow, red tint: red) // through a viewport on the bottom-right quadrant, with no vertex buffer in its pipeline. @@ -856,6 +922,116 @@ int main() { unsigned(std::size(x8_cases))); } + // An A8_UNORM render target (VK_FORMAT_A8_UNORM_KHR, VulkanDeviceInfo::a8_render_target): the full-screen draw + // writes alpha 1, and the alpha blend reads the cleared alpha 0.25 (byte 64) as the destination. + { + D3D12_FEATURE_DATA_FORMAT_SUPPORT a8_support{DXGI_FORMAT_A8_UNORM}; + EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &a8_support, + sizeof(a8_support)))); + if (!(a8_support.Support1 & D3D12_FORMAT_SUPPORT1_RENDER_TARGET)) { + std::printf("A8_UNORM render target: not supported on this device (no VK_FORMAT_A8_UNORM_KHR)\n"); + } else { + struct A8Case { + const char* name; + BOOL blend; + D3D12_BLEND src_alpha, dst_alpha; + int want; + }; + constexpr A8Case a8_cases[] = { + {"no blend", FALSE, D3D12_BLEND_ONE, D3D12_BLEND_ZERO, 255}, + {"alpha ZERO, ONE", TRUE, D3D12_BLEND_ZERO, D3D12_BLEND_ONE, 64}, + {"alpha INV_DEST_ALPHA, ZERO", TRUE, D3D12_BLEND_INV_DEST_ALPHA, D3D12_BLEND_ZERO, 191}, + }; + const D3D12_DESCRIPTOR_HEAP_DESC a8_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, + D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + Ref a8_heap; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&a8_heap_desc, IID_PPV_ARGS(&a8_heap.p)))); + const D3D12_CPU_DESCRIPTOR_HANDLE a8_rtv{ + SIZE_T(reinterpret_cast(slot(a8_heap.p, 9))(a8_heap.p))}; + D3D12_RESOURCE_DESC a8_desc = rt_desc; + a8_desc.Width = a8_desc.Height = 4; + a8_desc.Format = DXGI_FORMAT_A8_UNORM; + Ref a8_target; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &a8_desc, + D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr, + IID_PPV_ARGS(&a8_target.p)))); + // The same target through CreateCommittedResource3 with its own format as the castable list. An R8_UNORM + // list is refused: no other format can be a view format of a VK_FORMAT_A8_UNORM_KHR image. + Ref a8_inner10; + EXPECT(SUCCEEDED(inner->QueryInterface(IID_PPV_ARGS(&a8_inner10.p)))); + D3D12_RESOURCE_DESC1 a8_desc1{}; + a8_desc1.Dimension = a8_desc.Dimension; + a8_desc1.Width = a8_desc.Width; + a8_desc1.Height = a8_desc.Height; + a8_desc1.DepthOrArraySize = a8_desc.DepthOrArraySize; + a8_desc1.MipLevels = a8_desc.MipLevels; + a8_desc1.Format = a8_desc.Format; + a8_desc1.SampleDesc = a8_desc.SampleDesc; + a8_desc1.Layout = a8_desc.Layout; + a8_desc1.Flags = a8_desc.Flags; + const DXGI_FORMAT a8_own = DXGI_FORMAT_A8_UNORM, a8_r8 = DXGI_FORMAT_R8_UNORM; + Ref a8_cast_target, a8_r8_target; + EXPECT(SUCCEEDED(a8_inner10->CreateCommittedResource3(&default_heap, D3D12_HEAP_FLAG_NONE, &a8_desc1, + D3D12_BARRIER_LAYOUT_RENDER_TARGET, nullptr, nullptr, 1, &a8_own, IID_PPV_ARGS(&a8_cast_target.p)))); + EXPECT(a8_inner10->CreateCommittedResource3(&default_heap, D3D12_HEAP_FLAG_NONE, &a8_desc1, + D3D12_BARRIER_LAYOUT_RENDER_TARGET, nullptr, nullptr, 1, &a8_r8, IID_PPV_ARGS(&a8_r8_target.p)) == + E_INVALIDARG); + EXPECT(!a8_r8_target.p); + const FLOAT a8_clear[4] = {0.9f, 0.8f, 0.7f, 0.25f}; // only alpha lands + const D3D12_VIEWPORT a8_viewport{0, 0, 4, 4, 0, 1}; + const D3D12_RECT a8_scissor{0, 0, 4, 4}; + UINT64 a8_fence = 50; // after the B8G8R8X8 block's 41..50; 51..56, before the step-rate block's 61 + for (ID3D12Resource* const a8_resource : {a8_target.p, a8_cast_target.p}) + for (const A8Case& c : a8_cases) { + device->CreateRenderTargetView(a8_resource, nullptr, a8_rtv); + D3D12_GRAPHICS_PIPELINE_STATE_DESC a8_pso_desc = fullscreen_desc; + a8_pso_desc.RTVFormats[0] = DXGI_FORMAT_A8_UNORM; + a8_pso_desc.BlendState.RenderTarget[0] = { + c.blend, FALSE, D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD, c.src_alpha, + c.dst_alpha, D3D12_BLEND_OP_ADD, D3D12_LOGIC_OP_NOOP, D3D12_COLOR_WRITE_ENABLE_ALL}; + Ref a8_pso; + EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&a8_pso_desc, IID_PPV_ARGS(&a8_pso.p)))); + EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, a8_pso.p))); + list->ClearRenderTargetView(a8_rtv, a8_clear, 0, nullptr); + list->SetGraphicsRootSignature(root.p); + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + list->RSSetViewports(1, &a8_viewport); + list->RSSetScissorRects(1, &a8_scissor); + list->OMSetRenderTargets(1, &a8_rtv, FALSE, nullptr); + list->SetGraphicsRootConstantBufferView(1, upload_va + 2048); + list->DrawInstanced(3, 1, 0, 0); + const auto a8_to_copy = transition(a8_resource, D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &a8_to_copy); + D3D12_TEXTURE_COPY_LOCATION a8_dst{readback.p, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}}; + a8_dst.PlacedFootprint = {0, {DXGI_FORMAT_A8_UNORM, 4, 4, 1, 256}}; + D3D12_TEXTURE_COPY_LOCATION a8_src{a8_resource, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}}; + list->CopyTextureRegion(&a8_dst, 0, 0, 0, &a8_src, nullptr); + const auto a8_to_target = transition(a8_resource, D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_RENDER_TARGET); + list->ResourceBarrier(1, &a8_to_target); + EXPECT(list->Close() == S_OK); + queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); + ++a8_fence; + EXPECT(SUCCEEDED(queue->Signal(fence.p, a8_fence)) && + SUCCEEDED(fence->SetEventOnCompletion(a8_fence, nullptr))); + const auto* got = static_cast(mapped); + for (UINT y = 0; y < 4; ++y) + for (UINT x = 0; x < 4; ++x) { + const int byte = got[y * 256 + x]; + if (std::abs(byte - c.want) <= 1) continue; + std::fprintf(stderr, "A8 target%s, %s: texel (%u,%u) got %d, want %d\n", + a8_resource == a8_cast_target.p ? " (castable list)" : "", c.name, x, y, + byte, c.want); + return 1; + } + } + std::printf("A8_UNORM render target: clear, draw and %u alpha blends matched, also with an A8_UNORM " + "castable list (R8_UNORM refused)\n", unsigned(std::size(a8_cases))); + } + } + // Instance step rate > 1 (VK_KHR/EXT_vertex_attribute_divisor): two per-instance colours in slot 1: // entry 0 = red, entry 1 = magenta (both preserved by the {1,0,1} tint). With step rate 2: // - Draw 1 (top-left, 2 instances from 0): instances 0 and 1 both read entry 0/2 = 0 (red). diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp index fd827f9a1a..3d6051b0c7 100644 --- a/runtime/test/d3d12_existing_heap_test.cpp +++ b/runtime/test/d3d12_existing_heap_test.cpp @@ -6,13 +6,25 @@ // committed range; without it, the device reports EXISTING_HEAPS unsupported and answers an accepted range E_NOTIMPL. // No shaders or game data. // https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device3-openexistingheapfromaddress +#include "../shims/title_gpu_placements.h" +#include "../shims/xg_xs_layout.h" #include "vk_test_device.h" #include "host_adapter.h" #include "host_wine.h" #include "../shims/d3d12_com.h" +#include "../src/title_page_watch.h" +#include "../src/gfx10_descriptors.h" +#include "../src/deferred_image_binding.h" #include +#include +#include +#include +#include #include +#include +#include #include +#include #include #define EXPECT(condition) do { \ @@ -27,6 +39,38 @@ } \ } while (0) +// The process heap as check_heap_lock_faults needs it: an allocation that waits while a thread holds the heap's lock. +// The NT heap's low-fragmentation front end serves most small sizes without that lock, so a real deadlock waits for an +// allocation its back end serves (measured natively: 8, 1000 and 4000-byte blocks wait while another thread holds the +// process heap's lock, 48 and 200-byte ones don't), which a short test can't count on. Here, while the gate is on, +// every operator new and delete of the program takes g_heap_gate shared, and the test's "title" threads that hold the +// heap's lock hold the gate exclusively: any allocation the layer makes while it holds a lock the write-fault handler +// waits for then deadlocks at once. +namespace { +SRWLOCK g_heap_gate = SRWLOCK_INIT; +std::atomic g_heap_gate_on{false}; +struct HeapGate { + const bool on = g_heap_gate_on.load(std::memory_order_acquire); + HeapGate() { + if (on) AcquireSRWLockShared(&g_heap_gate); + } + ~HeapGate() { + if (on) ReleaseSRWLockShared(&g_heap_gate); + } +}; +} // namespace + +void* operator new(std::size_t bytes) { + HeapGate gate; + if (void* p = std::malloc(bytes ? bytes : 1)) return p; + throw std::bad_alloc(); +} +void operator delete(void* p) noexcept { + HeapGate gate; + std::free(p); +} +void operator delete(void* p, std::size_t) noexcept { operator delete(p); } + namespace { template struct Ref { @@ -172,12 +216,13 @@ int check_import(ID3D12Device* device, bool supported) { // Its GPU VA is the address itself, and what the CPU writes there is what a GPU copy reads, with no upload: the // pattern is written after the buffer exists and read back through a READBACK buffer. Checked on a VirtualAlloc range // and on a view of a pagefile-backed section, the form xmem's physical pages are mapped in. A texture gets a committed -// texture whose GPU VA is the same title address (its pixels do not alias the pages yet); an address off the import -// alignment E_INVALIDARG. +// texture whose GPU VA is the same title address (its pixels do not alias the pages yet); an address off the buffer +// alignment gets the shadow fallback at the same VA. // `may_refuse`: the driver is allowed to refuse importing these pages, and the layer then answers with its fallback. // RADV imports host memory through amdgpu userptr, which takes anonymous memory only, so it refuses a view of a // pagefile-backed section with EPERM (measured on an RX 9060 XT under Wine, found in review), while NVIDIA and -// AMD's Windows driver import it. The fallback is checked to exist; the readback below needs the import. +// AMD's Windows driver import it. The fallback is checked to exist; the readback below needs the import. Since the shadow fallback +// keeps the title's VA, a refused import still reads back through the shadow. int check_title_placed(ID3D12Device* device, const char* kind, void* pages, UINT64 size, bool may_refuse = false) { const char* who = "vulkan slot-133 buffer"; D3D12_RESOURCE_DESC desc{}; @@ -251,21 +296,197 @@ int check_title_placed(ID3D12Device* device, const char* kind, void* pages, UINT EXPECT(FAILED(rt::d3d12::create_buffer_at_host_address(device, pages, too_many_mips, 0x6u, IID_PPV_ARGS(&refused_texture.p))) && refused_texture.p == nullptr); - // An address off the buffer alignment can't be bound inside the import: the ordinary-buffer fallback answers. + // An address off the buffer alignment can't be bound inside the import: a shadow buffer answers, at the same VA + // (a driver whose buffer alignment is 1 imports it; the VA is the address either way). Ref fallback; + desc.Width = size - 1; EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, bytes + 1, desc, 0xFFFFFFFFu, IID_PPV_ARGS(&fallback.p)), S_OK); - EXPECT(fallback->GetGPUVirtualAddress() != reinterpret_cast(bytes + 1)); + EXPECT(fallback->GetGPUVirtualAddress() == reinterpret_cast(bytes + 1)); std::printf("%s: %s, %llu bytes: GPU VA is the address, a GPU copy reads the CPU's writes\n", who, kind, static_cast(size)); return 0; } +std::uint8_t pattern_byte(UINT64 i, unsigned seed) { + return static_cast(i * 131u + (i >> 8) * 7u + seed); +} + +// Distinct, simultaneously live GPU resources may occupy the same console placement. +int check_placed_texture_views(ID3D12Device* device, void* pages) { + const char* who = "placed texture views"; + D3D12_RESOURCE_DESC array{}; + array.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + array.Width = array.Height = 8; + array.DepthOrArraySize = 6; + array.MipLevels = 1; + array.SampleDesc.Count = 1; + array.Format = DXGI_FORMAT_R32_UINT; + array.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + // A title-authored T# addresses the placement, even when newer resources share those pages. + auto layers = array; + layers.Width = layers.Height = 512; + layers.Format = DXGI_FORMAT_R16_UNORM; + auto face = layers; + face.DepthOrArraySize = 1; + rt::d3d12::TitleGpuPlacements placements; + placements.add(0x10000, &layers); + placements.add(0x10000, &face); + leonida::gfx10::Image raw{}; + raw.width = raw.height = 512; + raw.type = leonida::gfx10::ImageType::image_2d_array; + raw.mip_count = 1; + raw.layer_count = 6; + const auto fits = [&](const auto& d) { return placements.matches(raw, d); }; + EXPECT(placements.find(0x20000, 0x10000, fits) == &layers); + placements.remove(0x10000, &layers); + EXPECT(!placements.find(0x10000, 0, fits)); + Ref older, newer; + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, array, 0, IID_PPV_ARGS(&older.p)), S_OK); + D3D12_RESOURCE_DESC single = array; + single.DepthOrArraySize = 1; + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, single, 0, IID_PPV_ARGS(&newer.p)), S_OK); + D3D12_UNORDERED_ACCESS_VIEW_DESC uav{}; + uav.Format = array.Format; + uav.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; + uav.Texture2DArray.FirstArraySlice = 5; + uav.Texture2DArray.ArraySize = 1; + std::array resource{}; + std::array view{}; + leonida::gfx10::ImageWords placed{}, expected{}; + std::memcpy(resource.data(), &array, sizeof(array)); + std::memcpy(view.data(), &uav, sizeof(uav)); + const auto va = reinterpret_cast(pages); + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = array.Format; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Texture2DArray.MipLevels = 1; + srv.Texture2DArray.ArraySize = 6; + std::array srv_words{}; + std::memcpy(srv_words.data(), &srv, sizeof(srv)); + const D3D12_CPU_DESCRIPTOR_HANDLE slot{reinterpret_cast(placed.data())}; + EXPECT(!rt::d3d12::write_placed_texture_view(device, false, resource.data(), srv_words.data(), 0, slot) && + placed == leonida::gfx10::ImageWords{}); + EXPECT(rt::d3d12::write_placed_texture_view(device, false, resource.data(), srv_words.data(), va, slot)); + leonida::gfx10::Image restored{}; + EXPECT(leonida::gfx10::decode(placed, restored) && restored.layer_count == 6); + EXPECT(rt::d3d12::write_placed_texture_view(device, true, resource.data(), view.data(), va, + {reinterpret_cast(placed.data())})); + device->CreateUnorderedAccessView(older.p, nullptr, &uav, {reinterpret_cast(expected.data())}); + leonida::gfx10::Image decoded{}; + if (rt::d3d12::bindless_set_layout(device)) { + std::uint32_t key[8]; + std::memcpy(key, placed.data(), sizeof(key)); + EXPECT(rt::d3d12::bindless_hash_lookup(device, key) != 0); + std::puts("placed texture UAV registered in the GPU descriptor table"); + } + EXPECT(placed == expected && leonida::gfx10::decode(placed, decoded) && decoded.first_layer == 5 && + decoded.layer_count == 1 && decoded.mip_count == 1); + uav.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; + uav.Texture2D = {}; + device->CreateUnorderedAccessView(newer.p, nullptr, &uav, {reinterpret_cast(expected.data())}); + leonida::gfx10::Image other{}; + EXPECT(leonida::gfx10::decode(expected, other) && other.address != decoded.address); + EXPECT(!rt::d3d12::write_placed_texture_view(device, true, resource.data(), view.data(), 0, + {reinterpret_cast(placed.data())})); + EXPECT(placed == leonida::gfx10::ImageWords{}); + auto volume = single; + volume.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D; + volume.DepthOrArraySize = 8; + volume.MipLevels = 2; + Ref volume_target; + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, volume, 0, IID_PPV_ARGS(&volume_target.p)), S_OK); + std::memcpy(resource.data(), &volume, sizeof(volume)); + uav.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D; + uav.Texture3D = {1, 0, 4}; + std::memcpy(view.data(), &uav, sizeof(uav)); + EXPECT(rt::d3d12::write_placed_texture_view(device, true, resource.data(), view.data(), va, + {reinterpret_cast(placed.data())})); + EXPECT(leonida::gfx10::decode(placed, decoded) && decoded.type == leonida::gfx10::ImageType::image_3d && + decoded.first_mip == 1 && decoded.mip_count == 1); + uav.Texture3D.WSize = 2; + std::memcpy(view.data(), &uav, sizeof(uav)); + EXPECT(!rt::d3d12::write_placed_texture_view(device, true, resource.data(), view.data(), va, + {reinterpret_cast(placed.data())}) && + placed == leonida::gfx10::ImageWords{}); + return 0; +} + +// The shadow fallback of slot 133: pages the driver does not import (write-combined, uncached, not all committed) +// still give a buffer whose GPU VA is the address. It is a copy of the pages, made again before every submission: +// a pattern written to the first `committed` bytes after the buffer exists is what a GPU copy in the next +// ExecuteCommandLists reads, and so is a second pattern in the submission after. Bytes past `committed` are not +// committed: they are never read, and the GPU sees zeros there. The same holds where the range was imported after +// all (a Wine that drops the cache modifier), so the caller need not know which path answered. +int check_title_placed_shadow(ID3D12Device* device, const char* kind, void* pages, UINT64 committed, UINT64 size) { + const char* who = "vulkan slot-133 shadow"; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = size; + desc.Height = desc.DepthOrArraySize = desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + Ref buffer; + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, desc, 0xFFFFFFFFu, IID_PPV_ARGS(&buffer.p)), S_OK); + EXPECT(buffer->GetGPUVirtualAddress() == reinterpret_cast(pages)); + D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; + Ref readback; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback.p)))); + D3D12_COMMAND_QUEUE_DESC queue_desc{D3D12_COMMAND_LIST_TYPE_DIRECT}; + Ref queue; + Ref allocator; + Ref list; + Ref fence; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, + IID_PPV_ARGS(&list.p)))); + EXPECT(SUCCEEDED(list->Close())); + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr); + EXPECT(done != nullptr); + auto* bytes = static_cast(pages); + UINT64 fence_value = 0; + for (const unsigned seed : {7u, 93u}) { + // Written after the buffer exists (and, the second time, after a submission read the first pattern). + for (UINT64 i = 0; i < committed; ++i) bytes[i] = pattern_byte(i, seed); + EXPECT(SUCCEEDED(allocator->Reset())); + EXPECT(SUCCEEDED(list->Reset(allocator.p, nullptr))); + list->CopyBufferRegion(readback.p, 0, buffer.p, 0, size); + EXPECT(SUCCEEDED(list->Close())); + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + EXPECT(SUCCEEDED(queue->Signal(fence.p, ++fence_value))); + EXPECT(SUCCEEDED(fence->SetEventOnCompletion(fence_value, done))); + EXPECT(WaitForSingleObject(done, 30000) == WAIT_OBJECT_0); + void* mapped = nullptr; + EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); + const auto* got = static_cast(mapped); + UINT64 wrong = size; + for (UINT64 i = 0; i < size && wrong == size; ++i) + if (got[i] != (i < committed ? pattern_byte(i, seed) : 0)) wrong = i; + readback->Unmap(0, nullptr); + if (wrong != size) + std::fprintf(stderr, "%s: %s: pattern %u: first wrong byte at %llu\n", who, kind, seed, + static_cast(wrong)); + EXPECT(wrong == size); + } + CloseHandle(done); + std::printf("%s: %s, %llu bytes (%llu committed): GPU VA is the address, each submission reads the pages' " + "latest bytes\n", + who, kind, static_cast(size), static_cast(committed)); + return 0; +} + int check_title_placed_all(ID3D12Device* device) { constexpr SIZE_T size = 4 * 0x10000; int failures = 0; void* pages = VirtualAlloc(nullptr, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); if (!pages) return 1; failures += check_title_placed(device, "VirtualAlloc range", pages, size); + failures += check_placed_texture_views(device, pages); // Inside a page, as the title places small UAV buffers (64-byte aligned, found in review on an RTX 5090): the // import starts at the page and the buffer is bound at the offset. failures += check_title_placed(device, "64 bytes into a page", static_cast(pages) + 64, 0x1000 - 64); @@ -277,50 +498,1367 @@ int check_title_placed_all(ID3D12Device* device) { UnmapViewOfFile(view); CloseHandle(section); - // Cache-modified ranges are not imported (WC imports read wrong bytes on an RTX 5090 in review). Some Wine - // versions report a requested WC allocation as plain read-write memory; check the protection actually supplied. - // PAGE_NOCACHE also exercises the fallback on those hosts, rather than dropping the cache-protection check. + // Cache-modified ranges are not imported (WC imports read wrong bytes on an RTX 5090 in review): a shadow buffer + // answers at the same VA. Some Wine versions report a requested WC allocation as plain read-write memory; check + // the protection actually supplied. PAGE_NOCACHE also exercises the fallback on those hosts, rather than + // dropping the cache-protection check. const char* who = "vulkan slot-133 buffer"; + for (DWORD modifier : {DWORD(PAGE_WRITECOMBINE), DWORD(PAGE_NOCACHE)}) { + void* pages = VirtualAlloc(nullptr, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE | modifier); + EXPECT(pages != nullptr); + MEMORY_BASIC_INFORMATION region{}; + EXPECT(VirtualQuery(pages, ®ion, sizeof(region)) == sizeof(region)); + const bool cache_modified = (region.Protect & (PAGE_WRITECOMBINE | PAGE_NOCACHE)) != 0; + if (!cache_modified) EXPECT(region.Protect == PAGE_READWRITE); + const int failed = check_title_placed_shadow(device, modifier == PAGE_WRITECOMBINE ? "write-combined range" + : "uncached range", + pages, size, size); + std::printf("%s: cache modifier 0x%lx, reported protection 0x%lx: %s\n", who, modifier, region.Protect, + failed ? "FAILED" + : cache_modified ? "shadow buffer verified" + : "modifier not reported; read-write import verified"); + failures += failed; + VirtualFree(pages, 0, MEM_RELEASE); + } + { + // A larger write-combined range, so the per-submission copy the layer logs is measured on more than a few + // pages (retail places 182 MiB, 74 MiB of it write-combined). + constexpr SIZE_T large = 64u << 20; + void* pages = VirtualAlloc(nullptr, large, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE | PAGE_WRITECOMBINE); + EXPECT(pages != nullptr); + failures += check_title_placed_shadow(device, "64 MiB write-combined range", pages, large, large); + VirtualFree(pages, 0, MEM_RELEASE); + } + char* partial = static_cast(VirtualAlloc(nullptr, size, MEM_RESERVE, PAGE_READWRITE)); + EXPECT(partial != nullptr && VirtualAlloc(partial, size / 2, MEM_COMMIT, PAGE_READWRITE) == partial); + // Pages not committed yet (xmem commits on first touch) are not imported either: the shadow copies the committed + // half and never reads the other, which a GPU copy sees as zeros. + failures += check_title_placed_shadow(device, "half-committed range", partial, size / 2, size); + VirtualFree(partial, 0, MEM_RELEASE); + return failures; +} + +// Submits a GPU copy of all of `buffer` to a READBACK buffer and waits for it: what the GPU read at that submission. +struct GpuReader { + const char* who = "vulkan slot-133 written pages"; + ID3D12Device* device = nullptr; + UINT64 size = 0; + Ref readback; + Ref queue; + Ref allocator; + Ref list; + Ref fence; + HANDLE done = nullptr; + UINT64 fence_value = 0; + + ~GpuReader() { + if (done) CloseHandle(done); + } + int init(ID3D12Device* d, UINT64 bytes) { + device = d; + size = bytes; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = size; + desc.Height = desc.DepthOrArraySize = desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback.p)))); + D3D12_COMMAND_QUEUE_DESC queue_desc{D3D12_COMMAND_LIST_TYPE_DIRECT}; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, + IID_PPV_ARGS(&list.p)))); + EXPECT(SUCCEEDED(list->Close())); + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + done = CreateEventW(nullptr, FALSE, FALSE, nullptr); + EXPECT(done != nullptr); + return 0; + } + int read(ID3D12Resource* buffer, std::vector& out) { + EXPECT(SUCCEEDED(allocator->Reset())); + EXPECT(SUCCEEDED(list->Reset(allocator.p, nullptr))); + list->CopyBufferRegion(readback.p, 0, buffer, 0, size); + EXPECT(SUCCEEDED(list->Close())); + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + EXPECT(SUCCEEDED(queue->Signal(fence.p, ++fence_value))); + EXPECT(SUCCEEDED(fence->SetEventOnCompletion(fence_value, done))); + EXPECT(WaitForSingleObject(done, 30000) == WAIT_OBJECT_0); + void* mapped = nullptr; + EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); + out.assign(static_cast(mapped), static_cast(mapped) + size); + readback->Unmap(0, nullptr); + return 0; + } +}; + +// The first byte where the GPU's copy differs from `want`, or -1. +long long first_difference(const std::vector& got, const std::vector& want) { + for (size_t i = 0; i < got.size() && i < want.size(); ++i) + if (got[i] != want[i]) return static_cast(i); + return got.size() == want.size() ? -1 : static_cast(std::min(got.size(), want.size())); +} + +ID3D12Resource* place_shadow(ID3D12Device* device, void* pages, UINT64 size) { D3D12_RESOURCE_DESC desc{}; desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; desc.Width = size; desc.Height = desc.DepthOrArraySize = desc.MipLevels = 1; desc.SampleDesc.Count = 1; desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; - for (DWORD modifier : {DWORD(PAGE_WRITECOMBINE), DWORD(PAGE_NOCACHE)}) { - void* cached_pages = VirtualAlloc(nullptr, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE | modifier); - EXPECT(cached_pages != nullptr); - MEMORY_BASIC_INFORMATION region{}; - EXPECT(VirtualQuery(cached_pages, ®ion, sizeof(region)) == sizeof(region)); - const bool cache_modified = (region.Protect & (PAGE_WRITECOMBINE | PAGE_NOCACHE)) != 0; - { - Ref buffer; - EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, cached_pages, desc, 0xFFFFFFFFu, IID_PPV_ARGS(&buffer.p)), S_OK); - if (cache_modified) { - EXPECT(buffer->GetGPUVirtualAddress() != reinterpret_cast(cached_pages)); - } else { - EXPECT(region.Protect == PAGE_READWRITE); - EXPECT(buffer->GetGPUVirtualAddress() == reinterpret_cast(cached_pages)); + ID3D12Resource* buffer = nullptr; + if (FAILED(rt::d3d12::create_buffer_at_host_address(device, pages, desc, 0xFFFFFFFFu, IID_PPV_ARGS(&buffer)))) + return nullptr; + if (buffer->GetGPUVirtualAddress() != reinterpret_cast(pages)) { + buffer->Release(); + return nullptr; + } + return buffer; +} + +DWORD protection_of(const void* address) { + MEMORY_BASIC_INFORMATION region{}; + return VirtualQuery(address, ®ion, sizeof(region)) && region.State == MEM_COMMIT ? region.Protect : 0; +} + +// A shadow is copied again only where the title wrote since the last submission (the shadow's pages are read-only +// between submissions, and a write fault marks them). Checked by what a GPU copy reads after each step, compared byte +// for byte with what the CPU wrote, over the whole buffer: +// 1. a pattern over everything committed, then a submission; +// 2. one 4 KiB page rewritten (plus the last byte of the range), then a submission: the new page arrives and the rest +// keeps the first pattern; +// 3. nothing written: the same bytes again; +// 4. a page that was read-only after a submission is written by a second thread while the first waits, then a +// submission. +// `committed` bytes from the start are committed; the rest reads as zeros. The protection after a submission is +// printed: PAGE_READONLY with the range's cache attribute when the writes are watched. +int check_written_pages(ID3D12Device* device, const char* kind, std::uint8_t* pages, UINT64 committed, UINT64 size) { + const char* who = "vulkan slot-133 written pages"; + Ref buffer; + buffer.p = place_shadow(device, pages, size); + EXPECT(buffer.p != nullptr); + GpuReader reader; + if (reader.init(device, size)) return 1; + std::vector want(size, 0), got; + for (UINT64 i = 0; i < committed; ++i) want[i] = pages[i] = pattern_byte(i, 11); + EXPECT(reader.read(buffer.p, got) == 0); + EXPECT(first_difference(got, want) == -1); + const DWORD watched = protection_of(pages); + + // Step 2: one page in the middle of the committed part, and the last committed byte. + const UINT64 page = (committed / 2) & ~UINT64(0xfff); + for (UINT64 i = page; i < page + 0x1000 && i < committed; ++i) want[i] = pages[i] = pattern_byte(i, 201); + want[committed - 1] = pages[committed - 1] = 0xa5; + EXPECT(reader.read(buffer.p, got) == 0); + long long wrong = first_difference(got, want); + if (wrong >= 0) std::fprintf(stderr, "%s: %s: one page rewritten: first wrong byte at %lld\n", who, kind, wrong); + EXPECT(wrong == -1); + + // Step 3: nothing written since. + EXPECT(reader.read(buffer.p, got) == 0); + EXPECT(first_difference(got, want) == -1); + + // Step 4: a write from another thread, to the first page. + HANDLE writer = CreateThread(nullptr, 0, [](void* p) -> DWORD { + auto* bytes = static_cast(p); + for (int i = 0; i < 64; ++i) bytes[i] = std::uint8_t(0xc0 + i); + return 0; + }, pages, 0, nullptr); + EXPECT(writer != nullptr && WaitForSingleObject(writer, 10000) == WAIT_OBJECT_0); + CloseHandle(writer); + for (int i = 0; i < 64; ++i) want[i] = std::uint8_t(0xc0 + i); + EXPECT(reader.read(buffer.p, got) == 0); + EXPECT(first_difference(got, want) == -1); + const DWORD after = protection_of(pages); + buffer.p->Release(); + buffer.p = nullptr; + // Released: the pages are the title's again, read-write, and a write doesn't fault. + EXPECT(protection_of(pages) == 0 || (protection_of(pages) & 0xff) == PAGE_READWRITE); + pages[0] ^= 1; + std::printf("%s: %s, %llu bytes (%llu committed): a rewritten page, a write from another thread and an unchanged " + "submission all read back right; protection between submissions 0x%lx, 0x%lx\n", + who, kind, static_cast(size), static_cast(committed), watched, + after); + return 0; +} + +// Pages that change under a live shadow: committed later, decommitted, written after a submission. A reserved range +// whose first half is committed; then a page of the second half is committed and written, and the first 64 KiB is +// decommitted (it reads as zeros again). +int check_commit_changes(ID3D12Device* device) { + const char* who = "vulkan slot-133 written pages"; + constexpr SIZE_T size = 4 * 0x10000; + auto* pages = static_cast(VirtualAlloc(nullptr, size, MEM_RESERVE, PAGE_READWRITE)); + EXPECT(pages != nullptr && VirtualAlloc(pages, size / 2, MEM_COMMIT, PAGE_READWRITE) == pages); + int failures = 0; + { + Ref buffer; + buffer.p = place_shadow(device, pages, size); + EXPECT(buffer.p != nullptr); + GpuReader reader; + if (reader.init(device, size)) return 1; + std::vector want(size, 0), got; + for (UINT64 i = 0; i < size / 2; ++i) want[i] = pages[i] = pattern_byte(i, 3); + EXPECT(reader.read(buffer.p, got) == 0); + EXPECT(first_difference(got, want) == -1); + EXPECT((protection_of(pages) & 0xff) == PAGE_READONLY); + EXPECT(reader.read(buffer.p, got) == 0); + wchar_t flag[2]{}; + const bool full_walk = GetEnvironmentVariableW(L"LEONIDA_SHADOW_FULL_WALK", flag, 2) == 1 && flag[0] == L'1'; + // The full walk also queries the clean, protected half. + EXPECT(rt::d3d12::title_shadow_refresh_queries(device) == (full_walk ? 2 : 1)); + EXPECT(first_difference(got, want) == -1); + // Committed after the shadow was made, then written. + std::uint8_t* later = pages + 3 * 0x10000; + EXPECT(VirtualAlloc(later, 0x1000, MEM_COMMIT, PAGE_READWRITE) == later); + leonida::title_memory_map::changed(); // as the title's VirtualAlloc shim does + for (UINT64 i = 0; i < 0x1000; ++i) want[3 * 0x10000 + i] = later[i] = pattern_byte(i, 77); + EXPECT(reader.read(buffer.p, got) == 0); + long long wrong = first_difference(got, want); + if (wrong >= 0) std::fprintf(stderr, "%s: page committed later: first wrong byte at %lld\n", who, wrong); + EXPECT(wrong == -1); + // Decommitted: zeros, and the rest unchanged. + EXPECT(VirtualFree(pages, 0x10000, MEM_DECOMMIT)); + leonida::title_memory_map::changed(); // as the title's VirtualFree shim does + std::fill(want.begin(), want.begin() + 0x10000, std::uint8_t(0)); + EXPECT(reader.read(buffer.p, got) == 0); + wrong = first_difference(got, want); + if (wrong >= 0) std::fprintf(stderr, "%s: decommitted page: first wrong byte at %lld\n", who, wrong); + EXPECT(wrong == -1); + // Committed again and written: it arrives. + EXPECT(VirtualAlloc(pages, 0x1000, MEM_COMMIT, PAGE_READWRITE) == pages); + leonida::title_memory_map::changed(); + for (UINT64 i = 0; i < 0x1000; ++i) want[i] = pages[i] = pattern_byte(i, 5); + EXPECT(reader.read(buffer.p, got) == 0); + EXPECT(first_difference(got, want) == -1); + // A title write opens the watched page without changing the map generation. + const auto generation = leonida::title_memory_map::generation(); + EXPECT((protection_of(pages) & 0xff) == PAGE_READONLY); + want[0] = pages[0] ^= 0xff; + EXPECT((protection_of(pages) & 0xff) == PAGE_READWRITE); + EXPECT(leonida::title_memory_map::generation() == generation); + EXPECT(reader.read(buffer.p, got) == 0); + EXPECT(first_difference(got, want) == -1); + } + std::printf("%s: a page committed after the shadow, a decommitted page and a recommitted one read back right\n", + who); + VirtualFree(pages, 0, MEM_RELEASE); + return failures; +} + +// The negative control, and the case it stands for. One pagefile-backed section (SEC_RESERVE, half committed, as xmem +// backs physical pages) is mapped at two addresses, A and B; the shadow is placed at A. A write through B doesn't fault +// at A, so without a mark the page it changed is not copied: the GPU still reads the old bytes. That shows the test +// sees a page the tracking missed. Once the page is reported aliased (what xmem does when it maps one physical page +// at two addresses: leonida::title_page_aliases), it is copied at every submission and the write arrives. +int check_aliased_write(ID3D12Device* device) { + const char* who = "vulkan slot-133 aliased page"; + constexpr SIZE_T size = 4 * 0x10000; + HANDLE section = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE | SEC_RESERVE, 0, DWORD(size), + nullptr); + EXPECT(section != nullptr); + auto* a = static_cast(MapViewOfFile(section, FILE_MAP_ALL_ACCESS, 0, 0, size)); + auto* b = static_cast(MapViewOfFile(section, FILE_MAP_ALL_ACCESS, 0, 0, size)); + EXPECT(a != nullptr && b != nullptr && VirtualAlloc(a, size / 2, MEM_COMMIT, PAGE_READWRITE) == a); + const UINT64 committed = size / 2; + long long unmarked = -1, marked = -1; + { + Ref buffer; + buffer.p = place_shadow(device, a, size); + EXPECT(buffer.p != nullptr); + GpuReader reader; + if (reader.init(device, size)) return 1; + std::vector want(size, 0), got; + for (UINT64 i = 0; i < committed; ++i) want[i] = a[i] = pattern_byte(i, 19); + EXPECT(reader.read(buffer.p, got) == 0); + EXPECT(first_difference(got, want) == -1); + // Through B, the page at offset 0x11000 (in A's second 64 KiB). + constexpr UINT64 at = 0x11000; + for (UINT64 i = at; i < at + 0x1000; ++i) want[i] = b[i] = pattern_byte(i, 133); + EXPECT(std::memcmp(a + at, want.data() + at, 0x1000) == 0); // the same memory + EXPECT(reader.read(buffer.p, got) == 0); + unmarked = first_difference(got, want); + // Reported aliased: copied from now on. + leonida::title_page_aliases::set(reinterpret_cast(a + at), true); + EXPECT(reader.read(buffer.p, got) == 0); + marked = first_difference(got, want); + // And a later write through B, while it stays aliased. + for (UINT64 i = at; i < at + 64; ++i) want[i] = b[i] = 0x3c; + EXPECT(reader.read(buffer.p, got) == 0); + EXPECT(first_difference(got, want) == -1); + leonida::title_page_aliases::set(reinterpret_cast(a + at), false); + } + UnmapViewOfFile(b); + UnmapViewOfFile(a); + CloseHandle(section); + std::printf("%s: a write through another view of the page, not marked: first stale byte at %lld (expected: in " + "the page, 69632); marked aliased: %s\n", + who, unmarked, marked == -1 ? "arrives" : "STILL STALE"); + EXPECT(unmarked == 0x11000); + EXPECT(marked == -1); + return 0; +} + +// Kernel writes into a watched page. ReadFile writes from kernel mode, so a page a shadow made read-only fails it +// with ERROR_NOACCESS instead of faulting into the layer: the plain call fails (the control). Through the file shims' +// path (leonida::kernel_writes::read_file, what the title's ReadFile import resolves to), the destination is pinned +// and opened first: the read succeeds and its bytes reach the GPU at the next submission, synchronously and with an +// overlapped read on an asynchronous handle. +int check_kernel_write(ID3D12Device* device) { + const char* who = "vulkan slot-133 kernel write"; + constexpr SIZE_T size = 4 * 0x10000; + constexpr DWORD chunk = 0x2000; + wchar_t directory[MAX_PATH]{}, path[MAX_PATH]{}; + EXPECT(GetTempPathW(MAX_PATH, directory) && GetTempFileNameW(directory, L"lsh", 0, path)); + std::vector file_bytes(2 * chunk); + for (size_t i = 0; i < file_bytes.size(); ++i) file_bytes[i] = std::uint8_t(i * 29u + 1u); + { + const HANDLE out = CreateFileW(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY, nullptr); + DWORD wrote = 0; + EXPECT(out != INVALID_HANDLE_VALUE); + const BOOL ok = WriteFile(out, file_bytes.data(), DWORD(file_bytes.size()), &wrote, nullptr); + CloseHandle(out); + EXPECT(ok && wrote == file_bytes.size()); + } + auto* pages = static_cast(VirtualAlloc(nullptr, size, MEM_RESERVE, PAGE_READWRITE | PAGE_WRITECOMBINE)); + EXPECT(pages != nullptr && VirtualAlloc(pages, size / 2, MEM_COMMIT, PAGE_READWRITE | PAGE_WRITECOMBINE) == pages); + DWORD plain_error = 0, watched = 0; + bool plain_failed = false; + { + Ref buffer; + buffer.p = place_shadow(device, pages, size); + EXPECT(buffer.p != nullptr); + GpuReader reader; + if (reader.init(device, size)) return 1; + std::vector want(size, 0), got; + for (UINT64 i = 0; i < size / 2; ++i) want[i] = pages[i] = pattern_byte(i, 41); + EXPECT(reader.read(buffer.p, got) == 0); + EXPECT(first_difference(got, want) == -1); + watched = protection_of(pages + 0x4000); + + // The control: a plain ReadFile into a page made read-only by the last submission. + HANDLE in = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); + EXPECT(in != INVALID_HANDLE_VALUE); + DWORD read = 0; + plain_failed = !::ReadFile(in, pages + 0x4000, chunk, &read, nullptr); + plain_error = plain_failed ? GetLastError() : 0; + if (!plain_failed) std::memcpy(want.data() + 0x4000, file_bytes.data(), chunk); // not watched after all + + // Through the shims' path: the same read succeeds. + SetFilePointer(in, 0, nullptr, FILE_BEGIN); + read = 0; + const BOOL ok = leonida::kernel_writes::read_file(in, pages + 0x4000, chunk, &read, nullptr); + CloseHandle(in); + EXPECT(ok && read == chunk); + std::memcpy(want.data() + 0x4000, file_bytes.data(), chunk); + EXPECT(reader.read(buffer.p, got) == 0); + long long wrong = first_difference(got, want); + if (wrong >= 0) std::fprintf(stderr, "%s: synchronous read: first wrong byte at %lld\n", who, wrong); + EXPECT(wrong == -1); + + // Overlapped, on an asynchronous handle, into the next page (read-only again after that submission). + in = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, nullptr); + EXPECT(in != INVALID_HANDLE_VALUE); + OVERLAPPED overlapped{}; + overlapped.Offset = chunk; + overlapped.hEvent = CreateEventW(nullptr, TRUE, FALSE, nullptr); + BOOL queued = leonida::kernel_writes::read_file(in, pages + 0x8000, chunk, nullptr, &overlapped); + const bool pending = !queued && GetLastError() == ERROR_IO_PENDING; + EXPECT(queued || pending); + // A submission while it may still be in flight leaves the pinned page writable. + EXPECT(reader.read(buffer.p, got) == 0); + read = 0; + EXPECT(GetOverlappedResult(in, &overlapped, &read, TRUE) && read == chunk); + CloseHandle(overlapped.hEvent); + CloseHandle(in); + std::memcpy(want.data() + 0x8000, file_bytes.data() + chunk, chunk); + EXPECT(reader.read(buffer.p, got) == 0); + wrong = first_difference(got, want); + if (wrong >= 0) std::fprintf(stderr, "%s: overlapped read: first wrong byte at %lld\n", who, wrong); + EXPECT(wrong == -1); + // Its pin is gone once the read completed: nothing is left pinned. + EXPECT(leonida::kernel_writes::state().count.load() == 0); + } + VirtualFree(pages, 0, MEM_RELEASE); + DeleteFileW(path); + std::printf("%s: plain ReadFile into a watched page (protection 0x%lx): %s (error %lu); through the file shims: " + "synchronous and overlapped reads succeed and reach the GPU\n", + who, watched, plain_failed ? "fails" : "succeeds", plain_error); + // The control must show the failure the shims prevent, wherever the page was watched. + if ((watched & 0xff) == PAGE_READONLY) EXPECT(plain_failed && plain_error == ERROR_NOACCESS); + return 0; +} + +// Shadows that share pages, as the title places them: buffers of a few KiB back to back, off page boundaries, so most +// 4 KiB pages hold the end of one buffer and the start of the next. A page has one owner that may make it read-only, +// so the shadows over a run of pages that overlap or touch share one tracker; checked, with what the GPU reads after +// each step compared byte for byte with what the CPU wrote: +// 1. six buffers back to back are one tracker, and two apart (a page between them) two more; a buffer reaching +// both joins those two into one; +// 2. a submission with nothing written queries no page (with a tracker per buffer, every buffer but a page's owner +// found it read-only, not its own, and queried and copied it at every submission); +// 3. bytes written on both sides of a buffer boundary, inside one page, reach both buffers; +// 4. a kernel write (ReadFile through the file shims) into a shared page reaches both buffers; +// 5. a released buffer's own pages are writable again (no fault, no copy), and its neighbours still read right. +int check_shared_pages(ID3D12Device* device) { + const char* who = "vulkan slot-133 shared pages"; + constexpr SIZE_T size = 4 * 0x10000; + auto* pages = static_cast( + VirtualAlloc(nullptr, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE | PAGE_WRITECOMBINE)); + EXPECT(pages != nullptr); + struct Placed { + UINT64 offset, bytes; + Ref buffer; + GpuReader reader; + }; + // Back to back from 0x40: page 0 holds the end of 0 and the start of 1, page 1 the end of 1 and the start of 2, + // and so on; buffer 3 alone covers pages 3 and 4. Buffers 6 and 7 are apart (page 0x11 between them); 8 bridges them. + const UINT64 layout[][2] = {{0x40, 0xc00}, {0xc40, 0x1000}, {0x1c40, 0x400}, {0x2040, 0x3000}, + {0x5040, 0x800}, {0x5840, 0xa40}, {0x10100, 0x800}, {0x12100, 0x800}, + {0x10900, 0x1800}}; + constexpr size_t kCount = sizeof(layout) / sizeof(layout[0]); + std::vector> placed; + std::vector want(size), got; + for (UINT64 i = 0; i < size; ++i) want[i] = pages[i] = pattern_byte(i, 19); + const auto read_all = [&](size_t skip) -> long long { // the first buffer that reads wrong, or -1 + for (size_t k = 0; k < placed.size(); ++k) { + if (k == skip || !placed[k]->buffer.p) continue; + if (placed[k]->reader.read(placed[k]->buffer.p, got)) return static_cast(k); + const std::vector expected(want.begin() + std::ptrdiff_t(placed[k]->offset), + want.begin() + std::ptrdiff_t(placed[k]->offset + placed[k]->bytes)); + const long long wrong = first_difference(got, expected); + if (wrong >= 0) { + std::fprintf(stderr, "%s: buffer %zu (+0x%llx): first wrong byte at +0x%llx\n", who, k, + static_cast(placed[k]->offset), wrong); + return static_cast(k); } } - std::printf("%s: cache modifier 0x%lx, reported protection 0x%lx: %s\n", who, modifier, region.Protect, - cache_modified ? "ordinary-buffer fallback verified" - : "modifier not reported; read-write import verified"); - VirtualFree(cached_pages, 0, MEM_RELEASE); + return -1; + }; + // Which placements are shadows is the driver's: an import needs the buffer alignment (0x40 isn't), and some Wine + // versions report write-combined pages as plain memory, so a driver there may import the aligned ones (6, 7, 8). + // The trackers expected follow the shadows actually made, joined as the layer joins them: a new shadow joins every + // tracker whose pages overlap or touch its own, and a release never splits one (it goes with its last shadow). + struct Run { + UINT64 first, last; + std::vector members; + }; + std::vector runs; + std::vector shadowed(kCount, false); + const auto join_runs = [&](size_t k) { + const UINT64 first = layout[k][0] & ~UINT64(0xfff); + const UINT64 last = (layout[k][0] + layout[k][1] + 0xfff) & ~UINT64(0xfff); + Run joined{first, last, {k}}; + std::erase_if(runs, [&](const Run& run) { + if (run.first > last || first > run.last) return false; + joined.first = std::min(joined.first, run.first); + joined.last = std::max(joined.last, run.last); + joined.members.insert(joined.members.end(), run.members.begin(), run.members.end()); + return true; + }); + runs.push_back(std::move(joined)); + }; + const auto leave_runs = [&](size_t k) { + for (Run& run : runs) std::erase(run.members, k); + std::erase_if(runs, [](const Run& run) { return run.members.empty(); }); + }; + const std::uint64_t trackers_before = rt::d3d12::title_shadow_trackers(device); + for (size_t k = 0; k < kCount; ++k) { + auto p = std::make_unique(); + p->offset = layout[k][0]; + p->bytes = layout[k][1]; + p->buffer.p = place_shadow(device, pages + p->offset, p->bytes); + EXPECT(p->buffer.p != nullptr); + if (p->reader.init(device, p->bytes)) return 1; + shadowed[k] = rt::d3d12::title_shadow_buffer(p->buffer.p); + if (shadowed[k]) join_runs(k); + placed.push_back(std::move(p)); + // All shadows (Windows): 0-5 are one tracker, 6 and 7 one each. + if (k == kCount - 2) EXPECT(rt::d3d12::title_shadow_trackers(device) - trackers_before == runs.size()); } - char* partial = static_cast(VirtualAlloc(nullptr, size, MEM_RESERVE, PAGE_READWRITE)); - EXPECT(partial != nullptr && VirtualAlloc(partial, size / 2, MEM_COMMIT, PAGE_READWRITE) == partial); + const size_t shadows = size_t(std::count(shadowed.begin(), shadowed.end(), true)); + // Step 1: buffer 8 joined the trackers of 6 and 7 (all shadows: 2 trackers). + const std::uint64_t trackers = rt::d3d12::title_shadow_trackers(device) - trackers_before; + EXPECT(trackers == runs.size()); + EXPECT(read_all(SIZE_MAX) == -1); + if (shadowed[0] || shadowed[1]) // watched, by the one owner of page 0 + EXPECT((protection_of(pages + 0xc40) & 0xff) == PAGE_READONLY); + + // Step 2: nothing written since. + EXPECT(read_all(SIZE_MAX) == -1); + const std::uint64_t clean_queries = rt::d3d12::title_shadow_refresh_queries(device); + EXPECT(clean_queries == 0); + + // Step 3: the last byte of buffer 0 and the first of buffer 1 (page 0), and the bytes around 7 and 8's boundary. + want[0xc3f] = pages[0xc3f] = 0x5a; + want[0xc40] = pages[0xc40] = 0xa5; + for (UINT64 i = 0x120f0; i < 0x12110; ++i) want[i] = pages[i] = std::uint8_t(i * 13u); + EXPECT(read_all(SIZE_MAX) == -1); + + // Step 4: a kernel write into page 1 (buffers 1 and 2) through the file shims. + wchar_t directory[MAX_PATH]{}, path[MAX_PATH]{}; + EXPECT(GetTempPathW(MAX_PATH, directory) && GetTempFileNameW(directory, L"lsp", 0, path)); + std::vector file_bytes(0x200); + for (size_t i = 0; i < file_bytes.size(); ++i) file_bytes[i] = std::uint8_t(i * 7u + 3u); { - // Pages not committed yet (xmem commits on first touch) are not imported either: the fallback answers. - Ref fallback; - EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, partial, desc, 0xFFFFFFFFu, IID_PPV_ARGS(&fallback.p)), S_OK); - EXPECT(fallback->GetGPUVirtualAddress() != reinterpret_cast(partial)); + const HANDLE out = CreateFileW(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY, nullptr); + DWORD wrote = 0; + EXPECT(out != INVALID_HANDLE_VALUE); + const BOOL ok = WriteFile(out, file_bytes.data(), DWORD(file_bytes.size()), &wrote, nullptr); + CloseHandle(out); + EXPECT(ok && wrote == file_bytes.size()); } - VirtualFree(partial, 0, MEM_RELEASE); - std::printf("%s: a partly committed range falls back to an ordinary buffer\n", who); + const HANDLE in = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); + EXPECT(in != INVALID_HANDLE_VALUE); + DWORD read = 0; + const BOOL read_ok = leonida::kernel_writes::read_file(in, pages + 0x1b00, DWORD(file_bytes.size()), &read, nullptr); + CloseHandle(in); + DeleteFileW(path); + EXPECT(read_ok && read == file_bytes.size()); + std::copy(file_bytes.begin(), file_bytes.end(), want.begin() + 0x1b00); + EXPECT(read_all(SIZE_MAX) == -1); + + // Step 5: buffer 3 goes. Pages 3 and 4 were its alone: writable again, and passed over. Pages 2 and 5, shared + // with buffers 2 and 4, are still watched and still reach them. + EXPECT(read_all(SIZE_MAX) == -1); // pages read-only again after the kernel write's pin ended + placed[3]->buffer.p->Release(); + placed[3]->buffer.p = nullptr; + leave_runs(3); + EXPECT((protection_of(pages + 0x3000) & 0xff) == PAGE_READWRITE); + EXPECT((protection_of(pages + 0x4000) & 0xff) == PAGE_READWRITE); + if (shadowed[2]) EXPECT((protection_of(pages + 0x2000) & 0xff) == PAGE_READONLY); + want[0x2030] = pages[0x2030] = 0x11; // buffer 2's last bytes + want[0x5050] = pages[0x5050] = 0x22; // buffer 4's + pages[0x3800] = 0x33; // nobody's now + EXPECT(read_all(3) == -1); + EXPECT(rt::d3d12::title_shadow_trackers(device) - trackers_before == runs.size()); + + placed.clear(); + EXPECT(rt::d3d12::title_shadow_trackers(device) == trackers_before); + EXPECT((protection_of(pages + 0x40) & 0xff) == PAGE_READWRITE); + EXPECT((protection_of(pages + 0x12000) & 0xff) == PAGE_READWRITE); + VirtualFree(pages, 0, MEM_RELEASE); + std::printf("%s: %zu buffers back to back and across pages (%zu of them shadows) share %llu trackers; an unchanged " + "submission queries %llu pages; boundary writes, a kernel write into a shared page and a released " + "neighbour read back right\n", + who, kCount, shadows, static_cast(trackers), + static_cast(clean_queries)); + return 0; +} + +// Creating a logical RTV needs no memory. Its first GPU clear binds the placement before replay. +int check_placed_target_backing(ID3D12Device* device) { + const char* who = "slot-133 first GPU use"; + std::atomic attempts{0}; + leonida::DeferredImageBinding retry(&attempts, [](void* p) { + return static_cast*>(p)->fetch_add(1) != 0; + }); + EXPECT(!retry.ensure() && !retry.bound()); + std::array callers; + for (auto& thread : callers) thread = std::thread([&] { retry.ensure(); }); + for (auto& thread : callers) thread.join(); + EXPECT(retry.bound() && attempts.load() == 2); + constexpr UINT width = 16, height = 8, pitch = 256; + void* pages = VirtualAlloc(nullptr, 65536, MEM_RESERVE, PAGE_NOACCESS); + EXPECT(pages); + D3D12_RESOURCE_DESC d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + d.Width = width; + d.Height = height; + d.DepthOrArraySize = d.MipLevels = d.SampleDesc.Count = 1; + d.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + d.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + Ref target; + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, d, 2, IID_PPV_ARGS(&target.p)), S_OK); + D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}; + Ref heap; + EXPECT_HR(device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&heap.p)), S_OK); + auto rtv = heap->GetCPUDescriptorHandleForHeapStart(); + device->CreateRenderTargetView(target.p, nullptr, rtv); + const char* setting = std::getenv("LEONIDA_PLACED_IMAGE_DEFER"); + const bool lazy = !setting || std::strcmp(setting, "0"); + EXPECT(bool(rt::d3d12::vulkan_memory_flags(target.p)) == !lazy); + GpuReader gpu; + EXPECT(!gpu.init(device, pitch * height)); + EXPECT_HR(gpu.allocator->Reset(), S_OK); + EXPECT_HR(gpu.list->Reset(gpu.allocator.p, nullptr), S_OK); + const float color[]{1, 0, 1, 1}; + gpu.list->ClearRenderTargetView(rtv, color, 0, nullptr); + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Transition = {target.p, 0, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE}; + gpu.list->ResourceBarrier(1, &barrier); + D3D12_TEXTURE_COPY_LOCATION src{target.p, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + D3D12_TEXTURE_COPY_LOCATION dst{gpu.readback.p, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + dst.PlacedFootprint.Footprint = {d.Format, width, height, 1, pitch}; + gpu.list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + EXPECT_HR(gpu.list->Close(), S_OK); + ID3D12CommandList* lists[]{gpu.list.p}; + gpu.queue->ExecuteCommandLists(1, lists); + EXPECT_HR(gpu.queue->Signal(gpu.fence.p, 1), S_OK); + EXPECT_HR(gpu.fence->SetEventOnCompletion(1, gpu.done), S_OK); + EXPECT(WaitForSingleObject(gpu.done, 30000) == WAIT_OBJECT_0); + EXPECT(rt::d3d12::vulkan_memory_flags(target.p)); + void* mapped = nullptr; + EXPECT_HR(gpu.readback->Map(0, nullptr, &mapped), S_OK); + for (UINT y = 0; y < height; ++y) { + const auto* pixels = reinterpret_cast(static_cast(mapped) + y * pitch); + EXPECT(std::all_of(pixels, pixels + width, [](auto px) { return px == 0xffff00ff; })); + } + gpu.readback->Unmap(0, nullptr); + target.p->Release(); + target.p = nullptr; + VirtualFree(pages, 0, MEM_RELEASE); + return 0; +} + +// Two sampled BC placements have distinct T#s. A CPU write to the first and a GPU copy into +// the second must each promote only their destination and keep previously copied descriptors usable. +int check_shared_bc_placements(ID3D12Device* device) { + const char* who = "shared slot-133 BC images"; + if (!rt::d3d12::bindless_set_layout(device)) return 0; + constexpr UINT width = 32, height = 32, pitch = width / 4 * 8; + void* pages = VirtualAlloc(nullptr, 2 * 65536, MEM_RESERVE, PAGE_NOACCESS); + EXPECT(pages); + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = width; + desc.Height = height; + desc.DepthOrArraySize = desc.MipLevels = desc.SampleDesc.Count = 1; + desc.Format = DXGI_FORMAT_BC1_UNORM; + Ref a, b; + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, desc, 0, IID_PPV_ARGS(&a.p)), S_OK); + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, static_cast(pages) + 65536, desc, 0, + IID_PPV_ARGS(&b.p)), S_OK); + std::uint32_t av[8]{}, bv[8]{}; + device->CreateShaderResourceView(a.p, nullptr, {reinterpret_cast(av)}); + device->CreateShaderResourceView(b.p, nullptr, {reinterpret_cast(bv)}); + const auto first = rt::d3d12::bindless_hash_lookup(device, av); + const auto second = rt::d3d12::bindless_hash_lookup(device, bv); + EXPECT(first && second && first != second); + const bool shared = !rt::d3d12::vulkan_memory_flags(a.p); + EXPECT(bool(rt::d3d12::vulkan_memory_flags(b.p)) == !shared); + std::array pattern{}, result{}; + for (std::size_t i = 0; i < pattern.size(); ++i) pattern[i] = std::uint8_t(i * 13 + 71); + EXPECT_HR(a->WriteToSubresource(0, nullptr, pattern.data(), pitch, pattern.size()), S_OK); + EXPECT(rt::d3d12::vulkan_memory_flags(a.p)); + EXPECT(bool(rt::d3d12::vulkan_memory_flags(b.p)) == !shared); + const auto private_a = rt::d3d12::bindless_hash_lookup(device, av); + EXPECT(private_a && (!shared || private_a != first)); + EXPECT(rt::d3d12::bindless_hash_lookup(device, bv) == second); + GpuReader gpu; + EXPECT(!gpu.init(device, 65536)); + EXPECT_HR(gpu.allocator->Reset(), S_OK); + EXPECT_HR(gpu.list->Reset(gpu.allocator.p, nullptr), S_OK); + gpu.list->CopyResource(b.p, a.p); + EXPECT_HR(gpu.list->Close(), S_OK); + ID3D12CommandList* lists[]{gpu.list.p}; + gpu.queue->ExecuteCommandLists(1, lists); + EXPECT_HR(gpu.queue->Signal(gpu.fence.p, 1), S_OK); + EXPECT_HR(gpu.fence->SetEventOnCompletion(1, gpu.done), S_OK); + EXPECT(WaitForSingleObject(gpu.done, 30000) == WAIT_OBJECT_0); + EXPECT(rt::d3d12::vulkan_memory_flags(b.p)); + const auto private_b = rt::d3d12::bindless_hash_lookup(device, bv); + EXPECT(private_b && (!shared || private_b != second)); + EXPECT_HR(b->ReadFromSubresource(result.data(), pitch, result.size(), 0, nullptr), S_OK); + EXPECT(result == pattern); + std::printf("%s: %s, CPU write and GPU copy preserved all %zu bytes\n", who, shared ? "shared" : "eager", result.size()); + a.p->Release(); a.p = nullptr; + b.p->Release(); b.p = nullptr; + VirtualFree(pages, 0, MEM_RELEASE); + return 0; +} + +// Slot 70 may hand out several T#s before any texels exist. Keep copies of the original +// descriptors, replace one pending image at the same address, then fill from one notified write. +int check_pending_stream_views(ID3D12Device* device) { + const char* who = "pending slot-70 views"; + if (!rt::d3d12::bindless_set_layout(device)) return 0; + constexpr SIZE_T bytes = 65536; + void* pages = VirtualAlloc(nullptr, bytes, MEM_RESERVE, PAGE_NOACCESS); + EXPECT(pages); + GpuReader gpu; + EXPECT(!gpu.init(device, bytes)); + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Height = 8; + desc.DepthOrArraySize = desc.MipLevels = desc.SampleDesc.Count = 1; + desc.Format = DXGI_FORMAT_R8_UNORM; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = desc.Format; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srv.Texture2D.MipLevels = 1; + leonida::gfx10::ImageWords slot{}; + auto view = [&](unsigned width, UINT mapping) { + desc.Width = width; + srv.Shader4ComponentMapping = mapping; + std::array resource{}; + std::array words{}; + std::memcpy(resource.data(), &desc, sizeof(desc)); + std::memcpy(words.data(), &srv, sizeof(srv)); + return rt::d3d12::write_placed_texture_view(device, false, resource.data(), words.data(), + reinterpret_cast(pages), {reinterpret_cast(slot.data())}); + }; + auto index = [&](const auto& descriptor) { + std::uint32_t key[8]; + std::memcpy(key, descriptor.data(), sizeof(key)); + return rt::d3d12::bindless_hash_lookup(device, key); + }; + EXPECT(view(16, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING)); + const auto replaced = slot; + EXPECT(view(32, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING)); + const auto first = slot; + EXPECT(view(32, D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(0, 0, 0, 0))); + const auto second = slot; + slot = {}; + EXPECT(first != second && first != replaced); + const char* defer = std::getenv("LEONIDA_TITLE_IMAGE_DEFER"); + if (!defer || std::strcmp(defer, "0")) + EXPECT(!index(first) && !index(second)); + EXPECT(!index(replaced)); + EXPECT(VirtualAlloc(pages, bytes, MEM_COMMIT, PAGE_READWRITE) == pages); + std::memset(pages, 73, bytes); + leonida::title_texel_writes::note(pages, bytes); + ID3D12CommandList* lists[]{gpu.list.p}; + gpu.queue->ExecuteCommandLists(1, lists); + EXPECT_HR(gpu.queue->Signal(gpu.fence.p, 1), S_OK); + EXPECT_HR(gpu.fence->SetEventOnCompletion(1, gpu.done), S_OK); + EXPECT(WaitForSingleObject(gpu.done, 30000) == WAIT_OBJECT_0); + EXPECT(index(first) && index(second) && !index(replaced)); + // Replace the synthetic owner before releasing the CPU pages. + Ref placement; + desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, desc, 6, IID_PPV_ARGS(&placement.p)), S_OK); + EXPECT(!index(first) && !index(second)); + placement.p->Release(); + placement.p = nullptr; + VirtualFree(pages, 0, MEM_RELEASE); + return 0; +} + +// A persistent Map can become readable without notifying xmem or calling Map a second time. +int check_mapped_plane(ID3D12Device* device) { + const char* who = "persistent slot-133 plane"; + constexpr UINT width = 256, height = 8, size = width * height; + void* pages = VirtualAlloc(nullptr, 65536, MEM_RESERVE, PAGE_NOACCESS); + EXPECT(pages); + GpuReader gpu; + EXPECT(!gpu.init(device, size)); + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = width; + desc.Height = height; + desc.Format = DXGI_FORMAT_R8_UNORM; + desc.SampleDesc.Count = desc.DepthOrArraySize = desc.MipLevels = 1; + leonida::title_xg_layouts::note({UINT(desc.Dimension), UINT(desc.Format), height, 1, 1, width}, 1); + Ref texture; + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, desc, 6, IID_PPV_ARGS(&texture.p)), S_OK); + void* mapped = nullptr; + EXPECT_HR(texture->Map(0, nullptr, &mapped), S_OK); + EXPECT(mapped == pages); + ID3D12CommandList* lists[]{gpu.list.p}; + std::array pixels{}; + for (unsigned pass = 0; pass < 3; ++pass) { + if (pass) { + if (pass == 1) EXPECT(VirtualAlloc(mapped, size, MEM_COMMIT, PAGE_READWRITE) == mapped); + std::memset(mapped, 61 * pass, size); + } + gpu.queue->ExecuteCommandLists(1, lists); + EXPECT_HR(gpu.queue->Signal(gpu.fence.p, pass + 1), S_OK); + EXPECT_HR(gpu.fence->SetEventOnCompletion(pass + 1, gpu.done), S_OK); + EXPECT(WaitForSingleObject(gpu.done, 30000) == WAIT_OBJECT_0); + if (pass) { + EXPECT_HR(texture->ReadFromSubresource(pixels.data(), width, size, 0, nullptr), S_OK); + EXPECT(std::all_of(pixels.begin(), pixels.end(), [&](auto value) { return value == 61 * pass; })); + } + } + texture->Unmap(0, nullptr); + texture.p->Release(); + texture.p = nullptr; + VirtualFree(pages, 0, MEM_RELEASE); + return 0; +} + +// Several threads write the same watched pages while submissions keep making them read-only again. Two threads that +// fault on one page race: the first fault reopens it, a submission can protect it again before the second fault is +// handled, and the second write must still be retried, not refused (refused, the process ends: seen natively). After +// the writers stop, one more submission brings every page across. With `write_watched`, over memory reserved with +// MEM_WRITE_WATCH as xmem records it (leonida::title_write_watch): the threads race on the faults that make the block +// hot, and the writes go on with no guard. +int check_concurrent_writes(ID3D12Device* device, bool write_watched) { + const char* who = "vulkan slot-133 written pages"; + constexpr SIZE_T size = 2 * 0x10000, committed = size / 2; // one 64 KiB block: every fault lands in it + constexpr unsigned kWriters = 12; + auto* pages = static_cast( + VirtualAlloc(nullptr, size, MEM_RESERVE | (write_watched ? MEM_WRITE_WATCH : 0), PAGE_READWRITE)); + EXPECT(pages != nullptr && VirtualAlloc(pages, committed, MEM_COMMIT, PAGE_READWRITE) == pages); + if (write_watched) leonida::title_write_watch::add(reinterpret_cast(pages), size); + int failures = 0; + unsigned submissions = 0; + { + Ref buffer; + buffer.p = place_shadow(device, pages, size); + EXPECT(buffer.p != nullptr); + GpuReader reader; + if (reader.init(device, size)) return 1; + std::vector got; + EXPECT(reader.read(buffer.p, got) == 0); + EXPECT((protection_of(pages) & 0xff) == PAGE_READONLY); + std::atomic stop{false}; + std::vector writers; + for (unsigned t = 0; t < kWriters; ++t) + writers.emplace_back([&stop, pages, t] { + for (std::uint8_t round = 1; !stop.load(std::memory_order_relaxed); ++round) + for (SIZE_T at = t * 8; at < committed; at += 0x1000) + *reinterpret_cast(pages + at) = round; + }); + bool read_failed = false; + const ULONGLONG until = GetTickCount64() + 2000; + while (!read_failed && GetTickCount64() < until) { + read_failed = reader.read(buffer.p, got) != 0; + ++submissions; + } + stop = true; + for (std::thread& w : writers) w.join(); + EXPECT(!read_failed); + EXPECT(reader.read(buffer.p, got) == 0); + const std::vector want(pages, pages + committed); + got.resize(committed); + const long long wrong = first_difference(got, want); + if (wrong >= 0) std::fprintf(stderr, "%s: concurrent writers: first wrong byte at %lld\n", who, wrong); + EXPECT(wrong == -1); + } + std::printf("%s: %u threads writing the same %s pages through %u submissions: no write refused, the last " + "submission reads back right\n", + who, kWriters, write_watched ? "write-watched" : "guarded", submissions); + if (write_watched) leonida::title_write_watch::remove(reinterpret_cast(pages)); + VirtualFree(pages, 0, MEM_RELEASE); return failures; } +// The title's ordinary memory, which xmem reserves with MEM_WRITE_WATCH and records (leonida::title_write_watch). Its +// pages start guarded; the first write fault on a 64 KiB block makes it hot, and from then on its shadows ask the kernel +// which pages were written instead of making it read-only, until it goes kCool (64) refreshes unwritten. Checked, half +// committed (so the pages are not imported and a shadow answers) and with each cache attribute, by what a GPU copy reads +// after each step compared byte for byte with what the CPU wrote: +// 1. a pattern after the shadow exists: one fault per block, which makes it hot; read-write from then on, and a +// submission with nothing written finds no page written and queries only the reserved half; +// 2. a title write to a hot page reaches the GPU at the next submission, with no fault; +// 3. a plain ReadFile (no file shim) into a hot page succeeds, and its bytes reach the GPU; +// 4. an overlapped read through the file shims (the page pinned while it may be in flight) reaches it too; +// 5. a second device's shadow of the same pages, a tracker of its own: a write reaches both devices, though the +// first one's asking cleared the kernel's bit (the journal keeps it for the other); +// 6. a page decommitted and committed again between submissions (zeros, and no write) arrives once marked; +// 7. after 66 submissions with nothing written the blocks are guarded again (read-only), and the next write faults, +// makes them hot again and arrives. +// No fault comes after a block went hot until it cooled, on either device. +int check_write_watched(ID3D12Device* device, ID3D12Device* second, DWORD modifier) { + const char* who = "vulkan slot-133 write-watched pages"; + const char* kind = modifier ? "write-combined" : "read-write"; + constexpr SIZE_T size = 4 * 0x10000; + auto* pages = static_cast( + VirtualAlloc(nullptr, size, MEM_RESERVE | MEM_WRITE_WATCH, PAGE_READWRITE | modifier)); + EXPECT(pages != nullptr && VirtualAlloc(pages, size / 2, MEM_COMMIT, PAGE_READWRITE | modifier) == pages); + leonida::title_write_watch::add(reinterpret_cast(pages), size); // as xmem records it + wchar_t directory[MAX_PATH]{}, path[MAX_PATH]{}; + EXPECT(GetTempPathW(MAX_PATH, directory) && GetTempFileNameW(directory, L"lww", 0, path)); + std::vector file_bytes(0x3000); + for (size_t i = 0; i < file_bytes.size(); ++i) file_bytes[i] = std::uint8_t(i * 23u + 9u); + { + const HANDLE out = CreateFileW(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY, nullptr); + DWORD wrote = 0; + EXPECT(out != INVALID_HANDLE_VALUE); + const BOOL ok = WriteFile(out, file_bytes.data(), DWORD(file_bytes.size()), &wrote, nullptr); + CloseHandle(out); + EXPECT(ok && wrote == file_bytes.size()); + } + rt::d3d12::TitleShadowWatch clean{}; + std::uint64_t clean_queries = 0, hot_faults = 0; + DWORD before = 0, hot = 0, cooled = 0; + { + Ref buffer, other; + buffer.p = place_shadow(device, pages, size); + EXPECT(buffer.p != nullptr); + GpuReader reader, other_reader; + if (reader.init(device, size)) return 1; + std::vector want(size, 0), got; + const auto read_back = [&](const char* step) -> long long { + if (reader.read(buffer.p, got)) return 0; + const long long wrong = first_difference(got, want); + if (wrong >= 0) std::fprintf(stderr, "%s: %s: %s: first wrong byte at %lld\n", who, kind, step, wrong); + return wrong; + }; + const auto faults = [](ID3D12Device* d) { return rt::d3d12::title_shadow_watch(d).faults; }; + + // Step 1. + before = protection_of(pages); + EXPECT((before & 0xff) == PAGE_READONLY); // guarded until written + const std::uint64_t faults_before = faults(device); + for (UINT64 i = 0; i < size / 2; ++i) want[i] = pages[i] = pattern_byte(i, 61); + EXPECT(faults(device) - faults_before == 2); // one per 64 KiB block + EXPECT(read_back("pattern") == -1); + hot = protection_of(pages); + EXPECT((hot & 0xff) == PAGE_READWRITE); + EXPECT(rt::d3d12::title_shadow_watch(device).hot_bytes == size / 2); + EXPECT(rt::d3d12::title_shadow_watch(device).watched_bytes == size); + EXPECT(read_back("nothing written") == -1); + clean = rt::d3d12::title_shadow_watch(device); + clean_queries = rt::d3d12::title_shadow_refresh_queries(device); + EXPECT(clean.asks == 1 && clean.written == 0); + EXPECT(clean_queries == 1); // the reserved half + hot_faults = faults(device); + + // Step 2. + for (UINT64 i = 0x5000; i < 0x6000; ++i) want[i] = pages[i] = pattern_byte(i, 177); + EXPECT(read_back("one page written") == -1); + EXPECT(rt::d3d12::title_shadow_watch(device).written == 1); + + // Step 3. + HANDLE in = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); + EXPECT(in != INVALID_HANDLE_VALUE); + DWORD read = 0; + const BOOL plain = ::ReadFile(in, pages + 0x8800, 0x2000, &read, nullptr); + CloseHandle(in); + EXPECT(plain && read == 0x2000); + std::memcpy(want.data() + 0x8800, file_bytes.data(), 0x2000); + EXPECT(read_back("plain ReadFile") == -1); + + // Step 4. + in = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, nullptr); + EXPECT(in != INVALID_HANDLE_VALUE); + OVERLAPPED overlapped{}; + overlapped.Offset = 0x1000; + overlapped.hEvent = CreateEventW(nullptr, TRUE, FALSE, nullptr); + const BOOL queued = leonida::kernel_writes::read_file(in, pages + 0x10000, 0x2000, nullptr, &overlapped); + EXPECT(queued || GetLastError() == ERROR_IO_PENDING); + EXPECT(reader.read(buffer.p, got) == 0); // while it may still be in flight + read = 0; + EXPECT(GetOverlappedResult(in, &overlapped, &read, TRUE) && read == 0x2000); + CloseHandle(overlapped.hEvent); + CloseHandle(in); + std::memcpy(want.data() + 0x10000, file_bytes.data() + 0x1000, 0x2000); + EXPECT(read_back("overlapped read through the file shims") == -1); + EXPECT(leonida::kernel_writes::state().count.load() == 0); + EXPECT(faults(device) == hot_faults); + + // Step 5. The second device guards the pages at first: its own fault makes them hot there too. + if (second) { + other.p = place_shadow(second, pages, size); + EXPECT(other.p != nullptr); + if (other_reader.init(second, size)) return 1; + EXPECT(other_reader.read(other.p, got) == 0); + EXPECT(first_difference(got, want) == -1); + EXPECT((protection_of(pages + 0x3000) & 0xff) == PAGE_READONLY); + for (UINT64 i = 0x3010; i < 0x3020; ++i) want[i] = pages[i] = std::uint8_t(0x90 + i); + EXPECT(faults(second) == 1); + EXPECT(read_back("written, first device") == -1); + EXPECT(other_reader.read(other.p, got) == 0); + long long wrong = first_difference(got, want); + if (wrong >= 0) std::fprintf(stderr, "%s: %s: second device: first wrong byte at %lld\n", who, kind, wrong); + EXPECT(wrong == -1); + // Hot on both: a write reaches both, whichever asks first. + for (UINT64 i = 0x3020; i < 0x3030; ++i) want[i] = pages[i] = std::uint8_t(0x30 + i); + EXPECT(other_reader.read(other.p, got) == 0); + EXPECT(first_difference(got, want) == -1); + EXPECT(read_back("written, second device asked first") == -1); + EXPECT(faults(second) == 1); + } + EXPECT(faults(device) == hot_faults); + + // Step 6. + EXPECT(VirtualFree(pages + 0x7000, 0x1000, MEM_DECOMMIT)); + EXPECT(VirtualAlloc(pages + 0x7000, 0x1000, MEM_COMMIT, PAGE_READWRITE | modifier) == pages + 0x7000); + leonida::title_memory_map::changed(); + leonida::title_write_watch::mark(reinterpret_cast(pages + 0x7000), + reinterpret_cast(pages + 0x8000)); + std::fill(want.begin() + 0x7000, want.begin() + 0x8000, std::uint8_t(0)); + EXPECT(read_back("decommitted and committed again") == -1); + EXPECT(faults(device) == hot_faults); + + // Step 7, with the second device's copy gone (its guards would make the pages read-only meanwhile). + if (other.p) { + other.p->Release(); + other.p = nullptr; + } + for (int i = 0; i < 66; ++i) EXPECT(reader.read(buffer.p, got) == 0); + EXPECT(first_difference(got, want) == -1); + cooled = protection_of(pages); + EXPECT((cooled & 0xff) == PAGE_READONLY); + EXPECT(rt::d3d12::title_shadow_watch(device).hot_bytes == 0); + want[0x100] = pages[0x100] = 0x7e; + EXPECT(faults(device) == hot_faults + 1); + EXPECT(read_back("written after cooling") == -1); + EXPECT((protection_of(pages) & 0xff) == PAGE_READWRITE); + } + leonida::title_write_watch::remove(reinterpret_cast(pages)); + VirtualFree(pages, 0, MEM_RELEASE); + DeleteFileW(path); + std::printf("%s: %s, %llu bytes (half committed): protection 0x%lx guarded, 0x%lx once written (hot), 0x%lx after " + "66 unwritten submissions; while hot no fault, and an unchanged submission asks %llu times, finds " + "nothing written and queries %llu pages; a title write, a plain ReadFile, an overlapped read, %s and a " + "recommitted page read back right\n", + who, kind, static_cast(size), before, hot, cooled, + static_cast(clean.asks), static_cast(clean_queries), + second ? "a second device's copy" : "(no second device)"); + return 0; +} + +// A write-watched reservation the title releases and reserves again at the same address between two submissions, as +// xmem records it: remove(), then add() of the new reservation, and nothing marked (a MEM_RESERVE | MEM_COMMIT in one +// call writes nothing). Its pages were hot and clean in the tracker and are write-watched again, now by a reservation +// whose kernel bits are clear, so no asking finds them written: the copy must still read the new reservation's zeros, +// then what the title writes there. Over two adjacent reservations under one shadow: +// 1. the second one released and reserved again: it reads as zeros, the first keeps its bytes; +// 2. a write into the new reservation arrives; +// 3. both released and reserved again as one reservation over the whole range: zeros everywhere. +int check_rereserved(ID3D12Device* device) { + const char* who = "vulkan slot-133 write-watched pages"; + constexpr SIZE_T half = 2 * 0x10000, size = 2 * half; + // Two adjacent reservations: a range reserved and released, then reserved again as two halves. + auto* pages = static_cast(VirtualAlloc(nullptr, size, MEM_RESERVE, PAGE_READWRITE)); + EXPECT(pages != nullptr && VirtualFree(pages, 0, MEM_RELEASE)); + const auto reserve = [](std::uint8_t* at, SIZE_T bytes, DWORD type) { + if (VirtualAlloc(at, bytes, type | MEM_WRITE_WATCH, PAGE_READWRITE) != at) return false; + leonida::title_write_watch::add(reinterpret_cast(at), bytes); // as xmem records it + leonida::title_memory_map::changed(); + return true; + }; + const auto release = [](std::uint8_t* at) { + leonida::title_write_watch::remove(reinterpret_cast(at)); + const bool ok = VirtualFree(at, 0, MEM_RELEASE) != 0; + leonida::title_memory_map::changed(); + return ok; + }; + EXPECT(reserve(pages, half, MEM_RESERVE) && reserve(pages + half, half, MEM_RESERVE)); + // The first 64 KiB of each committed: not imported, so a shadow answers. + EXPECT(VirtualAlloc(pages, 0x10000, MEM_COMMIT, PAGE_READWRITE) == pages); + EXPECT(VirtualAlloc(pages + half, 0x10000, MEM_COMMIT, PAGE_READWRITE) == pages + half); + bool whole = false; + { + Ref buffer; + buffer.p = place_shadow(device, pages, size); + EXPECT(buffer.p != nullptr); + GpuReader reader; + if (reader.init(device, size)) return 1; + std::vector want(size, 0), got; + const auto read_back = [&](const char* step) -> long long { + if (reader.read(buffer.p, got)) return 0; + const long long wrong = first_difference(got, want); + if (wrong >= 0) std::fprintf(stderr, "%s: re-reserved: %s: first wrong byte at %lld\n", who, step, wrong); + return wrong; + }; + // Written once (a fault per block makes it hot), then a submission that copies it and one that finds it clean. + const auto write_all = [&](unsigned seed) { + for (SIZE_T i = 0; i < size; ++i) { + MEMORY_BASIC_INFORMATION region{}; + if ((i & 0xfff) == 0 && (!VirtualQuery(pages + i, ®ion, sizeof(region)) || region.State != MEM_COMMIT)) { + i += 0xfff; + continue; + } + want[i] = pages[i] = pattern_byte(i, seed); + } + }; + EXPECT(read_back("placed") == -1); + write_all(91); + EXPECT(read_back("written") == -1); + EXPECT(read_back("nothing written") == -1); + EXPECT(rt::d3d12::title_shadow_watch(device).hot_bytes == 2 * 0x10000); + + // Step 1. + EXPECT(release(pages + half) && reserve(pages + half, half, MEM_RESERVE | MEM_COMMIT)); + std::fill(want.begin() + half, want.end(), std::uint8_t(0)); + EXPECT(read_back("second reservation released and reserved again") == -1); + + // Step 2. + for (SIZE_T i = half + 0x2000; i < half + 0x2100; ++i) want[i] = pages[i] = std::uint8_t(i * 7u + 1u); + EXPECT(read_back("written in the new reservation") == -1); + + // Step 3, hot and clean everywhere first. + write_all(93); + EXPECT(read_back("written again") == -1); + EXPECT(read_back("nothing written again") == -1); + EXPECT(release(pages) && release(pages + half) && reserve(pages, size, MEM_RESERVE | MEM_COMMIT)); + whole = true; + std::fill(want.begin(), want.end(), std::uint8_t(0)); + EXPECT(read_back("both released, reserved again as one") == -1); + } + if (whole) { + release(pages); + } else { + release(pages); + release(pages + half); + } + std::printf("%s: a write-watched reservation released and reserved again at the same address between two " + "submissions reads as the new reservation's zeros, then its writes (one of two adjacent reservations, " + "and both as one)\n", + who); + return 0; +} + +// Title threads take write faults while they hold the process heap's lock: XMemAlloc is _aligned_malloc, so HeapAlloc +// and HeapFree write block headers on pages a shadow may guard. The fault handler waits for the tracker's lock, so +// whoever holds that lock, and whatever lock that holder waits for (the write-watch record and journal, the alias set, +// the kernel-write pins), must never wait for the process heap meanwhile. One shadow over two adjacent reservations, a +// write-watched one (kept hot, so every submission asks about it) and a plain one (guarded), while submissions run back +// to back and: +// - threads take the process heap's lock (HeapLock, as HeapAlloc does inside, and the heap gate above: every +// allocation waits for them), _aligned_malloc and _aligned_free under it and write a guarded page: a fault, with +// the heap's lock held, at every submission; +// - threads _aligned_malloc and _aligned_free blocks of every size class without it; +// - a thread keeps the write-watched half hot; +// - threads change the write-watch record (a reservation added and removed), the journal (mark), the alias set and +// the kernel-write pins, each of which the next refresh takes. +// A watchdog ends the process (exit code 3) when no submission or writer got anywhere for 30 s: a deadlock. +int check_heap_lock_faults(ID3D12Device* device) { + const char* who = "vulkan slot-133 heap-lock faults"; + constexpr SIZE_T half = 4 * 0x10000, size = 2 * half, committed = half / 2; + const bool write_watched = leonida::title_write_watch::enabled(); + auto* pages = static_cast(VirtualAlloc(nullptr, size, MEM_RESERVE, PAGE_READWRITE)); + EXPECT(pages != nullptr && VirtualFree(pages, 0, MEM_RELEASE)); + std::uint8_t* const watched = pages; // write-watched (when write watching is on) + std::uint8_t* const guarded = pages + half; // plain + EXPECT(VirtualAlloc(watched, half, MEM_RESERVE | (write_watched ? MEM_WRITE_WATCH : 0), PAGE_READWRITE) == watched); + EXPECT(VirtualAlloc(guarded, half, MEM_RESERVE, PAGE_READWRITE) == guarded); + EXPECT(VirtualAlloc(watched, committed, MEM_COMMIT, PAGE_READWRITE) == watched); + EXPECT(VirtualAlloc(guarded, committed, MEM_COMMIT, PAGE_READWRITE) == guarded); + if (write_watched) leonida::title_write_watch::add(reinterpret_cast(watched), half); + // Elsewhere: a write-watched reservation for the record thread to add and remove, and pages to pin. + auto* spare = static_cast(VirtualAlloc(nullptr, 0x10000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + EXPECT(spare != nullptr); + + std::atomic progress{0}; // bumped by every submission and every writer's round + std::atomic stop{false}, finished{false}; + std::thread watchdog([&] { + std::uint64_t seen = progress.load(); + ULONGLONG since = GetTickCount64(); + while (!finished.load()) { + Sleep(100); + const std::uint64_t now = progress.load(); + if (now != seen) { + seen = now; + since = GetTickCount64(); + } else if (GetTickCount64() - since > 30000) { + // No heap here: the process heap may be what is stuck. + static const char message[] = + "vulkan slot-133 heap-lock faults: no progress for 30 s: deadlock (a lock the write-fault handler " + "waits for is held by a thread waiting for the process heap)\n"; + DWORD wrote = 0; + WriteFile(GetStdHandle(STD_ERROR_HANDLE), message, DWORD(sizeof(message) - 1), &wrote, nullptr); + TerminateProcess(GetCurrentProcess(), 3); + } + } + }); + unsigned submissions = 0; + std::uint64_t faults = 0; + int failed = 0; + { + Ref buffer; + buffer.p = place_shadow(device, pages, size); + GpuReader reader; + std::vector got; + if (!buffer.p || reader.init(device, size) || reader.read(buffer.p, got)) { + failed = 1; + } else { + for (SIZE_T i = 0; i < committed; i += 0x1000) watched[i] = 1; // hot from now on + const std::uint64_t faults_before = rt::d3d12::title_shadow_watch(device).faults; + std::vector threads; + g_heap_gate_on = true; + for (unsigned t = 0; t < 3; ++t) + threads.emplace_back([&, t] { + const HANDLE heap = GetProcessHeap(); + for (std::uint8_t round = 1; !stop.load(std::memory_order_relaxed); ++round) { + AcquireSRWLockExclusive(&g_heap_gate); + HeapLock(heap); + void* block = _aligned_malloc(64 + (round % 32) * 160, 16); + for (SIZE_T at = t * 64; at < committed; at += 0x10000) // a byte per block + *reinterpret_cast(guarded + at) = round; + _aligned_free(block); + HeapUnlock(heap); + ReleaseSRWLockExclusive(&g_heap_gate); + progress.fetch_add(1, std::memory_order_relaxed); + // About 50 us outside the lock: the other threads get to allocate. + LARGE_INTEGER now{}, frequency{}; + QueryPerformanceFrequency(&frequency); + QueryPerformanceCounter(&now); + const LONGLONG until = now.QuadPart + frequency.QuadPart / 20000; + while (QueryPerformanceCounter(&now) && now.QuadPart < until) YieldProcessor(); + } + }); + for (unsigned t = 0; t < 3; ++t) + threads.emplace_back([&, t] { + std::vector blocks(64, nullptr); + for (unsigned round = 0; !stop.load(std::memory_order_relaxed); ++round) { + void*& block = blocks[(round * 7 + t) % blocks.size()]; + _aligned_free(block); + block = _aligned_malloc(16u << ((round + t) % 13), 16); + if (round % 64 == 0) progress.fetch_add(1, std::memory_order_relaxed); + } + for (void* block : blocks) _aligned_free(block); + }); + threads.emplace_back([&] { + for (std::uint8_t round = 1; !stop.load(std::memory_order_relaxed); ++round) + for (SIZE_T at = 8; at < committed; at += 0x1000) + *reinterpret_cast(watched + at) = round; + }); + threads.emplace_back([&] { + const auto spare_at = reinterpret_cast(spare); + for (unsigned round = 0; !stop.load(std::memory_order_relaxed); ++round) { + if (write_watched) { + leonida::title_write_watch::add(spare_at, 0x10000); + leonida::title_write_watch::mark(reinterpret_cast(watched) + (round % 16) * 0x1000, + reinterpret_cast(watched) + committed); + leonida::title_write_watch::remove(spare_at); + } + leonida::title_page_aliases::set(reinterpret_cast(guarded + half - 0x10000), + round % 2 == 0); + const std::uint64_t pin = leonida::kernel_writes::begin_write(spare + (round % 16) * 0x1000, 0x1000, + nullptr); + leonida::kernel_writes::end_write(pin, false); + } + leonida::title_page_aliases::set(reinterpret_cast(guarded + half - 0x10000), false); + }); + const ULONGLONG until = GetTickCount64() + 3000; + while (!failed && GetTickCount64() < until) { + failed = reader.read(buffer.p, got); + ++submissions; + progress.fetch_add(1, std::memory_order_relaxed); + } + stop = true; + for (std::thread& t : threads) t.join(); + g_heap_gate_on = false; + const auto watch_after = rt::d3d12::title_shadow_watch(device); + faults = watch_after.faults - faults_before; + // With write watching on, the watched half must have stayed hot (asked each refresh, not guarded): else + // the asking path this stresses never ran and the test proves nothing about it. + if (write_watched && !failed && watch_after.hot_bytes == 0) { + std::fprintf(stderr, "%s: the write-watched half is not hot after the stress\n", who); + failed = 1; + } + if (!failed) failed = reader.read(buffer.p, got); + if (!failed) { + const std::vector want_guarded(guarded, guarded + committed); + const std::vector got_guarded(got.begin() + half, got.begin() + half + committed); + const long long wrong = first_difference(got_guarded, want_guarded); + if (wrong >= 0) std::fprintf(stderr, "%s: guarded half: first wrong byte at %lld\n", who, wrong); + failed = wrong >= 0; + } + } + } + finished = true; + watchdog.join(); + if (write_watched) leonida::title_write_watch::remove(reinterpret_cast(watched)); + VirtualFree(watched, 0, MEM_RELEASE); + VirtualFree(guarded, 0, MEM_RELEASE); + VirtualFree(spare, 0, MEM_RELEASE); + EXPECT(!failed); + EXPECT(faults > 0); + std::printf("%s: %u submissions while threads faulted on guarded pages holding the process heap's lock (%llu " + "faults) and others churned the heap, the write-watch record and journal, the aliases and the pins: " + "no deadlock, the last submission reads back right\n", + who, submissions, static_cast(faults)); + return 0; +} + +int check_written_pages_all(ID3D12Device* device) { + int failures = 0; + constexpr SIZE_T size = 4 * 0x10000; + for (DWORD modifier : {DWORD(0), DWORD(PAGE_WRITECOMBINE)}) { + // Half committed, so the import is refused whatever the cache attribute and the shadow answers. + auto* pages = static_cast(VirtualAlloc(nullptr, size, MEM_RESERVE, PAGE_READWRITE | modifier)); + if (!pages || VirtualAlloc(pages, size / 2, MEM_COMMIT, PAGE_READWRITE | modifier) != pages) return failures + 1; + failures += check_written_pages(device, modifier ? "half-committed write-combined range" + : "half-committed range", + pages, size / 2, size); + VirtualFree(pages, 0, MEM_RELEASE); + // Wholly committed and write-combined (not imported), and placed 64 bytes into its first page. + if (modifier) { + pages = static_cast(VirtualAlloc(nullptr, size, MEM_RESERVE | MEM_COMMIT, + PAGE_READWRITE | modifier)); + if (!pages) return failures + 1; + failures += check_written_pages(device, "write-combined range", pages, size, size); + failures += check_written_pages(device, "write-combined range, 64 bytes in", pages + 64, size - 64, + size - 64); + VirtualFree(pages, 0, MEM_RELEASE); + } + } + failures += check_commit_changes(device); + failures += check_concurrent_writes(device, false); + if (leonida::title_write_watch::enabled()) failures += check_concurrent_writes(device, true); + failures += check_aliased_write(device); + failures += check_kernel_write(device); + failures += check_shared_pages(device); + return failures; +} + +// Replace mapped bytes twice, including compressed edge blocks, mip tails and array slices. +int check_mapped_bc_array(ID3D12Device* device) { + const char* who = "persistent BC1 array"; + rt::xg_xs::ResourceDesc x{}; + x.dimension = rt::xg_xs::kTexture2D; + x.width = 28; + x.height = 20; + x.depth_or_array = 2; + x.mips = 4; + x.format = DXGI_FORMAT_BC1_UNORM; + x.samples = 1; + rt::xg_xs::Texture tiled{}; + EXPECT(rt::xg_xs::build_texture(x, tiled)); + auto* pages = static_cast(VirtualAlloc(nullptr, tiled.layout.size, MEM_RESERVE | MEM_COMMIT, + PAGE_READWRITE)); + EXPECT(pages); + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Format = DXGI_FORMAT_BC1_UNORM; + desc.Width = x.width; + desc.Height = x.height; + desc.SampleDesc.Count = 1; + desc.DepthOrArraySize = UINT16(x.depth_or_array); + desc.MipLevels = UINT16(x.mips); + leonida::title_xg_layouts::note({UINT(desc.Dimension), UINT(desc.Format), desc.Height, + desc.DepthOrArraySize, desc.MipLevels, desc.Width}, x.layout); + GpuReader gpu; + EXPECT(!gpu.init(device, 256)); + Ref texture; + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, desc, 6, IID_PPV_ARGS(&texture.p)), S_OK); + void* mapped = nullptr; + EXPECT_HR(texture->Map(0, nullptr, &mapped), S_OK); + EXPECT(mapped == pages); + std::vector columns; + std::vector> patterns(x.mips * x.depth_or_array); + for (unsigned pass = 1; pass <= 2; ++pass) { + for (unsigned sub = 0; sub < patterns.size(); ++sub) { + const auto level = sub % x.mips; + const auto& mip = tiled.layout.plane[0].mips[level]; + const auto row = mip.width_elements * tiled.format.bytes, bytes = row * mip.height_elements; + auto& pattern = patterns[sub]; + pattern.resize(bytes); + for (unsigned i = 0; i < bytes; ++i) pattern[i] = std::uint8_t(pass * 71 + sub * 13 + i); + rt::xg_xs::copy_elements(tiled, level, sub / x.mips, pattern.data(), pages, row, bytes, columns); + } + ID3D12CommandList* lists[]{gpu.list.p}; + gpu.queue->ExecuteCommandLists(1, lists); + EXPECT_HR(gpu.queue->Signal(gpu.fence.p, pass), S_OK); + EXPECT_HR(gpu.fence->SetEventOnCompletion(pass, gpu.done), S_OK); + EXPECT(WaitForSingleObject(gpu.done, 30000) == WAIT_OBJECT_0); + for (unsigned sub = 0; sub < patterns.size(); ++sub) { + const auto& mip = tiled.layout.plane[0].mips[sub % x.mips]; + std::vector got(patterns[sub].size()); + EXPECT_HR(texture->ReadFromSubresource(got.data(), mip.width_elements * tiled.format.bytes, + UINT(got.size()), sub, nullptr), S_OK); + EXPECT(got == patterns[sub]); + } + } + texture->Unmap(0, nullptr); + texture.p->Release(); + texture.p = nullptr; + VirtualFree(pages, 0, MEM_RELEASE); + return 0; +} + void print_cases(const std::vector& cases, const char* who) { for (const Case& c : cases) std::printf("%s: %-44s hr=0x%08lX size=%llu align=%llu type=%d cpu=%d pool=%d flags=0x%x\n", who, c.name, @@ -332,6 +1870,8 @@ void print_cases(const std::vector& cases, const char* who) { } // namespace int main() { + _putenv_s("LEONIDA_TITLE_TEXTURE_PERIOD_MS", "0"); + _putenv_s("LEONIDA_TITLE_TEXTURE_CHECK_KB", "0"); vktest::Device vk; const auto status = vk.initialize(); if (status == vktest::DeviceStatus::unavailable) return 77; @@ -347,12 +1887,36 @@ int main() { info.queue = vk.queue; info.queue_family = vk.family; info.host_pointer_alignment = vk.host_pointer_alignment; + info.host_image_copy = vk.host_image_copy; + info.bindless = vk.bindless; + info.bindless_partially_bound = vk.partially_bound; if (FAILED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&ours.p)))) return 1; failures += check(ours.p, "vulkan"); const std::vector vulkan_cases = open_cases(ours.p); print_cases(vulkan_cases, "vulkan"); failures += check_import(ours.p, vk.host_pointer_alignment != 0); + failures += check_placed_target_backing(ours.p); if (vk.host_pointer_alignment) failures += check_title_placed_all(ours.p); + if (vk.host_image_copy) { + failures += check_pending_stream_views(ours.p); + failures += check_shared_bc_placements(ours.p); + failures += check_mapped_plane(ours.p); + failures += check_mapped_bc_array(ours.p); + } + failures += check_written_pages_all(ours.p); + { + // A second device over the same Vulkan device: its shadows are trackers of their own. + Ref second; + if (FAILED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&second.p)))) second.p = nullptr; + // LEONIDA_WRITE_WATCH=0 (the d3d12_existing_heap_no_write_watch test): xmem records nothing, and only the + // guarded cases run. + if (leonida::title_write_watch::enabled()) { + for (const DWORD modifier : {DWORD(0), DWORD(PAGE_WRITECOMBINE)}) + failures += check_write_watched(ours.p, second.p, modifier); + failures += check_rereserved(ours.p); + } + } + failures += check_heap_lock_faults(ours.p); Ref factory; if (!hostwine::host_is_wine() && SUCCEEDED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p)))) { for (const bool warp : {false, true}) { diff --git a/runtime/test/d3d12_f16_halves_test.cpp b/runtime/test/d3d12_f16_halves_test.cpp index c2f194e31b..bbd516e5c5 100644 --- a/runtime/test/d3d12_f16_halves_test.cpp +++ b/runtime/test/d3d12_f16_halves_test.cpp @@ -222,7 +222,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); + reinterpret_cast(&device.p), /*console_lists=*/false))); rt::d3d12::set_device_outer(inner, device.p); D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; diff --git a/runtime/test/d3d12_first_light_test.cpp b/runtime/test/d3d12_first_light_test.cpp index 8dcc2ca9c3..c5aea7fd59 100644 --- a/runtime/test/d3d12_first_light_test.cpp +++ b/runtime/test/d3d12_first_light_test.cpp @@ -134,7 +134,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); + reinterpret_cast(&device.p), /*console_lists=*/false))); rt::d3d12::set_device_outer(inner, device.p); // No root parameters: the VS applies no matrix and the PS has no bindings (vk_harness pushes zeros too). diff --git a/runtime/test/d3d12_fspx_compute_test.cpp b/runtime/test/d3d12_fspx_compute_test.cpp index f07b9eea5a..cf047a0927 100644 --- a/runtime/test/d3d12_fspx_compute_test.cpp +++ b/runtime/test/d3d12_fspx_compute_test.cpp @@ -281,7 +281,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); + reinterpret_cast(&device.p), /*console_lists=*/false))); rt::d3d12::set_device_outer(inner, device.p); if (rt::d3d12::device_push_constants_need_fallback(inner)) { std::printf("d3d12_fspx_compute_test: skipped, the PSOs need 144 push-constant bytes and this GPU has %u\n", @@ -345,6 +345,18 @@ int main() { pso_desc.CS = {code_c.data(), code_c.size()}; EXPECT(device->CreateComputePipelineState(&pso_desc, IID_PPV_ARGS(&none_bare.p)) == E_INVALIDARG && !none_bare.p); + + // LEONIDA_STUB_PIPELINES=1 stubs only a missing translation: the unknown kind-0 state becomes a stub, + // while the ambiguous bare program, whose translations exist, is still refused. + EXPECT(SetEnvironmentVariableW(L"LEONIDA_STUB_PIPELINES", L"1")); + Ref stub_other, still_bare; + pso_desc.CS = {c_other.data(), c_other.size()}; + const HRESULT stub_hr = device->CreateComputePipelineState(&pso_desc, IID_PPV_ARGS(&stub_other.p)); + pso_desc.CS = {code_c.data(), code_c.size()}; + const HRESULT bare_hr = device->CreateComputePipelineState(&pso_desc, IID_PPV_ARGS(&still_bare.p)); + SetEnvironmentVariableW(L"LEONIDA_STUB_PIPELINES", nullptr); + EXPECT(stub_hr == S_OK && stub_other.p); + EXPECT(bare_hr == E_INVALIDARG && !still_bare.p); } // Slot 67 with all four pairs (RT-99): the proxy passes kind 0 on, so program C resolves by its state there diff --git a/runtime/test/d3d12_geometry_test.cpp b/runtime/test/d3d12_geometry_test.cpp index 6d8bb59571..1cfe035b76 100644 --- a/runtime/test/d3d12_geometry_test.cpp +++ b/runtime/test/d3d12_geometry_test.cpp @@ -91,7 +91,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); + reinterpret_cast(&device.p), /*console_lists=*/false))); rt::d3d12::set_device_outer(inner, device.p); D3D12_ROOT_PARAMETER params[2] = {}; diff --git a/runtime/test/d3d12_graphics_direct_heaps_test.cpp b/runtime/test/d3d12_graphics_direct_heaps_test.cpp new file mode 100644 index 0000000000..b09cbc3b63 --- /dev/null +++ b/runtime/test/d3d12_graphics_direct_heaps_test.cpp @@ -0,0 +1,310 @@ +// Directly indexed descriptor heaps for graphics draws, through the Xbox-ABI proxy over the Vulkan device. +// +// A root signature with CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED and/or SAMPLER_HEAP_DIRECTLY_INDEXED gives the console's +// vertex and pixel shaders the bound heaps' 32-bit shader VAs in the user-data dwords right after the explicit root +// arguments (from s8, one dword per table): resource heap first, then sampler heap. The vertex and pixel shaders here +// (test/glsl/vs_user_data_window.vert, ps_user_data_window.frag) both read s10..s13 and write what they saw to two +// UINT render targets, one pixel per draw: +// 0. three constants (s8..s10), both flags: s10 = constant, s11 = resource heap, s12 = sampler heap; +// 1. the same signature without the flags: s11..s13 stay 0; +// 2. a table (s8) and three constants (s9..s11): s12 = resource heap, s13 = sampler heap; +// 3. three constants, the sampler flag alone: s11 = sampler heap; +// 4. as 0 after SetDescriptorHeaps with the resource heap alone: the sampler heap's dword is 0 for that draw only +// (each draw snapshots the heaps, as a dispatch does). +// The recorded Draw commands are checked too. With --off (ctest d3d12_graphics_direct_heaps_off sets +// LEONIDA_GRAPHICS_DIRECT_HEAPS=0) no draw gets a heap dword. No game data. +// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. +#include "shader_fixture_path.h" +#include "test_temp_dir.h" +#include "vk_test_device.h" +#include "d3d12_test_shaders.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" +#include "../src/shader_library.h" + +#include +#include +#include +#include +#include +#include + +#if !defined(LEONIDA_TEST_VS_SPV) || !defined(LEONIDA_TEST_PS_SPV) +#error "LEONIDA_TEST_VS_SPV and LEONIDA_TEST_PS_SPV must name the compiled test shaders" +#endif + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +using namespace d3d12test; +using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slots 9/10: CPU/GPU handle in RAX + +int main(int argc, char** argv) { + const bool off = argc == 2 && std::strcmp(argv[1], "--off") == 0; + if (off) { + const char* v = std::getenv("LEONIDA_GRAPHICS_DIRECT_HEAPS"); + EXPECT(v && std::strcmp(v, "0") == 0); + } + vktest::Device d; + const auto device_status = d.initialize(); + if (device_status == vktest::DeviceStatus::unavailable) { + std::fprintf(stderr, "SKIP: no usable Vulkan 1.3 device\n"); + return 77; + } + EXPECT(device_status == vktest::DeviceStatus::ready); + + const auto vs_program = fssm_program({0x56530011, 0xbf810000}); + const auto ps_program = fssm_program({0x50530011, 0xbf810000}); + const auto vs_container = shader_container(vs_program), ps_container = shader_container(ps_program); + const testfiles::ScratchDir scratch("leonida_graphics_direct_heaps_test"); + const auto& library = scratch.path(); + EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_VS_SPV), library / "vs_user_data_window.spv")); + EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_PS_SPV), library / "ps_user_data_window.spv")); + { + std::ofstream index(library / "index.json", std::ios::binary); + index << "{\"vs_user_data_window\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_program) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"input_signature\": []},\n" + " \"ps_user_data_window\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(ps_program) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"outputs\": [0, 1]}}"; + } + + constexpr UINT draws = 5; + constexpr UINT pixel_bytes = 16; // R32G32B32A32_UINT + std::array, draws> vs_seen{}, ps_seen{}, want{}; + { + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = d.instance_proc; + info.instance = d.instance; + info.physical = d.physical; + info.device = d.device; + info.queue = d.queue; + info.queue_family = d.family; + info.buffer_device_address = true; + info.subgroup = d.subgroup; + info.shader_dir = library.string(); + ID3D12Device* inner = nullptr; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); + Ref device; + EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), + reinterpret_cast(&device.p), /*console_lists=*/false))); + rt::d3d12::set_device_outer(inner, device.p); + + // The shader-visible heaps whose VAs the draws receive. + const D3D12_DESCRIPTOR_HEAP_DESC resource_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 8, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + const D3D12_DESCRIPTOR_HEAP_DESC sampler_desc{D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 8, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + Ref resources, samplers; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&resource_desc, IID_PPV_ARGS(&resources.p)))); + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&sampler_desc, IID_PPV_ARGS(&samplers.p)))); + const std::uint64_t res = reinterpret_cast(slot(resources.p, 10))(resources.p); + const std::uint64_t smp = reinterpret_cast(slot(samplers.p, 10))(samplers.p); + EXPECT(res >= 0x10000 && res < (1ull << 32) && smp >= 0x10000 && smp < (1ull << 32) && res != smp); + + // Root signatures: three constants (s8..s10), or a table (s8) and three constants (s9..s11). + D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; + D3D12_ROOT_PARAMETER three[1] = {}; + three[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + three[0].Constants = {0, 0, 3}; + D3D12_ROOT_PARAMETER table_first[2] = {}; + table_first[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + table_first[0].DescriptorTable = {1, &range}; + table_first[1] = three[0]; + constexpr auto both = D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED | + D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED; + const auto make_root = [&](const D3D12_ROOT_PARAMETER* params, UINT count, D3D12_ROOT_SIGNATURE_FLAGS flags, + Ref& out) { + D3D12_VERSIONED_ROOT_SIGNATURE_DESC desc{}; + desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + desc.Desc_1_0 = {count, params, 0, nullptr, flags}; + const auto blob = serialize_root_signature(desc); + return !blob.empty() && + SUCCEEDED(device->CreateRootSignature(0, blob.data(), blob.size(), IID_PPV_ARGS(&out.p))); + }; + Ref three_both, three_none, table_both, three_sampler; + EXPECT(make_root(three, 1, both, three_both)); + EXPECT(make_root(three, 1, D3D12_ROOT_SIGNATURE_FLAG_NONE, three_none)); + EXPECT(make_root(table_first, 2, both, table_both)); + EXPECT(make_root(three, 1, D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED, three_sampler)); + + D3D12_GRAPHICS_PIPELINE_STATE_DESC pso_desc{}; + pso_desc.VS = {vs_container.data(), vs_container.size()}; + pso_desc.PS = {ps_container.data(), ps_container.size()}; + pso_desc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + pso_desc.BlendState.RenderTarget[1].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + pso_desc.SampleMask = 0xffffffff; + pso_desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + pso_desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + pso_desc.RasterizerState.DepthClipEnable = TRUE; + pso_desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + pso_desc.NumRenderTargets = 2; + pso_desc.RTVFormats[0] = pso_desc.RTVFormats[1] = DXGI_FORMAT_R32G32B32A32_UINT; + pso_desc.SampleDesc.Count = 1; + const auto make_pso = [&](ID3D12RootSignature* root, Ref& out) { + auto desc = pso_desc; + desc.pRootSignature = root; + return SUCCEEDED(device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&out.p))); + }; + Ref pso_three_both, pso_three_none, pso_table_both, pso_three_sampler; + EXPECT(make_pso(three_both.p, pso_three_both)); + EXPECT(make_pso(three_none.p, pso_three_none)); + EXPECT(make_pso(table_both.p, pso_table_both)); + EXPECT(make_pso(three_sampler.p, pso_three_sampler)); + + // Two 5x1 UINT targets (what the VS saw, what the PS saw) and their RTVs. + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; + D3D12_RESOURCE_DESC rt_desc{}; + rt_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + rt_desc.Width = draws; + rt_desc.Height = 1; + rt_desc.DepthOrArraySize = 1; + rt_desc.MipLevels = 1; + rt_desc.Format = DXGI_FORMAT_R32G32B32A32_UINT; + rt_desc.SampleDesc.Count = 1; + rt_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + std::array, 2> targets; + std::array, 2> rtv_heaps; + std::array rtvs{}; + const D3D12_DESCRIPTOR_HEAP_DESC rtv_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, + 0}; + for (std::size_t t = 0; t < targets.size(); ++t) { + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &rt_desc, + D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr, + IID_PPV_ARGS(&targets[t].p)))); + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&rtv_desc, IID_PPV_ARGS(&rtv_heaps[t].p)))); + rtvs[t] = {SIZE_T(reinterpret_cast(slot(rtv_heaps[t].p, 9))(rtv_heaps[t].p))}; + device->CreateRenderTargetView(targets[t].p, nullptr, rtvs[t]); + } + Ref readback; + const auto readback_desc = buffer_desc(1024); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback.p)))); + + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + Ref queue; + Ref allocator; + Ref list; + Ref fence; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, + pso_three_both.p, IID_PPV_ARGS(&list.p)))); + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + + const FLOAT seven[4] = {7, 7, 7, 7}; // a pixel no draw reached reads 7s + for (const auto& rtv : rtvs) list->ClearRenderTargetView(rtv, seven, 0, nullptr); + list->OMSetRenderTargets(2, rtvs.data(), FALSE, nullptr); + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + const D3D12_RECT scissor{0, 0, LONG(draws), 1}; + list->RSSetScissorRects(1, &scissor); + ID3D12DescriptorHeap* both_heaps[] = {resources.p, samplers.p}; + list->SetDescriptorHeaps(2, both_heaps); + const std::uint32_t r = off ? 0 : std::uint32_t(res), s = off ? 0 : std::uint32_t(smp); + const UINT a[3] = {0xA0, 0xA1, 0xA2}, b[3] = {0xB0, 0xB1, 0xB2}; + const auto draw_at = [&](UINT pixel, ID3D12PipelineState* pso, ID3D12RootSignature* root, bool table) { + const D3D12_VIEWPORT viewport{float(pixel), 0, 1, 1, 0, 1}; + list->RSSetViewports(1, &viewport); + list->SetPipelineState(pso); + list->SetGraphicsRootSignature(root); + if (table) { + list->SetGraphicsRootDescriptorTable(0, {res}); + list->SetGraphicsRoot32BitConstants(1, 3, b, 0); + } else { + list->SetGraphicsRoot32BitConstants(0, 3, a, 0); + } + list->DrawInstanced(3, 1, 0, 0); + }; + draw_at(0, pso_three_both.p, three_both.p, false); + want[0] = {0xA2, r, s, 0}; + draw_at(1, pso_three_none.p, three_none.p, false); + want[1] = {0xA2, 0, 0, 0}; + draw_at(2, pso_table_both.p, table_both.p, true); + want[2] = {0xB1, 0xB2, r, s}; + draw_at(3, pso_three_sampler.p, three_sampler.p, false); + want[3] = {0xA2, s, 0, 0}; + list->SetDescriptorHeaps(1, &resources.p); // the sampler heap is unbound for the next draw + draw_at(4, pso_three_both.p, three_both.p, false); + want[4] = {0xA2, r, 0, 0}; + + for (std::size_t t = 0; t < targets.size(); ++t) { + const auto to_copy = transition(targets[t].p, D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &to_copy); + D3D12_TEXTURE_COPY_LOCATION dst{}; + dst.pResource = readback.p; + dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst.PlacedFootprint = {512 * t, {DXGI_FORMAT_R32G32B32A32_UINT, draws, 1, 1, 256}}; + D3D12_TEXTURE_COPY_LOCATION src{}; + src.pResource = targets[t].p; + src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + } + EXPECT(list->Close() == S_OK); + + // The recorded draws carry the same words, snapshotted per draw. + std::vector commands; + EXPECT(rt::d3d12::recorded_commands(list.p, commands)); + UINT recorded = 0; + for (const auto& command : commands) { + const auto* draw = std::get_if(&command); + if (!draw) continue; + EXPECT(recorded < draws); + const auto& w = want[recorded++]; + for (UINT k = 0; k < 4; ++k) EXPECT(draw->user_data[10 + k] == w[k]); + for (UINT k = 14; k < draw->user_data.size(); ++k) EXPECT(draw->user_data[k] == 0); + } + EXPECT(recorded == draws); + + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); + EXPECT(SUCCEEDED(queue->Signal(fence.p, 1))); + EXPECT(SUCCEEDED(fence->SetEventOnCompletion(1, nullptr))); + void* mapped = nullptr; + EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); + const auto* bytes = static_cast(mapped); + for (UINT pixel = 0; pixel < draws; ++pixel) { + std::memcpy(vs_seen[pixel].data(), bytes + pixel * pixel_bytes, pixel_bytes); + std::memcpy(ps_seen[pixel].data(), bytes + 512 + pixel * pixel_bytes, pixel_bytes); + } + readback->Unmap(0, nullptr); + + for (auto* p : {&pso_three_both, &pso_three_none, &pso_table_both, &pso_three_sampler}) p->reset(); + for (auto* p : {&three_both, &three_none, &table_both, &three_sampler}) p->reset(); + for (auto& t : targets) t.reset(); + for (auto& h : rtv_heaps) h.reset(); + readback.reset(); + resources.reset(); + samplers.reset(); + list.reset(); + allocator.reset(); + queue.reset(); + fence.reset(); + EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); + } + + unsigned mismatches = 0; + for (UINT pixel = 0; pixel < draws; ++pixel) { + for (const auto* seen : {&vs_seen, &ps_seen}) { + const auto& got = (*seen)[pixel]; + if (got == want[pixel]) continue; + ++mismatches; + std::fprintf(stderr, "draw %u %s s10..s13: got %08x %08x %08x %08x want %08x %08x %08x %08x\n", pixel, + seen == &vs_seen ? "VS" : "PS", got[0], got[1], got[2], got[3], want[pixel][0], + want[pixel][1], want[pixel][2], want[pixel][3]); + } + } + EXPECT(!mismatches); + if (d.validation_errors()) { + std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); + return 1; + } + std::printf("graphics direct heaps%s: %u draws, the VS and PS read s10..s13 as recorded (heap dwords after the " + "explicit arguments at s11/s12 or s12/s13, sampler alone at s11, none without the flags, per-draw " + "snapshot)\n", + off ? " (LEONIDA_GRAPHICS_DIRECT_HEAPS=0: none supplied)" : "", draws); + return 0; +} diff --git a/runtime/test/d3d12_m2_formats_test.cpp b/runtime/test/d3d12_m2_formats_test.cpp index 8730c511df..a9481b29ce 100644 --- a/runtime/test/d3d12_m2_formats_test.cpp +++ b/runtime/test/d3d12_m2_formats_test.cpp @@ -219,11 +219,11 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); + reinterpret_cast(&device.p), /*console_lists=*/false))); rt::d3d12::set_device_outer(inner, device.p); EXPECT(rt::d3d12::bindless_set(device.p) != VK_NULL_HANDLE); - // Root signature: [0] a table of one SRV (s0:s1), [1] a table of one sampler (s2:s3), as in the M2 test. + // Root signature: [0] a table of one SRV (s8), [1] a table of one sampler (s9), as in the M2 test. D3D12_DESCRIPTOR_RANGE srv_range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; D3D12_DESCRIPTOR_RANGE sampler_range{D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, 1, 0, 0, 0}; D3D12_ROOT_PARAMETER params[2] = {}; diff --git a/runtime/test/d3d12_m2_textured_test.cpp b/runtime/test/d3d12_m2_textured_test.cpp index f5734e7544..7b464649cf 100644 --- a/runtime/test/d3d12_m2_textured_test.cpp +++ b/runtime/test/d3d12_m2_textured_test.cpp @@ -6,7 +6,7 @@ // with a POINT filter (the 16-byte S#); // - a root signature of two descriptor tables, [0] one SRV and [1] one sampler, and SetDescriptorHeaps, // SetGraphicsRootDescriptorTable and DrawIndexedInstanced of a quad (a vertex-index-driven vs_m2.asm, six indices). -// test/shaders/ps_m2.asm s_loads the T# from the table in s[0:1] and the S# from the table in s[2:3] and image_samples +// test/shaders/ps_m2.asm s_loads the T# from the table in s8 and the S# from the table in s9 and image_samples // with them; the translated shader hashes both and finds their bindless indices in the descriptor hash table (set 0, // binding 2), so the pipeline layout holds set 0 and every draw binds it. The PSO is found by the SHA-256 of the FSSM // program in the DXBC container, as in the M1.5 test. @@ -143,11 +143,11 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); + reinterpret_cast(&device.p), /*console_lists=*/false))); rt::d3d12::set_device_outer(inner, device.p); EXPECT(rt::d3d12::bindless_set(device.p) != VK_NULL_HANDLE); - // Root signature: [0] a table of one SRV (s0:s1), [1] a table of one sampler (s2:s3). + // Root signature: [0] a table of one SRV (s8), [1] a table of one sampler (s9): the console's graphics layout. D3D12_DESCRIPTOR_RANGE srv_range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; D3D12_DESCRIPTOR_RANGE sampler_range{D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, 1, 0, 0, 0}; D3D12_ROOT_PARAMETER params[2] = {}; @@ -186,7 +186,7 @@ int main() { indexed_params[0].DescriptorTable = {1, &indexed_range}; indexed_params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; indexed_params[2].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; - indexed_params[2].Constants = {0, 0, 2}; // s4 = SRV index, s5 = SRV stride in bytes + indexed_params[2].Constants = {0, 0, 2}; // s10 = SRV index, s11 = SRV stride in bytes D3D12_VERSIONED_ROOT_SIGNATURE_DESC indexed_desc = root_desc; indexed_desc.Desc_1_0.NumParameters = 3; indexed_desc.Desc_1_0.pParameters = indexed_params; diff --git a/runtime/test/d3d12_m3_frame_test.cpp b/runtime/test/d3d12_m3_frame_test.cpp index bbf8b53178..d7cf8e8f34 100644 --- a/runtime/test/d3d12_m3_frame_test.cpp +++ b/runtime/test/d3d12_m3_frame_test.cpp @@ -176,12 +176,12 @@ int main(int argc, char** argv) { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); + reinterpret_cast(&device.p), /*console_lists=*/false))); rt::d3d12::set_device_outer(inner, device.p); EXPECT(rt::d3d12::bindless_set(device.p) != VK_NULL_HANDLE); - // Pass 1: [0] eight 32-bit constants (s0..s7). Pass 2: [0] one SRV (s[0:1]), [1] one sampler (s[2:3]), - // [2] one constant (s4). + // Pass 1: [0] eight 32-bit constants (s8..s15). Pass 2: [0] one SRV (s8), [1] one sampler (s9), + // [2] one constant (s10). The console's graphics layout: from s8, one dword per table. D3D12_ROOT_PARAMETER consts1{}; consts1.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; consts1.Constants = {0, 0, 8}; diff --git a/runtime/test/d3d12_m4_compute_test.cpp b/runtime/test/d3d12_m4_compute_test.cpp index c50a63b042..bad8ed98ef 100644 --- a/runtime/test/d3d12_m4_compute_test.cpp +++ b/runtime/test/d3d12_m4_compute_test.cpp @@ -134,7 +134,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); + reinterpret_cast(&device.p), /*console_lists=*/false))); rt::d3d12::set_device_outer(inner, device.p); EXPECT(rt::d3d12::bindless_set(device.p) != VK_NULL_HANDLE); diff --git a/runtime/test/d3d12_mesh_test.cpp b/runtime/test/d3d12_mesh_test.cpp index aae2fb1623..30ccdaded6 100644 --- a/runtime/test/d3d12_mesh_test.cpp +++ b/runtime/test/d3d12_mesh_test.cpp @@ -20,8 +20,10 @@ #include "d3d12_test_shaders.h" #include "../shims/d3d12_com.h" #include "../shims/d3d12_xs_device.h" +#include "../shims/d3d12_xs_pso_stream.h" #include "../src/shader_library.h" +#include #include #include @@ -97,7 +99,10 @@ D3D12_MESH_SHADER_TIER mesh_tier(ID3D12Device* device) { } // namespace -int main() { +int main(int argc, char** argv) { + const bool pc_only = argc == 2 && std::string_view(argv[1]) == "--pc-stream-only"; + EXPECT(argc == 1 || pc_only); + EXPECT(SetEnvironmentVariableW(L"LEONIDA_XS_STREAM_ENUM", pc_only ? L"0" : L"1")); vktest::Device d; d.request_mesh_shader = true; const auto device_status = d.initialize(); @@ -110,7 +115,10 @@ int main() { const auto ms_program = fssm_program({0x4d530001, 0xbf810000}); const auto ps_program = fssm_program({0x50530001, 0xbf810000}); const auto vs_program = fssm_program({0x56530002, 0xbf810000}); - const auto ms_container = shader_container(ms_program), ps_container = shader_container(ps_program); + auto ms_container = shader_container(ms_program); + const auto ps_container = shader_container(ps_program); + // The synthetic container has one part at 36, followed by its eight-byte header. + ms_container[36 + 8 + 2] = 13; // DXIL mesh shader kind const auto vs_container = shader_container(vs_program); const auto library = std::filesystem::temp_directory_path() / "leonida_mesh_test"; std::filesystem::create_directories(library); @@ -154,15 +162,18 @@ int main() { return true; }; const auto root_signature = [&](ID3D12Device* device, Ref& root) { - // [0] two constants (s0, s1: offset), [1] a root CBV (s2:s3: tint), as in d3d12_draw_test. - D3D12_ROOT_PARAMETER params[2] = {}; + // The mesh fixture reads s0:s1 (offset) and the colour fixture, built as ps_draw_s0.spv, s2:s3 (tint VA). + // Select the runtime's packed s0 layout by declaring 25 words: one more than fits above s8. + D3D12_ROOT_PARAMETER params[3] = {}; params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; params[0].Constants = {0, 0, 2}; params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; params[1].Descriptor = {1, 0}; + params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[2].Constants = {2, 0, 21}; D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; - root_desc.Desc_1_0 = {2, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + root_desc.Desc_1_0 = {3, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; const auto blob = serialize_root_signature(root_desc); return !blob.empty() && SUCCEEDED(device->CreateRootSignature(0, blob.data(), blob.size(), IID_PPV_ARGS(&root.p))); @@ -277,6 +288,53 @@ int main() { bad.add(DepthStencil1Subobject{.inner = bounds}); EXPECT(create(device.p, bad, refused) == E_NOTIMPL && !refused.p); + // A console stream: its numbering has no gap at 23, so its mesh shader is 24 (the PC's AS) and its + // RASTERIZER1 26 (the PC's DEPTH_STENCIL2). An AS without an MS is no PC stream, so the layer reads it with the + // console's numbering and makes the mesh PSO. The PC reading of the same bytes alone would refuse it. + D3D12_RASTERIZER_DESC1 raster1{}; + raster1.FillMode = D3D12_FILL_MODE_SOLID; + raster1.CullMode = D3D12_CULL_MODE_NONE; + raster1.DepthClipEnable = TRUE; + for (int with_raster1 = 0; with_raster1 < 2; ++with_raster1) { + Stream console; + console.add(RootSubobject{.inner = root.p}); + console.add(Subobject{.inner = ms}); + console.add(PsSubobject{.inner = ps}).add(TargetsSubobject{.inner = one_target()}); + if (with_raster1) + console.add(Subobject{.inner = raster1}); + console.add(MaskSubobject{.inner = UINT_MAX}); + Ref console_pso; + using Create = HRESULT(WINAPI*)(ID3D12Device*, const D3D12_PIPELINE_STATE_STREAM_DESC*, REFIID, void**); + const auto desc = console.desc(); + const HRESULT console_hr = reinterpret_cast(slot(device.p, 86))(device.p, &desc, IID_PPV_ARGS(&console_pso.p)); + if (pc_only) { + EXPECT(FAILED(console_hr) && !console_pso.p); + } else { + EXPECT(SUCCEEDED(console_hr) && console_pso.p); + // Slot 55 must also walk raw 26 as RASTERIZER1 and retain the mesh bytecode after the base is released. + using Derive = HRESULT(WINAPI*)(ID3D12Device*, ID3D12PipelineState*, UINT, const void*, REFIID, void**); + std::array record{}; + const std::uint32_t mask[] = {3, UINT_MAX}; + std::memcpy(record.data(), mask, sizeof(mask)); + mesh_pso.reset(); + EXPECT(SUCCEEDED(reinterpret_cast(slot(device.p, 55))( + device.p, console_pso.p, 1, record.data(), IID_PPV_ARGS(&mesh_pso.p))) && mesh_pso.p); + } + } + // Even a known mesh FSSM must not reinterpret type 24 if the container declares another stage. + auto as_container = ms_container; + as_container[36 + 8 + 2] = 14; // amplification + Stream as_only; + as_only.add(RootSubobject{.inner = root.p}) + .add(AsSubobject{.inner = {as_container.data(), as_container.size()}}) + .add(PsSubobject{.inner = ps}).add(TargetsSubobject{.inner = one_target()}); + EXPECT(FAILED(create(device.p, as_only, refused)) && !refused.p); + // An MS and an AS in PC numbering stay the PC's (and refused, the layer builds no AS). + bad = mesh_stream; + bad.add(Subobject{.inner = ms}); + EXPECT(create(device.p, bad, refused) == E_NOTIMPL && !refused.p); + std::printf("console-numbered mesh streams: %s\n", pc_only ? "refused in PC-only mode" : "both created"); + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}; const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; diff --git a/runtime/test/d3d12_msaa_draw_test.cpp b/runtime/test/d3d12_msaa_draw_test.cpp index 5017a01a3d..3437fe0301 100644 --- a/runtime/test/d3d12_msaa_draw_test.cpp +++ b/runtime/test/d3d12_msaa_draw_test.cpp @@ -88,7 +88,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); + reinterpret_cast(&device.p), /*console_lists=*/false))); rt::d3d12::set_device_outer(inner, device.p); if (rt::d3d12::device_push_constants_need_fallback(inner)) { std::printf("d3d12_msaa_draw_test: skipped, the PSOs need 144 push-constant bytes and this GPU has %u\n", diff --git a/runtime/test/d3d12_present_test.cpp b/runtime/test/d3d12_present_test.cpp index 5c626ea80b..b94e958522 100644 --- a/runtime/test/d3d12_present_test.cpp +++ b/runtime/test/d3d12_present_test.cpp @@ -376,7 +376,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); + reinterpret_cast(&device.p), /*console_lists=*/false))); rt::d3d12::set_device_outer(inner, device.p); auto presenter = rt::d3d12::create_window_presenter(inner, window); EXPECT(presenter); diff --git a/runtime/test/d3d12_r9g9b9e5_uav_test.cpp b/runtime/test/d3d12_r9g9b9e5_uav_test.cpp index 13b3bace56..89bda1d8a4 100644 --- a/runtime/test/d3d12_r9g9b9e5_uav_test.cpp +++ b/runtime/test/d3d12_r9g9b9e5_uav_test.cpp @@ -368,6 +368,16 @@ int main() { const bool native_storage = (e5_props.optimalTilingFeatures & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT) != 0; const bool native_attach = (e5_props.optimalTilingFeatures & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT) != 0; const bool rect_clears_supported = !native_storage || native_attach; + // An R9G9B9E5 texture that allows render targets is created as B10G11R11 when the GPU cannot attach E5B9G9R9 + // natively: the layer's console format stand-ins (fa83b2825) render and store in that format instead, so the host + // accepts the resource and GetResourceAllocationInfo sizes it. + VkFormatProperties b10_props{}; + d.instance_fn("vkGetPhysicalDeviceFormatProperties")( + d.physical, VK_FORMAT_B10G11R11_UFLOAT_PACK32, &b10_props); + const bool target_stand_in = !native_attach && + (b10_props.optimalTilingFeatures & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT) != 0 && + (b10_props.optimalTilingFeatures & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT) != 0 && + (b10_props.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) != 0; { rt::d3d12::VulkanDeviceInfo info{}; @@ -385,6 +395,8 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p)))); // 1. CheckFeatureSupport(FORMAT_SUPPORT): typed UAV is advertised; render target and depth-stencil stay off. + // The render-target bit is the format's own native support: a texture that allows render targets is still + // created where the B10G11R11 stand-in can render it (see the creation loop below). D3D12_FEATURE_DATA_FORMAT_SUPPORT fs{DXGI_FORMAT_R9G9B9E5_SHAREDEXP}; EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &fs, sizeof(fs)))); if (!(fs.Support1 & D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW)) { @@ -465,7 +477,12 @@ int main() { D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS}) { const auto desc = tex_desc(D3D12_RESOURCE_DIMENSION_TEXTURE2D, 16, 16, 1, 1, DXGI_FORMAT_R9G9B9E5_SHAREDEXP, flags); - const bool supported = native_attach && (!(flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) || native_storage); + // Creation follows the backing the layer found, not the format's native bits alone: a render target needs + // a native attachment or the B10G11R11 stand-in, and unordered access needs a storage image or the + // mutable R32_UINT emulation the format support above advertises. + const bool supported = (native_attach || target_stand_in) && + (!(flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) || + (fs.Support1 & D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW) != 0); Ref target; const HRESULT hr = device->CreateCommittedResource(&def_heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&target.p)); diff --git a/runtime/test/d3d12_rect_list_test.cpp b/runtime/test/d3d12_rect_list_test.cpp new file mode 100644 index 0000000000..05b90a81c8 --- /dev/null +++ b/runtime/test/d3d12_rect_list_test.cpp @@ -0,0 +1,341 @@ +// The console's rectangle and quad lists drawn through the D3D12-on-Vulkan layer (src/rect_list_geometry.h). +// +// Built like d3d12_translated_draw_test.cpp, from the same translated vs_m15 / ps_m15 (the VS fetches its vertices +// through a V#; the PS multiplies the colour by (0.5, 2, 1, 1) and adds the bias, 0 here), so the shaders are real +// translator output found by the SHA-256 of their FSSM programs. +// frame 1, rectangle list: PSO topology type 19, IASetPrimitiveTopology(17), DrawInstanced(3). The three corners +// v1 (-1, 1), v2 (1, 1), v3 (-1, -1) cover the top-left, top-right and bottom-left of the 64x64 target; the fourth +// corner, v2 + v3 - v1 = (1, -1) with colour c2 + c3 - c1, is made by the layer. Every pixel must carry the plane +// through the three corner colours; the bottom-right quadrant is only right when the fourth corner is. +// frame 2, quad list: PSO topology type TRIANGLE, IASetPrimitiveTopology(19), DrawInstanced(8): two quads (corners +// in order around the quad), the top-left and bottom-right quadrants, each one colour. These pixels are exact. +// Pixels are read back and compared; the other two quadrants of frame 2 stay the clear colour. LEONIDA_VK_VALIDATION=1 +// runs it under the validation layer. +#include "vk_test_device.h" +#include "d3d12_test_shaders.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" +#include "../src/gfx10_descriptors.h" +#include "../src/shader_library.h" + +#include +#include +#include +#include +#include +#include + +#ifndef LEONIDA_TEST_M15_DIR +#error "LEONIDA_TEST_M15_DIR must name the folder build.py wrote (spirv/index.json, fssm/*.fssm)" +#endif + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +using namespace d3d12test; +using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slots 9/10: handle in RAX + +namespace { + +std::vector read_file(const std::filesystem::path& path) { + std::ifstream in(path, std::ios::binary); + return {std::istreambuf_iterator(in), std::istreambuf_iterator()}; +} + +struct Vertex { // 32 bytes, as vs_m15.asm reads it + float position[4]; + float color[4]; +}; + +using Pixel = std::array; +constexpr UINT target_extent = 64; +constexpr UINT pitch = target_extent * sizeof(Pixel); +constexpr D3D_PRIMITIVE_TOPOLOGY rect_list = D3D_PRIMITIVE_TOPOLOGY(17), quad_list = D3D_PRIMITIVE_TOPOLOGY(19); +const std::uint32_t rect_type_value = 19; // not an enumerator of D3D12_PRIMITIVE_TOPOLOGY_TYPE + +std::array make_vsharp(std::uint64_t base, std::uint32_t records) { + leonida::gfx10::Buffer buffer; + buffer.address = base; + buffer.stride = 32; + buffer.num_records = records; + buffer.format = 77; // GFX10_FORMAT_32_32_32_32_FLOAT + buffer.oob_select = leonida::gfx10::OobSelect::structured; + return leonida::gfx10::encode(buffer); +} + +Vertex vertex(float x, float y, const float* c) { return Vertex{{x, y, 0.0f, 1.0f}, {c[0], c[1], c[2], c[3]}}; } + +} // namespace + +int main() { + vktest::Device d; + const auto device_status = d.initialize(); + if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips + EXPECT(device_status == vktest::DeviceStatus::ready); + if (!d.enabled.geometryShader) { + std::printf("SKIP: no geometryShader on this GPU\n"); + return 77; + } + const std::filesystem::path root_dir = LEONIDA_TEST_M15_DIR; + const auto vs_program = read_file(root_dir / "fssm" / "vs_m15.fssm"); + const auto ps_program = read_file(root_dir / "fssm" / "ps_m15.fssm"); + EXPECT(vs_program.size() >= 4 && ps_program.size() == 0x110); + const auto vs_container = shader_container(vs_program), ps_container = shader_container(ps_program); + + // Frame 1: the rectangle's three corners. Vertices 0..2. Frame 2: two quads, vertices 3..10. + const float ca[4] = {0.0f, 0.0f, 0.0f, 1.0f}, cb[4] = {1.0f, 0.0f, 0.5f, 1.0f}, cc[4] = {0.0f, 0.5f, 1.0f, 1.0f}; + const float q1[4] = {0.25f, 0.5f, 0.75f, 1.0f}, q2[4] = {1.0f, 0.0f, 0.5f, 1.0f}; + const Vertex vertices[11] = {vertex(-1, 1, ca), vertex(1, 1, cb), vertex(-1, -1, cc), + vertex(-1, 1, q1), vertex(0, 1, q1), vertex(0, 0, q1), vertex(-1, 0, q1), + vertex(0, 0, q2), vertex(1, 0, q2), vertex(1, -1, q2), vertex(0, -1, q2)}; + static_assert(sizeof(Vertex) == 32 && sizeof(vertices) == 352); + + std::vector rect_pixels(target_extent * target_extent), quad_pixels(target_extent * target_extent); + { + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = d.instance_proc; + info.instance = d.instance; + info.physical = d.physical; + info.device = d.device; + info.queue = d.queue; + info.queue_family = d.family; + info.buffer_device_address = true; + info.features = d.enabled; // geometryShader: the rectangle stage needs it + info.shader_dir = (root_dir / "spirv").string(); + ID3D12Device* inner = nullptr; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); + Ref device; + EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), + reinterpret_cast(&device.p)))); + rt::d3d12::set_device_outer(inner, device.p); + + D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; + D3D12_ROOT_PARAMETER params[2] = {}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[0].DescriptorTable = {1, &range}; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[1].Constants = {0, 0, 4}; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; + root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + root_desc.Desc_1_0 = {2, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + const auto root_blob = serialize_root_signature(root_desc); + EXPECT(!root_blob.empty()); + Ref root; + EXPECT(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p)))); + + D3D12_GRAPHICS_PIPELINE_STATE_DESC pso_desc{}; + pso_desc.pRootSignature = root.p; + pso_desc.VS = {vs_container.data(), vs_container.size()}; + pso_desc.PS = {ps_container.data(), ps_container.size()}; + pso_desc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + pso_desc.SampleMask = 0xffffffff; + pso_desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + pso_desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + pso_desc.RasterizerState.DepthClipEnable = TRUE; + pso_desc.NumRenderTargets = 1; + pso_desc.RTVFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT; + pso_desc.SampleDesc.Count = 1; + Ref rect_pso, quad_pso; + std::memcpy(&pso_desc.PrimitiveTopologyType, &rect_type_value, sizeof(rect_type_value)); // 19: rectangles + EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&rect_pso.p)))); + pso_desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&quad_pso.p)))); + + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}; + const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; + Ref vertex_buffer, upload, readback, target; + const auto vb_desc = buffer_desc(sizeof(vertices)); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &vb_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&vertex_buffer.p)))); + const auto upload_desc = buffer_desc(1024); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &upload_desc, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + IID_PPV_ARGS(&upload.p)))); + const auto readback_desc = buffer_desc(pitch * target_extent); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback.p)))); + D3D12_RESOURCE_DESC rt_desc{}; + rt_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + rt_desc.Width = rt_desc.Height = target_extent; + rt_desc.DepthOrArraySize = 1; + rt_desc.MipLevels = 1; + rt_desc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; + rt_desc.SampleDesc.Count = 1; + rt_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &rt_desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&target.p)))); + std::uint8_t* up = nullptr; + EXPECT(SUCCEEDED(upload->Map(0, nullptr, reinterpret_cast(&up)))); + std::memcpy(up, vertices, sizeof(vertices)); + + // Two V#s over the one vertex buffer: slot 0 the rectangle's three corners, slot 1 the eight quad corners. + const D3D12_DESCRIPTOR_HEAP_DESC srv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 2, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + Ref srv_heap; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&srv_heap_desc, IID_PPV_ARGS(&srv_heap.p)))); + const std::uint64_t cpu = reinterpret_cast(slot(srv_heap.p, 9))(srv_heap.p); + const std::uint64_t gpu = reinterpret_cast(slot(srv_heap.p, 10))(srv_heap.p); + const UINT step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + EXPECT(cpu && gpu >= 0x10000 && gpu < (1ull << 32) && step >= 16); + const std::uint64_t buffer_va = vertex_buffer->GetGPUVirtualAddress(); + EXPECT(buffer_va >= 0x10000); + const std::array vsharps[2] = {make_vsharp(buffer_va, 3), + make_vsharp(buffer_va + 3 * sizeof(Vertex), 8)}; + for (unsigned i = 0; i < 2; ++i) + std::memcpy(reinterpret_cast(cpu + std::uint64_t(i) * step), vsharps[i].data(), 16); + + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + Ref rtv_heap; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&rtv_heap.p)))); + const D3D12_CPU_DESCRIPTOR_HANDLE rtv{ + SIZE_T(reinterpret_cast(slot(rtv_heap.p, 9))(rtv_heap.p))}; + device->CreateRenderTargetView(target.p, nullptr, rtv); + + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + Ref queue; + Ref allocator; + Ref list; + Ref fence; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, rect_pso.p, + IID_PPV_ARGS(&list.p)))); + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + + list->CopyBufferRegion(vertex_buffer.p, 0, upload.p, 0, sizeof(vertices)); + D3D12_RESOURCE_BARRIER barriers[2] = { + transition(vertex_buffer.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE), + transition(target.p, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_RENDER_TARGET)}; + list->ResourceBarrier(2, barriers); + + const auto render_frame = [&](UINT64 frame, ID3D12PipelineState* pso, D3D_PRIMITIVE_TOPOLOGY topology, + unsigned vsharp_slot, UINT vertex_count, std::vector& out) -> int { + if (frame > 1) { + EXPECT(SUCCEEDED(allocator->Reset())); + EXPECT(SUCCEEDED(list->Reset(allocator.p, pso))); + auto to_target = transition(target.p, D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_RENDER_TARGET); + list->ResourceBarrier(1, &to_target); + } else { + list->SetPipelineState(pso); + } + const FLOAT clear[4] = {0.5f, 0.125f, 0.25f, 0.5f}; + list->ClearRenderTargetView(rtv, clear, 0, nullptr); + list->SetGraphicsRootSignature(root.p); + ID3D12DescriptorHeap* heaps[] = {srv_heap.p}; + list->SetDescriptorHeaps(1, heaps); + list->IASetPrimitiveTopology(topology); + const D3D12_VIEWPORT viewport{0, 0, float(target_extent), float(target_extent), 0, 1}; + const D3D12_RECT scissor{0, 0, LONG(target_extent), LONG(target_extent)}; + list->RSSetViewports(1, &viewport); + list->RSSetScissorRects(1, &scissor); + list->OMSetRenderTargets(1, &rtv, FALSE, nullptr); + const float constants[4] = {0, 0, 0, 0}; // no offset, no bias + list->SetGraphicsRootDescriptorTable(0, D3D12_GPU_DESCRIPTOR_HANDLE{gpu + std::uint64_t(vsharp_slot) * step}); + list->SetGraphicsRoot32BitConstants(1, 4, constants, 0); + list->DrawInstanced(vertex_count, 1, 0, 0); + D3D12_RESOURCE_BARRIER to_copy = transition(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &to_copy); + D3D12_TEXTURE_COPY_LOCATION dst{}; + dst.pResource = readback.p; + dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst.PlacedFootprint = {0, {DXGI_FORMAT_R32G32B32A32_FLOAT, target_extent, target_extent, 1, pitch}}; + D3D12_TEXTURE_COPY_LOCATION src{}; + src.pResource = target.p; + src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + EXPECT(list->Close() == S_OK); + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); + EXPECT(SUCCEEDED(queue->Signal(fence.p, frame))); + EXPECT(SUCCEEDED(fence->SetEventOnCompletion(frame, nullptr))); + void* mapped = nullptr; + EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); + std::memcpy(out.data(), mapped, out.size() * sizeof(Pixel)); + readback->Unmap(0, nullptr); + return 0; + }; + EXPECT(render_frame(1, rect_pso.p, rect_list, 0, 3, rect_pixels) == 0); + EXPECT(render_frame(2, quad_pso.p, quad_list, 1, 8, quad_pixels) == 0); + for (auto* r : {&vertex_buffer, &upload, &readback, &target}) r->reset(); + rect_pso.reset(); + quad_pso.reset(); + root.reset(); + srv_heap.reset(); + rtv_heap.reset(); + list.reset(); + allocator.reset(); + queue.reset(); + fence.reset(); + EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); + } + + // Rectangle: the plane through the three corner colours, at each pixel centre, through the PS's scale. + const float scale[4] = {0.5f, 2.0f, 1.0f, 1.0f}; + unsigned covered = 0, off = 0; + float worst = 0.0f; + for (UINT row = 0; row < target_extent; ++row) { + for (UINT col = 0; col < target_extent; ++col) { + const float u = (float(col) + 0.5f) / target_extent, v = (float(row) + 0.5f) / target_extent; + const Pixel& got = rect_pixels[row * target_extent + col]; + bool pixel_ok = true; + for (int c = 0; c < 4; ++c) { + const float want = (ca[c] + u * (cb[c] - ca[c]) + v * (cc[c] - ca[c])) * scale[c]; + const float error = std::fabs(got[c] - want); + worst = std::fmax(worst, error); + if (!(error <= 2e-5f)) pixel_ok = false; + } + covered += pixel_ok; + if (!pixel_ok && off++ < 8) + std::fprintf(stderr, "rect pixel (%u, %u): got %g,%g,%g,%g\n", col, row, got[0], got[1], got[2], got[3]); + } + } + // The four quadrant centres on their own, so a wrong fourth corner is named by quadrant. + const char* names[4] = {"top left", "top right", "bottom left", "bottom right"}; + for (int quadrant = 0; quadrant < 4; ++quadrant) { + const UINT col = (quadrant & 1 ? 48 : 16), row = (quadrant & 2 ? 48 : 16); + const Pixel& got = rect_pixels[row * target_extent + col]; + const float u = (float(col) + 0.5f) / target_extent, v = (float(row) + 0.5f) / target_extent; + for (int c = 0; c < 4; ++c) { + const float want = (ca[c] + u * (cb[c] - ca[c]) + v * (cc[c] - ca[c])) * scale[c]; + if (!(std::fabs(got[c] - want) <= 2e-5f)) { + std::fprintf(stderr, "rect %s quadrant: channel %d got %g want %g\n", names[quadrant], c, got[c], want); + return 1; + } + } + } + EXPECT(covered == target_extent * target_extent); + + // Quad list: whole-bit comparison; two quadrants one colour each, the rest the clear colour. + const Pixel clear_color = {0.5f, 0.125f, 0.25f, 0.5f}; + const Pixel top_left = {q1[0] * scale[0], q1[1] * scale[1], q1[2], q1[3]}; + const Pixel bottom_right = {q2[0] * scale[0], q2[1] * scale[1], q2[2], q2[3]}; + unsigned quad_wrong = 0; + for (UINT row = 0; row < target_extent; ++row) { + for (UINT col = 0; col < target_extent; ++col) { + const bool top = row < target_extent / 2, left = col < target_extent / 2; + const Pixel& want = top && left ? top_left : (!top && !left ? bottom_right : clear_color); + const Pixel& got = quad_pixels[row * target_extent + col]; + if (std::memcmp(&got, &want, sizeof(Pixel)) == 0) continue; + if (quad_wrong++ < 8) + std::fprintf(stderr, "quad pixel (%u, %u): got %g,%g,%g,%g want %g,%g,%g,%g\n", col, row, got[0], got[1], + got[2], got[3], want[0], want[1], want[2], want[3]); + } + } + EXPECT(!quad_wrong); + if (d.validation_errors()) { + std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); + return 1; + } + std::printf("rect list: %u of %u pixels on the colour plane (worst error %g), all four quadrants; quad list: " + "%u of %u pixels exact\n", + covered, target_extent * target_extent, double(worst), target_extent * target_extent - quad_wrong, + target_extent * target_extent); + return 0; +} diff --git a/runtime/test/d3d12_set0_compute_test.cpp b/runtime/test/d3d12_set0_compute_test.cpp index c2dfdfc397..a37f486d72 100644 --- a/runtime/test/d3d12_set0_compute_test.cpp +++ b/runtime/test/d3d12_set0_compute_test.cpp @@ -98,7 +98,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); + reinterpret_cast(&device.p), /*console_lists=*/false))); rt::d3d12::set_device_outer(inner, device.p); if (rt::d3d12::device_push_constants_need_fallback(inner)) { std::printf("d3d12_set0_compute_test: skipped, the PSOs need 144 push-constant bytes and this GPU has %u\n", diff --git a/runtime/test/d3d12_stub_pipelines_test.cpp b/runtime/test/d3d12_stub_pipelines_test.cpp new file mode 100644 index 0000000000..ebe3d8aae6 --- /dev/null +++ b/runtime/test/d3d12_stub_pipelines_test.cpp @@ -0,0 +1,88 @@ +// LEONIDA_STUB_PIPELINES (diagnostic): a pipeline whose translated shader is missing is created as a no-op stub +// instead of failing. Without the switch, a graphics PSO with no shader library is E_FAIL, as before; with it, the +// call succeeds and the PSO is never registered, so it binds as no pipeline at all (its draws and dispatches are +// no-ops, D3D-482). Synthetic only: no shader library, no game data, nothing reaches the GPU. +#include "../shims/d3d12_com.h" + +#include +#include + +namespace { + +int g_failed = 0; +#define CHECK(x) \ + do { \ + if (!(x)) { \ + std::fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #x); \ + ++g_failed; \ + } \ + } while (0) + +template +struct Ref { + T* p = nullptr; + ~Ref() { + if (p) p->Release(); + } +}; + +D3D12_GRAPHICS_PIPELINE_STATE_DESC graphics_desc() { + static const unsigned char kBytes[16] = {'D', 'X', 'B', 'C'}; // never parsed: the library lookup comes first + D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{}; + desc.VS = {kBytes, sizeof kBytes}; + desc.SampleMask = UINT_MAX; + desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + desc.NumRenderTargets = 1; + desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + desc.SampleDesc.Count = 1; + return desc; +} + +} // namespace + +int main() { + // No shader library, whatever the environment says. + SetEnvironmentVariableW(L"LEONIDA_SHADERS", nullptr); + _putenv_s("LEONIDA_STUB_PIPELINES", ""); + + Ref device; + if (FAILED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&device.p))) || !device.p) { + std::printf("SKIP: no Vulkan device\n"); + return 77; + } + const D3D12_GRAPHICS_PIPELINE_STATE_DESC desc = graphics_desc(); + + { // Off: refused as before, and no object. + Ref pso; + const HRESULT hr = device.p->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pso.p)); + if (hr == E_NOTIMPL) { // a device without the GPU address arena or graphics entry points refuses earlier + std::printf("SKIP: the device cannot create graphics pipelines (E_NOTIMPL)\n"); + return 77; + } + CHECK(hr == E_FAIL); + CHECK(!pso.p); + } + { // "0" is off too. + _putenv_s("LEONIDA_STUB_PIPELINES", "0"); + Ref pso; + CHECK(device.p->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pso.p)) == E_FAIL && !pso.p); + } + { // On: a stub that is no registered pipeline, so SetPipelineState binds none. + _putenv_s("LEONIDA_STUB_PIPELINES", "1"); + Ref pso; + CHECK(device.p->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pso.p)) == S_OK); + CHECK(pso.p != nullptr); + CHECK(rt::d3d12::graphics_pipeline_id(pso.p) == 0); + CHECK(rt::d3d12::compute_pipeline_id(pso.p) == 0); + } + { // Real refusals are not stubbed: a bad description is still E_INVALIDARG. + D3D12_GRAPHICS_PIPELINE_STATE_DESC bad = desc; + bad.VS = {}; + Ref pso; + CHECK(device.p->CreateGraphicsPipelineState(&bad, IID_PPV_ARGS(&pso.p)) == E_INVALIDARG && !pso.p); + } + _putenv_s("LEONIDA_STUB_PIPELINES", ""); + + std::printf("%s\n", g_failed ? "FAILED" : "PASS"); + return g_failed ? 1 : 0; +} diff --git a/runtime/test/d3d12_subgroup_test.cpp b/runtime/test/d3d12_subgroup_test.cpp index ccc0d2aff9..2da834f2a2 100644 --- a/runtime/test/d3d12_subgroup_test.cpp +++ b/runtime/test/d3d12_subgroup_test.cpp @@ -3,7 +3,9 @@ // SHA-256 of its FSSM program, writing eight words through the V# in s[4:7] (four root constants in the console compute layout), read back: // w64 native cs_w64x_readlane translated natively: v_readlane across both halves of a wave64. Exact only in a // 64-wide subgroup, so the PSO must ask for 64 (and full subgroups) on a device that can give it. -// On a device that cannot (NVIDIA: 32 only) the PSO reports it, and the result is not judged. +// Where the device's subgroup size range does not reach 64 (NVIDIA reports 32..32) the case prints +// SKIP with that range and is not run; where the range reaches 64 but it cannot be required, the PSO +// reports it and the result is not judged. // w64 emulated the same shader translated with --wave64-emulate: exact on any size, the PSO asks for nothing. // w32 native cs_wqm_w32, a wave32 shader with whole-quad mode on lane masks; the PSO asks for 32 where the // device's default or range would otherwise change it. @@ -18,6 +20,7 @@ #include #include +#include #include #include #include @@ -185,7 +188,7 @@ Result run(vktest::Device& d, const std::filesystem::path& library, const leonid CASE_EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; CASE_EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); + reinterpret_cast(&device.p), /*console_lists=*/false))); rt::d3d12::set_device_outer(inner, device.p); // Root signature: [0] four constants (s4..s7 in the console compute layout, D3D-448), the V# the shaders store @@ -379,7 +382,7 @@ DrawResult draw(vktest::Device& d, const std::filesystem::path& library, const l CASE_EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; CASE_EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); + reinterpret_cast(&device.p), /*console_lists=*/false))); rt::d3d12::set_device_outer(inner, device.p); D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; @@ -529,6 +532,13 @@ const Pixel readlane_expected = {0x40000079u, 0x40000010u, 0x40000064u, 0x400000 } // namespace int main() { + // The PSO's subgroup requests are recorded when its Vulkan pipeline is made, and the layer builds compute + // pipelines lazily by default: at the first dispatch (or on the warm-up thread), not at + // CreateComputePipelineState. `run` reads them straight after creation, so build at creation on this thread; and + // keep the warm-up thread off so a pipeline it is still compiling cannot outlive the device the test releases + // (it crashed the process after a failed check). + _putenv_s("LEONIDA_LAZY_COMPUTE", "0"); + _putenv_s("LEONIDA_COMPUTE_WARMUP", "0"); vktest::Device d; const auto device_status = d.initialize(); if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips @@ -541,6 +551,15 @@ int main() { unsigned judged = 0; for (const Shader* shader : {&w64_native, &w64_emulated, &w32_native}) { + // A wave64 shader translated natively is exact only in a 64-wide subgroup, so it can be judged only where + // the device's subgroup size range (VkPhysicalDeviceSubgroupSizeControlProperties) reaches 64. NVIDIA + // reports 32..32: there the native case is skipped for its reason, and the emulated build is the one to use. + if (shader == &w64_native && (caps.max_size < 64 || caps.min_size > 64)) { + std::printf("SKIP (%s): this device's subgroup sizes are %u..%u (default %u), so a 64-wide subgroup " + "cannot be had and the native wave64 result is not judged\n", shader->label, caps.min_size, + caps.max_size, caps.default_size); + continue; + } const leonida::SubgroupRequest want = expected_request(*shader, caps); const Result result = run(d, shader_dir(*shader), caps); EXPECT(!result.failure); diff --git a/runtime/test/d3d12_title_va_test.cpp b/runtime/test/d3d12_title_va_test.cpp new file mode 100644 index 0000000000..e7fafe5cb7 --- /dev/null +++ b/runtime/test/d3d12_title_va_test.cpp @@ -0,0 +1,655 @@ +// A buffer the title places at its own VA (Xbox device slot 133, rt::d3d12::create_buffer_at_host_address) is read +// by a shader written to the translator's address contract (heap_base + console VA, docs/d3d12_vulkan.md section +// 3.3), through the two kinds of address the layer writes for it: +// - a root view (SetComputeRootUnorderedAccessView with the title's VA): read 256 bytes past its base and written +// at its base, then copied to a READBACK buffer; +// - a buffer V# (CreateShaderResourceView of the title's buffer), the way translated vertex shaders fetch their +// vertices: read and written to an arena buffer. +// The title's VA is a VirtualAlloc address, far past the 4 GiB arena. Both page kinds are covered: read-write pages +// (imported with VK_EXT_external_memory_host where the driver takes them) and write-combined pages (refused by the +// import, so a shadow copy in the arena, the retail case on an RTX 5070 Ti). The data is written after the buffer +// exists, so the shadow's copy before the submission is what the GPU reads. +// Then the title's own memory outside any slot-133 buffer (a constant ring, #8862 section 3.5): a V# the CPU writes +// into a bound table itself, a created CBV and a root view. +// Negative controls: a second title buffer with other data must not be what the first one's V# reads; an arena +// buffer's V# keeps its VA; the title's range is forgotten when the buffer is released; a raw arena V# and a +// T#-shaped slot in a scanned table keep their bytes; a reserved, uncommitted address is left alone. The shader is test/glsl/cs_user_data.comp. No game data. LEONIDA_VK_VALIDATION=1 for the +// Khronos validation layer. +#include "shader_fixture_path.h" +#include "test_temp_dir.h" +#include "vk_test_device.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" +#include "../src/gfx10_descriptors.h" +#include "../src/shader_library.h" +#include "../src/title_va_alias.h" +#include "../src/title_page_watch.h" +#include "../src/title_geometry_watch.h" + +#include +#include +#include +#include +#include +#include + +#ifndef LEONIDA_TEST_CS_SPV +#error "LEONIDA_TEST_CS_SPV must name the compiled test shader" +#endif + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +namespace { + +using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slots 9/10: handle in RAX +using XboxComputePipelineFn = HRESULT(WINAPI*)(void* device, const D3D12_COMPUTE_PIPELINE_STATE_DESC*, std::uint64_t, + std::uint64_t, const IID*, void**); +using SerializeFn = HRESULT(WINAPI*)(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC*, ID3DBlob**, ID3DBlob**); + +template +struct Ref { + T* p = nullptr; + ~Ref() { reset(); } + void reset() { + if (p) p->Release(); + p = nullptr; + } + T* operator->() const { return p; } +}; + +void* slot(void* object, unsigned index) { return (*reinterpret_cast(object))[index]; } + +void put32(std::vector& out, std::uint32_t v) { + for (int i = 0; i < 4; ++i) out.push_back(std::uint8_t(v >> (8 * i))); +} + +std::vector zlib_stored(const std::vector& data) { + std::vector out = {0x78, 0x01, 0x01}; + const auto length = std::uint16_t(data.size()); + out.insert(out.end(), {std::uint8_t(length), std::uint8_t(length >> 8), std::uint8_t(~length), + std::uint8_t(~length >> 8)}); + out.insert(out.end(), data.begin(), data.end()); + std::uint32_t a = 1, b = 0; + for (const std::uint8_t x : data) { + a = (a + x) % 65521; + b = (b + a) % 65521; + } + const std::uint32_t adler = (b << 16) | a; + out.insert(out.end(), {std::uint8_t(adler >> 24), std::uint8_t(adler >> 16), std::uint8_t(adler >> 8), + std::uint8_t(adler)}); + return out; +} + +// The game's shader container shape (DXBC > DXIL > XDAT 0x0D > XBCH > zlib > FSSM), as d3d12_compute_test builds it. +std::vector shader_container(const std::vector& fssm) { + const auto stream = zlib_stored(fssm); + std::vector xbch = {'X', 'B', 'C', 'H'}; + for (const std::uint32_t v : {1u, std::uint32_t(stream.size()), 0u, std::uint32_t(fssm.size()), 0u}) put32(xbch, v); + xbch.insert(xbch.end(), stream.begin(), stream.end()); + std::vector dxil(16, 0); + dxil.insert(dxil.end(), {'X', 'D', 'A', 'T'}); + put32(dxil, 1); + put32(dxil, 12); + put32(dxil, 0x0d); + put32(dxil, 16 + 12 + 12); + put32(dxil, std::uint32_t(xbch.size())); + dxil.insert(dxil.end(), xbch.begin(), xbch.end()); + std::vector out = {'D', 'X', 'B', 'C'}; + out.resize(28, 0); + put32(out, 1); + put32(out, 36); + out.insert(out.end(), {'D', 'X', 'I', 'L'}); + put32(out, std::uint32_t(dxil.size())); + out.insert(out.end(), dxil.begin(), dxil.end()); + return out; +} + +std::vector serialize(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC& desc) { + const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); + const auto fn = d3d12 ? reinterpret_cast( + reinterpret_cast(GetProcAddress(d3d12, "D3D12SerializeVersionedRootSignature"))) + : nullptr; + std::vector out; + ID3DBlob* blob = nullptr; + if (fn && SUCCEEDED(fn(&desc, &blob, nullptr)) && blob) { + const auto* p = static_cast(blob->GetBufferPointer()); + out.assign(p, p + blob->GetBufferSize()); + blob->Release(); + } + return out; +} + +D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes, D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) { + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = bytes; + desc.Height = 1; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + desc.Flags = flags; + return desc; +} + +// The 48-bit base address of the 16-byte GFX10 buffer V# at `cpu` (dword 0, and dword 1 bits 0-15). +std::uint64_t vsharp_base(std::uint64_t cpu) { + std::uint32_t w[2]; + std::memcpy(w, reinterpret_cast(cpu), sizeof(w)); + return std::uint64_t(w[0]) | (std::uint64_t(w[1] & 0xFFFFu) << 32); +} + +D3D12_SHADER_RESOURCE_VIEW_DESC raw_srv(UINT first_word, UINT words) { + D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; + desc.Format = DXGI_FORMAT_R32_TYPELESS; + desc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + desc.Buffer.FirstElement = first_word; + desc.Buffer.NumElements = words; + desc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + return desc; +} + +constexpr UINT kElements = 64, kBytes = kElements * 4; +constexpr UINT64 kPages = 64 * 1024; +constexpr UINT kSrvWord = 256; // the V# reads title words 256..319 +constexpr UINT kRootAdd = 7; // root view mode: title word i = title word 64 + i + 7 + +struct Context { + ID3D12Device* inner = nullptr; // the Vulkan device (slot 133's backend takes it) + ID3D12Device* device = nullptr; // the Xbox-ABI proxy over it + ID3D12RootSignature* root = nullptr; + ID3D12PipelineState* pso = nullptr; + ID3D12CommandQueue* queue = nullptr; + ID3D12Fence* fence = nullptr; + UINT64 fence_value = 0; + std::uint64_t arena = 0; +}; + +// One kind of title pages: `protect` is PAGE_READWRITE, or with PAGE_WRITECOMBINE. +int check_kind(Context& c, const char* kind, DWORD protect, int& checks) { + void* pages = VirtualAlloc(nullptr, kPages, MEM_TOP_DOWN | MEM_RESERVE | MEM_COMMIT, protect); + void* other_pages = VirtualAlloc(nullptr, kPages, MEM_TOP_DOWN | MEM_RESERVE | MEM_COMMIT, protect); + EXPECT(pages && other_pages); + const auto title_va = reinterpret_cast(pages); + EXPECT(title_va >= c.arena); // outside the arena: heap_base + title_va names nothing of the layer's + const D3D12_RESOURCE_DESC desc = buffer_desc(kPages); + Ref title, other; + EXPECT(SUCCEEDED(rt::d3d12::create_buffer_at_host_address(c.inner, pages, desc, 0xFFFFFFFFu, + IID_PPV_ARGS(&title.p)))); + EXPECT(SUCCEEDED(rt::d3d12::create_buffer_at_host_address(c.inner, other_pages, desc, 0xFFFFFFFFu, + IID_PPV_ARGS(&other.p)))); + EXPECT(title->GetGPUVirtualAddress() == title_va); // the title keeps its own VA + const std::uint64_t shader_va = leonida::title_va_aliases().shader_va(title_va); + EXPECT(shader_va != title_va); + const bool arena_copy = shader_va < c.arena; + const bool vsharp_fits = (shader_va >> 48) == 0; + + // The data, written after the buffers exist. + auto* words = static_cast(pages); + auto* other_words = static_cast(other_pages); + for (UINT i = 0; i < kPages / 4; ++i) { + words[i] = 0xA0000000u + i * 3u; + other_words[i] = 0xB0000000u + i * 5u; + } + + // Descriptors: the title buffer's V# (and the other buffer's), and the negative controls. + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 8, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + Ref heap; + EXPECT(SUCCEEDED(c.device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap.p)))); + const std::uint64_t cpu = reinterpret_cast(slot(heap.p, 9))(heap.p); + const std::uint64_t gpu = reinterpret_cast(slot(heap.p, 10))(heap.p); + const UINT inc = c.device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + const D3D12_SHADER_RESOURCE_VIEW_DESC srv = raw_srv(kSrvWord, kElements); + c.device->CreateShaderResourceView(title.p, &srv, D3D12_CPU_DESCRIPTOR_HANDLE{cpu}); + c.device->CreateShaderResourceView(other.p, &srv, D3D12_CPU_DESCRIPTOR_HANDLE{cpu + inc}); + EXPECT(vsharp_base(cpu) == ((shader_va + kSrvWord * 4) & 0xFFFFFFFFFFFFull)); + + // An arena buffer for the V# read's result, a READBACK buffer for both results. + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}, readback_heap{D3D12_HEAP_TYPE_READBACK}; + Ref out, readback; + const auto uav = buffer_desc(kBytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + EXPECT(SUCCEEDED(c.device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &uav, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, + IID_PPV_ARGS(&out.p)))); + const auto readback_desc = buffer_desc(3 * kBytes); + EXPECT(SUCCEEDED(c.device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback.p)))); + // An arena buffer's V# keeps its VA: identity outside title-placed buffers. + const D3D12_CONSTANT_BUFFER_VIEW_DESC arena_cbv{out->GetGPUVirtualAddress(), 256}; + c.device->CreateConstantBufferView(&arena_cbv, D3D12_CPU_DESCRIPTOR_HANDLE{cpu + 3 * inc}); + EXPECT(vsharp_base(cpu + 3 * inc) == out->GetGPUVirtualAddress()); + + Ref allocator; + Ref list; + EXPECT(SUCCEEDED(c.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + EXPECT(SUCCEEDED(c.device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, c.pso, + IID_PPV_ARGS(&list.p)))); + ID3D12DescriptorHeap* heaps[] = {heap.p}; + list->SetDescriptorHeaps(1, heaps); + list->SetComputeRootSignature(c.root); + // Through the V# (buffer SRV mode, s5 = 0xFFFFFFFF), into the arena buffer. Skipped when the buffer's copy is + // not within a V#'s 48 bits of heap_base (an import the driver put below the arena), which the layer logs. + if (vsharp_fits) { + list->SetComputeRoot32BitConstant(0, 0, 0); + list->SetComputeRoot32BitConstant(0, 0xFFFFFFFFu, 1); + list->SetComputeRootUnorderedAccessView(1, out->GetGPUVirtualAddress()); + list->SetComputeRootDescriptorTable(2, D3D12_GPU_DESCRIPTOR_HANDLE{gpu}); + list->Dispatch(1, 1, 1); + } + // Through the root view: the title's own VA, read at +256 bytes and written at +0. + list->SetComputeRoot32BitConstant(0, kRootAdd, 0); + list->SetComputeRoot32BitConstant(0, 0xFFFFFFFEu, 1); + list->SetComputeRootUnorderedAccessView(1, title_va); + list->Dispatch(1, 1, 1); + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + list->ResourceBarrier(1, &barrier); + D3D12_RESOURCE_BARRIER to_copy{}; + to_copy.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + to_copy.Transition.pResource = out.p; + to_copy.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + to_copy.Transition.StateBefore = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + to_copy.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE; + list->ResourceBarrier(1, &to_copy); + list->CopyBufferRegion(readback.p, 0, out.p, 0, kBytes); + list->CopyBufferRegion(readback.p, kBytes, title.p, 0, kBytes); + EXPECT(list->Close() == S_OK); + ID3D12CommandList* lists[] = {list.p}; + c.queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(c.queue) == leonida::ReplayResult::success); + EXPECT(SUCCEEDED(c.queue->Signal(c.fence, ++c.fence_value))); + EXPECT(SUCCEEDED(c.fence->SetEventOnCompletion(c.fence_value, nullptr))); + + void* mapped = nullptr; + EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); + const auto* got = static_cast(mapped); + UINT srv_ok = 0, srv_other = 0, root_ok = 0; + for (UINT i = 0; i < kElements; ++i) { + if (got[i] == words[kSrvWord + i]) ++srv_ok; + if (got[i] == other_words[kSrvWord + i]) ++srv_other; + if (got[kElements + i] == words[64 + i] + kRootAdd) ++root_ok; + } + readback->Unmap(0, nullptr); + std::printf("%s pages: GPU copy %s (shader VA %s); V# read %s, %u/%u words matched, %u/%u read the other " + "buffer's (negative control); root view read+write %u/%u matched\n", + kind, arena_copy ? "in the arena" : "with its own device address", + arena_copy ? "an arena offset" : "device address - heap_base", + vsharp_fits ? "run" : "skipped (out of a V#'s 48 bits)", vsharp_fits ? srv_ok : 0, kElements, + vsharp_fits ? srv_other : 0, kElements, root_ok, kElements); + if (vsharp_fits) { + EXPECT(srv_ok == kElements); + EXPECT(srv_other == 0); + } + EXPECT(root_ok == kElements); + + // After release, the buffer's range is gone from the table: its old copy is not named any more. + title.reset(); + EXPECT(leonida::title_va_aliases().shader_va(title_va) == title_va); + checks += 2; + other.reset(); + heap.reset(); + VirtualFree(pages, 0, MEM_RELEASE); + VirtualFree(other_pages, 0, MEM_RELEASE); + return 0; +} + +// The title's own memory outside any slot-133 buffer: a VirtualAlloc range standing for its per-frame constant ring +// (#8862 section 3.5). Three ways a shader is given an address in it, each read back through an arena buffer: +// - a buffer V# the CPU writes into a shader-visible heap itself, as the title does (rewritten before the submission); +// - a V# made by CreateConstantBufferView (translated when written); +// - a root view (translated when set). +// Negative controls: a raw V# whose base is an arena buffer and a T#-shaped slot whose base is the ring keep their +// bytes; committed memory that is not the title's, and a title range with no committed page, are left alone. +// Two CPU addresses of one mapped physical tile. The runtime gets this information from XMem in production. +static std::uintptr_t source_tile, peer_tile; +void aliases_of_test_tile(std::uintptr_t va, std::vector& peers) { + if (va == source_tile) peers.push_back(peer_tile); +} +int check_title_memory(Context& c, int& checks, bool geometry) { + constexpr UINT64 ring_bytes = 256 * 1024; + auto* ring = static_cast(VirtualAlloc(nullptr, ring_bytes, MEM_TOP_DOWN | MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + EXPECT(ring); + const auto ring_va = reinterpret_cast(ring); + EXPECT(ring_va >= c.arena); + auto& aliases = leonida::title_va_aliases(); + aliases.add_title_memory(ring_va, ring_bytes); // as the xmem shims record what they hand the title + const std::uint64_t table_before = aliases.translated(leonida::TitleVaAliases::table_view); + const std::uint64_t created_before = aliases.translated(leonida::TitleVaAliases::created_view); + const std::uint64_t root_before = aliases.translated(leonida::TitleVaAliases::root_view); + + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}, readback_heap{D3D12_HEAP_TYPE_READBACK}; + const auto uav = buffer_desc(kBytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + Ref out[3], readback; + for (auto& o : out) + EXPECT(SUCCEEDED(c.device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &uav, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, + IID_PPV_ARGS(&o.p)))); + const auto readback_desc = buffer_desc(3 * kBytes); + EXPECT(SUCCEEDED(c.device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback.p)))); + + struct ConsoleHeap { + D3D12_DESCRIPTOR_HEAP_DESC desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 8, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + UINT64 address{}, size{}; + } h; + if (geometry) { + h.size = 65536; + h.desc.NumDescriptors = UINT(h.size / 32); + h.address = reinterpret_cast(VirtualAlloc(nullptr, h.size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + EXPECT(h.address); + } + Ref heap; + EXPECT(SUCCEEDED(c.device->CreateDescriptorHeap(&h.desc, IID_PPV_ARGS(&heap.p)))); + const std::uint64_t cpu = reinterpret_cast(slot(heap.p, 9))(heap.p); + const std::uint64_t gpu = reinterpret_cast(slot(heap.p, 10))(heap.p); + const UINT inc = c.device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + EXPECT(!geometry || cpu == h.address); + const auto raw_vsharp = [](std::uint64_t address) { + leonida::gfx10::Buffer b{}; + b.address = address; + b.num_records = kBytes; + b.format = leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT); + b.oob_select = leonida::gfx10::OobSelect::raw; + return leonida::gfx10::encode(b); + }; + // Slot 0: a V# the CPU writes itself, its base in the ring. Slot 1: CreateConstantBufferView of the ring. + // Slot 2: a raw 64-bit VA (out[2]) for the root-view mode. Slots 3 and 4: the negative controls. + std::uint64_t guest = ring_va; + HANDLE section{}; + void* primary{}; + void* peer{}; + constexpr auto data_offset = 0x1000u; + if (geometry) { + section = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, 65536, nullptr); + EXPECT(section); + primary = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 0); + peer = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 0); + EXPECT(primary && peer); + source_tile = reinterpret_cast(primary); + peer_tile = reinterpret_cast(peer); + leonida::geometry_writes::aliases.store(&aliases_of_test_tile); + auto* gpu_range = VirtualAlloc(nullptr, ring_bytes, MEM_TOP_DOWN | MEM_RESERVE, PAGE_NOACCESS); + EXPECT(gpu_range); + guest = reinterpret_cast(gpu_range); + leonida::title_gpu_views::note_reservation(source_tile, 65536, false); + EXPECT(leonida::title_gpu_views::note_reservation(guest, 65536, true)); + aliases.add_title_memory(guest, ring_bytes); + const auto srv = raw_srv(0, kElements); + EXPECT(rt::d3d12::write_placed_buffer_view(c.inner, false, &srv, guest + data_offset, kBytes, + D3D12_CPU_DESCRIPTOR_HANDLE{cpu + 7 * inc})); + EXPECT(vsharp_base(cpu + 7 * inc) == guest + data_offset); + } + const auto v0 = raw_vsharp(guest + data_offset); + std::memcpy(reinterpret_cast(cpu + (geometry ? 9 * inc : 0)), v0.data(), sizeof(v0)); + const D3D12_CONSTANT_BUFFER_VIEW_DESC cbv{ring_va + 0x2000, 256}; + // Simulate a Wine process whose title reservations leave no usable address in the main arena. + const auto* opt = std::getenv("LEONIDA_STREAM_BUFFER_WINDOWS"); + const bool external = opt && !std::strcmp(opt, "1"); + if (external) aliases.add_title_memory(1, c.arena - 1); + c.device->CreateConstantBufferView(&cbv, D3D12_CPU_DESCRIPTOR_HANDLE{cpu + inc}); + if (external) aliases.remove_title_memory(1); + const auto created = vsharp_base(cpu + inc); + EXPECT(created != cbv.BufferLocation && created == aliases.shader_va(cbv.BufferLocation)); + EXPECT((created >= c.arena) == external); // translated when written + const std::uint64_t out2 = out[2]->GetGPUVirtualAddress(); + std::memcpy(reinterpret_cast(cpu + 2 * inc), &out2, sizeof(out2)); + const auto arena_vsharp = raw_vsharp(out[0]->GetGPUVirtualAddress()); + std::memcpy(reinterpret_cast(cpu + 3 * inc), arena_vsharp.data(), sizeof(arena_vsharp)); + auto image_like = raw_vsharp(ring_va + 0x4000); + image_like[3] |= 0x8u << 28; // TYPE: an image + std::memcpy(reinterpret_cast(cpu + 4 * inc), image_like.data(), sizeof(image_like)); + std::uint8_t before3[32], before4[32]; + std::memcpy(before3, reinterpret_cast(cpu + 3 * inc), 32); + std::memcpy(before4, reinterpret_cast(cpu + 4 * inc), 32); + + // The ring's data, written before the submission (after the descriptors, as a title fills its ring per frame). + for (UINT i = 0; i < ring_bytes / 4; ++i) ring[i] = 0xC0000000u + i * 7u; + if (geometry) { + // Only the other mapping changes after the view is made. Never write through the address the runtime reads. + std::memcpy(static_cast(peer) + data_offset, ring + data_offset / 4, kBytes); + } + + Ref allocator; + Ref list; + EXPECT(SUCCEEDED(c.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + EXPECT(SUCCEEDED(c.device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, c.pso, + IID_PPV_ARGS(&list.p)))); + ID3D12DescriptorHeap* heaps[] = {heap.p}; + list->SetDescriptorHeaps(1, heaps); + list->SetComputeRootSignature(c.root); + // The CPU-written V# (buffer SRV mode). + list->SetComputeRoot32BitConstant(0, geometry ? 9 : 0, 0); + list->SetComputeRoot32BitConstant(0, geometry ? 0xFFFFFFFCu : 0xFFFFFFFFu, 1); + list->SetComputeRootUnorderedAccessView(1, out[0]->GetGPUVirtualAddress()); + list->SetComputeRootDescriptorTable(2, D3D12_GPU_DESCRIPTOR_HANDLE{gpu}); + list->Dispatch(1, 1, 1); + // A console CBV uses 16-byte records. Read its first four words through the same indexed-load fixture. + list->SetComputeRoot32BitConstant(0, geometry ? 1 : 0, 0); + list->SetComputeRoot32BitConstant(0, geometry ? 0xFFFFFFFCu : 0, 1); + list->SetComputeRootUnorderedAccessView(1, out[1]->GetGPUVirtualAddress()); + list->SetComputeRootDescriptorTable(2, D3D12_GPU_DESCRIPTOR_HANDLE{gpu + inc}); + list->Dispatch(1, 1, 1); + // A root view into the ring, read 256 bytes past its base, written through slot 2's raw VA. + list->SetComputeRoot32BitConstant(0, kRootAdd, 0); + list->SetComputeRoot32BitConstant(0, 0xFFFFFFFDu, 1); + list->SetComputeRootUnorderedAccessView(1, ring_va + 0x3000); + list->SetComputeRootDescriptorTable(2, D3D12_GPU_DESCRIPTOR_HANDLE{gpu + 2 * inc}); + list->Dispatch(1, 1, 1); + // The negative-control slots are bound too, so the scan reads them. + list->SetComputeRootDescriptorTable(2, D3D12_GPU_DESCRIPTOR_HANDLE{gpu + 3 * inc}); + list->SetComputeRootDescriptorTable(2, D3D12_GPU_DESCRIPTOR_HANDLE{gpu + 4 * inc}); + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + list->ResourceBarrier(1, &barrier); + for (UINT k = 0; k < 3; ++k) { + D3D12_RESOURCE_BARRIER to_copy{}; + to_copy.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + to_copy.Transition.pResource = out[k].p; + to_copy.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + to_copy.Transition.StateBefore = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + to_copy.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE; + list->ResourceBarrier(1, &to_copy); + list->CopyBufferRegion(readback.p, k * kBytes, out[k].p, 0, kBytes); + } + EXPECT(list->Close() == S_OK); + ID3D12CommandList* lists[] = {list.p}; + c.queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(c.queue) == leonida::ReplayResult::success); + EXPECT(SUCCEEDED(c.queue->Signal(c.fence, ++c.fence_value))); + EXPECT(SUCCEEDED(c.fence->SetEventOnCompletion(c.fence_value, nullptr))); + + void* mapped = nullptr; + EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); + const auto* got = static_cast(mapped); + UINT raw_ok = 0, cbv_ok = 0, root_ok = 0; + for (UINT i = 0; i < kElements; ++i) { + if (got[i] == ring[data_offset / 4 + (geometry ? i % 4 : i)]) ++raw_ok; + if (got[kElements + i] == ring[0x2000 / 4 + (geometry ? i % 4 : i)]) ++cbv_ok; + if (got[2 * kElements + i] == ring[0x3000 / 4 + 64 + i] + kRootAdd) ++root_ok; + } + readback->Unmap(0, nullptr); + const bool rewritten = geometry + ? vsharp_base(cpu + 9 * inc) == guest + data_offset // shader followed the copy; original bytes intact + : vsharp_base(cpu) != ring_va + data_offset && vsharp_base(cpu) == aliases.shader_va(ring_va + data_offset); + const bool arena_kept = !std::memcmp(before3, reinterpret_cast(cpu + 3 * inc), 32); + const bool image_kept = !std::memcmp(before4, reinterpret_cast(cpu + 4 * inc), 32); + std::printf("title memory (a constant ring): CPU-written table V# %u/%u (rewritten before the submission: %s), " + "created CBV %u/%u, root view %u/%u; negative controls: arena V# kept %s, T#-shaped slot kept %s; " + "translated: %llu table V#, %llu created, %llu root\n", + raw_ok, kElements, rewritten ? "yes" : "no", cbv_ok, kElements, root_ok, kElements, + arena_kept ? "yes" : "no", image_kept ? "yes" : "no", + static_cast(aliases.translated(leonida::TitleVaAliases::table_view) - table_before), + static_cast(aliases.translated(leonida::TitleVaAliases::created_view) - + created_before), + static_cast(aliases.translated(leonida::TitleVaAliases::root_view) - root_before)); + EXPECT(raw_ok == kElements && cbv_ok == kElements && root_ok == kElements); + EXPECT(rewritten && arena_kept && image_kept); + // Left alone and counted: committed memory that is not the title's (the runtime's own, say), and a title range + // with no committed page. + const std::uint64_t untranslated_before = aliases.untranslated(leonida::TitleVaAliases::created_view); + void* host = VirtualAlloc(nullptr, 65536, MEM_TOP_DOWN | MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + void* gone = VirtualAlloc(nullptr, 65536, MEM_TOP_DOWN | MEM_RESERVE, PAGE_READWRITE); + const auto host_va = reinterpret_cast(host), gone_va = reinterpret_cast(gone); + aliases.add_title_memory(gone_va, 65536); + const D3D12_CONSTANT_BUFFER_VIEW_DESC not_title{host_va, 256}, reserved_only{gone_va, 256}; + c.device->CreateConstantBufferView(¬_title, D3D12_CPU_DESCRIPTOR_HANDLE{cpu + 5 * inc}); + c.device->CreateConstantBufferView(&reserved_only, D3D12_CPU_DESCRIPTOR_HANDLE{cpu + 6 * inc}); + EXPECT(vsharp_base(cpu + 5 * inc) == (host_va & 0xFFFFFFFFFFFFull)); + EXPECT(vsharp_base(cpu + 6 * inc) == (gone_va & 0xFFFFFFFFFFFFull)); + EXPECT(aliases.untranslated(leonida::TitleVaAliases::created_view) - untranslated_before == 2); + if (geometry) { + heap.reset(); + leonida::geometry_writes::aliases.store(nullptr); + UnmapViewOfFile(peer); + UnmapViewOfFile(primary); + CloseHandle(section); + VirtualFree(reinterpret_cast(h.address), 0, MEM_RELEASE); + aliases.remove_title_memory(guest); + VirtualFree(reinterpret_cast(guest), 0, MEM_RELEASE); + } + aliases.remove_title_memory(gone_va); + aliases.remove_title_memory(ring_va); + VirtualFree(host, 0, MEM_RELEASE); + VirtualFree(gone, 0, MEM_RELEASE); + checks += 4; + return 0; +} + +// Four 4 MiB slabs fill the 16 MiB fixture budget. A final 1 MiB view still fits +// immediately after the 3 MiB view in the second slab. +int check_geometry_slab_tails(Context& c) { + constexpr std::uint64_t mib = 1ull << 20; + constexpr std::array sizes{3, 3, 4, 4, 1}; + void* pages = VirtualAlloc(nullptr, 15 * mib, MEM_TOP_DOWN | MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + EXPECT(pages); + const auto source = reinterpret_cast(pages); + auto& aliases = leonida::title_va_aliases(); + aliases.add_title_memory(source, 15 * mib); + alignas(32) std::uint32_t slot[8]{}; + const auto dest = reinterpret_cast(slot); + std::array addresses{}; + std::uint64_t offset = 0; + for (std::size_t i = 0; i < sizes.size(); ++i) { + const auto bytes = sizes[i] * mib; + const auto srv = raw_srv(0, UINT(bytes / 4)); + EXPECT(rt::d3d12::write_placed_buffer_view(c.inner, false, &srv, source + offset, bytes, {dest})); + addresses[i] = vsharp_base(dest); + EXPECT(addresses[i] != source + offset); + offset += bytes; + } + EXPECT(addresses[4] == addresses[1] + sizes[1] * mib); + aliases.remove_title_memory(source); + VirtualFree(pages, 0, MEM_RELEASE); + std::puts("geometry slab tails: the final 1 MiB view used free space in an earlier slab at the cap"); + return 0; +} + +} // namespace + +int main() { + const char* setting = std::getenv("LEONIDA_GEOMETRY_MB"); + const bool geometry = setting && std::atoi(setting) > 0; + vktest::Device d; + const auto device_status = d.initialize(); + if (device_status == vktest::DeviceStatus::unavailable) { + std::fprintf(stderr, "SKIP: no usable Vulkan 1.3 device\n"); + return 77; + } + EXPECT(device_status == vktest::DeviceStatus::ready); + + std::vector fssm = {'F', 'S', 'S', 'M'}; + put32(fssm, 6000); + for (std::uint32_t i = 0; i < 14; ++i) put32(fssm, 0xbf810000u + i); + const auto container = shader_container(fssm); + const testfiles::ScratchDir scratch("leonida_title_va_test"); + const auto& library = scratch.path(); + EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), library / "cs_user_data.spv")); + { + std::ofstream index(library / "index.json", std::ios::binary); + index << "{\"cs_user_data\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << leonida::sha256_hex(fssm) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"local_size\": [64, 1, 1], " + "\"uses_code_base\": true, \"wave64\": false}}"; + } + + int checks = 0; + { + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = d.instance_proc; + info.instance = d.instance; + info.physical = d.physical; + info.device = d.device; + info.queue = d.queue; + info.queue_family = d.family; + info.buffer_device_address = true; + if (geometry) info.host_pointer_alignment = d.host_pointer_alignment; + info.subgroup = d.subgroup; + info.shader_dir = library.string(); + ID3D12Device* inner = nullptr; // owned by the proxy, as in d3d12_compute_test + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); + Ref device; + EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), + reinterpret_cast(&device.p)))); + rt::d3d12::set_device_outer(inner, device.p); + + // [0] two constants (s4, s5), [1] a root UAV (s6:s7), [2] a one-descriptor table (s8): the console compute + // layout cs_user_data.comp reads. + D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, 1, 0, 0}; + D3D12_ROOT_PARAMETER params[3] = {}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[0].Constants = {0, 0, 2}; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + params[1].Descriptor = {0, 0}; + params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[2].DescriptorTable = {1, &range}; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; + root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + root_desc.Desc_1_0 = {3, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + if (geometry) root_desc.Desc_1_0.Flags = D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED; + const auto root_blob = serialize(root_desc); + EXPECT(!root_blob.empty()); + Ref root; + EXPECT(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p)))); + D3D12_COMPUTE_PIPELINE_STATE_DESC pso_desc{}; + pso_desc.pRootSignature = root.p; + pso_desc.CS = {container.data(), container.size()}; + const IID pso_iid = __uuidof(ID3D12PipelineState); + Ref pso; + EXPECT(SUCCEEDED(reinterpret_cast(slot(device.p, 62))( + device.p, &pso_desc, 0, 0, &pso_iid, reinterpret_cast(&pso.p)))); + + const D3D12_COMMAND_QUEUE_DESC queue_desc{}; + Ref queue; + Ref fence; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + + Context c; + c.inner = inner; + c.device = device.p; + c.root = root.p; + c.pso = pso.p; + c.queue = queue.p; + c.fence = fence.p; + c.arena = rt::d3d12::device_arena_size(device.p); + EXPECT(c.arena > 0); + if (check_kind(c, "read-write", PAGE_READWRITE, checks)) return 1; + if (check_kind(c, "write-combined", PAGE_READWRITE | PAGE_WRITECOMBINE, checks)) return 1; + if (check_title_memory(c, checks, geometry)) return 1; + if (geometry && std::atoi(setting) == 16 && check_geometry_slab_tails(c)) return 1; + } + if (d.validation_errors()) { + std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); + return 1; + } + std::printf("title-placed buffers: a translated shader reached both page kinds through a root view and a buffer " + "V#; %d descriptor-level negative controls held\n", + checks); + return 0; +} diff --git a/runtime/test/d3d12_translated_draw_test.cpp b/runtime/test/d3d12_translated_draw_test.cpp index 62ce7b65cb..7497e2d152 100644 --- a/runtime/test/d3d12_translated_draw_test.cpp +++ b/runtime/test/d3d12_translated_draw_test.cpp @@ -3,8 +3,8 @@ // them through llvm-mc and tools/rdna2spirv.py (test/shaders/build.py), which writes spirv/index.json with each // program's fssm_sha256. The proxy's CreateGraphicsPipelineState then finds both stages by the SHA-256 of the FSSM // program inside the DXBC container, as it would for the game; nothing here bypasses that lookup. What it covers: -// - the user-data contract: a descriptor-table root argument (s0:s1, the table's console VA) and four root constants -// (s2..s5) reach the VS and the PS through the 144-byte push-constant block; +// - the user-data contract: a descriptor-table root argument (s8, the table's console VA) and four root constants +// (s9..s12) reach the VS and the PS through the 144-byte push-constant block, in the console's graphics layout; // - vertex fetch: the VS has no input layout; it s_loads a V# the application wrote into a shader-visible descriptor // slot and fetches position and colour with buffer_load_dwordx4 ... idxen. The V# points at a DEFAULT-heap vertex // buffer (a range of the GPU address arena, copied from an upload buffer). A V# cannot point at the upload @@ -180,12 +180,12 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); + reinterpret_cast(&device.p), /*console_lists=*/false))); rt::d3d12::set_device_outer(inner, device.p); #endif - // Root signature: [0] a descriptor table of one SRV (s0:s1, the table's console VA), [1] four 32-bit - // constants (s2, s3: the draw's offset; s4: the PS's bias; s5 unused). No input layout: the VS fetches. + // Root signature: [0] a descriptor table of one SRV (s8, the table's console VA), [1] four 32-bit + // constants (s9, s10: the draw's offset; s11: the PS's bias; s12 unused). No input layout: the VS fetches. D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; D3D12_ROOT_PARAMETER params[2] = {}; params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; @@ -316,7 +316,7 @@ int main() { struct Draw { unsigned slot; - float constants[4]; // s2, s3: offset; s4: bias; s5: unused + float constants[4]; // s9, s10: offset; s11: bias; s12: unused UINT vertices; }; const Draw draws[3] = {{0, {x_offset, 0, bias, 0}, 6}, // top left diff --git a/runtime/test/d3d12_vulkan_device_test.cpp b/runtime/test/d3d12_vulkan_device_test.cpp index f51ce2191a..f0efc4a2a8 100644 --- a/runtime/test/d3d12_vulkan_device_test.cpp +++ b/runtime/test/d3d12_vulkan_device_test.cpp @@ -4374,6 +4374,14 @@ int compare_invalid_arguments(ID3D12Device* ours) { std::printf("invalid arguments format %d %s: the host accepts it, this Vulkan driver can't\n", f, what); continue; } + // The other way round is a mismatch, except where the layer takes a console format stand-in the host + // cannot attach: an R9G9B9E5 render target is made as B10G11R11 (console format stand-ins, fa83b2825), + // which the title asserts on. Only present on a GPU without a native E5B9G9R9 attachment. + if (SUCCEEDED(a) && FAILED(b) && format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP && + flags == D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) { + std::printf("invalid arguments format %d RT: a console stand-in the host itself refuses\n", f); + continue; + } ++mismatches; std::fprintf(stderr, "invalid arguments format %d %s: ours 0x%08lx, host 0x%08lx\n", f, what, a, b); } @@ -5094,7 +5102,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); + reinterpret_cast(&device.p), /*console_lists=*/false))); rt::d3d12::set_device_outer(inner, device.p); // the proxy now owns `inner` EXPECT(rt::d3d12_xs::is_device_proxy(device.p)); EXPECT(rt::d3d12_xs::device_proxy_slot_count(device.p) == 80); // ID3D12Device11 @@ -5428,7 +5436,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(fallback_info, IID_PPV_ARGS(&fallback_inner)))); Ref fallback_device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(fallback_inner, __uuidof(ID3D12Device), - reinterpret_cast(&fallback_device.p)))); + reinterpret_cast(&fallback_device.p), /*console_lists=*/false))); rt::d3d12::set_device_outer(fallback_inner, fallback_device.p); D3D12_FEATURE_DATA_D3D12_OPTIONS8 options8{TRUE}; EXPECT(fallback_device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS8, &options8, @@ -5533,7 +5541,11 @@ int main() { if (feature_mismatches < 0) std::printf("CheckFeatureSupport: no host D3D12 device to compare with, skipped\n"); EXPECT(feature_mismatches <= 0); - const int allocation_mismatches = compare_allocation_info(device.p); + // GetResourceAllocationInfo is compared on the layer's own PC device, not on the proxy: the proxy answers the + // console's placement of a title description (whole console tiles at the console's own alignment, + // d3d12_xs_alloc_size.h), which xs_proxy_mock's slot 25 test pins. The layer itself must match the PC runtime. + ID3D12Device* const layer_device = rt::d3d12_xs::device_proxy_real_device(device.p); + const int allocation_mismatches = compare_allocation_info(layer_device); if (allocation_mismatches < 0) std::printf("GetResourceAllocationInfo: no host D3D12 device to compare with, skipped\n"); EXPECT(allocation_mismatches <= 0); @@ -5590,7 +5602,14 @@ int main() { Ref granted_q; EXPECT(SUCCEEDED(device->CreateCommandQueue(&rt_desc, IID_PPV_ARGS(&granted_q.p))) && granted_q.p); if (granted_q.p) { - EXPECT(granted_q->GetDesc().Priority == D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME); + // PC GetDesc shares console slot 18 with the newer layout's GetTimestampFrequency; the proxy + // serves the frequency getter while the layout is undetected, so the desc is read on the real + // queue instead. + if (auto* real_q = rt::d3d12_xs::queue_proxy_real_queue(granted_q.p)) { + EXPECT(real_q->GetDesc().Priority == D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME); + } else { + EXPECT(granted_q->GetDesc().Priority == D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME); + } } granted_q.reset(); rt::d3d12::set_global_realtime_privilege_override_for_test(-1); @@ -5764,8 +5783,12 @@ int main() { E_INVALIDARG); } { + // On the Xbox device proxy, slot 61 is the title's CreateSamplerX (e22994464), where ID3D12Device5 has + // CreateMetaCommand, so these PC methods are checked on the Vulkan device behind the proxy. + ID3D12Device* const pc5 = rt::d3d12_xs::is_device_proxy(device.p) ? rt::d3d12_xs::device_proxy_real_device(device.p) + : device.p; Ref device5; - EXPECT(SUCCEEDED(device->QueryInterface(IID_PPV_ARGS(&device5.p)))); + EXPECT(SUCCEEDED(pc5->QueryInterface(IID_PPV_ARGS(&device5.p)))); UINT meta_count = 7; EXPECT(device5->EnumerateMetaCommands(&meta_count, nullptr) == S_OK && meta_count == 0); EXPECT(device5->EnumerateMetaCommands(nullptr, nullptr) == E_INVALIDARG); @@ -6580,12 +6603,18 @@ int main() { Ref device10; Ref one, two; EXPECT(SUCCEEDED(device->QueryInterface(IID_PPV_ARGS(&device4.p)))); - // Not through the proxy: its slot 78 is the Xbox SetFrameIntervalX (2dbcb882c), not this method. - EXPECT(SUCCEEDED(inner->QueryInterface(IID_PPV_ARGS(&device10.p)))); - EXPECT(SUCCEEDED(device4->CreateReservedResource1(&tiled_desc, D3D12_RESOURCE_STATE_COMMON, nullptr, - nullptr, IID_PPV_ARGS(&one.p)))); + // On the Xbox device proxy, slot 78 is the title's SetFrameIntervalX (#6935) and slot 55 is the Xbox + // CreateDerivedPipelineState, so the PC methods are checked on the Vulkan device behind the proxy. + ID3D12Device* pc = rt::d3d12_xs::is_device_proxy(device.p) ? rt::d3d12_xs::device_proxy_real_device(device.p) + : device.p; + EXPECT(SUCCEEDED(pc->QueryInterface(IID_PPV_ARGS(&device10.p)))); + Ref real4; + EXPECT(SUCCEEDED(pc->QueryInterface(IID_PPV_ARGS(&real4.p)))); + EXPECT(SUCCEEDED(real4->CreateReservedResource1(&tiled_desc, D3D12_RESOURCE_STATE_COMMON, nullptr, + nullptr, IID_PPV_ARGS(&one.p)))); EXPECT(SUCCEEDED(device10->CreateReservedResource2(&tiled_desc, D3D12_BARRIER_LAYOUT_COMMON, nullptr, nullptr, 0, nullptr, IID_PPV_ARGS(&two.p)))); + EXPECT(two.p); EXPECT(one.p && two.p); UINT tiles = 0; device->GetResourceTiling(two.p, &tiles, nullptr, nullptr, nullptr, 0, nullptr); diff --git a/runtime/test/d3d12_xmem_placed_test.cpp b/runtime/test/d3d12_xmem_placed_test.cpp index 368b32510b..cc70fa4376 100644 --- a/runtime/test/d3d12_xmem_placed_test.cpp +++ b/runtime/test/d3d12_xmem_placed_test.cpp @@ -1,7 +1,8 @@ // Xbox device slot 133 (CreatePlacedResourceX) on xmem physical pages that were mapped but never touched. xmem // commits physical pages on first touch, so such a range is still reserved when the title places a buffer on it, and // the Vulkan layer's import (rt::d3d12::create_buffer_at_host_address) refuses reserved pages and answers with its -// fallback buffer, which the CPU's writes never reach. With rt::xmem::commit_physical_range registered as the slot's +// fallback buffer: a shadow that copies only committed pages, so a reserved page reads as zeros and a write to it +// faults. With rt::xmem::commit_physical_range registered as the slot's // pages hook (rt::d3d12_xs::set_placed_at_va_pages_hook, as gta6rt does), the pages are committed first: the buffer's // GPU VA is the window itself and a GPU copy reads what the CPU writes there afterwards. // Needs VK_EXT_external_memory_host (skipped otherwise). No shaders or game data. @@ -113,12 +114,15 @@ int run(ID3D12Device* real, void* device) { desc.Layout = static_cast(0x1); // the Xbox row-major word const auto window_va = reinterpret_cast(window); - // Without the hook the reserved pages are refused and the fallback answers. + // Without the hook the reserved pages are refused and the fallback answers. Its GPU VA is the title's address + // either way: the imported buffer is bound to the window (create_host_buffer: va_ = start), and the shadow keeps + // that VA too so the descriptors and views the title builds from it still find the buffer (89261c7ed, + // d3d12_existing_heap_test.cpp). The reserved state is what shows the import refused these pages. rt::d3d12_xs::set_placed_at_va_pages_hook(nullptr); { Ref fallback; EXPECT(place(device, window, desc, &fallback.p) == S_OK && fallback.p); - EXPECT(fallback->GetGPUVirtualAddress() != window_va); + EXPECT(fallback->GetGPUVirtualAddress() == window_va); EXPECT(state_is(window, MEM_RESERVE)); } std::printf("%s: untouched physical pages without the hook: still reserved, fallback buffer\n", who); diff --git a/runtime/test/d3d12_xs_frame_events_test.cpp b/runtime/test/d3d12_xs_frame_events_test.cpp new file mode 100644 index 0000000000..d67c323ecc --- /dev/null +++ b/runtime/test/d3d12_xs_frame_events_test.cpp @@ -0,0 +1,44 @@ +// Portable C++20 tests for runtime/src/d3d12_xs_frame_events.h (no Windows or Vulkan dependency). +#include "../src/d3d12_xs_frame_events.h" + +#include +#include + +#define CHECK(condition) do { \ + if (!(condition)) { \ + std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); \ + return 1; \ + } \ +} while (0) + +int main() { + using namespace leonida::d3d12_xs; + + // 1. Struct ABI geometry. + CHECK(sizeof(XboxFrameEvent) == 0x38); + XboxFrameEvent events[6] = {}; + events[0].event_type = 0x1000u; + events[0].status = 0x5Au; + events[0].timestamp = 0x123456789ABCDEF0ull; + + // 2. Valid non-empty query clears *num_events to 0 without disturbing caller buffer bytes. + std::uint32_t count = 6; + CHECK(query_frame_events_empty(&count, events) == FrameEventQueryStatus::ok); + CHECK(count == 0); + CHECK(events[0].event_type == 0x1000u && events[0].status == 0x5Au && + events[0].timestamp == 0x123456789ABCDEF0ull); + + // 3. Zero-capacity query with null buffer succeeds cleanly. + count = 0; + CHECK(query_frame_events_empty(&count, nullptr) == FrameEventQueryStatus::ok); + CHECK(count == 0); + + // 4. Null count pointer and non-zero capacity with null buffer are rejected without mutating *num_events. + CHECK(query_frame_events_empty(nullptr, events) == FrameEventQueryStatus::null_count); + count = 4; + CHECK(query_frame_events_empty(&count, nullptr) == FrameEventQueryStatus::null_buffer); + CHECK(count == 4); + + std::printf("d3d12_xs_frame_events: 0x38-byte record geometry and GetFrameEventsX validation passed\n"); + return 0; +} diff --git a/runtime/test/descriptor_table_test.cpp b/runtime/test/descriptor_table_test.cpp index 1d03dff27b..387bd0c606 100644 --- a/runtime/test/descriptor_table_test.cpp +++ b/runtime/test/descriptor_table_test.cpp @@ -19,6 +19,104 @@ using namespace leonida; +// The shared contract vectors (the translator's desc_probe and this table must agree on both kinds): 512 slots, mask +// 511. Each row is a key -> the bare FNV-1a hash (slot 345 and friends) and the fnv1a_fmix32 hash (spread). +struct HashVector { + DescriptorKey key; + std::uint32_t fnv1a; + std::uint32_t fnv1a_slot; + std::uint32_t fnv1a_fmix32; + std::uint32_t fnv1a_fmix32_slot; +}; + +constexpr std::array kHashVectors{{ + {{0x00100000u, 0x00000000u, 0x90500FACu, 0x00000000u, 0u, 0u, 0u, 0u}, 0x1CD4CD59u, 345, 0x7CE036C5u, 197}, + {{0x10100000u, 0x00000000u, 0x90500FACu, 0x00000000u, 0u, 0u, 0u, 0u}, 0x0CD4CD59u, 345, 0x646B8915u, 277}, + {{0x20100000u, 0x00000000u, 0x90500FACu, 0x00000000u, 0u, 0u, 0u, 0u}, 0x3CD4CD59u, 345, 0xC2E843B6u, 438}, + {{0x30100000u, 0x00000000u, 0x90500FACu, 0x00000000u, 0u, 0u, 0u, 0u}, 0x2CD4CD59u, 345, 0xE11420E3u, 227}, + {{0x12345678u, 0x9ABCDEF0u, 0x0FEDCBA9u, 0x87654321u, 0x11111111u, 0x22222222u, 0x33333333u, 0x44444444u}, + 0xBD4A977Fu, 383, 0x3AE592B1u, 177}, + {{0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u}, 0x9BE17165u, 357, 0xBB10DC19u, 25}, + {{0x00010001u, 0x00400040u, 0x10014FACu, 0x00000000u, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu}, + 0x814225E4u, 484, 0xD5398A35u, 53}, + {{0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu}, + 0xB0E4285Du, 93, 0x98A3F73Au, 314}, +}}; + +int test_shared_hash_vectors() { + for (const HashVector& v : kHashVectors) { + EXPECT(hash_descriptor_key(v.key, DescriptorHashKind::fnv1a) == v.fnv1a); + EXPECT(hash_descriptor_key(v.key, DescriptorHashKind::fnv1a_fmix32) == v.fnv1a_fmix32); + EXPECT((v.fnv1a & 511u) == v.fnv1a_slot); + EXPECT((v.fnv1a_fmix32 & 511u) == v.fnv1a_fmix32_slot); + // fnv1a_fmix32 is the same FNV loop plus the finalizer, and the old default overload is still bare FNV-1a. + EXPECT(hash_descriptor_key_fnv1a(v.key.data()) == v.fnv1a); + EXPECT(finalize_descriptor_hash(v.fnv1a) == v.fnv1a_fmix32); + EXPECT(hash_descriptor_key(v.key) == v.fnv1a); + } + return 0; +} + +// The clustering the fmix32 finalizer removes: T#s that differ only in the top nibble of dword 0 share slot 345 under +// bare FNV-1a (four keys in one probe run), and land in four different home slots under fnv1a_fmix32. +int test_fmix32_spreads_the_clustered_keys() { + constexpr std::uint32_t mask = 511; + std::array fnv1a_slots{}, fmix32_slots{}; + for (std::size_t i = 0; i < fnv1a_slots.size(); ++i) { + fnv1a_slots[i] = hash_descriptor_key(kHashVectors[i].key, DescriptorHashKind::fnv1a) & mask; + fmix32_slots[i] = hash_descriptor_key(kHashVectors[i].key, DescriptorHashKind::fnv1a_fmix32) & mask; + EXPECT(fnv1a_slots[i] == 345u); + } + for (std::size_t i = 0; i < fmix32_slots.size(); ++i) + for (std::size_t j = i + 1; j < fmix32_slots.size(); ++j) EXPECT(fmix32_slots[i] != fmix32_slots[j]); + return 0; +} + +// A table finds every key it holds with the kind it was built with, at that kind's home slot and probe window; a table +// built with the other kind does not answer them (the minority of a mixed library misses to index 0). +int test_table_uses_the_kind_it_was_built_with() { + constexpr std::uint32_t slots = 512; + constexpr std::uint32_t mask = slots - 1; + for (const DescriptorHashKind kind : {DescriptorHashKind::fnv1a, DescriptorHashKind::fnv1a_fmix32}) { + DescriptorTable table(slots, kind); + EXPECT(table.capacity() == slots && table.mask() == mask && table.hash_kind() == kind); + for (std::size_t i = 0; i < kHashVectors.size(); ++i) EXPECT(table.insert(kHashVectors[i].key, i + 1)); + EXPECT(table.size() == kHashVectors.size()); + for (std::size_t i = 0; i < kHashVectors.size(); ++i) { + EXPECT(table.lookup(kHashVectors[i].key) == i + 1); + EXPECT(table.contains(kHashVectors[i].key)); + // The key is in its own kind's probe window, with its index and the occupied marker. + const std::uint32_t home = hash_descriptor_key(kHashVectors[i].key, kind) & mask; + bool found = false; + for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) { + std::uint32_t words[10] = {}; + EXPECT(table.read_slot((home + k) & mask, words)); + if (std::memcmp(words, kHashVectors[i].key.data(), sizeof(DescriptorKey)) == 0) { + EXPECT(words[8] == i + 1 && words[9] == kSlotOccupiedMarker); + found = true; + break; + } + } + EXPECT(found); + } + } + // Lookups placed with fnv1a_fmix32 fall outside the bare FNV-1a window (345..352) of the clustered keys. + DescriptorTable fmix32_table(slots, DescriptorHashKind::fnv1a_fmix32); + for (std::size_t i = 0; i < 4; ++i) EXPECT(fmix32_table.insert(kHashVectors[i].key, i + 1)); + for (std::size_t i = 0; i < 4; ++i) { + const std::uint32_t fnv1a_home = hash_descriptor_key(kHashVectors[i].key, DescriptorHashKind::fnv1a) & mask; + bool found = false; + for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) { + std::uint32_t words[10] = {}; + EXPECT(fmix32_table.read_slot((fnv1a_home + k) & mask, words)); + found |= std::memcmp(words, kHashVectors[i].key.data(), sizeof(DescriptorKey)) == 0; + } + EXPECT(!found); + } + // The table's own kind still finds them (the same table, looked up as the device would). + for (std::size_t i = 0; i < 4; ++i) EXPECT(fmix32_table.lookup(kHashVectors[i].key) == i + 1); + return 0; +}// The bare FNV-1a contract the translator's desc_probe has always used (the default, no marker). int test_fnv1a_hash_matches_contract() { // Verified against vk_texture_test.cpp key_hash and rdna2spirv.py desc_probe const std::uint32_t zeros[8] = {0, 0, 0, 0, 0, 0, 0, 0}; @@ -452,6 +550,9 @@ int main() { EXPECT(test_unresolvable_hash_collision() == 0); EXPECT(test_capacity_overflow() == 0); EXPECT(test_fnv1a_hash_matches_contract() == 0); + EXPECT(test_shared_hash_vectors() == 0); + EXPECT(test_fmix32_spreads_the_clustered_keys() == 0); + EXPECT(test_table_uses_the_kind_it_was_built_with() == 0); EXPECT(test_ssharp_key_padding() == 0); EXPECT(test_basic_insertion_and_lookup() == 0); EXPECT(test_insert_reports_mapping_changes() == 0); diff --git a/runtime/test/device_proxy_test.cpp b/runtime/test/device_proxy_test.cpp index 1c17072436..d138e9eeb6 100644 --- a/runtime/test/device_proxy_test.cpp +++ b/runtime/test/device_proxy_test.cpp @@ -11,11 +11,13 @@ // slot 8/36 CreateCommandQueue/CreateFence (return queue and fence proxies that run GPU work) // Slot 9 on the device is CreateCommandAllocator on the PC vtable and must still forward, which proves the handle // getters were not wedged into the device slots. Console output also shows the proxy's first-call slot log. +#include #include #include #include #include +#include #include #include #include @@ -26,6 +28,11 @@ #include "d3d12_xs_desc_clean.h" #include "d3d12_xs_device.h" #include "shims.h" +#include "../src/frame_pacer.h" +#include "../src/shader_library.h" + +#include +#include namespace { @@ -108,6 +115,190 @@ bool load_compute_shader(ComPtr& bytecode) { return SUCCEEDED(hr) && bytecode; } +// ---- Slot 55 (CreateDerivedPipelineState) ---- + +constexpr std::size_t kRecordBytes = 0x14c; + +// One record: u32 tag, then the payload at +4 (d3d12_xs_pso_stream.h). +void put_record(unsigned char* record, std::uint32_t tag, const void* payload, std::size_t size) { + std::memset(record, 0, kRecordBytes); + std::memcpy(record, &tag, sizeof(tag)); + if (size) std::memcpy(record + 4, payload, size); +} + +std::size_t align_up(std::size_t value, std::size_t align) { return (value + align - 1) / align * align; } + +// A stream written in the console's layout: u32 type, payload at its alignment, next entry 8-aligned. +struct StreamBytes { + std::vector bytes; + void add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type, const void* payload, std::size_t size, std::size_t align) { + const std::size_t at = bytes.size(); + bytes.resize(at + 4); + const std::uint32_t t = type; + std::memcpy(bytes.data() + at, &t, sizeof(t)); + bytes.resize(align_up(at + 4, align), 0); + const auto* p = static_cast(payload); + bytes.insert(bytes.end(), p, p + size); + bytes.resize(align_up(bytes.size(), 8), 0); + } +}; + +bool compile_hlsl(const char* source, const char* target, ComPtr& bytecode) { + HMODULE compiler = LoadLibraryExA("d3dcompiler_47.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); + auto compile = compiler ? reinterpret_cast(GetProcAddress(compiler, "D3DCompile")) : nullptr; + if (!compile) return false; + ComPtr errors; + const HRESULT hr = compile(source, std::strlen(source), "device_proxy_slot55.hlsl", nullptr, nullptr, "main", + target, D3DCOMPILE_ENABLE_STRICTNESS, 0, bytecode.GetAddressOf(), + errors.GetAddressOf()); + if (FAILED(hr) && errors) std::printf("shader compile error: %s\n", static_cast(errors->GetBufferPointer())); + return SUCCEEDED(hr) && bytecode; +} + +// Graphics stream with every state a derived record can patch: DEPTH_STENCIL1, RASTERIZER, BLEND, SAMPLE_MASK. +std::vector graphics_stream(ID3D12RootSignature* root, ID3DBlob* vs, ID3DBlob* ps) { + StreamBytes s; + s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, &root, sizeof(root), alignof(void*)); + const D3D12_SHADER_BYTECODE vs_code{vs->GetBufferPointer(), vs->GetBufferSize()}; + const D3D12_SHADER_BYTECODE ps_code{ps->GetBufferPointer(), ps->GetBufferSize()}; + s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, &vs_code, sizeof(vs_code), alignof(void*)); + s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, &ps_code, sizeof(ps_code), alignof(void*)); + D3D12_RT_FORMAT_ARRAY rt{}; + rt.RTFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + rt.NumRenderTargets = 1; + s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, &rt, sizeof(rt), 4); + const DXGI_FORMAT dsv = DXGI_FORMAT_UNKNOWN; + s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, &dsv, sizeof(dsv), 4); + const DXGI_SAMPLE_DESC sample{1, 0}; + s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, &sample, sizeof(sample), 4); + const D3D12_PRIMITIVE_TOPOLOGY_TYPE topology = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, &topology, sizeof(topology), 4); + + D3D12_BLEND_DESC blend{}; + for (auto& rtb : blend.RenderTarget) { + rtb.SrcBlend = rtb.SrcBlendAlpha = D3D12_BLEND_ONE; + rtb.DestBlend = rtb.DestBlendAlpha = D3D12_BLEND_ZERO; + rtb.BlendOp = rtb.BlendOpAlpha = D3D12_BLEND_OP_ADD; + rtb.LogicOp = D3D12_LOGIC_OP_NOOP; + rtb.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + } + s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, &blend, sizeof(blend), 4); + const UINT mask = 0xffffffffu; + s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, &mask, sizeof(mask), 4); + D3D12_RASTERIZER_DESC raster{}; + raster.FillMode = D3D12_FILL_MODE_SOLID; + raster.CullMode = D3D12_CULL_MODE_BACK; + raster.DepthClipEnable = TRUE; + s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, &raster, sizeof(raster), 4); + D3D12_DEPTH_STENCIL_DESC1 ds{}; + ds.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; + ds.DepthFunc = D3D12_COMPARISON_FUNC_LESS; + ds.StencilReadMask = ds.StencilWriteMask = 0xff; + for (D3D12_DEPTH_STENCILOP_DESC* op : {&ds.FrontFace, &ds.BackFace}) { + op->StencilFailOp = op->StencilDepthFailOp = op->StencilPassOp = D3D12_STENCIL_OP_KEEP; + op->StencilFunc = D3D12_COMPARISON_FUNC_ALWAYS; + } + s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1, &ds, sizeof(ds), 4); + return s.bytes; +} + +void check_derived_states(ID3D12Device* device, void** proxy_vtbl, ID3D12RootSignature* root, + ID3D12PipelineState* compute_base, ID3D12PipelineState* native_base) { + using DeriveFn = HRESULT(WINAPI*)(void*, void*, std::uint64_t, const void*, const IID*, void**); + auto derive = reinterpret_cast(proxy_vtbl[55]); + const IID iid = __uuidof(ID3D12PipelineState); + unsigned char rec_tag5[kRecordBytes], rec_raster[kRecordBytes]; + unsigned char five[5 * kRecordBytes] = {}; + put_record(rec_tag5, 5, nullptr, 0); + D3D12_RASTERIZER_DESC raster{}; + raster.FillMode = D3D12_FILL_MODE_WIREFRAME; + raster.CullMode = D3D12_CULL_MODE_BACK; + raster.DepthClipEnable = TRUE; + put_record(rec_raster, 1, &raster, sizeof(raster)); + ComPtr out; + + // Refusals: a compute base has no graphics subobjects, a native compute PSO was never kept, and the arguments. + out.Reset(); + check(derive(device, compute_base, 1, rec_tag5, &iid, reinterpret_cast(out.GetAddressOf())) == E_INVALIDARG + && !out, "slot 55 refuses tag 5 (E_INVALIDARG, null output)"); + out.Reset(); + check(derive(device, compute_base, 1, rec_raster, &iid, reinterpret_cast(out.GetAddressOf())) == E_INVALIDARG + && !out, "slot 55 refuses a rasterizer record on a base without RASTERIZER (E_INVALIDARG)"); + out.Reset(); + check(derive(device, native_base, 1, rec_raster, &iid, reinterpret_cast(out.GetAddressOf())) == E_FAIL + && !out, "slot 55 refuses a base PSO that was never kept (null output, no derivation)"); + out.Reset(); + check(derive(device, compute_base, 1, nullptr, &iid, reinterpret_cast(out.GetAddressOf())) == E_POINTER, + "slot 55 with null records is E_POINTER"); + out.Reset(); + check(derive(device, compute_base, 0, rec_raster, &iid, reinterpret_cast(out.GetAddressOf())) == E_INVALIDARG, + "slot 55 with n = 0 is E_INVALIDARG"); + check(derive(device, compute_base, 5, five, &iid, reinterpret_cast(out.GetAddressOf())) == E_INVALIDARG, + "slot 55 with n = 5 is E_INVALIDARG"); + check(derive(device, compute_base, 1, rec_raster, nullptr, reinterpret_cast(out.GetAddressOf())) == E_POINTER, + "slot 55 with null riid is E_POINTER"); + + // Positive: a graphics base through slot 86, then tags 0, 1 and 3 in one call, tag 2 alone, and tag 2 again on + // the derived PSO (a derived PSO is a base too). + ComPtr vs, ps; + if (!compile_hlsl("float4 main() : SV_Position { return float4(0, 0, 0, 1); }", "vs_5_0", vs) || + !compile_hlsl("float4 main() : SV_Target { return float4(0, 0, 0, 1); }", "ps_5_0", ps)) { + check(false, "graphics shaders compile for the slot 55 positive test"); + return; + } + const std::vector stream = graphics_stream(root, vs.Get(), ps.Get()); + D3D12_PIPELINE_STATE_STREAM_DESC stream_desc{stream.size(), const_cast(stream.data())}; + using CreateStreamFn = HRESULT(WINAPI*)(void*, const D3D12_PIPELINE_STATE_STREAM_DESC*, const IID*, void**); + ComPtr base; + HRESULT hr = reinterpret_cast(proxy_vtbl[86])(device, &stream_desc, &iid, + reinterpret_cast(base.GetAddressOf())); + check(SUCCEEDED(hr) && base, "slot 86 creates the graphics base PSO (WARP accepts the stream)"); + if (!base) return; + + D3D12_DEPTH_STENCIL_DESC ds{}; + ds.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; + ds.DepthFunc = D3D12_COMPARISON_FUNC_LESS; + ds.StencilReadMask = ds.StencilWriteMask = 0xff; + for (D3D12_DEPTH_STENCILOP_DESC* op : {&ds.FrontFace, &ds.BackFace}) { + op->StencilFailOp = op->StencilDepthFailOp = op->StencilPassOp = D3D12_STENCIL_OP_KEEP; + op->StencilFunc = D3D12_COMPARISON_FUNC_ALWAYS; + } + unsigned char recs[3 * kRecordBytes]; + put_record(recs, 0, &ds, sizeof(ds)); + put_record(recs + kRecordBytes, 1, &raster, sizeof(raster)); + const UINT sample_mask = 0x1; + put_record(recs + 2 * kRecordBytes, 3, &sample_mask, sizeof(sample_mask)); + ComPtr three; + hr = derive(device, base.Get(), 3, recs, &iid, reinterpret_cast(three.GetAddressOf())); + check(SUCCEEDED(hr) && three, "slot 55 derives a PSO from tags 0, 1 and 3 (n = 3) on the graphics base"); + + D3D12_BLEND_DESC blend{}; + for (auto& rtb : blend.RenderTarget) { + rtb.SrcBlend = rtb.SrcBlendAlpha = D3D12_BLEND_ONE; + rtb.DestBlend = rtb.DestBlendAlpha = D3D12_BLEND_ZERO; + rtb.BlendOp = rtb.BlendOpAlpha = D3D12_BLEND_OP_ADD; + rtb.LogicOp = D3D12_LOGIC_OP_NOOP; + rtb.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + } + // Four records (raster, depth-stencil, sample mask, blend): the largest count the console builds. + unsigned char four_recs[4 * kRecordBytes]; + std::memcpy(four_recs, recs, 3 * kRecordBytes); + put_record(four_recs + 3 * kRecordBytes, 2, &blend, sizeof(blend)); + ComPtr quad; + hr = derive(device, base.Get(), 4, four_recs, &iid, reinterpret_cast(quad.GetAddressOf())); + check(SUCCEEDED(hr) && quad, "slot 55 derives a PSO from four records (n = 4)"); + + unsigned char rec_blend[kRecordBytes]; + put_record(rec_blend, 2, &blend, sizeof(blend)); + ComPtr blended; + hr = derive(device, base.Get(), 1, rec_blend, &iid, reinterpret_cast(blended.GetAddressOf())); + check(SUCCEEDED(hr) && blended, "slot 55 derives a PSO from tag 2 (blend), n = 1"); + + ComPtr chained; + hr = derive(device, three.Get(), 1, rec_blend, &iid, reinterpret_cast(chained.GetAddressOf())); + check(SUCCEEDED(hr) && chained, "slot 55 derives from a derived PSO (its stream is kept too)"); +} + } // namespace int main(int argc, char** argv) { @@ -246,6 +437,69 @@ int main(int argc, char** argv) { const D3D12_RESOURCE_ALLOCATION_INFO pc_info = device->GetResourceAllocationInfo(0, 1, &desc); check(pc_info.SizeInBytes == want.SizeInBytes && pc_info.Alignment == want.Alignment, "slot 25 still answers the PC (C++) form"); + // A console depth-stencil texture that allows unordered access too, as a title sizes one: a 2D + // R32G8X24_TYPELESS texture with ALLOW_DEPTH_STENCIL | ALLOW_UNORDERED_ACCESS and the console layout word. The + // PC device refuses the flag pair (negative control); slot 25 sizes it as the depth-stencil texture alone. + D3D12_RESOURCE_DESC ds_uav{}; + ds_uav.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + ds_uav.Width = 2560; + ds_uav.Height = 1440; + ds_uav.DepthOrArraySize = 1; + ds_uav.MipLevels = 1; + ds_uav.Format = DXGI_FORMAT_R32G8X24_TYPELESS; + ds_uav.SampleDesc.Count = 1; + ds_uav.Layout = static_cast(0x101); + ds_uav.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + D3D12_RESOURCE_DESC pc_pair = ds_uav; + pc_pair.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; + check(real->GetResourceAllocationInfo(0, 1, &pc_pair).SizeInBytes == UINT64_MAX, + "the PC device refuses a depth-stencil texture with unordered access (negative control)"); + D3D12_RESOURCE_DESC ds_only = pc_pair; + ds_only.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; + const D3D12_RESOURCE_ALLOCATION_INFO ds_want = real->GetResourceAllocationInfo(0, 1, &ds_only); + check(ds_want.SizeInBytes != UINT64_MAX, "WARP sizes the depth-stencil texture without unordered access"); + const D3D12_RESOURCE_DESC ds_clean = rt::d3d12_xs::pc_resource_desc(ds_uav); + check(ds_clean.Flags == D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, + "pc_resource_desc drops unordered access from a depth-stencil texture"); + D3D12_RESOURCE_DESC uav_buffer = buffer_desc(); + uav_buffer.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + D3D12_RESOURCE_DESC rt_uav = ds_only; + rt_uav.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + rt_uav.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + check(rt::d3d12_xs::pc_resource_desc(uav_buffer).Flags == D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS && + rt::d3d12_xs::pc_resource_desc(rt_uav).Flags == rt_uav.Flags, + "pc_resource_desc keeps unordered access on buffers and color textures"); + D3D12_RESOURCE_ALLOCATION_INFO ds_got{~0ull, ~0ull}; + get_alloc_info(&ds_got, device.Get(), 0, 1, &ds_uav); + // Sized as the console lays it out (12eb84f75: a depth plane and a stencil plane in 64 KiB tiles), which can + // be less than the PC answer for the depth-stencil texture alone, so only "sized, and in 32 bits" is checked. + check(ds_got.SizeInBytes != UINT64_MAX && ds_got.SizeInBytes != 0 && (ds_got.SizeInBytes >> 32) == 0, + "slot 25 (C ABI) sizes a console depth-stencil texture with unordered access"); + } + + constexpr auto kUav = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + constexpr auto kDepthStencil = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; + constexpr auto kRenderTarget = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + const struct { + DXGI_FORMAT format; + D3D12_RESOURCE_FLAGS input; + D3D12_RESOURCE_FLAGS expected; + const char* message; + } flag_cases[] = { + {DXGI_FORMAT_B5G5R5A1_UNORM, kRenderTarget | kUav, kRenderTarget, "B5G5R5A1 keeps only RT"}, + {DXGI_FORMAT_R32G8X24_TYPELESS, kDepthStencil | kUav, kDepthStencil, "R32G8X24 depth keeps only DS"}, + {DXGI_FORMAT_R8G8B8A8_UNORM, kRenderTarget | kUav, kRenderTarget | kUav, "RGBA8 keeps RT and UAV"}, + {DXGI_FORMAT_R32_FLOAT, kUav, kUav, "R32_FLOAT keeps UAV"}, + {DXGI_FORMAT_R32_TYPELESS, kUav, kUav, "R32_TYPELESS without DS keeps UAV"}, + {DXGI_FORMAT_D16_UNORM, kDepthStencil | kUav, kDepthStencil, "D16 depth keeps only DS"}, + }; + for (const auto& test : flag_cases) { + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Format = test.format; + desc.Flags = test.input; + const auto clean = rt::d3d12_xs::pc_resource_desc(desc); + check(clean.Flags == test.expected && clean.Format == test.format && desc.Flags == test.input, test.message); } D3D12_RESOURCE_DESC reserved_desc = buffer_desc(); @@ -436,15 +690,20 @@ int main(int argc, char** argv) { check(hr == S_OK && token2 != 0 && token2 != token, "slot 80 returns a fresh token on the next wait"); hr = reinterpret_cast(proxy_vtbl[80])(device.Get(), 0, 0, nullptr, 0, nullptr); check(hr == E_POINTER, "slot 80 refuses a null token with E_POINTER"); + const auto tokens = rt::d3d12_xs::device_frame_tokens(device.Get()); + check(tokens && tokens->issued() == token2 && token2 == token + 1, + "slot 80 tokens come from the device's frame token source"); + check(!rt::d3d12_xs::device_frame_tokens(nullptr), "a non-proxy has no frame token source"); check(rt::d3d12_xs::device_slot_hits(78) == 1 && rt::d3d12_xs::device_slot_hits(79) == 1 && rt::d3d12_xs::device_slot_hits(80) == 3, "slots 78/79/80 hit counters are 1/1/3"); - D3D12_COMMAND_QUEUE_DESC xbox_queue{}; - xbox_queue.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; + // The console description is 32 bytes: the PC prefix, then four Xbox words (the proxy logs them). + struct { D3D12_COMMAND_QUEUE_DESC pc; std::uint32_t extra[4]; } xbox_queue{}; + xbox_queue.pc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; const IID iid_queue = __uuidof(ID3D12CommandQueue); ComPtr xbox_queue_proxy; - hr = reinterpret_cast(proxy_vtbl[48])(device.Get(), &xbox_queue, &iid_queue, + hr = reinterpret_cast(proxy_vtbl[48])(device.Get(), reinterpret_cast(&xbox_queue), &iid_queue, reinterpret_cast(xbox_queue_proxy.GetAddressOf())); check(hr == S_OK && rt::d3d12_xs::is_queue_proxy(xbox_queue_proxy.Get()), "slot 48 CreateCommandQueueX returns a queue proxy"); @@ -549,6 +808,7 @@ int main(int argc, char** argv) { "slot 86 creates a PSO via PC ID3D12Device2::CreatePipelineState (slot 47)"); check(rt::d3d12_xs::device_slot_hits(86) == 1, "slot 86 hit counter is 1"); check(rt::d3d12_xs::device_slot_first_call_seen(86), "slot 86 first-call flag is set"); + check_derived_states(device.Get(), proxy_vtbl, root_signature.Get(), pso86.Get(), pso67.Get()); } } @@ -742,10 +1002,335 @@ int main(int argc, char** argv) { check(hook_state.free_count == 1 && hook_state.freed_ptr == hook_state.backing && hook_state.freed_attr == rt::d3d12_xs::kXmemDescriptorHeapAttributes, "releasing the hooked heap frees its backing through __XMemAllocationHooks__"); - rt::shims::remove_xmem_allocation_hooks(&title_hooks); + + // End-to-end console command list clear + readback with title-backed RTV and DSV heaps: + // verifies CPU handle translation on console slots 50/51/52 and FLOAT Depth (XMM3) on slot 51. + { + struct DualHeapState { + alignas(64) std::uint8_t rtv_backing[1024]{}; + alignas(64) std::uint8_t dsv_backing[1024]{}; + int next_slice = 0; + }; + static DualHeapState dual_state; + dual_state = {}; + struct DualHooks { + static void* __stdcall alloc(std::size_t size, std::uint64_t attr) { + if ((attr & 0x3FFFull) != 4 || size > 1024) return nullptr; + return dual_state.next_slice++ == 0 ? dual_state.rtv_backing : dual_state.dsv_backing; + } + static void __stdcall free(void*, std::uint64_t) {} + }; + const rt::shims::XMemAllocationHooks dual_hooks{&DualHooks::alloc, &DualHooks::free}; + rt::shims::remove_xmem_allocation_hooks(&title_hooks); + rt::shims::add_xmem_allocation_hooks(&dual_hooks, &dual_hooks); + + D3D12_DESCRIPTOR_HEAP_DESC rtv_hd{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 2, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + D3D12_DESCRIPTOR_HEAP_DESC dsv_hd{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 2, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + ComPtr rtv_heap, dsv_heap; + hr = device->CreateDescriptorHeap(&rtv_hd, IID_PPV_ARGS(rtv_heap.GetAddressOf())); + HRESULT hr_dsv = device->CreateDescriptorHeap(&dsv_hd, IID_PPV_ARGS(dsv_heap.GetAddressOf())); + check(SUCCEEDED(hr) && SUCCEEDED(hr_dsv) && rtv_heap && dsv_heap, + "hooked RTV and DSV heaps create through slot 14"); + + const D3D12_HEAP_PROPERTIES default_hp = default_heap(); + D3D12_HEAP_PROPERTIES readback_hp = default_heap(); + readback_hp.Type = D3D12_HEAP_TYPE_READBACK; + D3D12_RESOURCE_DESC rt_desc{}; + rt_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + rt_desc.Width = 4; + rt_desc.Height = 4; + rt_desc.DepthOrArraySize = 1; + rt_desc.MipLevels = 1; + rt_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + rt_desc.SampleDesc = {1, 0}; + rt_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + + D3D12_RESOURCE_DESC ds_desc = rt_desc; + ds_desc.Format = DXGI_FORMAT_D32_FLOAT; + ds_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; + + D3D12_RESOURCE_DESC rb_desc = buffer_desc(); + rb_desc.Width = 4096; + rb_desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + + ComPtr rt_tex, ds_tex, rb_buf; + hr = device->CreateCommittedResource(&default_hp, D3D12_HEAP_FLAG_NONE, &rt_desc, + D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr, + IID_PPV_ARGS(rt_tex.GetAddressOf())); + HRESULT hr2 = device->CreateCommittedResource(&default_hp, D3D12_HEAP_FLAG_NONE, &ds_desc, + D3D12_RESOURCE_STATE_DEPTH_WRITE, nullptr, + IID_PPV_ARGS(ds_tex.GetAddressOf())); + HRESULT hr3 = device->CreateCommittedResource(&readback_hp, D3D12_HEAP_FLAG_NONE, &rb_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(rb_buf.GetAddressOf())); + check(SUCCEEDED(hr) && SUCCEEDED(hr2) && SUCCEEDED(hr3), + "RT, DS and readback resources create for console list clear test"); + + if (rtv_heap && dsv_heap && rt_tex && ds_tex && rb_buf) { + const auto rtv_cpu = reinterpret_cast( + (*reinterpret_cast(rtv_heap.Get()))[9])(rtv_heap.Get()); + const auto dsv_cpu = reinterpret_cast( + (*reinterpret_cast(dsv_heap.Get()))[9])(dsv_heap.Get()); + const UINT rtv_inc = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); + const UINT dsv_inc = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV); + const D3D12_CPU_DESCRIPTOR_HANDLE rtv_h{rtv_cpu.ptr + rtv_inc}; + const D3D12_CPU_DESCRIPTOR_HANDLE dsv_h{dsv_cpu.ptr + dsv_inc}; + check(rtv_cpu.ptr == reinterpret_cast(dual_state.rtv_backing) && + dsv_cpu.ptr == reinterpret_cast(dual_state.dsv_backing), + "RTV and DSV heaps report their title-backed CPU descriptor bases"); + + device->CreateRenderTargetView(rt_tex.Get(), nullptr, rtv_h); + device->CreateDepthStencilView(ds_tex.Get(), nullptr, dsv_h); + + using CreateQueueXFn = HRESULT(WINAPI*)(void*, const D3D12_COMMAND_QUEUE_DESC*, const IID*, void**); + using CreateListXFn = HRESULT(WINAPI*)(void*, const void*, ID3D12CommandAllocator*, + ID3D12PipelineState*, const IID*, void**); + using CloseFn = HRESULT(WINAPI*)(void*); + using BarrierFn = void(WINAPI*)(void*, UINT, const D3D12_RESOURCE_BARRIER*); + using CopyTexFn = void(WINAPI*)(void*, const D3D12_TEXTURE_COPY_LOCATION*, UINT, UINT, UINT, + const D3D12_TEXTURE_COPY_LOCATION*, const D3D12_BOX*); + using OmSetRtFn = void(WINAPI*)(void*, UINT, const D3D12_CPU_DESCRIPTOR_HANDLE*, BOOL, + const D3D12_CPU_DESCRIPTOR_HANDLE*); + using ClearDsvFn = void(WINAPI*)(void*, D3D12_CPU_DESCRIPTOR_HANDLE, D3D12_CLEAR_FLAGS, FLOAT, UINT8, + UINT, const D3D12_RECT*); + using ClearRtvFn = void(WINAPI*)(void*, D3D12_CPU_DESCRIPTOR_HANDLE, const FLOAT[4], UINT, + const D3D12_RECT*); + + const D3D12_COMMAND_QUEUE_DESC qd{}; + const IID iid_q = __uuidof(ID3D12CommandQueue); + const IID iid_l = __uuidof(ID3D12GraphicsCommandList); + ComPtr clear_q; + ComPtr clear_alloc; + ComPtr clear_list; + ComPtr clear_fence; + hr = reinterpret_cast(proxy_vtbl[48])( + device.Get(), &qd, &iid_q, reinterpret_cast(clear_q.GetAddressOf())); + HRESULT hra = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, + IID_PPV_ARGS(clear_alloc.GetAddressOf())); + struct { + UINT Type; + UINT NodeMask; + } ld{D3D12_COMMAND_LIST_TYPE_DIRECT, 0}; + HRESULT hrl = SUCCEEDED(hra) ? reinterpret_cast(proxy_vtbl[73])( + device.Get(), &ld, clear_alloc.Get(), nullptr, &iid_l, + reinterpret_cast(clear_list.GetAddressOf())) + : hra; + HRESULT hrf = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(clear_fence.GetAddressOf())); + check(SUCCEEDED(hr) && SUCCEEDED(hra) && SUCCEEDED(hrl) && SUCCEEDED(hrf) && + rt::d3d12_xs::is_list_proxy(clear_list.Get()), + "console list proxy created for hooked RTV/DSV clear"); + + if (clear_q && clear_list && clear_fence) { + void** lv = *reinterpret_cast(clear_list.Get()); + const FLOAT rgba[4] = {1.0f, 0.0f, 0.5f, 1.0f}; + reinterpret_cast(lv[50])(clear_list.Get(), 1, &rtv_h, FALSE, &dsv_h); + reinterpret_cast(lv[52])(clear_list.Get(), rtv_h, rgba, 0, nullptr); + reinterpret_cast(lv[51])(clear_list.Get(), dsv_h, D3D12_CLEAR_FLAG_DEPTH, 0.25f, 0, 0, + nullptr); + + D3D12_RESOURCE_BARRIER b[2]{}; + b[0].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b[0].Transition = {rt_tex.Get(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE}; + b[1].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b[1].Transition = {ds_tex.Get(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + D3D12_RESOURCE_STATE_DEPTH_WRITE, D3D12_RESOURCE_STATE_COPY_SOURCE}; + reinterpret_cast(lv[26])(clear_list.Get(), 2, b); + + D3D12_TEXTURE_COPY_LOCATION dst_rt{}, src_rt{}, dst_ds{}, src_ds{}; + dst_rt.pResource = rb_buf.Get(); + dst_rt.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst_rt.PlacedFootprint = {0, {DXGI_FORMAT_R8G8B8A8_UNORM, 4, 4, 1, 256}}; + src_rt.pResource = rt_tex.Get(); + src_rt.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + dst_ds.pResource = rb_buf.Get(); + dst_ds.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst_ds.PlacedFootprint = {1536, {DXGI_FORMAT_R32_TYPELESS, 4, 4, 1, 256}}; + src_ds.pResource = ds_tex.Get(); + src_ds.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + reinterpret_cast(lv[16])(clear_list.Get(), &dst_rt, 0, 0, 0, &src_rt, nullptr); + reinterpret_cast(lv[16])(clear_list.Get(), &dst_ds, 0, 0, 0, &src_ds, nullptr); + + const HRESULT hr_close = reinterpret_cast(lv[9])(clear_list.Get()); + check(hr_close == S_OK, "console list Close succeeds after title-backed RTV/DSV clears"); + + ID3D12CommandList* lists[] = {clear_list.Get()}; + clear_q->ExecuteCommandLists(1, lists); + HANDLE ev = CreateEventW(nullptr, FALSE, FALSE, nullptr); + const bool done = ev && SUCCEEDED(clear_q->Signal(clear_fence.Get(), 1)) && + SUCCEEDED(clear_fence->SetEventOnCompletion(1, ev)) && + WaitForSingleObject(ev, 5000) == 0; + if (ev) CloseHandle(ev); + check(done, "console list clear commands complete on the GPU"); + + void* mapped = nullptr; + const D3D12_RANGE range{0, 4096}; + if (done && SUCCEEDED(rb_buf->Map(0, &range, &mapped)) && mapped) { + const auto* bytes = static_cast(mapped); + const bool rt_ok = bytes[0] == 255 && bytes[1] == 0 && (bytes[2] == 127 || bytes[2] == 128) && + bytes[3] == 255; + float depth_got = -1.0f; + std::memcpy(&depth_got, bytes + 1536, sizeof(depth_got)); + const bool ds_ok = std::fabs(depth_got - 0.25f) < 1e-6f; + check(rt_ok, "console slot 52 ClearRenderTargetView writes expected RGBA texel via hooked heap"); + check(ds_ok, "console slot 51 ClearDepthStencilView preserves FLOAT depth 0.25 via XMM3"); + const D3D12_RANGE empty{0, 0}; + rb_buf->Unmap(0, &empty); + } + } + } + rtv_heap.Reset(); + dsv_heap.Reset(); + rt::shims::remove_xmem_allocation_hooks(&dual_hooks); + } } // Hold a reference to the PC device so the final check can prove the proxy's Release balances its own. + // Slot 57 (DeserializeGraphicsPipelineStateX): + // 1. Guard-page test on the measured 188-byte (0xbc) pipeline blob from PSO #1 (record 8916), whose third element + // ("TEXCOORD" at 0x9b, fields at 0xa4) has its 28-byte block truncated by 4 bytes at 0xbc. Placing the 188-byte + // blob at the very end of a committed page right before a PAGE_NOACCESS guard page proves the parser decodes all + // 3 elements (POSITION R32G32B32_FLOAT @0, COLOR R8G8B8A8_UNORM @12, TEXCOORD R32G32_FLOAT @16) without reading + // past `blob_size`. + // 2. ShaderLibrary `fspx_gfx/index.json` loading and separate `fspx_size()`, `fspx_gfx_size()`, `bvh_size()` counters. + { + auto put_u32 = [](std::uint8_t* dst, std::size_t off, std::uint32_t v) { + std::memcpy(dst + off, &v, 4); + }; + std::uint8_t blob188[0xbc]{}; + put_u32(blob188, 0x00, 0xea6f6e56u); // PSO 1 magic/checksum + put_u32(blob188, 0x04, 0x00001000u); // constant + put_u32(blob188, 0x08, 0u); + put_u32(blob188, 0x0c, 1u); + put_u32(blob188, 0x10, 0x0000001cu); // 28 bytes (7 u32) per element + put_u32(blob188, 0x1c, 0xffffffffu); + put_u32(blob188, 0x24, 0x00130100u); + put_u32(blob188, 0x28, 1u); + put_u32(blob188, 0x38, 0x00000070u); // 4 + 3*28 + (9+6+9) = 112 + put_u32(blob188, 0x3c, 0x0000000cu); + put_u32(blob188, 0x4c, 3u); // 3 input elements + put_u32(blob188, 0x50, 9u); // max name stride including NUL + + // Element 0 @ 0x54: "POSITION\0" (9 B) + 28 B fields @ 0x5d..0x79 + std::memcpy(blob188 + 0x54, "POSITION", 9); + put_u32(blob188, 0x5d + 0x00, 0u); // InputSlot 0 + put_u32(blob188, 0x5d + 0x04, static_cast(DXGI_FORMAT_R32G32B32_FLOAT)); // 6 + put_u32(blob188, 0x5d + 0x08, 0u); // SemanticIndex 0 + put_u32(blob188, 0x5d + 0x0c, 0u); // AlignedByteOffset 0 + put_u32(blob188, 0x5d + 0x18, 6u); + + // Element 1 @ 0x79: "COLOR\0" (6 B) + 28 B fields @ 0x7f..0x9b + std::memcpy(blob188 + 0x79, "COLOR", 6); + put_u32(blob188, 0x7f + 0x00, 0u); + put_u32(blob188, 0x7f + 0x04, static_cast(DXGI_FORMAT_R8G8B8A8_UNORM)); // 28 + put_u32(blob188, 0x7f + 0x08, 0u); + put_u32(blob188, 0x7f + 0x0c, 12u); + put_u32(blob188, 0x7f + 0x18, 9u); + + // Element 2 @ 0x9b: "TEXCOORD\0" (9 B) + 24 B fields @ 0xa4..0xbc (truncated by 4 B at 0xbc!) + std::memcpy(blob188 + 0x9b, "TEXCOORD", 9); + put_u32(blob188, 0xa4 + 0x00, 0u); + put_u32(blob188, 0xa4 + 0x04, static_cast(DXGI_FORMAT_R32G32_FLOAT)); // 16 + put_u32(blob188, 0xa4 + 0x08, 0u); + put_u32(blob188, 0xa4 + 0x0c, 16u); + + SYSTEM_INFO si{}; + GetSystemInfo(&si); + const std::size_t page = si.dwPageSize ? si.dwPageSize : 4096; + auto* pages = static_cast( + VirtualAlloc(nullptr, page * 2, MEM_RESERVE, PAGE_NOACCESS)); + check(pages != nullptr, "slot 57 pipeline blob guard pages reserved"); + if (pages) { + void* committed = VirtualAlloc(pages, page, MEM_COMMIT, PAGE_READWRITE); + check(committed == pages, "slot 57 pipeline blob first page committed before guard page"); + std::uint8_t* guarded_blob = pages + page - sizeof(blob188); + std::memcpy(guarded_blob, blob188, sizeof(blob188)); + std::vector elems; + const bool ok = rt::d3d12_xs::parse_xbox_pipeline_blob_input_layout( + guarded_blob, sizeof(blob188), elems); + check(ok && elems.size() == 3, + "slot 57 pipeline blob parser decodes 3 elements from truncated 188-byte blob adjacent to PAGE_NOACCESS"); + if (elems.size() == 3) { + check(elems[0].semantic_name == "POSITION" && elems[0].format == DXGI_FORMAT_R32G32B32_FLOAT && + elems[0].aligned_byte_offset == 0 && elems[0].input_slot == 0, + "slot 57 pipeline blob element 0 is POSITION R32G32B32_FLOAT @0"); + check(elems[1].semantic_name == "COLOR" && elems[1].format == DXGI_FORMAT_R8G8B8A8_UNORM && + elems[1].aligned_byte_offset == 12 && elems[1].input_slot == 0, + "slot 57 pipeline blob element 1 is COLOR R8G8B8A8_UNORM @12"); + check(elems[2].semantic_name == "TEXCOORD" && elems[2].format == DXGI_FORMAT_R32G32_FLOAT && + elems[2].aligned_byte_offset == 16 && elems[2].input_slot == 0, + "slot 57 pipeline blob element 2 is TEXCOORD R32G32_FLOAT @16"); + } + VirtualFree(pages, 0, MEM_RELEASE); + } + + // Slot 57 null-argument checks on the device proxy. + void** vtable = *reinterpret_cast(device.Get()); + using Slot57Fn = HRESULT(WINAPI*)(void*, const void*, const IID*, void**); + const IID iid_pso = __uuidof(ID3D12PipelineState); + void* pso_out = reinterpret_cast(0x1111); + hr = reinterpret_cast(vtable[57])(device.Get(), nullptr, &iid_pso, &pso_out); + check(FAILED(hr) && pso_out == nullptr, "slot 57 nulls its output for a null description"); + + // Synthetic test for ShaderLibrary loading `fspx_gfx/index.json` alongside `fspx/index.json` and `bvh/index.json` + // while keeping `fspx_size()`, `fspx_gfx_size()`, and `bvh_size()` independent. + wchar_t temp_root[MAX_PATH]{}; + if (GetTempPathW(MAX_PATH, temp_root)) { + const std::filesystem::path tmp_dir = + std::filesystem::path(temp_root) / ("leonida_fspx_gfx_test_" + std::to_string(GetCurrentProcessId())); + std::error_code ec; + std::filesystem::create_directories(tmp_dir / "fspx", ec); + std::filesystem::create_directories(tmp_dir / "fspx_gfx", ec); + std::filesystem::create_directories(tmp_dir / "bvh", ec); + { + std::ofstream(tmp_dir / "index.json") << "{\n}\n"; + std::ofstream(tmp_dir / "fspx" / "index.json") + << "{\n" + << " \"libcs_00001\": {\n" + << " \"stage\": \"cs\",\n" + << " \"fspx_code_sha256\": \"1111111111111111111111111111111111111111111111111111111111111111\"\n" + << " }\n" + << "}\n"; + std::ofstream(tmp_dir / "fspx_gfx" / "index.json") + << "{\n" + << " \"9e5ffd2c6c521c037cf57582a23f8ff7ba494a71ca63bb899357caee8baab850\": {\n" + << " \"stage\": \"ps\",\n" + << " \"spv\": \"9e5ffd2c6c521c03_libps_00842.spv\",\n" + << " \"fspx_code_sha256\": \"9e5ffd2c6c521c037cf57582a23f8ff7ba494a71ca63bb899357caee8baab850\"\n" + << " },\n" + << " \"160fbe4368fb1a6349a2683bf72817f183d780c42a35cf25c86560917228061a\": {\n" + << " \"stage\": \"vs\",\n" + << " \"spv\": \"160fbe4368fb1a63_libvs_00843.spv\",\n" + << " \"fspx_code_sha256\": \"160fbe4368fb1a6349a2683bf72817f183d780c42a35cf25c86560917228061a\"\n" + << " }\n" + << "}\n"; + std::ofstream(tmp_dir / "bvh" / "index.json") + << "{\n" + << " \"bvh_00001\": {\n" + << " \"stage\": \"cs\",\n" + << " \"fspx_code_sha256\": \"2222222222222222222222222222222222222222222222222222222222222222\"\n" + << " }\n" + << "}\n"; + } + leonida::ShaderLibrary lib; + std::string err; + const bool loaded = lib.load(tmp_dir, &err); + check(loaded, "ShaderLibrary::load loads index.json + fspx + fspx_gfx + bvh"); + check(lib.fspx_size() == 1, "ShaderLibrary::fspx_size() counts only fspx/ entries"); + check(lib.fspx_gfx_size() == 2, "ShaderLibrary::fspx_gfx_size() counts only fspx_gfx/ entries"); + check(lib.bvh_size() == 1, "ShaderLibrary::bvh_size() counts only bvh/ entries"); + const auto* ps_entry = + lib.find_fspx_by_code("9e5ffd2c6c521c037cf57582a23f8ff7ba494a71ca63bb899357caee8baab850"); + const auto* vs_entry = + lib.find_fspx_by_code("160fbe4368fb1a6349a2683bf72817f183d780c42a35cf25c86560917228061a"); + check(ps_entry && ps_entry->stage == "ps" && ps_entry->spv_file == "fspx_gfx/9e5ffd2c6c521c03_libps_00842.spv", + "fspx_gfx PS entry preserves stage and its spv filename, under the folder prefix"); + check(vs_entry && vs_entry->stage == "vs" && vs_entry->spv_file == "fspx_gfx/160fbe4368fb1a63_libvs_00843.spv", + "fspx_gfx VS entry preserves stage and its spv filename, under the folder prefix"); + std::filesystem::remove_all(tmp_dir, ec); + } + } + if (real) real->AddRef(); // Drop every device child before the proxy so the PC device is not released first. root_signature.Reset(); diff --git a/runtime/test/dstorage_test.cpp b/runtime/test/dstorage_test.cpp index 1e8ea73183..4c1bb7d2f8 100644 --- a/runtime/test/dstorage_test.cpp +++ b/runtime/test/dstorage_test.cpp @@ -15,7 +15,12 @@ #include #include +#include +#include "../src/bcpack.h" +#include "../src/bcpack_stream.h" +#include "../src/title_page_watch.h" #include "dstorage_xs_abi.h" +#include "dstorage_staging.h" #include "file_system.h" #include "shims.h" @@ -177,6 +182,58 @@ IDStorageStatusArrayX* make_status(Env& env, UINT32 capacity) { // ---- tests ---------------------------------------------------------------------------------------------------------- +void test_staging_budget() { + using leonida::dstorage::StagingPool; + using leonida::dstorage::staging_bytes; + DSTORAGE_REQUEST r{}; + r.SourceSize = 64; + r.DestinationSize = 64; + check(staging_bytes(r) == 0, "raw buffer copy needs no staging"); + r.Options.AsUINT64 = options::kSourceMemory | options::kSourcePages; + r.SourcePageOffset = 65535; + check(staging_bytes(r) == 80, "two source page numbers are charged with the payload"); + r.Options.AsUINT64 = options::kZlib | (7ull << options::kBcpackShift); + r.IntermediateSize = 512; + r.DestinationSize = 256; + check(staging_bytes(r) == 768, "combined transform charges largest simultaneously live pair"); + r.Options.AsUINT64 |= 1ull << options::kSwizzleShift; + r.DestinationSize = 1024; + check(staging_bytes(r) == 2048, "unshuffle holds both complete block images"); + + StagingPool pool; + constexpr uint64_t limit = StagingPool::limit; + { + StagingPool::Lease publisher(pool), helper(pool), refused(pool); + publisher.acquire(limit - 100); + check(!refused.try_pair(101), "helper falls back when either member of pair cannot fit"); + check(helper.try_pair(100), "helper and publisher reserve the exact remaining budget"); + check(!refused.try_pair(1), "full pool prevents another helper allocation"); + } + { + StagingPool::Lease a(pool), b(pool), c(pool); + check(a.try_pair(1) && b.try_pair(1) && !c.try_pair(1), "at most two helpers hold buffers"); + } + std::atomic waiting{}, entered{}; + std::thread other; + { + StagingPool::Lease large(pool), concurrent(pool); + large.acquire(limit + 1); + check(!concurrent.try_pair(1), "oversize request holds the pool exclusively"); + other = std::thread([&] { + StagingPool::Lease next(pool); + waiting = true; + next.acquire(limit); + entered = true; + }); + while (!waiting) std::this_thread::yield(); + check(!entered, "ordinary publisher waits while exclusive request holds buffers"); + } + other.join(); + check(entered, "waiting publisher wakes when exclusive buffers are released"); + StagingPool::Lease reclaimed(pool); + check(reclaimed.try_pair(limit), "pool is entirely reusable after the last publisher"); +} + void test_layout_and_options() { DSTORAGE_REQUEST_OPTIONS o{}; o.ZlibDecompress = 1; @@ -371,6 +428,33 @@ void test_open_paths(Env& env) { q->Release(); } +// Simulate a committed page made read-only by the runtime's D3D shadow tracker. +void test_shadowed_file_destination(Env& env) { + constexpr DWORD size = 4096; + void* page = VirtualAlloc(nullptr, size, MEM_RESERVE | MEM_COMMIT, PAGE_READONLY); + check(page != nullptr, "allocate a watched file destination"); + if (!page) return; + auto* file = open(env, L"game:/data/b.bin"); + auto* queue = make_queue(env); + auto* status = make_status(env, 1); + leonida::kernel_writes::set_opener([](uintptr_t begin, uintptr_t end) { + DWORD old = 0; + VirtualProtect(reinterpret_cast(begin), end - begin, PAGE_READWRITE, &old); + }); + auto request = file_request(file, 129, page, size); + queue->EnqueueRequest(&request); + queue->EnqueueStatus(status, 0); + queue->Submit(); + queue->Close(); + leonida::kernel_writes::set_opener(nullptr); + check_hr(status->GetHResult(0), S_OK, "file read to a watched destination"); + check(std::memcmp(page, env.b.data() + 129, size) == 0, "watched destination received the file range"); + status->Release(); + queue->Release(); + file->Release(); + VirtualFree(page, 0, MEM_RELEASE); +} + void test_reads_and_errors(Env& env) { IDStorageFileX* b = open(env, L"GAME:\\data\\b.bin"); // 10,000 bytes IDStorageFileX* big = open(env, L"GAME:\\data\\big.bin"); @@ -404,10 +488,10 @@ void test_reads_and_errors(Env& env) { cases.push_back({r, E_DSTORAGE_INVALID_DESTINATION_SIZE, "zlib with DestinationSize equal to SourceSize"}); r = file_request(b, 0, few.data(), 8); r.Options.BcpackMode = DSTORAGE_BCPACK_MODE_BC1; - cases.push_back({r, E_NOTIMPL, "BCPack is not implemented yet"}); + cases.push_back({r, E_DSTORAGE_INVALID_DESTINATION_SIZE, "BCPack needs a larger output"}); r = file_request(b, 0, few.data(), 8); r.Options.SwizzleMode = DSTORAGE_SWIZZLE_MODE_4K_4K_8K; - cases.push_back({r, E_NOTIMPL, "swizzle is not implemented yet"}); + cases.push_back({r, E_DSTORAGE_INVALID_DESTINATION_SIZE, "partial swizzle group"}); r = file_request(b, 0, few.data(), 8); r.Options.AsUINT64 = 8ull << options::kBcpackShift; cases.push_back({r, E_DSTORAGE_INVALID_BCPACK_MODE, "BCPack mode 8"}); @@ -419,7 +503,7 @@ void test_reads_and_errors(Env& env) { cases.push_back({r, E_DSTORAGE_RESERVED_FIELDS, "a reserved option bit"}); r = file_request(b, 0, few.data(), 8); r.Options.DestinationIsPhysicalPages = 1; - cases.push_back({r, E_NOTIMPL, "physical pages are not implemented yet"}); + cases.push_back({r, E_INVALIDARG, "unknown physical page"}); r = file_request(b, 0, few.data(), 8); r.IntermediateSize = 4; cases.push_back({r, E_DSTORAGE_INVALID_INTERMEDIATE_SIZE, "IntermediateSize without zlib and BCPack"}); @@ -887,8 +971,8 @@ void test_iid_policy_events_and_cancel(Env& env) { q->Release(); } -// Holds the queue's worker inside a copy: the copy's source is a guard page, and this handler waits on the first -// touch until the test releases it. The guard is gone after that fault, so the copy then goes on. +// Hold the worker at its first read. PAGE_NOACCESS gives a catchable access violation on Windows and Proton. +// The handler restores read access before retrying exactly that instruction. struct GuardHold { uint8_t* page = nullptr; HANDLE entered = nullptr; @@ -898,10 +982,12 @@ GuardHold* g_hold = nullptr; LONG CALLBACK hold_on_guard(EXCEPTION_POINTERS* x) { const EXCEPTION_RECORD* e = x->ExceptionRecord; - if (!g_hold || e->ExceptionCode != STATUS_GUARD_PAGE_VIOLATION || e->NumberParameters < 2) + if (!g_hold || e->ExceptionCode != EXCEPTION_ACCESS_VIOLATION || e->NumberParameters < 2) return EXCEPTION_CONTINUE_SEARCH; const auto* address = reinterpret_cast(e->ExceptionInformation[1]); if (address < g_hold->page || address >= g_hold->page + 4096) return EXCEPTION_CONTINUE_SEARCH; + DWORD old; + if (!VirtualProtect(g_hold->page, 4096, PAGE_READWRITE, &old)) return EXCEPTION_CONTINUE_SEARCH; SetEvent(g_hold->entered); WaitForSingleObject(g_hold->release, 10000); return EXCEPTION_CONTINUE_EXECUTION; @@ -930,7 +1016,7 @@ void test_stats_timing(Env& env) { } std::memset(hold.page, 0x5A, 4096); DWORD old = 0; - VirtualProtect(hold.page, 4096, PAGE_READWRITE | PAGE_GUARD, &old); + check(VirtualProtect(hold.page, 4096, PAGE_NOACCESS, &old) != FALSE, "arm the first-read barrier"); std::vector out(4096, 0); DSTORAGE_REQUEST r{}; r.Options.SourceType = DSTORAGE_REQUEST_SOURCE_MEMORY; @@ -1122,9 +1208,9 @@ void test_zlib(Env& env) { {file.size() - 16, 32, 64, E_DSTORAGE_END_OF_FILE, nullptr, "a zlib source past the end of the file"}, {at_dynamic, z, 3191, E_DSTORAGE_INVALID_INTERMEDIATE_SIZE, nullptr, "zlib with an IntermediateSize", 0, 16}, - {at_dynamic, z, 3191, E_NOTIMPL, nullptr, "zlib and BCPack is not implemented yet", + {at_dynamic, z, 3191, E_DSTORAGE_INVALID_DESTINATION_SIZE, nullptr, "zlib plus BCPack needs whole blocks", static_cast(DSTORAGE_BCPACK_MODE_BC1) << options::kBcpackShift, 64}, - {at_dynamic, z, 3191, E_NOTIMPL, nullptr, "zlib and swizzle is not implemented yet", + {at_dynamic, z, 3191, E_DSTORAGE_INVALID_DESTINATION_SIZE, nullptr, "zlib plus swizzle needs complete groups", static_cast(DSTORAGE_SWIZZLE_MODE_4K_4K_8K) << options::kSwizzleShift}, }; @@ -1215,6 +1301,214 @@ void test_zlib(Env& env) { "TotalDecompressionRequestCount counts the zlib requests that reached the inflate"); check(after.DecompressionErrors - before.DecompressionErrors == 8, "DecompressionErrors counts the bad streams"); check(after.PendingDecompressionRequestCount == 0, "no decompression is pending afterwards"); + + // Both file transforms may prepare concurrently, but publish to the same buffer + // in enqueue order. The status after an invalid pair must retain its first error. + f = open(env, L"GAME:\\data\\zlib.bin"); + q = make_queue(env, kMinQueueCapacity, false); + s = make_status(env, 2); + std::vector overlap(dynamic_plain.size() + 1, 0xee); + auto enqueue_zlib = [&](uint64_t at, uint32_t source, uint32_t dest) { + auto request = file_request(f, at, overlap.data(), source); + request.Options.AsUINT64 = options::kZlib; + request.DestinationSize = dest; + q->EnqueueRequest(&request); + }; + enqueue_zlib(at_dynamic, z, 3191); + enqueue_zlib(at_fixed, 77, 196); + q->EnqueueStatus(s, 0); + enqueue_zlib(at_check, z, 3191); + enqueue_zlib(at_type, 77, 196); + q->EnqueueStatus(s, 1); + q->Submit(); + f->Close(); + check(wait_complete(s, 1), "adjacent file transforms retire before the final status"); + check_hr(s->GetHResult(0), S_OK, "overlapping file outputs complete in queue order"); + check_hr(s->GetHResult(1), E_DSTORAGE_ZLIB_PARITY_FAIL, "a pair reports the first failure in enqueue order"); + auto expected = dynamic_plain; + std::copy(fixed_plain.begin(), fixed_plain.end(), expected.begin()); + expected.push_back(0xee); + check(overlap == expected, "ordered publication and failed transforms preserve every destination byte"); + s->Release(); + q->Release(); + f->Release(); +} + +struct Vector { + unsigned codec; + std::span raw, plain, wrapped; +}; +#include "dstorage_vectors.inc" + +leonida::bcpack::Calibration test_profile() { + leonida::bcpack::Calibration history{}; + auto& six = history.bc6[255]; + for (unsigned c = 0; c < 3; ++c) six.ep[8 * c + 1] = 16; + six.ep_class = six.ix_class = 3; + six.ep_confirmed.fill(16); + six.ix_confirmed.fill(4); + auto& seven = history.bc7[255]; + seven.ep.fill(64); + seven.ep_bits.fill(8); + seven.ep_confirmed.fill(8); + seven.ix_bits.fill(4); + seven.ix_confirmed.fill(4); + return history; +} + +void test_extended(Env& env) { + auto* q = make_queue(env, 0x80, false, DSTORAGE_REQUEST_SOURCE_MEMORY, DSTORAGE_PRIORITY_REALTIME); + auto* status = make_status(env, 1); + auto submit = [&](DSTORAGE_REQUEST& r, HRESULT want) { + q->EnqueueRequest(&r); + q->EnqueueStatus(status, 0); + check_hr(status->GetHResult(0), E_PENDING, "extended request is pending before Submit"); + q->Submit(); + check(wait_complete(status, 0), "extended request retires"); + check_hr(status->GetHResult(0), want, "extended request status"); + }; + DSTORAGE_REQUEST r{}; + for (const auto& v : vectors) { + for (bool zlib : {false, true}) { + const auto source = zlib ? v.wrapped : v.raw; + const size_t bytes = v.plain.size(); + std::vector output(bytes+1, 0xA5); + r = {}; + r.Options.AsUINT64 = options::kSourceMemory | (v.codec << options::kBcpackShift) | zlib; + r.Source = source.data(); + r.SourceSize = static_cast(source.size()); + r.IntermediateSize = zlib ? static_cast(v.raw.size()) : 0; + r.Destination = output.data(); + r.DestinationSize = static_cast(bytes); + submit(r, S_OK); + check(std::equal(v.plain.begin(), v.plain.end(), output.begin()) && output.back() == 0xA5, + "BC blocks equal the Python decoder, including all mode fields"); + if (!zlib) { + std::fill(output.begin(), output.end(), 0xA5); + r.SourceSize /= 2; + submit(r, E_DSTORAGE_DECOMPRESSION_ERROR); + check(std::all_of(output.begin(), output.end(), [](uint8_t v){return v == 0xA5;}), + "a truncated BCPack stream publishes no bytes"); + } + } + } + { + auto history = test_profile(); + auto& six = history.bc6[255]; + auto& seven = history.bc7[255]; + for (unsigned codec : {6u, 7u}) { + const std::span raw = codec == 6 ? std::span(profile_raw6) : profile_raw7; + const uint8_t* first = codec == 6 ? profile_first6 : profile_first7; + std::vector result(512); + check(leonida::bcpack::decode(codec, raw, result, false, &history) == leonida::bcpack::Quality::confirmed, + "confirmed local BPTC predictor accepts the stream"); + bool exact = true; + for (size_t j = 0; j < result.size(); ++j) exact &= result[j] == first[j % 16]; + check(exact, "propagated external BPTC history matches all reference blocks"); + DSTORAGE_REQUEST from_profile{}; + from_profile.Options.AsUINT64 = options::kSourceMemory | (uint64_t(codec) << options::kBcpackShift); + from_profile.Source = raw.data(); + from_profile.SourceSize = static_cast(raw.size()); + from_profile.Destination = result.data(); + from_profile.DestinationSize = static_cast(result.size()); + std::fill(result.begin(), result.end(), 0xA5); + submit(from_profile, S_OK); + bool default_exact = true; + for (size_t j = 0; j < result.size(); ++j) default_exact &= result[j] == first[j % 16]; + check(default_exact, "default sidecar next to the shader library supplies exact reference blocks"); + if (codec == 6) six.ep_class = 1; + else seven.ep_confirmed.fill(0); + check(leonida::bcpack::decode(codec, raw, result, false, &history) == leonida::bcpack::Quality::failed && + leonida::bcpack::decode(codec, raw, result, true, &history) == leonida::bcpack::Quality::fitted, + "partially confirmed BPTC profile requires fitted mode"); + } + } + std::vector fitted(512); + check(leonida::bcpack::decode(1, fitted_raw, fitted) == leonida::bcpack::Quality::failed, + "strict decoding rejects fitted history"); + check(leonida::bcpack::decode(1, fitted_raw, fitted, true) == leonida::bcpack::Quality::fitted && + std::equal(std::begin(fitted_first), std::end(fitted_first), fitted.begin()), + "opt-in fitted history matches the reference and reports its quality"); + + // Three groups make an accidental per-64-KiB permutation distinguishable from macro-unshuffle. + const std::vector> planes = {{1,1,2},{1,1,6},{1,3,1,1,2},{1,3,1,3}}; + for (unsigned m = 1; m <= 4; ++m) { + std::vector input, expected; + for (unsigned c = 0; c < planes[m-1].size(); ++c) + for (int group = 0; group < 3; ++group) + input.insert(input.end(), planes[m-1][c]*4096, uint8_t(16*group+c)); + for (int group = 0; group < 3; ++group) + for (unsigned c = 0; c < planes[m-1].size(); ++c) + expected.insert(expected.end(), planes[m-1][c]*4096, uint8_t(16*group+c)); + std::vector output(expected.size()); + r = {}; + r.Options.AsUINT64 = options::kSourceMemory | (m << options::kSwizzleShift); + r.Source = input.data(); + r.Destination = output.data(); + r.SourceSize = r.DestinationSize = static_cast(output.size()); + submit(r, S_OK); + check(output == expected, "all component stripes reach the corresponding group"); + } + + const auto alloc = reinterpret_cast( + rt::shims::find("xmem.dll", "XMemAllocatePhysicalPages")); + const auto reserve = reinterpret_cast( + rt::shims::find("xmem.dll", "XMemVirtualAlloc")); + const auto map = reinterpret_cast( + rt::shims::find("xmem.dll", "XMemMapPhysicalPages")); + const auto free_pages = reinterpret_cast( + rt::shims::find("xmem.dll", "XMemFreePhysicalPages")); + uint64_t pages[2]{}, count = 2; + constexpr size_t page = 65536, offset = page-7; + auto* window = static_cast(reserve(nullptr, 2*page, MEM_RESERVE | 0x20400000, 0x21, PAGE_READWRITE)); + const bool allocated = window && alloc(0x280, &count, pages); + const bool mapped = allocated && map(window, 2, pages) == window; + check(mapped, "two physical pages mapped"); + if (mapped) { + ULONG_PTR scatter[] = {pages[1], 0}; + const auto& v = vectors[0]; + r = {}; + r.Options.AsUINT64 = options::kSourceMemory | options::kDestinationPages | options::kZlib | + (v.codec << options::kBcpackShift); + r.DestinationPageArray = scatter; + r.DestinationPageOffset = offset; + r.DestinationSize = static_cast(v.plain.size()); + r.Source = v.wrapped.data(); + r.SourceSize = static_cast(v.wrapped.size()); + r.IntermediateSize = static_cast(v.raw.size()); + submit(r, E_INVALIDARG); + check(window[page+offset] == 0, "bad final page leaves the first untouched"); + bool overflow; + leonida::title_texel_writes::take(overflow); + q->EnqueueRequest(&r); + q->EnqueueStatus(status, 0); + HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + q->EnqueueSetEvent(event); + scatter[1] = pages[0]; // resolved when the worker runs + q->Submit(); + check(WaitForSingleObject(event, 10000) == WAIT_OBJECT_0, "event follows the scatter write"); + CloseHandle(event); + check_hr(status->GetHResult(0), S_OK, "page list resolved after enqueue"); + check(std::equal(v.plain.begin(), v.plain.begin()+7, window+page+offset) && + std::equal(v.plain.begin()+7, v.plain.end(), window), "scatter is visible through the mapped CPU view"); + const auto ranges = leonida::title_texel_writes::take(overflow); + check(ranges.size() == 2 && ranges[0].first == reinterpret_cast(window+page+offset) && + ranges[1].first == reinterpret_cast(window), "refill sees both mapped ranges"); + std::vector out(v.plain.size()); + r = {}; + r.Options.AsUINT64 = options::kSourceMemory | options::kSourcePages; + r.SourcePageArray = scatter; + r.SourcePageOffset = offset; + r.SourceSize = r.DestinationSize = static_cast(out.size()); + r.Destination = out.data(); + submit(r, S_OK); + check(std::equal(v.plain.begin(), v.plain.end(), out.begin()), "gather follows the page list and offset"); + map(window, 2, nullptr); + } + if (allocated) free_pages(count, pages); + if (window) VirtualFree(window, 0, MEM_RELEASE); + status->Release(); + q->Release(); } } // namespace @@ -1237,12 +1531,31 @@ int main() { write_file(env.game / L"data" / L"b.bin", env.b); write_file(env.game / L"data" / L"big.bin", env.big); rt::fs::configure(env.game, env.overlay); - + const auto profile = test_profile(); + std::vector packed_profile(8 + sizeof profile); + std::memcpy(packed_profile.data(), "BCPHIST1", 8); + std::memcpy(packed_profile.data() + 8, &profile, sizeof profile); + write_file(env.root / L"shaders/bcpack/history.bcph", packed_profile); + SetEnvironmentVariableW(L"LEONIDA_DSTORAGE_HISTORY", nullptr); + SetEnvironmentVariableW(L"LEONIDA_SHADERS", (env.root / L"shaders/spirv").c_str()); + + + bool entropy_exact = true; + for (int width = 1; width <= 8; ++width) { + for (int q = 0; q < 16; ++q) { + const auto& model = leonida::bcpack::detail::model_for(width, q); + for (uint32_t slot = 0; slot < 65536; ++slot) + entropy_exact &= model.symbol(slot, true) == model.symbol(slot, false); + } + } + check(entropy_exact, "fast entropy lookup matches scalar division for every slot in all 128 models"); test_layout_and_options(); + test_staging_budget(); test_registry(env); test_factory_checks(env); test_open_paths(env); test_reads_and_errors(env); + test_shadowed_file_destination(env); test_fence_order_and_events(env); test_cancel(env); test_auto_submit_and_full_queue(env); @@ -1252,6 +1565,7 @@ int main() { test_iid_policy_events_and_cancel(env); test_stats_timing(env); test_stats(env); + test_extended(env); test_zlib(env); // after test_stats, whose request totals it would change fs::remove_all(env.root, ec); diff --git a/runtime/test/dstorage_vectors.py b/runtime/test/dstorage_vectors.py new file mode 100644 index 0000000000..0d2d50305d --- /dev/null +++ b/runtime/test/dstorage_vectors.py @@ -0,0 +1,93 @@ +"""Make synthetic DirectStorage requests with the test rANS encoder and the reference BCn decoder.""" +from pathlib import Path +import sys +import zlib + +root = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(root / "tests")) +import test_bcpack as enc + + +def build(codec): + block_count = 64 + single = codec in (1, 4) + count = block_count if single else 2 * block_count + lanes = [[0] * count for _ in enc.bcpack.LANE_WIDTHS[codec]] + for k in range(2, 11 if codec >= 6 else 12): + for i in range(count): + lanes[k][i] = (i % 4 + k) % 5 + if codec == 6: + for i in range(block_count): + mode = i % 14 + lanes[15][2*i:2*i+2] = (mode, i % 32) + bits = 3 if mode < 10 else 4 + # The initial half-range index needs a negative delta to reach zero. + if i: + lanes[1][2*i:2*i+2] = enc._deint4(1) + delta = 0 if i else (1 << bits) - 1 + for y in range(4): + lanes[11+y][2*i:2*i+2] = [enc._pack_ix_pair(delta, delta, y)] * 2 + if codec == 7: + # Use all eight modes with zero p-bits and legal anchor indices. + cfg = enc.bptc.load_bc7() + for i in range(block_count): + rank = next(r for r, v in enumerate(cfg["config"]) + if v[0] == i % 8 and r not in cfg["inferred"]) + lanes[15][2*i:2*i+2] = divmod(cfg["rank_of"].index(rank), 16) + for k in (2, 6, 7, 8, 10): + lanes[k] = [0] * count + # Select the smallest model encoding per lane so both bare and wrapped requests + # meet DirectStorage's requirement that the destination exceed the source. + widths = enc.bcpack.LANE_WIDTHS[codec] + q = [min(range(16), key=lambda q: len(enc._encode_fragment(symbols, w, w, q)[0])) + for symbols, w in zip(lanes, widths)] + raw = enc.encode_lanes(lanes, codec, q=q) + plain = enc.bcpack.decode(raw, codec, 8 * count) + assert len(raw) < len(plain) and len(zlib.compress(raw)) < len(plain) + return raw, plain + + +def write(out): + for codec in (1, 3, 4, 5, 6, 7): + raw, plain = build(codec) + for name, data in (("raw", raw), ("plain", plain), ("wrapped", zlib.compress(raw))): + print(f"static constexpr uint8_t {name}{codec}[] = {{", file=out) + for i in range(0, len(data), 24): + print(" " + ", ".join(map(str, data[i:i+24])) + ",", file=out) + print("};", file=out) + for codec in (6, 7): + lanes = [[0] * 64 for _ in range(16)] + cfg = enc.bptc.load_bc7() + rank = cfg["config"].index((6, 0, 0, 0)) + for block in range(32): + lanes[1][2*block:2*block+2] = enc._deint4(1) + if codec == 7: + lanes[15][2*block:2*block+2] = divmod(cfg["rank_of"].index(rank), 16) + history = {"bc6h": {"endpointHistory": {255: [[4096, 0, 0, 0]] * 3}, "indexHistory": {255: [0]*16}, + "endpointClass": {255: 3}, "indexClass": {255: 3}}, + "bc7": {"historyEndpoints": {255: [64]*24}, "historyEndpointBits": {255: [8]*24}, + "historyEndpointConfirmedBits": {255: [8]*24}, "historyIndices": {255: [0]*32}, + "historyIndexBits": {255: [4]*32}, "historyIndexConfirmedBits": {255: [4]*32}}} + packed = enc.encode_lanes(lanes, codec, q=10) + expected = enc.bcpack.decode(packed, codec, 512, history=history) + assert expected[:16] * 32 == expected + for label, data in (("profile_raw", packed), ("profile_first", expected[:16])): + print(f"static constexpr uint8_t {label}{codec}[] = {{{', '.join(map(str, data))}}};", file=out) + seed = next(iter(enc.tables.BC1_HISTORY_PROVISIONAL)) + lanes = [[0] * 64 for _ in range(12)] + distance = 256 - seed + lanes[0][0] = enc._zig(distance if distance < 128 else distance - 256) + raw = enc.encode_lanes(lanes, 1, q=12) + plain, info = enc.bcpack.decode_with_info(raw, 1, 512, allow_provisional=True) + assert info + print(f"static constexpr uint8_t fitted_raw[] = {{{', '.join(map(str, raw))}}};", file=out) + print(f"static constexpr uint8_t fitted_first[] = {{{', '.join(map(str, plain[:8]))}}};", file=out) + print("static constexpr Vector vectors[] = {", file=out) + for c in (1, 3, 4, 5, 6, 7): + print(f" {{{c}, raw{c}, plain{c}, wrapped{c}}},", file=out) + print("};", file=out) + + +if __name__ == "__main__": + with Path(sys.argv[1]).open("w", encoding="utf-8", newline="\n") as output: + write(output) diff --git a/runtime/test/dxgi_swapchain_count_test.cpp b/runtime/test/dxgi_swapchain_count_test.cpp index 4efa3ebefe..fbbca182ac 100644 --- a/runtime/test/dxgi_swapchain_count_test.cpp +++ b/runtime/test/dxgi_swapchain_count_test.cpp @@ -270,7 +270,8 @@ int run_case(const char* label, std::uint32_t requested, std::uint32_t native, s std::mutex mutex; leonida::VulkanSwapchain swapchain(get_instance_proc, reinterpret_cast(1), reinterpret_cast(2), get_device_proc, - reinterpret_cast(3), reinterpret_cast(4), 0, mutex); + reinterpret_cast(3), reinterpret_cast(4), 0, mutex, + /*diagnostics=*/nullptr); if (!swapchain.create(reinterpret_cast(static_cast(1)), 64, 64, VK_FORMAT_B8G8R8A8_UNORM, requested)) return fail("VulkanSwapchain::create"); @@ -377,7 +378,8 @@ int run_failed_resize(const char* label, std::uint32_t requested, std::uint32_t std::mutex mutex; leonida::VulkanSwapchain swapchain(get_instance_proc, reinterpret_cast(1), reinterpret_cast(2), get_device_proc, - reinterpret_cast(3), reinterpret_cast(4), 0, mutex); + reinterpret_cast(3), reinterpret_cast(4), 0, mutex, + /*diagnostics=*/nullptr); if (!swapchain.create(reinterpret_cast(static_cast(1)), 64, 64, VK_FORMAT_B8G8R8A8_UNORM, requested)) return fail("VulkanSwapchain::create"); diff --git a/runtime/test/fixtures/tiny_gdk_load.cpp b/runtime/test/fixtures/tiny_gdk_load.cpp index 7a6ca6cc6c..2d1cf6af34 100644 --- a/runtime/test/fixtures/tiny_gdk_load.cpp +++ b/runtime/test/fixtures/tiny_gdk_load.cpp @@ -1,7 +1,7 @@ // A mapped program that reaches the GDK runtime the way xgameruntime.lib's thunks do: it has no import of -// xgameruntime.dll, loads it with LoadLibraryW and looks the five run-time entry points up with GetProcAddress -// (measured in the package's libHttpClient.GDK.dll and XCurl.dll, docs/runtime_imports.md "Run-time loaded -// modules"). Run under `gta6rt --run`, its own kernel32 imports are bound by the loader, so LoadLibraryW and +// xgameruntime.dll, loads it with LoadLibraryW and looks the five run-time entry points and XErrorReport up with +// GetProcAddress (measured in the package's libHttpClient.GDK.dll and XCurl.dll, docs/runtime_imports.md "Run-time +// loaded modules"). Run under `gta6rt --run`, its own kernel32 imports are bound by the loader, so LoadLibraryW and // GetProcAddress must reach runtime/shims/library_loader.cpp and the offline xgameruntime shim. Run on its own, // LoadLibraryW goes to Windows and either fails or loads the PC's Gaming Services runtime, and this never prints // PASS. Ordinary test code; no game data. @@ -23,6 +23,9 @@ struct Options { // InitializeApiImplEx2's fourth argument (xodus-gaming/ using InitEx2 = HRESULT(WINAPI*)(ULONG, ULONG, char, const Options*); using Query = HRESULT(WINAPI*)(const GUID*, REFIID, void**); using Uninit = HRESULT(WINAPI*)(); +using Report = HRESULT(WINAPI*)(HRESULT, const char*); + +HRESULT g_reported = S_OK; // what the XErrorSetCallback callback last received int fail(const char* stage, unsigned long value) { std::printf("tiny_gdk_load: FAIL %s (0x%08lx)\n", stage, value); @@ -66,8 +69,9 @@ int main() { if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, L"xgameruntime.dll", &host_view) && host_view == runtime) return fail("xgameruntime.dll came from the host loader, not the shims", 0); + // XErrorReport too: the thunks look it up with the five entry points and refuse the runtime when it is missing. const char* names[] = {"InitializeApiImpl", "InitializeApiImplEx", "InitializeApiImplEx2", "UninitializeApiImpl", - "QueryApiImpl"}; + "QueryApiImpl", "XErrorReport"}; for (const char* name : names) if (!GetProcAddress(runtime, name)) return fail(name, GetLastError()); SetLastError(0); @@ -98,6 +102,27 @@ int main() { reinterpret_cast(vtable[17])(obj, queue); reinterpret_cast(vtable[2])(obj); + // The XErrorReport export and XErrorImpl's slot 3 are one function: a report through the export reaches the + // callback XErrorImpl's slot 4 (XErrorSetCallback) set. + const GUID error_class = {0x8ca467f7, 0x22e8, 0x4096, {0x84, 0x56, 0xbb, 0x8a, 0xa1, 0x3f, 0x79, 0xd8}}; + void* error = nullptr; + hr = query(&error_class, error_class, &error); + if (hr != S_OK || !error) return fail("QueryApiImpl hands out XErrorImpl", static_cast(hr)); + void* const* error_vtable = *static_cast(error); + using Callback = bool(CALLBACK*)(HRESULT, const char*, void*); + using SetCallback = void(STDMETHODCALLTYPE*)(void*, Callback, void*); + const Callback on_error = [](HRESULT reported, const char*, void*) { + g_reported = reported; + return true; + }; + reinterpret_cast(error_vtable[4])(error, on_error, nullptr); + auto report = reinterpret_cast(GetProcAddress(runtime, "XErrorReport")); + hr = report(E_FAIL, "tiny_gdk_load"); + reinterpret_cast(error_vtable[4])(error, nullptr, nullptr); + reinterpret_cast(error_vtable[2])(error); + if (hr != S_OK || g_reported != E_FAIL) + return fail("the XErrorReport export reaches the XErrorSetCallback callback", static_cast(hr)); + // A class not served (an id no runtime class has, made up for this test) is refused, with the out pointer // cleared. const GUID unserved = {0x4c454f4e, 0x4944, 0x4100, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}}; diff --git a/runtime/test/fixtures/tiny_startup_cmdline.cpp b/runtime/test/fixtures/tiny_startup_cmdline.cpp index b04529179a..e0c672c709 100644 --- a/runtime/test/fixtures/tiny_startup_cmdline.cpp +++ b/runtime/test/fixtures/tiny_startup_cmdline.cpp @@ -43,10 +43,26 @@ bool capture(Snapshot& s) { copy(s.wline, GetCommandLineW()); } +// Wine's ucrtbase (11.20 measured) builds both argv widths while it loads, so a process-attach callback already +// sees the final argc, __argv and __wargv, and a narrow main still has __wargv. Microsoft's UCRT configures neither +// before CRT startup and only the narrow one for main. Only under Wine is that accepted, so on Windows a loader that +// configures argv early still fails. +bool host_is_wine() { + static const bool wine = GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "wine_get_version") != nullptr; + return wine; +} + bool matches(const Snapshot& a, const Snapshot& b) { // Native UCRT has not configured either argv width at process attach. GetCommandLine is already complete. - return a.argc == 0 && !a.has_argv && !a.has_wargv && - std::strcmp(a.line, b.line) == 0 && std::wcscmp(a.wline, b.wline) == 0; + bool argv_ok = a.argc == 0 && !a.has_argv && !a.has_wargv; + if (!argv_ok && host_is_wine()) { + // Wine: argv may already be configured at attach, but then it must be the final one. + argv_ok = a.argc == b.argc && a.has_argv == b.has_argv && a.has_wargv == b.has_wargv; + for (int i = 0; argv_ok && i < a.argc; ++i) + argv_ok = (!a.has_argv || std::strcmp(a.argv[i], b.argv[i]) == 0) && + (!a.has_wargv || std::wcscmp(a.wargv[i], b.wargv[i]) == 0); + } + return argv_ok && std::strcmp(a.line, b.line) == 0 && std::wcscmp(a.wline, b.wline) == 0; } } // namespace @@ -83,7 +99,7 @@ extern "C" __declspec(allocate(".CRT$XLB")) PIMAGE_TLS_CALLBACK g_startup_callba int main(int argc, char** argv) { Snapshot entry{}; bool ok = capture(entry) && g_captured && matches(g_startup, entry) && startup_cmdline_matches(&entry); - ok = ok && argc == entry.argc && entry.has_argv && !entry.has_wargv; + ok = ok && argc == entry.argc && entry.has_argv && (!entry.has_wargv || host_is_wine()); for (int i = 0; ok && i < argc; ++i) ok = std::strcmp(argv[i], entry.argv[i]) == 0; std::printf("tiny_startup_cmdline: %s\n", ok ? "PASS" : "FAIL"); return ok ? 0 : 1; diff --git a/runtime/test/fixtures/tiny_thread_hook.cpp b/runtime/test/fixtures/tiny_thread_hook.cpp new file mode 100644 index 0000000000..0187d3265e --- /dev/null +++ b/runtime/test/fixtures/tiny_thread_hook.cpp @@ -0,0 +1,16 @@ +// Tiny fixture DLL for loader_tls_index0_test (threads): calls a function of the test EXE from its +// DllMain(DLL_THREAD_ATTACH). Loaded before the runtime's TLS helper, so on a new thread this runs before the helper's +// DLL_THREAD_ATTACH, the window in which only the OS has set up the thread's TLS. Ordinary test code, no game data. +#include + +namespace { +using Hook = void(__cdecl*)(); +Hook volatile g_hook = nullptr; +} // namespace + +extern "C" __declspec(dllexport) void __cdecl tiny_thread_hook_set(Hook hook) { g_hook = hook; } + +BOOL WINAPI DllMain(HINSTANCE, DWORD reason, LPVOID) { + if (reason == DLL_THREAD_ATTACH && g_hook) g_hook(); + return TRUE; +} diff --git a/runtime/test/fixtures/tiny_tls_clones.cpp b/runtime/test/fixtures/tiny_tls_clones.cpp new file mode 100644 index 0000000000..c3b957c4d0 --- /dev/null +++ b/runtime/test/fixtures/tiny_tls_clones.cpp @@ -0,0 +1,13 @@ +// Tiny fixture EXE for check_tls_clone_cleanup.cmake. It is ordinary test code, not game content. +// +// It imports two DLLs with static TLS, tiny_tls.dll and tiny_tls_cb_only.dll, and has TLS of its own. Mapped by gta6rt +// the EXE takes module TLS index 0, one DLL takes the primary helper's index and the other needs a helper clone +// (leonida_tls_host__1.dll in %TEMP%), whose file gta6rt has to delete when it exits. +extern "C" __declspec(dllimport) int __cdecl tiny_tls_get(); +extern "C" __declspec(dllimport) int __cdecl tiny_tls_cb_attach_count(); + +namespace { +thread_local int t_value = 3; +} + +int main() { return tiny_tls_get() == 7 && tiny_tls_cb_attach_count() >= 0 && t_value == 3 ? 0 : 1; } diff --git a/runtime/test/fixtures/tiny_tls_ga.cpp b/runtime/test/fixtures/tiny_tls_ga.cpp new file mode 100644 index 0000000000..a44d0e97d4 --- /dev/null +++ b/runtime/test/fixtures/tiny_tls_ga.cpp @@ -0,0 +1,35 @@ +// Tiny fixture EXE for module TLS index 0. It is ordinary test code, not game content. +// +// Built /GA (CMakeLists.txt), the EXE-only option that lets the compiler assume the image is the process executable +// and so has module TLS index 0: every thread_local access below reads TEB->ThreadLocalStoragePointer[0] directly +// (mov rax, gs:[58h]; mov rax, [rax]) and never loads _tls_index. Mapped with any other index, the getter reads +// whatever block sits in slot 0. loader_tls_index0_test calls the exports on threads of its own; under +// `gta6rt --run` (run_tiny_tls_ga) main() checks the value on the game thread and on a second thread and returns 0 +// only when both read the template value 42. +#include +#include + +extern "C" unsigned long _tls_index; + +namespace { +thread_local int t_value = 42; +} + +extern "C" __declspec(dllexport) __declspec(noinline) int __cdecl tiny_ga_get() { return t_value; } +extern "C" __declspec(dllexport) __declspec(noinline) void __cdecl tiny_ga_set(int value) { t_value = value; } +// Where this thread's t_value is, so the test can find its offset inside the slot-0 block. +extern "C" __declspec(dllexport) __declspec(noinline) int* __cdecl tiny_ga_address() { return &t_value; } +extern "C" __declspec(dllexport) unsigned long __cdecl tiny_ga_tls_index() { return _tls_index; } +extern "C" __declspec(dllexport) unsigned long* __cdecl tiny_ga_tls_index_address() { return &_tls_index; } + +int main() { + const int on_main = tiny_ga_get(); + tiny_ga_set(7); + int on_thread = -1; + std::thread worker([&] { on_thread = tiny_ga_get(); }); + worker.join(); + const bool ok = on_main == 42 && on_thread == 42 && tiny_ga_get() == 7; + std::printf("tiny_tls_ga: tls_index=%lu main=%d thread=%d %s\n", _tls_index, on_main, on_thread, + ok ? "OK" : "FAILED"); + return ok ? 0 : 1; +} diff --git a/runtime/test/frame_pacer_test.cpp b/runtime/test/frame_pacer_test.cpp index 81b647fd26..e7859698e2 100644 --- a/runtime/test/frame_pacer_test.cpp +++ b/runtime/test/frame_pacer_test.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include using namespace leonida; @@ -86,6 +87,24 @@ int main() { EXPECT(pacer.tokens_issued() == 2); } + { + ManualFrameClock clock; + auto tokens = std::make_shared(); + FramePacer pacer(clock, tokens); + EXPECT(pacer.token_source() == tokens); + const std::uint64_t outside = tokens->issue(); + EXPECT(outside == 1 && pacer.tokens_issued() == 1); + EXPECT(pacer.check_present_token(outside) == pacer_hr::ok); + EXPECT(pacer.check_present_token(outside + 1) == pacer_hr::invalid_arg); + EXPECT(setup(pacer, 1)); + clock.advance_us(period); + std::uint64_t token = 0; + EXPECT(pacer.wait_frame_event(frame_event_origin, 0, 0, &token) == pacer_hr::ok && token == outside + 1); + EXPECT(tokens->issue() == outside + 2); + EXPECT(pacer.check_present_token(outside + 2) == pacer_hr::ok); + EXPECT(pacer.check_present_token(outside + 3) == pacer_hr::invalid_arg); + } + // An offset delays the event inside the period: origin n comes at n * period + offset. { ManualFrameClock clock; diff --git a/runtime/test/gameinput_no_sdl_test.cpp b/runtime/test/gameinput_no_sdl_test.cpp new file mode 100644 index 0000000000..c8443f3b36 --- /dev/null +++ b/runtime/test/gameinput_no_sdl_test.cpp @@ -0,0 +1,46 @@ +// gameinput.dll!#1 without SDL3: the retail executable imports GameInputCreate by ordinal, and a build without SDL3 +// still has to hand back an interface instead of letting the loader fall through to the host's gameinput.dll, which +// answers with a null pointer that the title dereferences. +#include + +#include +#include + +#include "shims.h" + +namespace { +int g_failed = 0; +void check(bool ok, const char* what) { + std::printf("%s %s\n", ok ? "ok " : "FAIL ", what); + if (!ok) ++g_failed; +} +} // namespace + +int main() { + auto create = reinterpret_cast(rt::shims::find("gameinput.dll", "#1")); + auto named = reinterpret_cast(rt::shims::find("gameinput.dll", "GameInputCreate")); + check(create != nullptr, "the ordinal import gameinput.dll!#1 is served"); + check(named != nullptr, "the name GameInputCreate is served"); + if (!create) return 1; + + void* object = nullptr; + check(create(&object) == S_OK, "GameInputCreate returns S_OK"); + check(object != nullptr, "GameInputCreate hands back a non-null interface"); + if (!object) return 1; + + auto* vtable = *static_cast(object); + auto add_ref = reinterpret_cast(vtable[1]); + auto release = reinterpret_cast(vtable[2]); + check(add_ref(object) >= 1, "slot 1 (AddRef) is callable and counts"); + check(release(object) >= 0, "slot 2 (Release) is callable and does not underflow"); + + // A device query answers a clean refusal through the same object rather than faulting. + auto get_devices = reinterpret_cast(vtable[9]); + void* devices = reinterpret_cast(0x1); + check(get_devices(object, 0, &devices) == E_NOTIMPL, "an unserved slot returns E_NOTIMPL"); + check(devices == reinterpret_cast(0x1), "an unserved slot writes nothing to its out-parameter"); + + check(create(nullptr) == E_POINTER, "a null out parameter is E_POINTER"); + std::printf("%d failure(s)\n", g_failed); + return g_failed ? 1 : 0; +} diff --git a/runtime/test/gfx10_descriptors_test.cpp b/runtime/test/gfx10_descriptors_test.cpp index 85843edb83..efd0ce4eee 100644 --- a/runtime/test/gfx10_descriptors_test.cpp +++ b/runtime/test/gfx10_descriptors_test.cpp @@ -167,7 +167,15 @@ int main() { for (const FormatRow& row : format_table) { CHECK(row.gfx10 >= previous && row.gfx10 > 0 && row.gfx10 < 512); CHECK(seen.insert(row.vulkan).second); - CHECK(valid_swizzle(row.channels) && row.channels[0] != select_zero && row.channels[0] != select_one); + // Every format reads its first channel as red, but A8 (an A8_UNORM render target), whose only channel is alpha. +#ifdef VK_KHR_MAINTENANCE_5_EXTENSION_NAME + const bool alpha_only = row.vulkan == VK_FORMAT_A8_UNORM_KHR; +#else + const bool alpha_only = false; +#endif + CHECK(valid_swizzle(row.channels) && + (alpha_only ? row.channels == channels_a + : row.channels[0] != select_zero && row.channels[0] != select_one)); CHECK(format_from_vulkan(row.vulkan) == row.gfx10); CHECK(format_swizzle(row.vulkan) == row.channels); if (row.gfx10 != previous) { @@ -176,6 +184,17 @@ int main() { } previous = row.gfx10; } +#ifdef VK_KHR_MAINTENANCE_5_EXTENSION_NAME + // An A8 render target shares 8_UNORM with R8: an A8 image keeps its own view format, and the T#'s X is its alpha. + CHECK(format_from_vulkan(VK_FORMAT_A8_UNORM_KHR) == 1 && vulkan_format(1) == VK_FORMAT_R8_UNORM); + CHECK(vulkan_view_format(VK_FORMAT_A8_UNORM_KHR, 1) == VK_FORMAT_A8_UNORM_KHR); + { + const VkComponentMapping a8 = vulkan_swizzle(Swizzle{select_zero, select_zero, select_zero, select_x}, + VK_FORMAT_A8_UNORM_KHR); + CHECK(a8.r == VK_COMPONENT_SWIZZLE_ZERO && a8.g == VK_COMPONENT_SWIZZLE_ZERO && + a8.b == VK_COMPONENT_SWIZZLE_ZERO && a8.a == VK_COMPONENT_SWIZZLE_A); + } +#endif CHECK(vulkan_format(56) == VK_FORMAT_R8G8B8A8_UNORM && vulkan_format(130) == VK_FORMAT_R8G8B8A8_SRGB); CHECK(vulkan_format(22) == VK_FORMAT_R32_SFLOAT && format_from_vulkan(VK_FORMAT_D32_SFLOAT) == 22); CHECK(vulkan_format(7) == VK_FORMAT_R16_UNORM && format_from_vulkan(VK_FORMAT_D16_UNORM) == 7); diff --git a/runtime/test/glsl/cs_user_data.comp b/runtime/test/glsl/cs_user_data.comp index b285c0f3f9..85ce43927e 100644 --- a/runtime/test/glsl/cs_user_data.comp +++ b/runtime/test/glsl/cs_user_data.comp @@ -37,13 +37,42 @@ Words at(uvec2 va) { void main() { const uint i = gl_GlobalInvocationID.x; - Words table = at(uvec2(pc.s[8], 0u)); Words result = at(uvec2(pc.s[6], pc.s[7])); + if (pc.s[5] == 0xFFFFFFFCu) { + // Direct resource indexing. The explicit table is unrelated; the heap follows it at s9. + uint value = 0u; + if (pc.s[9] != 0u) { + Words view = at(uvec2(pc.s[9] + 32u * pc.s[4], 0u)); + uint byteOffset = (i % 4u) * 4u; + if (view.w[2] >= byteOffset + 4u) { + // V# buffer addresses are signed 48-bit offsets from heap_base. + uint high = uint(int(view.w[1] << 16u) >> 16); + value = at(uvec2(view.w[0], high)).w[byteOffset / 4u]; + } + } + result.w[i] = value; + return; + } + if (pc.s[5] == 0xFFFFFFFEu) { + // Root view read mode (d3d12_title_va_test): read through the root UAV itself, 256 bytes past its base, and + // write at the base, so the root view's address is both read and written. + result.w[i] = result.w[64u + i] + pc.s[4]; + return; + } + Words table = at(uvec2(pc.s[8], 0u)); + if (pc.s[5] == 0xFFFFFFFDu) { + // Root view read to a table pointer (d3d12_title_va_test): read through the root view, 256 bytes past its + // base, and write where the table entry's raw 64-bit VA points. + Words target = at(uvec2(table.w[0], table.w[1])); + target.w[i] = result.w[64u + i] + pc.s[4]; + return; + } if (pc.s[5] == 0u) { - // CBV V# mode: table holds a 16-byte GFX10 raw buffer descriptor written by CreateConstantBufferView. - const uint num_records = table.w[2]; + // Scalar CBV reads use byte capacity for both the console row descriptor and the raw override. + const uint stride = (table.w[1] >> 16u) & 0x3FFFu; + const uint capacity = table.w[2] * max(1u, stride); const uint byte_off = pc.s[4] + i * 4u; - if (byte_off + 4u <= num_records) { + if (byte_off + 4u <= capacity) { Words cbv = at(uvec2(table.w[0], table.w[1] & 0xFFFFu)); result.w[i] = cbv.w[byte_off >> 2u]; } else { @@ -60,9 +89,10 @@ void main() { if (oob_select == 3u) { const uint byte_off = pc.s[4] + i * 4u; result.w[i] = (byte_off + 4u <= num_records) ? at(base).w[byte_off >> 2u] : 0u; - } else if (oob_select == 1u && stride >= 4u) { - const uint idx = pc.s[4] + i; - result.w[i] = (idx < num_records) ? at(base).w[(idx * stride) >> 2u] : 0u; + } else if (oob_select <= 1u && stride >= 4u) { + const uint field = pc.s[4]; + const bool in_bounds = i < num_records && (oob_select == 1u || field <= stride - 4u); + result.w[i] = in_bounds ? at(base).w[(i * stride + field) >> 2u] : 0u; } else { result.w[i] = 0u; } diff --git a/runtime/test/glsl/ps_depth_write.frag b/runtime/test/glsl/ps_depth_write.frag index 959d1dd9de..b176e08ccf 100644 --- a/runtime/test/glsl/ps_depth_write.frag +++ b/runtime/test/glsl/ps_depth_write.frag @@ -1,5 +1,5 @@ #version 460 -// A pixel shader that writes its own depth (SV_Depth), for d3d12_depth24_draw_test: s2 is the depth it writes. On a +// A pixel shader that writes its own depth (SV_Depth), for d3d12_depth24_draw_test: s10 is the depth it writes. On a // D24 target the value is stored quantised to 24 bits, and D3D applies no depth bias to it. layout(push_constant) uniform UserData { @@ -9,5 +9,5 @@ layout(push_constant) uniform UserData { } pc; void main() { - gl_FragDepth = uintBitsToFloat(pc.s[2]); + gl_FragDepth = uintBitsToFloat(pc.s[10]); } diff --git a/runtime/test/glsl/ps_draw.frag b/runtime/test/glsl/ps_draw.frag index 2361330f41..d8e29425d7 100644 --- a/runtime/test/glsl/ps_draw.frag +++ b/runtime/test/glsl/ps_draw.frag @@ -1,10 +1,16 @@ #version 460 // A pixel shader written to the translator's runtime contract, standing in for a translated one in -// d3d12_draw_test. s2:s3 is a root CBV: the console VA of three floats (a tint), read at heap base + VA. The output -// is (red * tint.x, tint.y, blue * tint.z, 1). +// d3d12_draw_test. The tests' signatures are two root constants then a root CBV, so in the console's graphics layout +// (from s8, two dwords per root view: docs/d3d12_vulkan.md, D3D-448) s10:s11 is the CBV: the console VA of three +// floats (a tint), read at heap base + VA. The output is (red * tint.x, tint.y, blue * tint.z, 1). +// d3d12_mesh_test pads its signature onto the runtime's s0 fallback layout and builds this with -DROOT_BASE=0 (s2:s3). #extension GL_EXT_buffer_reference : require #extension GL_EXT_buffer_reference_uvec2 : require +#ifndef ROOT_BASE +#define ROOT_BASE 8 +#endif + layout(buffer_reference, std430, buffer_reference_align = 4) buffer Floats { float f[]; }; @@ -25,6 +31,6 @@ uvec2 add64(uvec2 a, uvec2 b) { } void main() { - Floats tint = Floats(add64(pc.heap_base, uvec2(pc.s[2], pc.s[3]))); + Floats tint = Floats(add64(pc.heap_base, uvec2(pc.s[ROOT_BASE + 2], pc.s[ROOT_BASE + 3]))); target = vec4(color.r * tint.f[0], tint.f[1], color.b * tint.f[2], 1.0); } diff --git a/runtime/test/glsl/ps_user_data_window.frag b/runtime/test/glsl/ps_user_data_window.frag new file mode 100644 index 0000000000..cd09e3cfc8 --- /dev/null +++ b/runtime/test/glsl/ps_user_data_window.frag @@ -0,0 +1,18 @@ +#version 460 +// The pixel shader of d3d12_graphics_direct_heaps_test: render target 0 gets the user-data dwords s10..s13 the +// vertex shader read, render target 1 the same dwords as this stage reads them. + +layout(location = 0) flat in uvec4 vs_words; +layout(location = 0) out uvec4 vs_target; +layout(location = 1) out uvec4 ps_target; + +layout(push_constant) uniform UserData { + uint s[32]; + uvec2 heap_base; + uvec2 code_base; +} pc; + +void main() { + vs_target = vs_words; + ps_target = uvec4(pc.s[10], pc.s[11], pc.s[12], pc.s[13]); +} diff --git a/runtime/test/glsl/vs_depth.vert b/runtime/test/glsl/vs_depth.vert index de1d6ee40d..34c1205a26 100644 --- a/runtime/test/glsl/vs_depth.vert +++ b/runtime/test/glsl/vs_depth.vert @@ -1,7 +1,8 @@ #version 460 // A full-screen triangle at a chosen depth, written to the translator's runtime contract (docs/design.md, "User -// data"), for d3d12_depth24_draw_test: s0 is the depth at the centre and s1 how much it changes per unit of clip-space -// x, so s1 = 0 gives a flat triangle and anything else a constant slope across the target. +// data"), for d3d12_depth24_draw_test: s8 is the depth at the centre and s9 how much it changes per unit of clip-space +// x, so s9 = 0 gives a flat triangle and anything else a constant slope across the target. Graphics root arguments +// start at s8 in the console layout (docs/d3d12_vulkan.md, D3D-448): the test's three root constants are s8..s10. layout(push_constant) uniform UserData { uint s[32]; @@ -12,5 +13,5 @@ layout(push_constant) uniform UserData { void main() { const vec2 corner = vec2(float(gl_VertexIndex & 2), float((gl_VertexIndex << 1) & 2)); const vec2 xy = corner * 2.0 - 1.0; - gl_Position = vec4(xy, uintBitsToFloat(pc.s[0]) + uintBitsToFloat(pc.s[1]) * xy.x, 1.0); + gl_Position = vec4(xy, uintBitsToFloat(pc.s[8]) + uintBitsToFloat(pc.s[9]) * xy.x, 1.0); } diff --git a/runtime/test/glsl/vs_draw.vert b/runtime/test/glsl/vs_draw.vert index 3cde02a50e..a6e61dacb6 100644 --- a/runtime/test/glsl/vs_draw.vert +++ b/runtime/test/glsl/vs_draw.vert @@ -2,7 +2,8 @@ // A vertex shader written to the translator's runtime contract (docs/design.md, "Vertex fetch" and "User data"), // standing in for a translated one in d3d12_draw_test. Inputs sit at location = D3D input register: COLOR is // register 0 and POSITION register 1 here, the reverse of the input layout's order, so the test shows that the -// layout is matched by semantic. s0, s1 (root constants) move the vertex in clip space. +// layout is matched by semantic. The first root parameter, two root constants, moves the vertex in clip space: s8, s9, +// since graphics root arguments start at s8 in the console layout (docs/d3d12_vulkan.md, D3D-448). layout(location = 0) in vec4 color; // COLOR0, input register 0 layout(location = 1) in vec4 position; // POSITION0, input register 1 @@ -16,7 +17,7 @@ layout(push_constant) uniform UserData { } pc; void main() { - const vec2 offset = vec2(uintBitsToFloat(pc.s[0]), uintBitsToFloat(pc.s[1])); + const vec2 offset = vec2(uintBitsToFloat(pc.s[8]), uintBitsToFloat(pc.s[9])); gl_Position = vec4(position.xy + offset, 0.0, 1.0); out_color = color; } diff --git a/runtime/test/glsl/vs_draw_int.vert b/runtime/test/glsl/vs_draw_int.vert index ea57824692..2d7f299aa3 100644 --- a/runtime/test/glsl/vs_draw_int.vert +++ b/runtime/test/glsl/vs_draw_int.vert @@ -14,7 +14,7 @@ layout(push_constant) uniform UserData { } pc; void main() { - const vec2 offset = vec2(uintBitsToFloat(pc.s[0]), uintBitsToFloat(pc.s[1])); + const vec2 offset = vec2(uintBitsToFloat(pc.s[8]), uintBitsToFloat(pc.s[9])); // s8, s9 as in vs_draw.vert gl_Position = vec4(position.xy + offset, 0.0, 1.0); out_color = vec4(color); } diff --git a/runtime/test/glsl/vs_user_data_window.vert b/runtime/test/glsl/vs_user_data_window.vert new file mode 100644 index 0000000000..759396689b --- /dev/null +++ b/runtime/test/glsl/vs_user_data_window.vert @@ -0,0 +1,19 @@ +#version 460 +// A vertex shader with no vertex inputs, written to the translator's runtime contract (docs/design.md, "User data"), +// for d3d12_graphics_direct_heaps_test: one triangle covering the viewport that hands the user-data dwords s10..s13 +// it reads to the pixel shader. Those are where a directly indexed signature's heaps land after a few dwords of +// explicit root arguments from s8. + +layout(location = 0) flat out uvec4 vs_words; + +layout(push_constant) uniform UserData { + uint s[32]; + uvec2 heap_base; + uvec2 code_base; +} pc; + +void main() { + const vec2 corner = vec2(float(gl_VertexIndex & 2), float((gl_VertexIndex << 1) & 2)); + gl_Position = vec4(corner * 2.0 - 1.0, 0.0, 1.0); + vs_words = uvec4(pc.s[10], pc.s[11], pc.s[12], pc.s[13]); +} diff --git a/runtime/test/kernel_writes_test.cpp b/runtime/test/kernel_writes_test.cpp new file mode 100644 index 0000000000..20b3477487 --- /dev/null +++ b/runtime/test/kernel_writes_test.cpp @@ -0,0 +1,88 @@ +// leonida::kernel_writes::read_file (runtime/src/title_page_watch.h) into memory that is reserved until its first +// touch, as xmem maps the title's physical pages (SEC_RESERVE section views committed by a fault handler): the kernel's +// write does not fault such a page in, so the read fails with ERROR_NOACCESS unless the committer runs first. No game +// data. +#include + +#include +#include +#include +#include + +#include "../src/title_page_watch.h" + +namespace { + +int g_checks = 0; +int g_failures = 0; + +void check(bool condition, const char* what) { + ++g_checks; + std::printf("%s %s\n", condition ? "PASS" : "FAIL", what); + if (!condition) ++g_failures; +} + +constexpr DWORD kViewBytes = 1 << 20; +constexpr DWORD kFileBytes = 256 * 1024; + +std::uint8_t* g_view = nullptr; +int g_commits = 0; + +// Stands in for rt::xmem::commit_physical_range: commits the part of the test view the range covers. +bool commit_view(const void* address, std::size_t bytes) { + ++g_commits; + const auto* begin = static_cast(address); + if (begin < g_view || begin + bytes > g_view + kViewBytes) return true; // not ours + return VirtualAlloc(const_cast(begin), bytes, MEM_COMMIT, PAGE_READWRITE) != nullptr; +} + +} // namespace + +int main() { + wchar_t dir[MAX_PATH], path[MAX_PATH]; + GetTempPathW(MAX_PATH, dir); + GetTempFileNameW(dir, L"kwt", 0, path); + std::vector bytes(kFileBytes); + for (DWORD i = 0; i < kFileBytes; ++i) bytes[i] = static_cast(i * 7 + (i >> 9)); + HANDLE file = CreateFileW(path, GENERIC_READ | GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, + FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE, nullptr); + DWORD written = 0; + check(file != INVALID_HANDLE_VALUE && WriteFile(file, bytes.data(), kFileBytes, &written, nullptr) && + written == kFileBytes, "temporary file written"); + + HANDLE section = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE | SEC_RESERVE, 0, kViewBytes, + nullptr); + g_view = section ? static_cast(MapViewOfFile(section, FILE_MAP_ALL_ACCESS, 0, 0, kViewBytes)) + : nullptr; + MEMORY_BASIC_INFORMATION info{}; + check(g_view && VirtualQuery(g_view, &info, sizeof(info)) && info.State == MEM_RESERVE, + "the destination view is reserved, not committed"); + std::uint8_t* destination = g_view + 0x10000; + + // Without a committer: what the title saw (Windows answers ERROR_NOACCESS; another host may fault the page in). + OVERLAPPED at{}; + DWORD got = 0; + const BOOL plain = leonida::kernel_writes::read_file(file, destination, kFileBytes, &got, &at); + std::printf(" without a committer: %s, error %lu\n", plain ? "read" : "failed", plain ? 0ul : GetLastError()); + + leonida::kernel_writes::set_committer(&commit_view); + at = {}; + got = 0; + const BOOL ok = leonida::kernel_writes::read_file(file, destination, kFileBytes, &got, &at); + check(ok && got == kFileBytes, "with the committer the read completes"); + check(ok && std::memcmp(destination, bytes.data(), kFileBytes) == 0, "and the destination holds the file's bytes"); + check(plain || g_commits == 1, "the committer ran once, for the failed read's retry"); + + // A read that succeeds first time does not call the committer. + const int before = g_commits; + at = {}; + check(leonida::kernel_writes::read_file(file, destination, kFileBytes, &got, &at) && g_commits == before, + "a read into committed memory does not call the committer"); + + leonida::kernel_writes::set_committer(nullptr); + UnmapViewOfFile(g_view); + CloseHandle(section); + CloseHandle(file); + std::printf("%d checks, %d failures\n", g_checks, g_failures); + return g_failures ? 1 : 0; +} diff --git a/runtime/test/loader_tls_index0_test.cpp b/runtime/test/loader_tls_index0_test.cpp new file mode 100644 index 0000000000..e9d6418766 --- /dev/null +++ b/runtime/test/loader_tls_index0_test.cpp @@ -0,0 +1,574 @@ +// End-to-end checks for module TLS index 0 and a mapped executable, against locally built fixtures. +// +// Windows gives the process executable module TLS index 0, and MSVC code built with /GA relies on it: it reads +// TEB->ThreadLocalStoragePointer[0] without loading _tls_index. tiny_tls_ga.exe is such an image (a thread_local int +// with the initializer 42, built /GA). rt::reserve_tls_index0 moves this test EXE's own TLS (index 0 at start) to the +// home clone's index, whose TLS template is a copy of this EXE's; the Loader then gives the executable index 0. +// +// loader_tls_index0_test runs +// Reserve at start, then: this EXE keeps its TLS on the reserving thread and every later thread finds a fresh +// copy at the home index; the executable reads 42 on the loading thread, a thread older than load() and new +// threads; its getter is /GA code; tiny_tls.dll keeps a helper index alongside; two runs in a row both get +// index 0, and a second executable mapped meanwhile gets a helper index. +// loader_tls_index0_test threads +// Threads are created all through the reservation, one waits suspended with no TLS array yet, and +// tiny_thread_hook.dll (loaded before the helper) runs this EXE's code in each new thread's DLL_THREAD_ATTACH, +// before the helper's: all of them find this EXE's TLS at the home index, the hook included. +// loader_tls_index0_test noreserve +// Without the reservation the executable maps with a helper index and this EXE keeps index 0. +// +// gta6rt_tls_host.dll must sit next to this EXE, as for loader_tls_test. No game files are needed. Every function +// that runs before the reservation, or calls it, touches no thread_local data: MSVC may keep a TLS slot address in a +// frame across calls, and the reservation has to come before any such frame exists (pe_loader.h). +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "pe_loader.h" + +extern "C" unsigned long _tls_index; // this EXE's module TLS index, read through its TLS directory's AddressOfIndex + +namespace { + +namespace fs = std::filesystem; + +int g_checks = 0; +int g_failures = 0; + +void check(bool condition, const char* what) { + ++g_checks; + std::printf("%s %s\n", condition ? "PASS" : "FAIL", what); + if (!condition) ++g_failures; +} + +// This EXE's own TLS: thread_local reads here go through _tls_index, so they follow the move. +thread_local int t_host = 1234; +thread_local bool t_hooked = false; +thread_local int t_seen_in_hook = -1; + +__declspec(noinline) int host_value() { return t_host; } +__declspec(noinline) void set_host_value(int value) { t_host = value; } +__declspec(noinline) const uint8_t* host_address() { return reinterpret_cast(&t_host); } + +void** module_tls_slots() { return reinterpret_cast(__readgsqword(0x58)); } + +const IMAGE_TLS_DIRECTORY64* tls_of(HMODULE module) { + auto* base = reinterpret_cast(module); + auto* nt = + reinterpret_cast(base + reinterpret_cast(base)->e_lfanew); + const auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS]; + return dir.Size ? reinterpret_cast(base + dir.VirtualAddress) : nullptr; +} + +// This EXE's TLS template: what every fresh block of it starts as. +struct Template { + const uint8_t* data = nullptr; + size_t size = 0; +}; +Template own_template() { + const auto* tls = tls_of(GetModuleHandleW(nullptr)); + return {reinterpret_cast(tls->StartAddressOfRawData), + static_cast(tls->EndAddressOfRawData - tls->StartAddressOfRawData + tls->SizeOfZeroFill)}; +} + +// The home clone, found by its file name, and the index the OS gave it (from its own AddressOfIndex, not from +// this EXE's _tls_index). +HMODULE home_module() { + const std::wstring name = L"leonida_tls_host_" + std::to_wstring(GetCurrentProcessId()) + L"_home.dll"; + return GetModuleHandleW(name.c_str()); +} +DWORD home_index() { + const HMODULE home = home_module(); + return home ? *reinterpret_cast(tls_of(home)->AddressOfIndex) : rt::kNoTlsIndex; +} + +bool inside(const uint8_t* p, const void* block, size_t size) { + const auto* b = static_cast(block); + return b && p >= b && p + sizeof(int) <= b + size; +} + +// Where this thread finds t_host: in the block at the home index, and not in the one at slot 0. +bool host_tls_at_home() { + const DWORD home = home_index(); + const size_t size = own_template().size; + return home != rt::kNoTlsIndex && inside(host_address(), module_tls_slots()[home], size) && + !inside(host_address(), module_tls_slots()[0], size); +} + +template +Fn find_export(const rt::Module& m, const char* name) { + const auto it = m.exports.find(name); + if (it == m.exports.end()) throw std::runtime_error(std::string("missing export ") + name); + return reinterpret_cast(it->second); +} + +struct Ga { + int(__cdecl* get)(); + void(__cdecl* set)(int); + int*(__cdecl* address)(); + unsigned long(__cdecl* tls_index)(); + unsigned long*(__cdecl* tls_index_address)(); +}; + +Ga ga_exports(const rt::Module& m) { + return {find_export(m, "tiny_ga_get"), find_export(m, "tiny_ga_set"), + find_export(m, "tiny_ga_address"), + find_export(m, "tiny_ga_tls_index"), + find_export(m, "tiny_ga_tls_index_address")}; +} + +// Code bytes of a function, past an incremental-linking jump stub (Debug builds export the stub). +const uint8_t* code_of(const void* fn) { + const auto* p = static_cast(fn); + if (p[0] == 0xE9) { + int32_t rel; + std::memcpy(&rel, p + 1, 4); + p += 5 + rel; + } + return p; +} + +// The /GA shape of the getter, up to its ret: a load of gs:[58h] (65 REX.W 8B /r with a SIB of disp32 0x58) and no +// rip-relative operand that lands on the image's _tls_index. +bool reads_slot0_without_index(const void* fn, const void* tls_index) { + const uint8_t* p = code_of(fn); + bool gs58 = false, index = false; + for (size_t i = 0; i < 64 && p[i] != 0xC3; ++i) { + if (p[i] == 0x65 && (p[i + 1] & 0xF8) == 0x48 && p[i + 2] == 0x8B && (p[i + 3] & 0xC7) == 0x04 && + p[i + 4] == 0x25 && p[i + 5] == 0x58 && !p[i + 6] && !p[i + 7] && !p[i + 8]) + gs58 = true; + int32_t disp; + std::memcpy(&disp, p + i, 4); + for (int tail = 4; tail <= 5; ++tail) // the displacement ends the instruction or is followed by an imm8 + index |= p + i + tail + disp == tls_index; + } + return gs58 && !index; +} + +// Calls the getter with stand-in blocks in slot 0 (77 at the variable's offset) and in slot `other` (88), and the +// executable's _tls_index pointing at `other`: /GA code reads 77, code that loads _tls_index reads 88. Slot `other` +// is this EXE's own TLS meanwhile, so nothing here touches thread_local data. +__declspec(noinline) int read_through_stand_ins(const Ga& ga, size_t offset, DWORD other) { + alignas(64) static uint8_t zero_slot[4096], other_slot[4096]; + const int seventy_seven = 77, eighty_eight = 88; + std::memcpy(zero_slot + offset, &seventy_seven, sizeof(int)); + std::memcpy(other_slot + offset, &eighty_eight, sizeof(int)); + void** slots = module_tls_slots(); + unsigned long* index = ga.tls_index_address(); + void* const saved0 = slots[0]; + void* const saved_other = slots[other]; + const unsigned long saved_index = *index; + slots[0] = zero_slot; + slots[other] = other_slot; + *index = other; + const int seen = ga.get(); + *index = saved_index; + slots[other] = saved_other; + slots[0] = saved0; + return seen; +} + +// What a thread started after the reservation sees, without any install call. +struct NewThreadView { + bool from_template = false; // its TLS at the home index starts from this EXE's template, not from zeros + int ga = -1, ga_after_set = -1, host = -1, dll = -1; + bool host_at_home = false; + void* slot0 = nullptr; +}; + +// ga may be null: then only this EXE's own TLS is looked at. +NewThreadView run_new_thread(const Ga* ga, int(__cdecl* dll_get)() = nullptr) { + NewThreadView v; + std::thread t([&] { + // Not the whole block: the helper's DLL_THREAD_ATTACH has already written the loader's own thread_local + // state there. -1 is a template value that a zero-filled block would not have. + v.from_template = t_seen_in_hook == -1; + v.slot0 = module_tls_slots()[0]; + if (ga) { + v.ga = ga->get(); + ga->set(9); + v.ga_after_set = ga->get(); + } + v.host = host_value(); + set_host_value(4321); + v.host_at_home = host_tls_at_home(); + if (dll_get) v.dll = dll_get(); + }); + t.join(); + return v; +} + +__declspec(noinline) bool call_reserve(std::string* why) { return rt::reserve_tls_index0(why); } + +// ---- runs ---- + +// A thread started before the reservation that runs no TLS code before it. After the move it installs the +// executable's copy itself (install_tls_for_thread, as for any module and a thread older than load()). +struct EarlyThread { + HANDLE go = CreateEventW(nullptr, TRUE, FALSE, nullptr); + HANDLE done = CreateEventW(nullptr, TRUE, FALSE, nullptr); + HANDLE quit = CreateEventW(nullptr, TRUE, FALSE, nullptr); + HANDLE handle = nullptr; + rt::Loader* loader = nullptr; + rt::Module* module = nullptr; + Ga ga{}; + int host = -1, ga_installed = -1, ga_after_set = -1; + bool host_at_home = false, block_in_slot0 = false, slot0_restored = false; + + static __declspec(noinline) void checks(EarlyThread* t) { + t->host = host_value(); + t->host_at_home = host_tls_at_home(); + void* before = module_tls_slots()[0]; + t->loader->install_tls_for_thread(*t->module); + t->block_in_slot0 = module_tls_slots()[0] != before; + t->ga_installed = t->ga.get(); + t->ga.set(5); + t->ga_after_set = t->ga.get(); + t->loader->uninstall_tls_for_thread(*t->module); + t->slot0_restored = module_tls_slots()[0] == before; + } + static DWORD WINAPI body(void* p) { // no TLS here: it runs from before the reservation + auto* t = static_cast(p); + WaitForSingleObject(t->go, INFINITE); + if (t->loader) checks(t); + SetEvent(t->done); + WaitForSingleObject(t->quit, INFINITE); // ends after both Loaders are gone + return 0; + } + __declspec(noinline) void start() { handle = CreateThread(nullptr, 0, &body, this, 0, nullptr); } + void finish() { + SetEvent(go); + SetEvent(quit); + if (handle) { + WaitForSingleObject(handle, INFINITE); + CloseHandle(handle); + } + for (HANDLE h : {go, done, quit}) CloseHandle(h); + } +}; + +void test_first_run(const fs::path& exe, const fs::path& dll, EarlyThread& early, void* own_block) { + std::printf("\n-- first run: %s --\n", exe.string().c_str()); + const DWORD home = home_index(); + void* block = nullptr; + void* saved = nullptr; + { + rt::Loader loader(exe.parent_path()); + rt::Module& m = loader.load(exe); + const Ga ga = ga_exports(m); + std::printf(" this EXE's _tls_index is now %lu; the executable's block=%p\n", _tls_index, m.tls_block); + + check(m.tls_index == 0, "the mapped executable gets module TLS index 0"); + check(ga.tls_index() == 0, "its AddressOfIndex (_tls_index) holds 0"); + check(m.tls_block && module_tls_slots()[0] == m.tls_block, "slot 0 of this thread holds its template copy"); + check(ga.get() == 42, "its /GA getter reads the template value 42 on the loading thread"); + check(module_tls_slots()[home] == own_block && host_value() == 555, + "this EXE's TLS on the loading thread is still the same block, now at the home index"); + check(m.tls_saved_block && m.tls_saved_block != own_block, "the block saved from slot 0 is not this EXE's"); + + const auto offset = reinterpret_cast(ga.address()) - static_cast(m.tls_block); + const bool offset_ok = offset >= 0 && static_cast(offset) + sizeof(int) <= m.tls_block_size && + static_cast(offset) + sizeof(int) <= 4096; + check(offset_ok, "the executable's thread_local lies inside its slot-0 block"); + if (offset_ok) + check(read_through_stand_ins(ga, static_cast(offset), home) == 77, + "the getter reads slot 0 even when its _tls_index names another slot (/GA code)"); +#if LEONIDA_GA_FIXTURE_IS_GA + check(reads_slot0_without_index(reinterpret_cast(ga.get), ga.tls_index_address()), + "the fixture's getter has the /GA shape: gs:[58h] and no load of _tls_index"); +#else + std::printf("SKIP the fixture's /GA code shape (this compiler may ignore /GA)\n"); +#endif + + ga.set(43); + const NewThreadView fresh = run_new_thread(&ga); + check(fresh.from_template, "a new thread's TLS at the home index starts from this EXE's template"); + check(fresh.ga == 42, "a thread started after load() reads 42 without an install call"); + check(fresh.ga_after_set == 9 && ga.get() == 43, "its write stays in its own copy"); + check(fresh.slot0 != m.tls_block, "its slot 0 is its own block, not the loading thread's"); + check(fresh.host == 1234 && fresh.host_at_home, + "this EXE's thread_local starts at 1234 there, at the home index"); + check(host_value() == 555, "this EXE's value on the loading thread is unchanged"); + + early.loader = &loader; + early.module = &m; + early.ga = ga; + SetEvent(early.go); + WaitForSingleObject(early.done, INFINITE); + check(early.host == 1234 && early.host_at_home, + "a thread that existed before the reservation finds a fresh copy of this EXE's TLS at the home index"); + // With main's install_on_existing_threads, load() itself gave this already-running thread its copy in slot 0 + // (the executable's slot included), so install_tls_for_thread is a no-op there and slot 0 does not change + // across the call. Without that, install_tls_for_thread puts the copy in. Either way the thread reads its own. + check(early.ga_installed == 42 && early.ga_after_set == 5, + "that thread has its own copy in slot 0 (from load(), or from install_tls_for_thread)"); + check(early.slot0_restored, "uninstall_tls_for_thread puts that thread's slot 0 back"); + + loader.initialise(); + check(m.initialised, "initialise() runs the executable's TLS callbacks (it has none)"); + check(run_new_thread(&ga).ga == 42, "after initialise() a new thread still reads 42"); + + rt::Module& d = loader.load(dll); + const auto dll_get = find_export(d, "tiny_tls_get"); + check(d.tls_index != rt::kNoTlsIndex && d.tls_index != 0 && d.tls_index != home, + "tiny_tls.dll gets a helper index, neither 0 nor the home index"); + check(dll_get() == 7 && ga.get() == 43 && host_value() == 555, + "the DLL, the executable and this EXE each read their own value on the loading thread"); + const NewThreadView both = run_new_thread(&ga, dll_get); + check(both.dll == 7 && both.ga == 42 && both.host == 1234, + "a new thread reads the DLL's 7, the executable's 42 and this EXE's 1234"); + + block = m.tls_block; + saved = m.tls_saved_block; + } + check(module_tls_slots()[0] == saved, "~Loader puts slot 0's earlier block back"); + MEMORY_BASIC_INFORMATION info{}; + check(VirtualQuery(block, &info, sizeof(info)) == 0 || info.State == MEM_FREE, "~Loader frees the copy"); + check(_tls_index == home && host_value() == 555, "this EXE keeps the home index and its value after the run"); +} + +void test_second_run(const fs::path& exe) { + std::printf("\n-- second run, and a second executable at once --\n"); + wchar_t temp[MAX_PATH]; + GetTempPathW(MAX_PATH, temp); + const fs::path copy = + fs::path(temp) / ("leonida_tls_index0_copy_" + std::to_string(GetCurrentProcessId()) + ".exe"); + // CopyFileW, not fs::copy_file: MSVC's copy_file calls CopyFile2, which Wine 9 doesn't implement. + check(CopyFileW(exe.c_str(), copy.c_str(), FALSE) != 0, "copied the executable under a second name"); + { + rt::Loader loader(exe.parent_path()); + rt::Module& m = loader.load(exe); + const Ga ga = ga_exports(m); + loader.initialise(); + check(m.tls_index == 0 && ga.get() == 42, "a second Loader maps the executable at index 0 again, value 42"); + check(run_new_thread(&ga).ga == 42 && host_value() == 555, "new threads and this EXE's value still check out"); + + rt::Module& other = loader.load(copy); + const Ga other_ga = ga_exports(other); + check(other.tls_index != 0 && other.tls_index != rt::kNoTlsIndex && other_ga.tls_index() == other.tls_index, + "a second executable mapped meanwhile gets a helper index in its _tls_index"); + check(m.tls_index == 0 && ga.get() == 42, "the first keeps index 0 and its value"); + } + std::error_code ec; + fs::remove(copy, ec); +} + +void test_home_template() { + std::printf("\n-- the home clone --\n"); + const HMODULE home = home_module(); + check(home != nullptr, "the home clone is loaded"); + if (!home) return; + const auto* tls = tls_of(home); + const Template tmpl = own_template(); + std::printf(" this EXE's TLS is %zu bytes; the home clone's template is %llu bytes\n", tmpl.size, + static_cast(tls->EndAddressOfRawData - tls->StartAddressOfRawData)); + check(tls->EndAddressOfRawData - tls->StartAddressOfRawData == tmpl.size, + "the home template is exactly as large as this EXE's TLS (template plus zero fill)"); + check(std::memcmp(reinterpret_cast(tls->StartAddressOfRawData), tmpl.data, tmpl.size) == 0, + "the home template holds this EXE's template"); +} + +// Runs before the reservation: TLS here is fine, as no frame outlives the call. +__declspec(noinline) void* before_reservation() { + check(_tls_index == 0, "before the reservation this test EXE holds module TLS index 0 (Windows gave it)"); + set_host_value(555); + check(inside(host_address(), module_tls_slots()[0], own_template().size), "its TLS is the block in slot 0"); + return module_tls_slots()[0]; +} + +__declspec(noinline) void after_reservation(bool reserved, const std::string& why, void* own_block, EarlyThread& early, + const fs::path& exe, const fs::path& dll) { + if (!why.empty()) std::printf(" reserve_tls_index0: %s\n", why.c_str()); + check(reserved && why.empty(), "reserve_tls_index0 succeeds"); + const DWORD home = home_index(); + check(home != rt::kNoTlsIndex && home != 0 && _tls_index == home, + "this EXE's _tls_index is the home clone's own index"); + check(module_tls_slots()[home] == own_block && module_tls_slots()[0] != own_block && host_value() == 555, + "on the reserving thread this EXE's block moved, with its value, from slot 0 to the home index"); + std::string again; + check(rt::reserve_tls_index0(&again) && again.empty(), "a second call returns the first result"); + test_home_template(); + test_first_run(exe, dll, early, own_block); + test_second_run(exe); +} + +__declspec(noinline) int scenario_runs(const fs::path& exe, const fs::path& dll) { + void* own_block = before_reservation(); + EarlyThread early; + early.start(); + std::string why; + const bool reserved = call_reserve(&why); + after_reservation(reserved, why, own_block, early, exe, dll); + early.finish(); + return 0; +} + +// ---- threads ---- + +constexpr int kChurn = 64; +struct ThreadResult { + int host = -1, seen_in_hook = -1; + bool hooked = false, at_home = false, fresh = false; +}; +ThreadResult g_results[kChurn + 1]; +HANDLE g_handles[kChurn + 1]; +HANDLE g_go = nullptr; +std::atomic g_hook_active{false}; +std::atomic g_created{0}; +std::atomic g_stop_churn{false}; + +// Runs in tiny_thread_hook.dll's DllMain(DLL_THREAD_ATTACH), before the TLS helper's own DLL_THREAD_ATTACH. +void __cdecl hook_body() { + if (!g_hook_active.load()) return; // TLS only once the reservation is done + t_seen_in_hook = host_value(); + t_hooked = host_tls_at_home(); + set_host_value(4321); +} + +__declspec(noinline) void record(int i) { + g_results[i].hooked = t_hooked; + g_results[i].seen_in_hook = t_seen_in_hook; + g_results[i].host = host_value(); + g_results[i].at_home = host_tls_at_home(); +} + +DWORD WINAPI churn_body(void* p) { // no TLS before the wait: it may start before the reservation + WaitForSingleObject(g_go, INFINITE); + record(static_cast(reinterpret_cast(p))); + return 0; +} + +DWORD WINAPI churn_creator(void*) { // runs through the reservation and touches no TLS + for (int i = 1; i <= kChurn; ++i) { + void* index = reinterpret_cast(static_cast(i)); + g_handles[i] = CreateThread(nullptr, 0, &churn_body, index, 0, nullptr); + g_created.store(i); + if (i >= kChurn / 2) while (!g_stop_churn.load()) Sleep(0); // the rest after the reservation + Sleep(0); + } + return 0; +} + +using NtQueryInformationThreadFn = LONG(NTAPI*)(HANDLE, int, PVOID, ULONG, PULONG); + +// TEB->ThreadLocalStoragePointer of another thread. +void* tls_array_of(HANDLE thread) { + struct { + LONG exit_status; + PVOID teb; + PVOID ids[2]; + ULONG_PTR affinity; + LONG priority, base_priority; + } info{}; + const auto query = reinterpret_cast( + GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "NtQueryInformationThread")); + if (!query || query(thread, 0, &info, sizeof(info), nullptr) < 0 || !info.teb) return reinterpret_cast(1); + return *reinterpret_cast(static_cast(info.teb) + 0x58); +} + +__declspec(noinline) void threads_after(bool reserved, HANDLE suspended, bool suspended_had_no_array) { + check(reserved, "reserve_tls_index0 succeeds while threads are being created"); + check(suspended_had_no_array, "the thread created suspended has no TLS array yet when the reservation starts"); + std::printf(" %d threads created before the reservation returned\n", g_created.load()); + g_hook_active = true; + SetEvent(g_go); + g_stop_churn = true; + ResumeThread(suspended); + HANDLE creator = g_handles[0]; + WaitForSingleObject(creator, INFINITE); + CloseHandle(creator); + WaitForSingleObject(suspended, INFINITE); + CloseHandle(suspended); + int hooked = 0, ok = 0, window_ok = 0; + for (int i = 1; i <= kChurn; ++i) { + WaitForSingleObject(g_handles[i], INFINITE); + CloseHandle(g_handles[i]); + } + for (int i = 0; i <= kChurn; ++i) { + const ThreadResult& r = g_results[i]; + ok += r.at_home && r.host == (r.hooked ? 4321 : 1234); + hooked += r.hooked; + window_ok += r.hooked && r.seen_in_hook == 1234; + } + std::printf(" %d of %d threads ran the hook in DLL_THREAD_ATTACH\n", hooked, kChurn + 1); + check(ok == kChurn + 1, "every thread created before, during or after the reservation finds this EXE's TLS at the " + "home index, with the value it should have"); + check(g_results[0].hooked && g_results[0].at_home && g_results[0].host == 4321, + "the suspended thread, resumed afterwards, gets a fresh copy and keeps the hook's write"); + check(hooked > 0 && window_ok == hooked, + "code of this EXE run before the helper's DLL_THREAD_ATTACH reads a fresh copy of its TLS (1234) there"); +} + +__declspec(noinline) int scenario_threads(const fs::path& hook_dll) { + HMODULE hook = LoadLibraryW(hook_dll.c_str()); // before the helper, so its DLL_THREAD_ATTACH comes first + using SetHook = void(__cdecl*)(void(__cdecl*)()); + auto set_hook = hook ? reinterpret_cast(GetProcAddress(hook, "tiny_thread_hook_set")) : nullptr; + check(set_hook != nullptr, "tiny_thread_hook.dll is loaded"); + if (!set_hook) return 1; + set_hook(&hook_body); + g_go = CreateEventW(nullptr, TRUE, FALSE, nullptr); + HANDLE suspended = CreateThread(nullptr, 0, &churn_body, nullptr, CREATE_SUSPENDED, nullptr); + g_handles[0] = CreateThread(nullptr, 0, &churn_creator, nullptr, 0, nullptr); + while (g_created.load() < 4) Sleep(0); + const bool no_array = tls_array_of(suspended) == nullptr; + const bool reserved = call_reserve(nullptr); + threads_after(reserved, suspended, no_array); + CloseHandle(g_go); + return 0; +} + +// ---- noreserve ---- + +__declspec(noinline) int scenario_noreserve(const fs::path& exe) { + rt::Loader loader(exe.parent_path()); + rt::Module& m = loader.load(exe); + check(m.tls_index != 0 && m.tls_index != rt::kNoTlsIndex, + "without reserve_tls_index0 the executable gets a helper index"); + check(_tls_index == 0, "and this EXE keeps module TLS index 0"); + check(ga_exports(m).tls_index() == m.tls_index, "the executable's _tls_index holds that helper index"); + return 0; +} + +void print_result() { + if (g_failures == 0) + std::printf("\nloader_tls_index0_test: OK (%d checks)\n", g_checks); + else + std::printf("\nloader_tls_index0_test: FAILED (%d checks, %d failure%s)\n", g_checks, g_failures, + g_failures == 1 ? "" : "s"); +} + +} // namespace + +int main(int argc, char** argv) { + std::setvbuf(stdout, nullptr, _IONBF, 0); + if (argc != 5) { + std::fprintf(stderr, + "usage: loader_tls_index0_test runs|threads|noreserve " + "\n"); + return 2; + } + std::printf("loader_tls_index0_test %s: module TLS index 0 for a mapped executable\n", argv[1]); + const std::string scenario = argv[1]; + const fs::path exe = argv[2], dll = argv[3], hook = argv[4]; + try { + if (!fs::exists(exe) || !fs::exists(dll) || !fs::exists(hook)) throw std::runtime_error("a fixture is missing"); + if (scenario == "runs") scenario_runs(exe, dll); + else if (scenario == "threads") scenario_threads(hook); + else if (scenario == "noreserve") scenario_noreserve(exe); + else throw std::runtime_error("unknown scenario " + scenario); + } catch (const std::exception& e) { + ++g_checks; + ++g_failures; + std::printf("FAIL unexpected exception: %s\n", e.what()); + } + print_result(); + return g_failures ? 1 : 0; +} diff --git a/runtime/test/package_splash_test.cpp b/runtime/test/package_splash_test.cpp new file mode 100644 index 0000000000..ff71043951 --- /dev/null +++ b/runtime/test/package_splash_test.cpp @@ -0,0 +1,86 @@ +// Exercise manifest lookup, WIC scaling and upload with a synthetic 2x1 red bitmap. +#include "vk_test_device.h" +#include "../shims/d3d12_com.h" +#include "../shims/package_splash.h" + +#include +#include +#include +#include +#include + +#define EXPECT(expr) do { if (!(expr)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #expr); return 1; } } while (0) + +int main() { + namespace fs = std::filesystem; + namespace splash = rt::package_splash; + using Microsoft::WRL::ComPtr; + const auto dir = fs::current_path() / (L"splash-test-" + std::to_wstring(GetCurrentProcessId())); + EXPECT(fs::create_directory(dir)); + struct Cleanup { + fs::path dir; + ~Cleanup() { std::error_code ec; fs::remove_all(dir, ec); } + } cleanup{dir}; + + SetEnvironmentVariableW(L"LEONIDA_PACKAGE_SPLASH", nullptr); + splash::configure(dir); + EXPECT(!splash::configured()); + BITMAPINFOHEADER info{}; + info.biSize = sizeof(info); + info.biWidth = 2; + info.biHeight = info.biPlanes = 1; + info.biBitCount = 24; + BITMAPFILEHEADER file{}; + file.bfType = 0x4d42; + file.bfOffBits = sizeof(file) + sizeof(info); + file.bfSize = file.bfOffBits + 8; + const unsigned char row[8]{0, 0, 255, 0, 0, 255, 0, 0}; + std::ofstream(dir / L"art.bmp", std::ios::binary).write(reinterpret_cast(&file), sizeof(file)) + .write(reinterpret_cast(&info), sizeof(info)).write(reinterpret_cast(row), sizeof(row)); + const auto config = dir / L"MicrosoftGame.Config"; + std::ofstream(config) << ""; + splash::configure(dir); + EXPECT(!splash::configured()); + std::ofstream(config) << "" + ""; + splash::configure(dir); + EXPECT(splash::configured()); + SetEnvironmentVariableW(L"LEONIDA_PACKAGE_SPLASH", L"0"); + splash::configure(dir); + EXPECT(!splash::configured()); + SetEnvironmentVariableW(L"LEONIDA_PACKAGE_SPLASH", nullptr); + fs::remove(config); + std::ofstream(dir / L"appxmanifest.xml") << ""; + splash::configure(dir); + EXPECT(splash::configured()); + + vktest::Device vk; + const auto status = vk.initialize(); + if (status == vktest::DeviceStatus::unavailable) return 77; + EXPECT(status == vktest::DeviceStatus::ready); + rt::d3d12::VulkanDeviceInfo gpu{}; + gpu.get_instance_proc = vk.instance_proc; + gpu.instance = vk.instance; + gpu.physical = vk.physical; + gpu.device = vk.device; + gpu.queue = vk.queue; + gpu.queue_family = vk.family; + gpu.host_image_copy = vk.host_image_copy; + ComPtr device; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(gpu, IID_PPV_ARGS(&device)))); + ComPtr texture; + texture.Attach(splash::create_texture(device.Get(), 4, 4)); + EXPECT(texture); + std::array pixels{}; + EXPECT(SUCCEEDED(texture->ReadFromSubresource(pixels.data(), 16, 64, 0, nullptr))); + for (unsigned i = 0; i < pixels.size(); ++i) + EXPECT((pixels[i] & 0xffffff) == ((i >= 4 && i < 12) ? 0xff0000u : 0u)); + texture.Attach(splash::create_texture(device.Get(), 6, 2)); + EXPECT(texture); + EXPECT(SUCCEEDED(texture->ReadFromSubresource(pixels.data(), 24, 48, 0, nullptr))); + for (unsigned i = 0; i < 12; ++i) + EXPECT((pixels[i] & 0xffffff) == ((i % 6 >= 1 && i % 6 <= 4) ? 0xff0000u : 0u)); + std::puts("package splash: manifest, rollback, aspect fit and Vulkan readback passed"); + return 0; +} diff --git a/runtime/test/pipeline_cache_file_test.cpp b/runtime/test/pipeline_cache_file_test.cpp index 73dad65de8..d60efd2ed4 100644 --- a/runtime/test/pipeline_cache_file_test.cpp +++ b/runtime/test/pipeline_cache_file_test.cpp @@ -1,8 +1,9 @@ // Exercise checkpoint replacement and real filesystem errors without a Vulkan device. -#include "pipeline_cache_file.h" +#include "../src/pipeline_cache_file.h" #include #include +#include #include #include #include @@ -10,6 +11,7 @@ #ifdef _WIN32 #include +#include "../shims/d3d12_pipeline_checkpoint.h" #else #include #include @@ -45,6 +47,30 @@ static int test_checkpoint(const fs::path& dir) { CHECK(fs::is_directory(directory)); #ifdef _WIN32 + { + using namespace rt::d3d12; + CHECK(cache_temp_suffix(L"123.0") && !cache_temp_suffix(L".2") && !cache_temp_suffix(L"1.2.3")); + CacheStagingFile next(cache, 128); + CHECK(next.data); + std::memcpy(next.data, "short", 5); + CHECK(next.publish(cache, 5) && contents(cache) == "short"); + { CacheStagingFile aborted(cache, 16); CHECK(aborted.data); } + CHECK(contents(cache) == "short"); + CHECK(!write_pipeline_cache_file(cache, saved.data(), saved.size())); + const auto orphan = dir / "cache.bin.tmp.140.0", fresh = dir / "cache.bin.tmp.141.0"; + const auto held = dir / "cache.bin.tmp.142.0"; + for (const auto& path : {orphan, fresh, held}) std::ofstream(path) << "partial"; + auto old = fs::file_time_type::clock::now() - std::chrono::hours(1); + fs::last_write_time(orphan, old); + fs::last_write_time(held, old); + HANDLE live = CreateFileW(held.c_str(), GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, nullptr); + CHECK(live != INVALID_HANDLE_VALUE); + clean_stale_cache_files(cache); + CHECK(!fs::exists(orphan) && fs::exists(fresh) && fs::exists(held) && contents(cache) == saved); + CloseHandle(live); + fs::remove(fresh); + fs::remove(held); + } // A reader that did not share DELETE access prevents replacement. HANDLE held = CreateFileW(cache.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); diff --git a/runtime/test/pipeline_cache_store_test.cpp b/runtime/test/pipeline_cache_store_test.cpp new file mode 100644 index 0000000000..dbf174768b --- /dev/null +++ b/runtime/test/pipeline_cache_store_test.cpp @@ -0,0 +1,93 @@ +// The two pure decisions behind D3D-704: how large a session cache may be (LEONIDA_PIPELINE_CACHE_BYTES) and +// whether a blob's VkPipelineCacheHeaderVersionOne names this device. No Vulkan, no GPU, no files. +#include "../src/pipeline_cache_store.h" + +#include +#include +#include +#include +#include + +#define CHECK(condition) do { \ + if (!(condition)) { \ + std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); \ + return 1; \ + } \ +} while (0) + +namespace store = leonida::pipeline_cache_store; + +static void put32(std::uint8_t* p, std::uint32_t value) { + for (int i = 0; i < 4; ++i) p[i] = static_cast(value >> (8 * i)); +} + +static int test_limit() { + using store::default_save_limit; + // Absent, empty and the default knob. + CHECK(store::parse_save_limit(nullptr).bytes == default_save_limit); + CHECK(store::parse_save_limit(nullptr).valid); + CHECK(store::parse_save_limit("").bytes == default_save_limit); + // 0 is the documented "off", not a typo, and leading zeros are still a number. + CHECK(store::parse_save_limit("0").bytes == 0); + CHECK(store::parse_save_limit("0").valid); + CHECK(store::parse_save_limit("007").bytes == 7); + CHECK(store::parse_save_limit("1048576").bytes == 1048576); + const std::string largest = std::to_string(std::numeric_limits::max()); + CHECK(store::parse_save_limit(largest.c_str()).bytes == std::numeric_limits::max()); + // Anything that is not a plain byte count falls back to the default and says the value was rejected. + for (const char* text : {"-1", "+1", " 1", "1 ", "12x", "0x10", "1.5", "99999999999999999999999999"}) { + const auto limit = store::parse_save_limit(text); + CHECK(!limit.valid); + CHECK(limit.bytes == default_save_limit); + } + return 0; +} + +static int test_header() { + leonida::cached_pso::Identity identity; + identity.vendor = 0x1002; + identity.device = 0x73ff; + identity.driver = 0x02000d0b; + + std::uint8_t header[store::header_bytes] = {}; + put32(header, store::header_bytes); + put32(header + 4, store::header_version_one); + put32(header + 8, identity.vendor); + put32(header + 12, identity.device); + for (int i = 0; i < 16; ++i) header[16 + i] = identity.cache_uuid[i] = static_cast(i + 1); + CHECK(store::header_matches(header, sizeof(header), identity)); + // Extra payload past the header does not matter: the driver reads the header and then its own data. + std::uint8_t blob[store::header_bytes + 8] = {}; + std::memcpy(blob, header, sizeof(header)); + CHECK(store::header_matches(blob, sizeof(blob), identity)); + + // Too short and null are "no cache", never a read past the end. + CHECK(!store::header_matches(header, store::header_bytes - 1, identity)); + CHECK(!store::header_matches(nullptr, store::header_bytes, identity)); + + // The four fields a driver checks before trusting a blob from another device, driver or header version. + auto differs = [&](int offset, std::uint32_t value) { + std::uint8_t changed[store::header_bytes]; + std::memcpy(changed, header, sizeof(changed)); + put32(changed + offset, value); + return !store::header_matches(changed, sizeof(changed), identity); + }; + CHECK(differs(0, store::header_bytes + 4)); + CHECK(differs(4, store::header_version_one + 1)); + CHECK(differs(8, identity.vendor + 1)); + CHECK(differs(12, identity.device + 1)); + std::uint8_t uuid[store::header_bytes]; + std::memcpy(uuid, header, sizeof(uuid)); + uuid[16] ^= 0xff; + CHECK(!store::header_matches(uuid, sizeof(uuid), identity)); + // vendorID/deviceID are u32s little-endian; the same bytes read the other way name another device. + leonida::cached_pso::Identity swapped = identity; + swapped.vendor = 0x02100000; + CHECK(!store::header_matches(header, sizeof(header), swapped)); + return 0; +} + +int main() { + if (const int failed = test_limit()) return failed; + return test_header(); +} diff --git a/runtime/test/pso_stream_test.cpp b/runtime/test/pso_stream_test.cpp new file mode 100644 index 0000000000..07ac13a326 --- /dev/null +++ b/runtime/test/pso_stream_test.cpp @@ -0,0 +1,268 @@ +// Pipeline state stream copies and the derived-state patch (device slot 55) with synthetic streams only: no D3D12 +// device, no game data. The layout rule is the one measured on the console's slot 86 stream (see the offsets check). +#include + +#include +#include +#include + +#include "d3d12_xs_pso_stream.h" + +namespace { + +int g_failures = 0; + +void check(bool ok, const char* what) { + std::printf("%s %s\n", ok ? "PASS" : "FAIL", what); + if (!ok) ++g_failures; +} + +std::size_t align_up(std::size_t v, std::size_t a) { return (v + a - 1) / a * a; } + +// Builds a stream the way the console lays it out: u32 type, payload at its natural alignment, next entry 8-aligned. +struct StreamBuilder { + std::vector bytes; + void entry(unsigned type, const void* payload, std::size_t size, std::size_t payload_align) { + const std::size_t at = bytes.size(); + bytes.resize(at + 4); + std::memcpy(bytes.data() + at, &type, 4); + const std::size_t pay = align_up(at + 4, payload_align); + bytes.resize(pay, 0); + const auto* p = static_cast(payload); + bytes.insert(bytes.end(), p, p + size); + bytes.resize(align_up(bytes.size(), 8), 0); + } +}; + +// The test's own copy of the layout rule: payload offset of the first subobject of `wanted`, or npos. +std::size_t payload_of_type(const std::vector& s, unsigned wanted) { + std::size_t off = 0; + while (off + 4 <= s.size()) { + unsigned type; + std::memcpy(&type, s.data() + off, 4); + std::size_t size = sizeof(D3D12_SHADER_BYTECODE), align = 8; + if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND) { size = sizeof(D3D12_BLEND_DESC); align = 4; } + else if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK) { size = 4; align = 4; } + else if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER) { size = sizeof(D3D12_RASTERIZER_DESC); align = 4; } + else if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1) { size = sizeof(D3D12_DEPTH_STENCIL_DESC1); align = 4; } + else if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE) { size = 8; align = 8; } + else if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT) { size = sizeof(D3D12_INPUT_LAYOUT_DESC); align = 8; } + const std::size_t pay = align_up(off + 4, align); + if (type == wanted) return pay; + off = align_up(pay + size, 8); + } + return static_cast(-1); +} + +const unsigned char kVsCode[32] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, + 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32}; +const char kSemantic[] = "POSITION"; + +D3D12_INPUT_ELEMENT_DESC make_element(const char* name) { + D3D12_INPUT_ELEMENT_DESC e{}; + e.SemanticName = name; + e.Format = DXGI_FORMAT_R32G32B32_FLOAT; + return e; +} + +// Root signature (null), VS, BLEND, SAMPLE_MASK, RASTERIZER, DEPTH_STENCIL1, INPUT_LAYOUT. +std::vector base_stream(const D3D12_INPUT_ELEMENT_DESC* elements, unsigned element_count) { + StreamBuilder s; + ID3D12RootSignature* root = nullptr; + s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, &root, 8, 8); + D3D12_SHADER_BYTECODE vs{kVsCode, sizeof(kVsCode)}; + s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, &vs, sizeof(vs), 8); + D3D12_BLEND_DESC blend{}; + s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, &blend, sizeof(blend), 4); + UINT mask = 0xffffffffu; + s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, &mask, 4, 4); + D3D12_RASTERIZER_DESC raster{}; + raster.FillMode = D3D12_FILL_MODE_SOLID; + s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, &raster, sizeof(raster), 4); + D3D12_DEPTH_STENCIL_DESC1 ds1{}; + ds1.DepthEnable = TRUE; + s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1, &ds1, sizeof(ds1), 4); + D3D12_INPUT_LAYOUT_DESC layout{elements, element_count}; + s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT, &layout, sizeof(layout), 8); + return s.bytes; +} + +// One derived record: tag at +0, payload at +4. +std::vector record(unsigned tag, const void* payload, std::size_t size) { + std::vector r(rt::d3d12_xs::kDerivedRecordSize, 0); + std::memcpy(r.data(), &tag, 4); + if (size) std::memcpy(r.data() + 4, payload, size); + return r; +} + +void test_layout_matches_console_offsets() { + // Console slot 86 stream: types 0..5 then BLEND at +0x88 (payload +0x8c), SAMPLE_MASK at +0x1d8, RASTERIZER at + // +0x1e0, DEPTH_STENCIL1 at +0x210 (measured in the notes, mesure sur l'exe). + StreamBuilder s; + ID3D12RootSignature* root = nullptr; + s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, &root, 8, 8); + D3D12_SHADER_BYTECODE sb{}; + for (unsigned i = 0; i < 5; ++i) s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS + i, &sb, sizeof(sb), 8); + check(s.bytes.size() == 0x88, "six entries (types 0..5) end at +0x88"); + D3D12_BLEND_DESC blend{}; + s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, &blend, sizeof(blend), 4); + check(payload_of_type(s.bytes, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND) == 0x8c, + "BLEND payload at +0x8c"); + check(s.bytes.size() == 0x1d8, "BLEND entry ends at +0x1d8"); + UINT mask = 1; + s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, &mask, 4, 4); + check(s.bytes.size() == 0x1e0, "SAMPLE_MASK entry is 8 bytes, next entry at +0x1e0"); +} + +void test_capture_and_deep_copy() { + D3D12_INPUT_ELEMENT_DESC elements[1] = {make_element(kSemantic)}; + std::vector base = base_stream(elements, 1); + D3D12_PIPELINE_STATE_STREAM_DESC desc{base.size(), base.data()}; + auto rec = rt::d3d12_xs::PsoStreamRecord::capture(desc); + check(rec != nullptr, "a synthetic base stream is captured"); + if (!rec) return; + check(rec->bytes().size() == base.size(), "the copy has the stream's size"); + + // Scribble over the source and its pointed-to data: the copy must still hold the original content. + std::memset(base.data(), 0xee, base.size()); + elements[0].SemanticName = "XXXXXXXX"; + D3D12_SHADER_BYTECODE vs_copy{}; + std::memcpy(&vs_copy, rec->bytes().data() + payload_of_type(rec->bytes(), D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS), + sizeof(vs_copy)); + check(vs_copy.pShaderBytecode != kVsCode && vs_copy.BytecodeLength == sizeof(kVsCode) && + std::memcmp(vs_copy.pShaderBytecode, kVsCode, sizeof(kVsCode)) == 0, + "shader bytecode is copied, not referenced"); + D3D12_INPUT_LAYOUT_DESC il{}; + std::memcpy(&il, rec->bytes().data() + payload_of_type(rec->bytes(), D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT), + sizeof(il)); + check(il.NumElements == 1 && std::strcmp(il.pInputElementDescs[0].SemanticName, kSemantic) == 0, + "input layout semantic names are copied"); +} + +void test_derive_single_and_all_tags() { + D3D12_INPUT_ELEMENT_DESC elements[1] = {make_element(kSemantic)}; + std::vector base = base_stream(elements, 1); + auto rec = rt::d3d12_xs::PsoStreamRecord::capture({base.size(), base.data()}); + if (!rec) { check(false, "base captured for derive tests"); return; } + + D3D12_BLEND_DESC blend{}; + blend.RenderTarget[0].RenderTargetWriteMask = 0x5; + auto r2 = record(2, &blend, sizeof(blend)); + std::vector out; + check(rt::d3d12_xs::derive_stream(*rec, r2.data(), 1, out) == rt::d3d12_xs::DeriveStatus::ok, + "tag 2 (blend) derives"); + const std::size_t bp = payload_of_type(out, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND); + check(std::memcmp(out.data() + bp, &blend, sizeof(blend)) == 0, "tag 2 payload lands in the BLEND subobject"); + check(out.size() == rec->bytes().size(), "derived stream keeps the base size"); + + D3D12_RASTERIZER_DESC raster{}; + raster.FillMode = D3D12_FILL_MODE_WIREFRAME; + D3D12_DEPTH_STENCIL_DESC ds{}; + ds.DepthEnable = FALSE; + UINT mask = 0x3; + std::vector three; + auto r0 = record(0, &ds, sizeof(ds)); + auto r1 = record(1, &raster, sizeof(raster)); + auto r3 = record(3, &mask, 4); + three.insert(three.end(), r0.begin(), r0.end()); + three.insert(three.end(), r1.begin(), r1.end()); + three.insert(three.end(), r3.begin(), r3.end()); + check(rt::d3d12_xs::derive_stream(*rec, three.data(), 3, out) == rt::d3d12_xs::DeriveStatus::ok, + "three records (tags 0, 1, 3) derive"); + const std::size_t rp = payload_of_type(out, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER); + const std::size_t mp = payload_of_type(out, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK); + const std::size_t dp = payload_of_type(out, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1); + check(std::memcmp(out.data() + rp, &raster, sizeof(raster)) == 0, "tag 1 payload lands in RASTERIZER"); + check(std::memcmp(out.data() + mp, &mask, 4) == 0, "tag 3 payload lands in SAMPLE_MASK"); + check(std::memcmp(out.data() + dp, &ds, sizeof(ds)) == 0, "tag 0 patches the DS1 prefix"); + const std::size_t tail = dp + sizeof(ds); + check(out[tail] == 0 && out[tail + 1] == 0 && out[tail + 2] == 0 && out[tail + 3] == 0, + "tag 0 keeps the DS1 depth-bounds field of the base"); +} + +void test_stencil_mask_record() { + // Tag 5 carries the two stencil mask bytes at the DEPTH_STENCIL offsets 0x10/0x11 and zeros elsewhere (read from the + // title's writes). It overlays only those two bytes of the base's DEPTH_STENCIL (or DEPTH_STENCIL1) payload. + D3D12_INPUT_ELEMENT_DESC elements[1] = {make_element(kSemantic)}; + std::vector base = base_stream(elements, 1); + auto rec = rt::d3d12_xs::PsoStreamRecord::capture({base.size(), base.data()}); + if (!rec) { check(false, "base captured for the tag 5 tests"); return; } + const std::size_t dp = payload_of_type(rec->bytes(), D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1); + + unsigned char mask_payload[0x16] = {}; + mask_payload[0x10] = 0x0f; // read mask + mask_payload[0x11] = 0x3c; // write mask + auto r5 = record(5, mask_payload, sizeof(mask_payload)); + std::vector out; + check(rt::d3d12_xs::derive_stream(*rec, r5.data(), 1, out) == rt::d3d12_xs::DeriveStatus::ok, + "tag 5 alone derives on a base with DEPTH_STENCIL1"); + check(out[dp + 0x10] == 0x0f && out[dp + 0x11] == 0x3c, "tag 5 overlays the two stencil mask bytes"); + bool rest_same = true; + for (std::size_t i = 0; i < 0x38; ++i) + if (i != 0x10 && i != 0x11 && out[dp + i] != rec->bytes()[dp + i]) rest_same = false; + check(rest_same, "tag 5 leaves the other DEPTH_STENCIL1 bytes unchanged"); + + // Order: records apply in the order they are given. Tag 0 writes its own masks, tag 5 overrides them. + D3D12_DEPTH_STENCIL_DESC ds{}; + ds.StencilReadMask = 0x01; + ds.StencilWriteMask = 0x02; + auto r0 = record(0, &ds, sizeof(ds)); + std::vector seq; + seq.insert(seq.end(), r0.begin(), r0.end()); + seq.insert(seq.end(), r5.begin(), r5.end()); + check(rt::d3d12_xs::derive_stream(*rec, seq.data(), 2, out) == rt::d3d12_xs::DeriveStatus::ok, + "tag 0 then tag 5 derive together"); + check(out[dp + 0x10] == 0x0f && out[dp + 0x11] == 0x3c, "tag 5 after tag 0 wins (record order)"); + + seq.clear(); + seq.insert(seq.end(), r5.begin(), r5.end()); + seq.insert(seq.end(), r0.begin(), r0.end()); + check(rt::d3d12_xs::derive_stream(*rec, seq.data(), 2, out) == rt::d3d12_xs::DeriveStatus::ok, + "tag 5 then tag 0 derive together"); + check(out[dp + 0x10] == 0x01 && out[dp + 0x11] == 0x02, "tag 0 after tag 5 wins (record order)"); +} + +void test_refusals() { + D3D12_INPUT_ELEMENT_DESC elements[1] = {make_element(kSemantic)}; + std::vector base = base_stream(elements, 1); + auto rec = rt::d3d12_xs::PsoStreamRecord::capture({base.size(), base.data()}); + if (!rec) { check(false, "base captured for refusal tests"); return; } + std::vector out; + + auto r6 = record(6, nullptr, 0); + check(rt::d3d12_xs::derive_stream(*rec, r6.data(), 1, out) == rt::d3d12_xs::DeriveStatus::unknown_tag, + "tag 6 is refused (meaning not known)"); + + // A base without a rasterizer subobject cannot take a tag-1 record. + StreamBuilder s; + ID3D12RootSignature* root = nullptr; + s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, &root, 8, 8); + D3D12_BLEND_DESC blend{}; + s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, &blend, sizeof(blend), 4); + auto norast = rt::d3d12_xs::PsoStreamRecord::capture({s.bytes.size(), s.bytes.data()}); + if (!norast) { check(false, "stream without rasterizer captured"); return; } + D3D12_RASTERIZER_DESC raster{}; + auto r1 = record(1, &raster, sizeof(raster)); + check(rt::d3d12_xs::derive_stream(*norast, r1.data(), 1, out) == rt::d3d12_xs::DeriveStatus::missing_state, + "tag 1 on a base without RASTERIZER is refused"); + + // A subobject type this module does not walk: VIEW_INSTANCING (payload with a pointer, not modelled). + StreamBuilder v; + unsigned char junk[32] = {}; + v.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VIEW_INSTANCING, junk, sizeof(junk), 8); + check(rt::d3d12_xs::PsoStreamRecord::capture({v.bytes.size(), v.bytes.data()}) == nullptr, + "a stream with an unmodelled subobject type is not captured"); +} + +} // namespace + +int main() { + std::printf("pso_stream_test: derived pipeline state streams\n"); + test_layout_matches_console_offsets(); + test_capture_and_deep_copy(); + test_derive_single_and_all_tags(); + test_stencil_mask_record(); + test_refusals(); + std::printf("%s: %d failure(s)\n", g_failures ? "FAILED" : "OK", g_failures); + return g_failures ? 1 : 0; +} diff --git a/runtime/test/queue_proxy_test.cpp b/runtime/test/queue_proxy_test.cpp index 967313d53a..d1e09d39f9 100644 --- a/runtime/test/queue_proxy_test.cpp +++ b/runtime/test/queue_proxy_test.cpp @@ -8,8 +8,9 @@ // - heap, queue and fence proxies are unwrapped where the real runtime receives them (Signal/Wait, // SetEventOnMultipleFenceCompletion, MakeResident/Evict/SetResidencyPriority/EnqueueMakeResident, // CreateSharedHandle), and OpenSharedHandle wraps a shared fence; -// - slots past the public chain are refused (E_NOTIMPL) up to the end of the table, and a slot past the table -// faults on the vtable read in the guard region and is counted; +// - slots past the public chain answer the console contract — a queue slot returns S_OK having signalled +// nothing (frame pacing flows through those methods), a fence slot is refused with E_NOTIMPL — and a +// slot past either table faults on the vtable read in the guard region and is counted; // - calls from eight threads at once, and repeated device, queue and fence creation without leaks; // - the child-process runner of the differential check itself: large output, hangs, crashes, failed starts. // No shaders, game data or Xbox DLLs. LEONIDA_VK_VALIDATION=1 runs the Vulkan device under @@ -396,25 +397,60 @@ int check_slots(const Backend& b) { } } - // The refused tail: every unmodelled slot from the end of the public chain to the end of the table. + // Fence slot 12 (value, descriptor, flags): the address of the completed value, which follows a queue's + // signal without another call (a wait on the real fence refreshes it). + { + before = fhits(12); + const auto* completed = reinterpret_cast(raw_call(fence.p, 12, 9, 0, 0)); + EXPECT(completed && *completed == fence->GetCompletedValue() && fhits(12) == before + 1); + EXPECT(SUCCEEDED(queue->Signal(fence.p, 9))); + bool seen = false; + for (int i = 0; i < 5000 && !seen; ++i) { + seen = *completed == 9; + if (!seen) Sleep(1); + } + EXPECT(seen); + EXPECT(raw_call(fence.p, 12, 9, 0, 0) == reinterpret_cast(completed)); + } + + // The console queue tail answers S_OK instead of refusing: frame pacing flows through those + // methods, the contract xs_proxy_mock checks too. The two methods the proxy models — SignalX at + // 23 and PresentX at 30 on the older layout the 16/17 calls above pinned — are checked below. + // The fence tail below is still refused — nothing console-shaped was measured past its public chain. + // (Fence slot 12 is not part of that tail: it is served, above.) + // Queue slot 35 (the console ExecuteCommandLists variant) is not part of the tail either. for (unsigned slot = 19; slot < xs::queue_proxy_table_size(); ++slot) { - if (xs::queue_slot_overridden(slot)) continue; + if (slot == 23 || slot == 30 || xs::queue_slot_overridden(slot)) continue; before = qhits(slot); - EXPECT(as_hr(call_slot(queue.p, slot)) == E_NOTIMPL); + EXPECT(as_hr(call_slot(queue.p, slot)) == S_OK); EXPECT(qhits(slot) == before + 1 && xs::queue_slot_first_call_seen(slot)); } + // SignalX forwards to the real queue's Signal with the extra word dropped: the fence reaching 9 + // proves the call was forwarded rather than swallowed by the console-tail answer. + before = qhits(23); + EXPECT(as_hr(raw_call(queue.p, 23, reinterpret_cast(fence.p), 9)) == S_OK); + EXPECT(qhits(23) == before + 1 && xs::queue_slot_first_call_seen(23)); + if (wait_for(label, fence.p, 9)) return 1; + // PresentX is handled by the presentation front end, not refused: its status is the swapchain's + // (a black frame on the test window, or S_OK where it cannot present), so anything but E_NOTIMPL + // shows the modelled path ran. + before = qhits(30); + EXPECT(as_hr(call_slot(queue.p, 30)) != E_NOTIMPL); + EXPECT(qhits(30) == before + 1 && xs::queue_slot_first_call_seen(30)); for (unsigned slot = fence_slots; slot < xs::fence_proxy_table_size(); ++slot) { + if (slot == 12) continue; before = fhits(slot); EXPECT(as_hr(call_slot(fence.p, slot)) == E_NOTIMPL); EXPECT(fhits(slot) == before + 1 && xs::fence_slot_first_call_seen(slot)); } - // The objects still work after refused calls. + // The objects still work after the console-only calls. EXPECT(SUCCEEDED(queue->Signal(fence.p, 10))); if (wait_for(label, fence.p, 10)) return 1; EXPECT(xs::command_object_proxy_ref_count(queue.p) == 1 && xs::command_object_proxy_ref_count(fence.p) == 1); } EXPECT(xs::device_proxy_ref_count(device) == device_refs); // every queue and fence gave its reference back - std::printf("%s: every public queue and fence slot forwarded and counted; tail refused\n", label); + std::printf("%s: every public queue and fence slot forwarded and counted; fence slot 12 follows a queue " + "signal; queue tail S_OK, fence tail refused\n", label); return 0; } diff --git a/runtime/test/replay_copy_offset_test.cpp b/runtime/test/replay_copy_offset_test.cpp index b5f93c102a..515befb3cd 100644 --- a/runtime/test/replay_copy_offset_test.cpp +++ b/runtime/test/replay_copy_offset_test.cpp @@ -5,6 +5,7 @@ #include #include +#include #include #include @@ -15,13 +16,27 @@ std::vector b2i_copies; std::vector i2b_copies; std::vector depth24_jobs; -VKAPI_ATTR void VKAPI_CALL noop_barrier(VkCommandBuffer, VkPipelineStageFlags, VkPipelineStageFlags, VkDependencyFlags, - std::uint32_t, const VkMemoryBarrier*, std::uint32_t, - const VkBufferMemoryBarrier*, std::uint32_t, const VkImageMemoryBarrier*) {} +// Whether a barrier since the last buffer copy ordered earlier transfer writes before transfer reads and writes, and +// that answer for each vkCmdCopyBuffer in turn: D3D12 orders back-to-back copies, Vulkan needs the barrier. +bool transfer_writes_ordered = false; +std::vector buffer_copy_ordered; + +VKAPI_ATTR void VKAPI_CALL rec_barrier(VkCommandBuffer, VkPipelineStageFlags src_stages, VkPipelineStageFlags dst_stages, + VkDependencyFlags, std::uint32_t memory_count, const VkMemoryBarrier* memory, + std::uint32_t, const VkBufferMemoryBarrier*, std::uint32_t, + const VkImageMemoryBarrier*) { + const VkAccessFlags after = VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT; + for (std::uint32_t i = 0; i < memory_count; ++i) + if ((src_stages & VK_PIPELINE_STAGE_TRANSFER_BIT) && (dst_stages & VK_PIPELINE_STAGE_TRANSFER_BIT) && + (memory[i].srcAccessMask & VK_ACCESS_TRANSFER_WRITE_BIT) && (memory[i].dstAccessMask & after) == after) + transfer_writes_ordered = true; +} VKAPI_ATTR void VKAPI_CALL rec_copy_buffer(VkCommandBuffer, VkBuffer, VkBuffer, std::uint32_t count, const VkBufferCopy* regions) { for (std::uint32_t i = 0; i < count; ++i) buffer_copies.push_back(regions[i]); + buffer_copy_ordered.push_back(transfer_writes_ordered); + transfer_writes_ordered = false; } VKAPI_ATTR void VKAPI_CALL rec_copy_b2i(VkCommandBuffer, VkBuffer, VkImage, VkImageLayout, std::uint32_t count, @@ -52,11 +67,12 @@ void expect(bool ok, const char* what) { } // namespace -int main() { +int main(int argc, char** argv) { using namespace leonida; + const bool expect_ordered = !(argc == 2 && std::strcmp(argv[1], "--expect-unordered") == 0); ReplayFunctions vk{}; - vk.pipeline_barrier = noop_barrier; + vk.pipeline_barrier = rec_barrier; vk.copy_buffer = rec_copy_buffer; vk.copy_buffer_to_image = rec_copy_b2i; vk.copy_image_to_buffer = rec_copy_i2b; @@ -135,6 +151,8 @@ int main() { const auto run = [&](const CommandList& list) { buffer_copies.clear(); + buffer_copy_ordered.clear(); + transfer_writes_ordered = false; b2i_copies.clear(); i2b_copies.clear(); depth24_jobs.clear(); @@ -149,6 +167,21 @@ int main() { expect(buffer_copies.size() == 1 && buffer_copies[0].srcOffset == src_buf.buffer_offset && buffer_copies[0].dstOffset == dst_buf.buffer_offset && buffer_copies[0].size == src_buf.size, "CopyResource applies src and dst buffer_offset"); + expect(buffer_copy_ordered == std::vector{expect_ordered}, + "a buffer copy is ordered after earlier transfer writes (an earlier list on the queue may have written)"); + } + + // 1b. Back-to-back copies into the same buffer, with no barrier from the application: D3D12 runs them in order, + // so each vkCmdCopyBuffer needs its own barrier after the transfer write before it (one barrier ahead of the + // first copy would leave the second unordered against the first). + { + CommandList list; + expect(list.copy_buffer({2, 0, 1, 0, 256}) && list.copy_buffer({2, 128, 1, 512, 256}) && list.close(), + "record two overlapping CopyBufferRegion calls"); + expect(run(list) == ReplayResult::success, "back-to-back buffer copies replay"); + expect(buffer_copies.size() == 2, "both buffer copies are emitted"); + expect(buffer_copy_ordered == (std::vector{expect_ordered, expect_ordered}), + "each back-to-back buffer copy is ordered after the transfer write before it"); } // 2. CopyResource within a single shared backing VkBuffer (arena): disjoint & adjacent succeed, overlap fails. diff --git a/runtime/test/replay_cpu_bench.cpp b/runtime/test/replay_cpu_bench.cpp index 0da65357bb..e4c15cd339 100644 --- a/runtime/test/replay_cpu_bench.cpp +++ b/runtime/test/replay_cpu_bench.cpp @@ -625,6 +625,44 @@ int main(int argc, char** argv) { ++failures; } + // A pending PSO must skip only its own commands. Reuse the same list after + // publication: both direct and indirect dispatch and the draw must now emit. + { + auto vk = scene.vk; + auto original = scene.bare; + const auto ready = original.pipeline; + bool published = false; + scene.bare.pipeline = {}; + scene.bare.async_build = true; + scene.bare.variant = [&](std::uint32_t) { return published ? ready : VK_NULL_HANDLE; }; + ComputePipeline waiting{}, available{}; + waiting.async_build = true; + available.pipeline = ready; + vk.compute_pipeline = [&](std::uintptr_t id) { return id == 1 ? &waiting : &available; }; + static unsigned direct, indirect, draws; + vk.dispatch = [](VkCommandBuffer, std::uint32_t, std::uint32_t, std::uint32_t) { ++direct; }; + vk.dispatch_indirect = [](VkCommandBuffer, VkBuffer, VkDeviceSize) { ++indirect; }; + vk.draw = [](VkCommandBuffer, std::uint32_t, std::uint32_t, std::uint32_t, std::uint32_t) { ++draws; }; + CommandList mixed; + ExecuteIndirect args{IndirectKind::dispatch, 12, 1, Scene::upload}; + args.pipeline = 1; + const bool recorded_mixed = mixed.dispatch({1, {}, 1, 1, 1}) && mixed.execute_indirect(args) && + mixed.draw(plain) && mixed.dispatch({2, {}, 1, 1, 1}) && mixed.close(); + const auto run_mixed = [&] { + direct = indirect = draws = 0; + return replay(mixed, VK_NULL_HANDLE, resolve, vk) == ReplayResult::success; + }; + bool pass = recorded_mixed && run_mixed() && direct == 1 && indirect == 0 && draws == 0; + published = true; + waiting.pipeline = ready; + pass = run_mixed() && direct == 2 && indirect == 1 && draws == 1 && pass; + scene.bare = std::move(original); + if (!pass) { + std::fprintf(stderr, "FAIL pending pipelines: mixed command list skipped ready work or emitted pending work\n"); + ++failures; + } + } + // The counts don't depend on timing: a second run must make exactly the same allocations and calls. const Result again = run(scene, lists, frame, reps, warmup); if (again.emit.vk_calls != f.emit.vk_calls || again.prepare.allocations != f.prepare.allocations) { diff --git a/runtime/test/replay_query_edges_test.cpp b/runtime/test/replay_query_edges_test.cpp index 1e3da7c29b..0b741a07f4 100644 --- a/runtime/test/replay_query_edges_test.cpp +++ b/runtime/test/replay_query_edges_test.cpp @@ -176,6 +176,11 @@ struct MockReplay { expect(!current->conditional, "resolve fill inside predicate"); current->fill(b, off, n, value); }; + // A plain buffer copy is ordered after earlier transfer writes with a barrier, as image copies are; this + // fake only has to accept the call. + v.pipeline_barrier = +[](VkCommandBuffer, VkPipelineStageFlags, VkPipelineStageFlags, VkDependencyFlags, + unsigned, const VkMemoryBarrier*, unsigned, const VkBufferMemoryBarrier*, unsigned, + const VkImageMemoryBarrier*) {}; v.copy_buffer = +[](VkCommandBuffer, VkBuffer a, VkBuffer b, unsigned n, const VkBufferCopy* copies) { ++current->native_copies; for (unsigned i = 0; i < n; ++i) { diff --git a/runtime/test/root_signature_test.cpp b/runtime/test/root_signature_test.cpp index 831739a8c3..169c656f90 100644 --- a/runtime/test/root_signature_test.cpp +++ b/runtime/test/root_signature_test.cpp @@ -421,24 +421,61 @@ int main() { // An empty signature is valid and uses nothing. const StagePackResult empty = pack_stage(RootSignature{}, Stage::Compute); - check(empty.ok && empty.first_sgpr.empty() && empty.end_sgpr == 4, "pack_stage: empty signature"); + check(empty.ok && empty.first_sgpr.empty() && empty.spill_dword.empty() && empty.end_sgpr == 4 && + empty.spill_dwords == 0, + "pack_stage: empty signature"); } - // pack_stage refuses a spill instead of truncating: compute has 28 SGPRs above s4, mesh 16 above s16. + // Compute spills parameters from the first one that does not fit whole from s4..s31 into the packed spill array + // (s[0:1]); non-compute stages still refuse spills. Compute budget is 28 inline SGPRs above s4, mesh 16 above s16. { RootSignature exact; exact.params = {consts(28)}; - check(pack_stage(exact, Stage::Compute).ok, "pack_stage: 28 constants fill compute exactly"); + const StagePackResult exact_r = pack_stage(exact, Stage::Compute); + check(exact_r.ok && exact_r.end_sgpr == 32 && exact_r.spill_dwords == 0 && + exact_r.spill_dword == std::vector({kNoSpill}), + "pack_stage: 28 constants fill compute inline SGPRs with no spill"); + RootSignature over; - over.params = {consts(27), view()}; // the view would need s31..s32 + over.params = {consts(27), view()}; // the view would need s31..s32, so it spills const StagePackResult r = pack_stage(over, Stage::Compute); - check(!r.ok && r.first_sgpr.empty() && r.error.find("root parameter 1") != std::string::npos && - r.error.find("spill") != std::string::npos, - "pack_stage: a parameter that does not fit whole is refused and named"); + check(r.ok && r.first_sgpr == std::vector({4, kNoSgpr}) && + r.spill_dword == std::vector({kNoSpill, 0}) && r.end_sgpr == 31 && r.spill_dwords == 2, + "pack_stage: compute parameter that does not fit whole spills at offset 0"); + RootSignature fits_old; - fits_old.params = {consts(30)}; // fits pack()'s 32 from s0, not 28 from s4 - check(pack(fits_old).ok && !pack_stage(fits_old, Stage::Compute).ok, - "pack_stage: compute budget is 28, not 32"); + fits_old.params = {consts(30)}; // fits pack()'s 32 from s0, spills on compute from s4 + const StagePackResult cs_fits = pack_stage(fits_old, Stage::Compute); + check(pack(fits_old).ok && cs_fits.ok && cs_fits.first_sgpr == std::vector({kNoSgpr}) && + cs_fits.spill_dword == std::vector({0}) && cs_fits.end_sgpr == 4 && + cs_fits.spill_dwords == 30, + "pack_stage: compute inline budget is 28 from s4; 30 constants spill all 30 dwords"); + + // Mixed spill without alignment padding: table (1), root view (2), constants (3) pack at 0, 1, 3. + RootSignature mixed_spill; + mixed_spill.params = {consts(26), view(), table(), view(), consts(3)}; + const StagePackResult ms = pack_stage(mixed_spill, Stage::Compute); + check(ms.ok && ms.first_sgpr == std::vector({4, 30, kNoSgpr, kNoSgpr, kNoSgpr}) && + ms.spill_dword == std::vector({kNoSpill, kNoSpill, 0, 1, 3}) && ms.end_sgpr == 32 && + ms.spill_dwords == 6, + "pack_stage: compute spill packs mixed table, unaligned root view, and constants contiguously"); + + // Once one parameter spills, every subsequent parameter spills even if a later 1-dword table would fit in s31. + RootSignature monotonic; + monotonic.params = {consts(27), view(), table()}; + const StagePackResult mr = pack_stage(monotonic, Stage::Compute); + check(mr.ok && mr.first_sgpr == std::vector({4, kNoSgpr, kNoSgpr}) && + mr.spill_dword == std::vector({kNoSpill, 0, 2}) && mr.end_sgpr == 31 && + mr.spill_dwords == 3, + "pack_stage: first spilling parameter sends every subsequent parameter to the spill array"); + + // 64-dword D3D12 cost still holds for spilling compute signatures. + RootSignature max64; + max64.params = {consts(64)}; + const StagePackResult m64 = pack_stage(max64, Stage::Compute); + check(m64.ok && m64.end_sgpr == 4 && m64.spill_dwords == 64 && m64.d3d12_cost == 64, + "pack_stage: 64-dword spilled compute signature accepted"); + RootSignature tables; tables.params.assign(20, table()); // one dword each: compute s4..s23; pack() needs 40 check(pack_stage(tables, Stage::Compute).ok && !pack(tables).ok, @@ -446,19 +483,30 @@ int main() { tables.params.assign(16, table()); // fills mesh s16..s31 exactly check(pack_stage(tables, Stage::Mesh).ok, "pack_stage: 16 tables fill the mesh stage exactly"); tables.params.push_back(table()); - check(!pack_stage(tables, Stage::Mesh).ok, "pack_stage: a 17th table spills on mesh"); + const StagePackResult mesh_spill = pack_stage(tables, Stage::Mesh); + check(!mesh_spill.ok && mesh_spill.first_sgpr.empty() && + mesh_spill.error.find("root parameter 16") != std::string::npos && + mesh_spill.error.find("spill") != std::string::npos, + "pack_stage: a 17th table still refuses to spill on mesh"); + check(!pack_stage(over, Stage::Pixel).ok && !pack_stage(over, Stage::Vertex).ok, + "pack_stage: non-compute graphics stages still refuse spills"); } // pack_stage keeps pack()'s validation. { + RootSignature invalid_sig; + RootParameter bad_param; + bad_param.type = static_cast(0xffffffffu); + invalid_sig.params = {bad_param}; + check(!pack_stage(invalid_sig, Stage::Compute).ok, "pack_stage: invalid parameter enum rejected"); RootSignature zero; zero.params = {consts(0)}; check(!pack_stage(zero, Stage::Compute).ok, "pack_stage: zero-value constants rejected"); - // Every parameter takes at least as many SGPRs as it costs, so the 32-SGPR budget refuses before the - // 64-dword cost limit can; an over-cost signature is refused all the same. RootSignature costly; - costly.params = {consts(40), consts(30)}; - check(!pack_stage(costly, Stage::Compute).ok, "pack_stage: over-cost signature refused"); + costly.params = {consts(32), consts(33)}; + const StagePackResult costly_r = pack_stage(costly, Stage::Compute); + check(!costly_r.ok && costly_r.error.find("64-dword") != std::string::npos, + "pack_stage: over-cost signature refused even when compute spills"); RootSignature many; many.params.assign(65, table()); check(!pack_stage(many, Stage::Compute).ok, "pack_stage: more than 64 parameters rejected"); diff --git a/runtime/test/shader_library_corpus_test.cpp b/runtime/test/shader_library_corpus_test.cpp index 7fdba23743..962cc7e4d5 100644 --- a/runtime/test/shader_library_corpus_test.cpp +++ b/runtime/test/shader_library_corpus_test.cpp @@ -7,9 +7,10 @@ // from the DXIL/XDAT/XBCH entry, hash it and look it up under the container's stage. The stage comes from the DXIL // part's program header, not from index.json. Every container has to resolve to its own entry (the one named after // the file, or one of its `~N` duplicates) with a readable SPIR-V module, and every RPF index entry has to be reached -// by a container. The entries from /fspx/index.json and /bvh/index.json are counted apart: their -// programs come from the FidelityFX DLL and from XboxBvhBuilder.dll, not from the carved DXBC containers, so they are -// not orphans. Containers with more than one 0x0D payload are +// by a container. The entries from /fspx/index.json, /bvh/index.json and /exe/index.json +// are counted apart: their programs come from the FidelityFX DLL, from XboxBvhBuilder.dll and from the game +// executable, not from the carved DXBC containers, so they are not orphans. Containers with more than one 0x0D +// payload are // counted, and their first payload must not stand in for the last: that is the rule fssm_program follows, so a // regression to the first payload fails here. // @@ -192,16 +193,17 @@ int main() { } if (containers == 0) fail("no .dxbc containers in", dxbc_dir); - const std::size_t rpf_entries = library.size() - library.fspx_size() - library.bvh_size(); + const std::size_t rpf_entries = library.size() - library.fspx_size() - library.fspx_compute_size() - + library.bvh_size() - library.exe_size(); if (reached.size() != rpf_entries) fail(std::to_string(reached.size() > rpf_entries ? reached.size() - rpf_entries : rpf_entries - reached.size()) + " RPF index entries not matched one to one", spirv_dir); std::printf("%zu containers, %zu RPF index entries, %zu reached, %zu FSPX index entries, %zu BVH builder index " - "entries; %zu containers with more than one program; " + "entries, %zu executable index entries; %zu containers with more than one program; " "%zu not translated; %d failures\n", - containers, rpf_entries, reached.size(), library.fspx_size(), library.bvh_size(), multi, untranslated, - failures); + containers, rpf_entries, reached.size(), library.fspx_size(), library.bvh_size(), + library.exe_size(), multi, untranslated, failures); if (untranslated) std::fprintf(stderr, "%zu container(s) have no index entry: the translator left them out, so the lookup had " "nothing to find. Run the shaders stage again with a current translator.\n", diff --git a/runtime/test/shader_library_test.cpp b/runtime/test/shader_library_test.cpp index 55105d987f..439e7ab82c 100644 --- a/runtime/test/shader_library_test.cpp +++ b/runtime/test/shader_library_test.cpp @@ -576,6 +576,16 @@ int main() { CHECK(zlib_inflate(fixed, out, max_limit) && out == bytes("hello hello hello leonida")); CHECK(zlib_inflate(dynamic, out, max_limit) && out == skewed(600)); CHECK(!zlib_inflate(bytes("not zlib"), out)); + // The reason a caller can ask for (dstorage.cpp reports each with its own HRESULT). + ZlibError why = ZlibError::limit; + CHECK(zlib_inflate(dynamic, out, 600, &why) && why == ZlibError::none); + CHECK(!zlib_inflate(dynamic, out, 599, &why) && why == ZlibError::limit); + CHECK(!zlib_inflate(bytes("not zlib"), out, 1 << 20, &why) && why == ZlibError::header); + broken = dynamic; + broken.back() ^= 1; + CHECK(!zlib_inflate(broken, out, 1 << 20, &why) && why == ZlibError::checksum); + broken.resize(100); + CHECK(!zlib_inflate(broken, out, 1 << 20, &why) && why == ZlibError::data); Json json; // "s" holds an escaped quote and a \u escape for U+00E9, which the reader must turn into UTF-8. @@ -719,6 +729,81 @@ int main() { CHECK(!library.load(dir.string(), &error) && !error.empty()); // refused, not thrown std::filesystem::remove_all(dir); + // The descriptor-hash marker (`descriptor_hash` in each module's meta, descriptor_table.h): absent is bare fnv1a; + // the census covers the root index and every sub-index, and the majority decides. LEONIDA_DESCRIPTOR_HASH overrides + // in the device, through descriptor_hash_kind_from_env. + { + const auto root = dir / "hash_kinds"; + const auto write_index = [](const std::filesystem::path& folder, const std::string& modules) { + std::filesystem::create_directories(folder); + std::ofstream index(folder / "index.json", std::ios::binary); + index << "{" << modules << "}"; + }; + const auto module = [](const char* name, const char* marker) { + std::string out = "{\"stage\": \"vs\", \"fssm_sha256\": \"" + std::string(name) + "\""; + if (marker) out += ", \"descriptor_hash\": \"" + std::string(marker) + "\""; + return out + "}"; + }; + const auto census = [](const ShaderLibrary& library, std::size_t fmix32, std::size_t fnv1a) { + return library.descriptor_hash_census().fnv1a_fmix32 == fmix32 && + library.descriptor_hash_census().fnv1a == fnv1a; + }; + + // All-new and all-old: every module agrees, so that is the kind. + write_index(root, "\"a\": " + module("aa", "fnv1a_fmix32") + ", \"b\": " + module("bb", "fnv1a_fmix32")); + ShaderLibrary all_new; + CHECK(all_new.load(root.string(), &error)); + CHECK(census(all_new, 2, 0) && all_new.descriptor_hash_kind() == DescriptorHashKind::fnv1a_fmix32); + + write_index(root, "\"a\": " + module("aa", nullptr) + ", \"b\": " + module("bb", nullptr)); + ShaderLibrary all_old; + CHECK(all_old.load(root.string(), &error)); + CHECK(census(all_old, 0, 2) && all_old.descriptor_hash_kind() == DescriptorHashKind::fnv1a); + + // Mixed: the majority wins (an explicit "fnv1a" counts as fnv1a, like an absent marker). + write_index(root, "\"a\": " + module("aa", "fnv1a_fmix32") + ", \"b\": " + module("bb", "fnv1a_fmix32") + + ", \"c\": " + module("cc", nullptr)); + ShaderLibrary mixed_majority; + CHECK(mixed_majority.load(root.string(), &error)); + CHECK(census(mixed_majority, 2, 1) && + mixed_majority.descriptor_hash_kind() == DescriptorHashKind::fnv1a_fmix32); + + write_index(root, "\"a\": " + module("aa", "fnv1a_fmix32") + ", \"b\": " + module("bb", "fnv1a") + + ", \"c\": " + module("cc", nullptr) + ", \"d\": " + module("dd", nullptr)); + ShaderLibrary mixed_minority; + CHECK(mixed_minority.load(root.string(), &error)); + CHECK(census(mixed_minority, 1, 3) && mixed_minority.descriptor_hash_kind() == DescriptorHashKind::fnv1a); + + // A tie has no majority: the old bare FNV-1a stays. + write_index(root, "\"a\": " + module("aa", "fnv1a_fmix32") + ", \"b\": " + module("bb", nullptr)); + ShaderLibrary tied; + CHECK(tied.load(root.string(), &error)); + CHECK(census(tied, 1, 1) && tied.descriptor_hash_kind() == DescriptorHashKind::fnv1a); + + // A sub-index's marker is counted too: two old modules in the root and one new one in fspx/ is a 1 fnv1a_fmix32 + // / 2 fnv1a library, and loading a folder replaces the census rather than adding to it. + write_index(root, "\"a\": " + module("aa", nullptr) + ", \"b\": " + module("bb", nullptr)); + write_index(root / "fspx", "\"upscaler\": " + module("cc", "fnv1a_fmix32")); + ShaderLibrary sub_index; + CHECK(sub_index.load(root.string(), &error)); + CHECK(census(sub_index, 1, 2) && sub_index.descriptor_hash_kind() == DescriptorHashKind::fnv1a); + CHECK(sub_index.load(root.string(), &error) && census(sub_index, 1, 2)); // reload, not accumulate + std::filesystem::remove_all(root / "fspx"); + CHECK(sub_index.load(root.string(), &error) && census(sub_index, 0, 2)); + + // LEONIDA_DESCRIPTOR_HASH: an exact kind name wins over the census; anything else is ignored. + DescriptorHashKind chosen = DescriptorHashKind::fnv1a_fmix32; + CHECK(descriptor_hash_kind_from_env("fnv1a", &chosen) && chosen == DescriptorHashKind::fnv1a); + CHECK(descriptor_hash_kind_from_env("fnv1a_fmix32", &chosen) && + chosen == DescriptorHashKind::fnv1a_fmix32); + CHECK(!descriptor_hash_kind_from_env(nullptr, &chosen)); + CHECK(!descriptor_hash_kind_from_env("", &chosen)); + CHECK(!descriptor_hash_kind_from_env("Fnv1a", &chosen)); + CHECK(!descriptor_hash_kind_from_env("other", &chosen)); + CHECK(chosen == DescriptorHashKind::fnv1a_fmix32); // a refused value leaves the caller's kind alone + std::filesystem::remove_all(dir); + } + if (const int line = fspx_checks()) return line; // FSPX entries: found by fspx_code_sha256, in the main index or in /fspx/index.json (named "fspx/"). @@ -744,6 +829,7 @@ int main() { const auto found = fspx.fspx_candidates("cs", code_hash); CHECK(found.size() == 1 && found[0]->name == "fspx/upscaler_00" && found[0]->local_size[0] == 8 && found[0]->wave64 && found[0]->fssm_sha256.empty()); + CHECK(found[0]->code_base_known && !found[0]->uses_code_base); CHECK(fspx.spirv(*found[0]).size() == 5); // /fspx/upscaler_00.spv // The key computed both ways finds the entry: from the container slot 62 gets, from the bare program. CHECK(fspx.program_candidates("cs", compute_program(accc_container(fspx_payload(code)))) == found); @@ -764,6 +850,17 @@ int main() { fspx.fspx_candidates("cs", code_hash).empty()); std::filesystem::remove(dir / "fspx" / "index.json"); CHECK(fspx.load(dir.string(), &error) && fspx.size() == 2 && fspx.fspx_size() == 0 && fspx.find("cs", hash)); + std::filesystem::rename(dir / "fspx", dir / "fspx_compute"); + { + std::ofstream sub(dir / "fspx_compute" / "index.json", std::ios::binary); + sub << "{\"upscaler_00\": {\"stage\": \"cs\", \"fspx_code_sha256\": \"" << code_hash + << "\", \"fspx_state_sha256\": \"" << sha256_hex(std::vector(28, 0x11)) << "\"}}"; + } + CHECK(fspx.load(dir.string(), &error) && fspx.size() == 3 && fspx.fspx_size() == 0 && + fspx.fspx_compute_size() == 1); + const auto compute = fspx.program_candidates("cs", compute_program(fspx_payload(code))); + CHECK(compute.size() == 1 && compute[0]->name == "fspx_compute/upscaler_00" && + fspx.spirv(*compute[0]).size() == 5); std::filesystem::remove_all(dir); } @@ -850,7 +947,7 @@ int main() { std::filesystem::create_directories(dir / "fspx"); write(dir / "index.json", "{" + game + "}"); write(dir / "fspx" / "index.json", - "{\"upscaler_00\": {\"stage\": \"cs\", \"fspx_code_sha256\": \"" + sha256_hex(code) + "\"}}"); + "{\"upscaler_00\": {\"stage\": \"cs\", \"uses_code_base\": false, \"fspx_code_sha256\": \"" + sha256_hex(code) + "\"}}"); // The second entry is a program whose metadata failed: no key, so nothing can find it and it is not counted. write(dir / "bvh" / "index.json", "{\"BuilderProgram\": " + program_entry + ",\n \"NoKey\": {\"error\": \"ValueError: synthetic\"}}"); @@ -865,11 +962,14 @@ int main() { const auto found = bvh.program_candidates("cs", program); CHECK(found.size() == 1 && found[0]->name == "bvh/BuilderProgram" && found[0] == bvh.find("cs", builder_hash)); CHECK(found[0]->lds_bytes == 32768 && found[0]->wave64 && found[0]->subgroup_size == 64 && - found[0]->uses_code_base && found[0]->local_size[0] == 64 && found[0]->fspx_code_sha256.empty()); + found[0]->code_base_known && found[0]->uses_code_base && found[0]->local_size[0] == 64 && found[0]->fspx_code_sha256.empty()); CHECK(bvh.spirv(*found[0]).size() == 5); // /bvh/BuilderProgram.spv // The other indexes are untouched: the game's shader and the FSPX program are found as before, each by its // own key, and a builder program is neither an FSPX program nor a shader of another stage. CHECK(bvh.find("cs", hash) && bvh.find("cs", hash)->name == "cs_game"); + CHECK(!bvh.find("cs", hash)->code_base_known); + const auto* no_code_base = bvh.program_candidates("cs", compute_program(code)).at(0); + CHECK(no_code_base->code_base_known && !no_code_base->uses_code_base); CHECK(bvh.program_candidates("cs", compute_program(code)).at(0)->name == "fspx/upscaler_00"); CHECK(bvh.fspx_candidates("cs", builder_hash).empty() && bvh.candidates("vs", builder_hash).empty()); // A program the translator left out (Box16Rehydration today) has no entry: nothing is found, and no other @@ -896,6 +996,38 @@ int main() { std::filesystem::remove_all(dir); } + // game_scarlett_master.exe's inline containers (docs/embedded_shaders.md, "Retail executable"): translated into + // /exe (entries named "exe/") and found by fssm_sha256, like the game's and the builder's shaders. + { + const std::string exe_hash = sha256_hex(bytes("scarlett master executable shader")); + const std::uint32_t words[5] = {0x07230203, 0x00010500, 0, 1, 0}; + std::filesystem::create_directories(dir / "exe"); + { + std::ofstream index(dir / "exe" / "index.json", std::ios::binary); + index << "{\"container_00\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << exe_hash + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"wave64\": true, \"subgroup_size\": 64, " + "\"input_signature\": [{\"semantic\": \"SV_VertexID\", \"semantic_index\": 0, \"register\": 0, " + "\"system_value\": 6, \"component_type\": \"uint\"}]}}"; + std::ofstream spv(dir / "exe" / "container_00.spv", std::ios::binary); + spv.write(reinterpret_cast(words), sizeof(words)); + } + { + std::ofstream index(dir / "index.json", std::ios::binary | std::ios::trunc); + index << "{\"vs_game\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << hash << "\"}}"; + } + ShaderLibrary exe; + CHECK(exe.load(dir.string(), &error) && exe.size() == 2 && exe.exe_size() == 1); + const auto found = exe.candidates("vs", exe_hash); + CHECK(found.size() == 1 && found[0]->name == "exe/container_00" && found[0]->wave64 && + found[0]->push_constant_bytes == 144 && found[0]->input_signature.size() == 1 && + found[0]->input_signature[0].semantic == "SV_VertexID"); + CHECK(exe.spirv(*found[0]).size() == 5); // /exe/container_00.spv + CHECK(exe.candidates("vs", hash).at(0)->name == "vs_game"); + CHECK(exe.candidates("ps", exe_hash).empty()); + std::filesystem::remove_all(dir / "exe"); + std::filesystem::remove_all(dir); + } + // The review case on #1911: one kind-6 program in two containers whose kind-0 entries differ (32x1x1 and // 64x1x1), translated to two different modules. A container picks its own entry by fspx_state_sha256; a bare // kind-6 program cannot tell them apart and is refused as ambiguous; with one module for the key it is accepted. diff --git a/runtime/test/shaders/ps_m15.asm b/runtime/test/shaders/ps_m15.asm index 4c924a72fc..399c50dd4c 100644 --- a/runtime/test/shaders/ps_m15.asm +++ b/runtime/test/shaders/ps_m15.asm @@ -5,7 +5,8 @@ ; code base, dwords 34-35, is the console VA of the FSSM program the layer uploaded). The table of four floats is at ; blob offset 0x100: 0x100 - 4 = 0xfc. build.py writes that blob (fssm-at / fssm-data below) next to the SPIR-V, and ; adds its SHA-256 to the index, as the translator's --fssm-dir does for the game's programs. -; scale = (0.5, 2.0, 1.0, 1.0) s4 = bias, a float from the root constants (s2, s3 are the VS offset) +; scale = (0.5, 2.0, 1.0, 1.0) s11 = bias, a float from the root constants (s9, s10 are the VS offset; the +; console's graphics layout puts the table at s8 and the four constants at s9..s12), moved to s4 ; mrt0 = (r * 0.5 + bias, g * 2.0 + bias, b * 1.0 + bias, a * 1.0) ; The test draws colour (0.25, 0.5, 0.75, 1) with bias 0 and 0.125, and colour (1, 0, 0.5, 1) with bias 0.25. Every ; value is a short binary fraction, so the float render target holds the exact result, bit for bit: @@ -18,6 +19,7 @@ s_getpc_b64 s[6:7] s_add_u32 s6, s6, 0xfc s_addc_u32 s7, s7, 0 +s_mov_b32 s4, s11 s_load_dwordx4 s[8:11], s[6:7], 0x0 v_interp_p1_f32_e32 v2, v0, attr0.x v_interp_p2_f32_e32 v2, v1, attr0.x diff --git a/runtime/test/shaders/ps_m2.asm b/runtime/test/shaders/ps_m2.asm index 0f23cefa3d..fe2fa4530e 100644 --- a/runtime/test/shaders/ps_m2.asm +++ b/runtime/test/shaders/ps_m2.asm @@ -1,12 +1,18 @@ ; M2 pixel shader: samples a texture found through two root descriptor tables. Run: d3d12_m2_textured_test. -; User data from the root signature ([0] a table holding one SRV, [1] a table holding one sampler): -; s[0:1] = console VA of the SRV table's first slot: the 32 bytes of the T# CreateShaderResourceView wrote -; s[2:3] = console VA of the sampler table's first slot: the 16 bytes of the S# CreateSampler wrote +; User data from the root signature ([0] a table holding one SRV, [1] a table holding one sampler), in the console's +; graphics layout (from s8, one dword per table: the heaps live below 4 GiB): +; s8 = console VA of the SRV table's first slot: the 32 bytes of the T# CreateShaderResourceView wrote +; s9 = console VA of the sampler table's first slot: the 16 bytes of the S# CreateSampler wrote +; The first four instructions move them to s[0:1] and s[2:3] with high dwords 0, as the game's shaders force s9 to 0. ; The translator hashes the T# and the S# the shader loads and looks both up in the descriptor hash table (set 0, ; binding 2); the indices pick the image (binding 0) and the sampler (binding 1) in the bindless set. ; attr0.xy = (u, v), 0..1 over the quad. mrt0 = the texel under the pixel. ; fssm-at: 0x10 ; fssm-data: 0x324d5350 0x20535020 +s_mov_b32 s0, s8 +s_mov_b32 s1, 0 +s_mov_b32 s2, s9 +s_mov_b32 s3, 0 s_load_dwordx8 s[8:15], s[0:1], 0x0 s_load_dwordx4 s[16:19], s[2:3], 0x0 s_waitcnt lgkmcnt(0) diff --git a/runtime/test/shaders/ps_m2_array.asm b/runtime/test/shaders/ps_m2_array.asm index 96260bd0a2..663b8ce565 100644 --- a/runtime/test/shaders/ps_m2_array.asm +++ b/runtime/test/shaders/ps_m2_array.asm @@ -1,9 +1,14 @@ ; M2 pixel shader for a 2D array view: ps_m2.asm with dim:SQ_RSRC_IMG_2D_ARRAY and slice coordinate 1.0. Run: -; d3d12_m2_formats_test. User data as in ps_m2.asm ([0] a table holding one SRV, [1] a table holding one sampler). +; d3d12_m2_formats_test. User data as in ps_m2.asm ([0] a table holding one SRV at s8, [1] a table holding one sampler +; at s9), moved to s[0:1] and s[2:3] as there. ; The slice is relative to the view: a view of slices 0..2 reads slice 1, a view of slices 1..2 reads slice 2. ; attr0.xy = (u, v), 0..1 over the quad. mrt0 = the texel under the pixel. ; fssm-at: 0x10 ; fssm-data: 0x324d5350 0x59525241 +s_mov_b32 s0, s8 +s_mov_b32 s1, 0 +s_mov_b32 s2, s9 +s_mov_b32 s3, 0 s_load_dwordx8 s[8:15], s[0:1], 0x0 s_load_dwordx4 s[16:19], s[2:3], 0x0 s_waitcnt lgkmcnt(0) diff --git a/runtime/test/shaders/ps_m2_literal.asm b/runtime/test/shaders/ps_m2_literal.asm index f77ef197f4..cbf635031e 100644 --- a/runtime/test/shaders/ps_m2_literal.asm +++ b/runtime/test/shaders/ps_m2_literal.asm @@ -2,9 +2,12 @@ ; shaders do (docs/design.md, Literal samplers): CLAMP_LAST_TEXEL on all axes, bilinear min/mag, point mip, MAX_LOD ; 12. No heap slot names this S#, so the layer registers it when a pipeline uses the shader; otherwise the shader's ; hash lookup finds the fallback sampler. Run: d3d12_m2_textured_test. -; s[0:1] = console VA of the SRV table's first slot (the T#). attr0.xy = (u, v). mrt0 = the sampled texel. +; s8 = console VA of the SRV table's first slot (the T#; the console's graphics layout, one dword per table from +; s8), moved to s[0:1] with the high dword 0. attr0.xy = (u, v). mrt0 = the sampled texel. ; fssm-at: 0x10 ; fssm-data: 0x324d5350 0x4c544c20 +s_mov_b32 s0, s8 +s_mov_b32 s1, 0 s_load_dwordx8 s[8:15], s[0:1], 0x0 s_movk_i32 s16, 0x92 s_mov_b32 s17, 0xc00000 diff --git a/runtime/test/shaders/ps_m2_uoff.asm b/runtime/test/shaders/ps_m2_uoff.asm index 1c96f50d55..1d38287094 100644 --- a/runtime/test/shaders/ps_m2_uoff.asm +++ b/runtime/test/shaders/ps_m2_uoff.asm @@ -2,10 +2,17 @@ ; and the fallback sampler give the same pixels; with U + 1 the CLAMP sampler returns the last column and the WRAP one ; the same texel as without the offset, so the pixels tell which sampler the draw used. Idea and measurements by ; @Vonsek (#1489). Run: d3d12_m2_textured_test. -; The same unbounded SRV table stays bound across both draws. Root constants s4 and s5 hold -; the descriptor index and byte stride, respectively. +; The same unbounded SRV table stays bound across both draws. User data as in ps_m2.asm (the SRV table at s8, the +; sampler table at s9), then root constants s10 and s11 hold the descriptor index and byte stride, respectively; the +; first six instructions move them to s[0:1], s[2:3] (high dwords 0), s4 and s5. ; fssm-at: 0x10 ; fssm-data: 0x324d5350 0x4f465520 +s_mov_b32 s0, s8 +s_mov_b32 s1, 0 +s_mov_b32 s2, s9 +s_mov_b32 s3, 0 +s_mov_b32 s4, s10 +s_mov_b32 s5, s11 s_mul_i32 s20, s4, s5 s_load_dwordx8 s[8:15], s[0:1], s20 s_load_dwordx4 s[16:19], s[2:3], 0x0 diff --git a/runtime/test/shaders/ps_m3.asm b/runtime/test/shaders/ps_m3.asm index be2a59e2db..fe5d76c129 100644 --- a/runtime/test/shaders/ps_m3.asm +++ b/runtime/test/shaders/ps_m3.asm @@ -1,14 +1,15 @@ ; M3 pixel shader, pass 1: two render targets from root constants. Run: d3d12_m3_frame_test. -; User data (the root signature of vs_m3.asm, [0], eight 32-bit constants): s5, s6, s7 = c0, c1, c2 (floats, k/255). +; User data (the root signature of vs_m3.asm, [0], eight 32-bit constants from s8): s13, s14, s15 = c0, c1, c2 (floats, +; k/255). ; mrt0 = (c0, c1, c2, 1.0) an R8G8B8A8_UNORM target ; mrt1 = (c1 + c2) an R32_FLOAT target: one float add, so the CPU gets the same bits ; fssm-at: 0x10 ; fssm-data: 0x33535350 0x20535020 -v_mov_b32_e32 v2, s5 -v_mov_b32_e32 v3, s6 -v_mov_b32_e32 v4, s7 +v_mov_b32_e32 v2, s13 +v_mov_b32_e32 v3, s14 +v_mov_b32_e32 v4, s15 v_mov_b32_e32 v5, 1.0 -v_add_f32_e32 v6, s6, v4 +v_add_f32_e32 v6, s14, v4 exp mrt0 v2, v3, v4, v5 exp mrt1 v6, off, off, off done vm s_endpgm diff --git a/runtime/test/shaders/ps_m3_post.asm b/runtime/test/shaders/ps_m3_post.asm index 8488030587..34a03dca5e 100644 --- a/runtime/test/shaders/ps_m3_post.asm +++ b/runtime/test/shaders/ps_m3_post.asm @@ -1,11 +1,18 @@ ; M3 pixel shader, pass 2: samples the first render target of pass 1 (read through an SRV in a descriptor table) and ; swaps red and blue. Run: d3d12_m3_frame_test. -; User data from the root signature ([0] a table of one SRV, [1] a table of one sampler, [2] one 32-bit constant): -; s[0:1] = console VA of the SRV table's first slot (the T#); s[2:3] = console VA of the sampler table's slot (the S#) -; s4 = the output's alpha, a float (changes every frame) +; User data from the root signature ([0] a table of one SRV, [1] a table of one sampler, [2] one 32-bit constant), in +; the console's graphics layout (from s8, one dword per table: the heaps live below 4 GiB): +; s8 = console VA of the SRV table's first slot (the T#); s9 = console VA of the sampler table's slot (the S#) +; s10 = the output's alpha, a float (changes every frame) +; The first five instructions move them to s[0:1], s[2:3] (high dwords 0, as the game's shaders force s9 to 0) and s4. ; attr0.xy = (u, v), 0..1 over the target. mrt0 = (texel.b, texel.g, texel.r, s4) ; fssm-at: 0x10 ; fssm-data: 0x33505350 0x20535020 +s_mov_b32 s0, s8 +s_mov_b32 s1, 0 +s_mov_b32 s2, s9 +s_mov_b32 s3, 0 +s_mov_b32 s4, s10 s_load_dwordx8 s[8:15], s[0:1], 0x0 s_load_dwordx4 s[16:19], s[2:3], 0x0 s_waitcnt lgkmcnt(0) diff --git a/runtime/test/shaders/ps_m3_query.asm b/runtime/test/shaders/ps_m3_query.asm index 0693cf5e23..f94841e150 100644 --- a/runtime/test/shaders/ps_m3_query.asm +++ b/runtime/test/shaders/ps_m3_query.asm @@ -1,12 +1,12 @@ ; M3 occlusion probe: one color export, with all framebuffer writes disabled by the PSO. -; Same root constants as ps_m3.asm; no depth export, discard or memory side effects. +; Same root constants as ps_m3.asm (c0, c1, c2 at s13, s14, s15); no depth export, discard or memory side effects. ; Vulkan permits occlusion counts multiplied by the number of written color outputs, even with PRECISE. ; Keep the probe single-output so its count can be compared exactly with the CPU's visible rectangle area. ; fssm-at: 0x10 ; fssm-data: 0x33515350 0x20535020 -v_mov_b32_e32 v2, s5 -v_mov_b32_e32 v3, s6 -v_mov_b32_e32 v4, s7 +v_mov_b32_e32 v2, s13 +v_mov_b32_e32 v3, s14 +v_mov_b32_e32 v4, s15 v_mov_b32_e32 v5, 1.0 exp mrt0 v2, v3, v4, v5 done vm s_endpgm diff --git a/runtime/test/shaders/vs_m15.asm b/runtime/test/shaders/vs_m15.asm index 3ac449b0b4..5b1d381d86 100644 --- a/runtime/test/shaders/vs_m15.asm +++ b/runtime/test/shaders/vs_m15.asm @@ -2,9 +2,11 @@ ; translated game VS that fetch without the driver's fetch program do. Run: d3d12_translated_draw_test (the VS through ; a D3D12 graphics PSO found by the SHA-256 of its FSSM program). ; -; User data, from the root signature [0] descriptor table, [1] four 32-bit constants (docs/d3d12_vulkan.md 3.5): -; s[0:1] = console VA of the table's first slot: the 16 bytes of a V# (base VA, stride 32, 9 records) -; s2, s3 = the draw's clip-space offset (x, y) as floats; s4, s5 = used by the pixel shader (s4: bias) +; User data, from the root signature [0] descriptor table, [1] four 32-bit constants, in the console's graphics layout +; (from s8, one dword per table: the heaps live below 4 GiB): +; s8 = console VA of the table's first slot: the 16 bytes of a V# (base VA, stride 32, 9 records) +; s9, s10 = the draw's clip-space offset (x, y) as floats; s11, s12 = used by the pixel shader (s11: bias) +; The first four instructions move them to s[0:1] (the high dword 0, as the game's shaders force s9 to 0), s2 and s3. ; v0 = VertexIndex. The draw has BaseVertex 0 and BaseInstance 0, so v0 is the same with and without the translator's ; zero-based ids (PR 436): both give 0, 1, 2, ... for DrawInstanced(n, 1, 0, 0). A non-zero StartVertexLocation would ; make the two differ (hardware: zero-based, base in an SGPR), so the test never uses one. @@ -13,6 +15,10 @@ ; param0 = colour ; fssm-at: 0x10 ; fssm-data: 0x35314d56 0x20535620 +s_mov_b32 s0, s8 +s_mov_b32 s1, 0 +s_mov_b32 s2, s9 +s_mov_b32 s3, s10 s_load_dwordx4 s[8:11], s[0:1], 0x0 s_waitcnt lgkmcnt(0) buffer_load_dwordx4 v[4:7], v0, s[8:11], 0 idxen diff --git a/runtime/test/shaders/vs_m3.asm b/runtime/test/shaders/vs_m3.asm index 3bcc2278e7..9c9eb4d589 100644 --- a/runtime/test/shaders/vs_m3.asm +++ b/runtime/test/shaders/vs_m3.asm @@ -1,8 +1,9 @@ ; M3 vertex shader: a rectangle from the vertex index, placed and set at a depth by root constants. Run: ; d3d12_m3_frame_test (found by the SHA-256 of its FSSM program, as vs_m15 and vs_m2 are). -; User data, from the root signature [0], eight 32-bit constants (floats) = s0..s7: -; s0, s1 = clip-space x, y of the first corner; s2, s3 = x, y of the opposite corner; s4 = depth (clip z) -; s5, s6, s7 = used by the pixel shader +; User data, from the root signature [0], eight 32-bit constants (floats) = s8..s15 (the console's graphics layout +; starts at s8): +; s8, s9 = clip-space x, y of the first corner; s10, s11 = x, y of the opposite corner; s12 = depth (clip z) +; s13, s14, s15 = used by the pixel shader ; v0 = VertexIndex, 0..3 (the test draws indices 0 1 2 2 1 3 with DrawIndexedInstanced and base vertex 0): ; u = v0 & 1, v = (v0 >> 1) & 1; pos0 = (x0 + u * (x1 - x0), y0 + v * (y1 - y0), z, 1) ; The corners are multiples of 1/32 and the depths are dyadic, so every operation here is exact however it is fused. @@ -13,15 +14,15 @@ v_and_b32_e32 v2, 2, v0 v_cvt_f32_u32_e32 v1, v1 v_cvt_f32_u32_e32 v2, v2 v_mul_f32_e32 v2, 0.5, v2 -v_mov_b32_e32 v7, s0 -v_mov_b32_e32 v8, s1 -v_mov_b32_e32 v9, s2 -v_mov_b32_e32 v10, s3 +v_mov_b32_e32 v7, s8 +v_mov_b32_e32 v8, s9 +v_mov_b32_e32 v9, s10 +v_mov_b32_e32 v10, s11 v_sub_f32_e32 v9, v9, v7 v_sub_f32_e32 v10, v10, v8 v_fma_f32 v3, v1, v9, v7 v_fma_f32 v4, v2, v10, v8 -v_mov_b32_e32 v5, s4 +v_mov_b32_e32 v5, s12 v_mov_b32_e32 v6, 1.0 exp pos0 v3, v4, v5, v6 done s_endpgm diff --git a/runtime/test/startup_trace_test.cpp b/runtime/test/startup_trace_test.cpp index 336f957eb4..170ea39d55 100644 --- a/runtime/test/startup_trace_test.cpp +++ b/runtime/test/startup_trace_test.cpp @@ -272,6 +272,8 @@ void test_trace(const fs::path& dir) { check(has(e, "\"code\":\"0xc0000005\""), "exception code"); check(has(e, "\"at\":" + mod + hex_rva(kFaultRva) + "\""), "exception address is module+RVA"); check(has(e, "\"access\":\"read\"") && has(e, "\"address\":\"0x0\""), "access kind and faulting address"); + check(has(e, "\"region\":{\"base\":\"0x0\"") && has(e, "\"state\":\"0x10000\""), + "the faulting page's region (address 0 is free memory)"); check(has(e, "\"stack\":[" + mod.substr(0) + hex_rva(kFaultRva)), "stack starts at the faulting instruction"); check(find_line(lines, "exit") == &lines.back(), "exit comes last"); diff --git a/runtime/test/subgroup_size_test.cpp b/runtime/test/subgroup_size_test.cpp index d20e9e5e1a..2628509fc7 100644 --- a/runtime/test/subgroup_size_test.cpp +++ b/runtime/test/subgroup_size_test.cpp @@ -261,6 +261,32 @@ int main() { CHECK(caps.subgroup_size_control && !caps.compute_full_subgroups); } + // --- Partition-invariant wave64 graphics ---------------------------------------------------------------- + { + // The translator's tier (index.json `wave64_graphics`, docs/design.md "Wave64 graphics"): A and B are exact + // when the wave is cut into two 32-lane halves, C is not. An entry without the analysis stays conservative. + ShaderEntry e = entry("ps", true); + CHECK(!graphics_partition_invariant(e)); + e.wave64_graphics = "A"; + CHECK(graphics_partition_invariant(e)); + e.wave64_graphics = "B"; + CHECK(graphics_partition_invariant(e)); + e.wave64_graphics = "C"; + CHECK(!graphics_partition_invariant(e)); + // Only a wave64 VS/PS/GS carries the analysis; compute, mesh and wave32 entries do not. + e = entry("vs", true); + e.wave64_graphics = "A"; + CHECK(graphics_partition_invariant(e)); + for (const char* stage : {"cs", "ms"}) { + e = entry(stage, true); + e.wave64_graphics = "A"; + CHECK(!graphics_partition_invariant(e)); + } + e = entry("ps", false); + e.wave64_graphics = "A"; + CHECK(!graphics_partition_invariant(e)); + } + std::printf("subgroup size decision: AMD-like, NVIDIA-like, old RADV, limits, create-info chain and query OK\n"); return 0; } diff --git a/runtime/test/thread_stacks_test.cpp b/runtime/test/thread_stacks_test.cpp new file mode 100644 index 0000000000..60b48870f3 --- /dev/null +++ b/runtime/test/thread_stacks_test.cpp @@ -0,0 +1,168 @@ +// rt::StackSampler (runtime/src/thread_stacks.cpp, LEONIDA_STACKS): the call chain of a thread blocked in a known +// function, and of a thread whose stack keeps changing while it is sampled. No game data. +#include +#include + +#include +#include +#include +#include + +#include "../src/thread_stacks.h" + +namespace { + +int g_checks = 0; +int g_failures = 0; + +void check(bool condition, const char* what) { + ++g_checks; + std::printf("%s %s\n", condition ? "PASS" : "FAIL", what); + if (!condition) ++g_failures; +} + +// The function an address lies in, by its unwind entry (immune to incremental-link thunks). The optimiser can move +// part of a function into a separate chunk whose unwind info chains to the function's own entry: follow the chain. +DWORD64 function_of(DWORD64 address) { + DWORD64 base = 0; + const auto* entry = RtlLookupFunctionEntry(address, &base, nullptr); + if (!entry) return 0; + for (int depth = 0; depth < 32; ++depth) { + if (entry->UnwindData & 1) { // An indirect entry names another RUNTIME_FUNCTION. + entry = reinterpret_cast(base + (entry->UnwindData & ~DWORD(1))); + continue; + } + const auto* info = reinterpret_cast(base + entry->UnwindData); + if (!((info[0] >> 3) & UNW_FLAG_CHAININFO)) break; + const unsigned codes = (info[2] + 1u) & ~1u; // The code array is padded to an even count. + entry = reinterpret_cast(info + 4 + codes * 2); + } + return base + entry->BeginAddress; +} + +// The function that called this one. +__declspec(noinline) DWORD64 here() { return function_of(reinterpret_cast(_ReturnAddress())); } + +// Frame index of the first frame in `function`, or -1. +int find(const std::uint64_t* frames, size_t count, DWORD64 function) { + for (size_t i = 0; i < count; ++i) + if (function && function_of(frames[i]) == function) return static_cast(i); + return -1; +} + +std::atomic g_blocked_fn{0}, g_blocked_main_fn{0}, g_spin_fn{0}; +std::atomic g_stop{false}; +std::atomic g_sink{0}; + +// A frame larger than a page (probed by __chkstk), blocked in WaitForSingleObject. +__declspec(noinline) int blocked_here(HANDLE ready, HANDLE release) { + volatile char pad[64 * 1024]; + pad[0] = 1; + pad[sizeof(pad) - 1] = 2; + g_blocked_fn = here(); + SetEvent(ready); + WaitForSingleObject(release, INFINITE); + return pad[0] + pad[sizeof(pad) - 1]; // Keeps the frame alive across the wait, and the call from a tail call. +} + +HANDLE g_ready = nullptr; +HANDLE g_release = nullptr; + +__declspec(noinline) DWORD WINAPI blocked_main(void*) { + g_blocked_main_fn = here(); + const int value = blocked_here(g_ready, g_release); + return static_cast(value) + 1; +} + +__declspec(noinline) unsigned recurse(unsigned depth) { + volatile unsigned local[16]; + local[0] = depth; + local[15] = depth * 3; + if (depth == 0) return local[15]; + return recurse(depth - 1) + local[0]; +} + +__declspec(noinline) DWORD WINAPI spin_main(void*) { + g_spin_fn = here(); + while (!g_stop.load(std::memory_order_relaxed)) g_sink.fetch_add(recurse(g_sink.load() % 48 + 1)); + return 0; +} + +void blocked_thread() { + g_ready = CreateEventW(nullptr, TRUE, FALSE, nullptr); + g_release = CreateEventW(nullptr, TRUE, FALSE, nullptr); + HANDLE thread = CreateThread(nullptr, 0, blocked_main, nullptr, 0, nullptr); + check(thread && WaitForSingleObject(g_ready, 5000) == WAIT_OBJECT_0, "helper thread reached its wait"); + rt::StackSampler sampler; + std::uint64_t frames[rt::StackSampler::kMaxFrames] = {}; + size_t count = 0; + int blocked = -1, outer = -1; + for (int attempt = 0; attempt < 100 && (blocked < 0 || outer < 0); ++attempt) { + count = sampler.sample(thread, frames); + blocked = find(frames, count, g_blocked_fn); + outer = find(frames, count, g_blocked_main_fn); + if (blocked < 0 || outer < 0) Sleep(10); + } + for (size_t i = 0; i < count; ++i) std::printf(" #%zu 0x%llx\n", i, static_cast(frames[i])); + check(blocked > 0, "the chain holds blocked_here below the wait it called"); + check(outer > blocked, "and blocked_main above it, through the 64 KiB frame"); + SetEvent(g_release); + DWORD code = 0; + check(WaitForSingleObject(thread, 5000) == WAIT_OBJECT_0 && GetExitCodeThread(thread, &code) && code == 4, + "the sampled thread resumed and finished normally"); + CloseHandle(thread); + CloseHandle(g_ready); + CloseHandle(g_release); +} + +// The live stack changes after every sample's resume: each chain must come from the copy and reach spin_main. +void moving_thread() { + HANDLE thread = CreateThread(nullptr, 0, spin_main, nullptr, 0, nullptr); + while (!g_spin_fn) Sleep(1); + rt::StackSampler sampler; + std::uint64_t frames[rt::StackSampler::kMaxFrames] = {}; + int sampled = 0, reached = 0, deep = 0; + for (int i = 0; i < 300; ++i) { + const size_t count = sampler.sample(thread, frames); + if (!count) continue; + ++sampled; + // Deeper than kMaxFrames recursion stops at the cap without reaching spin_main; that is not a failure. + if (count == rt::StackSampler::kMaxFrames && find(frames, count, g_spin_fn) < 0) { + ++deep; + continue; + } + if (find(frames, count, g_spin_fn) >= 0) ++reached; + else if (sampled - reached - deep <= 2) { + std::printf(" chain %d misses spin_main (0x%llx):\n", i, static_cast(g_spin_fn.load())); + for (size_t f = 0; f < count; ++f) + std::printf(" #%zu 0x%llx in 0x%llx\n", f, static_cast(frames[f]), + static_cast(function_of(frames[f]))); + } + } + g_stop = true; + WaitForSingleObject(thread, 5000); + CloseHandle(thread); + std::printf(" %d samples, %d reach spin_main, %d at the frame cap\n", sampled, reached, deep); + check(sampled == 300, "every sample of a running thread succeeded"); + check(reached + deep == sampled, "every chain of a moving stack unwinds to its thread function"); +} + +void parse() { + std::vector t; + check(rt::parse_stack_times("90,180", t) && t == std::vector{90, 180}, "parse 90,180"); + check(rt::parse_stack_times("180,90,90", t) && t == std::vector{90, 180}, "parse sorts and dedupes"); + check(!rt::parse_stack_times("", t) && t.empty(), "empty text refused"); + check(!rt::parse_stack_times("1,,2", t) && !rt::parse_stack_times("1,", t) && !rt::parse_stack_times("x", t) && + !rt::parse_stack_times("-5", t) && !rt::parse_stack_times("1.5", t), + "bad tokens refused"); +} + +} // namespace + +int main() { + parse(); + blocked_thread(); + moving_thread(); + std::printf("%d checks, %d failures\n", g_checks, g_failures); + return g_failures ? 1 : 0; +} diff --git a/runtime/test/title_va_alias_test.cpp b/runtime/test/title_va_alias_test.cpp new file mode 100644 index 0000000000..b658ed3cce --- /dev/null +++ b/runtime/test/title_va_alias_test.cpp @@ -0,0 +1,72 @@ +// leonida::TitleVaAliases (src/title_va_alias.h): where an address inside a title-placed buffer (Xbox device slot +// 133) is translated to, and that everything else is left alone. No GPU. +#include "../src/title_va_alias.h" + +#include +#include + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +int main() { + leonida::TitleVaAliases a; + constexpr std::uint64_t title = 0x20000000000ull; // a synthetic user-mode VA far above 4 GiB + constexpr std::uint64_t size = 0x10000; + constexpr std::uint64_t arena = 0x2340000; + // Empty: identity everywhere. + EXPECT(a.size() == 0 && a.shader_va(title) == title && a.shader_va(0) == 0); + EXPECT(!a.add(title, 0, arena)); // empty range + EXPECT(!a.add(UINT64_MAX - 4, 16, arena)); // wraps + EXPECT(a.add(title, size, arena) && a.size() == 1); + // Inside: the same offset in the copy, first and last byte included. + EXPECT(a.shader_va(title) == arena); + EXPECT(a.shader_va(title + 0x123) == arena + 0x123); + EXPECT(a.shader_va(title + size - 1) == arena + size - 1); + // Negative controls: one byte before, the end itself, and an arena VA are untouched. + EXPECT(a.shader_va(title - 1) == title - 1); + EXPECT(a.shader_va(title + size) == title + size); + EXPECT(a.shader_va(arena) == arena); + // The free span around an address: between the ranges, so a window made for it never covers one. + std::uint64_t lo = 1, hi = 1; + a.gap(title + size + 5, lo, hi); + EXPECT(lo == title + size && hi == UINT64_MAX); + a.gap(title - 5, lo, hi); + EXPECT(lo == 0 && hi == title); + // Without a device's resolver, resolve only translates what was added, and counts it. + EXPECT(a.resolve(title + 4, 4, leonida::TitleVaAliases::root_view) == arena + 4); + EXPECT(a.resolve(title - 4, 4, leonida::TitleVaAliases::root_view) == title - 4); + EXPECT(a.translated(leonida::TitleVaAliases::root_view) == 1); + a.note(title + 8, leonida::TitleVaAliases::vertex_view); + a.note(title - 8, leonida::TitleVaAliases::vertex_view); + EXPECT(a.untranslated(leonida::TitleVaAliases::vertex_view) == 1); + // The title's memory: a commit inside a reservation is one range; outside every range is not the title's. + std::uint64_t mlo = 0, mhi = 0; + a.add_title_memory(0x40000000, 0x100000); + a.add_title_memory(0x40010000, 0x1000); + EXPECT(a.title_memory(0x40080000, mlo, mhi) && mlo == 0x40000000 && mhi == 0x40100000); + EXPECT(!a.title_memory(0x40100000, mlo, mhi) && !a.title_memory(0x3FFFFFFF, mlo, mhi)); + a.remove_title_memory(0x40000000); + EXPECT(!a.title_memory(0x40080000, mlo, mhi)); + // A wrapping target (an import below heap_base) is kept as is: modular arithmetic. + constexpr std::uint64_t below = 0xFFFFFFFFFFF00000ull; + EXPECT(a.add(title + 0x100000, size, below) && a.shader_va(title + 0x100010) == below + 0x10); + std::uint64_t source{}, available{}; + EXPECT(a.source_of_vsharp((below + 0x10) & ((1ull << 48) - 1), source, available)); + EXPECT(source == title + 0x100010 && available == size - 0x10); + EXPECT(!a.source_of_vsharp((below + size) & ((1ull << 48) - 1), source, available)); + // A new buffer over part of a live range replaces it; the old range's removal does not touch the new one. + EXPECT(a.add(title + 0x8000, size, 0x5000000)); + EXPECT(a.shader_va(title) == title); // the replaced range is gone entirely + EXPECT(a.shader_va(title + 0x8000) == 0x5000000); + a.remove(title, arena); // stale: nothing starts there any more + EXPECT(a.shader_va(title + 0x8000) == 0x5000000); + a.remove(title + 0x8000, 0x1234); // another target: kept + EXPECT(a.shader_va(title + 0x8000) == 0x5000000); + a.remove(title + 0x8000, 0x5000000); + EXPECT(a.shader_va(title + 0x8000) == title + 0x8000); + a.remove(title + 0x100000, below); + EXPECT(a.size() == 0 && a.shader_va(title + 0x100010) == title + 0x100010); + std::printf("title_va_alias: translation inside a title-placed range, identity outside it and after release\n"); + return 0; +} diff --git a/runtime/test/title_window_test.cpp b/runtime/test/title_window_test.cpp new file mode 100644 index 0000000000..b3ea9ac825 --- /dev/null +++ b/runtime/test/title_window_test.cpp @@ -0,0 +1,104 @@ +// find_title_window (shims/title_window.h): the window PresentX shows a GDKX title's frames in. +// +// The windows belong to a thread that never pumps its messages, as the title's window thread may be busy at the first +// PresentX: the lookup must still answer at once. The negative control shows that thread really does not answer a +// sent message (WM_GETTEXT, what GetWindowTextW sends across threads, times out), so a lookup that sent one would block. + +#include "title_window.h" + +#include +#include +#include + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +namespace { + +struct Windows { + HWND title = nullptr; // visible, unowned, the largest client area: the title's window + HWND small = nullptr; // visible, unowned, smaller + HWND hidden = nullptr; // never shown (like the IME windows and a driver's dummy window) + HWND owned = nullptr; // visible but owned by `title` (a dialog, not a top-level frame) + HWND tool = nullptr; // visible tool window +}; + +HWND make(const wchar_t* name, DWORD ex_style, DWORD style, int width, int height, HWND owner) { + return CreateWindowExW(ex_style | WS_EX_NOACTIVATE, L"LeonidaTitleWindowTest", name, style, 0, 0, width, height, + owner, nullptr, GetModuleHandleW(nullptr), nullptr); +} + +} // namespace + +int main() { + WNDCLASSW window_class{}; + window_class.lpfnWndProc = DefWindowProcW; + window_class.hInstance = GetModuleHandleW(nullptr); + window_class.lpszClassName = L"LeonidaTitleWindowTest"; + EXPECT(RegisterClassW(&window_class)); + + // A process with no window of its own has no title window. + EXPECT(rt::d3d12::find_title_window(GetCurrentProcessId()) == nullptr); + + Windows windows; + HANDLE made = CreateEventW(nullptr, TRUE, FALSE, nullptr); + HANDLE release = CreateEventW(nullptr, TRUE, FALSE, nullptr); + EXPECT(made && release); + std::thread window_thread([&] { + windows.hidden = make(L"hidden", 0, WS_OVERLAPPEDWINDOW, 900, 700, nullptr); + windows.small = make(L"small", 0, WS_OVERLAPPEDWINDOW | WS_VISIBLE, 160, 120, nullptr); + windows.title = make(L"title", 0, WS_OVERLAPPEDWINDOW | WS_VISIBLE, 320, 240, nullptr); + windows.owned = make(L"owned", 0, WS_OVERLAPPEDWINDOW | WS_VISIBLE, 800, 600, windows.title); + windows.tool = make(L"tool", WS_EX_TOOLWINDOW, WS_OVERLAPPEDWINDOW | WS_VISIBLE, 800, 600, nullptr); + SetEvent(made); + WaitForSingleObject(release, INFINITE); // no message loop: like a title window thread that is busy + DestroyWindow(windows.tool); + DestroyWindow(windows.owned); + DestroyWindow(windows.title); + DestroyWindow(windows.small); + DestroyWindow(windows.hidden); + }); + WaitForSingleObject(made, INFINITE); + int result = 0; + [&] { + auto check = [&](bool ok, int line, const char* what) { + if (!ok && !result) { + std::fprintf(stderr, "line %d: %s\n", line, what); + result = 1; + } + }; +#define CHECK(condition) check((condition), __LINE__, #condition) + CHECK(windows.title && windows.small && windows.hidden && windows.owned && windows.tool); + + // Negative control: the window thread does not answer a sent message. + wchar_t text[16]{}; + DWORD_PTR copied = 0; + CHECK(!SendMessageTimeoutW(windows.title, WM_GETTEXT, 16, reinterpret_cast(text), SMTO_BLOCK, 200, + &copied)); + + // The lookup answers at once anyway, and picks the visible unowned non-tool window with the largest client + // area: not the larger hidden, owned or tool windows. + const auto start = std::chrono::steady_clock::now(); + const HWND found = rt::d3d12::find_title_window(GetCurrentProcessId()); + const auto took = std::chrono::steady_clock::now() - start; + CHECK(found == windows.title); + CHECK(took < std::chrono::milliseconds(100)); + + // The runtime's own window, excluded, is never the answer. + CHECK(rt::d3d12::find_title_window(GetCurrentProcessId(), windows.title) == windows.small); + // Another process's windows are not this title's. + CHECK(rt::d3d12::find_title_window(GetCurrentProcessId() ^ 0x40000000u) == nullptr); +#undef CHECK + }(); + SetEvent(release); + window_thread.join(); + CloseHandle(made); + CloseHandle(release); + if (result) return result; + + // Gone with its windows. + EXPECT(rt::d3d12::find_title_window(GetCurrentProcessId()) == nullptr); + std::puts("title_window: ok"); + return 0; +} diff --git a/runtime/test/title_write_watch_test.cpp b/runtime/test/title_write_watch_test.cpp new file mode 100644 index 0000000000..fdf00570fc --- /dev/null +++ b/runtime/test/title_write_watch_test.cpp @@ -0,0 +1,148 @@ +// leonida::title_write_watch (runtime/src/title_page_watch.h): the record of the title's write-watched reservations, and +// the journal that shares the kernel's answers between the trackers over the same pages (an asking clears the kernel's +// bits for everyone). No game data, no GPU. +// 1. two readers over one page both see a write, though the first one's asking cleared the kernel's bit; +// 2. a reader isn't told again what it saw, and a write after its asking is in its next one; +// 3. a kernel write (a plain ReadFile, no file shim) into a write-watched page is in the answer, and doesn't fail; +// 4. memory the kernel doesn't write-watch (a section view) is refused; +// 5. a reader that joins another's pages (merge_reader) sees what the other had not seen yet; +// 6. the record: add, contains, for_each_in split by reservation, remove. +#include + +#include +#include +#include +#include +#include + +#include "../src/title_page_watch.h" + +namespace { + +namespace ww = leonida::title_write_watch; +using Runs = std::vector>; + +int g_checks = 0; +int g_failures = 0; + +void check(bool condition, const char* what) { + ++g_checks; + std::printf("%s %s\n", condition ? "PASS" : "FAIL", what); + if (!condition) ++g_failures; +} + +// One asking for `reader`: the pages it is told were written, and whether a run was refused. +struct Answer { + std::set pages; + bool refused = false; +}; +Answer ask(std::uint64_t reader, const Runs& runs) { + Answer answer; + ww::ask( + reader, runs, + [&](std::uintptr_t from, std::uintptr_t to) { + for (std::uintptr_t p = from; p < to; p += ww::kPage) answer.pages.insert(p); + }, + [&](std::uintptr_t, std::uintptr_t) { answer.refused = true; }); + return answer; +} + +} // namespace + +int main() { + constexpr SIZE_T kBytes = 16 * ww::kPage; + auto* pages = static_cast( + VirtualAlloc(nullptr, kBytes, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE)); + check(pages != nullptr, "a write-watched reservation"); + if (!pages) return 1; + const auto base = reinterpret_cast(pages); + ww::add(base, kBytes); + const Runs all{{base, base + kBytes}}; + const std::uint64_t a = ww::open_reader(), b = ww::open_reader(); + + // 1. Both readers see one write. + pages[3 * ww::kPage + 5] = 1; + Answer first = ask(a, all); + check(!first.refused && first.pages == std::set{base + 3 * ww::kPage}, + "the first reader is told the written page"); + Answer second = ask(b, all); + check(!second.refused && second.pages == std::set{base + 3 * ww::kPage}, + "the second reader is told it too, though the first asking cleared the kernel's bit"); + + // 2. Nothing new for either; a later write reaches both, and only that one. + check(ask(a, all).pages.empty() && ask(b, all).pages.empty(), "a reader isn't told again what it saw"); + pages[7 * ww::kPage] = 2; + pages[8 * ww::kPage] = 2; + first = ask(a, Runs{{base + 4 * ww::kPage, base + kBytes}}); + check(first.pages == std::set{base + 7 * ww::kPage, base + 8 * ww::kPage}, + "a later write is in the next asking (asked over part of the reservation)"); + check(ask(b, all).pages == first.pages, "and in the other reader's next one"); + + // 3. A kernel write: a plain buffered ReadFile into the watched pages succeeds and is in the answer. + wchar_t directory[MAX_PATH]{}, path[MAX_PATH]{}; + GetTempPathW(MAX_PATH, directory); + GetTempFileNameW(directory, L"lww", 0, path); + HANDLE file = CreateFileW(path, GENERIC_READ | GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, + FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE, nullptr); + std::vector bytes(2 * ww::kPage); + for (std::size_t i = 0; i < bytes.size(); ++i) bytes[i] = std::uint8_t(i * 11 + 3); + DWORD done = 0; + check(file != INVALID_HANDLE_VALUE && WriteFile(file, bytes.data(), DWORD(bytes.size()), &done, nullptr) && + done == bytes.size(), + "temporary file written"); + SetFilePointer(file, 0, nullptr, FILE_BEGIN); + done = 0; + const BOOL read = ::ReadFile(file, pages + 10 * ww::kPage + 0x800, DWORD(bytes.size()), &done, nullptr); + CloseHandle(file); + check(read && done == bytes.size(), "a plain ReadFile into write-watched pages succeeds (they stay writable)"); + const std::set kernel_pages{base + 10 * ww::kPage, base + 11 * ww::kPage, base + 12 * ww::kPage}; + check(ask(a, all).pages == kernel_pages, "the kernel's write is in the answer, all three pages it touched"); + check(ask(b, all).pages == kernel_pages, "for the other reader too"); + + // 4. A section view is not write-watched: refused, and nothing reported. + HANDLE section = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, 0x10000, nullptr); + auto* view = section ? static_cast(MapViewOfFile(section, FILE_MAP_ALL_ACCESS, 0, 0, 0x10000)) + : nullptr; + check(view != nullptr, "a section view"); + if (view) { + view[0] = 1; + const auto at = reinterpret_cast(view); + const Answer refused = ask(a, Runs{{at, at + 0x10000}}); + check(refused.refused && refused.pages.empty(), "the kernel refuses a section view"); + UnmapViewOfFile(view); + } + if (section) CloseHandle(section); + + // 5. A reader that takes over another's pages asks from the older of the two lastings. + pages[0] = 3; + check(ask(a, all).pages == std::set{base}, "reader a sees a write reader b hasn't asked about"); + const std::uint64_t c = ww::open_reader(); + check(ask(c, all).pages.empty(), "a new reader is told nothing written before it"); + ww::merge_reader(c, b); + check(ask(c, all).pages == std::set{base}, "having joined b's pages, it is told what b missed"); + ww::close_reader(b); + ww::close_reader(c); + + // 6. The record of reservations. + const auto other = reinterpret_cast( + VirtualAlloc(nullptr, 4 * ww::kPage, MEM_RESERVE | MEM_WRITE_WATCH, PAGE_READWRITE)); + ww::add(other, 4 * ww::kPage); + const std::uintptr_t lo = (std::min)(base, other), hi = (std::max)(base + kBytes, other + 4 * ww::kPage); + Runs split; + ww::for_each_in(lo, hi, [&](std::uintptr_t from, std::uintptr_t to) { split.emplace_back(from, to); }); + check(split.size() == 2, "for_each_in gives one run per reservation"); + check(ww::contains(base + kBytes - 1) && !ww::contains(base + kBytes + 0x10000 * 64), + "contains: inside a reservation, and not far past it"); + const auto generation = ww::generation(); + ww::remove(other + ww::kPage); // any address inside it + check(!ww::contains(other) && ww::contains(base) && ww::generation() != generation, + "remove forgets the reservation holding the address, and only it"); + ww::remove(base); + ww::close_reader(a); + VirtualFree(reinterpret_cast(other), 0, MEM_RELEASE); + VirtualFree(pages, 0, MEM_RELEASE); + + std::printf("title_write_watch_test: %s (%d checks, %d failures)\n", g_failures ? "FAILED" : "OK", g_checks, + g_failures); + return g_failures ? 1 : 0; +} diff --git a/runtime/test/unimplemented_policy_test.cpp b/runtime/test/unimplemented_policy_test.cpp index 8941901296..796b9a0de1 100644 --- a/runtime/test/unimplemented_policy_test.cpp +++ b/runtime/test/unimplemented_policy_test.cpp @@ -231,10 +231,18 @@ void test_classification() { check(cls("gameinput.dll", "GameInputCreate") == ReturnClass::HResult, "GameInputCreate is hresult"); check(cls("dstorage_xs.dll", "DStorageGetFactory") == ReturnClass::HResult, "the console dstorage name is hresult"); + check(cls("xcrdapi.dll", "DStorageGetFactory") == ReturnClass::HResult, "xcrdapi's DStorageGetFactory is hresult"); + check(cls("xcrdapi.dll", "XCrdLeonidaPolicyProbe") == ReturnClass::Other, "other xcrdapi imports are other"); check(cls("xg_xs.dll", "XGCreateTexture2DComputer") == ReturnClass::Other, "unmeasured xg_xs import is other"); - check(cls("acphal.dll", "AcpHalCreate") == ReturnClass::HResult, "AcpHalCreate is hresult"); - check(cls("acphal.dll", "ApuFree") == ReturnClass::Other, "ApuFree returns void"); - check(cls("acphal.dll", "ApuMapVirtualAddress") == ReturnClass::Other, "ApuMapVirtualAddress returns uint32_t"); + check(cls("xg_xs.dll", "XGCreateTextureComputer") == ReturnClass::Other, + "the xg_xs shim's export is bound, not classified here"); + check(cls("chad.dll", "XDspConnect") == ReturnClass::HResult, "chad XDsp* is hresult"); + check(cls("xapu.dll", "XApuConnect") == ReturnClass::HResult, "xapu XApu* is hresult"); + check(cls("xapu.dll", "XApuGetResultCount") == ReturnClass::Other, "xapu XApuGetResultCount returns uint32_t"); + check(cls("acphal.dll", "AcpHalCreate") == ReturnClass::HResult, "AcpHalCreate is hresult from registry"); + check(cls("acphal.dll", "ApuFree") == ReturnClass::Other, "ApuFree is void"); + check(cls("acphal.dll", "ApuMapVirtualAddress") == ReturnClass::Other, + "ApuMapVirtualAddress returns a 32-bit APU address"); check(cls("xgameruntime.dll", "XGameRuntimeInitialize") == ReturnClass::HResult, "XGameRuntimeInitialize"); check(cls("xgameruntime.dll", "XUserAddAsync") == ReturnClass::HResult, "XUser* is hresult"); check(cls("xgameruntime.dll", "XTaskQueueCreate") == ReturnClass::HResult, "XTaskQueueCreate is hresult"); diff --git a/runtime/test/vk_bindless_grow_test.cpp b/runtime/test/vk_bindless_grow_test.cpp new file mode 100644 index 0000000000..126de2f79e --- /dev/null +++ b/runtime/test/vk_bindless_grow_test.cpp @@ -0,0 +1,329 @@ +// The bindless set (src/vulkan_bindless.h) under churn and under memory pressure, at the Vulkan level, no shaders. +// +// 1. Churn: 2D image views are added, keyed in the hash table, and removed again, frame after frame, with one live +// key rebound each frame so every flush makes a new generation. Past its initial capacity the table must stop +// growing (erased slots and freed indices are reused), and after a warm-up the generations come from the +// spares: no further table buffers or descriptor pools are allocated. +// 2. Device-local memory runs out while the table grows: the new table goes to host memory and the flush works. +// 3. No memory at all and no spare, nothing running: the table is rewritten in place. +// 4. No memory at all, work still running, and the table must grow: the flush does not fail (the submission would +// be refused): it keeps the previous table and catches up once memory is back. An index removed meanwhile is +// not given out again until then, since the stale table may still name it. +// vkAllocateMemory and vkCreateDescriptorPool are wrapped through the PFN_vkGetDeviceProcAddr the set loads with, +// to count them and to fail them on demand. Exit 77 when the device lacks the set's descriptor-indexing features. +// LEONIDA_VK_VALIDATION=1 runs under VK_LAYER_KHRONOS_validation; a validation error fails the test. +#ifndef VK_NO_PROTOTYPES +#define VK_NO_PROTOTYPES +#endif +#include "vk_test_device.h" +#include "../src/vulkan_bindless.h" + +#include +#include +#include + +#define EXPECT(condition) \ + do { \ + if (!(condition)) { \ + std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); \ + return 1; \ + } \ + } while (0) + +namespace { + +using namespace leonida; + +PFN_vkGetDeviceProcAddr g_get = nullptr; +PFN_vkAllocateMemory g_allocate = nullptr; +PFN_vkCreateDescriptorPool g_create_pool = nullptr; +VkPhysicalDeviceMemoryProperties g_memory{}; + +enum class Fail { none, device_local, all }; +Fail g_fail = Fail::none; +bool g_fail_pools = false; +unsigned g_allocations = 0, g_pools = 0, g_refused = 0; + +VKAPI_ATTR VkResult VKAPI_CALL allocate_memory(VkDevice device, const VkMemoryAllocateInfo* info, + const VkAllocationCallbacks* callbacks, VkDeviceMemory* memory) { + const bool local = + (g_memory.memoryTypes[info->memoryTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) != 0; + if (g_fail == Fail::all || (g_fail == Fail::device_local && local)) { + ++g_refused; + return VK_ERROR_OUT_OF_DEVICE_MEMORY; + } + ++g_allocations; + return g_allocate(device, info, callbacks, memory); +} + +VKAPI_ATTR VkResult VKAPI_CALL create_pool(VkDevice device, const VkDescriptorPoolCreateInfo* info, + const VkAllocationCallbacks* callbacks, VkDescriptorPool* pool) { + if (g_fail_pools) { + ++g_refused; + return VK_ERROR_OUT_OF_DEVICE_MEMORY; + } + ++g_pools; + return g_create_pool(device, info, callbacks, pool); +} + +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_proc(VkDevice device, const char* name) { + if (!std::strcmp(name, "vkAllocateMemory")) return reinterpret_cast(allocate_memory); + if (!std::strcmp(name, "vkCreateDescriptorPool")) return reinterpret_cast(create_pool); + return g_get(device, name); +} + +DescriptorKey numbered(std::uint32_t n) { + return {n, 0x9e3779b9u * n, n ^ 0x55555555u, n >> 3, 7, n * n, 0x80000000u, ~n}; +} + +} // namespace + +int main() { + vktest::Device device; + if (const auto status = device.initialize(); status != vktest::DeviceStatus::ready) + return status == vktest::DeviceStatus::unavailable ? 77 : 1; + if (!device.bindless) { + std::printf("unsupported: the device lacks the bindless set's descriptor-indexing features\n"); + return 77; + } + g_get = device.device_proc; + g_allocate = device.fn("vkAllocateMemory"); + g_create_pool = device.fn("vkCreateDescriptorPool"); + device.instance_fn("vkGetPhysicalDeviceMemoryProperties")(device.physical, + &g_memory); + bool host_type = false; // a HOST_VISIBLE | HOST_COHERENT type outside DEVICE_LOCAL memory + for (std::uint32_t i = 0; i < g_memory.memoryTypeCount; ++i) { + const auto flags = g_memory.memoryTypes[i].propertyFlags; + host_type |= (flags & (VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) == + (VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) && + !(flags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); + } + const auto create_view = device.fn("vkCreateImageView"); + const auto destroy_view = device.fn("vkDestroyImageView"); + const VkImage image = device.image(VK_FORMAT_R8G8B8A8_UNORM, 1, 1, 1, VK_IMAGE_USAGE_SAMPLED_BIT); + EXPECT(image); + + int failed = 0; + { + BindlessFeatures features; + features.update_after_bind = true; + features.partially_bound = device.partially_bound; + BindlessSet set(get_proc, device.device, g_memory, features); + EXPECT(set.ok()); + const DescriptorTable& table = set.table(); + const std::uint32_t initial_free = set.free_images(ImageDimension::dim_2d); + const std::size_t initial_slots = table.capacity(); + + // One submission per frame; run() waits for it, so `submitted` is also what has completed. busy: the + // flush is told one more submission may still read the current set. + std::uint64_t submitted = 0; + const auto frame = [&](bool busy = false) { + bool flushed = false; + const bool ran = device.run([&](VkCommandBuffer command_buffer) { + if (!set.fallbacks_ready()) set.record_fallback_init(command_buffer); + set.release_retired(submitted); + flushed = set.flush(command_buffer, submitted + (busy ? 1 : 0), [&] { return submitted; }); + return true; + }); + set.table_upload_result(ran); + ++submitted; + return ran && flushed; + }; + + struct Live { + DescriptorKey key; + std::uint32_t index; + VkImageView view; + }; + std::deque live; + std::uint32_t next_key = 1; + const auto make_view = [&] { + VkImageViewCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; + info.image = image; + info.viewType = VK_IMAGE_VIEW_TYPE_2D; + info.format = VK_FORMAT_R8G8B8A8_UNORM; + info.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + VkImageView view = VK_NULL_HANDLE; + return create_view(device.device, &info, nullptr, &view) == VK_SUCCESS ? view : VK_NULL_HANDLE; + }; + const auto add = [&]() -> bool { + const VkImageView view = make_view(); + if (!view) return false; + const std::uint32_t index = set.add_image(ImageDimension::dim_2d, view, VK_IMAGE_LAYOUT_GENERAL); + if (!index) return false; + const DescriptorKey key = numbered(next_key++); + set.insert_key(key, index); + live.push_back({key, index, view}); + return true; + }; + // What a texture's destruction does: its key leaves the table, its index the set, then its view goes. The + // last flush ran to completion, so nothing reads the view (the device defers this until then). + const auto remove = [&](const Live& entry) { + set.erase_key(entry.key); + set.remove_image(ImageDimension::dim_2d, entry.index); + destroy_view(device.device, entry.view, nullptr); + }; + + // 1. Churn. + constexpr unsigned frames = 400, per_frame = 8, max_live = 150; + std::size_t warm_slots = 0; + unsigned warm_allocations = 0, warm_pools = 0; + std::uint64_t warm_generations = 0; + for (unsigned f = 0; f < frames; ++f) { + for (unsigned i = 0; i < per_frame; ++i) EXPECT(add()); + while (live.size() > max_live) { + remove(live.front()); + live.pop_front(); + } + // A live texture gets another view (the read-only entry of a T# replaced by one with storage, say): its + // key is rebound, a change to an entry running work may probe, so the flush makes a new generation. + Live& rebound = live[f % live.size()]; + const VkImageView view = make_view(); + EXPECT(view); + const std::uint32_t index = set.add_image(ImageDimension::dim_2d, view, VK_IMAGE_LAYOUT_GENERAL); + EXPECT(index); + set.insert_key(rebound.key, index); + EXPECT(set.flush_replaces_table()); + set.remove_image(ImageDimension::dim_2d, rebound.index); + destroy_view(device.device, rebound.view, nullptr); + rebound.index = index; + rebound.view = view; + EXPECT(frame()); + EXPECT(!set.last_flush_degraded() && set.retired_count() <= 1); + if (f + 1 == frames / 2) { + warm_slots = table.capacity(); + warm_allocations = g_allocations; + warm_pools = g_pools; + warm_generations = set.generations_made(); + } + } + const unsigned churn_allocations = g_allocations - warm_allocations, churn_pools = g_pools - warm_pools; + std::printf("churn: %u frames, %u keys added, %zu live; table %zu -> %zu slots (%zu at half time), %llu " + "generations, %llu from spares; second half: %u allocations, %u descriptor pools\n", + frames, next_key - 1, live.size(), initial_slots, table.capacity(), warm_slots, + static_cast(set.generations_made()), + static_cast(set.spares_reused()), churn_allocations, churn_pools); + EXPECT(table.capacity() > initial_slots); // driven past its initial capacity + EXPECT(table.size() == live.size()); + // Bounded: 3200 keys went through a table that holds 150, and it stays where the warm-up left it, at most + // one more doubling (probe clustering can force one below half load). + EXPECT(table.capacity() <= 2 * warm_slots && table.capacity() <= 16 * max_live); + EXPECT(set.free_images(ImageDimension::dim_2d) == initial_free - live.size()); + EXPECT(set.generations_made() - warm_generations >= frames / 2); + EXPECT(set.spares_reused() >= frames / 2 - 4); + EXPECT(churn_allocations <= 2 && churn_pools <= 1); // a doubling at most allocates; the spares serve the rest + EXPECT(set.table_host_fallbacks() == 0 && set.degraded_flushes() == 0); + + // 2. Device-local memory is gone and the table must grow past every spare: host memory. + const std::size_t before_growth = table.capacity(); + std::vector extra; + for (std::uint32_t k = 0; table.capacity() == before_growth; ++k) { + extra.push_back(numbered(1000000 + k)); + set.insert_key(extra.back(), live.front().index); + } + g_fail = Fail::device_local; + const unsigned refused_before = g_refused; + EXPECT(frame()); + EXPECT(!set.last_flush_degraded() && set.table_buffer_bytes() >= table.size_bytes()); + if (host_type) { + EXPECT(g_refused > refused_before && set.table_host_fallbacks() == 1); + EXPECT(!set.table_in_device_local_memory()); + } else { + std::printf("no host memory outside device-local memory: the host fallback is not checked\n"); + } + EXPECT(frame()); // releases the old generation; it is too small to keep as a spare + EXPECT(set.spare_count() == 0 && set.retired_count() == 0); + + // 3. Nothing can be allocated, no spare fits, nothing runs: the table is rewritten in place. + g_fail = Fail::all; + g_fail_pools = true; + const std::size_t bytes = set.table_buffer_bytes(); + set.insert_key(live.back().key, live.front().index); // rebinds a live key: needs a new generation + EXPECT(set.flush_replaces_table()); + EXPECT(frame()); + EXPECT(set.in_place_rewrites() == 1 && !set.last_flush_degraded() && set.table_buffer_bytes() == bytes); + EXPECT(!set.flush_replaces_table()); + + // 4. Nothing can be allocated, work still runs, and the table must grow: the flush keeps the old table and + // still succeeds, with the descriptors of the new image written; the table catches up once memory is back. + EXPECT(add()); + const std::size_t old_slots = table.capacity(); + for (std::uint32_t k = 0; table.capacity() == old_slots; ++k) { + extra.push_back(numbered(2000000 + k)); + set.insert_key(extra.back(), live.back().index); + } + EXPECT(set.flush_replaces_table()); + EXPECT(frame(true)); + EXPECT(set.last_flush_degraded() && set.degraded_flushes() == 1); + EXPECT(set.last_failure() != nullptr && set.table_buffer_bytes() == bytes); + EXPECT(set.flush_replaces_table()); // still owed + // A texture goes while the GPU's table is stale: that table still maps its key to its index, so the index is + // not given out again (to answer that key with another image) until the table has caught up. + const Live gone = live.front(); + live.pop_front(); + const std::uint32_t free_before = set.free_images(ImageDimension::dim_2d); + remove(gone); + EXPECT(set.free_images(ImageDimension::dim_2d) == free_before); + EXPECT(frame(true)); // and again: never a failed flush + EXPECT(set.degraded_flushes() == 2 && set.free_images(ImageDimension::dim_2d) == free_before); + EXPECT(add() && live.back().index != gone.index); + g_fail = Fail::none; + g_fail_pools = false; + const std::uint64_t made = set.generations_made(); + EXPECT(frame(true)); + EXPECT(!set.last_flush_degraded() && set.generations_made() == made + 1); + EXPECT(set.free_images(ImageDimension::dim_2d) == free_before); // the held index is back; add() took one + EXPECT(set.table_buffer_bytes() >= table.size_bytes() && !set.flush_replaces_table()); + std::printf("pressure: %llu host fallbacks, %llu in-place rewrites, %llu degraded flushes (%s), table %zu " + "slots\n", + static_cast(set.table_host_fallbacks()), + static_cast(set.in_place_rewrites()), + static_cast(set.degraded_flushes()), + set.last_failure() ? set.last_failure() : "-", table.capacity()); + + for (const Live& entry : live) remove(entry); + live.clear(); + EXPECT(frame()); + EXPECT(set.free_images(ImageDimension::dim_2d) == initial_free); + set.release_retired(); + } + { + // 5. A first flush under full memory (review of #64): no table ever reached the GPU, so there is nothing to + // keep. Degrading would leave shaders reading uninitialised buffers (word 0 is the probe mask): the flush + // refuses instead, and succeeds once memory is back. + BindlessFeatures features; + features.update_after_bind = true; + features.partially_bound = device.partially_bound; + BindlessSet set(get_proc, device.device, g_memory, features); + EXPECT(set.ok()); + const std::size_t initial_slots = set.table().capacity(); + for (std::uint32_t k = 0; set.table().capacity() == initial_slots; ++k) + set.insert_key(numbered(3000000 + k), 0); + g_fail = Fail::all; + g_fail_pools = true; + bool flushed = true; + device.run([&](VkCommandBuffer command_buffer) { + if (!set.fallbacks_ready()) set.record_fallback_init(command_buffer); + flushed = set.flush(command_buffer, 1, [] { return std::uint64_t(0); }); + return true; + }); + set.table_upload_result(true); + EXPECT(!flushed && set.degraded_flushes() == 0); + g_fail = Fail::none; + g_fail_pools = false; + device.run([&](VkCommandBuffer command_buffer) { + flushed = set.flush(command_buffer, 1, [] { return std::uint64_t(0); }); + return true; + }); + set.table_upload_result(true); + EXPECT(flushed && !set.last_flush_degraded() && set.table_buffer_bytes() >= set.table().size_bytes()); + set.release_retired(); + std::printf("first flush under full memory: refused, then uploaded once memory is back\n"); + } + if (device.validation_errors()) { + std::printf("%u validation errors\n", device.validation_errors()); + failed = 1; + } + if (!failed) std::printf("vk_bindless_grow: ok\n"); + return failed; +} diff --git a/runtime/test/vk_host_texture_order_test.cpp b/runtime/test/vk_host_texture_order_test.cpp new file mode 100644 index 0000000000..34120f00e5 --- /dev/null +++ b/runtime/test/vk_host_texture_order_test.cpp @@ -0,0 +1,45 @@ +// Title texture uploads must keep a queue submission from racing the host copy. +#include "../src/vulkan_backend.h" + +#include +#include + +namespace { +unsigned waits = 0; +VkResult wait_result = VK_SUCCESS; +VkResult VKAPI_CALL idle(VkDevice) { ++waits; return wait_result; } +PFN_vkVoidFunction VKAPI_CALL no_proc(VkDevice, const char*) { return nullptr; } +} + +int main() { + leonida::VulkanContext ctx(no_proc, VK_NULL_HANDLE, false); + ctx.vk.vkDeviceWaitIdle = idle; + leonida::ResourceBinding binding{}; + binding.image = reinterpret_cast(1); + binding.mip_levels = 1; + ctx.add_resource(1, binding, VK_IMAGE_LAYOUT_GENERAL); + ctx.add_resource(2, binding, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); + unsigned copies = 0; + const auto copy = [&] { + ++copies; + bool raced = false; + std::thread contender([&] { + if (ctx.submit_mutex().try_lock()) { + raced = true; + ctx.submit_mutex().unlock(); + } + }); + contender.join(); + return !raced; + }; + ctx.note_image_work_locked(); + if (ctx.write_host_texture(2, 0, copy) != VK_NOT_READY || copies || waits) return 1; + if (ctx.write_host_texture(1, 0, copy) != VK_SUCCESS || copies != 1 || waits != 1) return 1; + if (ctx.write_host_texture(1, 0, copy) != VK_SUCCESS || copies != 2 || waits != 1) return 1; + ctx.note_image_work_locked(); + wait_result = VK_ERROR_DEVICE_LOST; + if (ctx.write_host_texture(1, 0, copy) != VK_ERROR_DEVICE_LOST || copies != 2 || waits != 2) return 1; + const auto stats = ctx.host_texture_stats(); + if (stats.copies != 2 || stats.waits != 2) return 1; + std::puts("ordered texture upload: layout, submit exclusion, wait reuse, wait failure passed"); +} diff --git a/runtime/test/vk_pipeline_check.cpp b/runtime/test/vk_pipeline_check.cpp index a237f60ffe..a247ba1707 100644 --- a/runtime/test/vk_pipeline_check.cpp +++ b/runtime/test/vk_pipeline_check.cpp @@ -49,7 +49,7 @@ // pipelines stage's retry. #include "vulkan_loader.h" #include "vk_device_pick.h" -#include "pipeline_cache_file.h" +#include "../src/pipeline_cache_file.h" #include "pipeline_cache_snapshot.h" #include "large_module_gate.h" #include "pipeline_summary.h" @@ -1115,7 +1115,7 @@ int main(int argc, char** argv) { auto has = [&](const char* e) { for (auto& x : exts) if (!std::strcmp(x.extensionName, e)) return true; return false; }; std::vector enable; - // Query what the GPU supports for core 1.2/1.3 and any optional extensions requested by `work`. + // Query the core and optional device features used by the checker. VkPhysicalDeviceMeshShaderFeaturesEXT mesh{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT}; VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR bary{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_KHR}; VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT lock{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_INTERLOCK_FEATURES_EXT}; diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h index 0e5befcdc4..f72a927855 100644 --- a/runtime/test/vk_test_device.h +++ b/runtime/test/vk_test_device.h @@ -108,6 +108,9 @@ class Device { bool host_image_copy = false; // VK_EXT_host_image_copy and hostImageCopy enabled bool request_depth_range_unrestricted = false; bool depth_range_unrestricted = false; // VK_EXT_depth_range_unrestricted enabled + // VK_KHR_maintenance5 enabled, where VK_FORMAT_A8_UNORM_KHR can be sampled and blended as a colour attachment, as + // gta6rt enables it (VulkanDeviceInfo::a8_render_target). + bool a8_render_target = false; // create(true) only: VK_KHR (else EXT) swapchain_maintenance1 and its feature enabled, with the surface half on the // instance, so a vsync swapchain can switch to IMMEDIATE or FIFO_RELAXED per present. bool swapchain_maintenance1 = false; @@ -506,6 +509,29 @@ class Device { host_copy.pNext = *v13_.next(); // after the conditional rendering features, if any *v13_.next() = &host_copy; } +#ifdef VK_KHR_MAINTENANCE_5_EXTENSION_NAME + VkPhysicalDeviceMaintenance5FeaturesKHR maintenance5{ + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_5_FEATURES_KHR}; + if (std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { + return std::strcmp(e.extensionName, VK_KHR_MAINTENANCE_5_EXTENSION_NAME) == 0; + })) { + VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &maintenance5}; + instance_fn("vkGetPhysicalDeviceFeatures2")(physical, &query); + VkFormatProperties a8{}; + instance_fn("vkGetPhysicalDeviceFormatProperties")( + physical, VK_FORMAT_A8_UNORM_KHR, &a8); + const VkFormatFeatureFlags needed = VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT | + VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT | + VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT | + VK_FORMAT_FEATURE_TRANSFER_SRC_BIT | VK_FORMAT_FEATURE_TRANSFER_DST_BIT; + a8_render_target = + maintenance5.maintenance5 == VK_TRUE && (a8.optimalTilingFeatures & needed) == needed; + } + if (a8_render_target) { + maintenance5.pNext = *v13_.next(); + *v13_.next() = &maintenance5; + } +#endif #ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME // VK_KHR_shader_fma where the device has it: translated shaders built with --fma khr use OpFmaKHR. @@ -591,6 +617,9 @@ class Device { if (conditional_rendering) device_extensions.push_back(conditional_extension); if (host_image_copy) device_extensions.push_back(host_image_copy_name); if (host_pointer_alignment) device_extensions.push_back(VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME); +#ifdef VK_KHR_MAINTENANCE_5_EXTENSION_NAME + if (a8_render_target) device_extensions.push_back(VK_KHR_MAINTENANCE_5_EXTENSION_NAME); +#endif const char* swapchain = "VK_KHR_swapchain"; if (presentation) device_extensions.push_back(swapchain); #if defined(VK_KHR_swapchain_maintenance1) diff --git a/runtime/test/vulkan_device_fault_test.cpp b/runtime/test/vulkan_device_fault_test.cpp new file mode 100644 index 0000000000..d6bfe13d74 --- /dev/null +++ b/runtime/test/vulkan_device_fault_test.cpp @@ -0,0 +1,153 @@ +#include "../src/vulkan_device_fault.h" + +using namespace leonida; + +namespace { +int feature_queries = 0; +int fault_queries = 0; +int checkpoint_queries = 0; +bool supported = true; +bool fault_data_written = false; +void* last_marker = nullptr; + +VKAPI_ATTR void VKAPI_CALL query_features(VkPhysicalDevice, VkPhysicalDeviceFeatures2* features) { + ++feature_queries; + for (auto* next = static_cast(features->pNext); next; next = next->pNext) { + if (next->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FAULT_FEATURES_EXT) { + auto* fault = reinterpret_cast(next); + fault->deviceFault = supported; + fault->deviceFaultVendorBinary = supported; + } else if (next->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DIAGNOSTICS_CONFIG_FEATURES_NV) { + reinterpret_cast(next)->diagnosticsConfig = supported; + } + } +} + +VKAPI_ATTR VkResult VKAPI_CALL get_fault(VkDevice, VkDeviceFaultCountsEXT* counts, VkDeviceFaultInfoEXT* info) { + ++fault_queries; + if (!info) { + counts->addressInfoCount = 1; + counts->vendorInfoCount = 1; + counts->vendorBinarySize = 8; + return VK_SUCCESS; + } + if (counts->addressInfoCount != 1 || counts->vendorInfoCount != 1 || counts->vendorBinarySize != 8 || + !info->pAddressInfos || !info->pVendorInfos || !info->pVendorBinaryData) + return VK_ERROR_UNKNOWN; + info->pAddressInfos[0] = {VK_DEVICE_FAULT_ADDRESS_TYPE_READ_INVALID_EXT, 0x1234, 4}; + info->pVendorInfos[0].vendorFaultCode = 1; + fault_data_written = true; + return VK_SUCCESS; +} + +VKAPI_ATTR void VKAPI_CALL set_checkpoint(VkCommandBuffer, const void* marker) { + last_marker = const_cast(marker); +} + +VKAPI_ATTR void VKAPI_CALL get_checkpoints(VkQueue, std::uint32_t* count, VkCheckpointDataNV* checkpoints) { + ++checkpoint_queries; + *count = 1; + if (checkpoints) { + checkpoints[0].stage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; + checkpoints[0].pCheckpointMarker = last_marker; + } +} + +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_proc(VkDevice, const char* name) { + if (std::strcmp(name, "vkGetDeviceFaultInfoEXT") == 0) return reinterpret_cast(get_fault); + if (std::strcmp(name, "vkCmdSetCheckpointNV") == 0) return reinterpret_cast(set_checkpoint); + if (std::strcmp(name, "vkGetQueueCheckpointDataNV") == 0) + return reinterpret_cast(get_checkpoints); + return nullptr; +} +} // namespace + +int main() { + const VkExtensionProperties advertised[] = {{VK_EXT_DEVICE_FAULT_EXTENSION_NAME, 2}, + {VK_NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME, 2}, + {VK_NV_DEVICE_DIAGNOSTICS_CONFIG_EXTENSION_NAME, 2}}; + const VkPhysicalDeviceVulkan12Features existing{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; + VkDeviceCreateInfo device{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, &existing}; + DeviceFaultFeatures features; + std::vector extensions; + const auto absent = features.enable(VK_NULL_HANDLE, query_features, {}, extensions, device); + if (absent.fault || absent.checkpoints || absent.diagnostics_config || feature_queries || !extensions.empty() || + device.pNext != &existing) + return 1; + supported = false; + const auto disabled = features.enable(VK_NULL_HANDLE, query_features, advertised, extensions, device); + if (disabled.fault || !disabled.checkpoints || disabled.diagnostics_config || extensions.size() != 1 || + device.pNext != &existing) + return 2; + extensions.clear(); + supported = true; + const auto enabled = features.enable(VK_NULL_HANDLE, query_features, advertised, extensions, device); + const VkDeviceDiagnosticsConfigFlagsNV flags = VK_DEVICE_DIAGNOSTICS_CONFIG_ENABLE_SHADER_DEBUG_INFO_BIT_NV | + VK_DEVICE_DIAGNOSTICS_CONFIG_ENABLE_RESOURCE_TRACKING_BIT_NV | + VK_DEVICE_DIAGNOSTICS_CONFIG_ENABLE_AUTOMATIC_CHECKPOINTS_BIT_NV; + if (!enabled.fault || !enabled.checkpoints || !enabled.diagnostics_config || extensions.size() != 3 || + features.fault.deviceFaultVendorBinary != VK_TRUE || device.pNext != &features.config || + features.config.flags != flags || features.config.pNext != &features.diagnostics || + features.diagnostics.pNext != &features.fault || features.fault.pNext != &existing) + return 3; + + if constexpr (sizeof(void*) >= 8) { + const auto marker = CheckpointMarker::decode(CheckpointMarker::encode( + UINT32_MAX, CheckpointMarker::max_list, CheckpointMarker::max_command, CheckpointKind::resolve)); + if (marker.submission != UINT32_MAX || marker.list != CheckpointMarker::max_list || + marker.command != CheckpointMarker::max_command || marker.kind != CheckpointKind::resolve || + CheckpointMarker::encode(1, 0, CheckpointMarker::max_command + 1, CheckpointKind::clear) || + CheckpointMarker::decode(0).submission) + return 4; + } + + DeviceFaultDiagnostics diagnostics(get_proc, VK_NULL_HANDLE, enabled); + const auto queue = reinterpret_cast(std::uintptr_t{1}); + diagnostics.add_queue(queue); + diagnostics.add_queue(queue); + auto submission = diagnostics.begin_submission(diagnostics.next_execute_call(), queue, "direct", 2); + diagnostics.pipeline_names[4] = {"test_shader"}; + if (const auto set = diagnostics.checkpoint_command()) { + const CheckpointRecorder recorder{set, submission, diagnostics.pipeline_names, 1}; + recorder.record(VK_NULL_HANDLE, 7, CheckpointKind::draw, VK_NULL_HANDLE, 4); + recorder.record(VK_NULL_HANDLE, 9, CheckpointKind::copy); + const auto marker = CheckpointMarker::decode(reinterpret_cast(last_marker)); + if (marker.submission != submission.sequence || marker.list != 1 || marker.command != 9 || + marker.kind != CheckpointKind::copy || submission.lists[1].shaders.size() != 1) + return 5; + } + // The CPU history must survive missing driver checkpoints and a list longer than the ring. + const CheckpointRecorder cpu{nullptr, submission, diagnostics.pipeline_names, 1}; + std::array roots{}; + roots[5] = 42; + for (unsigned i = 0; i < 70; ++i) + cpu.dispatch(VK_NULL_HANDLE, i, VK_NULL_HANDLE, 4, roots, {i, 2, 3}); + cpu.dispatch(VK_NULL_HANDLE, 70, VK_NULL_HANDLE, 4, roots, {}, true, 17, 32, 19, 64, 4, 12); + const auto& oldest = submission.dispatches[submission.dispatch_count % submission.dispatch_limit]; + const auto& latest = submission.dispatches[(submission.dispatch_count - 1) % submission.dispatch_limit]; + if (submission.dispatches.size() != 64 || oldest.command != 7 || oldest.groups[0] != 7 || + oldest.roots[5] != 42 || std::strcmp(oldest.shader, "test_shader") || + latest.list != 1 || !latest.indirect || latest.argument_buffer != 17 || latest.count_offset != 64 || + latest.stride != 12 || latest.queue != queue) return 7; + diagnostics.publish(std::move(submission)); + // A stopped timeline emits the CPU history once. Idle time and new completions reset the clock. + using Watch = SubmissionProgressWatch; + using namespace std::chrono_literals; + Watch watch; + const Watch::Clock::time_point start{}; + if (watch.sample(Watch::State::idle, 3, start) || + watch.sample(Watch::State::pending, 3, start + 30s) || + watch.sample(Watch::State::pending, 3, start + 44s) || + !watch.sample(Watch::State::pending, 3, start + 45s) || + watch.sample(Watch::State::pending, 3, start + 70s) || + watch.sample(Watch::State::pending, 4, start + 71s) || + watch.sample(Watch::State::submit_lock_busy, 4, start + 86s) || + !watch.sample(Watch::State::submit_lock_busy, 4, start + 101s)) return 8; + diagnostics.report_stall("synthetic pending work", 5, 4); + if (fault_queries || checkpoint_queries) return 9; + if (DeviceFaultDiagnostics::observe(&diagnostics, VK_SUCCESS, "test success") != VK_SUCCESS || fault_queries || + DeviceFaultDiagnostics::observe(&diagnostics, VK_ERROR_DEVICE_LOST, "test loss") != VK_ERROR_DEVICE_LOST || + DeviceFaultDiagnostics::observe(&diagnostics, VK_ERROR_DEVICE_LOST, "test repeat") != VK_ERROR_DEVICE_LOST || + fault_queries != 2 || !fault_data_written || checkpoint_queries != 2) + return 6; +} diff --git a/runtime/test/vulkan_title_image_pool_test.cpp b/runtime/test/vulkan_title_image_pool_test.cpp new file mode 100644 index 0000000000..9666e70c02 --- /dev/null +++ b/runtime/test/vulkan_title_image_pool_test.cpp @@ -0,0 +1,71 @@ +// Small optimal images share memory until their deferred image destruction has run. +#define VK_NO_PROTOTYPES +#include "../src/vulkan_title_image_pool.h" + +#include + +namespace { +unsigned allocated, freed, destroyed, next_type; +bool fail_alloc, fail_bind; +VkDeviceSize last_offset; +VKAPI_ATTR VkResult VKAPI_CALL bind_image(VkDevice, VkImage, VkDeviceMemory, VkDeviceSize offset) { + last_offset = offset; + return fail_bind ? VK_ERROR_OUT_OF_DEVICE_MEMORY : VK_SUCCESS; +} +VKAPI_ATTR void VKAPI_CALL destroy_image(VkDevice, VkImage, const VkAllocationCallbacks*) { ++destroyed; } +VKAPI_ATTR void VKAPI_CALL free_memory(VkDevice, VkDeviceMemory, const VkAllocationCallbacks*) { ++freed; } +#define CHECK(cond) do { if (!(cond)) { std::fprintf(stderr, "failed at line %d: %s\n", __LINE__, #cond); return 1; } } while (false) +} + +int main() { + leonida::TitleImagePool pool; + VkMemoryRequirements req{800, 2048, 1}; + unsigned next_image = 0; + const auto make = [&] { + const auto image = (VkImage)(std::uintptr_t(++next_image)); + return pool.bind(VK_NULL_HANDLE, image, req, bind_image, destroy_image, free_memory, + [](VkDeviceSize, std::uint32_t& type) { + type = next_type; + return fail_alloc ? VkDeviceMemory{} : (VkDeviceMemory)(std::uintptr_t(++allocated)); + }); + }; + auto a = make(); + CHECK(a && last_offset == 0); + auto b = make(); + CHECK(b && last_offset == 2048 && allocated == 1 && b->page == a->page); + // Simulate removing the first image from replay, then draining its deferred deletion later. + auto retired = std::move(a); + auto c = make(); + CHECK(c && last_offset == 4096 && destroyed == 0); + retired.reset(); + CHECK(destroyed == 1 && freed == 0); + fail_bind = true; + CHECK(!make() && last_offset == 0 && destroyed == 1); + fail_bind = false; + a = make(); + CHECK(a && last_offset == 0 && allocated == 1); + req.memoryTypeBits = 2; + next_type = 1; + auto other = make(); + CHECK(other && other->page != a->page && allocated == 2); + b.reset(); c.reset(); a.reset(); other.reset(); + CHECK(freed == 2 && destroyed == 5); + + req.size = 2u << 20; + std::vector> live; + for (int i = 0; i < 5; ++i) live.push_back(make()); + CHECK(live.front() && live.back() && allocated == 4 && last_offset == 0); + CHECK(live[0]->page == live[3]->page && live[4]->page != live[3]->page); + live.clear(); + CHECK(freed == 4 && destroyed == 10); + fail_alloc = true; + CHECK(!make() && allocated == 4 && freed == 4); + fail_alloc = false; + req.size++; + CHECK(!make() && allocated == 4); + req = {701440, 512, 2}; + a = make(); b = make(); + CHECK(a && b && a->page == b->page && last_offset % req.alignment == 0); + CHECK(last_offset >= req.size && last_offset <= req.size + req.size / 8); + std::puts("title image pool alignment, type separation, retirement, reuse and fallback OK"); +} diff --git a/runtime/test/xapu_test.cpp b/runtime/test/xapu_test.cpp new file mode 100644 index 0000000000..c9e538ddf3 --- /dev/null +++ b/runtime/test/xapu_test.cpp @@ -0,0 +1,102 @@ +// Checks the registered xapu.dll shim against the measured call shapes +// (docs/audio_hal_exe_calls.md, PR #6981). +// +// Every export is resolved through rt::shims::find so the test exercises +// the same shim table the runtime installs. The measured call shapes: +// XApuConnect(out24*, out16*, handle**), XApuEnqueueCommand(handle, cmd*, 0), +// XApuGetResultCount(handle, 0), XApuDequeueResult(handle, out*), +// XApuDisconnect(handle). +#include + +#include +#include +#include + +#include "shims.h" + +namespace { + +using XApuConnectFn = HRESULT(__stdcall*)(void*, void*, void**); +using XApuDisconnectFn = HRESULT(__stdcall*)(void*); +using XApuEnqueueCommandFn = HRESULT(__stdcall*)(void*, const uint32_t*, uint64_t); +using XApuGetResultCountFn = uint32_t(__stdcall*)(void*, uint64_t); +using XApuDequeueResultFn = HRESULT(__stdcall*)(void*, void*); + +int g_checks = 0; +int g_failures = 0; + +void check(bool condition, const char* what) { + ++g_checks; + std::printf("%s %s\n", condition ? "PASS" : "FAIL", what); + if (!condition) ++g_failures; +} + +} // namespace + +int main() { + std::printf("xapu_test: registered xapu.dll shim\n"); + + const auto connect = reinterpret_cast(rt::shims::find("xapu.dll", "XApuConnect")); + const auto disconnect = reinterpret_cast(rt::shims::find("xapu.dll", "XApuDisconnect")); + const auto enqueue = reinterpret_cast(rt::shims::find("xapu.dll", "XApuEnqueueCommand")); + const auto count = reinterpret_cast(rt::shims::find("xapu.dll", "XApuGetResultCount")); + const auto dequeue = reinterpret_cast(rt::shims::find("xapu.dll", "XApuDequeueResult")); + + check(connect != nullptr, "XApuConnect is registered"); + check(disconnect != nullptr, "XApuDisconnect is registered"); + check(enqueue != nullptr, "XApuEnqueueCommand is registered"); + check(count != nullptr, "XApuGetResultCount is registered"); + check(dequeue != nullptr, "XApuDequeueResult is registered"); + check(rt::shims::owns_dll("xapu.dll"), "the registry owns xapu.dll"); + if (!connect || !disconnect || !enqueue || !count || !dequeue) return 1; + + // XApuConnect: measured (out24*, out16*, handle**) with 3 args. + // Returns a handle and fills out16[0..1] with {buffer, size}. + // out24 is zeroed. + uint8_t out24[24]; + uint64_t out16[2] = {}; + std::memset(out24, 0xcc, sizeof(out24)); + void* handle = nullptr; + check(SUCCEEDED(connect(out24, out16, &handle)) && handle != nullptr, + "XApuConnect succeeds with a handle"); + check(out24[0] == 0 && out24[23] == 0, + "XApuConnect zeroes the 24-byte output"); + check(connect(out24, out16, nullptr) == E_INVALIDARG, + "XApuConnect(nullptr handle) returns E_INVALIDARG"); + + if (!handle) return 1; + auto* base = reinterpret_cast(out16[0]); + check(base != nullptr && out16[1] >= 0x14000 + 128 * 0x1E00, + "XApuConnect returns the shared buffer and its size"); + if (base) { + const size_t last = 0x14000 + 127 * 0x1E00 + 0x1E00 - 1; + check(base[0] == 0 && base[last] == 0, + "the shared buffer is zeroed"); + base[127 * 0x280] = 1; + check(base[127 * 0x280] == 1, + "the shared buffer is writable at slot 127's input"); + } + + // XApuEnqueueCommand(handle, cmd*, 0): 3 args, the third is flags=0. + for (uint32_t type = 1; type <= 3; ++type) { + uint32_t command[16] = {type, 5}; + check(enqueue(handle, command, 0) == S_OK, + "XApuEnqueueCommand accepts a command"); + } + + // XApuGetResultCount(handle, 0): 2 args, the second is flags=0. + check(count(handle, 0) == 0, + "XApuGetResultCount returns 0 (no results)"); + + // XApuDequeueResult(handle, out*): 2 args, returns a negative HRESULT. + uint8_t result[0x50] = {}; + check(FAILED(dequeue(handle, result)), + "XApuDequeueResult on the empty queue returns a negative HRESULT"); + + // XApuDisconnect(handle): 1 arg. + check(disconnect(handle) == S_OK, + "XApuDisconnect succeeds"); + + std::printf("%d checks, %d failures\n", g_checks, g_failures); + return g_failures ? 1 : 0; +} \ No newline at end of file diff --git a/runtime/test/xbox_bvh_builder_test.cpp b/runtime/test/xbox_bvh_builder_test.cpp new file mode 100644 index 0000000000..3deb816b46 --- /dev/null +++ b/runtime/test/xbox_bvh_builder_test.cpp @@ -0,0 +1,430 @@ +// The XboxBvhBuilder.dll shim (shims/xbox_bvh_builder.cpp) on the standalone Vulkan device, called the way the +// title's imports bind: rt::shims::find("xboxbvhbuilder.dll", ), `this` first. A BLAS and a TLAS are +// built through BuildRaytracingAccelerationStructureBatched2X, the BLAS is compacted through +// CopyRaytracingAccelerationStructure, and the three are written to as .bin + .json for +// `python -I tools/xdxr_bvh.py check-build ` (ctest: xbox_bvh_builder + xbox_bvh_builder_check), which +// checks the records and traces rays against brute force. Also checked: the shim's prebuild sizes are the layer's, +// an element asking for offline statistics is skipped and leaves its destination untouched, a non-empty XDXR stream +// is accepted, rehydration answers E_NOTIMPL, and builders are released. +// +// xbox_bvh_builder_test the shim +// xbox_bvh_builder_test --console run with LEONIDA_BVH_BUILDER=console: nothing is registered +// +// Exit 77 without a Vulkan device. No game files. +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" +#include "../shims/shims.h" +#include "../src/xdxr_descs.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace rt::shims { +size_t xbox_bvh_builder_live_count(); +} + +namespace { + +namespace xdxr = leonida::xdxr; + +int g_checks = 0; +int g_failures = 0; + +void check(bool condition, const char* what) { + ++g_checks; + std::printf("%s %s\n", condition ? "PASS" : "FAIL", what); + if (!condition) ++g_failures; +} + +template struct Ref { + T* p = nullptr; + ~Ref() { if (p) p->Release(); } + T* operator->() const { return p; } + T** put() { return &p; } +}; + +int fail(const char* what, HRESULT hr = S_OK) { + std::fprintf(stderr, "FAIL: %s (hr 0x%08lx)\n", what, static_cast(hr)); + return 1; +} + +HRESULT buffer(ID3D12Device* device, D3D12_HEAP_TYPE heap, UINT64 size, D3D12_RESOURCE_STATES state, + D3D12_RESOURCE_FLAGS flags, ID3D12Resource** out) { + D3D12_HEAP_PROPERTIES props{}; + props.Type = heap; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = size ? size : 1; + desc.Height = 1; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + desc.Flags = flags; + return device->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, IID_PPV_ARGS(out)); +} + +std::string num(double x) { + char s[64]; + std::snprintf(s, sizeof s, "%.9g", x); + return s; +} + +bool write_file(const std::string& path, const void* data, std::size_t bytes) { + std::ofstream f(path, std::ios::binary); + f.write(static_cast(data), std::streamsize(bytes)); + return bool(f); +} + +// The exports, as the executable imports them. +constexpr const char kDll[] = "xboxbvhbuilder.dll"; +constexpr const char kConstruct[] = "??0XboxBvhBuilder@@QEAA@PEAUID3D12Device11@@_N@Z"; +constexpr const char kDestruct[] = "??1XboxBvhBuilder@@QEAA@XZ"; +constexpr const char kMorton[] = "?Set64BitMortonCodes@XboxBvhBuilder@@QEAAX_N@Z"; +constexpr const char kPrebuild[] = + "?GetRaytracingAccelerationStructurePrebuildInfo@XboxBvhBuilder@@QEAAXPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_" + "STRUCTURE_INPUTS@@PEBUD3D12XBOX_XDXR_STREAM_DESC@@PEAUD3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO@@@Z"; +constexpr const char kBatched[] = + "?BuildRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList6@@IPEBUD3D12" + "XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2@@@Z"; +constexpr const char kCopy[] = + "?CopyRaytracingAccelerationStructure@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@_K1W4D3D12_" + "RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE@@@Z"; +constexpr const char kRehydrate[] = + "?RehydrateRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAJPEAUID3D12GraphicsCommandList8@@IPEBU" + "D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@PEB_K@Z"; + +using Construct = void*(*)(void*, void*, bool); +using Destruct = void (*)(void*); +using Morton = void (*)(void*, bool); +using Prebuild = void (*)(void*, const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS*, const xdxr::StreamDesc*, + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO*); +using Batched = void (*)(void*, void*, UINT, const xdxr::BatchedDesc2*); +using Copy = void (*)(void*, void*, UINT64, UINT64, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE); +using Rehydrate = HRESULT (*)(void*, void*, UINT, const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC*, + const UINT64*); + +template F shim(const char* name) { return reinterpret_cast(rt::shims::find(kDll, name)); } + +} // namespace + +int main(int argc, char** argv) { + if (argc < 2) { + std::fprintf(stderr, "usage: xbox_bvh_builder_test | --console\n"); + return 2; + } + if (std::strcmp(argv[1], "--console") == 0) { + // LEONIDA_BVH_BUILDER=console: the imports must bind to the bundled DLL, so the shim registers nothing. + check(shim(kConstruct) == nullptr && shim(kBatched) == nullptr && + !rt::shims::owns_dll(kDll), + "LEONIDA_BVH_BUILDER=console registers none of the exports"); + std::printf("xbox_bvh_builder_test: %d of %d checks failed\n", g_failures, g_checks); + return g_failures ? 1 : 0; + } + const std::string dir = argv[1]; + std::error_code ec; + std::filesystem::create_directories(dir, ec); + for (const auto& entry : std::filesystem::directory_iterator(dir, ec)) { + const auto ext = entry.path().extension(); + if (ext == ".bin" || ext == ".json") std::filesystem::remove(entry.path(), ec); + } + + // ---- the seven exports are registered ---- + const auto construct = shim(kConstruct); + const auto destruct = shim(kDestruct); + const auto morton = shim(kMorton); + const auto prebuild = shim(kPrebuild); + const auto batched = shim(kBatched); + const auto copy = shim(kCopy); + const auto rehydrate = shim(kRehydrate); + check(construct && destruct && morton && prebuild && batched && copy && rehydrate && rt::shims::owns_dll(kDll), + "the seven exports the executable imports are served by the shim"); + if (!(construct && destruct && morton && prebuild && batched && copy && rehydrate)) return 1; + + char rt_as[8] = {}; + std::size_t rt_as_length = 0; + if (getenv_s(&rt_as_length, rt_as, "LEONIDA_RT_AS") == 0 && rt_as_length > 1 && std::strcmp(rt_as, "khr") == 0) { + std::puts("SKIP: LEONIDA_RT_AS=khr"); + return 77; + } + Ref device; + if (FAILED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(device.put())))) { + std::puts("SKIP: no Vulkan D3D12 device"); + return 77; + } + + // ---- the builder object: the title's storage, larger than anything the shim could write ---- + alignas(16) unsigned char builder[256]; + std::memset(builder, 0xab, sizeof builder); + check(construct(builder, device.p, true) == builder, "the constructor returns `this`"); + bool untouched = true; + for (unsigned char b : builder) untouched = untouched && b == 0xab; + check(untouched && rt::shims::xbox_bvh_builder_live_count() == 1, + "nothing is written into the title's builder object; its state is kept aside"); + morton(builder, true); + + // ---- geometry: a triangle soup ---- + std::mt19937 rng(23); + std::uniform_real_distribution spread(-4.0f, 4.0f), jitter(-0.6f, 0.6f); + const UINT tris = 400; + std::vector soup; + for (UINT t = 0; t < tris; ++t) { + const float c[3] = {spread(rng), spread(rng), spread(rng)}; + for (int k = 0; k < 9; ++k) soup.push_back(c[k % 3] + jitter(rng)); + } + const UINT64 soup_bytes = soup.size() * 4; + Ref upload; + HRESULT hr = buffer(device.p, D3D12_HEAP_TYPE_UPLOAD, 256 + soup_bytes + 3 * 64, D3D12_RESOURCE_STATE_GENERIC_READ, + D3D12_RESOURCE_FLAG_NONE, upload.put()); + if (FAILED(hr)) return fail("upload buffer", hr); + char* mapped = nullptr; + if (FAILED(upload->Map(0, nullptr, reinterpret_cast(&mapped)))) return fail("Map upload"); + std::memcpy(mapped, soup.data(), std::size_t(soup_bytes)); + const UINT64 soup_va = upload->GetGPUVirtualAddress(); + + D3D12_RAYTRACING_GEOMETRY_DESC geometry{}; + geometry.Type = D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES; + geometry.Flags = D3D12_RAYTRACING_GEOMETRY_FLAG_OPAQUE; + geometry.Triangles.VertexFormat = DXGI_FORMAT_R32G32B32_FLOAT; + geometry.Triangles.VertexCount = tris * 3; + geometry.Triangles.VertexBuffer = {soup_va, 12}; + D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS blas_inputs{}; + blas_inputs.Type = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL; + blas_inputs.Flags = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PREFER_FAST_TRACE | + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_ALLOW_COMPACTION; + blas_inputs.DescsLayout = D3D12_ELEMENTS_LAYOUT_ARRAY; + blas_inputs.NumDescs = 1; + blas_inputs.pGeometryDescs = &geometry; + + // ---- GetRaytracingAccelerationStructurePrebuildInfo: the layer's sizes, with or without a stream ---- + const xdxr::StreamRecord2 record{2, 0, -1.0f, 0.0f}; // a type-2 record with its defaults + const xdxr::StreamDesc stream{sizeof record, &record}; + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO blas_info{}, layer_info{}; + prebuild(builder, &blas_inputs, &stream, &blas_info); + device->GetRaytracingAccelerationStructurePrebuildInfo(&blas_inputs, &layer_info); + check(blas_info.ResultDataMaxSizeInBytes == layer_info.ResultDataMaxSizeInBytes && + blas_info.ScratchDataSizeInBytes == layer_info.ScratchDataSizeInBytes, + "the shim's prebuild sizes are the layer's own"); + if (!blas_info.ResultDataMaxSizeInBytes) { + std::puts("SKIP: the device does not build XDXR acceleration structures (no bufferDeviceAddress)"); + return 77; + } + // The title's device is a d3d12_xs device proxy (D3D12XboxCreateDevice): a builder constructed on one reaches the + // real device behind it. + { + Ref proxy; + alignas(16) unsigned char proxied[64]; + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO through_proxy{}; + device->AddRef(); // create_device_proxy takes one reference to the real device on success + const bool wrapped = SUCCEEDED(rt::d3d12_xs::create_device_proxy(device.p, IID_PPV_ARGS(proxy.put()))); + if (!wrapped) device->Release(); + const bool made = wrapped && rt::d3d12_xs::device_proxy_real_device(proxy.p) != nullptr; + if (made) { + construct(proxied, proxy.p, true); + prebuild(proxied, &blas_inputs, nullptr, &through_proxy); + destruct(proxied); + } + check(made && through_proxy.ResultDataMaxSizeInBytes == layer_info.ResultDataMaxSizeInBytes && + through_proxy.ScratchDataSizeInBytes == layer_info.ScratchDataSizeInBytes, + "a builder constructed on a d3d12_xs device proxy uses the real device behind it"); + } + D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS tlas_inputs{}; + tlas_inputs.Type = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL; + tlas_inputs.DescsLayout = D3D12_ELEMENTS_LAYOUT_ARRAY; + tlas_inputs.NumDescs = 2; + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO tlas_info{}; + prebuild(builder, &tlas_inputs, nullptr, &tlas_info); + if (!tlas_info.ResultDataMaxSizeInBytes) return fail("TLAS prebuild info is empty"); + + // ---- buffers ---- + const D3D12_RESOURCE_FLAGS uav = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + const D3D12_RESOURCE_STATES as_state = D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE; + Ref blas, refused, tlas, scratch, scratch2, info, blas_rb, refused_rb, tlas_rb, info_rb; + const UINT64 scratch_size = blas_info.ScratchDataSizeInBytes > tlas_info.ScratchDataSizeInBytes + ? blas_info.ScratchDataSizeInBytes : tlas_info.ScratchDataSizeInBytes; + if (FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, blas_info.ResultDataMaxSizeInBytes, as_state, uav, blas.put())) || + FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, blas_info.ResultDataMaxSizeInBytes, as_state, uav, refused.put())) || + FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, tlas_info.ResultDataMaxSizeInBytes, as_state, uav, tlas.put())) || + FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, scratch_size, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, uav, scratch.put())) || + FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, scratch_size, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, uav, scratch2.put())) || + FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, 16, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, uav, info.put())) || + FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_READBACK, blas_info.ResultDataMaxSizeInBytes, + D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE, blas_rb.put())) || + FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_READBACK, blas_info.ResultDataMaxSizeInBytes, + D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE, refused_rb.put())) || + FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_READBACK, tlas_info.ResultDataMaxSizeInBytes, + D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE, tlas_rb.put())) || + FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_READBACK, 16, D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_FLAG_NONE, info_rb.put()))) + return fail("acceleration-structure buffers", hr); + + // ---- instances ---- + const float c = std::cos(0.9f), s = std::sin(0.9f); + const float xforms[2][12] = {{1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0}, {c, 0, s, 10, 0, 1, 0, -2, -s, 0, c, 1}}; + D3D12_RAYTRACING_INSTANCE_DESC instances[2]{}; + for (int i = 0; i < 2; ++i) { + std::memcpy(instances[i].Transform, xforms[i], sizeof xforms[i]); + instances[i].InstanceID = 40 + i; + instances[i].InstanceMask = 0xff; + instances[i].AccelerationStructure = blas->GetGPUVirtualAddress(); + } + const UINT64 instances_at = (soup_bytes + 255) / 256 * 256; + std::memcpy(mapped + instances_at, instances, sizeof instances); + upload->Unmap(0, nullptr); + tlas_inputs.InstanceDescs = upload->GetGPUVirtualAddress() + instances_at; + + D3D12_COMMAND_QUEUE_DESC qd{}; + qd.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; + Ref queue; + Ref allocator; + Ref list; + Ref fence; + if (FAILED(device->CreateCommandQueue(&qd, IID_PPV_ARGS(queue.put()))) || + FAILED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(allocator.put()))) || + FAILED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, IID_PPV_ARGS(list.put()))) || + FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(fence.put())))) + return fail("queue, allocator, list or fence"); + UINT64 fence_value = 0; + auto submit = [&]() { + if (FAILED(list->Close())) return false; + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + if (FAILED(queue->Signal(fence.p, ++fence_value))) return false; + HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + const bool done = event && SUCCEEDED(fence->SetEventOnCompletion(fence_value, event)) && + WaitForSingleObject(event, 10000) == WAIT_OBJECT_0; + if (event) CloseHandle(event); + return done && SUCCEEDED(device->GetDeviceRemovedReason()); + }; + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + + // ---- BuildRaytracingAccelerationStructureBatched2X: the BLAS (with a stream and a COMPACTED_SIZE postbuild), + // and an element asking for offline statistics, which the DLL refuses and the shim skips ---- + const xdxr::PostbuildInfoDesc compacted_post{info->GetGPUVirtualAddress(), + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_COMPACTED_SIZE, 0}; + const xdxr::PostbuildInfoDesc statistics_post{info->GetGPUVirtualAddress() + 8, + xdxr::kPostbuildInfoOfflineStatistics, 0}; + xdxr::BatchedDesc2 elements[2]{}; + for (xdxr::BatchedDesc2& e : elements) { + std::memcpy(&e.inputs, &blas_inputs, sizeof e.inputs); + e.stream = stream; + } + elements[0].dest_acceleration_structure_data = blas->GetGPUVirtualAddress(); + elements[0].scratch_acceleration_structure_data = scratch->GetGPUVirtualAddress(); + elements[0].num_postbuild_info_descs = 1; + elements[0].postbuild_info_descs = &compacted_post; + elements[1].dest_acceleration_structure_data = refused->GetGPUVirtualAddress(); + elements[1].scratch_acceleration_structure_data = scratch2->GetGPUVirtualAddress(); + elements[1].num_postbuild_info_descs = 1; + elements[1].postbuild_info_descs = &statistics_post; + batched(builder, list.p, 2, elements); + list->ResourceBarrier(1, &barrier); + xdxr::BatchedDesc2 top{}; + top.dest_acceleration_structure_data = tlas->GetGPUVirtualAddress(); + std::memcpy(&top.inputs, &tlas_inputs, sizeof top.inputs); + top.scratch_acceleration_structure_data = scratch->GetGPUVirtualAddress(); + batched(builder, list.p, 1, &top); + batched(builder, list.p, 0, nullptr); // an empty batch does nothing + list->ResourceBarrier(1, &barrier); + list->CopyBufferRegion(blas_rb.p, 0, blas.p, 0, blas_info.ResultDataMaxSizeInBytes); + list->CopyBufferRegion(refused_rb.p, 0, refused.p, 0, blas_info.ResultDataMaxSizeInBytes); + list->CopyBufferRegion(tlas_rb.p, 0, tlas.p, 0, tlas_info.ResultDataMaxSizeInBytes); + list->CopyBufferRegion(info_rb.p, 0, info.p, 0, 16); + if (!submit()) return fail("the batched builds did not complete"); + + UINT64 post[2] = {}; + { + void* p = nullptr; + if (FAILED(info_rb->Map(0, nullptr, &p))) return fail("Map postbuild"); + std::memcpy(post, p, sizeof post); + info_rb->Unmap(0, nullptr); + } + check(post[0] && post[0] % 64 == 0 && post[0] <= blas_info.ResultDataMaxSizeInBytes, + "the BLAS element's COMPACTED_SIZE postbuild is written"); + check(post[1] == 0, "the offline-statistics element is skipped: its postbuild destination is untouched"); + { + void* p = nullptr; + std::uint32_t units = 0; + if (SUCCEEDED(refused_rb->Map(0, nullptr, &p))) { + std::memcpy(&units, static_cast(p) + 4, 4); + refused_rb->Unmap(0, nullptr); + } + check(units == 0, "and no structure was built into its destination"); + } + + // ---- CopyRaytracingAccelerationStructure COMPACT into a buffer of exactly COMPACTED_SIZE ---- + Ref compacted, compacted_rb; + if (FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, post[0], as_state, uav, compacted.put())) || + FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_READBACK, post[0], D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_FLAG_NONE, compacted_rb.put()))) + return fail("compacted buffers", hr); + if (FAILED(allocator->Reset()) || FAILED(list->Reset(allocator.p, nullptr))) return fail("Reset for compaction"); + copy(builder, list.p, compacted->GetGPUVirtualAddress(), blas->GetGPUVirtualAddress(), + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT); + list->ResourceBarrier(1, &barrier); + list->CopyBufferRegion(compacted_rb.p, 0, compacted.p, 0, post[0]); + if (!submit()) return fail("the compaction did not complete"); + + // ---- RehydrateRaytracingAccelerationStructureBatched2X: not implemented yet ---- + D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC rehydrate_desc{}; + const UINT64 source = blas->GetGPUVirtualAddress(); + check(rehydrate(builder, list.p, 1, &rehydrate_desc, &source) == E_NOTIMPL, + "RehydrateRaytracingAccelerationStructureBatched2X answers E_NOTIMPL (stage 2)"); + + // ---- dump for xdxr_bvh.py check-build ---- + auto dump = [&](ID3D12Resource* rb, UINT64 size, const std::string& name, const std::string& json) { + void* p = nullptr; + if (FAILED(rb->Map(0, nullptr, &p))) return false; + std::uint32_t units = 0; + std::memcpy(&units, static_cast(p) + 4, 4); // header totalSizeIn64BNodes + const UINT64 used = (UINT64(units) + 1) * 64; // the field does not count the 64-byte header + const bool ok = units && used <= size && write_file(dir + "/" + name + ".bin", p, std::size_t(used)) && + write_file(dir + "/" + name + ".json", json.data(), json.size()); + rb->Unmap(0, nullptr); + return ok; + }; + std::string triangles = "["; + for (UINT t = 0; t < tris; ++t) { + triangles += t ? ",\n [" : "\n ["; + for (int k = 0; k < 3; ++k) + triangles += (k ? ", [" : "[") + num(soup[9 * t + 3 * k]) + ", " + num(soup[9 * t + 3 * k + 1]) + ", " + + num(soup[9 * t + 3 * k + 2]) + "]"; + triangles += ", 0, " + std::to_string(t) + "]"; + } + triangles += "]"; + check(dump(blas_rb.p, blas_info.ResultDataMaxSizeInBytes, "shim_blas", + "{\"kind\": \"blas\", \"address\": " + std::to_string(blas->GetGPUVirtualAddress()) + + ", \"triangles\": " + triangles + "}\n"), + "the BLAS built through the shim is written for check-build"); + std::string inst = "["; + for (int i = 0; i < 2; ++i) { + inst += i ? ", {\"transform\": [" : "{\"transform\": ["; + for (int k = 0; k < 12; ++k) inst += (k ? ", " : "") + num(xforms[i][k]); + inst += "], \"mask\": 255, \"blas\": 0}"; + } + inst += "]"; + check(dump(tlas_rb.p, tlas_info.ResultDataMaxSizeInBytes, "shim_tlas", + "{\"kind\": \"tlas\", \"address\": " + std::to_string(tlas->GetGPUVirtualAddress()) + + ", \"bias\": 0, \"blas\": [\"shim_blas\"], \"instances\": " + inst + "}\n"), + "the TLAS built through the shim is written for check-build"); + check(dump(compacted_rb.p, post[0], "shim_blas_compacted", + "{\"kind\": \"blas\", \"address\": " + std::to_string(compacted->GetGPUVirtualAddress()) + + ", \"triangles\": " + triangles + "}\n"), + "the BLAS compacted through the shim is written for check-build"); + + // ---- the destructor releases the builder ---- + destruct(builder); + destruct(builder); // a second destruction of the same storage is ignored + check(rt::shims::xbox_bvh_builder_live_count() == 0, "the destructor releases the builder's state"); + + std::printf("xbox_bvh_builder_test: %d of %d checks failed\n", g_failures, g_checks); + return g_failures ? 1 : 0; +} diff --git a/runtime/test/xbox_present_test.cpp b/runtime/test/xbox_present_test.cpp index 1526f87a7a..bc311a87e2 100644 --- a/runtime/test/xbox_present_test.cpp +++ b/runtime/test/xbox_present_test.cpp @@ -368,15 +368,17 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); + reinterpret_cast(&device.p), /*console_lists=*/false))); rt::d3d12::set_device_outer(inner, device.p); auto presenter = rt::d3d12::create_window_presenter(inner, window); EXPECT(presenter); EXPECT(presenter->enable_capture()); leonida::ManualFrameClock clock; - auto owner = std::make_unique(std::move(presenter), &clock); + auto owner = std::make_unique(std::move(presenter), &clock, + rt::d3d12_xs::device_frame_tokens(device.p)); rt::d3d12::XboxPresentation& xbox = *owner; + EXPECT(xbox.pacer().token_source() == rt::d3d12_xs::device_frame_tokens(device.p)); D3D12_COMMAND_QUEUE_DESC queue_desc{}; Ref queue; @@ -470,6 +472,29 @@ int main() { return rt::d3d12::XboxPresentPlaneParameters{t, 1, &s.resource.p, rect, 0}; }; + // Shell art covers startup clears. A single coloured source texel hands off the entire frame; + // later black frames must stay black. These shell presents consume no Xbox frame tokens. + { + Source shell, title; + const FLOAT black[4] = {0, 0, 0, 1}; + EXPECT(make_source(DXGI_FORMAT_R8G8B8A8_UNORM, shell) && fill(shell, red)); + EXPECT(make_source(DXGI_FORMAT_R8G8B8A8_UNORM, title) && fill(title, black)); + auto& launch = xbox.presenter(); + EXPECT(launch.present_splash(shell.resource.p)); + EXPECT(SUCCEEDED(launch.present(title.resource.p, 1))); + EXPECT(launch.read_back(frame.bytes, &frame.extent, &frame.format)); + EXPECT(region_is(frame, 0, 0, width, height, {255, 0, 0})); + const D3D12_RECT corner{0, 0, 1, 1}; + EXPECT(fill(title, blue, 1, &corner)); + EXPECT(SUCCEEDED(launch.present(title.resource.p, 1))); + EXPECT(launch.read_back(frame.bytes, &frame.extent, &frame.format)); + EXPECT(region_is(frame, 0, 0, 1, 1, {0, 0, 255})); + EXPECT(region_is(frame, width - 1, height - 1, width, height, {0, 0, 0})); + EXPECT(SUCCEEDED(launch.present_blank(1))); + EXPECT(launch.read_back(frame.bytes, &frame.extent, &frame.format)); + EXPECT(region_is(frame, 0, 0, width, height, {0, 0, 0})); + } + // 1 plane, solid colour, RGBA8. Source rgba; EXPECT(make_source(DXGI_FORMAT_R8G8B8A8_UNORM, rgba)); @@ -665,6 +690,22 @@ int main() { EXPECT(region_is(frame, 0, 0, width, height, {51, 153, 230})); EXPECT(xbox.presents() == presented_before + 3); + using DeviceWaitFrameEventFn = HRESULT(WINAPI*)(void*, UINT, UINT, void*, UINT, std::uint64_t*); + const auto device_wait = + reinterpret_cast((*reinterpret_cast(device.p))[80]); + std::uint64_t device_token = 0; + EXPECT(device_wait(device.p, rt::d3d12::xbox_frame_event_origin, 0, nullptr, 0, &device_token) == S_OK); + EXPECT(device_token != 0 && device_token == xbox.pacer().tokens_issued()); + plane = plane_of(second, device_token + 1); + EXPECT(xbox.PresentX(1, &plane, nullptr) == E_INVALIDARG); + EXPECT(xbox.presents() == presented_before + 3); + plane = plane_of(rgba, device_token); + EXPECT(xbox.PresentX(1, &plane, nullptr) == S_OK); + EXPECT(xbox.presents() == presented_before + 4); + EXPECT(grab(frame)); + EXPECT(region_is(frame, 0, 0, width, height, {51, 153, 230})); + std::printf("a token from device slot 80 (WaitFrameEventX) presents: ok\n"); + // Sources the GPU cannot blit are refused with DXGI_ERROR_UNSUPPORTED and present nothing: multisampled, // integer and block-compressed. The last frame stays on screen and the token is still usable afterwards. { diff --git a/runtime/test/xg_xs_test.cpp b/runtime/test/xg_xs_test.cpp index 7db9b60962..3def1e3dd1 100644 --- a/runtime/test/xg_xs_test.cpp +++ b/runtime/test/xg_xs_test.cpp @@ -1,91 +1,355 @@ -// Checks the registered xg_xs.dll shim against the call shapes measured in the game executable (runtime/shims/xg_xs.cpp). -// -// Both exports are resolved through rt::shims::find, so this is the table the runtime installs. The checks: both -// return E_NOTIMPL, XGSuggestSwizzleMode leaves the caller's field alone, XGCreateTextureComputer still hands out a -// computer (two measured callers use it without checking the HRESULT), and the computer's slots called at the -// measured sites (1, 2, 8, 10) return without writing what their arguments point to. #include +#include #include #include +#include #include +#include #include "shims.h" +#include "xg_xs_layout.h" +#include "../src/title_texture_memory.h" +#include "../src/title_texture_refresh.h" namespace { +using namespace rt::xg_xs; using CreateFn = HRESULT(__stdcall*)(const void*, void**); using SuggestFn = HRESULT(__stdcall*)(const void*, uint32_t, uint32_t*); -using ReleaseFn = ULONG(__stdcall*)(void*); -using Slot2Fn = HRESULT(__stdcall*)(void*, void*); -using Slot8Fn = HRESULT(__stdcall*)(void*, void*, uint32_t, uint32_t, const void*, uint32_t, uint32_t); -using Slot10Fn = HRESULT(__stdcall*)(void*, uint32_t*, void*, void*, uint32_t*, uint32_t, void*); -constexpr HRESULT kNotImpl = static_cast(rt::shims::kENotImpl); +using RefFn = ULONG(__stdcall*)(void*); +using LayoutFn = HRESULT(__stdcall*)(void*, ResourceLayout*); +using SizeFn = uint64_t(__stdcall*)(void*); +using OffsetFn = uint64_t(__stdcall*)(void*, uint32_t, uint32_t, uint64_t, uint32_t, uint32_t, uint32_t, uint32_t*); +using IntoFn = HRESULT(__stdcall*)(void*, void*, uint32_t, uint32_t, const void*, uint32_t, uint32_t); +using FromFn = HRESULT(__stdcall*)(void*, void*, uint32_t, uint32_t, uint32_t, const void*, uint32_t, uint32_t); +struct Tiling { uint32_t width; uint16_t height, depth; uint32_t start; }; +using TilingFn = HRESULT(__stdcall*)(void*, uint32_t*, uint32_t*, uint32_t*, uint32_t*, uint32_t, Tiling*); int g_checks = 0; int g_failures = 0; void check(bool condition, const char* what) { ++g_checks; - std::printf("%s %s\n", condition ? "PASS" : "FAIL", what); - if (!condition) ++g_failures; + if (!condition) { + ++g_failures; + std::printf("FAIL %s\n", what); + } } -bool all_bytes(const uint8_t* p, size_t n, uint8_t value) { - for (size_t i = 0; i < n; ++i) - if (p[i] != value) return false; - return true; +template +Fn slot(void* computer, unsigned index) { + return reinterpret_cast((*static_cast(computer))[index]); +} + +bool make(CreateFn create, const ResourceDesc& d, void*& computer, const char* what) { + const bool success = create(&d, &computer) == S_OK && computer; + check(success, what); + return success; +} + +void check_addresses(const Texture& t) { + const ElementAddress address(t); + std::vector seen(t.layout.size / t.format.bytes); + for (uint32_t slice = 0; slice < t.array; ++slice) { + for (uint32_t level = 0; level < t.layout.mips; ++level) { + const auto& mip = t.layout.plane[0].mips[level]; + const auto tail = address.tail_origin(mip); + for (uint32_t y = 0; y < mip.height_elements; ++y) { + for (uint32_t x = 0; x < mip.width_elements; ++x) { + const auto off = address.offset(mip, tail, x, y, slice); + if (off % t.format.bytes || off / t.format.bytes >= seen.size() || seen[off / t.format.bytes]) { + check(false, "every mip/array element has a distinct aligned address inside the resource"); + return; + } + seen[off / t.format.bytes] = true; + } + } + } + } + check(true, "every mip/array element has a distinct aligned address inside the resource"); +} + +// copy_elements (row + column addressing) reads every element where offset() says it is. +void check_detile(const Texture& t) { + const ElementAddress address(t); + std::vector tiled(t.layout.size); + for (size_t i = 0; i < tiled.size(); ++i) tiled[i] = uint8_t(i * 2654435761u >> 13); + std::vector columns; + for (uint32_t slice = 0; slice < t.array; ++slice) { + for (uint32_t level = 0; level < t.layout.mips; ++level) { + const auto& mip = t.layout.plane[0].mips[level]; + const uint32_t pitch = mip.width_elements * t.format.bytes + 4; + std::vector linear(size_t(pitch) * mip.height_elements); + copy_elements(t, level, slice, tiled.data(), linear.data(), pitch, 0, columns); + const auto tail = address.tail_origin(mip); + for (uint32_t y = 0; y < mip.height_elements; ++y) { + for (uint32_t x = 0; x < mip.width_elements; ++x) { + const uint64_t at = address.offset(mip, tail, x, y, slice); + if (std::memcmp(linear.data() + size_t(y) * pitch + size_t(x) * t.format.bytes, tiled.data() + at, + t.format.bytes)) { + check(false, "copy_elements reads each element at offset()"); + return; + } + } + } + } + } + check(true, "copy_elements reads each element at offset()"); } } // namespace int main() { + { + struct Entry { bool mapped, stale; int id; }; + Entry first{false, false, 1}, mapped{true, false, 2}, stale{false, true, 3}; + Entry last{false, false, 4}, added{false, false, 5}; + std::map entries{{10, &first}, {20, &mapped}, {30, &stale}, {40, &last}}; + std::uint64_t cursor = 0; + std::vector polled; + const auto visit = [&](Entry& t) { polled.push_back(t.id); }; + leonida::poll_title_textures(entries, cursor, visit, [&] { return !polled.empty(); }); + check(polled == std::vector{1}, "budget stops after a background texture"); + entries.erase(10); + entries[50] = &added; + leonida::poll_title_textures(entries, cursor, visit, [&] { return polled.size() == 2; }); + check(polled == std::vector{1, 4}, "poll resumes after deletion and skips priority textures"); + polled.clear(); + leonida::poll_title_textures(entries, cursor, visit, [] { return false; }); + check(polled == std::vector{5, 4}, "unlimited poll wraps once and includes new textures"); + cursor = 20; + polled.clear(); + for (unsigned pass = 0; pass < 3; ++pass) + leonida::poll_title_textures(entries, cursor, visit, [] { return true; }); + check(polled == std::vector{4}, "an expired wall budget advances past priority entries to the next texture"); + + } + + { + leonida::TitleWriteRanges writes{{20, 30}, {10, 20}, {15, 17}, {60, 75}, {60, 67}, {90, 90}}; + const auto original = writes; + leonida::merge_title_writes(writes); + check(writes == leonida::TitleWriteRanges{{10, 30}, {60, 75}}, "coalesce overlapping and adjacent writes"); + bool same = true; + for (unsigned begin = 0; begin < 100; ++begin) { + for (unsigned end = begin; end < 100; ++end) { + const bool overlap = std::any_of(original.begin(), original.end(), [&](auto r) { + return begin < end && r.first < r.second && r.first < end && r.second > begin; + }); + same &= leonida::title_write_overlaps(writes, begin, end) == overlap; + } + } + check(same, "indexed writes find the same overlaps as scanning each original notification"); + } + + SYSTEM_INFO sys{}; + GetSystemInfo(&sys); + const auto page = sys.dwPageSize; + leonida::TextureReadability residency; + unsigned probes = 0; + bool committed = false; + const auto probe = [&] { ++probes; return committed; }; + for (unsigned pass = 0; pass < 100; ++pass) residency.check(8, true, probe); + check(probes == 1 && residency.pending(), "unchanged reserved texture is probed only once in 100 passes"); + check(!residency.check(9, true, probe) && probes == 2, "a new map generation retries the failed footprint"); + committed = true; + residency.retry(); // overlapping DirectStorage or XG write + check(residency.check(9, true, probe) && probes == 3, "write notification retries at the same generation"); + committed = false; + check(!residency.check(9, true, probe) && probes == 4, "previous success is rechecked before the next read"); + check(!residency.check(9, false, probe) && probes == 5, "rollback disables the failed-probe cache"); + HANDLE section = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE | SEC_RESERVE, 0, 65536, nullptr); + if (!section) return 1; + void* view = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 65536); + if (!view) return 1; + const auto placed = reinterpret_cast(view); + const auto first_touch = [](const void* at, std::size_t bytes) { + return VirtualAlloc(const_cast(at), bytes, MEM_COMMIT, PAGE_READWRITE) != nullptr; + }; + check(!leonida::texture_memory_readable(placed, 65536), "background polling leaves mapped first-touch pages reserved"); + check(!leonida::texture_memory_readable(placed, 65536, [](const void*, std::size_t) { return true; }), + "a section outside xmem stays deferred when the commit hook leaves it reserved"); + check(leonida::texture_memory_readable(placed, 65536, first_touch), "persistent Map can populate a physical section before checking it"); + UnmapViewOfFile(view); + CloseHandle(section); + void* reservation = VirtualAlloc(nullptr, 2 * page, MEM_RESERVE, PAGE_NOACCESS); + if (!reservation) return 1; + const auto address = reinterpret_cast(reservation); + check(!leonida::texture_memory_readable(address, page), "untouched reserved texture is deferred"); + check(!leonida::texture_memory_readable(address, page, first_touch), "a persistent Map cannot commit a bare reservation"); + leonida::TextureReadability persistent_map; + const auto probe_mapped = [&] { return leonida::texture_memory_readable(address, page); }; + check(!persistent_map.check(11, false, probe_mapped), "persistent Map defers a reserved texture before decoder writes"); + if (!VirtualAlloc(reservation, page, MEM_COMMIT, PAGE_READWRITE)) return 1; + auto* pixels = static_cast(reservation); + pixels[page - 1] = 93; + check(persistent_map.check(11, false, probe_mapped) && pixels[page - 1] == 93, + "persistent Map sees decoder writes after a failed probe at the same generation"); + check(leonida::texture_memory_readable(address + 3, page - 3) && + !leonida::texture_memory_readable(address + 3, page), "range crossing into a reserved mip is deferred"); + if (!VirtualAlloc(reinterpret_cast(address + page), page, MEM_COMMIT, PAGE_READONLY)) return 1; + check(leonida::texture_memory_readable(address, 2 * page), "later stream commit completes the footprint"); + DWORD previous = 0; + if (!VirtualProtect(reservation, page, PAGE_READWRITE | PAGE_GUARD, &previous)) return 1; + check(!leonida::texture_memory_readable(address, 2 * page), "guarded texture page remains untouched"); + VirtualFree(reservation, page, MEM_DECOMMIT); + check(!leonida::texture_memory_readable(address, page), "previously readable page is rechecked after decommit"); + VirtualFree(reservation, 0, MEM_RELEASE); + auto create = reinterpret_cast(rt::shims::find("xg_xs.dll", "XGCreateTextureComputer")); auto suggest = reinterpret_cast(rt::shims::find("xg_xs.dll", "XGSuggestSwizzleMode")); - check(create != nullptr, "XGCreateTextureComputer is registered"); - check(suggest != nullptr, "XGSuggestSwizzleMode is registered"); - check(rt::shims::owns_dll("xg_xs.dll"), "the registry owns xg_xs.dll"); + check(create && suggest && rt::shims::owns_dll("xg_xs.dll"), "XG exports are registered"); if (!create || !suggest) return 1; - uint8_t desc[0x38] = {}; - uint32_t mode = 0x1234; - check(suggest(desc, 0, &mode) == kNotImpl, "XGSuggestSwizzleMode returns E_NOTIMPL"); - check(mode == 0x1234, "XGSuggestSwizzleMode leaves the mode field as the caller set it"); - - check(create(desc, nullptr) == E_POINTER, "XGCreateTextureComputer(desc, nullptr) is E_POINTER"); + ResourceDesc d{3, 0, 256, 128, 1, 1, DXGI_FORMAT_R8_UNORM, 1, 0, 0, 0}; + check(suggest(&d, 0, &d.layout) == S_OK && d.layout == 0x105, "2D SRV selects SW_4KB_S with aliased output"); + uint32_t mode = 0xdeadbeef; + check(suggest(&d, 1, &mode) == E_NOTIMPL && mode == 0xdeadbeef, "unknown selector leaves output unchanged"); + check(create(&d, nullptr) == E_POINTER, "null computer output is rejected"); void* computer = nullptr; - check(create(desc, &computer) == kNotImpl, "XGCreateTextureComputer returns E_NOTIMPL"); - check(computer != nullptr, "XGCreateTextureComputer still stores a computer for the callers that do not check"); - if (!computer) return 1; - - void* const* vtable = *static_cast(computer); - uint8_t layout[0x800]; - std::memset(layout, 0xcd, sizeof(layout)); - check(reinterpret_cast(vtable[2])(computer, layout) == kNotImpl, "slot 2 returns E_NOTIMPL"); - check(all_bytes(layout, sizeof(layout), 0xcd), "slot 2 writes nothing to its output"); - - uint8_t dst[64]; - std::memset(dst, 0xcd, sizeof(dst)); - const uint8_t src[64] = {}; - check(reinterpret_cast(vtable[8])(computer, dst, 0, 0, src, 16, 64) == kNotImpl, - "slot 8 returns E_NOTIMPL"); - check(all_bytes(dst, sizeof(dst), 0xcd), "slot 8 writes nothing to its destination"); - - uint32_t count = 0, inout = 0x10; - uint8_t a[12] = {}, b[12] = {}, list[0xc0] = {}; - check(reinterpret_cast(vtable[10])(computer, &count, a, b, &inout, 0, list) == kNotImpl, - "slot 10 returns E_NOTIMPL"); - check(count == 0 && inout == 0x10 && all_bytes(a, 12, 0) && all_bytes(b, 12, 0) && - all_bytes(list, sizeof(list), 0), - "slot 10 leaves the caller's zero-filled outputs as they were"); - check(reinterpret_cast(vtable[31])(computer, layout) == kNotImpl, "the last slot (31) is traced too"); - - auto release = reinterpret_cast(vtable[1]); - release(computer); - release(computer); - check(reinterpret_cast(vtable[2])(computer, layout) == kNotImpl, - "the computer stays usable after more Releases than it was handed out"); + if (!make(create, d, computer, "create 2D SW_4KB_S computer")) return 1; + + ResourceLayout l; + std::memset(&l, 0xa5, sizeof(l)); + auto get_layout = slot(computer, 2); + auto get_offset = slot(computer, 6); + auto copy_into = slot(computer, 8); + check(get_layout(computer, &l) == S_OK, "slot 2 fills the Series layout"); + check(l.size == 32768 && l.alignment == 4096 && l.planes == 1 && l.mips == 1 && l.dimension == 3, + "256x128 R8 uses eight 64x64 SW_4KB_S blocks"); + check(l.plane[0].mips[0].pitch_bytes == 256 && l.plane[0].mips[0].offset == 0, + "slot 2 reports pitch and offset"); + const std::array unused{}; + check(std::memcmp(&l.plane[1], unused.data(), sizeof(unused)) == 0 && !l.reserved, + "slot 2 clears all three unused planes and the trailing reserved word"); + check(slot(computer, 3)(computer) == 32768 && slot(computer, 4)(computer) == 4096, + "size and alignment agree with slot 2"); + uint32_t bit = 99; + check(get_offset(computer, 0, 0, 0, 1, 0, 0, &bit) == 16 && bit == 0 && + get_offset(computer, 0, 0, 64, 0, 0, 0, nullptr) == 4096, + "SW_4KB_S addresses Y0 at bit 4 and X6 in the second tile"); + std::vector tiled(l.size, 0xcd); + constexpr unsigned pitch = 260; + std::vector linear(pitch * 128, 0); + linear[64] = 17; + linear[pitch] = 29; + check(copy_into(computer, tiled.data(), 0, 0, linear.data(), pitch, 0) == S_OK && + tiled[4096] == 17 && tiled[16] == 29, "slot 8 writes expected tiled offsets from padded linear rows"); + check(copy_into(computer, tiled.data(), 0, 1, linear.data(), pitch, 0) == E_INVALIDARG, + "slot 8 rejects an out-of-range subresource"); + check(copy_into(computer, tiled.data(), 0, 0, linear.data(), 255, 0) == E_INVALIDARG, + "slot 8 rejects a short row pitch"); + check(slot(computer, 10)(computer, nullptr, nullptr, nullptr, nullptr, 0, nullptr) == E_FAIL, + "slot 10 requires a 64 KiB mode"); + check(slot(computer, 0)(computer) == 2 && slot(computer, 1)(computer) == 1 && + slot(computer, 1)(computer) == 0, "release deletes the computer at refcount zero"); + + // The VIctory 256x256 BC7 SW_64KB_D fixture has one 64 KiB standard + // mip and a tail block before it. Exercise it as a two-element array. + d = {3, 0, 256, 256, 2, 0, DXGI_FORMAT_BC7_UNORM, 1, 0, 0x10a, 0}; + if (!make(create, d, computer, "create BC7 mipmapped array computer")) return 1; + check(slot(computer, 2)(computer, &l) == S_OK, "get BC7 layout"); + const auto& p = l.plane[0]; + check(l.size == 262144 && l.mips == 9 && p.slice_bytes == 131072 && + p.standard_mips == 1 && p.tail_mips == 8 && p.element_bytes == 16, + "BC7 array uses a standard block and a tail block per slice"); + check(p.mips[0].offset == 65536 && p.mips[0].pitch_bytes == 1024 && + p.mips[1].offset == 32768 && p.mips[1].in_tail, + "BC7 standard mip and first tail offsets match fixture"); + uint32_t tiles = 0, packed[3]{}, shape[3]{}, count = 18; + std::array tilings{}; + tilings[1].start = 0xdeadbeef; + check(slot(computer, 10)(computer, &tiles, packed, shape, &count, 0, tilings.data()) == S_OK && + tiles == 4 && packed[0] == 0x0801 && packed[1] == 1 && packed[2] == 0 && + shape[0] == 256 && shape[1] == 256 && shape[2] == 1 && count == 2 && + tilings[0].start == 1 && tilings[9].start == 3 && tilings[1].start == 0xdeadbeef, + "slot 10 reports standard tiles, texture-unit shape and packed tail"); + tiled.assign(l.size, 0); + std::array block{}, back{}; + block[0] = 77; + const unsigned last_mip_in_slice_1 = 17; + check(slot(computer, 8)(computer, tiled.data(), 0, last_mip_in_slice_1, block.data(), 16, 0) == S_OK && + tiled[p.slice_bytes + p.mips[8].offset] == 77 && + slot(computer, 9)(computer, back.data(), 0, last_mip_in_slice_1, 0, tiled.data(), 16, 0) == S_OK && + back == block, "slots 8 and 9 copy a BC block in the second slice's tail"); + slot(computer, 1)(computer); + + // The addrlib padded mip sizes use ceil division even for odd extents. + Texture texture; + d = {3, 0, 30, 20, 1, 0, DXGI_FORMAT_R8G8B8A8_UNORM, 1, 0, 1, 0}; + check(build_texture(d, texture) && texture.layout.size == 10240 && + texture.layout.plane[0].mips[0].offset == 5120 && texture.layout.plane[0].mips[0].pitch_bytes == 256, + "row-major chain aligns each physical pitch to 256 B"); + + for (const uint32_t swizzle : {0x105u, 0x109u, 0x10au}) { + for (DXGI_FORMAT format : {DXGI_FORMAT_R8_UNORM, DXGI_FORMAT_R8G8_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM, + DXGI_FORMAT_BC1_UNORM, DXGI_FORMAT_BC7_UNORM}) { + d = {3, 0, 259, 175, 2, 0, uint32_t(format), 1, 0, swizzle, 0}; + if (build_texture(d, texture)) check_addresses(texture), check_detile(texture); + else check(false, "create odd-sized tiled mip chain"); + } + } + + d = {4, 0, 9, 2, 2, 1, DXGI_FORMAT_R8G8B8A8_UNORM, 1, 0, 0x105, 0}; + if (!make(create, d, computer, "create single-mip 3D SW_4KB_S computer")) return 1; + check(slot(computer, 2)(computer, &l) == S_OK && + l.size == 8192 && l.plane[0].mips[0].padded_depth == 8 && l.plane[0].mips[0].tile_depth == 8, + "3D 4KB_S blocks for RGBA8 are 8x16x8"); + check(slot(computer, 6)(computer, 0, 0, 0, 0, 1, 0, nullptr) == 16 && + slot(computer, 6)(computer, 0, 0, 8, 0, 0, 0, nullptr) == 4096, + "3D 4KB_S selects Z0 at bit 4 and X3 in the second tile"); + slot(computer, 1)(computer); + + // GFX10 thick 4 KiB blocks: each 16-deep slab has one tail block, one + // level-1 block and four level-0 blocks. Crossing z=16 skips the whole slab. + ResourceDesc volume{4, 0, 32, 32, 32, 6, DXGI_FORMAT_R8_UNORM, 1, 0, 0x105, 0}; + if (!build_texture(volume, texture)) return 1; + const ElementAddress thick(texture); + const auto& levels = texture.layout.plane[0].mips; + check(texture.layout.size == 49152 && levels[2].in_tail && levels[2].depth == 8 && + thick.offset(levels[0], {}, 0, 0, 0) == 8192 && + thick.offset(levels[0], {}, 0, 0, 16) == 32768 && + thick.offset(levels[2], thick.tail_origin(levels[2]), 0, 0, 0) == 2048, + "3D mip chain uses per-slab macro offsets and a thick tail origin"); + for (DXGI_FORMAT format : {DXGI_FORMAT_R8_UNORM, DXGI_FORMAT_R16_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM, + DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R32G32B32A32_FLOAT, + DXGI_FORMAT_BC1_UNORM, DXGI_FORMAT_BC5_UNORM}) { + volume = {4, 0, 61, 35, 67, 7, uint32_t(format), 1, 0, 0x105, 0}; + if (!build_texture(volume, texture)) return 1; + const ElementAddress addr(texture); + std::vector used(texture.layout.size); + bool distinct = true, matches = true; + for (unsigned level = 0; level < texture.layout.mips; ++level) { + const auto& mip = texture.layout.plane[0].mips[level]; + const auto tail = addr.tail_origin(mip); + const unsigned pitch = mip.width_elements * texture.format.bytes + 8; + const unsigned slice_pitch = pitch * mip.height_elements + 16; + std::vector source(slice_pitch * mip.depth), back(source.size()), tiled(texture.layout.size); + std::vector columns; + for (unsigned z = 0; z < mip.depth; ++z) + for (unsigned y = 0; y < mip.height_elements; ++y) + for (unsigned x = 0; x < mip.width_elements; ++x) { + const auto at = addr.offset(mip, tail, x, y, z); + if (at % texture.format.bytes || at > used.size() - texture.format.bytes || used[at]) { + distinct = false; + continue; + } + used[at] = 1; + source[z * slice_pitch + y * pitch + x * texture.format.bytes] = uint8_t(1 + (x+y+z)%251); + } + if (!distinct) break; + copy_elements(texture, level, 0, source.data(), tiled.data(), pitch, slice_pitch, columns); + copy_elements(texture, level, 0, tiled.data(), back.data(), pitch, slice_pitch, columns); + matches &= back == source; + } + check(distinct && matches, "odd volume mips and z slices are disjoint and preserve padded linear pitches"); + } + d.samples = 4; + check(create(&d, &computer) == E_NOTIMPL && computer, "unsupported texture keeps a safe fallback object"); + check(slot(computer, 2)(computer, &l) == E_NOTIMPL && l.size == 8192 && + slot(computer, 1)(computer) == 1, "fallback leaves caller outputs untouched and is safe to release"); std::printf("%d checks, %d failures\n", g_checks, g_failures); return g_failures ? 1 : 0; } diff --git a/runtime/test/xgameruntime_test.cpp b/runtime/test/xgameruntime_test.cpp index 8c1fb456e7..0fe693913a 100644 --- a/runtime/test/xgameruntime_test.cpp +++ b/runtime/test/xgameruntime_test.cpp @@ -266,8 +266,8 @@ void check_measured_classes(QueryFn query, XSystemAnalyticsInfo (*named_analytic } // xgameruntime.lib's thunks don't import the runtime: they LoadLibraryW(L"xgameruntime.dll") and GetProcAddress five -// names (measured in the package's libHttpClient.GDK.dll and XCurl.dll). Drive that path through the loader shims, -// bound by the api set XCurl.dll imports them from, as a mapped image would be. +// entry points and XErrorReport (measured in the package's libHttpClient.GDK.dll and XCurl.dll). Drive that path +// through the loader shims, bound by the api set XCurl.dll imports them from, as a mapped image would be. void check_run_time_load() { using LoadW = HMODULE(WINAPI*)(LPCWSTR); using LoadExA = HMODULE(WINAPI*)(LPCSTR, HANDLE, DWORD); @@ -294,12 +294,15 @@ void check_run_time_load() { "the same module for a bare name, a full path in any case, LoadLibraryExA and GetModuleHandleW"); const char* entry_points[] = {"InitializeApiImpl", "InitializeApiImplEx", "InitializeApiImplEx2", - "UninitializeApiImpl", "QueryApiImpl"}; + "UninitializeApiImpl", "QueryApiImpl", "XErrorReport"}; bool all = true; for (const char* n : entry_points) all = all && get_proc(rt_mod, n) && reinterpret_cast(get_proc(rt_mod, n)) == rt::shims::find("xgameruntime.dll", n); - check(all, "GetProcAddress serves the five entry points xgameruntime.lib looks up"); + check(all, "GetProcAddress serves the six names xgameruntime.lib looks up (five entry points and XErrorReport)"); + using ReportExport = HRESULT(WINAPI*)(HRESULT, const char*); + auto report_export = reinterpret_cast(get_proc(rt_mod, "XErrorReport")); + check(report_export && report_export(E_FAIL, "export") == S_OK, "the XErrorReport export answers S_OK"); SetLastError(0); check(get_proc(rt_mod, "NoSuchRuntimeFunction") == nullptr && GetLastError() == ERROR_PROC_NOT_FOUND, "an unserved name is NULL with ERROR_PROC_NOT_FOUND, as from a real module"); @@ -819,16 +822,37 @@ void check_run_time_load() { "slot 26 (XPackageCloseMountHandle) closes the handle"); SetEnvironmentVariableA("LEONIDA_CONTENT_PACKAGES", nullptr); using Stub = HRESULT(STDMETHODCALLTYPE*)(void*); - check(reinterpret_cast(slot(pk, 5))(pk) == E_NOTIMPL && reinterpret_cast(slot(pk, 40))(pk) == E_NOTIMPL, - "the slots without an offline answer (5, 40) are E_NOTIMPL"); + check(reinterpret_cast(slot(pk, 20))(pk) == E_NOTIMPL && reinterpret_cast(slot(pk, 40))(pk) == E_NOTIMPL && + reinterpret_cast(slot(pk, 41))(pk) == E_NOTIMPL, + "the slots without an offline answer (20, 40, 41) are E_NOTIMPL"); + // Slot 39, XPackageEnumeratePackages(kind, scope, context, callback): the title enumerates content packages + // (kind 1); there are none offline, so S_OK and the callback never runs. No callback is E_INVALIDARG. + { + using PackageCallback = bool(CALLBACK*)(void*, const void*); + using EnumeratePackages = HRESULT(STDMETHODCALLTYPE*)(void*, uint32_t, uint32_t, void*, PackageCallback); + const auto enumerate_packages = reinterpret_cast(slot(pk, 39)); + int listed = 0; + const PackageCallback count_package = [](void* ctx, const void*) -> bool { + ++*static_cast(ctx); + return true; + }; + check(enumerate_packages(pk, 1, 0, &listed, count_package) == S_OK && + enumerate_packages(pk, 1, 1, &listed, count_package) == S_OK && + enumerate_packages(pk, 0, 0, &listed, count_package) == S_OK && listed == 0 && + enumerate_packages(pk, 1, 0, &listed, nullptr) == E_INVALIDARG, + "slot 39 (XPackageEnumeratePackages): S_OK and no callback (no content packages offline); " + "a null callback is E_INVALIDARG"); + } struct Progress { uint64_t total, installed, launch; bool launchable, completed; } progress{~0ull, 7, 7, false, false}; using GetProgress = void(STDMETHODCALLTYPE*)(void*, void*, Progress*); reinterpret_cast(slot(pk, 7))(pk, nullptr, &progress); - check(progress.launchable && progress.completed && progress.installed == progress.total, - "slot 7 (void XPackageGetInstallationProgress) writes an installed, launchable, completed package"); + check(progress.launchable && progress.completed && progress.total != 0 && progress.total != ~0ull && + progress.installed == progress.total && progress.launch == progress.total, + "slot 7 (void XPackageGetInstallationProgress) writes an installed, launchable, completed package: " + "every one of a non-zero number of bytes installed"); using Update = bool(STDMETHODCALLTYPE*)(void*, void*); using UnregProgress = bool(STDMETHODCALLTYPE*)(void*, void*, XTaskQueueRegistrationToken, bool); using UnregInstalled = bool(STDMETHODCALLTYPE*)(void*, XTaskQueueRegistrationToken, bool); @@ -838,18 +862,196 @@ void check_run_time_load() { reinterpret_cast(slot(pk, 22))(pk, XTaskQueueRegistrationToken{1}, false) && !reinterpret_cast(slot(pk, 34))(pk, "pkg"), "the bool slots 8, 10, 22 and 34 return their documented offline answers"); + { + // Slots 5-19: the installation monitor and the chunks of the fully installed package (answers ported from + // VIctory's xpackage.rs). Selector: XPackageChunkSelectorType (Language 0, Tag 1, Chunk 2, Feature 3), + // then the string or chunk id. + struct Selector { + uint32_t type; + union { + const char* text; + uint32_t chunk_id; + }; + }; + static_assert(sizeof(Selector) == 16, "XPackageChunkSelector is 16 bytes"); + const HRESULT no_package = static_cast(0x89245208); // E_GAMEPACKAGE_NO_PACKAGE_IDENTIFIER + char own[64] = {}; + reinterpret_cast(slot(pk, 3))(pk, sizeof(own), own); + Selector selectors[2] = {}; + selectors[0].type = 2; + selectors[0].chunk_id = 1000; + selectors[1].type = 1; + selectors[1].text = "core"; + + using CreateMonitor = HRESULT(STDMETHODCALLTYPE*)(void*, const char*, uint32_t, const Selector*, uint32_t, + XTaskQueueHandle, void**); + using CloseMonitor = void(STDMETHODCALLTYPE*)(void*, void*); + const auto close_monitor = reinterpret_cast(slot(pk, 6)); + void* monitor = nullptr; + void* other = reinterpret_cast(1); + check(reinterpret_cast(slot(pk, 5))(pk, own, 2, selectors, 1000, nullptr, &monitor) == S_OK && + monitor != nullptr && + reinterpret_cast(slot(pk, 5))(pk, "NotInstalled_0000000000000000000", 0, nullptr, + 0, nullptr, &other) == no_package && + other == nullptr && + reinterpret_cast(slot(pk, 5))(pk, own, 0, nullptr, 0, nullptr, nullptr) == E_POINTER, + "slot 5 (XPackageCreateInstallationMonitor): a monitor for the process's package, none for another"); + Progress watched{~0ull, 7, 7, false, false}; + reinterpret_cast(slot(pk, 7))(pk, monitor, &watched); + check(watched.completed && watched.launchable && watched.total != 0 && watched.installed == watched.total && + !reinterpret_cast(slot(pk, 8))(pk, monitor), + "slots 7/8 on that monitor: complete, and the update reports no change"); + + using RegisterProgress = HRESULT(STDMETHODCALLTYPE*)(void*, void*, void*, void*, XTaskQueueRegistrationToken*); + using ProgressCallback = void(CALLBACK*)(void*, void*); + static std::atomic s_progress_calls{0}; + const ProgressCallback on_progress = [](void*, void*) { s_progress_calls.fetch_add(1); }; + XTaskQueueRegistrationToken t1{0}, t2{0}; + const auto register_progress = reinterpret_cast(slot(pk, 9)); + check(register_progress(pk, monitor, nullptr, reinterpret_cast(on_progress), &t1) == S_OK && + register_progress(pk, monitor, nullptr, reinterpret_cast(on_progress), &t2) == S_OK && + t1.token != 0 && t2.token != 0 && t1.token != t2.token && + register_progress(pk, monitor, nullptr, nullptr, &t1) == E_INVALIDARG && + reinterpret_cast(slot(pk, 10))(pk, monitor, t2, true) && + s_progress_calls.load() == 0, + "slot 9 (XPackageRegisterInstallationProgressChanged): S_OK, distinct non-zero tokens, no callback"); + close_monitor(pk, monitor); + close_monitor(pk, monitor); // a second close frees nothing + close_monitor(pk, nullptr); + check(true, "slot 6 (XPackageCloseInstallationMonitorHandle) closes it; a second close or null is ignored"); + + using Find = HRESULT(STDMETHODCALLTYPE*)(void*, const char*, uint32_t, const Selector*, uint32_t*); + const auto find = reinterpret_cast(slot(pk, 12)); + uint32_t a1 = 9, a2 = 9, a3 = 9; + check(find(pk, own, 2, selectors, &a1) == S_OK && a1 == 0 && find(pk, own, 0, nullptr, &a2) == S_OK && + a2 == 0 && find(pk, "NotInstalled_0000000000000000000", 1, selectors, &a3) == no_package && + a3 == 9 && find(pk, nullptr, 1, selectors, &a3) == E_INVALIDARG && + find(pk, own, 1, selectors, nullptr) == E_POINTER, + "slot 12 (XPackageFindChunkAvailability): Ready (0) for any selector of the process's package"); + + using Enumerate = HRESULT(STDMETHODCALLTYPE*)(void*, const char*, uint32_t, void*, + bool(CALLBACK*)(void*, const Selector*, uint32_t)); + struct Seen { + int calls = 0; + bool all_ready = true; + std::string languages; + } seen; + const auto on_chunk = [](void* ctx, const Selector* s, uint32_t availability) -> bool { + auto* out = static_cast(ctx); + ++out->calls; + out->all_ready = out->all_ready && availability == 0 && s && s->type == 0; + if (s && s->type == 0 && s->text) out->languages += std::string(s->text) + ";"; + return true; + }; + const auto enumerate = reinterpret_cast(slot(pk, 13)); + char tmp2[MAX_PATH] = {}; + GetTempPathA(sizeof(tmp2), tmp2); + const std::string chunk_game = std::string(tmp2) + "leonida_xpackage_chunk_test"; + CreateDirectoryA(chunk_game.c_str(), nullptr); + SetEnvironmentVariableA("LEONIDA_GAME_DIR", chunk_game.c_str()); + if (FILE* f = std::fopen((chunk_game + "\\MicrosoftGame.Config").c_str(), "wb")) { + std::fputs("", f); + std::fclose(f); + } + const HRESULT languages_hr = enumerate(pk, own, 0, &seen, on_chunk); + Seen chunks; + check(languages_hr == S_OK && seen.calls == 2 && seen.all_ready && seen.languages == "aa-AA;bb-BB;" && + enumerate(pk, own, 2, &chunks, on_chunk) == S_OK && chunks.calls == 0 && + enumerate(pk, own, 9, &chunks, on_chunk) == E_INVALIDARG && + enumerate(pk, own, 0, &chunks, nullptr) == E_INVALIDARG && + enumerate(pk, "NotInstalled_0000000000000000000", 0, &chunks, on_chunk) == no_package, + "slot 13 (XPackageEnumerateChunkAvailability): the declared languages, each Ready; nothing pending"); + DeleteFileA((chunk_game + "\\MicrosoftGame.Config").c_str()); + RemoveDirectoryA(chunk_game.c_str()); + SetEnvironmentVariableA("LEONIDA_GAME_DIR", nullptr); + + using Order = HRESULT(STDMETHODCALLTYPE*)(void*, const char*, uint32_t, const Selector*); + check(reinterpret_cast(slot(pk, 14))(pk, own, 2, selectors) == S_OK && + reinterpret_cast(slot(pk, 14))(pk, "NotInstalled_0000000000000000000", 2, selectors) == + no_package, + "slot 14 (XPackageChangeChunkInstallOrder): S_OK"); + + using Install = HRESULT(STDMETHODCALLTYPE*)(void*, const char*, uint32_t, const Selector*, uint32_t, bool, + XTaskQueueHandle, void**); + void* installed = nullptr; + check(reinterpret_cast(slot(pk, 15))(pk, own, 2, selectors, 500, true, nullptr, &installed) == + S_OK && installed != nullptr, + "slot 15 (XPackageInstallChunks): S_OK with a monitor"); + close_monitor(pk, installed); + + using InstallAsync = HRESULT(STDMETHODCALLTYPE*)(void*, const char*, uint32_t, const Selector*, uint32_t, + bool, XAsyncBlock*); + using InstallResult = HRESULT(STDMETHODCALLTYPE*)(void*, XAsyncBlock*, void**); + const auto install_async = reinterpret_cast(slot(pk, 16)); + const auto install_result = reinterpret_cast(slot(pk, 17)); + XAsyncBlock install_block{}; + void* async_monitor = nullptr; + check(install_async(pk, own, 2, selectors, 500, false, &install_block) == S_OK && + XAsyncGetStatus(&install_block, true) == S_OK && + install_result(pk, &install_block, &async_monitor) == S_OK && async_monitor != nullptr, + "slots 16/17 (XPackageInstallChunksAsync/Result): the block completes with S_OK, the result is a monitor"); + close_monitor(pk, async_monitor); + XAsyncBlock missing_block{}; + void* missing_monitor = reinterpret_cast(1); + check(install_async(pk, "NotInstalled_0000000000000000000", 1, selectors, 0, false, &missing_block) == S_OK && + XAsyncGetStatus(&missing_block, true) == no_package && + install_result(pk, &missing_block, &missing_monitor) == no_package && missing_monitor == nullptr, + "slots 16/17 for a package that is not installed complete with E_GAMEPACKAGE_NO_PACKAGE_IDENTIFIER"); + + using Estimate = HRESULT(STDMETHODCALLTYPE*)(void*, const char*, uint32_t, const Selector*, uint64_t*, bool*); + uint64_t download = 77; + bool confirm = true; + check(reinterpret_cast(slot(pk, 18))(pk, own, 2, selectors, &download, &confirm) == S_OK && + download == 0 && !confirm, + "slot 18 (XPackageEstimateDownloadSize): 0 bytes, no user confirmation"); + + using UninstallChunks = HRESULT(STDMETHODCALLTYPE*)(void*, const char*, uint32_t, const Selector*); + uint32_t after = 9; + check(reinterpret_cast(slot(pk, 19))(pk, own, 2, selectors) == S_OK && + find(pk, own, 2, selectors, &after) == S_OK && after == 0, + "slot 19 (XPackageUninstallChunks): S_OK, and the chunks stay Ready"); + + // Slots 37/38, XPackageMountWithUiAsync/Result: a mapped content package mounts as slot 23 mounts it; + // any other identifier completes with E_GAMEPACKAGE_NO_PACKAGE_IDENTIFIER. + using MountUiAsync = HRESULT(STDMETHODCALLTYPE*)(void*, const char*, XAsyncBlock*); + using MountUiResult = HRESULT(STDMETHODCALLTYPE*)(void*, XAsyncBlock*, uint64_t*); + using MountPathSize = HRESULT(STDMETHODCALLTYPE*)(void*, uint64_t, size_t*); + const auto mount_ui = reinterpret_cast(slot(pk, 37)); + const auto mount_ui_result = reinterpret_cast(slot(pk, 38)); + SetEnvironmentVariableA("LEONIDA_CONTENT_PACKAGES", "UIDLC_1234567890123456789012345=C:\\LeonidaUiDLC"); + XAsyncBlock ui_block{}; + uint64_t ui_mount = 0; + size_t ui_need = 0; + check(mount_ui(pk, "UIDLC_1234567890123456789012345", &ui_block) == S_OK && + XAsyncGetStatus(&ui_block, true) == S_OK && + mount_ui_result(pk, &ui_block, &ui_mount) == S_OK && ui_mount != 0 && + reinterpret_cast(slot(pk, 24))(pk, ui_mount, &ui_need) == S_OK && + ui_need == std::strlen("C:\\LeonidaUiDLC") + 1, + "slots 37/38 mount a mapped content package and hand out its mount handle"); + reinterpret_cast(slot(pk, 26))(pk, ui_mount); + SetEnvironmentVariableA("LEONIDA_CONTENT_PACKAGES", nullptr); + XAsyncBlock ui_missing{}; + uint64_t ui_none = 7; + check(mount_ui(pk, "NotInstalled_0000000000000000000", &ui_missing) == S_OK && + XAsyncGetStatus(&ui_missing, true) == no_package && + mount_ui_result(pk, &ui_missing, &ui_none) == no_package && ui_none == 0 && + mount_ui(pk, nullptr, &ui_missing) == E_INVALIDARG, + "slots 37/38 for a package that is not installed complete with E_GAMEPACKAGE_NO_PACKAGE_IDENTIFIER"); + } const GUID chain[] = { package_cls, {0x3720de07, 0xe8e4, 0x44a3, {0xad, 0x32, 0xb3, 0x59, 0xe8, 0xad, 0xbe, 0x55}}, {0xf92d8712, 0x2b27, 0x4d8a, {0xbf, 0x01, 0x11, 0xa6, 0xf8, 0xe3, 0xeb, 0x42}}, - package3}; + package3, + // IXPackageImpl4, the id the retail executable's 18 XPackage thunks ask for. + {0x0b9d556e, 0xab70, 0x43f4, {0xba, 0xa0, 0x99, 0x99, 0xac, 0x4c, 0xb0, 0x40}}}; bool all = true; for (const GUID& iid : chain) { void* same = nullptr; all = all && query(&package_cls, iid, &same) == S_OK && same == pk; if (same) release(same); } - check(all, "IXPackageImpl3 answers for IXPackageImpl and IXPackageImpl2 too"); + check(all, "the object answers for IXPackageImpl, IXPackageImpl2, IXPackageImpl3 and IXPackageImpl4"); release(pk); } { diff --git a/runtime/test/xgameruntime_user_test.cpp b/runtime/test/xgameruntime_user_test.cpp index 3a9b4c8e07..54e38a2487 100644 --- a/runtime/test/xgameruntime_user_test.cpp +++ b/runtime/test/xgameruntime_user_test.cpp @@ -6,9 +6,12 @@ // xgameruntime_user_test --expect-gamertag TAG the same, run with LEONIDA_GAMERTAG=TAG #include +#include + #include #include #include +#include #include #include @@ -54,6 +57,59 @@ template F at(void* obj, int index) { return reinterpret_cast(slot( // Waits for an XAsyncBlock on the process queue, as a title polling XAsyncGetStatus(wait = true) does. bool finished(XAsyncBlock* async) { return XAsyncGetStatus(async, true) != E_PENDING; } +// Sends stderr, where the shim's "[rt] xgameruntime: XUser ... first call" lines go, to a temporary file until +// finish(), which returns what was written. +struct StderrCapture { + char path[MAX_PATH] = {}; + int saved = -1; + StderrCapture() { + char dir[MAX_PATH] = {}; + GetTempPathA(sizeof(dir), dir); + GetTempFileNameA(dir, "xur", 0, path); + std::fflush(stderr); + saved = _dup(2); + std::FILE* out = nullptr; + if (fopen_s(&out, path, "wb") == 0 && out) { + if (saved >= 0) _dup2(_fileno(out), 2); + std::fclose(out); + } + } + std::string finish() { + std::fflush(stderr); + if (saved >= 0) { + _dup2(saved, 2); + _close(saved); + saved = -1; + } + std::string text; + std::FILE* in = nullptr; + if (fopen_s(&in, path, "rb") == 0 && in) { + char chunk[4096]; + for (size_t n; (n = std::fread(chunk, 1, sizeof(chunk), in)) > 0;) text.append(chunk, n); + std::fclose(in); + } + DeleteFileA(path); + return text; + } + ~StderrCapture() { finish(); } +}; + +int count_of(const std::string& text, const std::string& needle) { + int count = 0; + for (size_t at = text.find(needle); at != std::string::npos; at = text.find(needle, at + 1)) ++count; + return count; +} + +// The line of `text` that contains `needle`, or "" when none does. +std::string line_with(const std::string& text, const std::string& needle) { + const size_t at = text.find(needle); + if (at == std::string::npos) return {}; + const size_t newline_before = text.rfind('\n', at); + const size_t begin = newline_before == std::string::npos ? 0 : newline_before + 1; + const size_t end = text.find('\n', at); + return text.substr(begin, end == std::string::npos ? std::string::npos : end - begin); +} + } // namespace int main(int argc, char** argv) { @@ -81,6 +137,10 @@ int main(int argc, char** argv) { check(query(&kUserClass, kOther, &none) == E_NOINTERFACE && none == nullptr, "an interface the class doesn't have is E_NOINTERFACE with a cleared out pointer"); + // Every call from here to the gamertag checks is the slot's first in this process: its first-call lines are read + // back below. + StderrCapture capture; + // ---- XUserAddAsync / XUserAddResult (slots 7, 8) ---- using AddAsync = HRESULT(STDMETHODCALLTYPE*)(void*, uint32_t, XAsyncBlock*); using AddResult = HRESULT(STDMETHODCALLTYPE*)(void*, XAsyncBlock*, XUserHandle*); @@ -209,6 +269,25 @@ int main(int argc, char** argv) { "a buffer one byte short is E_INSUFFICIENT_BUFFER"); check(tag(tag_face, h, 7, sizeof(buf), buf, &used) == E_INVALIDARG, "an unknown component is E_INVALIDARG"); + // ---- first-call lines: one per slot (per gamertag component), whatever the number of calls ---- + const std::string log = capture.finish(); + std::fputs(log.c_str(), stdout); + check(count_of(log, "[rt] xgameruntime: XUser AddAsync first call: options 0x1,") == 1 && + count_of(log, "XUser AddAsync first call") == 1, + "XUserAddAsync logs its first call (options 0x1) once, not for the two calls after it"); + check(count_of(log, "[rt] xgameruntime: XUser AddResult first call:") == 1 && + count_of(log, "[rt] xgameruntime: XUser CheckPrivilege first call:") == 1 && + count_of(log, "[rt] xgameruntime: XUser GetState first call:") == 1 && + count_of(log, "[rt] xgameruntime: XUser RegisterForChangeEvent first call:") == 1, + "AddResult, CheckPrivilege, GetState and RegisterForChangeEvent log their first call once"); + const std::string classic = line_with(log, "[rt] xgameruntime: XUser GetGamertag first call: Classic (0)"); + check(count_of(log, "XUser GetGamertag first call: Classic (0)") == 1 && + classic.find(std::string("-> 0x00000000, \"") + expect_tag + "\"") != std::string::npos, + "XUserGetGamertag logs the first Classic call once, with S_OK and the gamertag (not the short-buffer call)"); + check(count_of(log, "[rt] xgameruntime: XUser GetGamertag first call:") == 5 && + line_with(log, "GetGamertag first call: unknown component (7)").find("0x80070057") != std::string::npos, + "one GetGamertag line per component asked for (four, and the unknown one with E_INVALIDARG)"); + // ---- handles: duplicate, close, all accounted for (3, 4) ---- using Dup = HRESULT(STDMETHODCALLTYPE*)(void*, XUserHandle, XUserHandle*); using Close = void(STDMETHODCALLTYPE*)(void*, XUserHandle); diff --git a/runtime/test/xmem_test.cpp b/runtime/test/xmem_test.cpp index 0c151bb9c7..3ed069fdfa 100644 --- a/runtime/test/xmem_test.cpp +++ b/runtime/test/xmem_test.cpp @@ -9,14 +9,18 @@ // graphics protection bits and commits 2 MiB guest pages; the placeholder flags pass through; physical pages keep their // contents across unmap and remap, alias when mapped twice, and scatter-map per address. #include +#include #include #include #include #include +#include #include #include +#include #include +#include #include #include #include @@ -25,6 +29,38 @@ #include "shims.h" #include "startup_trace.h" #include "xmem.h" +#include "../src/title_page_watch.h" + +// The process heap as test_heap_lock_faults needs it (the same gate as d3d12_existing_heap_test's): an allocation that +// waits while a thread holds the heap's lock. The NT heap's low-fragmentation front end serves most small sizes +// without that lock, so a real deadlock waits for an allocation its back end serves, which a short test can't count +// on. Here, while the gate is on, every operator new and delete of the program (xmem.cpp's included) takes +// g_heap_gate shared, and the test's "title" threads that hold the heap's lock hold the gate exclusively: any +// allocation xmem makes while it holds a lock its fault handler waits for then deadlocks at once. +namespace { +SRWLOCK g_heap_gate = SRWLOCK_INIT; +std::atomic g_heap_gate_on{false}; +struct HeapGate { + const bool on = g_heap_gate_on.load(std::memory_order_acquire); + HeapGate() { + if (on) AcquireSRWLockShared(&g_heap_gate); + } + ~HeapGate() { + if (on) ReleaseSRWLockShared(&g_heap_gate); + } +}; +} // namespace + +void* operator new(std::size_t bytes) { + HeapGate gate; + if (void* p = std::malloc(bytes ? bytes : 1)) return p; + throw std::bad_alloc(); +} +void operator delete(void* p) noexcept { + HeapGate gate; + std::free(p); +} +void operator delete(void* p, std::size_t) noexcept { operator delete(p); } namespace { @@ -395,17 +431,38 @@ void test_physical_pages(const PhysicalApi& api) { } check(numbers_ok, "page numbers are distinct non-zero multiples of 16 below 2^25"); + auto generation = leonida::title_memory_map::generation(); check(api.map(window, kPages, pages) == window, "XMemMapPhysicalPages returns the address it mapped"); + check(leonida::title_memory_map::generation() != generation, "mapping physical pages invalidates shadows"); for (uint64_t i = 0; i < kPages; ++i) fill_page(window + i * kPage64k, 0x1000u * static_cast(i + 1)); { MEMORY_BASIC_INFORMATION info{}; VirtualQuery(window, &info, sizeof(info)); check(info.State == MEM_COMMIT && info.Type == MEM_MAPPED && info.Protect == PAGE_READWRITE, "a mapped page is a read-write view with the window's protection"); + check(info.AllocationBase == window && info.RegionSize == kPages * kPage64k, + "consecutive pages of one allocation are mapped as one view"); } + // A page unmapped or remapped inside that view splits it; its neighbours keep their pages. + void* const middle = window + kPage64k; + generation = leonida::title_memory_map::generation(); + check(api.scatter(&middle, 1, nullptr) == TRUE && reserved_only(window + kPage64k), + "a page inside a view unmaps on its own"); + check(page_holds(window, 0x1000u) && page_holds(window + 2 * kPage64k, 0x3000u) && + page_holds(window + 3 * kPage64k, 0x4000u), + "the pages around it stay mapped with their contents"); + check(leonida::title_memory_map::generation() != generation, "scatter unmapping invalidates shadows"); + check(api.map(middle, 1, &pages[1]) == middle && page_holds(window + kPage64k, 0x2000u), + "a page maps again into the gap"); + check(api.map(window, kPages, nullptr) == window, "XMemMapPhysicalPages with no page array unmaps"); check(reserved_only(window) && reserved_only(window + 3 * kPage64k), "unmapped pages are reserved again"); + // The split above left the range as several host placeholders; the whole run maps again over them. + check(api.map(window, kPages, pages) == window && page_holds(window, 0x1000u) && + page_holds(window + 3 * kPage64k, 0x4000u), + "a run maps again over a range an earlier partial unmap split"); + check(api.map(window, kPages, nullptr) == window && reserved_only(window), "and unmaps again"); // Remap in reverse order into the other window: each page keeps its contents. uint64_t reversed[kPages]; @@ -650,9 +707,11 @@ void test_first_touch_during_remap(const PhysicalApi& api) { std::atomic stop{false}; std::atomic touches{0}; std::atomic unmapped_faults{0}; + std::atomic started_writers{0}; std::vector writers; for (int t = 0; t < 4; ++t) { writers.emplace_back([&, t] { + started_writers.fetch_add(1); uint64_t i = static_cast(t); while (!stop.load(std::memory_order_relaxed)) { auto* const word = @@ -666,6 +725,8 @@ void test_first_touch_during_remap(const PhysicalApi& api) { } }); } + // The remaps can finish before a writer is scheduled on a fast host, so wait for all four to run first. + while (started_writers.load() < 4) Sleep(0); const ULONGLONG started = GetTickCount64(); bool remapped = true; for (uint64_t s = 0; s < kSlices; ++s) { @@ -674,6 +735,8 @@ void test_first_touch_during_remap(const PhysicalApi& api) { remapped &= api.map(window, kSlice, nullptr) == window; } remapped &= api.map(window, kSlice, pages.data() + (kSlices - 1) * kSlice) == window; + // The last slice stays mapped: give the writers up to a second to land a write in it before stopping them. + for (const ULONGLONG until = GetTickCount64() + 1000; touches.load() == 0 && GetTickCount64() < until;) Sleep(1); stop.store(true); for (auto& writer : writers) writer.join(); const ULONGLONG elapsed = GetTickCount64() - started; @@ -689,6 +752,102 @@ void test_first_touch_during_remap(const PhysicalApi& api) { check(api.free_pages(count, pages.data()) == TRUE, "XMemFreePhysicalPages frees the remap race pages"); } +// Splitting a view briefly unmaps the view's other pages; a thread reading one of them meanwhile must not fault. +// Unmapping page k of the view [k, end) splits it every time, and the last page of each view is the one being read. +void test_split_under_reader(const PhysicalApi& api) { + constexpr uint64_t kPages = 2048; // two capped views + auto* const window = static_cast( + api.virtual_alloc(nullptr, kPages * kPage64k, MEM_RESERVE | kXmem64kPages, 0x23, PAGE_READWRITE)); + std::vector pages(kPages); + uint64_t count = kPages; + check(window && api.allocate(0x280, &count, pages.data()) == TRUE && count == kPages && + api.map(window, kPages, pages.data()) == window, + "a 2,048-page run maps for the split test"); + if (!window || count != kPages) return; + uint8_t* const read_pages[2] = {window + 1023 * kPage64k, window + 2047 * kPage64k}; + fill_page(read_pages[0], 0x11000u); + fill_page(read_pages[1], 0x11000u); + std::atomic done{false}; + std::atomic reads{0}, wrong{0}; + std::thread reader([&] { + for (uint64_t i = 0; !done.load(std::memory_order_relaxed); ++i) { + wrong += read_u32(read_pages[i & 1], 0) != 0x11000u; + ++reads; + } + }); + bool unmapped = true; + for (uint64_t k = 0; k < kPages - 1; ++k) { + if (k == 1023) continue; + void* const page = window + k * kPage64k; + unmapped &= api.scatter(&page, 1, nullptr) == TRUE; + } + done = true; + reader.join(); + check(unmapped, "2,046 pages unmap one at a time, each splitting the view a reader is in"); + check(reads.load() > 0 && wrong.load() == 0, "the reader of the views' last pages never faults or misreads"); + // The last split was of [2046, 2048): a fault there is retried, one on another mapped page is not. + api.map(window, kPages, nullptr); + api.free_pages(kPages, pages.data()); +} + +// A run longer than one host view is mapped as capped views, so unmapping one page inside it only remaps the rest of +// that view; every other page keeps its contents. +void test_long_run(const PhysicalApi& api) { + constexpr uint64_t kPages = 1100; // more than the 1024-page view cap + auto* const window = static_cast( + api.virtual_alloc(nullptr, kPages * kPage64k, MEM_RESERVE | kXmem64kPages, 0x23, PAGE_READWRITE)); + std::vector pages(kPages); + uint64_t count = kPages; + check(window && api.allocate(0x280, &count, pages.data()) == TRUE, "a long run's window and pages are allocated"); + if (!window || count != kPages) return; + check(api.map(window, kPages, pages.data()) == window, "a run longer than the view cap maps"); + // The pages are committed on first touch, so an untouched view reads MEM_RESERVE on Windows (Wine reports + // MEM_COMMIT); either way the first region is one mapped view of exactly the cap. + MEMORY_BASIC_INFORMATION info{}; + VirtualQuery(window, &info, sizeof(info)); + check(info.Type == MEM_MAPPED && (info.State == MEM_COMMIT || info.State == MEM_RESERVE) && + info.RegionSize == 1024 * kPage64k, + "it is mapped as views of at most 1024 pages"); + for (uint64_t i = 0; i < kPages; ++i) fill_page(window + i * kPage64k, static_cast(i + 1)); + void* const hole = window + 10 * kPage64k; + check(api.scatter(&hole, 1, nullptr) == TRUE && reserved_only(hole), "a page inside the first view unmaps"); + bool kept = true; + for (uint64_t i = 0; i < kPages; ++i) { + if (i != 10) kept &= page_holds(window + i * kPage64k, static_cast(i + 1)); + } + check(kept, "every other page of the run keeps its contents"); + // Several pages across the boundary of two capped views unmap together; the pages on both sides stay. + check(api.map(window + 1000 * kPage64k, 50, nullptr) == window + 1000 * kPage64k && + reserved_only(window + 1000 * kPage64k) && reserved_only(window + 1049 * kPage64k), + "a multi-page range across two views unmaps"); + check(page_holds(window + 999 * kPage64k, 1000u) && page_holds(window + 1050 * kPage64k, 1051u), + "the pages on both sides of it keep their contents"); + // Mapping other pages over the middle of a live run replaces just those pages. + check(api.map(window + 500 * kPage64k, 3, &pages[600]) == window + 500 * kPage64k && + page_holds(window + 500 * kPage64k, 601u) && page_holds(window + 502 * kPage64k, 603u), + "pages mapped over the middle of a live run replace it there"); + check(page_holds(window + 499 * kPage64k, 500u) && page_holds(window + 503 * kPage64k, 504u), + "and the run's pages around them keep their contents"); + check(api.map(window, kPages, nullptr) == window && reserved_only(window) && + reserved_only(window + (kPages - 1) * kPage64k), + "the whole run unmaps"); + check(api.free_pages(kPages, pages.data()) == TRUE, "the long run's pages are freed"); + check(api.map(window, 1, pages.data()) == nullptr && reserved_only(window), "a freed page does not map again"); + // Pages freed while still mapped keep their memory, and splitting their view later still maps the rest again. + count = 4; + check(api.allocate(0x280, &count, pages.data()) == TRUE && count == 4 && api.map(window, 4, pages.data()) == window, + "four pages map as one view"); + if (count != 4) return; + for (uint64_t i = 0; i < 4; ++i) fill_page(window + i * kPage64k, static_cast(i + 1)); + check(api.free_pages(4, pages.data()) == TRUE, "they are freed while mapped"); + void* const second = window + kPage64k; + check(api.scatter(&second, 1, nullptr) == TRUE && !reserved_only(window) && + !reserved_only(window + 2 * kPage64k) && page_holds(window, 1u) && + page_holds(window + 2 * kPage64k, 3u) && page_holds(window + 3 * kPage64k, 4u), + "unmapping one of them afterwards keeps the others' memory"); + api.map(window, 4, nullptr); +} + // The placeholder flags pass through: reserve a placeholder, carve windows and committed memory out of it. void test_placeholders(const PhysicalApi& api) { auto* const base = static_cast( @@ -740,19 +899,181 @@ void test_write_combine_window(const PhysicalApi& api) { const bool mapped = api.map(window, 1, &page) == window; check(mapped, "a page maps into a window reserved with PAGE_WRITECOMBINE"); if (mapped) { - // Physical pages are committed on first touch, so the view is written before it is queried. - *static_cast(window) = 1; + // Queried after the first touch: the page is committed lazily, and an untouched view reads MEM_RESERVE + // with no protection on Windows. + fill_page(window, 0x77000000u); MEMORY_BASIC_INFORMATION info{}; VirtualQuery(window, &info, sizeof(info)); check(info.State == MEM_COMMIT && info.Protect == PAGE_READWRITE, "the page mapped there is a plain read-write view"); - fill_page(window, 0x77000000u); check(page_holds(window, 0x77000000u), "the page in the write-combine window holds data"); } check(api.map(window, 1, nullptr) == window, "unmap the write-combine window"); check(api.free_pages(1, &page) == TRUE, "free the write-combine window's page"); } +// Counts the access violations in [g_counted_begin, g_counted_end). Added after xmem's handler with First = 1, so it +// runs before it and sees every fault there, the ones xmem then commits included. +std::atomic g_counted_begin{0}, g_counted_end{0}; +std::atomic g_counted_faults{0}; + +LONG CALLBACK count_window_faults(EXCEPTION_POINTERS* info) { + const EXCEPTION_RECORD* record = info ? info->ExceptionRecord : nullptr; + if (record && record->ExceptionCode == EXCEPTION_ACCESS_VIOLATION && record->NumberParameters >= 2) { + const auto at = static_cast(record->ExceptionInformation[1]); + if (at >= g_counted_begin.load(std::memory_order_relaxed) && at < g_counted_end.load(std::memory_order_relaxed)) + g_counted_faults.fetch_add(1, std::memory_order_relaxed); + } + return EXCEPTION_CONTINUE_SEARCH; +} + +// About `us` microseconds of spinning, without a call that could allocate. +void spin_for(LONGLONG us) { + LARGE_INTEGER now{}, frequency{}; + QueryPerformanceFrequency(&frequency); + QueryPerformanceCounter(&now); + const LONGLONG until = now.QuadPart + frequency.QuadPart * us / 1000000; + while (QueryPerformanceCounter(&now) && now.QuadPart < until) YieldProcessor(); +} + +// Title threads take access violations while they hold the process heap's lock: XMemAlloc is _aligned_malloc, so +// HeapAlloc and HeapFree write block headers on title pages, which may be physical pages waiting for their first touch +// or pages the D3D12 layer's shadows guard. xmem's handler waits for g_fault_lock (shared) at every access violation, +// its own or not, so whoever holds that lock exclusively (a map or an unmap of physical pages) must never wait for the +// process heap meanwhile: it would wait for the faulting thread, which waits for it. While +// - threads take the process heap's lock (HeapLock, as HeapAlloc does inside, and the heap gate above) and, holding +// it, _aligned_malloc and _aligned_free and write a word into every page of a window whose pages are mapped fresh +// all the time (a first-touch commit, or a fault on a page that is being unmapped) and into a read-only page (a +// fault that isn't xmem's, as on a guarded shadow page); +// - threads allocate physical pages, map them into their part of the window (as a run, or page by page through the +// scatter call), and unmap and free them, some freed while still mapped so that the unmap drops the last +// reference to their section; +// a watchdog ends the process (exit code 3) when nothing got anywhere for 30 s: a deadlock. +void test_heap_lock_faults(const PhysicalApi& api) { + if (const HMODULE ntdll = GetModuleHandleW(L"ntdll.dll"); ntdll && GetProcAddress(ntdll, "wine_get_version")) { + // Under Wine a holder of the fault lock still reaches the process heap through the host's own view calls (or + // Wine's fault dispatch needs it): the test deadlocks there with the fix in. The Wine side is an open item. + std::printf("SKIP heap-lock faults under Wine: a fault-lock holder still waits for the process heap there\n"); + return; + } + constexpr uint64_t kMappers = 2, kSlice = 4, kPages = kMappers * kSlice; + constexpr unsigned kTouchers = 3; + auto* const window = static_cast( + api.virtual_alloc(nullptr, kPages * kPage64k, MEM_RESERVE | kXmem64kPages, 0x21, PAGE_READWRITE)); + auto* const read_only = static_cast(VirtualAlloc(nullptr, 0x1000, MEM_RESERVE | MEM_COMMIT, PAGE_READONLY)); + check(window != nullptr && read_only != nullptr, "a window and a read-only page for the heap-lock faults"); + if (!window || !read_only) return; + g_counted_begin = reinterpret_cast(window); + g_counted_end = reinterpret_cast(window) + kPages * kPage64k; + g_counted_faults = 0; + // xmem's handler is in by now (the first XMemAllocatePhysicalPages put it in), so this one runs first. + void* const counter = AddVectoredExceptionHandler(1, &count_window_faults); + check(counter != nullptr, "a fault counter in front of xmem's handler"); + if (!counter) return; + + std::atomic progress{0}; // bumped by every round of every thread + std::atomic stop{false}, finished{false}, failed{false}; + std::thread watchdog([&] { + uint64_t seen = progress.load(); + ULONGLONG since = GetTickCount64(); + while (!finished.load()) { + Sleep(100); + const uint64_t now = progress.load(); + if (now != seen) { + seen = now; + since = GetTickCount64(); + } else if (GetTickCount64() - since > 30000) { + // No heap here: the process heap may be what is stuck. + static const char message[] = + "xmem heap-lock faults: no progress for 30 s: deadlock (a holder of the lock xmem's fault handler " + "waits for is waiting for the process heap)\n"; + DWORD wrote = 0; + WriteFile(GetStdHandle(STD_ERROR_HANDLE), message, DWORD(sizeof(message) - 1), &wrote, nullptr); + TerminateProcess(GetCurrentProcess(), 3); + } + } + }); + std::atomic rounds{0}, missed{0}, read_only_faults{0}, maps{0}; + std::vector threads; + threads.reserve(kTouchers + kMappers); + g_heap_gate_on = true; + for (unsigned t = 0; t < kTouchers; ++t) + threads.emplace_back([&, t] { + const HANDLE heap = GetProcessHeap(); + for (unsigned round = 0; !stop.load(std::memory_order_relaxed); ++round) { + uint64_t round_missed = 0; + bool round_read_only = false; + AcquireSRWLockExclusive(&g_heap_gate); + HeapLock(heap); + void* block = _aligned_malloc(64 + (round % 32) * 160, 16); + for (uint64_t p = 0; p < kPages; ++p) { + auto* const word = + static_cast(static_cast(window + p * kPage64k)) + t; + round_missed += access_faults(word, true); + } + round_read_only = access_faults(static_cast(static_cast(read_only)), true); + _aligned_free(block); + HeapUnlock(heap); + ReleaseSRWLockExclusive(&g_heap_gate); + missed.fetch_add(round_missed, std::memory_order_relaxed); + read_only_faults.fetch_add(round_read_only, std::memory_order_relaxed); + rounds.fetch_add(1, std::memory_order_relaxed); + progress.fetch_add(1, std::memory_order_relaxed); + spin_for(50); // the other threads get to allocate + } + }); + for (uint64_t m = 0; m < kMappers; ++m) + threads.emplace_back([&, m] { + uint8_t* const slice = window + m * kSlice * kPage64k; + uint64_t pages[kSlice]{}; + void* addresses[kSlice]{}; + for (uint64_t k = 0; k < kSlice; ++k) addresses[k] = slice + k * kPage64k; + for (uint64_t round = 0; !stop.load(std::memory_order_relaxed); ++round) { + uint64_t count = kSlice; + if (api.allocate(0x280, &count, pages) != TRUE || count != kSlice) { + failed = true; + break; + } + bool ok = round % 2 == 0 ? api.map(slice, kSlice, pages) == slice + : api.scatter(addresses, static_cast(kSlice), pages) == TRUE; + spin_for(100); // the touchers get to fault the fresh pages in + // Freed while mapped: the unmap then drops the last reference to the section. + const bool free_first = round % 3 == 0; + if (free_first) ok &= api.free_pages(kSlice, pages) == TRUE; + ok &= api.map(slice, kSlice, nullptr) == slice; + if (!free_first) ok &= api.free_pages(kSlice, pages) == TRUE; + if (!ok) { + failed = true; + break; + } + maps.fetch_add(1, std::memory_order_relaxed); + progress.fetch_add(1, std::memory_order_relaxed); + } + }); + for (const ULONGLONG until = GetTickCount64() + 3000; !failed.load() && GetTickCount64() < until;) Sleep(10); + stop = true; + for (std::thread& thread : threads) thread.join(); + g_heap_gate_on = false; + finished = true; + watchdog.join(); + RemoveVectoredExceptionHandler(counter); + g_counted_end = 0; + + const uint64_t window_faults = g_counted_faults.load(); + // A fault in the window that the toucher's own handler didn't catch is one xmem's handler resolved: a first touch + // (or a retry of one another toucher committed meanwhile). + const uint64_t committed = window_faults > missed.load() ? window_faults - missed.load() : 0; + check(!failed.load(), "physical pages allocate, map (run and scatter), unmap and free while faults hold the heap"); + check(maps.load() > 0 && rounds.load() > 0, "the mappers and the faulting threads both made progress"); + check(committed > 0, "threads holding the process heap's lock took first-touch faults xmem committed"); + check(read_only_faults.load() == rounds.load(), "every write to the read-only page faulted through xmem's handler"); + std::printf("heap-lock faults: %llu mappings, %llu rounds holding the process heap's lock, %llu first touches " + "committed, %llu faults on unmapped pages: no deadlock\n", + static_cast(maps.load()), static_cast(rounds.load()), + static_cast(committed), static_cast(missed.load())); + VirtualFree(read_only, 0, MEM_RELEASE); +} + // gta6rt --trace: one "xmem_attributes" event per distinct raw attribute word and API, none with the trace off. void test_attribute_trace(XMemAllocFn alloc, XMemFreeFn free_mem, XMemVirtualAllocFn virtual_alloc) { wchar_t temp[MAX_PATH]; @@ -883,6 +1204,8 @@ void test_transfer_trace(XMemTransferMemoryFn transfer) { } using HostVirtualAllocFn = void*(WINAPI*)(void*, SIZE_T, DWORD, DWORD); +using HostVirtualFreeFn = BOOL(WINAPI*)(void*, SIZE_T, DWORD); +using HostVirtualProtectFn = BOOL(WINAPI*)(void*, SIZE_T, DWORD, PDWORD); // RT-217: a title's kernel32!VirtualAlloc carries the console's MEM_GRAPHICS / MEM_TITLE type bits, which the host // rejects. The registered shim has to drop them and still allocate. @@ -892,18 +1215,30 @@ void test_title_virtual_alloc() { const char* const dlls[] = {"kernel32.dll", "kernelbase.dll", "api-ms-win-core-memory-l1-1-0.dll"}; for (const char* dll : dlls) { const auto alloc = reinterpret_cast(rt::shims::find(dll, "VirtualAlloc")); + const auto free = reinterpret_cast(rt::shims::find(dll, "VirtualFree")); + const auto protect = reinterpret_cast(rt::shims::find(dll, "VirtualProtect")); char what[160]; - std::snprintf(what, sizeof what, "registry exposes %s!VirtualAlloc", dll); - check(alloc != nullptr, what); - if (!alloc) continue; + std::snprintf(what, sizeof what, "registry exposes %s's virtual memory shims", dll); + check(alloc && free && protect, what); + if (!alloc || !free || !protect) continue; + auto generation = leonida::title_memory_map::generation(); void* const gfx = alloc(nullptr, 0x10000, MEM_RESERVE | MEM_COMMIT, 0x2004); // PAGE_GRAPHICS_READWRITE check(gfx != nullptr, "title VirtualAlloc with protect 0x2004 succeeds"); if (gfx) { + check(leonida::title_memory_map::generation() != generation, "title VirtualAlloc invalidates shadows"); MEMORY_BASIC_INFORMATION mbi{}; check(VirtualQuery(gfx, &mbi, sizeof mbi) && mbi.Protect == PAGE_READWRITE, "protect 0x2004 commits PAGE_READWRITE"); - VirtualFree(gfx, 0, MEM_RELEASE); + DWORD old = 0; + generation = leonida::title_memory_map::generation(); + check(protect(gfx, 0x1000, PAGE_READONLY, &old) && old == PAGE_READWRITE, + "title VirtualProtect changes protection and returns the previous protection"); + check(leonida::title_memory_map::generation() != generation, "title VirtualProtect invalidates shadows"); + generation = leonida::title_memory_map::generation(); + check(free(gfx, 0x1000, MEM_DECOMMIT), "title VirtualFree decommits a page"); + check(leonida::title_memory_map::generation() != generation, "title VirtualFree invalidates shadows"); + check(free(gfx, 0, MEM_RELEASE), "release the graphics allocation"); } for (const DWORD bits : {kMemGraphics, kMemTitle, kMemGraphics | kMemTitle, DWORD{0}}) { void* const p = alloc(nullptr, 0x10000, MEM_RESERVE | MEM_COMMIT | bits, PAGE_READWRITE); @@ -918,6 +1253,171 @@ void test_title_virtual_alloc() { } } +// The title's ordinary reservations are write-watched for the D3D12 layer's shadows (leonida::title_write_watch): +// XMemVirtualAlloc's plain, 2 MiB and 64 KiB committed regions and kernel32!VirtualAlloc's reservations, each recorded +// until the title releases it. Placeholders and physical-page windows are not (a section view can't be), nor is a +// region the title asked to be write-watched itself (its bits are the title's). With LEONIDA_WRITE_WATCH=0 (the +// xmem_no_write_watch test) nothing is. +void test_write_watched_reservations(XMemVirtualAllocFn virtual_alloc) { + const bool on = leonida::title_write_watch::enabled(); + std::printf("xmem_test: write watching %s\n", on ? "on" : "off (LEONIDA_WRITE_WATCH=0)"); + const auto kernel_watching = [](void* base, SIZE_T size) { + void* found[16]{}; + ULONG_PTR count = 16; + ULONG granularity = 0; + return GetWriteWatch(0, base, size, found, &count, &granularity) == 0; + }; + const auto title_free = reinterpret_cast(rt::shims::find("kernel32.dll", "VirtualFree")); + const auto title_alloc = reinterpret_cast(rt::shims::find("kernel32.dll", "VirtualAlloc")); + check(title_free && title_alloc, "registry exposes kernel32.dll's VirtualAlloc and VirtualFree shims"); + if (!title_free || !title_alloc) return; + struct Case { + const char* what; + DWORD type; + SIZE_T size; + bool watched; + }; + const Case cases[] = { + {"plain reserve+commit", MEM_RESERVE | MEM_COMMIT, 0x3000, true}, + {"commit at no address", MEM_COMMIT, 0x3000, true}, + {"reserve only", MEM_RESERVE, 0x20000, true}, + {"2 MiB pages", kXmemLargePages | MEM_RESERVE | MEM_COMMIT, kPage2m, true}, + {"64 KiB pages committed", kXmem64kPages | MEM_RESERVE | MEM_COMMIT, kPage64k * 2, true}, + {"64 KiB physical-page window", kXmem64kPages | MEM_RESERVE, kPage64k * 2, false}, + {"placeholder", MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, kPage64k * 2, false}, + {"the title's own write watch", MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, 0x3000, false}, + }; + for (const Case& c : cases) { + void* const base = virtual_alloc(nullptr, c.size, c.type, 0, PAGE_READWRITE); + char what[192]; + std::snprintf(what, sizeof what, "XMemVirtualAlloc %s succeeds", c.what); + check(base != nullptr, what); + if (!base) continue; + const auto at = reinterpret_cast(base); + const bool want = on && c.watched; + std::snprintf(what, sizeof what, "XMemVirtualAlloc %s: %s for the shadows", c.what, + want ? "recorded write-watched" : "not recorded"); + check(leonida::title_write_watch::contains(at) == want && + leonida::title_write_watch::contains(at + c.size - 1) == want, + what); + if (want) { + std::snprintf(what, sizeof what, "XMemVirtualAlloc %s: the kernel write-watches it", c.what); + check(kernel_watching(base, c.size), what); + } + if ((c.type & MEM_RESERVE_PLACEHOLDER) || ((c.type & kXmem64kPages) == kXmem64kPages && !(c.type & MEM_COMMIT))) { + VirtualFree(base, 0, MEM_RELEASE); + continue; + } + std::snprintf(what, sizeof what, "title VirtualFree releases the region (%s) and forgets it", c.what); + check(title_free(base, 0, MEM_RELEASE) && !leonida::title_write_watch::contains(at), what); + } + // kernel32!VirtualAlloc as the title calls it: a reservation is recorded, a commit inside it adds nothing. + void* const reserved = title_alloc(nullptr, 0x40000, MEM_RESERVE, PAGE_READWRITE); + check(reserved != nullptr, "title VirtualAlloc reserves"); + if (!reserved) return; + const auto at = reinterpret_cast(reserved); + const auto generation = leonida::title_write_watch::generation(); + check(title_alloc(reserved, 0x1000, MEM_COMMIT, PAGE_READWRITE) == reserved, "title VirtualAlloc commits in it"); + check(leonida::title_write_watch::generation() == generation, "a commit inside a reservation records nothing new"); + check(leonida::title_write_watch::contains(at + 0x3ffff) == on, + on ? "title VirtualAlloc's reservation is recorded write-watched" : "title VirtualAlloc's is not recorded"); + if (on) { + check(kernel_watching(reserved, 0x40000), "the kernel write-watches title VirtualAlloc's reservation"); + static_cast(reserved)[0x10] = 1; + void* found[4]{}; + ULONG_PTR count = 4; + ULONG granularity = 0; + check(GetWriteWatch(0, reserved, 0x40000, found, &count, &granularity) == 0 && count == 1 && + found[0] == reserved, + "a write to it is in the kernel's answer"); + } else { + check(!kernel_watching(reserved, 0x40000), "LEONIDA_WRITE_WATCH=0: the kernel does not write-watch it"); + } + check(title_free(reserved, 0, MEM_RELEASE) && !leonida::title_write_watch::contains(at), + "title VirtualFree releases it and forgets it"); +} + +// A reservation the title releases and reserves again at the same address is a new one to the shadows' journal +// (leonida::title_write_watch::ask): a reader that asked over the old one is told all of the new one's pages as +// written, though nothing wrote them (a new reservation's kernel bits are clear, and a MEM_RESERVE | MEM_COMMIT in one +// call marks nothing). Through kernel32!VirtualAlloc and XMemVirtualAlloc; a page decommitted and committed again +// inside a reservation is told as written too. And the title's XMemGetWriteWatch and XMemResetWriteWatch refuse a +// reservation write-watched for the shadows (on the console it is not write-watched, and a reset would clear the bits +// the shadows ask about): the journal still sees the write. +void test_write_watch_rereserve(XMemVirtualAllocFn virtual_alloc, XMemGetWriteWatchFn get_write_watch, + XMemResetWriteWatchFn reset_write_watch) { + if (!leonida::title_write_watch::enabled()) return; + namespace ww = leonida::title_write_watch; + const auto title_free = reinterpret_cast(rt::shims::find("kernel32.dll", "VirtualFree")); + const auto title_alloc = reinterpret_cast(rt::shims::find("kernel32.dll", "VirtualAlloc")); + if (!title_free || !title_alloc) return; + constexpr SIZE_T kSize = 0x10000; + // The pages of [base, base + kSize) the reader is told were written. + const auto told = [](std::uint64_t reader, void* base) { + const auto from = reinterpret_cast(base); + const std::vector> runs{{from, from + kSize}}; + size_t pages = 0; + ww::ask( + reader, runs, [&](uintptr_t a, uintptr_t b) { pages += (b - a) / ww::kPage; }, [](uintptr_t, uintptr_t) {}); + return pages; + }; + struct Way { + const char* what; + std::function reserve; // MEM_RESERVE | MEM_COMMIT at the address (null: anywhere) + }; + const Way ways[] = { + {"kernel32!VirtualAlloc", + [&](void* at) { return title_alloc(at, kSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); }}, + {"XMemVirtualAlloc", [&](void* at) { return virtual_alloc(at, kSize, MEM_RESERVE | MEM_COMMIT, 0, PAGE_READWRITE); }}, + }; + char what[192]; + for (const Way& way : ways) { + void* base = nullptr; + std::uint64_t reader = 0; + bool told_once = true, same_address = false; + // Another thread may take the range between the release and the new reservation: tried again elsewhere. + for (int attempt = 0; attempt < 8 && !same_address; ++attempt) { + base = way.reserve(nullptr); + if (!base) break; + reader = ww::open_reader(); + static_cast(base)[0x10] = 1; + told_once = told_once && told(reader, base) == 1 && told(reader, base) == 0; + void* const again = title_free(base, 0, MEM_RELEASE) ? way.reserve(base) : nullptr; + same_address = again == base; + if (!same_address) { + ww::close_reader(reader); + if (again) title_free(again, 0, MEM_RELEASE); + } + } + std::snprintf(what, sizeof what, "%s: a write to a new reservation is told once", way.what); + check(told_once, what); + std::snprintf(what, sizeof what, "%s: released and reserved again at the same address", way.what); + check(same_address, what); + if (!same_address) continue; + std::snprintf(what, sizeof what, "%s: the new reservation's pages are all told as written", way.what); + check(told(reader, base) == kSize / ww::kPage, what); + check(told(reader, base) == 0, "and only once"); + std::snprintf(what, sizeof what, "%s: a page decommitted and committed again is told as written", way.what); + check(title_free(static_cast(base) + 0x3000, 0x1000, MEM_DECOMMIT) && + title_alloc(static_cast(base) + 0x3000, 0x1000, MEM_COMMIT, PAGE_READWRITE) && + told(reader, base) == 1, + what); + // The title's own write-watch calls leave the shadows' bits alone. + static_cast(base)[0x5010] = 1; + void* found[16]{}; + ULONG_PTR count = 16; + ULONG granularity = 0; + std::snprintf(what, sizeof what, "%s: XMemResetWriteWatch and XMemGetWriteWatch refuse the shadows' reservation", + way.what); + check(reset_write_watch(base, kSize) != 0 && + get_write_watch(WRITE_WATCH_FLAG_RESET, base, kSize, found, &count, &granularity) != 0, + what); + check(told(reader, base) == 1, "the write is still told to the shadows"); + ww::close_reader(reader); + title_free(base, 0, MEM_RELEASE); + } +} + void print_result() { if (g_failures == 0) { std::printf("xmem_test: OK (%d checks)\n", g_checks); @@ -992,6 +1492,9 @@ int main() { } test_title_virtual_alloc(); + if (virtual_alloc) test_write_watched_reservations(virtual_alloc); + if (virtual_alloc && get_write_watch && reset_write_watch) + test_write_watch_rereserve(virtual_alloc, get_write_watch, reset_write_watch); if (alloc_default && free_default) test_default_alloc(alloc, free_mem, alloc_default, free_default); if (tools_mem) check(tools_mem() == FALSE, "XMemIsToolsMemAvailable returns FALSE (no devkit tools memory)"); @@ -1000,8 +1503,11 @@ int main() { test_physical_pages_commit_on_touch(physical); test_commit_physical_pages(physical); test_first_touch_during_remap(physical); + test_long_run(physical); + test_split_under_reader(physical); test_placeholders(physical); test_write_combine_window(physical); + test_heap_lock_faults(physical); } print_result(); diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index 126a5fd43c..7d2b77c796 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -2,6 +2,9 @@ // - devices that stop at ID3D12Device, Device1, Device3 and Device9: the slots of a missing interface (45/46, // 50, 75) are refused without reaching the device, the others get the real objects behind the proxies; // - fences with and without ID3D12Fence1: 11 or 12 public slots, QueryInterface and slot 11 to match; +// - fence slot 12: the address of a completed value that follows the real fence, from a CPU Signal through the +// proxy and from a signal the proxy never sees, up to device removal, with the descriptor's code pointer unused, and +// the completion event left open when another reference keeps the real fence alive past the proxy; // - creation that fails, that returns S_OK with no object, a null IID or output, and an interface the real object // has but the proxy does not model; // - OpenSharedHandle of a fence (as ID3D12Fence, IUnknown, Fence1), of a non-fence object, of an invalid handle, @@ -74,7 +77,7 @@ namespace xs = rt::d3d12_xs; // ---- Mocks ---- -enum class Kind { device, queue, fence, resource, allocator, command_list, heap }; +enum class Kind { device, queue, fence, resource, allocator, command_list, list, heap }; constexpr unsigned kMockSlots = 128; constexpr std::uint64_t kFenceHandle = 0x1000, kResourceHandle = 0x2000; // the handles the mock device opens @@ -94,23 +97,43 @@ struct Mock { int list_level; // command_list: 0=base (60 slots), 7=GCL7 (81 slots), 8=GCL8 (82 slots) bool fence1; // fence: answers ID3D12Fence1; device: the fences it makes do bool allocator_tag; // allocator: answers kLeonidaCommandAllocatorTag; device: the allocators it makes do + bool full_chain_lists; // device: CreateCommandList makes a full-chain list mock (Kind::list), else command_list bool create_null; // device: creation returns create_result with no object HRESULT create_result; // device: what creation returns (S_OK makes the object) bool list_refuse; // device: CreateCommandList refuses every riid with E_NOINTERFACE IID create_riid; // device: copy of the riid its last CreateCommandList got (the caller's may be a local) Mock* last_child; // device: the object its last creation or open made + Mock* device10_alias; // device: when set, QueryInterface(ID3D12Device10) answers this object, not itself + SRWLOCK lock; // fence: guards completed, armed_value and armed_event (zeroed = SRWLOCK_INIT) + std::uint64_t completed; // fence: what GetCompletedValue (slot 8) returns + std::uint64_t armed_value; // fence: the value SetEventOnCompletion (slot 9) waits for + HANDLE armed_event; // fence: the event it sets then, or null unsigned calls[kMockSlots]; - std::uint64_t args[kMockSlots][5]; + std::uint64_t args[kMockSlots][6]; std::uint64_t array[kMockSlots][4]; // device: the first entries of the array argument, as received D3D12_COMMAND_QUEUE_DESC queue_desc; // device: the description of its last CreateCommandQueue (slot 8) IUnknown* held; // ID3D12Object::SetPrivateDataInterface (slot 5): one reference, until destroyed D3D_FEATURE_LEVEL max_level; // device: the highest level FEATURE_LEVELS reports (0: the query is refused) + std::uint64_t tail[kMockSlots][3]; // device slots 27/53: the words after the fifth (a6..a8), as received + bool words_only; // device slot 27: record the words and return S_OK, creating nothing + UINT om_rtv_count; // list slot 46 (OMSetRenderTargets): captured RTV/DSV handles + BOOL om_single_range; + SIZE_T om_rtvs[D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT]; + bool om_has_dsv; + SIZE_T om_dsv; + SIZE_T clear_dsv_handle; // list slot 47 (ClearDepthStencilView): typed float-ABI capture + D3D12_CLEAR_FLAGS clear_dsv_flags; + FLOAT clear_dsv_depth; + UINT8 clear_dsv_stencil; + UINT clear_dsv_num_rects; + const D3D12_RECT* clear_dsv_rects; }; Mock g_pool[256]; unsigned g_pool_used = 0; void** mock_vtable(); +void** mock_list_vtable(); Mock* new_mock(Kind kind) { if (g_pool_used == std::size(g_pool)) { @@ -119,11 +142,44 @@ Mock* new_mock(Kind kind) { } Mock* m = &g_pool[g_pool_used++]; std::memset(m, 0, sizeof(*m)); - m->vtable = mock_vtable(); + m->vtable = (kind == Kind::list || kind == Kind::command_list) ? mock_list_vtable() : mock_vtable(); m->kind = kind; + if (kind == Kind::fence) m->completed = kCompletedValue; return m; } +// A mock fence's completed value, read and written under its lock: the proxy's wait thread calls slots 8 and 9 while +// the test signals. Signal sets the one armed event once the value reaches it, as the PC fence does. +std::uint64_t fence_completed(Mock* m) { + AcquireSRWLockExclusive(&m->lock); + const std::uint64_t value = m->completed; + ReleaseSRWLockExclusive(&m->lock); + return value; +} + +void fence_signal(Mock* m, std::uint64_t value) { + AcquireSRWLockExclusive(&m->lock); + m->completed = value; + if (m->armed_event && value >= m->armed_value) { + SetEvent(m->armed_event); + m->armed_event = nullptr; + } + ReleaseSRWLockExclusive(&m->lock); +} + +HRESULT fence_set_event(Mock* m, std::uint64_t value, HANDLE event) { + if (!event) return S_OK; // the PC fence would block until `value`; no caller here does that + AcquireSRWLockExclusive(&m->lock); + if (m->completed >= value) { + SetEvent(event); + } else { + m->armed_value = value; + m->armed_event = event; + } + ReleaseSRWLockExclusive(&m->lock); + return S_OK; +} + bool mock_has(const Mock* m, REFIID iid) { if (IsEqualIID(iid, __uuidof(IUnknown)) || IsEqualIID(iid, __uuidof(ID3D12Object))) return true; if (m->kind == Kind::device) { @@ -175,6 +231,16 @@ bool mock_has(const Mock* m, REFIID iid) { case Kind::allocator: return IsEqualIID(iid, __uuidof(ID3D12CommandAllocator)) || (m->allocator_tag && IsEqualIID(iid, xs::kLeonidaCommandAllocatorTag)); + case Kind::list: { + // The mock answers every graphics-command-list interface so the proxy sees the full 82-slot chain. + const IID lists[] = {__uuidof(ID3D12CommandList), __uuidof(ID3D12GraphicsCommandList), + __uuidof(ID3D12GraphicsCommandList1), __uuidof(ID3D12GraphicsCommandList2), + __uuidof(ID3D12GraphicsCommandList3), __uuidof(ID3D12GraphicsCommandList4), + __uuidof(ID3D12GraphicsCommandList5), __uuidof(ID3D12GraphicsCommandList6), + __uuidof(ID3D12GraphicsCommandList7), __uuidof(ID3D12GraphicsCommandList8)}; + for (const IID& list_iid : lists) if (IsEqualIID(iid, list_iid)) return true; + return false; + } default: return false; } } @@ -183,6 +249,9 @@ HRESULT mock_query(Mock* m, const IID* riid, void** out) { if (!out) return E_POINTER; *out = nullptr; if (!riid || !mock_has(m, *riid)) return E_NOINTERFACE; +#ifdef __ID3D12Device10_INTERFACE_DEFINED__ + if (m->device10_alias && IsEqualIID(*riid, __uuidof(ID3D12Device10))) m = m->device10_alias; +#endif *out = m; ++m->refs; return S_OK; @@ -236,6 +305,8 @@ D3D12_RESOURCE_DESC g_seen_descs[4]; // the first descriptions the mock device' std::uint32_t g_seen_desc_count = 0; std::uint32_t g_seen_calls = 0; // slot 25 calls since the test cleared it; only the first is recorded +std::uint64_t g_texture_size_bias = 0; // added to each texture's answer: a driver that pads more than the console + std::uint64_t mock_allocation_info(std::uint64_t ret, std::uint64_t count, std::uint64_t descs_word, D3D12_RESOURCE_ALLOCATION_INFO1* each = nullptr) { const auto* descs = reinterpret_cast(descs_word); @@ -247,7 +318,9 @@ std::uint64_t mock_allocation_info(std::uint64_t ret, std::uint64_t count, std:: D3D12_RESOURCE_ALLOCATION_INFO total{0, 1}; bool refused = false; for (std::uint32_t i = 0; descs && i < static_cast(count); ++i) { - const D3D12_RESOURCE_ALLOCATION_INFO one = mock_one_allocation(descs[i]); + D3D12_RESOURCE_ALLOCATION_INFO one = mock_one_allocation(descs[i]); + if (descs[i].Dimension != D3D12_RESOURCE_DIMENSION_BUFFER && one.SizeInBytes != UINT64_MAX) + one.SizeInBytes += g_texture_size_bias; refused = refused || one.SizeInBytes == UINT64_MAX; const std::uint64_t offset = mock_align(total.SizeInBytes, one.Alignment); if (each) each[i] = {offset, one.Alignment, one.SizeInBytes}; @@ -259,15 +332,18 @@ std::uint64_t mock_allocation_info(std::uint64_t ret, std::uint64_t count, std:: return ret; } -// `words` are the call's first five words (a1..a5), copied into the thunk's own frame. +// `words` are the call's first six words (a1..a6), copied into the thunk's own frame. std::uint64_t mock_call(Mock* m, unsigned slot, const std::uint64_t* words) { - const std::uint64_t a1 = words[0], a2 = words[1], a3 = words[2], a4 = words[3]; + const std::uint64_t a1 = words[0], a2 = words[1], a3 = words[2], a4 = words[3], a5 = words[4], a6 = words[5]; if (m->kind == Kind::device) { switch (slot) { case 8: // CreateCommandQueue if (a1) std::memcpy(&m->queue_desc, reinterpret_cast(a1), sizeof(m->queue_desc)); return static_cast(mock_create(m, Kind::queue, a2, a3)); case 9: return static_cast(mock_create(m, Kind::allocator, a2, a3)); // CreateCmdAllocator + // Slot 12 (CreateCommandList) never reaches this switch: the device vtable's slot is the dedicated + // mock_create_command_list, which needs the sixth word the generic thunk does not declare on some + // builds and which picks the list mock's chain breadth from full_chain_lists. case 14: return static_cast(mock_create(m, Kind::heap, a2, a3)); // CreateDescriptorHeap case 15: return kMockDescriptorInc; // GetDescriptorHandleIncrementSize case 23: // CopyDescriptors @@ -342,9 +418,25 @@ std::uint64_t mock_call(Mock* m, unsigned slot, const std::uint64_t* words) { } return S_OK; } - if (m->kind == Kind::fence && slot == 8) return kCompletedValue; // GetCompletedValue - if (m->kind == Kind::queue && slot == 10) copy_array(m, slot, a2, a1); // ExecuteCommandLists(count, lists) - if (m->kind == Kind::command_list && slot == 28) copy_array(m, slot, a2, a1); // SetDescriptorHeaps(count, heaps) + if (m->kind == Kind::fence) { + switch (slot) { + case 8: return fence_completed(m); // GetCompletedValue + case 9: return static_cast(fence_set_event(m, a1, reinterpret_cast(a2))); + case 10: fence_signal(m, a1); return S_OK; // Signal + default: break; + } + } + if (m->kind == Kind::queue && slot == 10) copy_array(m, 10, a2, a1); // ExecuteCommandLists(count, lists) + if ((m->kind == Kind::command_list || m->kind == Kind::list) && slot == 28) + copy_array(m, slot, a2, a1); // SetDescriptorHeaps(count, heaps) + if (m->kind == Kind::queue && slot == 16 && a1) { + // GetTimestampFrequency writes a fixed value — unless a1 is a mock object, which on this slot is a + // newer-layout Signal's fence, not an out pointer. + const auto at = static_cast(a1); + const auto base = reinterpret_cast(g_pool); + const bool is_mock = at >= base && at < base + sizeof(g_pool) && (at - base) % sizeof(Mock) == 0; + if (!is_mock) *reinterpret_cast(a1) = 1000000; + } if (m->kind == Kind::heap && slot == 9) { if (a1) reinterpret_cast(a1)->ptr = kMockHeapCpuStart; return kMockHeapCpuStart; @@ -353,12 +445,29 @@ std::uint64_t mock_call(Mock* m, unsigned slot, const std::uint64_t* words) { if (a1) reinterpret_cast(a1)->ptr = kMockHeapGpuStart; return kMockHeapGpuStart; } + if ((m->kind == Kind::list || m->kind == Kind::command_list) && slot == 46) { // OMSetRenderTargets + m->om_rtv_count = static_cast(a1); + m->om_single_range = static_cast(a3); + std::memset(m->om_rtvs, 0, sizeof(m->om_rtvs)); + const auto* rtvs = reinterpret_cast(a2); + if (rtvs && m->om_rtv_count > 0) { + const UINT n = m->om_single_range + ? 1u + : (m->om_rtv_count < D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT + ? m->om_rtv_count + : D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT); + for (UINT i = 0; i < n; ++i) m->om_rtvs[i] = rtvs[i].ptr; + } + const auto* dsv = reinterpret_cast(a4); + m->om_has_dsv = dsv != nullptr; + m->om_dsv = dsv ? dsv->ptr : 0; + } return S_OK; } template std::uint64_t WINAPI mock_slot(Mock* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, std::uint64_t a4, - std::uint64_t a5) { + std::uint64_t a5, std::uint64_t a6) { if constexpr (Slot == 0) { return static_cast(mock_query(self, reinterpret_cast(a1), reinterpret_cast(a2))); @@ -385,12 +494,23 @@ std::uint64_t WINAPI mock_slot(Mock* self, std::uint64_t a1, std::uint64_t a2, s // forwarding them as stack arguments let MSVC tail-call mock_call and write into the caller's saved // registers (an optimized build corrupted the test's own locals that way). ++self->calls[Slot]; - const std::uint64_t words[] = {a1, a2, a3, a4, a5}; + const std::uint64_t words[] = {a1, a2, a3, a4, a5, a6}; std::memcpy(self->args[Slot], words, sizeof(words)); return mock_call(self, Slot, words); } } +void WINAPI mock_clear_depth_stencil_view(Mock* self, D3D12_CPU_DESCRIPTOR_HANDLE dsv, D3D12_CLEAR_FLAGS flags, + FLOAT depth, UINT8 stencil, UINT num_rects, const D3D12_RECT* rects) { + ++self->calls[47]; + self->clear_dsv_handle = dsv.ptr; + self->clear_dsv_flags = flags; + self->clear_dsv_depth = depth; + self->clear_dsv_stencil = stencil; + self->clear_dsv_num_rects = num_rects; + self->clear_dsv_rects = rects; +} + // PC ID3D12Device::CreateCommandList takes six words after `this`, one more than the generic mock thunk declares, so // it gets its own entry in the table: the out pointer is a6 (first stack argument on x64) and has to be written. HRESULT WINAPI mock_create_command_list(Mock* self, std::uint64_t node_mask, std::uint64_t type, @@ -407,17 +527,61 @@ HRESULT WINAPI mock_create_command_list(Mock* self, std::uint64_t node_mask, std *out = nullptr; if (self->list_refuse) return E_NOINTERFACE; if (self->create_null || FAILED(self->create_result)) return self->create_result; - Mock* child = new_mock(Kind::command_list); + Mock* child = new_mock(self->full_chain_lists ? Kind::list : Kind::command_list); child->list_level = self->list_level; self->last_child = child; return mock_query(child, riid, out); } +// PC ID3D12Device::CreateCommittedResource (slot 27) takes seven words after `this`, so it has its own entry too. It +// records what it was given (the description by value) and makes a resource mock. +struct CommittedCall { + D3D12_HEAP_PROPERTIES heap; + D3D12_HEAP_FLAGS heap_flags; + D3D12_RESOURCE_DESC desc; + D3D12_RESOURCE_STATES state; + const D3D12_CLEAR_VALUE* clear; + const IID* riid; +}; +CommittedCall g_committed{}; + +HRESULT WINAPI mock_create_committed_resource(Mock* self, const D3D12_HEAP_PROPERTIES* heap, + D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC* desc, + D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear, + const IID* riid, void** out) { + ++self->calls[27]; + // The first words are kept as every other slot's are (the lease checks read them), and the table is shared by + // every mock kind: only a device creates a resource here. + const std::uint64_t words[6] = {reinterpret_cast(heap), static_cast(heap_flags), + reinterpret_cast(desc), static_cast(state), + reinterpret_cast(clear), reinterpret_cast(riid)}; + std::memcpy(self->args[27], words, 5 * sizeof(words[0])); + const std::uint64_t rest[3] = {reinterpret_cast(riid), reinterpret_cast(out), 0}; + std::memcpy(self->tail[27], rest, sizeof(rest)); + if (self->kind != Kind::device) return static_cast(mock_call(self, 27, words)); + // The initial-state checks pass made-up words for the clear value, riid and output: nothing is read or created. + if (self->words_only) return S_OK; + g_committed = CommittedCall{}; + if (heap) g_committed.heap = *heap; + g_committed.heap_flags = heap_flags; + if (desc) g_committed.desc = *desc; + g_committed.state = state; + g_committed.clear = clear; + g_committed.riid = riid; + if (!out) return S_FALSE; + *out = nullptr; + if (self->create_null || FAILED(self->create_result)) return self->create_result; + Mock* child = new_mock(Kind::resource); + self->last_child = child; + return mock_query(child, riid, out); +} + #ifdef __ID3D12Device10_INTERFACE_DEFINED__ // PC ID3D12Device10::CreateCommittedResource3 takes ten words after `this`, so it has its own entry (PC slot 76) that // keeps all of them: the resource description is copied because the caller's copy is a local of the proxy. struct CommittedResource3Call { unsigned calls; + const Mock* device; // the PC object the call arrived on const D3D12_HEAP_PROPERTIES* heap; D3D12_HEAP_FLAGS heap_flags; D3D12_RESOURCE_DESC1 desc; @@ -436,28 +600,31 @@ HRESULT WINAPI mock_create_committed_resource3(Mock* self, const D3D12_HEAP_PROP const D3D12_CLEAR_VALUE* clear, const void* session, std::uint32_t castable_count, const DXGI_FORMAT* castable_formats, const IID* riid, void** out) { - g_committed3 = {g_committed3.calls + 1, heap, flags, *desc, layout, clear, session, castable_count, + g_committed3 = {g_committed3.calls + 1, self, heap, flags, *desc, layout, clear, session, castable_count, castable_formats, riid, out}; return mock_create(self, Kind::resource, reinterpret_cast(riid), reinterpret_cast(out)); } #endif +// PC CreateCommittedResource (27) and CreateCommittedResource1 (53) take seven and eight words after `this`; the generic +// thunk keeps five, so these two record the rest as well (a6..a8 in tail). +template +std::uint64_t WINAPI mock_committed_resource(Mock* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, + std::uint64_t a4, std::uint64_t a5, std::uint64_t a6, std::uint64_t a7, + std::uint64_t a8) { + ++self->calls[Slot]; + const std::uint64_t head[] = {a1, a2, a3, a4, a5}; + const std::uint64_t rest[] = {a6, a7, a8}; + std::memcpy(self->args[Slot], head, sizeof(head)); + std::memcpy(self->tail[Slot], rest, sizeof(rest)); + return S_OK; +} + template void fill_mock_vtable(void** vtable, std::index_sequence) { ((vtable[I] = reinterpret_cast(&mock_slot(I)>)), ...); } -// PC ID3D12Device::CreateCommittedResource(heap, flags, desc, state, clear, riid, out) takes seven words after `this`, -// so a device answers it from its own entry; other kinds keep the generic path for slot 27. -HRESULT WINAPI mock_create_committed_resource(Mock* self, std::uint64_t heap, std::uint64_t flags, std::uint64_t desc, - std::uint64_t state, std::uint64_t clear, const IID* riid, void** out) { - ++self->calls[27]; - const std::uint64_t words[] = {heap, flags, desc, state, clear}; - std::memcpy(self->args[27], words, sizeof(words)); - if (self->kind != Kind::device) return mock_call(self, 27, words); - return mock_create(self, Kind::resource, reinterpret_cast(riid), reinterpret_cast(out)); -} - void** mock_vtable() { static void* table[kMockSlots]; static const bool filled = [] { @@ -467,6 +634,18 @@ void** mock_vtable() { #ifdef __ID3D12Device10_INTERFACE_DEFINED__ table[76] = reinterpret_cast(&mock_create_committed_resource3); #endif + table[53] = reinterpret_cast(&mock_committed_resource<53>); + return true; + }(); + (void)filled; + return table; +} + +void** mock_list_vtable() { + static void* table[kMockSlots]; + static const bool filled = [] { + fill_mock_vtable(table, std::make_index_sequence{}); + table[47] = reinterpret_cast(&mock_clear_depth_stencil_view); return true; }(); (void)filled; @@ -482,6 +661,14 @@ using SlotFn = std::uint64_t(WINAPI*)(void*, std::uint64_t, std::uint64_t, std:: std::uint64_t raw(const void* object, unsigned slot, std::uint64_t a1 = 0, std::uint64_t a2 = 0, std::uint64_t a3 = 0, std::uint64_t a4 = 0, std::uint64_t a5 = 0, std::uint64_t a6 = 0) { void* const* vtable = *reinterpret_cast(object); + return reinterpret_cast(vtable[slot])(const_cast(object), a1, a2, a3, a4, a5, a6, 0, 0, 0, 0, + 0, 0, 0, 0); +} + +// The same with a sixth word, the first stack argument (slot 133's output pointer). +std::uint64_t raw6(const void* object, unsigned slot, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, + std::uint64_t a4, std::uint64_t a5, std::uint64_t a6) { + void* const* vtable = *reinterpret_cast(object); return reinterpret_cast(vtable[slot])(const_cast(object), a1, a2, a3, a4, a5, a6, 0, 0, 0, 0, 0, 0, 0, 0); } @@ -513,14 +700,16 @@ const D3D12_COMMAND_QUEUE_DESC kQueueDesc{}; const std::uint32_t kXboxQueueDesc[8] = {}; // A device proxy over a new mock device. The proxy takes the mock's one reference. -void* make_device(Mock*& mock, int level, bool fence1, bool allocator_tag = true) { +void* make_device(Mock*& mock, int level, bool fence1, bool allocator_tag = true, bool full_chain_lists = false) { mock = new_mock(Kind::device); mock->device_level = level; mock->fence1 = fence1; mock->allocator_tag = allocator_tag; + mock->full_chain_lists = full_chain_lists; mock->refs = 1; void* device = nullptr; - if (FAILED(xs::create_device_proxy(reinterpret_cast(mock), __uuidof(ID3D12Device), &device))) + if (FAILED(xs::create_device_proxy(reinterpret_cast(mock), __uuidof(ID3D12Device), &device, + /*console_lists=*/true))) return nullptr; return device; } @@ -602,6 +791,9 @@ int check_host_device_floor() { // ---- 1. Device interface levels ---- +// D3D12_RESOURCE_STATES is a 32-bit enum: MSVC stores only the low half of its 8-byte stack slot. +std::uint32_t state_of(std::uint64_t word) { return static_cast(word); } + int check_levels() { struct Level { int level; unsigned slots; } const levels[] = {{0, 44}, {1, 47}, {3, 51}, {9, 76}}; for (const Level& l : levels) { @@ -662,8 +854,9 @@ int check_levels() { EXPECT(r75 == E_NOTIMPL && !queue1 && mock->calls[75] == 0); } - // 133: past every PC device vtable; the retail title calls it. Refused, not a jump through a missing entry. - EXPECT(hr_of(raw(device, 133)) == E_NOTIMPL && mock->calls[127] == 0); + // 134: past every PC device vtable and not handled by the proxy (133 is, see check_placed_resource_x). + // Refused, not a jump through a missing entry. + EXPECT(hr_of(raw(device, 134)) == E_NOTIMPL && mock->calls[127] == 0); // 133 with a handler (CreatePlacedResourceX): the arguments in the title's positions (va, desc, state, // clear, riid, out) reach the handler with the real device, the Xbox flag bits masked to the PC ones the host @@ -875,6 +1068,136 @@ int check_fence1() { return 0; } +// ---- Fence slot 12: the completed value at an address ---- + +std::atomic g_descriptor_calls{0}; +void WINAPI descriptor_callback() { g_descriptor_calls.fetch_add(1); } + +// True once *completed reads `value`, within five seconds (the proxy's wait thread writes it). +bool reads_within(const volatile std::uint64_t* completed, std::uint64_t value) { + for (int i = 0; i < 5000; ++i) { + if (*completed == value) return true; + Sleep(1); + } + return *completed == value; +} + +bool fence_armed_for(Mock* fence, std::uint64_t value) { + AcquireSRWLockExclusive(&fence->lock); + const bool armed = fence->armed_event && fence->armed_value == value; + ReleaseSRWLockExclusive(&fence->lock); + return armed; +} + +int check_fence_completed_value() { + for (const bool fence1 : {false, true}) { // past ID3D12Fence1 either way + Mock* mock = nullptr; + void* device = make_device(mock, 9, fence1); + EXPECT(device); + void* fence = make_fence(device); + Mock* const fence_mock = mock->last_child; + void* other = make_fence(device); + Mock* const other_mock = mock->last_child; + EXPECT(fence && other && fence_mock != other_mock); + + // The title's shape: (value, descriptor with a code pointer in its second word, flags). + const std::uint64_t descriptor[4] = {0, reinterpret_cast(&descriptor_callback), 0, 0}; + const auto* completed = + reinterpret_cast(raw(fence, 12, 9, word(descriptor), 1)); + EXPECT(completed && *completed == kCompletedValue); + EXPECT(xs::fence_slot_first_call_seen(12)); + EXPECT(raw(fence, 12, 9, word(descriptor), 1) == word(completed)); // one address per fence + const auto* other_completed = reinterpret_cast(raw(other, 12, 0, 0, 0)); + EXPECT(other_completed && other_completed != completed); + + // A CPU Signal through the proxy shows at once. + EXPECT(hr_of(raw(fence, 10, 9)) == S_OK && fence_mock->completed == 9); + EXPECT(*completed == 9 && *other_completed == kCompletedValue); + // A signal the proxy never sees (a queue's, on the GPU) shows without another call, and again after it. + fence_signal(fence_mock, 12); + EXPECT(reads_within(completed, 12)); + fence_signal(fence_mock, 40); + EXPECT(reads_within(completed, 40)); + fence_signal(other_mock, 8); + EXPECT(reads_within(other_completed, 8) && *completed == 40); + // Wait for the wait thread to arm its next threshold before rewinding. + const ULONGLONG until = GetTickCount64() + 1000; + while (!fence_armed_for(fence_mock, 41) && GetTickCount64() < until) Sleep(1); + EXPECT(fence_armed_for(fence_mock, 41)); + EXPECT(hr_of(raw(fence, 10, 3)) == S_OK && *completed == 3); + fence_signal(fence_mock, 15); + EXPECT(fence_completed(fence_mock) == 15); + if (!reads_within(completed, 15)) { + std::fprintf(stderr, "rewind: underlying fence %llu, slot 12 mirror %llu\n", + static_cast(fence_completed(fence_mock)), + static_cast(*completed)); + return 1; + } + // A rewind by a producer outside the proxy can go straight below its outstanding event. + fence_signal(fence_mock, 2); + EXPECT(reads_within(completed, 2)); + fence_signal(fence_mock, 7); + EXPECT(reads_within(completed, 7)); + // The fallback must leave the pending completion event alone. + EXPECT(fence_armed_for(fence_mock, 41)); + fence_signal(fence_mock, 45); + EXPECT(reads_within(completed, 45)); + // Device removal: the real fence reports ~0, which the title tests for, and nothing is armed after it. + fence_signal(fence_mock, ~std::uint64_t{0}); + EXPECT(reads_within(completed, ~std::uint64_t{0})); + Sleep(50); + AcquireSRWLockExclusive(&fence_mock->lock); + const bool rearmed = fence_mock->armed_event != nullptr; + ReleaseSRWLockExclusive(&fence_mock->lock); + EXPECT(!rearmed); + EXPECT(g_descriptor_calls.load() == 0); // the descriptor's code pointer is not called + + // Release waits out the wait thread; both fences and the device go back to zero references. + EXPECT(release(fence) == 0 && fence_mock->refs == 0); + EXPECT(release(other) == 0 && other_mock->refs == 0); + + // A fence whose slot 12 is never called arms nothing on the real fence. + void* quiet = make_fence(device); + Mock* const quiet_mock = mock->last_child; + EXPECT(quiet && hr_of(raw(quiet, 10, 3)) == S_OK && raw(quiet, 8) == 3 && quiet_mock->calls[9] == 0); + EXPECT(release(quiet) == 0 && quiet_mock->refs == 0); + + // Another reference keeps the real fence alive past the proxy. Its pending completion still names the + // mirror's event and cannot be cancelled, so the event stays open and a later signal sets it. + void* shared = make_fence(device); + Mock* const shared_mock = mock->last_child; + EXPECT(shared && raw(shared, 12, 0, 0, 0) != 0); + const ULONGLONG armed_by = GetTickCount64() + 1000; + while (!fence_armed_for(shared_mock, kCompletedValue + 1) && GetTickCount64() < armed_by) Sleep(1); + EXPECT(fence_armed_for(shared_mock, kCompletedValue + 1)); + ++shared_mock->refs; // the other holder + EXPECT(release(shared) == 0 && shared_mock->refs == 1); + AcquireSRWLockExclusive(&shared_mock->lock); + const HANDLE pending = shared_mock->armed_event; + ReleaseSRWLockExclusive(&shared_mock->lock); + DWORD handle_flags = 0; + EXPECT(pending && GetHandleInformation(pending, &handle_flags)); + fence_signal(shared_mock, kCompletedValue + 1); + EXPECT(WaitForSingleObject(pending, 0) == WAIT_OBJECT_0); + --shared_mock->refs; + + // Out of memory for the mirror: slot 12 returns null, and the next call works. + void* starved = make_fence(device); + EXPECT(starved); + g_fail_news = 1; + const std::uint64_t none = raw(starved, 12, 0, 0, 0); + g_fail_news = 0; + EXPECT(none == 0); + const auto* later = reinterpret_cast(raw(starved, 12, 0, 0, 0)); + EXPECT(later && *later == kCompletedValue); + EXPECT(release(starved) == 0); + EXPECT(release(device) == 0 && mock->refs == 0); + } + std::printf("%s: fence slot 12 returns one address per fence whose completed value follows CPU and unseen " + "signals up to device removal; the descriptor is not called\n", g_label); + return 0; +} + // ---- 3. Creation failures and refused interfaces ---- int check_create_failures() { @@ -1064,9 +1387,21 @@ int check_allocators() { EXPECT(xs::is_allocator_proxy(allocator) && word(xs::allocator_proxy_real_allocator(allocator)) == word(real)); EXPECT(mock->args[9][0] == D3D12_COMMAND_LIST_TYPE_DIRECT && real->refs == 1); EXPECT(xs::allocator_proxy_slot_count(allocator) == 9 && xs::device_proxy_ref_count(device) == device_refs + 1); - // Reset (slot 8) reaches the real allocator; every slot past it up to the table end is refused. + // Reset (slot 8) reaches the real allocator; slot 9 (SetAllocatorCallbackX) records callback/context and + // succeeds without touching the real vtable; every slot past 9 up to the table end is refused. EXPECT(hr_of(raw(allocator, 8)) == S_OK && real->calls[8] == 1); - for (unsigned slot = 9; slot < xs::allocator_proxy_table_size(); ++slot) + EXPECT(xs::allocator_proxy_callback(allocator) == 0 && xs::allocator_proxy_callback_context(allocator) == 0); + EXPECT(xs::allocator_proxy_callback(nullptr) == 0 && xs::allocator_proxy_callback_context(device) == 0); + constexpr std::uintptr_t fake_cb = 0x12345678u; + constexpr std::uintptr_t fake_ctx = 0x9abcdef0u; + const std::uint64_t slot9_hits_before = xs::allocator_slot_hits(9); + EXPECT(hr_of(raw(allocator, 9, fake_cb, fake_ctx, 0, 0xfeedfaceu)) == S_OK && real->calls[9] == 0); + EXPECT(xs::allocator_slot_hits(9) == slot9_hits_before + 1 && xs::allocator_slot_first_call_seen(9)); + EXPECT(xs::allocator_proxy_callback(allocator) == fake_cb && + xs::allocator_proxy_callback_context(allocator) == fake_ctx); + EXPECT(hr_of(raw(allocator, 9, 0, 0)) == S_OK && real->calls[9] == 0); + EXPECT(xs::allocator_proxy_callback(allocator) == 0 && xs::allocator_proxy_callback_context(allocator) == 0); + for (unsigned slot = 10; slot < xs::allocator_proxy_table_size(); ++slot) EXPECT(hr_of(raw(allocator, slot)) == E_NOTIMPL && real->calls[slot] == 0); // The tag and the real object stay hidden: QueryInterface answers only the modelled interfaces. void* found = reinterpret_cast(1); @@ -1126,6 +1461,86 @@ int check_allocators() { return 0; } +// ---- 6b. Device slot 133: a resource placed at a VA becomes a committed DEFAULT-heap resource ---- +// +// The device stops at ID3D12Device9 (76 slots), so 133 is past its table: the proxy must answer it before the +// beyond-table refusal and reach the PC CreateCommittedResource (slot 27) with a cleaned description. +int check_placed_resource_x() { + Mock* mock = nullptr; + void* device = make_device(mock, 9, true); + EXPECT(device && xs::device_slot_overridden(133)); + xs::reset_device_proxy_stats(); + constexpr std::uint64_t kVa = 0x7f0000000000ull; // any address: the stand-in does not touch it + // A bit above every PC flag; an integer (a D3D12_RESOURCE_FLAGS value past the last enumerator is not a constant + // expression for clang-cl), cast with the PC flag at run time. + constexpr std::uint32_t kXboxFlag = 0x20000; + + // A buffer with an Xbox flag bit, a non-PC layout word and the all-ones state: PC flags only, ROW_MAJOR, COMMON, + // no clear value, DEFAULT heap, and the caller's IID. + D3D12_RESOURCE_DESC buffer{}; + buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buffer.Width = 1 << 20; + buffer.Height = 1; + buffer.DepthOrArraySize = 1; + buffer.MipLevels = 1; + buffer.SampleDesc.Count = 1; + buffer.Layout = static_cast(0x101); + buffer.Flags = static_cast(D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | kXboxFlag); + const D3D12_CLEAR_VALUE clear{DXGI_FORMAT_R8G8B8A8_UNORM, {{0, 0, 0, 1}}}; + void* resource = nullptr; + EXPECT(hr_of(raw6(device, 133, kVa, word(&buffer), 0xFFFFFFFFu, word(&clear), word(&kResourceIid), + word(&resource))) == S_OK); + EXPECT(resource && reinterpret_cast(resource)->kind == Kind::resource); + EXPECT(mock->calls[27] == 1 && mock->calls[127] == 0 && xs::device_slot_hits(133) == 1); + EXPECT(g_committed.heap.Type == D3D12_HEAP_TYPE_DEFAULT && g_committed.heap_flags == D3D12_HEAP_FLAG_NONE); + EXPECT(g_committed.desc.Flags == D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + EXPECT(g_committed.desc.Layout == D3D12_TEXTURE_LAYOUT_ROW_MAJOR && g_committed.desc.Width == buffer.Width); + EXPECT(g_committed.state == D3D12_RESOURCE_STATE_COMMON && !g_committed.clear); + EXPECT(g_committed.riid == &kResourceIid); + EXPECT(release(resource) == 0); + + // A render-target texture in a PC state keeps the state and its clear value; the layout becomes UNKNOWN. + D3D12_RESOURCE_DESC target = buffer; + target.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + target.Width = 64; + target.Height = 32; + target.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + target.Flags = static_cast(D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | kXboxFlag); + EXPECT(hr_of(raw6(device, 133, kVa, word(&target), D3D12_RESOURCE_STATE_RENDER_TARGET, word(&clear), + word(&kResourceIid), word(&resource))) == S_OK); + EXPECT(mock->calls[27] == 2 && g_committed.desc.Flags == D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET); + EXPECT(g_committed.desc.Layout == D3D12_TEXTURE_LAYOUT_UNKNOWN); + EXPECT(g_committed.state == D3D12_RESOURCE_STATE_RENDER_TARGET && g_committed.clear == &clear); + EXPECT(release(resource) == 0); + // The same texture in the all-ones state is created in COMMON. + EXPECT(hr_of(raw6(device, 133, kVa, word(&target), 0xFFFFFFFFu, 0, word(&kResourceIid), word(&resource))) == + S_OK); + EXPECT(mock->calls[27] == 3 && g_committed.state == D3D12_RESOURCE_STATE_COMMON); + EXPECT(release(resource) == 0); + + // Refusals before the device is called; the output is cleared. + resource = reinterpret_cast(1); + EXPECT(hr_of(raw6(device, 133, kVa, 0, 0, 0, word(&kResourceIid), word(&resource))) == E_INVALIDARG); + EXPECT(!resource); + resource = reinterpret_cast(1); + EXPECT(hr_of(raw6(device, 133, kVa, word(&buffer), 0, 0, 0, word(&resource))) == E_POINTER && !resource); + EXPECT(hr_of(raw6(device, 133, kVa, word(&buffer), 0, 0, word(&kResourceIid), 0)) == E_POINTER); + EXPECT(mock->calls[27] == 3); + + // A failed creation is returned as it is, with no object. + mock->create_result = E_OUTOFMEMORY; + resource = reinterpret_cast(1); + EXPECT(hr_of(raw6(device, 133, kVa, word(&buffer), 0, 0, word(&kResourceIid), word(&resource))) == + E_OUTOFMEMORY); + EXPECT(!resource && mock->calls[27] == 4); + mock->create_result = S_OK; + + EXPECT(release(device) == 0 && mock->refs == 0); + std::printf("%s: device slot 133 places a resource as a committed DEFAULT one (PC flags, COMMON for all-ones, " + "clear value for targets only), past a 76-slot device\n", g_label); + return 0; +} + // ---- 7. Xbox device slots from the public HLE (48, 73, 78, 79, 80) and the retail title (41) ---- @@ -1136,7 +1551,9 @@ int check_allocators() { int check_xbox_slots() { #ifdef __ID3D12Device11_INTERFACE_DEFINED__ Mock* mock = nullptr; - void* device = make_device(mock, 11, true); + // Full-chain lists: the console IID maps to ID3D12GraphicsCommandList6, which a command_list-kind mock + // does not answer. + void* device = make_device(mock, 11, true, true, true); EXPECT(device && xs::device_proxy_slot_count(device) == 80); xs::reset_device_proxy_stats(); @@ -1155,7 +1572,13 @@ int check_xbox_slots() { EXPECT(hr_of(raw(device, 80, 0, 0, 0, 0, 0)) == E_POINTER); EXPECT(mock->calls[80] == 0 && xs::device_slot_hits(80) == 3); - // 48 CreateCommandQueueX(desc, riid, out): the queue proxy, created through the PC slot 8 path. + // 81 GetFrameStatisticsX with no presenter attached: S_FALSE and no statistics, never the PC slot 81 + // (check_presentation_wiring covers an attached presenter). + UINT stats_count = 7; + EXPECT(hr_of(raw(device, 81, token, 0x1a, word(&stats_count), 0)) == S_FALSE && stats_count == 0); + EXPECT(mock->calls[81] == 0 && xs::device_slot_hits(81) == 1); + + // 48 CreateCommandQueueX(desc, riid, out): the queue proxy, created through the PC slot 8 path (filtered desc copy). void* queue = nullptr; EXPECT(hr_of(raw(device, 48, word(kXboxQueueDesc), word(&kQueueIid), word(&queue))) == S_OK); EXPECT(xs::is_queue_proxy(queue) && mock->calls[48] == 0 && mock->calls[8] == 1); @@ -1179,18 +1602,46 @@ int check_xbox_slots() { const IID list_iid = __uuidof(ID3D12GraphicsCommandList); void* list = nullptr; EXPECT(hr_of(raw(device, 73, word(&desc), word(allocator), 0, word(&list_iid), word(&list))) == S_OK); - EXPECT(xs::is_command_list_proxy(list)); - EXPECT(xs::command_list_proxy_real_list(list) && - reinterpret_cast(xs::command_list_proxy_real_list(list))->kind == Kind::command_list); + // The list is the console list proxy over the PC list the mock made (slot 12's path); the mock's kind depends on + // full_chain_lists. + EXPECT(xs::is_list_proxy(list) && word(xs::list_proxy_real_list(list)) == word(mock->last_child)); + EXPECT(mock->last_child->kind == Kind::command_list || mock->last_child->kind == Kind::list); EXPECT(mock->calls[73] == 0 && mock->calls[12] == 1 && xs::device_slot_hits(73) == 1); EXPECT(mock->args[12][0] == 0 && mock->args[12][1] == D3D12_COMMAND_LIST_TYPE_DIRECT); EXPECT(mock->args[12][2] == word(real_allocator) && mock->args[12][3] == 0); - EXPECT(mock->args[12][4] == word(&list_iid)); + EXPECT(IsEqualIID(*reinterpret_cast(mock->args[12][4]), list_iid)); + + // The measured console list IID (the 1.0.2.1 executable's only GUID of that form) maps to + // ID3D12GraphicsCommandList6: slot 73 answers it, and a QueryInterface for it on the proxy returns the proxy. + const IID console_list_iid = {0xc3827890, 0x4024, 0x474c, {0x98, 0xcf, 0x64, 0x5b, 0x51, 0xdc, 0x48, 0x74}}; + void* console_list = nullptr; + EXPECT(hr_of(raw(device, 73, word(&desc), word(allocator), 0, word(&console_list_iid), + word(&console_list))) == S_OK); + EXPECT(xs::is_list_proxy(console_list)); + EXPECT(mock->calls[12] == 2); + void* asked = nullptr; + EXPECT(hr_of(raw(console_list, 0, word(&console_list_iid), word(&asked))) == S_OK && asked == console_list); + EXPECT(release(asked) == 1 && release(console_list) == 0); // Release the list before the refusal calls below: the COM convention (and the handler) nulls the caller's // output on failure, so an invalid call would clear this pointer. EXPECT(release(list) == 0); + // An IID that is neither a PC list IID nor the measured console one (made up for the test) goes to the PC device + // as asked, once, and its refusal comes back (main's slot 73; check_console_command_list has the console IID). + // {8d2c4f61-3a5e-4b7c-9e10-2f6a8b4c3d51} + constexpr GUID kConsoleListIid{0x8d2c4f61, 0x3a5e, 0x4b7c, {0x9e, 0x10, 0x2f, 0x6a, 0x8b, 0x4c, 0x3d, 0x51}}; + void* unknown_list = nullptr; + EXPECT(FAILED(hr_of(raw(device, 73, word(&desc), word(allocator), 0, word(&kConsoleListIid), + word(&unknown_list))))); + EXPECT(!unknown_list && mock->calls[12] == 3 && mock->calls[73] == 0); + // A PC list IID the proxy answers is returned as asked. + const IID list1_iid = __uuidof(ID3D12GraphicsCommandList1); + void* list1 = nullptr; + EXPECT(hr_of(raw(device, 73, word(&desc), word(allocator), 0, word(&list1_iid), word(&list1))) == S_OK); + EXPECT(xs::is_list_proxy(list1) && mock->calls[12] == 4); + EXPECT(release(list1) == 0); + // Missing description, allocator or output: E_INVALIDARG/E_POINTER before the real device is called. EXPECT(hr_of(raw(device, 73, 0, word(allocator), 0, word(&list_iid), word(&list))) == E_INVALIDARG); EXPECT(hr_of(raw(device, 73, word(&desc), 0, 0, word(&list_iid), word(&list))) == E_INVALIDARG); @@ -1351,11 +1802,89 @@ int check_xbox_slots() { #endif } -// ---- 7b. Xbox queue ExecuteCommandLists variant (queue slot 35 -> PC slot 10) ---- +// ---- 7b. Console initial state 0x6 on a committed texture (slots 27, 53 and 76) ---- +// +// The console creates render-target and depth textures with state 0x6, which the PC runtime refuses for a texture. The +// mock device records the state it was given (slot 27's fourth word, a4 in args[27][3] / args[53][3]). +D3D12_RESOURCE_DESC resource_desc(D3D12_RESOURCE_DIMENSION dimension, D3D12_RESOURCE_FLAGS flags) { + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = dimension; + desc.Width = 64; + desc.Height = 64; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Flags = flags; + return desc; +} -int check_xbox_queue_slots() { +std::uint64_t raw8(const void* object, unsigned slot, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, + std::uint64_t a4, std::uint64_t a5, std::uint64_t a6, std::uint64_t a7, std::uint64_t a8 = 0) { + void* const* vtable = *reinterpret_cast(object); + return reinterpret_cast(vtable[slot])(const_cast(object), a1, a2, a3, a4, a5, a6, a7, a8, 0, 0, 0, + 0, 0, 0); +} + +int check_committed_resource_states() { Mock* mock = nullptr; void* device = make_device(mock, 9, true); + EXPECT(device && xs::device_proxy_slot_count(device) == 76); + mock->words_only = true; // slot 27 has the creating mock entry (slots 76/133 need it); here only the words count + const D3D12_HEAP_PROPERTIES props{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_RESOURCE_DESC rt = resource_desc(D3D12_RESOURCE_DIMENSION_TEXTURE2D, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET); + const D3D12_RESOURCE_DESC ds = resource_desc(D3D12_RESOURCE_DIMENSION_TEXTURE2D, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL); + const D3D12_RESOURCE_DESC plain = resource_desc(D3D12_RESOURCE_DIMENSION_TEXTURE2D, D3D12_RESOURCE_FLAG_NONE); + const D3D12_RESOURCE_DESC buffer = resource_desc(D3D12_RESOURCE_DIMENSION_BUFFER, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET); + const std::uint64_t kConsole = 0x6; + const std::uint64_t kRender = D3D12_RESOURCE_STATE_RENDER_TARGET; + const std::uint64_t kDepth = D3D12_RESOURCE_STATE_DEPTH_WRITE; + + // Slot 27 (the title's CreateCommittedResource) and slot 53 (CreateCommittedResource1): the real device sees + // the mapped state; the description and the other words arrive as they were. + // The words after the state (clear value, protected session, riid, out) are distinct, so their positions show. + for (const unsigned slot : {27u, 53u}) { + const std::uint64_t before = mock->calls[slot]; + const std::uint64_t clear = 0xC1EA, session = 0x5E55, riid = 0x41D, out = 0x0B7; + const std::uint64_t first = slot == 27 ? riid : session; + EXPECT(hr_of(raw8(device, slot, word(&props), 0x40, word(&rt), kConsole, clear, first, slot == 27 ? out : riid, + slot == 27 ? 0 : out)) == S_OK); + EXPECT(mock->args[slot][1] == 0x40 && mock->args[slot][4] == clear); + EXPECT(mock->tail[slot][0] == first && mock->tail[slot][1] == (slot == 27 ? out : riid)); + EXPECT(slot == 27 || mock->tail[slot][2] == out); + EXPECT(mock->calls[slot] == before + 1 && state_of(mock->args[slot][3]) == kRender); + EXPECT(mock->args[slot][0] == word(&props) && mock->args[slot][2] == word(&rt)); + EXPECT(hr_of(raw(device, slot, word(&props), 0, word(&ds), kConsole)) == S_OK); + EXPECT(state_of(mock->args[slot][3]) == kDepth); + // Left alone: a buffer with 0x6, a render target with state 0, a texture without a use flag, any other state. + EXPECT(hr_of(raw(device, slot, word(&props), 0, word(&buffer), kConsole)) == S_OK && state_of(mock->args[slot][3]) == kConsole); + EXPECT(hr_of(raw(device, slot, word(&props), 0, word(&rt), 0)) == S_OK && state_of(mock->args[slot][3]) == 0); + EXPECT(hr_of(raw(device, slot, word(&props), 0, word(&plain), kConsole)) == S_OK && state_of(mock->args[slot][3]) == kConsole); + EXPECT(hr_of(raw(device, slot, word(&props), 0, word(&rt), 0x4)) == S_OK && state_of(mock->args[slot][3]) == 0x4); + } + EXPECT(rt.Flags == D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET && ds.Flags == D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL); + + // Slot 76 (the Xbox resource creation) reaches the PC device's slot 27 with the same mapping. + const IID resource_iid = __uuidof(ID3D12Resource); + void* resource = nullptr; + EXPECT(hr_of(raw8(device, 76, word(&props), 0, word(&rt), kConsole, 0, word(&resource_iid), word(&resource))) == S_OK); + EXPECT(state_of(mock->args[27][3]) == kRender); + EXPECT(hr_of(raw8(device, 76, word(&props), 0, word(&ds), kConsole, 0, word(&resource_iid), word(&resource))) == S_OK); + EXPECT(state_of(mock->args[27][3]) == kDepth); + EXPECT(hr_of(raw8(device, 76, word(&props), 0, word(&buffer), kConsole, 0, word(&resource_iid), word(&resource))) == S_OK); + EXPECT(state_of(mock->args[27][3]) == kConsole); + + EXPECT(xs::device_slot_overridden(27) && xs::device_slot_overridden(53)); + EXPECT(release(device) == 0 && mock->refs == 0); + std::printf("%s: committed textures with state 0x6 reach the PC device as RENDER_TARGET or DEPTH_WRITE; buffers and " + "other states are unchanged\n", g_label); + return 0; +} + +// ---- 7c. Xbox queue ExecuteCommandLists variant (queue slot 35 -> PC slot 10) ---- + +int check_xbox_queue_slots() { + Mock* mock = nullptr; + void* device = make_device(mock, 9, true, true, true); // full-chain list mocks, as check_lists EXPECT(device); void* queue = make_queue(device); EXPECT(queue); @@ -1365,25 +1894,39 @@ int check_xbox_queue_slots() { EXPECT(xs::queue_slot_overridden(35) && xs::queue_slot_overridden(14) && xs::queue_slot_overridden(15)); EXPECT(!xs::queue_slot_overridden(10) && !xs::queue_slot_overridden(34) && !xs::queue_slot_overridden(36)); - // Real objects, not numbers: the array is read to replace list proxies by their real lists, as slot 10's is. - Mock* const list_a = new_mock(Kind::command_list); - Mock* const list_b = new_mock(Kind::command_list); - void* lists[2] = {list_a, list_b}; + // With the console list proxy (#2490) on this branch, slot 35 hands the real queue the lists the way slot 10 does: + // a copy of the array with each list proxy replaced by its real list. So the entries are real objects here (the + // unwrap reads each one's first word), one a list proxy and one a plain object that goes through unchanged, and + // the mock queue records the array it was given. + const IID allocator_iid = __uuidof(ID3D12CommandAllocator); + const IID gcl_iid = __uuidof(ID3D12GraphicsCommandList); + void* allocator = nullptr; + EXPECT(hr_of(raw(device, 9, 0, word(&allocator_iid), word(&allocator))) == S_OK); + void* list = nullptr; + EXPECT(hr_of(raw(device, 12, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, word(allocator), 0, word(&gcl_iid), + word(&list))) == S_OK); + Mock* const real_list = mock->last_child; + EXPECT(xs::is_list_proxy(list) && word(xs::list_proxy_real_list(list)) == word(real_list)); + Mock* const plain = new_mock(Kind::resource); + void* lists[2] = {list, plain}; EXPECT(raw(queue, 35, (0xdeadbeefull << 32) | 2ull, word(lists)) == 0); EXPECT(xs::queue_slot_hits(35) == 1 && xs::queue_slot_first_call_seen(35)); EXPECT(xs::queue_slot_hits(10) == 0); EXPECT(queue_mock->calls[35] == 0 && queue_mock->calls[10] == 1); EXPECT(queue_mock->args[10][0] == 2); - EXPECT(queue_mock->array[10][0] == word(list_a) && queue_mock->array[10][1] == word(list_b)); - EXPECT(lists[0] == list_a && lists[1] == list_b); // the caller's array is not written + EXPECT(queue_mock->array[10][0] == word(real_list) && queue_mock->array[10][1] == word(plain)); + // PC slot 10 itself is the same path. + EXPECT(raw(queue, 10, 2, word(lists)) == 0 && queue_mock->calls[10] == 2); + EXPECT(queue_mock->array[10][0] == word(real_list) && queue_mock->array[10][1] == word(plain)); + EXPECT(release(list) == 0 && release(allocator) == 0); EXPECT(raw(queue, 35, 0, 0) == 0); - EXPECT(xs::queue_slot_hits(35) == 2 && queue_mock->calls[35] == 0 && queue_mock->calls[10] == 2); + EXPECT(xs::queue_slot_hits(35) == 2 && queue_mock->calls[35] == 0 && queue_mock->calls[10] == 3); EXPECT(queue_mock->args[10][0] == 0 && queue_mock->args[10][1] == 0); EXPECT(release(queue) == 0 && release(device) == 0 && mock->refs == 0); - std::printf("%s: queue slot 35 routes ExecuteCommandLists(count, lists) to PC slot 10 with UINT count masking\n", - g_label); + std::printf("%s: queue slot 35 routes ExecuteCommandLists(count, lists) to PC slot 10 with UINT count masking " + "and list proxies unwrapped\n", g_label); return 0; } @@ -1393,10 +1936,11 @@ struct EnvPresenter { int stats = 0, present = 0, suspend = 0, resume = 0; }; -int run_env_slots(bool valid, bool on_slot74 = false) { - const char* frame_interval = on_slot74 ? "74" : valid ? "96" : "2"; +int run_env_slots(bool valid, bool on_slot70 = false, bool on_slot74 = false) { + const char* frame_interval = on_slot70 ? "70" : on_slot74 ? "74" : valid ? "96" : "2"; + const char* schedule_event = valid ? "97" : "2"; - const char* wait_event = valid ? "98" : "2"; + const char* wait_event = on_slot74 ? "74" : valid ? "98" : "2"; const char* queue_x = valid ? "99" : "2"; const char* list_x = valid ? "100" : "2"; const char* frame_statistics = valid ? "101" : "2"; @@ -1416,7 +1960,12 @@ int run_env_slots(bool valid, bool on_slot74 = false) { EXPECT(device); xs::reset_device_proxy_stats(); std::uint64_t token = 0; - if (on_slot74) { + if (on_slot70) { + // SetFrameIntervalX moved onto 70, which also has a built-in handler: the override wins, so (output, interval, + // latency, flags) is a frame-interval call, never a shader-resource view whose handle is the latency. + EXPECT(hr_of(raw(device, 70, 0, 16667, 1, 0)) == S_OK && mock->calls[70] == 0 && mock->calls[18] == 0); + EXPECT(hr_of(raw(device, 78, 0, 16667, 1, 0)) == S_OK && mock->calls[78] == 1); // the old default is a PC slot now + } else if (on_slot74) { // SetFrameIntervalX moved onto 74, which also has a built-in handler: the override wins, so (output, interval, // latency, flags) is a frame-interval call that reaches no PC slot, not the stand-in that ignores its words. EXPECT(hr_of(raw(device, 74, 0, 16667, 1, 0)) == S_OK && mock->calls[74] == 0); @@ -1443,7 +1992,7 @@ int run_env_slots(bool valid, bool on_slot74 = false) { EXPECT(release(allocator) == 0); // The presenter answers frame statistics at 101 only (81 is not routed, so the mock refuses it); PresentX - // stays at 30, SuspendX answers at 33, and ResumeX, asked for 30, is unrouted, so 32 is refused. + // stays at 30, SuspendX answers at 33, and ResumeX, asked for 30, is unrouted, so 32 never reaches it. EnvPresenter env{}; xs::PresentationHandler h{}; h.context = &env; @@ -1469,7 +2018,8 @@ int run_env_slots(bool valid, bool on_slot74 = false) { EXPECT(hr_of(raw(device, 81, 77, 0x1a, word(&count), 0)) == E_NOTIMPL && env.stats == 1); EXPECT(hr_of(raw(queue, 30, 1, 0, 0)) == S_OK && env.present == 1); EXPECT(hr_of(raw(queue, 33)) == S_OK && env.suspend == 1); - EXPECT(hr_of(raw(queue, 32)) == E_NOTIMPL && env.resume == 0); + raw(queue, 32); // a console queue slot: answered by the queue proxy, never by the presenter's ResumeX + EXPECT(env.resume == 0); EXPECT(xs::set_presentation_handler(device, nullptr)); EXPECT(release(queue) == 0); } else { @@ -1479,11 +2029,196 @@ int run_env_slots(bool valid, bool on_slot74 = false) { EXPECT(hr_of(raw(device, 79, 0, 0, 0, 0)) == S_OK && mock->calls[79] == 0); EXPECT(hr_of(raw(device, 80, 0, 0, 0, 0, word(&token))) == S_OK && token && mock->calls[80] == 0); EXPECT(hr_of(raw(device, 81, 0, 0, 0, 0)) == S_FALSE); // the default GetFrameStatisticsX slot, unattached - EXPECT(hr_of(raw(device, 71)) == S_OK && mock->calls[71] == 1); // not an Xbox slot: forwarded + // Slot 71 is the Xbox placed-UAV view of the title's own memory (d19339b07), not a PC slot: the proxy + // handles it before the PC vtable, so the PC slot 71 (CreateSamplerFeedbackUnorderedAccessView) is never + // reached and the mock records nothing. + EXPECT(hr_of(raw(device, 71)) == S_OK && mock->calls[71] == 0 && xs::device_slot_hits(71) == 1); + // A PC slot that is neither an Xbox route nor one of the defaults is still forwarded unchanged. + EXPECT(hr_of(raw(device, 72)) == S_OK && mock->calls[72] == 1); // not an Xbox slot: forwarded } EXPECT(release(device) == 0 && mock->refs == 0); std::printf("%s: environment slot overrides %s\n", g_label, - valid ? "move all five routes" : "outside 3..127 are ignored"); + valid ? "move all six routes" : "outside 3..127 are ignored"); + return 0; +} + +// ---- 9. Command lists (device slot 12): the console-shaped proxy and AllocateUploadMemory ---- + +int check_lists() { + const IID allocator_iid = __uuidof(ID3D12CommandAllocator); + const IID gcl_iid = __uuidof(ID3D12GraphicsCommandList); + Mock* mock = nullptr; + void* device = make_device(mock, 9, true, true, true); + EXPECT(device); + const unsigned long device_refs = xs::device_proxy_ref_count(device); + void* allocator = nullptr; + EXPECT(hr_of(raw(device, 9, 0, word(&allocator_iid), word(&allocator))) == S_OK); + Mock* const real_allocator = mock->last_child; + // CreateCommandList(node_mask, type, allocator, pso, iid, out): the allocator proxy is unwrapped on the way + // in and the list comes back console-shaped. + void* list = nullptr; + EXPECT(hr_of(raw(device, 12, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, word(allocator), 0, word(&gcl_iid), + word(&list))) == S_OK); + Mock* const real = mock->last_child; + EXPECT(real->kind == Kind::list && mock->args[12][2] == word(real_allocator)); + EXPECT(xs::is_list_proxy(list) && word(xs::list_proxy_real_list(list)) == word(real)); + EXPECT(xs::device_proxy_ref_count(device) == device_refs + 2); // allocator + list + // The console object body sits at +0x18 with the write cursor pinned at the record limits. + const auto* body = reinterpret_cast(word(list) + 0x18); + // Object offsets +0x18/+0x28/+0x30 are body[0]/body[2]/body[3]: the cursor is pinned at both record limits. + EXPECT(body[0] == body[2] && body[0] == body[3]); + // GetDevice answers with the Xbox-ABI device. + void* found = nullptr; + const IID device_iid = __uuidof(ID3D12Device); + EXPECT(hr_of(raw(list, 7, word(&device_iid), word(&found))) == S_OK && found == device); + EXPECT(release(found) >= 1); + // A forwarded console slot: Dispatch is console 14 (PC slot 14 too — order holds through 26). + EXPECT(hr_of(raw(list, 14, 1, 1, 1)) == S_OK && real->calls[14] == 1); + // Console slot 139 is the retail title's Reset(allocator, pso) (Pipodi measured it on 1.0.2.1): the allocator + // proxy unwraps and the call reaches the real list's PC slot 10. + EXPECT(hr_of(raw(list, 139, word(allocator), 0)) == S_OK && real->calls[10] == 1 && + real->args[10][0] == word(real_allocator)); + // Console-only extras (27-30) and the unmeasured tail are recorded and return 0, never forwarded. + EXPECT(raw(list, 27, 1, 2, 3, 4) == 0 && real->calls[27] == 0); + EXPECT(raw(list, 148, 0, 16) == 0); // AllocateUploadMemory(0, ...) refuses + // AllocateUploadMemory carves from the upload arena; a later root SRV gets a real address for it. + const std::uint64_t p1 = raw(list, 148, 4096, 64); + const std::uint64_t p2 = raw(list, 148, 16, 16); + EXPECT(p1 && p2 > p1 && (p1 & 63) == 0 && p2 >= p1 + 4096); + // A size that wraps the arena arithmetic is refused and moves nothing: UINT64_MAX used to return a + // pointer and corrupt the cursor so the next request re-handed the same range (daemosofchaos's + // report on #2490). A non-power-of-two alignment is unmeasured and refused rather than guessed. + EXPECT(raw(list, 148, ~0ull, 16) == 0); + EXPECT(raw(list, 148, 16, 48) == 0); + const std::uint64_t p3 = raw(list, 148, 16, 16); + EXPECT(p3 && p3 == p2 + 16); // fresh memory right after p2 — both refusals left the cursor alone + // Console 43 -> PC 39 (SetComputeRootShaderResourceView): the arena pointer crosses as a GPU VA (the mock + // device cannot map a real buffer, so the fallback arena translates to the same address). + EXPECT(hr_of(raw(list, 43, 0, p1)) == S_OK && real->calls[39] == 1 && real->args[39][1] == p1); + // The view-struct paths (IASetIndexBuffer console 47 -> PC 43, IASetVertexBuffers console 48 -> PC 44) reach + // the real list; the arena VAs inside the views are rewritten in the proxy's copies. + D3D12_INDEX_BUFFER_VIEW ib_view{}; + ib_view.BufferLocation = p1; + EXPECT(hr_of(raw(list, 47, word(&ib_view))) == S_OK && real->calls[43] == 1); + D3D12_VERTEX_BUFFER_VIEW vb_views[2]{}; + vb_views[0].BufferLocation = p1; + vb_views[1].BufferLocation = 0xDEAD0000; // a VA outside the arena passes through + EXPECT(hr_of(raw(list, 48, 0, 2, word(vb_views))) == S_OK && real->calls[44] == 1); + D3D12_STREAM_OUTPUT_BUFFER_VIEW so_view{}; + so_view.BufferLocation = p1; + so_view.BufferFilledSizeLocation = p2; + EXPECT(hr_of(raw(list, 49, 0, 1, word(&so_view))) == S_OK && real->calls[45] == 1); + // The console tail past the PC chain is refused with E_NOTIMPL only when the mapped PC slot is missing. + EXPECT(hr_of(raw(list, 146, word(list), 0)) == S_OK && real->calls[80] == 1); // enhanced Barrier -> GCL7 80 + EXPECT(release(list) == 0 && real->refs == 0); + EXPECT(release(allocator) == 0 && real_allocator->refs == 0); + EXPECT(xs::device_proxy_ref_count(device) == device_refs); + EXPECT(release(device) == 0 && mock->refs == 0); + + // A PC caller (console_lists=false — the default, what the GPU harnesses use) gets the real list back: + // slot 12 returns the mock, not a proxy, so its PC vtable indices stay valid. + Mock* pc_mock = new_mock(Kind::device); + pc_mock->device_level = 9; + pc_mock->refs = 1; + void* pc_device = nullptr; + EXPECT(SUCCEEDED(xs::create_device_proxy(reinterpret_cast(pc_mock), __uuidof(ID3D12Device), + &pc_device))); + void* pc_list = nullptr; + EXPECT(hr_of(raw(pc_device, 12, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, 0, 0, word(&gcl_iid), + word(&pc_list))) == S_OK); + EXPECT(pc_list && !xs::is_list_proxy(pc_list) && + reinterpret_cast(pc_list)->kind == Kind::command_list); + EXPECT(release(pc_list) == 0); + EXPECT(release(pc_device) == 0 && pc_mock->refs == 0); + std::printf("%s: lists come back console-shaped (cursor pinned, GetDevice, Dispatch forwarded, extras " + "recorded); AllocateUploadMemory hands out arena pointers a root SRV receives\n", g_label); + return 0; +} + +// ---- 10. SignalX layout detection ------------------------------------------------------------ +// A fence at queue slot 25 while the layout is still unknown is itself the newer-layout evidence: a title that +// signals only through SignalX never reaches Signal/Wait at 16/17, so an unanswered SignalX used to return +// S_OK having signalled nothing — a waiter on that fence value then hangs (shdann's report on #2490: the first +// SignalX gave hr=0 calls=0, the value was lost). + +int check_signalx_detection() { + Mock* mock = nullptr; + void* device = make_device(mock, 9, true); + EXPECT(device); + void* queue = make_queue(device); + void* fence = make_fence(device); + EXPECT(queue && fence); + Mock* const queue_mock = reinterpret_cast(xs::queue_proxy_real_queue(queue)); + const auto real_fence = word(xs::fence_proxy_real_fence(fence)); + // Undetected layout, fence at slot 25: forwarded as Signal and pins the device to the newer layout. + EXPECT(hr_of(raw(queue, 25, word(fence), 7)) == S_OK && queue_mock->calls[14] == 1 && + queue_mock->args[14][0] == real_fence && queue_mock->args[14][1] == 7); + // Now proven newer: Signal at 16 and SignalX at 25 keep forwarding. + EXPECT(hr_of(raw(queue, 16, word(fence), 8)) == S_OK && queue_mock->calls[14] == 2 && + queue_mock->args[14][1] == 8); + EXPECT(hr_of(raw(queue, 25, word(fence), 9)) == S_OK && queue_mock->calls[14] == 3 && + queue_mock->args[14][1] == 9); + // A second queue on the same device inherits the shared detection. + void* queue2 = make_queue(device); + EXPECT(queue2); + Mock* const queue2_mock = reinterpret_cast(xs::queue_proxy_real_queue(queue2)); + EXPECT(hr_of(raw(queue2, 25, word(fence), 11)) == S_OK && queue2_mock->calls[14] == 1 && + queue2_mock->args[14][1] == 11); + EXPECT(release(queue2) == 0); + EXPECT(release(queue) == 0 && release(fence) == 0 && release(device) == 0 && mock->refs == 0); + + // Proven older stays older: a non-fence at slot 16 pins the older layout (the frequency getter), and a + // fence at 25 afterwards is an unmodelled console method — S_OK with no forward, not a second detection. + Mock* mock2 = nullptr; + void* device2 = make_device(mock2, 9, true); + void* queue3 = make_queue(device2); + void* fence3 = make_fence(device2); + EXPECT(device2 && queue3 && fence3); + Mock* const queue3_mock = reinterpret_cast(xs::queue_proxy_real_queue(queue3)); + EXPECT(hr_of(raw(queue3, 16, 0, 0)) == S_OK && queue3_mock->calls[16] == 1 && + queue3_mock->calls[14] == 0); + EXPECT(hr_of(raw(queue3, 25, word(fence3), 13)) == S_OK && queue3_mock->calls[14] == 0); + // The older SignalX at slot 23 still forwards under the pinned-older layout. + EXPECT(hr_of(raw(queue3, 23, word(fence3), 15)) == S_OK && queue3_mock->calls[14] == 1 && + queue3_mock->args[14][1] == 15); + EXPECT(release(queue3) == 0 && release(fence3) == 0 && release(device2) == 0 && mock2->refs == 0); + + // A fence at the older SignalX slot while undetected forwards but does NOT pin: a newer title could reach + // an unmodelled slot-23 method with a fence argument, and a premature older pin would drop its real + // SignalX at 25. + Mock* mock3 = nullptr; + void* device3 = make_device(mock3, 9, true); + void* queue4 = make_queue(device3); + void* fence4 = make_fence(device3); + EXPECT(device3 && queue4 && fence4); + Mock* const queue4_mock = reinterpret_cast(xs::queue_proxy_real_queue(queue4)); + EXPECT(hr_of(raw(queue4, 23, word(fence4), 17)) == S_OK && queue4_mock->calls[14] == 1 && + queue4_mock->args[14][1] == 17); + EXPECT(hr_of(raw(queue4, 25, word(fence4), 19)) == S_OK && queue4_mock->calls[14] == 2 && + queue4_mock->args[14][1] == 19); + EXPECT(release(queue4) == 0 && release(fence4) == 0 && release(device3) == 0 && mock3->refs == 0); + + // Ambiguous slot 18 on an undetected queue: the older GetDesc or the newer frequency getter. It is + // served as the frequency query — a desc write is far wider than the 8 bytes a frequency caller + // passes (a title often reads the frequency before its first fence call); once a fence proves the + // layout the same call keeps reaching the getter through the shifted path. + Mock* mock4 = nullptr; + void* device4 = make_device(mock4, 9, true); + void* queue5 = make_queue(device4); + void* fence5 = make_fence(device4); + EXPECT(device4 && queue5 && fence5); + Mock* const queue5_mock = reinterpret_cast(xs::queue_proxy_real_queue(queue5)); + UINT64 hz = 0; + EXPECT(hr_of(raw(queue5, 18, word(&hz))) == S_OK && hz == 1000000 && + queue5_mock->calls[16] == 1 && queue5_mock->calls[18] == 0); + hz = 0; + EXPECT(hr_of(raw(queue5, 16, word(fence5), 8)) == S_OK); + EXPECT(hr_of(raw(queue5, 18, word(&hz))) == S_OK && hz == 1000000 && + queue5_mock->calls[16] == 2 && queue5_mock->calls[18] == 0); + EXPECT(release(queue5) == 0 && release(fence5) == 0 && release(device4) == 0 && mock4->refs == 0); + std::printf("xs_proxy_mock: SignalX on an undetected queue's slot 25 forwards as Signal and marks the " + "newer layout; proven-older stays older, a fence at 23 does not pin, and an undetected " + "slot 18 answers the frequency getter\n"); return 0; } @@ -1921,11 +2656,14 @@ int check_tail(bool want_guarded) { // Signal (14) still reaches the real queue, with the real fence. EXPECT(hr_of(raw(queue, 14, word(fence), 5)) == S_OK && queue_mock->calls[14] == 1 && queue_mock->args[14][0] == word(xs::fence_proxy_real_fence(fence)) && queue_mock->args[14][1] == 5); + // Console-only queue methods (the tail past the PC chain, SignalX, PresentX) report S_OK instead of + // refusing: frame pacing flows through them. Nothing is forwarded — the real queue never sees them. for (unsigned slot = 19; slot < xs::queue_proxy_table_size(); ++slot) { - if (xs::queue_slot_overridden(slot)) continue; - EXPECT(hr_of(raw(queue, slot)) == E_NOTIMPL && queue_mock->calls[slot] == 0); + if (xs::queue_slot_overridden(slot)) continue; // slot 35 is forwarded (check_xbox_queue_slots) + EXPECT(hr_of(raw(queue, slot)) == S_OK && queue_mock->calls[slot] == 0); } - for (unsigned slot = 12; slot < xs::fence_proxy_table_size(); ++slot) EXPECT(hr_of(raw(fence, slot)) == E_NOTIMPL); + EXPECT(raw(fence, 12) != 0); // the completed value's address (check_fence_completed_value) + for (unsigned slot = 13; slot < xs::fence_proxy_table_size(); ++slot) EXPECT(hr_of(raw(fence, slot)) == E_NOTIMPL); EXPECT(xs::queue_table_overruns() == 0 && xs::fence_table_overruns() == 0); EXPECT(release(queue) == 0 && release(fence) == 0 && release(device) == 0 && mock->refs == 0); return 0; @@ -2075,7 +2813,7 @@ int check_committed_resource_leases() { desc.SampleDesc.Count = 1; desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; - // Slot 76: the lease is the console-tiled size slot 25 answers (135 tiles), not the PC one. + // Slot 76: the lease is the console tile size (135 tiles), not the PC one. void* resource = nullptr; std::uint64_t words76[10] = {word(&heap), 0, word(&desc), 0, 0, word(&kResourceIid), word(&resource), 0, 0, 0}; EXPECT(hr_of(raw10(device, 76, words76)) == S_OK && resource); @@ -2104,6 +2842,19 @@ int check_committed_resource_leases() { EXPECT(release(resource) == 0 && g_heap_hook.free_calls == 2); #endif + // A driver whose PC answer is above the console tiles (AMD's Windows driver: 513 x 64 KiB for a 3840 x 2160 RGBA8 + // target, 510 tiles on the console) still leases the tiles: the title's 64 MiB range holds two of those and no more. + desc.Width = 3840; + desc.Height = 2160; + g_texture_size_bias = 6 * 65536; // the mock's 507 x 64 KiB becomes 513 x 64 KiB + resource = nullptr; + EXPECT(hr_of(raw10(device, 76, words76)) == S_OK && resource); + EXPECT(g_heap_hook.last_alloc_size == 30ull * 17 * 65536); + EXPECT(release(resource) == 0); + g_texture_size_bias = 0; + desc.Width = 1920; + desc.Height = 1080; + // Hooks that return null: the resource is still created, and nothing is freed later. g_heap_hook.next_ptr = nullptr; resource = nullptr; @@ -2123,6 +2874,144 @@ int check_committed_resource_leases() { return 0; } +int check_list_cpu_handles() { + g_heap_hook = {}; + xs::set_descriptor_heap_allocator(&mock_heap_alloc, &mock_heap_free); + + Mock* real = nullptr; + void* device = make_device(real, 9, true, true, true); + EXPECT(device != nullptr); + + constexpr SIZE_T kCustomBase = 0x77880000ull; + g_heap_hook.next_ptr = reinterpret_cast(kCustomBase); + D3D12_DESCRIPTOR_HEAP_DESC desc{}; + desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV; + desc.NumDescriptors = 8; + const IID iid_heap = __uuidof(ID3D12DescriptorHeap); + void* heap = nullptr; + EXPECT(SUCCEEDED(hr_of(raw(device, 14, word(&desc), word(&iid_heap), word(&heap))))); + EXPECT(heap != nullptr && raw(heap, 9) == kCustomBase); + + const IID iid_alloc = __uuidof(ID3D12CommandAllocator); + const IID iid_gcl = __uuidof(ID3D12GraphicsCommandList); + void* allocator = nullptr; + EXPECT(SUCCEEDED(hr_of(raw(device, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, word(&iid_alloc), word(&allocator))))); + void* list = nullptr; + EXPECT(SUCCEEDED(hr_of(raw(device, 12, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, word(allocator), 0, + word(&iid_gcl), word(&list))))); + EXPECT(list != nullptr && xs::is_list_proxy(list)); + Mock* const real_list = reinterpret_cast(xs::list_proxy_real_list(list)); + EXPECT(real_list != nullptr); + + const SIZE_T off1 = 1 * kMockDescriptorInc; + const SIZE_T off4 = 4 * kMockDescriptorInc; + const SIZE_T off6 = 6 * kMockDescriptorInc; + const SIZE_T outside = kCustomBase + desc.NumDescriptors * kMockDescriptorInc; + + // Console slot 50 -> PC slot 46 (OMSetRenderTargets): multiple RTV handles + DSV handle, caller arrays untouched. + { + D3D12_CPU_DESCRIPTOR_HANDLE rtvs[2] = {{kCustomBase + off1}, {outside}}; + D3D12_CPU_DESCRIPTOR_HANDLE dsv{kCustomBase + off6}; + raw(list, 50, 2, word(rtvs), FALSE, word(&dsv)); + EXPECT(real_list->calls[46] == 1); + EXPECT(real_list->om_rtv_count == 2 && real_list->om_single_range == FALSE); + EXPECT(real_list->om_rtvs[0] == kMockHeapCpuStart + off1 && real_list->om_rtvs[1] == outside); + EXPECT(real_list->om_has_dsv && real_list->om_dsv == kMockHeapCpuStart + off6); + EXPECT(rtvs[0].ptr == kCustomBase + off1 && rtvs[1].ptr == outside && dsv.ptr == kCustomBase + off6); + } + // Single descriptor range: only rtvs[0] is read and translated even when NumRenderTargetDescriptors > 1; null DSV. + { + D3D12_CPU_DESCRIPTOR_HANDLE single_rtv{kCustomBase + off4}; + raw(list, 50, 3, word(&single_rtv), TRUE, 0); + EXPECT(real_list->calls[46] == 2); + EXPECT(real_list->om_rtv_count == 3 && real_list->om_single_range == TRUE); + EXPECT(real_list->om_rtvs[0] == kMockHeapCpuStart + off4 && !real_list->om_has_dsv); + EXPECT(single_rtv.ptr == kCustomBase + off4); + } + // Zero RTVs with a non-null DSV. + { + D3D12_CPU_DESCRIPTOR_HANDLE dsv{kCustomBase + off1}; + raw(list, 50, 0, 0, FALSE, word(&dsv)); + EXPECT(real_list->calls[46] == 3); + EXPECT(real_list->om_rtv_count == 0 && real_list->om_has_dsv && real_list->om_dsv == kMockHeapCpuStart + off1); + } + // Count beyond D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT (8): forwards safely without overrunning stack scratch. + { + D3D12_CPU_DESCRIPTOR_HANDLE nine[9]{}; + for (UINT i = 0; i < 9; ++i) nine[i].ptr = outside + i * kMockDescriptorInc; + raw(list, 50, 9, word(nine), FALSE, 0); + EXPECT(real_list->calls[46] == 4 && real_list->om_rtv_count == 9); + } + + // Console slot 51 -> PC slot 47 (ClearDepthStencilView): CPU handle translated AND FLOAT Depth in XMM3 preserved. + { + using ClearDsvFn = void(WINAPI*)(void*, D3D12_CPU_DESCRIPTOR_HANDLE, D3D12_CLEAR_FLAGS, FLOAT, UINT8, UINT, + const D3D12_RECT*); + void* const* list_vtbl = *reinterpret_cast(list); + auto clear_dsv = reinterpret_cast(list_vtbl[51]); + const D3D12_RECT rect{1, 2, 3, 4}; + clear_dsv(list, D3D12_CPU_DESCRIPTOR_HANDLE{kCustomBase + off6}, + D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, 0.375f, 0x5Au, 1, &rect); + EXPECT(real_list->calls[47] == 1); + EXPECT(real_list->clear_dsv_handle == kMockHeapCpuStart + off6); + EXPECT(real_list->clear_dsv_flags == (D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL)); + EXPECT(real_list->clear_dsv_depth == 0.375f); + EXPECT(real_list->clear_dsv_stencil == 0x5Au); + EXPECT(real_list->clear_dsv_num_rects == 1 && real_list->clear_dsv_rects == &rect); + + // Second call (past first-call log): outside-range handle passes through and a different depth float holds. + clear_dsv(list, D3D12_CPU_DESCRIPTOR_HANDLE{outside}, D3D12_CLEAR_FLAG_DEPTH, 0.625f, 0u, 0, nullptr); + EXPECT(real_list->calls[47] == 2); + EXPECT(real_list->clear_dsv_handle == outside); + EXPECT(real_list->clear_dsv_depth == 0.625f); + EXPECT(real_list->clear_dsv_num_rects == 0 && real_list->clear_dsv_rects == nullptr); + } + + // Console slot 52 -> PC slot 48 (ClearRenderTargetView): CPU handle translated, color and rects forwarded. + { + const FLOAT color[4] = {0.25f, 0.5f, 0.75f, 1.0f}; + const D3D12_RECT rect{0, 0, 8, 8}; + raw(list, 52, kCustomBase + off1, word(color), 1, word(&rect)); + EXPECT(real_list->calls[48] == 1); + EXPECT(real_list->args[48][0] == kMockHeapCpuStart + off1); + EXPECT(real_list->args[48][1] == word(color) && real_list->args[48][2] == 1 && + real_list->args[48][3] == word(&rect)); + + raw(list, 52, outside, word(color), 0, 0); + EXPECT(real_list->calls[48] == 2 && real_list->args[48][0] == outside); + } + + // Console slots 53/54 -> PC slots 49/50 (ClearUnorderedAccessViewUint/Float): GPU handle kept, CPU handle remapped. + { + const UINT uvals[4] = {1, 2, 3, 4}; + const FLOAT fvals[4] = {1.0f, 0.5f, 0.25f, 0.0f}; + const D3D12_RECT rect{2, 2, 6, 6}; + raw(list, 53, kMockHeapGpuStart + off1, kCustomBase + off4, 0x3333ull, word(uvals), 1, word(&rect)); + EXPECT(real_list->calls[49] == 1); + EXPECT(real_list->args[49][0] == kMockHeapGpuStart + off1); + EXPECT(real_list->args[49][1] == kMockHeapCpuStart + off4); + EXPECT(real_list->args[49][2] == 0x3333ull && real_list->args[49][3] == word(uvals) && + real_list->args[49][4] == 1 && real_list->args[49][5] == word(&rect)); + + raw(list, 54, kMockHeapGpuStart + off6, kCustomBase + off6, 0x4444ull, word(fvals), 0, 0); + EXPECT(real_list->calls[50] == 1); + EXPECT(real_list->args[50][0] == kMockHeapGpuStart + off6); + EXPECT(real_list->args[50][1] == kMockHeapCpuStart + off6); + EXPECT(real_list->args[50][2] == 0x4444ull && real_list->args[50][3] == word(fvals) && + real_list->args[50][4] == 0 && real_list->args[50][5] == 0); + + raw(list, 54, kMockHeapGpuStart, outside, 0x4444ull, word(fvals), 0, 0); + EXPECT(real_list->calls[50] == 2 && real_list->args[50][1] == outside); + } + + EXPECT(raw(list, 2) == 0); + EXPECT(raw(allocator, 2) == 0); + EXPECT(raw(heap, 2) == 0); + EXPECT(raw(device, 2) == 0 && real->refs == 0); + xs::set_descriptor_heap_allocator(nullptr, nullptr); + return 0; +} + // ---- Guard-region setup failures: this executable's import table, patched before the first proxy table ---- std::atomic g_injected{0}; @@ -2196,19 +3085,60 @@ int run_fault_mode(const char* mode) { g_armed = false; if (failed) return 1; EXPECT(g_injected.load() > 0); // the proxy's own call was the one refused - std::printf("%s: %s refused %d time(s): the tables %s guarded, the proxies forward and refuse their tail as " - "before\n", m.flag, m.function, g_injected.load(), m.guarded ? "stay" : "are not"); + std::printf("%s: %s refused %d time(s): the tables %s guarded, the proxies forward and answer their " + "console tail as before\n", m.flag, m.function, g_injected.load(), + m.guarded ? "stay" : "are not"); return 0; } return 2; } +// ---- 12. List tail slot names (D3D-445) --------------------------------------------------------------------- +// From CopyTextureRegionX on, the newer layout sits two slots later than the older one (d3d12_xs_console_abi.md +// 5.3). A diagnostic name follows the device-wide layout, so slot 85 of the newer layout and slot 83 of the older +// layout are both CopyTextureRegionX, and neither number gets that name under the other layout. + +int check_list_tail_names() { + const unsigned char older = xs::kConsoleLayoutOlder, newer = xs::kConsoleLayoutNewer; + const auto same = [](const char* a, const char* b) { return a && b && std::strcmp(a, b) == 0; }; + EXPECT(same(xs::list_tail_slot_name(83, older), "CopyTextureRegionX")); + EXPECT(same(xs::list_tail_slot_name(85, newer), "CopyTextureRegionX")); + // The same numbers under the other layout are different methods. + EXPECT(!xs::list_tail_slot_name(83, newer)); // not a measured slot of the newer layout + EXPECT(xs::list_tail_slot_name(85, older) && !same(xs::list_tail_slot_name(85, older), "CopyTextureRegionX")); + // Every measured newer->older pair has one name, and the eight names differ. + const unsigned pairs[][2] = {{85, 83}, {86, 84}, {87, 85}, {90, 88}, {91, 89}, {92, 90}, {95, 93}, {96, 94}}; + for (const auto& pair : pairs) { + EXPECT(same(xs::list_tail_slot_name(pair[0], newer), xs::list_tail_slot_name(pair[1], older))); + for (const auto& other : pairs) + EXPECT(pair[1] == other[1] || + !same(xs::list_tail_slot_name(pair[1], older), xs::list_tail_slot_name(other[1], older))); + } + // Slots outside the measured set have no tail name in either layout, and no slot has one before the layout is + // known: the log then prints the slot number only, as before. + for (unsigned slot = 0; slot < 160; ++slot) { + bool older_tail = false, newer_tail = false; + for (const auto& pair : pairs) { + newer_tail = newer_tail || slot == pair[0]; + older_tail = older_tail || slot == pair[1]; + } + EXPECT((xs::list_tail_slot_name(slot, older) != nullptr) == older_tail); + EXPECT((xs::list_tail_slot_name(slot, newer) != nullptr) == newer_tail); + EXPECT(!xs::list_tail_slot_name(slot, 0)); + EXPECT(!xs::list_tail_slot_name(slot, 3)); + } + return 0; +} + // Device slot 127 is ID3D12Device10::CreateCommittedResource3 with Xbox descriptors (RT-5 stop 15). Past the PC // vtable it used to be refused with E_NOTIMPL; the PC device must now get the resource with the Xbox layout word and // flag bits gone and every other word as the title passed it. int check_committed_resource3_x() { #ifdef __ID3D12Device10_INTERFACE_DEFINED__ constexpr std::uint32_t kXboxLayoutTiled = 0x101, kXboxFlagBit = 0x40000, kBarrierLayoutUndefined = 0xFFFFFFFFu; + constexpr std::uint32_t kTightAlignment = 0x400, // D3D12_RESOURCE_FLAG_USE_TIGHT_ALIGNMENT + kHeapNotZeroed = 0x1000; // D3D12_HEAP_FLAG_CREATE_NOT_ZEROED + static const int session_sentinel = 0; D3D12_HEAP_PROPERTIES heap{}; heap.Type = D3D12_HEAP_TYPE_DEFAULT; D3D12_CLEAR_VALUE clear{}; @@ -2224,7 +3154,7 @@ int check_committed_resource3_x() { texture.SampleDesc.Count = 1; texture.Layout = static_cast(kXboxLayoutTiled); texture.Flags = static_cast(D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | - D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | kXboxFlagBit); + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | kXboxFlagBit | kTightAlignment); // A PC device with ID3D12Device10: the render target comes back, as the console's call returns it. Mock* mock = nullptr; @@ -2233,22 +3163,25 @@ int check_committed_resource3_x() { xs::reset_device_proxy_stats(); g_committed3 = {}; void* resource = nullptr; - std::uint64_t words[10] = {word(&heap), D3D12_HEAP_FLAG_NONE, word(&texture), kBarrierLayoutUndefined, - word(&clear), 0, 2, word(castable), word(&kResourceIid), word(&resource)}; + std::uint64_t words[10] = {word(&heap), kHeapNotZeroed, word(&texture), kBarrierLayoutUndefined, + word(&clear), word(&session_sentinel), 2, word(castable), word(&kResourceIid), word(&resource)}; EXPECT(hr_of(raw10(device, 127, words)) == S_OK); EXPECT(resource && reinterpret_cast(resource)->kind == Kind::resource); EXPECT(g_committed3.calls == 1 && xs::device_slot_hits(127) == 1); - EXPECT(g_committed3.heap == &heap && g_committed3.clear == &clear && !g_committed3.session); + EXPECT(g_committed3.heap == &heap && g_committed3.clear == &clear); + EXPECT(g_committed3.heap_flags == static_cast(kHeapNotZeroed)); // the title's heap flags + EXPECT(g_committed3.session == &session_sentinel); // and protected session EXPECT(g_committed3.layout == kBarrierLayoutUndefined); EXPECT(g_committed3.castable_count == 2 && g_committed3.castable_formats == castable); EXPECT(g_committed3.riid == &kResourceIid); EXPECT(g_committed3.desc.Layout == D3D12_TEXTURE_LAYOUT_UNKNOWN); - EXPECT(g_committed3.desc.Flags == + // The Xbox-only bit goes, and so does tight alignment, which is not in the slot 127 mask (kPcResourceFlagsMask). + EXPECT(static_cast(g_committed3.desc.Flags) == (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)); EXPECT(g_committed3.desc.Width == 1920 && g_committed3.desc.Height == 1080 && g_committed3.desc.Format == DXGI_FORMAT_R8G8B8A8_TYPELESS && g_committed3.desc.SampleDesc.Count == 1); EXPECT(texture.Layout == static_cast(kXboxLayoutTiled)); // the title's description is read only - static_cast(release(resource)); + EXPECT(release(resource) == 0); // the title's one reference is the only one: nothing leaked, nothing extra // A buffer takes the row-major layout. D3D12_RESOURCE_DESC1 buffer = texture; @@ -2261,6 +3194,7 @@ int check_committed_resource3_x() { resource = nullptr; EXPECT(hr_of(raw10(device, 127, words)) == S_OK && resource); EXPECT(g_committed3.calls == 2 && g_committed3.desc.Layout == D3D12_TEXTURE_LAYOUT_ROW_MAJOR); + EXPECT(release(resource) == 0); // The PC device's own refusal reaches the title with a null object. mock->create_result = E_OUTOFMEMORY; @@ -2269,10 +3203,13 @@ int check_committed_resource3_x() { EXPECT(hr_of(raw10(device, 127, words)) == E_OUTOFMEMORY && !resource); mock->create_result = S_OK; - // A null description, IID or output is refused before the PC device is called. + // A null heap, description, IID or output is refused before the PC device is called. const unsigned before = g_committed3.calls; std::uint64_t bad[10]; std::memcpy(bad, words, sizeof(bad)); + bad[0] = 0; + EXPECT(hr_of(raw10(device, 127, bad)) == E_POINTER); + std::memcpy(bad, words, sizeof(bad)); bad[2] = 0; EXPECT(hr_of(raw10(device, 127, bad)) == E_POINTER); std::memcpy(bad, words, sizeof(bad)); @@ -2285,6 +3222,24 @@ int check_committed_resource3_x() { EXPECT(xs::device_slot_overridden(127)); EXPECT(release(device) == 0); + // A PC device whose ID3D12Device10 is another pointer than the device itself: the call goes to that one, and the + // reference the proxy took on it is given back. The base pointer is a trap that answers E_UNEXPECTED. + Mock* split_mock = nullptr; + void* split_device = make_device(split_mock, 10, true); + EXPECT(split_device); + Mock* alias = new_mock(Kind::device); + alias->device_level = 10; + alias->refs = 1; + split_mock->device10_alias = alias; + split_mock->create_result = E_UNEXPECTED; + resource = nullptr; + words[9] = word(&resource); + EXPECT(hr_of(raw10(split_device, 127, words)) == S_OK && resource); + EXPECT(g_committed3.device == alias); + EXPECT(alias->refs == 1); + EXPECT(release(resource) == 0); + EXPECT(release(split_device) == 0); + // A PC device that stops at ID3D12Device9 has no CreateCommittedResource3: E_NOTIMPL, a null object, no PC call. Mock* old_mock = nullptr; void* old_device = make_device(old_mock, 9, true); @@ -2329,22 +3284,20 @@ int check_console_command_list() { EXPECT(xs::console_to_pc_list_slot(146) == 80); // GCL7 Barrier EXPECT(xs::console_to_pc_list_slot(148) == xs::kListNotForwarded); // AllocateUploadMemory + xs::reset_device_proxy_stats(); // the list slot counts below start from this test Mock* mock_device = nullptr; void* device = make_device(mock_device, 11, true); EXPECT(device != nullptr); - // 2. PC Slot 12 vs Xbox Slot 73 - // PC Slot 12 returns unwrapped list directly, so PC tests like tiny_frame can call slot 48 (ClearRenderTargetView) + // 2. Slot 12 and Xbox slot 73. On a device proxy made for console callers (console_lists, as make_device does), + // slot 12 gives the console list proxy too: the merge into main kept the boot stack's slot 12 (main's form + // returned the unwrapped PC list here). PC callers get PC lists from a proxy made with console_lists=false + // (check_lists covers both). void* pc_list = nullptr; const IID list_iid = __uuidof(ID3D12GraphicsCommandList); EXPECT(hr_of(raw(device, 12, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, 0, 0, word(&list_iid), word(&pc_list))) == S_OK); EXPECT(pc_list != nullptr); - EXPECT(!xs::is_command_list_proxy(pc_list)); - Mock* real_pc_list = reinterpret_cast(pc_list); - EXPECT(real_pc_list->kind == Kind::command_list); - // In PC ABI, slot 48 is ClearRenderTargetView - raw(pc_list, 48, 0x1111, 0x2222, 0, 0); - EXPECT(real_pc_list->calls[48] == 1); + EXPECT(xs::is_command_list_proxy(pc_list)); EXPECT(release(pc_list) == 0); // Xbox Slot 73 returns wrapped console command list proxy @@ -2414,8 +3367,13 @@ int check_console_command_list() { EXPECT(real_list->calls[59] == 1); EXPECT(real_list->args[59][0] == 0x10); - // Console slot 148 (AllocateUploadMemory stub) -> returns 0 without faulting - EXPECT(raw(list_proxy, 148, 2048, 512, 0, 0) == 0); + // Console slot 148 (AllocateUploadMemory) -> an upload-arena pointer (the boot stack's arena, which the merge + // kept; main's stub returned 0) + { + const std::uint64_t upload = raw(list_proxy, 148, 2048, 512, 0, 0); + EXPECT(upload != 0); + EXPECT(upload % 512 == 0); + } EXPECT(xs::list_slot_hits(148) == 1); EXPECT(xs::list_slot_first_call_seen(148)); @@ -2600,17 +3558,19 @@ int check_presentation_wiring() { UINT count = 3; EXPECT(hr_of(raw(device, 81, 77, 0x1a, word(&count), 0)) == S_FALSE && count == 0 && p.stats_calls == 1); - // Queue slot 30 routes to PresentX while attached. SuspendX and ResumeX have no default route, so 31/32 are refused - // and never reach the presenter (the env mode, run_env_slots, routes them). + // Queue slot 30 routes to PresentX while attached. SuspendX and ResumeX have no default route, so 31/32 stay with + // the queue proxy's console slots and never reach the presenter (the env mode, run_env_slots, routes them). EXPECT(hr_of(raw(queue, 30, 1, 0x1000, 0x2000)) == S_OK && p.present_calls == 1 && p.last_planes == 1); - EXPECT(hr_of(raw(queue, 31, 0)) == E_NOTIMPL && p.suspend_calls == 0); - EXPECT(hr_of(raw(queue, 32)) == E_NOTIMPL && p.resume_calls == 0); + raw(queue, 31, 0); + raw(queue, 32); + EXPECT(p.suspend_calls == 0 && p.resume_calls == 0); - // Detaching restores default E_NOTIMPL refusal on beyond-PC queue slots. + // Detaching: GetFrameStatisticsX no longer reaches the presenter (queue slot 30 goes back to the queue proxy's + // own PresentX, which check_xbox_queue_slots and the boot runs cover). EXPECT(xs::set_presentation_handler(device, nullptr)); UINT none = 7; // unattached GetFrameStatisticsX: no statistics yet, never the PC slot 81 EXPECT(hr_of(raw(device, 81, 77, 0x1a, word(&none), 0)) == S_FALSE && none == 0 && p.stats_calls == 1); - EXPECT(hr_of(raw(queue, 30, 1, 0, 0)) == E_NOTIMPL && p.present_calls == 1); + EXPECT(p.present_calls == 1); EXPECT(release(queue) == 0); EXPECT(release(device) == 0 && mock->refs == 0); @@ -2624,23 +3584,22 @@ int main(int argc, char** argv) { if (argc == 2) { if (std::strcmp(argv[1], "--env-slots") == 0) return run_env_slots(true); if (std::strcmp(argv[1], "--env-slots-invalid") == 0) return run_env_slots(false); - if (std::strcmp(argv[1], "--env-slots-74") == 0) return run_env_slots(true, true); + if (std::strcmp(argv[1], "--env-slots-70") == 0) return run_env_slots(true, true); + if (std::strcmp(argv[1], "--env-slots-74") == 0) return run_env_slots(true, false, true); return run_fault_mode(argv[1]); } if (argc != 1) return 2; - if (check_tail(true) || check_host_device_floor() || check_levels() || check_slot48() || check_fence1() || check_create_failures() || check_open_shared() || - check_alloc_failures() || check_allocators() || check_xbox_slots() || check_console_command_list() || - check_custom_heap_properties() || - check_resource_allocation_info() || check_slot70() || check_committed_resource3_x() || - check_descriptor_heap_hooks() || - check_render_target_sizes() || - check_allocation_descriptions_cleaned() || - check_render_target_layout() || - check_committed_resource_leases() || - check_slot74() || - check_xbox_queue_slots() || - check_presentation_wiring()) + if (check_tail(true) || check_host_device_floor() || check_levels() || check_slot48() || check_fence1() || + check_fence_completed_value() || check_create_failures() || check_open_shared() || + check_alloc_failures() || check_allocators() || check_xbox_slots() || check_lists() || + check_console_command_list() || check_signalx_detection() || check_list_tail_names() || + check_custom_heap_properties() || check_resource_allocation_info() || check_slot70() || + check_committed_resource3_x() || check_descriptor_heap_hooks() || check_render_target_sizes() || + check_allocation_descriptions_cleaned() || check_render_target_layout() || + check_committed_resource_leases() || check_committed_resource_states() || check_slot74() || + check_xbox_queue_slots() || check_list_cpu_handles() || check_presentation_wiring()) return 1; + if (check_placed_resource_x()) return 1; std::printf("xs_proxy_mock_test: PASS (%d allocations refused on purpose)\n", g_failed_news); return 0; } diff --git a/scripts/build_runtime.ps1 b/scripts/build_runtime.ps1 index f24cc073fb..21838be1f7 100644 --- a/scripts/build_runtime.ps1 +++ b/scripts/build_runtime.ps1 @@ -86,14 +86,16 @@ $build || exit /b 1 Write-Warning "CMake and Ninja weren't found (neither VS C++ CMake tools nor native PATH tools): building with cl.exe directly, without the GameInput shim (SDL3) and without the Rust XMA2 decoder (XMA voices are silent). Install CMake + Ninja or VS's CMake tools component to get it." $xtaskqueueDir = Join-Path $root "third_party\xtaskqueue" $xtaskqueueFiles = "Source\Task\TaskQueue.cpp", "Source\Task\AsyncLib.cpp", "Source\Task\ThreadPool_win32.cpp", "Source\Task\WaitTimer_win32.cpp" | ForEach-Object { "`"$xtaskqueueDir\$_`"" } - $files = "src\main.cpp", "src\host_cpu.cpp", "src\pe_loader.cpp", "shims\registry.cpp", "shims\file_system.cpp", "shims\xmem.cpp", "shims\xg_xs.cpp", "shims\acphal.cpp", "shims\d3d12_xs.cpp", "shims\d3d12_xs_device.cpp", "shims\d3d12_xs_rootsig.cpp", "shims\xgameruntime.cpp", "shims\xgameruntime_user.cpp", "shims\xgameruntime_gamesave.cpp", "shims\xgameruntime_store.cpp", "shims\xgameruntime_offline.cpp", "shims\winhttp_offline.cpp", "shims\ws2_offline.cpp", "shims\library_loader.cpp", "shims\process.cpp", "shims\com_shim.cpp", "shims\bcrypt_rng.cpp", "shims\xapu_chad.cpp", "shims\dstorage.cpp" | ForEach-Object { "`"$src\$_`"" } + $files = "src\main.cpp", "src\thread_stacks.cpp", "src\bcpack.cpp", "src\host_cpu.cpp", "src\pe_loader.cpp", "shims\registry.cpp", "shims\file_system.cpp", "shims\xmem.cpp", "shims\xg_xs.cpp", "shims\acphal.cpp", "shims\d3d12_xs.cpp", "shims\d3d12_xs_device.cpp", "shims\d3d12_xs_pso_stream.cpp", "shims\d3d12_xs_rootsig.cpp", "shims\xgameruntime.cpp", "shims\xgameruntime_user.cpp", "shims\xgameruntime_gamesave.cpp", "shims\xgameruntime_store.cpp", "shims\xgameruntime_offline.cpp", "shims\winhttp_offline.cpp", "shims\ws2_offline.cpp", "shims\library_loader.cpp", "shims\process.cpp", "shims\xbox_bvh_builder.cpp", "shims\com_shim.cpp", "shims\bcrypt_rng.cpp", "shims\xapu_chad.cpp", "shims\dstorage.cpp" | ForEach-Object { "`"$src\$_`"" } $includes = "/I `"$src\src`" /I `"$src\shims`" /I `"$src\shims\xtaskqueue`" /I `"$xtaskqueueDir\Include`" /I `"$xtaskqueueDir\Source\Task`" /I `"$xtaskqueueDir\Source\Common`"" $opt = if ($Debug) { "/Od /MDd" } else { "/O2 /MD" } $body = @" cd /d "$out" || exit /b 1 rem BUILD-1457: a game thread with the default stack size gets this program's reserve, and drivers compile on it. The same number as in CMakeLists.txt. rem Keep the host base in step with runtime\CMakeLists.txt GTA6RT_HOST_BASE. -cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /Zi $opt /MP$jobs /DWIN32_LEAN_AND_MEAN /DNOMINMAX /DUNICODE /D_UNICODE $includes $($files -join ' ') $($xtaskqueueFiles -join ' ') /Fe:gta6rt.exe /link /OPT:NOREF /BASE:0x10000000000 /STACK:8388608 psapi.lib ole32.lib || exit /b 1 +python -I "$root\tools\gen_bcpack_runtime_tables.py" "bcpack_tables.inc" || exit /b 1 +cl /nologo /std:c++20 /EHsc /O2 /I "." "$root\tools\bcpack_history_train.cpp" /Fe:bcpack_history_train.exe || exit /b 1 +cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /Zi $opt /MP$jobs /DWIN32_LEAN_AND_MEAN /DNOMINMAX /DUNICODE /D_UNICODE /I "." $includes $($files -join ' ') $($xtaskqueueFiles -join ' ') /Fe:gta6rt.exe /link /OPT:NOREF /BASE:0x10000000000 /STACK:8388608 psapi.lib ole32.lib || exit /b 1 cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /MT /DWIN32_LEAN_AND_MEAN /DNOMINMAX "$src\src\tls_host.cpp" /LD /Fe:gta6rt_tls_host.dll || exit /b 1 cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "$src\shims" "$src\shims\d3d12_xs_rootsig.cpp" "$src\shims\registry.cpp" "$src\shims\d3d12_xs.cpp" "$src\shims\d3d12_xs_device.cpp" "$src\test\root_sig_test.cpp" /Fe:root_sig_test.exe /link d3d12.lib || exit /b 1 cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "$src\shims" "$src\shims\d3d12_xs_rootsig.cpp" "$src\shims\registry.cpp" "$src\shims\d3d12_xs.cpp" "$src\shims\d3d12_xs_device.cpp" "$src\test\device_proxy_test.cpp" /Fe:device_proxy_test.exe /link d3d12.lib dxgi.lib || exit /b 1 diff --git a/scripts/check_no_game_data.py b/scripts/check_no_game_data.py index bccee5e681..ae3d06e77f 100644 --- a/scripts/check_no_game_data.py +++ b/scripts/check_no_game_data.py @@ -42,6 +42,7 @@ ("RPF9 archive", 0, b"9FPR"), ("RPF9 archive", 0, b"RPF9"), ("TTPF texture pool", 0, b"TTPF"), + ("local BCPack predictor profile", 0, b"BCPHIST1"), ("RAGE resource", 0, b"RSC7"), ("RAGE resource", 0, b"RSC8"), ("RAGE resource", 0, b"RSCC"), diff --git a/scripts/linux-boot/boot-digest.sh b/scripts/linux-boot/boot-digest.sh new file mode 100755 index 0000000000..dd2289e30a --- /dev/null +++ b/scripts/linux-boot/boot-digest.sh @@ -0,0 +1,75 @@ +#!/bin/bash +# ExecStopPost of a leonida-boot-* unit: runs after the boot ends however it ended (exit, crash, oomd kill, timeout). +# Writes /opt/leonida/work//boot-.digest.txt and appends a line to /opt/leonida/work/boots.tsv. +# Local only: digests quote trace lines, so they never go into commits or PRs. +set -u +AGENT=$1; N=$2; WORK=/opt/leonida/work/$AGENT; LOG=$WORK/boot-$N.log; RES=$WORK/boot-$N.resources.tsv +META=$WORK/boot-$N.meta; OUT=$WORK/boot-$N.digest.txt; LEDGER=/opt/leonida/work/boots.tsv +START=$(sed -n 's/^start_epoch=//p' "$META" 2>/dev/null); BOOT=$(sed -n 's/^boot_epoch=//p' "$META" 2>/dev/null) +START=${START:-$(date +%s)}; BOOT=${BOOT:-$START}; END=$(date +%s) +RESULT=${SERVICE_RESULT:-?}; ECODE=${EXIT_CODE:-?}; ESTAT=${EXIT_STATUS:-?} +D3D=$(grep -o 'd3d12=[^ ]*' "$LOG" 2>/dev/null | tail -1 | cut -d= -f2) +STDOUT=${D3D/d3d12-run-/stdout-run-} +CAP=/opt/leonida/capture/$AGENT-$N + +verdict=OK +# systemd-oomd can kill the unit's processes without the unit ending in "oom-kill" (boot.sh then exits on its own). +if journalctl --user -u "leonida-boot-$AGENT-$N" --since "@$START" -q --no-pager 2>/dev/null | grep -q 'systemd-oomd killed'; then RESULT=oom-kill; fi +case "$RESULT" in + oom-kill) verdict="KILLED BY OOM (systemd-oomd or kernel): memory, not a crash" ;; + timeout) verdict="TIMEOUT" ;; + exit-code) verdict="EXITED WITH ERROR (code $ECODE status $ESTAT)" ;; + signal|core-dump) verdict="KILLED BY SIGNAL ($ESTAT)" ;; + success) verdict="OK (ran to its time limit or exited cleanly)" ;; +esac +grep -q 'time limit reached' "$LOG" 2>/dev/null && [ "$RESULT" = success ] && verdict="OK (ran its full time limit)" + +cnt() { local c=0; [ -f "$D3D" ] && c=$(grep -a -c -E "$@" "$D3D"); echo "${c:-0}"; } +{ + echo "== leonida boot $AGENT-$N: $verdict" + echo "unit result=$RESULT exit_code=$ECODE exit_status=$ESTAT" + echo "queued $((BOOT-START)) s, ran $((END-BOOT)) s; trace $D3D" + sed -n '/^LEONIDA_\|^WINEDEBUG\|^unit=/p' "$META" 2>/dev/null | tr '\n' ' '; echo + echo + echo "-- counts" + echo "PresentX ok $(cnt 'XboxPresentation::PresentX ok') refused $(cnt 'XboxPresentation::PresentX failed')" + echo "CreatePipelineState failed $(cnt 'CreatePipelineState failed') FSPX compute misses $(cnt 'no translated compute shader for FSPX') slot-67 failed $(cnt 'slot 67 call .* failed')" + echo "E_NOTIMPL $(cnt 'E_NOTIMPL') wine err: lines $(cnt '^[0-9a-f]{4}:err:|:err:') exceptions $(cnt -i 'exception|unhandled|page fault|access violation')" + grep -a -m1 -E 'translated shaders \(' "$D3D" 2>/dev/null + grep -a 'present-probe: source frame .* via' "$D3D" 2>/dev/null | tail -1 | sed 's/.*via/source via/' | cut -c1-120 + echo + echo "-- frames (swapchain; then the title's own backbuffer when LEONIDA_CAPTURE_SOURCE=1)" + [ -f "$CAP/index.txt" ] && { echo "$(wc -l < "$CAP/index.txt") captured; last: $(tail -1 "$CAP/index.txt" | cut -c1-110)"; awk '{m=$(NF-2)+$(NF-1)+$NF; if (m>0) n++} END{print n+0 " of " NR " frames non-black"}' "$CAP/index.txt"; } || echo "no capture index" + grep -a 'present-probe: source frame .* mean' "$D3D" 2>/dev/null | tail -2 | sed 's/.*source frame/source frame/' | cut -c1-140 + echo + echo "-- resources (2 s samples)" + [ -s "$RES" ] && awk -F'\t' 'NR>1{ if(min==""||$2sw)sw=$3; if($4>um)um=$4; if($5>us)us=$5; if($6+0>gm)gm=$6 } END{printf "min RAM available %s MB, max swap used %s MB, game peak %s MB RAM + %s MB swap, VRAM peak %s MB\n",min,sw,um,us,gm}' "$RES" || echo "no samples" + journalctl --user -u "leonida-boot-$AGENT-$N" --since "@$START" -q --no-pager 2>/dev/null | grep -E 'Consumed|oom|Failed' | sed 's/^.*\]: //' | sort -u | cut -c1-200 + # Compare with other boots instead of guessing: on the console (Series S) path the title itself grows to ~20 GB of + # RAM+swap by ~130 s (fsdraw-6: 9.9 GB + 11.2 GB), mostly zero pages that zram compresses well. + [ -s "$RES" ] && awk -F'\t' 'NR>1{t=$4+$5; if(t>m)m=t} END{printf "game peak RAM+swap %.1f GB (console-path baseline ~20 GB at 130 s; oomd kills when zram swap passes 98%%)\n", m/1024}' "$RES" + echo + echo "-- system events during the boot (OOM, GPU Xid, segfaults)" + { journalctl --since "@$BOOT" -q --no-pager 2>/dev/null | grep -i -E 'systemd-oomd.*(Marked|killed)|oom-kill|out of memory|NVRM: Xid|segfault|gta6rt|wineserver.*crash' ; } | cut -c1-200 | tail -15 + echo + echo "-- distinct error lines (normalised, with counts; top 60)" + for f in "$D3D" "$STDOUT"; do [ -f "$f" ] && cat "$f"; done 2>/dev/null \ + | grep -a -i -E 'error|fail|E_NOTIMPL|E_INVALIDARG|E_FAIL|0x8[0-9a-f]{7}|exception|assert|abort|unhandled|page fault|refused|not implemented|no translated|no emulation|crash|:err:|fatal|cannot|could not|unsupported|invalid' \ + | grep -a -v -E ' ok$| called$' \ + | sed -E 's/#[0-9]+/#N/g; s/0x[0-9a-fA-F]{6,}/0xADDR/g; s/\b[0-9a-f]{64}\b/SHA/g; s/[0-9]{4,}/NUM/g; s/^[0-9a-f]{4}:/TID:/' \ + | cut -c1-220 | sort | uniq -c | sort -rn | head -60 + echo + echo "-- where the trace ended" + [ -f "$D3D" ] && tail -n 8 "$D3D" | cut -c1-200 +} > "$OUT" 2>&1 + +frames=$( [ -f "$CAP/index.txt" ] && awk '{m=$(NF-2)+$(NF-1)+$NF; if (m>0) n++} END{print (n+0) "/" NR}' "$CAP/index.txt" || echo "-") +peak=$( [ -s "$RES" ] && awk -F'\t' 'NR>1{if($4>u)u=$4} END{print u+0}' "$RES" || echo "-") +exec 7>>"$LEDGER"; flock 7 +# Both the unit's ExecStopPost and the outer wrapper call this; the first one to finish records the boot. +grep -q -P "^[^\t]*\t$AGENT\t$N\t" "$LEDGER" 2>/dev/null && exit 0 +[ -s "$LEDGER" ] || printf 'end\tagent\tn\tresult\tran_s\tpresentx_ok\tpso_failed\tfspx_miss\tnonblack_frames\tpeak_mb\tgta6rt\n' >&7 +printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$(date '+%F %T')" "$AGENT" "$N" "$RESULT" "$((END-BOOT))" \ + "$(cnt 'XboxPresentation::PresentX ok')" "$(cnt 'CreatePipelineState failed')" "$(cnt 'no translated compute shader for FSPX')" \ + "$frames" "$peak" "$(sed -n 's/^unit=.*gta6rt=\([^ ]*\).*/\1/p' "$META")" >&7 +exit 0 diff --git a/scripts/linux-boot/boot-inner.sh b/scripts/linux-boot/boot-inner.sh new file mode 100755 index 0000000000..e52d3daeff --- /dev/null +++ b/scripts/linux-boot/boot-inner.sh @@ -0,0 +1,45 @@ +#!/bin/bash +# Runs inside the leonida-boot-* unit (see run-boot.sh). Waits for memory, takes the locks, samples resources, boots. +set -u +WORK=/opt/leonida/work/$BOOT_AGENT; N=$BOOT_N; LOG=$WORK/boot-$N.log; RES=$WORK/boot-$N.resources.tsv +META=$WORK/boot-$N.meta +: > "$LOG" +echo "start_epoch=$(date +%s)" > "$META" +echo "unit=leonida-boot-$BOOT_AGENT-$N gta6rt=$GTA6RT secs=$BOOT_SECS" >> "$META" +env | grep -E '^(LEONIDA_|WINEDEBUG=)' | sort >> "$META" + +mem_free_mb() { # RAM available plus a third of free zram swap (zram pages cost RAM, roughly 3:1) + awk '/^MemAvailable:/{a=$2} /^SwapFree:/{s=$2} END{printf "%d", (a + s/3)/1024}' /proc/meminfo +} +NEED=${LEONIDA_BOOT_MIN_FREE_MB:-6500} +swap_pct() { awk '/^SwapTotal:/{t=$2} /^SwapFree:/{f=$2} END{printf "%d", t ? (t-f)*100/t : 0}' /proc/meminfo; } + +exec 8>/opt/leonida/.gpu.lock; flock 8 # one boot at a time +echo "[run-boot] $(date +%T) got the GPU lock" >> "$LOG" +for i in $(seq 1 40); do # up to 10 min for memory headroom + f=$(mem_free_mb); sp=$(swap_pct); [ "$f" -ge "$NEED" ] && [ "$sp" -lt 70 ] && break + echo "[run-boot] $(date +%T) waiting for memory: ${f} MB free (need ${NEED}), swap ${sp}% (need < 70%)" >> "$LOG"; sleep 15 +done +echo "[run-boot] $(date +%T) memory before boot: $(mem_free_mb) MB free, swap $(swap_pct)%" >> "$LOG" +exec 9>/opt/leonida/.build.lock; flock 9 # no compiles while the game runs +echo "[run-boot] $(date +%T) got the build lock; booting" >> "$LOG" +echo "boot_epoch=$(date +%s)" >> "$META" + +CG=/sys/fs/cgroup$(cut -d: -f3 /proc/self/cgroup) +( printf 'time\tmem_avail_mb\tswap_used_mb\tunit_mem_mb\tunit_swap_mb\tgpu_mem_mb\tgpu_util\n' + while :; do + read -r ma su < <(awk '/^MemAvailable:/{a=$2} /^SwapTotal:/{t=$2} /^SwapFree:/{f=$2} END{print int(a/1024), int((t-f)/1024)}' /proc/meminfo) + um=$(( $(cat "$CG/memory.current" 2>/dev/null || echo 0) / 1048576 )); us=$(( $(cat "$CG/memory.swap.current" 2>/dev/null || echo 0) / 1048576 )) + g=$(nvidia-smi --query-gpu=memory.used,utilization.gpu --format=csv,noheader,nounits 2>/dev/null | tr -d ' ' | tr ',' '\t') + printf '%s\t%s\t%s\t%s\t%s\t%s\n' "$(date +%T)" "$ma" "$su" "$um" "$us" "${g:-? ?}" + sleep 2 + done ) > "$RES" 2>/dev/null & +SAMPLER=$! + +/opt/leonida/boot.sh run "$BOOT_SECS" >> "$LOG" 2>&1 +rc=$? +kill $SAMPLER 2>/dev/null +echo "[run-boot] $(date +%T) boot.sh exit $rc" >> "$LOG" +# boot.sh stops the title with timeout(1) at the time limit: 124 means it ran the whole time, which is success here. +[ "$rc" = 124 ] && { echo "[run-boot] time limit reached" >> "$LOG"; rc=0; } +exit $rc diff --git a/scripts/linux-boot/boot.sh b/scripts/linux-boot/boot.sh new file mode 100755 index 0000000000..55f84f019d --- /dev/null +++ b/scripts/linux-boot/boot.sh @@ -0,0 +1,42 @@ +#!/bin/bash +# Boot the packaged port under Wine with the network off (unshare -rn: user + network namespace, no root). +# usage: boot.sh dry-run|init|run [seconds] (run defaults to 150 s, then the title is stopped) +# Traces stay local in /opt/leonida/traces: they can quote game data, never post them. +set -u +MODE=${1:?dry-run|init|run}; SECS=${2:-150} +OUT=/opt/leonida +REPO=${LEONIDA_REPO:-$(cd "$(dirname "$(readlink -f "$0")")/../.." && pwd)} # the checkout this script is in +STAMP=$(date +%H%M%S) +T=$OUT/traces; mkdir -p "$T" "$OUT/overlay" "$OUT/cache/nv" + +WINE=${WINE:-wine} # e.g. WINE=".../Proton - Experimental/files/bin/wine" WINEPREFIX=~/.local/share/leonida-proton/pfx +export WINEPREFIX=${WINEPREFIX:-$HOME/.local/share/leonida-wine} WINEDEBUG=${WINEDEBUG:--all} WINEDLLOVERRIDES="mscoree,mshtml=" +export LEONIDA_D3D12=vulkan +export LEONIDA_SHADERS=$OUT/work/shaders/spirv +export LEONIDA_ARENA_MB=${LEONIDA_ARENA_MB:-2048} +export LEONIDA_PIPELINE_CACHE_BYTES=${LEONIDA_PIPELINE_CACHE_BYTES:-4294967296} +export LEONIDA_STARTUP_CACHE_CHECKPOINTS=1 +export __GL_SHADER_DISK_CACHE=1 __GL_SHADER_DISK_CACHE_PATH=$OUT/cache/nv __GL_SHADER_DISK_CACHE_SIZE=21474836480 +export __GL_SHADER_DISK_CACHE_SKIP_CLEANUP=1 +[ -n "${SKIP_INT3:-}" ] && export LEONIDA_SKIP_INT3=1 + +GAME_WIN='Z:\opt\gta6\GTA6.Xbox.v1.0.2.1' +EXE=/opt/gta6/GTA6.Xbox.v1.0.2.1/game_scarlett_master.exe +TRACE_WIN="Z:\\opt\\leonida\\traces\\boot-$MODE-$STAMP.jsonl" +D3D=$T/d3d12-$MODE-$STAMP.log +GTA6RT=${GTA6RT:-$OUT/gta6rt.exe}; [ -f "$GTA6RT" ] || GTA6RT=$REPO/runtime/build/boot/gta6rt.exe # GTA6RT=/gta6rt.exe boots a private build without installing it + +args=(--"$MODE" "$EXE" --game-dir "$GAME_WIN" --overlay 'Z:\opt\leonida\overlay' --trace "$TRACE_WIN") +[ "$MODE" = run ] && args+=(--trace-d3d12) +echo "[boot] $MODE gta6rt=$GTA6RT trace=$T/boot-$MODE-$STAMP.jsonl d3d12=$D3D" +# unshare: new user + network namespace, so the title has no network at all +if [ "$MODE" = run ]; then + timeout --signal=INT --kill-after=20 "$SECS" unshare -rn "$WINE" "$GTA6RT" "${args[@]}" > "$T/stdout-$MODE-$STAMP.log" 2> "$D3D" +else + unshare -rn "$WINE" "$GTA6RT" "${args[@]}" > "$T/stdout-$MODE-$STAMP.log" 2> "$D3D" +fi +rc=$?; echo "[boot] exit=$rc" +sleep 0 +python3 -I "$REPO/tools/boot_trace.py" "$T/boot-$MODE-$STAMP.jsonl" --d3d12 "$D3D" > "$T/summary-$MODE-$STAMP.txt" 2>&1 +echo "[boot] summary: $T/summary-$MODE-$STAMP.txt" +exit $rc diff --git a/scripts/linux-boot/configure-worktree.sh b/scripts/linux-boot/configure-worktree.sh new file mode 100755 index 0000000000..c983b33571 --- /dev/null +++ b/scripts/linux-boot/configure-worktree.sh @@ -0,0 +1,9 @@ +#!/bin/bash +# usage: configure-worktree.sh +# Configures a Windows build of the runtime on Linux with clang-cl and an xwin SDK (XWIN_DIR, default +# ~/.local/share/xwin-sdk). SDL3_SRC= makes the configure work offline. +set -eu; W=$(realpath "$1") +cmake -S "$W/runtime" -B "$W/runtime/build/boot" -G Ninja -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_TOOLCHAIN_FILE="$W/runtime/cmake/clang-cl-xwin.cmake" -DXWIN_DIR="${XWIN_DIR:-$HOME/.local/share/xwin-sdk}" \ + -DLEONIDA_BUILD_WINDOWS_RUNTIME=ON -DLEONIDA_SDL3=ON \ + ${SDL3_SRC:+-DFETCHCONTENT_SOURCE_DIR_SDL3="$SDL3_SRC"} diff --git a/scripts/linux-boot/run-boot.sh b/scripts/linux-boot/run-boot.sh new file mode 100755 index 0000000000..523d177950 --- /dev/null +++ b/scripts/linux-boot/run-boot.sh @@ -0,0 +1,56 @@ +#!/bin/bash +# Boot gta6rt as its own systemd --user unit, protected from the swarm and logged in full. +# +# usage: run-boot.sh [seconds=150] [KEY=VALUE ...] +# e.g. run-boot.sh fsdraw 3 /path/wt-fsdraw/runtime/build/boot/gta6rt.exe 150 LEONIDA_FOO=1 +# +# What it does for you: +# - runs the boot outside your agent's process tree (survives agent/session restarts); +# - waits for memory headroom before starting, then holds the GPU lock AND the build lock for the whole boot, +# so no compile competes with the game for RAM; +# - Series S profile, late-frame capture, source capture and Wine's error channel on by default (override with KEY=VALUE); +# - samples RAM / swap / the game's memory / VRAM every 2 s; +# - after the boot, even when systemd-oomd or a crash kills it, writes a digest with the unit result, OOM and GPU +# kernel events and every distinct error line, and appends one line to the shared ledger /opt/leonida/work/boots.tsv. +# +# Outputs (in /opt/leonida/work//): boot-.log boot-.resources.tsv boot-.digest.txt +set -u +AGENT=${1:?agent}; N=${2:?n}; EXE=${3:?gta6rt.exe}; SECS=${4:-150}; shift $(( $# >= 4 ? 4 : $# )) +[ -f "$EXE" ] || { echo "run-boot: no such gta6rt: $EXE" >&2; exit 2; } +# gta6rt loads gta6rt_tls_host.dll from its own folder; without it the title gets no module TLS index and exits at once. +[ -f "$(dirname "$EXE")/gta6rt_tls_host.dll" ] || { echo "run-boot: $(dirname "$EXE")/gta6rt_tls_host.dll is missing: copy it next to the exe (build it with the gta6rt target) or boot the exe from its build folder" >&2; exit 2; } +WORK=/opt/leonida/work/$AGENT; mkdir -p "$WORK" +UNIT=leonida-boot-$AGENT-$N +if systemctl --user is-active --quiet "$UNIT"; then echo "run-boot: $UNIT is already running" >&2; exit 2; fi + +declare -A ENV=( + [WINE]="$HOME/.local/share/Steam/steamapps/common/Proton - Experimental/files/bin/wine" + [WINEPREFIX]="$HOME/.local/share/leonida-proton/pfx" + [WINEDEBUG]="-all,err+all" + [GTA6RT]="$EXE" + [LEONIDA_CAPTURE]="Z:\\opt\\leonida\\capture\\$AGENT-$N" + [LEONIDA_CAPTURE_EVERY]=4800 [LEONIDA_CAPTURE_LIMIT]=24 [LEONIDA_CAPTURE_SOURCE]=1 + [LEONIDA_DEVICE_TYPE]=6 + [LEONIDA_PIPELINE_CACHE_DIR]="Z:\\opt\\leonida\\cache\\pipelines" +) +for kv in "$@"; do ENV[${kv%%=*}]="${kv#*=}"; done +args=() +for k in "${!ENV[@]}"; do args+=(--setenv="$k=${ENV[$k]}"); done + +echo "run-boot: $UNIT starting (queues for memory headroom, the GPU lock and the build lock)" +rm -f "$WORK/boot-$N.digest.txt" +systemd-run --user --collect --quiet --unit="$UNIT" -p WorkingDirectory=/opt/leonida \ + --setenv=BOOT_AGENT="$AGENT" --setenv=BOOT_N="$N" --setenv=BOOT_SECS="$SECS" "${args[@]}" \ + /opt/leonida/boot-inner.sh || { echo "run-boot: could not start $UNIT" >&2; exit 2; } +# The digest is written by a separate, tiny watcher unit: it survives systemd-oomd killing the boot's cgroup and the +# caller's shell going away. It waits for the boot unit to end, reads its result from the journal and writes the digest. +systemd-run --user --collect --quiet --unit="leonida-digest-$AGENT-$N" -p MemoryMax=256M \ + /bin/bash -c 'while systemctl --user is-active --quiet "$0" || systemctl --user is-activating --quiet "$0"; do sleep 3; done + START=$(sed -n "s/^start_epoch=//p" "/opt/leonida/work/$1/boot-$2.meta" 2>/dev/null) + RES=$(journalctl --user -u "$0" ${START:+--since "@$START"} -q --no-pager 2>/dev/null | grep -o "Failed with result .[a-z-]*." | tail -1 | tr -d "\x27" | sed "s/Failed with result //") + SERVICE_RESULT=${RES:-success} exec /opt/leonida/boot-digest.sh "$1" "$2"' "$UNIT" "$AGENT" "$N" +# Block until the digest exists (so a caller that waits on this script gets the result), then print it. +while [ ! -s "$WORK/boot-$N.digest.txt" ] || systemctl --user is-active --quiet "leonida-digest-$AGENT-$N"; do sleep 5; done +echo "run-boot: $UNIT finished. Digest:" +cat "$WORK/boot-$N.digest.txt" +head -1 "$WORK/boot-$N.digest.txt" | grep -q ': OK' && exit 0 || exit 1 diff --git a/scripts/translate_pipeline_compute.py b/scripts/translate_pipeline_compute.py new file mode 100644 index 0000000000..a7d70ab54f --- /dev/null +++ b/scripts/translate_pipeline_compute.py @@ -0,0 +1,170 @@ +"""Build an interrupted or new pipeline compute pack from shader_library.py output (Linux). + +Two translation processes, including the parent, each run at most one SPIRV-Tools process. +Validated modules and their receipts survive interruption. The runtime index is published last. +""" +import argparse +import fcntl +import hashlib +import json +import os +import resource +import shutil +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path[:0] = [str(ROOT / "tools"), str(ROOT)] +from make_game import file_sha256 as digest, translation_sources_digest +import rdna2spirv as translator + + +def build_one(src, out, name, settings, compact=False): + listing = src / "disasm" / (name + ".s") + side = src / "fspx" / name + code, state = (Path(str(side) + suffix) for suffix in (".code", ".state")) + code_key, state_key = digest(code), digest(state) + container = src / (name + ".dxbc") + inputs = [settings, name, code_key, state_key, digest(listing), digest(Path(str(side) + ".json")), + digest(container) if container.is_file() else None] + key = hashlib.sha256(json.dumps(inputs).encode()).hexdigest() + receipt = out / ".compute-cache" / (key + ".json") + if receipt.exists(): + try: + row = json.loads(receipt.read_text(encoding="utf-8")) + if (row["meta"]["fspx_code_sha256"], row["meta"]["fspx_state_sha256"]) == (code_key, state_key): + module_hash = row["module"] + if len(module_hash) == 64 and all(c in "0123456789abcdef" for c in module_hash): + if digest(out / (name + "_" + module_hash + ".spv")) == module_hash: + return row + except (OSError, ValueError, KeyError, TypeError): + pass + + asm = translator.translate(str(listing)) + with tempfile.TemporaryDirectory(dir=out / ".compute-cache") as tmp: + sa, sv = Path(tmp) / "module.spvasm", Path(tmp) / "module.spv" + sa.write_text(asm, encoding="utf-8", newline="\n") + result = translator.assemble_spirv(str(sa), str(sv), asm_text=asm, compact=compact) + if result.returncode: + raise translator.Unsupported((result.stderr.splitlines() or ["SPIR-V tool failed"])[0]) + meta = translator.shader_meta(translator.translate.last_gen, asm, src_path=str(listing)) + if (meta.get("stage"), meta.get("fspx_code_sha256"), meta.get("fspx_state_sha256")) != ( + "cs", code_key, state_key): + raise ValueError("compute stage or FSPX identity mismatch") + module_hash = digest(sv) + sv.replace(out / (name + "_" + module_hash + ".spv")) + row = {"meta": meta, "module": module_hash} + translator.write_index(str(receipt), row) + return row + + +def build_part(src, out, names, settings, report, compact=False): + rows, failures = {}, {} + for number, name in enumerate(names, 1): + try: + rows[name] = build_one(src, out, name, settings, compact) + except (translator.Unsupported, MemoryError) as e: + failures[name] = str(e) or type(e).__name__ + if number % 100 == 0 or number == len(names): + print(f"worker {os.getpid()}: {number}/{len(names)}, {len(failures)} failed", flush=True) + translator.write_index(str(report), {"rows": rows, "failures": failures}) + + +def build(src, out, names, settings, jobs, compact=False): + cache = out / ".compute-cache" + cache.mkdir(exist_ok=True) + with (cache / "lock").open("ab") as lock, tempfile.TemporaryDirectory(dir=cache) as tmp: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + reports = [Path(tmp) / str(i) for i in range(jobs)] + pid = os.fork() if jobs == 2 else None + if pid == 0: + try: + build_part(src, out, names[1::2], settings, reports[1], compact) + except BaseException: + import traceback + traceback.print_exc() + os._exit(1) + os._exit(0) + try: + build_part(src, out, names[::jobs], settings, reports[0], compact) + finally: + if pid and os.waitpid(pid, 0)[1]: + raise RuntimeError("second translation worker failed") + + index, failures, pairs = {}, {}, {} + for report in reports: + part = json.loads(report.read_text(encoding="utf-8")) + failures.update(part["failures"]) + for name, row in part["rows"].items(): + module, meta = row["module"], row["meta"] + pair = meta["fspx_code_sha256"], meta["fspx_state_sha256"] + if pairs.setdefault(pair, module) != module: + raise ValueError("conflicting compute modules for one code/state pair") + # The same binary can implement different code/state keys. Each needs a runtime entry. + entry = name + "_" + module + index[entry] = meta + by_hash = {} + for name, reason in failures.items(): + code = digest(src / "fspx" / (name + ".code")) + state = digest(src / "fspx" / (name + ".state")) + by_hash.setdefault(code, {})[state] = reason + translator.write_index(str(out / "failures.json"), by_hash) + translator.write_index(str(out / "index.json"), index) + print(f"{len(index)}/{len(names)} valid, {len(failures)} failed") + return int(bool(failures)) + + +def main(): + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument("inputs", type=Path, help="unpacked library with index.json, disasm/ and fspx/") + ap.add_argument("--out", type=Path, required=True, help="dedicated runtime library subdirectory") + ap.add_argument("--jobs", type=int, choices=(1, 2), default=2) + ap.add_argument("--memory-mib", type=int, default=768, help="virtual memory per process (default 768 MiB)") + ap.add_argument("--descriptor-hash", choices=translator.DESCRIPTOR_HASHES, default="fnv1a", + help="bindless descriptor table hash shared with the runtime") + ap.add_argument("--loop-limit", type=translator.spirv_loop_guard.parse_limit, + default=translator.spirv_loop_guard.DEFAULT_LIMIT, help="maximum loop visits (0 disables)") + ap.add_argument("--compact-spirv", action="store_true", help="compact modules with spirv-opt before validation") + ap.add_argument("--wave64-emulate", action="store_true") + args = ap.parse_args() + if args.memory_mib < 1: + ap.error("--memory-mib must be positive") + src, out = args.inputs.resolve(), args.out.resolve() + if out == src or src in out.parents or out in src.parents: + ap.error("input and output directories must be separate") + os.setpriority(os.PRIO_PROCESS, 0, 19) + soft, hard = resource.getrlimit(resource.RLIMIT_AS) + bound = min(n for n in (args.memory_mib << 20, soft, hard) if n != resource.RLIM_INFINITY) + resource.setrlimit(resource.RLIMIT_AS, (bound, hard)) + versions = [] + required_tools = ["spirv-as", "spirv-val"] + if args.compact_spirv: + required_tools.append("spirv-opt") + for tool in required_tools: + binary = shutil.which(tool) + if not binary: + ap.error(tool + " is required") + versions.append(digest(Path(binary))) + settings = [translation_sources_digest(), digest(Path(__file__)), versions, args.wave64_emulate, + args.loop_limit, args.descriptor_hash] + rows = json.loads((src / "index.json").read_text(encoding="utf-8")) + names = [] + for row in rows: + if row["stage"] != "cs": + continue + filename = row["file"] + if Path(filename).name != filename or not filename.endswith(".dxbc") or "\\" in filename: + ap.error("invalid compute filename in input index") + names.append(filename[:-5]) + if not names or len(set(names)) != len(names): + ap.error("expected unique compute filenames in the input index") + out.mkdir(parents=True, exist_ok=True) + translator.DESCRIPTOR_HASH = args.descriptor_hash + translator.LOOP_LIMIT = args.loop_limit + translator.WAVE64_EMULATE = args.wave64_emulate + return build(src, out, sorted(names), settings, args.jobs, args.compact_spirv) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/windows-boot/README.md b/scripts/windows-boot/README.md new file mode 100644 index 0000000000..b4ad475665 --- /dev/null +++ b/scripts/windows-boot/README.md @@ -0,0 +1,93 @@ +# Native Windows boot harness + +`boot.ps1` boots the retail executable under `gta6rt` on native Windows the way the Linux harness +([`scripts/linux-boot/`](../linux-boot/)) does under Proton: same switches, one game process at a time, a trace of +every boot and a short digest at the end. Windows PowerShell 5.1 is enough. New here? the repository README +covers the setup that comes before this. + +## Run it + +```powershell +# What would run, with every path checked; launches nothing. +powershell -NoProfile -File scripts\windows-boot\boot.ps1 -DryRun -GameDir D:\GTA6pkg -Shaders E:\leonida-work\shaders\spirv + +# A 200 s boot with the default unattended presses (a@45,a@60,a@75,a@90). +powershell -NoProfile -File scripts\windows-boot\boot.ps1 -Name first -Seconds 200 -GameDir D:\GTA6pkg -Shaders E:\leonida-work\shaders\spirv + +# Extra or changed switches: trailing KEY=VALUE arguments (KEY= removes one), as run-boot.sh takes them. +powershell -NoProfile -File scripts\windows-boot\boot.ps1 -Name split -Seconds 120 LEONIDA_PRESENT_PLANE1=0 "LEONIDA_PEEK=,," + +# Every parameter. +Get-Help -Full .\scripts\windows-boot\boot.ps1 +``` + +Set `LEONIDA_GAME_DIR`, `LEONIDA_SHADERS` (and `GTA6RT`, `LEONIDA_RUNS` if you use other places) once in your +profile and the parameters can be left out. Defaults: `gta6rt` from `runtime\build\RelWithDebInfo\` of this +checkout, the executable from the game folder (`-Exe` or `LEONIDA_EXE` when it lives elsewhere), outputs in `$HOME\leonida-runs`. +The script refuses an output folder inside the repository. + +## What it sets + +Only when your shell has not set them already (`-DryRun` prints the final list): + +| Variable | Default | Why | +|---|---|---| +| `LEONIDA_D3D12` | `vulkan` | the runtime's D3D12-on-Vulkan backend | +| `LEONIDA_DEVICE_TYPE` | `6` | Series S identity; the runtime answers the title's `ConsoleMode` registry read with it (1920x1080) | +| `LEONIDA_ARENA_MB` | `2048` | as on Linux | +| `LEONIDA_PIPELINE_CACHE_BYTES` | `4294967296` | pipeline cache size limit | +| `LEONIDA_STARTUP_CACHE_CHECKPOINTS` | `1` | save the pipeline cache during startup | +| `LEONIDA_PIPELINE_CACHE_DIR` | `\pipeline-cache` | one warmed cache shared by every build you boot | +| `LEONIDA_PEEK` / `_SECONDS` | the game-state and session-state RVAs from `LEONIDA_GAME_STATE_RVA` and `LEONIDA_SESSION_STATE_RVA` (measured locally, not kept here; unset: no peek) / `5` | game state and session state (low dword), the two numbers every RESULT reports | +| `LEONIDA_DEVICE_FAULT` | `1` | on device loss: `VK_EXT_device_fault` info, checkpoints, last replay steps | +| `LEONIDA_KEYBOARD_PAD` | `always` (with an input script) | keyboard as a pad even unfocused, so the script's presses arrive | +| `LEONIDA_CAPTURE_EVERY` / `_LIMIT` | `60` / `40` | a swapchain read-back every 60 presents, at most 40 | +| `DISABLE_RTSS_LAYER`, `DISABLE_VULKAN_OBS_CAPTURE` | `1` | keep third-party Vulkan overlay layers out of the process | + +Per run, from the parameters: `LEONIDA_SHADERS` (`-Shaders`), `LEONIDA_CAPTURE` (`\cap_`, `-NoCapture` +turns it off), `LEONIDA_INPUT_SCRIPT` (`-InputScript`, `-NoInput` for none), `LEONIDA_STACKS` (`-Stacks 30,60`: every +thread's call chain at those seconds, unwound in-process, which works natively where `tools/re/mdmp_unwind.py` +cannot walk Windows' own DLLs). Other `LEONIDA_*` variables in your shell pass through and are listed. + +The command is `gta6rt --run --game-dir --overlay \overlay --trace .jsonl --trace-d3d12`. +The overlay takes everything the title writes, so the package folder can stay read-only. + +## What you get + +In the output folder: `.log` (stderr: `[rt]` lines and the D3D12 trace), `.stdout.log`, +`.jsonl` (startup trace), `.summary.txt` (`tools/boot_trace.py`), `.digest.txt` and +`cap_\` (PPM frames plus `index.txt` with the mean RGB of each). The digest: + +``` +== boot first: ran its full time limit (200 s), stopped +shaders: [rt] d3d12: 26586 translated shaders (21 fspx, 0 fspx_compute, 0 fspx_gfx, 52 bvh, 10 exe) from ... +states: t=0s game=0 session=0 | t=15s game=2 session=0 | t=30s game=3 session=3 | t=60s game=3 session=d +presents: PresentX ok 1581, failed 0 +input: 13 presses logged +faults: none +frames: 14 captured, 0 non-black; last mean rgb 0.00 0.00 0.00; brightest 0.00 0.00 0.00 +``` + +`-DigestOnly -Name ` writes the summary and digest again for an earlier run. The digest holds counts and +states only, which is what goes into a RESULT on the board; the logs, traces, captures and dumps can quote the game +and stay on your machine ([AGENTS.md](../../AGENTS.md), "No game data"). + +How to read the states: game state goes 1, 2 (init), 3 (running); session state goes 0, 1, 3 (landing +screen waiting for A), `d` after A. `docs/linux_proton.md` (the same stages apply natively) +section 2 has the healthy sequence with times and section 3 "which blank do you have". + +## One game at a time + +The script holds the named mutex `Local\LeonidaGameBoot` for the whole boot and also waits while any `gta6rt.exe` +runs (another agent's boot, or one started by hand), up to `-LockWaitSeconds` (default an hour, then exit 3). Two +game processes on one GPU make both runs meaningless and can take the driver down. + +## Helper tools (`tools/re/windows/`) + +| Tool | What for | +|---|---| +| `sym.py IMAGE RVA...` | `gta6rt.exe+0x...` frames to function and line through dbghelp and the build's PDB (the Windows SDK's or Visual Studio's `dbghelp.dll`; `LEONIDA_DBGHELP` names another) | +| `ripsample.ps1 [-Seconds 20]` | sampling profiler of a running `gta6rt`: per thread, where it spends its time, as module+RVA (`TITLE+0x...` for the title) | +| `minidump.py PID OUT.dmp` | a minidump through dbghelp's `MiniDumpWriteDump`. Do not use `rundll32 comsvcs.dll MiniDump`: Defender flags it. A dump holds game memory: local only | + +Each prints its usage with `-h` (Python) or `Get-Help` (PowerShell). diff --git a/scripts/windows-boot/boot.ps1 b/scripts/windows-boot/boot.ps1 new file mode 100644 index 0000000000..36bcee7a6b --- /dev/null +++ b/scripts/windows-boot/boot.ps1 @@ -0,0 +1,460 @@ +<# +.SYNOPSIS + Boot the retail executable under gta6rt on native Windows, one game process at a time, and print a digest. + +.DESCRIPTION + The native counterpart of scripts/linux-boot/: sets the switches both machines boot with (see + docs/re/howto-blank-to-story-load.md, section 1), runs `gta6rt --run` with --trace and --trace-d3d12 for + -Seconds, stops it, runs tools/boot_trace.py and prints a short digest: exit, game/session state over time, + PresentX count, device-fault lines, capture means. Paste numbers from the digest into a RESULT on the + coordination board, never the logs: they can quote the game (AGENTS.md, "No game data"). + + Only one game process runs at a time: the script holds a named mutex and also waits while any gta6rt.exe is + running (another agent's boot, or one started by hand). + + Every default switch is used only when the variable is not already set in this shell; other LEONIDA_* + variables of the shell pass through; -SetEnv overrides all of them. -DryRun lists the result. Outputs go to -OutDir (never inside the repository): + \.log stderr of gta6rt: [rt] diagnostics and [d3d12-trace] lines + \.stdout.log stdout of gta6rt + \.jsonl startup trace (--trace) + \.summary.txt tools/boot_trace.py report + \.digest.txt the digest printed at the end + \cap_\ swapchain captures (PPM) and index.txt with mean RGB per frame + +.PARAMETER Name + Run name; output files are named after it. Default: boot-. + +.PARAMETER Seconds + How long the game runs before it is stopped. Default 180. + +.PARAMETER GameDir + Your package folder (MicrosoftGame.Config and the .rpf archives as plain files). Default: $env:LEONIDA_GAME_DIR, + else game_path.txt beside gta6rt.exe (written by make_game.py's runtime stage). + +.PARAMETER Exe + game_scarlett_master.exe. Default: $env:LEONIDA_EXE, else \game_scarlett_master.exe. + +.PARAMETER Runtime + gta6rt.exe (gta6rt_tls_host.dll must sit beside it). Default: $env:GTA6RT, else + \runtime\build\RelWithDebInfo\gta6rt.exe. + +.PARAMETER Shaders + The translated library, \shaders\spirv. Default: $env:LEONIDA_SHADERS; when neither is given the + runtime reads shader_path.txt beside gta6rt.exe. + +.PARAMETER OutDir + Folder for logs, traces and captures. Default: $env:LEONIDA_RUNS, else $HOME\leonida-runs. + +.PARAMETER Overlay + Writable folder for everything the title writes (saves, caches). Default \overlay. + +.PARAMETER InputScript + LEONIDA_INPUT_SCRIPT: timed pad presses, seconds since the pad's first poll (button@seconds, comma-separated; + buttons a b x y start back lb rb up down left right). Sets LEONIDA_KEYBOARD_PAD=always. Builds older than + main @ 8146ef690 ignore a script longer than 63 characters. Default 'a@45,a@60,a@75,a@90'. + +.PARAMETER NoInput + No input script (LEONIDA_KEYBOARD_PAD then stays as this shell has it: LEONIDA_KEYBOARD_PAD=1 to play by + hand with the window focused). + +.PARAMETER Stacks + LEONIDA_STACKS: whole seconds at which every thread's call chain is printed to the log, e.g. '30,60'. + +.PARAMETER SetEnv + Extra or overriding environment variables as a hashtable, when called from a PowerShell prompt: + & .\scripts\windows-boot\boot.ps1 -SetEnv @{ LEONIDA_PEEK_SECONDS = '2' }. A value of '' removes the variable. + +.PARAMETER EnvPairs + Any further arguments, each KEY=VALUE, as scripts/linux-boot/run-boot.sh takes them. These work with + powershell -File too: ... -Name x LEONIDA_PRESENT_PLANE1=0 "LEONIDA_PEEK=,". + Applied after -SetEnv. KEY= removes the variable for this boot. + +.PARAMETER NoCapture + Do not set LEONIDA_CAPTURE. + +.PARAMETER ExtraArgs + More gta6rt arguments, appended after the standard ones. + +.PARAMETER Python + Python 3.12+ used for tools/boot_trace.py. Default: python, else py -3. + +.PARAMETER SummaryLines + How many lines of the boot_trace.py report to print. Default 40; 0 prints none. + +.PARAMETER LockWaitSeconds + How long to wait for another boot to finish. Default 3600. + +.PARAMETER DryRun + Print the environment and the command line, check the paths, launch nothing. + +.PARAMETER DigestOnly + Launch nothing; write the summary and digest again from an earlier run's files (-Name, -OutDir). + +.EXAMPLE + powershell -NoProfile -File scripts\windows-boot\boot.ps1 -DryRun -GameDir D:\GTA6pkg -Shaders E:\leonida-work\shaders\spirv + +.EXAMPLE + powershell -NoProfile -File scripts\windows-boot\boot.ps1 -Name first -Seconds 200 -GameDir D:\GTA6pkg -Shaders E:\leonida-work\shaders\spirv + +.EXAMPLE + powershell -NoProfile -File scripts\windows-boot\boot.ps1 -Name stall -Seconds 90 -Stacks 40,80 "LEONIDA_PEEK=," + +.EXAMPLE + powershell -NoProfile -File scripts\windows-boot\boot.ps1 -DigestOnly -Name first +#> +[CmdletBinding(PositionalBinding = $false)] +param( + [string]$Name = "", + [int]$Seconds = 180, + [string]$GameDir = "", + [string]$Exe = "", + [string]$Runtime = "", + [string]$Shaders = "", + [string]$OutDir = "", + [string]$Overlay = "", + [string]$InputScript = "a@45,a@60,a@75,a@90", + [string]$Stacks = "", + [hashtable]$SetEnv = @{}, + [switch]$NoCapture, + [switch]$NoInput, + [string[]]$ExtraArgs = @(), + [string]$Python = "", + [int]$SummaryLines = 40, + [int]$LockWaitSeconds = 3600, + [switch]$DryRun, + [switch]$DigestOnly, + [Parameter(ValueFromRemainingArguments = $true)] + [string[]]$EnvPairs = @() +) + +Set-StrictMode -Version 2.0 +$ErrorActionPreference = "Stop" + +$RepoRoot = [System.IO.Path]::GetFullPath((Join-Path $PSScriptRoot "..\..")) +$ExeName = "game_scarlett_master.exe" + +function Get-FirstValue { + param([object[]]$Candidates) + foreach ($c in $Candidates) { if ($c -and ([string]$c).Trim()) { return ([string]$c).Trim() } } + return "" +} + +function Read-SideFile { + # One line from a text file make_game.py writes beside gta6rt.exe (game_path.txt, shader_path.txt). + param([string]$Path) + if (Test-Path -LiteralPath $Path -PathType Leaf) { + $line = Get-Content -LiteralPath $Path -TotalCount 1 + if ($line) { return ([string]$line).Trim() } + } + return "" +} + +function ConvertTo-ProcessArgument { + # Quote one argument the way the MSVC CRT splits a command line (backslashes before a quote are doubled). + param([string]$Value) + if ($Value -ne "" -and $Value -notmatch '[\s"]') { return $Value } + $sb = New-Object System.Text.StringBuilder + [void]$sb.Append('"') + $slashes = 0 + foreach ($ch in $Value.ToCharArray()) { + if ($ch -eq '\') { $slashes++; continue } + if ($ch -eq '"') { [void]$sb.Append('\', 2 * $slashes + 1) } elseif ($slashes) { [void]$sb.Append('\', $slashes) } + $slashes = 0 + [void]$sb.Append($ch) + } + if ($slashes) { [void]$sb.Append('\', 2 * $slashes) } + [void]$sb.Append('"') + return $sb.ToString() +} + +function Test-InsideFolder { + param([string]$Path, [string]$Folder) + $p = [System.IO.Path]::GetFullPath($Path).TrimEnd('\') + '\' + $f = [System.IO.Path]::GetFullPath($Folder).TrimEnd('\') + '\' + return $p.StartsWith($f, [System.StringComparison]::OrdinalIgnoreCase) +} + +function Resolve-Python { + param([string]$Requested) + if ($Requested) { return @($Requested) } + if (Get-Command python -ErrorAction SilentlyContinue) { return @("python") } + if (Get-Command py -ErrorAction SilentlyContinue) { return @("py", "-3") } + return @() +} + +# ------------------------------------------------------------------------------------------------ paths + +if (-not $Name) { $Name = "boot-" + (Get-Date -Format "yyyyMMdd-HHmmss") } +if ($NoInput) { $InputScript = "" } +if ($Name -notmatch '^[A-Za-z0-9._-]+$') { throw "-Name may hold letters, digits, '.', '_' and '-' only: $Name" } + +$Runtime = Get-FirstValue @($Runtime, $env:GTA6RT, (Join-Path $RepoRoot "runtime\build\RelWithDebInfo\gta6rt.exe")) +$RuntimeDir = Split-Path -Parent $Runtime +$GameDir = Get-FirstValue @($GameDir, $env:LEONIDA_GAME_DIR, (Read-SideFile (Join-Path $RuntimeDir "game_path.txt"))) +$Exe = Get-FirstValue @($Exe, $env:LEONIDA_EXE, $(if ($GameDir) { Join-Path $GameDir $ExeName } else { "" })) +$Shaders = Get-FirstValue @($Shaders, $env:LEONIDA_SHADERS) +$OutDir = Get-FirstValue @($OutDir, $env:LEONIDA_RUNS, (Join-Path $HOME "leonida-runs")) +$OutDir = [System.IO.Path]::GetFullPath($OutDir) +$Overlay = Get-FirstValue @($Overlay, (Join-Path $OutDir "overlay")) +$Capture = Join-Path $OutDir ("cap_" + $Name) +$LogFile = Join-Path $OutDir ($Name + ".log") +$StdoutFile = Join-Path $OutDir ($Name + ".stdout.log") +$TraceFile = Join-Path $OutDir ($Name + ".jsonl") +$SummaryFile = Join-Path $OutDir ($Name + ".summary.txt") +$DigestFile = Join-Path $OutDir ($Name + ".digest.txt") + +$problems = New-Object System.Collections.Generic.List[string] +if (Test-InsideFolder $OutDir $RepoRoot) { $problems.Add("-OutDir $OutDir is inside the repository; logs and captures must stay outside it") } +if (-not (Test-Path -LiteralPath $Runtime -PathType Leaf)) { $problems.Add("no gta6rt.exe at $Runtime (build it, or pass -Runtime / set GTA6RT)") } +elseif (-not (Test-Path -LiteralPath (Join-Path $RuntimeDir "gta6rt_tls_host.dll") -PathType Leaf)) { + $problems.Add("gta6rt_tls_host.dll is missing beside $Runtime (build the gta6rt target; without it the title exits at once)") +} +if (-not $GameDir) { $problems.Add("no game folder: pass -GameDir or set LEONIDA_GAME_DIR") } +elseif (-not (Test-Path -LiteralPath (Join-Path $GameDir "MicrosoftGame.Config") -PathType Leaf)) { + $problems.Add("$GameDir has no MicrosoftGame.Config: -GameDir is the folder with it and the .rpf archives") +} +if (-not $Exe -or -not (Test-Path -LiteralPath $Exe -PathType Leaf)) { $problems.Add("no $ExeName at '$Exe' (pass -Exe)") } +if ($Shaders) { + if (-not (Test-Path -LiteralPath (Join-Path $Shaders "index.json") -PathType Leaf)) { + $problems.Add("$Shaders has no index.json: -Shaders is \shaders\spirv after make_game.py --stages check,shaders") + } elseif (-not (Test-Path -LiteralPath (Join-Path $Shaders "exe\index.json") -PathType Leaf)) { + Write-Warning "$Shaders has no exe\index.json: the title's 10 embedded shaders are missing and frames cannot draw (JOIN.md, 'The executable trap')" + } +} elseif (-not (Read-SideFile (Join-Path $RuntimeDir "shader_path.txt"))) { + $problems.Add("no shader library: pass -Shaders \shaders\spirv or set LEONIDA_SHADERS") +} + +# ------------------------------------------------------------------------------------------ environment + +# Defaults: used only when this shell has not set the variable. They match the Linux harness (scripts/linux-boot/). +$defaults = [ordered]@{ + LEONIDA_D3D12 = "vulkan" + LEONIDA_DEVICE_TYPE = "6" # Series S identity; the runtime answers the ConsoleMode registry read with it + LEONIDA_ARENA_MB = "2048" + LEONIDA_PIPELINE_CACHE_BYTES = "4294967296" + LEONIDA_STARTUP_CACHE_CHECKPOINTS = "1" + LEONIDA_PIPELINE_CACHE_DIR = (Join-Path $OutDir "pipeline-cache") + # LEONIDA_PEEK: the game-state and session-state RVAs (measured locally, not kept in the repository) when + # LEONIDA_GAME_STATE_RVA and LEONIDA_SESSION_STATE_RVA name them; see below. + LEONIDA_PEEK_SECONDS = "5" + LEONIDA_DEVICE_FAULT = "1" # device-loss report (VK_EXT_device_fault, checkpoints) + LEONIDA_CAPTURE_EVERY = "60" + LEONIDA_CAPTURE_LIMIT = "40" + DISABLE_RTSS_LAYER = "1" # third-party Vulkan overlay layers off + DISABLE_VULKAN_OBS_CAPTURE = "1" +} +if ($InputScript) { $defaults["LEONIDA_KEYBOARD_PAD"] = "always" } +$gameStateRva = "$env:LEONIDA_GAME_STATE_RVA".ToLowerInvariant() -replace '^0x', '' +$sessionStateRva = "$env:LEONIDA_SESSION_STATE_RVA".ToLowerInvariant() -replace '^0x', '' +if ($gameStateRva -and $sessionStateRva) { $defaults["LEONIDA_PEEK"] = "0x$gameStateRva,0x$sessionStateRva" } +# Per-run values: always this script's (from its parameters), whatever the shell has. +$perRun = [ordered]@{ + LEONIDA_CAPTURE = $(if ($NoCapture) { "" } else { $Capture }) + LEONIDA_INPUT_SCRIPT = $InputScript +} +if ($Shaders) { $perRun["LEONIDA_SHADERS"] = $Shaders } +if ($Stacks) { $perRun["LEONIDA_STACKS"] = $Stacks } + +$bootEnv = [ordered]@{} +foreach ($k in $defaults.Keys) { + $cur = [Environment]::GetEnvironmentVariable($k) + if ($cur) { $bootEnv[$k] = $cur } else { $bootEnv[$k] = $defaults[$k] } +} +foreach ($k in $perRun.Keys) { $bootEnv[$k] = $perRun[$k] } +# Other LEONIDA_* switches already set in this shell are passed through as they are; they are listed below. +foreach ($item in (Get-ChildItem Env: | Where-Object { $_.Name -like "LEONIDA_*" })) { + if (-not $bootEnv.Contains($item.Name)) { $bootEnv[$item.Name] = $item.Value } +} +foreach ($k in $SetEnv.Keys) { $bootEnv[[string]$k] = [string]$SetEnv[$k] } +foreach ($pair in $EnvPairs) { + if ($pair -notmatch '^([A-Za-z_][A-Za-z0-9_]*)=(.*)$') { throw "not a parameter and not KEY=VALUE: '$pair' (Get-Help $PSCommandPath -Full)" } + $bootEnv[$Matches[1]] = $Matches[2] +} +if ($bootEnv["LEONIDA_CAPTURE"]) { $Capture = $bootEnv["LEONIDA_CAPTURE"] } + +$gameArgs = @("--run", $Exe, "--game-dir", $GameDir, "--overlay", $Overlay, "--trace", $TraceFile, "--trace-d3d12") + $ExtraArgs +$argLine = ($gameArgs | ForEach-Object { ConvertTo-ProcessArgument ([string]$_) }) -join " " + +if (-not $DigestOnly) { + Write-Output "[boot] $Name ${Seconds}s repo $RepoRoot" + Write-Output "[boot] gta6rt $Runtime" + Write-Output "[boot] out $OutDir" + foreach ($k in $bootEnv.Keys) { if ($bootEnv[$k] -ne "") { Write-Output ("[boot] env {0}={1}" -f $k, $bootEnv[$k]) } } + Write-Output "[boot] command $(ConvertTo-ProcessArgument $Runtime) $argLine" +} + +if ($DigestOnly) { + if (-not (Test-Path -LiteralPath $LogFile)) { Write-Output "[boot] no $LogFile to digest"; exit 2 } + $problems.Clear() +} +if ($problems.Count) { + foreach ($p in $problems) { Write-Output "[boot] problem: $p" } + if (-not $DryRun) { exit 2 } +} +if ($DryRun) { Write-Output "[boot] dry run: nothing launched"; exit $(if ($problems.Count) { 2 } else { 0 }) } + +$verdict = "digest of an earlier run (-DigestOnly)" +$exitCode = 0 +if (-not $DigestOnly) { + + # --------------------------------------------------------------------------------------------- the lock + + $mutex = New-Object System.Threading.Mutex($false, "Local\LeonidaGameBoot") + $owned = $false + $saved = @{} + $exitCode = 0 + try { + $deadline = (Get-Date).AddSeconds($LockWaitSeconds) + $said = $false + while (-not $owned) { + try { $owned = $mutex.WaitOne(5000) } catch [System.Threading.AbandonedMutexException] { $owned = $true } + if ($owned -and (Get-Process -Name gta6rt -ErrorAction SilentlyContinue)) { + # A game started by hand or by another script that does not take this lock: wait for it too. + $mutex.ReleaseMutex(); $owned = $false; Start-Sleep -Seconds 5 + } + if (-not $owned) { + if (-not $said) { Write-Output "[boot] waiting: another game process is running (one at a time)"; $said = $true } + if ((Get-Date) -gt $deadline) { Write-Output "[boot] gave up waiting after $LockWaitSeconds s"; exit 3 } + } + } + + foreach ($d in @($OutDir, $Overlay)) { New-Item -ItemType Directory -Force -Path $d | Out-Null } + if ($bootEnv["LEONIDA_PIPELINE_CACHE_DIR"]) { + New-Item -ItemType Directory -Force -Path $bootEnv["LEONIDA_PIPELINE_CACHE_DIR"] | Out-Null + } + if ($bootEnv["LEONIDA_CAPTURE"]) { + # A capture folder reused by the same -Name: drop the earlier run's frames and index, nothing else. + New-Item -ItemType Directory -Force -Path $Capture | Out-Null + Get-ChildItem -LiteralPath $Capture -File | Where-Object { $_.Name -like "frame_*.ppm" -or $_.Name -like "*index.txt" } | + Remove-Item -Force -Confirm:$false + } + foreach ($f in @($LogFile, $StdoutFile, $TraceFile, $SummaryFile, $DigestFile)) { + if (Test-Path -LiteralPath $f) { Remove-Item -LiteralPath $f -Force -Confirm:$false } + } + + foreach ($k in $bootEnv.Keys) { + $saved[$k] = [Environment]::GetEnvironmentVariable($k) + $v = $bootEnv[$k]; if ($v -eq "") { $v = $null } + [Environment]::SetEnvironmentVariable($k, $v) + } + + # ------------------------------------------------------------------------------------------- the boot + $started = Get-Date + $proc = Start-Process -FilePath $Runtime -ArgumentList $argLine -WorkingDirectory $RepoRoot -NoNewWindow -PassThru ` + -RedirectStandardError $LogFile -RedirectStandardOutput $StdoutFile + $handle = $proc.Handle # keeps the exit code readable after the process ends + $stopped = $false + if (-not $proc.WaitForExit($Seconds * 1000)) { + $stopped = $true + try { Stop-Process -Id $proc.Id -Force -Confirm:$false } catch { } + [void]$proc.WaitForExit(20000) + } + $ran = [int]((Get-Date) - $started).TotalSeconds + $rc = $null + try { $rc = $proc.ExitCode } catch { } + if ($stopped) { $verdict = "ran its full time limit ($ran s), stopped"; $exitCode = 0 } + elseif ($rc -eq $null) { $verdict = "exited by itself after $ran s, exit code unknown"; $exitCode = 1 } + else { $verdict = ("exited by itself after {0} s, exit code {1} (0x{2:x8})" -f $ran, $rc, ([int64]$rc -band 0xffffffffL)); $exitCode = [int]$rc } + } finally { + foreach ($k in $saved.Keys) { [Environment]::SetEnvironmentVariable($k, $saved[$k]) } + if ($owned) { $mutex.ReleaseMutex() } + $mutex.Dispose() + } +} + +# -------------------------------------------------------------------------------------------- the digest + +$py = @(Resolve-Python $Python) +if ($py.Count) { + $pyArgs = @() + if ($py.Count -gt 1) { $pyArgs += $py[1..($py.Count - 1)] } + $pyArgs += @("-I", (Join-Path $RepoRoot "tools\boot_trace.py"), $TraceFile, "--d3d12", $LogFile) + # Windows PowerShell 5.1 turns a native program's stderr into error records; with "Stop" that would end the script. + $ErrorActionPreference = "Continue" + & $py[0] @pyArgs 2>&1 | ForEach-Object { "$_" } | Out-File -FilePath $SummaryFile -Encoding utf8 + $ErrorActionPreference = "Stop" +} else { + "no python found for tools/boot_trace.py" | Out-File -FilePath $SummaryFile -Encoding utf8 +} + +$peekRx = [regex]'\[rt\] peek t=(\d+)s:(.*)$' +$valRx = [regex]'0x([0-9a-f]+)=([0-9a-f?]+)' +$states = New-Object System.Collections.Generic.List[string] +$lastPeek = ""; $prevPair = "" +$presentOk = 0; $presentFailed = 0; $presses = 0 +$shaderLine = ""; $faults = New-Object System.Collections.Generic.List[string] +$wrapped = 0 +if (Test-Path -LiteralPath $LogFile) { + foreach ($line in [System.IO.File]::ReadLines($LogFile)) { + if ($line.Contains("XboxPresentation::PresentX")) { + if ($line.EndsWith(" ok")) { $presentOk++ } elseif ($line.EndsWith(" failed")) { $presentFailed++ } + continue + } + if ($line.Contains("[rt] peek t=")) { + $m = $peekRx.Match($line) + if ($m.Success) { + $lastPeek = $line.Substring($line.IndexOf("[rt] peek")) + $game = "?"; $session = "?" + foreach ($v in $valRx.Matches($m.Groups[2].Value)) { + $rva = $v.Groups[1].Value; $val = $v.Groups[2].Value + if ($gameStateRva -and $rva -eq $gameStateRva) { $game = $val } + elseif ($sessionStateRva -and $rva -eq $sessionStateRva -and $val -ne "?") { + $low = $val.PadLeft(16, '0').Substring(8).TrimStart('0') # the session state is the low dword + $session = $(if ($low) { $low } else { "0" }) + } + } + $pair = "game=$game session=$session" + if ($pair -ne $prevPair) { $states.Add("t=$($m.Groups[1].Value)s $pair"); $prevPair = $pair } + } + continue + } + if ($line.Contains("[rt] gameinput: press ")) { + # Buttons only: with the keyboard pad, mouse movement is logged as right-stick presses (rsup, rsdown...). + if ($line -notmatch 'gameinput: press [lr]s') { $presses++ } + continue + } + if ($line.Contains("[rt] device-fault:") -and -not $line.Contains("device-fault: enabled")) { if ($faults.Count -lt 8) { $faults.Add($line.Trim()) }; continue } + if ($line.Contains("VK_ERROR_DEVICE_LOST") -and $faults.Count -lt 8) { $faults.Add($line.Trim()); continue } + if (-not $shaderLine -and $line.Contains(" translated shaders (")) { $shaderLine = $line.Substring([Math]::Max(0, $line.IndexOf("[rt]"))).Trim() } + if ($line.Contains("wrapped V#")) { $wrapped++ } + } +} + +$capText = "no captures" +$capIndex = Join-Path $Capture "index.txt" +if (Test-Path -LiteralPath $capIndex) { + $frames = 0; $nonBlack = 0; $last = ""; $maxSum = -1.0; $maxText = "" + $meanRx = [regex]'mean rgb ([0-9.]+) ([0-9.]+) ([0-9.]+)' + foreach ($line in [System.IO.File]::ReadLines($capIndex)) { + $m = $meanRx.Match($line) + if (-not $m.Success) { continue } + $frames++ + $r = [double]::Parse($m.Groups[1].Value, [Globalization.CultureInfo]::InvariantCulture) + $g = [double]::Parse($m.Groups[2].Value, [Globalization.CultureInfo]::InvariantCulture) + $b = [double]::Parse($m.Groups[3].Value, [Globalization.CultureInfo]::InvariantCulture) + $sum = $r + $g + $b + if ($sum -gt 0) { $nonBlack++ } + $last = "$($m.Groups[1].Value) $($m.Groups[2].Value) $($m.Groups[3].Value)" + if ($sum -gt $maxSum) { $maxSum = $sum; $maxText = $last } + } + $capText = "$frames captured, $nonBlack non-black; last mean rgb $last; brightest $maxText" +} + +$digest = New-Object System.Collections.Generic.List[string] +$digest.Add("== boot ${Name}: $verdict") +$digest.Add("shaders: $(if ($shaderLine) { $shaderLine } else { 'no translated-shaders line (Vulkan device not reached?)' })") +$digest.Add("states: $(if ($states.Count) { $states -join ' | ' } else { 'no peek lines' })") +$digest.Add("presents: PresentX ok $presentOk, failed $presentFailed") +$digest.Add("input: $presses presses logged") +$digest.Add("faults: $(if ($faults.Count) { $faults.Count.ToString() + ' device-fault lines' } else { 'none' })") +foreach ($f in $faults) { $digest.Add(" $f") } +if ($wrapped) { $digest.Add("wrapped: $wrapped lines mention wrapped V#s") } +$digest.Add("frames: $capText") +$digest.Add("files: $LogFile, $TraceFile, $SummaryFile") +$digest | Out-File -FilePath $DigestFile -Encoding utf8 +$digest +if ($SummaryLines -gt 0 -and (Test-Path -LiteralPath $SummaryFile)) { + Write-Output "-- boot_trace.py (first $SummaryLines lines of $SummaryFile)" + Get-Content -LiteralPath $SummaryFile -TotalCount $SummaryLines +} +exit $exitCode diff --git a/tests/semantic/fixtures/buffer_format_unreadable.asm b/tests/semantic/fixtures/buffer_format_unreadable.asm new file mode 100644 index 0000000000..37e3c72e1e --- /dev/null +++ b/tests/semantic/fixtures/buffer_format_unreadable.asm @@ -0,0 +1,6 @@ +; s[4:7] is the tested V#. The harness gives s[0:3] a separate output range. +v_cmpx_eq_u32_e32 0, v0 +buffer_load_format_xyzw v[4:7], off, s[4:7], 0 +s_waitcnt vmcnt(0) +buffer_store_dwordx4 v[4:7], off, s[0:3], 0 +s_endpgm diff --git a/tests/semantic/fixtures/descriptor_hash_lookup.asm b/tests/semantic/fixtures/descriptor_hash_lookup.asm new file mode 100644 index 0000000000..9c92235cc5 --- /dev/null +++ b/tests/semantic/fixtures/descriptor_hash_lookup.asm @@ -0,0 +1,49 @@ +; Synthetic SPIR-V harness for the translator's descriptor lookup function. +; One workgroup per key. The table and keys share binding 2. Return hash and index in the heap. +OpCapability Shader +OpCapability Int64 +OpCapability PhysicalStorageBufferAddresses +OpExtension "SPV_KHR_physical_storage_buffer" +OpMemoryModel PhysicalStorageBuffer64 GLSL450 +OpEntryPoint GLCompute %main "main" %group %desc_map %pc +OpExecutionMode %main LocalSize 1 1 1 +OpDecorate %group BuiltIn WorkgroupId +OpDecorate %words ArrayStride 4 +OpMemberDecorate %table 0 Offset 0 +OpDecorate %table Block +OpDecorate %desc_map DescriptorSet 0 +OpDecorate %desc_map Binding 2 +OpMemberDecorate %push 0 Offset 128 +OpDecorate %push Block +%void = OpTypeVoid +%bool = OpTypeBool +%uint = OpTypeInt 32 0 +%ulong = OpTypeInt 64 0 +%v3uint = OpTypeVector %uint 3 +%true = OpConstantTrue %bool +%words = OpTypeRuntimeArray %uint +%table = OpTypeStruct %words +%push = OpTypeStruct %ulong +%table_ptr = OpTypePointer StorageBuffer %table +%group_ptr = OpTypePointer Input %v3uint +%push_ptr = OpTypePointer PushConstant %push +%heap_ptr = OpTypePointer PushConstant %ulong +%physical_word = OpTypePointer PhysicalStorageBuffer %uint +%_ptr_Function_uint = OpTypePointer Function %uint +%_ptr_SB_uint = OpTypePointer StorageBuffer %uint +%desc_map = OpVariable %table_ptr StorageBuffer +%pc = OpVariable %push_ptr PushConstant +%group = OpVariable %group_ptr Input +%entry_type = OpTypeFunction %void +%fn_desc_lookup = OpTypeFunction %uint %uint %uint %uint %uint %uint %uint %uint %uint +; CONSTANTS +%main = OpFunction %void None %entry_type +%entry = OpLabel +%xyz = OpLoad %v3uint %group +%i = OpCompositeExtract %uint %xyz 0 +%row = OpIMul %uint %i %c8 +%start = OpIAdd %uint %row %c1401 +; LOOKUP_AND_READBACK +OpReturn +OpFunctionEnd +; LOOKUP_FUNCTION diff --git a/tests/semantic/fixtures/fspx_short_prologue.asm b/tests/semantic/fixtures/fspx_short_prologue.asm new file mode 100644 index 0000000000..70f9f96c01 --- /dev/null +++ b/tests/semantic/fixtures/fspx_short_prologue.asm @@ -0,0 +1,6 @@ +; Two synthetic VOP3 NOPs with SRC2 selecting a literal. Each consumes 12 bytes. +; The second literal resembles s_endpgm. Only the last instruction ends the program. +.long 0xd5800011, 0x03fe0102, 0x12345678 +.long 0xd5800022, 0x03fe0501, 0xbf810000 +s_nop 0 +s_endpgm diff --git a/tests/semantic/fixtures/loop_iteration_guard.asm b/tests/semantic/fixtures/loop_iteration_guard.asm new file mode 100644 index 0000000000..ca57148e5e --- /dev/null +++ b/tests/semantic/fixtures/loop_iteration_guard.asm @@ -0,0 +1,11 @@ +; s4 is the requested stopping value. Each invocation reports every visit. +; An even increment cannot meet an odd bound, including across u32 wrap. +v_lshlrev_b32_e32 v2, 2, v0 +s_mov_b32 s8, 0 +again: +s_add_u32 s8, s8, 2 +v_mov_b32_e32 v1, s8 +buffer_store_dword v1, v2, s[0:3], 0 offen +s_cmp_eq_u32 s8, s4 +s_cbranch_scc0 again +s_endpgm diff --git a/tests/semantic/fixtures/ps_vsharp_sext48.asm b/tests/semantic/fixtures/ps_vsharp_sext48.asm new file mode 100644 index 0000000000..c04b029d3b --- /dev/null +++ b/tests/semantic/fixtures/ps_vsharp_sext48.asm @@ -0,0 +1,10 @@ +; V# base = 0xffffffffffc0 (-64), stride 0, RAW bounds. Read at heap_base - 48 and heap_base. + s_mov_b32 s4, 0xffffffc0 + s_mov_b32 s5, 0x0000ffff + s_mov_b32 s6, 0x44 + s_mov_b32 s7, 0x31016fac + buffer_load_dword v0, off, s[4:7], 0 offset:16 + buffer_load_dword v1, off, s[4:7], 0 offset:64 + s_waitcnt vmcnt(0) + exp mrt0 v0, v1, v0, v1 done vm + s_endpgm diff --git a/tests/semantic/fixtures/smem_vcc_mask_pointer.asm b/tests/semantic/fixtures/smem_vcc_mask_pointer.asm new file mode 100644 index 0000000000..13912715b9 --- /dev/null +++ b/tests/semantic/fixtures/smem_vcc_mask_pointer.asm @@ -0,0 +1,9 @@ +; Lane 12 compares equal. Its carry bit makes the low address 4096 on wave32. +s_mov_b32 vcc_hi, 0 +v_cmp_eq_u32_e32 vcc_lo, 12, v0 +s_load_dword s8, vcc, 0 +s_waitcnt lgkmcnt(0) +v_mov_b32_e32 v6, 0x3000 +v_mov_b32_e32 v7, s8 +global_store_dword v6, v7, s[0:1] +s_endpgm diff --git a/tests/semantic/fixtures/smem_vcc_pair.asm b/tests/semantic/fixtures/smem_vcc_pair.asm new file mode 100644 index 0000000000..d83f9478a9 --- /dev/null +++ b/tests/semantic/fixtures/smem_vcc_pair.asm @@ -0,0 +1,18 @@ +; A wave32 carries a >4 GiB scalar pointer in VCC. Copy it both ways and XOR both halves. +s_mov_b32 s4, 0x1040 +s_mov_b32 s5, 1 +s_mov_b64 vcc, s[4:5] +s_mov_b64 s[14:15], vcc +v_cndmask_b32_e32 v7, 0, 1, vcc_lo +s_mov_b32 s6, 0x40 +s_mov_b32 s7, 2 +s_xor_b64 vcc, s[6:7], vcc +s_load_dword s8, vcc, 0 +s_waitcnt lgkmcnt(0) +v_mov_b32_e32 v4, s14 +v_mov_b32_e32 v5, s15 +v_mov_b32_e32 v6, s8 +v_lshlrev_b32_e32 v1, 4, v0 +v_add_nc_u32_e32 v1, 0x3000, v1 +global_store_dwordx4 v1, v[4:7], s[0:1] +s_endpgm diff --git a/tests/semantic/fixtures/smem_vcc_pointer.asm b/tests/semantic/fixtures/smem_vcc_pointer.asm new file mode 100644 index 0000000000..1564773680 --- /dev/null +++ b/tests/semantic/fixtures/smem_vcc_pointer.asm @@ -0,0 +1,10 @@ +; VCC contains a scalar byte address. An unbounded SMEM load reads its two words. +s_mov_b32 vcc_lo, 0x1000 +s_mov_b32 vcc_hi, 0 +s_load_dwordx2 s[8:9], vcc, 4 +s_waitcnt lgkmcnt(0) +v_mov_b32_e32 v0, 0x3000 +v_mov_b32_e32 v1, s8 +v_mov_b32_e32 v2, s9 +global_store_dwordx2 v0, v[1:2], s[0:1] +s_endpgm diff --git a/tests/semantic/fixtures/store_dynamic_vsharp.asm b/tests/semantic/fixtures/store_dynamic_vsharp.asm new file mode 100644 index 0000000000..4834f8b8e6 --- /dev/null +++ b/tests/semantic/fixtures/store_dynamic_vsharp.asm @@ -0,0 +1,7 @@ +; Store four distinct f32 words through the V# supplied by the caller. +v_mov_b32_e32 v4, 1.0 +v_mov_b32_e32 v5, 2.0 +v_mov_b32_e32 v6, 0x40400000 +v_mov_b32_e32 v7, 4.0 +buffer_store_format_xyzw v[4:7], off, s[0:3], 0 +s_endpgm diff --git a/tests/semantic/fixtures/vcc_scalar_tuple_moves.asm b/tests/semantic/fixtures/vcc_scalar_tuple_moves.asm new file mode 100644 index 0000000000..240bbb3e42 --- /dev/null +++ b/tests/semantic/fixtures/vcc_scalar_tuple_moves.asm @@ -0,0 +1,21 @@ +; Build a buffer resource in SGPRs 104..107. Read both scalar words back after a tuple load. +s_mov_b32 s104, 0x4000 +s_mov_b32 s105, 0 +s_mov_b32 s8, 8 +s_mov_b32 s9, 0x31016fac +s_mov_b64 vcc, s[8:9] +s_buffer_load_dwordx2 s[10:11], [s104,s105,vcc_lo,vcc_hi], 0 +s_waitcnt lgkmcnt(0) +s_mov_b64 vcc, s[10:11] +s_mov_b64 s[12:13], vcc +s_add_u32 s14, vcc_hi, 3 +s_buffer_load_dwordx4 [s104,s105,vcc_lo,vcc_hi], s[0:3], 0x4000 +s_waitcnt lgkmcnt(0) +s_mov_b64 s[20:21], vcc +v_mov_b32_e32 v4, s12 +v_mov_b32_e32 v5, s13 +v_mov_b32_e32 v6, s14 +v_mov_b32_e32 v7, s21 +v_lshlrev_b32_e32 v1, 4, v0 +buffer_store_dwordx4 v[4:7], v1, s[0:3], 0 offen +s_endpgm diff --git a/tests/semantic/fixtures/vcc_tuple_word.asm b/tests/semantic/fixtures/vcc_tuple_word.asm new file mode 100644 index 0000000000..7917e36d9e --- /dev/null +++ b/tests/semantic/fixtures/vcc_tuple_word.asm @@ -0,0 +1,4 @@ +; Synthetic s_buffer_load_dwordx4 from s[4:7] into s104, s105, vcc_lo, vcc_hi. +; A following scalar wait is outside the eight bytes the decoder must restore. +.long 0xf4281a02, 0xfa000000 +s_waitcnt lgkmcnt(0) diff --git a/tests/semantic/fixtures/vopc_dpp_compare.asm b/tests/semantic/fixtures/vopc_dpp_compare.asm new file mode 100644 index 0000000000..747c206de6 --- /dev/null +++ b/tests/semantic/fixtures/vopc_dpp_compare.asm @@ -0,0 +1,10 @@ +; Each lane compares a permuted neighbour's float against its own lane index. +v_cvt_f32_u32 v2, v0 +v_cmp_gt_f32_dpp vcc, v2, v2 quad_perm:[2,3,0,1] row_mask:0xf bank_mask:0xf bound_ctrl:1 +v_cndmask_b32 v3, 0, 1, vcc +v_cmp_gt_f32_dpp vcc, v2, v2 dpp8:[7,6,5,4,3,2,1,0] +v_cndmask_b32 v4, 0, 1, vcc +v_lshlrev_b32 v5, 3, v0 +buffer_store_dwordx2 v[3:4], v5, s[0:3], 0 offen +s_endpgm + diff --git a/tests/semantic/fixtures/waterfall_table_offset.asm b/tests/semantic/fixtures/waterfall_table_offset.asm new file mode 100644 index 0000000000..f2412fbf40 --- /dev/null +++ b/tests/semantic/fixtures/waterfall_table_offset.asm @@ -0,0 +1,20 @@ +; Synthetic descriptor table. Each group of eight lanes uses one of four V#s. +; s[0:3] describes the output. s[4:5] points to four input descriptors. +v_lshrrev_b32_e32 v1, 3, v0 +v_and_b32_e32 v1, 3, v1 +v_lshlrev_b32_e32 v1, 4, v1 +v_lshlrev_b32_e32 v2, 2, v0 +s_mov_b32 s12, exec_lo +s_mov_b32 s13, exec_lo +again: +v_readfirstlane_b32 s14, v1 +v_cmpx_eq_u32_e32 s14, v1 +s_load_dwordx4 s[16:19], s[4:5], s14 +s_waitcnt lgkmcnt(0) +buffer_load_dword v3, off, s[16:19], 0 +s_waitcnt vmcnt(0) +s_andn2_wrexec_b32 s13, s13 +s_cbranch_execnz again +s_mov_b32 exec_lo, s12 +buffer_store_dword v3, v2, s[0:3], 0 offen +s_endpgm diff --git a/tests/semantic/fixtures/wave64_scalar_mask_bits.asm b/tests/semantic/fixtures/wave64_scalar_mask_bits.asm new file mode 100644 index 0000000000..69bc1dba49 --- /dev/null +++ b/tests/semantic/fixtures/wave64_scalar_mask_bits.asm @@ -0,0 +1,20 @@ +; Read EXEC with bits in either half and when empty. Then replicate scalar bits into VCC. +s_cmp_eq_u32 1, 1 +s_mov_b64 exec, 0 +s_flbit_i32_b64 s6, exec +s_mov_b32 exec_lo, 0x200 +s_flbit_i32_b64 s7, exec +s_mov_b32 exec_hi, 0x100 +s_flbit_i32_b64 s8, exec +s_mov_b64 exec, -1 +s_bitreplicate_b64_b32 vcc, 0x80000021 +s_cselect_b32 s9, 2, 0 +v_cndmask_b32 v4, 0, 1, vcc +v_add_nc_u32 v4, s9, v4 +v_mov_b32 v1, s6 +v_mov_b32 v2, s7 +v_mov_b32 v3, s8 +v_lshlrev_b32 v5, 4, v0 +buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen +s_endpgm + diff --git a/tests/semantic/fixtures/wave64_valu_mask_width.asm b/tests/semantic/fixtures/wave64_valu_mask_width.asm new file mode 100644 index 0000000000..d7175c9279 --- /dev/null +++ b/tests/semantic/fixtures/wave64_valu_mask_width.asm @@ -0,0 +1,12 @@ +; Hand-written wave32-style predicates in a wave64 listing. s9 starts as all ones. +s_mov_b32 s9, -1 +v_cmp_lt_u32_e64 s8, v0, 36 +v_cndmask_b32_e64 v1, 0, 1, s[8:9] +v_add_co_u32_e64 v2, s10, -33, v0 +v_add_co_ci_u32_e64 v2, vcc_lo, 0, 0, s[10:11] +s_mov_b32 s14, 0 +s_mov_b32 s15, 16 +v_cndmask_b32_e64 v3, 0, 7, s14 +v_lshlrev_b32_e32 v4, 4, v0 +buffer_store_dwordx3 v[1:3], v4, s[0:3], 0 offen +s_endpgm diff --git a/tests/semantic/spirv_mini_interp.py b/tests/semantic/spirv_mini_interp.py index 8932a24486..8868dd5fb0 100644 --- a/tests/semantic/spirv_mini_interp.py +++ b/tests/semantic/spirv_mini_interp.py @@ -107,7 +107,7 @@ def __repr__(self): # Operations whose result is undefined when an operand is (they have no side effect and no control). _PURE = frozenset({ "OpBitwiseAnd", "OpBitwiseOr", "OpBitwiseXor", "OpNot", "OpShiftLeftLogical", "OpShiftRightLogical", - "OpShiftRightArithmetic", "OpIAdd", "OpISub", "OpIMul", "OpUConvert", "OpBitCount", "OpIEqual", + "OpShiftRightArithmetic", "OpIAdd", "OpISub", "OpIMul", "OpUMod", "OpUConvert", "OpBitCount", "OpIEqual", "OpINotEqual", "OpSLessThan", "OpULessThan", "OpUGreaterThan", "OpUGreaterThanEqual", "OpCopyObject", "OpBitcast", "OpBitFieldUExtract", "OpBitFieldSExtract", "OpBitFieldInsert", @@ -756,6 +756,12 @@ def sval(x): if op == "OpKill": killed = True break + if op == "OpSwitch": + key = val(a[0]) + mask = wmask(id_type[a[0]]) + target = next((label for literal, label in zip(a[2::2], a[3::2]) + if int(literal, 0) & mask == key & mask), a[1]) + op, a = "OpBranch", [target] if op == "OpBranch": if a[0] not in labels: raise UnsupportedConstruct(f"unknown branch target {a[0]}") @@ -988,6 +994,9 @@ def sval(x): values[res] = (val(a[1]) + val(a[2])) & wmask(a[0]) elif op == "OpISub": values[res] = (val(a[1]) - val(a[2])) & wmask(a[0]) + elif op == "OpUMod": + divisor = val(a[2]) & wmask(a[0]) + values[res] = (val(a[1]) & wmask(a[0])) % divisor if divisor else UNDEF elif op == "OpIMul": values[res] = (val(a[1]) * val(a[2])) & wmask(a[0]) elif op == "OpUConvert": diff --git a/tests/semantic/test_alu_dot4_i8.py b/tests/semantic/test_alu_dot4_i8.py index 23c73bdaa0..a074ad8f25 100644 --- a/tests/semantic/test_alu_dot4_i8.py +++ b/tests/semantic/test_alu_dot4_i8.py @@ -15,8 +15,9 @@ op_sel 2 and op_sel_hi 5, which llvm-mc does not decode (docs/fspx.md). Run on the same hardware as two raw words (0xCC165008 0x0C0E0501: v8 = v1 . v2 + v3 with those fields), that form gave the words of MEASURED_OP_SEL: the dot product with the two 16-bit halves of the second source exchanged, as op_sel selects halves for the packed 16-bit -ops. `ref_op_sel` reproduces them; the translator refuses any op_sel on these two instructions until a listing can -carry it. +ops. `ref_op_sel` reproduces them. A listing carries the form since tools/shader_disasm.py prints it +(tests/semantic/test_fspx_dot4_op_sel_disasm.py), and the translator also recovers it from the binary when a +listing lacks it (rdna2spirv.skipped_form). neg_lo and neg_hi. llvm-mc accepts them on v_dot4_i32_i8 for gfx1036 (not on v_dot4c_i32_i8), and the hardware does not ignore them: on the same GPU, 5 operand sets with 8 forms each gave the words of `ref_neg`, 9 of which are in @@ -164,6 +165,45 @@ def test_op_sel_matches_hardware_words(self): spv = support.translate_lines("ps_dot4_op_sel", lines) self.assertEqual(support.mrt0_words(spv), [measured] * 4) + def test_llvm_gap_restores_the_measured_dot_and_its_following_store(self): + from test_vcc_tuple_fallback import PROGRAM_VARIANTS, OUT, run, translate + # Synthetic v8 = dot(v1, swap_halves(v2)) + v3. The store observes the real destination. + program = [ + ("v_mov_b32_e32 v1, 0x04030201", "ff 02 02 7e 01 02 03 04"), + ("v_mov_b32_e32 v2, 0x08070605", "ff 02 04 7e 05 06 07 08"), + ("v_mov_b32_e32 v3, 0", "80 02 06 7e"), + (None, "08 50 16 cc 01 05 0e 0c"), + ("v_mov_b32_e32 v6, 0x3000", "ff 02 0c 7e 00 30 00 00"), + ("global_store_dword v6, v8, s[0:1]", "00 80 70 dc 06 08 00 00"), + ("s_endpgm", "00 00 81 bf"), + ] + for variant in PROGRAM_VARIANTS: + with self.subTest(variant=variant): + self.assertEqual(run(translate(program, variant), {})[OUT], 62) + for word in ("08 d0 16 cc", "08 50 96 cc", "08 48 16 cc"): + with self.subTest(word=word), self.assertRaisesRegex(support.rdna2spirv.Unsupported, "undecodable"): + translate(program[:3] + [(None, word + " 01 05 0e 0c")] + program[4:]) + + def test_llvm_inline_dot_uses_the_stored_source_half(self): + import struct + from test_vcc_tuple_fallback import listing_and_blob, OUT, run, NAME + w0 = 0xcc164008 + w1 = 257 | (138 << 9) | (259 << 18) | (1 << 27) + raw = struct.pack(" aligned -> succeeds. diff --git a/tests/semantic/test_buffer_formats_all.py b/tests/semantic/test_buffer_formats_all.py index ca580a998c..37bbe704ea 100644 --- a/tests/semantic/test_buffer_formats_all.py +++ b/tests/semantic/test_buffer_formats_all.py @@ -147,6 +147,19 @@ def test_loads_through_tbuffer_formats(self): class StoresMatchTheModel(unittest.TestCase): + def test_dynamic_format_switch_and_unknown_codes(self): + with open(os.path.join(HERE, "fixtures", "store_dynamic_vsharp.asm"), encoding="utf-8") as f: + spv = support.translate_lines("cs_dynamic_format", f.read().splitlines(), fssm=tv.CS_BOUNDS_FSSM) + words = [0x3f800000, 0x40000000, 0x40400000, 0x40800000] + for code, count in ((0, 0), (20, 1), (22, 1), (77, 4), (78, 0), (127, 0)): + with self.subTest(code=code): + memory = {OUT_BASE + i * 4: SENTINEL for i in range(5)} + support.run_fragment(spv, inputs={"%wg_id": (0, 0, 0), "%local_id": (0, 0, 0)}, + push_constants=[OUT_BASE, 0, 16, 0x30000000 | code << 12 | DST_XYZW], + memory=memory) + self.assertEqual([memory[OUT_BASE + i * 4] for i in range(5)], + words[:count] + [SENTINEL] * (5 - count)) + def test_stores_through_the_v_sharp(self): for code in ADDED: name = model.GFX10_NAMES[code] diff --git a/tests/semantic/test_buffer_oob_dst_sel.py b/tests/semantic/test_buffer_oob_dst_sel.py index f8b997cb28..d693c7cdbb 100644 --- a/tests/semantic/test_buffer_oob_dst_sel.py +++ b/tests/semantic/test_buffer_oob_dst_sel.py @@ -98,6 +98,17 @@ def _run_cs( ) return mem, spv + def test_invalid_format_with_nonempty_range_skips_backing_load(self): + with open(os.path.join(HERE, "fixtures", "buffer_format_unreadable.asm"), encoding="utf-8") as f: + lines = [line.strip() for line in f if not line.startswith(";")] + for code in (0, 78, 127, 20): + with self.subTest(code=code): + pcs = [0, 0, 16, OUT_V, BASE, 0, 16, word3(code, DST_X_0_1_1)] + [0] * 24 + mem, _ = self._run_cs(lines, push_constants=pcs) + self.assertEqual(bool(mem.reads), code == 20) + self.assertEqual([dict.get(mem, i, 0) for i in (0, 4, 8, 12)], + [0x3F000000 if code == 20 else 0, 0, 1, 1]) + def test_all_supported_formats_preserve_dst_sel_one_when_oob(self): """Runtime V# sweep across every format in Gen.FORMATS (xyzw, d16_xyzw, d16_xyz, d16_x).""" lines = [ diff --git a/tests/semantic/test_control_flow_branches.py b/tests/semantic/test_control_flow_branches.py index 4193a8073f..d5e712c353 100644 --- a/tests/semantic/test_control_flow_branches.py +++ b/tests/semantic/test_control_flow_branches.py @@ -409,12 +409,30 @@ def deref(p): ip = 0 steps = 0 + current = previous = None # the block being run and the one that branched to it, for OpPhi while ip < len(self.insns): steps += 1 if steps > max_steps: raise BranchExecutionLimitError(f"Step limit {max_steps} exceeded: possible infinite loop") res, op, a, _ = self.insns[ip] - if op in _IGNORED or op == "OpLabel": + if op == "OpLabel": + previous, current = current, res + ip += 1 + continue + if op == "OpPhi": + # The block's phis read their incoming values together (tools/spirv_loop_guard.py adds them). + chosen = {} + while ip < len(self.insns) and self.insns[ip][1] == "OpPhi": + phi_res, _, phi_args, _ = self.insns[ip] + pairs = list(zip(phi_args[1::2], phi_args[2::2])) + incoming = next((v for v, parent in pairs if parent == previous), None) + if incoming is None: + raise UnsupportedConstruct(f"OpPhi {phi_res} has no value for block {previous}") + chosen[phi_res] = val(incoming) + ip += 1 + values.update(chosen) + continue + if op in _IGNORED: ip += 1 continue if op in ("OpReturn", "OpFunctionEnd"): diff --git a/tests/semantic/test_descriptor_hash.py b/tests/semantic/test_descriptor_hash.py new file mode 100644 index 0000000000..4ca3f3ac7c --- /dev/null +++ b/tests/semantic/test_descriptor_hash.py @@ -0,0 +1,98 @@ +"""Shared descriptor vectors from plaaasma. Check full 32-bit hashes and probe the emitted lookup.""" +from pathlib import Path +import sys +import unittest +from unittest.mock import patch + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +import support +import rdna2spirv as rd +import spirv_mini_interp as si + +VECTORS = ( + ((0x00100000, 0, 0x90500fac, 0, 0, 0, 0, 0), 0x1cd4cd59, 345, 0x7ce036c5, 197), + ((0x10100000, 0, 0x90500fac, 0, 0, 0, 0, 0), 0x0cd4cd59, 345, 0x646b8915, 277), + ((0x20100000, 0, 0x90500fac, 0, 0, 0, 0, 0), 0x3cd4cd59, 345, 0xc2e843b6, 438), + ((0x30100000, 0, 0x90500fac, 0, 0, 0, 0, 0), 0x2cd4cd59, 345, 0xe11420e3, 227), + ((0x12345678, 0x9abcdef0, 0x0fedcba9, 0x87654321, 0x11111111, 0x22222222, 0x33333333, 0x44444444), + 0xbd4a977f, 383, 0x3ae592b1, 177), + ((0,) * 8, 0x9be17165, 357, 0xbb10dc19, 25), + ((0x00010001, 0x00400040, 0x10014fac, 0, *([0xffffffff] * 4)), 0x814225e4, 484, 0xd5398a35, 53), + ((0xffffffff,) * 8, 0xb0e4285d, 93, 0x98a3f73a, 314), +) +OUTPUT = 0x8000 + + +def table_and_expected(mode): + table = [511] + [0xabababab] * (512 * 10) + expected = [] + for i, (key, fnv, old_slot, mixed, new_slot) in enumerate(VECTORS): + value, slot = (fnv, old_slot) if mode == "fnv1a" else (mixed, new_slot) + assert value & 511 == slot + # Start at the *published* home slot. Include collisions and a hit on the eighth probe. + probe = 7 if i == 7 else 0 + while table[1 + 10 * ((slot + probe) & 511) + 8] != 0xabababab: + probe += 1 + assert probe < 8 + start = 1 + 10 * ((slot + probe) & 511) + table[start:start + 9] = [*key, 100 + i] + table.extend(key) + expected.extend((value, 100 + i)) + return table, expected + + +def readback_shader(mode): + with patch.object(rd, "DESCRIPTOR_HASH", mode): + g = rd.Gen("cs") + g.emulate = True # Single-invocation workgroups need no subgroup broadcast of the result. + keys = [] + for i in range(8): + off, ptr, key = g.tmp(), g.tmp(), g.tmp() + g.emit(f"{off} = OpIAdd %uint %start {g.cu(i)}") + g.emit(f"{ptr} = OpAccessChain %_ptr_SB_uint %desc_map {g.cu(0)} {off}") + g.emit(f"{key} = OpLoad %uint {ptr}") + keys.append(key) + hashed = g.desc_hash(keys) + index = g.desc_lookup(keys) + g.emit("%hp = OpAccessChain %heap_ptr %pc %c0") + g.emit("%heap = OpLoad %ulong %hp") + for i, value in enumerate((hashed, index)): + off, wide, addr, ptr = g.tmp(), g.tmp(), g.tmp(), g.tmp() + g.emit(f"{off} = OpIAdd %uint %row {g.cu(OUTPUT + 4 * i)}") + g.emit(f"{wide} = OpUConvert %ulong {off}") + g.emit(f"{addr} = OpIAdd %ulong %heap {wide}") + g.emit(f"{ptr} = OpConvertUToPtr %physical_word {addr}") + g.emit(f"OpStore {ptr} {value} Aligned 4") + g.cu(8) + g.cu(1 + 512 * 10) + asm = (HERE / "fixtures/descriptor_hash_lookup.asm").read_text(encoding="utf-8") + constants = [f"{ident} = OpConstant %uint {value}" for value, ident in g.consts.items()] + for marker, lines in (("CONSTANTS", constants), ("LOOKUP_AND_READBACK", g.body), ("LOOKUP_FUNCTION", g.desc_fn)): + asm = asm.replace("; " + marker, "\n".join(lines)) + return "\n".join(line for line in asm.splitlines() if not line.startswith(";")) + "\n" + + +class DescriptorHashTest(unittest.TestCase): + def test_entire_hash_and_probed_index(self): + for mode in rd.DESCRIPTOR_HASHES: + with self.subTest(mode=mode): + asm = readback_shader(mode) + table, expected = table_and_expected(mode) + memory = {} + for i in range(len(VECTORS)): + si.run_workgroup(asm, 1, 1, inputs_for=lambda _: {"%group": (i, 0, 0)}, + resources={"%desc_map": table}, push_constants=[0] * 36, memory=memory) + self.assertEqual([memory[OUTPUT + 4 * i] for i in range(len(expected))], expected) + + def test_every_module_records_its_build_mode(self): + for mode in rd.DESCRIPTOR_HASHES: + with patch.object(rd, "DESCRIPTOR_HASH", mode): + asm = support.translate_lines("ps_hash_marker", ["v_mov_b32 v0, 0", + "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"]) + meta = rd.shader_meta(rd.translate.last_gen, asm) + self.assertEqual(meta.get("descriptor_hash"), None if mode == "fnv1a" else mode) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_dot4_printed_op_sel.py b/tests/semantic/test_dot4_printed_op_sel.py new file mode 100644 index 0000000000..85b90feef6 --- /dev/null +++ b/tests/semantic/test_dot4_printed_op_sel.py @@ -0,0 +1,117 @@ +"""A v_dot4_i32_i8 whose op_sel/op_sel_hi llvm-mc printed as the defaults takes the stored fields. + +llvm-mc decodes a VOP3P v_dot4_i32_i8 with op_sel_hi other than [1,1,1] but prints and re-encodes it with op_sel 0 and +op_sel_hi 7, so the listing names halves the instruction does not read. translate() used to refuse it ("a field the +disassembler dropped"); it now reads the two fields from the blob when they are the only difference +(rdna2spirv.dot4_op_sel_fields), and the v_dot4_i32_i8 rule applies them as measured on gfx1036 +(tests/semantic/test_alu_dot4_i8.py). Ported from luizwidmer/palmetto (GPL-3.0). Hand-built listing and blob, the +encodings assembled from the VOP3P field layout; no game data. + + python -I tests/semantic/test_dot4_printed_op_sel.py -v +""" +import os +import struct +import sys +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +if HERE not in sys.path: + sys.path.insert(0, HERE) + +from support import mrt0_words, rdna2spirv, translate_listing # noqa: E402 + +NAME = "ps_dot4_printed_op_sel" +CODE_START = 0x100 +A, B, C = 0x80FF7F01, 0x12F0FE7F, 0x00001000 + + +def dot4(op_sel=0, op_sel_hi=7, dst=0, srcs=(1, 2, 3)): + """VOP3P v_dot4_i32_i8 (opcode 0x16) vdst, v[srcs] with the given op_sel and op_sel_hi.""" + w0 = 0xCC000000 | (0x16 << 16) | ((op_sel_hi >> 2) & 1) << 14 | (op_sel & 7) << 11 | dst + w1 = (op_sel_hi & 3) << 27 | (256 + srcs[2]) << 18 | (256 + srcs[1]) << 9 | (256 + srcs[0]) + return struct.pack("<2I", w0, w1).hex(" ") + + +def v_mov(reg, value): + return (f"v_mov_b32_e32 v{reg}, 0x{value:x}", f"ff {2 * reg:02x} 02 7e " + struct.pack("> off) & 0xFF + return v - 256 if v & 0x80 else v + total = addend + for k in range(4): + half = (op_sel if k < 2 else op_sel_hi) + xo = 16 * ((half >> 0) & 1) + 8 * (k & 1) + yo = 16 * ((half >> 1) & 1) + 8 * (k & 1) + total += byte(a, xo) * byte(b, yo) + return total & 0xFFFFFFFF + + +def translate(stored_dot4, reanchor=False): + printed = SETUP + [PRINTED] + TAIL + stored = SETUP + [("", stored_dot4)] + TAIL + code = b"".join(bytes.fromhex(enc) for _, enc in stored) + data = listing(printed, CODE_START + len(code)) + blob = bytes(CODE_START) + code + if reanchor: # a listing with an undecodable word after the code goes through the re-anchoring path + data += b"; warning: invalid instruction encoding\n" + blob += b"\xff" * 4 + return translate_listing(NAME, data, fssm=blob) + + +class Dot4PrintedOpSelTest(unittest.TestCase): + def test_reference_is_the_plain_dot_product_for_the_defaults(self): + sb = [lambda x, k=k: (((x >> 8 * k) & 0xFF) ^ 0x80) - 0x80 for k in range(4)] + self.assertEqual(ref(A, B, C), (sum(f(A) * f(B) for f in sb) + C) & 0xFFFFFFFF) + + def test_default_fields_translate_as_printed(self): + self.assertEqual(mrt0_words(translate(dot4())), [ref(A, B, C)] * 4) + + def test_stored_op_sel_hi_is_read_from_the_blob(self): + # op_sel_hi [1,0,1]: byte pairs 2..3 of S1 come from its low half. llvm-mc decodes it and prints [1,1,1]. + for reanchor in (False, True): + with self.subTest(reanchor=reanchor): + got = mrt0_words(translate(dot4(op_sel_hi=5), reanchor)) + self.assertEqual(got, [ref(A, B, C, op_sel_hi=5)] * 4) + self.assertNotEqual(ref(A, B, C, op_sel_hi=5), ref(A, B, C)) + + def test_stored_op_sel_on_source_0_is_read_from_the_blob(self): + got = mrt0_words(translate(dot4(op_sel=1, op_sel_hi=6))) + self.assertEqual(got, [ref(A, B, C, op_sel=1, op_sel_hi=6)] * 4) + + def test_a_non_default_s2_half_stays_refused(self): + with self.assertRaises(rdna2spirv.Unsupported) as cm: + translate(dot4(op_sel_hi=3)) + self.assertIn("op_sel", str(cm.exception)) + + def test_another_difference_is_still_a_dropped_field(self): + # The stored word names v4 as S2, the printed one v3: not an op_sel difference. + with self.assertRaises(rdna2spirv.Unsupported) as cm: + translate(dot4(op_sel_hi=5, srcs=(1, 2, 4))) + self.assertIn("dropped", str(cm.exception)) + + def test_fields_helper(self): + printed = bytes.fromhex(dot4()) + self.assertEqual(rdna2spirv.dot4_op_sel_fields(bytes.fromhex(dot4(op_sel_hi=5)), printed, + "v_dot4_i32_i8"), (0, 5)) + self.assertIsNone(rdna2spirv.dot4_op_sel_fields(printed, printed, "v_dot4_i32_i8")) + self.assertIsNone(rdna2spirv.dot4_op_sel_fields(bytes.fromhex(dot4(op_sel_hi=5)), printed, + "v_dot2_i32_i16")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_ds_swizzle_b32.py b/tests/semantic/test_ds_swizzle_b32.py index 929e74acab..90767b6025 100644 --- a/tests/semantic/test_ds_swizzle_b32.py +++ b/tests/semantic/test_ds_swizzle_b32.py @@ -760,14 +760,15 @@ class EmulationAndParsingTests(unittest.TestCase): """Structural SPIR-V checks for `--wave64-emulate`; unparsed offsets raise Unsupported.""" def test_wave64_emulate_lowers_all_five_modes_via_x_buf_without_subgroup_ops(self): + # The last field is the 16-bit offset the swizzle() form assembles to, for the reference model. cases = [ - ("quad", "swizzle(QUAD_PERM,3,2,1,0)", r"%cfffffffc\b"), - ("bitmask", 'swizzle(BITMASK_PERM,"10p0i")', r"%cffffffe5\b"), - ("swap", "swizzle(SWAP,16)", r"OpBitwiseXor %uint %\w+ %c10\b"), - ("reverse", "swizzle(REVERSE,32)", r"OpBitwiseXor %uint %\w+ %c1f\b"), - ("broadcast", "swizzle(BROADCAST,16,5)", r"%cfffffff0\b"), + ("quad", "swizzle(QUAD_PERM,3,2,1,0)", r"%cfffffffc\b", 0x801B), + ("bitmask", 'swizzle(BITMASK_PERM,"10p0i")', r"%cffffffe5\b", 0x0605), + ("swap", "swizzle(SWAP,16)", r"OpBitwiseXor %uint %\w+ %c10\b", 0x401F), + ("reverse", "swizzle(REVERSE,32)", r"OpBitwiseXor %uint %\w+ %c1f\b", 0x7C1F), + ("broadcast", "swizzle(BROADCAST,16,5)", r"%cfffffff0\b", 0x00B0), ] - for label, mod_str, expected_pat in cases: + for label, mod_str, expected_pat, offset16 in cases: with self.subTest(mode=label): lines = [ "s_mov_b64 exec, -1", @@ -784,13 +785,16 @@ def test_wave64_emulate_lowers_all_five_modes_via_x_buf_without_subgroup_ops(sel self.assertIn("%x_buf = OpVariable", spv) self.assertGreaterEqual(spv.count("OpControlBarrier"), 2) self.assertRegex(spv, expected_pat) - # spirv_mini_interp.py deliberately rejects the Workgroup-memory round loop. - with self.assertRaises(si.UnsupportedConstruct): - si.run_workgroup( - spv, 64, 32, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i % 32}, - push_constants=VSHARP + [0] * 28, memory={}, - ) + # spirv_mini_interp.py runs the Workgroup-memory round loop since it models OpSwitch: the 64 lanes + # match the reference model. + mem = _Heap() + si.run_workgroup( + spv, 64, 32, + inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i % 32}, + push_constants=VSHARP + [0] * 28, memory=mem, + ) + want = ref_swizzle([100 + i for i in range(64)], [0] * 64, offset16, (1 << 64) - 1) + self.assertEqual([mem.get(4 * k) for k in range(64)], want) # Wave32 shaders are unaffected by WAVE64_EMULATE = True. w32_lines = [ diff --git a/tests/semantic/test_fspx_dot4_op_sel_disasm.py b/tests/semantic/test_fspx_dot4_op_sel_disasm.py new file mode 100644 index 0000000000..7ff52527f4 --- /dev/null +++ b/tests/semantic/test_fspx_dot4_op_sel_disasm.py @@ -0,0 +1,157 @@ +"""The FidelityFX upscaler's programs (docs/fspx.md) hold 89 v_dot4_i32_i8 words with op_sel 2 and op_sel_hi 5, which +llvm-mc does not decode: it rejects the first dword, reads the second as another instruction, and the translator then +refuses the program ("fall-through into undecodable words"), so 9 of the 29 programs had no pipeline and the DLL's +next pipeline call faulted. tools/shader_disasm.py now prints such a word as the instruction it is, with its +op_sel/op_sel_hi fields and its real encoding, so the translator reads it and checks it against the blob. + +Each case assembles a small program with llvm-mc, turns one v_dot4_i32_i8 into the op_sel 2 / op_sel_hi 5 form by +setting those fields in its two dwords, disassembles the bytes with shader_disasm, and translates the listing in the +FSPX layout (disasm/, fspx/.code and .json). The expected words are the ones measured on gfx1036 +(MEASURED_OP_SEL in test_alu_dot4_i8.py). They need llvm-mc with the AMDGPU target (LLVM_MC, or llvm-mc on PATH) and +skip without it. No GPU and no game files. + + python -I tests/semantic/test_fspx_dot4_op_sel_disasm.py +""" +import json +import os +import struct +import subprocess +import sys +import tempfile +import unittest +import warnings + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(os.path.dirname(HERE)) +sys.dont_write_bytecode = True +sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")) +sys.path.insert(0, HERE) + +import rdna2spirv # noqa: E402 +import shader_disasm # noqa: E402 +import spirv_mini_interp as si # noqa: E402 +from test_alu_dot4_i8 import MEASURED_OP_SEL, ref # noqa: E402 + +MCPU = "gfx1030" # fspx_unpack.py's default: LLVM decodes v_dot4_i32_i8 for it and not for gfx1013 +STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("> 2) << 14 + w1 = w1 & ~(3 << 27) | (op_sel_hi & 3) << 27 + return struct.pack("<2I", w0, w1) + + +def program(a, b, addend, middle): + """Code bytes of: v8 = the v_dot4_i32_i8 given by `middle` (its two dwords), v9 = the plain v_dot4_i32_i8 on the + same registers, both written to mrt0. Returns (code, byte offset of the first dot4).""" + head = b"".join(assemble(line) for line in ( + f"v_mov_b32_e32 v1, 0x{a:08x}", f"v_mov_b32_e32 v2, 0x{b:08x}", f"v_mov_b32_e32 v3, 0x{addend:08x}")) + tail = b"".join(assemble(line) for line in ( + "v_dot4_i32_i8 v9, v1, v2, v3", "exp mrt0 v8, v9, v8, v9 done vm", "s_endpgm")) + return head + middle + tail, len(head) + + +def translate_fspx(name, listing, code): + """SPIR-V assembly for a listing in the FSPX layout, with the code bytes it was disassembled from beside it.""" + with tempfile.TemporaryDirectory() as tmp: + for d in ("disasm", "fspx"): + os.mkdir(os.path.join(tmp, d)) + with open(os.path.join(tmp, name + ".dxbc"), "wb") as f: + f.write(STUB_DXBC) + with open(os.path.join(tmp, "fspx", name + ".code"), "wb") as f: + f.write(code) + with open(os.path.join(tmp, "fspx", name + ".json"), "w", encoding="utf-8") as f: + json.dump({}, f) + src = os.path.join(tmp, "disasm", name + ".s") + with open(src, "w", encoding="utf-8", newline="\n") as f: + f.write(listing) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ResourceWarning) + return rdna2spirv.translate(src) + + +def listing_of(name, code): + asm, bad, err = shader_disasm.disasm(code, MCPU) + return f"; {name} code 0x0..0x{len(code):x} (fspx), {MCPU}, {bad} invalid words\n" + asm, bad + + +@unittest.skipUnless(llvm_decodes_v_dot4(), "needs llvm-mc with the AMDGPU target that decodes v_dot4_i32_i8") +class Dot4OpSelListing(unittest.TestCase): + def plain_pair(self): + return assemble("v_dot4_i32_i8 v8, v1, v2, v3") + + def test_the_listing_carries_the_op_sel_word_and_the_program_runs(self): + for a, b, addend, measured in MEASURED_OP_SEL: + with self.subTest(a=f"{a:#010x}", b=f"{b:#010x}", addend=f"{addend:#010x}"): + middle = with_op_sel(self.plain_pair(), 2, 5) + code, at = program(a, b, addend, middle) + listing, bad = listing_of("ps_fspx_dot4_op_sel", code) + self.assertEqual(bad, 0, listing) + lines = [ln for ln in listing.splitlines() if "v_dot4_i32_i8" in ln] + self.assertEqual(len(lines), 2, listing) + self.assertIn("v_dot4_i32_i8 v8, v1, v2, v3 op_sel:[0,1,0] op_sel_hi:[1,0,1]", lines[0]) + self.assertIn("encoding: [" + ",".join(f"0x{x:02x}" for x in middle) + "]", lines[0]) + self.assertNotIn("op_sel", lines[1]) # the plain instruction next to it stays plain + words = support_words(translate_fspx("ps_fspx_dot4_op_sel", listing, code)) + self.assertEqual(words, [measured, ref(a, b, addend), measured, ref(a, b, addend)]) + + def test_other_op_sel_values_stay_undecodable(self): + # Only op_sel 2 / op_sel_hi 5 was measured on hardware; anything else is still rejected, never guessed. + for op_sel, op_sel_hi in ((1, 5), (4, 5), (2, 7), (0, 5), (2, 4)): + with self.subTest(op_sel=op_sel, op_sel_hi=op_sel_hi): + code, _ = program(1, 1, 0, with_op_sel(self.plain_pair(), op_sel, op_sel_hi)) + listing, bad = listing_of("ps_fspx_dot4_other", code) + self.assertNotIn("op_sel:[0,1,0] op_sel_hi:[1,0,1]", listing) + with self.assertRaises(rdna2spirv.Unsupported): # undecodable, or printed without a dropped field + translate_fspx("ps_fspx_dot4_other", listing, code) + + def test_a_clamp_or_neg_bit_on_the_word_stays_undecodable(self): + for name, shift, dword in (("clamp", 15, 0), ("neg_hi", 8, 0), ("neg_lo", 29, 1)): + with self.subTest(field=name): + middle = list(struct.unpack("<2I", with_op_sel(self.plain_pair(), 2, 5))) + middle[dword] |= 1 << shift + code, _ = program(1, 1, 0, struct.pack("<2I", *middle)) + listing, bad = listing_of("ps_fspx_dot4_mods", code) + self.assertGreaterEqual(bad, 1) + self.assertNotIn("op_sel:[0,1,0]", listing) + + def test_data_that_looks_like_the_word_is_left_alone(self): + # The same two dwords as a 32-bit literal and the instruction after it decode with no invalid word, so they + # are not touched: only a word llvm-mc rejected is read as v_dot4_i32_i8. + pair = struct.unpack("<2I", with_op_sel(self.plain_pair(), 2, 5)) + code = (assemble("v_mov_b32_e32 v4, 0x%08x" % pair[0]) + assemble("v_fmac_legacy_f32 v7, v1, v2") + + assemble("s_endpgm")) + self.assertEqual(struct.unpack_from("<2I", code, 4), pair) + listing, bad = listing_of("ps_fspx_dot4_literal", code) + self.assertEqual(bad, 0, listing) + self.assertNotIn("op_sel", listing) + + +def support_words(spv): + out = si.run_fragment(spv) + return list(out["%out_mrt0"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_global_mem_offset.py b/tests/semantic/test_global_mem_offset.py index eba6f34b75..6e9ba6ca18 100644 --- a/tests/semantic/test_global_mem_offset.py +++ b/tests/semantic/test_global_mem_offset.py @@ -131,6 +131,11 @@ def _step(self, w): value = self._value(args[0]) & MASK32 elif op == "OpShiftLeftLogical" and ty == "%ulong": value = (self._value(args[0]) << self._value(args[1])) & MASK64 + elif op == "OpShiftRightArithmetic" and ty == "%ulong": + operand = self._value(args[0]) + if operand >> 63: + operand -= 1 << 64 + value = (operand >> self._value(args[1])) & MASK64 elif op == "OpShiftLeftLogical" and ty == "%uint": value = (self._value(args[0]) << self._value(args[1])) & MASK32 elif op == "OpShiftRightLogical" and ty == "%uint": diff --git a/tests/semantic/test_image_cube_store_glc.py b/tests/semantic/test_image_cube_store_glc.py index e8bbca2202..0a1c7cf861 100644 --- a/tests/semantic/test_image_cube_store_glc.py +++ b/tests/semantic/test_image_cube_store_glc.py @@ -12,7 +12,6 @@ """ import os import re -import shlex import shutil import struct import subprocess @@ -20,6 +19,8 @@ import unittest import support + +import mc_command # noqa: E402 (support puts tools/ on sys.path) import rdna2spirv PS_EPILOGUE = ["exp mrt0 v0, v1, v2, v3 done vm", "s_endpgm"] @@ -50,9 +51,16 @@ def vdata_reg(dmask, d16=False): def llvm_mc_cmd(): + """llvm-mc's argv, or None when there is none. + + LLVM_MC is one executable path or a whole command line (`wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc` on + Windows, whose official LLVM build has no AMDGPU target). POSIX shlex.split eats the backslashes of a Windows + path (H:\\GTA6\\...\\llvm-mc.exe becomes H:GTA6...), so the split is the shared one in tools/mc_command.py that + the tools use: a value that is one existing file path stays one argv element, and a command line is still split. + """ env = os.environ.get("LLVM_MC") if env: - return shlex.split(env) + return mc_command.split_command(env) exe = shutil.which("llvm-mc") return [exe] if exe else None diff --git a/tests/semantic/test_lane_mask_bitreplicate_flbit.py b/tests/semantic/test_lane_mask_bitreplicate_flbit.py new file mode 100644 index 0000000000..ecc55775b2 --- /dev/null +++ b/tests/semantic/test_lane_mask_bitreplicate_flbit.py @@ -0,0 +1,97 @@ +"""s_bitreplicate_b64_b32 into VCC and s_flbit_i32_b64 of a lane mask, run on every lane of a wave64 in +spirv_mini_interp.run_workgroup. + +RDNA2 ISA, SOP1: + - s_bitreplicate_b64_b32: D[2i+1] = D[2i] = S0[i], i in 0..31; SCC is not written. Into VCC, lane L's bit is S0 bit + L // 2. + Of a 32-bit lane-mask source (exec_lo/exec_hi, vcc_lo/vcc_hi) into scalar data, S0 is that half of the wave's + mask, read as data (Gen.wave_mask), then replicated as any scalar. + - s_flbit_i32_b64: the zeros above the first 1 from bit 63, -1 when S0 is 0. Of EXEC that is 63 minus the wave's + last active lane. +Synthetic programs only. +""" +import unittest + +import saveexec_run as h +import support +import spirv_mini_interp as si + +OUT_AT = 256 + + +def run(lines): + spv = support.translate_lines("cs_lane_mask_bitreplicate_flbit", lines, fssm=h.fssm()) + return si.run_workgroup(spv, 64, 64, inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, + push_constants=h.VSHARP + [0] * 28, memory={}) + + +def lane_index(): + return ["v_mbcnt_lo_u32_b32 v1, -1, 0", "v_mbcnt_hi_u32_b32 v1, -1, v1", "v_lshlrev_b32_e32 v21, 2, v1"] + + +def flbit_model(mask): + return 63 - (mask.bit_length() - 1) if mask else 0xFFFFFFFF + + +class LaneMaskBitreplicateFlbit(unittest.TestCase): + def test_bitreplicate_into_vcc(self): + for k in (0x0F0F0F0F, 0xFF00FF00, 0, 0xFFFFFFFF, 0x80000001, 0x12345678): + with self.subTest(k=hex(k)): + mem = run(lane_index() + [f"s_bitreplicate_b64_b32 vcc, {k:#x}", "v_cndmask_b32_e64 v2, 0, 1, vcc", + "buffer_store_dword v2, v21, s[0:3], 0 offen", "s_endpgm"]) + got = [mem[4 * lane] for lane in range(64)] + self.assertEqual(got, [(k >> (lane // 2)) & 1 for lane in range(64)]) + + def test_flbit_of_exec(self): + for mask in (h.ALL64, 1, 0x8000000000000000, 0x00000000FFFFFFFF, 0x0000F00000000000, 0x10): + with self.subTest(exec=hex(mask)): + mem = run(lane_index() + [f"s_mov_b32 exec_lo, {mask & 0xFFFFFFFF:#x}", f"s_mov_b32 exec_hi, {mask >> 32:#x}", + "s_flbit_i32_b64 s10, exec", "s_mov_b64 exec, -1", + "v_cmpx_eq_u32_e32 0, v1", "v_mov_b32_e32 v20, s10", + f"v_mov_b32_e32 v21, {OUT_AT}", "buffer_store_dword v20, v21, s[0:3], 0 offen", + "s_endpgm"]) + self.assertEqual(mem[OUT_AT], flbit_model(mask)) + + def test_flbit_of_vcc(self): + # VCC from a compare: the lanes l with l < n. + for n in (0, 1, 31, 33, 64): + with self.subTest(n=n): + mem = run(lane_index() + [f"v_cmp_gt_u32_e32 vcc, {n}, v1", "s_flbit_i32_b64 s10, vcc", + "v_cmpx_eq_u32_e32 0, v1", "v_mov_b32_e32 v20, s10", + f"v_mov_b32_e32 v21, {OUT_AT}", "buffer_store_dword v20, v21, s[0:3], 0 offen", + "s_endpgm"]) + self.assertEqual(mem[OUT_AT], flbit_model((1 << n) - 1)) + + def bitreplicate_of(self, setup, src): + mem = run(lane_index() + setup + [f"s_bitreplicate_b64_b32 s[10:11], {src}", "s_mov_b64 exec, -1", + "v_cmpx_eq_u32_e32 0, v1", "v_mov_b32_e32 v20, s10", + "v_mov_b32_e32 v22, s11", f"v_mov_b32_e32 v21, {OUT_AT}", + "buffer_store_dword v20, v21, s[0:3], 0 offen", + "buffer_store_dword v22, v21, s[0:3], 0 offen offset:4", "s_endpgm"]) + return mem[OUT_AT] | mem[OUT_AT + 4] << 32 + + def test_bitreplicate_of_exec_half_into_data(self): + # Every lane that runs the instruction reads the same 32 mask bits; each becomes two bits of s[10:11]. + for mask in (h.ALL64, 0x00000000FFFFFFFF, 0xFFFFFFFF00000000, 0x8000000180000001, 0x0F0F0F0F12345678): + for half, src in ((0, "exec_lo"), (1, "exec_hi")): + with self.subTest(exec=hex(mask), src=src): + word = (mask >> (32 * half)) & 0xFFFFFFFF + got = self.bitreplicate_of([f"s_mov_b32 exec_lo, {mask & 0xFFFFFFFF:#x}", + f"s_mov_b32 exec_hi, {mask >> 32:#x}"], src) + self.assertEqual(got, bitreplicate_model(word)) + + def test_bitreplicate_of_a_compare_into_data(self): + # VCC from a compare: lanes l < n. Its low and high halves replicated as data. + for n in (0, 1, 17, 32, 45, 64): + for half, src in ((0, "vcc_lo"), (1, "vcc_hi")): + with self.subTest(n=n, src=src): + got = self.bitreplicate_of([f"v_cmp_gt_u32_e32 vcc, {n}, v1"], src) + self.assertEqual(got, bitreplicate_model((((1 << n) - 1) >> (32 * half)) & 0xFFFFFFFF)) + + +def bitreplicate_model(word): + return sum(3 << (2 * i) for i in range(32) if (word >> i) & 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_library_compute_forms.py b/tests/semantic/test_library_compute_forms.py new file mode 100644 index 0000000000..c9ecc4c5d5 --- /dev/null +++ b/tests/semantic/test_library_compute_forms.py @@ -0,0 +1,176 @@ +"""Hand-written pipeline-library cases. No game, GPU or LLVM installation needed.""" +import struct +import sys +import unittest +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +from test_fspx_rules import run_cs +from unittest.mock import patch +import support +from test_wave64_emulate_opt import run_emulated_workgroup +from test_fspx_wave_size import fssm_header, translate as translate_fspx +import spirv_mini_interp +import fspx_unpack +import rdna2_decode +import rdna2spirv +import shader_library + + +def fixture(name): + return [s for line in (HERE / "fixtures" / (name + ".asm")).read_text(encoding="utf-8").splitlines() + if (s := line.partition(";")[0].strip())] + + +def raw_words(lines): + return b"".join(struct.pack("> lane) & 1]) + + def test_wave64_scalar_mask_bits(self): + for subgroup_size in (32, 64): + with self.subTest(subgroup=subgroup_size), patch.object(rdna2spirv, "WAVE64_EMULATE", subgroup_size == 32): + spv = support.translate_lines("cs_scalar_mask_bits", fixture("wave64_scalar_mask_bits"), + fssm=fssm_header(False)) + pcs = [0, 0, 0xffffffff, 0x31016fac] + [0] * 32 + if subgroup_size == 32: + memory, _ = run_emulated_workgroup(spv, (64, 1, 1), push_constants=pcs) + else: + memory = {} + spirv_mini_interp.run_workgroup(spv, 64, 64, inputs_for=lambda i: { + "%local_id": (i, 0, 0), "%local_index": i, "%sg_lane": i, + "%wg_id": (0, 0, 0)}, push_constants=pcs, memory=memory) + for lane in range(64): + self.assertEqual([memory[lane * 16 + i * 4] for i in range(4)], + [0xffffffff, 54, 23, 2 + ((0x80000021 >> (lane // 2)) & 1)]) + + def test_vopc_dpp_encoded_fields_and_recovery(self): + # Hand-encode VOPC gt.f32 with v12 as src1, v7 as src0. Reverse the four/eight lanes. + msb = (0x3e << 25) | (4 << 17) | (12 << 9) + dpp8 = sum((7 - i) << (8 + 3 * i) for i in range(8)) + for tag, ext, control in ((250, 0xff080000 | (0x1b << 8), "quad_perm:[3,2,1,0]"), + (233, dpp8, "dpp8:[7,6,5,4,3,2,1,0]")): + blob = struct.pack("= 33), 7 if lane == 36 else 0]) + + def test_numeric_vcc_moves_in_buffer_tuple(self): + body = fixture("vcc_scalar_tuple_moves") + push = [0, 0, 0xffffffff, 0x31016fac] + [0] * 32 + seed = [0x12345678, 0x25ac87d2, 0xace750bd, 0xfedcba98] + for wave in (32, 64): + with self.subTest(wave=wave): + memory = {0x4000 + 4 * i: value for i, value in enumerate(seed)} + if wave == 32: + asm, _ = translate_fspx(body[:-1], wave32=True) + spirv_mini_interp.run_workgroup(asm, 32, 32, inputs_for=lambda lane: { + "%local_id": (lane, 0, 0), "%local_index": lane, "%sg_lane": lane, + "%wg_id": (0, 0, 0)}, push_constants=push, memory=memory) + else: + with patch.object(rdna2spirv, "WAVE64_EMULATE", True): + asm = support.translate_lines("cs_vcc_word_moves", body, fssm=fssm_header(False)) + memory, _ = run_emulated_workgroup(asm, (64, 1, 1), push_constants=push, memory=memory) + for lane in range(wave): + self.assertEqual([memory.get(16 * lane + 4 * j) for j in range(4)], + [seed[0], seed[1], seed[1] + 3, seed[3]]) + + def test_scalar_pointer_in_vcc(self): + body = fixture("smem_vcc_pointer") + words = {0x1004: 0x12345678, 0x1008: 0x89123456} + result = run_cs(body[:-1], words) + self.assertEqual([result.get(0x3000), result.get(0x3004)], list(words.values())) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_loop_iteration_guard.py b/tests/semantic/test_loop_iteration_guard.py new file mode 100644 index 0000000000..27193f19db --- /dev/null +++ b/tests/semantic/test_loop_iteration_guard.py @@ -0,0 +1,58 @@ +"""Per-lane readback for terminating and unreachable loop bounds.""" +from pathlib import Path +import unittest +from unittest.mock import patch + +from test_loop_ballot_barrier import _translate_cs, rdna2spirv +from spirv_mini_interp import run_workgroup + +FIXTURE = Path(__file__).with_name("fixtures") / "loop_iteration_guard.asm" + + +def module(lanes, limit, structured=True): + lines = [s for s in FIXTURE.read_text().splitlines() if s and not s.startswith(";")] + lines.insert(0, "s_mov_b64 exec, -1" if lanes == 64 else "s_mov_b32 exec_lo, -1") + with patch.object(rdna2spirv, "LOOP_LIMIT", limit): + text, gen = _translate_cs("cs_guard", lines, threads=lanes, emulate=lanes == 64, structured=structured) + assert gen.wave64 == (lanes == 64) and gen.emulate == (lanes == 64) + return text + + +def execute(text, lanes, bound): + mem = run_workgroup( + text, lanes, 32, + inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), + "%sg_lane": i % 32, "%local_index": i}, + push_constants=[0, 0, lanes * 4, 0x31016FAC, bound] + [0] * 27, memory={}) + return [mem[i * 4] for i in range(lanes)] + + +class LoopGuardTests(unittest.TestCase): + def test_finite_and_nonterminating(self): + for lanes in (32, 64): + with self.subTest(lanes=lanes): + plain, guarded = module(lanes, 0), module(lanes, 16) + self.assertNotIn("%loop_guard_", plain) + self.assertIn("%loop_guard_", guarded) + self.assertEqual(execute(plain, lanes, 6), [6] * lanes) + self.assertEqual(execute(guarded, lanes, 6), [6] * lanes) + self.assertEqual(execute(guarded, lanes, 1), [32] * lanes) + + def test_dispatch_loop_also_stops(self): + for lanes in (32, 64): + with self.subTest(lanes=lanes): + guarded = module(lanes, 16, structured=False) + self.assertEqual(execute(guarded, lanes, 6), [6] * lanes) + words = execute(guarded, lanes, 1) + self.assertTrue(all(0 < v <= 32 and v % 2 == 0 for v in words)) + + + def test_inner_budget_resets_on_each_entry(self): + lines = ["s_mov_b32 s8, 0", "s_mov_b32 s9, 0", "outer:", "s_mov_b32 s10, 0", + "inner:", "s_add_u32 s9, s9, 1", "s_add_u32 s10, s10, 1", "s_cmp_eq_u32 s10, 3", + "s_cbranch_scc0 inner", "s_add_u32 s8, s8, 1", "s_cmp_eq_u32 s8, 3", "s_cbranch_scc0 outer", + "v_mov_b32_e32 v1, s9", "v_lshlrev_b32_e32 v2, 2, v0", + "buffer_store_dword v1, v2, s[0:3], 0 offen", "s_endpgm"] + with patch.object(rdna2spirv, "LOOP_LIMIT", 3): + text, _ = _translate_cs("cs_guard_nested", lines, threads=32) + self.assertEqual(execute(text, 32, 0), [9] * 32) diff --git a/tests/semantic/test_salu_flbit_64.py b/tests/semantic/test_salu_flbit_64.py index faf480eb32..3ee0e42f52 100644 --- a/tests/semantic/test_salu_flbit_64.py +++ b/tests/semantic/test_salu_flbit_64.py @@ -123,9 +123,10 @@ def test_inline_source(self): self.assertEqual(run_lines(["s_flbit_i32_b64 s0, 1"])[0], 63) self.assertEqual(run_lines(["s_flbit_i32_i64 s0, -1"])[0], M32) - def test_lane_mask_source_is_rejected(self): + # b64 of a lane mask in wave64 reads the whole wave's mask: tests/semantic/test_lane_mask_bitreplicate_flbit.py. + def test_signed_lane_mask_source_is_rejected(self): with self.assertRaises(rdna2spirv.Unsupported): - run_lines(["s_flbit_i32_b64 s0, exec"]) + run_lines(["s_flbit_i32_i64 s0, exec"]) if __name__ == "__main__": diff --git a/tests/semantic/test_salu_quadmask_bitreplicate.py b/tests/semantic/test_salu_quadmask_bitreplicate.py index 9fa67cbbfb..3af4a0ab5b 100644 --- a/tests/semantic/test_salu_quadmask_bitreplicate.py +++ b/tests/semantic/test_salu_quadmask_bitreplicate.py @@ -155,6 +155,14 @@ def test_seeded(self): self.assertEqual(run([f"s_mov_b32 s2, {lo:#x}", "s_bitreplicate_b64_b32 s[10:11], s2"])[:2], (bitreplicate(lo) & M32, bitreplicate(lo) >> 32)) + def test_bitreplicate_into_vcc_in_wave32_is_refused(self): + # In wave32 VCC's high word is data, which a lane mask cannot carry; the wave64 form runs on every lane in + # tests/semantic/test_lane_mask_bitreplicate_flbit.py. + with self.assertRaises(rdna2spirv.Unsupported): + translate(["s_bitreplicate_b64_b32 vcc, 0x0f0f0f0f", + "v_cndmask_b32_e64 v0, 0x40000000, 0x40000001, vcc", + "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"]) + def test_lane_masks_rejected(self): for lines in (["v_cmp_gt_u32_e32 vcc, 5, v0", "s_quadmask_b64 s[10:11], vcc"], ["s_quadmask_b32 s10, exec_lo"], diff --git a/tests/semantic/test_scalar_mem_smem.py b/tests/semantic/test_scalar_mem_smem.py index 1ea98ba3e4..a6d31d97c6 100644 --- a/tests/semantic/test_scalar_mem_smem.py +++ b/tests/semantic/test_scalar_mem_smem.py @@ -478,6 +478,11 @@ def _step(self, words): value = self._value(args[0]) & MASK32 elif op == "OpShiftLeftLogical" and ty == "%ulong": value = (self._value(args[0]) << self._value(args[1])) & MASK64 + elif op == "OpShiftRightArithmetic" and ty == "%ulong": + operand = self._value(args[0]) + if operand >> 63: + operand -= 1 << 64 + value = (operand >> self._value(args[1])) & MASK64 elif op == "OpBitwiseOr" and ty == "%ulong": value = self._value(args[0]) | self._value(args[1]) elif op == "OpIAdd" and ty == "%ulong": diff --git a/tests/semantic/test_slot67_operand_forms.py b/tests/semantic/test_slot67_operand_forms.py new file mode 100644 index 0000000000..e54188c714 --- /dev/null +++ b/tests/semantic/test_slot67_operand_forms.py @@ -0,0 +1,47 @@ +"""Compute operand forms used by the pipeline library. Synthetic RDNA2 instructions only.""" +import unittest + +from test_carry_exec_mask import _run_cs + + +class Slot67OperandForms(unittest.TestCase): + def test_wave64_bitreplicate_exec_reenables_lanes_and_keeps_scc(self): + lines = [ + "s_cmp_eq_u32 1, 1", + "s_mov_b64 exec, 0", + "s_bitreplicate_b64_b32 exec, 0x80010001", + "s_cselect_b32 s8, 7, 9", + "v_mov_b32 v1, s8", + "v_lshlrev_b32 v2, 2, v0", + "buffer_store_dword v1, v2, s[0:3], 0 offen", + ] + expected = {i * 4: 7 for i in (0, 1, 32, 33, 62, 63)} + self.assertEqual(_run_cs("cs_bitreplicate_exec", lines), expected) + + # The merge into main kept main's wave32 VCC_HI model (47494e725: VCC_HI that holds a compare result is a + # per-lane mask), not this branch's packed-word form (1f001c739). On hardware `s_mov_b32 s8, vcc_hi` copies the + # packed 32-bit word (0x80000004 here); main's translator gives each lane its own mask value instead, so this + # case fails there. Kept as the expectation the translator should meet. + @unittest.expectedFailure + def test_wave32_compare_high_word_preserves_low_and_clears_inactive_bits(self): + lines = [ + "v_cmp_lt_u32_e64 vcc_lo, v0, 6", + "s_mov_b32 exec_lo, 0x80000005", + "v_cmp_ne_u32_e64 vcc_hi, 0, v0", + "s_mov_b32 exec_lo, -1", + "s_mov_b32 s8, vcc_hi", + "v_mov_b32 v1, s8", + "v_cndmask_b32_e64 v2, 0, 1, vcc_hi", + "v_cndmask_b32_e64 v3, 0, 1, vcc_lo", + "v_lshlrev_b32 v4, 4, v0", + "buffer_store_dword v1, v4, s[0:3], 0 offen", + "buffer_store_dword v2, v4, s[0:3], 0 offen offset:4", + "buffer_store_dword v3, v4, s[0:3], 0 offen offset:8", + ] + expected = {i * 16 + offset: value for i in range(32) + for offset, value in ((0, 0x80000004), (4, int(i in (2, 31))), (8, int(i < 6)))} + self.assertEqual(_run_cs("cs_cmp_vcc_hi", lines, wave_size=32), expected) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_valu_mul_legacy_denorm.py b/tests/semantic/test_valu_mul_legacy_denorm.py index 304880ebb9..47bcc1683a 100644 --- a/tests/semantic/test_valu_mul_legacy_denorm.py +++ b/tests/semantic/test_valu_mul_legacy_denorm.py @@ -38,6 +38,8 @@ def test_inputs_flush_before_legacy_zero_override(self): # give +0 under the legacy DX9 zero-times-anything rule. for src0, src1 in [ (0x00000001, 0x4B800000), + (0x7F800000, 0x807FFFFF), + (0xFF800000, 0x007FFFFF), (0x80000001, 0x4B800000), (0x00000001, 0x7F800000), (0x80000001, 0xFFC00000), diff --git a/tests/semantic/test_valu_permlane16.py b/tests/semantic/test_valu_permlane16.py index 413635ce70..f317a63bc6 100644 --- a/tests/semantic/test_valu_permlane16.py +++ b/tests/semantic/test_valu_permlane16.py @@ -685,13 +685,16 @@ def test_wave64_emulate_lowers_permlane_through_x_buf_without_subgroup_ops(self) self.assertRegex(spv, r"OpBitFieldUExtract %uint %\w+ %\w+ %c4\b") self.assertIn("OpBitwiseAnd %uint %", spv) self.assertIn("%cfffffff0", spv) - # spirv_mini_interp.py deliberately rejects the emulated Workgroup/loop scheduler. - with self.assertRaises(si.UnsupportedConstruct): - si.run_workgroup( - spv, 64, 32, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i % 32}, - push_constants=VSHARP + [0] * 28, memory={}, - ) + # spirv_mini_interp.py runs the emulated Workgroup/loop scheduler since it models OpSwitch: the 64 lanes + # match the reference model. + mem = _Heap() + si.run_workgroup( + spv, 64, 32, + inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i % 32}, + push_constants=VSHARP + [0] * 28, memory=mem, + ) + want = ref_permlane(spv is spv_x16, [100 + i for i in range(64)], [0] * 64, ID_S1, ID_S2, (1 << 64) - 1) + self.assertEqual([mem.get(4 * k) for k in range(64)], want) # v_permlanex16_b32 XORs the masked half base with 16 (%c10); v_permlane16_b32 does not. xor16_pat = r"OpBitwiseAnd %uint %\w+ %cfffffff0\n\s*%\w+ = OpBitwiseXor %uint %\w+ %c10\b" diff --git a/tests/semantic/test_vcc_tuple_fallback.py b/tests/semantic/test_vcc_tuple_fallback.py new file mode 100644 index 0000000000..3aa66c9def --- /dev/null +++ b/tests/semantic/test_vcc_tuple_fallback.py @@ -0,0 +1,410 @@ +"""A scalar tuple that runs into vcc is translated from the blob when llvm-mc cannot decode it. + +llvm-mc rejects s_buffer_load_dwordx8 into s[100:107], a buffer resource in s[104:107] and an image resource in +s[100:107] (SGPRs 106 and 107 are vcc). It skips the first word as invalid and leaves the second word as junk, so +translate() refused every such shader ("reachable instruction with normalized encoding", or "fall-through into +undecodable words"; docs/shader_library.md section 5), or, when the junk matched the blob, translated a program +with the load missing. The words are now decoded from the blob as the VCCTuple lists the translator takes. + +Hand-built listings and blobs of synthetic instructions (encodings from llvm-mc 19, the three tuple words patched in +their register field), no game data. + + python -I tests/semantic/test_vcc_tuple_fallback.py -v +""" +import os +import struct +import sys +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +if HERE not in sys.path: + sys.path.insert(0, HERE) + +from support import rdna2spirv, translate_listing # noqa: E402 +import fssm_header # noqa: E402 +import spirv_mini_interp as si # noqa: E402 + +NAME = "cs_vcc_tuple" +CODE_START = 0x148 +BASE, OUT = 0x1000, 0x3000 +INVALID = "; warning: invalid instruction encoding" + +SET_SGPR_V = [ # s4..s7 = a V# over BASE (32 bytes), as tests/semantic/test_fspx_rules.py builds it + ("s_mov_b32 s4, 0x1000", "ff 03 84 be 00 10 00 00"), + ("s_mov_b32 s5, 0", "80 03 85 be"), + ("s_mov_b32 s6, 32", "a0 03 86 be"), + ("s_mov_b32 s7, 0x30000000", "ff 03 87 be 00 00 00 30"), +] +WAIT = ("s_waitcnt lgkmcnt(0)", "7f c0 8c bf") +WAIT_V = ("s_waitcnt vmcnt(0)", "70 3f 8c bf") +STORE_X4 = [ + ("v_mov_b32_e32 v6, 0x3000", "ff 02 0c 7e 00 30 00 00"), + ("global_store_dwordx4 v6, v[10:13], s[0:1]", "00 80 78 dc 06 0a 00 00"), + ("s_endpgm", "00 00 81 bf"), +] +# the words llvm-mc cannot decode (each is two dwords): the llvm-mc 19 encoding of the same instruction one tuple +# lower, with its register field patched into vcc +LOAD_X8_VCC = "02 19 2c f4 00 00 00 fa" # s_buffer_load_dwordx8 [s100..s105,vcc_lo,vcc_hi], s[4:7], 0x0 +LOAD_X4_VCC = "02 1a 28 f4 00 00 00 fa" # s_buffer_load_dwordx4 [s104,s105,vcc_lo,vcc_hi], s[4:7], 0x0 +LOAD_DW_FROM_VCC = "b4 02 20 f4 00 00 00 fa" # s_buffer_load_dword s10, [s104,s105,vcc_lo,vcc_hi], 0x0 +BUFFER_LOAD_VCC = "00 10 30 e0 01 0b 1a 80" # buffer_load_dword v11, v1, [s104,s105,vcc_lo,vcc_hi], 0 offen +IMAGE_LOAD_VCC = "08 1f 00 f0 01 04 19 00" # image_load v[4:7], v[1:2], [s100..s105,vcc_lo,vcc_hi] 2D unorm +PROGRAM_VARIANTS = ("invalid", "junk", "normalized") + + +def encoding(raw): + return "; encoding: [" + ",".join(f"0x{b:02x}" for b in bytes.fromhex(raw)) + "]" + + +def listing_and_blob(program, variant="invalid"): + """program: (text, hex) pairs; a pair whose text is None is a word llvm-mc rejects, listed as the variant says.""" + code = b"".join(bytes.fromhex(raw) for _, raw in program) + lines = [] + for text, raw in program: + if text is not None: + lines.append(f"\t{text:<40}{encoding(raw)}") + continue + raw_bytes = bytes.fromhex(raw) + lines.append(INVALID) + if len(raw_bytes) == 4: + continue + second = raw_bytes[4:8] + if variant == "invalid": + lines.append(INVALID) + elif variant == "junk": # the second word decodes as an instruction of its own, bytes as stored + lines.append(f"\ts_nop 0{'':<33}" + encoding(second.hex())) + else: # printed with another encoding than the blob holds + lines.append("\texp mrt0 v0, v0, v0, v0 done vm " + encoding("0f 18 00 f8 00 00 00 00")) + head = f"; {NAME} code 0x{CODE_START:x}..0x{CODE_START + len(code):x} (scan), gfx1013, 2 invalid words" + header = bytearray(CODE_START) + struct.pack_into("<4I", header, 0x138, 0x88, 32, 1, 1) + struct.pack_into("