diff --git a/docs/README.md b/docs/README.md index 8db9cc0801..3aec00ea91 100644 --- a/docs/README.md +++ b/docs/README.md @@ -13,6 +13,7 @@ method, scope and caveats. No game data is included. | [boot_leads.md](boot_leads.md) | Open leads that may move the retail boot further (TLS at module index 0, feature level at device creation, command-list replay, descriptor words, shader corpus count, frame pacing), each with where it lands, how to implement it and how to test it. Hypotheses, not measurements. | | [rpf.md](rpf.md) | RPF9 archive layout, the carve tools and the unreadable encrypted TOC. | | [linux.md](linux.md) | Linux in one page: what runs natively and what runs under Wine or Proton, the Ubuntu packages, `Build.sh`, the runtime cross-build, and why there is no native Linux `gta6rt`. | +| [running.md](running.md) | Running the game per platform and GPU (Linux/Wine with AMD, Linux/Proton and Windows with NVIDIA, Windows with AMD, Intel, macOS): build, shaders, pipeline pre-compile, driver settings, environment, what to expect; each value measured by us, reported by others (linked) or TBD. | | [testing.md](testing.md) | Running the GPU tests on your own GPU: setup per OS, wave64 emulation, running without a GPU on Mesa llvmpipe, and known problems. | | [gpu_test_results.md](gpu_test_results.md) | Published GPU test results by hardware, driver and commit, with pass, skip and failure counts. | | [modding.md](modding.md) | The mod format: `mods//mod.json`, checked and loaded in name order by `gta6rt`; a swap takes effect once the game's archetype lookup is hooked (needs the executable, RT-5). A mod names game models and holds no game data. | diff --git a/docs/audio_hal_exe_calls.md b/docs/audio_hal_exe_calls.md index c04943c7d5..a500e16fc3 100644 --- a/docs/audio_hal_exe_calls.md +++ b/docs/audio_hal_exe_calls.md @@ -52,6 +52,26 @@ turns such an address back into a pointer. That is an inference from the shapes; `XApuEnqueueCommand` and `XApuDequeueResult` share one handle global, which `XApuDisconnect` clears: a command queue with a result queue, connected once and torn down once. How `chad.dll`'s handle relates to it is not read. +`runtime/shims/xapu_queue.cpp` serves the five `xapu.dll` imports and `runtime/shims/xapu_chad.cpp` the five +`chad.dll` ones. +The `xapu.dll` signatures, structure layouts, command kinds, option bits and error codes come from Marvisak/VIctory +(, GPL-3.0-or-later, `crates/victory-hle/src/modules/apu.rs` at commit `ffe310e`), +which runs the retail executable through these calls. Only the facts are used (see +[related_projects.md](related_projects.md)); the top of `xapu_queue.cpp` lists them. They agree with the shapes above: + +| Shape measured here | What the layout says | +|---|---| +| `XApuConnect`: a 24-byte title global first, a 16-byte output second | the global is an input of six dwords (processing kind, streams, commands per stream, memory bytes, frames per output, options); the output is the zeroed memory and a result event | +| `XApuEnqueueCommand`: a stack-built command whose first dword is 1, 2 or 3 and second a stream slot, then 0 | a 24-byte command id (kind, stream, sequence, options, context): 1 activates, 2 deactivates, 3 processes an Opus packet; the third argument is an optional count of the commands accepted | +| `XApuDequeueResult`: a 0x50-byte result, read at +0, +4 and +0x34 | the command id at +0, the output byte count at +0x34; `0x8AC81001` while none is ready | +| `XApuDisconnect`: the handle, then `0x20` | the second argument is not read | + +What the results carry is the shim's own: each accepted command gets one result in command order, with the error codes +of the layout. A process result carries the frame count and PCM when `runtime/opus_decoder` is built, and otherwise the +frame count of the Opus packet's table-of-contents byte (RFC 6716, section 3.1) with zeros in its output (silence). +`xapu_chad_test` covers the layouts and the silent path; `xapu_opus_test` covers the decoded path with a generated +packet. + ## `xg_xs.dll` and `XCRDAPI.dll` | Import | Sites | What the sites show | diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 35dbd0f620..98cf32aad2 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -961,7 +961,8 @@ The compute path, end to end: primitive overestimation no greater than `0.5 - 1/512` pixels, leaving half a minimum grid step within the Tier 1 uncertainty bound. `ConservativeRaster=ON` uses overestimate mode with zero extra overestimation, including unbound-attachment variants. OFF keeps the ordinary pipeline. Missing support, unknown modes, - wireframe and non-triangle PSOs are refused; conservative TIR (`ForcedSampleCount != 0`) remains `E_NOTIMPL`. + wireframe and non-triangle PSOs are refused (a mesh PSO needs no topology type: its module has to output + triangles, `conservative_raster::mesh_outputs_triangles`); conservative TIR (`ForcedSampleCount != 0`) remains `E_NOTIMPL`. Tier 2 additionally requires `degenerateTrianglesRasterized` and primitive overestimation plus half a device subpixel step no greater than 1/256 pixel. Other eligible devices retain Tier 1. The standalone device does not expose Tier 3: the Xbox `SV_InnerCoverage` input mapping has not been confirmed. See @@ -1697,6 +1698,18 @@ The copies: 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. +- **What the GPU wrote goes back.** The same return copy serves slot-133 shadows (a buffer the driver would not + import, a compute result the title reads again): the ranges are recorded through the alias of the buffer's pages and + the tracker there carries them back. `d3d12_placed_write_back` covers it. A copy is a read-side mirror, so a UAV or a raw write into a window would land in + the copy and the title would never see it ([#1537](https://github.com/ubiquitarianism/leonida/issues/1537), the + `WRITE_INVALID` stop at the world start). Every title range a submission's bindings reach is kept, and the next + refresh copies those ranges from the copy to the title's pages *before* it copies the pages forward, so a page the + title itself wrote in between keeps the title's newer bytes and its GPU result is dropped. Up to 8,192 ranges and + 64 MiB a submission (a V# has no read/write bit, so a read-only view costs a copy too; past the caps the ranges are + left behind, logged once). `LEONIDA_TITLE_WRITEBACK=0` turns it off. A batch is fenced: it is kept with the ticket + of the submission that will use it and copied back only when the context reports that ticket retired, so a range + another submission is still writing is never read half done. A queue held deep (console ordering) can leave batches + waiting: past 64 of them the oldest go back without their ticket, logged once. - A **window that is refused** (the budget is spent, the arena is full, or the pages are not committed yet) is backed by a persistent geometry copy of exactly the requested range (`LEONIDA_GEOMETRY_MB`) instead; when no copy can be made either, the view is written with **no base and no records** — loads return 0 and stores are dropped. A raw @@ -1719,6 +1732,22 @@ The copies: 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. + - **Where the copies live**: device-local memory through the BAR by default. `LEONIDA_GEOMETRY_HOST=1` puts them + in system memory outside VRAM (write-back where the device offers a cached host type, `=2` write-combined), + as VIctory keeps its copies of title memory (approach only). In a world run on the RX 7900 XTX the copies held + 4.4-6 GB of VRAM. The cost moves to the bus: the GPU reads every vertex and index of a copy from system memory, + so a geometry-heavy pass can take longer; measure frame time with and without it before making it a default. + - **When a copy goes**: a view is retired when its title range is freed, decommitted or unmapped, and also when a + remap gives one of its pages another frame or none (`XMemMapPhysicalPages` with pages, the scatter call, + `CopyPageMappingsBatchX`; xmem's `RemapReleases`, `LEONIDA_GEOMETRY_REMAP_RELEASE=0` turns it off): the title + streams by remapping its pools' frames, and before this the copies of what those pages held stayed for the + device's life (`evicted 0` in every world run). A page mapped again to the frame it had is no change. A retired + view leaves the lookups at once, its alias ranges and translated heap slots are invalidated, its stream-pool + extent is forgotten, and its memory is freed only after every ExecuteCommandLists replay in progress at the + retirement has recorded its submissions and those have completed (`kAfterExecutes`). Before it leaves the + refresh it is copied once more from its pages if they are readable: a list recorded before a remap that took the + view's address (a root view) reads the new bytes, as on the console. The next view of the range makes a new copy. + `geometry_views_test` cases 14-16 and `xmem_test` (`test_remap_releases`) cover this without a GPU. - **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: @@ -1805,6 +1834,178 @@ fit on smaller PC GPUs. This is a product requirement, not something the layer c compatible single-mip RGBA8 2D textures (section 4.2). Other descriptions have fully allocated backing. Wider texture coverage and the game's use of tile streaming remain open. +**Diagnostics for descriptors the title builds itself** (all off by default, logging only unless said otherwise): + +- `LEONIDA_UNKNOWN_TSHARP=1`: one line for each distinct base address a title-written T# names with no texture there + (its shape, the tiling bits and whether the address is title memory), up to 300 addresses, and every 8192 such + lookups a summary by format, type and tiling. +- `LEONIDA_UNBACKED_VSHARP=1`: the buffer V#s `fix_vsharp` writes empty because nothing backs their base; one line for + each of the first 120 distinct bases and every 8192 a summary by 4 GiB range of the base. +- `LEONIDA_UPLOAD_LOG=1` (`d3d12_xs_device.cpp`): each upload chunk (CPU base, device address, size) and the first 96, + then every 8192nd, `AllocateUploadMemory` result as an offset into its chunk. +- `LEONIDA_UPLOAD_ALIAS=1` (an experiment, changes behaviour): enters each upload chunk's CPU range in the title VA + table, so a V# the title wrote with the CPU pointer `AllocateUploadMemory` handed it is rewritten to the chunk + instead of left empty. A chunk below the arena needs `LEONIDA_IMPORT_BELOW_ARENA=1` as well. + +#### Address guard (`LEONIDA_ADDRESS_GUARD=1`, `rdna2spirv.py --address-guard`) + +**Prototype, off by default.** + +**Why.** The layer rewrites the addresses it can see: root views, the V#s it writes, and the V#s the title writes into +shader-visible heaps. It writes an empty V# when nothing backs an address (above). The translator checks a V#'s +record count but not its base. Any other address becomes `heap_base` plus an arbitrary value: +- a V# a shader builds in SGPRs from data; +- a raw `global_`/`flat_` address (530 of the 26,503 shaders of package 1.0.2.1, 69 of the 2,684 pipeline-library + programs); +- a stale or offset-like value. + +On RADV such an access page-faults. Two RX 7900 XTX runs (Mesa 26.3.1, under Wine) ended with the same sequence: +- a `gfxhub` fault from client TCP with PERMISSION_FAULTS 0x3; +- a compute-ring timeout and "MES failed to respond"; +- a MODE1 reset ("VRAM is lost"). + +Both faults were 4.8 GiB and 20 GiB above `heap_base`, past the arena's end. + +"Inside the arena" is not the right bound. Several buffers are legitimately outside it, at a positive offset from +`heap_base` (a negative one with `LEONIDA_IMPORT_BELOW_ARENA=1`): +- geometry copies; +- upload and readback buffers; +- imported title memory; +- separate window buffers. + +The guard checks each access against what the runtime actually backs. An access that fails reads 0 and drops its +store, so a wild address never reaches the GPU. The overall process follows VIctory +([`crates/victory-gpu/src/memory.rs`](https://github.com/marvisak/victory), GPL-3.0). Its page table of 64 KiB pages +routes every computed address, and memory no copy holds reads 0 and takes no writes. The structure below is our own: +VIctory's table names descriptor views, this one is a bitmap over device addresses. + +**Structure: a two-level page table of 4 KiB pages over the 48-bit offset space, behind an arena compare.** The +check works on the heap offset, the sign-extended 48-bit value `Gen.host_addr` adds to `heap_base`: +- **Level 1:** 65,536 words indexed by offset bits 47..32. Each word names the level-2 block of one 4 GiB chunk. +- **Level 2:** blocks of 32,768 words, one bit per 4 KiB page (bits 31..12). +- **Two fixed blocks:** block 0 is empty and block 1 is full; allocated blocks start at 2. +- **Size:** the table is a host-visible buffer of its own, 256 KiB plus 128 KiB per block (8.25 MiB for 62 blocks). + +Why this structure: +- **Pages of 4 KiB** are the GPU's own mapping granularity. A page any byte of a backing touches is mapped as a whole, + so marking pages outward is exact for faults. A 64 KiB page would mark memory that may not be mapped. +- **Level 1 by 4 GiB chunk** covers the whole signed 48-bit space (negative offsets index from 0x8000 up). A real run + touches a handful of chunks, so the table stays small. +- **Other structures cost more per access.** A sorted range table needs a binary search: about 10 dependent loads for + a thousand backings, against 2 here. A coarse region bitmap plus a fine range table needs a search in the fine part. +- **The arena needs no lookup.** It is one fully bound `VkBuffer`, so any offset below its size passes on a compare. + That is the common case: descriptor heaps, default-heap buffers and windows in the arena. + +**The header.** It sits at arena offset `0x70000`, after the zero page and the quad indices, and holds: +- a 64-bit magic (`"LGUARD01"`); +- the arena's size (the compare's limit); +- the table's address minus `heap_base`; +- a refusal count and the last refused offset, which the shaders write. + +Two sinks follow the header: `0x71000` (zero area, what refused loads read) and `0x78000` (dump area, where refused +stores and atomics go). None of `[0x70000, 0x80000)` is handed out. With `LEONIDA_ARENA_NULL_MB` the range lies in the +null region, so its offset never moves. `runtime/src/address_guard.h` and `tools/address_guard.py` (the Python +reference) hold the format. + +**Each access.** `Gen.host_addr` takes the access kind (load, store or atomic) and its span. Under `--address-guard` +it calls one function per module, `%guard_fn`, which is straight-line at the call site, so no caller's block +structure changes. The function computes `end = offset + span - 1` and then decides: +- **Passes on a compare:** the runtime's guard is off (no magic), or `offset` and `end` are both below the limit. The + result is `heap_base + offset`. The cost is a 64-bit add, two 64-bit compares and a select. +- **Otherwise, a lookup:** the bits of the pages of `offset` and of `end`. That is two independent pairs of dependent + 32-bit loads (level 1, then level 2). +- **Refused:** an access whose bits are not both set adds 1 to the header's count, writes its offset, and goes to the + zero area (a load) or the dump area (a store or atomic), at its offset within its page. Alignment is kept, and every + span fits inside a sink. +- **Atomics** run on the dump area, and their returned value is replaced by 0 (`Gen.guard_zero`). The CAS loops (float + min/max, inc/dec) end there too, as on any other memory. + +The entry block reads the header's first six dwords once per invocation, from the arena, so that read is always +backed. When the base is uniform, as for `s_load`, `s_buffer_load` and a V# from SGPRs plus a uniform offset, the +compiler keeps the whole check scalar: one check per instruction, not per lane. A per-lane address (`global_` with a +VGPR address, `offen`/`idxen`) is checked per lane, and the slow path runs only for lanes outside the arena. + +**What is checked.** Every `heap_base` access goes through `host_addr`: +- buffer loads and stores (dword, sub-dword, typed, format; swizzled spans are computed at run time); +- `global_` loads, stores, sub-dword and atomics; +- buffer atomics, `_x2` included; +- `s_load` and `s_buffer_load`; +- the BVH node reads of `image_bvh*_intersect_ray` (span by node type). + +These are not checked: +- images (T#s go through the hash table, not an address); +- LDS; +- the `--mesh-compute` output buffer (a runtime address); +- `s_getpc` code reads. + +The translator does not translate `flat_` instructions (they raise `Unsupported`), so none reaches memory today. A +translation added later must go through `host_addr` like `global_` does. + +**Keeping the table current.** The spans are the same backings the console heap pass's backed table uses +(`update_gpu_backed`): +- every `gpu_backings` entry outside the arena (upload and readback buffers, imports, slot-133 buffers, windows + outside the arena); +- the geometry copies' blocks; +- the separate window buffers' blocks. + +`update_address_guard` runs in the queue's `before_execute`, after the heap refresh, the windows and the geometry +copies. It differs from that table in four ways: +- It rebuilds whenever `backing_generation` or a block layout changed, with no 100 ms limit, because a backing made + since the last submission must not read 0. +- It writes only the words that changed, level 2 before level 1. +- A chunk keeps its block for good, so a submission still in flight never reads a block that now means another chunk. +- When the 62 blocks run out, a new chunk gets the full block (unchecked, as without the guard), and that is logged. + +A release clears its bits at the next submission. D3D12 forbids releasing memory the GPU still uses, so only a wild +access in flight at that moment could still pass. + +**Cost per access:** +- **Fast path:** about 8 scalar or vector ALU operations. +- **Outside the arena:** about 40 operations and 4 loads, from a table small enough to stay in cache. +- **Per invocation:** 6 uniform header loads. +- **Per submission (runtime):** nothing until a backing changes, then a rebuild of the used blocks (128 KiB each) + and a diff. + +**Switches.** +- `--address-guard` records `"address_guard": true` in `index.json`. +- `LEONIDA_ADDRESS_GUARD=1` makes the runtime reserve the range, create the table and write the header. +- Either alone does nothing: a guarded module on a runtime without the guard finds no magic, and every access passes + after one compare. +- Without the flag the module is byte for byte what it was. + +**What a run with the guard shows.** +- One line when the device is made: `[rt] d3d12: address guard on ...`. +- At most one line a second: `[rt] d3d12: address guard: N access(es) refused so far (+k), the last at heap offset + 0x...`. Each refusal is a wild access that would have reached the GPU. The offset says where to look (above the + arena's end, as in the two faults). +- A run that reset the GPU before should keep going, with wrong pixels where a refused access mattered. + +**Risks and open points.** +- A refused access that mattered (a backing the layer never registered) now reads 0 instead of faulting. That is + silent apart from the count. +- An access is checked as a whole. A multi-dword load whose first dwords are inside a V# and a backing, but whose + last dword is past both on an unbacked page, reads 0 in full. +- The table is read through the GPU's caches. A page whose bit changes while a submission is in flight can be seen + either way by that submission. +- Sparse buffers outside the arena are guarded only if they are registered as backings. + +**Checked:** +- `tests/semantic/test_address_guard.py`: the fixture `cs_address_guard` with the guard on, with it off at run time + and without the flag, through `spirv_mini_interp`; the kind and span of each instruction family; the table model; + the constants shared by the translator, the runtime and `tools/address_guard.py`. +- `runtime/test/address_guard_test.cpp`: the page table, incremental writes, negative offsets, wrap, chunks and + overflow. +- `scripts/run_address_guard_gpu_test.py`: the fixture on a 2 MiB heap whose table backs one page outside the + "arena". Every address it touches is inside the buffer, so no run can fault. With the guard on, the refused loads + read 0 although memory is there, the store and the atomic land in the dump area and the count is 6. With the guard + off, the same module reads that memory. It passed on lavapipe (Mesa 26.3.1). +- Corpus (package 1.0.2.1, 2026-11-26): + - `--shard 0/8` of the shaders: 3,313 translated and 3,313 `spirv-val`-valid, with the guard and without. + - The pipeline library: 2,683 of 2,684 translated and valid, with the guard and without (the same one fails + either way). + - Without the flag, every module is byte for byte the same as before the change. + - With it, the SPIR-V grows by 1.8% (shaders) and 1.6% (library). + ### 3.4 Descriptor heaps and the bindless model The game can use D3D12 descriptors in three ways, and the layer must handle all of them: @@ -2415,6 +2616,24 @@ Pipeline creation: Replacing part of the previous file would corrupt it. `LEONIDA_PIPELINE_CACHE_BYTES` caps what a session adds, at a checkpoint or at teardown (an offline `pipeline_cache.bin` seed, which the driver hands back as part of the union, is not counted; 4 GiB by default, zero disables the session file). + The session file can't keep a crashed run's compiles: it is written at teardown and at the optional checkpoints + below only. The heavy pipeline cache (RT-HEAVY-PIPELINE-CACHE, `runtime/src/heavy_pipeline_cache.h`) keeps the graphics ones; compute pipelines go to the per-pipeline journal + described below. Every graphics build first asks the corpus cache with + `VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT`. A pipeline the corpus doesn't have is built against a + second cache, seeded from `pipeline_cache.heavy.bin` next to `pipeline_cache.bin`, so that cache holds only the + corpus's misses. + A build that takes at least `LEONIDA_HEAVY_PIPELINE_CACHE_MS` (500 by default) marks the heavy cache for writing. + A thread of its own writes it whole: 3 s after the newest slow build, and no later than 20 s after the first unwritten + one, through the same staging file and rename as the session cache. A crash therefore loses at most the last 20 s + of slow builds, and the next launch starts with the rest. A write that fails, or whose + `vkGetPipelineCacheData` returns anything but `VK_SUCCESS` (`VK_INCOMPLETE` means the cache grew after the size + query, so the blob is truncated), leaves the previous file in place and the cache dirty: it is tried again 5 s + later, the delay doubling with each failure in a row up to 2 min, so the cache is not left unsaved until teardown + and a write that keeps failing does not spin. At device teardown the thread stops, and the cache is + written if any build went into it. Fast builds are kept that way: without an offline seed every build is a miss, + so they no longer reach `pipeline_cache.session.bin`. `LEONIDA_HEAVY_PIPELINE_CACHE_MS=0` turns the heavy cache off, and with it the + `pipelineCreationCacheControl` feature unless `LEONIDA_PIPELINE_COMPILE=cache-only` asks for it. A cache-only create + (`cache-only`) is left as it is. `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. diff --git a/docs/design.md b/docs/design.md index eee5be2cc4..656418c99a 100644 --- a/docs/design.md +++ b/docs/design.md @@ -372,6 +372,7 @@ How the generated SPIR-V expects the runtime to work: | Integer clamp | The VOP3 `clamp` bit on `v_add_nc_u32`, `v_sub_nc_u32`, `v_subrev_nc_u32` saturates the result to [0, 0xFFFFFFFF], and on `v_add_nc_i32`/`v_sub_nc_i32` to [0x80000000, 0x7FFFFFFF]; without it they wrap. GFX9+ semantics: LLVM selects `uaddsat`/`usubsat` and `saddsat`/`ssubsat` to exactly these ops with clamp set. **Until this change clamp was silently ignored on the unsigned ops** (and the signed ones were `Unsupported`). Checked on the CPU by `tests/semantic/test_alu_add_nc_clamp.py`. The carry-out unsigned ops (`v_add_co_u32`, `v_sub_co_u32`, `v_subrev_co_u32`, `v_add_co_ci_u32`, `v_sub_co_ci_u32`, `v_subrev_co_ci_u32`) with VOP3 `clamp` likewise saturate D to `0xFFFFFFFF` on add carry or `0` on sub borrow while still reporting the real carry/borrow bit in `sdst` (**until 2026-11-22 the translator ignored `clamp` on all six**); confirmed natively on RDNA2 (AMD Radeon 680M `gfx1035` wave32 & wave64 via `tools/hw_oracle`, and independently on `gfx1036` in #1746) and CPU-checked by `tests/semantic/test_alu_add_co_clamp.py`. The 16-bit unsigned add/sub (`v_add_nc_u16`, `v_sub_nc_u16`, and the `v_add_u16`/`v_sub_u16`/`v_subrev_u16` `_e64` names) saturate to [0, 0xFFFF] with `clamp` (llvm-mc 21 gfx1030 encodes the bit on them, and LLVM selects i16 `uaddsat`/`usubsat` to them); **until 2026-11-22 the translator wrapped instead**. `clamp` on any other 16-bit integer op raises `Unsupported`. CPU-checked by `tests/semantic/test_alu_u16_clamp.py` (the high half of the destination is kept), **not GPU-verified**. CPU-checked by `tests/semantic/test_alu_u16_clamp.py` (the high half of the destination is kept), and **Hardware-verified on RDNA2** (AMD Radeon 680M, `gfx1035`, Windows 11, driver `26.5.1`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137): all 32-bit and 16-bit `*_nc_*` `clamp` cases (including `op_sel` and kept destination half on u16) match hardware bit-for-bit. **Open divergence measured on the same hardware:** `v_add_co_u32`, `v_sub_co_u32`, `v_subrev_co_u32`, `v_add_co_ci_u32`, `v_sub_co_ci_u32` and `v_subrev_co_ci_u32` with `clamp` saturate D (`0xFFFFFFFF` / `0`) while still reporting the real carry/borrow in `sdst`, whereas the translator currently ignores `clamp` on these carry-out ops. | | Carry-out subtract of a register from itself | `v_sub_co_u32`, `v_subrev_co_u32`, `v_sub_co_ci_u32` and `v_subrev_co_ci_u32` whose two sources are the same operand (`vD, sdst, vX, vX`) are written out as what x - x gives: D = 0 - carry in and borrow out = carry in (D = 0 and no borrow without a carry in; `clamp` saturates D to 0 on that borrow), with no `OpISubBorrow %x %x`. The values are the same as before; the form is there for AMD's Windows driver, whose compiler dies with an access violation (`0xC0000005` in `amdvlk64.dll`, at `0xafeb87` in 32.0.21037.1004 and `0xaff2d7` in 32.0.21045.29003, Radeon iGPU of a Ryzen 9 9950X3D, gfx1036) creating a native wave64 compute pipeline in which the borrow of an `OpISubBorrow` of one value with itself predicates the value operand of an `OpGroupNonUniformShuffle`. Measured by editing the translated module of a reduced `crosslane_fuzz.py` program (`v_sub_co_u32_e64 v4, s[18:19], v1, v1`, `s_and_saveexec_b64`, `ds_bpermute_b32`): `OpISubBorrow %x %x` crashes 3 of 3, also with the same id written twice, while a borrow of two different registers, `x < x`, `x != x`, `x - 0`, a literal `false` mask, the shuffle of a literal 0 and the same module without the shuffle all compile and run. The `--wave64-emulate` form of the same programs has no shuffle and never crashed. Found with `crosslane_fuzz.py --seed 880317 --wave 64 --w64-native --no-maskdata --dpp --ext --programs 400`: programs 1 and 181 were harness errors (exit 3221225477) on both drivers and match with this form (399 of 400 match, the other one differs only in a hypothesis op, as before). Checked on the CPU by `tests/semantic/test_sub_co_same_operand.py` (wave32 and native wave64 run, the emulated form by its text). **Not counted over the corpus**: whether a game shader subtracts a register from itself with a carry out is unmeasured (no package here), and other ways for that driver to see an `OpISubBorrow` of two equal values (two registers holding the same value) are not covered. | | Push-constant tail as a uniform block (`--pc-tail-ubo`) | For devices whose `maxPushConstantsSize` is 128, Vulkan's minimum, which can't take the 144-byte block (152 with `--mesh-compute`): AMD's older Windows drivers on RDNA2 iGPUs (Radeon 680M on 22.40.84.06, 610M on 24.10.16.14, the Ryzen 5 7600's iGPU on 24.10.24; a 610M on 26.11.2 reports 256) and some Intel Arc drivers (D3D-14, `push_constants_need_fallback` in `d3d12_vulkan_device.cpp`). The push-constant block keeps dwords 0–31 (s0–s31, 128 bytes). The tail that follows them by default, the heap base and code base and, with `--mesh-compute`, the output address, becomes `%pc_tail`: a uniform block at **set 1, binding 0** with the same members in the same order at offsets 0, 4, … (16 bytes, 24 with `--mesh-compute`). Set 1 is otherwise unused, so set 0's update-after-bind table doesn't change. The block is declared, and listed in the entry point's interface, only when the shader reads the tail (a memory access through the heap base, `s_getpc_b64`, or the `--mesh-compute` epilogue); the index then records `"pc_tail": {"set": 1, "binding": 0, "bytes": 16}`, and `"push_constant_bytes"` is 128 for every module. `"bindings"` still lists set 0 only. Without the flag nothing changes. **Checked:** `tests/test_pc_tail_ubo.py` (on `cs_store` and `ps_m15`: the block, its interface entry, `spirv-val`, the metadata, no block without a tail read, and the `--mesh-compute` address). The whole hand-written GPU test set in `runtime/test/shaders` is translated with the flag by `build.py` or `scripts/run_gpu_tests.py` under `LEONIDA_PC_TAIL_UBO=1`, and the index's `pc_tail` entries say which modules read the tail; how many do changes as shaders are added, so no count is kept here. The GPU test programs bind the block (`runtime/test/vk_pc_tail.h`; the list is in docs/testing.md), except with `--mesh-compute`, whose tests skip. The D3D12 layer does not yet: it refuses pipelines on a device with fewer than 144 push-constant bytes (`push_constants_fit` in `d3d12_vulkan_device.cpp`). | +| Address guard (`--address-guard`) | **Prototype, off by default.** Every `Gen.host_addr` access (buffer, `global_`, scalar and BVH loads, stores and atomics) calls `%guard_fn` with the access's sign-extended 48-bit heap offset, its kind and its span. An access whose first and last byte are below the arena's size passes after one compare. Any other access looks up the 4 KiB pages of its first and last byte in the runtime's two-level page table (level 1 by offset bits 47..32, level 2 one bit per page). A refused load reads the zero area at `heap_base + 0x71000`. A refused store or atomic goes to the dump area at `+ 0x78000`, and an atomic returns 0. Each refusal is counted in the header at `+ 0x70000`. The entry block reads that header once. Without its magic (runtime `LEONIDA_ADDRESS_GUARD` unset) every access passes, and without the flag the module is unchanged byte for byte. The index records `"address_guard": true`. Format: `runtime/src/address_guard.h`, `tools/address_guard.py`; design and costs: `docs/d3d12_vulkan.md` 3.3, "Address guard". **Checked:** `tests/semantic/test_address_guard.py` (fixture `cs_address_guard` through `spirv_mini_interp` with the guard on, off at run time and without the flag; kinds and spans per instruction family; the table model), `runtime/test/address_guard_test.cpp`, and `scripts/run_address_guard_gpu_test.py` (lavapipe, Mesa 26.3.1: the refused loads read 0 over real memory, and the store and the atomic land in the dump area). | | `v_mad_u32_u16` / `v_mad_i32_i16` op_sel on S2 and D, and clamp | D = S0.half · S1.half + S2, the halves zero- (u16) or sign-extended (i16), op_sel bit 0 / 1 reading the high half of S0 / S1. The other bits and `clamp` were refused (`Unsupported: op_sel/clamp`) until their results were measured on RDNA2 (AMD Radeon iGPU, gfx1036, Windows driver 26.10.1, raw kernels through `tools/hw_oracle`, wave32 and wave64 alike; EGEN-HW-MAD-U32-U16, 44 words): **op_sel bit 2 adds S2[31:16] zero-extended, in the i16 op too** (`v_mad_i32_i16 d, 3, 3, 0xffff8000 op_sel:[0,0,1,0]` gives `0x00010008`, not 8); an inline float constant there is its f32 pattern (`1.0` adds `0x3f80`); **op_sel bit 3 writes the result shifted left by 16** (low half 0, the old D not kept); **`clamp` saturates the 32-bit sum** to [0, 0xffffffff] (u16) or [0x80000000, 0x7fffffff] (i16), before that shift (the 16-bit product itself never overflows). GPU-checked with `runtime/test/shaders/ps_valu16_mad_sel.asm` (4096/4096 on NVIDIA GeForce RTX 5080, driver 616.92, and the gfx1036 iGPU); CPU-checked by `tests/semantic/test_alu_mad_32_16.py` (40 seeded cases against a Python reference) and `tests/semantic/test_value_semantics.py`. | | `v_add_nc_i16`, `v_sub_nc_i16` | GFX10 VOP3-only signed 16-bit add and subtract. Without `clamp` they are bit-identical to `v_add_nc_u16`/`v_sub_nc_u16` (the low 16 bits wrap) and take the same path: `op_sel:[s0,s1,dst]` picks each source's half and the destination half, and the other half of D is kept. With `clamp`, the exact sum or difference of the sign-extended halves saturates to [-32768, 32767] (`SClamp`), where the u16 forms saturate to [0, 0xFFFF]. RDNA2 (GFX10.3) dropped reversed 16-bit integer subtraction (`v_subrev_nc_u16` / `v_subrev_nc_i16` do not exist on hardware; `v_subrev_f16` is the only 16-bit reverse subtract opcode). Checked by `tests/semantic/test_valu_add_sub_nc_i16.py` (a value grid with and without `clamp`, `op_sel`, literals, SGPR sources, and untouched half preservation) and **Hardware-verified on AMD RDNA2** (`gfx1036`, wave32 and wave64 via `tools/int_hw_probe.py`, `valu_add_nc_clamp/v_add_sub_nc_i16_clamp`): signed saturation to [-32768, 32767], `op_sel` source selection, and untouched destination half preservation match hardware bit-for-bit. Until 2026-11-22 both raised `Unsupported`. CPU-checked by `tests/semantic/test_valu_add_sub_nc_i16.py` (a value grid with and without `clamp`, `op_sel` including the destination half, and equality with the u16 forms without `clamp`). **GPU-verified** on native RDNA2 (gfx1036, the Radeon iGPU of a Ryzen 7 9800X3D, Windows driver 32.0.21042.62) through `tools/hw_oracle`, one-thread raw kernels: 112 of 112 directed cases (both ops; 0x7FFF+1, 0x8000+1, 0x8000+0xFFFF, 0x7FFF+0x7FFF, 0x8000+0x8000 and others, each with and without `clamp` and with `op_sel` `[0,0,0]`, `[1,0,1]`, `[0,1,0]` and `[1,1,1]`, the destination preset to 0xA5A5A5A5). For example `v_add_nc_i16(0x7FFF, 1)` gives 0x8000 wrapped and 0x7FFF with `clamp`, `v_sub_nc_i16(0x8000, 1) clamp` gives 0x8000, and the destination half `op_sel` doesn't pick keeps its 0xA5A5. `tools/pk16_diff.py --oracle translator,hw --ops v_add_nc_i16,v_sub_nc_i16 --programs 3000 --seed 1`: 3000 of 3000 programs agree with the hardware and the translator. **Not GPU-verified.** Measured on native gfx1100: `clamp` saturates the exact sign-extended sum to [-32768, 32767] and the other half of D is kept. | | Gather sampler LOD | Before choosing the mip for the four fetches in `image_gather4_l(_o)`, clamp the requested LOD to S# word 1's MIN_LOD [11:0] and MAX_LOD [23:12] (unsigned 4.8). `ps_gather_sampler_lod.asm` reads the S# from the heap. On RTX 5080 and Radeon Graphics, a maximum of 0.25 selects the base quadrants and a minimum of 0.75 selects the cyan mip across the 64×64 draw. Without these bounds half of each frame reads the wrong level. Radeon also agreed with native `OpImageGather Lod` (`VK_AMD_texture_gather_bias_lod`) for those bounds. At exactly 0.5, with bounds [0,1], that native draw selected mip 1; the emulation now computes the mip as `Floor(LOD + 0.5)`, ties up, and also selects mip 1 (before SHADER-152 it used `RoundEven`, which selected mip 0). It computes `floor(LOD) + (LOD - floor(LOD) >= 0.5)`, which is exact in binary32, not `Floor(LOD + 0.5)`: that sum rounds `0x3effffff` up to 1.0, and on an RTX 5070 (621.24) the gather then read mip 1 where native `image_sample_l` at the same LOD reads mip 0. | @@ -444,6 +445,7 @@ How the generated SPIR-V expects the runtime to work: | 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. How each `op_sel`/`op_sel_hi` form that can reach the translator is confirmed: (1) `op_sel` 2 / `op_sel_hi` 5 without `clamp` or `neg`, which `llvm-mc` rejects: measured on `gfx1036` (the 5 sets above); `shader_disasm.py` prints it with its real encoding (`tests/semantic/test_fspx_dot4_op_sel_disasm.py`) and `skipped_form` recovers it from a gap in a listing made without that pass. (2) `op_sel` 0 / `op_sel_hi` 5 with an inline integer S1 and no `clamp` or `neg`, which `llvm-mc` decodes but prints with the default `op_sel_hi` 7: `restore_dot4_inline_sel` takes the stored field back, in a clean listing (`check_printed_encodings`) and in both re-anchoring paths; `op_sel_hi[1]` clear makes byte pairs 2..3 read S1's low half, the selection measured in (1), but the word itself was not run on hardware; confirmed by a count over the corpus (29 FidelityFX DLL programs, 1.0.2.1, LLVM 21.1.8: 22 translate without it, 24 with it, all 24 pass `spirv-val`; Code-embedded data row) and pinned by `tests/semantic/test_reanchor_dot4_inline_sel.py`. (3) Every other form `llvm-mc` decodes but prints with the default fields (for example `op_sel_hi` 5 with a VGPR S1, or `op_sel` 1 / `op_sel_hi` 6) is not measured and is refused as a dropped field; `tests/semantic/test_dot4_printed_op_sel.py` checks forms (2) and (3) with hand-built words. A general rule that took the stored fields of any such word (from luizwidmer/palmetto) was not taken for that reason. `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. | +| Wave64 emulation: single-wave barrier fallback | `translate()` re-translates an emulated compute program as the round loop (`Gen.x_scheduler`) when its inline structured form has an `OpControlBarrier` inside a selection or loop construct (`barriers_under_control_flow`), because a barrier only part of the workgroup reaches hangs NVIDIA (Xid 109). That fallback applies **only to multi-wave plans**. A single-wave workgroup (`plan_structured_emulation` mode `inline_all`, `x_lanes == 64`, also a partial group of fewer than 64 threads) is one wave: `%pc` between blocks comes from scalar state and votes read back from `%x_buf`, so every invocation takes the same path, and lane-local `%pc` exists only inside `emit_folded_region`'s `if (%active)` bodies, which emit no exchange and no barrier. Its barriers stay where the exchanges are, at the top level or under `%pc`-only guards. Why: the round loop keeps nearly the whole register file live across its back edge and through a switch over every segment (thousands of cases in large programs); on RADV/ACO (RX 7900 XTX, Mesa 26.3.1, offline `vk_pipeline_check` compiles only) that drove `aco::spill` past a 12 GiB cap (53 GB uncapped) on a large single-wave program the structured form compiles in 7–8.5 min under 3 GiB, and past 12 GiB in 35 s on a 4.9 MB one that compiles in 5 s at 0.3 GiB structured. ACO's static latency for single-wave programs with loops was 17 to 280 times that of the structured form, with VGPR spills each round, and three such programs (loops of up to thousands of iterations, one round per block visited) hung game runs on that GPU. Confirmed by a count over the 1.0.2.1 corpus: of the 820 single-wave emulated compute shaders of the main set that the fallback had put in the round loop, 666 get an `inline_all` plan, and in all 666 every barrier is at the top level or under constructs whose conditions load only `%pc` (none reads `%active`, a VGPR or `local_id`); the other 154 have no plan and stay rounds either way. Re-translated with this rule, exactly those 666 come out structured, the pipeline library's single-wave rounds drop from 818 to 171 (all 297 of them with loops are structured), and the translated and `spirv-val`-valid counts are unchanged (26,503 main, 2,683 library); recompiled, the 4.9 MB program takes 3.6 s at 0.37 GiB. CPU-checked by `tests/semantic/test_wave64_single_wave_barrier.py` (`wave64_single_wave_barrier.asm`: a cross-half `v_readlane_b32` in a uniform loop and a uniform branch, structured and round forms give the same words, every barrier guard loads only `%pc`), `test_wave64_emulate_opt.py` (`cs_inline_64`/`cs_inline_40`, both wave orders) and `test_loop_ballot_barrier.py`. **Not GPU-verified on NVIDIA**, the platform the fallback was written for. | | 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. | | LDS access order within a wave (`Volatile`) | RDNA2 runs a wave in lockstep with an in-order LDS queue, so a `ds_read` issued after a `ds_write` sees every lane's write with no `s_barrier` between them (`cs_w64x_lds_raw`), and a `ds_write` issued after a `ds_read` does not change what that read returned (`cs_w64x_lds_war`). Translated, a lane is an invocation, and the Vulkan memory model orders nothing between invocations without a barrier or an atomic, so a driver's compiler may move an invocation's load ahead of its own earlier store to another address, or merge two loads of one address. Results consistent with these optimizations were observed with AMD's Windows driver 24.30.46 (LLPC, Vulkan 1.3.302) on a Radeon 880M (RDNA3.5, native 64-wide compute subgroups): on `main` `561b65a8` both tests failed on every run with uninitialized Workgroup memory in all eight words, and in `cs_w64x_lds_war` the second read returned the same words as the first. Rule: every plain LDS `OpLoad` and `OpStore` (`lds_load`, `lds_store` and the two ADDTID forms) carries the `Volatile` memory operand, which prevents elimination, duplication or combination of the access ([SPIR-V memory operands](https://registry.khronos.org/SPIR-V/specs/unified1/SPIRV.html#Memory_Access)). This rule applies to plain accesses only. On that GPU and driver `Volatile` on the store alone or on the load alone made `cs_w64x_lds_raw` return its expected words (hand-edited SPIR-V, 3 of 3 runs each, against 0 of 4 unmodified), and with the rule both tests pass: `run_gpu_tests.py` goes from 210 to 212 of 232 passed with none failing (20 skipped), native and with `LEONIDA_W64_EMULATE=1`. An RTX 5070 Laptop (NVIDIA 621.01) gives the same results before and after (183 of 232 native, 214 emulated; `ms_wave_info_s3` fails both times). The operand changes 17 of the 238 test shaders and nothing but those loads and stores. A [full Xbox 1.0.2.1 corpus comparison](https://github.com/ItsNotRexed/Leonida/pull/6714#issuecomment-7107280378) translated and validated all 26,503 shaders at both 561b65a8 and 58deee34. Only the added operands differed in the 484 compute and 5 mesh modules that changed. The RAW and WAR results establish a workaround on the tested driver. Portable ordering between invocations requires synchronization appropriate to the accesses (see #2345). Under `--wave64-emulate` the halves meet at the round barriers as before; the operand is emitted there too. CPU-checked by `tests/semantic/test_lds_volatile.py` (every plain access form on the wave32, wave64 and emulated paths, and no other access is Volatile). | diff --git a/docs/directstorage.md b/docs/directstorage.md index 919d52282a..1618d221fc 100644 --- a/docs/directstorage.md +++ b/docs/directstorage.md @@ -84,6 +84,19 @@ The first boot with the executable settles most of this: the dry-run report show `DSTORAGE_QUEUE_OPTIONS::AutoSubmitDisabled`). An enqueue into a full queue waits for space, as the reference says; with auto-submit disabled only a `Submit` from another thread frees it. One worker thread per queue runs the submitted entries in order, so every notification follows all the entries before it. +- **Reads into physical pages wait for `Submit`**: an automatic submit stops at the first request whose + destination is a physical page list; that request and every entry behind it wait for the title's own `Submit`. + A title may fill the page-number table such a list points into only in its submit path, so an early read finds + page 0 (the entry fails) or the number the slot held before (the data lands in a page that now belongs to + something else, with no error). A full queue submits the held entries too, since the title cannot call `Submit` + while it waits in an enqueue, and so does `Close`. The idea is from VIctory (`Marvisak/VIctory` `eddde73`, also + in `fxceless/victory-fork` `79cfdd9`); the queue here keeps its order, so entries behind a held read wait with + it. `LEONIDA_DSTORAGE_HOLD_PAGES=0` restores the automatic submit of everything. A hold ends after + `LEONIDA_DSTORAGE_HOLD_MS` milliseconds without a `Submit` (2000 unless set): the held entries are submitted with + their page lists as they are, as a timed release, so a path that never calls `Submit` cannot stall for good. `0` + is no time limit (a hold of five seconds is then logged once). The `[rt] ds-hold` line counts automatic submits, + reads held, full-queue and timed releases, and destination lists that named page 0 when written (`event=`, at + each power of two of the counter that moved). - **Requests**: copied at enqueue. A file request reads `SourceSize` bytes at `FileOffset` into `Destination`; a memory request copies `Source` to `Destination` (`memmove`, so an overlapping pair is safe); a zlib request inflates those `SourceSize` bytes into `Destination` (below). Checked in this order when the worker reaches the @@ -190,7 +203,16 @@ The first boot with the executable settles most of this: the dry-run report show 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. + bits. A packed tail whose larger mips are BCPack-coded too has no raw or zlib sibling, so a history field that + only such tails use stayed unknown: in the game runs of 2026-11-25 two BC7 tail streams of one pool failed + with `missing-endpoint` (alpha fields of two history entries). For the streams that still start a chain at a + missing field, the fitter now decodes the nearest BCPack sibling with the profile so far and fits against it, + repeating while a round adds fields. The sibling may sit in the same refused BC7 stream: every block whose + chains start elsewhere is still determined, and the undetermined ones are left out of the reference. Those + fields are fitted, never confirmed, and fill only what the other fits left empty. On the 1.0.2.1 package this + raised the BC7 endpoint fields from 4,228 to 4,406 of 6,144; the runtime decoder then refuses 8 of 5,167 BC7 + streams instead of 60 (both failing requests decode), and the 268 BC6H streams are unchanged (10 refused; a + refused BC6H sibling is not used as a reference yet). 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 @@ -213,8 +235,9 @@ The first boot with the executable settles most of this: the dry-run report show `runtime/test/dstorage_test.cpp` (ctest `dstorage`) runs on synthetic files in `%TEMP%` through the registry entries under all three module names: `GAME:` reads with an overlay copy winning, offsets, zero size, a range past the end, -cancellation, auto-submit, a full queue, status arrays, fences (a CPU fence object that checks the data is in place -when it is signalled), events, error records, file and queue close with requests in flight, a destination the +cancellation, auto-submit, reads into physical pages held for `Submit` (a page list changed or filled before it, +a full queue, the time limit, the switch), a full queue, status arrays, fences (a CPU fence object that checks the +data is in place when it is signalled), events, error records, file and queue close with requests in flight, a destination the process cannot write, four threads enqueueing at once, the interface-id policy (unknown and system ids refused by `QueryInterface`, learned by creating calls), a `GetHandle` handle with its own file position, an event closed (and its handle value reused) before it is set, and cancelled requests that also had an enqueue error. zlib requests use diff --git a/docs/gameinput.md b/docs/gameinput.md index 1301a4a49f..c18d96a055 100644 --- a/docs/gameinput.md +++ b/docs/gameinput.md @@ -58,7 +58,8 @@ scripted pad, driven by the script alone: controller axis and controller button state. A reading is taken when the title asks for one and the script's state has changed since the last, so no thread polls; the history keeps the last 64 readings. - **The timeline:** the same as with SDL3 (`runtime/shims/gameinput_script.h` holds the parser, the timeline and the - log lines for both): seconds from the first `GameInputCreate`, each press held 300 ms, then released. + log lines for both): seconds from the first `GameInputCreate`, each press held 300 ms (or its own `:hold`, see + `LEONIDA_INPUT_SCRIPT` below), then released. - **Not served:** reading callbacks, aggregate devices, rumble and every other device. Those slots answer `E_NOTIMPL` and log the slot once. Controllers and the [keyboard pad](#keyboard-pad) still need SDL3. @@ -74,6 +75,10 @@ A press is logged when the title reads it, so a press the title never reads is n turns the `press` lines off. Without `LEONIDA_INPUT_SCRIPT`, the shim serves no devices and answers `E_NOTIMPL` for every slot past `Release`, as before. +`LEONIDA_INPUT_FILE=` drives a run whose display takes no keyboard input (a headless session): every line +appended to that file names one button of the script's table (`a`, `down`, ...) and becomes a press at once, held +like a scripted one. The file is read again at most every 250 ms. It is for local runs only. + `scripts/build_runtime.ps1` (what `make_game.py` runs) builds the shim only on its CMake path, when Visual Studio's C++ CMake tools are installed. Its direct-`cl.exe` fallback compiles a fixed file list without the shim and warns about it. @@ -335,7 +340,7 @@ line is logged when it takes effect); tracking goes on underneath, so clearing i | `LEONIDA_PROMPTS_SWITCH_MS` | `300` | shortest time between two changes of the active input family, 0..2000 ms | | `LEONIDA_GAMEINPUT_THREAD` | `1` | `0` stops the background poll thread; only `rt::gameinput::poll()` then reads the pads (tests) | | `LEONIDA_KEYBOARD_PAD` | `off` | `1` adds the [keyboard pad](#keyboard-pad), read while this process has focus; `always` reads keys whatever has focus | -| `LEONIDA_INPUT_SCRIPT` | unset | Comma-separated `button@seconds` entries, e.g. `a@2,a@4,start@6`. With SDL3 they drive the keyboard pad, which has to be enabled; without SDL3 they drive [one scripted pad](#scripted-input-without-sdl3), the only device. The first pad update (without SDL3, the first `GameInputCreate`) reads the script once at startup and starts the clock. `reload_config()` does not reread it. Each press lasts 300 ms. Buttons are `a b x y start back lb rb up down left right`. Spaces around entries are allowed. Empty entries, unknown buttons and invalid times (including negative or non-finite values) are counted and ignored. | +| `LEONIDA_INPUT_SCRIPT` | unset | Comma-separated `button@seconds` entries, e.g. `a@2,a@4,start@6`. With SDL3 they drive the keyboard pad, which has to be enabled; without SDL3 they drive [one scripted pad](#scripted-input-without-sdl3), the only device. The first pad update (without SDL3, the first `GameInputCreate`) reads the script once at startup and starts the clock. `reload_config()` does not reread it. Each press lasts 300 ms, or `hold` seconds when the entry is `button@seconds:hold` (more than 0, at most 600). With SDL3 a press then stays down until the title has read the pads six times since it began, but never past 5 s from its start (or its hold, if longer). A title reads its pad once a frame, so at a few seconds a frame a 300 ms press can fall between two reads and never arrive: on the retail title's "Couldn't autosave" prompt, three 300 ms `b` presses did nothing, while 120 presses 0.5 s apart got through; one `b@1100:3` replaces them. Buttons are `a b x y start back lb rb up down left right`. Spaces around entries are allowed. Empty entries, unknown buttons, invalid times (including negative or non-finite values) and invalid holds (0 or less, more than 600, not a number) are counted and ignored. | | `LEONIDA_MOUSE_SENSITIVITY` | `1` | scales how far the mouse moves the keyboard pad's right stick, 0.1..10 | SDL's own hints (`SDL_JOYSTICK_*`, see SDL's `SDL_hints.h`) also apply, for example `SDL_JOYSTICK_HIDAPI_PS5=0` to diff --git a/docs/linux_proton.md b/docs/linux_proton.md index de4760d70a..b981c2ef2f 100644 --- a/docs/linux_proton.md +++ b/docs/linux_proton.md @@ -150,6 +150,10 @@ Each item was a stop on at least one of the machines. Tests named in the pull re ## Where it stops +- **Writes into title memory.** A window is a read-side copy, so a UAV or raw write used to stop at the copy: the + missing return copy is the `WRITE_INVALID` device loss of #1537. The layer now copies the reached ranges back to + the title's pages at the next refresh, before the forward copy, and the title's own newer words win. Not yet + measured on a GPU with the world phase in front of it. - **Streamed memory that reaches its destination late or not at all.** The title calls queue slot 31 (`CopyPageMappingsBatchX`) about 300 times per boot. With #968 this branch maps each batch's pool pages at the destination and at the paired CPU view the layer reads (`docs/d3d12_vulkan.md`, section 4.9), so most streamed @@ -166,6 +170,63 @@ Each item was a stop on at least one of the machines. Tests named in the pull re - **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. +## AMD on Linux: what got the world drawn + +On 2026-11-26 a Linux machine with an RX 7900 XTX (and a Ryzen 9 7950X3D's RDNA2 iGPU), Mesa 26.3.1 (RADV) and Wine +drew the first world frames: the opening night street and a sunset street with palms, cars and a character, over +eight minutes in the world without a GPU hang, at about one frame per six seconds. The runtime was `main` `a73a57e13` +with #1914, #1957, #1972, #2044, #2097, #2124, #2129, #2144, #2162, #2195 and #2240 merged; they went into `main` +together with this section. Each step below removed a stop that ended every earlier run; they are in the order +they were found. + +1. **Raise amdgpu's GPU timeout.** `modinfo amdgpu -p` shows `lockup_timeout` with a default of 2000 ms: the kernel + resets any ring whose job runs over 2 s. World frames take seconds, so a run ended about 30 s into the world with + `ring gfx_0.0.0 timeout` in `journalctl -k`, no page fault, and a black last frame. Raise it as root and reboot: + `amdgpu.lockup_timeout=30000,60000,10000,10000` on the kernel command line (graphics, compute, SDMA, video, in + ms), or `options amdgpu lockup_timeout=30000,60000,10000,10000` in a file under `/etc/modprobe.d/` followed by an + initramfs rebuild. A real hang then freezes that ring, and a desktop on the same GPU, for up to that long, so don't + make it unlimited. Windows reporters raise `TdrDelay` for the same reason. +2. **Native wave64 shaders.** On a GPU that runs wave64 natively (AMD RDNA), translate with + `make_game.py --stages shaders --wave64-emulate off`. Before `max_subgroup_decider` (`make_game.py`), the auto + mode took the smallest `maxSubgroupSize` over every Vulkan device, so an installed llvmpipe (8) turned emulation on for all + 23,841 wave64 shaders. Emulated single-wave compute programs were then translated in the round-loop form, which + hung the GPU on several library programs and drove RADV's compiler past 12 GiB (53 GB uncapped) on the largest; the + translator no longer does that for single-wave programs ([design.md](design.md), row "Wave64 emulation: + single-wave barrier fallback"). + The auto mode now leaves CPU devices out when a GPU is listed and names the device that decided. +3. **Fill the pipeline journal with the runtime itself.** `gta6rt --precompile-pipelines --threads 16`, under Wine, + with the environment of the game run (`LEONIDA_SHADERS`, `LEONIDA_PIPELINE_CACHE_DIR`, `LEONIDA_DEVICE_FAULT`; + `--precompile-pipelines` in [d3d12_vulkan.md](d3d12_vulkan.md)). It built 3,693 compute pipelines; the next boot took + 1,900 of them from the journal in 0.1 s of driver time, and the menus ran at 30 frames/s instead of under one. + The `pipeline_cache.bin` that `make_game.py`'s pipelines stage writes with `vk_pipeline_check` gave no hits: 0 of + 5,526 journal pipeline keys were in its 29,861 objects (9 shader binaries were identical, so the machine code + matched and the keys did not). Each of three differences is enough for a miss on RADV: + - **The set of shaders:** the runtime's warm-up builds the library's compute programs (`library/index.json`, + 2,683 modules); the stage builds the main index and `bvh/`, and only 25 library modules are byte-identical to a + main-index one. + - **Robustness:** on RADV the runtime enables `robustBufferAccess`, `robustBufferAccess2` and `nullDescriptor`; + `vk_pipeline_check` turns `robustBufferAccess` off and leaves robustness2 off. RADV puts the robustness state into + every shader stage key, so every pipeline, compute and graphics, misses. + - **Layout and subgroup request:** for compute with set-0 bindings (2,244 of the 2,683) the checker builds set 0 + from default bindless features and requests the subgroup size without the runtime's full-subgroups flag; RADV + hashes the whole set layout and the stage flags. Graphics would miss anyway: the checker pairs each stage with a + stub and fixed state, and RADV hashes the full graphics state. +4. **Leave out the ray-tracing programs.** 724 library compute programs have 2 MiB of SPIR-V or more (676 of them + ray-tracing resolve) and take 89-167 s each in the driver. `LEONIDA_RT_AS=off` drops acceleration-structure builds + and copies, and `LEONIDA_SKIP_COMPUTE=,,...` with those programs' `lib_cs_NNNNN` names (picked by + module size from `library/index.json`) never builds or dispatches them. The picture then lacks whatever those + passes draw. +5. **Keep the title's hang watchdog kicked.** The title exits on purpose (a write to address 0) when its main loop has + not reported for 30 s, which a world load under the runtime exceeds. `LEONIDA_TITLE_WATCHDOG=0` defuses it only + together with `LEONIDA_TITLE_WATCHDOG_KICK=,` (hex; `runtime/src/main.cpp`); the two values are + measured locally and never committed. With `=0` alone the loader logs that the watchdog stays armed. + +The rest of that run's environment came from a Linux/Proton report on an RTX 3090: `LEONIDA_ASYNC_PIPELINES=0`, +`LEONIDA_DEVICE_TYPE=6`, `LEONIDA_MAP_READBACK=1`, `LEONIDA_TITLE_WINDOWS_MB=4096`, `LEONIDA_FRAME_PACING=1` and +`LEONIDA_PRESENT_NO_TEAR=1`. Still wrong after it: frames alternate between white-out, a correct picture and black; +some geometry is drawn in the wrong place; VRAM reached 18.3 of 22.3 GB; the run ended on a breakpoint in the title +after 12 minutes. + ## Reporting a result Say the machine (OS, GPU and driver, RAM), the commit, the environment switches that differ from the defaults, and diff --git a/docs/running.md b/docs/running.md new file mode 100644 index 0000000000..3b7e61f64c --- /dev/null +++ b/docs/running.md @@ -0,0 +1,142 @@ +# Running the game, per platform and GPU + +How the retail game has been run on each platform and GPU so far: the build, the shader pack, the pipeline +pre-compile, the driver and OS settings, the environment and what to expect. Every value is marked: + +- **measured by us**: by the maintainers who wrote this page, on the machine named in that section; +- **reported by others**: from a public issue or comment, linked; not checked by us; +- **TBD**: nobody has reported it yet. A report fills it in ([Reporting](#reporting)). + +Paths are placeholders: `` is the repository, `` the folder with `gta6rt.exe` and +`gta6rt_tls_host.dll`, `` the work folder `make_game.py` writes, `` a folder for pipeline caches, +`` the game's package folder and `` its executable. Under Wine, a Linux path is passed as `Z:`. + +## Settings every platform needs + +- **The title's hang watchdog.** The title exits on purpose (a write to address 0) when its main loop has not reported + for 30 s, which a world load under the runtime exceeds. `LEONIDA_TITLE_WATCHDOG=0` keeps it from firing only together + with `LEONIDA_TITLE_WATCHDOG_KICK=,` (hex), two addresses in the executable that each person + measures in their own copy (`runtime/src/main.cpp` describes the trap instruction the first must point at). The + values are never committed. With `=0` alone the loader logs that the watchdog stays armed. (Measured by us; the + watchdog was identified in [#2019](https://github.com/ubiquitarianism/leonida/issues/2019#issuecomment-7172996360).) +- **The GPU timeout.** World frames take seconds each. The OS's GPU timeout must be longer, or the driver resets the + GPU: amdgpu's `lockup_timeout` on Linux, `TdrDelay` on Windows (sections below). +- **Large ray-tracing programs.** 724 library compute programs have 2 MiB of SPIR-V or more (676 of them ray-tracing + resolve) and take 89-167 s each in the driver ([reported by others](https://github.com/ubiquitarianism/leonida/issues/1608#issuecomment-7184700506); + the count of 724 also measured by us). `LEONIDA_RT_AS=off` drops acceleration-structure builds and + `LEONIDA_SKIP_COMPUTE=,,...` with those programs' names (picked by module size from + `/shaders/spirv/library/index.json`) never builds or dispatches them. The picture then lacks what they draw. + +## Linux, Wine, AMD RX 7900 XTX (RADV) + +Measured by us on 2026-11-26: RX 7900 XTX, Ryzen 9 7950X3D, Linux 7.3, Mesa 26.3.1 (RADV), Wine. Details and the +reasons behind each step: [linux_proton.md](linux_proton.md#amd-on-linux-what-got-the-world-drawn). + +- **Build:** the clang-cl + xwin cross-build ([testing.md](testing.md#the-windows-runtime-on-linux-under-wine-or-proton)), + with SDL3 for the keyboard pad. +- **Shaders:** `python -I make_game.py --stages shaders --wave64-emulate off --work --out `. The GPU runs + wave64 natively; emulation is not needed. (`auto` picks the same here since llvmpipe no longer decides.) +- **Pipeline pre-compile:** `wine /gta6rt.exe --precompile-pipelines --threads 16` with the run's + `LEONIDA_SHADERS`, `LEONIDA_PIPELINE_CACHE_DIR` and `LEONIDA_DEVICE_FAULT`, before the first run. It built 3,693 + compute pipelines. Not `make_game.py --stages pipelines`: its cache never matches the runtime's driver keys. +- **Driver and OS:** `amdgpu.lockup_timeout=30000,60000,10000,10000` on the kernel command line (the default is + 2000 ms; reboot needed). +- **Environment:** + + | Setting | Why | + |---|---| + | `LEONIDA_D3D12=vulkan` | the Vulkan backend | + | `LEONIDA_SHADERS=Z:/shaders/spirv` | the native pack | + | `LEONIDA_PIPELINE_CACHE_DIR=Z:/pso` | the journal the pre-compile filled | + | `MESA_SHADER_CACHE_DIR=/mesa`, `MESA_SHADER_CACHE_MAX_SIZE=16G` | RADV's own cache, large enough for the pack | + | `LEONIDA_STARTUP_CACHE_CHECKPOINTS=1` | session cache snapshots during the boot | + | `LEONIDA_ASYNC_PIPELINES=0` | draws wait for their pipeline instead of being skipped | + | `LEONIDA_SERIAL_BIG_COMPILES=0`, `LEONIDA_COMPUTE_WARMUP_MAX_BYTES=8388608` | warm-up limits, as in the NVIDIA report below | + | `LEONIDA_RT_AS=off`, `LEONIDA_SKIP_COMPUTE=` | the large ray-tracing programs ([above](#settings-every-platform-needs)) | + | `LEONIDA_TITLE_WATCHDOG=0`, `LEONIDA_TITLE_WATCHDOG_KICK=,` | the title's hang watchdog ([above](#settings-every-platform-needs)) | + | `LEONIDA_DEVICE_TYPE=6`, `LEONIDA_MAP_READBACK=1`, `LEONIDA_FRAME_PACING=1`, `LEONIDA_PRESENT_NO_TEAR=1` | taken over from the NVIDIA report below; their effect on AMD was not measured one by one | + | `LEONIDA_ARENA_MB=4095`, `LEONIDA_TITLE_WINDOWS_MB=4096`, `LEONIDA_GEOMETRY_MB=6144` | room for the title's buffers in the world | + | `LEONIDA_CONSOLE_RELEASE_FILTER=1`, `LEONIDA_SHADOW_ALIAS_MS=5000`, `LEONIDA_CONSOLE_FIX_US=0` | carried from earlier boot runs; their effect here was not measured one by one | + | `LEONIDA_DEVICE_FAULT=1` | a device-loss report if the GPU hangs | + | `LEONIDA_KEYBOARD_PAD=always` | the keyboard as the pad | + +- **Command:** from ``, `wine /gta6rt.exe --run Z: --game-dir Z:`. +- **What to expect:** menus at 30 frames/s with no in-game compiling; the world after the story load, over eight + minutes without a GPU hang, at about one frame per six seconds. +- **Known problems:** frames alternate between white-out, a correct picture and black; some geometry is drawn in the + wrong place; VRAM reached 18.3 of 22.3 GB; the run ended on a breakpoint (`int3`) in the title after 12 minutes. + +## Linux, Wine, AMD RDNA2 iGPU (Ryzen 7000, RADV) + +Measured by us on 2026-11-25/26, the same machine's integrated GPU (gfx1036), headless, before the watchdog's KICK +was known. The settings that drew the world on the RX 7900 XTX have not been tried here: TBD. + +- **Build, shaders, pipeline pre-compile:** as for the RX 7900 XTX; the iGPU also runs wave64 natively. +- **Driver and OS:** the same `lockup_timeout` applies (TBD whether the values above are enough here). +- **Environment:** select the iGPU with `MESA_VK_DEVICE_SELECT=1002:164e` and + `MESA_VK_DEVICE_SELECT_FORCE_DEFAULT_DEVICE=1`. A cold compute warm-up made the title crawl at 0.12 frames/s behind + our own warm-ups; `LEONIDA_COMPUTE_WARMUP_LIVE_MAX_BYTES=131072` holds large warm-ups back while the title submits + (191 frames/s in the menus with it, measured on the RX 7900 XTX). +- **What to expect:** the boot, the first-run pages and the story load's loading screen (about 1,100 s into a run with + a partly warm cache). Every run then ended in the title's watchdog exit, about two minutes into the world load, + because only `LEONIDA_TITLE_WATCHDOG=0` was set. World frames: TBD. +- **Known problems:** TBD beyond the above. + +## Linux, Proton, NVIDIA + +Reported by others: [#1608, comment 7184700506](https://github.com/ubiquitarianism/leonida/issues/1608#issuecomment-7184700506) +(RTX 3090 24 GB, NVIDIA 590.48.01, GE-Proton11-14, Debian 13). Not run by us. + +- **Build:** clang-cl + xwin cross-build; `main` plus several pull requests and two local changes (listed in the report). +- **Shaders:** the main corpus, the library and FSPX with llvm-mc 23.1.6. Wave64 emulation: TBD from the report (it is + needed on NVIDIA's 32-wide subgroups; `auto` turns it on there). +- **Pipeline pre-compile:** caches warm from two earlier runs; no separate pre-compile is reported. +- **Driver and OS:** TBD. +- **Environment:** `LEONIDA_ASYNC_PIPELINES=0`, `LEONIDA_RT_AS=off`, `LEONIDA_SKIP_COMPUTE=`, + `LEONIDA_DEVICE_TYPE=6`, `LEONIDA_TITLE_WATCHDOG=0`, `LEONIDA_MAP_READBACK=1`, `LEONIDA_HOST_IMAGE_COPY=0`, + `LEONIDA_ARENA_MB=4095`, `LEONIDA_TITLE_WINDOWS_MB=4096`, `LEONIDA_SERIAL_BIG_COMPILES=0`, `LEONIDA_FRAME_PACING=1`, + `LEONIDA_PRESENT_NO_TEAR=1`. The report gives the reason for the skip list only: without it the world start waits + hours on the ray-tracing programs; with asynchronous pipelines instead the screen stayed black. +- **Command:** TBD. +- **What to expect:** the opening night street from about 650 s, at 0.1-0.2 frames/s, no device loss through 934 s. + The black stretch before it is graphics pipelines of 1-2.6 MB SPIR-V compiling one at a time, 5-10 s each. +- **Known problems:** nothing ray-traced is in the picture. + +## Windows, NVIDIA + +Reported by others: [#2019](https://github.com/ubiquitarianism/leonida/issues/2019) (RTX 5090 32 GB, driver 616.92, +Windows 11). Not run by us. + +- **Build:** `scripts/build_runtime.ps1` with SDL3, RelWithDebInfo. +- **Shaders:** `make_game.py --stages check,shaders,runtime` (26,503 shaders translated); wave64 emulation as `auto` + decides (on for NVIDIA). +- **Pipeline pre-compile:** TBD. +- **Driver and OS:** `TdrDelay` and `TdrDdiDelay` raised to 60 s, after which an 8.9 s pipeline build no longer + reset the device. +- **Environment:** `LEONIDA_D3D12=vulkan`, `LEONIDA_KEYBOARD_PAD=always`; the rest TBD. +- **Command:** `gta6rt.exe --first-run-ui game_scarlett_master.exe` from the package folder. +- **What to expect:** the first-run UI, then the title's watchdog exit at 145-204 s. With `LEONIDA_TITLE_WATCHDOG=0` + (before the KICK variable existed) the boot went on at about 24 frames/s and the machine then bugchecked + (`CRITICAL_PROCESS_DIED`) before a world frame. With the KICK values: TBD. +- **Known problems:** TBD. + +## Windows, AMD + +TBD: no public report of a game run on Windows with an AMD GPU is known to us. What the code does: on RDNA1 and RDNA2 +under AMD's Windows driver, `make_game.py`'s `auto` translates native wave64, because that driver crashes on many +emulated wave64 compute pipelines (#857). `TdrDelay` applies as for NVIDIA. + +## Intel + +TBD. + +## macOS (MoltenVK) + +TBD. + +## Reporting + +Post a run in the coordination issue, with the fields of these sections: machine (OS, GPU, driver, RAM), the commit, +how the shaders were made, the pipeline pre-compile, the OS and driver settings, every `LEONIDA_*` variable that +differs from the defaults (never the watchdog's RVA values), and how far the run got with its frame rate. Keep logs, +traces and screenshots on your machine ([linux_proton.md](linux_proton.md#reporting-a-result)). diff --git a/docs/runtime_imports.md b/docs/runtime_imports.md index e38dfbf744..e408d223d3 100644 --- a/docs/runtime_imports.md +++ b/docs/runtime_imports.md @@ -170,7 +170,7 @@ policy "other" (none is counted as returning an `HRESULT`), and they come from s | `xg_xs.dll` | 2: `XGCreateTextureComputer`, `XGSuggestSwizzleMode` | texture layout computation | | `XCRDAPI.dll` | 1: `DStorageGetFactory` | DirectStorage | | `chad.dll` | 5: `XDspActivate`, `XDspConnectWithMaximumStreamLimit`, `XDspDeactivate`, `XDspDisconnect`, `XDspSubmitCommand` | the audio DSP | -| `xapu.dll` | 5: `XApuConnect`, `XApuDequeueResult`, `XApuDisconnect`, `XApuEnqueueCommand`, `XApuGetResultCount` | the audio processing unit | +| `xapu.dll` | 5: `XApuConnect`, `XApuDequeueResult`, `XApuDisconnect`, `XApuEnqueueCommand`, `XApuGetResultCount` | the audio processing unit (Opus decode when `runtime/opus_decoder` is built) | | `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: @@ -203,17 +203,19 @@ again at detach (reason 0), and there is no `exception`, `error` or `unimplement unimplemented imports is reached by the TLS callbacks or the `DllMain`s. The executable's audio imports `xapu.dll` (`XApuConnect`, `XApuDequeueResult`, `XApuDisconnect`, -`XApuEnqueueCommand`, `XApuGetResultCount`) and `chad.dll` (`XDspActivate`, `XDspConnectWithMaximumStreamLimit`, -`XDspDeactivate`, `XDspDisconnect`, `XDspSubmitCommand`) are served by `runtime/shims/xapu_chad.cpp`. The shapes were -read statically from the executable's call sites: one each, four for `XApuEnqueueCommand`. Both connects succeed with -a handle; the APU connect also returns a zeroed shared buffer the title writes stream input to and reads output from. -Commands are accepted and not processed, so the audio stays silent. A stream open (type 1) and a stream close -(type 2) each queue one result of the same type and slot, because the title frees a stream id only when the close -result arrives. `XDspActivate` writes its two outputs as pointers to zeroed memory, which the title reads as "command -done" after each `XDspSubmitCommand`. `XApuConnect` leaves its first argument, a global of the title, untouched. The -buffer size (128 stream slots), the two results and the zeroed DSP status are hypotheses, explained in the file. -`xapu_chad_test` calls all ten in those shapes. With `--trace`, the first call of each, and the first command of each type, is an -`audio_queue` event. +`XApuEnqueueCommand`, `XApuGetResultCount`) are served by `runtime/shims/xapu_queue.cpp`; `chad.dll` +(`XDspActivate`, `XDspConnectWithMaximumStreamLimit`, `XDspDeactivate`, `XDspDisconnect`, `XDspSubmitCommand`) by +`runtime/shims/xapu_chad.cpp`. The shapes were read statically from the executable's call sites: one each, four for +`XApuEnqueueCommand`. `XApuConnect` reads the title's 24-byte `ConnectInput` (process 1 = Opus at 48 kHz, stream +count, commands per stream, a shared buffer, options) and returns `{shared buffer, result event}`; it never writes the +input. Activate, process, deactivate and reset commands are copied from the title's stack command, and each queues one +result in order. A process command decodes its Opus packet through `runtime/opus_decoder` (Rust over the BSD-3-Clause +`opus-pure`) into the slot's output, honouring first frame, frame count, output length and the deinterleaved option; +without the crate the result carries the table-of-contents frame count and silence. The layouts follow Marvisak/VIctory +`crates/victory-hle/src/modules/apu.rs` (GPL-3.0-or-later). `XDspActivate` writes its two outputs as pointers to zeroed +memory, which the title reads as "command done" after each `XDspSubmitCommand`; the DSP stays silent. `xapu_chad_test` +covers the layouts, the queue and the silent path; `xapu_opus_test` the decoded path. With `--trace`, the first call of +each, and the first command of each type, is an `audio_queue` event. The table above was measured before this shim and still lists these ten as unimplemented; they are served now. The call shapes agree with `docs/audio_hal_exe_calls.md`, which was measured with `tools/import_call_sites.py`. What this does not show: `--run` has not been run, so the entry point has not been called and no import is known to be diff --git a/make_game.py b/make_game.py index 03d93a2b8b..f1af5a172d 100644 --- a/make_game.py +++ b/make_game.py @@ -1879,26 +1879,54 @@ def keep_recorded_fallback(flag: str, work: str) -> bool: return True -def smallest_max_subgroup(vulkaninfo_text: str): - """The smallest maxSubgroupSize vulkaninfo reports over all devices (text or --json output), or None.""" +def max_subgroup_decider(vulkaninfo_text: str): + """(size, device, left_out): the smallest maxSubgroupSize vulkaninfo reports (text or --json output), the name + of the device that reports it (None when the output names no devices), and the names of the CPU devices left + out. A CPU device (llvmpipe, lavapipe, SwiftShader) only counts when no other device is listed: the runtime + ranks it below every GPU (runtime/src/vulkan_device_filter.h, tools/vk_subgroup_info.py device_rank), and + llvmpipe's maxSubgroupSize of 8 would otherwise turn emulation on beside a GPU with native wave64. size is + None when it can't be told.""" size = r'maxSubgroupSize"?\s*[=:]\s*(\d+)' # A device's own name is the least indented one; deeper ones (VK_KHR_maintenance7's layered APIs, e.g. # MoltenVK's Metal device, in both the text and the --json output) belong to the device above them. - names = list(re.finditer(r'(?m)^([ \t]*)"?deviceName"?\s*[=:]', vulkaninfo_text)) + names = list(re.finditer(r'(?m)^([ \t]*)"?deviceName"?\s*[=:]\s*"?([^"\n]*)', vulkaninfo_text)) depth = min((len(m.group(1)) for m in names), default=0) - starts = [m.start() for m in names if len(m.group(1)) == depth] - if not starts: + devices = [m for m in names if len(m.group(1)) == depth] + if not devices: sizes = [int(n) for n in re.findall(size, vulkaninfo_text)] - return min(sizes) if sizes else None + return (min(sizes) if sizes else None), None, [] + # deviceType sits beside deviceName in VkPhysicalDeviceProperties (just before it in the text output; the + # --json output may order the keys differently), so each device takes the nearest one at the same depth. + types = [(m.start(), m.group(2)) for m in + re.finditer(r'(?m)^([ \t]*)"?deviceType"?\s*[=:]\s*"?([A-Z_0-9]+)', vulkaninfo_text) + if len(m.group(1)) == depth] + + def is_cpu(pos): + if not types: + return False + kind = min(types, key=lambda t: abs(t[0] - pos))[1] + return kind.endswith("TYPE_CPU") or kind == "4" + # One section per device (a 1.3 device can print the size twice, in two property structs): one value each, # and a device that prints none makes the answer unknown rather than being left out of the smallest. per_device = [] - for a, b in zip(starts, starts[1:] + [len(vulkaninfo_text)]): - sizes = [int(n) for n in re.findall(size, vulkaninfo_text[a:b])] - if not sizes: - return None - per_device.append(min(sizes)) - return min(per_device) + ends = [m.start() for m in devices[1:]] + [len(vulkaninfo_text)] + for m, end in zip(devices, ends): + sizes = [int(n) for n in re.findall(size, vulkaninfo_text[m.start():end])] + per_device.append((min(sizes) if sizes else None, m.group(2).strip().rstrip(","), is_cpu(m.start()))) + gpus = [d for d in per_device if not d[2]] + left_out = [d[1] for d in per_device if d[2]] if gpus else [] + counted = gpus or per_device + if any(d[0] is None for d in counted): + return None, None, left_out + smallest = min(counted, key=lambda d: d[0]) + return smallest[0], smallest[1], left_out + + +def smallest_max_subgroup(vulkaninfo_text: str): + """The smallest maxSubgroupSize vulkaninfo reports (text or --json output), or None; CPU devices only count when + no GPU is listed (max_subgroup_decider).""" + return max_subgroup_decider(vulkaninfo_text)[0] def wave64_settings(mode: str, *, mesh_compute: bool = False) -> tuple[bool, bool]: @@ -1906,7 +1934,8 @@ def wave64_settings(mode: str, *, mesh_compute: bool = False) -> tuple[bool, boo shader is only exact without it when the GPU gives it 64-wide subgroups; with it, it is exact on any subgroup size, at the cost of a workgroup barrier per segment. "auto" keeps emulation off on native-wave64 RDNA1/2 under the AMD Windows driver. Elsewhere it turns emulation on unless every Vulkan device reports - maxSubgroupSize >= 64 and the runtime probe does not rule out native wave64.""" + maxSubgroupSize >= 64 and the runtime probe does not rule out native wave64; a CPU device (llvmpipe) only + counts when no GPU is listed (max_subgroup_decider).""" if mode == "on": return True, False if mode == "off": @@ -1927,24 +1956,28 @@ def wave64_settings(mode: str, *, mesh_compute: bool = False) -> tuple[bool, boo "(#857), so auto uses native wave64 and rebuilds emulated outputs (--wave64-emulate on to force emulation)") return False, False exe = shutil.which("vulkaninfo") - size = None + size, decider, left_out = None, None, [] if exe: try: r = subprocess.run([exe], capture_output=True, text=True, errors="replace", timeout=120) - size = smallest_max_subgroup(r.stdout) + size, decider, left_out = max_subgroup_decider(r.stdout) except (OSError, subprocess.SubprocessError): size = None + if left_out: + log(f"shaders: left out of the wave64 choice, as the runtime never picks a CPU device beside a GPU: " + f"{', '.join(left_out)}") if size is None: log("shaders: couldn't read the GPU's subgroup size from vulkaninfo: wave64 emulation on " "(exact on every GPU; --wave64-emulate off to skip it on a GPU with 64-wide subgroups)") return True, True on = size < 64 + by = f" ({decider})" if decider else "" if not on and native64 is False: stages = "compute" if compute_only else "both compute and mesh" - log(f"shaders: smallest maximum subgroup size is {size}, but the Vulkan query found no 64-wide path for " + log(f"shaders: smallest maximum subgroup size is {size}{by}, but the Vulkan query found no 64-wide path for " f"{stages} (fixed default size or required-size control): wave64 emulation on") return True, True - log(f"shaders: smallest maximum subgroup size is {size}: wave64 emulation {'on' if on else 'off'}") + log(f"shaders: smallest maximum subgroup size is {size}{by}: wave64 emulation {'on' if on else 'off'}") return on, True diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 10ee582b12..b8cef55c65 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -158,6 +158,54 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) message(FATAL_ERROR "LEONIDA_REQUIRE_XMA2_DECODER is enabled, but the Rust XMA2 decoder is unavailable") endif() + # Rust Opus decoder (runtime/opus_decoder), the same pattern as the XMA2 decoder: cargo at + # configure time, a prebuilt -DLEONIDA_OPUS_DECODER_LIB, or the silent path in xapu_queue.cpp. + option(LEONIDA_REQUIRE_OPUS_DECODER "Fail configure if the Rust Opus decoder is unavailable" OFF) + set(LEONIDA_OPUS_DECODER_LIB "" CACHE FILEPATH + "Prebuilt leonida_opus_decoder.lib (skips running cargo at configure time)") + include("${CMAKE_CURRENT_SOURCE_DIR}/cmake/opus_decoder.cmake") + leonida_resolve_prebuilt_opus_decoder("${LEONIDA_OPUS_DECODER_LIB}" "${CMAKE_BINARY_DIR}" _opus_lib_resolved) + if(_opus_lib_resolved) + message(STATUS "Using prebuilt Rust Opus decoder: ${_opus_lib_resolved}") + else() + if(NOT LEONIDA_CARGO) + find_program(LEONIDA_CARGO cargo) + endif() + if(LEONIDA_CARGO) + set(_opus_target x86_64-pc-windows-msvc) + set(_opus_target_dir ${CMAKE_BINARY_DIR}/opus_decoder) + set(_opus_lib ${_opus_target_dir}/${_opus_target}/release/leonida_opus_decoder.lib) + set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS + ${CMAKE_CURRENT_SOURCE_DIR}/opus_decoder/Cargo.toml + ${CMAKE_CURRENT_SOURCE_DIR}/opus_decoder/Cargo.lock + ${CMAKE_CURRENT_SOURCE_DIR}/opus_decoder/src/lib.rs) + execute_process( + COMMAND ${LEONIDA_CARGO} build --release --locked --target ${_opus_target} + --manifest-path ${CMAKE_CURRENT_SOURCE_DIR}/opus_decoder/Cargo.toml + --target-dir ${_opus_target_dir} + TIMEOUT 300 + RESULT_VARIABLE _opus_result) + if(_opus_result STREQUAL "0" AND EXISTS "${_opus_lib}") + set(_opus_lib_resolved "${_opus_lib}") + else() + message(WARNING "cargo build of runtime/opus_decoder failed: the XAPU Opus path will be silent") + endif() + else() + message(STATUS "cargo not found: runtime/opus_decoder not built, the XAPU Opus path will be silent") + endif() + endif() + if(_opus_lib_resolved) + add_library(leonida_opus_decoder STATIC IMPORTED) + set_target_properties(leonida_opus_decoder PROPERTIES + IMPORTED_LOCATION "${_opus_lib_resolved}" + INTERFACE_INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}/opus_decoder" + INTERFACE_COMPILE_DEFINITIONS LEONIDA_HAVE_OPUS_DECODER=1 + INTERFACE_LINK_LIBRARIES "kernel32;ntdll;userenv;ws2_32;dbghelp;synchronization") + endif() + if(LEONIDA_REQUIRE_OPUS_DECODER AND NOT TARGET leonida_opus_decoder) + message(FATAL_ERROR "LEONIDA_REQUIRE_OPUS_DECODER is enabled, but the Rust Opus 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") @@ -199,6 +247,7 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) shims/com_shim.cpp shims/silent_audio.cpp shims/bcrypt_rng.cpp + shims/xapu_queue.cpp shims/xapu_chad.cpp shims/dstorage.cpp ) @@ -352,6 +401,9 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) target_link_libraries(gta6rt PRIVATE leonida_xma2_decoder) target_link_libraries(acphal_test PRIVATE leonida_xma2_decoder) endif() + if(TARGET leonida_opus_decoder) + target_link_libraries(gta6rt PRIVATE leonida_opus_decoder) + endif() # The Zen 2 instructions a desktop CPU may lack (src/cpu_emulation.h): decoded, emulated on a CONTEXT, and run for # real with the #UD handler installed, so an Intel host takes the emulated path and an AMD one the native path. @@ -382,9 +434,11 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) 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. + # xapu.dll and chad.dll, the APU and audio DSP command queues, resolved through the registry like xmem_test; Opus + # frame counts from hand-made packets. add_executable(xapu_chad_test test/xapu_chad_test.cpp + shims/xapu_queue.cpp shims/xapu_chad.cpp shims/registry.cpp ) @@ -393,6 +447,20 @@ 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) + if(TARGET leonida_opus_decoder) + # xapu_queue.cpp with the decoder compiled in, against the generated Opus tone. + add_executable(xapu_opus_test + test/xapu_opus_test.cpp + shims/xapu_queue.cpp + shims/registry.cpp + ) + target_include_directories(xapu_opus_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) + target_compile_definitions(xapu_opus_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(xapu_opus_test PRIVATE /W4 /permissive- /utf-8) + target_link_options(xapu_opus_test PRIVATE /OPT:NOREF) + target_link_libraries(xapu_opus_test PRIVATE leonida_opus_decoder) + endif() + # 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. @@ -814,6 +882,9 @@ if(BUILD_TESTING) 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(heavy_pipeline_cache_test test/heavy_pipeline_cache_test.cpp) + add_test(NAME heavy_pipeline_cache COMMAND heavy_pipeline_cache_test) + # The per-pipeline journal files compute pipelines are kept in: naming, header check, atomic replacement. add_executable(pipeline_cache_journal_test test/pipeline_cache_journal_test.cpp) add_test(NAME pipeline_cache_journal COMMAND pipeline_cache_journal_test) @@ -1434,6 +1505,8 @@ if(BUILD_TESTING) # Which SPIR-V modules declare a storage image or buffer they may write (src/spirv_stores.h), on hand-built words. add_executable(spirv_stores_test test/spirv_stores_test.cpp) add_test(NAME spirv_stores COMMAND spirv_stores_test) + add_executable(list_value_wait_budget_test test/list_value_wait_budget_test.cpp) + add_test(NAME list_value_wait_budget COMMAND list_value_wait_budget_test) add_executable(shader_fixture_path_test test/shader_fixture_path_test.cpp) add_test(NAME shader_fixture_path COMMAND shader_fixture_path_test) add_executable(resource_tiling_test test/resource_tiling_test.cpp) @@ -1596,6 +1669,9 @@ 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_opus_test) + add_test(NAME xapu_opus COMMAND xapu_opus_test) + endif() if(WIN32 AND TARGET xapu_test) add_test(NAME xapu COMMAND xapu_test) endif() @@ -3656,6 +3732,18 @@ if(TARGET Vulkan::Headers) target_compile_options(d3d12_unmapped_vsharp_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_unmapped_vsharp COMMAND d3d12_unmapped_vsharp_test) set_tests_properties(d3d12_unmapped_vsharp PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_CONSOLE_FIX_US=0") + # The host-RAM mirror of a console heap's GPU copy (src/console_heap_copy.h) agrees with the copy through the first + # refresh, title writes and a filtered release sweep; run again without the mirror, where the copy must not change. + add_executable(d3d12_console_heap_mirror_test test/d3d12_console_heap_mirror_test.cpp shims/d3d12_xs_device.cpp) + target_link_libraries(d3d12_console_heap_mirror_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_console_heap_mirror_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_VULKAN_DEVICE) + target_compile_options(d3d12_console_heap_mirror_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_console_heap_mirror COMMAND d3d12_console_heap_mirror_test) + set_tests_properties(d3d12_console_heap_mirror PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT + "LEONIDA_CONSOLE_FIX_US=0;LEONIDA_CONSOLE_RELEASE_FILTER=1;LEONIDA_HEAP_MIRROR_CHECK=1") + add_test(NAME d3d12_console_heap_mirror_off COMMAND d3d12_console_heap_mirror_test) + set_tests_properties(d3d12_console_heap_mirror_off PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT + "LEONIDA_CONSOLE_FIX_US=0;LEONIDA_CONSOLE_RELEASE_FILTER=1;LEONIDA_HEAP_MIRROR=0") add_executable(d3d12_indirect_zero_test test/d3d12_indirect_zero_test.cpp) target_link_libraries(d3d12_indirect_zero_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) target_compile_definitions(d3d12_indirect_zero_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) @@ -3824,6 +3912,13 @@ if(TARGET Vulkan::Headers) # is written zero-size, and a dispatch through it reads zeros. add_test(NAME d3d12_title_window_cap COMMAND d3d12_title_va_test --window-cap) set_tests_properties(d3d12_title_window_cap PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_TITLE_WINDOWS_MB=0") + # A window is a read-side mirror refreshed before every submission: what a shader writes into it goes back to + # the title's pages at the next refresh, and the title's own newer words still win (#1537, WRITE_INVALID). + add_test(NAME d3d12_title_window_write_back COMMAND d3d12_title_va_test --window-writeback) + set_tests_properties(d3d12_title_window_write_back PROPERTIES SKIP_RETURN_CODE 77) + # The same return copy for a slot-133 buffer's shadow (the write-back of a compute result the title reads again). + add_test(NAME d3d12_placed_write_back COMMAND d3d12_title_va_test --placed-writeback) + set_tests_properties(d3d12_placed_write_back PROPERTIES SKIP_RETURN_CODE 77) add_test(NAME d3d12_api_descriptor_copy COMMAND d3d12_title_va_test --api-descriptor-copy) set_tests_properties(d3d12_api_descriptor_copy PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_DESC_MIRROR=1") add_test(NAME d3d12_api_descriptor_copy_off COMMAND d3d12_title_va_test --api-descriptor-copy-off) @@ -4179,6 +4274,11 @@ if(TARGET Vulkan::Headers) target_compile_options(d3d12_mesh_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_mesh COMMAND d3d12_mesh_test) set_tests_properties(d3d12_mesh PROPERTIES SKIP_RETURN_CODE 77) + # The same draws through the heavy pipeline cache (src/heavy_pipeline_cache.h): every build first asks the + # offline cache without compiling, and a miss is built against the heavy cache in a folder of its own. + add_test(NAME d3d12_mesh_heavy_cache COMMAND d3d12_mesh_test) + set_tests_properties(d3d12_mesh_heavy_cache PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT + "LEONIDA_HEAVY_PIPELINE_CACHE_MS=1;LEONIDA_PIPELINE_CACHE_DIR=${CMAKE_CURRENT_BINARY_DIR}/heavy_cache_test") else() message(STATUS "glslangValidator not found: d3d12_compute_test, d3d12_draw_test, d3d12_set0_compute_test and d3d12_mesh_test are not built") endif() @@ -4579,6 +4679,12 @@ if(TARGET Vulkan::Headers) target_compile_options(arena_blocks_test PRIVATE /W4 /permissive- /utf-8) endif() add_test(NAME arena_blocks COMMAND arena_blocks_test) + # The address guard's page table (src/address_guard.h; docs/d3d12_vulkan.md, "Address guard"). + add_executable(address_guard_test test/address_guard_test.cpp) + if(WIN32 AND MSVC) + target_compile_options(address_guard_test PRIVATE /W4 /permissive- /utf-8) + endif() + add_test(NAME address_guard COMMAND address_guard_test) add_executable(title_window_plan_bounds_test test/title_window_plan_bounds_test.cpp) if(WIN32 AND MSVC) target_compile_options(title_window_plan_bounds_test PRIVATE /W4 /permissive- /utf-8) @@ -4590,6 +4696,12 @@ if(TARGET Vulkan::Headers) target_compile_options(console_heap_vsharp_slots_test PRIVATE /W4 /permissive- /utf-8) endif() add_test(NAME console_heap_vsharp_slots COMMAND console_heap_vsharp_slots_test) + # Host-RAM mirror of a console resource heap's GPU copy (src/console_heap_copy.h). + add_executable(console_heap_copy_test test/console_heap_copy_test.cpp) + if(WIN32 AND MSVC) + target_compile_options(console_heap_copy_test PRIVATE /W4 /permissive- /utf-8) + endif() + add_test(NAME console_heap_copy COMMAND console_heap_copy_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}) diff --git a/runtime/README.md b/runtime/README.md index 23a7811abe..84190039ca 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -353,7 +353,7 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_POOL_DIAG_AT` | unset | *Diagnostic.* `+0x` of the title's transient-pool assert, as the trace prints it (measured locally): the trace dumps the pool's resource list when that int3 is hit (`shims/startup_trace.h`). | | `LEONIDA_PEEK` | unset | *Diagnostic.* `[:n],,...` (hex): a thread prints the 8-byte values at these RVAs of the title's image (`:n` = n consecutive values) every `LEONIDA_PEEK_SECONDS` (`src/main.cpp`). The RVAs are measured locally and not kept in the repository. `scripts/windows-boot/boot.ps1` no longer sets the game-state and session-state RVAs by default: it sets `LEONIDA_PEEK` only from `LEONIDA_GAME_STATE_RVA` and `LEONIDA_SESSION_STATE_RVA`, and without them its RESULT states read `?` ([scripts/windows-boot/README.md](../scripts/windows-boot/README.md)). | | `LEONIDA_PEEK_SECONDS` | `10` | *Diagnostic.* The period of the `LEONIDA_PEEK` thread (`src/main.cpp`), which prints 8-byte values of the title's image. | -| `LEONIDA_INPUT_SCRIPT` | unset | Timed pad presses, `button@seconds` separated by commas (`a@70,a@85,start@120`), each held 300 ms; the clock starts with the shim. Works with and without SDL3: with SDL3 it drives the keyboard pad (`LEONIDA_KEYBOARD_PAD=always`), without SDL3 one scripted pad that is the only device. Controllers and the keyboard pad still need SDL3. Format and buttons in [docs/gameinput.md](../docs/gameinput.md#environment-variables). | +| `LEONIDA_INPUT_SCRIPT` | unset | Timed pad presses, `button@seconds` separated by commas (`a@70,a@85,start@120`), each held 300 ms or its own `button@seconds:hold`; the clock starts with the shim. Works with and without SDL3: with SDL3 it drives the keyboard pad (`LEONIDA_KEYBOARD_PAD=always`), without SDL3 one scripted pad that is the only device. Controllers and the keyboard pad still need SDL3. Format and buttons in [docs/gameinput.md](../docs/gameinput.md#environment-variables). | | `LEONIDA_INPUT_LOG` | on | The GameInput shim logs every press in `LEONIDA_INPUT_SCRIPT`'s form (`name@seconds`), so a session played by hand can be replayed. `0` turns the lines off. | | `LEONIDA_LOG_ALLOCINFO` | unset | *Diagnostic.* `1` logs every device slot 25 call (`GetResourceAllocationInfo`) with its thread, description and sizes (`shims/d3d12_xs_device.cpp`). | | `LEONIDA_LOG_EXE_PIPELINES` | unset | *Diagnostic.* When set, one line per distinct graphics pipeline that uses a program translated from the executable's inline containers. | @@ -382,6 +382,8 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_REFRESH_PER_FRAME` | `0` | Trades correctness for speed. `1`: the slot-133 shadows, title windows and geometry copies are brought up to date only by the first submission after each present, not by every submission; `2`: the console descriptor heaps too. A GPU read of them can then be a frame behind the title's writes (wrong pixels). `0` refreshes all of them at every submission. | | `LEONIDA_GEOMETRY_ASYNC` | unset | Trades correctness for speed. `1` refreshes the geometry copies (`shims/d3d12_geometry_views.h`) on a worker thread of the layer, started at submission and not waited for, instead of on the title's submitting thread. A draw may read a copy the worker is still writing: wrong vertices for a frame. | | `LEONIDA_GEOMETRY_WHOLE_VIEWS` | unset | A geometry copy that is already filled copies only the 64 KiB tiles of title memory written since the last refresh (`shims/d3d12_geometry_views.h`). Any value other than `0` copies every view over a written tile whole, as before. | +| `LEONIDA_GEOMETRY_HOST` | unset | Where the geometry copies (`shims/d3d12_geometry_views.h`, under `LEONIDA_GEOMETRY_MB`) live. Unset or `0`: device-local memory through the BAR while the driver gives it (several GB of VRAM in a world run). `1`: system memory outside VRAM, write-back where the device offers a cached host type; `2`: system memory, write-combined. The GPU then reads every vertex and index of a copy over the bus, which can cost frame time in geometry-heavy passes. A device whose host-visible memory is all device-local (an integrated GPU) keeps its types. The choice is logged once and in the `geometry buffers` line. | +| `LEONIDA_GEOMETRY_REMAP_RELEASE` | on | A remap of physical pages (`XMemMapPhysicalPages`, the scatter call, `CopyPageMappingsBatchX`) that gives a page another frame, or none, retires the geometry copies over it, as freeing or unmapping it does: the title streams by remapping its pools' frames, and the copies of what they held were kept for the device's life. A retired copy is copied once more from the new pages if they are readable, then freed once every submission that may name it has finished. A page mapped again to the frame it had is no change. `0` turns it off. | | `LEONIDA_TITLE_FILL_ASYNC` | unset | Trades correctness for speed. `1` stops device slot 70 views from hashing and filling the texture they name on the title's thread: a texture never filled or known stale is queued for a worker thread that fills one texture at a time. Until then a shader samples the image as it is, empty or a frame behind. | | `LEONIDA_TITLE_VIEW_REFRESH_MS` | `0` | The shortest time, in milliseconds, between two checks of a title texture's bytes when a device slot 70 view of it is written. `0` checks at every view. The periodic pass still checks the texture on its own period, and a texture known stale is checked at once. Has no effect with `LEONIDA_TITLE_FILL_ASYNC=1`. | | `LEONIDA_TITLE_EVERY_BUDGET_US` | `0` | Microseconds one pass over the textures filled from the title's memory may spend on the textures it visits every pass (mapped by the title, or known stale), resuming where the last pass stopped; the texture that crosses the limit is finished. A mapped texture never filled yet is visited first whatever the limit. `0` visits all of them every pass. It limits the synchronous pass only: with `LEONIDA_TEXTURE_REFRESH_ASYNC=1` the pass runs on the refresh worker, and the limit does not apply. | @@ -423,6 +425,8 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_CONSOLE_GPU_TSHARPS` | on | With `LEONIDA_CONSOLE_HEAP_GPU=1`, the T#s of changed slots are registered by the resolver thread and the refresh only decodes them. `0` registers them on the submitting thread, under the fix budget. | | `LEONIDA_CONSOLE_GPU_RETRY_MS` | `2000` | With `LEONIDA_CONSOLE_HEAP_GPU=1`, how often V# words that got no backing are asked for again, on a timer that bounds the cost per submission. | | `LEONIDA_CONSOLE_GPU_FILTER` | `LEONIDA_CONSOLE_RELEASE_FILTER`'s value | With `LEONIDA_CONSOLE_HEAP_GPU=1`, `1`: a released backing, an alias range that went or a word answered since asks for a rescan of only the slots it touches, not of every V# slot. Overflows and key resets still rescan everything. | +| `LEONIDA_HEAP_MIRROR` | `1` | `0`: no host-RAM mirror of a console resource heap's copy in the arena (`src/console_heap_copy.h`). With the mirror, the CPU reads of the copy (the `LEONIDA_CONSOLE_RELEASE_FILTER` sweep) come from host RAM, not uncached device memory across PCIe. A copy in an import of host memory, and one the `LEONIDA_CONSOLE_HEAP_GPU` pass writes, never has one. | +| `LEONIDA_HEAP_MIRROR_CHECK` | unset | `1`: at every release sweep the mirror is compared with the copy (a read of the whole copy); the first differing slots are logged, and the heap log line counts the checks and differing slots. | | `LEONIDA_CONSOLE_RELEASE_FILTER` | unset | `1`: when a backing is released, only the console-heap slots whose V#s point into it are fixed again (by actual Vulkan address), instead of every V# slot of the heap. The heap log line counts the sweeps, live slots, fixes and full fallbacks. | | `LEONIDA_SHADOW_GPU` | unset | `1`: aliased pages of the slot-133 shadows are copied on the GPU at the start of a submission, from an import of the mapped title section (`VK_EXT_external_memory_host`, per 2 MiB window, kept while xmem's map journal shows no change over it). Destinations outside the arena and pages that do not import are copied by the CPU as before. | | `LEONIDA_SHADOW_GPU_MB` | `1024` | With `LEONIDA_SHADOW_GPU=1`, the MiB of title memory imported for those copies at most. | diff --git a/runtime/cmake/opus_decoder.cmake b/runtime/cmake/opus_decoder.cmake new file mode 100644 index 0000000000..1286b15fa4 --- /dev/null +++ b/runtime/cmake/opus_decoder.cmake @@ -0,0 +1,23 @@ +# Resolves -DLEONIDA_OPUS_DECODER_LIB= for runtime/CMakeLists.txt. +# +# When LEONIDA_OPUS_DECODER_LIB is set, the runtime links that prebuilt static library directly and +# skips running cargo at configure time. A value that does not name an existing file is a configure +# error rather than a silent fallback to silent XAPU output. +function(leonida_resolve_prebuilt_opus_decoder lib_input base_dir out_var) + if(NOT lib_input) + set(${out_var} "" PARENT_SCOPE) + return() + endif() + if(IS_ABSOLUTE "${lib_input}") + set(_resolved "${lib_input}") + else() + cmake_path(ABSOLUTE_PATH lib_input BASE_DIRECTORY "${base_dir}" NORMALIZE OUTPUT_VARIABLE _resolved) + endif() + if(EXISTS "${_resolved}" AND NOT IS_DIRECTORY "${_resolved}") + set(${out_var} "${_resolved}" PARENT_SCOPE) + else() + message(FATAL_ERROR + "LEONIDA_OPUS_DECODER_LIB does not point to an existing file: ${_resolved} " + "(pass the path to leonida_opus_decoder.lib or leave it empty to build with cargo)") + endif() +endfunction() diff --git a/runtime/opus_decoder/Cargo.lock b/runtime/opus_decoder/Cargo.lock new file mode 100644 index 0000000000..1659ab14ea --- /dev/null +++ b/runtime/opus_decoder/Cargo.lock @@ -0,0 +1,16 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "leonida-opus-decoder" +version = "0.1.0" +dependencies = [ + "opus-pure", +] + +[[package]] +name = "opus-pure" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2da6dcc20af557d030b6f206e75c764bcda8c28a5bd03c73935c7e8fcf5f4f4a" diff --git a/runtime/opus_decoder/Cargo.toml b/runtime/opus_decoder/Cargo.toml new file mode 100644 index 0000000000..e3ed59bc3a --- /dev/null +++ b/runtime/opus_decoder/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "leonida-opus-decoder" +version = "0.1.0" +edition = "2021" +license = "GPL-3.0-or-later" +publish = false + +[lib] +name = "leonida_opus_decoder" +crate-type = ["staticlib", "rlib"] + +[dependencies] +opus-pure = "0.2.4" + +[profile.release] +panic = "unwind" diff --git a/runtime/opus_decoder/README.md b/runtime/opus_decoder/README.md new file mode 100644 index 0000000000..2b516e4963 --- /dev/null +++ b/runtime/opus_decoder/README.md @@ -0,0 +1,33 @@ +# Opus decoder C ABI + +This crate exposes a C ABI around the BSD-3-Clause `opus-pure` package for the console audio +decoder (`xapu.dll`). The command protocol lives in `runtime/shims/xapu_chad.cpp`; this crate only +decodes one Opus packet into interleaved f32 PCM, resets the decoder, and (for tests) encodes a +synthetic tone. + +## Build + +```sh +cargo fmt --manifest-path runtime/opus_decoder/Cargo.toml -- --check +cargo test --manifest-path runtime/opus_decoder/Cargo.toml --locked +cargo build --release --manifest-path runtime/opus_decoder/Cargo.toml --locked +``` + +`runtime/CMakeLists.txt` builds this crate for `x86_64-pc-windows-msvc` at configure time when +`cargo` is on `PATH` and links it into `gta6rt` and `xapu_chad_test` with +`LEONIDA_HAVE_OPUS_DECODER` defined. The first build fetches `opus-pure` from crates.io. Set +`CARGO_NET_OFFLINE=true` for a configure that uses only the local Cargo cache. + +Without `cargo`, when the build fails, or with the `cl.exe` fallback of `scripts/build_runtime.ps1`, +the XAPU path stays silent. Use `-DLEONIDA_REQUIRE_OPUS_DECODER=ON` to require the decoder in a +CMake build. + +To link an already-built `leonida_opus_decoder.lib` without invoking `cargo` during CMake +configure, pass `-DLEONIDA_OPUS_DECODER_LIB=`. + +## Facts and credit + +The `xapu.dll` command protocol (connect input/output, per-stream command budget, activate / +process / reset / deactivate, result order) follows Marvisak/VIctory +`crates/victory-hle/src/modules/apu.rs` (GPL-3.0-or-later), which this repository already credits for +other modules. `opus-pure` is BSD-3-Clause and stays a dependency; no code from it is copied. diff --git a/runtime/opus_decoder/leonida_opus_decoder.h b/runtime/opus_decoder/leonida_opus_decoder.h new file mode 100644 index 0000000000..d5473510df --- /dev/null +++ b/runtime/opus_decoder/leonida_opus_decoder.h @@ -0,0 +1,44 @@ +#ifndef LEONIDA_OPUS_DECODER_H +#define LEONIDA_OPUS_DECODER_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* 120 ms at 48 kHz: the longest Opus packet, in samples per channel. */ +#define LEONIDA_OPUS_MAX_FRAMES 5760u + +typedef struct LeonidaOpusDecoder LeonidaOpusDecoder; + +enum LeonidaOpusStatus { + LEONIDA_OPUS_OK = 0, + LEONIDA_OPUS_INVALID_ARGUMENT = 1, + LEONIDA_OPUS_INVALID_FORMAT = 2, + LEONIDA_OPUS_DECODER_FAILURE = 3, + LEONIDA_OPUS_OUT_OF_MEMORY = 4, + LEONIDA_OPUS_PANIC = 5, + LEONIDA_OPUS_BUFFER_TOO_SMALL = 6, +}; + +int32_t leonida_opus_decoder_create(uint32_t sample_rate, uint32_t channels, + LeonidaOpusDecoder **out_decoder); +uint32_t leonida_opus_decoder_channels(const LeonidaOpusDecoder *decoder); +int32_t leonida_opus_decode_packet(LeonidaOpusDecoder *decoder, + const uint8_t *input, size_t input_len, + float *out, size_t out_capacity_frames, + uint32_t *out_frames); +int32_t leonida_opus_decoder_reset(LeonidaOpusDecoder *decoder); +void leonida_opus_decoder_destroy(LeonidaOpusDecoder *decoder); +/* Test helper: encodes frame_count interleaved f32 frames to one packet at 48 kHz. */ +int32_t leonida_opus_encode_test(const float *input, uint32_t frame_count, + uint32_t channels, uint8_t *out, + size_t out_capacity, size_t *out_len); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/runtime/opus_decoder/src/lib.rs b/runtime/opus_decoder/src/lib.rs new file mode 100644 index 0000000000..1e6c7dc831 --- /dev/null +++ b/runtime/opus_decoder/src/lib.rs @@ -0,0 +1,244 @@ +#![deny(unsafe_op_in_unsafe_fn)] + +//! C ABI around the pure-Rust `opus-pure` decoder, for the console audio decoder (`xapu.dll`). +//! +//! The command protocol lives in `runtime/shims/xapu_chad.cpp`; this crate only turns one Opus +//! packet into interleaved f32 PCM, resets the decoder, and (for tests) encodes a synthetic tone. +//! `opus-pure` is BSD-3-Clause; this wrapper is GPL-3.0-or-later, like the rest of the runtime. + +use std::panic::{catch_unwind, AssertUnwindSafe}; +use std::ptr; +use std::sync::Mutex; + +use opus_pure::{Application, OpusDecoder, OpusEncoder}; + +pub const LEONIDA_OPUS_OK: i32 = 0; +pub const LEONIDA_OPUS_INVALID_ARGUMENT: i32 = 1; +pub const LEONIDA_OPUS_INVALID_FORMAT: i32 = 2; +pub const LEONIDA_OPUS_DECODER_FAILURE: i32 = 3; +pub const LEONIDA_OPUS_OUT_OF_MEMORY: i32 = 4; +pub const LEONIDA_OPUS_PANIC: i32 = 5; +pub const LEONIDA_OPUS_BUFFER_TOO_SMALL: i32 = 6; + +/// 120 ms at 48 kHz, the longest Opus packet, in samples per channel. +pub const LEONIDA_OPUS_MAX_FRAMES: usize = 5760; + +#[repr(C)] +pub struct LeonidaOpusDecoder { + decoder: Mutex, + channels: usize, +} + +#[no_mangle] +pub unsafe extern "C" fn leonida_opus_decoder_channels(decoder: *const LeonidaOpusDecoder) -> u32 { + if decoder.is_null() { + return 0; + } + unsafe { (*decoder).channels as u32 } +} + +/// Creates a decoder for one mono or stereo Opus stream at `sample_rate` (the title uses 48000). +/// +/// # Safety +/// `out` must be writable for one pointer. The returned decoder must be destroyed once, after +/// every call that uses it has finished. +#[no_mangle] +pub unsafe extern "C" fn leonida_opus_decoder_create( + sample_rate: u32, + channels: u32, + out: *mut *mut LeonidaOpusDecoder, +) -> i32 { + if out.is_null() { + return LEONIDA_OPUS_INVALID_ARGUMENT; + } + unsafe { *out = ptr::null_mut() }; + if sample_rate == 0 || sample_rate > i32::MAX as u32 || !(1..=2).contains(&channels) { + return LEONIDA_OPUS_INVALID_FORMAT; + } + match catch_unwind(AssertUnwindSafe(|| { + OpusDecoder::new(sample_rate as i32, channels as usize).map(|decoder| { + Box::new(LeonidaOpusDecoder { + decoder: Mutex::new(decoder), + channels: channels as usize, + }) + }) + })) { + Ok(Ok(decoder)) => { + unsafe { *out = Box::into_raw(decoder) }; + LEONIDA_OPUS_OK + } + Ok(Err(_)) => LEONIDA_OPUS_INVALID_FORMAT, + Err(_) => LEONIDA_OPUS_PANIC, + } +} + +/// Decodes one Opus packet into `out` as interleaved f32 frames. +/// +/// # Safety +/// `decoder` must come from `leonida_opus_decoder_create`. `input` must reference `input_len` +/// readable bytes; `out` must hold `out_capacity_frames * channels` floats; `out_frames` must be +/// writable. Do not destroy the decoder concurrently with this call. +#[no_mangle] +pub unsafe extern "C" fn leonida_opus_decode_packet( + decoder: *mut LeonidaOpusDecoder, + input: *const u8, + input_len: usize, + out: *mut f32, + out_capacity_frames: usize, + out_frames: *mut u32, +) -> i32 { + if decoder.is_null() + || input.is_null() + || input_len == 0 + || out.is_null() + || out_frames.is_null() + { + return LEONIDA_OPUS_INVALID_ARGUMENT; + } + let decoder = unsafe { &*decoder }; + let channels = decoder.channels; + let Ok(mut guard) = decoder.decoder.lock() else { + return LEONIDA_OPUS_DECODER_FAILURE; + }; + let packet = unsafe { std::slice::from_raw_parts(input, input_len) }; + let mut pcm = vec![0f32; LEONIDA_OPUS_MAX_FRAMES * channels]; + match guard.decode(packet, LEONIDA_OPUS_MAX_FRAMES, &mut pcm) { + Ok(frames) => { + if frames > out_capacity_frames { + return LEONIDA_OPUS_BUFFER_TOO_SMALL; + } + let samples = frames * channels; + unsafe { + ptr::copy_nonoverlapping(pcm.as_ptr(), out, samples); + *out_frames = frames as u32; + } + LEONIDA_OPUS_OK + } + Err(_) => LEONIDA_OPUS_DECODER_FAILURE, + } +} + +/// # Safety +/// `decoder` must come from `leonida_opus_decoder_create` and not be used concurrently. +#[no_mangle] +pub unsafe extern "C" fn leonida_opus_decoder_reset(decoder: *mut LeonidaOpusDecoder) -> i32 { + if decoder.is_null() { + return LEONIDA_OPUS_INVALID_ARGUMENT; + } + let decoder = unsafe { &*decoder }; + let Ok(mut guard) = decoder.decoder.lock() else { + return LEONIDA_OPUS_DECODER_FAILURE; + }; + let _ = guard.reset_state(); + LEONIDA_OPUS_OK +} + +/// # Safety +/// `decoder` must be a live handle and must not be used after this call. +#[no_mangle] +pub unsafe extern "C" fn leonida_opus_decoder_destroy(decoder: *mut LeonidaOpusDecoder) { + if !decoder.is_null() { + unsafe { drop(Box::from_raw(decoder)) }; + } +} + +/// Test helper: encodes `frame_count` interleaved f32 frames to one Opus packet at 48 kHz. +/// +/// # Safety +/// `input` must hold `frame_count * channels` floats; `out` must hold `out_capacity` bytes; +/// `out_len` must be writable. +#[no_mangle] +pub unsafe extern "C" fn leonida_opus_encode_test( + input: *const f32, + frame_count: u32, + channels: u32, + out: *mut u8, + out_capacity: usize, + out_len: *mut usize, +) -> i32 { + if input.is_null() + || out.is_null() + || out_len.is_null() + || frame_count == 0 + || !(1..=2).contains(&channels) + { + return LEONIDA_OPUS_INVALID_ARGUMENT; + } + let samples = frame_count as usize * channels as usize; + let input = unsafe { std::slice::from_raw_parts(input, samples) }; + let mut encoder = match OpusEncoder::new(48_000, channels as usize, Application::Audio) { + Ok(encoder) => encoder, + Err(_) => return LEONIDA_OPUS_INVALID_FORMAT, + }; + let mut packet = vec![0u8; out_capacity.max(4000)]; + match encoder.encode(input, frame_count as usize, &mut packet) { + Ok(bytes) if bytes <= out_capacity => { + unsafe { + ptr::copy_nonoverlapping(packet.as_ptr(), out, bytes); + *out_len = bytes; + } + LEONIDA_OPUS_OK + } + Ok(_) => LEONIDA_OPUS_BUFFER_TOO_SMALL, + Err(_) => LEONIDA_OPUS_DECODER_FAILURE, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn encodes_and_decodes_a_tone() { + const FRAMES: u32 = 960; + const CHANNELS: u32 = 2; + let mut tone = Vec::with_capacity((FRAMES * CHANNELS) as usize); + for i in 0..FRAMES { + let sample = ((i as f32) * 440.0 * std::f32::consts::TAU / 48_000.0).sin() * 0.5; + tone.push(sample); + tone.push(sample); + } + let mut packet = [0u8; 1500]; + let mut packet_len = 0usize; + // SAFETY: the buffers are owned by this test. + let encoded = unsafe { + leonida_opus_encode_test( + tone.as_ptr(), + FRAMES, + CHANNELS, + packet.as_mut_ptr(), + packet.len(), + &mut packet_len, + ) + }; + assert_eq!(encoded, LEONIDA_OPUS_OK); + assert!(packet_len > 0); + + let mut decoder = ptr::null_mut(); + // SAFETY: `decoder` is writable for one pointer. + assert_eq!( + unsafe { leonida_opus_decoder_create(48_000, CHANNELS, &mut decoder) }, + LEONIDA_OPUS_OK + ); + let mut pcm = vec![0f32; LEONIDA_OPUS_MAX_FRAMES * CHANNELS as usize]; + let mut frames = 0u32; + // SAFETY: the packet and PCM buffers are owned by this test. + let decoded = unsafe { + leonida_opus_decode_packet( + decoder, + packet.as_ptr(), + packet_len, + pcm.as_mut_ptr(), + LEONIDA_OPUS_MAX_FRAMES, + &mut frames, + ) + }; + assert_eq!(decoded, LEONIDA_OPUS_OK); + assert_eq!(frames, FRAMES); + let energy: f32 = + pcm[..(frames * CHANNELS) as usize].iter().map(|s| s * s).sum::() / (frames * CHANNELS) as f32; + assert!(energy > 0.01, "decoded a tone, energy {energy}"); + // SAFETY: created above, destroyed once. + unsafe { leonida_opus_decoder_destroy(decoder) }; + } +} diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index ca2b027893..76e946b47b 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -169,6 +169,9 @@ struct VulkanDeviceInfo { bool occlusion_query_precise = false; bool prepare_on_bind = false; bool cold_graphics_compile = false; // Driver supports a cache-only create and reports when compilation is pending. + // pipelineCreationCacheControl is on for the heavy pipeline cache (src/heavy_pipeline_cache.h): a pipeline the + // offline cache does not have is created against the cache of pipeline_cache.heavy.bin, written back as it grows. + bool heavy_pipeline_cache = false; bool pipeline_statistics_query = false; bool presentation = false; // VK_KHR_surface + VK_KHR_win32_surface on the instance, VK_KHR_swapchain on the device // VK_KHR_swapchain_maintenance1 (or VK_EXT_swapchain_maintenance1) and its swapchainMaintenance1 feature are @@ -387,6 +390,10 @@ std::uint64_t device_arena_size(ID3D12Device* device); // Copies `bytes` of the device's GPU address arena at console VA `va` (what shaders read there: a heap's GPU copy, // the null slots after it) into `out`. False without an arena or when the range is not inside it. For tests. bool read_arena(ID3D12Device* device, std::uint64_t va, void* out, std::size_t bytes); +// The slots whose host-RAM mirror differs from the GPU copy of the console descriptor heap at `console_va` +// (src/console_heap_copy.h), compared now: 0 when they agree, -1 when there is no such heap or it has no mirror. +// For tests. +long long console_heap_mirror_mismatches(ID3D12Device* device, std::uint64_t console_va); // The blocks of device memory that textures share (src/image_memory.h): how many, their bytes, and the textures in // them. For tests. diff --git a/runtime/shims/d3d12_compute_input_probe.h b/runtime/shims/d3d12_compute_input_probe.h index 70ac61e52c..fdec0348e3 100644 --- a/runtime/shims/d3d12_compute_input_probe.h +++ b/runtime/shims/d3d12_compute_input_probe.h @@ -195,7 +195,7 @@ bool gpu_words_now(State& state, std::uint64_t at, std::array& for (const auto& heap : state.console_heaps) { const auto delta = at - heap->shader_va; if (heap->copy && delta <= heap->bytes && sizeof(out) <= heap->bytes - delta) { - std::memcpy(out.data(), heap->copy + delta, sizeof(out)); + std::memcpy(out.data(), heap->copy.gpu() + delta, sizeof(out)); return true; } } @@ -249,7 +249,7 @@ void recheck(State& state) { if (!lock.owns_lock()) std::fputs("[rt] compute-input: after loss, console heaps locked\n", stderr); else for (const auto& heap : state.console_heaps) - if (heap->copy) scan("console", heap->shader_va, heap->copy, heap->bytes); + if (heap->copy) scan("console", heap->shader_va, heap->copy.gpu(), heap->bytes); } { std::unique_lock lock(state.visible_heap_mutex, std::try_to_lock); @@ -294,7 +294,7 @@ Backing descriptor(State& state, std::uint64_t seq, std::size_t list, std::size_ 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)); + std::memcpy(gpu.data(), heap->copy.view() + delta, sizeof(gpu)); have_gpu = true; break; } diff --git a/runtime/shims/d3d12_geometry_views.h b/runtime/shims/d3d12_geometry_views.h index feb4ff52e0..ebfab4b74e 100644 --- a/runtime/shims/d3d12_geometry_views.h +++ b/runtime/shims/d3d12_geometry_views.h @@ -9,13 +9,14 @@ #include #include #include +#include #include #include #include namespace rt::d3d12 { -// One persistent device-local copy for each geometry extent. The console heap retains its original indices. +// One persistent copy for each geometry extent, in device-local memory (or system memory: LEONIDA_GEOMETRY_HOST). 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. // Views whose title range is released are retired immediately and their backing storage is reclaimed once // in-flight GPU submissions up to their retire ticket have completed; previously cap-refused ranges retry @@ -30,6 +31,7 @@ class GeometryViews { struct NoopRetire { void operator()(Address, std::size_t, VkDeviceSize) const noexcept {} }; + struct NoCopy {}; struct View { Address source{}; std::size_t size{}; @@ -121,7 +123,7 @@ class GeometryViews { std::atomic free_generation_{0}; std::uint64_t serial_{}, bytes_{}, cap_refusals_{}, allocation_failures_{}, ready_{}, uploads_{}, uploaded_{}; std::uint64_t submissions_{}, dirty_refreshes_{}, refilled_{}, tile_fills_{}; - std::uint64_t evicted_{}, reaped_{}, retries_succeeded_{}; + std::uint64_t evicted_{}, reaped_{}, retries_succeeded_{}, final_copies_{}; std::unordered_map tile_reads_; // refresh(): offset in tile_scratch_, SIZE_MAX unreadable // refresh() scratch: per view, whether it waits on a tile (pinned), is filled whole, was touched, was counted; // and the tiles found written, in address order. @@ -213,6 +215,7 @@ class GeometryViews { public: explicit GeometryViews(std::uint64_t cap_override = 0) : cap_override_(cap_override) { + pool_.set_system_memory(system_memory_setting()); leonida::geometry_writes::subscribe(releases_); } ~GeometryViews() { leonida::geometry_writes::unsubscribe(releases_); } @@ -231,6 +234,16 @@ class GeometryViews { std::uint64_t effective_cap() const { return cap_override_ ? cap_override_ : cap(); } + // LEONIDA_GEOMETRY_HOST: where the copies live. Unset or 0: device-local memory (the BAR) while the driver gives it; + // 1: system memory, write-back (cached) where the device offers it; 2: system memory, write-combined. The GPU then + // reads the copies over the bus (VRAM saved, each read of a vertex or index slower). + static int system_memory_setting() { + const char* v = std::getenv("LEONIDA_GEOMETRY_HOST"); + if (!v || !*v || *v == '0') return TitleBufferWindows::kDeviceLocal; + return *v == '2' ? TitleBufferWindows::kSystemUncached : TitleBufferWindows::kSystemCached; + } + int system_memory() const { return pool_.system_memory(); } + bool has_released() const { return leonida::geometry_writes::has_released(releases_); } bool has_retired() const { return retired_count_.load(std::memory_order_acquire) != 0; } bool has_pending_reclaim() const { return has_released() || has_retired(); } @@ -258,6 +271,10 @@ class GeometryViews { std::lock_guard lock(mutex_); return evicted_; } + std::uint64_t final_copies() const { + std::lock_guard lock(mutex_); + return final_copies_; + } std::uint64_t reaped() const { std::lock_guard lock(mutex_); return reaped_; @@ -393,9 +410,14 @@ class GeometryViews { // Retires every live view overlapping [begin, end), unlinking it from lookup/refresh/watch immediately and // deferring its backing storage reclamation until GPU submissions through `retire_ticket` have completed // (kAfterExecutes: through the submissions of every replay in progress now, see execute_end). - template + // With `final_copy` (a refresh's copy), a ready view whose title range is readable now is copied from it once more + // before it leaves the refresh: a range the title remapped holds new bytes, and a list recorded before the remap + // that took the view's address (a root view) and runs in a submission the view waits for reads those, as it would + // have read them in the console's memory, and as the refresh this retirement replaces would have copied them. + // Freed or unmapped memory is not readable, so such a view keeps what it held. + template std::size_t retire_range(Address begin, Address end, std::uint64_t retire_ticket = 0, - OnRetire&& on_retire = {}) { + OnRetire&& on_retire = {}, Copy&& final_copy = {}) { if (end <= begin) return 0; struct CallbackItem { Address source; @@ -425,6 +447,13 @@ class GeometryViews { const std::size_t first_retired = retired_.size(); for (const auto id : ids) { View& v = views_[id]; + if constexpr (!std::is_same_v, NoCopy>) { + if (v.ready && final_copy(v.dst, reinterpret_cast(v.source), v.size) == + GeometryCopy::copied) { + ++final_copies_; + uploaded_ += v.size; + } + } detach_tiles_locked(id, v.source, v.size); if (v.ready) { --ready_; @@ -495,21 +524,21 @@ class GeometryViews { return freed; } - // Drains released title ranges recorded by xmem (retiring matching views at `retire_ticket`) and reaps retired - // views whose GPU work completed by `completed_ticket`. - template + // Drains released title ranges recorded by xmem (retiring matching views at `retire_ticket`, with `final_copy` as + // retire_range takes it) and reaps retired views whose GPU work completed by `completed_ticket`. + template void drain_released(Device& device, std::uint64_t retire_ticket, std::uint64_t completed_ticket, - OnRetire&& on_retire = {}) { + OnRetire&& on_retire = {}, Copy&& final_copy = {}) { std::vector> ranges; leonida::geometry_writes::take_released(releases_, ranges); for (const auto& [begin, end] : ranges) { - retire_range(begin, end, retire_ticket, on_retire); + retire_range(begin, end, retire_ticket, on_retire, final_copy); leonida::title_gpu_views::Range pair{}; if (end > begin && leonida::title_gpu_views::view_at(begin, 1, pair) && begin >= pair.gpu && begin - pair.gpu < pair.size) { const Address offset = begin - pair.gpu; const Address span = (std::min)(end - begin, pair.size - offset); - retire_range(pair.cpu + offset, pair.cpu + offset + span, retire_ticket, on_retire); + retire_range(pair.cpu + offset, pair.cpu + offset + span, retire_ticket, on_retire, final_copy); } } reap(device, completed_ticket); @@ -666,14 +695,17 @@ class GeometryViews { if (!effective_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, retried ok %llu, evicted %llu (reaped %llu, retired %zu), " - "allocation failures %llu, uploads %llu (%llu bytes), watched tiles %zu, reserved %llu bytes\n", + "cap refused %llu, retried ok %llu, evicted %llu (reaped %llu, retired %zu, copied at " + "retirement %llu), allocation failures %llu, uploads %llu (%llu bytes), watched tiles %zu, " + "reserved %llu bytes (%s)\n", keys_.size() + refused_.size(), live_views_, (unsigned long long)bytes_, (unsigned long long)ready_, (unsigned long long)(effective_cap() >> 20), (unsigned long long)cap_refusals_, (unsigned long long)retries_succeeded_, (unsigned long long)evicted_, - (unsigned long long)reaped_, retired_.size(), (unsigned long long)allocation_failures_, + (unsigned long long)reaped_, retired_.size(), (unsigned long long)final_copies_, + (unsigned long long)allocation_failures_, (unsigned long long)uploads_, (unsigned long long)uploaded_, tiles_.size(), - static_cast(pool_.reserved())); + static_cast(pool_.reserved()), + pool_.system_memory() ? "system memory" : "device-local"); std::fprintf(stderr, "[rt] geometry refresh: %llu/%llu submissions uploaded dirty views, %llu bytes (%llu views by " "their written tiles only); %.3f s checking and refreshing sources, %llu bytes cleared\n", static_cast(dirty_refreshes_), static_cast(submissions_), diff --git a/runtime/shims/d3d12_title_buffer_windows.h b/runtime/shims/d3d12_title_buffer_windows.h index 06927cb4b6..c85809e8e2 100644 --- a/runtime/shims/d3d12_title_buffer_windows.h +++ b/runtime/shims/d3d12_title_buffer_windows.h @@ -38,6 +38,10 @@ class TitleBufferWindows { std::chrono::steady_clock::time_point failed_at_{}; bool failed_ = false; bool local_refused_ = false; // device-local blocks refused once: host memory from then on + // SystemMemory: where a device_local allocation goes instead (set_system_memory; GeometryViews from + // LEONIDA_GEOMETRY_HOST). + int system_memory_ = 0; + bool system_memory_logged_ = false; std::uint64_t quick_refusals_ = 0; // The blocks' (device address, capacity), readable without the owner's lock: published in order, a slot never // reused before release(). A destroyed block's slot keeps its other fields and only its address goes to 0 (the @@ -73,7 +77,38 @@ class TitleBufferWindows { blocks_.erase(it); } + // The memory types a system-memory block may take: host-visible ones outside device-local memory (the GPU reads + // them over the bus), the write-back (cached) ones only when `cached`, else the write-combined ones only. None of + // them: every type `bits` allows (an integrated GPU, whose memory is all device-local). + template + static std::uint32_t system_memory_types(const Device& d, std::uint32_t bits, bool cached) { + if constexpr (requires { d.memory.memoryTypes[0].propertyFlags; d.memory.memoryTypeCount; }) { + std::uint32_t host = 0, wanted = 0; + for (std::uint32_t i = 0; i < d.memory.memoryTypeCount && i < 32; ++i) { + if (!(bits & (1u << i))) continue; + const VkMemoryPropertyFlags f = d.memory.memoryTypes[i].propertyFlags; + if ((f & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) || !(f & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) || + !(f & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) + continue; + host |= 1u << i; + if (bool(f & VK_MEMORY_PROPERTY_HOST_CACHED_BIT) == cached) wanted |= 1u << i; + } + return wanted ? wanted : host ? host : bits; + } else { + (void)d; + (void)cached; + return bits; + } + } + public: + // Where blocks asked for as device_local go: kDeviceLocal (Resizable BAR while the driver gives it, the default), + // kSystemCached (host memory outside VRAM, write-back where the device offers it: what VIctory gives its copies + // of title memory) or kSystemUncached (host memory outside VRAM, write-combined). The GPU reads the system-memory + // kinds over the bus. Set before the first allocation. + static constexpr int kDeviceLocal = 0, kSystemCached = 1, kSystemUncached = 2; + void set_system_memory(int kind) { system_memory_ = kind; } + int system_memory() const { return system_memory_; } VkDeviceSize reserved() const { return reserved_; } // f(device address, capacity) for each live block; from any thread. template @@ -186,10 +221,26 @@ class TitleBufferWindows { // story load the driver refused every 4 MiB device-local, host-visible block with a device address // (VK_ERROR_OUT_OF_HOST_MEMORY, speed-8/-9) while host memory still served: once that happens, later blocks // go straight to host memory instead of through DeviceState::allocate's sleeping retries first. + // A device_local request under set_system_memory takes system memory instead, out of the types that are not + // device-local (memory_type_order would otherwise give the first host-visible type, which can be the BAR). VkMemoryPropertyFlags chosen = 0; - const bool want_local = device_local && !local_refused_; - b.memory = d.allocate(req, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, - want_local ? VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT : 0, &chosen, true); + const bool system = device_local && system_memory_ != kDeviceLocal; + const bool want_local = device_local && !local_refused_ && !system; + VkMemoryRequirements types = req; + if (system) types.memoryTypeBits = system_memory_types(d, req.memoryTypeBits, system_memory_ == kSystemCached); + b.memory = d.allocate(types, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, + want_local ? VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT + : system && system_memory_ == kSystemCached ? VK_MEMORY_PROPERTY_HOST_CACHED_BIT + : 0, + &chosen, true); + if (b.memory && system && !system_memory_logged_) { + system_memory_logged_ = true; + std::fprintf(stderr, "[rt] d3d12: title buffer copies in system memory (LEONIDA_GEOMETRY_HOST): memory " + "flags 0x%x (%s, %s)\n", + unsigned(chosen), + (chosen & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) ? "device-local: no other type" : "not VRAM", + (chosen & VK_MEMORY_PROPERTY_HOST_CACHED_BIT) ? "write-back" : "write-combined"); + } if (b.memory && want_local && !(chosen & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)) { local_refused_ = true; std::fprintf(stderr, "[rt] d3d12: title buffer windows: device-local memory refused a %llu KiB block; " diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index eabbd0cd1a..eedc0662e1 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -32,6 +32,7 @@ #include "dxgi_com.h" #include "../src/arena_size.h" #include "../src/value_write_sink.h" +#include "../src/address_guard.h" #include "../src/arena_blocks.h" #include "../src/gfx10_descriptors.h" #include "../src/depth24_fragment.h" @@ -47,6 +48,7 @@ #include "../src/pipeline_cache_file.h" #include "../src/pipeline_profile.h" #include "../src/submit_phases.h" +#include "../src/heavy_pipeline_cache.h" #include "../src/pipeline_cache_store.h" #include "../src/pipeline_cache_journal.h" #include "../src/large_module_gate.h" @@ -65,6 +67,7 @@ #include "../src/spirv_f16_halves.h" #include "../src/spirv_stores.h" #include "../src/title_va_alias.h" +#include "../src/console_heap_copy.h" #include "../src/console_heap_vsharp_slots.h" #include "../src/title_window_plan.h" #include "../src/vulkan_present.h" @@ -127,6 +130,8 @@ constexpr VkDeviceSize kZeroPage = 64 * 1024; // zeroed: what unbound vertex an constexpr auto kQuadIndicesPerQuad = std::uint32_t(leonida::quad_triangle_indices.size()); constexpr std::uint32_t kQuadIndexCount = 16 * 1024 * kQuadIndicesPerQuad; constexpr VkDeviceSize kArenaReserved = kZeroPage + VkDeviceSize(kQuadIndexCount) * sizeof(std::uint32_t); +// LEONIDA_ADDRESS_GUARD's header and sinks follow the quad indices (src/address_guard.h). +static_assert(kArenaReserved <= leonida::address_guard::kGuardHeader); 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); @@ -159,6 +164,18 @@ void log_once(const char* what, int value) { if (first_diagnostic(what, value)) std::fprintf(stderr, "[rt] d3d12: %s %d\n", what, value); } +// LEONIDA_ADDRESS_GUARD=1: the address guard (docs/d3d12_vulkan.md, "Address guard"). The arena keeps its guard +// header and sinks at heap_base + 0x70000..0x80000 and a page table of every backing outside it is kept current +// before each submission, so shaders translated with `rdna2spirv.py --address-guard` read 0 from, and drop stores +// to, an address nothing backs. Without it those shaders find no header and check nothing. +bool address_guard_enabled() { + static const bool on = [] { + wchar_t value[2]{}; + return GetEnvironmentVariableW(L"LEONIDA_ADDRESS_GUARD", value, 2) == 1 && value[0] == L'1'; + }(); + return on; +} + // Matches the offset interpretation of the selected shader pack. bool signed_vsharp_offsets() { static const bool on = [] { @@ -225,18 +242,24 @@ bool copy_guarded(std::uint8_t* to, const std::uint8_t* from, std::size_t bytes, // (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) { +#pragma pack(push, 1) +struct UnalignedWord64 { + std::uint64_t value; +}; +#pragma pack(pop) + +LEONIDA_GUARDED_NO_BUILTIN 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); + const std::uint64_t w = reinterpret_cast(at + i)->value; h = (h ^ w) * 0x100000001b3ull; h ^= h >> 29; } return h; } // The reads of hash_guarded, in a frame of its own: an inline load inside the __try is not covered by clang-cl -// without /EHa (src/guarded_copy.h). -__declspec(noinline) std::uint64_t hash_bytes(const std::uint8_t* p, std::size_t bytes, bool every_byte) { +// without /EHa, and a CRT memcpy call is not covered under Wine (src/guarded_copy.h). +__declspec(noinline) LEONIDA_GUARDED_NO_BUILTIN std::uint64_t hash_bytes(const std::uint8_t* p, std::size_t bytes, + bool every_byte) { std::uint64_t h = 0x9e3779b97f4a7c15ull ^ bytes; if (bytes <= (256u << 10) || every_byte) { h = mix_words(h, p, bytes & ~std::size_t(7)); @@ -373,6 +396,43 @@ class ShadowPages { ShadowPages(const ShadowPages&) = delete; ShadowPages& operator=(const ShadowPages&) = delete; + // What the GPU writes into the copies of [from, to) goes back to the title's pages: the pages are made writable + // first (the tracker guards them) and every target is copied from its shadow. Returns the bytes written. Called + // before the next refresh, so a page the title writes again is copied forward over the result, as on a GPU that + // shares the memory. + std::size_t write_back(std::uintptr_t from, std::uintptr_t to) { + from = std::max(from, first_), to = std::min(to, last_); + if (from >= to) return 0; + AcquireSRWLockExclusive(&lock_); + // A page the title wrote since it was last copied holds the newer bytes already: its GPU result is dropped and + // the refresh's own copy carries the title's. A guarded page (read-only since that copy) or one asked about and + // found unchanged takes the GPU's. + const auto held = [&](std::size_t i) { + const std::uint8_t s = state_[i]; + return (s & kZero) || (!(s & kProtected) && !(s & kClean)); + }; + std::size_t written = 0; + for (std::uintptr_t at = from & ~(kPage - 1); at < ((to + kPage - 1) & ~(kPage - 1));) { + std::size_t pages = 0; + while (at + (pages + 1) * kPage <= ((to + kPage - 1) & ~(kPage - 1)) && + held((at - first_) / kPage + pages) == held((at - first_) / kPage)) + ++pages; + if (!held((at - first_) / kPage)) { + const std::uintptr_t a = std::max(at, from), b = std::min(at + pages * kPage, to); + reopen_locked(at, at + pages * kPage); + for (const Target& t : targets_) { + const std::uintptr_t x = std::max(a, t.begin), y = std::min(b, t.end); + if (x >= y || !t.shadow) continue; + std::memcpy(reinterpret_cast(x), t.shadow + (x - t.begin), y - x); + written += y - x; + } + } + at += pages * kPage; + } + ReleaseSRWLockExclusive(&lock_); + return written; + } + // 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(); } @@ -1387,6 +1447,30 @@ std::filesystem::path pipeline_cache_session_path() { return path; } +// The pipelines the offline seed does not have, kept next to it and written while the game runs +// (src/heavy_pipeline_cache.h). +std::filesystem::path pipeline_cache_heavy_path() { + std::filesystem::path path = pipeline_cache_path(); + if (!path.empty()) path.replace_filename(L"pipeline_cache.heavy.bin"); + return path; +} + +// LEONIDA_HEAVY_PIPELINE_CACHE_MS: a compile at least this long schedules a write of the heavy cache; 0 turns the +// heavy cache off. One line for a value that is not a number. +std::uint32_t heavy_pipeline_cache_ms() { + static const std::uint32_t ms = [] { + char text[32] = {}; + size_t length = 0; + const bool present = getenv_s(&length, text, "LEONIDA_HEAVY_PIPELINE_CACHE_MS") == 0 && length > 1; + const auto threshold = leonida::heavy_pipeline_cache::parse_threshold(present ? text : ""); + if (!threshold.valid) + std::fprintf(stderr, "[rt] d3d12: LEONIDA_HEAVY_PIPELINE_CACHE_MS=%s is not a number of milliseconds; " + "using %u\n", text, threshold.ms); + return threshold.ms; + }(); + return ms; +} + std::size_t pipeline_cache_save_limit(); // LOCAL FIX (pipeline journal, pipeline_cache_journal.h): where each compute pipeline's own cache file goes, beside @@ -1670,6 +1754,66 @@ void save_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDev else std::fprintf(stderr, "[rt] d3d12: pipeline cache snapshot incomplete (%d); previous session retained\n", int(result)); } +// The heavy cache, seeded from pipeline_cache.heavy.bin when it is there and made for this device; empty otherwise. +VkPipelineCache create_heavy_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDevice device, + const leonida::cached_pso::Identity& identity) { + const auto path = pipeline_cache_heavy_path(); + clean_stale_cache_files(path); + VkPipelineCache cache = VK_NULL_HANDLE; + { + const PipelineCacheSeed seed(path); + if (seed.data() && seed.compatible(identity)) { + const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, nullptr, 0, + seed.size(), seed.data()}; + if (vk.vkCreatePipelineCache(device, &create, nullptr, &cache) == VK_SUCCESS) { + std::fprintf(stderr, "[rt] d3d12: loaded %zu bytes from pipeline_cache.heavy.bin\n", seed.size()); + return cache; + } + std::fprintf(stderr, "[rt] d3d12: Vulkan declined pipeline_cache.heavy.bin; starting it empty\n"); + } else if (seed.data()) { + std::fprintf(stderr, "[rt] d3d12: pipeline_cache.heavy.bin does not match this Vulkan device; starting " + "it empty\n"); + } + } + const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO}; + if (vk.vkCreatePipelineCache(device, &create, nullptr, &cache) != VK_SUCCESS) return VK_NULL_HANDLE; + return cache; +} + +// Writes the heavy cache whole: a staging file renamed over pipeline_cache.heavy.bin, so the file on disk is always +// a complete blob. It only holds what the offline seed missed, so it has no size limit of its own. +bool save_heavy_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDevice device, VkPipelineCache cache, + std::uint64_t compiles, std::uint64_t hits) { + if (!cache || !vk.vkGetPipelineCacheData) return false; + const auto path = pipeline_cache_heavy_path(); + if (path.empty()) return false; + const auto start = compile_us(); + std::size_t size = 0; + if (vk.vkGetPipelineCacheData(device, cache, &size, nullptr) != VK_SUCCESS || + size <= sizeof(VkPipelineCacheHeaderVersionOne)) + return false; + CacheStagingFile staging(path, size); + if (!staging.data) { + std::fprintf(stderr, "[rt] d3d12: could not map a staging file for %zu heavy pipeline cache bytes\n", size); + return false; + } + auto written = size; + const VkResult result = vk.vkGetPipelineCacheData(device, cache, &written, staging.data); + // VK_INCOMPLETE means the cache grew after the size query and the blob is a truncated snapshot; it must not + // replace a complete file. The writer tries again later with a fresh size. + const bool ok = result == VK_SUCCESS && written > sizeof(VkPipelineCacheHeaderVersionOne) && written <= size && + staging.publish(path, written); + if (ok) + std::fprintf(stderr, "[rt] d3d12: wrote %zu bytes to pipeline_cache.heavy.bin in %.1f s (%llu slow builds " + "and %llu other builds past the offline cache so far)\n", + written, double(compile_us() - start) / 1e6, static_cast(compiles), + static_cast(hits)); + else + std::fprintf(stderr, "[rt] d3d12: pipeline_cache.heavy.bin not written (%d); the previous file is kept\n", + int(result)); + return ok; +} + // 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), unless the translator's // partition-invariance tier says otherwise. Logged once per stage with the first shader's name, then again at 10, 100, @@ -2305,6 +2449,105 @@ struct DeviceState { return pipeline_cache_handle; } + // The heavy pipeline cache (src/heavy_pipeline_cache.h) and the thread that writes it. + std::once_flag heavy_cache_once; + VkPipelineCache heavy_cache_handle = VK_NULL_HANDLE; + std::mutex heavy_mutex; + std::condition_variable heavy_wake; + leonida::heavy_pipeline_cache::WriteSchedule heavy_schedule; // under heavy_mutex + bool heavy_stop = false; // under heavy_mutex + std::thread heavy_writer; // started at the first slow build + std::atomic heavy_compiles{0}, heavy_hits{0}; + std::atomic heavy_changed{false}; // a build went into the heavy cache since it was loaded + + VkPipelineCache heavy_cache() { + std::call_once(heavy_cache_once, [this] { + if (context->vk.vkCreatePipelineCache) + heavy_cache_handle = create_heavy_pipeline_cache(context->vk, info.device, pso_identity); + }); + return heavy_cache_handle; + } + + // A build past the offline cache took `took_ms`: a slow one schedules a write. + void note_heavy_build(ULONGLONG took_ms) { + heavy_changed = true; + if (took_ms < heavy_pipeline_cache_ms()) { + ++heavy_hits; + return; + } + ++heavy_compiles; + std::lock_guard lock(heavy_mutex); + if (heavy_stop) return; + heavy_schedule.note_heavy(GetTickCount64()); + if (!heavy_writer.joinable()) { + try { + heavy_writer = std::thread([this] { write_heavy_cache_loop(); }); + } catch (const std::exception&) { + return; // no thread: the cache is still written at teardown + } + } + heavy_wake.notify_one(); + } + + void write_heavy_cache_loop() { + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL); + std::unique_lock lock(heavy_mutex); + while (!heavy_stop) { + if (!heavy_schedule.dirty()) { + heavy_wake.wait(lock); + continue; + } + const std::uint64_t now = GetTickCount64(); + if (!heavy_schedule.due(now)) { + heavy_wake.wait_for(lock, std::chrono::milliseconds(heavy_schedule.due_ms() - now)); + continue; + } + const std::uint64_t generation = heavy_schedule.generation(); + lock.unlock(); + const bool saved = save_heavy_pipeline_cache(context->vk, info.device, heavy_cache_handle, + heavy_compiles.load(), heavy_hits.load()); + lock.lock(); + // A failed write leaves the cache dirty: it is tried again after a growing delay, not only at teardown. + if (saved) heavy_schedule.written(generation, now); + else heavy_schedule.failed(now); + } + } + + // At device teardown, with no build running: stop the writer and write the cache if any build went into it. + // Fast builds never schedule a write, so this is where they are kept: without an offline seed every build is + // a miss, and these are the builds pipeline_cache.session.bin used to keep. + void finish_heavy_cache() { + { + std::lock_guard lock(heavy_mutex); + heavy_stop = true; + } + heavy_wake.notify_all(); + if (heavy_writer.joinable()) heavy_writer.join(); + if (!heavy_cache_handle) return; + if (heavy_changed.load() && !active_compiles.load()) + save_heavy_pipeline_cache(context->vk, info.device, heavy_cache_handle, heavy_compiles.load(), + heavy_hits.load()); + context->vk.vkDestroyPipelineCache(info.device, heavy_cache_handle, nullptr); + heavy_cache_handle = VK_NULL_HANDLE; + } + + // vkCreateGraphicsPipelines through `create(cache, flags)` (compute pipelines have their journal). With the heavy + // cache, the offline cache is asked first without compiling; a pipeline it does not have is built against the heavy + // cache, which a slow build then writes back to disk. A caller that already asked for a cache-only create keeps it. + template + VkResult create_pipeline(VkPipelineCreateFlags flags, Create&& create) { + constexpr VkPipelineCreateFlags cache_only = VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT; + const VkPipelineCache corpus = pipeline_cache(); + if (!info.heavy_pipeline_cache || (flags & cache_only)) return create(corpus, flags); + const VkResult cached = create(corpus, flags | cache_only); + if (cached != VK_PIPELINE_COMPILE_REQUIRED) return cached; + const VkPipelineCache heavy = heavy_cache(); + const ULONGLONG started = GetTickCount64(); + const VkResult built = create(heavy ? heavy : corpus, flags); + if (built == VK_SUCCESS && heavy) note_heavy_build(GetTickCount64() - started); + return built; + } + QueueClock clock; // device-wide calibration entry points std::vector timestamp_bits; @@ -2442,6 +2685,7 @@ struct DeviceState { if (!pages) return; const leonida::submit_phases::Scope timed(leonida::submit_phases::shadows); std::lock_guard lock(shadow_mutex); + write_back_titles(); // what the last submission wrote in the copies, before the forward copy below if (shadows.empty()) return; const auto start = clock::now(); // LEONIDA_SHADOW_ALIAS_MS (0 by default: every submission): pages xmem maps at two addresses, which no guard @@ -2568,7 +2812,24 @@ struct DeviceState { 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; - // The stream pools' mappings (title_gpu_views): one per readable run of a pool, kept for the device's life. + // What the GPU wrote into a copy of the title's memory goes back to the title's pages: the ranges reached since + // the last submission (title_va_alias.h note_reached), copied back at the next refresh before the forward copy. + // A window is a read-side mirror, so without this a UAV or a raw write lands in the copy and the title never sees + // it (#1537, the WRITE_INVALID stop at the world start). + std::mutex title_write_back_mutex; // its own: taken under shadow_mutex, never the other way round + std::map title_write_back; // start -> end, of the submission about to run + std::deque>> title_write_back_pending; // by ticket + std::uint64_t title_write_back_refused = 0; // ranges past the caps, logged once + std::uint64_t title_write_back_bytes = 0; // queued for this submission + std::uint64_t title_write_back_total = 0; // copied back, all submissions + std::uint64_t title_write_back_calls = 0; // log line count + std::uint64_t title_write_back_unfenced = 0; + static constexpr std::size_t kTitleWriteBackBatches = 64; // pending batches before the oldest goes back unfenced + static constexpr std::size_t kTitleWriteBackRanges = 8192; // ranges kept per submission + static constexpr std::uint64_t kTitleWriteBackBytes = 64ull << 20; // bytes copied back per submission + // The stream pools' mappings (title_gpu_views): one per readable run of a pool. A window is kept for the device's + // life; a geometry copy goes when its view is retired (the pages were freed, unmapped or remapped: + // drain_geometry_releases), and the next request for those pages makes a new one. struct PoolSpan { std::uint64_t source; // the readable side of the pair the copy is made from std::uint64_t twin; // the extent's address in the pair's other view (0 when there is none) @@ -2579,6 +2840,7 @@ struct DeviceState { std::vector pool_spans; std::atomic pool_span_count{0}; std::uint64_t pool_span_bytes = 0; + std::uint64_t pool_spans_retired = 0; // geometry-copy extents whose view was retired (forget_pool_span) std::uint64_t title_window_refusals = 0; // windows neither the budget nor the arena allowed std::uint64_t unbacked_requests = 0; // title addresses no backing could be made for (zero-size views) @@ -2600,26 +2862,67 @@ struct DeviceState { // another queue's replay that translated its slots before this retirement may still name it. A ticket read here // would be one short of this submission, which records its own only after before_execute_ (and with an idle GPU // the view would be reaped in this very call). + // A retired view's last copy is made here from the title's pages as they are now (GeometryViews::retire_range): a + // range the title remapped (xmem's RemapReleases) holds its new bytes, which the refresh below would have copied. + // A stream-pool extent it backed leaves pool_spans: the next request for those pages makes a new mapping. void drain_geometry_releases() { if (!context || !geometry.has_pending_reclaim()) return; const std::uint64_t completed_ticket = geometry.has_retired() ? context->completed_retire_ticket() : 0; - geometry.drain_released(*this, rt::d3d12::GeometryViews::kAfterExecutes, completed_ticket, - forget_geometry_alias); + geometry.drain_released( + *this, rt::d3d12::GeometryViews::kAfterExecutes, completed_ticket, + [this](std::uintptr_t source, std::size_t size, VkDeviceSize va) { + forget_geometry_alias(source, size, va); + forget_pool_span(va); + }, + copy_geometry); + } + void forget_pool_span(VkDeviceSize va) { + std::lock_guard windows(title_window_mutex); + const auto it = std::find_if(pool_spans.begin(), pool_spans.end(), + [&](const PoolSpan& span) { return span.geometry && span.shader_va == va; }); + if (it == pool_spans.end()) return; + pool_span_bytes -= it->size; + pool_spans.erase(it); + pool_span_count.store(pool_spans.size(), std::memory_order_relaxed); + ++pool_spans_retired; } // ExecuteCommandLists replays in progress, for GeometryViews::kAfterExecutes (see drain_geometry_releases). - static std::vector& geometry_execute_serials() { - thread_local std::vector serials; + // A plain aggregate on purpose: a C++ thread_local with a destructor in gta6rt.exe adds TLS callbacks to the image + // the loader's TLS index-0 move must not have (pe_loader.cpp reserve_tls_index0; VulkanContext::stage_xdxr_table + // keeps its range list a member for the same reason). A std::vector here made the title's CRT abort at startup. + struct GeometryExecuteSerials { + static constexpr unsigned kCapacity = 32; // a replay has not been seen nested this deep + std::uint64_t serials[kCapacity]{}; + unsigned count{}; + unsigned skipped{}; // replays begun while the stack was full: the innermost, ended first + }; + static GeometryExecuteSerials& geometry_execute_serials() { + thread_local GeometryExecuteSerials serials; return serials; } void geometry_execute_begin() { if (!geometry.cap()) return; - geometry_execute_serials().push_back(geometry.execute_begin()); + auto& serials = geometry_execute_serials(); + if (serials.count == GeometryExecuteSerials::kCapacity) { + static std::atomic logged{false}; + if (!logged.exchange(true)) + std::fprintf(stderr, "[rt] d3d12: ExecuteCommandLists nested more than %u deep; a geometry view retired " + "in the extra replay is not deferred to it\n", + GeometryExecuteSerials::kCapacity); + ++serials.skipped; + return; + } + serials.serials[serials.count++] = geometry.execute_begin(); } void geometry_execute_end() { + if (!geometry.cap()) return; auto& serials = geometry_execute_serials(); - if (!geometry.cap() || serials.empty()) return; - const std::uint64_t serial = serials.back(); - serials.pop_back(); + if (serials.skipped != 0) { + --serials.skipped; + return; + } + if (serials.count == 0) return; + const std::uint64_t serial = serials.serials[--serials.count]; geometry.execute_end(serial, [this] { return context->submitted_retire_ticket(); }); } static rt::d3d12::GeometryCopy copy_geometry(std::uint8_t* to, const std::uint8_t* from, std::size_t size) { @@ -2733,6 +3036,93 @@ struct DeviceState { return offset; } + // A binding of the title's memory reached for the coming submission: keep its range for the copy back after it. + // Over-inclusive on purpose (a read-only view costs a copy, a write is never missed: a V# has no read/write bit). + void note_title_write(std::uint64_t va, std::uint64_t bytes) { + static const bool on = [] { + char value[2] = {}; + std::size_t length = 0; + return getenv_s(&length, value, sizeof(value), "LEONIDA_TITLE_WRITEBACK") != 0 || value[0] != '0'; + }(); + if (!on || !va || !bytes) return; + std::uint64_t lo = 0, hi = 0; + if (!leonida::title_va_aliases().title_memory(va, lo, hi) || va >= hi) return; + const std::uint64_t end = va + std::min(bytes, hi - va); + std::lock_guard lock(title_write_back_mutex); + auto it = title_write_back.lower_bound(va); + if (it != title_write_back.begin()) { + auto previous = std::prev(it); + if (previous->second >= va) { + if (previous->second < end) previous->second = end; + return; + } + } + if (it != title_write_back.end() && it->first <= end) { + it->second = std::max(it->second, end); + return; + } + if (title_write_back.size() >= kTitleWriteBackRanges || title_write_back_bytes >= kTitleWriteBackBytes) { + if (!title_write_back_refused++) + log_once("past LEONIDA_TITLE_WRITEBACK's caps: reached ranges are not copied back this submission; " + "ranges refused:", + 1); + return; + } + title_write_back_bytes += end - va; + title_write_back.emplace(va, end); + } + + // What the GPU wrote into those copies goes back to the title's pages, so a later read by the title or the next + // forward copy sees it. Only once the submission that wrote them has completed: a batch carries the ticket of the + // submission after it (a submission's commands are recorded before it exists), and is copied back when the + // context reports that ticket done. Runs at the start of a refresh, under shadow_mutex and before the forward + // copies, so a page the title wrote again is copied forward over the result. + void write_back_titles() { + if (!&context) return; + const std::uint64_t done = context->completed_retire_ticket(); + std::vector> finished; // one entry per range, collected under the lock + { + std::lock_guard lock(title_write_back_mutex); + if (!title_write_back.empty()) { + // The ranges of the submission about to execute, which is the next ticket. + title_write_back_pending.push_back({context->submitted_retire_ticket() + 1, + std::move(title_write_back)}); + title_write_back.clear(); + title_write_back_bytes = 0; + } + bool forced = false; + while (!title_write_back_pending.empty() && + (title_write_back_pending.front().first <= done || + title_write_back_pending.size() > kTitleWriteBackBatches)) { + forced = forced || title_write_back_pending.front().first > done; + for (const auto& [begin, end] : title_write_back_pending.front().second) + finished.push_back({begin, end}); + title_write_back_pending.pop_front(); + } + // A queue held deep (console ordering) can leave batches waiting: the oldest go back anyway, once each. + if (forced && !title_write_back_unfenced++) + log_once("more than 64 title write-back batches wait on their submissions: the oldest are copied " + "back without their ticket; batches:", + 1); + } + if (finished.empty()) return; + std::uint64_t written = 0, ranges = 0; + for (const auto& [begin, end] : finished) + for (const ShadowPagesPtr& s : shadows) + if (end > s->first() && begin < s->last()) { + const std::uint64_t bytes = s->write_back(begin, end); + written += bytes; + ranges += bytes != 0; + } + title_write_back_total += written; + if (!written) return; + if (++title_write_back_calls <= 4 || !(title_write_back_calls & (title_write_back_calls - 1))) + std::fprintf(stderr, "[rt] d3d12: %llu KiB of the GPU's writes in %llu reached range(s) went back to the " + "title's pages (%llu KiB so far)\n", + static_cast(written >> 10), static_cast(ranges), + static_cast(title_write_back_total >> 10)); + } + // A stream pool's address (a CPU view paired with a GPU-only alias). Rule B // first: the CPU view is where the host reads the frames, so that is what the copy is made from; the GPU-only // pages are the same frames through the title's queue slot 31 and are read only when the CPU view is not @@ -3471,6 +3861,45 @@ struct DeviceState { static constexpr unsigned kVsharpPathCount = 6; std::array, kVsharpPathCount> vsharp_paths{}; + // LEONIDA_UNBACKED_VSHARP=1 (diagnostic): the buffer V#s fix_vsharp writes empty because nothing backs their base. + // One line for each of the first 120 distinct bases (span and stride), and every 8192 such V#s a summary by 4 GiB + // range of the base, so the address ranges the world's data comes from can be compared with the title memory. + static void note_unbacked_vsharp(uint64_t base, uint64_t span, uint32_t stride, const uint32_t* w) { + static const bool on = [] { + const char* v = std::getenv("LEONIDA_UNBACKED_VSHARP"); + return v && *v == '1'; + }(); + if (!on) return; + static std::mutex mutex; + static std::unordered_map seen; // base -> span + static std::map by_range; // base >> 32 -> distinct bases + static uint64_t count = 0; + std::lock_guard lock(mutex); + ++count; + if (seen.emplace(base, span).second) { + ++by_range[base >> 32]; + if (seen.size() <= 120) + std::fprintf(stderr, + "[rt] unbacked-vsharp: #%zu base 0x%llx span %llu stride %u words %08x %08x %08x %08x\n", + seen.size(), static_cast(base), static_cast(span), + stride, w[0], w[1], w[2], w[3]); + } + if (!(count % 8192)) { + std::vector> top; + for (const auto& [range, n] : by_range) top.emplace_back(n, range); + std::sort(top.rbegin(), top.rend()); + std::string text; + char item[64]; + for (std::size_t i = 0; i < top.size() && i < 10; ++i) { + std::snprintf(item, sizeof(item), "%s0x%llx00000000 x%llu", i ? "; " : "", + static_cast(top[i].second), static_cast(top[i].first)); + text += item; + } + std::fprintf(stderr, "[rt] unbacked-vsharp: %llu empty V#s, %zu distinct bases; by 4 GiB range: %s\n", + static_cast(count), seen.size(), text.c_str()); + } + } + VsharpResult fix_vsharp(uint32_t* w, VsharpPath path) { if ((w[3] >> 30) || !w[2]) return VsharpResult::unchanged; // image, empty slot or raw pointer const uint64_t base = uint64_t(w[0]) | (uint64_t(w[1] & 0xffff) << 32); @@ -3490,6 +3919,7 @@ struct DeviceState { std::fprintf(stderr, "[rt] d3d12: %s V# at 0x%llx (%llu bytes) has no GPU backing; zero records\n", where, (unsigned long long)base, (unsigned long long)span); } + note_unbacked_vsharp(base, span, stride, w); w[0] = w[1] = w[2] = 0; return VsharpResult::empty; } @@ -3685,13 +4115,13 @@ struct DeviceState { [](const PoolSpan& span) { return span.geometry; }); std::fprintf(stderr, "[rt] d3d12: title memory: %zu windows (%llu KiB of a %llu MiB budget, %llu refused), %zu " - "stream-pool extents (one mapping each, %llu KiB; %lld by geometry copy), %llu addresses " - "given a zero-size view\n", + "stream-pool extents (one mapping each, %llu KiB; %lld by geometry copy, %llu retired with " + "their copy), %llu addresses given a zero-size view\n", title_windows.size(), static_cast(title_window_bytes >> 10), static_cast(title_window_cap >> 20), static_cast(title_window_refusals), pool_spans.size(), static_cast(pool_span_bytes >> 10), - static_cast(geometry_spans), + static_cast(geometry_spans), static_cast(pool_spans_retired), static_cast(unbacked_requests)); } } @@ -3758,7 +4188,10 @@ struct DeviceState { VkDeviceSize guard = 0; // null bytes after the GPU copy (heap_guard_bytes/heap_guard_for), its allocation bool resource_heap = false; // a CBV/SRV/UAV heap; a sampler heap's S#s are copied as written bool imported = false; - std::uint8_t* copy = nullptr; // writable GPU mirror of the console heap + // The translated copy shaders read, and its host-RAM mirror (src/console_heap_copy.h): written only through + // copy.write()/copy.zero(), read on the CPU only through copy.view(). + leonida::ConsoleHeapCopy copy; + std::uint64_t mirror_checks = 0, mirror_mismatches = 0; // LEONIDA_HEAP_MIRROR_CHECK, since the last log line // Keep large scratch allocations out of the low addresses the title can use for its heap. std::unique_ptr scratch; std::uint8_t* input{}; @@ -3937,7 +4370,7 @@ struct DeviceState { } if (empty) heap.empty_slots.insert(std::uint32_t(slot)); else if (!heap.empty_slots.empty()) heap.empty_slots.erase(std::uint32_t(slot)); - std::memcpy(heap.copy + slot * kDescriptorSize, w, kDescriptorSize); + heap.copy.write(slot * kDescriptorSize, w, kDescriptorSize); heap.live_vsharps.set(slot, leonida::ConsoleHeapVsharpSlots::is_live_vsharp(w)); return settled; } @@ -3985,7 +4418,7 @@ struct DeviceState { }(); const std::size_t end = std::min(offset + bytes, std::size_t(heap.bytes)); if (!heap.resource_heap) { - std::memcpy(heap.copy + offset, heap.input + offset, end - offset); + heap.copy.write(offset, heap.input + offset, end - offset); return; } for (std::size_t at = offset & ~std::size_t(kDescriptorSize - 1); at + kDescriptorSize <= end; @@ -3998,8 +4431,14 @@ struct DeviceState { if (budget_us && !heap.fix_over && !(++heap.fix_count & 15) && std::chrono::steady_clock::now() - heap.fix_start >= std::chrono::microseconds(budget_us)) heap.fix_over = true; - if (heap.fix_over) { - std::memset(heap.copy + at, 0, kDescriptorSize); + // Buffer V#s (!(w3 >> 30)) only rebase address offsets, so they are fast and must never be + // deferred or nulled: at the first world frame lib_cs_01144 reads its loop bound from a buffer + // slot; nulling it causes an infinite loop and device loss. Only image T#s are deferred past budget. + std::uint32_t w3 = 0; + std::memcpy(&w3, heap.previous + at + 12, sizeof(w3)); + const bool is_buffer_vsharp = !(w3 >> 30); + if (heap.fix_over && !is_buffer_vsharp) { + heap.copy.zero(at, kDescriptorSize); heap.live_vsharps.clear(slot); ++heap.deferred_fixes; if (!heap.retry[slot]) { @@ -4092,6 +4531,59 @@ struct DeviceState { unbound_tsharp_tracker().note(heap.console_va, offset, words, why); } + // LEONIDA_HEAP_MIRROR=0: no host-RAM mirror of a console heap's copy in the arena (src/console_heap_copy.h); the + // release sweep then reads the copy itself, as before the mirror. + static bool heap_mirror_enabled() { + static const bool on = [] { + char value[4] = {}; + return !(GetEnvironmentVariableA("LEONIDA_HEAP_MIRROR", value, sizeof(value)) == 1 && value[0] == '0'); + }(); + return on; + } + // LEONIDA_HEAP_MIRROR_CHECK=1: the mirror compared with the copy at every release sweep (it reads the whole copy, + // so it costs what the mirror saves), the first slots that differ logged. + static bool heap_mirror_check_enabled() { + static const bool on = [] { + char value[4] = {}; + return GetEnvironmentVariableA("LEONIDA_HEAP_MIRROR_CHECK", value, sizeof(value)) == 1 && value[0] == '1'; + }(); + return on; + } + // The slots whose mirror differs from the copy (0: none, or no mirror); the first few logged, for the first + // sweeps that find any. + std::size_t check_console_heap_mirror(ConsoleHeap& heap) { // console_heap_mutex held + if (!heap.copy.mirrored()) return 0; + constexpr std::size_t kShown = 8; + std::vector slots; + const std::size_t count = heap.copy.mismatches(kDescriptorSize, kShown, slots); + ++heap.mirror_checks; + heap.mirror_mismatches += count; + static std::atomic reports{0}; + if (count && reports.fetch_add(1, std::memory_order_relaxed) < 16) { + std::fprintf(stderr, "[rt] d3d12: LEONIDA_HEAP_MIRROR_CHECK: console descriptor heap 0x%llx: %zu slots of " + "the host mirror differ from the copy\n", + static_cast(heap.console_va), count); + for (const std::size_t slot : slots) { + std::uint32_t mirror[8], copy[8]; + std::memcpy(mirror, heap.copy.view() + slot * kDescriptorSize, sizeof(mirror)); + std::memcpy(copy, heap.copy.gpu() + slot * kDescriptorSize, sizeof(copy)); + std::fprintf(stderr, "[rt] d3d12: slot %zu: mirror %08x %08x %08x %08x %08x %08x %08x %08x, copy %08x " + "%08x %08x %08x %08x %08x %08x %08x\n", + slot, mirror[0], mirror[1], mirror[2], mirror[3], mirror[4], mirror[5], mirror[6], mirror[7], + copy[0], copy[1], copy[2], copy[3], copy[4], copy[5], copy[6], copy[7]); + } + } + return count; + } + // Tests: the mirror of the console heap at `console_va` compared with its copy now. -1: no such heap, or no mirror. + long long console_heap_mirror_mismatches(std::uint64_t console_va) { + std::lock_guard lock(console_heap_mutex); + for (const auto& heap : console_heaps) + if (heap->console_va == console_va) + return heap->copy.mirrored() ? static_cast(check_console_heap_mirror(*heap)) : -1; + return -1; + } + void refresh_console_heap(ConsoleHeap& heap) { // console_heap_mutex held if (heap.imported) return; // directly imported sampler heap if (heap.gpu >= 0) return refresh_console_heap_gpu(heap); @@ -4102,7 +4594,7 @@ struct DeviceState { const auto t0 = clock::now(); 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); + heap.copy.zero(offset, bytes); std::memset(heap.previous + offset, 0, bytes); const auto first = std::uint32_t(offset / kDescriptorSize); const auto end = std::uint32_t((offset + bytes) / kDescriptorSize); @@ -4153,13 +4645,16 @@ struct DeviceState { ++heap.rescans; const auto rescan_start = clock::now(); // Even an unchanged title slot may name a buffer released since the last submission. - // Walk the host-RAM V# bitset instead of reading every slot of `heap.copy` (which may be uncached WC VRAM). + // Walk the host-RAM V# bitset instead of reading every slot of `heap.copy` (which may be uncached WC VRAM), + // and read the copy's words from its host-RAM mirror. + if (heap_mirror_check_enabled()) check_console_heap_mirror(heap); + const std::uint8_t* const translated = heap.copy.view(); heap.live_vsharps.for_each([&](std::size_t slot) { ++heap.release_candidates; if (filtered) { const auto at = slot * kDescriptorSize; const auto* src = reinterpret_cast(heap.previous + at); - const auto* dst = reinterpret_cast(heap.copy + at); + const auto* dst = reinterpret_cast(translated + at); if (!affected(src, dst) && !affected(src + 4, dst + 4)) return; } ++heap.release_fixes; @@ -4248,6 +4743,13 @@ struct DeviceState { (unsigned long long)heap->release_fixes, (unsigned long long)heap->release_rebases, (unsigned long long)heap->release_full); heap->release_sweeps = heap->release_candidates = heap->release_fixes = heap->release_rebases = heap->release_full = 0; + if (heap_mirror_check_enabled() && heap->copy.mirrored()) + std::fprintf(stderr, "[rt] d3d12: LEONIDA_HEAP_MIRROR_CHECK: console descriptor heap 0x%llx: %llu " + "checks, %llu slots differing in all\n", + static_cast(heap->console_va), + static_cast(heap->mirror_checks), + static_cast(heap->mirror_mismatches)); + heap->mirror_checks = heap->mirror_mismatches = 0; if (heap->resource_heap) { std::uint64_t paths[kVsharpPathCount]; for (unsigned i = 0; i < kVsharpPathCount; ++i) @@ -4405,7 +4907,7 @@ struct DeviceState { heap->input = heap->scratch.get(); heap->previous = heap->scratch.get() + bytes; heap->shader_va = offset; - heap->copy = arena.mapped + offset; + heap->copy.attach(arena.mapped + offset, std::size_t(bytes), heap_mirror_enabled()); heap->guard = guard; heap->imported = false; in_arena = true; @@ -4428,7 +4930,7 @@ struct DeviceState { if (heap->scratch) { auto* backing = heap->scratch.get(); if (import_console_heap(*heap, reinterpret_cast(backing), bytes + guard)) { - heap->copy = backing; + heap->copy.attach(backing, std::size_t(bytes), false); // host RAM already: no mirror heap->guard = guard; } heap->input = backing + bytes + guard; @@ -4465,9 +4967,10 @@ struct DeviceState { "a heap index past it reads the arena's next bytes; guard MiB", int(guard >> 20)); heap->shader_va = offset; - heap->copy = arena.mapped + offset; + // A sampler heap's copy is read by no CPU sweep: no mirror. + heap->copy.attach(arena.mapped + offset, std::size_t(bytes), resource_heap && heap_mirror_enabled()); } - std::memset(heap->copy, 0, std::size_t(bytes + heap->guard)); + heap->copy.zero(0, std::size_t(bytes + heap->guard)); if (!heap->input) { heap->mirror.assign(std::size_t(bytes), 0); heap->made.assign(std::size_t(bytes), 0); @@ -5009,6 +5512,7 @@ struct DeviceState { return; } heap.gpu = index; + heap.copy.drop_mirror(); // the pass writes the copy from now on; the CPU neither writes nor reads it heap.vsharp_bits.assign((heap.bytes / kDescriptorSize + 63) / 64, 0); std::fprintf(stderr, "[rt] d3d12: LEONIDA_CONSOLE_HEAP_GPU: console descriptor heap 0x%llx (%llu slots) is " "translated by the pass (heap %d)\n", @@ -5319,6 +5823,148 @@ struct DeviceState { gpu_counts.backed_ms += std::chrono::duration(std::chrono::steady_clock::now() - start).count(); } + // LEONIDA_ADDRESS_GUARD=1 (docs/d3d12_vulkan.md, "Address guard"): the page table the guarded shaders read, a + // host-visible buffer of its own whose address minus heap_base is in the guard header at arena offset + // kGuardHeader. Built from the same backings as the console heap pass's backed table (gpu_backings, the + // geometry copies' blocks and the separate window buffers), but whole and at once: a backing made since the last + // submission must not read 0. + struct AddressGuard { + VkBuffer buffer = VK_NULL_HANDLE; + VkDeviceMemory memory = VK_NULL_HANDLE; + std::uint32_t* words = nullptr; + std::unique_ptr table; + std::uint64_t generation = ~0ull, blocks = ~0ull, heaps = ~0ull; // heaps: the console heaps' ranges, hashed + std::uint32_t refused_logged = 0, overflow_logged = 0; + std::uint64_t updates = 0, words_written = 0; + std::chrono::steady_clock::time_point logged{}; + std::mutex mutex; + } guard; + + // Make the page table and write the header (called once the arena is mapped). False leaves the guard off: the + // header keeps no magic, so guarded shaders check nothing. + bool create_address_guard() { + namespace ag = leonida::address_guard; + if (!context || !arena.mapped || arena.size < ag::kGuardEnd) return false; + auto& vk = context->vk; + guard.table = std::make_unique(); + VkBufferCreateInfo create{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; + create.size = guard.table->bytes(); + create.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; + create.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + if (vk.vkCreateBuffer(info.device, &create, nullptr, &guard.buffer) != VK_SUCCESS) { + guard.buffer = VK_NULL_HANDLE; + return false; + } + VkMemoryRequirements requirements{}; + vk.vkGetBufferMemoryRequirements(info.device, guard.buffer, &requirements); + guard.memory = allocate(requirements, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, nullptr, true); + void* mapped = nullptr; + if (!guard.memory || vk.vkBindBufferMemory(info.device, guard.buffer, guard.memory, 0) != VK_SUCCESS || + vk.vkMapMemory(info.device, guard.memory, 0, VK_WHOLE_SIZE, 0, &mapped) != VK_SUCCESS) { + destroy_address_guard(); + return false; + } + guard.words = static_cast(mapped); + std::memcpy(guard.words, guard.table->words().data(), guard.table->bytes()); + VkBufferDeviceAddressInfo address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; + address.buffer = guard.buffer; + const VkDeviceAddress table = vk.vkGetBufferDeviceAddress(info.device, &address); + auto* header = reinterpret_cast(arena.mapped + ag::kGuardHeader); + std::memset(arena.mapped + ag::kGuardHeader, 0, std::size_t(ag::kGuardEnd - ag::kGuardHeader)); + header->limit = arena.size; + header->table = table - arena.address; + std::atomic_thread_fence(std::memory_order_release); + header->magic = ag::magic(); // last: a shader that sees it sees the rest + std::fprintf(stderr, "[rt] d3d12: address guard on (LEONIDA_ADDRESS_GUARD): %llu KiB page table, header at " + "heap_base + 0x%llx; shaders translated with --address-guard read 0 from memory nothing " + "backs and drop their stores there\n", + static_cast(guard.table->bytes() >> 10), + static_cast(ag::kGuardHeader)); + return true; + } + void destroy_address_guard() { + if (!context) return; + auto& vk = context->vk; + if (guard.buffer) vk.vkDestroyBuffer(info.device, guard.buffer, nullptr); + if (guard.memory) vk.vkFreeMemory(info.device, guard.memory, nullptr); + guard.buffer = VK_NULL_HANDLE; + guard.memory = VK_NULL_HANDLE; + guard.words = nullptr; + } + + // Before each submission: the page table says exactly what is backed now, and refusals since the last line are + // logged (at most once a second). Rebuilt only when a backing came or went; only changed words are written. + void update_address_guard() { + namespace ag = leonida::address_guard; + if (!guard.words) return; + // A console descriptor heap whose GPU copy lies outside the arena (an import of the title's pages, which + // shaders read at shader_va = its device address minus heap_base) is read through heap_base + VA like a + // buffer, but no gpu_backing names it: its bytes and the null guard after them are entered here. Without + // this the guard refused every descriptor-table load from such a heap (run 28: a 38 MB imported heap at + // shader VA 0x87e00000, past a 2 GiB arena). Collected before guard.mutex, in console_heap_mutex's order. + std::vector> heap_spans; + std::uint64_t heap_signature = 0xcbf29ce484222325ull; + { + std::lock_guard heaps(console_heap_mutex); + for (const auto& h : console_heaps) { + if (!h || !h->bytes) continue; + const std::uint64_t begin = h->shader_va, end = h->shader_va + h->bytes + h->guard; + heap_signature = (heap_signature ^ begin) * 0x100000001b3ull; + heap_signature = (heap_signature ^ end) * 0x100000001b3ull; + if (!(begin < arena.size && end <= arena.size)) heap_spans.emplace_back(begin, end); + } + } + std::lock_guard lock(guard.mutex); + const std::uint64_t generation = backing_generation.load(std::memory_order_relaxed); + const std::uint64_t blocks = geometry.pool().layout_generation() + external_windows.layout_generation(); + if (generation != guard.generation || blocks != guard.blocks || heap_signature != guard.heaps) { + guard.generation = generation; + guard.blocks = blocks; + guard.heaps = heap_signature; + std::vector> spans = heap_spans; + { + std::lock_guard backing_lock(backing_mutex); + gpu_backings.for_each([&](std::uint64_t va, std::uint64_t bytes) { + const std::uint64_t offset = va - arena.address; + // The arena's own ranges pass on the limit compare; only what lies outside needs pages. + if (bytes && !(offset < arena.size && bytes <= arena.size - offset)) + spans.emplace_back(offset, offset + bytes); + }); + } + const auto block = [&](VkDeviceAddress address, VkDeviceSize bytes) { + const std::uint64_t offset = address - arena.address; + if (address && bytes) spans.emplace_back(offset, offset + bytes); + }; + geometry.pool().for_each_block(block); + external_windows.for_each_block(block); + guard.words_written += guard.table->assign(spans, [&](std::size_t i, std::uint32_t v) { + std::atomic_ref(guard.words[i]).store(v, std::memory_order_relaxed); + }); + ++guard.updates; + if (guard.table->overflowed() != guard.overflow_logged) { + guard.overflow_logged = guard.table->overflowed(); + std::fprintf(stderr, "[rt] d3d12: address guard: %u 4 GiB chunk(s) of backings past the page table's " + "%u blocks are not checked\n", + guard.overflow_logged, guard.table->blocks_used()); + } + } + auto* header = reinterpret_cast(arena.mapped + ag::kGuardHeader); + const std::uint32_t refused = std::atomic_ref(header->refused).load(std::memory_order_relaxed); + const auto now = std::chrono::steady_clock::now(); + if (refused != guard.refused_logged && now - guard.logged >= std::chrono::seconds(1)) { + guard.logged = now; + std::fprintf(stderr, "[rt] d3d12: address guard: %u access(es) refused so far (+%u), the last at heap " + "offset 0x%llx by module 0x%08x; %llu table update(s), %llu word(s) written\n", + refused, refused - guard.refused_logged, + static_cast(header->last_refused), + std::atomic_ref(header->last_module).load(std::memory_order_relaxed), + static_cast(guard.updates), + static_cast(guard.words_written)); + guard.refused_logged = refused; + } + } + // The ask table: the title's memory and both addresses of its GPU-window pairs. A V# base outside them that the // other tables do not answer is one vsharp_address could only answer 0 for. void update_gpu_ask() { @@ -6972,6 +7618,12 @@ struct DeviceState { return nullptr; } }; +// TitleBufferWindows::system_memory_types reads the memory types through these (LEONIDA_GEOMETRY_HOST): without them +// it would leave every type allowed, the BAR included. +static_assert(requires(const DeviceState& d) { + d.memory.memoryTypes[0].propertyFlags; + d.memory.memoryTypeCount; +}); // The Vulkan format for a texture this layer can create, with the D24 fallback; VK_FORMAT_UNDEFINED, after a log // line, when it cannot. Committed and placed textures share it so both refuse the same formats for the same reason. @@ -11191,8 +11843,11 @@ class PipelineState final log_once("conservative rasterization needs enabled VK_EXT_conservative_rasterization and Tier 1 precision", 1); return E_INVALIDARG; } - if (r.FillMode != D3D12_FILL_MODE_SOLID || - topology_type != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) return E_INVALIDARG; + // A mesh pipeline has no input assembler, so its stream need not set the topology type: what is rasterized + // is the module's output, and it has to be triangles as well. + if (r.FillMode != D3D12_FILL_MODE_SOLID) return E_INVALIDARG; + if (mesh ? !leonida::conservative_raster::mesh_outputs_triangles(stages[0].words) + : topology_type != 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 stream_unsupported("target-independent rasterization; forced sample count", int(r.ForcedSampleCount)); @@ -12074,7 +12729,11 @@ class PipelineState final const leonida::dev_status::Build dev_build(r.mesh ? "mesh pipeline" : "graphics pipeline"); 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); + const auto result = device_.create_pipeline(flags, [&](VkPipelineCache with, VkPipelineCreateFlags f) { + info.flags = f; + pipeline = VK_NULL_HANDLE; + return device_.context->vk.vkCreateGraphicsPipelines(device_.info.device, with, 1, &info, nullptr, &pipeline); + }); if (status) *status = result; profile.finish(int(result)); trace.end(trigger, profile_shaders_.c_str(), unbound, bytes, result); @@ -12890,6 +13549,57 @@ void DeviceState::drain_titles_gone() { // 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. +// LEONIDA_UNKNOWN_TSHARP=1 (diagnostic): one line for each distinct base address a title-written T# names with no +// texture there (its shape, the tiling bits SW_MODE = dword 3 bits 20..24 by the GFX10 layout, unverified, and whether +// the address is title memory), up to 300 addresses, and every 8192 such lookups a summary by format, type and tiling. +// What a texture made from the T# on its first read would have to create. +void note_unknown_tsharp(const leonida::gfx10::ImageWords& words, const leonida::gfx10::Image& image) { + static const bool on = [] { + const char* v = std::getenv("LEONIDA_UNKNOWN_TSHARP"); + return v && *v == '1'; + }(); + if (!on) return; + struct Shape { + std::uint32_t format, type, sw, width, height, depth, mips, layers; + }; + static std::mutex mutex; + static std::unordered_map seen; + static std::map by_shape; + static std::uint64_t lookups = 0, in_title = 0; + const Shape s{image.format, std::uint32_t(image.type), (words[3] >> 20) & 0x1f, image.width, image.height, + image.depth, image.resource_mips, image.layer_count}; + std::uint64_t lo = 0, hi = 0; + const bool title = leonida::title_va_aliases().title_memory(image.address, lo, hi); + std::lock_guard lock(mutex); + ++lookups; + if (seen.emplace(image.address, s).second) { + in_title += title; + char key[64]; + std::snprintf(key, sizeof(key), "fmt %u type %u sw %u", s.format, s.type, s.sw); + ++by_shape[key]; + if (seen.size() <= 300) + std::fprintf(stderr, + "[rt] unknown-tsharp: #%zu base 0x%llx fmt %u type %u sw %u %ux%ux%u mips %u layers %u%s\n", + seen.size(), static_cast(image.address), s.format, s.type, s.sw, s.width, + s.height, s.depth, s.mips, s.layers, title ? " (title memory)" : " (not title memory)"); + if (seen.size() <= 24) + std::fprintf(stderr, "[rt] unknown-tsharp: #%zu words %08x %08x %08x %08x %08x %08x %08x %08x\n", seen.size(), + words[0], words[1], words[2], words[3], words[4], words[5], words[6], words[7]); + } + if (!(lookups % 8192)) { + std::vector> top; + for (const auto& [k, n] : by_shape) top.emplace_back(n, k); + std::sort(top.rbegin(), top.rend()); + std::string text; + for (std::size_t i = 0; i < top.size() && i < 10; ++i) + text += (i ? "; " : "") + top[i].second + " x" + std::to_string(top[i].first); + std::fprintf(stderr, + "[rt] unknown-tsharp: %llu lookups, %zu distinct addresses (%llu in title memory); by shape: %s\n", + static_cast(lookups), seen.size(), static_cast(in_title), + text.c_str()); + } +} + 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) { @@ -12923,6 +13633,7 @@ TitleImage bind_title_image(DeviceState& device, const leonida::gfx10::ImageWord } if (!owner) { if (why) *why = "no texture at T# address"; + note_unknown_tsharp(words, image); return TitleImage::unknown; } const Resource& r = *owner; @@ -13601,6 +14312,8 @@ class Device final const phases::Scope timed(phases::geometry); state_.geometry.refresh(DeviceState::copy_geometry); } + // Last, once the heap refresh, the windows and the geometry copies have made what this submission reads. + state_.update_address_guard(); const phases::Scope timed(phases::textures); if (async_texture_refresh()) { if (!t_in_title_textures) { @@ -13643,6 +14356,9 @@ class Device final [](void* device, std::uint64_t table, std::uint32_t descriptors) { static_cast(device)->scan_title_table(table, descriptors); }); + leonida::title_va_aliases().set_noter([](void* device, std::uint64_t va, std::uint64_t bytes) { + static_cast(device)->note_title_write(va, bytes); + }); state_.image_memory = std::make_unique( [device = info.device, make = state_.context->vk.vkAllocateMemory](std::uint32_t type, std::uint64_t bytes) { VkMemoryAllocateInfo block{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; @@ -14269,14 +14985,20 @@ class Device final // Under the arena's lock: an insert rebalances the tree and rewrites child links, which a walk on // another thread must not see half done. std::lock_guard lock(arena.mutex); - arena.blocks.reset(null_bytes + kArenaReserved, arena.size); - arena.first = null_bytes + kArenaReserved; + // LEONIDA_ADDRESS_GUARD: the guard header and sinks at [0x70000, 0x80000) are never handed out either + // (inside the null region when there is one, else just past the quad indices). + arena.first = std::max(null_bytes + kArenaReserved, + address_guard_enabled() ? leonida::address_guard::kGuardEnd : 0); + arena.blocks.reset(arena.first, arena.size); char check[2] = {}; size_t check_length = 0; arena.check_all = getenv_s(&check_length, check, "LEONIDA_ARENA_CHECK") == 0 && check_length > 1 && check[0] != '0'; } - arena.peak_end = null_bytes + kArenaReserved; + arena.peak_end = arena.first; + if (address_guard_enabled() && !state_.create_address_guard()) + std::fprintf(stderr, "[rt] d3d12: LEONIDA_ADDRESS_GUARD=1 but the address guard could not be set up; " + "guarded shaders check nothing\n"); char log[4] = {}; length = 0; arena.log = getenv_s(&length, log, "LEONIDA_ARENA_LOG") == 0 && length > 1 && log[0] != '0'; @@ -14383,12 +15105,14 @@ class Device final state_.bindless.reset(); } state_.report_arena(); + state_.destroy_address_guard(); 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); } + state_.finish_heavy_cache(); if (state_.pipeline_cache_handle) { // Nothing should be building into the cache now (the compiler's jobs for this device are gone, and so // is every PSO). If something is, its pipelines are half in the cache: keep the previous session file. @@ -15514,6 +16238,8 @@ class Device final const bool guard = check_pages_before_read(); if (!guard && !t.memory.pending()) return true; const bool mapped = t.mapped && refresh_mapped_pages(); + if (!title_pass_ && guard && !mapped) + t.memory.sync_map(title_map_generation_, static_cast(t.cpu), t.layout.layout.size); const auto commit = mapped ? leonida::kernel_writes::state().committer.load(std::memory_order_acquire) : nullptr; const bool waited = t.memory.pending(); // The answer is kept (generation 0) until a map change over the texture, a write into it or the periodic @@ -17820,7 +18546,7 @@ class Device final // 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; + if (!&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'); @@ -20341,6 +21067,14 @@ bool read_arena(ID3D12Device* device, std::uint64_t va, void* out, std::size_t b return true; } +long long console_heap_mirror_mismatches(ID3D12Device* device, std::uint64_t console_va) { + if (!device) return -1; + ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); + if (!real) real = device; + Device* d = Device::from(real); + return d ? d->state().console_heap_mirror_mismatches(console_va) : -1; +} + namespace { const leonida::BindlessSet* bindless_of(ID3D12Device* device) { if (!device) return nullptr; @@ -20911,8 +21645,12 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin v13.compute_full_subgroups, info.subgroup); const char* compile_mode = std::getenv("LEONIDA_PIPELINE_COMPILE"); const auto mode = compile_mode ? std::string_view(compile_mode) : std::string_view{}; - v13.enable_pipeline_cache_control = mode == "cache-only" && v13.core && v13.pipeline_cache_control; - info.cold_graphics_compile = v13.enable_pipeline_cache_control; + // pipelineCreationCacheControl: for LEONIDA_PIPELINE_COMPILE=cache-only, and for the heavy pipeline cache unless + // LEONIDA_HEAVY_PIPELINE_CACHE_MS=0 turns it off. + v13.enable_pipeline_cache_control = + (mode == "cache-only" || heavy_pipeline_cache_ms()) && v13.core && v13.pipeline_cache_control; + info.cold_graphics_compile = mode == "cache-only" && v13.enable_pipeline_cache_control; + info.heavy_pipeline_cache = heavy_pipeline_cache_ms() && v13.enable_pipeline_cache_control; info.prepare_on_bind = mode == "on-demand"; void* v13_chain = v13.enable(ext_chain); // D3D-78 uses the core robustness and format-feature flags. Leave the Vulkan 1.2 extension path unchanged. diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 87cc26dd33..c5f12dc050 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -2289,6 +2289,12 @@ HRESULT queue_copy_page_mappings(ChildProxy* self, UINT count, const xmem::PageB if (!map && rt::xmem::copy_page_mappings_fn) map = ©_page_mappings_default; if (!map || !count) return S_OK; if (!batches || flags) return E_INVALIDARG; + // Which implementation remaps, once: a boot's read-fault reports belong to that route's tests. + static std::atomic route_logged{false}; + if (!route_logged.exchange(true, std::memory_order_relaxed)) + std::fprintf(stderr, "[rt] d3d12_xs: CopyPageMappingsBatchX remaps through %s\n", + map == ©_page_mappings_default ? "xmem's range callback (copy_page_mappings_fn)" + : "the installed batch hook (set_copy_page_mappings_hook)"); auto* queue = reinterpret_cast(self->real); using clock = std::chrono::steady_clock; const auto t0 = clock::now(); @@ -2840,6 +2846,32 @@ struct UploadArena { constexpr std::size_t kUploadChunkMin = 8 << 20; // one chunk serves a title's whole frame of uploads +// LEONIDA_UPLOAD_LOG=1 (diagnostic): each upload chunk (its CPU base, device address and size), and the first 96 and +// then every 8192nd AllocateUploadMemory result as an offset into its chunk, so the addresses the title builds +// descriptors from can be matched with the memory it was handed. +inline bool upload_log() { + static const bool on = [] { + const char* v = std::getenv("LEONIDA_UPLOAD_LOG"); + return v && *v == '1'; + }(); + return on; +} +inline void log_upload_result(const UploadChunk* chunk, std::uint64_t result, std::uint64_t size, + std::uint64_t alignment) { + if (!upload_log() || !chunk) return; + static std::atomic calls{0}; + const std::uint64_t n = ++calls; + if (n > 96 && (n % 8192)) return; + const std::uint64_t base = reinterpret_cast(chunk->cpu_base); + std::fprintf(stderr, + "[rt] upload-log: #%llu result 0x%llx = chunk 0x%llx + offset 0x%llx (size %llu, alignment %llu; " + "chunk device address 0x%llx)\n", + static_cast(n), static_cast(result), + static_cast(base), static_cast(result - base), + static_cast(size), static_cast(alignment), + static_cast(chunk->gpu_base)); +} + UploadChunk* upload_chunk_new(DeviceProxy* device, std::size_t size) { auto* chunk = new (std::nothrow) UploadChunk{}; if (!chunk) return nullptr; @@ -2865,6 +2897,24 @@ UploadChunk* upload_chunk_new(DeviceProxy* device, std::size_t size) { chunk->resource = resource; chunk->cpu_base = static_cast(cpu); chunk->gpu_base = resource->GetGPUVirtualAddress(); + // LEONIDA_UPLOAD_ALIAS=1 (experiment): the title takes the pointer AllocateUploadMemory hands it for a GPU + // address too (the console's memory is unified) and writes it into the descriptors it builds itself. Entered in + // the title VA table, the chunk's CPU range answers with the chunk's console VA (its device address minus + // heap_base), so a V# the title wrote with such a pointer is rewritten to the chunk instead of left empty. A + // chunk below the arena has a negative console VA, usable in a V# only with LEONIDA_IMPORT_BELOW_ARENA=1. + static const bool alias = [] { + const char* v = std::getenv("LEONIDA_UPLOAD_ALIAS"); + return v && *v == '1'; + }(); + if (alias) { + const bool added = leonida::title_va_aliases().add(reinterpret_cast(chunk->cpu_base), + chunk->size, chunk->gpu_base); + std::fprintf(stderr, "[rt] d3d12_xs: upload chunk 0x%llx (%llu bytes) entered as an alias of console VA " + "0x%llx: %s\n", + static_cast(reinterpret_cast(chunk->cpu_base)), + static_cast(chunk->size), static_cast(chunk->gpu_base), + added ? "ok" : "refused"); + } return chunk; } if (resource) resource->Release(); @@ -2912,7 +2962,9 @@ std::uint64_t upload_alloc(DeviceProxy* device, std::uint64_t size, std::uint64_ 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::uint64_t result = reinterpret_cast(chunk->cpu_base + aligned); + log_upload_result(chunk, result, size, alignment); + return result; } } const std::size_t chunk_size = need + alignment > kUploadChunkMin ? need + alignment : kUploadChunkMin; @@ -2926,7 +2978,14 @@ std::uint64_t upload_alloc(DeviceProxy* device, std::uint64_t size, std::uint64_ 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); + if (upload_log()) + std::fprintf(stderr, "[rt] upload-log: new chunk at 0x%llx, device address 0x%llx, %llu bytes (%s)\n", + static_cast(reinterpret_cast(chunk->cpu_base)), + static_cast(chunk->gpu_base), static_cast(chunk->size), + chunk->resource ? "mapped upload buffer" : "VirtualAlloc fallback"); + const std::uint64_t result = reinterpret_cast(chunk->cpu_base + aligned); + log_upload_result(chunk, result, size, alignment); + return result; } // An address inside an upload chunk becomes the chunk's device address plus the offset; anything else — a @@ -2949,6 +3008,9 @@ void destroy_upload_state(void* upload_state) { for (UploadChunk* chunk = arena->chunks; chunk;) { UploadChunk* next = chunk->next; if (chunk->resource) { + const char* alias = std::getenv("LEONIDA_UPLOAD_ALIAS"); + if (alias && *alias == '1') + leonida::title_va_aliases().remove(reinterpret_cast(chunk->cpu_base), chunk->gpu_base); chunk->resource->Unmap(0, nullptr); chunk->resource->Release(); } else { diff --git a/runtime/shims/d3d12_xs_list_values.h b/runtime/shims/d3d12_xs_list_values.h index e49eefa989..b4f24bbbbe 100644 --- a/runtime/shims/d3d12_xs_list_values.h +++ b/runtime/shims/d3d12_xs_list_values.h @@ -31,8 +31,10 @@ // - The thread that signals a gate runs the work the layer held behind it (QueueHolds: the held lists' submission, // the shadow refresh, a deferred Present). That is the releaser, a second thread: the pump only decides, so // writes keep landing and other gates keep timing out while held work runs. -// Bounded: a gate is signalled after LEONIDA_VALUE_WAIT_TIMEOUT_MS (default 200 ms) whatever memory holds, counted -// from when the gates before it on its queue opened, and logged once per address. Short timeouts (4 ms) go to an +// Bounded: a gate is signalled after LEONIDA_VALUE_WAIT_TIMEOUT_MS (default 200 ms) of idle wait time, counted from +// when the gates before it on its queue opened and paused (up to a finite cap scaled with the gate's own budget) while +// the releaser is running held work, while an acyclic matching producer write is in flight, or while unrelated +// unblocked GPU work is running (src/list_value_wait_budget.h); logged once per address. Short timeouts (4 ms) go to an // address that timed out three times in a row, and, once four gates in a row timed out (the title waits for values // no modelled write stores, a new address each frame), to every wait whose address was never met: a frame then pays // a few milliseconds, not the full timeout, per such wait. A wait cut short is watched for the rest of the full @@ -56,10 +58,12 @@ #include #include #include +#include #include #include #include "d3d12_xs_device.h" // console_value_met, ListValueStats +#include "../src/list_value_wait_budget.h" // leonida::list_value_wait: work-aware timeout clock & producer graph #include "../src/title_page_watch.h" // leonida::kernel_writes::store #include "../src/value_write_sink.h" // leonida::value_sink: the arena and xmem's PAGE_NOACCESS pages @@ -362,7 +366,8 @@ class Pump { if (writes.empty() || exiting_.load(std::memory_order_relaxed)) return; // stop(): see there { std::lock_guard lock(mutex_); - writes_.push_back({std::move(queue), value, std::move(writes)}); + const std::uint64_t after_gate = max_pending_gate_locked(queue.get()); + writes_.push_back({std::move(queue), value, std::move(writes), after_gate}); } start_or_settle(); } @@ -396,7 +401,7 @@ class Pump { gate.value = value; gate.started = true; gate.since = Clock::now(); - gate.deadline = Clock::time_point::max(); + gate.last_tick = gate.since; gate.after = after; gate.action = std::move(action); gates_.push_back(std::move(gate)); @@ -502,13 +507,15 @@ class Pump { std::shared_ptr queue; std::uint64_t value; std::vector writes; + std::uint64_t after_gate = 0; // highest pending gate value on `queue` ahead of this write group }; struct Gate { std::shared_ptr queue; std::uint64_t value = 0; std::vector waits; - Clock::time_point deadline; // set by start_gate - Clock::time_point since; + leonida::list_value_wait::GateTimeoutState timeout{}; // work-aware timeout clock (set by start_gate) + Clock::time_point last_tick{}; + Clock::time_point since{}; bool started = false; // the gates before it on its queue have opened: its time runs bool cut_short = false; // given the short timeout std::uint64_t after = 0; // action gates: the queue's `written` value the action runs behind @@ -632,12 +639,21 @@ class Pump { releasing_ = true; } SetEvent(wake_); // the pump may be in an untimed wait: it watches the Signals from here on + struct PendingReleaseGuard { + std::atomic* count; + std::size_t remaining; + ~PendingReleaseGuard() { + if (remaining) count->fetch_sub(remaining, std::memory_order_release); + } + } pending_guard{&pending_releases_, batch.size()}; for (Release& release : batch) { if (stop_.load(std::memory_order_relaxed)) break; signal_value_.store(release.value, std::memory_order_relaxed); signal_since_ms_.store(GetTickCount64() | 1, std::memory_order_relaxed); // never 0 while inside signal(release); signal_since_ms_.store(0, std::memory_order_relaxed); + pending_releases_.fetch_sub(1, std::memory_order_release); + --pending_guard.remaining; } std::lock_guard lock(release_mutex_); releasing_ = false; @@ -721,36 +737,114 @@ class Pump { writes_.swap(rest); } - // The gates whose waits are met, whose time is up or whose action's turn has come, taken off the list in each + // Highest pending gate value currently in `gates_` for `queue` (0 if none). Called with mutex_ held. + std::uint64_t max_pending_gate_locked(const QueueValues* queue) const { + std::uint64_t highest = 0; + for (const Gate& g : gates_) + if (g.queue.get() == queue && g.value > highest) highest = g.value; + return highest; + } + + // The gates whose waits are met, whose idle time is up or whose action's turn has come, taken off the list in each // queue's order (a queue's gate values rise in submission order, so a later one must not be signalled first: it - // would open the earlier one too). `force` (no threads): every gate, now. Called with mutex_ held. - void take_open(bool force, std::vector& opening) { - std::vector blocked; + // would open the earlier one too). A memory gate's timeout clock pauses while held work is being released, while + // an acyclic matching producer write is in flight, or (up to a cap) while unrelated unblocked GPU work is running + // (src/list_value_wait_budget.h). `force` (no threads): every gate, now. Called with mutex_ held. + void take_open(bool force, bool landed_any, std::vector& opening) { + if (gates_.empty()) return; const auto now = Clock::now(); - for (auto it = gates_.begin(); it != gates_.end();) { - const QueueValues* queue = it->queue.get(); - if (std::find(blocked.begin(), blocked.end(), queue) != blocked.end()) { - ++it; - continue; + namespace lvw = leonida::list_value_wait; + + // Build the lightweight producer/gate dependency view lazily only if a started memory gate is still unmet. + bool graph_built = false; + std::vector flat_writes; + std::vector view_writes; + std::vector flat_waits; + std::vector view_gates; + std::vector> gate_wait_ranges; // (offset, count) into flat_waits + const auto ensure_graph = [&] { + if (graph_built) return; + graph_built = true; + std::size_t total_writes = 0; + for (const WriteGroup& wg : writes_) total_writes += wg.writes.size(); + flat_writes.reserve(total_writes); + view_writes.reserve(writes_.size()); + for (const WriteGroup& wg : writes_) { + const std::size_t start = flat_writes.size(); + for (const Write& w : wg.writes) + flat_writes.push_back({w.address, w.value, w.bytes, w.kind != WriteKind::value}); + view_writes.push_back({wg.queue.get(), wg.after_gate, + std::span(flat_writes).subspan(start, wg.writes.size())}); + } + std::size_t total_waits = 0; + for (const Gate& g : gates_) + if (!g.action) total_waits += g.waits.size(); + flat_waits.reserve(total_waits); + gate_wait_ranges.reserve(gates_.size()); + for (const Gate& g : gates_) { + const std::size_t start = flat_waits.size(); + if (!g.action) { + for (const Wait& w : g.waits) + if (!met_now(w)) flat_waits.push_back({w.address, w.reference, w.comparison, w.wide}); + } + gate_wait_ranges.emplace_back(start, flat_waits.size() - start); + } + view_gates.reserve(gates_.size()); + for (std::size_t i = 0; i < gates_.size(); ++i) { + const auto [off, cnt] = gate_wait_ranges[i]; + view_gates.push_back({gates_[i].queue.get(), gates_[i].value, static_cast(gates_[i].action), + std::span(flat_waits).subspan(off, cnt)}); } + }; + + std::vector blocked; + std::vector opened(gates_.size(), false); + for (std::size_t idx = 0; idx < gates_.size(); ++idx) { + Gate& gate = gates_[idx]; + const QueueValues* queue = gate.queue.get(); + if (std::find(blocked.begin(), blocked.end(), queue) != blocked.end()) continue; bool open = force; - if (it->action) { - open = open || queue->written->GetCompletedValue() >= it->after; + if (gate.action) { + open = open || queue->written->GetCompletedValue() >= gate.after; } else { - if (!it->started) start_gate(*it, now); + if (!gate.started) start_gate(gate, now); bool met = true; - for (const Wait& wait : it->waits) met = met && met_now(wait); - open = open || met || now >= it->deadline; - if (open) note_outcome(*it, met || force); + for (const Wait& wait : gate.waits) met = met && met_now(wait); + bool timed_out = false; + if (!open && !met) { + const std::uint64_t dt_us = + now > gate.last_tick + ? static_cast( + std::chrono::duration_cast(now - gate.last_tick).count()) + : 0u; + gate.last_tick = now; + const bool releaser_busy = + landed_any || !opening.empty() || pending_releases_.load(std::memory_order_acquire) != 0; + lvw::PauseReason reason = lvw::PauseReason::releaser_busy; + if (!releaser_busy) { + ensure_graph(); + reason = lvw::pause_reason(false, view_writes, view_gates, idx, console_value_met); + } + timed_out = gate.timeout.advance(dt_us, reason); + } else { + gate.last_tick = now; + } + open = open || met || timed_out; + if (open) note_outcome(gate, met || force, now); } if (open) { - opening.push_back({std::move(it->queue), it->value, std::move(it->action)}); - it = gates_.erase(it); + opening.push_back({std::move(gate.queue), gate.value, std::move(gate.action)}); + opened[idx] = true; } else { blocked.push_back(queue); - ++it; } } + if (!opening.empty()) { + std::deque rest; + for (std::size_t idx = 0; idx < gates_.size(); ++idx) + if (!opened[idx]) rest.push_back(std::move(gates_[idx])); + gates_.swap(rest); + } } // Writes landed, then gates opened: the pump's one step. `force` runs on the caller's thread when the threads do @@ -763,12 +857,15 @@ class Pump { busy_ = true; take_landed(force, landing); } + const bool landed_any = !landing.empty(); for (const WriteGroup& group : landing) land(group); std::vector opening; { std::lock_guard lock(mutex_); watch_late(); - take_open(force, opening); + take_open(force, landed_any, opening); + if (!force && !opening.empty()) + pending_releases_.fetch_add(opening.size(), std::memory_order_release); } if (!opening.empty()) { if (force) { @@ -919,7 +1016,10 @@ class Pump { gate.started = true; gate.cut_short = cut_short; gate.since = now; - gate.deadline = now + std::chrono::milliseconds(cut_short ? kDemotedTimeoutMs : full); + gate.last_tick = now; + const unsigned gate_ms = cut_short ? kDemotedTimeoutMs : full; + const auto caps = leonida::list_value_wait::default_pause_caps(gate_ms, cut_short); + gate.timeout.reset(static_cast(gate_ms) * 1000u, caps.active_us, caps.max_us); } // A wait for `address` was met (in time, or late): the address has met history and its timeouts in a row end. @@ -961,15 +1061,15 @@ class Pump { } // Called with mutex_ held. - void note_outcome(const Gate& gate, bool met) { + void note_outcome(const Gate& gate, bool met, Clock::time_point now) { if (met) { bump(counters().gates_met); timeouts_in_a_row_ = 0; for (const Wait& wait : gate.waits) note_met(wait.address); if (gate.cut_short && !gate.waits.empty()) lift_demotion(gate.waits.front().address); - if (logged_met_ < 4) { // the first few, to show the model at work in a boot log + if (logged_met_ < 4 && !gate.waits.empty()) { // the first few, to show the model at work in a boot log ++logged_met_; - const double ms = std::chrono::duration(Clock::now() - gate.since).count(); + const double ms = std::chrono::duration(now - gate.since).count(); std::fprintf(stderr, "[rt] d3d12_xs: a queue's wait for 0x%llx was met after %.2f ms\n", static_cast(gate.waits.front().address), ms); } @@ -990,14 +1090,14 @@ class Pump { for (const Wait& wait : gate.waits) { if (met_now(wait)) continue; if (gate.cut_short && !watched && late_.size() < kMaxLate) { - late_.push_back({wait, gate.since + std::chrono::milliseconds(full)}); + late_.push_back({wait, now + std::chrono::milliseconds(full)}); watched = true; } Streak* streak = find_streak(wait.address); if (!streak) streak = add_streak(wait.address); ++streak->timeouts; - std::uint64_t now = 0; - read_value(wait.address, wait.wide, now); + std::uint64_t current = 0; + read_value(wait.address, wait.wide, current); if (!streak->logged) { streak->logged = true; static std::atomic addresses{0}; @@ -1008,7 +1108,7 @@ class Pump { gate.cut_short ? kDemotedTimeoutMs : full, static_cast(wait.address), wait.wide ? 64u : 32u, wait.comparison, static_cast(wait.reference), - static_cast(now)); + static_cast(current)); } if (streak->timeouts == kDemoteAfter) { static std::atomic demoted{0}; @@ -1041,6 +1141,7 @@ class Pump { std::condition_variable release_ready_; std::deque releases_; bool releasing_ = false; + std::atomic pending_releases_{0}; // queued + active releases, read lock-free in take_open() std::atomic signal_since_ms_{0}; // GetTickCount64 when the releaser's current Signal began, or 0 std::atomic signal_value_{0}; std::atomic releaser_tid_{0}; diff --git a/runtime/shims/dstorage.cpp b/runtime/shims/dstorage.cpp index fe800fe686..103a5c9df8 100644 --- a/runtime/shims/dstorage.cpp +++ b/runtime/shims/dstorage.cpp @@ -10,6 +10,8 @@ // it has. Completion is therefore in queue order, as the API guarantees. // - 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. +// - A queue half full submits itself, but a read into physical pages and everything enqueued behind it wait for +// the title's own Submit: the title may fill the page list only then (hold_pages below). // Nothing here goes online or touches the GPU. #include #include @@ -38,6 +40,7 @@ #include "../src/shader_directory.h" #include "../src/dstorage_swizzle.h" #include "../src/dstorage_trace.h" +#include "../src/dstorage_hold.h" #include "dstorage_xs_abi.h" #include "dstorage_staging.h" #include "startup_trace.h" @@ -542,6 +545,47 @@ HRESULT read_file_range(HANDLE handle, uint64_t offset, void* destination, uint3 return S_OK; } +// ---- Reads into physical pages wait for the title's Submit ------------------------------------------------------- +// +// A request into physical pages names them through a pointer into the title's own page-number table, and a title may +// fill that table for a batch only in its submit path, right before Submit. A queue that submits itself at half its +// capacity then starts such a read early: it finds page 0 and fails, or finds the number the slot held before and +// writes the data into a page that now belongs to something else, with no error at all. So a self-submit stops at +// the first read into physical pages: that read and every entry behind it (the queue completes in order) wait for +// the title's Submit. A full queue still submits everything, since the title cannot call Submit while it waits in an +// enqueue, and Close does as before. The idea is from VIctory (Marvisak/VIctory eddde73, carried in +// fxceless/victory-fork 79cfdd9); the code here is written anew for this queue. +// +// LEONIDA_DSTORAGE_HOLD_PAGES=0 restores the old self-submit of everything. A hold has a time limit, so that a +// title path that never calls Submit and counted on the self-submit cannot stall for good: held entries that have +// waited LEONIDA_DSTORAGE_HOLD_MS milliseconds (2000 unless set) are submitted, page lists as they are, and counted +// as a timed release. 0 is no limit: they wait for Submit, however long. Both are read when a queue is created. +constexpr uint32_t kDefaultHoldMs = 2000; + +uint32_t environment_number(const wchar_t* name, uint32_t fallback) { + wchar_t value[16]{}; + const DWORD n = GetEnvironmentVariableW(name, value, 16); + if (n == 0 || n >= 16) return fallback; + wchar_t* end = nullptr; + const unsigned long parsed = std::wcstoul(value, &end, 10); + return end && *end == 0 ? static_cast(parsed) : fallback; +} + +// One line with every counter, at each power of two of the counter that moved: countable in a truncated log +// without a line per event. +void log_hold(const char* event, uint64_t n, unsigned capacity, size_t held_now) { + if (n & (n - 1)) return; + const auto& h = leonida::dstorage::hold_stats(); + std::lock_guard lock(log_mutex()); + std::fprintf(stderr, "[rt] ds-hold event=%s self_submits=%llu held_reads=%llu full_releases=%llu " + "timed_releases=%llu page0_entries=%llu capacity=%u held_now=%zu\n", event, + static_cast(h.self_submits.load()), + static_cast(h.held_reads.load()), + static_cast(h.full_releases.load()), + static_cast(h.timed_releases.load()), + static_cast(h.page0_entries.load()), capacity, held_now); +} + // ---- Queues ------------------------------------------------------------------------------------------------------- // Only sampled when request tracing is enabled. Times include work done by the file/decode worker. @@ -576,7 +620,10 @@ struct Entry { class Queue final : public IDStorageQueueX2 { public: - explicit Queue(const DSTORAGE_QUEUE_DESC1& desc) : desc_(desc) { + explicit Queue(const DSTORAGE_QUEUE_DESC1& desc) + : desc_(desc), + hold_pages_(environment_number(L"LEONIDA_DSTORAGE_HOLD_PAGES", 1) != 0), + hold_release_ms_(environment_number(L"LEONIDA_DSTORAGE_HOLD_MS", kDefaultHoldMs)) { error_event_ = CreateEventW(nullptr, TRUE, FALSE, nullptr); clear_record_locked(); std::lock_guard lock(stats().mutex); @@ -781,15 +828,64 @@ class Queue final : public IDStorageQueueX2 { bool auto_submit() const { return !desc_.Options.AutoSubmitDisabled; } size_t used_locked() const { return entries_.size() + in_flight_; } + // A read into physical pages: its page list may not be filled before the title's Submit (hold_pages above). + static bool into_pages(const Entry& e) { + return e.type == Entry::Type::Request && (e.request.Options.AsUINT64 & options::kDestinationPages) != 0; + } + + // The queue has reached half its capacity and holds nothing yet. Submits up to the first read into physical + // pages, which waits with everything behind it for the title's Submit. + void self_submit_locked() { + auto& h = leonida::dstorage::hold_stats(); + if (!hold_pages_) { + log_hold("self-submit", ++h.self_submits, desc_.Capacity, 0); + submit_locked(); + return; + } + size_t end = submitted_; + while (end < entries_.size() && !into_pages(entries_[end])) ++end; + if (end < entries_.size()) { + uint64_t reads = 0; + for (size_t i = end; i < entries_.size(); ++i) reads += into_pages(entries_[i]); + h.held_reads += reads; + holding_ = true; + hold_warned_ = false; + held_since_ = std::chrono::steady_clock::now(); + } + const size_t held_now = entries_.size() - end; + const bool hold = holding_; // submit_locked ends a hold when it submits everything + submit_locked(end); + holding_ = hold; + if (holding_) work_.notify_one(); // the worker starts timing the hold + log_hold("self-submit", ++h.self_submits, desc_.Capacity, held_now); + } + void enqueue(Entry&& e) { { std::unique_lock lock(mutex_); - // A full queue waits for the worker to free a slot. With auto-submit on, half the queue is always - // submitted by then; with it off, only a Submit from another thread frees one (as the reference warns). - space_.wait(lock, [&] { return closing_ || used_locked() < usable(); }); + // A full queue waits for the worker to free a slot. With auto-submit on, half the queue was submitted + // by then, except what is held for the title's Submit: the title cannot make that call while it waits + // here, so a full queue submits the held entries too, page lists as they are. With auto-submit off, + // only a Submit from another thread frees a slot (as the reference warns). + space_.wait(lock, [&] { + if (closing_ || used_locked() < usable()) return true; + if (holding_) { + const size_t held_now = entries_.size() - submitted_; + submit_locked(); + log_hold("full-queue", ++leonida::dstorage::hold_stats().full_releases, desc_.Capacity, held_now); + log_once("full-hold", "a full queue submitted reads into physical pages before the title's " + "Submit (their page lists may not be filled yet)"); + } + return false; + }); if (!closing_) { entries_.push_back(std::move(e)); - if (auto_submit() && entries_.size() - submitted_ >= half()) submit_locked(); + if (holding_) { + // Behind a held read: it waits with it, whatever it is. No second self-submit until the hold ends. + if (into_pages(entries_.back())) ++leonida::dstorage::hold_stats().held_reads; + } else if (auto_submit() && entries_.size() - submitted_ >= half()) { + self_submit_locked(); + } return; } } @@ -801,10 +897,16 @@ class Queue final : public IDStorageQueueX2 { release_references(e); } - void submit_locked() { + // Submits the entries before "end". Without one it submits all of them and ends a hold: the title's Submit, a + // full queue, Close, a hold that ran out of time. + void submit_locked(size_t end = SIZE_MAX) { + if (end >= entries_.size()) { + end = entries_.size(); + holding_ = false; + } uint32_t requests = 0; uint64_t source_bytes = 0, destination_bytes = 0; - for (size_t i = submitted_; i < entries_.size(); ++i) { + for (size_t i = submitted_; i < end; ++i) { Entry& e = entries_[i]; if (e.file) e.file_counted = e.file->add_pending(); if (e.counted) { @@ -820,12 +922,49 @@ class Queue final : public IDStorageQueueX2 { p.TotalRequestSourceByteCount += source_bytes; p.TotalRequestDestinationByteCount += destination_bytes; } - if (entries_.size() > submitted_) { - submitted_ = entries_.size(); + if (end > submitted_) { + submitted_ = end; work_.notify_one(); } } + // How long the worker sleeps before it looks at a hold again: until the time limit runs out, a quarter of a + // second at most (and exactly that without a limit, for the five-second line). + std::chrono::milliseconds hold_wait_locked() const { + long long ms = 250; + if (hold_release_ms_) { + const auto waited = std::chrono::duration_cast( + std::chrono::steady_clock::now() - held_since_).count(); + ms = std::clamp(static_cast(hold_release_ms_) - waited, 1, 250); + } + return std::chrono::milliseconds(ms); + } + + // On the worker while entries are held: a hold with a time limit ends when it runs out (a timed release), and + // one without says once that it has lasted five seconds (a title that never calls Submit would show up as this + // line and nothing after it). + void hold_tick_locked() { + if (!holding_) return; + const auto waited = std::chrono::duration_cast( + std::chrono::steady_clock::now() - held_since_).count(); + const size_t held_now = entries_.size() - submitted_; + if (hold_release_ms_ && waited >= static_cast(hold_release_ms_)) { + submit_locked(); + log_hold("timed", ++leonida::dstorage::hold_stats().timed_releases, desc_.Capacity, held_now); + log_once("timed-hold", "timed release: reads into physical pages held for the title's Submit were " + "submitted after LEONIDA_DSTORAGE_HOLD_MS without one (their page lists may " + "not be filled; the ds-hold line counts these)"); + } else if (waited >= 5000 && !hold_warned_) { + hold_warned_ = true; + std::lock_guard lock(log_mutex()); + std::fprintf(stderr, "[rt] dstorage: %zu entries behind a read into physical pages have waited %lld ms " + "for the title's Submit (queue %p, capacity %u; LEONIDA_DSTORAGE_HOLD_MS= " + "submits them after n ms, LEONIDA_DSTORAGE_HOLD_PAGES=0 never holds)\n", + held_now, static_cast(waited), static_cast(this), + unsigned(desc_.Capacity)); + } + } + struct Prepared { Entry& entry; HRESULT result = S_OK; @@ -859,7 +998,11 @@ class Queue final : public IDStorageQueueX2 { bool paired = false; { std::unique_lock lock(mutex_); - work_.wait(lock, [&] { return submitted_ > 0 || closed_; }); + while (!(submitted_ > 0 || closed_)) { + if (!holding_) work_.wait(lock); + else if (work_.wait_for(lock, hold_wait_locked()) == std::cv_status::timeout) + hold_tick_locked(); + } if (submitted_ == 0) return; head = std::move(entries_.front()); entries_.pop_front(); @@ -1088,6 +1231,10 @@ class Queue final : public IDStorageQueueX2 { 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; + // Page 0 is never a title page: a destination list that names it was not filled when its request ran, and + // the request fails below. Counted, since each one is data the title asked for and did not get. + if (write && std::find(numbers.begin(), numbers.end(), uint64_t{0}) != numbers.end()) + log_hold("page0", ++leonida::dstorage::hold_stats().page0_entries, 0, 0); if (rt::xmem::transfer_physical(numbers, offset, buffer, write)) return S_OK; return HRESULT_FROM_WIN32(GetLastError()); } @@ -1305,6 +1452,11 @@ class Queue final : public IDStorageQueueX2 { std::condition_variable work_, space_, idle_; std::deque entries_; size_t submitted_ = 0; // the first submitted_ entries are submitted + const bool hold_pages_; // LEONIDA_DSTORAGE_HOLD_PAGES + const uint32_t hold_release_ms_; // LEONIDA_DSTORAGE_HOLD_MS (kDefaultHoldMs unless set); 0: no time limit + bool holding_ = false; // under mutex_: a self-submit left entries for the title's Submit + bool hold_warned_ = false; // under mutex_: this hold's five-second line was written + std::chrono::steady_clock::time_point held_since_{}; // under mutex_ size_t in_flight_ = 0; bool closing_ = false; bool closed_ = false; diff --git a/runtime/shims/gameinput.cpp b/runtime/shims/gameinput.cpp index fa5889d6a8..5abb2a2fe9 100644 --- a/runtime/shims/gameinput.cpp +++ b/runtime/shims/gameinput.cpp @@ -1887,7 +1887,9 @@ 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]); // LEONIDA_INPUT_SCRIPT="a@70,a@85,start@120" (with LEONIDA_KEYBOARD_PAD=always): timed presses on the keyboard - // pad, in seconds since the pad's first update, each held 300 ms. For unattended boots: the title's first prompt + // pad, in seconds since the pad's first update, each held 300 ms or its own button@seconds:hold, and then until the + // title has read the pads kReads times since it began (never past kMaxHold seconds, or the hold if it is longer, so + // a title that stops reading does not keep the button). For unattended boots: the title's first prompt // waits for a button with no timeout (docs/re/notes/firstframe.md, step 5). The parser, the timeline and the // button names are gameinput_script.h's, shared with the scripted pad of a build without SDL3. namespace script = rt::gameinput::script; @@ -1899,7 +1901,21 @@ void update_keyboard_pad() { s.presses.size(), s.rejected); return s; }(); - if (!scripted.empty()) { + // LEONIDA_INPUT_FILE= (local, for headless runs whose display takes no keyboard input): every line appended + // to the file names one button of gameinput_script.h's table ("a", "down", ...) and becomes a press at once, held + // like a scripted one (300 ms and six readings, at most 5 s). The file is read again at most every 250 ms. + struct FilePress { + uint32_t bit; + double at; + uint64_t began; + bool started; + }; + static std::vector file_presses; + static const std::string input_file = [] { + const char* v = std::getenv("LEONIDA_INPUT_FILE"); + return std::string(v ? v : ""); + }(); + if (!scripted.empty() || !input_file.empty()) { static const ULONGLONG origin = GetTickCount64(); const double now = (GetTickCount64() - origin) / 1000.0; script::Held held{}; @@ -1908,15 +1924,51 @@ void update_keyboard_pad() { static std::vector began(scripted.presses.size(), 0); static std::vector started(scripted.presses.size(), 0); const uint64_t calls = g_reading_calls.load(std::memory_order_relaxed); + if (!input_file.empty()) { + static ULONGLONG last_read = 0; + static std::size_t lines_done = 0; + const ULONGLONG tick = GetTickCount64(); + if (tick - last_read >= 250) { + last_read = tick; + if (FILE* f = std::fopen(input_file.c_str(), "r")) { + char line[64]; + std::size_t n = 0; + while (std::fgets(line, sizeof(line), f)) { + if (++n <= lines_done) continue; + lines_done = n; + std::string name(line); + while (!name.empty() && (name.back() == '\n' || name.back() == '\r' || name.back() == ' ')) + name.pop_back(); + bool known = false; + for (const script::Button& b : script::kButtons) + if (name == b.name) { + file_presses.push_back({b.bit, now, 0, false}); + known = true; + } + std::fprintf(stderr, "[rt] gameinput: input file line %zu \"%s\" at %.1f s%s\n", n, + name.c_str(), now, known ? "" : " (unknown button, ignored)"); + } + std::fclose(f); + } + } + for (auto& p : file_presses) { + if (now < p.at || now >= p.at + kMaxHold) continue; + if (!p.started) { + p.started = true; + p.began = calls; + } + if (now < p.at + 0.3 || calls - p.began < kReads) held.buttons |= p.bit; + } + } for (std::size_t i = 0; i < scripted.presses.size(); ++i) { const auto& press = scripted.presses[i]; bool active = false; - if (now >= press.at && now < press.at + kMaxHold) { + if (now >= press.at && now < press.at + std::max(press.hold, kMaxHold)) { if (!started[i]) { started[i] = 1; began[i] = calls; } - active = now < press.at + 0.3 || calls - began[i] < kReads; + active = now < press.at + press.hold || calls - began[i] < kReads; } if (!active) continue; if (press.stick) held.stick = press.stick; @@ -1924,7 +1976,7 @@ void update_keyboard_pad() { } if (held.stick) right_y = held.stick > 0 ? -kStickFull : kStickFull; // SDL's +Y is down for (const script::Button& b : script::kButtons) { - if (!(scripted.named & b.bit)) continue; + if (!(scripted.named & b.bit) && input_file.empty()) continue; const auto button = static_cast(b.sdl); SDL_SetJoystickVirtualButton(g_keyboard.js, button, (held.buttons & b.bit) || down[button]); } diff --git a/runtime/shims/gameinput_script.h b/runtime/shims/gameinput_script.h index 7595067500..5be5544240 100644 --- a/runtime/shims/gameinput_script.h +++ b/runtime/shims/gameinput_script.h @@ -5,10 +5,13 @@ // // LEONIDA_INPUT_SCRIPT="a@70,a@85,start@120" // -// Each entry is button@seconds, the seconds counted from the shim's first update. A press is held for kHoldSeconds, -// then released. Buttons: a b x y start back lb rb up down left right; rsup and rsdown throw the right stick fully up -// or down for the same time (they replay the stick throws the press log writes). Spaces around an entry are allowed; -// empty entries, unknown buttons and invalid times (negative, non-finite, trailing text) are counted as rejected. +// Each entry is button@seconds[:hold], the seconds counted from the shim's first update. A press is held for `hold` +// seconds (kHoldSeconds when the entry has none), then released: a longer hold reaches a title that reads its pad +// only every few seconds, as the retail title does at world-start frame rates. Buttons: a b x y start back lb rb +// up down left right; rsup and rsdown throw the right stick fully up or down for the same time (they replay the +// stick throws the press log writes). Spaces around an entry are allowed; empty entries, unknown buttons, invalid +// times (negative, non-finite, trailing text) and invalid holds (zero, negative, non-finite, more than +// kMaxHoldSeconds) are counted as rejected. #pragma once #include #include @@ -24,6 +27,7 @@ namespace rt::gameinput::script { constexpr double kHoldSeconds = 0.3; +constexpr double kMaxHoldSeconds = 600; // a typo such as b@10:1100 should not hold B for the whole run // One scriptable button: its name in the script and the press log, its GameInput gamepad bit, and its SDL3 // SDL_GamepadButton number, which the "scripted press of button " line has always carried (tools/stage_timeline.py @@ -46,6 +50,7 @@ struct Press { uint32_t button = 0; // a GameInput gamepad bit, or 0 for a stick throw int stick = 0; // +1 rsup, -1 rsdown (GameInput's +Y is up) double at = 0; // seconds + double hold = kHoldSeconds; }; struct Script { @@ -72,17 +77,22 @@ inline Script parse(std::string text) { const char* time = item.c_str() + sep + 1; char* tail; const double seconds = std::strtod(time, &tail); - if (tail == time || !std::isfinite(seconds) || seconds < 0 || - item.find_first_not_of(whitespace, static_cast(tail - item.c_str())) != std::string::npos) - continue; + if (tail == time || !std::isfinite(seconds) || seconds < 0) continue; + double hold = kHoldSeconds; + if (*tail == ':') { + const char* hold_text = tail + 1; + hold = std::strtod(hold_text, &tail); + if (tail == hold_text || !std::isfinite(hold) || hold <= 0 || hold > kMaxHoldSeconds) continue; + } + if (item.find_first_not_of(whitespace, static_cast(tail - item.c_str())) != std::string::npos) continue; const auto is = [&](const char* name) { return item.compare(first, sep - first, name) == 0; }; if (is("rsup") || is("rsdown")) { - out.presses.push_back({0, is("rsup") ? 1 : -1, seconds}); + out.presses.push_back({0, is("rsup") ? 1 : -1, seconds, hold}); continue; } for (const Button& b : kButtons) { if (is(b.name)) { - out.presses.push_back({b.bit, 0, seconds}); + out.presses.push_back({b.bit, 0, seconds, hold}); out.named |= b.bit; break; } @@ -102,7 +112,7 @@ struct Held { inline Held held_at(const Script& script, double seconds) { Held h; for (const Press& p : script.presses) { - if (seconds < p.at || seconds >= p.at + kHoldSeconds) continue; + if (seconds < p.at || seconds >= p.at + p.hold) continue; if (p.stick) h.stick = p.stick; else h.buttons |= p.button; } diff --git a/runtime/shims/xapu_chad.cpp b/runtime/shims/xapu_chad.cpp index 35bda2b72f..e46a61c977 100644 --- a/runtime/shims/xapu_chad.cpp +++ b/runtime/shims/xapu_chad.cpp @@ -1,24 +1,8 @@ -// xapu.dll and chad.dll: the console's audio processing unit (APU) and audio DSP command queues. No PC has either, -// so these give the title connections whose calls succeed, a zeroed shared buffer, a result for each stream open and -// close, and zeroed DSP status: the audio the APU would render stays silent, and nothing the title submits is processed. +// chad.dll: the console's audio DSP command queue. No PC has one, so this gives the title a connection whose calls +// succeed and zeroed DSP status: nothing the title submits is processed. xapu.dll, the APU command queue, is in +// xapu_queue.cpp. // // Read from the executable's call sites (counts in docs/runtime_imports.md), statically, never run: -// XApuConnect(block24*, out16*, handle*) 1 site; success is SUCCEEDED(hr). The first qword of the 16-byte -// output is read later as the base of a CPU-visible buffer: per-stream -// input at base + slot * 0x280 and output at base + 0x14000 + -// slot * 0x1E00. The first argument is a 24-byte global of the title -// that other title code also addresses; whether it is an input or an -// output is not known, so it is left untouched. -// XApuEnqueueCommand(handle, cmd*, 0) 4 sites; the return value is never read. cmd's first dword is a type -// (1, 2 and 3 seen), the second a stream slot. -// XApuGetResultCount(handle, 0) 1 site; 0 skips the loop that dequeues. -// XApuDequeueResult(handle, out*) 1 site, called count times into a zeroed 0x50-byte local; a negative -// HRESULT skips that result. The loop reads a type at +0, a stream slot -// at +4 and a dword at +0x34. Its per-slot state machine takes a type 1 -// result as "opened" and returns the slot to the title's free list only -// on a type 2 result, after the title enqueued a type 2 command. -// XApuDisconnect(handle, 0x20) 1 site; the return value is never read. The constant second -// argument is not declared here: nothing reads it. // XDspConnectWithMaximumStreamLimit(buffer, u32, u32, 0x80, 1, handle*) 1 site; success is a return of 0. The // buffer comes from the title's XMemAlloc and stays the title's. // XDspActivate(handle, desc*, out*, out*) 1 site; success is a return of 0, else the caller returns -1. The two @@ -30,12 +14,6 @@ // at +4 equals *id. // XDspDeactivate, XDspDisconnect 1 site each, tail calls: the caller returns what they return. // -// HYPOTHESIS: the shared buffer is 0x14000 + 128 * 0x1E00 bytes. 128 slots is what fits 0x14000 at the 0x280 input -// stride, and the DSP connect passes 0x80 as its stream limit; no call site shows a bound. The 16-byte output is -// written as {base, size}; only the base is measured. -// HYPOTHESIS: a type 1 (open) or type 2 (close) command produces one result of the same type for the same slot; the -// title's state machine fits that, the console is not measured. Without the close result the title's 256 stream ids -// run out. Only the two dwords are written; other command types are accepted with S_OK and produce no result. // HYPOTHESIS: XDspActivate's outputs point at zeroed memory owned by the connection. XDspSubmitCommand leaves *id at // the title's 0, so the zeroed status reads as "command 0 done, no error" and the title does not wait. #include @@ -43,7 +21,6 @@ #include #include -#include #include #include #include @@ -54,30 +31,13 @@ namespace { -constexpr size_t kApuBufferSize = 0x14000 + 128 * 0x1E00; - -// shortcut: results past this cap are dropped (each leaks one stream id); raise it if a title that never dequeues -// must still work. -constexpr size_t kMaxResults = 4096; - -struct ApuResult { - uint32_t type; - uint32_t slot; -}; - -struct ApuConnection { - void* buffer; - std::mutex mutex; - std::deque results; -}; - struct DspConnection { uint8_t status[256]; uint8_t stream[256]; }; -// gta6rt --trace FILE: the first call of each function and the first XApuEnqueueCommand of each command type, with -// the caller, so the first boot shows what the title sends without a line per call. +// gta6rt --trace FILE: the first call of each function, with the caller, so the first boot shows what the title sends +// without a line per call. void note(const char* api, uint64_t value, const void* caller) { if (!rt::startup_trace::enabled()) return; static std::mutex mutex; @@ -92,71 +52,6 @@ void note(const char* api, uint64_t value, const void* caller) { rt::startup_trace::quote(rt::startup_trace::where(reinterpret_cast(caller)))); } -HRESULT __stdcall XApuConnect(void* block24, void* out16, void** handle) { - note("XApuConnect", 0, _ReturnAddress()); - if (!handle) return E_INVALIDARG; - *handle = nullptr; - void* buffer = VirtualAlloc(nullptr, kApuBufferSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); // zeroed - if (!buffer) return E_OUTOFMEMORY; - auto* c = new (std::nothrow) ApuConnection; // a throwing new would unwind into the title - if (!c) { - VirtualFree(buffer, 0, MEM_RELEASE); - return E_OUTOFMEMORY; - } - c->buffer = buffer; - *handle = c; - (void)block24; - if (out16) { - const uint64_t info[2] = {reinterpret_cast(buffer), kApuBufferSize}; - std::memcpy(out16, info, sizeof info); - } - return S_OK; -} - -HRESULT __stdcall XApuDisconnect(void* handle) { - note("XApuDisconnect", 0, _ReturnAddress()); - auto* c = static_cast(handle); - if (!c) return E_INVALIDARG; - VirtualFree(c->buffer, 0, MEM_RELEASE); - delete c; - return S_OK; -} - -HRESULT __stdcall XApuEnqueueCommand(void* handle, const uint32_t* command, uint64_t flags) { - note("XApuEnqueueCommand", command ? command[0] : ~0ull, _ReturnAddress()); - (void)flags; - auto* c = static_cast(handle); - if (!c || !command) return E_INVALIDARG; - if (command[0] == 1 || command[0] == 2) { - try { - const std::lock_guard lock(c->mutex); - if (c->results.size() < kMaxResults) c->results.push_back({command[0], command[1]}); - } catch (...) { // out of memory: the result is lost, nothing may unwind into the title - } - } - return S_OK; -} - -uint32_t __stdcall XApuGetResultCount(void* handle, uint64_t flags) { - note("XApuGetResultCount", 0, _ReturnAddress()); - (void)flags; - auto* c = static_cast(handle); - if (!c) return 0; - const std::lock_guard lock(c->mutex); - return static_cast(c->results.size()); -} - -HRESULT __stdcall XApuDequeueResult(void* handle, void* result) { - note("XApuDequeueResult", 0, _ReturnAddress()); - auto* c = static_cast(handle); - if (!c || !result) return E_INVALIDARG; - const std::lock_guard lock(c->mutex); - if (c->results.empty()) return E_FAIL; - std::memcpy(result, &c->results.front(), sizeof(ApuResult)); // the rest stays as the caller zeroed it - c->results.pop_front(); - return S_OK; -} - HRESULT __stdcall XDspConnectWithMaximumStreamLimit(void* buffer, uint32_t a, uint32_t b, uint32_t max_streams, uint32_t flags, void** handle) { note("XDspConnectWithMaximumStreamLimit", max_streams, _ReturnAddress()); @@ -199,14 +94,6 @@ HRESULT __stdcall XDspSubmitCommand(void*, void*, uint32_t*) { } // 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)}, -); - SHIM_TABLE(chad, {"chad.dll", "XDspActivate", reinterpret_cast(&XDspActivate)}, {"chad.dll", "XDspConnectWithMaximumStreamLimit", reinterpret_cast(&XDspConnectWithMaximumStreamLimit)}, diff --git a/runtime/shims/xapu_queue.cpp b/runtime/shims/xapu_queue.cpp new file mode 100644 index 0000000000..e754376ba4 --- /dev/null +++ b/runtime/shims/xapu_queue.cpp @@ -0,0 +1,438 @@ +// xapu.dll: the console's audio processing unit (APU) command queue. No PC has one, so this keeps the queue the title +// talks to - one result per accepted command, in command order, with the console's error codes. With +// runtime/opus_decoder built (LEONIDA_HAVE_OPUS_DECODER) a process command decodes its Opus packet to PCM; without +// it the result carries the frame count its table-of-contents byte gives and silence in its output. +// +// Read from the executable's call sites (counts in docs/runtime_imports.md, shapes in docs/audio_hal_exe_calls.md), +// statically, never run: +// XApuConnect(input24*, out16*, handle*) 1 site; success is SUCCEEDED(hr). The first qword of the 16-byte +// output is read later as the base of a CPU-visible buffer: per-stream +// input at base + slot * 0x280 and output at base + 0x14000 + +// slot * 0x1E00. The first argument is a 24-byte global of the title +// that other title code also addresses. +// XApuEnqueueCommand(handle, cmd*, 0) 4 sites; the return value is never read. cmd's first dword is a type +// (1, 2 and 3 seen), the second a stream slot. +// XApuGetResultCount(handle, 0) 1 site; 0 skips the loop that dequeues. +// XApuDequeueResult(handle, out*) 1 site, called count times into a zeroed 0x50-byte local; a negative +// HRESULT skips that result. The loop reads a type at +0, a stream slot +// at +4 and a dword at +0x34. Its per-slot state machine takes a type 1 +// result as "opened" and returns the slot to the title's free list only +// on a type 2 result, after the title enqueued a type 2 command. +// XApuDisconnect(handle, 0x20) 1 site; the return value is never read. +// +// Where the layouts come from. The signatures, structure layouts, command kinds, option bits and error codes below +// are facts recorded by Marvisak/VIctory (GPL-3.0-or-later, crates/victory-hle/src/modules/apu.rs at commit ffe310e), +// whose runtime runs the retail executable through these calls; see docs/related_projects.md. Nothing of its code is +// copied; this file is written from those facts. They agree with every shape above: the first argument of +// XApuConnect is an input, the dword the title reads at +0x34 of a result is its output byte count, and a type 1 +// (activate) or type 2 (deactivate) command gives a result of the same kind for the same stream. +// HRESULT XApuConnect(const ConnectInput*, ConnectOutput*, Connection** out) +// HRESULT XApuDisconnect(Connection*, uint32_t) the second argument is not read +// HRESULT XApuEnqueueCommand(Connection*, const void* command, uint32_t* accepted_so_far) may be null +// HRESULT XApuDequeueResult(Connection*, Result* out) 0x8AC81001 while no result is ready +// uint32_t XApuGetResultCount(Connection*, uint32_t* dequeued_so_far) may be null; returns the results ready +// A connection is for one kind of processing; kind 1 is Opus decoding to 32-bit float PCM at 48 kHz, and any other +// kind is E_NOTIMPL. Every command starts with the 24-byte CommandId. A command refused at once (unknown kind, +// stream out of range, or the stream already holding `commands_per_stream` results not dequeued) gives no result; +// every other command gives one, with its error, if any, in the result. +// +// Without runtime/opus_decoder a process command's frame count comes from the Opus packet's table-of-contents byte +// (RFC 6716, section 3.1), clipped from first_frame, to frame_count and to what output_bytes holds, and that output +// range is written with zeros, so the title sees streams advance at the right rate and the audio stays silent. With +// the crate, fill() decodes the packet and writes its PCM instead. +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(LEONIDA_HAVE_OPUS_DECODER) +#include "leonida_opus_decoder.h" +#endif + +#include "shims.h" +#include "startup_trace.h" + +namespace { + +constexpr HRESULT kNotImpl = static_cast(rt::shims::kENotImpl); +constexpr HRESULT kQueueFull = static_cast(0x8AC81000u); +constexpr HRESULT kNoResult = static_cast(0x8AC81001u); +constexpr HRESULT kInvalidCommand = static_cast(0x8AC81002u); +constexpr HRESULT kInvalidStream = static_cast(0x8AC81003u); +constexpr HRESULT kAlreadyActive = static_cast(0x8AC81005u); +constexpr HRESULT kBadPacket = static_cast(0x8AC81008u); + +constexpr uint32_t kDecodeOpus = 1; // ConnectInput::processing + +constexpr uint32_t kActivate = 1; // CommandId::kind +constexpr uint32_t kDeactivate = 2; +constexpr uint32_t kProcess = 3; +constexpr uint32_t kReset = 5; // 4 is notify; neither carries anything to do while nothing is decoded + +constexpr uint32_t kSignalWhenDone = 0x1; // CommandId::options: set the result event when the result is ready +constexpr uint32_t kResultEvent = 0x8; // ConnectInput::options: create an auto-reset event and hand it out +constexpr uint32_t kDeinterleavedOutput = 0x4; // ConnectInput::options: split stereo into two planes +constexpr uint32_t kOpusSampleRate = 48000; + +constexpr uint32_t kMaxStreams = 500; +constexpr uint32_t kMaxCommandsPerStream = 16; +constexpr uint32_t kMaxFrames = 5760; // 120 ms at 48 kHz, the longest Opus packet (RFC 6716, section 3.2.5) + +#pragma pack(push, 1) +struct ConnectInput { + uint32_t processing; + uint32_t streams; + uint32_t commands_per_stream; + uint32_t memory_bytes; + uint32_t frames_per_output; // 0 for decoding + uint32_t options; +}; +struct ConnectOutput { + void* memory; // zeroed, for the title's packets and output + HANDLE result_event; +}; +struct CommandId { + uint32_t kind; + uint32_t stream; + uint32_t sequence; + uint32_t options; + uint64_t context; +}; +struct ActivateCommand { + CommandId id; + uint32_t channels; // 1 or 2 + uint32_t init_bytes; + const void* init; + float start_pitch; + uint32_t processing_bytes; + void* processing; +}; +struct ProcessCommand { + CommandId id; + float pitch_ramp; + float target_pitch; + uint32_t first_frame; + uint32_t frame_count; + uint32_t input_bytes; + const uint8_t* input; + uint32_t output_bytes; + uint8_t* output; +}; +struct Result { + CommandId id; + uint32_t state; + uint64_t state_data; + uint64_t usec; + HRESULT error; + uint32_t frames; + uint32_t output_bytes; + uint8_t* output; + float pitch; + uint32_t input_bytes; + const uint8_t* input; +}; +#pragma pack(pop) +static_assert(sizeof(ConnectInput) == 24, "six dwords"); +static_assert(sizeof(ConnectOutput) == 16, "memory and event"); +static_assert(sizeof(CommandId) == 24, "kind, stream, sequence, options, context"); +static_assert(sizeof(ActivateCommand) == 56, "CommandId and the activate fields"); +static_assert(sizeof(ProcessCommand) == 64, "CommandId and the process fields"); +static_assert(sizeof(Result) == 0x50, "the result the title dequeues"); +static_assert(offsetof(Result, state) == 0x18 && offsetof(Result, error) == 0x2C && + offsetof(Result, output_bytes) == 0x34 && offsetof(Result, pitch) == 0x40 && + offsetof(Result, input) == 0x48, + "the offsets the title and the layout agree on"); + +struct Stream { + bool active = false; + uint32_t channels = 0; + uint32_t pending = 0; // results queued and not dequeued +#if defined(LEONIDA_HAVE_OPUS_DECODER) + LeonidaOpusDecoder* decoder = nullptr; +#endif +}; + +struct Connection { + void* memory = nullptr; + HANDLE event = nullptr; + uint32_t commands_per_stream = 0; + bool deinterleaved = false; + std::mutex mutex; + std::vector streams; + std::deque results; + uint32_t accepted = 0; + uint32_t dequeued = 0; +}; + +// gta6rt --trace FILE: the first call of each function and the first XApuEnqueueCommand of each command kind, with +// the caller, so the first boot shows what the title sends without a line per call. +void note(const char* api, uint64_t value, const void* caller) { + if (!rt::startup_trace::enabled()) return; + static std::mutex mutex; + static std::set> seen; + { + const std::lock_guard lock(mutex); + if (!seen.insert({api, value}).second) return; + } + rt::startup_trace::event( + "audio_queue", std::string("\"api\":") + rt::startup_trace::quote(api) + + ",\"value\":" + rt::startup_trace::quote(rt::startup_trace::hex(value)) + ",\"caller\":" + + rt::startup_trace::quote(rt::startup_trace::where(reinterpret_cast(caller)))); +} + +// Samples per channel at 48 kHz in one Opus packet, from its table-of-contents byte and frame count code (RFC 6716, +// section 3.1); 0 for a packet that is not valid. The no-decoder path counts frames this way. +uint32_t opus_packet_frames(const uint8_t* packet, uint32_t bytes) { + if (!packet || bytes == 0) return 0; + static constexpr uint32_t kSilk[4] = {480, 960, 1920, 2880}; // 10, 20, 40, 60 ms + static constexpr uint32_t kHybrid[2] = {480, 960}; // 10, 20 ms + static constexpr uint32_t kCelt[4] = {120, 240, 480, 960}; // 2.5, 5, 10, 20 ms + const uint32_t config = packet[0] >> 3; + const uint32_t per_frame = config < 12 ? kSilk[config & 3] : config < 16 ? kHybrid[config & 1] : kCelt[config & 3]; + uint32_t count = 0; + switch (packet[0] & 3) { + case 0: count = 1; break; + case 1: + case 2: count = 2; break; + default: + if (bytes < 2) return 0; + count = packet[1] & 0x3F; + break; + } + if (count == 0 || count * per_frame > kMaxFrames) return 0; + return count * per_frame; +} + +// Fills a process command's result: the packet's PCM when runtime/opus_decoder is built, silence (with the frame +// count from the table-of-contents byte) otherwise. +void fill(Connection& connection, Stream& stream, const ProcessCommand& c, Result& r) { + r.input = c.input; + r.input_bytes = c.input_bytes; + r.output = c.output; + if (!c.input || !c.output || c.input_bytes == 0) { + r.error = E_INVALIDARG; + return; + } +#if defined(LEONIDA_HAVE_OPUS_DECODER) + if (stream.decoder) { + const uint32_t channels = leonida_opus_decoder_channels(stream.decoder); + if (channels == 0) { + r.error = kInvalidStream; + return; + } + std::vector pcm; + try { + pcm.resize(size_t(kMaxFrames) * channels); + } catch (...) { + r.error = E_OUTOFMEMORY; + return; + } + uint32_t decoded = 0; + if (leonida_opus_decode_packet(stream.decoder, c.input, c.input_bytes, pcm.data(), kMaxFrames, &decoded) != + LEONIDA_OPUS_OK) { + r.error = kBadPacket; + return; + } + const uint32_t first = c.first_frame < decoded ? c.first_frame : decoded; + uint32_t frames = decoded - first; + if (frames > c.frame_count) frames = c.frame_count; + const uint32_t room = c.output_bytes / (4 * channels); + if (frames > room) frames = room; + const uint32_t bytes = frames * channels * 4; + if (connection.deinterleaved && channels == 2) { + float* out = reinterpret_cast(c.output); + for (uint32_t i = 0; i < frames; ++i) { + out[i] = pcm[(first + i) * 2]; + out[frames + i] = pcm[(first + i) * 2 + 1]; + } + } else if (bytes != 0) { + std::memcpy(c.output, pcm.data() + first * channels, bytes); + } + r.frames = frames; + r.output_bytes = bytes; + return; + } +#endif + const uint32_t decoded = opus_packet_frames(c.input, c.input_bytes); + if (decoded == 0) { + r.error = kBadPacket; + return; + } + const uint32_t first = c.first_frame < decoded ? c.first_frame : decoded; + uint32_t frames = decoded - first; + if (frames > c.frame_count) frames = c.frame_count; + const uint32_t room = c.output_bytes / (4 * stream.channels); + if (frames > room) frames = room; + const uint32_t bytes = frames * stream.channels * 4; + std::memset(c.output, 0, bytes); // interleaved or not, silence is zeros + r.frames = frames; + r.output_bytes = bytes; +} + +HRESULT __stdcall XApuConnect(const ConnectInput* input, ConnectOutput* output, Connection** out) { + note("XApuConnect", input ? input->processing : ~0ull, _ReturnAddress()); + if (!input || !output || !out) return E_INVALIDARG; + *out = nullptr; + ConnectInput in; + std::memcpy(&in, input, sizeof(in)); + if (in.streams == 0 || in.streams > kMaxStreams || in.commands_per_stream == 0 || + in.commands_per_stream > kMaxCommandsPerStream || in.memory_bytes == 0) + return E_INVALIDARG; + if (in.processing != kDecodeOpus) { + std::fprintf(stderr, "[rt] xapu: XApuConnect for processing kind %u: only Opus decoding (1); E_NOTIMPL\n", + in.processing); + return kNotImpl; + } + if (in.frames_per_output != 0) return E_INVALIDARG; + + auto* c = new (std::nothrow) Connection; // a throwing new would unwind into the title + if (!c) return E_OUTOFMEMORY; + try { + c->streams.resize(in.streams); + } catch (...) { + delete c; + return E_OUTOFMEMORY; + } + c->memory = VirtualAlloc(nullptr, in.memory_bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); // zeroed + if (!c->memory) { + delete c; + return E_OUTOFMEMORY; + } + if (in.options & kResultEvent) { + c->event = CreateEventW(nullptr, FALSE, FALSE, nullptr); // auto-reset + if (!c->event) { + const HRESULT hr = HRESULT_FROM_WIN32(GetLastError()); + VirtualFree(c->memory, 0, MEM_RELEASE); + delete c; + return hr; + } + } + c->commands_per_stream = in.commands_per_stream; + c->deinterleaved = (in.options & kDeinterleavedOutput) != 0; + const ConnectOutput o{c->memory, c->event}; + std::memcpy(output, &o, sizeof(o)); + *out = c; +#if defined(LEONIDA_HAVE_OPUS_DECODER) + std::fprintf(stderr, "[rt] xapu: connected for Opus decoding, %u streams; packets decoded\n", in.streams); +#else + std::fprintf(stderr, "[rt] xapu: connected for Opus decoding, %u streams; packets counted, not decoded\n", + in.streams); +#endif + return S_OK; +} + +HRESULT __stdcall XApuDisconnect(Connection* c, uint32_t /*0x20 at the measured site*/) { + note("XApuDisconnect", 0, _ReturnAddress()); + if (!c) return E_INVALIDARG; +#if defined(LEONIDA_HAVE_OPUS_DECODER) + for (Stream& s : c->streams) + if (s.decoder) leonida_opus_decoder_destroy(s.decoder); +#endif + if (c->event) CloseHandle(c->event); + VirtualFree(c->memory, 0, MEM_RELEASE); + delete c; + return S_OK; +} + +HRESULT __stdcall XApuEnqueueCommand(Connection* c, const void* command, uint32_t* accepted_so_far) { + if (!c || !command) return E_INVALIDARG; + CommandId id; + std::memcpy(&id, command, sizeof(id)); + note("XApuEnqueueCommand", id.kind, _ReturnAddress()); + if (id.kind < kActivate || id.kind > kReset) return kInvalidCommand; + + const std::lock_guard lock(c->mutex); + if (id.stream >= c->streams.size()) return kInvalidStream; + Stream& stream = c->streams[id.stream]; + if (stream.pending >= c->commands_per_stream) return kQueueFull; + + Result r{}; + r.id = id; + r.pitch = 1.0f; + if (id.kind == kActivate) { + ActivateCommand a; + std::memcpy(&a, command, sizeof(a)); + if (stream.active) { + r.error = kAlreadyActive; + } else if (a.channels < 1 || a.channels > 2) { + r.error = E_INVALIDARG; + } else { + stream.active = true; + stream.channels = a.channels; +#if defined(LEONIDA_HAVE_OPUS_DECODER) + if (leonida_opus_decoder_create(kOpusSampleRate, a.channels, &stream.decoder) != LEONIDA_OPUS_OK) { + stream.active = false; + stream.channels = 0; + r.error = E_INVALIDARG; + } +#endif + } + } else if (id.kind == kDeactivate) { + stream.active = false; +#if defined(LEONIDA_HAVE_OPUS_DECODER) + if (stream.decoder) { + leonida_opus_decoder_destroy(stream.decoder); + stream.decoder = nullptr; + } +#endif + } else if (id.kind == kReset) { +#if defined(LEONIDA_HAVE_OPUS_DECODER) + if (stream.decoder) leonida_opus_decoder_reset(stream.decoder); +#endif + } else if (id.kind == kProcess) { + ProcessCommand p; + std::memcpy(&p, command, sizeof(p)); + if (!stream.active) r.error = kInvalidStream; + else fill(*c, stream, p, r); + } + try { + c->results.push_back(r); + } catch (...) { // out of memory: refuse the command, nothing may unwind into the title + return E_OUTOFMEMORY; + } + ++stream.pending; + ++c->accepted; + if (accepted_so_far) *accepted_so_far = c->accepted; + if ((id.options & kSignalWhenDone) && c->event) SetEvent(c->event); + return S_OK; +} + +HRESULT __stdcall XApuDequeueResult(Connection* c, Result* out) { + note("XApuDequeueResult", 0, _ReturnAddress()); + if (!c || !out) return E_INVALIDARG; + const std::lock_guard lock(c->mutex); + if (c->results.empty()) return kNoResult; + const Result r = c->results.front(); + c->results.pop_front(); + --c->streams[r.id.stream].pending; + ++c->dequeued; + std::memcpy(out, &r, sizeof(r)); + return S_OK; +} + +uint32_t __stdcall XApuGetResultCount(Connection* c, uint32_t* dequeued_so_far) { + note("XApuGetResultCount", 0, _ReturnAddress()); + if (!c) return 0; + const std::lock_guard lock(c->mutex); + if (dequeued_so_far) *dequeued_so_far = c->dequeued; + return static_cast(c->results.size()); +} + +} // 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)}, +); diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp index 384f7bd278..cbd857fce9 100644 --- a/runtime/shims/xmem.cpp +++ b/runtime/shims/xmem.cpp @@ -1032,12 +1032,62 @@ constexpr size_t kUnmapRecords = 1024; UnmapRecord g_unmaps[kUnmapRecords]; uint64_t g_unmap_count = 0; thread_local const char* t_unmap_cause = "unmap"; + +// A remap of physical pages (XMemMapPhysicalPages with pages, the scatter call, CopyPageMappingsBatchX): the pages +// whose frame it took away. unmap_range_locked records each page that held a frame while one is installed (under the +// fault lock: host_heap only, nothing else); when it goes, with g_phys_mutex still held and the fault lock not, every +// page now mapped to another frame than it had (or to none) is reported as released, in runs, so the geometry copies +// over it are retired as over freed or unmapped memory (geometry_writes::note_released, GeometryViews::drain_released): +// the title streams by remapping the frames of its pools, and the copies of what those pages held before were kept +// for the device's life. A page mapped again to the frame it had is no change. LEONIDA_GEOMETRY_REMAP_RELEASE=0: off. +bool remap_releases_enabled() { + static const bool on = [] { + const char* v = std::getenv("LEONIDA_GEOMETRY_REMAP_RELEASE"); + return !v || std::strcmp(v, "0") != 0; + }(); + return on; +} +struct RemapReleases; +thread_local RemapReleases* t_remap_releases = nullptr; +struct RemapReleases { + leonida::host_heap::vector> pages; // address, the frame it had + bool active = false; + RemapReleases() { + if (!t_remap_releases && remap_releases_enabled()) { + t_remap_releases = this; + active = true; + } + } + RemapReleases(const RemapReleases&) = delete; + RemapReleases& operator=(const RemapReleases&) = delete; + ~RemapReleases(); // g_phys_mutex held, the fault lock not +}; struct UnmapCause { const char* was; explicit UnmapCause(const char* cause) : was(std::exchange(t_unmap_cause, cause)) {} ~UnmapCause() { t_unmap_cause = was; } }; +RemapReleases::~RemapReleases() { + if (!active) return; + t_remap_releases = nullptr; + if (pages.empty()) return; + std::sort(pages.begin(), pages.end()); + uintptr_t run_begin = 0, run_end = 0; + for (const auto& [at, frame] : pages) { + const auto now = g_mapped.find(at); + if (now != g_mapped.end() && now->second == frame) continue; // the frame it had: no change + if (run_end == at && run_end > run_begin) { + run_end = at + kPhysicalPageSize; + continue; + } + if (run_end > run_begin) leonida::geometry_writes::note_released(run_begin, run_end); + run_begin = at; + run_end = at + kPhysicalPageSize; + } + if (run_end > run_begin) leonida::geometry_writes::note_released(run_begin, run_end); +} + // With g_fault_lock held exclusively. 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. @@ -1064,6 +1114,7 @@ bool unmap_range_locked(uintptr_t start, uintptr_t end) { // 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()) { + if (t_remap_releases) t_remap_releases->pages.emplace_back(at, mapped->second); note_mapping(mapped->second, at, false); g_mapped.erase(mapped); } @@ -1575,7 +1626,7 @@ LONG CALLBACK physical_page_fault(EXCEPTION_POINTERS* info) { MEMORY_BASIC_INFORMATION seen{}; // the page as the decision saw it char read_note[1024]; DWORD read_note_size = 0; - bool plant_read = false, promote = false; + bool plant_read = false, promote = false, from_title = false; bool queried = false; { const FaultLockShared lock; @@ -1594,7 +1645,8 @@ LONG CALLBACK physical_page_fault(EXCEPTION_POINTERS* info) { if (where != kNoReservation || access == 1) queried = VirtualQuery(reinterpret_cast(accessed), &seen, sizeof(seen)) != 0; const auto pc = reinterpret_cast(record->ExceptionAddress); - if (access == 0 && result == PageCommit::not_ours && title_code(pc)) { + from_title = access == 0 && result == PageCommit::not_ours && title_code(pc); + if (from_title) { if (!queried) queried = VirtualQuery(reinterpret_cast(accessed), &seen, sizeof(seen)) != 0; read_note_size = describe_read(read_note, pc, accessed, seen); plant_read = where == kInWindow && g_pool_zero_pages; @@ -1670,7 +1722,8 @@ LONG CALLBACK physical_page_fault(EXCEPTION_POINTERS* info) { exit = FaultExit::committed; } else if (answered) { exit = FaultExit::answered; - } else if (result == PageCommit::committed_before && !escalated) { + } else if ((result == PageCommit::committed_before && !escalated) || + (title_page && access == 0 && result == PageCommit::not_ours && !from_title)) { exit = FaultExit::passed_guarded; // a guard's (the D3D12 layer's), routine: not noted } else if (title_page || reserved_write) { note_fault(kRefused, accessed, access, result, where, seen); @@ -1834,6 +1887,7 @@ void* WINAPI XMemMapPhysicalPages(void* address, uint64_t page_count, const uint } drain_fault_notes(); const std::lock_guard lock(g_phys_mutex); + RemapReleases remap_releases; // reported as it goes: after the fault lock, with g_phys_mutex const uintptr_t end = start + page_count * kPhysicalPageSize; const UnmapCause cause(page_array ? "XMemMapPhysicalPages (remap)" : "XMemMapPhysicalPages (unmap)"); if (!page_array) { @@ -1957,6 +2011,7 @@ BOOL scatter_refused(ScatterFailure reason, uintptr_t address, DWORD error) { BOOL WINAPI XMemMapPhysicalPagesScatter(void* const* addresses, uint32_t page_count, const uint64_t* page_array) { drain_fault_notes(); const std::lock_guard lock(g_phys_mutex); + RemapReleases remap_releases; if (page_count && !addresses) { return scatter_refused(ScatterFailure::missing_addresses, 0, ERROR_INVALID_PARAMETER); } @@ -1969,6 +2024,7 @@ BOOL WINAPI XMemMapPhysicalPagesScatter(void* const* addresses, uint32_t page_co return scatter_refused(ScatterFailure::unaligned, address, ERROR_INVALID_PARAMETER); } const uint64_t page = page_array ? page_array[i] : 0; + const UnmapCause cause(page ? "XMemMapPhysicalPagesScatter (remap)" : "XMemMapPhysicalPagesScatter (unmap)"); if (page == 0) { if (!unmap_page(address)) return scatter_refused(ScatterFailure::unmap, address, GetLastError()); continue; @@ -1991,6 +2047,34 @@ BOOL WINAPI XMemMapPhysicalPagesScatter(void* const* addresses, uint32_t page_co // calls with the same page make them. Every source page is looked up before any destination page changes, so a source // range that overlaps the destination maps what was there before the call. A destination in a GPU-only range is mapped // at its paired CPU range too (title_gpu_views), and a source page missing at a GPU-only address is looked up there. +// A page of that CPU range the title mapped itself is the title's (title_mapped_twin): the copy leaves it as it is. + +// With g_phys_mutex held. True when the paired CPU page at `address` holds a mapping of the title's own: its +// XMemMapPhysicalPages or XMemMapPhysicalPagesScatter call, or a slot-31 copy onto that address. The console's +// CopyPageMappingsBatchX changes only the GPU-only range's page table, so such a page keeps what the title put +// there; only a page the copy mirrored there itself (MapOwner::mirror), a zero plant, or a page with no mapping +// follows the GPU-only range. Each page kept is counted, and the first ones logged. +bool title_mapped_twin(uintptr_t address, uintptr_t gpu, bool unmap) { + MapOwner owner; + { + const FaultLockShared faults; + uintptr_t base = 0; + const View* const view = covering_view(address, base); + if (!view || view->zero || view->owner == MapOwner::mirror) return false; + owner = view->owner; + } + static std::atomic kept{0}; + const uint64_t n = kept.fetch_add(1, std::memory_order_relaxed) + 1; + if (n <= 8 || (n & (n - 1)) == 0) + std::fprintf(stderr, + "[rt] xmem: slot-31 %s at 0x%llx left the title's %s mapping at its paired CPU page 0x%llx " + "(%llu such pages so far)\n", + unmap ? "unmap" : "copy", static_cast(gpu), + owner == MapOwner::scatter ? "scatter" : owner == MapOwner::slot31 ? "slot-31" : "physical", + static_cast(address), static_cast(n)); + return true; +} + bool copy_page_mappings(void* destination, const void* source, uint64_t pages, bool repeat_first) { const uintptr_t to = reinterpret_cast(destination); const uintptr_t from = reinterpret_cast(source); @@ -2005,14 +2089,21 @@ bool copy_page_mappings(void* destination, const void* source, uint64_t pages, b return false; } const std::lock_guard lock(g_phys_mutex); + RemapReleases remap_releases; // The destination is usually a GPU-only reservation, which the D3D12 layer reads at its paired CPU view // (title_gpu_views::to_cpu); that view gets the same pages, or it would stay reserved and never readable. const uintptr_t cpu_to = leonida::title_gpu_views::to_cpu(to, pages * kPhysicalPageSize); const Window* const cpu_window = cpu_to != to ? find_window(cpu_to, pages * kPhysicalPageSize) : nullptr; if (!source) { for (uint64_t i = 0; i < pages; ++i) { - if (!unmap_page(to + i * kPhysicalPageSize)) return false; - if (cpu_window && !unmap_page(cpu_to + i * kPhysicalPageSize)) return false; + const uintptr_t gpu = to + i * kPhysicalPageSize, cpu = cpu_to + i * kPhysicalPageSize; + { + const UnmapCause cause("CopyPageMappingsBatchX (unmap)"); + if (!unmap_page(gpu)) return false; + } + if (!cpu_window || title_mapped_twin(cpu, gpu, true)) continue; + const UnmapCause cause("CopyPageMappingsBatchX (unmap paired CPU page)"); + if (!unmap_page(cpu)) return false; } return true; } @@ -2035,8 +2126,11 @@ bool copy_page_mappings(void* destination, const void* source, uint64_t pages, b const DWORD cpu_protect = cpu_window ? view_protect(*cpu_window) : 0; for (uint64_t i = 0; i < pages; ++i) { const uint64_t page = found[static_cast(i)]; - if (!map_page(to + i * kPhysicalPageSize, page, protect, MapOwner::slot31)) return false; - if (cpu_window && !map_page(cpu_to + i * kPhysicalPageSize, page, cpu_protect, MapOwner::mirror)) return false; + const uintptr_t gpu = to + i * kPhysicalPageSize, cpu = cpu_to + i * kPhysicalPageSize; + const UnmapCause cause(page ? "CopyPageMappingsBatchX (remap)" : "CopyPageMappingsBatchX (hole)"); + if (!map_page(gpu, page, protect, MapOwner::slot31)) return false; + if (cpu_window && !title_mapped_twin(cpu, gpu, false) && !map_page(cpu, page, cpu_protect, MapOwner::mirror)) + return false; } return true; } @@ -2399,6 +2493,7 @@ bool copy_page_mappings(std::uint32_t count, const PageBatch* batches, std::uint std::vector frames; drain_fault_notes(); const std::lock_guard lock(g_phys_mutex); + RemapReleases remap_releases; try { for (uint32_t b = 0; b < count; ++b) { const auto& batch = batches[b]; diff --git a/runtime/shims/xmem.h b/runtime/shims/xmem.h index 96fb89e7ea..6e0017f2ba 100644 --- a/runtime/shims/xmem.h +++ b/runtime/shims/xmem.h @@ -55,7 +55,7 @@ enum class FaultExit : int { answered, // a mapped page committed, or found committed and allowed (another thread's map or commit) planted, // a window page the title never mapped, backed by a zero page committed, // a section page in the title's reservation with no view of xmem's, committed - passed_guarded, // a committed page of xmem's views whose protection refuses the access: its guard's to answer + passed_guarded, // a committed page whose protection refuses the access, or a host guarded read of an unmapped page passed_foreign, // memory that is not the title's reservation and not only reserved: someone else's fault left_to_title, // the title's reservation, or a write into memory that is only reserved: noted (FaultNote) count diff --git a/runtime/src/address_guard.h b/runtime/src/address_guard.h new file mode 100644 index 0000000000..dab43d40ab --- /dev/null +++ b/runtime/src/address_guard.h @@ -0,0 +1,163 @@ +// The address guard's page table (docs/d3d12_vulkan.md, "Address guard"): what the runtime backs around heap_base, +// for shaders translated with `tools/rdna2spirv.py --address-guard` (LEONIDA_ADDRESS_GUARD=1). Header-only, no +// Vulkan: the device writes the words this computes into a mapped buffer. tools/address_guard.py is the Python +// reference of the same format and of the check a guarded access makes. +// +// Layout. A header at arena offset kGuardHeader (64 bytes, AddressGuardHeader), then two sinks: refused loads read +// kGuardZero, refused stores and atomics write kGuardDump, each at the access's offset within its 4 KiB page. The +// page table is its own buffer; the header holds its address minus heap_base. Table words: kGuardLevel1 level-1 +// words indexed by bits 47..32 of the 48-bit heap offset (one per 4 GiB chunk), naming the chunk's level-2 block; +// then the blocks, kGuardBlockWords words each, one bit per 4 KiB page (bits 31..12). Block 0 is empty (nothing +// backed), block 1 full (everything passes: a chunk the table has no room for), blocks 2.. are allocated. +#pragma once + +#include +#include +#include +#include +#include + +namespace leonida::address_guard { + +// Shared with tools/rdna2spirv.py (GUARD_*) and tools/address_guard.py; tests/semantic/test_address_guard.py reads +// these lines. +constexpr std::uint64_t kGuardHeader = 0x70000; +constexpr std::uint64_t kGuardZero = 0x71000; +constexpr std::uint64_t kGuardDump = 0x78000; +constexpr std::uint64_t kGuardEnd = 0x80000; +constexpr std::uint32_t kGuardLevel1 = 1u << 16; +constexpr std::uint32_t kGuardBlockWords = 1u << 15; +constexpr char kGuardMagicText[] = "LGUARD01"; +constexpr std::uint64_t kMask48 = (1ull << 48) - 1; +constexpr std::uint32_t kEmptyBlock = 0, kFullBlock = 1, kFirstBlock = 2; + +constexpr std::uint64_t magic() { + std::uint64_t v = 0; + for (int i = 7; i >= 0; --i) v = v << 8 | std::uint8_t(kGuardMagicText[i]); + return v; +} + +struct AddressGuardHeader { + std::uint64_t magic; // magic(): the shaders check only when it is there + std::uint64_t limit; // the arena's size: an access below it passes without a lookup + std::uint64_t table; // the page table's device address minus heap_base (mod 2^64) + std::uint32_t refused; // the shaders add 1 per refused access + std::uint32_t last_module; // the last refusing module's id: FNV-1a of its file stem (shaders write it; diagnostics) + std::uint64_t last_refused; // the last refused access's heap offset (written by the shaders, not atomically) + std::uint8_t pad[24]; +}; +static_assert(sizeof(AddressGuardHeader) == 64); +static_assert(kGuardHeader + sizeof(AddressGuardHeader) <= kGuardZero && kGuardZero < kGuardDump && + kGuardDump < kGuardEnd); + +// The table's contents and the words that changed. Blocks are given to chunks for good: a chunk that loses its last +// backing keeps its (now empty) block, so a submission still in flight never reads a block that came to mean +// another chunk. When the blocks run out, a new chunk gets the full block (logged by the caller through +// overflowed()): its accesses then pass unchecked, as without the guard. +class AddressGuardTable { +public: + explicit AddressGuardTable(std::uint32_t blocks = 62) : blocks_(blocks) { + words_.assign(word_count(), 0); + std::fill_n(words_.begin() + kGuardLevel1 + std::size_t(kFullBlock) * kGuardBlockWords, kGuardBlockWords, + 0xFFFFFFFFu); + } + + std::size_t word_count() const { return kGuardLevel1 + std::size_t(kFirstBlock + blocks_) * kGuardBlockWords; } + std::size_t bytes() const { return word_count() * sizeof(std::uint32_t); } + // The whole table, for the first upload. + const std::vector& words() const { return words_; } + std::uint32_t blocks_used() const { return used_; } + std::uint32_t overflowed() const { return overflowed_; } + + // Make the table say exactly `spans` (heap offset [start, end), 48-bit; a span may wrap through 2^48 for a + // negative offset). A page any byte of a span touches is backed: the GPU maps memory in whole pages. Each word + // that changes is passed to `write(index, value)`, level-2 words before level-1 ones, so a reader that sees a + // chunk's new block also sees its bits. Returns the number of words written. + template + std::size_t assign(const std::vector>& spans, Write&& write) { + next_.assign(std::size_t(used_) * kGuardBlockWords, 0); + std::vector level1(words_.begin(), words_.begin() + kGuardLevel1); + for (const auto& [start, end] : spans) { + if (end == start) continue; + const std::uint64_t first = (start & kMask48) >> 12; + const std::uint64_t last = ((end - 1) & kMask48) >> 12; + if (first <= last) { + mark(level1, first, last); + } else { // wraps through 2^48: two runs + mark(level1, first, (kMask48 >> 12)); + mark(level1, 0, last); + } + } + std::size_t written = 0; + const std::size_t base = kGuardLevel1 + std::size_t(kFirstBlock) * kGuardBlockWords; + for (std::size_t i = 0; i < next_.size(); ++i) { + if (words_[base + i] == next_[i]) continue; + words_[base + i] = next_[i]; + write(base + i, next_[i]); + ++written; + } + for (std::uint32_t i = 0; i < kGuardLevel1; ++i) { + if (words_[i] == level1[i]) continue; + words_[i] = level1[i]; + write(std::size_t(i), level1[i]); + ++written; + } + return written; + } + + // The table's bit for the page of heap offset `offset`. + bool page_backed(std::uint64_t offset) const { + offset &= kMask48; + const std::uint32_t block = words_[(offset >> 32) & (kGuardLevel1 - 1)]; + const std::uint64_t page = (offset >> 12) & 0xFFFFF; + return (words_[kGuardLevel1 + std::size_t(block) * kGuardBlockWords + (page >> 5)] >> (page & 31)) & 1; + } + + // What a guarded access of `extent` bytes at heap offset `offset` does (the shaders' %guard_fn): passes when + // its first and last byte are below `limit` or on backed pages. `offset` is sign-extended from 48 bits. + bool passes(std::uint64_t offset, std::uint64_t extent, std::uint64_t limit) const { + if (offset & (1ull << 47)) offset |= ~kMask48; + else offset &= kMask48; + const std::uint64_t end = offset + extent - 1; + if (offset < limit && end < limit) return true; + return page_backed(offset) && page_backed(end); + } + +private: + // Set the bits of pages [first, last] (48-bit page numbers), giving their chunks blocks as needed. + void mark(std::vector& level1, std::uint64_t first, std::uint64_t last) { + for (std::uint64_t chunk = first >> 20; chunk <= last >> 20; ++chunk) { + std::uint32_t& block = level1[chunk]; + if (block == kEmptyBlock) { + if (used_ < blocks_) { + block = kFirstBlock + used_++; + next_.resize(std::size_t(used_) * kGuardBlockWords, 0); + } else { + block = kFullBlock; + ++overflowed_; + } + } + if (block < kFirstBlock) continue; + std::uint32_t* bits = next_.data() + std::size_t(block - kFirstBlock) * kGuardBlockWords; + const std::uint64_t lo = std::max(first, chunk << 20) & 0xFFFFF; + const std::uint64_t hi = std::min(last, (chunk << 20) | 0xFFFFF) & 0xFFFFF; + for (std::uint64_t page = lo; page <= hi;) { + if (!(page & 31) && page + 31 <= hi) { + bits[page >> 5] = 0xFFFFFFFFu; + page += 32; + } else { + bits[page >> 5] |= 1u << (page & 31); + ++page; + } + } + } + } + + std::uint32_t blocks_; + std::uint32_t used_ = 0; + std::uint32_t overflowed_ = 0; + std::vector words_; // what the GPU's copy holds + std::vector next_; // the allocated blocks being built by assign() +}; + +} // namespace leonida::address_guard diff --git a/runtime/src/conservative_raster.h b/runtime/src/conservative_raster.h index 469066d17f..82d6dfaca1 100644 --- a/runtime/src/conservative_raster.h +++ b/runtime/src/conservative_raster.h @@ -46,4 +46,21 @@ inline InnerCoverageRequirements inner_coverage_requirements(std::span words) { + if (words.size() < 5 || words[0] != 0x07230203) return false; + bool triangles = false; + for (std::size_t i = 5; i < words.size();) { + const auto count = words[i] >> 16, op = words[i] & 0xffff; + if (!count || count > words.size() - i) return false; + if (op == 16 && count >= 3) { // OpExecutionMode + if (words[i + 2] == 5298) triangles = true; + else if (words[i + 2] == 5269 || words[i + 2] == 27) return false; + } + i += count; + } + return triangles; +} } // namespace leonida::conservative_raster diff --git a/runtime/src/console_heap_copy.h b/runtime/src/console_heap_copy.h new file mode 100644 index 0000000000..96a1f1ad4a --- /dev/null +++ b/runtime/src/console_heap_copy.h @@ -0,0 +1,97 @@ +#pragma once +// A console resource heap's translated copy (DeviceState::ConsoleHeap::copy): the bytes shaders read, and a host-RAM +// mirror of them that the CPU reads instead. +// +// The copy lies in the GPU address arena when the import of host memory is not used (arena.mapped + offset), and the +// arena prefers DEVICE_LOCAL | HOST_VISIBLE memory (ReBAR): a CPU read of it is an uncached read across PCIe. The +// release sweep of refresh_console_heap with LEONIDA_CONSOLE_RELEASE_FILTER=1 reads words 0-2 of both V# halves of +// every live V# slot (about 470k in a game run) to decide whether the slot needs fixing, and that read cost +// 0.9-1.0 s a sweep. Every CPU write goes through write() and zero(), which write both the copy and the mirror, so +// view() (the mirror, or the copy when there is none) holds what the GPU reads. +// +// No mirror when the copy is already host RAM (the import of the heap's own scratch), when LEONIDA_HEAP_MIRROR=0, or +// once the copy is written by the GPU pass (LEONIDA_CONSOLE_HEAP_GPU: drop_mirror(); the CPU neither writes nor reads +// the copy then). The mirror covers the heap's bytes only, not the null guard after them (written once, at creation). +// +// LEONIDA_HEAP_MIRROR_CHECK=1: refresh_console_heap compares the mirror with the copy at every release sweep +// (mismatches()) and logs the first slots that differ. + +#include +#include +#include +#include +#include + +namespace leonida { + +class ConsoleHeapCopy { +public: + // `gpu`: the copy shaders read; `bytes`: the heap's bytes (the mirror's size, when `mirrored`). + void attach(std::uint8_t* gpu, std::size_t bytes, bool mirrored) { + gpu_ = gpu; + bytes_ = bytes; + mirror_.clear(); + mirror_.shrink_to_fit(); + if (gpu && mirrored) mirror_.assign(bytes, 0); + } + // The mirror goes; view() is the copy from now on. + void drop_mirror() { + mirror_.clear(); + mirror_.shrink_to_fit(); + } + + explicit operator bool() const noexcept { return gpu_ != nullptr; } + std::uint8_t* gpu() const noexcept { return gpu_; } + bool mirrored() const noexcept { return !mirror_.empty(); } + std::size_t bytes() const noexcept { return bytes_; } + + // What the CPU reads: the mirror, or the copy itself. + const std::uint8_t* view() const noexcept { return mirror_.empty() ? gpu_ : mirror_.data(); } + + // [at, at + n) of the copy, and of the mirror where it reaches. + void write(std::size_t at, const void* bytes, std::size_t n) { + std::memcpy(gpu_ + at, bytes, n); + if (const std::size_t m = mirror_span(at, n)) std::memcpy(mirror_.data() + at, bytes, m); + } + void zero(std::size_t at, std::size_t n) { + std::memset(gpu_ + at, 0, n); + if (const std::size_t m = mirror_span(at, n)) std::memset(mirror_.data() + at, 0, m); + } + + // LEONIDA_HEAP_MIRROR_CHECK: the slots of `slot_bytes` whose mirror bytes differ from the copy's, at most `limit` + // of them in `out` (in ascending order); returns how many slots differ in all. 0 without a mirror. + std::size_t mismatches(std::size_t slot_bytes, std::size_t limit, std::vector& out) const { + out.clear(); + if (mirror_.empty() || !slot_bytes) return 0; + // Read the copy in large blocks: one pass over device memory, compared in host RAM. + constexpr std::size_t kBlock = std::size_t(1) << 16; + std::vector block; + std::size_t count = 0; + const std::size_t step = std::max(slot_bytes, kBlock / slot_bytes * slot_bytes); + for (std::size_t at = 0; at < bytes_; at += step) { + const std::size_t n = std::min(step, bytes_ - at); + block.resize(n); + std::memcpy(block.data(), gpu_ + at, n); + if (!std::memcmp(block.data(), mirror_.data() + at, n)) continue; + for (std::size_t s = 0; s < n; s += slot_bytes) { + const std::size_t k = std::min(slot_bytes, n - s); + if (!std::memcmp(block.data() + s, mirror_.data() + at + s, k)) continue; + if (out.size() < limit) out.push_back((at + s) / slot_bytes); + ++count; + } + } + return count; + } + +private: + std::size_t mirror_span(std::size_t at, std::size_t n) const noexcept { + if (mirror_.empty() || at >= mirror_.size()) return 0; + return std::min(n, mirror_.size() - at); + } + + std::uint8_t* gpu_ = nullptr; + std::size_t bytes_ = 0; + std::vector mirror_; +}; + +} // namespace leonida diff --git a/runtime/src/dstorage_hold.h b/runtime/src/dstorage_hold.h new file mode 100644 index 0000000000..1695c1e7c8 --- /dev/null +++ b/runtime/src/dstorage_hold.h @@ -0,0 +1,23 @@ +// Counters of the DirectStorage queues' rule "reads into physical pages wait for the title's Submit" +// (shims/dstorage.cpp, docs/directstorage.md). Process-wide, so the log line and the test read the same numbers. +#pragma once + +#include +#include + +namespace leonida::dstorage { + +struct HoldStats { + std::atomic self_submits{0}; // a queue half full submitted itself + std::atomic held_reads{0}; // reads into physical pages such a submit left for the title's Submit + std::atomic full_releases{0}; // a full queue submitted its held entries (the title waits in an enqueue) + std::atomic timed_releases{0}; // LEONIDA_DSTORAGE_HOLD_MS ran out before the title's Submit + std::atomic page0_entries{0}; // destination page lists that named page 0 when their data was written +}; + +inline HoldStats& hold_stats() { + static HoldStats stats; + return stats; +} + +} // namespace leonida::dstorage diff --git a/runtime/src/heavy_pipeline_cache.h b/runtime/src/heavy_pipeline_cache.h new file mode 100644 index 0000000000..8cad10e660 --- /dev/null +++ b/runtime/src/heavy_pipeline_cache.h @@ -0,0 +1,94 @@ +// A pipeline cache that survives a crash, for the pipelines the offline corpus does not have (RT-HEAVY-PIPELINE-CACHE). +// +// The offline seed (pipeline_cache.bin, several GiB) covers what the `pipelines` build stage creates. A pipeline it +// misses is compiled on the spot, and some of those take the driver seconds each. pipeline_cache.session.bin cannot +// keep them across a crash: it is written at device teardown only, and a cache seeded from the corpus returns the +// whole corpus, over its write limit, so it is not written at all. +// +// So a pipeline is first created against the corpus cache with VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED. +// When the driver would have to compile, it is created again against a cache of its own, seeded from +// pipeline_cache.heavy.bin. That cache holds only the corpus's misses, so it stays small. After a compile that took +// at least LEONIDA_HEAVY_PIPELINE_CACHE_MS (default 500 ms), it is written back to disk on a thread of its own: a +// staging file renamed over the old one, so a crash at any point leaves the last complete file. +// +// This header holds the pure decisions (the threshold and when to write). Vulkan and the file live in the device. +#pragma once + +#include +#include + +namespace leonida::heavy_pipeline_cache { + +inline constexpr std::uint32_t default_threshold_ms = 500; + +struct Threshold { + std::uint32_t ms = default_threshold_ms; // 0: off + bool valid = true; // false: the text was not a number; ms stays the default +}; + +// LEONIDA_HEAVY_PIPELINE_CACHE_MS: a compile at least this long schedules a write; 0 turns the heavy cache off. +inline Threshold parse_threshold(const char* text) { + if (!text || !*text) return {}; + std::uint64_t value = 0; + for (const char* p = text; *p; ++p) { + if (*p < '0' || *p > '9') return {default_threshold_ms, false}; + value = value * 10 + std::uint64_t(*p - '0'); + if (value > 3'600'000) return {default_threshold_ms, false}; // an hour: past it the text is a mistake + } + return {std::uint32_t(value), true}; +} + +// When the writer thread writes. A heavy compile marks the cache dirty; the write waits `settle_ms` after the +// newest one (heavy compiles come in bursts at a load, and each write copies the whole heavy cache) but never more +// than `max_delay_ms` after the first unwritten one, so a long burst is still saved as it goes. A write that fails +// keeps the cache dirty and is tried again `retry_ms` later, the delay doubling with each failure in a row up to +// `max_retry_ms`, so a disk that stays full or a driver that keeps failing does not make the writer spin. +class WriteSchedule { +public: + static constexpr std::uint64_t settle_ms = 3000; + static constexpr std::uint64_t max_delay_ms = 20000; + static constexpr std::uint64_t retry_ms = 5000; + static constexpr std::uint64_t max_retry_ms = 120000; + + void note_heavy(std::uint64_t now_ms) { + if (!dirty_) first_ = now_ms; + dirty_ = true; + last_ = now_ms; + ++generation_; + } + bool dirty() const { return dirty_; } + // The time to write at; only meaningful while dirty. + std::uint64_t due_ms() const { + const std::uint64_t settled = last_ + settle_ms, latest = first_ + max_delay_ms; + const std::uint64_t at = settled < latest ? settled : latest; + return at > retry_at_ ? at : retry_at_; + } + bool due(std::uint64_t now_ms) const { return dirty_ && now_ms >= due_ms(); } + // Taken when a write starts; the write covers every heavy compile noted up to then. + std::uint64_t generation() const { return generation_; } + // A write that started at `generation` and `started_ms` is done. A heavy compile noted after it started, even in + // the same millisecond tick, keeps the cache dirty for the next write, due as if it were first noted then. + void written(std::uint64_t generation, std::uint64_t started_ms) { + failures_ = 0; + retry_at_ = 0; + if (generation_ == generation) dirty_ = false; + else first_ = started_ms; + } + // A write that started at `started_ms` failed: the cache stays dirty and the next try waits out the backoff. + void failed(std::uint64_t started_ms) { + std::uint64_t delay = retry_ms; + for (std::uint32_t i = 0; i < failures_ && delay < max_retry_ms; ++i) delay *= 2; + if (delay > max_retry_ms) delay = max_retry_ms; + if (failures_ < 64) ++failures_; + retry_at_ = started_ms + delay; + } + std::uint32_t failures() const { return failures_; } + +private: + bool dirty_ = false; + std::uint64_t first_ = 0, last_ = 0, generation_ = 0; + std::uint32_t failures_ = 0; // failed writes in a row + std::uint64_t retry_at_ = 0; // no write before this time after a failure +}; + +} // namespace leonida::heavy_pipeline_cache diff --git a/runtime/src/list_value_wait_budget.h b/runtime/src/list_value_wait_budget.h new file mode 100644 index 0000000000..8e1fd52190 --- /dev/null +++ b/runtime/src/list_value_wait_budget.h @@ -0,0 +1,251 @@ +#pragma once +// Work-aware timeout clock and cycle-safe producer dependency analysis for console command-list memory waits +// (runtime/shims/d3d12_xs_list_values.h, docs/d3d12_xs_console_abi.md §5.5). +// +// A memory wait gate needs a bounded timeout so an unmodelled write (one the runtime never lands) cannot hang a queue +// forever. Counting wall-clock time blindly cuts waits short whenever the runtime is busy running held work (e.g. +// multi-second CPU shadow/texture copies inside the releaser) or while an in-flight producer write has not finished on +// the GPU yet, running dependent queues out of order. +// +// This header separates the policy from Windows/D3D12 handles so it can be verified portably under sanitizers: +// - `pause_reason()` decides whether submitted or held work can still satisfy a gate without creating a deadlock cycle: +// 1. `releaser_busy`: held work from an already-opened gate is currently being released/submitted; +// 2. `matching_producer`: an in-flight WriteGroup whose final write to a waited address can satisfy an unmet wait, and +// every pending gate preceding that WriteGroup is cycle-free with respect to the waiting queue; +// 3. `active_work`: unrelated unblocked GPU work (a WriteGroup or action gate with no pending gate ahead of it) is +// still executing, paused only up to `active_pause_cap_us` so a continuously streaming queue cannot starve an +// unmodelled wait. +// - `GateTimeoutState` tracks idle wait time (`elapsed_us`) separately from paused time, expiring once `elapsed_us` +// reaches `budget_us`. Every pause reason (`releaser_busy` and `matching_producer` included) is bounded by a finite +// `max_pause_cap_us` so a producer stuck behind an untracked dependency (e.g. a title fence wait or a hung Signal) +// still expires instead of hanging forever, and demoted (`cut_short`) gates scale both caps with their short budget. +// +// Pure C++20 standard library only. + +#include +#include +#include +#include +#include + +namespace leonida::list_value_wait { + +enum class PauseReason : std::uint8_t { + none = 0, // no submitted or held work can still satisfy this gate -> timeout clock ticks + releaser_busy = 1, // releaser thread is executing or draining opened gates + matching_producer = 2, // an acyclic in-flight WriteGroup can satisfy an unmet wait of this gate + active_work = 3, // unrelated unblocked submitted work is still executing (bounded by active_pause_cap_us) +}; + +struct WaitPredicate { + std::uint64_t address = 0; + std::uint64_t reference = 0; + std::uint32_t comparison = 0; + bool wide = false; +}; + +struct PendingWrite { + std::uint64_t address = 0; + std::uint64_t value = 0; + std::uint8_t bytes = 0; + bool timestamp = false; // GPU/system timestamp: final value is unknown until landing +}; + +struct PendingWriteGroup { + const void* queue = nullptr; + std::uint64_t after_gate = 0; // highest pending gate value on `queue` ahead of this group when submitted (0: none) + std::span writes; +}; + +struct PendingGate { + const void* queue = nullptr; + std::uint64_t value = 0; + bool is_action = false; // waits only on earlier GPU work on `queue`, never on memory + std::span unmet_waits; // waits not currently satisfied in memory (empty for action gates) +}; + +struct PauseCaps { + std::uint64_t active_us = 0; // cap on pausing solely for unrelated active_work + std::uint64_t max_us = 0; // hard finite cap across ALL pause reasons (releaser_busy, matching_producer, active_work) +}; + +// Pause caps scaled with the gate's own timeout budget (`gate_timeout_ms`) and demotion state (`cut_short`): +// - Normal gates: `active_us = 300x` and `max_us = 1500x` of `gate_timeout_ms`, capped at 10 min. At the default +// 200 ms timeout this allows up to 60 s for unrelated GPU work and up to 300 s (5 min) while the releaser or an +// acyclic matching producer is working (covering multi-minute world-phase pipeline builds), while guaranteeing a +// finite exit if a producer is held behind an untracked dependency (title fence wait or stuck Signal). +// - Demoted (`cut_short`) gates: `active_us = 1x` and `max_us = 4x` of `gate_timeout_ms` (4 ms / 16 ms at the 4 ms +// demoted budget), so an unmodelled wait only pays a few milliseconds instead of inheriting the full timeout's cap. +inline constexpr PauseCaps default_pause_caps(unsigned gate_timeout_ms, bool cut_short = false) { + constexpr std::uint64_t kMaxCapMs = 600000u; // 10 min hard ceiling + const std::uint64_t base_ms = gate_timeout_ms ? std::uint64_t{gate_timeout_ms} : 1u; + const auto scale_ms = [base_ms](std::uint64_t mult) -> std::uint64_t { + return base_ms > kMaxCapMs / mult ? kMaxCapMs : base_ms * mult; + }; + const std::uint64_t active_ms = cut_short ? (base_ms < kMaxCapMs ? base_ms : kMaxCapMs) : scale_ms(300u); + const std::uint64_t max_ms = cut_short ? scale_ms(4u) : scale_ms(1500u); + return {active_ms * 1000u, max_ms * 1000u}; +} + +inline constexpr std::uint64_t default_active_pause_cap_us(unsigned gate_timeout_ms, bool cut_short = false) { + return default_pause_caps(gate_timeout_ms, cut_short).active_us; +} + +inline constexpr std::uint64_t default_max_pause_cap_us(unsigned gate_timeout_ms, bool cut_short = false) { + return default_pause_caps(gate_timeout_ms, cut_short).max_us; +} + +struct GateTimeoutState { + std::uint64_t budget_us = 0; + std::uint64_t elapsed_us = 0; + std::uint64_t active_paused_us = 0; + std::uint64_t active_pause_cap_us = 0; + std::uint64_t total_paused_us = 0; + std::uint64_t max_pause_cap_us = 0; + bool paused_ever = false; + + void reset(std::uint64_t budget, std::uint64_t active_cap, std::uint64_t max_cap) { + budget_us = budget; + elapsed_us = 0; + active_paused_us = 0; + total_paused_us = 0; + max_pause_cap_us = max_cap; + active_pause_cap_us = active_cap < max_cap ? active_cap : max_cap; + paused_ever = false; + } + + // Advances the gate by `dt_us` under `reason`. Returns true once the idle timeout budget is exhausted. + // Every pause reason is bounded by `max_pause_cap_us`; unrelated `active_work` is additionally bounded by + // `active_pause_cap_us`. + bool advance(std::uint64_t dt_us, PauseReason reason) { + std::uint64_t room = 0; + if (reason == PauseReason::releaser_busy || reason == PauseReason::matching_producer) { + room = total_paused_us < max_pause_cap_us ? max_pause_cap_us - total_paused_us : 0u; + } else if (reason == PauseReason::active_work) { + const std::uint64_t total_room = + total_paused_us < max_pause_cap_us ? max_pause_cap_us - total_paused_us : 0u; + const std::uint64_t active_room = + active_paused_us < active_pause_cap_us ? active_pause_cap_us - active_paused_us : 0u; + room = total_room < active_room ? total_room : active_room; + } + if (room > 0) { + if (dt_us == 0) return false; + paused_ever = true; + const std::uint64_t absorb = dt_us < room ? dt_us : room; + total_paused_us += absorb; + if (reason == PauseReason::active_work) active_paused_us += absorb; + dt_us -= absorb; + } + if (dt_us > UINT64_MAX - elapsed_us) + elapsed_us = UINT64_MAX; + else + elapsed_us += dt_us; + return elapsed_us >= budget_us; + } +}; + +namespace detail { + +// True when `group`'s final write touching [wait.address, wait.address + need) lands a value that meets `wait` +// (or is a timestamp write to the exact address whose runtime value is unknown until landing). +template +inline bool write_group_matches_wait(const PendingWriteGroup& group, const WaitPredicate& wait, MetFn&& met) { + const std::uint64_t need = wait.wide ? 8u : 4u; + if (!wait.address || wait.address > UINT64_MAX - need) return false; + const std::uint64_t wait_end = wait.address + need; + for (std::size_t i = group.writes.size(); i-- > 0;) { + const PendingWrite& w = group.writes[i]; + if (!w.bytes || w.address > UINT64_MAX - w.bytes) continue; + const std::uint64_t write_end = w.address + w.bytes; + if (w.address >= wait_end || wait.address >= write_end) continue; + if (w.address == wait.address && w.bytes >= need && + (w.timestamp || met(wait.comparison, w.value, wait.reference, wait.wide))) + return true; + // A later write in the same group overwrote or partially overlapped the waited range with a non-matching value. + return false; + } + return false; +} + +// True when no pending gate in `gates` precedes `(queue, after_gate)`. +inline bool is_unblocked(std::span gates, const void* queue, std::uint64_t after_gate) { + if (!after_gate) return true; + for (const PendingGate& g : gates) + if (g.queue == queue && g.value <= after_gate) return false; + return true; +} + +// True when `gate_idx` (directly or transitively via matching in-flight writes) depends on a gate on `target_queue`. +template +inline bool gate_can_reach_queue(std::size_t gate_idx, const void* target_queue, + std::span writes, std::span gates, + MetFn&& met, std::vector& visiting) { + const PendingGate& g = gates[gate_idx]; + if (g.queue == target_queue) return true; + if (g.is_action) return false; + if (std::find(visiting.begin(), visiting.end(), gate_idx) != visiting.end()) return false; + visiting.push_back(gate_idx); + for (const WaitPredicate& wait : g.unmet_waits) { + for (const PendingWriteGroup& w : writes) { + if (!write_group_matches_wait(w, wait, met)) continue; + if (!w.after_gate) continue; + for (std::size_t b = 0; b < gates.size(); ++b) { + if (gates[b].queue != w.queue || gates[b].value > w.after_gate) continue; + if (gates[b].queue == target_queue || + gate_can_reach_queue(b, target_queue, writes, gates, met, visiting)) { + visiting.pop_back(); + return true; + } + } + } + } + visiting.pop_back(); + return false; +} + +} // namespace detail + +// Decides whether the timeout clock of `gates[target_idx]` should pause on this pump pass. +// `met(comparison, value, reference, wide)` must implement the same predicate as `console_value_met`. +template +inline PauseReason pause_reason(bool releaser_busy, std::span writes, + std::span gates, std::size_t target_idx, MetFn&& met) { + if (releaser_busy) return PauseReason::releaser_busy; + if (target_idx >= gates.size()) return PauseReason::none; + const PendingGate& target = gates[target_idx]; + if (target.is_action) return PauseReason::none; + + // 1. A matching in-flight WriteGroup whose preceding gates (if any) do not cycle back to `target.queue`. + std::vector visiting; + for (const WaitPredicate& wait : target.unmet_waits) { + for (const PendingWriteGroup& w : writes) { + if (!detail::write_group_matches_wait(w, wait, met)) continue; + bool cyclic = false; + if (w.after_gate) { + for (std::size_t b = 0; b < gates.size(); ++b) { + if (gates[b].queue != w.queue || gates[b].value > w.after_gate) continue; + visiting.clear(); + if (gates[b].queue == target.queue || + detail::gate_can_reach_queue(b, target.queue, writes, gates, met, visiting)) { + cyclic = true; + break; + } + } + } + if (!cyclic) return PauseReason::matching_producer; + } + } + + // 2. Unrelated unblocked submitted GPU work (an unblocked WriteGroup on any queue, or an unblocked action gate on + // another queue) that could still write memory via a shader/copy or unblock a CPU producer. + for (const PendingWriteGroup& w : writes) { + if (detail::is_unblocked(gates, w.queue, w.after_gate)) return PauseReason::active_work; + } + for (const PendingGate& g : gates) { + if (!g.is_action || g.queue == target.queue) continue; + if (g.value == 0 || detail::is_unblocked(gates, g.queue, g.value - 1)) return PauseReason::active_work; + } + return PauseReason::none; +} + +} // namespace leonida::list_value_wait diff --git a/runtime/src/title_geometry_watch.h b/runtime/src/title_geometry_watch.h index ca600fb9b3..dfb0ae5b52 100644 --- a/runtime/src/title_geometry_watch.h +++ b/runtime/src/title_geometry_watch.h @@ -1,6 +1,7 @@ #pragma once #include "title_page_watch.h" +#include #include #include #include @@ -72,7 +73,22 @@ inline void note_released(std::uintptr_t begin, std::uintptr_t end) { std::lock_guard subscribers_lock(s.subscribers_mutex); for (ReleaseQueue* q : s.subscribers) { std::lock_guard lock(q->mutex); - if (q->ranges.size() < 65536) { + bool room = q->ranges.size() < 65536; + if (!room) { + // Full: first the ranges that overlap or touch become one (remaps report page runs, often neighbours), and + // only when that leaves it more than half full does it all become one covering range. + std::sort(q->ranges.begin(), q->ranges.end()); + std::size_t kept = 0; + for (std::size_t i = 1; i < q->ranges.size(); ++i) { + if (q->ranges[i].first <= q->ranges[kept].second) + q->ranges[kept].second = (std::max)(q->ranges[kept].second, q->ranges[i].second); + else + q->ranges[++kept] = q->ranges[i]; + } + q->ranges.resize(kept + 1); + room = q->ranges.size() <= 32768; + } + if (room) { q->ranges.emplace_back(begin, end); } else { std::uintptr_t merged_lo = begin; diff --git a/runtime/src/title_texture_memory.h b/runtime/src/title_texture_memory.h index a97e5bed66..ff9f004e07 100644 --- a/runtime/src/title_texture_memory.h +++ b/runtime/src/title_texture_memory.h @@ -1,14 +1,17 @@ #pragma once #include +#include #include #include #include +#include "title_page_watch.h" + namespace leonida { // Keep negative probes until the title changes the map or a writer reports this footprint. With cache_success, -// positive ones too: a caller that is told of every map change over the footprint (retry) and reads it under a guard -// (a page gone since faults into a defer) need not walk the pages before every read. +// positive ones too: a caller that is told of every map change over the footprint (retry or sync_map) and reads it +// under a guard (a page gone since faults into a defer) need not walk the pages before every read. class TextureReadability { public: template @@ -16,16 +19,37 @@ class TextureReadability { if (cache_failure && pending_ && !retry_ && generation_ == generation) return false; if (cache_success && probed_ && !pending_ && !retry_ && generation_ == generation) return true; generation_ = generation; // snapshot before the probe so a concurrent map change is noticed + map_generation_ = title_memory_map::generation(); retry_ = false; probed_ = true; pending_ = !probe(); return !pending_; } + // Between refresh passes, check whether the map journal recorded a change over [cpu, cpu + size) since both + // this texture's last probe and the last pass's sweep. + void sync_map(std::uint64_t pass_generation, std::uintptr_t cpu, std::uint64_t size) { + if (!probed_ || retry_) return; + const std::uint64_t since = (std::max)(map_generation_, pass_generation); + if (title_memory_map::generation() == since) return; + const std::uintptr_t end = size > (std::numeric_limits::max)() - cpu + ? (std::numeric_limits::max)() + : cpu + static_cast(size); + std::uint64_t now = 0; + bool overlapped = false; + if (!title_memory_map::changes_since( + since, now, cpu, end, [&](std::uintptr_t, std::uintptr_t) { overlapped = true; }) || + overlapped) { + retry_ = true; + } else { + map_generation_ = now; + } + } 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; + std::uint64_t map_generation_ = 0; bool pending_ = false, retry_ = false, probed_ = false; }; diff --git a/runtime/src/title_va_alias.h b/runtime/src/title_va_alias.h index f3fd2b410d..66a7f58947 100644 --- a/runtime/src/title_va_alias.h +++ b/runtime/src/title_va_alias.h @@ -45,6 +45,9 @@ class TitleVaAliases { // 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); + // Every binding resolved to a copy of the title's memory: [va, va + bytes) as they are reached at (the device keeps + // them for the copy back after the submission, see DeviceState::write_back_titles). + using Noter = void (*)(void* context, std::uint64_t va, std::uint64_t bytes); // [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. @@ -180,6 +183,7 @@ class TitleVaAliases { std::uint64_t to = shader_va(va); if (to != va) { translated_[kind].fetch_add(1, std::memory_order_relaxed); + note_reached(va, bytes); return to; } Resolver resolver; @@ -191,6 +195,7 @@ class TitleVaAliases { } if (!resolver || !resolver(context, va, bytes, to)) return va; (to != va ? translated_ : untranslated_)[kind].fetch_add(1, std::memory_order_relaxed); + if (to != va) note_reached(va, bytes); return to; } @@ -200,6 +205,18 @@ class TitleVaAliases { if (va && shader_va(va) != va) untranslated_[kind].fetch_add(1, std::memory_order_relaxed); } + // [va, va + bytes) is reached as a copy of the title's memory: the device keeps it for the copy back. + void note_reached(std::uint64_t va, std::uint64_t bytes) { + Noter noter; + void* context; + { + std::lock_guard lock(hook_mutex_); + noter = noter_; + context = hook_context_; + } + if (noter) noter(context, va, bytes); + } + // 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) { @@ -344,10 +361,16 @@ class TitleVaAliases { hook_context_ = nullptr; resolver_ = nullptr; scanner_ = nullptr; + noter_ = nullptr; } // The resolver alone, for a device that scans its descriptor tables itself. void set_resolver(void* context, Resolver resolver) { set_hooks(context, resolver, nullptr); } void clear_resolver(void* context) { clear_hooks(context); } + // Set after set_hooks, so the hook (and its context) stays the device's: what reached a copy of the title's memory. + void set_noter(Noter noter) { + std::lock_guard lock(hook_mutex_); + noter_ = noter; + } std::size_t size() const { return count_.load(std::memory_order_acquire); } std::uint64_t invalidations() const { return invalidations_.load(std::memory_order_acquire); } @@ -424,6 +447,7 @@ class TitleVaAliases { BufferMaker maker_ = nullptr; Resolver resolver_ = nullptr; TableScanner scanner_ = nullptr; + Noter noter_ = nullptr; void* source_context_ = nullptr; DescriptorSource source_ = nullptr; std::atomic pulled_{0}; diff --git a/runtime/test/address_guard_test.cpp b/runtime/test/address_guard_test.cpp new file mode 100644 index 0000000000..02baa7bb8e --- /dev/null +++ b/runtime/test/address_guard_test.cpp @@ -0,0 +1,127 @@ +// leonida::address_guard::AddressGuardTable (src/address_guard.h): the address guard's page table. Pages any byte +// of a span touches are backed, a chunk keeps its level-2 block for good, a released span's bits go, negative +// offsets (a buffer below the arena) and spans across 4 GiB chunks work, only changed words are written, level-2 +// before level-1, and a chunk past the table's room gets the full block. No GPU, no device. +#include "../src/address_guard.h" + +#include +#include +#include +#include + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +namespace { + +using leonida::address_guard::AddressGuardTable; +using Spans = std::vector>; +namespace ag = leonida::address_guard; + +constexpr std::uint64_t kLimit = 0x80000; // the "arena" +constexpr std::uint64_t kGiB = 1ull << 30; + +// A copy of the GPU's table, written only through assign()'s callback, and the order of the writes. +struct Gpu { + std::vector words; + std::vector order; + explicit Gpu(const AddressGuardTable& t) : words(t.words()) {} + auto writer() { + return [this](std::size_t i, std::uint32_t v) { + words[i] = v; + order.push_back(i); + }; + } +}; + +int basics() { + AddressGuardTable t(4); + Gpu gpu(t); + EXPECT(t.word_count() == ag::kGuardLevel1 + 6u * ag::kGuardBlockWords); + EXPECT(!t.passes(0x90000, 4, kLimit)); + EXPECT(t.passes(0x7fffc, 4, kLimit)); // below the limit: no lookup + EXPECT(!t.passes(0x7fffc, 8, kLimit)); // its last byte is past it, on an unbacked page + + const Spans spans{{0x90000, 0x90001}, {5 * 4 * kGiB + 0x1000, 5 * 4 * kGiB + 0x3000}}; + const std::size_t written = t.assign(spans, gpu.writer()); + EXPECT(written > 0); + EXPECT(gpu.words == t.words()); + EXPECT(t.blocks_used() == 2); + EXPECT(t.passes(0x90000, 4, kLimit)); + EXPECT(t.passes(0x90ffc, 4, kLimit)); // one byte of the span marks the whole page + EXPECT(!t.passes(0x90ffc, 8, kLimit)); // the last byte is on the next page + EXPECT(t.passes(5 * 4 * kGiB + 0x2ff0, 16, kLimit)); + EXPECT(!t.passes(5 * 4 * kGiB + 0x3000, 4, kLimit)); + EXPECT(!t.passes(6 * 4 * kGiB, 4, kLimit)); + + // Level-2 words are written before level-1 ones. + bool seen_level1 = false; + for (const std::size_t i : gpu.order) { + if (i < ag::kGuardLevel1) seen_level1 = true; + else EXPECT(!seen_level1); + } + + // The same spans again: nothing to write. + gpu.order.clear(); + EXPECT(t.assign(spans, gpu.writer()) == 0); + + // A release: its bits go, its chunk keeps its block. + const std::uint32_t chunk5 = t.words()[5]; + EXPECT(chunk5 >= ag::kFirstBlock); + EXPECT(t.assign(Spans{{0x90000, 0x91000}}, gpu.writer()) > 0); + EXPECT(gpu.words == t.words()); + EXPECT(!t.passes(5 * 4 * kGiB + 0x2ff0, 4, kLimit)); + EXPECT(t.words()[5] == chunk5); + EXPECT(t.passes(0x90000, 4, kLimit)); + return 0; +} + +int negative_and_wide() { + AddressGuardTable t(4); + Gpu gpu(t); + // A buffer 8 KiB below heap_base (LEONIDA_IMPORT_BELOW_ARENA=1), as the 48-bit offset a V# holds. + const std::uint64_t below = (0ull - 0x2000) & ag::kMask48; + // One that runs from below heap_base into the arena's first page: wraps through 2^48. + const std::uint64_t wrap = (0ull - 0x1000) & ag::kMask48; + // A 6 GiB buffer across two chunks: whole words of bits. + const std::uint64_t wide = 8 * kGiB + 0x10000; + t.assign(Spans{{below, below + 0x1000}, {wrap, 0x1000}, {wide, wide + 6 * kGiB}}, gpu.writer()); + EXPECT(gpu.words == t.words()); + EXPECT(t.passes(below, 4, kLimit)); + EXPECT(t.passes(0ull - 0x2000, 4, kLimit)); // the same offset sign-extended, as the shaders pass it + EXPECT(t.passes(0ull - 4, 8, kLimit)); // across zero: both pages backed + EXPECT(!t.passes(0ull - 0x3000, 4, kLimit)); + EXPECT(t.passes(wide, 4, kLimit)); + EXPECT(t.passes(wide + 4 * kGiB, 4, kLimit)); + EXPECT(t.passes(wide + 6 * kGiB - 4, 4, kLimit)); + EXPECT(!t.passes(wide + 6 * kGiB, 4, kLimit)); + EXPECT(!t.passes(wide - 4, 8, kLimit)); + EXPECT(t.blocks_used() == 4); // chunks 0xffff, 0 (the wrap), 2 and 3 + return 0; +} + +int out_of_room() { + AddressGuardTable t(1); + Gpu gpu(t); + t.assign(Spans{{4 * kGiB, 4 * kGiB + 1}, {8 * kGiB, 8 * kGiB + 1}}, gpu.writer()); + EXPECT(t.blocks_used() == 1); + EXPECT(t.overflowed() == 1); + EXPECT(t.passes(4 * kGiB, 4, kLimit)); + EXPECT(!t.passes(4 * kGiB + 0x1000, 4, kLimit)); + EXPECT(t.passes(8 * kGiB + 0x5000, 4, kLimit)); // the full block: all of that chunk passes + EXPECT(t.words()[2] == ag::kFullBlock); + return 0; +} + +} // namespace + +int main() { + // "LGUARD01" little-endian, as tools/address_guard.py packs it and the shaders compare it. + static_assert(ag::magic() == 0x313044524155474Cull); + if (int r = basics()) return r; + if (int r = negative_and_wide()) return r; + if (int r = out_of_room()) return r; + std::puts("address_guard_test: ok"); + return 0; +} diff --git a/runtime/test/conservative_raster_test.cpp b/runtime/test/conservative_raster_test.cpp index b862e5fcba..72ee4d5163 100644 --- a/runtime/test/conservative_raster_test.cpp +++ b/runtime/test/conservative_raster_test.cpp @@ -1,6 +1,7 @@ #include "../src/conservative_raster.h" #include #include +#include int main() { using leonida::conservative_raster::tier1; @@ -38,6 +39,18 @@ int main() { const auto requirements = inner_coverage_requirements(module); check(requirements.valid && requirements.fully_covered && requirements.post_depth); check(!inner_coverage_requirements(std::span(module).first(9)).valid); + using leonida::conservative_raster::mesh_outputs_triangles; + const auto with_mode = [](std::uint32_t mode) { + return std::vector{0x07230203, 0x00010500, 0, 2, 0, (3u << 16) | 16, 1, mode}; + }; + check(mesh_outputs_triangles(with_mode(5298))); // OutputTrianglesEXT + check(!mesh_outputs_triangles(with_mode(5269))); // OutputLinesEXT + check(!mesh_outputs_triangles(with_mode(27))); // OutputPoints + check(!mesh_outputs_triangles(with_mode(26))); // OutputVertices: no output topology + check(!mesh_outputs_triangles({})); + auto truncated = with_mode(5298); + truncated.pop_back(); + check(!mesh_outputs_triangles(truncated)); const std::uint32_t zero_count[] = {0x07230203, 0x00010500, 0, 2, 0, 0}; check(!inner_coverage_requirements(zero_count).valid); const std::uint32_t ordinary[] = {0x07230203, 0x00010500, 0, 2, 0, (2u << 16) | 17, 1}; diff --git a/runtime/test/console_heap_copy_test.cpp b/runtime/test/console_heap_copy_test.cpp new file mode 100644 index 0000000000..48618170e5 --- /dev/null +++ b/runtime/test/console_heap_copy_test.cpp @@ -0,0 +1,168 @@ +// Portable CPU-only unit test for leonida::ConsoleHeapCopy (runtime/src/console_heap_copy.h): the host-RAM mirror of a +// console heap's translated copy. A plain buffer stands in for the copy in the GPU address arena. Checks that every +// write and zero reaches both, that the null guard past the heap stays out of the mirror, that mismatches() finds a +// write that bypassed the helpers (the LEONIDA_HEAP_MIRROR_CHECK case), and that without a mirror view() is the copy. +// Then times a filtered release sweep over a large heap reading the mirror (the work refresh_console_heap does per +// rescan with LEONIDA_CONSOLE_RELEASE_FILTER=1), for reference; no game data. +#include "../src/console_heap_copy.h" +#include "../src/console_heap_vsharp_slots.h" +#include "../src/descriptor_range_changes.h" + +#include +#include +#include +#include +#include + +#define EXPECT(condition) \ + do { \ + if (!(condition)) { \ + std::fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #condition); \ + return 1; \ + } \ + } while (0) + +namespace { + +using leonida::ConsoleHeapCopy; +constexpr std::size_t kSlot = 32; + +int test_writes_reach_both() { + constexpr std::size_t slots = 256, bytes = slots * kSlot, guard = 4096; + std::vector gpu(bytes + guard, 0xCD); + ConsoleHeapCopy copy; + EXPECT(!copy); + copy.attach(gpu.data(), bytes, true); + EXPECT(copy && copy.mirrored() && copy.gpu() == gpu.data() && copy.bytes() == bytes); + EXPECT(copy.view() != gpu.data()); + // Creation: the copy and its guard zeroed; the mirror covers the heap only. + copy.zero(0, bytes + guard); + for (const auto b : gpu) EXPECT(b == 0); + std::vector differ; + EXPECT(copy.mismatches(kSlot, 8, differ) == 0 && differ.empty()); + + std::uint32_t w[8] = {0x1000, 0x20, 64, 0x3fffu, 0, 0, 0, 0}; + for (std::size_t s = 0; s < slots; s += 3) { + w[0] = std::uint32_t(0x1000 + s * 0x40); + copy.write(s * kSlot, w, sizeof(w)); + } + copy.zero(9 * kSlot, kSlot); + copy.zero(64 * kSlot, 32 * kSlot); // a zeroed range of slots + // A sampler heap's whole range copied at once. + std::vector run(5 * kSlot + 7, 0x5A); + copy.write(200 * kSlot + 3, run.data(), run.size()); + EXPECT(std::memcmp(copy.view(), gpu.data(), bytes) == 0); + EXPECT(copy.mismatches(kSlot, 8, differ) == 0); + // Past the heap: the copy's guard only, nothing out of the mirror's bounds. + copy.zero(bytes - kSlot, kSlot + guard); + std::uint32_t tail[8]; + std::memcpy(tail, copy.view() + bytes - kSlot, sizeof(tail)); + for (const auto t : tail) EXPECT(t == 0); + EXPECT(copy.mismatches(kSlot, 8, differ) == 0); + std::puts("writes and zeros reach the copy and the mirror; the guard stays out of the mirror"); + return 0; +} + +int test_mismatch_found() { + constexpr std::size_t slots = 8192, bytes = slots * kSlot; // 256 KiB: more than one compare block + std::vector gpu(bytes, 0); + ConsoleHeapCopy copy; + copy.attach(gpu.data(), bytes, true); + // Writes that bypass the helpers (a missed write site, or the GPU writing the copy). + gpu[5 * kSlot + 4] = 1; + gpu[4000 * kSlot] = 2; + gpu[4001 * kSlot + 31] = 3; + gpu[8191 * kSlot + 16] = 4; + std::vector differ; + EXPECT(copy.mismatches(kSlot, 3, differ) == 4); + EXPECT(differ.size() == 3 && differ[0] == 5 && differ[1] == 4000 && differ[2] == 4001); + EXPECT(copy.mismatches(kSlot, 8, differ) == 4 && differ.size() == 4 && differ[3] == 8191); + std::puts("mismatches() finds writes that bypassed the mirror, in slot order"); + return 0; +} + +int test_without_mirror() { + constexpr std::size_t bytes = 64 * kSlot; + std::vector gpu(bytes, 0); + ConsoleHeapCopy copy; + copy.attach(gpu.data(), bytes, false); // the copy is host RAM already + EXPECT(!copy.mirrored() && copy.view() == gpu.data()); + const std::uint32_t w[8] = {1, 2, 3, 4, 5, 6, 7, 8}; + copy.write(3 * kSlot, w, sizeof(w)); + EXPECT(!std::memcmp(gpu.data() + 3 * kSlot, w, sizeof(w))); + std::vector differ; + EXPECT(copy.mismatches(kSlot, 8, differ) == 0); + + copy.attach(gpu.data(), bytes, true); + EXPECT(copy.mirrored()); + copy.drop_mirror(); // the GPU pass writes the copy from now on + EXPECT(!copy.mirrored() && copy.view() == gpu.data()); + std::puts("without a mirror view() is the copy"); + return 0; +} + +// The filtered release sweep of refresh_console_heap over a heap of 576k slots (18 MiB) with 470k live V# slots, one +// released range touching about 2%: the time per sweep with its words read from host RAM. +int bench_filtered_sweep() { + constexpr std::size_t slots = 576 * 1024, bytes = slots * kSlot; + std::vector previous(bytes, 0), gpu(bytes, 0); + ConsoleHeapCopy copy; + copy.attach(gpu.data(), bytes, true); + leonida::ConsoleHeapVsharpSlots live; + live.reset(slots); + constexpr std::uint64_t kBuffers = 4096, kBufferBytes = 1 << 20, kArena = 1ull << 32; + for (std::size_t s = 0; s < slots; ++s) { + if (s % 11 == 10) continue; // T#s and empty slots + const std::uint64_t base = 0x100000 + (s * 2654435761u % kBuffers) * kBufferBytes + (s % 64) * 256; + std::uint32_t w[8] = {std::uint32_t(base), std::uint32_t(base >> 32) & 0xffffu, 256, 0x00027fac, 0, 0, 0, 0}; + std::memcpy(previous.data() + s * kSlot, w, sizeof(w)); + copy.write(s * kSlot, w, sizeof(w)); + live.set(s, leonida::ConsoleHeapVsharpSlots::is_live_vsharp(w)); + } + leonida::DescriptorRanges backing, aliases; + for (std::uint64_t b = 0; b < kBuffers; b += 50) // about 2% of the buffers released + backing.ranges.push_back({kArena + 0x100000 + b * kBufferBytes, kArena + 0x100000 + (b + 1) * kBufferBytes - 1}); + backing.merge(); + const auto bda = [&](std::uint64_t base) { return kArena + base; }; + const auto affected = [&](const std::uint32_t* src, const std::uint32_t* dst) { + if ((src[3] >> 30) || !src[2]) return false; + const std::uint64_t base = std::uint64_t(src[0]) | (std::uint64_t(src[1] & 0xffff) << 32); + const std::uint64_t fixed = std::uint64_t(dst[0]) | (std::uint64_t(dst[1] & 0xffff) << 32); + const auto stride = (src[1] >> 16) & 0x3fff; + const std::uint64_t n = std::uint64_t(src[2]) * (stride ? stride : 1); + return aliases.overlaps(base, 1) || backing.overlaps(bda(base), n) || (dst[2] && backing.overlaps(bda(fixed), n)); + }; + constexpr int kRuns = 9; + double best = 1e30, first = 0; + std::size_t hits = 0; + for (int run = 0; run < kRuns; ++run) { + hits = 0; + const auto start = std::chrono::steady_clock::now(); + const std::uint8_t* const translated = copy.view(); + live.for_each([&](std::size_t slot) { + const auto at = slot * kSlot; + const auto* src = reinterpret_cast(previous.data() + at); + const auto* dst = reinterpret_cast(translated + at); + if (affected(src, dst) || affected(src + 4, dst + 4)) ++hits; + }); + const double took = std::chrono::duration(std::chrono::steady_clock::now() - start).count(); + if (!run) first = took; + best = std::min(best, took); + } + EXPECT(hits > 0 && hits < live.live_count() / 10); + std::printf("filtered sweep over %zu live slots of %zu MiB, %zu affected: %.2f ms (best of %d, first %.2f), words " + "from the host mirror\n", + live.live_count(), bytes >> 20, hits, best, kRuns, first); + return 0; +} + +} // namespace + +int main() { + if (test_writes_reach_both()) return 1; + if (test_mismatch_found()) return 1; + if (test_without_mirror()) return 1; + if (bench_filtered_sweep()) return 1; + std::puts("ok"); + return 0; +} diff --git a/runtime/test/console_heap_vsharp_slots_test.cpp b/runtime/test/console_heap_vsharp_slots_test.cpp index ebb74be452..aa56b4fdd3 100644 --- a/runtime/test/console_heap_vsharp_slots_test.cpp +++ b/runtime/test/console_heap_vsharp_slots_test.cpp @@ -246,6 +246,80 @@ int test_retail_sized_heap_sparse_scan() { return 0; } +int test_console_fix_budget_buffer_vsharp_non_deferral() { + // Verifies that under fix_console_slots budget expiry (fix_over == true), buffer V# descriptors + // (!(w[3] >> 30)) are never deferred/nulled, while image T# descriptors ((w[3] >> 30) != 0) are deferred. + constexpr std::size_t kSlots = 16; + std::vector> gpu_copy(kSlots); + for (auto& slot : gpu_copy) slot.fill(0); + + ConsoleHeapVsharpSlots tracked; + tracked.reset(kSlots); + + // Populate slots with alternating buffer V# and image T# descriptors: + // Even slots: live buffer V#s + // Odd slots: image T#s + for (std::size_t i = 0; i < kSlots; ++i) { + std::array w{}; + if ((i & 1u) == 0) { + // Buffer V#: w[3] >> 30 == 0, num_records != 0 + w[0] = static_cast(0x1000 + i * 0x100); + w[1] = 0x20; + w[2] = 256; + w[3] = 0x00010000u; // w[3] >> 30 == 0 + } else { + // Image T#: w[3] >> 30 != 0 + w[0] = static_cast(0x5000 + i * 0x100); + w[2] = 128; + w[3] = (2u << 30) | 0x1234u; // w[3] >> 30 == 2 + } + gpu_copy[i] = w; + tracked.set(i, ConsoleHeapVsharpSlots::is_live_vsharp(w.data())); + } + + // Now simulate fix_console_slots when budget is expired (fix_over == true): + // Buffer V#s must be fixed in-place and never nulled/deferred; only image T#s are deferred. + std::size_t deferred_fixes = 0; + std::vector retries; + const bool fix_over = true; + + for (std::size_t slot = 0; slot < kSlots; ++slot) { + const std::array& input = gpu_copy[slot]; + const std::uint32_t w3 = input[3]; + const bool is_buffer_vsharp = !(w3 >> 30); + + if (fix_over && !is_buffer_vsharp) { + // Image T#: deferred past budget + gpu_copy[slot].fill(0); + tracked.clear(slot); + ++deferred_fixes; + retries.push_back(static_cast(slot)); + continue; + } + + // Buffer V#: fixed immediately, not deferred + tracked.set(slot, ConsoleHeapVsharpSlots::is_live_vsharp(input.data())); + } + + // All odd slots (image T#s) must have been deferred (nulled) + EXPECT(deferred_fixes == kSlots / 2); + EXPECT(retries.size() == kSlots / 2); + for (std::size_t slot : retries) { + EXPECT((slot & 1u) == 1u); + EXPECT(!tracked.test(slot)); + EXPECT(gpu_copy[slot][0] == 0 && gpu_copy[slot][2] == 0); + } + + // All even slots (buffer V#s) must have been preserved and remain live + for (std::size_t i = 0; i < kSlots; i += 2) { + EXPECT(tracked.test(i)); + EXPECT(gpu_copy[i][2] == 256); + EXPECT(ConsoleHeapVsharpSlots::is_live_vsharp(gpu_copy[i].data())); + } + EXPECT(tracked.live_count() == kSlots / 2); + return 0; +} + } // namespace int main() { @@ -254,6 +328,7 @@ int main() { if (test_in_place_invalidation_mutation()) return 1; if (test_differential_equivalence_against_linear_copy()) return 1; if (test_retail_sized_heap_sparse_scan()) return 1; + if (test_console_fix_budget_buffer_vsharp_non_deferral()) return 1; std::printf("console_heap_vsharp_slots_test: ok\n"); return 0; } diff --git a/runtime/test/d3d12_console_heap_mirror_test.cpp b/runtime/test/d3d12_console_heap_mirror_test.cpp new file mode 100644 index 0000000000..9a1319bb3e --- /dev/null +++ b/runtime/test/d3d12_console_heap_mirror_test.cpp @@ -0,0 +1,215 @@ +// The host-RAM mirror of a console descriptor heap's GPU copy (src/console_heap_copy.h) through a heap's life, with +// LEONIDA_CONSOLE_RELEASE_FILTER=1 (the release sweep reads the mirror to pick the slots to fix): the first refresh, +// slots the title rewrites and zeroes after it, and a released buffer whose V#s the sweep must find and null. After +// each step the GPU copy holds what it should and the mirror agrees with it byte for byte. Run twice by ctest: with +// the mirror, and with LEONIDA_HEAP_MIRROR=0 (no mirror; the sweep reads the copy, as before it), where the copy must +// come out the same. Nothing dispatches through a descriptor. No game data. +#include "vk_test_device.h" +#include "../shims/d3d12_com.h" +#include "../src/gfx10_descriptors.h" + +#include +#include +#include +#include + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +namespace { + +template +struct Ref { + T* p = nullptr; + ~Ref() { reset(); } + void reset() { + if (p) p->Release(); + p = nullptr; + } + T* operator->() const { return p; } +}; + +constexpr UINT kDescriptor = 32; +constexpr UINT kViewBytes = 256; +constexpr UINT kBufferBytes = 64 * 1024; + +D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes) { + 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; + return desc; +} + +leonida::gfx10::BufferWords raw_vsharp(std::uint64_t address) { + leonida::gfx10::Buffer b{}; + b.address = address; + b.num_records = kViewBytes; + b.format = leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT); + b.oob_select = leonida::gfx10::OobSelect::raw; + return leonida::gfx10::encode(b); +} + +std::uint64_t base_of(const std::uint32_t* w) { return std::uint64_t(w[0]) | (std::uint64_t(w[1] & 0xFFFFu) << 32); } +bool zero_size(const std::uint32_t* w) { return base_of(w) == 0 && w[2] == 0; } + +struct Heap { + static constexpr UINT slots = 4096; + static constexpr std::uint64_t bytes = std::uint64_t(slots) * kDescriptor; +}; + +// What a slot of the copy is expected to hold: the buffer it names, or nothing. +enum class Want { a, b, none, zero }; + +int check(ID3D12Device* device, std::uint64_t shader_va, std::uint64_t title, const Want* want, std::uint64_t a_va, + std::uint64_t b_va, bool mirrored, const char* step) { + static std::uint32_t copy[Heap::slots][kDescriptor / 4]; + EXPECT(rt::d3d12::read_arena(device, shader_va, copy, sizeof(copy))); + for (UINT s = 0; s < Heap::slots; ++s) { + const std::uint32_t* w = copy[s]; + bool ok = true; + switch (want[s]) { + case Want::a: ok = base_of(w) >= a_va && base_of(w) < a_va + kBufferBytes && w[2] == kViewBytes; break; + case Want::b: ok = base_of(w) >= b_va && base_of(w) < b_va + kBufferBytes && w[2] == kViewBytes; break; + case Want::none: ok = zero_size(w); break; + case Want::zero: for (int i = 0; i < 8; ++i) ok = ok && !w[i]; break; + } + if (!ok) { + std::fprintf(stderr, "%s: slot %u holds %08x %08x %08x %08x, wanted %d\n", step, s, w[0], w[1], w[2], w[3], + int(want[s])); + return 1; + } + } + const long long differ = rt::d3d12::console_heap_mirror_mismatches(device, title); + if (mirrored) EXPECT(differ == 0); + else EXPECT(differ == -1); + std::printf("%s: copy as expected, %s\n", step, mirrored ? "mirror agrees with it" : "no mirror"); + return 0; +} + +int run(ID3D12Device* device, bool mirrored) { + 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)))); + UINT64 fence_value = 0; + Ref allocator; + Ref list; + 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())); + ID3D12CommandList* lists[] = {list.p}; + const auto submit = [&]() -> int { // every submission refreshes the console heaps first + queue->ExecuteCommandLists(1, lists); + EXPECT(SUCCEEDED(queue->Signal(fence.p, ++fence_value))); + EXPECT(SUCCEEDED(fence->SetEventOnCompletion(fence_value, nullptr))); + return 0; + }; + + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const auto desc = buffer_desc(kBufferBytes); + Ref a, b; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&a.p)))); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&b.p)))); + const std::uint64_t a_va = a->GetGPUVirtualAddress(), b_va = b->GetGPUVirtualAddress(); + EXPECT(a_va && b_va); + + auto* title = static_cast(VirtualAlloc(nullptr, Heap::bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + EXPECT(title); + static Want want[Heap::slots]; + const auto put = [&](UINT slot, std::uint64_t va, Want w) { + const auto words = raw_vsharp(va); + std::memcpy(title + slot * kDescriptor, words.data(), sizeof(words)); + want[slot] = w; + }; + for (UINT s = 0; s < Heap::slots; ++s) want[s] = Want::zero; + // Before the heap exists: slots 0-1023 name A, 1024-2047 B, the rest empty but for one data slot. + for (UINT s = 0; s < 1024; ++s) put(s, a_va + (s % 256) * kViewBytes, Want::a); + for (UINT s = 1024; s < 2048; ++s) put(s, b_va + (s % 256) * kViewBytes, Want::b); + const std::uint32_t data[8] = {0x12345000u, 0x00007777u, 0x00000400u, 0x40000000u, 1, 2, 3, 4}; + std::memcpy(title + 3000 * kDescriptor, data, sizeof(data)); + want[3000] = Want::none; // its descriptor half null in the copy (fix_console_slot) + + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, Heap::slots, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + Ref heap; + const auto title_va = reinterpret_cast(title); + EXPECT(SUCCEEDED(rt::d3d12::create_console_descriptor_heap(device, &heap_desc, title_va, Heap::bytes, + IID_PPV_ARGS(&heap.p)))); + D3D12_DESCRIPTOR_HEAP_DESC got{}; + D3D12_GPU_VIRTUAL_ADDRESS shader_va = 0; + EXPECT(rt::d3d12::descriptor_heap_info(heap.p, got, shader_va)); + if (check(device, shader_va, title_va, want, a_va, b_va, mirrored, "first refresh")) return 1; + + // The title rewrites slots after the heap is made (the write watch finds them): a slot of B now names A, new V#s + // past what it filled, and a page of A's slots zeroed (128 slots). + put(1500, a_va + 0x400, Want::a); + for (UINT s = 2048; s < 2112; ++s) put(s, b_va + (s % 256) * kViewBytes, Want::b); + std::memset(title + 128 * kDescriptor, 0, 4096); + for (UINT s = 128; s < 256; ++s) want[s] = Want::zero; + if (submit()) return 1; + if (check(device, shader_va, title_va, want, a_va, b_va, mirrored, "title writes")) return 1; + + // A goes: the release sweep (filtered: only the V#s naming A) nulls the slots that name it, and only those. Its + // memory is given back once its GPU work retires, so a few submissions may pass first. + a.reset(); + for (UINT s = 0; s < Heap::slots; ++s) + if (want[s] == Want::a) want[s] = Want::none; + bool nulled = false; + for (int pass = 0; pass < 32 && !nulled; ++pass) { + if (submit()) return 1; + std::uint32_t w[8]; + EXPECT(rt::d3d12::read_arena(device, shader_va + 1500 * kDescriptor, w, sizeof(w))); + nulled = zero_size(w); + } + EXPECT(nulled); + if (check(device, shader_va, title_va, want, a_va, b_va, mirrored, "A released")) return 1; + + heap.reset(); + VirtualFree(title, 0, MEM_RELEASE); + return 0; +} + +} // namespace + +int main() { + char value[4] = {}; + const bool mirrored = !(GetEnvironmentVariableA("LEONIDA_HEAP_MIRROR", value, sizeof(value)) == 1 && value[0] == '0'); + vktest::Device d; + const auto status = d.initialize(); + if (status == vktest::DeviceStatus::unavailable) { + std::fprintf(stderr, "SKIP: no usable Vulkan 1.3 device\n"); + return 77; + } + EXPECT(status == vktest::DeviceStatus::ready); + { + 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; + Ref device; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p)))); + EXPECT(rt::d3d12::device_arena_size(device.p) > 0); + if (run(device.p, mirrored)) return 1; + } + if (d.validation_errors()) { + std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); + return 1; + } + std::puts("ok"); + return 0; +} diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp index 25fa1f6544..546c760555 100644 --- a/runtime/test/d3d12_existing_heap_test.cpp +++ b/runtime/test/d3d12_existing_heap_test.cpp @@ -1359,6 +1359,141 @@ int check_pending_stream_views(ID3D12Device* device) { return 0; } +namespace { +std::atomic g_view_av_thread{0}; +std::atomic g_view_avs{0}; + +LONG CALLBACK count_view_av(PEXCEPTION_POINTERS info) { + if (info && info->ExceptionRecord && info->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION && + GetCurrentThreadId() == g_view_av_thread.load(std::memory_order_relaxed)) { + g_view_avs.fetch_add(1, std::memory_order_relaxed); + } + return EXCEPTION_CONTINUE_SEARCH; +} +} // namespace + +// Map changes reported to title_memory_map between submissions must both retire a cached readable answer before a +// synchronous slot-70 view hashes decommitted pages, and wake a pending slot-70 view without waiting for a submission. +int check_placed_view_map_changes(ID3D12Device* device) { + const char* who = "slot-70 view map changes"; + if (!rt::d3d12::bindless_set_layout(device)) return 0; + GpuReader gpu; + EXPECT(!gpu.init(device, 4096)); + auto env_is = [](const char* name, const char* want) { + char buf[16]{}; + const DWORD n = GetEnvironmentVariableA(name, buf, sizeof(buf)); + return n > 0 && n < sizeof(buf) && std::strcmp(buf, want) == 0; + }; + auto index = [&](const leonida::gfx10::ImageWords& descriptor) { + std::uint32_t key[8]; + std::memcpy(key, descriptor.data(), sizeof(key)); + return rt::d3d12::bindless_hash_lookup(device, key); + }; + + // 1. Committed >256 KiB texture -> decommit interior 64 KiB + map::changed -> synchronous view takes zero AVs. + { + constexpr SIZE_T bytes = 512 * 1024; + auto* pages = static_cast(VirtualAlloc(nullptr, bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + EXPECT(pages); + std::memset(pages, 0x5a, bytes); + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = 512; + desc.Height = 1024; + desc.DepthOrArraySize = desc.MipLevels = 1; + 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; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + leonida::gfx10::ImageWords slot{}; + auto write_view = [&](UINT mapping) { + 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())}); + }; + EXPECT(write_view(D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING)); + EXPECT(index(slot) != 0); + + EXPECT(VirtualFree(pages + 65536, 65536, MEM_DECOMMIT) != FALSE); + leonida::title_memory_map::changed(pages + 65536, 65536); + + g_view_avs.store(0, std::memory_order_relaxed); + g_view_av_thread.store(GetCurrentThreadId(), std::memory_order_relaxed); + PVOID veh = AddVectoredExceptionHandler(1, &count_view_av); + EXPECT(veh != nullptr); + const bool wrote_after_unmap = write_view(D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(0, 0, 0, 0)); + RemoveVectoredExceptionHandler(veh); + g_view_av_thread.store(0, std::memory_order_relaxed); + EXPECT(wrote_after_unmap); + EXPECT(g_view_avs.load(std::memory_order_relaxed) == 0); + + EXPECT(VirtualAlloc(pages + 65536, 65536, MEM_COMMIT, PAGE_READWRITE) == pages + 65536); + leonida::title_memory_map::changed(pages + 65536, 65536); + 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); + placement.p->Release(); + placement.p = nullptr; + VirtualFree(pages, 0, MEM_RELEASE); + } + + // 2. Reserved texture -> commit + map::changed (no texel write note, no submission) -> synchronous view publishes. + { + constexpr SIZE_T bytes = 65536; + void* pages = VirtualAlloc(nullptr, bytes, MEM_RESERVE, PAGE_NOACCESS); + EXPECT(pages); + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = 32; + desc.Height = 8; + desc.DepthOrArraySize = desc.MipLevels = 1; + 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 first{}, second{}; + auto write_view = [&](UINT mapping, leonida::gfx10::ImageWords& out) { + 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(out.data())}); + }; + EXPECT(write_view(D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, first)); + if (!env_is("LEONIDA_TITLE_IMAGE_DEFER", "0")) EXPECT(!index(first)); + + EXPECT(VirtualAlloc(pages, bytes, MEM_COMMIT, PAGE_READWRITE) == pages); + std::memset(pages, 0x33, bytes); + leonida::title_memory_map::changed(pages, bytes); + + EXPECT(write_view(D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(0, 0, 0, 0), second)); + if (!env_is("LEONIDA_TITLE_FILL_ASYNC", "1")) EXPECT(index(first) && index(second)); + + 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); + 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"; @@ -2089,6 +2224,7 @@ int main(int argc, char** argv) { 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_placed_view_map_changes(ours.p); failures += check_shared_bc_placements(ours.p); failures += check_mapped_plane(ours.p); failures += check_mapped_bc_array(ours.p); @@ -2099,6 +2235,7 @@ int main(int argc, char** argv) { no_host_copy.host_image_copy = false; Ref staged; if (FAILED(rt::d3d12::create_vulkan_device(no_host_copy, IID_PPV_ARGS(&staged.p)))) return 1; + failures += check_placed_view_map_changes(staged.p); failures += check_mapped_plane(staged.p); failures += check_mapped_bc_array(staged.p); } diff --git a/runtime/test/d3d12_mesh_test.cpp b/runtime/test/d3d12_mesh_test.cpp index 775cfeb581..7b529546b4 100644 --- a/runtime/test/d3d12_mesh_test.cpp +++ b/runtime/test/d3d12_mesh_test.cpp @@ -150,6 +150,7 @@ int main(int argc, char** argv) { rt::d3d12::VulkanDeviceInfo info{}; info.prepare_on_bind=d.prepare_on_bind; info.cold_graphics_compile=d.cold_graphics_compile; + info.heavy_pipeline_cache=d.heavy_pipeline_cache; info.get_instance_proc = d.instance_proc; info.instance = d.instance; info.physical = d.physical; @@ -161,6 +162,7 @@ int main(int argc, char** argv) { info.mesh_shader = mesh; info.mesh_shader_queries = mesh && d.mesh_shader_queries; info.pipeline_statistics_query = d.pipeline_statistics_query; + info.conservative_rasterization = d.conservative_rasterization; return info; }; const auto make_device = [&](bool mesh, Ref& device) { @@ -253,6 +255,34 @@ int main(int argc, char** argv) { vs_stream.add(TopologySubobject{.inner = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE}); vs_stream.add(TargetsSubobject{.inner = one_target()}); EXPECT(SUCCEEDED(create(device.p, vs_stream, vs_pso))); + // Conservative rasterization in a mesh pipeline: its stream has no input assembler, so it need not name a topology + // type. A vertex pipeline without TRIANGLE is still refused, as is a wireframe mesh one. + { + D3D12_FEATURE_DATA_D3D12_OPTIONS options{}; + EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof options))); + if (options.ConservativeRasterizationTier != D3D12_CONSERVATIVE_RASTERIZATION_TIER_NOT_SUPPORTED) { + std::printf("conservative rasterization tier %d: mesh pipelines checked\n", int(options.ConservativeRasterizationTier)); + D3D12_RASTERIZER_DESC conservative{}; + conservative.FillMode = D3D12_FILL_MODE_SOLID; + conservative.CullMode = D3D12_CULL_MODE_NONE; + conservative.DepthClipEnable = TRUE; + conservative.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON; + Ref made; + Stream conservative_mesh = mesh_stream; + conservative_mesh.add(RasterizerSubobject{.inner = conservative}); + EXPECT(SUCCEEDED(create(device.p, conservative_mesh, made)) && made.p); + conservative.FillMode = D3D12_FILL_MODE_WIREFRAME; + Stream wireframe_mesh = mesh_stream; + wireframe_mesh.add(RasterizerSubobject{.inner = conservative}); + EXPECT(create(device.p, wireframe_mesh, refused) == E_INVALIDARG && !refused.p); + conservative.FillMode = D3D12_FILL_MODE_SOLID; + Stream no_topology_vs; + no_topology_vs.add(RootSubobject{.inner = root.p}).add(VsSubobject{.inner = vs}).add(PsSubobject{.inner = ps}); + no_topology_vs.add(TargetsSubobject{.inner = one_target()}); + no_topology_vs.add(RasterizerSubobject{.inner = conservative}); + EXPECT(create(device.p, no_topology_vs, refused) == E_INVALIDARG && !refused.p); + } + } // A mesh shader translated before the graphics root window would read its root arguments from the wrong // dwords: refused, with a log line that asks for the shaders stage again. { diff --git a/runtime/test/d3d12_title_va_test.cpp b/runtime/test/d3d12_title_va_test.cpp index e5ef143042..bf0f14f1ea 100644 --- a/runtime/test/d3d12_title_va_test.cpp +++ b/runtime/test/d3d12_title_va_test.cpp @@ -512,7 +512,194 @@ int check_window_overflow(Context& c) { VirtualFree(ring, 0, MEM_RELEASE); return 0; } -// These fixtures register their own pairs without XMem. Retire each before Wine can reuse either VA. +// What the GPU writes into a title window goes back to the title's pages (#1537, the WRITE_INVALID stop: a window is +// a read-side mirror, so a UAV write used to land in the copy and the title never saw it). The shader's write is read +// back through the pages themselves; then a write by the title must survive the next submission's forward copy. +struct WriteBack { + Context* c; + ID3D12CommandAllocator* allocator; + ID3D12GraphicsCommandList* list; + ID3D12Resource* out; + ID3D12DescriptorHeap* heap; + UINT64 gpu; +}; + +// One submission that dispatches through a root UAV at `va` and waits for it. False on a failed call. +int submit_write(WriteBack& s, std::uint64_t va) { + EXPECT(s.allocator->Reset() == S_OK); + EXPECT(s.list->Reset(s.allocator, s.c->pso) == S_OK); + ID3D12DescriptorHeap* heaps[] = {s.heap}; + s.list->SetDescriptorHeaps(1, heaps); + s.list->SetComputeRootSignature(s.c->root); + s.list->SetComputeRoot32BitConstant(0, 0, 0); + s.list->SetComputeRoot32BitConstant(0, 1, 1); // the step: a word the shader writes + s.list->SetComputeRootUnorderedAccessView(1, va); + s.list->SetComputeRootDescriptorTable(2, D3D12_GPU_DESCRIPTOR_HANDLE{s.gpu}); + s.list->Dispatch(1, 1, 1); + D3D12_RESOURCE_BARRIER to_copy{}; + to_copy.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + to_copy.Transition.pResource = s.out; + 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; + s.list->ResourceBarrier(1, &to_copy); + EXPECT(s.list->Close() == S_OK); + ID3D12CommandList* lists[] = {s.list}; + s.c->queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(s.c->queue) == leonida::ReplayResult::success); + EXPECT(SUCCEEDED(s.c->queue->Signal(s.c->fence, ++s.c->fence_value))); + s.c->fence->SetEventOnCompletion(s.c->fence_value, nullptr); // a null event waits, as D3D12 does + return 0; +} + +// The same gap on a buffer the title places at its own address (slot 133, the retail case for a compute result it +// reads back): the pages are not imported here, so the buffer is a shadow, and the write of a root UAV over the +// title's VA must reach the pages at the next submission - and the title's own newer words must still win. +int check_placed_write_back(Context& c, bool geometry) { + void* pages = VirtualAlloc(nullptr, kPages, MEM_TOP_DOWN | MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + EXPECT(pages); + const auto title_va = reinterpret_cast(pages); + auto* words = static_cast(pages); + for (UINT i = 0; i < kPages / 4; ++i) words[i] = 0xA0000000u + i * 3u; // never zero, unlike the shader's rows + auto& aliases = leonida::title_va_aliases(); + aliases.add_title_memory(title_va, kPages); // what the xmem shims do for the title's allocations + const D3D12_RESOURCE_DESC desc = buffer_desc(kPages); + Ref placed; + EXPECT(SUCCEEDED( + rt::d3d12::create_buffer_at_host_address(c.inner, pages, desc, 0xFFFFFFFFu, IID_PPV_ARGS(&placed.p)))); + EXPECT(placed->GetGPUVirtualAddress() == title_va); + EXPECT(aliases.shader_va(title_va) != title_va); // there is a copy to be reached through + + 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); + const auto readback_desc = buffer_desc(kBytes); + Ref out, readback; + EXPECT(SUCCEEDED(c.device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &uav, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, + IID_PPV_ARGS(&out.p)))); + EXPECT(SUCCEEDED(c.device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback.p)))); + 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)))); + 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)))); + EXPECT(list->Close() == S_OK); + WriteBack s{&c, allocator.p, list.p, out.p, heap.p, + reinterpret_cast(slot(heap.p, 10))(heap.p)}; + + const std::vector before(words, words + kElements); + EXPECT(submit_write(s, title_va) == 0); + UINT untouched = 0; + for (UINT i = 0; i < kElements; ++i) untouched += words[i] == before[i]; + // An imported buffer is the same memory and needs no copy; only a shadow owes the pages the GPU's words. + const bool shadow = !geometry && aliases.shader_va(title_va) >= c.arena; + if (shadow) { + std::printf("placed buffer write back: %u/%u words still held the title's before the next submission\n", + untouched, kElements); + EXPECT(untouched == kElements); + } + + EXPECT(submit_write(s, title_va) == 0); + std::vector written(words, words + kElements); + UINT reached = 0, changed = 0, nonzero = 0; + for (UINT i = 0; i < kElements; ++i) { + reached += written[i] == (0xA0000000u + i * 3u); + changed += written[i] != before[i]; + nonzero += written[i] != 0; + } + std::printf("placed buffer write back: %u/%u words reached the pages (%u changed, %u nonzero)\n", kElements - reached, + kElements, changed, nonzero); + EXPECT(changed == kElements && nonzero > 0); + (void)reached; + + // The title writes its own words over the result: the next submission copies them forward and they stay. + for (UINT i = 0; i < kElements; ++i) words[i] = 0xB16B00B5u; + EXPECT(submit_write(s, title_va) == 0); + UINT kept = 0; + for (UINT i = 0; i < kElements; ++i) kept += words[i] == 0xB16B00B5u; + std::printf("placed buffer write back: the title's own words survived %u/%u\n", kept, kElements); + EXPECT(kept == kElements); + + placed.reset(); // the shadow goes, the pages stay writable + aliases.remove_title_memory(title_va); + VirtualFree(pages, 0, MEM_RELEASE); + return 0; +} + +int check_window_write_back(Context& c, 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); + for (UINT i = 0; i < ring_bytes / 4; ++i) ring[i] = 0; + auto& aliases = leonida::title_va_aliases(); + aliases.add_title_memory(ring_va, ring_bytes); + + 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); + const auto readback_desc = buffer_desc(kBytes); + Ref out, readback; + EXPECT(SUCCEEDED(c.device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &uav, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, + IID_PPV_ARGS(&out.p)))); + EXPECT(SUCCEEDED(c.device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback.p)))); + 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)))); + 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)))); + EXPECT(list->Close() == S_OK); // Reset needs it closed, as the title leaves it + WriteBack s{&c, allocator.p, list.p, out.p, heap.p, + reinterpret_cast(slot(heap.p, 10))(heap.p)}; + + // The shader writes the range the root UAV names, which is the title's own pages here, far past the arena: the + // resolve already has to make a window for them before the submission. + EXPECT(aliases.shader_va(ring_va) == ring_va); + EXPECT(submit_write(s, ring_va) == 0); + EXPECT(aliases.shader_va(ring_va) != ring_va); // a window was made for the title's pages + if (!geometry) EXPECT(ring[0] == 0); // the copy took the write: the pages get it only after the next submission + + // The next submission's refresh copies the GPU's writes back, before it copies the pages forward. + EXPECT(submit_write(s, ring_va) == 0); + const std::vector written(ring, ring + kElements); + UINT nonzero = 0; + for (std::uint32_t w : written) nonzero += w != 0; + std::printf("write back: %u of %u words the shader wrote are in the title's pages\n", nonzero, kElements); + EXPECT(nonzero > 0); + + // The same submission again: the pages keep what they hold, the values do not drift. + EXPECT(submit_write(s, ring_va) == 0); + UINT stable = 0; + for (UINT i = 0; i < kElements; ++i) stable += ring[i] == written[i]; + std::printf("write back: the pages kept those words across two submissions %u/%u\n", stable, kElements); + EXPECT(stable == kElements); + + // A write by the title after a submission is copied forward over the result again, not overwritten by it. + for (UINT i = 0; i < kElements; ++i) ring[i] = 0xB16B00B5u; + EXPECT(submit_write(s, ring_va) == 0); + UINT kept = 0; + for (UINT i = 0; i < kElements; ++i) kept += ring[i] == 0xB16B00B5u; + std::printf("write back: the title's own words survived the next submission %u/%u\n", kept, kElements); + EXPECT(kept == kElements); + + aliases.remove_title_memory(ring_va); + VirtualFree(ring, 0, MEM_RELEASE); + return 0; +} + void remove_test_pair(std::uintptr_t gpu, std::uintptr_t cpu) { auto& state = leonida::title_gpu_views::state(); std::unique_lock lock(state.mutex); @@ -987,6 +1174,8 @@ int main(int argc, char** argv) { const bool api_copy = api_copy_off || (argc == 2 && std::strcmp(argv[1], "--api-descriptor-copy") == 0); const bool rebind = api_copy || mirror_off || second_device || (argc == 2 && std::strcmp(argv[1], "--rebound-tables") == 0); const bool window_cap = argc == 2 && std::strcmp(argv[1], "--window-cap") == 0; + const bool window_write_back = argc == 2 && std::strcmp(argv[1], "--window-writeback") == 0; + const bool placed_write_back = argc == 2 && std::strcmp(argv[1], "--placed-writeback") == 0; if (window_cap) { const char* cap = std::getenv("LEONIDA_TITLE_WINDOWS_MB"); if (!cap || std::strcmp(cap, "0")) { @@ -1101,6 +1290,25 @@ int main(int argc, char** argv) { std::printf("title memory past the window cap: the views were zero-size and the shader read zeros\n"); return 0; } + if (placed_write_back) { + if (check_placed_write_back(c, geometry)) return 1; + if (d.validation_errors()) { + std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); + return 1; + } + std::printf("title-placed buffer write back: the GPU's writes reached the title's pages\n"); + return 0; + } + if (window_write_back) { + if (check_window_write_back(c, geometry)) return 1; + if (d.validation_errors()) { + std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); + return 1; + } + std::printf("title window write back: the GPU's writes reached the title's pages and the title's own " + "words won\n"); + return 0; + } if (geometry && check_declined_imports(c)) return 1; if (geometry && check_import_over_shadow(c)) return 1; if (check_kind(c, "read-write", PAGE_READWRITE, checks)) return 1; diff --git a/runtime/test/d3d12_translated_draw_test.cpp b/runtime/test/d3d12_translated_draw_test.cpp index 5601102409..b45cc2c841 100644 --- a/runtime/test/d3d12_translated_draw_test.cpp +++ b/runtime/test/d3d12_translated_draw_test.cpp @@ -193,6 +193,7 @@ int main(int argc, char** argv) { rt::d3d12::VulkanDeviceInfo info{}; info.prepare_on_bind=d.prepare_on_bind; info.cold_graphics_compile=d.cold_graphics_compile; + info.heavy_pipeline_cache=d.heavy_pipeline_cache; info.get_instance_proc = d.instance_proc; info.instance = d.instance; info.physical = d.physical; diff --git a/runtime/test/d3d12_xmem_placed_test.cpp b/runtime/test/d3d12_xmem_placed_test.cpp index 7c64a23cf6..33b5d462ad 100644 --- a/runtime/test/d3d12_xmem_placed_test.cpp +++ b/runtime/test/d3d12_xmem_placed_test.cpp @@ -174,6 +174,82 @@ int queue_remap(ID3D12Device* real, ID3D12Device* proxy) { return 0; } +// Queue slot 31 as a retail run takes it: no batch hook, so the queue's default adapter sends each range to xmem's +// range callback (copy_page_mappings_fn), which mirrors a legacy-paired GPU-only destination at its CPU view. The +// source is a GPU-only pool backed only through its CPU alias, and the title maps a page of its own at one CPU twin +// while the remap waits behind queue work (deferred with list values, waited for without them). When the remap is +// applied, the GPU-only pages change and the title's CPU page keeps its bytes, through the copy and the unmap after it. +int queue_remap_default_route(ID3D12Device* real, ID3D12Device* proxy) { + using rt::xmem::PageBatch; + using rt::xmem::PageRange; + auto reserve = reinterpret_cast(rt::shims::find("xmem.dll", "XMemVirtualAlloc")); + auto allocate = reinterpret_cast(rt::shims::find("xmem.dll", "XMemAllocatePhysicalPages")); + auto map = reinterpret_cast(rt::shims::find("xmem.dll", "XMemMapPhysicalPages")); + auto free_pages = reinterpret_cast(rt::shims::find("xmem.dll", "XMemFreePhysicalPages")); + constexpr unsigned n = 2; + auto window = [&](DWORD protect) { + return static_cast(reserve(nullptr, n * kPage64k, MEM_RESERVE | kXmem64kPages, 0, protect)); + }; + // Two pairs, each a CPU range and then the GPU-only range of its size: the pool's and the destination's. + auto* pool_cpu = window(PAGE_READWRITE); + auto* pool = window(0x801); + auto* cpu = window(PAGE_READWRITE); + auto* dst = window(0x801); + EXPECT(pool_cpu && pool && cpu && dst); + EXPECT(leonida::title_gpu_views::to_cpu(uintptr_t(pool)) == uintptr_t(pool_cpu)); + EXPECT(leonida::title_gpu_views::to_cpu(uintptr_t(dst)) == uintptr_t(cpu)); + std::uint64_t pages[n + 1]{}, count = n + 1; + EXPECT(allocate(0x280, &count, pages) && count == n + 1); + EXPECT(map(pool_cpu, n, pages)); // the pool's pages are mapped at its CPU alias only + for (unsigned i = 0; i < n; ++i) pool_cpu[i * kPage64k] = static_cast(40 + i); + + D3D12_COMMAND_QUEUE_DESC desc{D3D12_COMMAND_LIST_TYPE_COPY}; + Ref queue; + Ref gate; + EXPECT(SUCCEEDED(proxy->CreateCommandQueue(&desc, IID_PPV_ARGS(&queue.p)))); + EXPECT(SUCCEEDED(real->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&gate.p)))); + auto* real_queue = rt::d3d12_xs::queue_proxy_real_queue(queue.p); + EXPECT(real_queue && SUCCEEDED(real_queue->Wait(gate.p, 1))); + rt::d3d12_xs::set_copy_page_mappings_hook(nullptr); // the retail route: the default adapter + using Copy = HRESULT(WINAPI*)(void*, UINT, const PageBatch*, std::uintptr_t, UINT, UINT); + auto call = reinterpret_cast((*reinterpret_cast(queue.p))[31]); + const PageRange copy_run[] = {{0, 0, n}}; + const PageBatch copy_batch{uintptr_t(dst), 1, copy_run}; + auto done = std::async(std::launch::async, [&] { return call(queue.p, 1, ©_batch, uintptr_t(pool), n, 0); }); + // While the remap waits behind the held work, the title maps a page of its own at the second CPU twin. + EXPECT(map(cpu + kPage64k, 1, &pages[n])); + cpu[kPage64k] = 77; + EXPECT(SUCCEEDED(gate->Signal(1))); + EXPECT(SUCCEEDED(done.get())); + EXPECT(SUCCEEDED(real_queue->Signal(gate.p, 2))); + HANDLE remapped = CreateEventW(nullptr, FALSE, FALSE, nullptr); + EXPECT(remapped && SUCCEEDED(gate->SetEventOnCompletion(2, remapped))); + const auto completion = WaitForSingleObject(remapped, 10000); + CloseHandle(remapped); + EXPECT(completion == WAIT_OBJECT_0); + EXPECT(dst[0] == 40 && dst[kPage64k] == 41); // the GPU-only pages, found through the pool's CPU alias + EXPECT(cpu[0] == 40); // a CPU twin with no mapping of the title's follows the copy + EXPECT(cpu[kPage64k] == 77); // the title's own page is kept + + // The unmap: the GPU-only pages and the mirrored twin are unmapped, the title's page stays. + const PageRange hole[] = {{2, 0, n}}; + const PageBatch unmap_batch{uintptr_t(dst), 1, hole}; + EXPECT(SUCCEEDED(call(queue.p, 1, &unmap_batch, uintptr_t(pool), n, 0))); + EXPECT(SUCCEEDED(real_queue->Signal(gate.p, 3))); + remapped = CreateEventW(nullptr, FALSE, FALSE, nullptr); + EXPECT(remapped && SUCCEEDED(gate->SetEventOnCompletion(3, remapped))); + EXPECT(WaitForSingleObject(remapped, 10000) == WAIT_OBJECT_0); + CloseHandle(remapped); + EXPECT(state_is(dst, MEM_RESERVE) && state_is(dst + kPage64k, MEM_RESERVE) && state_is(cpu, MEM_RESERVE)); + EXPECT(cpu[kPage64k] == 77); + + EXPECT(map(cpu + kPage64k, 1, nullptr) && map(pool_cpu, n, nullptr)); + EXPECT(free_pages(n + 1, pages)); + std::puts("queue slot 31 default route: a source through its CPU alias, a deferred copy and an unmap keep the " + "title's own CPU twin page"); + return 0; +} + // What a GPU copy of `buffer` reads now (a submission: the shadows are refreshed first). int read_back(ID3D12Device* real, ID3D12Resource* buffer, UINT64 size, std::vector& out) { D3D12_RESOURCE_DESC desc = buffer->GetDesc(); @@ -547,6 +623,7 @@ int main(int argc, char** argv) { failures += run(real.p, device.p, eager); failures += exposure_map_ranges(device.p); failures += queue_remap(real.p, device.p); + failures += queue_remap_default_route(real.p, device.p); failures += paired_views(real.p); } } diff --git a/runtime/test/dstorage_test.cpp b/runtime/test/dstorage_test.cpp index c24bcdb652..fa1b529d04 100644 --- a/runtime/test/dstorage_test.cpp +++ b/runtime/test/dstorage_test.cpp @@ -18,6 +18,7 @@ #include #include "../src/bcpack.h" #include "../src/bcpack_stream.h" +#include "../src/dstorage_hold.h" #include "../src/title_geometry_watch.h" #include "../src/title_page_watch.h" #include "xmem.h" @@ -1613,6 +1614,259 @@ void test_extended(Env& env) { q->Release(); } +// A queue half full submits itself, but a read into physical pages and everything behind it wait for Submit: the +// title may fill the page list right before its own Submit. Until then the list names no page (the read would +// fail) or the page its slot named before (the data would land in a page that belongs to something else). The two +// cases of Marvisak/VIctory eddde73, then the ways a hold ends without Submit. +void test_page_reads_wait_for_submit(Env& env) { + 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, bytes = 4096; + 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 for the held reads"); + if (!mapped) { + if (allocated) free_pages(count, pages); + if (window) VirtualFree(window, 0, MEM_RELEASE); + return; + } + auto& h = leonida::dstorage::hold_stats(); + const auto plain = pattern(bytes, 9); + const auto into_pages = [&](ULONG_PTR* list) { + DSTORAGE_REQUEST r{}; + r.Options.AsUINT64 = options::kSourceMemory | options::kDestinationPages; + r.DestinationPageArray = list; + r.DestinationPageOffset = 0; + r.Source = plain.data(); + r.SourceSize = r.DestinationSize = static_cast(bytes); + return r; + }; + const auto into_buffer = [&](uint8_t* out) { + DSTORAGE_REQUEST r{}; + r.Options.AsUINT64 = options::kSourceMemory; + r.Destination = out; + r.Source = plain.data(); + r.SourceSize = r.DestinationSize = 16; + return r; + }; + const auto zero = [&](const uint8_t* at, size_t n) { return std::all_of(at, at + n, [](uint8_t b) { return b == 0; }); }; + const auto holds_plain = [&](const uint8_t* at, size_t n) { return std::memcmp(at, plain.data(), n) == 0; }; + const auto errors = [&] { + DSTORAGE_STATS stats{}; + env.factory->GetStats(&stats); + return stats.ErrorCount; + }; + constexpr int kHalf = 0x40; // of a capacity of 0x80 + std::vector outs(kHalf * 16); + const auto reset = [&] { + std::memset(window, 0, 2*page); + std::fill(outs.begin(), outs.end(), uint8_t{0}); + }; + + // The list still names the slot's previous page when the queue submits itself, the right one by Submit. + { + reset(); + auto* q = make_queue(env, 0x80, true, DSTORAGE_REQUEST_SOURCE_MEMORY, DSTORAGE_PRIORITY_REALTIME); + auto* status = make_status(env, 1); + const uint64_t self = h.self_submits.load(), held = h.held_reads.load(), failed = errors(); + ULONG_PTR list[] = {static_cast(pages[0])}; + DSTORAGE_REQUEST r = into_buffer(outs.data()); + q->EnqueueRequest(&r); + r = into_pages(list); + q->EnqueueRequest(&r); + for (int i = 2; i < kHalf; ++i) { + r = into_buffer(outs.data() + i * 16); + q->EnqueueRequest(&r); // the last one makes half the capacity + } + check(wait_until([&] { return holds_plain(outs.data(), 16); }), + "the entry ahead of a read into pages starts when the queue submits itself"); + Sleep(50); // time for an early read to land in the old page + check(zero(window, bytes), "a self-submit does not write the page the list named before the title's Submit"); + check(zero(outs.data() + 2 * 16, 16), "entries behind a held read keep their place"); + check(h.self_submits.load() == self + 1 && h.held_reads.load() == held + 1, + "one self-submit and one held read are counted"); + DSTORAGE_QUEUE_INFO info{}; + q->Query(&info); + check(info.EmptySlotCount == 0x7f - (kHalf - 1), + "held entries still take their slots"); + list[0] = static_cast(pages[1]); // the title fills its page table, then submits + q->EnqueueStatus(status, 0); + check_hr(status->GetHResult(0), E_PENDING, "a status behind a held read is pending"); + q->Submit(); + check(wait_complete(status, 0), "the held entries run at Submit"); + check_hr(status->GetHResult(0), S_OK, "a read held for Submit succeeds"); + check(holds_plain(window + page, bytes), "the read lands in the page its list names at Submit"); + check(zero(window, bytes), "the page the list named before stays untouched"); + bool all = true; + for (int i = 2; i < kHalf; ++i) all = all && holds_plain(outs.data() + i * 16, 16); + check(all, "every entry behind the held read ran"); + check(errors() == failed, "no entry failed"); + status->Release(); + q->Release(); + } + + // The list is still empty when the queue submits itself: no failure, the read waits. + { + reset(); + auto* q = make_queue(env, 0x80, true, DSTORAGE_REQUEST_SOURCE_MEMORY, DSTORAGE_PRIORITY_REALTIME); + auto* status = make_status(env, 1); + const uint64_t page0 = h.page0_entries.load(), failed = errors(); + ULONG_PTR list[] = {0}; + DSTORAGE_REQUEST r = into_pages(list); + q->EnqueueRequest(&r); + for (int i = 1; i < kHalf; ++i) { + r = into_buffer(outs.data() + i * 16); + q->EnqueueRequest(&r); + } + Sleep(50); + check(h.page0_entries.load() == page0 && errors() == failed, "an empty page list is not read before Submit"); + list[0] = static_cast(pages[0]); + q->EnqueueStatus(status, 0); + q->Submit(); + check(wait_complete(status, 0), "the read with a late page list completes"); + check_hr(status->GetHResult(0), S_OK, "a page list filled before Submit is written"); + check(holds_plain(window, bytes) && errors() == failed, "its bytes are in the page"); + status->Release(); + q->Release(); + } + + // A full queue: the title waits in an enqueue and cannot call Submit, so the held entries go. + { + reset(); + auto* q = make_queue(env, 0x80, true, DSTORAGE_REQUEST_SOURCE_MEMORY, DSTORAGE_PRIORITY_REALTIME); + auto* status = make_status(env, 1); + const uint64_t full = h.full_releases.load(); + ULONG_PTR list[] = {static_cast(pages[1])}; + constexpr int kMany = 200; + std::vector sink(kMany * 16); + std::atomic done{false}; + std::thread producer([&] { + DSTORAGE_REQUEST r = into_pages(list); + q->EnqueueRequest(&r); + for (int i = 0; i < kMany; ++i) { + r = into_buffer(sink.data() + i * 16); + q->EnqueueRequest(&r); + } + q->EnqueueStatus(status, 0); + done.store(true); + }); + check(wait_until([&] { return done.load(); }), "a full queue with held entries does not wait for Submit"); + producer.join(); + check(h.full_releases.load() == full + 1, "the full queue's release is counted"); + q->Submit(); + check(wait_complete(status, 0), "the full queue's entries complete"); + check_hr(status->GetHResult(0), S_OK, "they succeed"); + bool all = holds_plain(window + page, bytes); + for (int i = 0; i < kMany; ++i) all = all && holds_plain(sink.data() + i * 16, 16); + check(all, "every entry of the full queue has its bytes"); + status->Release(); + q->Release(); + } + + // A hold has a time limit: held entries go after LEONIDA_DSTORAGE_HOLD_MS without Submit, 2000 ms unless set. + for (const wchar_t* limit : {static_cast(nullptr), L"200"}) { + reset(); + SetEnvironmentVariableW(L"LEONIDA_DSTORAGE_HOLD_MS", limit); + auto* q = make_queue(env, 0x80, true, DSTORAGE_REQUEST_SOURCE_MEMORY, DSTORAGE_PRIORITY_REALTIME); + SetEnvironmentVariableW(L"LEONIDA_DSTORAGE_HOLD_MS", nullptr); + const uint64_t timed = h.timed_releases.load(); + ULONG_PTR list[] = {static_cast(pages[0])}; + const auto begin = std::chrono::steady_clock::now(); + DSTORAGE_REQUEST r = into_pages(list); + q->EnqueueRequest(&r); + for (int i = 1; i < kHalf; ++i) { + r = into_buffer(outs.data() + i * 16); + q->EnqueueRequest(&r); + } + check(zero(window, bytes), "a hold with a time limit starts as a hold"); + if (!limit) { + Sleep(1000); + check(zero(window, bytes), "the default limit is not over after a second"); + } + check(wait_until([&] { return holds_plain(window, bytes); }), + limit ? "LEONIDA_DSTORAGE_HOLD_MS ends a hold" : "a hold ends by itself without the variable"); + const auto waited = std::chrono::duration_cast( + std::chrono::steady_clock::now() - begin).count(); + check(waited >= (limit ? 150 : 1900) && waited < (limit ? 2000 : 6000), + limit ? "after about the 200 ms asked for" : "after about the default 2000 ms"); + check(h.timed_releases.load() == timed + 1, "the timed release is counted"); + q->Release(); + } + + // LEONIDA_DSTORAGE_HOLD_MS=0: no time limit, the entries wait for Submit. + { + reset(); + SetEnvironmentVariableW(L"LEONIDA_DSTORAGE_HOLD_MS", L"0"); + auto* q = make_queue(env, 0x80, true, DSTORAGE_REQUEST_SOURCE_MEMORY, DSTORAGE_PRIORITY_REALTIME); + SetEnvironmentVariableW(L"LEONIDA_DSTORAGE_HOLD_MS", nullptr); + auto* status = make_status(env, 1); + const uint64_t timed = h.timed_releases.load(); + ULONG_PTR list[] = {static_cast(pages[0])}; + DSTORAGE_REQUEST r = into_pages(list); + q->EnqueueRequest(&r); + for (int i = 1; i < kHalf; ++i) { + r = into_buffer(outs.data() + i * 16); + q->EnqueueRequest(&r); + } + Sleep(2300); // past the default limit + check(zero(window, bytes) && h.timed_releases.load() == timed, "with 0 a hold outlasts the default limit"); + q->EnqueueStatus(status, 0); + q->Submit(); + check(wait_complete(status, 0) && holds_plain(window, bytes), "and ends at Submit"); + status->Release(); + q->Release(); + } + + // LEONIDA_DSTORAGE_HOLD_PAGES=0: the self-submit takes everything, as before. + { + reset(); + SetEnvironmentVariableW(L"LEONIDA_DSTORAGE_HOLD_PAGES", L"0"); + auto* q = make_queue(env, 0x80, true, DSTORAGE_REQUEST_SOURCE_MEMORY, DSTORAGE_PRIORITY_REALTIME); + SetEnvironmentVariableW(L"LEONIDA_DSTORAGE_HOLD_PAGES", nullptr); + const uint64_t held = h.held_reads.load(); + ULONG_PTR list[] = {static_cast(pages[1])}; + DSTORAGE_REQUEST r = into_pages(list); + q->EnqueueRequest(&r); + for (int i = 1; i < kHalf; ++i) { + r = into_buffer(outs.data() + i * 16); + q->EnqueueRequest(&r); + } + check(wait_until([&] { return holds_plain(window + page, bytes); }), + "LEONIDA_DSTORAGE_HOLD_PAGES=0 submits a read into pages with the rest"); + check(h.held_reads.load() == held, "and holds nothing"); + q->Release(); + } + + // A list that names page 0 when its data is written fails the entry and is counted. + { + auto* q = make_queue(env, 0x80, false, DSTORAGE_REQUEST_SOURCE_MEMORY, DSTORAGE_PRIORITY_REALTIME); + auto* status = make_status(env, 1); + const uint64_t page0 = h.page0_entries.load(); + ULONG_PTR list[] = {0}; + DSTORAGE_REQUEST r = into_pages(list); + q->EnqueueRequest(&r); + q->EnqueueStatus(status, 0); + q->Submit(); + check(wait_complete(status, 0), "the read with an empty page list completes"); + check_hr(status->GetHResult(0), E_INVALIDARG, "a page list naming page 0 at Submit fails its entry"); + check(h.page0_entries.load() == page0 + 1, "the entry with page 0 in its list is counted"); + status->Release(); + q->Release(); + } + + map(window, 2, nullptr); + free_pages(count, pages); + VirtualFree(window, 0, MEM_RELEASE); +} + } // namespace int main() { @@ -1668,6 +1922,7 @@ int main() { test_stats_timing(env); test_stats(env); test_extended(env); + test_page_reads_wait_for_submit(env); test_guarded_destinations(env); test_zlib(env); // after test_stats, whose request totals it would change diff --git a/runtime/test/gameinput_no_sdl_test.cpp b/runtime/test/gameinput_no_sdl_test.cpp index a131dc7c99..24a29f2a62 100644 --- a/runtime/test/gameinput_no_sdl_test.cpp +++ b/runtime/test/gameinput_no_sdl_test.cpp @@ -98,8 +98,10 @@ Pad read_at(IGameInput* input, IGameInputDevice* device, double seconds) { } int scripted_pad(CreateFn create) { - // Four presses (two overlapping A presses, Menu, a right-stick throw) and three rejected entries. - SetEnvironmentVariableA("LEONIDA_INPUT_SCRIPT", "a@1, START@2.5 ,a@1.2,rsup@4,bogus@1,a@-1,"); + // Five presses (two overlapping A presses, Menu, B held 0.8 s, a right-stick throw) and seven rejected entries + // (four of them holds that are zero, negative, missing or too long). + SetEnvironmentVariableA("LEONIDA_INPUT_SCRIPT", + "a@1, START@2.5 ,a@1.2,b@3:0.8 ,rsup@4,bogus@1,a@-1,,x@3:0,x@3:-1,x@3:,x@3:601"); rt::gameinput_no_sdl::set_clock(fake_clock); at(0); @@ -201,6 +203,10 @@ int scripted_pad(CreateFn create) { check(menu.buttons == GameInputGamepadMenu && menu.ui == GameInputUiNavigationMenu, "script: START (any case) holds Menu at 2.6 s"); check(read_at(input, device, 2.85).buttons == 0, "script: Menu is released at 2.85 s"); + check(read_at(input, device, 3.05).buttons == GameInputGamepadB, "script: b@3:0.8 holds B at 3.05 s"); + check(read_at(input, device, 3.7).buttons == GameInputGamepadB, + "script: B is still held at 3.7 s, past the 0.3 s default"); + check(read_at(input, device, 3.85).buttons == 0, "script: B is released after its 0.8 s hold"); const Pad up = read_at(input, device, 4.1); check(up.buttons == 0 && up.right_y == 1.0f && up.ui == GameInputUiNavigationScrollUp, "script: rsup throws the right stick up at 4.1 s"); diff --git a/runtime/test/gameinput_test.cpp b/runtime/test/gameinput_test.cpp index be9dc53984..09d959f34e 100644 --- a/runtime/test/gameinput_test.cpp +++ b/runtime/test/gameinput_test.cpp @@ -1718,10 +1718,12 @@ int main(int argc, char** argv) { check(create(&input) == S_OK && input, "GameInputCreate returns an instance"); if (argc == 2 && std::strcmp(argv[1], "--input-script") == 0) { if (!input) return 1; - // Only the X after byte 63 is due now. Its later entry must not cancel it. + // Only the X after byte 63 and the Y held 0.6 s are due now. X's later entry must not cancel it; the + // malformed holds at the end hold nothing. set_env("LEONIDA_INPUT_SCRIPT", "start@3600,start@3600,start@3600,start@3600,start@3600,start@3600, X@0 \t,x@3600," - "unknown@0,a@,a@x,,a@-0.1,a@nan,a@inf,a@1e999,a@0tail, ,"); + "unknown@0,a@,a@x,,a@-0.1,a@nan,a@inf,a@1e999,a@0tail, ,y@0:0.6," + "a@0:0,a@0:-1,a@0:,a@0:x,a@0:inf,a@0:601,a@0:1tail"); set_env("LEONIDA_KEYBOARD_PAD", "1"); rt::gameinput::set_keyboard_source(fake_key_down, fake_focus); rt::gameinput::set_cursor_source(fake_cursor); @@ -1730,27 +1732,32 @@ int main(int argc, char** argv) { rt::gameinput::reload_config(); rt::gameinput::poll(); const auto buttons = pad_state(input, nullptr).buttons; - const auto expected = GameInputGamepadX | GameInputGamepadB; - check((buttons & expected) == expected, "long script: the spaced X after byte 63 and the physical B are held"); + const auto expected = GameInputGamepadX | GameInputGamepadB | GameInputGamepadY; + check((buttons & expected) == expected, + "long script: the spaced X after byte 63, the held Y and the physical B are held"); check((buttons & ~expected) == 0, "malformed script entries hold no extra buttons"); g_focus = false; set_env("LEONIDA_INPUT_SCRIPT", "y@0"); rt::gameinput::reload_config(); rt::gameinput::poll(); - check(pad_state(input, nullptr).buttons == GameInputGamepadX, - "scripted X survives focus loss; reload does not replace it with Y"); + check(pad_state(input, nullptr).buttons == (GameInputGamepadX | GameInputGamepadY), + "scripted X and Y survive focus loss; reload does not replace the script with y@0"); Sleep(350); g_focus = true; rt::gameinput::poll(); - // A scripted press lasts its 300 ms and then until the title has read the pads six times since it began - // (update_keyboard_pad: kReads, at most kMaxHold seconds), so a title that polls slowly still sees it. Each - // pad_state() is one GetCurrentReading, and this is the third since the X began. - check(pad_state(input, nullptr).buttons == (GameInputGamepadX | GameInputGamepadB), - "long script: past its 300 ms the press is still held while the title has read the pads fewer than six times"); + // A scripted press lasts its hold (300 ms, or button@seconds:hold) and then until the title has read the pads + // six times since it began (update_keyboard_pad: kReads), so a title that polls slowly still sees it. Each + // pad_state() is one GetCurrentReading, and this is the third since X and Y began. + check(pad_state(input, nullptr).buttons == (GameInputGamepadX | GameInputGamepadB | GameInputGamepadY), + "long script: past its 300 ms X is still held while the title has read the pads fewer than six times"); for (int i = 0; i < 6; ++i) pad_state(input, nullptr); rt::gameinput::poll(); + check(pad_state(input, nullptr).buttons == (GameInputGamepadB | GameInputGamepadY), + "long script: X ends once the title has read it, y@0:0.6 is still held for its time, the key stays held"); + Sleep(400); + rt::gameinput::poll(); check(pad_state(input, nullptr).buttons == GameInputGamepadB, - "long script: the timed press ends once the title has read it, while the physical key stays held"); + "long script: Y is released after its 0.6 s hold, the title having read it six times"); input->Release(); std::printf("%d checks, %d failures\n", g_checks, g_failures); return g_failures ? 1 : 0; diff --git a/runtime/test/geometry_views_test.cpp b/runtime/test/geometry_views_test.cpp index caac93dc09..d1e9a07d88 100644 --- a/runtime/test/geometry_views_test.cpp +++ b/runtime/test/geometry_views_test.cpp @@ -16,7 +16,10 @@ // 13. a submission's sequence on an idle GPU (completed == submitted): a view retired by the drain in before_execute_ // (kAfterExecutes) is freed only after every replay begun before the retirement recorded its submissions and those // completed (a ticket read in the drain reaps it at once); its answers made without an alias are invalidated -// (forget_copy); its destroyed block leaves the lock-free block list and is reported to the device. +// (forget_copy); its destroyed block leaves the lock-free block list and is reported to the device; +// 14. LEONIDA_GEOMETRY_HOST picks a system-memory type (write-back for 1, write-combined for 2), never the BAR; +// 15. a retired view is copied once more from its pages when they are readable (a remap), not when they are not; +// 16. a full release queue joins touching ranges before it collapses to one covering range. #include #include @@ -61,7 +64,7 @@ VKAPI_ATTR void VKAPI_CALL requirements(VkDevice, VkBuffer buffer, VkMemoryRequi *out = {}; out->size = reinterpret_cast(buffer)->size; out->alignment = 65536; - out->memoryTypeBits = 1; + out->memoryTypeBits = 0xf; // the four types of test 14's device } VKAPI_ATTR VkResult VKAPI_CALL bind(VkDevice, VkBuffer buffer, VkDeviceMemory memory, VkDeviceSize) { reinterpret_cast(buffer)->memory = memory; @@ -510,6 +513,109 @@ int main() { } VirtualFree(fly_title, 0, MEM_RELEASE); + // 14. LEONIDA_GEOMETRY_HOST: the copies' memory type. A discrete GPU's types: 0 VRAM, 1 VRAM through the BAR, + // 2 system memory write-combined, 3 system memory write-back. 1 takes type 3 (write-back preferred), 2 type 2, + // unset any host-visible type with device-local preferred (the BAR); a device whose host-visible types are all + // device-local (an integrated GPU) keeps them all. + { + struct TypedDevice : FakeDevice { + VkPhysicalDeviceMemoryProperties memory{}; + std::uint32_t bits = 0; + VkMemoryPropertyFlags preferred = 0; + VkDeviceMemory allocate(const VkMemoryRequirements& r, VkMemoryPropertyFlags required, + VkMemoryPropertyFlags wanted, VkMemoryPropertyFlags* chosen, bool address) { + bits = r.memoryTypeBits; + preferred = wanted; + return FakeDevice::allocate(r, required, wanted, chosen, address); + } + }; + constexpr VkMemoryPropertyFlags kLocal = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, + kHost = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | + VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, + kCached = VK_MEMORY_PROPERTY_HOST_CACHED_BIT; + TypedDevice discrete; + discrete.memory.memoryTypeCount = 4; + const VkMemoryPropertyFlags discrete_types[4] = {kLocal, kLocal | kHost, kHost, kHost | kCached}; + for (int i = 0; i < 4; ++i) discrete.memory.memoryTypes[i].propertyFlags = discrete_types[i]; + TypedDevice integrated; + integrated.memory.memoryTypeCount = 2; + integrated.memory.memoryTypes[0].propertyFlags = kLocal; + integrated.memory.memoryTypes[1].propertyFlags = kLocal | kHost | kCached; + auto* host_title = + static_cast(VirtualAlloc(nullptr, kView, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); + if (!host_title) return 1; + const auto hbase = reinterpret_cast(host_title); + const auto made_with = [&](TypedDevice& dev, const char* setting) { + _putenv_s("LEONIDA_GEOMETRY_HOST", setting); + dev.bits = ~0u; + dev.preferred = 0; + rt::d3d12::GeometryViews v; + const bool made = v.resolve(dev, hbase, kView, copy) != 0; + const int kind = v.system_memory(); + v.release(dev); + return made ? kind : -1; + }; + check(made_with(discrete, "1") == rt::d3d12::TitleBufferWindows::kSystemCached && discrete.bits == 1u << 3 && + discrete.preferred == kCached, + "LEONIDA_GEOMETRY_HOST=1 puts the copies in write-back system memory, never the BAR"); + check(made_with(discrete, "2") == rt::d3d12::TitleBufferWindows::kSystemUncached && discrete.bits == 1u << 2 && + discrete.preferred == 0, + "LEONIDA_GEOMETRY_HOST=2 puts them in write-combined system memory"); + check(made_with(discrete, "") == rt::d3d12::TitleBufferWindows::kDeviceLocal && discrete.bits == 0xfu && + discrete.preferred == kLocal, + "unset, every type the buffer allows is tried, device-local first"); + check(made_with(integrated, "1") == rt::d3d12::TitleBufferWindows::kSystemCached && integrated.bits == 0xfu, + "on a device with no host type outside device-local memory, the types are left as they are"); + _putenv_s("LEONIDA_GEOMETRY_HOST", ""); + check(g_live_buffers == 0, "the memory-type views free their blocks"); + + // 15. A retired view is copied once more from the title's pages when they are readable (a remap gave them new + // bytes), and keeps what it held when they are not (freed or unmapped). + rt::d3d12::GeometryViews last; + std::memset(host_title, 0x11, kView); + const std::uint64_t va_l = last.resolve(device, hbase, kView, copy); + std::uint64_t host_l = 0, bytes_l = 0; + check(va_l && last.lookup(device.arena.address + va_l, host_l, bytes_l), "a view to retire"); + auto* held = reinterpret_cast(host_l); + // The remapped pages' bytes: the watched tiles are opened first (no fault handler here). + leonida::geometry_writes::notify(hbase, hbase + kView, leonida::geometry_writes::Event::open); + std::memset(host_title, 0x22, kView); + g_copies.clear(); + check(last.retire_range(hbase, hbase + kView, 1, [](std::uintptr_t, std::size_t, VkDeviceSize) {}, copy) == 1 && + held[0] == 0x22 && held[kView - 1] == 0x22 && last.final_copies() == 1 && g_copies.size() == 1, + "a retired view whose pages are readable is copied from them once more"); + const std::uint64_t va_l2 = last.resolve(device, hbase, kView, copy); + std::uint64_t host_l2 = 0; + check(va_l2 && last.lookup(device.arena.address + va_l2, host_l2, bytes_l), "and made again"); + auto* held2 = reinterpret_cast(host_l2); + leonida::geometry_writes::notify(hbase, hbase + kView, leonida::geometry_writes::Event::open); + std::memset(host_title, 0x33, kView); + const auto unreadable = [](std::uint8_t*, const std::uint8_t*, std::size_t) { + return rt::d3d12::GeometryCopy::unreadable; + }; + check(last.retire_range(hbase, hbase + kView, 2, [](std::uintptr_t, std::size_t, VkDeviceSize) {}, + unreadable) == 1 && + held2[0] == 0x22 && last.final_copies() == 1, + "one whose pages are not readable keeps what it held"); + check(last.reap(device, 2) == 2 && last.bytes() == 0, "both are freed at their tickets"); + last.release(device); + + // 16. A full release queue first joins ranges that touch (remaps report page runs): 65536 neighbouring ranges + // and one apart from them are two ranges, not one covering everything between them. + rt::d3d12::GeometryViews coalesce; + check(coalesce.resolve(device, hbase, kView, copy) != 0, "a view to watch the pages"); + for (std::size_t i = 0; i < 65536; ++i) + leonida::geometry_writes::note_released(hbase + i * 8, hbase + i * 8 + 8); + leonida::geometry_writes::note_released(hbase + kView - 4096, hbase + kView); + std::vector> joined; + leonida::geometry_writes::take_released(coalesce.release_queue(), joined); + check(joined.size() == 2 && joined[0] == std::make_pair(hbase, hbase + 65536 * 8) && + joined[1] == std::make_pair(hbase + kView - 4096, hbase + kView), + "65536 touching ranges become one, and a range apart from them stays apart"); + coalesce.release(device); + VirtualFree(host_title, 0, MEM_RELEASE); + } + std::printf("%d checks, %d failures\n", g_checks, g_failures); return g_failures ? 1 : 0; } diff --git a/runtime/test/heavy_pipeline_cache_test.cpp b/runtime/test/heavy_pipeline_cache_test.cpp new file mode 100644 index 0000000000..8181a047cd --- /dev/null +++ b/runtime/test/heavy_pipeline_cache_test.cpp @@ -0,0 +1,109 @@ +// src/heavy_pipeline_cache.h: the LEONIDA_HEAVY_PIPELINE_CACHE_MS threshold and when the heavy cache is written. +// No Vulkan, no GPU, no files. +#include "../src/heavy_pipeline_cache.h" + +#include +#include + +#define CHECK(condition) do { \ + if (!(condition)) { \ + std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); \ + return 1; \ + } \ +} while (0) + +namespace heavy = leonida::heavy_pipeline_cache; + +static int test_threshold() { + CHECK(heavy::parse_threshold(nullptr).ms == heavy::default_threshold_ms); + CHECK(heavy::parse_threshold("").ms == heavy::default_threshold_ms); + CHECK(heavy::parse_threshold("0").ms == 0 && heavy::parse_threshold("0").valid); // off + CHECK(heavy::parse_threshold("2000").ms == 2000); + CHECK(heavy::parse_threshold("0750").ms == 750); + // Not a number, a sign, a unit or an absurd value: the default, reported as invalid. + for (const char* bad : {"-1", "+5", "1s", "1.5", "abc", "3600001", "99999999999999999999"}) { + const auto t = heavy::parse_threshold(bad); + CHECK(!t.valid && t.ms == heavy::default_threshold_ms); + } + CHECK(heavy::parse_threshold("3600000").valid); + return 0; +} + +static int test_schedule() { + using S = heavy::WriteSchedule; + S s; + CHECK(!s.dirty() && !s.due(1'000'000)); + // One heavy compile: written once it has settled. + s.note_heavy(1000); + CHECK(s.dirty() && !s.due(1000 + S::settle_ms - 1) && s.due(1000 + S::settle_ms)); + s.written(s.generation(), 1000 + S::settle_ms); + CHECK(!s.dirty()); + // A burst, one compile a second for a minute: the write does not wait for the burst to end. + S burst; + for (std::uint64_t t = 10'000; t <= 70'000; t += 1000) { + burst.note_heavy(t); + if (burst.due(t)) { + CHECK(t - 10'000 >= S::max_delay_ms); // first write no later than max_delay after the first compile + burst.written(burst.generation(), t); + break; + } + } + CHECK(!burst.dirty()); + // A compile that finishes while a write is running is not lost: the cache stays dirty for the next write. + S racing; + racing.note_heavy(5000); + const std::uint64_t start = 5000 + S::settle_ms; + const std::uint64_t taken = racing.generation(); + racing.note_heavy(start + 10); // during the write + racing.written(taken, start); + CHECK(racing.dirty()); + CHECK(racing.due(start + 10 + S::settle_ms)); + // The same, inside one tick of a coarse clock: the compile noted at the write's own start time is still kept. + S tick; + tick.note_heavy(9000); + const std::uint64_t at = 9000 + S::settle_ms; + const std::uint64_t before = tick.generation(); + tick.note_heavy(at); + tick.written(before, at); + CHECK(tick.dirty()); + return 0; +} + +static int test_failed_write() { + using S = heavy::WriteSchedule; + S s; + s.note_heavy(1000); + std::uint64_t now = 1000 + S::settle_ms; + CHECK(s.due(now)); + // A failed write keeps the cache dirty and waits out the backoff before the next try. + s.failed(now); + CHECK(s.dirty() && s.failures() == 1); + CHECK(!s.due(now) && !s.due(now + S::retry_ms - 1) && s.due(now + S::retry_ms)); + // Failures in a row double the delay up to the cap, so a write that keeps failing does not spin. + std::uint64_t expect = S::retry_ms; + for (int i = 0; i < 12; ++i) { + now = s.due_ms(); + s.failed(now); + expect = expect * 2 > S::max_retry_ms ? S::max_retry_ms : expect * 2; + CHECK(s.due_ms() == now + expect); + } + CHECK(s.due_ms() - now == S::max_retry_ms); + // A heavy compile during the backoff does not bring the retry forward. + s.note_heavy(now + 1); + CHECK(!s.due(now + S::settle_ms + 1) && s.due(now + S::max_retry_ms)); + // A successful write clears the dirty flag and the backoff. + now = s.due_ms(); + s.written(s.generation(), now); + CHECK(!s.dirty() && s.failures() == 0); + s.note_heavy(now + 10); + CHECK(s.due(now + 10 + S::settle_ms)); + return 0; +} + +int main() { + if (const int r = test_threshold()) return r; + if (const int r = test_schedule()) return r; + if (const int r = test_failed_write()) return r; + std::printf("heavy_pipeline_cache: threshold parsing, the write schedule and retries after a failed write\n"); + return 0; +} diff --git a/runtime/test/list_value_wait_budget_test.cpp b/runtime/test/list_value_wait_budget_test.cpp new file mode 100644 index 0000000000..6bf9bfbf53 --- /dev/null +++ b/runtime/test/list_value_wait_budget_test.cpp @@ -0,0 +1,348 @@ +// Portable CPU-only unit tests for runtime/src/list_value_wait_budget.h (RT-LIST-VALUE-WAIT-WORK-AWARE-TIMEOUT): +// work-aware timeout pausing, finite pause caps across all pause reasons (including releaser_busy and +// matching_producer), demoted-gate cap scaling, cycle detection across multi-queue write/gate chains, overwrite-aware +// write matching, action gates, and a mock Pump tick driver. No Windows, D3D12, or Vulkan headers; no game files. +#include "../src/list_value_wait_budget.h" + +#include +#include +#include + +#define CHECK(cond) do { \ + if (!(cond)) { \ + std::fprintf(stderr, "line %d: CHECK failed: %s\n", __LINE__, #cond); \ + return 1; \ + } \ +} while (0) + +namespace { + +constexpr bool test_met(std::uint32_t comparison, std::uint64_t value, std::uint64_t reference, bool wide) { + if (!wide) { + value &= 0xffffffffu; + reference &= 0xffffffffu; + } + switch (comparison) { + case 2: return value < reference; + case 3: return value == reference; + case 4: return value <= reference; + case 5: return value > reference; + case 6: return value != reference; + case 7: return value >= reference; + default: return true; + } +} + +} // namespace + +int main() { + using namespace leonida::list_value_wait; + + int q1_tag = 0, q2_tag = 0, q3_tag = 0; + const void* const q1 = &q1_tag; + const void* const q2 = &q2_tag; + const void* const q3 = &q3_tag; + + // 1. Idle unmodelled wait: PauseReason::none -> expires at exact budget_us. + { + const WaitPredicate waits[] = {{0x1000, 5, 7, true}}; // >= 5 + const PendingGate gates[] = {{q1, 1, false, waits}}; + CHECK(pause_reason(false, {}, gates, 0, test_met) == PauseReason::none); + + GateTimeoutState t; + const PauseCaps caps = default_pause_caps(200, false); + t.reset(200'000, caps.active_us, caps.max_us); + CHECK(!t.advance(100'000, PauseReason::none)); + CHECK(t.elapsed_us == 100'000 && !t.paused_ever); + CHECK(!t.advance(99'999, PauseReason::none)); + CHECK(t.advance(1, PauseReason::none)); + CHECK(t.elapsed_us == 200'000); + } + + // 2. Releaser actively executing held work pauses the timeout clock (covering multi-minute world-phase pipeline + // builds without burning idle budget), yet still expires at the finite max_pause_cap_us if a Signal hangs. + { + const WaitPredicate waits[] = {{0x1000, 5, 7, true}}; + const PendingGate gates[] = {{q1, 1, false, waits}}; + CHECK(pause_reason(true, {}, gates, 0, test_met) == PauseReason::releaser_busy); + + GateTimeoutState t; + const PauseCaps caps = default_pause_caps(200, false); + CHECK(caps.active_us == 60'000'000ull && caps.max_us == 300'000'000ull); + t.reset(200'000, caps.active_us, caps.max_us); + // 120 seconds of releaser executing pipeline builds/copies burns 0 us of idle timeout budget. + for (int i = 0; i < 120; ++i) CHECK(!t.advance(1'000'000, PauseReason::releaser_busy)); + CHECK(t.elapsed_us == 0 && t.total_paused_us == 120'000'000ull && t.paused_ever); + // Once idle again, still gets its full 200 ms budget before expiring. + CHECK(!t.advance(199'000, PauseReason::none)); + CHECK(t.advance(1'000, PauseReason::none)); + + // Hung Signal (releaser_busy forever) hits the finite max_pause_cap_us and then drains budget_us. + GateTimeoutState hung; + hung.reset(200'000, caps.active_us, caps.max_us); + for (int i = 0; i < 300; ++i) CHECK(!hung.advance(1'000'000, PauseReason::releaser_busy)); + CHECK(hung.total_paused_us == 300'000'000ull && hung.elapsed_us == 0); + CHECK(!hung.advance(199'000, PauseReason::releaser_busy)); + CHECK(hung.advance(1'000, PauseReason::releaser_busy)); + CHECK(hung.elapsed_us == 200'000); + } + + // 3. Matching unblocked producer write on another queue (Wait-before-Signal) -> PauseReason::matching_producer. + { + const WaitPredicate waits[] = {{0x2000, 10, 7, true}}; // >= 10 + const PendingWrite w_ok[] = {{0x2000, 12, 8, false}}; + const PendingWriteGroup groups[] = {{q2, 0, w_ok}}; + const PendingGate gates[] = {{q1, 1, false, waits}}; + CHECK(pause_reason(false, groups, gates, 0, test_met) == PauseReason::matching_producer); + + // Timestamp write to the same address also matches (final value unknown until landing). + const PendingWrite w_ts[] = {{0x2000, 0, 8, true}}; + const PendingWriteGroup ts_groups[] = {{q2, 0, w_ts}}; + CHECK(pause_reason(false, ts_groups, gates, 0, test_met) == PauseReason::matching_producer); + + // Matching write overwritten later in the same WriteGroup by a non-matching value does NOT match, + // falling back to active_work (since q2's group is unblocked). + const PendingWrite w_overwritten[] = {{0x2000, 12, 8, false}, {0x2000, 3, 8, false}}; + const PendingWriteGroup ow_groups[] = {{q2, 0, w_overwritten}}; + CHECK(pause_reason(false, ow_groups, gates, 0, test_met) == PauseReason::active_work); + + // Partial overlap by a later write in the same group invalidates the earlier matching write. + const PendingWrite w_partial[] = {{0x2000, 12, 8, false}, {0x2004, 0, 4, false}}; + const PendingWriteGroup part_groups[] = {{q2, 0, w_partial}}; + CHECK(pause_reason(false, part_groups, gates, 0, test_met) == PauseReason::active_work); + + // 4-byte write cannot satisfy an 8-byte (wide) wait. + const PendingWrite w_narrow[] = {{0x2000, 12, 4, false}}; + const PendingWriteGroup nar_groups[] = {{q2, 0, w_narrow}}; + CHECK(pause_reason(false, nar_groups, gates, 0, test_met) == PauseReason::active_work); + + // 8-byte write CAN satisfy a 4-byte wait (low 32 bits compared). + const WaitPredicate wait32[] = {{0x2000, 10, 7, false}}; + const PendingWrite w_hi_lo[] = {{0x2000, 0x100000000ull | 12ull, 8, false}}; + const PendingWriteGroup hilo_groups[] = {{q2, 0, w_hi_lo}}; + const PendingGate gates32[] = {{q1, 1, false, wait32}}; + CHECK(pause_reason(false, hilo_groups, gates32, 0, test_met) == PauseReason::matching_producer); + } + + // 4. Same-queue ordering: a write submitted BEFORE the gate (after_gate < gate.value) IS a live producer; + // a write submitted AFTER the gate (after_gate >= gate.value) is a self-deadlock and MUST NOT pause the gate. + { + const WaitPredicate waits[] = {{0x3000, 1, 7, true}}; + const PendingWrite w[] = {{0x3000, 1, 8, false}}; + const PendingGate gates[] = {{q1, 2, false, waits}}; + + const PendingWriteGroup before_gate[] = {{q1, 1, w}}; // after_gate 1 < gate.value 2 (unblocked!) + CHECK(pause_reason(false, before_gate, gates, 0, test_met) == PauseReason::matching_producer); + + const PendingWriteGroup behind_gate[] = {{q1, 2, w}}; // after_gate 2 == gate.value 2 (held by itself!) + CHECK(pause_reason(false, behind_gate, gates, 0, test_met) == PauseReason::none); + } + + // 5. Mutual 2-queue cycle (Q1 waits on Q2's write behind G2; Q2 waits on Q1's write behind G1): + // NEITHER gate pauses, so the cycle breaks cleanly instead of deadlocking. + { + const WaitPredicate w1[] = {{0x4000, 1, 7, true}}; + const WaitPredicate w2[] = {{0x5000, 1, 7, true}}; + const PendingWrite pw1[] = {{0x5000, 1, 8, false}}; // Q1 writes what Q2 waits for, behind Q1's gate 1 + const PendingWrite pw2[] = {{0x4000, 1, 8, false}}; // Q2 writes what Q1 waits for, behind Q2's gate 1 + const PendingWriteGroup groups[] = {{q1, 1, pw1}, {q2, 1, pw2}}; + const PendingGate gates[] = {{q1, 1, false, w1}, {q2, 1, false, w2}}; + CHECK(pause_reason(false, groups, gates, 0, test_met) == PauseReason::none); + CHECK(pause_reason(false, groups, gates, 1, test_met) == PauseReason::none); + } + + // 6. 3-queue cycle involving a SECOND (non-front) gate on Q2: + // Q1 gate 1 waits on W2 (behind Q2 gates 1 & 2); Q2 gate 2 waits on W1 (behind Q1 gate 1). + // Checking all gates <= after_gate catches this indirect cycle! + { + const WaitPredicate w_q1[] = {{0x6000, 1, 7, true}}; + const WaitPredicate w_q2_g1[] = {{0x6100, 1, 7, true}}; // unrelated front gate on Q2 + const WaitPredicate w_q2_g2[] = {{0x6200, 1, 7, true}}; // second gate on Q2 waits on Q1 + const PendingWrite pw_q1[] = {{0x6200, 1, 8, false}}; // behind Q1 gate 1 + const PendingWrite pw_q2[] = {{0x6000, 1, 8, false}}; // behind Q2 gate 2 (after_gate = 2) + const PendingWriteGroup groups[] = {{q1, 1, pw_q1}, {q2, 2, pw_q2}}; + const PendingGate gates[] = { + {q1, 1, false, w_q1}, + {q2, 1, false, w_q2_g1}, + {q2, 2, false, w_q2_g2}, + }; + CHECK(pause_reason(false, groups, gates, 0, test_met) == PauseReason::none); + CHECK(pause_reason(false, groups, gates, 2, test_met) == PauseReason::none); + } + + // 7. Acyclic 3-queue chain (Q1 -> Q2 -> Q3 where Q3's gate has no producer): + // Q3 does NOT pause (times out first), while Q2 and Q1 wait for their upstream producers to run in order! + { + const WaitPredicate w_q1[] = {{0x7000, 1, 7, true}}; + const WaitPredicate w_q2[] = {{0x7100, 1, 7, true}}; + const WaitPredicate w_q3[] = {{0x7200, 1, 7, true}}; // unmodelled wait on Q3 + const PendingWrite pw_q2[] = {{0x7000, 1, 8, false}}; // Q2 feeds Q1 (behind Q2 gate 1) + const PendingWrite pw_q3[] = {{0x7100, 1, 8, false}}; // Q3 feeds Q2 (behind Q3 gate 1) + const PendingWriteGroup groups[] = {{q2, 1, pw_q2}, {q3, 1, pw_q3}}; + const PendingGate gates[] = { + {q1, 1, false, w_q1}, + {q2, 1, false, w_q2}, + {q3, 1, false, w_q3}, + }; + CHECK(pause_reason(false, groups, gates, 0, test_met) == PauseReason::matching_producer); + CHECK(pause_reason(false, groups, gates, 1, test_met) == PauseReason::matching_producer); + CHECK(pause_reason(false, groups, gates, 2, test_met) == PauseReason::none); + } + + // 8. Action gate on another queue counts as active_work when unblocked, and does NOT count when blocked behind a + // memory gate on its own queue. + { + const WaitPredicate w_q1[] = {{0x8000, 1, 7, true}}; + const WaitPredicate w_q2[] = {{0x8100, 1, 7, true}}; + const PendingGate unblocked_action[] = { + {q1, 1, false, w_q1}, + {q2, 1, true, {}}, // unblocked action gate on Q2 + }; + CHECK(pause_reason(false, {}, unblocked_action, 0, test_met) == PauseReason::active_work); + + const PendingGate blocked_action[] = { + {q1, 1, false, w_q1}, + {q2, 1, false, w_q2}, // memory gate blocking Q2 + {q2, 2, true, {}}, // action gate behind Q2's memory gate + }; + CHECK(pause_reason(false, {}, blocked_action, 0, test_met) == PauseReason::none); + } + + // 9. Bounded pause caps: active_work, matching_producer, releaser_busy, combined alternating reasons, and + // demoted-gate cap scaling. + { + CHECK(default_active_pause_cap_us(200) == 60'000'000ull); + CHECK(default_max_pause_cap_us(200) == 300'000'000ull); + CHECK(default_active_pause_cap_us(30) == 9'000'000ull); + CHECK(default_max_pause_cap_us(30) == 45'000'000ull); + CHECK(default_active_pause_cap_us(1) == 300'000ull); + CHECK(default_max_pause_cap_us(1) == 1'500'000ull); + CHECK(default_active_pause_cap_us(30000) == 600'000'000ull); + CHECK(default_max_pause_cap_us(30000) == 600'000'000ull); + CHECK(default_active_pause_cap_us(UINT_MAX) == 600'000'000ull); + CHECK(default_max_pause_cap_us(UINT_MAX) == 600'000'000ull); + + // Demoted (cut_short) gates scale caps with their short 4 ms budget instead of inheriting 60 s / 300 s. + const PauseCaps dem = default_pause_caps(4, true); + CHECK(dem.active_us == 4'000ull && dem.max_us == 16'000ull); + GateTimeoutState dem_active; + dem_active.reset(4'000, dem.active_us, dem.max_us); + CHECK(!dem_active.advance(4'000, PauseReason::active_work)); // absorbs 4 ms cap + CHECK(dem_active.active_paused_us == 4'000 && dem_active.elapsed_us == 0); + CHECK(!dem_active.advance(3'999, PauseReason::active_work)); + CHECK(dem_active.advance(1, PauseReason::active_work)); // expires at 8 ms total, not 60 s! + + GateTimeoutState dem_prod; + dem_prod.reset(4'000, dem.active_us, dem.max_us); + CHECK(!dem_prod.advance(16'000, PauseReason::matching_producer)); + CHECK(dem_prod.total_paused_us == 16'000 && dem_prod.elapsed_us == 0); + CHECK(dem_prod.advance(4'000, PauseReason::matching_producer)); // expires at 20 ms total + + // Normal gate active_work cap (5 s) vs larger max cap (20 s). + GateTimeoutState t; + t.reset(200'000, 5'000'000, 20'000'000); + for (int i = 0; i < 5; ++i) CHECK(!t.advance(1'000'000, PauseReason::active_work)); + CHECK(t.active_paused_us == 5'000'000 && t.total_paused_us == 5'000'000 && t.elapsed_us == 0 && t.paused_ever); + CHECK(!t.advance(199'000, PauseReason::active_work)); + CHECK(t.advance(1'000, PauseReason::active_work)); + CHECK(t.elapsed_us == 200'000); + + // Stuck matching_producer + alternating releaser_busy share total_paused_us <= max_pause_cap_us. + GateTimeoutState stuck; + stuck.reset(200'000, 2'000'000, 10'000'000); + CHECK(!stuck.advance(2'000'000, PauseReason::active_work)); // total = 2 s + CHECK(!stuck.advance(5'000'000, PauseReason::matching_producer)); // total = 7 s + CHECK(!stuck.advance(3'100'000, PauseReason::releaser_busy)); // 3 s paused (hits 10 s cap), 100 ms elapsed + CHECK(stuck.total_paused_us == 10'000'000 && stuck.elapsed_us == 100'000); + CHECK(!stuck.advance(99'999, PauseReason::matching_producer)); + CHECK(stuck.advance(1, PauseReason::matching_producer)); + CHECK(stuck.elapsed_us == 200'000); + + // Partial step straddling active_pause_cap_us splits cleanly between active_paused_us and elapsed_us. + GateTimeoutState t2; + t2.reset(200'000, 500'000, 1'000'000); + CHECK(!t2.advance(600'000, PauseReason::active_work)); // 500k paused, 100k elapsed + CHECK(t2.active_paused_us == 500'000 && t2.total_paused_us == 500'000 && t2.elapsed_us == 100'000); + CHECK(t2.advance(100'000, PauseReason::active_work)); + + // active_cap > max_cap is clamped to max_cap by reset(). + GateTimeoutState clamped; + clamped.reset(100'000, 9'000'000, 3'000'000); + CHECK(clamped.active_pause_cap_us == 3'000'000 && clamped.max_pause_cap_us == 3'000'000); + } + + // 10. Overflow-safe address / dt_us guards and zero-dt paused tick. + { + const WaitPredicate overflow_wait[] = {{UINT64_MAX - 2, 1, 7, true}}; + const PendingWrite overflow_write[] = {{UINT64_MAX - 2, 1, 8, false}}; + const PendingWriteGroup groups[] = {{q2, 0, overflow_write}}; + const PendingGate gates[] = {{q1, 1, false, overflow_wait}}; + // Write doesn't match due to address wrap guard, falls back to active_work for the unblocked group. + CHECK(pause_reason(false, groups, gates, 0, test_met) == PauseReason::active_work); + + GateTimeoutState t; + t.reset(1000, 0, 0); + CHECK(t.advance(UINT64_MAX, PauseReason::none)); + CHECK(t.elapsed_us == UINT64_MAX); + + GateTimeoutState z; + z.reset(0, 1000, 1000); + CHECK(!z.advance(0, PauseReason::releaser_busy)); + CHECK(!z.paused_ever); + } + + // 11. Mock Pump tick loop driving start_gate + pause_reason + GateTimeoutState end-to-end across 1 ms steps. + { + // (a) 200 ms gate held while releaser runs a 110 s pipeline build, then producer lands at 110.5 s: met! + const WaitPredicate waits[] = {{0x9000, 7, 7, true}}; + const PendingWrite prod_write[] = {{0x9000, 7, 8, false}}; + const PendingWriteGroup prod_groups[] = {{q2, 0, prod_write}}; + const PendingGate gates[] = {{q1, 1, false, waits}}; + + GateTimeoutState gate; + const PauseCaps full_caps = default_pause_caps(200, false); + gate.reset(200'000, full_caps.active_us, full_caps.max_us); + for (int ms = 0; ms < 110'000; ++ms) { + const PauseReason r = pause_reason(true, prod_groups, gates, 0, test_met); + CHECK(r == PauseReason::releaser_busy && !gate.advance(1'000, r)); + } + for (int ms = 0; ms < 500; ++ms) { + const PauseReason r = pause_reason(false, prod_groups, gates, 0, test_met); + CHECK(r == PauseReason::matching_producer && !gate.advance(1'000, r)); + } + CHECK(gate.elapsed_us == 0 && gate.total_paused_us == 110'500'000ull); + + // (b) Same gate with a matching producer stuck behind an untracked title fence wait: expires at 300.2 s! + GateTimeoutState stuck_gate; + stuck_gate.reset(200'000, full_caps.active_us, full_caps.max_us); + int expired_at_ms = -1; + for (int ms = 1; ms <= 305'000; ++ms) { + const PauseReason r = pause_reason(false, prod_groups, gates, 0, test_met); + if (stuck_gate.advance(1'000, r)) { + expired_at_ms = ms; + break; + } + } + CHECK(expired_at_ms == 300'200); + + // (c) Demoted gate (4 ms budget) with continuous unrelated GPU work on q2: expires at 8 ms! + const PendingWrite unrelated[] = {{0xA000, 1, 8, false}}; + const PendingWriteGroup unrel_groups[] = {{q2, 0, unrelated}}; + GateTimeoutState dem_gate; + const PauseCaps dem_caps = default_pause_caps(4, true); + dem_gate.reset(4'000, dem_caps.active_us, dem_caps.max_us); + int dem_expired_ms = -1; + for (int ms = 1; ms <= 100; ++ms) { + const PauseReason r = pause_reason(false, unrel_groups, gates, 0, test_met); + CHECK(r == PauseReason::active_work); + if (dem_gate.advance(1'000, r)) { + dem_expired_ms = ms; + break; + } + } + CHECK(dem_expired_ms == 8); + } + + std::printf("list_value_wait_budget_test: all checks passed\n"); + return 0; +} diff --git a/runtime/test/shaders/cs_address_guard.asm b/runtime/test/shaders/cs_address_guard.asm new file mode 100644 index 0000000000..fad068a66d --- /dev/null +++ b/runtime/test/shaders/cs_address_guard.asm @@ -0,0 +1,57 @@ +; group: 1,1,1 +; rsrc2: 0x8090 +; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm +; The address guard (rdna2spirv.py --address-guard; docs/d3d12_vulkan.md, "Address guard"). Translated with the guard, +; run by scripts/run_address_guard_gpu_test.py on a 2 MiB heap whose page table (built by that script) backs the +; arena (offsets below 0x80000, the header's limit) and the one 4 KiB page at 0x90000, and nothing else. The heap's +; real memory continues past both, so every address below is inside the buffer: with the guard off the same program +; reads and writes it, with the guard on the page table refuses the accesses outside 0x90000..0x90fff. Seeds: +; 0x90000 0xa11ce000 0x90004 0xa11ce004 0x90ffc 0xf00df00d 0x91000 0xf00df00e +; 0xa0000 0xbadbad00 0xa0004 0xbadbad04 0xa0008 0xbadbad08 +; Words stored to out[0..7] with the guard on (off: the second value): +; out[0] global_load_dword at 0x90000, a backed page outside the arena = 0xa11ce000 (0xa11ce000) +; out[1] global_load_dword at 0xa0000, unbacked = 0 (0xbadbad00) +; out[2] global_atomic_add glc at 0xa0008 with 1, unbacked: the old value = 0 (0xbadbad08) +; out[3] global_load_dwordx2 at 0x90ffc: its last byte is on an unbacked page, so all of it is refused +; = 0 (0xf00df00d) +; out[4] its second dword = 0 (0xf00df00e) +; out[5] buffer_load_dword through a V# built in SGPRs, base 0xa0000 = 0 (0xbadbad00) +; out[6] s_load_dword at 0x90004, backed = 0xa11ce004 (0xa11ce004) +; out[7] s_load_dword at 0xa0000, unbacked = 0 (0xbadbad00) +; global_store_dword 0x5707 at 0xa0004 (unbacked) goes to the dump area (0x78004) instead, and the atomic to 0x78008; +; the six refused accesses count themselves at header + 24 (0x70018) and the last one's offset is at 0x70020. +; Run: VKC_HEAP_INIT= VKC_OUT_WORDS=524288 VKC_DUMP= vk_compute_test cs_address_guard.spv 1 dump +v_mov_b32_e32 v0, 0x90000 +v_mov_b32_e32 v1, 0 +global_load_dword v2, v[0:1], off +v_mov_b32_e32 v0, 0xa0000 +global_load_dword v3, v[0:1], off +v_mov_b32_e32 v4, 0x5707 +global_store_dword v[0:1], v4, off offset:4 +v_mov_b32_e32 v5, 1 +global_atomic_add v5, v[0:1], v5, off offset:8 glc +v_mov_b32_e32 v0, 0x90ffc +global_load_dwordx2 v[6:7], v[0:1], off +s_mov_b32 s4, 0xa0000 +s_mov_b32 s5, 0 +s_mov_b32 s6, 0x100 +s_mov_b32 s7, 0x31016fac +v_mov_b32_e32 v8, 0 +buffer_load_dword v8, v8, s[4:7], 0 offen +s_mov_b32 s8, 0x90000 +s_mov_b32 s9, 0 +s_load_dword s10, s[8:9], 0x4 +s_load_dword s11, s[4:5], 0x0 +s_waitcnt vmcnt(0) lgkmcnt(0) +v_mov_b32_e32 v9, 0 +buffer_store_dword v2, v9, s[0:3], 0 offen +buffer_store_dword v3, v9, s[0:3], 0 offen offset:4 +buffer_store_dword v5, v9, s[0:3], 0 offen offset:8 +buffer_store_dword v6, v9, s[0:3], 0 offen offset:12 +buffer_store_dword v7, v9, s[0:3], 0 offen offset:16 +buffer_store_dword v8, v9, s[0:3], 0 offen offset:20 +v_mov_b32_e32 v10, s10 +buffer_store_dword v10, v9, s[0:3], 0 offen offset:24 +v_mov_b32_e32 v11, s11 +buffer_store_dword v11, v9, s[0:3], 0 offen offset:28 +s_endpgm diff --git a/runtime/test/title_memory_map_test.cpp b/runtime/test/title_memory_map_test.cpp index ba5a518a1d..ff226d6481 100644 --- a/runtime/test/title_memory_map_test.cpp +++ b/runtime/test/title_memory_map_test.cpp @@ -7,7 +7,8 @@ // 3. a reader further behind than the journal holds is told so (it then looks at everything); // 4. a change with no range overlaps every reader; // 5. TextureReadability keeps a positive answer, when asked to, until a retry; -// 6. a pass over 20,000 waiting textures probes only those under the one mapped block. +// 6. a pass over 20,000 waiting textures probes only those under the one mapped block; +// 7. between passes, sync_map retries only when a map change overlaps the texture's footprint. #include #include @@ -142,6 +143,48 @@ int main() { check(pass() == 4 && probes == 0, "a pass with no change probes nothing"); } + // 7. Synchronous view checks between passes (sync_map): unrelated map changes cost no probe, an overlapping unmap + // defers without reading, and an overlapping map wakes a waiting texture before the next pass. + { + constexpr std::uintptr_t cpu = kBase + 0x20000000; + constexpr std::uint64_t size = 512 * 1024; + const std::uint64_t pass_generation = map::generation(); + bool mapped = true; + unsigned probes = 0; + leonida::TextureReadability r; + const auto probe = [&] { + ++probes; + return mapped; + }; + check(r.check(0, true, probe, true) && probes == 1 && !r.pending(), + "sync_map: initial probe caches a readable answer"); + for (std::uintptr_t i = 0; i < 32; ++i) + map::changed(cpu + size + i * 0x10000, cpu + size + (i + 1) * 0x10000); + r.sync_map(pass_generation, cpu, size); + check(r.check(0, true, probe, true) && probes == 1, + "sync_map: map changes outside the footprint keep the cached answer"); + r.sync_map(pass_generation, cpu, size); + check(r.check(0, true, probe, true) && probes == 1, + "sync_map: a second check at the same generation does nothing"); + + mapped = false; + map::changed(cpu + 0x10000, cpu + 0x20000); + r.sync_map(pass_generation, cpu, size); + check(!r.check(0, true, probe, true) && r.pending() && probes == 2, + "sync_map: an overlapping unmap between passes reprobes and defers"); + + map::changed(cpu - 0x10000, cpu); + r.sync_map(pass_generation, cpu, size); + check(!r.check(0, true, probe, true) && r.pending() && probes == 2, + "sync_map: an adjacent non-overlapping change leaves a pending texture waiting"); + + mapped = true; + map::changed(cpu, cpu + size); + r.sync_map(pass_generation, cpu, size); + check(r.check(0, true, probe, true) && !r.pending() && probes == 3, + "sync_map: an overlapping map between passes wakes a pending texture at once"); + } + std::printf("%d checks, %d failures\n", g_checks, g_failures); return g_failures ? 1 : 0; } diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h index eb1be0a2c9..8369d594c7 100644 --- a/runtime/test/vk_test_device.h +++ b/runtime/test/vk_test_device.h @@ -123,6 +123,7 @@ class Device { bool occlusion_query_precise = false; // occlusionQueryPrecise enabled bool prepare_on_bind=false; bool cold_graphics_compile = false; + bool heavy_pipeline_cache = false; // LEONIDA_HEAVY_PIPELINE_CACHE_MS set and pipelineCreationCacheControl on bool pipeline_statistics_query = false; // pipelineStatisticsQuery enabled bool request_multi_draw_indirect = false, request_draw_indirect_count = false; bool draw_indirect_count_enabled = false; @@ -412,8 +413,13 @@ class Device { // (zero-based VS ids) is in; harmless before. const char* compile_mode = std::getenv("LEONIDA_PIPELINE_COMPILE"); const bool cache_only = compile_mode && std::strcmp(compile_mode, "cache-only") == 0; - v13_.enable_pipeline_cache_control = cache_only && v13_.core && v13_.pipeline_cache_control; - cold_graphics_compile = v13_.enable_pipeline_cache_control; + // LEONIDA_HEAVY_PIPELINE_CACHE_MS other than 0: the heavy pipeline cache path, as the runtime takes it by default + // (src/heavy_pipeline_cache.h). Tests leave it off unless asked. + const char* heavy_ms = std::getenv("LEONIDA_HEAVY_PIPELINE_CACHE_MS"); + const bool heavy = heavy_ms && *heavy_ms && std::strcmp(heavy_ms, "0") != 0; + v13_.enable_pipeline_cache_control = (cache_only || heavy) && v13_.core && v13_.pipeline_cache_control; + cold_graphics_compile = cache_only && v13_.enable_pipeline_cache_control; + heavy_pipeline_cache = heavy && v13_.enable_pipeline_cache_control; prepare_on_bind = compile_mode && std::strcmp(compile_mode, "on-demand") == 0; VkPhysicalDeviceVulkan11Features enable11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, v13_.enable(conditional_rendering ? &enable_conditional : nullptr)}; diff --git a/runtime/test/xapu_chad_test.cpp b/runtime/test/xapu_chad_test.cpp index dffa74404a..7e667492c7 100644 --- a/runtime/test/xapu_chad_test.cpp +++ b/runtime/test/xapu_chad_test.cpp @@ -1,7 +1,11 @@ -// Checks the registered xapu.dll and chad.dll shims in the call shapes the executable uses (runtime/shims/xapu_chad.cpp): -// the connections succeed, the APU's shared buffer is zeroed and writable at the offsets the title reaches, commands -// are accepted, an open and a close each give one result and nothing else does, XDspActivate hands out zeroed status -// and stream memory, and both disconnect. +// Checks the registered xapu.dll and chad.dll shims (runtime/shims/xapu_queue.cpp and runtime/shims/xapu_chad.cpp) +// in the call shapes the executable uses and against the layouts xapu_queue.cpp documents. +// +// xapu.dll: the connection's limits and its zeroed memory, writable at the offsets the title reaches; one result per +// accepted command, in command order, with its id echoed; the per-stream queue limit; the error codes, returned or in +// the result; a process command's frame count taken from the Opus packet's table-of-contents byte (RFC 6716, section +// 3.1) and clipped, with silence written; and the result event. The packets are hand-made TOC bytes, not audio. +// chad.dll: XDspActivate hands out zeroed status and stream memory, and both disconnect. #include #include @@ -12,10 +16,10 @@ 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 XApuConnectFn = HRESULT(__stdcall*)(const void*, void*, void**); +using XApuDisconnectFn = HRESULT(__stdcall*)(void*, uint32_t); +using XApuEnqueueCommandFn = HRESULT(__stdcall*)(void*, const void*, uint32_t*); +using XApuGetResultCountFn = uint32_t(__stdcall*)(void*, uint32_t*); using XApuDequeueResultFn = HRESULT(__stdcall*)(void*, void*); using XDspConnectFn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t, uint32_t, uint32_t, void**); using XDspActivateFn = HRESULT(__stdcall*)(void*, const void*, void**, void**); @@ -23,6 +27,55 @@ using XDspDeactivateFn = HRESULT(__stdcall*)(void*, uint64_t, uint64_t, uint64_t using XDspDisconnectFn = HRESULT(__stdcall*)(void*); using XDspSubmitCommandFn = HRESULT(__stdcall*)(void*, void*, uint32_t*); +constexpr HRESULT kQueueFull = static_cast(0x8AC81000u); +constexpr HRESULT kNoResult = static_cast(0x8AC81001u); +constexpr HRESULT kInvalidCommand = static_cast(0x8AC81002u); +constexpr HRESULT kInvalidStream = static_cast(0x8AC81003u); +constexpr HRESULT kAlreadyActive = static_cast(0x8AC81005u); +constexpr HRESULT kBadPacket = static_cast(0x8AC81008u); + +#pragma pack(push, 1) +struct ConnectInput { + uint32_t processing, streams, commands_per_stream, memory_bytes, frames_per_output, options; +}; +struct ConnectOutput { + void* memory; + HANDLE result_event; +}; +struct CommandId { + uint32_t kind, stream, sequence, options; + uint64_t context; +}; +struct ActivateCommand { + CommandId id; + uint32_t channels, init_bytes; + const void* init; + float start_pitch; + uint32_t processing_bytes; + void* processing; +}; +struct ProcessCommand { + CommandId id; + float pitch_ramp, target_pitch; + uint32_t first_frame, frame_count, input_bytes; + const uint8_t* input; + uint32_t output_bytes; + uint8_t* output; +}; +struct Result { + CommandId id; + uint32_t state; + uint64_t state_data, usec; + HRESULT error; + uint32_t frames, output_bytes; + uint8_t* output; + float pitch; + uint32_t input_bytes; + const uint8_t* input; +}; +#pragma pack(pop) +static_assert(sizeof(ActivateCommand) == 56 && sizeof(ProcessCommand) == 64 && sizeof(Result) == 0x50, "layouts"); + int g_checks = 0; int g_failures = 0; @@ -39,6 +92,8 @@ T get(const char* dll, const char* name) { return reinterpret_cast(fn); } +CommandId id(uint32_t kind, uint32_t stream, uint32_t options = 0) { return {kind, stream, 7, options, 0x1234}; } + } // namespace int main() { @@ -56,39 +111,165 @@ int main() { check(rt::shims::owns_dll("xapu.dll") && rt::shims::owns_dll("chad.dll"), "the shims own xapu.dll and chad.dll"); if (g_failures) return 1; - // XApuConnect(block24*, out16*, handle*), success read as SUCCEEDED. - uint8_t out24[24]; - uint64_t out16[2] = {}; - std::memset(out24, 0xcc, sizeof out24); + // XApuConnect(const ConnectInput*, ConnectOutput*, handle*): the first argument is read, never written. + ConnectOutput out{}; void* apu = nullptr; - check(SUCCEEDED(connect(out24, out16, &apu)) && apu, "XApuConnect succeeds with a handle"); - check(out24[0] == 0xcc && out24[23] == 0xcc, "XApuConnect leaves the title's 24-byte block alone"); - 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_output = 0x14000 + 127 * 0x1E00 + 0x1E00 - 1; // the end of slot 127's output - check(base[0] == 0 && base[last_output] == 0, "the shared buffer is zeroed"); - base[127 * 0x280] = 1; - base[last_output] = 1; - check(base[127 * 0x280] == 1 && base[last_output] == 1, "the shared buffer is writable at slot 127"); - } - check(connect(out24, out16, nullptr) == E_INVALIDARG, "XApuConnect without a handle pointer fails"); + ConnectInput bad{1, 0, 2, 0x10000, 0, 0}; + check(connect(&bad, &out, &apu) == E_INVALIDARG, "zero streams is E_INVALIDARG"); + bad = {1, 501, 2, 0x10000, 0, 0}; + check(connect(&bad, &out, &apu) == E_INVALIDARG, "more than 500 streams is E_INVALIDARG"); + bad = {1, 4, 17, 0x10000, 0, 0}; + check(connect(&bad, &out, &apu) == E_INVALIDARG, "more than 16 commands per stream is E_INVALIDARG"); + bad = {1, 4, 2, 0, 0, 0}; + check(connect(&bad, &out, &apu) == E_INVALIDARG, "no memory is E_INVALIDARG"); + bad = {1, 4, 2, 0x10000, 256, 0}; + check(connect(&bad, &out, &apu) == E_INVALIDARG, "frames per output for decoding is E_INVALIDARG"); + bad = {2, 4, 2, 0x10000, 0, 0}; + check(connect(&bad, &out, &apu) == static_cast(rt::shims::kENotImpl), + "a processing kind other than Opus decoding is E_NOTIMPL"); + check(apu == nullptr, "a failed XApuConnect hands out no handle"); + + // The memory the title addresses: input at base + slot * 0x280, output at base + 0x14000 + slot * 0x1E00. + constexpr uint32_t kMemory = 0x14000 + 128 * 0x1E00; + const ConnectInput in{1, 128, 2, kMemory, 0, 8}; + const ConnectInput in_copy = in; + check(SUCCEEDED(connect(&in, &out, &apu)) && apu, "XApuConnect for Opus decoding, 128 streams, 2 commands each"); + check(std::memcmp(&in, &in_copy, sizeof in) == 0, "XApuConnect leaves its input alone"); + check(out.memory != nullptr && out.result_event != nullptr, "it hands out memory and a result event"); + if (!apu || !out.memory) return 1; + auto* base = static_cast(out.memory); + const size_t last_output = 0x14000 + 127 * 0x1E00 + 0x1E00 - 1; // the end of slot 127's output + check(base[0] == 0 && base[last_output] == 0, "the memory is zeroed"); + base[127 * 0x280] = 1; + base[last_output] = 1; + check(base[127 * 0x280] == 1 && base[last_output] == 1, "the memory is writable at slot 127"); + base[127 * 0x280] = 0; + base[last_output] = 0; + + Result r{}; + check(dequeue(apu, &r) == kNoResult, "XApuDequeueResult with nothing queued is 0x8AC81001"); + uint32_t dequeued = 99; + check(count(apu, &dequeued) == 0 && dequeued == 0, "XApuGetResultCount: nothing ready, none dequeued"); - // Command types 1, 2 and 3 as the title builds them; the third argument is 0 at every site. - for (uint32_t type = 1; type <= 3; ++type) { - uint32_t command[16] = {type, 5}; - check(enqueue(apu, command, 0) == S_OK, "XApuEnqueueCommand accepts a command"); + // Activate stream 3 (stereo) and process one packet; the title's sites pass a null third argument. + const ActivateCommand activate{id(1, 3), 2, 0, nullptr, 1.0f, 0, nullptr}; + check(enqueue(apu, &activate, nullptr) == S_OK, "activate stream 3 with a null count pointer"); + check(WaitForSingleObject(out.result_event, 0) == WAIT_TIMEOUT, "a command not asking for it leaves the event"); + uint8_t* const packet = base + 3 * 0x280; + uint8_t* const pcm = base + 0x14000 + 3 * 0x1E00; + packet[0] = (31 << 3) | 0; // one 20 ms CELT frame (config 31, code 0): 960 frames per channel + std::memset(pcm, 0x55, 0x1E00 + 16); // the slot and the start of the next, to see nothing past it is written + ProcessCommand process{id(3, 3, 1), 0.0f, 1.0f, 0, 960, 40, packet, 960 * 8, pcm}; + uint32_t total = 0; + check(enqueue(apu, &process, &total) == S_OK && total == 2, "process on stream 3; two commands accepted"); + check(WaitForSingleObject(out.result_event, 0) == WAIT_OBJECT_0, "a command asking for it signals the event"); + check(WaitForSingleObject(out.result_event, 0) == WAIT_TIMEOUT, "the event resets itself"); + check(enqueue(apu, &process, &total) == kQueueFull && total == 2, + "a third command on a stream of two is 0x8AC81000 and not counted"); + check(count(apu, nullptr) == 2, "two results ready, with a null dequeued pointer"); + + check(dequeue(apu, &r) == S_OK && r.id.kind == 1 && r.id.stream == 3 && r.id.sequence == 7 && + r.id.context == 0x1234 && r.error == S_OK && r.pitch == 1.0f, + "results come in command order: the activate first, its id echoed"); + check(dequeue(apu, &r) == S_OK && r.id.kind == 3 && r.error == S_OK, "the process result follows"); + uint32_t dword34 = 0; + std::memcpy(&dword34, reinterpret_cast(&r) + 0x34, 4); + check(r.frames == 960 && dword34 == 960 * 8 && r.output == pcm && r.input == packet && r.input_bytes == 40, + "960 stereo float frames, the byte count at +0x34, the buffers echoed"); + bool silent = true; + for (int i = 0; i < 960 * 8; ++i) silent = silent && pcm[i] == 0; + check(silent && pcm[960 * 8] == 0x55, "the output range is silence, and nothing past it is written"); + check(count(apu, &dequeued) == 0 && dequeued == 2, "nothing ready, two dequeued"); + + // The TOC byte's frame size and count (RFC 6716, section 3.1), one stereo packet each. + struct Toc { + uint8_t toc, count; + uint32_t frames; + const char* what; + } const tocs[] = { + {(0 << 3) | 0, 0, 480, "SILK 10 ms, code 0: 480 frames"}, + {(3 << 3) | 1, 0, 5760, "SILK 60 ms, code 1 (two frames): 5760 frames"}, + {(13 << 3) | 2, 0, 1920, "hybrid 20 ms, code 2 (two frames): 1920 frames"}, + {(16 << 3) | 3, 5, 600, "CELT 2.5 ms, code 3 with five frames: 600 frames"}, + }; + for (const Toc& t : tocs) { + packet[0] = t.toc; + packet[1] = t.count; + process = {id(3, 3), 0.0f, 1.0f, 0, 6000, 40, packet, 0x1E00 * 4, pcm}; + r = {}; + check(enqueue(apu, &process, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == S_OK && + r.frames == (t.frames < 0x1E00 * 4 / 8 ? t.frames : 0x1E00 * 4 / 8), + t.what); } - check(count(apu, 0) == 2, "the open and the close each queued a result, the type 3 command none"); - for (uint32_t type = 1; type <= 2; ++type) { - uint32_t queued[0x50 / 4] = {}; - check(dequeue(apu, queued) == S_OK && queued[0] == type && queued[1] == 5 && queued[2] == 0 && queued[13] == 0, - "XApuDequeueResult returns the type and slot and leaves the rest zeroed"); + + // first_frame and frame_count clip like a decode: three 20 ms frames (code 3, count 3) = 2880, from frame 2000. + packet[0] = (31 << 3) | 3; + packet[1] = 3; + process = {id(3, 3), 0.0f, 1.0f, 2000, 4000, 40, packet, 0x1E00, pcm}; + enqueue(apu, &process, nullptr); + dequeue(apu, &r); + check(r.error == S_OK && r.frames == 880 && r.output_bytes == 880 * 8, "frames from first_frame to the packet's end"); + process.frame_count = 300; + enqueue(apu, &process, nullptr); + dequeue(apu, &r); + check(r.frames == 300, "no more than frame_count"); + process.frame_count = 4000; + process.output_bytes = 100 * 8 + 7; + enqueue(apu, &process, nullptr); + dequeue(apu, &r); + check(r.frames == 100 && r.output_bytes == 800, "and no more than the output holds"); + + // Errors carried in the result: the command is accepted and its result says what went wrong. + packet[1] = 7; // seven 20 ms frames: 140 ms, longer than an Opus packet may be + enqueue(apu, &process, nullptr); + dequeue(apu, &r); + check(r.error == kBadPacket && r.frames == 0, "an impossible packet: 0x8AC81008 in the result"); + packet[0] = (31 << 3) | 3; + packet[1] = 0; + enqueue(apu, &process, nullptr); + dequeue(apu, &r); + check(r.error == kBadPacket, "a code 3 packet of zero frames: 0x8AC81008"); + ProcessCommand empty = process; + empty.input_bytes = 0; + check(enqueue(apu, &empty, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == E_INVALIDARG, + "an empty input: E_INVALIDARG in the result"); + empty = process; + empty.output = nullptr; + check(enqueue(apu, &empty, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == E_INVALIDARG, + "a null output: E_INVALIDARG in the result"); + ProcessCommand stray = process; + stray.id.stream = 4; + check(enqueue(apu, &stray, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == kInvalidStream, + "a process on a stream never activated: 0x8AC81003 in the result"); + check(enqueue(apu, &activate, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == kAlreadyActive, + "activating an active stream: 0x8AC81005 in the result"); + ActivateCommand surround = activate; + surround.id.stream = 5; + surround.channels = 6; + check(enqueue(apu, &surround, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == E_INVALIDARG, + "six channels: E_INVALIDARG in the result"); + + // Errors returned at once, with no result. + stray.id.stream = 128; + check(enqueue(apu, &stray, nullptr) == kInvalidStream, "a stream past the connection's is 0x8AC81003"); + const CommandId unknown = id(9, 3); + check(enqueue(apu, &unknown, nullptr) == kInvalidCommand, "an unknown kind is 0x8AC81002"); + check(count(apu, nullptr) == 0, "neither left a result"); + + // Notify and reset give a result; deactivate gives one and closes the stream. + for (uint32_t kind : {4u, 5u, 2u}) { + const CommandId command = id(kind, 3); + check(enqueue(apu, &command, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.id.kind == kind && + r.id.stream == 3 && r.error == S_OK, + "notify, reset and deactivate each give a result of their kind for their stream"); } - check(count(apu, 0) == 0, "XApuGetResultCount is 0 again"); - uint8_t result[0x50] = {}; - check(FAILED(dequeue(apu, result)), "XApuDequeueResult on the empty queue fails"); - check(disconnect(apu) == S_OK, "XApuDisconnect succeeds"); + process.id.stream = 3; + enqueue(apu, &process, nullptr); + dequeue(apu, &r); + check(r.error == kInvalidStream, "after deactivate the stream takes no process command"); + check(enqueue(apu, &activate, &total) == S_OK && dequeue(apu, &r) == S_OK && r.error == S_OK, + "and it can be activated again"); + check(disconnect(apu, 0x20) == S_OK, "XApuDisconnect(handle, 0x20)"); // XDspConnectWithMaximumStreamLimit(buffer, u32, u32, 0x80, 1, handle*), success read as a return of 0. alignas(64) static uint8_t dsp_buffer[4096]; @@ -99,10 +280,10 @@ int main() { void* stream = nullptr; check(dsp_activate(dsp, description, reinterpret_cast(&status), &stream) == 0, "XDspActivate returns 0"); check(status && stream && static_cast(status) != stream, "XDspActivate writes both outputs"); - uint32_t id = 0; - check(dsp_submit(stream, dsp_buffer, &id) == 0, "XDspSubmitCommand returns 0"); + uint32_t dsp_id = 0; + check(dsp_submit(stream, dsp_buffer, &dsp_id) == 0, "XDspSubmitCommand returns 0"); // What the title's wait reads: no error at +0xc and the submitted id at +4. - check(status && status[3] == 0 && status[1] == id, "the status block reports the submitted command as done"); + check(status && status[3] == 0 && status[1] == dsp_id, "the status block reports the submitted command as done"); check(dsp_deactivate(dsp, 0, 0, 0) == 0, "XDspDeactivate returns 0"); check(dsp_disconnect(dsp) == 0, "XDspDisconnect returns 0"); diff --git a/runtime/test/xapu_opus_test.cpp b/runtime/test/xapu_opus_test.cpp new file mode 100644 index 0000000000..30eb33cfee --- /dev/null +++ b/runtime/test/xapu_opus_test.cpp @@ -0,0 +1,193 @@ +// Checks the decoded path of the registered xapu.dll shim (runtime/shims/xapu_queue.cpp) with +// runtime/opus_decoder built: the title's ConnectInput, activate/process/deactivate, one result per +// command in order, the 0x50-byte result layout, and a generated 440 Hz stereo packet decoded to +// 960 frames of f32 PCM, then clipped by first_frame / frame_count / output_bytes. The packet is +// encoded here; no game data. +#include + +#include +#include +#include +#include +#include + +#include "leonida_opus_decoder.h" +#include "shims.h" + +namespace { + +using XApuConnectFn = HRESULT(__stdcall*)(const void*, void*, void**); +using XApuDisconnectFn = HRESULT(__stdcall*)(void*, uint32_t); +using XApuEnqueueCommandFn = HRESULT(__stdcall*)(void*, const void*, uint32_t*); +using XApuGetResultCountFn = uint32_t(__stdcall*)(void*, uint32_t*); +using XApuDequeueResultFn = HRESULT(__stdcall*)(void*, void*); + +constexpr HRESULT kQueueFull = static_cast(0x8AC81000u); +constexpr HRESULT kInvalidStream = static_cast(0x8AC81003u); + +#pragma pack(push, 1) +struct ConnectInput { + uint32_t processing, streams, commands_per_stream, memory_bytes, frames_per_output, options; +}; +struct ConnectOutput { + void* memory; + HANDLE result_event; +}; +struct CommandId { + uint32_t kind, stream, sequence, options; + uint64_t context; +}; +struct ActivateCommand { + CommandId id; + uint32_t channels, init_bytes; + const void* init; + float start_pitch; + uint32_t processing_bytes; + void* processing; +}; +struct ProcessCommand { + CommandId id; + float pitch_ramp, target_pitch; + uint32_t first_frame, frame_count, input_bytes; + const uint8_t* input; + uint32_t output_bytes; + uint8_t* output; +}; +struct Result { + CommandId id; + uint32_t state; + uint64_t state_data, usec; + HRESULT error; + uint32_t frames, output_bytes; + uint8_t* output; + float pitch; + uint32_t input_bytes; + const uint8_t* input; +}; +#pragma pack(pop) +static_assert(sizeof(ActivateCommand) == 56 && sizeof(ProcessCommand) == 64 && sizeof(Result) == 0x50, "layouts"); + +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 +T get(const char* dll, const char* name) { + void* fn = rt::shims::find(dll, name); + check(fn != nullptr, name); + return reinterpret_cast(fn); +} + +CommandId id(uint32_t kind, uint32_t stream, uint32_t options = 0) { return {kind, stream, 7, options, 0x1234}; } + +} // namespace + +int main() { + std::printf("xapu_opus_test: decoded xapu.dll path\n"); + const auto connect = get("xapu.dll", "XApuConnect"); + const auto disconnect = get("xapu.dll", "XApuDisconnect"); + const auto enqueue = get("xapu.dll", "XApuEnqueueCommand"); + const auto count = get("xapu.dll", "XApuGetResultCount"); + const auto dequeue = get("xapu.dll", "XApuDequeueResult"); + if (g_failures) return 1; + + constexpr uint32_t kMemory = 0x14000 + 128 * 0x1E00; + const ConnectInput in{1, 128, 2, kMemory, 0, 0}; + const ConnectInput in_copy = in; + ConnectOutput out{}; + void* apu = nullptr; + check(SUCCEEDED(connect(&in, &out, &apu)) && apu, "XApuConnect for Opus decoding"); + check(std::memcmp(&in, &in_copy, sizeof in) == 0, "XApuConnect leaves its input alone"); + auto* base = static_cast(out.memory); + if (!apu || !base) return 1; + check(base[0] == 0 && base[kMemory - 1] == 0, "the shared memory is zeroed"); + + const ActivateCommand activate{id(1, 3), 2, 0, nullptr, 1.0f, 0, nullptr}; + check(enqueue(apu, &activate, nullptr) == S_OK, "activate stream 3 (stereo)"); + + std::vector tone(960 * 2); + for (uint32_t i = 0; i < 960; ++i) { + const float sample = static_cast(std::sin(double(i) * 440.0 * 6.283185307179586 / 48000.0)) * 0.5f; + tone[2 * i] = sample; + tone[2 * i + 1] = sample; + } + uint8_t encoded[1500]; + size_t encoded_len = 0; + check(leonida_opus_encode_test(tone.data(), 960, 2, encoded, sizeof encoded, &encoded_len) == LEONIDA_OPUS_OK && + encoded_len > 0, + "a synthetic 20 ms stereo Opus packet encodes"); + std::memcpy(base, encoded, encoded_len); + auto* const pcm = base + 0x14000 + 3 * 0x1E00; + std::memset(pcm, 0x55, 0x1E00 + 64); + ProcessCommand process{id(3, 3, 1), 0.0f, 1.0f, 0, 960, static_cast(encoded_len), base, 0x1E00, pcm}; + uint32_t total = 0; + check(enqueue(apu, &process, &total) == S_OK && total == 2, "process on stream 3; two commands accepted"); + check(enqueue(apu, &process, &total) == kQueueFull && total == 2, + "a third command on a stream of two is 0x8AC81000"); + check(count(apu, nullptr) == 2, "two results ready"); + + Result r{}; + check(dequeue(apu, &r) == S_OK && r.id.kind == 1 && r.id.stream == 3 && r.error == S_OK, + "results come in command order: the activate first"); + check(dequeue(apu, &r) == S_OK && r.id.kind == 3 && r.error == S_OK, "the process result follows"); + uint32_t dword34 = 0; + std::memcpy(&dword34, reinterpret_cast(&r) + 0x34, 4); + check(r.frames == 960 && dword34 == 960 * 8 && r.output == pcm && r.input == base && + r.input_bytes == static_cast(encoded_len), + "960 stereo float frames, the byte count at +0x34, the buffers echoed"); + float energy = 0.0f; + const auto* floats = reinterpret_cast(pcm); + for (uint32_t i = 0; i < 960 * 2; ++i) energy += floats[i] * floats[i]; + energy /= 960 * 2; + check(energy > 0.01f, "the decoded tone has energy"); + check(pcm[960 * 8] == 0x55, "nothing past the decoded range is written"); + check(count(apu, nullptr) == 0, "the queue is empty after both results"); + + // first_frame, frame_count and what output_bytes holds each clip the decoded frames. + process.first_frame = 500; + process.frame_count = 4000; + enqueue(apu, &process, nullptr); + dequeue(apu, &r); + check(r.error == S_OK && r.frames == 460 && r.output_bytes == 460 * 8, "frames from first_frame to the packet's end"); + process.frame_count = 300; + enqueue(apu, &process, nullptr); + dequeue(apu, &r); + check(r.frames == 300 && r.output_bytes == 300 * 8, "no more than frame_count"); + process.frame_count = 4000; + process.output_bytes = 100 * 8 + 7; + enqueue(apu, &process, nullptr); + dequeue(apu, &r); + check(r.frames == 100 && r.output_bytes == 800, "and no more than the output holds"); + + // Errors carried in the result. + ProcessCommand empty = process; + empty.input_bytes = 0; + check(enqueue(apu, &empty, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == E_INVALIDARG, + "an empty input: E_INVALIDARG in the result"); + empty = process; + empty.output = nullptr; + check(enqueue(apu, &empty, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == E_INVALIDARG, + "a null output: E_INVALIDARG in the result"); + ProcessCommand stray = process; + stray.id.stream = 4; + check(enqueue(apu, &stray, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == kInvalidStream, + "a process on a stream never activated: 0x8AC81003 in the result"); + + // Deactivate closes the stream; activating again creates a fresh decoder. + const CommandId deactivate = id(2, 3); + check(enqueue(apu, &deactivate, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == S_OK, + "deactivate gives a result and closes the stream"); + check(enqueue(apu, &process, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == kInvalidStream, + "after deactivate the stream takes no process command"); + check(enqueue(apu, &activate, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == S_OK, + "the stream can be activated again"); + check(disconnect(apu, 0x20) == S_OK, "XApuDisconnect(handle, 0x20)"); + + std::printf("%d checks, %d failures\n", g_checks, g_failures); + return g_failures ? 1 : 0; +} diff --git a/runtime/test/xmem_test.cpp b/runtime/test/xmem_test.cpp index 991388c7f5..adc24cca3e 100644 --- a/runtime/test/xmem_test.cpp +++ b/runtime/test/xmem_test.cpp @@ -31,6 +31,7 @@ #include "startup_trace.h" #include "xmem.h" #include "../src/title_page_watch.h" +#include "../src/title_geometry_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 @@ -429,6 +430,78 @@ struct PhysicalApi { XMemMapPhysicalPagesScatterFn scatter; }; +// A remap that gives watched pages another frame reports them released (geometry_writes::note_released), so the +// geometry copies of what they held are retired; a page mapped again to the frame it had is no change. Through +// XMemMapPhysicalPages, the scatter call and CopyPageMappingsBatchX. +void test_remap_releases(const PhysicalApi& api) { + namespace watch = leonida::geometry_writes; + constexpr uint64_t kPages = 3; + auto* const window = static_cast(api.virtual_alloc( + nullptr, kPages * kPage64k, MEM_RESERVE | kXmem64kPages, 0x23, PAGE_READWRITE | PAGE_GRAPHICS_READWRITE)); + uint64_t pages[4]{}; + uint64_t count = 4; + if (!window || api.allocate(0x280, &count, pages) != TRUE || count != 4) { + check(false, "remap releases: a window and four physical pages"); + return; + } + const auto base = reinterpret_cast(window); + watch::ReleaseQueue queue; + watch::subscribe(queue); + for (uint64_t i = 0; i < kPages; ++i) watch::acquire(base + i * kPage64k); // as a geometry copy over the pages + std::vector> released; + const auto take = [&] { + watch::take_released(queue, released); + return released; + }; + const auto covers = [&](uintptr_t from, uintptr_t to) { + for (const auto& [lo, hi] : released) + if (lo <= from && hi >= to) return true; + return false; + }; + const auto any_overlap = [&](uintptr_t from, uintptr_t to) { + for (const auto& [lo, hi] : released) + if (lo < to && hi > from) return true; + return false; + }; + + const uint64_t first[kPages] = {pages[0], pages[1], pages[2]}; + check(api.map(window, kPages, first) == window && take().empty(), + "remap releases: a first mapping of unmapped pages releases nothing"); + check(api.map(window + kPage64k, 1, &pages[1]) == window + kPage64k && take().empty(), + "remap releases: a page mapped again to the frame it has is no change"); + check(api.map(window + kPage64k, 1, &pages[3]) == window + kPage64k && !take().empty() && + covers(base + kPage64k, base + 2 * kPage64k) && !any_overlap(base, base + kPage64k) && + !any_overlap(base + 2 * kPage64k, base + 3 * kPage64k), + "remap releases: a page given another frame is released, its neighbours are not"); + const uint64_t rotated[kPages] = {pages[2], pages[0], pages[1]}; + check(api.map(window, kPages, rotated) == window && !take().empty() && covers(base, base + 3 * kPage64k), + "remap releases: a run given other frames is released whole"); + const uint64_t partly[kPages] = {pages[2], pages[3], pages[1]}; + check(api.map(window, kPages, partly) == window && !take().empty() && + covers(base + kPage64k, base + 2 * kPage64k) && !any_overlap(base, base + kPage64k) && + !any_overlap(base + 2 * kPage64k, base + 3 * kPage64k), + "remap releases: of a remapped run, only the page whose frame changed is released"); + void* const last = window + 2 * kPage64k; + check(api.scatter(&last, 1, &pages[0]) == TRUE && !take().empty() && + covers(base + 2 * kPage64k, base + 3 * kPage64k) && !any_overlap(base, base + 2 * kPage64k), + "remap releases: the scatter call releases the page it gives another frame"); + check(api.scatter(&last, 1, &pages[0]) == TRUE && take().empty(), + "remap releases: the scatter call with the frame the page has releases nothing"); + // CopyPageMappingsBatchX: page 0 gets the frame at page 1 (kind 0 from a pool at the window itself). + const rt::xmem::PageRange range{0, 1, 1}; + const rt::xmem::PageBatch batch{base, 1, &range}; + check(rt::xmem::copy_page_mappings(1, &batch, base, kPages, 0) && !take().empty() && + covers(base, base + kPage64k) && !any_overlap(base + kPage64k, base + 3 * kPage64k), + "remap releases: CopyPageMappingsBatchX releases the page it gives another frame"); + + check(api.map(window, kPages, nullptr) == window && !take().empty() && covers(base, base + 3 * kPage64k), + "remap releases: unmapping releases the range"); + for (uint64_t i = 0; i < kPages; ++i) watch::release(base + i * kPage64k); + watch::unsubscribe(queue); + api.free_pages(4, pages); + VirtualFree(window, 0, MEM_RELEASE); +} + // Physical pages in a 64 KiB-page window, as the measured callers use them: reserve a window, allocate pages, map them, // remap them elsewhere and in another order, unmap, free. void test_physical_pages(const PhysicalApi& api) { @@ -741,7 +814,19 @@ void test_copy_page_mappings_cpu_view(const PhysicalApi& api) { check(readable(other) && page_holds(other, 0x7300u), "a GPU-only source page unmapped there is looked up at its CPU range"); - // A null source unmaps both ranges. + // A CPU page the title mapped itself is the title's: a copy onto its GPU-only page, or an unmap of it, changes the + // GPU-only page alone (the console's CopyPageMappingsBatchX edits only that range's page table). + check(copy(gpu + 2 * kPage64k, pool + kPage64k, 1, false), "a copy onto a GPU-only page whose CPU page is the title's"); + check(readable(gpu + 2 * kPage64k) && page_holds(gpu + 2 * kPage64k, 0x7301u), + "the GPU-only page shows the copied pool page"); + check(readable(cpu + 2 * kPage64k) && page_holds(cpu + 2 * kPage64k, 0x7300u), + "the title's own mapping at the paired CPU page is kept, not replaced by the copy"); + check(copy(gpu + 2 * kPage64k, nullptr, 1, false), "a null source unmaps a GPU-only page whose CPU page is the title's"); + check(!readable(gpu + 2 * kPage64k), "the GPU-only page is unmapped"); + check(readable(cpu + 2 * kPage64k) && page_holds(cpu + 2 * kPage64k, 0x7300u), + "the title's own mapping at the paired CPU page survives the unmap"); + + // A null source unmaps both ranges where the CPU pages are the copy's own. check(copy(gpu, nullptr, kPool, false), "a null source unmaps the GPU-only range"); check(!readable(gpu) && !readable(cpu) && !readable(cpu + kPage64k), "the paired CPU range is unmapped with it"); @@ -1544,6 +1629,38 @@ void test_physical_pages_commit_on_touch(const PhysicalApi& api) { check(read_ok, "ReadFile fills a page that commit_physical_range committed"); check(api.map(second, 2, nullptr) == second && api.map(window, kMapped, nullptr) == window, "they unmap"); + { + // A host guarded read (outside the title image at 0x140000000) of an unmapped window page exits as + // passed_guarded without counting as left_to_title; a title read still counts as left_to_title. + void* const stub_page = VirtualAlloc(nullptr, 4096, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + const uint8_t mov_eax_rcx_ret[] = {0x8b, 0x01, 0xc3}; + DWORD stub_old = 0; + bool stub_ready = false; + if (stub_page) { + std::memcpy(stub_page, mov_eax_rcx_ret, sizeof(mov_eax_rcx_ret)); + stub_ready = VirtualProtect(stub_page, 4096, PAGE_EXECUTE_READ, &stub_old) != FALSE; + FlushInstructionCache(GetCurrentProcess(), stub_page, sizeof(mov_eax_rcx_ret)); + } + const auto host_read_faults = [&](const void* p) { + __try { + reinterpret_cast(stub_page)(p); + return false; + } __except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER + : EXCEPTION_CONTINUE_SEARCH) { + return true; + } + }; + const uint64_t guarded_before = rt::xmem::fault_exits(rt::xmem::FaultExit::passed_guarded); + const uint64_t left_before = rt::xmem::fault_exits(rt::xmem::FaultExit::left_to_title); + check(stub_ready && host_read_faults(second) && + rt::xmem::fault_exits(rt::xmem::FaultExit::passed_guarded) == guarded_before + 1 && + rt::xmem::fault_exits(rt::xmem::FaultExit::left_to_title) == left_before, + "a host guarded read of an unmapped window page exits as passed_guarded"); + check(access_faults(reinterpret_cast(second), false) && + rt::xmem::fault_exits(rt::xmem::FaultExit::left_to_title) == left_before + 1, + "a title read of an unmapped window page still exits as left_to_title"); + if (stub_page) VirtualFree(stub_page, 0, MEM_RELEASE); + } check(api.free_pages(count, pages.data()) == TRUE, "XMemFreePhysicalPages frees them"); } @@ -2655,6 +2772,7 @@ int main(int argc, char** argv) { // Keep the direct SEC_RESERVE control ahead of the first physical allocation, which installs xmem's VEH. g_section_write_control = measure_section_write_control(); test_physical_pages(physical); + test_remap_releases(physical); if (argc == 2 && std::strcmp(argv[1], "--file-pools") == 0) { test_placeholders(physical); print_result(); diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index cb350820e9..e808256231 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -4644,6 +4644,85 @@ int check_list_values_more() { WaitForSingleObject(job, INFINITE); CloseHandle(job); + // 11. Work-aware timeout in Pump (src/list_value_wait_budget.h): + // a) a matching in-flight producer pauses a held memory gate past the idle timeout until the producer lands; + // b) a busy releaser executing an action gate pauses a concurrent memory gate past the idle timeout; + // c) a demoted gate (4 ms budget) scales its pause caps with its short budget so unrelated active work does not + // hold it for the full timeout's cap; + // d) a matching producer stuck behind an unsignalled fence still hits a finite pause cap instead of hanging. + const auto write_on_a = [&](int index, std::uint64_t value, std::uint64_t& signal_value) -> bool { + if (FAILED(hr_of(raw(direct, 139, word(allocator), 0)))) return false; + raw(direct, 14, 1, 1, 1); // Dispatch + raw(direct, 72, word(&g_cells2[index]), value, 0, 0); // write64 + if (FAILED(hr_of(raw(direct, 9)))) return false; + g_queue_call_count = 0; + if (submit(qa, direct) != 0) return false; + signal_value = logged_signal(qa_mock, a_written); + return signal_value != 0; + }; + xs::set_list_value_wait_timeout_ms(40); + xs::reset_list_value_stats(); + // 11a. Wait on qb before qa submits its matching write (so relay() misses it and Pump holds a gate). + EXPECT(hold_on(qb, 27, 1)); + std::uint64_t producer_sig = 0; + EXPECT(write_on_a(27, 1, producer_sig)); + EXPECT(!xs::list_values_idle(150)); // >3x the 40 ms idle timeout: pauses while producer is in flight + stats = xs::list_value_stats(); + EXPECT(stats.gates_timed_out == 0 && stats.gates_met == 0 && cell2(27) == 0); + fence_signal(a_written, producer_sig); + EXPECT(xs::list_values_idle(3000) && cell2(27) == 1); + stats = xs::list_value_stats(); + EXPECT(stats.gates_met == 1 && stats.gates_timed_out == 0); + + // 11b. Releaser inside a 150 ms action gate pauses a concurrent memory gate past the 40 ms idle timeout. + xs::set_copy_page_mappings_hook([](std::uint32_t, const rt::xmem::PageBatch*, std::uintptr_t, std::uint32_t, + std::uint32_t) -> bool { + Sleep(150); + InterlockedExchange64(reinterpret_cast(&g_cells2[28]), 1); + return true; + }); + g_queue_call_count = 0; + EXPECT(hr_of(raw(qc, 31, 1, word(remap), 0x7000000000, 16, 0)) == S_OK); + const std::uint64_t action_sig = logged_signal(qc_mock, c_written); + EXPECT(action_sig != 0); + const std::uint64_t met_before_rel = xs::list_value_stats().gates_met; + const std::uint64_t to_before_rel = xs::list_value_stats().gates_timed_out; + EXPECT(hold_on(qb, 28, 1)); + fence_signal(c_written, action_sig); + EXPECT(xs::list_values_idle(3000) && cell2(28) == 1); + xs::set_copy_page_mappings_hook(nullptr); + stats = xs::list_value_stats(); + EXPECT(stats.gates_met == met_before_rel + 1 && stats.gates_timed_out == to_before_rel); + + // 11c. Demoted gate (3 timeouts -> 4 ms budget) with unrelated in-flight work on qa times out in a few ms, not + // the 12 s active-work cap of the 40 ms full timeout. + for (int i = 0; i < 3; ++i) EXPECT(hold_on(qb, 29, 1) && xs::list_values_idle(3000)); + std::uint64_t unrelated_sig = 0; + EXPECT(write_on_a(30, 1, unrelated_sig)); + const std::uint64_t short_before_dem = xs::list_value_stats().gates_short; + const std::uint64_t to_before_dem = xs::list_value_stats().gates_timed_out; + started = Clock::now(); + EXPECT(hold_on(qb, 29, 1)); + for (int i = 0; i < 1000 && xs::list_value_stats().gates_timed_out == to_before_dem; ++i) Sleep(1); + const auto demoted_active_ms = ms_since(started); + EXPECT(xs::list_value_stats().gates_timed_out == to_before_dem + 1 && + xs::list_value_stats().gates_short == short_before_dem + 1 && demoted_active_ms < 500); + fence_signal(a_written, unrelated_sig); + EXPECT(xs::list_values_idle(3000)); + + // 11d. Stuck matching producer (fence never signals) still hits the finite max pause cap instead of hanging. + const std::uint64_t to_before_stuck = xs::list_value_stats().gates_timed_out; + started = Clock::now(); + EXPECT(hold_on(qb, 29, 1)); + std::uint64_t stuck_sig = 0; + EXPECT(write_on_a(29, 1, stuck_sig)); + for (int i = 0; i < 1000 && xs::list_value_stats().gates_timed_out == to_before_stuck; ++i) Sleep(1); + const auto stuck_producer_ms = ms_since(started); + EXPECT(xs::list_value_stats().gates_timed_out == to_before_stuck + 1 && stuck_producer_ms < 500); + fence_signal(a_written, stuck_sig); + EXPECT(xs::list_values_idle(3000)); + xs::set_list_value_wait_timeout_ms(5000); + // 8. stop() ends both threads. Afterwards nothing new is landed or opened (the process is ending: a gate // signalled from another thread could open one whose remap was skipped, or go below one still to come), and // CopyPageMappingsBatchX remaps at the call rather than wait for a queue whose gates stay shut. diff --git a/scripts/build_runtime.ps1 b/scripts/build_runtime.ps1 index 5dd8bd3894..bb25cccd7e 100644 --- a/scripts/build_runtime.ps1 +++ b/scripts/build_runtime.ps1 @@ -86,7 +86,7 @@ $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\thread_stacks.cpp", "src\bcpack.cpp", "src\host_cpu.cpp", "src\pe_loader.cpp", "shims\registry.cpp", "shims\console_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\lifecycle.cpp", "shims\xbox_bvh_builder.cpp", "shims\com_shim.cpp", "shims\silent_audio.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\console_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\lifecycle.cpp", "shims\xbox_bvh_builder.cpp", "shims\com_shim.cpp", "shims\silent_audio.cpp", "shims\bcrypt_rng.cpp", "shims\xapu_queue.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 = @" diff --git a/scripts/run_address_guard_gpu_test.py b/scripts/run_address_guard_gpu_test.py new file mode 100644 index 0000000000..f7aa533664 --- /dev/null +++ b/scripts/run_address_guard_gpu_test.py @@ -0,0 +1,133 @@ +"""GPU test of the address guard (rdna2spirv.py --address-guard; docs/d3d12_vulkan.md, "Address guard"). + +Assembles runtime/test/shaders/cs_address_guard.asm, translates it with --address-guard and runs it with +vk_compute_test twice on a 2 MiB heap: once with the guard's header (the page table backs the arena and the page at +0x90000), once without its magic (the guard off). Every address the program uses is inside the heap's buffer, so +neither run can fault, whatever the guard does: the guard-on run shows that the refused accesses read 0 and left +memory alone although memory was there, and the guard-off run that the same module then reads it. + + python -I scripts/run_address_guard_gpu_test.py --build runtime/build [--llvm-mc CMD] [--work DIR] + +Pin the GPU (MESA_VK_DEVICE_SELECT, VK_DRIVER_FILES) as for scripts/run_gpu_tests.py. Exit 0 when both runs give +the expected words, 1 otherwise, 77 when vk_compute_test or llvm-mc is missing. +""" +import argparse +import os +import shutil +import struct +import subprocess +import sys +import tempfile + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(ROOT, "tools")) +import address_guard as ag # noqa: E402 + +NAME = "cs_address_guard" +HEAP_BYTES = 2 << 20 +LIMIT = ag.RESERVED_END # the "arena": offsets below it pass without a lookup +TABLE = 0x100000 # the page table, inside the buffer but past the arena +BACKED = [(0x90000, 0x91000)] # the one page outside the arena the table backs +SEEDS = {0x90000: 0xA11CE000, 0x90004: 0xA11CE004, 0x90FFC: 0xF00DF00D, 0x91000: 0xF00DF00E, + 0xA0000: 0xBADBAD00, 0xA0004: 0xBADBAD04, 0xA0008: 0xBADBAD08} +# out[0..7] (cs_address_guard.asm's header) and other words after the run. +EXPECTED_ON = [0xA11CE000, 0, 0, 0, 0, 0, 0xA11CE004, 0] +EXPECTED_OFF = [0xA11CE000, 0xBADBAD00, 0xBADBAD08, 0xF00DF00D, 0xF00DF00E, 0xBADBAD00, 0xA11CE004, 0xBADBAD00] +MEMORY_ON = {0xA0004: 0xBADBAD04, 0xA0008: 0xBADBAD08, # untouched + ag.DUMP + 4: 0x5707, ag.DUMP + 8: 1, # where the refused store and atomic went + ag.HEADER + 24: 6, # six refused accesses + ag.HEADER + 32: 0xA0000, ag.HEADER + 36: 0} # the last one, the s_load at 0xa0000 +MEMORY_OFF = {0xA0004: 0x5707, 0xA0008: 0xBADBAD09, ag.DUMP + 4: 0, ag.HEADER + 24: 0} + + +def heap(guard_on): + """The heap's bytes: header (without the magic when not `guard_on`), seeds and page table; zero elsewhere.""" + words = ag.table_words(BACKED) + end = TABLE + 4 * len(words) + assert end <= HEAP_BYTES + buf = bytearray(end) + hdr = bytearray(ag.header(LIMIT, TABLE)) + if not guard_on: + hdr[0:8] = bytes(8) + buf[ag.HEADER:ag.HEADER + len(hdr)] = hdr + for at, value in SEEDS.items(): + struct.pack_into("64 threads).""" - def test_single_wave_round_fallback_and_loop_carried_war(self): + def test_single_wave_inline_all_zero_switch_and_loop_carried_war(self): # 64-thread and partial 40-thread shaders with live-out scalars, loop-carried store->load->store WAR/RAW, - # and v_readfirstlane require uniform exchange barriers on both scheduling orders. + # and v_readfirstlane emit 0 OpSwitch cases and 0 x_spills while staying bit-exact on both scheduling + # orders. Their exchange barriers sit under `%pc`-only guards, which a single wave takes as one, so the + # barrier fallback of translate() does not apply to them (docs/design.md, "Wave64 emulation: + # single-wave barrier fallback"). insns = [ ("s_mov_b64 exec, -1", 4), ("s_mov_b32 s16, 10", 4), @@ -1314,10 +1317,11 @@ def test_single_wave_round_fallback_and_loop_carried_war(self): for threads in (64, 40): with self.subTest(threads=threads): spv, gen = _translate_encoded(f"cs_inline_{threads}", insns, (threads, 1, 1), emulate=True) - self.assertEqual(gen.control_flow, "emulated wave64 rounds") - self.assertIsNone(gen.emulate_plan) - self.assertIn("OpSwitch", spv) - self.assertFalse(rdna2spirv.barriers_under_control_flow(spv)) + self.assertEqual(gen.control_flow, "emulated wave64 structured") + self.assertEqual(gen.emulate_plan["mode"], "inline_all") + self.assertNotIn("OpSwitch", spv) + self.assertEqual(len(gen.x_spills), 0) + self.assertNotIn("OpGroupNonUniform", spv) for rev in (False, True): mem, _ = run_emulated_workgroup(spv, (threads, 1, 1), push_constants=VSHARP + [0] * 28, reverse_order=rev) # Reference simulation diff --git a/tests/semantic/test_wave64_single_wave_barrier.py b/tests/semantic/test_wave64_single_wave_barrier.py new file mode 100644 index 0000000000..4723393e3e --- /dev/null +++ b/tests/semantic/test_wave64_single_wave_barrier.py @@ -0,0 +1,123 @@ +"""A single-wave emulated program keeps its exchange barriers in the structured form (docs/design.md, "Wave64 +emulation: single-wave barrier fallback"). + +`translate()` re-translates an emulated program as the round loop when an `OpControlBarrier` sits under a branch or +loop, because a barrier only part of the workgroup reaches hangs NVIDIA. A one-wave workgroup (`inline_all` plan) +does not need that: every guard around its barriers tests only `%pc`, which all 64 invocations hold alike. The +fixture puts a cross-half `v_readlane_b32` (an exchange behind a barrier) in a uniform loop and in a uniform branch. + + python -I tests/semantic/test_wave64_single_wave_barrier.py -v +""" +import os +import re +import sys +import unittest +from pathlib import Path + +HERE = os.path.dirname(os.path.abspath(__file__)) +if HERE not in sys.path: + sys.path.insert(0, HERE) + +from test_loop_ballot_barrier import _translate_cs, rdna2spirv +from spirv_mini_interp import run_workgroup + +FIXTURE = Path(HERE) / "fixtures" / "wave64_single_wave_barrier.asm" +_DEF = re.compile(r"^\s*(%[\w.]+) = (Op\w+)([^\n]*)$", re.M) +_HEAD = re.compile(r"^\s*(?:(%[\w.]+) = )?(OpLabel|OpSelectionMerge|OpLoopMerge|OpBranchConditional|OpControlBarrier)" + r"\b([^\n]*)$", re.M) + + +def module(lanes, 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") + return _translate_cs("cs_single_wave_barrier", lines, threads=lanes, emulate=True, structured=structured) + + +def execute(text, lanes, s4): + 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, s4] + [0] * 27, memory={}) + return [mem[i * 4] for i in range(lanes)] + + +def barrier_guard_loads(text): + """For every OpControlBarrier, the variables the conditions of its enclosing constructs load. + + A selection's condition is the OpBranchConditional after its OpSelectionMerge; a loop's are the conditional + branches inside it that leave it or go back to its header.""" + defs = {name: (op, rest.split()) for name, op, rest in _DEF.findall(text)} + + def loads(value, seen): + if value in seen or value not in defs: + return set() + seen.add(value) + op, args = defs[value] + if op == "OpLoad": + return {args[1]} + found = set() + for arg in args: + if arg.startswith("%"): + found |= loads(arg, seen) + return found + + events = [(m.start(), m.group(1), m.group(2), m.group(3).split()) for m in _HEAD.finditer(text)] + label_at = {name: at for at, name, op, _ in events if op == "OpLabel"} + constructs, header = [], None + for i, (at, name, op, args) in enumerate(events): + if op == "OpLabel": + header = name + elif op in ("OpSelectionMerge", "OpLoopMerge"): + constructs.append((op, header, args[0], i)) + result = [] + for at, _, op, _ in events: + if op != "OpControlBarrier": + continue + loaded = set() + for kind, head, merge, index in constructs: + if not label_at[head] <= at < label_at[merge]: + continue + if kind == "OpSelectionMerge": + conds = [events[index + 1][3][0]] + else: + conds = [args[0] for b_at, _, b_op, args in events + if b_op == "OpBranchConditional" and label_at[head] <= b_at < label_at[merge] + and {merge, head} & set(args[1:])] + for cond in conds: + loaded |= loads(cond, set()) + result.append(loaded) + return result + + +class SingleWaveBarrierTests(unittest.TestCase): + def test_single_wave_stays_structured_with_pc_only_guards(self): + text, gen = module(64) + self.assertEqual(gen.control_flow, "emulated wave64 structured") + self.assertEqual(gen.emulate_plan["mode"], "inline_all") + self.assertNotIn("OpSwitch", text) + # The barriers are under control flow (so the multi-wave fallback would fire), but only under `%pc`. + self.assertTrue(rdna2spirv.barriers_under_control_flow(text)) + guards = barrier_guard_loads(text) + self.assertTrue(any(guards), "no barrier inside the loop or the branch") + for loaded in guards: + self.assertLessEqual(loaded, {"%pc"}) + + def test_structured_and_round_forms_agree(self): + # lane 40 after each of the 3 iterations: 41 + 42 + 43; the branch adds lane 41's 41 + 3 + 100. + structured, _ = module(64) + rounds, gen = module(64, structured=False) + self.assertEqual(gen.control_flow, "emulated wave64 rounds") + for s4, want in ((0, 126), (1, 126 + 144)): + with self.subTest(s4=s4): + self.assertEqual(execute(structured, 64, s4), [want] * 64) + self.assertEqual(execute(rounds, 64, s4), [want] * 64) + + def test_partial_single_wave_is_structured_too(self): + text, gen = module(48) + self.assertEqual(gen.control_flow, "emulated wave64 structured") + self.assertEqual(gen.emulate_plan["mode"], "inline_all") + self.assertEqual(execute(text, 48, 1), [126 + 144] * 48) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_dstorage_history.py b/tests/test_dstorage_history.py index 77e8179d73..be00af80ad 100644 --- a/tests/test_dstorage_history.py +++ b/tests/test_dstorage_history.py @@ -85,6 +85,58 @@ def test_visible_2d_mip_starts_after_first_256_compressed_blocks(self): self.assertEqual(bc7["historyEndpointConfirmedBits"][255][field], 0) self.assertLessEqual(abs(bc7["historyEndpoints"][255][field] - 128), 4) + def test_packed_tail_fits_against_decoded_bcpack_sibling(self): + # Mip 0 is zlib, mip 1 a self-contained BCPack stream and the packed tail (mips 2-4) starts its + # chains at history entry 255, whose alpha no raw or zlib sibling of the tail can show. + solid = bytes([0x40]) + bytes(15) + secret = (0, 0, 0, 128) * 6 + tail = _encode_bc7_mode6_tiled(solid * 256, secret_entry=255, secret_ep=secret, ref_count=255) + with tempfile.TemporaryDirectory() as name: + pool = Path(name)/"bcpack-parent.ttpf" + record = _pack_etpf(128, 128, 4, 1, 98, 4096) + _write_custom_rds5_pool(pool, [record], [(7, 4096, tail), (7, 4096, _encode_bc7_mode6_tiled(solid * 256)), + (8, 16384, zlib.compress(solid * 1024))]) + fits = {6: history.calib.Bc6hCalibrator(), 7: history.calib.Bc7Calibrator()} + history.calib.calibrate_from_pools([str(pool)], fits) + docs = {history.calib.CODEC_KEYS[c]: f.build_document()[0] for c, f in fits.items()} + history.extend_missing(docs, history.fit_slices([pool])) + bcpack = history.calib.bcpack + with self.assertRaises(bcpack.BcpackProvisionalError): + bcpack.decode(tail, 7, 4096, allow_provisional=True, history=docs) + history.fit_decoded_neighbors([pool], docs) + bc7 = docs["bc7"] + for field in (3, 7): + self.assertGreaterEqual(bc7["historyEndpointBits"][255][field], 4) + self.assertEqual(bc7["historyEndpointConfirmedBits"][255][field], 0) + self.assertLessEqual(abs(bc7["historyEndpoints"][255][field] - 128), 4) + self.assertEqual(bcpack.decode(tail, 7, 4096, allow_provisional=True, history=docs), solid * 256) + + def test_packed_tail_fits_against_its_own_refused_stream(self): + # One BCPack stream holds the packed tail (blocks 0-255) and mip 1 (blocks 256-511). Chains from history + # entry 255 stay inside the tail, so the stream is refused and no fit reaches the entry, but mip 1 is + # determined and is the reference. + solid = bytes([0x40]) + bytes(15) + secret = (0, 0, 0, 128) * 6 + stream = _encode_bc7_mode6_tiled(solid * 512, secret_entry=255, secret_ep=secret, ref_count=200) + with tempfile.TemporaryDirectory() as name: + pool = Path(name)/"one-stream.ttpf" + record = _pack_etpf(128, 128, 4, 1, 98, 4096) + _write_custom_rds5_pool(pool, [record], [(7, 8192, stream), (8, 16384, zlib.compress(solid * 1024))]) + fits = {6: history.calib.Bc6hCalibrator(), 7: history.calib.Bc7Calibrator()} + history.calib.calibrate_from_pools([str(pool)], fits) + docs = {history.calib.CODEC_KEYS[c]: f.build_document()[0] for c, f in fits.items()} + history.extend_missing(docs, history.fit_slices([pool])) + bcpack = history.calib.bcpack + with self.assertRaises(bcpack.BcpackProvisionalError): + bcpack.decode(stream, 7, 8192, allow_provisional=True, history=docs) + history.fit_decoded_neighbors([pool], docs) + bc7 = docs["bc7"] + for field in (3, 7): + self.assertGreaterEqual(bc7["historyEndpointBits"][255][field], 4) + self.assertEqual(bc7["historyEndpointConfirmedBits"][255][field], 0) + self.assertLessEqual(abs(bc7["historyEndpoints"][255][field] - 128), 4) + self.assertEqual(bcpack.decode(stream, 7, 8192, allow_provisional=True, history=docs), solid * 512) + def test_build_resume_and_repair(self): trainer = os.environ.get("LEONIDA_TEST_BCPACK_TRAINER") if not trainer and not shutil.which("cl" if os.name == "nt" else "c++"): diff --git a/tests/test_make_game_wave64.py b/tests/test_make_game_wave64.py index 74d36ecbbc..9ceb87c07f 100644 --- a/tests/test_make_game_wave64.py +++ b/tests/test_make_game_wave64.py @@ -49,6 +49,76 @@ def test_no_subgroup_size_gives_none(self): self.assertIsNone(make_game.smallest_max_subgroup("\tminSubgroupSize = 32\n")) +def typed_device(name, kind, size): + """vulkaninfo's plain-text layout for one device as a real run prints it: deviceType just before deviceName.""" + return ("VkPhysicalDeviceProperties:\n---------------------------\n" + f"\tdeviceType = PHYSICAL_DEVICE_TYPE_{kind}\n" + f"\tdeviceName = {name}\n" + "VkPhysicalDeviceVulkan13Properties:\n-----------------------------------\n" + "\tminSubgroupSize = " + f"{min(size, 32) if size >= 32 else size}\n" + f"\tmaxSubgroupSize = {size}\n") + + +class CpuDeviceTest(unittest.TestCase): + """A CPU device (llvmpipe: maxSubgroupSize 8) does not decide when a GPU is listed: the runtime ranks it last.""" + + def test_llvmpipe_beside_a_wave64_gpu_is_left_out(self): + text = (typed_device("AMD Radeon RX 7900 XTX (RADV NAVI31)", "DISCRETE_GPU", 64) + + typed_device("AMD Ryzen 9 7950X3D (RADV RAPHAEL_MENDOCINO)", "INTEGRATED_GPU", 64) + + typed_device("llvmpipe (LLVM 23.1.5, 256 bits)", "CPU", 8)) + self.assertEqual(make_game.smallest_max_subgroup(text), 64) + size, device, left_out = make_game.max_subgroup_decider(text) + self.assertEqual((size, device), (64, "AMD Radeon RX 7900 XTX (RADV NAVI31)")) + self.assertEqual(left_out, ["llvmpipe (LLVM 23.1.5, 256 bits)"]) + + def test_the_cpu_device_listed_first_is_left_out_too(self): + text = typed_device("llvmpipe", "CPU", 8) + typed_device("GPU", "DISCRETE_GPU", 64) + self.assertEqual(make_game.max_subgroup_decider(text), (64, "GPU", ["llvmpipe"])) + + def test_a_32_wide_gpu_still_decides(self): + text = (typed_device("A", "DISCRETE_GPU", 64) + typed_device("B", "INTEGRATED_GPU", 32) + + typed_device("llvmpipe", "CPU", 8)) + self.assertEqual(make_game.max_subgroup_decider(text), (32, "B", ["llvmpipe"])) + + def test_only_a_cpu_device_decides(self): + self.assertEqual(make_game.max_subgroup_decider(typed_device("llvmpipe", "CPU", 8)), (8, "llvmpipe", [])) + + def test_a_cpu_device_without_a_size_does_not_make_it_unknown(self): + text = (typed_device("GPU", "DISCRETE_GPU", 64) + + "VkPhysicalDeviceProperties:\n\tdeviceType = PHYSICAL_DEVICE_TYPE_CPU\n" + "\tdeviceName = old lavapipe\n") + self.assertEqual(make_game.smallest_max_subgroup(text), 64) + # ...but a GPU without one still does. + old_gpu = ("VkPhysicalDeviceProperties:\n\tdeviceType = PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU\n" + "\tdeviceName = old GPU\n") + self.assertIsNone(make_game.smallest_max_subgroup(text + old_gpu)) + + def test_json_key_order(self): + text = ('{"VkPhysicalDeviceProperties": {\n\t\t"deviceName": "llvmpipe",\n' + '\t\t"deviceType": "VK_PHYSICAL_DEVICE_TYPE_CPU"},\n' + '\t"VkPhysicalDeviceSubgroupSizeControlProperties": {\n\t\t"maxSubgroupSize": 8}}\n' + '{"VkPhysicalDeviceProperties": {\n\t\t"deviceName": "GPU",\n' + '\t\t"deviceType": "VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU"},\n' + '\t"VkPhysicalDeviceSubgroupSizeControlProperties": {\n\t\t"maxSubgroupSize": 64}}') + self.assertEqual(make_game.max_subgroup_decider(text), (64, "GPU", ["llvmpipe"])) + + def test_auto_logs_the_deciding_device_and_the_left_out_one(self): + text = typed_device("GPU", "DISCRETE_GPU", 64) + typed_device("llvmpipe", "CPU", 8) + lines = [] + + def fake_run(args, **kw): + if os.path.basename(str(args[-1])) == "vk_subgroup_info.py": + return subprocess.CompletedProcess(args, 0, stdout='{"native64": true}', stderr="") + return subprocess.CompletedProcess(args, 0, stdout=text, stderr="") + with mock.patch.object(make_game.shutil, "which", return_value="vulkaninfo"), \ + mock.patch.object(make_game.subprocess, "run", side_effect=fake_run), \ + mock.patch.object(make_game, "log", lambda *a: lines.append(" ".join(map(str, a)))): + self.assertFalse(make_game.wave64_emulate("auto")) + self.assertTrue(any("llvmpipe" in line and "left out" in line for line in lines), lines) + self.assertTrue(any("is 64 (GPU)" in line and "emulation off" in line for line in lines), lines) + + class Wave64EmulateTest(unittest.TestCase): """wave64_emulate(): on and off are taken as given; auto asks vulkaninfo and falls back to on.""" diff --git a/tools/address_guard.py b/tools/address_guard.py new file mode 100644 index 0000000000..1acbad5284 --- /dev/null +++ b/tools/address_guard.py @@ -0,0 +1,110 @@ +"""The address guard's page table and header, as the runtime writes them (runtime/src/address_guard.h) and the +shaders translated with `rdna2spirv.py --address-guard` read them (docs/d3d12_vulkan.md, "Address guard"). + +Standard library only. Used by the translator tests and scripts/run_address_guard_gpu_test.py to build a heap, and +as the Python reference of the check a guarded access makes: + + python -I tools/address_guard.py 0x90000:0x91000 --check 0x90ffc 8 + +Offsets are heap offsets (device address - heap_base), taken as 48-bit values: a negative one (a buffer below the +arena) is its two's complement in 48 bits, as the shaders sign-extend a V#'s base. +""" +import argparse +import struct +import sys + +# Shared with tools/rdna2spirv.py (ADDRESS_GUARD and the GUARD_* constants) and runtime/src/address_guard.h. +HEADER = 0x70000 # arena offset of the header +ZERO = 0x71000 # refused loads read here (+ the offset within its 4 KiB page) +DUMP = 0x78000 # refused stores and atomics write here +RESERVED_END = 0x80000 # the guard's part of the arena ends here +MAGIC = int.from_bytes(b"LGUARD01", "little") +L1 = 1 << 16 # level-1 words: bits 47..32 of the offset +BLOCK_WORDS = 1 << 15 # a level-2 block: one bit per 4 KiB page of a 4 GiB chunk +PAGE = 1 << 12 +MASK48 = (1 << 48) - 1 +EMPTY_BLOCK, FULL_BLOCK = 0, 1 # every table has them; allocated blocks start at 2 + + +def header(limit, table_offset, refused=0, last=0): + """The 64-byte header: magic, arena size (offsets below it pass without a lookup), the table's address minus + heap_base (mod 2^64), the refusal count and the last refused offset, which the shaders write.""" + return struct.pack("> 12, (((end - 1) & MASK48) >> 12) + 1): + chunks.setdefault(page >> 20, set()).add(page & 0xFFFFF) + level1 = [EMPTY_BLOCK] * L1 + blocks = [] + for chunk in sorted(chunks): + if max_blocks is not None and len(blocks) >= max_blocks: + level1[chunk] = FULL_BLOCK + continue + bits = [0] * BLOCK_WORDS + for page in chunks[chunk]: + bits[page >> 5] |= 1 << (page & 31) + level1[chunk] = 2 + len(blocks) + blocks.append(bits) + words = level1 + [0] * BLOCK_WORDS + [0xFFFFFFFF] * BLOCK_WORDS + for bits in blocks: + words += bits + return words + + +def page_backed(words, offset): + """The table's bit for the page of heap offset `offset`.""" + offset &= MASK48 + block = words[(offset >> 32) & (L1 - 1)] + page = (offset >> 12) & 0xFFFFF + return bool(words[L1 + block * BLOCK_WORDS + (page >> 5)] >> (page & 31) & 1) + + +def passes(words, limit, offset, extent): + """What a guarded access does: True when [offset, offset + extent) is below `limit` (the arena) or the pages of + its first and last byte are backed. `offset` is sign-extended from 48 bits, as the shaders do.""" + offset &= MASK48 + if offset >> 47: + offset -= 1 << 48 + end = offset + extent - 1 + if 0 <= offset < limit and 0 <= end < limit: + return True + return page_backed(words, offset) and page_backed(words, end) + + +def _int(text): + return int(text, 0) + + +def main(argv=None): + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("spans", nargs="*", help="backed heap offset spans, START:END (hex or decimal)") + ap.add_argument("--limit", type=_int, default=RESERVED_END, help="the arena's size (default %(default)#x)") + ap.add_argument("--check", nargs=2, type=_int, metavar=("OFFSET", "BYTES"), action="append", default=[], + help="print whether an access passes") + a = ap.parse_args(argv) + spans = [] + for text in a.spans: + start, _, end = text.partition(":") + spans.append((_int(start), _int(end))) + words = table_words(spans) + blocks = (len(words) - L1) // BLOCK_WORDS + print(f"table: {len(words) * 4} bytes, {blocks - 2} level-2 block(s) besides the empty and full ones") + for offset, extent in a.check: + print(f"{offset:#x} +{extent}: {'passes' if passes(words, a.limit, offset, extent) else 'refused'}") + return 0 + + +if __name__ == "__main__": + try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode + sys.stdout.reconfigure(errors="replace") + except (AttributeError, ValueError, OSError): + pass + sys.exit(main()) diff --git a/tools/bcpack_history_calib.py b/tools/bcpack_history_calib.py index 4c8312b41d..01bb3af2ec 100644 --- a/tools/bcpack_history_calib.py +++ b/tools/bcpack_history_calib.py @@ -1858,6 +1858,8 @@ def add_pool_chunk(self, lanes, nblocks, inv_lookup=None, chunk_rel_start=0, get if xy is None: continue qpts = get_quads(xy[0], xy[1]) + if qpts is None: # the sibling block is undetermined itself + continue spread = max(max(p[c] for p in qpts) - min(p[c] for p in qpts) for c in range(4)) weight = 4.0 if spread <= 6.0 else (2.0 if spread <= 18.0 else 0.5) sm = None if ns == 1 else (p2[part] if ns == 2 else p3[part]) diff --git a/tools/build_dstorage_history.py b/tools/build_dstorage_history.py index ee9c224bd5..8320f87d4a 100644 --- a/tools/build_dstorage_history.py +++ b/tools/build_dstorage_history.py @@ -93,6 +93,164 @@ def extend_missing(base, extra): base["bc7"][value][k][j] = extra["bc7"][value][k][j] +def _field_count(docs): + return (sum(map(bool, docs["bc6h"]["endpointClass"])) + sum(map(bool, docs["bc6h"]["indexClass"])) + + sum(bool(v) for key in ("historyEndpointBits", "historyIndexBits") for row in docs["bc7"][key] for v in row)) + + +def _unknown_references(codec, lanes, blocks, docs, table): + """Whether the stream's first 256 blocks start a predictor chain at a field the profile still lacks.""" + if codec == 7: + try: + return bool(calib.bcpack._bc7_check(lanes, min(blocks, 256), table, set(), has_history=True)) + except calib.bcpack.BcpackError: + return False + l0, l1 = lanes[0], lanes[1] + for i in range(min(blocks, 256)): + di = calib.bcpack._inter8(l1[2*i], l1[2*i+1]) + de = (di + calib.bcpack._unzig(calib.bcpack._inter8(l0[2*i], l0[2*i+1]))) & 255 + if (de > i and not docs["bc6h"]["endpointClass"][256+i-de] or + di > i and not docs["bc6h"]["indexClass"][256+i-di]): + return True + return False + + +def _decode_known(pool, start, size, docs, table, cache): + """Tiled bytes of a range plus the byte offsets (within it) of blocks the profile cannot determine. + + A BC7 stream that the decoder refuses for its unknown history still determines every block whose predictor + chains start elsewhere; only the blocks rooted at an unknown field, or failing the anchor and p-bit check, are + marked. Other BCPack streams must decode in provisional mode.""" + bcpack = calib.bcpack + out = bytearray(size) + unknown = set() + for virt, csize, offset, packed, codec, _ in pool.chunks_for(start, size): + key = (offset, packed, codec) + if key not in cache: + raw = pool.data[offset:offset+packed] + bad = () + if codec in (0, 8): + data = pool.read_range(virt, csize, None, bcpack_mode="off") + elif codec == 7: + lanes, _ = bcpack.decode_lanes(raw, 7, csize) + blocks = csize // 16 + missing = bcpack._bc7_check(lanes, blocks, table, set(), has_history=True) + data, status = bcpack._bc7_rebuild(lanes, blocks, table) + ends = {k for kind, k in missing if kind == "endpoint"} + idxs = {k for kind, k in missing if kind == "index"} + l0, l1 = lanes[0], lanes[1] + er, ir = [-1] * blocks, [-1] * blocks + for i in range(blocks): + di = bcpack._inter8(l1[2*i], l1[2*i+1]) + de = (di + bcpack._unzig(bcpack._inter8(l0[2*i], l0[2*i+1]))) & 255 + er[i] = -1 if de == 0 else (256 + i - de if de > i else er[i - de]) + ir[i] = -1 if di == 0 else (256 + i - di if di > i else ir[i - di]) + bad = {16 * i for i in range(blocks) if status[i] or er[i] in ends or ir[i] in idxs} + else: + data = bcpack.decode(raw, codec, csize, allow_provisional=True, history=docs) + cache[key] = (bytes(data), bad) + data, bad = cache[key] + lo, hi = max(start, virt), min(start + size, virt + csize) + out[lo - start:hi - start] = data[lo - virt:hi - virt] + unknown.update(virt + b - start for b in bad if lo <= virt + b < hi) + return bytes(out), unknown + + +def _known_quads(getter, layout, ref, kind, unknown): + """The sibling getter, answering None where a reference block is undetermined.""" + if not unknown: + return getter + bw, bh = (ref["pixels_w"] + 3) // 4, (ref["pixels_h"] + 3) // 4 + def get_quads(bx, by): + # A child's 2x2 pixels per quad lie in one block; a parent's quads cover a 2x2 block square. + x0, y0, span = (bx // 2, by // 2, 1) if kind == "child" else (2 * bx, 2 * by, 2) + for y in range(y0, y0 + span): + for x in range(x0, x0 + span): + if calib.tiled_offset(layout, ref, min(x, bw - 1), min(y, bh - 1)) in unknown: + return None + return getter(bx, by) + return get_quads + + +def fit_decoded_neighbors(pools, docs, rounds=4): + """Fill fields that only streams without a raw or zlib sibling reference. + + The other fits take their reference from a raw or zlib mip. A packed tail whose larger mips are BCPack-coded + too has none, so a field that only such streams use stays unknown and the runtime refuses them. Decode the + nearest BCPack sibling with the profile so far and fit against it; it may lie in the same refused stream, whose + undetermined blocks are left out of the reference. A decoded mip can be the reference of the next one, so + repeat while a round adds fields. Only fields still missing are filled, and never as confirmed. + """ + table = bptc.load_bc7(docs) + jobs = [] + for path in pools: + with closing(ttpf.Pool(path)) as pool: + wanted = set() + for _, size, offset, packed, codec, _ in pool.chunks: + if codec in (6, 7): + blocks = min(2048, size // 16) + lanes = calib.decode_lanes_prefix(pool.data[offset:offset+packed], codec, size, blocks*2) + if _unknown_references(codec, lanes, blocks, docs, table): + wanted.add(offset) + if not wanted: + continue + for index in range(pool.textures): + d = pool.descriptor(index) + codec = next((c for c in (6, 7) if d["format"] in calib.CODEC_DXGI[c]), None) + if not codec or d["dimension"] not in (1, 2): + continue + a = ttpf.analyze(pool, index) + if not a.get("available") or a.get("blocked"): + continue + layout = a["layout"] + for layer in range(d["depth"]): + for level, mip in enumerate(layout["mips"]): + start = (d["base"] + layout.get("data_offset", 0) + mip["offset"] + + layer * mip.get("slice_stride", layout.get("face_size", 0))) + if any(c[2] in wanted for c in pool.chunks_for(start, mip["region"])): + jobs.append((path, index, codec, layer, level)) + for _ in range(rounds): + before = _field_count(docs) + table = bptc.load_bc7(docs) + fits = {6: calib.Bc6hCalibrator(), 7: calib.Bc7Calibrator()} + for path in sorted({job[0] for job in jobs}): + with closing(ttpf.Pool(path)) as pool: + cache = {} + for _, index, codec, layer, level in (job for job in jobs if job[0] == path): + d = pool.descriptor(index) + layout = ttpf.analyze(pool, index)["layout"] + mips = layout["mips"] + def address(m): + return (d["base"] + layout.get("data_offset", 0) + m["offset"] + + layer * m.get("slice_stride", layout.get("face_size", 0))) + mip = mips[level] + start = address(mip) + chunks = [(size, offset, packed, virt - start, min(2048, size // 16)) + for virt, size, offset, packed, mode, _ in pool.chunks_for(start, mip["region"]) + if mode == codec and start - virt < 2048 * 16] + for neighbor, kind in ((level+1, "child"), (level-1, "parent")): + if not 0 <= neighbor < len(mips) or mips[neighbor]["region"] > 1048576: + continue + ref = mips[neighbor] + if codec not in pool.codecs(address(ref), ref["region"]): + continue # a raw or zlib sibling is the other fits' reference + try: + tiled, unknown = _decode_known(pool, address(ref), ref["region"], docs, table, cache) + except (calib.bcpack.BcpackError, ValueError): + continue + getter = _known_quads(calib._make_sibling_quads_getter(codec, layout, ref, tiled, kind, + signed=d["format"] == 96), + layout, ref, kind, unknown) + inverse = calib.make_inverse_tile_lookup(layout, mip) + for size, offset, packed, relative, blocks in chunks: + lanes = calib.decode_lanes_prefix(pool.data[offset:offset+packed], codec, size, blocks*2) + fits[codec].add_pool_chunk(lanes, blocks, inverse, relative, getter) + extend_missing(docs, {calib.CODEC_KEYS[c]: f.build_document()[0] for c, f in fits.items()}) + if _field_count(docs) == before: + break + return docs + + def collect(pools, trainer, temporary): """The host trainer consumes framed chunks and returns violation counts per candidate.""" output = temporary / "constraints" @@ -214,6 +372,7 @@ def build(game, output, trainer, base_history=None, json_out=None, if_needed=Fal calib.calibrate_from_pools(pools, fits) docs = {calib.CODEC_KEYS[c]: f.build_document()[0] for c, f in fits.items()} extend_missing(docs, fit_slices(pools)) + fit_decoded_neighbors(pools, docs) history = temp/"history.json" history.write_text(json.dumps(docs), encoding="utf-8", newline="\n") if not trainer: diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 4311f3100b..73df48ed8e 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -120,6 +120,33 @@ F16_HALVES = False F16_HALF_TOP = 29 OPT_SPIRV = False # --opt: run tools/spirv_opt.py basic-block peephole pass on emitted SPIR-V (#884) +# --address-guard: every access through heap_base + VA is checked against what the runtime backs (docs/d3d12_vulkan.md, +# "Address guard"); one that fails reads 0 and drops its store. The runtime (LEONIDA_ADDRESS_GUARD=1) writes a header +# at arena offset GUARD_HEADER: GUARD_MAGIC (u64), the arena's size (u64, offsets below it pass without a lookup), the +# page table's address minus heap_base (u64), a count of refused accesses (u32, the shaders add to it) and the last +# refused offset (u64). Without the magic every access passes, so a guarded module runs unchanged on a runtime with +# the guard off. A refused load reads the zero area, a refused store or atomic writes the dump area; both are in the +# arena's reserved first 512 KiB. Shared with runtime/src/address_guard.h. +ADDRESS_GUARD = False +# --address-guard (diagnostics): the module's id, FNV-1a of its file stem, which a refused access stores in the header +# (+28) next to its offset, so the runtime's refusal line names the module. Set by _translate for each file. +GUARD_MODULE_ID = 0 + + +def fnv1a32(text): + """32-bit FNV-1a of a UTF-8 string (the address guard's module id; tools/address_guard.py --module maps names).""" + h = 0x811C9DC5 + for b in text.encode("utf-8"): + h = ((h ^ b) * 0x01000193) & 0xFFFFFFFF + return h + + +GUARD_HEADER = 0x70000 +GUARD_ZERO = 0x71000 +GUARD_DUMP = 0x78000 +GUARD_MAGIC = int.from_bytes(b"LGUARD01", "little") +GUARD_L1 = 1 << 16 # level-1 entries: bits 47..32 of the 48-bit offset (4 GiB each) +GUARD_BLOCK_WORDS = 1 << 15 # level-2 block: one bit per 4 KiB page of a 4 GiB chunk # The heap base as one %ulong, in the entry block of %main: the push constants don't change during the invocation, and @@ -132,6 +159,109 @@ "%heap_base = OpBitwiseOr %ulong %heap_base_hi_sh %heap_base_lo64"] +def guard_entry(cl, cu): + """--address-guard: the entry-block lines that read the runtime's guard header at heap_base + GUARD_HEADER once + per invocation: %gd_on (the magic is there), %gd_limit (the arena's size) and %gd_table (the page table's address + minus heap_base). The header is in the arena's reserved range, so the read itself is always backed.""" + L = [f"%gd_hp = OpIAdd %ulong %heap_base {cl(GUARD_HEADER)}", + "%gd_p = OpConvertUToPtr %_ptr_PSB_arr %gd_hp"] + for i in range(6): + L += [f"%gd_w{i}p = OpAccessChain %_ptr_PSB_uint %gd_p {cu(i)}", f"%gd_w{i} = OpLoad %uint %gd_w{i}p Aligned 4"] + for name, lo, hi in (("magic", 0, 1), ("limit", 2, 3), ("table", 4, 5)): + L += [f"%gd_{name}_l = OpUConvert %ulong %gd_w{lo}", f"%gd_{name}_h = OpUConvert %ulong %gd_w{hi}", + f"%gd_{name}_s = OpShiftLeftLogical %ulong %gd_{name}_h %c64_32", + f"%gd_{name} = OpBitwiseOr %ulong %gd_{name}_s %gd_{name}_l"] + L.append(f"%gd_on = OpIEqual %bool %gd_magic {cl(GUARD_MAGIC)}") + return L + + +def guard_function(cl, cu): + """--address-guard: %guard_fn(heap_base, on, limit, table, offset, delta, sink) -> host address. + + `offset` is the access's sign-extended 48-bit heap offset and `delta` its span minus one. Without the runtime's + guard (`on` false), or when [offset, offset + delta] is below `limit` (the arena, all of it backed), the result is + heap_base + offset after one compare. Otherwise the page table at heap_base + table decides, per 4 KiB page of the + first and the last byte: level 1 is GUARD_L1 words indexed by offset bits 47..32 (the level-2 block of that 4 GiB + chunk: 0 none backed, 1 all), level 2 is one bit per page (bits 31..12), GUARD_BLOCK_WORDS words a block, after + level 1. A refused access counts itself in the header and goes to heap_base + sink + (offset & 0xFFF).""" + ul = "%ulong" + L = ["%guard_fn = OpFunction %ulong None %fn_guard", + "%ga_hb = OpFunctionParameter %ulong", "%ga_on = OpFunctionParameter %bool", + "%ga_lim = OpFunctionParameter %ulong", "%ga_tab = OpFunctionParameter %ulong", + "%ga_off = OpFunctionParameter %ulong", "%ga_delta = OpFunctionParameter %ulong", + "%ga_sink = OpFunctionParameter %ulong", + "%ga_entry = OpLabel", + f"%ga_end = OpIAdd {ul} %ga_off %ga_delta", + f"%ga_a = OpULessThan %bool %ga_off %ga_lim", + f"%ga_b = OpULessThan %bool %ga_end %ga_lim", + "%ga_in = OpLogicalAnd %bool %ga_a %ga_b", + "%ga_off_n = OpLogicalNot %bool %ga_on", + "%ga_pass = OpLogicalOr %bool %ga_in %ga_off_n", + "OpSelectionMerge %ga_m None", + "OpBranchConditional %ga_pass %ga_m %ga_slow", + "%ga_slow = OpLabel", + f"%ga_tb = OpIAdd {ul} %ga_hb %ga_tab"] + + def bit(k, o): + """Lines for %ga_bit{k}: the page-table bit of heap offset id `o`.""" + return [f"%ga_c{k} = OpShiftRightLogical {ul} {o} %c64_32", + f"%ga_ci{k} = OpBitwiseAnd {ul} %ga_c{k} {cl(GUARD_L1 - 1)}", + f"%ga_ca{k} = OpShiftLeftLogical {ul} %ga_ci{k} {cl(2)}", + f"%ga_cp{k} = OpIAdd {ul} %ga_tb %ga_ca{k}", + f"%ga_cq{k} = OpConvertUToPtr %_ptr_PSB_uint %ga_cp{k}", + f"%ga_e{k} = OpLoad %uint %ga_cq{k} Aligned 4", + f"%ga_e64{k} = OpUConvert {ul} %ga_e{k}", + f"%ga_pg{k} = OpShiftRightLogical {ul} {o} {cl(12)}", + f"%ga_pm{k} = OpBitwiseAnd {ul} %ga_pg{k} {cl(0xFFFFF)}", + f"%ga_pw{k} = OpShiftRightLogical {ul} %ga_pm{k} {cl(5)}", + f"%ga_eb{k} = OpIMul {ul} %ga_e64{k} {cl(GUARD_BLOCK_WORDS)}", + f"%ga_wi0{k} = OpIAdd {ul} %ga_eb{k} %ga_pw{k}", + f"%ga_wi{k} = OpIAdd {ul} %ga_wi0{k} {cl(GUARD_L1)}", + f"%ga_wa{k} = OpShiftLeftLogical {ul} %ga_wi{k} {cl(2)}", + f"%ga_wp{k} = OpIAdd {ul} %ga_tb %ga_wa{k}", + f"%ga_wq{k} = OpConvertUToPtr %_ptr_PSB_uint %ga_wp{k}", + f"%ga_w{k} = OpLoad %uint %ga_wq{k} Aligned 4", + f"%ga_pl{k} = OpUConvert %uint %ga_pm{k}", + f"%ga_sh{k} = OpBitwiseAnd %uint %ga_pl{k} {cu(31)}", + f"%ga_bs{k} = OpShiftRightLogical %uint %ga_w{k} %ga_sh{k}", + f"%ga_b1{k} = OpBitwiseAnd %uint %ga_bs{k} {cu(1)}", + f"%ga_bit{k} = OpINotEqual %bool %ga_b1{k} {cu(0)}"] + L += bit(0, "%ga_off") + bit(1, "%ga_end") + hdr = cl(GUARD_HEADER) + L += ["%ga_ok = OpLogicalAnd %bool %ga_bit0 %ga_bit1", + "OpSelectionMerge %ga_rm None", + "OpBranchConditional %ga_ok %ga_rm %ga_ref", + "%ga_ref = OpLabel", + # The refusal count (header +24) and the last refused offset (+32, low dword first): what the runtime logs. + f"%ga_h = OpIAdd {ul} %ga_hb {hdr}", + "%ga_hp = OpConvertUToPtr %_ptr_PSB_arr %ga_h", + f"%ga_cnt = OpAccessChain %_ptr_PSB_uint %ga_hp {cu(6)}", + f"%ga_old = OpAtomicIAdd %uint %ga_cnt {cu(1)} {cu(0)} {cu(1)}", + "%ga_lo = OpUConvert %uint %ga_off", + "%ga_hs = OpShiftRightLogical %ulong %ga_off %c64_32", + "%ga_hi = OpUConvert %uint %ga_hs", + f"%ga_lp = OpAccessChain %_ptr_PSB_uint %ga_hp {cu(8)}", + "OpStore %ga_lp %ga_lo Aligned 4", + f"%ga_hq = OpAccessChain %_ptr_PSB_uint %ga_hp {cu(9)}", + "OpStore %ga_hq %ga_hi Aligned 4", + # The refusing module's id (+28, diagnostics): GUARD_MODULE_ID, FNV-1a of the translated file's stem. + f"%ga_ip = OpAccessChain %_ptr_PSB_uint %ga_hp {cu(7)}", + f"OpStore %ga_ip {cu(GUARD_MODULE_ID)} Aligned 4", + "OpBranch %ga_rm", + "%ga_rm = OpLabel", + "OpBranch %ga_m", + "%ga_m = OpLabel", + "%ga_okp = OpPhi %bool %true %ga_entry %ga_ok %ga_rm", + f"%ga_good = OpIAdd {ul} %ga_hb %ga_off", + f"%ga_po = OpBitwiseAnd {ul} %ga_off {cl(0xFFF)}", + f"%ga_sb = OpIAdd {ul} %ga_hb %ga_sink", + f"%ga_bad = OpIAdd {ul} %ga_sb %ga_po", + f"%ga_r = OpSelect {ul} %ga_okp %ga_good %ga_bad", + "OpReturnValue %ga_r", + "OpFunctionEnd"] + return L + + def pc_tail_chain(name, member, c): """`name` = pointer to push-constant tail member `member`, numbered as in %UserData (1-2 heap base, 3-4 code base, 5-6 --mesh-compute output address): a member of the push-constant block by default, member - 1 of the uniform @@ -421,6 +551,7 @@ def __init__(self, stage, hoist_reg_ptrs=False, cache_active=False): self.bar_rounds = False # native wave32 cs with an s_barrier outside uniform control flow (bar_scheduler) self.uses_storage3d = False self.uses_heap = False + self.uses_guard = False # --address-guard: an access called %guard_fn (the entry block reads the header) self.uses_codebase = False self.uses_pc_tail = False # --pc-tail-ubo and the shader reads the tail (set in assemble) self.uses_long = False @@ -440,6 +571,8 @@ def __init__(self, stage, hoist_reg_ptrs=False, cache_active=False): self.fmt_fn = None # lines of the typed-buffer format-decode function, once a dynamic-format load needs it self.fmt_norm_fn = None # lines of the shared exact norm quotient for a run-time width (SHADER-849) self.fmt_enc_fn = None # shared format encoder for stores through a dynamic V# + self.guard_fn = None # --address-guard: lines of %guard_fn, once an access needs it + self.guard_last = None # --address-guard: (guarded address, unguarded address) of the last host_addr self.uses_fmt_tables = False # %fmt_desc_tab / %fmt_norm_rep_tab: a format's kind and channel widths self.x_round_fns: dict[str, list[str]] = {} # emulate_inline: helper functions for x_round pre-barrier setup self.x_round_fn_types: dict[int, str] = {} # emulate_inline: arity -> OpTypeFunction id for x_round_fns @@ -1596,8 +1729,14 @@ def f16_rtz(self, f): def modify_f(self, f, a): return self.tof(self.modify(self.tou(f), a)) - def host_addr(self, xbox_va): - """Add the sign-extended 48-bit effective VA to the heap base built in the entry block.""" + def host_addr(self, xbox_va, kind="load", extent=4): + """Add the sign-extended 48-bit effective VA to the heap base built in the entry block. + + --address-guard: the address is checked against the runtime's page table first (guard_addr). `kind` is + "load", "store" or "rmw" (an atomic): a refused load reads the zero area, a refused store or atomic the dump + area. `extent` is the bytes the access spans from this address: an int, or for a run-time span a callable + that emits it and returns the %ulong id of extent - 1 (guard_delta), called only with the guard so the + unguarded module stays byte for byte the same. Its first and last byte are checked.""" # V# truncates device_address - heap_base to 48 bits, including when an import lies below the heap. # Extend after adding byte offsets. Console user VAs and full-width root VAs already fit signed 48 bits. shift = self.cu(16) @@ -1607,8 +1746,77 @@ def host_addr(self, xbox_va): self.emit(f"{r} = OpIAdd %ulong %heap_base {offset}") self.uses_heap = True self.cu(1), self.cu(2) # member indices of the push-constant block, declared before assembly + if not ADDRESS_GUARD: + return r + return self.guard_addr(offset, r, kind, extent) + + def guard_delta(self, n, step): + """--address-guard: the %ulong id of (bytes spanned - 1) for n dwords (an int, or a %uint id of at least 1), + linear (step None) or each `step` bytes apart (a %uint id: a swizzled buffer access, buf_dword_ptr).""" + if isinstance(n, int) and (step is None or n == 1): + return self.cl(4 * n - 1) + if isinstance(n, int): + n1 = self.cu(n - 1) + else: + zero, dec, n1 = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{zero} = OpIEqual %bool {n} {self.cu(0)}") + self.emit(f"{dec} = OpISub %uint {n} {self.cu(1)}") + self.emit(f"{n1} = OpSelect %uint {zero} {self.cu(0)} {dec}") + m, m64, d = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{m} = OpIMul %uint {n1} {step if step is not None else self.cu(4)}") + self.emit(f"{m64} = OpUConvert %ulong {m}") + self.emit(f"{d} = OpIAdd %ulong {m64} {self.cl(3)}") + return d + + def guard_addr(self, offset, unguarded, kind, extent): + """--address-guard: the host address of the access at heap offset `offset` (sign-extended 48 bits): itself + when the runtime backs its first and last byte (or the runtime's guard is off), else a place in the arena's + zero area (a load) or dump area (a store, an atomic) at the same offset within a 4 KiB page, so alignment + holds. One call of %guard_fn (an arena offset passes on a compare; any other looks up two page-table bits).""" + self.uses_guard = True + delta = self.cl(extent - 1) if isinstance(extent, int) else extent() + sink = self.cl(GUARD_ZERO if kind == "load" else GUARD_DUMP) + if self.guard_fn is None: + self.guard_fn = guard_function(self.cl, self.cu) + guard_entry(self.cl, self.cu) # registers the entry block's constants while they can still be declared + r = self.tmp() + self.emit(f"{r} = OpFunctionCall %ulong %guard_fn %heap_base %gd_on %gd_limit %gd_table {offset} {delta} {sink}") + self.guard_last = (r, unguarded) return r + def sub_dwords(self, nbytes, b3): + """--address-guard: the dwords a 1- or 2-byte access at byte `b3` (a %uint id) of a dword reads: 1, or 2 for + a 2-byte access at byte 3 (an int or a %uint id).""" + if nbytes == 1: + return 1 + cross, n = self.tmp(), self.tmp() + self.emit(f"{cross} = OpIEqual %bool {b3} {self.cu(3)}") + self.emit(f"{n} = OpSelect %uint {cross} {self.cu(2)} {self.cu(1)}") + return n + + def store_element_dwords(self, fmt, fixed_fmt): + """--address-guard: the whole dwords a typed buffer store of one element writes (at least 1: a 1- or 2-byte + element is written through its own guarded dword): from the instruction's format, or the V#'s (`fmt`, a %uint + id) at run time.""" + if fixed_fmt is not None: + return max(1, self.FORMATS.get(fixed_fmt, (4,))[0] // 4) + size, q, n = self.fmt_size_of(fmt), self.tmp(), self.tmp() + self.emit(f"{q} = OpShiftRightLogical %uint {size} {self.cu(2)}") + self.emit(f"{n} = OpExtInst %uint %glsl UMax {q} {self.cu(1)}") + return n + + def guard_zero(self, value, ty="%uint"): + """--address-guard: `value` (an atomic's result) or 0 when the last host_addr was refused: a refused atomic + ran on the dump area, and what it returned from there means nothing. `value` unchanged without the guard.""" + if not ADDRESS_GUARD or self.guard_last is None: + return value + r, unguarded = self.guard_last + ok, out = self.tmp(), self.tmp() + zero = self.cu(0) if ty == "%uint" else self.cl(0) + self.emit(f"{ok} = OpIEqual %bool {r} {unguarded}") + self.emit(f"{out} = OpSelect {ty} {ok} {value} {zero}") + return out + def tof(self, u): """The %float with the bits of %uint u. Bitcasting a tou result back gives tou's argument (Gen.bitcast_from), so u must be a %uint and tou's argument a %float; an %int's bits go through int_bits.""" @@ -2336,7 +2544,7 @@ def buffer_sub(self, op, a, mods): self.emit(f"{f2} = OpISub %ulong {far} {self.cl(3)}") self.emit(f"{sel} = OpSelect %ulong {cross} {f2} {va}") va = sel - p, sh = self.global_byte_ptr(va) + p, sh = self.global_byte_ptr(va, "store" if store else "load") if store: byte, mk, inv, vs, t1, t2 = (self.tmp() for _ in range(6)) self.emit(f"{byte} = OpBitFieldUExtract %uint {old} {self.cu(16 * (half or 0) + 8 * k)} {self.cu(8)}") @@ -2386,7 +2594,7 @@ def buffer_load(self, op, a, mods): vd = a[0] addr, _, in_b, raw_parts, step = self.buffer_address(a, mods, parts=True) act = self.active_b() - ptr, host = self.tmp(), self.host_addr(addr) + ptr, host = self.tmp(), self.host_addr(addr, "load", lambda: self.guard_delta(n, step)) self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {host}") def guarded(cond, dwords): @@ -2453,7 +2661,7 @@ def buffer_load_sub(self, op, a, mods): self.emit(f"{b64} = OpUConvert %ulong {b3}") self.emit(f"{aligned} = OpISub %ulong {addr} {b64}") self.emit(f"{sh} = OpShiftLeftLogical %uint {b3} {self.cu(3)}") - ptr, host = self.tmp(), self.host_addr(aligned) + ptr, host = self.tmp(), self.host_addr(aligned, "load", lambda: self.guard_delta(self.sub_dwords(nbytes, b3), step)) self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {host}") p0, w0 = self.buf_dword_ptr(ptr, host, step, 0), self.tmp() self.emit(f"{w0} = OpLoad %uint {p0} Aligned 4") @@ -2957,7 +3165,7 @@ def _emit_atomic_fminmax_cas(self, kind, addr, val_f, cond): self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") self.emit(f"{lbl_do} = OpLabel") ptr, p, init = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(addr)}") + self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(addr, 'rmw')}") self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(0)}") self.emit(f"{init} = OpAtomicLoad %uint {p} {self.cu(1)} {self.cu(0)}") self.emit(f"OpBranch {lbl_hdr}") @@ -2975,6 +3183,7 @@ def _emit_atomic_fminmax_cas(self, kind, addr, val_f, cond): self.emit(f"{lbl_cont} = OpLabel") self.emit(f"OpBranch {lbl_hdr}") self.emit(f"{lbl_exit} = OpLabel") + cur = self.guard_zero(cur) self.emit(f"OpBranch {lbl_end}") self.emit(f"{lbl_end} = OpLabel") old = self.tmp() @@ -3022,7 +3231,7 @@ def global_atomic(self, op, a, mods): self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") self.emit(f"{lbl_do} = OpLabel") ptr, p = self.tmp(), self.tmp() - self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full)}") + self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full, 'rmw')}") self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(0)}") if is_inc_dec: res, done_lbl = self.atomic_inc_dec_cas(p, val, kind, lbl_do) @@ -3035,6 +3244,7 @@ def global_atomic(self, op, a, mods): self.emit(f"{res} = OpAtomicCompareExchange %uint {p} {self.cu(1)} {self.cu(0)} {self.cu(0)} {val} {cmp}") else: self.emit(f"{res} = {self.BUF_ATOMICS[kind][0]} %uint {p} {self.cu(1)} {self.cu(0)} {val}") + res = self.guard_zero(res) self.emit(f"OpBranch {lbl_end}") self.emit(f"{lbl_end} = OpLabel") self.emit(f"{old} = OpPhi %uint {res} {done_lbl} {self.cu(0)} {pre}") @@ -3086,13 +3296,14 @@ def global_atomic_x2(self, op, kind, a, mods): self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") self.emit(f"{lbl_do} = OpLabel") ptr = self.tmp() - self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full)}") + self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full, 'rmw', 8)}") res = [] for w in range(2): p, r = self.tmp(), self.tmp() self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(w)}") self.emit(f"{r} = {spv} %uint {p} {self.cu(1)} {self.cu(0)} {vals[w]}") res.append(r) + res = [self.guard_zero(r) for r in res] self.emit(f"OpBranch {lbl_end}") self.emit(f"{lbl_end} = OpLabel") olds = [] @@ -3160,7 +3371,7 @@ def buffer_atomic(self, op, a, mods): self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") self.emit(f"{lbl_do} = OpLabel") ptr, p = self.tmp(), self.tmp() - self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(addr)}") + self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(addr, 'rmw')}") self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(0)}") if is_inc_dec: res_do, done_lbl = self.atomic_inc_dec_cas(p, val, kind, lbl_do) @@ -3178,6 +3389,7 @@ def buffer_atomic(self, op, a, mods): self.emit(f"{res_do} = OpAtomicExchange %uint {p} {self.cu(1)} {self.cu(0)} {val}") else: self.emit(f"{res_do} = {spv} %uint {p} {self.cu(1)} {self.cu(0)} {val}") + res_do = self.guard_zero(res_do) self.emit(f"OpBranch {lbl_end}") self.emit(f"{lbl_end} = OpLabel") self.emit(f"{old} = OpPhi %uint {res_do} {done_lbl} {self.cu(0)} {pre_label}") @@ -3228,13 +3440,14 @@ def buffer_atomic_x2(self, op, kind, a, mods): self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") self.emit(f"{lbl_do} = OpLabel") ptr = self.tmp() - self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(addr)}") + self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(addr, 'rmw', 8)}") res = [] for w in range(2): p, r = self.tmp(), self.tmp() self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(w)}") self.emit(f"{r} = {self.BUF_ATOMICS[kind][0]} %uint {p} {self.cu(1)} {self.cu(0)} {vals[w]}") res.append(r) + res = [self.guard_zero(r) for r in res] self.emit(f"OpBranch {lbl_end}") self.emit(f"{lbl_end} = OpLabel") olds = [] @@ -3628,7 +3841,7 @@ def buffer_load_format(self, op, a, mods, fixed_fmt=None): self.emit(f"OpSelectionMerge {lbl_end} None") self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") self.emit(f"{lbl_do} = OpLabel") - ptr, host = self.tmp(), self.host_addr(aligned) + ptr, host = self.tmp(), self.host_addr(aligned, "load", lambda: self.guard_delta(need, step)) self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {host}") loaded = [] for i in range(5): @@ -3839,7 +4052,7 @@ def global_address(self, op, vaddr, saddr, mods): "global_load_sbyte_d16": (1, False, True, 0), "global_load_sbyte_d16_hi": (1, False, True, 1), "global_load_short_d16": (2, False, False, 0), "global_load_short_d16_hi": (2, False, False, 1)} - def global_byte_ptr(self, va): + def global_byte_ptr(self, va, kind="load"): """(pointer to the dword holding byte `va`, bit offset of that byte in it) for a ulong Xbox VA.""" lo, b3, b64, al, arr, p, sh = (self.tmp() for _ in range(7)) self.emit(f"{lo} = OpUConvert %uint {va}") @@ -3847,7 +4060,7 @@ def global_byte_ptr(self, va): self.emit(f"{b64} = OpUConvert %ulong {b3}") self.emit(f"{al} = OpISub %ulong {va} {b64}") # MoltenVK 1.4.0 needs an addressable array element for the Metal atomic operations (as buffer stores). - self.emit(f"{arr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(al)}") + self.emit(f"{arr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(al, kind)}") self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {arr} {self.cu(0)}") self.emit(f"{sh} = OpShiftLeftLogical %uint {b3} {self.cu(3)}") return p, sh @@ -3879,7 +4092,7 @@ def global_sub(self, op, a, mods): if k: va = self.tmp() self.emit(f"{va} = OpIAdd %ulong {full} {self.cl(k)}") - p, sh = self.global_byte_ptr(va) + p, sh = self.global_byte_ptr(va, "store" if store else "load") if store: byte, mk, inv, vs, t1, t2 = (self.tmp() for _ in range(6)) self.emit(f"{byte} = OpBitFieldUExtract %uint {old} {self.cu(16 * (half or 0) + 8 * k)} {self.cu(8)}") @@ -3948,7 +4161,8 @@ def global_mem(self, op, a, mods): self.emit(f"{b3} = OpBitwiseAnd %uint {lo32} {self.cu(3)}") self.emit(f"{b64} = OpUConvert %ulong {b3}") self.emit(f"{al} = OpISub %ulong {full} {b64}") - self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(al)}") + self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr " + f"{self.host_addr(al, 'load', lambda: self.guard_delta(self.sub_dwords(bits // 8, b3), None))}") self.emit(f"{p0} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(0)}") self.emit(f"{w} = OpLoad %uint {p0} Aligned 4") self.emit(f"{shb} = OpShiftLeftLogical %uint {b3} {self.cu(3)}") @@ -3975,7 +4189,7 @@ def global_mem(self, op, a, mods): vals.append(v) else: ptr = self.tmp() - self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full)}") + self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full, 'load', 4 * n)}") for i in range(n): p, v = self.tmp(), self.tmp() self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(i)}") @@ -3997,7 +4211,7 @@ def global_mem(self, op, a, mods): self.emit(f"OpBranchConditional {act} {lbl_do} {lbl_end}") self.emit(f"{lbl_do} = OpLabel") ptr = self.tmp() - self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full)}") + self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full, 'store', 4 * n)}") for i in range(n): p = self.tmp() self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(i)}") @@ -4543,7 +4757,7 @@ def buffer_store(self, op, a, mods, fixed_fmt=None): if words is not None and per is not None and len(words) > 1: # modes 0 and 3: every dword is stored only if it ends inside (measured: a store that straddles the edge # writes the dwords before it); a store past the end of the buffer is a host-memory hazard otherwise - ptr, host = self.tmp(), self.host_addr(addr) + ptr, host = self.tmp(), self.host_addr(addr, "store", lambda: self.guard_delta(len(words), step)) self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {host}") for i, w in enumerate(words): cond, lbl_do, lbl_end = self.tmp(), self.tmp() + "_do", self.tmp() + "_end" @@ -4570,7 +4784,8 @@ def buffer_store(self, op, a, mods, fixed_fmt=None): self.emit(f"OpSelectionMerge {lbl_end} None") self.emit(f"OpBranchConditional {act} {lbl_do} {lbl_end}") self.emit(f"{lbl_do} = OpLabel") - ptr, host = self.tmp(), self.host_addr(addr) + ptr, host = self.tmp(), self.host_addr(addr, "store", lambda: self.guard_delta( + len(words) if words is not None else self.store_element_dwords(plans[0], fixed_fmt), step)) self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {host}") if words is not None: for i, w in enumerate(words): @@ -4660,7 +4875,7 @@ def swiz2(arr): self.emit(f"{sh24} = OpBitwiseAnd %uint {sh8} {self.cu(24)}") # MoltenVK 1.4.0 needs an addressable array element for the Metal atomic operations. dword_arr = self.tmp() - self.emit(f"{dword_arr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(al)}") + self.emit(f"{dword_arr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(al, 'store')}") self.emit(f"{ap} = OpAccessChain %_ptr_PSB_uint {dword_arr} {self.cu(0)}") self.emit(f"{mk} = OpCopyObject %uint {self.cu((1 << (8 * size)) - 1)}") self.emit(f"{mks} = OpShiftLeftLogical %uint {mk} {sh24}") @@ -4703,7 +4918,7 @@ def swiz2(arr): self.emit(f"{sh24} = OpBitwiseAnd %uint {sh8} {self.cu(24)}") # MoltenVK 1.4.0 needs an addressable array element for the Metal atomic operations. dword_arr = self.tmp() - self.emit(f"{dword_arr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(al)}") + self.emit(f"{dword_arr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(al, 'store')}") self.emit(f"{ap} = OpAccessChain %_ptr_PSB_uint {dword_arr} {self.cu(0)}") self.emit(f"{one} = OpIEqual %bool {size} {self.cu(1)}") self.emit(f"{mk} = OpSelect %uint {one} {self.cu(0xFF)} {self.cu(0xFFFF)}") @@ -12795,7 +13010,7 @@ def store_slot(slot, val): self.emit(f"{addr} = OpBitwiseOr %ulong {sh} {l64}") self.emit(f"{full} = OpIAdd %ulong {addr} {o64}") ptr = self.tmp() - self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full)}") + self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full, 'load', 4 * n)}") self.uses_psb = True lim = None lim_val = None @@ -15217,7 +15432,14 @@ def u64(lo, hi): e(f"{off} = OpShiftLeftLogical %ulong {nm} {self.cl(3)}") e(f"{addr} = OpIAdd %ulong {base} {off}") ptr = T() - e(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(addr)}") + + def node_delta(): + """--address-guard: a box32 node (type 5) is read up to dword 27, the others up to dword 15.""" + b32, d = T(), T() + e(f"{b32} = OpIEqual %bool {ntype} {self.cu(5)}") + e(f"{d} = OpSelect %ulong {b32} {self.cl(4 * 28 - 1)} {self.cl(4 * 16 - 1)}") + return d + e(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(addr, 'load', node_delta)}") def ldw(i): pp, v = T(), T() @@ -16259,6 +16481,10 @@ def assemble(gen): types.append("%fn_desc_lookup = OpTypeFunction %uint " + " ".join(["%uint"] * 8)) if gen.tbuffer_norm_fns: types.append("%fn_tbuffer_norm = OpTypeFunction %uint %uint") + if gen.guard_fn: + # --address-guard: (heap_base, on, limit, table, offset, delta, sink) -> host address; no other function + # type of the module has this signature. + types.append("%fn_guard = OpTypeFunction %ulong %ulong %bool %ulong %ulong %ulong %ulong %ulong") if gen.fmt_fn or gen.fmt_enc_fn: types.append("%v4uint_fmt = OpTypeVector %uint 4") # dedupe_types merges it with any other uvec4 if gen.fmt_fn: @@ -16562,6 +16788,8 @@ def assemble(gen): gen.consts.setdefault(1, "%c1") gen.consts.setdefault(2, "%c2") fn += [pc_tail_chain("%ud_base_lo_p", 1, gen.cu), pc_tail_chain("%ud_base_hi_p", 2, gen.cu)] + HEAP_BASE_ENTRY + if gen.uses_guard: + fn += guard_entry(gen.cl, gen.cu) if gen.uses_codebase: fn += [pc_tail_chain("%ud_code_lo_p", 3, gen.cu), pc_tail_chain("%ud_code_hi_p", 4, gen.cu)] # A mesh shader reads its root arguments from the graphics window (user_data_dword, GRAPHICS_ROOT_DWORD). @@ -16687,7 +16915,7 @@ def assemble(gen): fn.append(f"{p} = OpAccessChain %_ptr_Function_uint {arr} {gen.cu(r)}") # Spill pointers last: a spilled value's type may be declared anywhere above. types += [f"{ptr} = OpTypePointer Function {t}" for t, ptr in gen.x_ptr_types.items()] - helpers = (gen.desc_fn or []) + (gen.fmt_fn or []) + (gen.fmt_enc_fn or []) + helpers = (gen.desc_fn or []) + (gen.fmt_fn or []) + (gen.fmt_enc_fn or []) + (gen.guard_fn or []) for function in gen.tbuffer_norm_fns.values(): helpers.extend(function) for function in gen.x_round_fns.values(): @@ -18165,6 +18393,8 @@ def barriers_under_control_flow(text): def _translate(path): + global GUARD_MODULE_ID + GUARD_MODULE_ID = fnv1a32(os.path.splitext(os.path.basename(path))[0]) info = parse_file(path) stage = stage_of(info["name"], path) if stage not in ("vs", "ps", "cs", "ms", "gs"): @@ -18885,11 +19115,19 @@ def translate(path): A workgroup barrier has to be reached by every invocation. NVIDIA waits for every thread, so one that an invocation never reaches stands the group until the driver resets the card (Xid 109, device lost). - A program that hangs costs a whole run; re-translating it costs one more pass offline.""" + A program that hangs costs a whole run; re-translating it costs one more pass offline. + + Only a multi-wave plan falls back. A single-wave workgroup (`inline_all`, `x_lanes == 64`) is one wave: + its barriers sit at the top level or under `%pc` guards, and `%pc` between blocks comes from scalar state + and votes read back from `%x_buf`, so all invocations take the same path; lane-local `%pc` exists only in + `emit_folded_region`'s `if (%active)` bodies, which emit no exchange and no barrier. The round loop is + also what drives RADV/ACO's spiller to tens of GB and the program 10-100 times slower (docs/design.md, + "Wave64 emulation: single-wave barrier fallback").""" global WAVE64_PLAN asm = _translate(path) gen = _translate.last_gen - if (gen is not None and getattr(gen, "emulate_plan", None) is not None + plan = getattr(gen, "emulate_plan", None) if gen is not None else None + if (plan is not None and plan.get("mode") != "inline_all" and barriers_under_control_flow(asm)): WAVE64_PLAN = False try: @@ -19461,6 +19699,8 @@ def shader_meta(g, asm, src_path=None, fssm_path=None): lay["params"] = {str(k): v for k, v in lay["params"].items()} m["mesh_compute"] = lay m["push_constant_bytes"] = lay["push_constant_bytes"] + if g.uses_guard: + m["address_guard"] = True # --address-guard: its accesses read the runtime's guard header if PC_TAIL_UBO: # --pc-tail-ubo: s0..s31 alone in push constants; the tail, if the shader reads it, in a uniform block. m["push_constant_bytes"] = 4 * USER_SGPRS @@ -19880,6 +20120,10 @@ def main(): help="keep only s0..s31 (128 bytes) in push constants and read the heap base, code base and " "--mesh-compute output address from a uniform block at set 1, binding 0 (metadata: pc_tail), " "for devices whose maxPushConstantsSize is below 144") + ap.add_argument("--address-guard", action="store_true", + help="check every heap_base + VA access against the runtime's page table of backed memory " + "(LEONIDA_ADDRESS_GUARD=1): an unbacked one reads 0 and drops its store instead of reaching " + "a wild GPU address (metadata: address_guard; docs/d3d12_vulkan.md, Address guard)") ap.add_argument("--descriptor-hash", choices=DESCRIPTOR_HASHES, default="fnv1a", help="bindless descriptor table hash shared with the runtime (default: fnv1a)") ap.add_argument("--descriptor-table", choices=DESCRIPTOR_TABLES, default="tagged", @@ -19919,8 +20163,9 @@ def main(): LOOP_LIMIT = a.loop_limit MAX_STRUCTURED_DEPTH = a.max_structured_depth global STRUCTURED, WAVE64_EMULATE, WAVE64_GRAPHICS, BARY_FALLBACK, TEXEL_OFFSET_FALLBACK, MESH_COMPUTE, FMA_KHR, SHADER_CLOCK, F16_HALVES, OPT_SPIRV - global PC_TAIL_UBO + global PC_TAIL_UBO, ADDRESS_GUARD PC_TAIL_UBO = a.pc_tail_ubo + ADDRESS_GUARD = a.address_guard global FMA_EXACT FMA_KHR = a.fma == "khr" SHADER_CLOCK = a.shader_clock == "khr"