upleb.uk

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

summaryrefslogtreecommitdiff
path: root/docs/d3d12_vulkan.md
diff options
context:
space:
mode:
Diffstat (limited to 'docs/d3d12_vulkan.md')
-rw-r--r--docs/d3d12_vulkan.md317
1 files changed, 298 insertions, 19 deletions
diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md
index 43886af30..45d4b4be4 100644
--- a/docs/d3d12_vulkan.md
+++ b/docs/d3d12_vulkan.md
@@ -680,9 +680,13 @@ side inwards:
680 covers a full 2048-sampler D3D12 heap plus room for literal and static S#s. 680 covers a full 2048-sampler D3D12 heap plus room for literal and static S#s.
681 - 2D images: up to 65536. 681 - 2D images: up to 65536.
682 - storage arrays: up to 4096 each, capped by their dimension's sampled array or by 256 for storage-only 1D arrays. 682 - storage arrays: up to 4096 each, capped by their dimension's sampled array or by 256 for storage-only 1D arrays.
683 - 2D-array images up to 16384, 3D and 1D images up to 4096 each (the title streams more cube maps, texture 683 - 2D-array, 3D and 1D images: up to 65536 each, as many as 2D, grown together (one count for the three while the
684 arrays and 1D lookups than the defaults hold: each distinct T# of one takes its own index, and a native boot 684 limits stop them short of it), so no dimension is favoured. A texture keeps an index for each distinct T# of
685 filled the 1024 2D-array and 256 1D indices during the story load). 685 it for as long as it lives, and which dimensions its textures have is the title's choice: a native boot
686 filled the default 1024 2D-array and 256 1D indices during the story load, and world runs filled the 4096 1D
687 indices of the sizes before this with 4092 T#s of 4090 live 1D textures. The bound is memory, not the
688 device's limits (RADV allows 8388606 sampled images): every element of every array is in each generation's
689 descriptor pool, used or not.
686 690
687 Growth leaves 64 descriptors of each limit to the other sets of a pipeline layout. It also stays within 691 Growth leaves 64 descriptors of each limit to the other sets of a pipeline layout. It also stays within
688 `maxPerSetDescriptors`, which never shrinks the default counts, because a layout past it may still be 692 `maxPerSetDescriptors`, which never shrinks the default counts, because a layout past it may still be
@@ -698,9 +702,18 @@ side inwards:
698 shader reads the fallback. `d3d12_descriptor_test` then fills each short array to its last index and checks that 702 shader reads the fallback. `d3d12_descriptor_test` then fills each short array to its last index and checks that
699 the next view and sampler are refused. 703 the next view and sampler are refused.
700 The MS arrays keep their default counts. On an RTX 5070 (driver 621.24, 1048576 of each type 704 The MS arrays keep their default counts. On an RTX 5070 (driver 621.24, 1048576 of each type
701 and 4000 samplers) the set has 65536 2D images, 3936 samplers, 16384 2D-array, 4096 3D and 4096 1D images and 705 and 4000 samplers) the set has 65536 2D, 2D-array, 3D and 1D images each, 3936 samplers and 4096 storage indices
702 4096 storage indices in each dimension: 152929 descriptors, 5-10 MiB at 32-64 bytes a descriptor. The device prints the counts it chose, and 706 in each dimension: 325729 descriptors with the MS pairs, 10-20 MiB at 32-64 bytes a descriptor. RADV (Mesa 26.3,
703 `bindless_sizing_test` checks the rules on synthetic limits. 707 the Raphael iGPU and the RX 7900 XTX) and llvmpipe get the same image counts and 4096 samplers. The device prints
708 the counts it chose (`bindless set:`), `bindless_sizing_test` checks the rules on synthetic limits, and
709 `vk_bindless_dimensions_test` reads 5000 live 1D, 2D-array and 3D images each through their indices in a set
710 sized from the device's own limits.
711 - A T# the title writes into a console descriptor heap that set 0 has no room for is refused, and counted in the
712 heap's `unbound T#s by reason` line, as `the bindless array of the T#'s dimension is full` (or `the bindless
713 storage arrays of the T#'s dimension are full` for a UAV whose dimension has free indices only above the shorter
714 storage arrays), not as `no view for the T#'s format or range`. The first such refusal of a dimension also logs
715 `a bindless image array is full; dimension N (name)` with the indices, the T#s and textures that hold them and how
716 many of those textures are still registered at their address (a texture's indices go back when it goes).
704 - An image view has one index in its dimension (2D, 2D array, 3D, 1D, 2DMS, 2DMS array or 1D array), shared by the 717 - An image view has one index in its dimension (2D, 2D array, 3D, 1D, 2DMS, 2DMS array or 1D array), shared by the
705 bindings for that dimension. The runtime adds sampled-image bindings in pairs for 2DMS and 2DMS array: 718 bindings for that dimension. The runtime adds sampled-image bindings in pairs for 2DMS and 2DMS array:
706 20/21 for floating-point and normalized color, 22/23 for unsigned integers, and 24/25 for signed integers. 719 20/21 for floating-point and normalized color, 22/23 for unsigned integers, and 24/25 for signed integers.
@@ -961,7 +974,8 @@ The compute path, end to end:
961 primitive overestimation no greater than `0.5 - 1/512` pixels, leaving half a minimum grid step within the 974 primitive overestimation no greater than `0.5 - 1/512` pixels, leaving half a minimum grid step within the
962 Tier 1 uncertainty bound. `ConservativeRaster=ON` uses overestimate mode with zero extra overestimation, 975 Tier 1 uncertainty bound. `ConservativeRaster=ON` uses overestimate mode with zero extra overestimation,
963 including unbound-attachment variants. OFF keeps the ordinary pipeline. Missing support, unknown modes, 976 including unbound-attachment variants. OFF keeps the ordinary pipeline. Missing support, unknown modes,
964 wireframe and non-triangle PSOs are refused; conservative TIR (`ForcedSampleCount != 0`) remains `E_NOTIMPL`. 977 wireframe and non-triangle PSOs are refused (a mesh PSO needs no topology type: its module has to output
978 triangles, `conservative_raster::mesh_outputs_triangles`); conservative TIR (`ForcedSampleCount != 0`) remains `E_NOTIMPL`.
965 Tier 2 additionally requires `degenerateTrianglesRasterized` and primitive overestimation plus half a 979 Tier 2 additionally requires `degenerateTrianglesRasterized` and primitive overestimation plus half a
966 device subpixel step no greater than 1/256 pixel. Other eligible devices retain Tier 1. The standalone 980 device subpixel step no greater than 1/256 pixel. Other eligible devices retain Tier 1. The standalone
967 device does not expose Tier 3: the Xbox `SV_InnerCoverage` input mapping has not been confirmed. See 981 device does not expose Tier 3: the Xbox `SV_InnerCoverage` input mapping has not been confirmed. See
@@ -1301,7 +1315,8 @@ and any validation error fails them.
1301- `indirect_clamp_test`: the `ExecuteIndirect` argument clamp pass itself (section 4.7), with no game files: every 1315- `indirect_clamp_test`: the `ExecuteIndirect` argument clamp pass itself (section 4.7), with no game files: every
1302 argument kind (draw, draw indexed, dispatch, mesh dispatch) and the counted variants, in-range records 1316 argument kind (draw, draw indexed, dispatch, mesh dispatch) and the counted variants, in-range records
1303 bit-identical, garbage records bounded, records and counts past `max_command_count` empty, and the per-batch work 1317 bit-identical, garbage records bounded, records and counts past `max_command_count` empty, and the per-batch work
1304 budget saturating; clean SKIP without a Vulkan device. 1318 budget saturating; dispatch records bounded by the device's `maxComputeWorkGroupCount` (70 000 x 1 x 1 kept and run
1319 where the device allows it, cut and counted where it does not); clean SKIP without a Vulkan device.
1305- `d3d12_gcl8_test`: the public `ID3D12GraphicsCommandList8` surface: `QueryInterface` for its IID, 1320- `d3d12_gcl8_test`: the public `ID3D12GraphicsCommandList8` surface: `QueryInterface` for its IID,
1306 `OMSetFrontAndBackStencilRef(1, 2)` with the recorded values, and the reference count around the query. It 1321 `OMSetFrontAndBackStencilRef(1, 2)` with the recorded values, and the reference count around the query. It
1307 creates only an allocator and a list, so it needs no GPU or Vulkan loader. 1322 creates only an allocator and a list, so it needs no GPU or Vulkan loader.
@@ -1697,6 +1712,21 @@ The copies:
1697 cannot fit between the title's address reservations can use a separate mapped buffer. The buffer's device address 1712 cannot fit between the title's address reservations can use a separate mapped buffer. The buffer's device address
1698 must fit as a positive 47-bit offset from the arena base. The same window cap and dirty-page refresh apply. 1713 must fit as a positive 47-bit offset from the arena base. The same window cap and dirty-page refresh apply.
1699 `LEONIDA_STREAM_BUFFER_WINDOWS=0` requires the window to fit in the arena. 1714 `LEONIDA_STREAM_BUFFER_WINDOWS=0` requires the window to fit in the arena.
1715- **What the GPU wrote goes back.** The same return copy serves slot-133 shadows (a buffer the driver would not
1716 import, a compute result the title reads again): the ranges are recorded through the alias of the buffer's pages and
1717 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
1718 the copy and the title would never see it ([#1537](https://github.com/ubiquitarianism/leonida/issues/1537), the
1719 `WRITE_INVALID` stop at the world start). Every title range a submission's bindings reach is kept, and the next
1720 refresh copies those ranges from the copy to the title's pages *before* it copies the pages forward, so a page the
1721 title itself wrote in between keeps the title's newer bytes and its GPU result is dropped. The copy back asks the
1722 write watch first (the refresh's own asking comes after it, so a hot page's last answer is a submission old), passes
1723 over pages whose mapping changed, that a kernel write may be filling or that xmem maps at another address too, and
1724 writes only the 256-byte pieces where the copy differs from the title's bytes: a read-only view writes nothing and
1725 its pages stay guarded. Up to 8,192 ranges and 64 MiB a submission (a V# has no read/write bit, so every view
1726 reached is compared; 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
1727 of the submission that will use it and copied back only when the context reports that ticket retired, so a range
1728 another submission is still writing is never read half done. A queue held deep (console ordering) can leave batches
1729 waiting: past 64 of them the oldest go back without their ticket, logged once.
1700- A **window that is refused** (the budget is spent, the arena is full, or the pages are not committed yet) is backed 1730- A **window that is refused** (the budget is spent, the arena is full, or the pages are not committed yet) is backed
1701 by a persistent geometry copy of exactly the requested range (`LEONIDA_GEOMETRY_MB`) instead; when no copy can be 1731 by a persistent geometry copy of exactly the requested range (`LEONIDA_GEOMETRY_MB`) instead; when no copy can be
1702 made either, the view is written with **no base and no records** — loads return 0 and stores are dropped. A raw 1732 made either, the view is written with **no base and no records** — loads return 0 and stores are dropped. A raw
@@ -1719,6 +1749,19 @@ The copies:
1719 encoding reuses only an independently established geometry view. An explicit table or placed SRV can 1749 encoding reuses only an independently established geometry view. An explicit table or placed SRV can
1720 establish that view. The Vulkan memory probe reports populated views, payload and reserved bytes, 1750 establish that view. The Vulkan memory probe reports populated views, payload and reserved bytes,
1721 upload totals, cap refusals and allocation failures. 1751 upload totals, cap refusals and allocation failures.
1752 - **Where the copies live**: device-local memory through the BAR by default. `LEONIDA_GEOMETRY_HOST=1` puts them
1753 in system memory outside VRAM (write-back where the device offers a cached host type, `=2` write-combined),
1754 as VIctory keeps its copies of title memory (approach only). In a world run on the RX 7900 XTX the copies held
1755 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,
1756 so a geometry-heavy pass can take longer; measure frame time with and without it before making it a default.
1757 - **When a copy goes**: a view is retired when its title range is freed, decommitted or unmapped. A remap of
1758 physical pages retires nothing: the copies follow the new pages through the refresh. A retired
1759 view leaves the lookups at once, its alias ranges and translated heap slots are invalidated, its stream-pool
1760 extent is forgotten, and its memory is freed only after every ExecuteCommandLists replay in progress at the
1761 retirement has recorded its submissions and those have completed (`kAfterExecutes`). Before it leaves the
1762 refresh it is copied once more from its pages if they are still readable (a heap block freed in memory that
1763 stays committed). The next view of the range makes a new copy.
1764 `geometry_views_test` cases 14-16 cover this without a GPU.
1722- **Which pages changed** since the last refresh: where xmem reserved the title's memory with `MEM_WRITE_WATCH` 1765- **Which pages changed** since the last refresh: where xmem reserved the title's memory with `MEM_WRITE_WATCH`
1723 (`XMemVirtualAlloc`'s ordinary regions and the title's `VirtualAlloc` reservations, not placeholders or 1766 (`XMemVirtualAlloc`'s ordinary regions and the title's `VirtualAlloc` reservations, not placeholders or
1724 physical-page windows), the kernel says (`GetWriteWatch` with reset, its answers kept for every copy over the page: 1767 physical-page windows), the kernel says (`GetWriteWatch` with reset, its answers kept for every copy over the page:
@@ -1730,6 +1773,15 @@ The copies:
1730 write-fault handler waits for the trackers' locks while the faulting thread may hold the process heap's lock (the 1773 write-fault handler waits for the trackers' locks while the faulting thread may hold the process heap's lock (the
1731 title's `XMemAlloc` blocks are `_aligned_malloc`'s), so the state changed under those locks allocates from a heap of 1774 title's `XMemAlloc` blocks are `_aligned_malloc`'s), so the state changed under those locks allocates from a heap of
1732 the runtime's own (`leonida::host_heap`), never the process heap. 1775 the runtime's own (`leonida::host_heap`), never the process heap.
1776- **What the GPU wrote into a copy stays** until the title changes the bytes under it. Some pages are copied at
1777 every refresh without a sign that the title wrote them (mapped at two addresses, left writable, reopened with the
1778 64 KiB around a written page, write-watched or pinned); copied whole, they overwrote a value a compute program had
1779 stored in the copy for the next frame with the title's unchanged bytes, so it read back as the title's old value
1780 every other frame. `ShadowPages` keeps a 64-bit sum per 256-byte piece of the bytes it copied last
1781 (`runtime/src/shadow_keep.h`) and copies a piece only when the title's bytes differ; a piece zeroed because its page
1782 went away is copied again in full once it comes back. Limit: a title that writes the same bytes again to reset a
1783 value the GPU changed is not seen (that needs the GPU's writes to reach the title's pages). `LEONIDA_SHADOW_KEEP=0`
1784 copies every page as before.
1733- **Only the title's memory** gets a copy: the blocks and ranges the xmem shims hand the title (`XMemAlloc`, 1785- **Only the title's memory** gets a copy: the blocks and ranges the xmem shims hand the title (`XMemAlloc`,
1734 `XMemAllocDefault`, `XMemVirtualAlloc`, the title's `VirtualAlloc`). An address anywhere else, the runtime's or a 1786 `XMemAllocDefault`, `XMemVirtualAlloc`, the title's `VirtualAlloc`). An address anywhere else, the runtime's or a
1735 host DLL's memory included, is left as it was and counted, as is an arena VA or a buffer the layer made. 1787 host DLL's memory included, is left as it was and counted, as is an arena VA or a buffer the layer made.
@@ -1805,6 +1857,178 @@ fit on smaller PC GPUs. This is a product requirement, not something the layer c
1805compatible single-mip RGBA8 2D textures (section 4.2). Other descriptions have fully allocated backing. Wider 1857compatible single-mip RGBA8 2D textures (section 4.2). Other descriptions have fully allocated backing. Wider
1806texture coverage and the game's use of tile streaming remain open. 1858texture coverage and the game's use of tile streaming remain open.
1807 1859
1860**Diagnostics for descriptors the title builds itself** (all off by default, logging only unless said otherwise):
1861
1862- `LEONIDA_UNKNOWN_TSHARP=1`: one line for each distinct base address a title-written T# names with no texture there
1863 (its shape, the tiling bits and whether the address is title memory), up to 300 addresses, and every 8192 such
1864 lookups a summary by format, type and tiling.
1865- `LEONIDA_UNBACKED_VSHARP=1`: the buffer V#s `fix_vsharp` writes empty because nothing backs their base; one line for
1866 each of the first 120 distinct bases and every 8192 a summary by 4 GiB range of the base.
1867- `LEONIDA_UPLOAD_LOG=1` (`d3d12_xs_device.cpp`): each upload chunk (CPU base, device address, size) and the first 96,
1868 then every 8192nd, `AllocateUploadMemory` result as an offset into its chunk.
1869- `LEONIDA_UPLOAD_ALIAS=1` (an experiment, changes behaviour): enters each upload chunk's CPU range in the title VA
1870 table, so a V# the title wrote with the CPU pointer `AllocateUploadMemory` handed it is rewritten to the chunk
1871 instead of left empty. A chunk below the arena needs `LEONIDA_IMPORT_BELOW_ARENA=1` as well.
1872
1873#### Address guard (`LEONIDA_ADDRESS_GUARD=1`, `rdna2spirv.py --address-guard`)
1874
1875**Prototype, off by default.**
1876
1877**Why.** The layer rewrites the addresses it can see: root views, the V#s it writes, and the V#s the title writes into
1878shader-visible heaps. It writes an empty V# when nothing backs an address (above). The translator checks a V#'s
1879record count but not its base. Any other address becomes `heap_base` plus an arbitrary value:
1880- a V# a shader builds in SGPRs from data;
1881- a raw `global_`/`flat_` address (530 of the 26,503 shaders of package 1.0.2.1, 69 of the 2,684 pipeline-library
1882 programs);
1883- a stale or offset-like value.
1884
1885On RADV such an access page-faults. Two RX 7900 XTX runs (Mesa 26.3.1, under Wine) ended with the same sequence:
1886- a `gfxhub` fault from client TCP with PERMISSION_FAULTS 0x3;
1887- a compute-ring timeout and "MES failed to respond";
1888- a MODE1 reset ("VRAM is lost").
1889
1890Both faults were 4.8 GiB and 20 GiB above `heap_base`, past the arena's end.
1891
1892"Inside the arena" is not the right bound. Several buffers are legitimately outside it, at a positive offset from
1893`heap_base` (a negative one with `LEONIDA_IMPORT_BELOW_ARENA=1`):
1894- geometry copies;
1895- upload and readback buffers;
1896- imported title memory;
1897- separate window buffers.
1898
1899The guard checks each access against what the runtime actually backs. An access that fails reads 0 and drops its
1900store, so a wild address never reaches the GPU. The overall process follows VIctory
1901([`crates/victory-gpu/src/memory.rs`](https://github.com/marvisak/victory), GPL-3.0). Its page table of 64 KiB pages
1902routes every computed address, and memory no copy holds reads 0 and takes no writes. The structure below is our own:
1903VIctory's table names descriptor views, this one is a bitmap over device addresses.
1904
1905**Structure: a two-level page table of 4 KiB pages over the 48-bit offset space, behind an arena compare.** The
1906check works on the heap offset, the sign-extended 48-bit value `Gen.host_addr` adds to `heap_base`:
1907- **Level 1:** 65,536 words indexed by offset bits 47..32. Each word names the level-2 block of one 4 GiB chunk.
1908- **Level 2:** blocks of 32,768 words, one bit per 4 KiB page (bits 31..12).
1909- **Two fixed blocks:** block 0 is empty and block 1 is full; allocated blocks start at 2.
1910- **Size:** the table is a host-visible buffer of its own, 256 KiB plus 128 KiB per block (8.25 MiB for 62 blocks).
1911
1912Why this structure:
1913- **Pages of 4 KiB** are the GPU's own mapping granularity. A page any byte of a backing touches is mapped as a whole,
1914 so marking pages outward is exact for faults. A 64 KiB page would mark memory that may not be mapped.
1915- **Level 1 by 4 GiB chunk** covers the whole signed 48-bit space (negative offsets index from 0x8000 up). A real run
1916 touches a handful of chunks, so the table stays small.
1917- **Other structures cost more per access.** A sorted range table needs a binary search: about 10 dependent loads for
1918 a thousand backings, against 2 here. A coarse region bitmap plus a fine range table needs a search in the fine part.
1919- **The arena needs no lookup.** It is one fully bound `VkBuffer`, so any offset below its size passes on a compare.
1920 That is the common case: descriptor heaps, default-heap buffers and windows in the arena.
1921
1922**The header.** It sits at arena offset `0x70000`, after the zero page and the quad indices, and holds:
1923- a 64-bit magic (`"LGUARD01"`);
1924- the arena's size (the compare's limit);
1925- the table's address minus `heap_base`;
1926- a refusal count and the last refused offset, which the shaders write.
1927
1928Two sinks follow the header: `0x71000` (zero area, what refused loads read) and `0x78000` (dump area, where refused
1929stores and atomics go). None of `[0x70000, 0x80000)` is handed out. With `LEONIDA_ARENA_NULL_MB` the range lies in the
1930null region, so its offset never moves. `runtime/src/address_guard.h` and `tools/address_guard.py` (the Python
1931reference) hold the format.
1932
1933**Each access.** `Gen.host_addr` takes the access kind (load, store or atomic) and its span. Under `--address-guard`
1934it calls one function per module, `%guard_fn`, which is straight-line at the call site, so no caller's block
1935structure changes. The function computes `end = offset + span - 1` and then decides:
1936- **Passes on a compare:** the runtime's guard is off (no magic), or `offset` and `end` are both below the limit. The
1937 result is `heap_base + offset`. The cost is a 64-bit add, two 64-bit compares and a select.
1938- **Otherwise, a lookup:** the bits of the pages of `offset` and of `end`. That is two independent pairs of dependent
1939 32-bit loads (level 1, then level 2).
1940- **Refused:** an access whose bits are not both set adds 1 to the header's count, writes its offset, and goes to the
1941 zero area (a load) or the dump area (a store or atomic), at its offset within its page. Alignment is kept, and every
1942 span fits inside a sink.
1943- **Atomics** run on the dump area, and their returned value is replaced by 0 (`Gen.guard_zero`). The CAS loops (float
1944 min/max, inc/dec) end there too, as on any other memory.
1945
1946The entry block reads the header's first six dwords once per invocation, from the arena, so that read is always
1947backed. When the base is uniform, as for `s_load`, `s_buffer_load` and a V# from SGPRs plus a uniform offset, the
1948compiler keeps the whole check scalar: one check per instruction, not per lane. A per-lane address (`global_` with a
1949VGPR address, `offen`/`idxen`) is checked per lane, and the slow path runs only for lanes outside the arena.
1950
1951**What is checked.** Every `heap_base` access goes through `host_addr`:
1952- buffer loads and stores (dword, sub-dword, typed, format; swizzled spans are computed at run time);
1953- `global_` loads, stores, sub-dword and atomics;
1954- buffer atomics, `_x2` included;
1955- `s_load` and `s_buffer_load`;
1956- the BVH node reads of `image_bvh*_intersect_ray` (span by node type).
1957
1958These are not checked:
1959- images (T#s go through the hash table, not an address);
1960- LDS;
1961- the `--mesh-compute` output buffer (a runtime address);
1962- `s_getpc` code reads.
1963
1964The translator does not translate `flat_` instructions (they raise `Unsupported`), so none reaches memory today. A
1965translation added later must go through `host_addr` like `global_` does.
1966
1967**Keeping the table current.** The spans are the same backings the console heap pass's backed table uses
1968(`update_gpu_backed`):
1969- every `gpu_backings` entry outside the arena (upload and readback buffers, imports, slot-133 buffers, windows
1970 outside the arena);
1971- the geometry copies' blocks;
1972- the separate window buffers' blocks.
1973
1974`update_address_guard` runs in the queue's `before_execute`, after the heap refresh, the windows and the geometry
1975copies. It differs from that table in four ways:
1976- It rebuilds whenever `backing_generation` or a block layout changed, with no 100 ms limit, because a backing made
1977 since the last submission must not read 0.
1978- It writes only the words that changed, level 2 before level 1.
1979- A chunk keeps its block for good, so a submission still in flight never reads a block that now means another chunk.
1980- When the 62 blocks run out, a new chunk gets the full block (unchecked, as without the guard), and that is logged.
1981
1982A release clears its bits at the next submission. D3D12 forbids releasing memory the GPU still uses, so only a wild
1983access in flight at that moment could still pass.
1984
1985**Cost per access:**
1986- **Fast path:** about 8 scalar or vector ALU operations.
1987- **Outside the arena:** about 40 operations and 4 loads, from a table small enough to stay in cache.
1988- **Per invocation:** 6 uniform header loads.
1989- **Per submission (runtime):** nothing until a backing changes, then a rebuild of the used blocks (128 KiB each)
1990 and a diff.
1991
1992**Switches.**
1993- `--address-guard` records `"address_guard": true` in `index.json`.
1994- `LEONIDA_ADDRESS_GUARD=1` makes the runtime reserve the range, create the table and write the header.
1995- Either alone does nothing: a guarded module on a runtime without the guard finds no magic, and every access passes
1996 after one compare.
1997- Without the flag the module is byte for byte what it was.
1998
1999**What a run with the guard shows.**
2000- One line when the device is made: `[rt] d3d12: address guard on ...`.
2001- At most one line a second: `[rt] d3d12: address guard: N access(es) refused so far (+k), the last at heap offset
2002 0x...`. Each refusal is a wild access that would have reached the GPU. The offset says where to look (above the
2003 arena's end, as in the two faults).
2004- A run that reset the GPU before should keep going, with wrong pixels where a refused access mattered.
2005
2006**Risks and open points.**
2007- A refused access that mattered (a backing the layer never registered) now reads 0 instead of faulting. That is
2008 silent apart from the count.
2009- An access is checked as a whole. A multi-dword load whose first dwords are inside a V# and a backing, but whose
2010 last dword is past both on an unbacked page, reads 0 in full.
2011- The table is read through the GPU's caches. A page whose bit changes while a submission is in flight can be seen
2012 either way by that submission.
2013- Sparse buffers outside the arena are guarded only if they are registered as backings.
2014
2015**Checked:**
2016- `tests/semantic/test_address_guard.py`: the fixture `cs_address_guard` with the guard on, with it off at run time
2017 and without the flag, through `spirv_mini_interp`; the kind and span of each instruction family; the table model;
2018 the constants shared by the translator, the runtime and `tools/address_guard.py`.
2019- `runtime/test/address_guard_test.cpp`: the page table, incremental writes, negative offsets, wrap, chunks and
2020 overflow.
2021- `scripts/run_address_guard_gpu_test.py`: the fixture on a 2 MiB heap whose table backs one page outside the
2022 "arena". Every address it touches is inside the buffer, so no run can fault. With the guard on, the refused loads
2023 read 0 although memory is there, the store and the atomic land in the dump area and the count is 6. With the guard
2024 off, the same module reads that memory. It passed on lavapipe (Mesa 26.3.1).
2025- Corpus (package 1.0.2.1, 2026-11-26):
2026 - `--shard 0/8` of the shaders: 3,313 translated and 3,313 `spirv-val`-valid, with the guard and without.
2027 - The pipeline library: 2,683 of 2,684 translated and valid, with the guard and without (the same one fails
2028 either way).
2029 - Without the flag, every module is byte for byte the same as before the change.
2030 - With it, the SPIR-V grows by 1.8% (shaders) and 1.6% (library).
2031
1808### 3.4 Descriptor heaps and the bindless model 2032### 3.4 Descriptor heaps and the bindless model
1809 2033
1810The game can use D3D12 descriptors in three ways, and the layer must handle all of them: 2034The game can use D3D12 descriptors in three ways, and the layer must handle all of them:
@@ -1874,8 +2098,18 @@ The game can use D3D12 descriptors in three ways, and the layer must handle all
1874 heap pointers read by the mesh and pixel stages after a rebind. `d3d12_mesh_test` checks the recorded dwords 2098 heap pointers read by the mesh and pixel stages after a rebind. `d3d12_mesh_test` checks the recorded dwords
1875 for a vertex draw, a resource-only rebind, a signature ending at s30 and one on the s0 layout. 2099 for a vertex draw, a resource-only rebind, a signature ending at s30 and one on the s0 layout.
1876 Set `LEONIDA_GRAPHICS_DIRECT_HEAPS=0` to restore the previous draw arguments. 2100 Set `LEONIDA_GRAPHICS_DIRECT_HEAPS=0` to restore the previous draw arguments.
1877 Missing console V# backing leaves a settled zero descriptor. Every 32 submissions a heap probes up to 2101 Missing console V# backing leaves a zero descriptor in the copy. Each V# half of a console resource heap's copy
1878 eight of these slots in round-robin order, including independent UAV-counter failures. 2102 (the buffer V# and the UAV counter) has a record in host RAM of what it resolved to: the title's base and span,
2103 the device address its copy names, and whether it resolved or waits (`src/console_heap_slot_records.h`, written
2104 only by `fix_console_slot`). Two indexes find the halves near a range, by base and by target, per power-of-two
2105 span class and 64 KiB-or-larger granule. Releases (a backing, a title-window or geometry block), alias ranges
2106 removed or replaced (`TitleVaAliases` tells its listeners as it happens, `forget_copy` included) and additions
2107 (a backing, an alias range, title memory) go on an unbounded per-device list; at the next submission each heap
2108 fixes again exactly the slots whose records a change touches: a release or removal every half naming it, an
2109 addition the waiting halves over it. Nothing walks the heap or reads the copy for this. A zeroed range, a slot
2110 the title rewrote and a heap destroyed drop their records. `console_heap_slot_records_test` checks that a release
2111 of a buffer 10 of 60,010 slots name looks at those 10, and compares the copy with a full re-resolution through
2112 random writes, releases, additions and alias changes.
1879 Console resource heap copies and shader-visible CBV/SRV/UAV heaps with at least 65,536 slots request 2113 Console resource heap copies and shader-visible CBV/SRV/UAV heaps with at least 65,536 slots request
1880 64 MiB of zeroed padding after their last descriptor. `LEONIDA_HEAP_GUARD_MB` sets the padding in MiB 2114 64 MiB of zeroed padding after their last descriptor. `LEONIDA_HEAP_GUARD_MB` sets the padding in MiB
1881 (0 disables it). When arena space is tight, allocation can fall back to the heap alone. Only indices 2115 (0 disables it). When arena space is tight, allocation can fall back to the heap alone. Only indices
@@ -2413,13 +2647,33 @@ Pipeline creation:
2413 merges into the offline seed. `LEONIDA_DIRECT_SESSION_CACHE=0` also uses a merge when only the session exists. 2647 merges into the offline seed. `LEONIDA_DIRECT_SESSION_CACHE=0` also uses a merge when only the session exists.
2414 The files must match the Vulkan vendor, device and pipeline-cache UUID. Vulkan supplies an opaque snapshot. 2648 The files must match the Vulkan vendor, device and pipeline-cache UUID. Vulkan supplies an opaque snapshot.
2415 Replacing part of the previous file would corrupt it. 2649 Replacing part of the previous file would corrupt it.
2416 `LEONIDA_PIPELINE_CACHE_BYTES` caps session writes (256 MiB by default, zero disables the session file). 2650 `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
2651 the session file).
2652 The session file can't keep a crashed run's compiles: it is written at teardown and at the optional checkpoints
2653 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
2654 described below. Every graphics build first asks the corpus cache with
2655 `VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT`. A pipeline the corpus doesn't have is built against a
2656 second cache, seeded from `pipeline_cache.heavy.bin` next to `pipeline_cache.bin`, so that cache holds only the
2657 corpus's misses.
2658 A build that takes at least `LEONIDA_HEAVY_PIPELINE_CACHE_MS` (500 by default) marks the heavy cache for writing.
2659 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
2660 one, through the same staging file and rename as the session cache. A crash therefore loses at most the last 20 s
2661 of slow builds, and the next launch starts with the rest. A write that fails, or whose
2662 `vkGetPipelineCacheData` returns anything but `VK_SUCCESS` (`VK_INCOMPLETE` means the cache grew after the size
2663 query, so the blob is truncated), leaves the previous file in place and the cache dirty: it is tried again 5 s
2664 later, the delay doubling with each failure in a row up to 2 min, so the cache is not left unsaved until teardown
2665 and a write that keeps failing does not spin. At device teardown the thread stops, and the cache is
2666 written if any build went into it. Fast builds are kept that way: without an offline seed every build is a miss,
2667 so they no longer reach `pipeline_cache.session.bin`. `LEONIDA_HEAVY_PIPELINE_CACHE_MS=0` turns the heavy cache off, and with it the
2668 `pipelineCreationCacheControl` feature unless `LEONIDA_PIPELINE_COMPILE=cache-only` asks for it. A cache-only create
2669 (`cache-only`) is left as it is.
2417 `LEONIDA_SKIP_COMPUTE=<part of a name>[,<part>...]` (`all`: every compute program) never builds the matching 2670 `LEONIDA_SKIP_COMPUTE=<part of a name>[,<part>...]` (`all`: every compute program) never builds the matching
2418 compute programs and drops their dispatches, direct and indirect; the first dropped dispatch of each is logged. 2671 compute programs at play and drops their dispatches, direct and indirect; the first dropped dispatch of each is
2419 It is a way past a program that hangs the GPU while the program or its input is fixed, not a fix. 2672 logged. It is a way past a program that hangs the GPU while the program or its input is fixed, not a fix.
2673 `--precompile-pipelines` (below) builds them anyway unless it is given `--skip-listed`.
2420 `LEONIDA_STARTUP_CACHE_CHECKPOINTS=1` also schedules a snapshot after a successful pipeline build, 2674 `LEONIDA_STARTUP_CACHE_CHECKPOINTS=1` also schedules a snapshot after a successful pipeline build,
2421 at most once per 120 seconds. It starts on the compile worker when queued builds have drained and the device 2675 at most once per 120 seconds. It starts on the compile worker when queued builds have drained and the device
2422 has no active builds. These snapshots have an additional 512 MiB ceiling. The driver fills a mapped staging 2676 has no active builds. The driver fills a mapped staging
2423 file directly. A successful snapshot atomically replaces the session. An interrupted write preserves the 2677 file directly. A successful snapshot atomically replaces the session. An interrupted write preserves the
2424 previous cache; the next launch removes unheld staging files older than ten minutes. 2678 previous cache; the next launch removes unheld staging files older than ten minutes.
2425 While the compute warm-up has builds queued that idle checkpoint never starts, and a boot that ends by a crash, 2679 While the compute warm-up has builds queued that idle checkpoint never starts, and a boot that ends by a crash,
@@ -2455,7 +2709,8 @@ Pipeline creation:
2455 folders can share one; the file names and the driver's checks keep a pipeline from one build from being taken 2709 folders can share one; the file names and the driver's checks keep a pipeline from one build from being taken
2456 for another's. 2710 for another's.
2457 `gta6rt --precompile-pipelines [--threads N] [--big-threads N] [--all] [--smallest-first] [--limit N] 2711 `gta6rt --precompile-pipelines [--threads N] [--big-threads N] [--all] [--smallest-first] [--limit N]
2458 [--min-bytes N] [--max-bytes N] [--filter PART]... [--list]` fills the journal ahead of play, with no game: it 2712 [--min-bytes N] [--max-bytes N] [--filter PART]... [--skip-listed] [--list]` fills the journal ahead of play, with
2713 no game: it
2459 creates the Vulkan device as `--run` does (so the same environment gives the same journal names and driver keys: 2714 creates the Vulkan device as `--run` does (so the same environment gives the same journal names and driver keys:
2460 LEONIDA_SHADERS, LEONIDA_PIPELINE_CACHE_DIR, and LEONIDA_DEVICE_FAULT/LEONIDA_AFTERMATH, whose diagnostics config 2715 LEONIDA_SHADERS, LEONIDA_PIPELINE_CACHE_DIR, and LEONIDA_DEVICE_FAULT/LEONIDA_AFTERMATH, whose diagnostics config
2461 makes other pipelines) and builds every compute entry of the library through the dispatch path 2716 makes other pipelines) and builds every compute entry of the library through the dispatch path
@@ -2465,6 +2720,19 @@ Pipeline creation:
2465 4 threads: modules of 3.6-5.8 MB took 46-145 s each, 12 in 312 s, about 3.5 GB of host memory each while in the 2720 4 threads: modules of 3.6-5.8 MB took 46-145 s each, 12 in 312 s, about 3.5 GB of host memory each while in the
2466 driver (14.5 GB peak for four). Graphics pipelines are not covered: they are built at a title's draw from its PSO 2721 driver (14.5 GB peak for four). Graphics pipelines are not covered: they are built at a title's draw from its PSO
2467 description and the bound formats, and take milliseconds. 2722 description and the bound formats, and take milliseconds.
2723 `LEONIDA_SKIP_COMPUTE` does not narrow the build: it is a play-time setting, players run the pre-compile with the
2724 game's environment, and a program left out here would stay out of the journal after the list is shortened. The run
2725 says how many entries the list names and builds them; `--skip-listed` leaves them out on purpose. The last line
2726 counts what was built (compiled, or found in a cache), what was journaled already or being built by another
2727 process, what failed, and what was left out and why: by `--skip-listed`, not buildable on this device (no SPIR-V,
2728 set-0 bindings without a bindless set, workgroup memory over the limit), or filtered out (`--filter`, the size
2729 bounds, `--limit`). The 89-167 s per program behind the skip list of the large `library/` programs came from
2730 wave64-emulated packs. Measured with a native wave64 pack on an RX 7900 XTX (RADV, Mesa 26.3.1, Wine): all 721
2731 programs of 2 MiB or more built, 360 of them in 170 s on 32 threads, 2.5-32 s each, the largest (13 MiB) in 28.5 s
2732 alone, at a peak of 14 GiB of RAM for the process. With all of them in the journal and no skip list, two world runs
2733 took them all from the journal (none built in the game) and ended as runs with the skip list do, in an idle-queue
2734 device loss or a stop with the GPU idle ([running.md](running.md#settings-every-platform-needs)); whether their
2735 output is correct is not measured.
2468 `LEONIDA_COMPILE_HELPER=1` (`shims/d3d12_compile_helper.h`) keeps first-ever compiles out of the title's process: 2736 `LEONIDA_COMPILE_HELPER=1` (`shims/d3d12_compile_helper.h`) keeps first-ever compiles out of the title's process:
2469 the driver's locks, which a long `vkCreateComputePipelines` holds and a `vkQueueSubmit` of the same process waits 2737 the driver's locks, which a long `vkCreateComputePipelines` holds and a `vkQueueSubmit` of the same process waits
2470 for, are per process. A compute build of `LEONIDA_COMPILE_HELPER_MIN_BYTES` or more (128 KiB) with no journal file 2738 for, are per process. A compute build of `LEONIDA_COMPILE_HELPER_MIN_BYTES` or more (128 KiB) with no journal file
@@ -4098,11 +4366,22 @@ Not implemented yet:
4098 `LEONIDA_SKIP_COMPUTE`) or mistranslates leaves whatever the memory held: a dispatch of billions of groups or a 4366 `LEONIDA_SKIP_COMPUTE`) or mistranslates leaves whatever the memory held: a dispatch of billions of groups or a
4099 draw of four billion vertices runs until the host resets the display driver. One small compute pass per 4367 draw of four billion vertices runs until the host resets the display driver. One small compute pass per
4100 `ExecuteIndirect` call copies the active records into device-local scratch with their values bounded - 2^24 4368 `ExecuteIndirect` call copies the active records into device-local scratch with their values bounded - 2^24
4101 vertices or indices, 2^26 vertex instances (count times instances), 65 535 groups per dimension, 2^20 groups per 4369 vertices or indices, 2^26 vertex instances (count times instances), the device's `maxComputeWorkGroupCount` groups
4102 dispatch and a 2^27-unit work budget per call that saturates through an atomic compare-and-swap - and writes an 4370 per dimension for a dispatch (65 535 for a mesh dispatch), 2^20 groups per dispatch and a 2^27-unit work budget per
4371 call that saturates through an atomic compare-and-swap - and writes an
4103 empty record past `min(count, max_command_count)` and past the budget, and the clamped count word a `*Count` draw 4372 empty record past `min(count, max_command_count)` and past the budget, and the clamped count word a `*Count` draw
4104 then reads (so the count is at most `maxDrawCount`, VUID-vkCmdDrawIndirectCount-countBuffer-02717). The indirect 4373 then reads (so the count is at most `maxDrawCount`, VUID-vkCmdDrawIndirectCount-countBuffer-02717). A draw record
4105 command reads that scratch. A draw emits the pass before its rendering scope opens: `vkCmdCopyBuffer` and a 4374 of 2^23 vertices or indices an instance or more is a slot the title has not filled: it runs empty and charges
4375 nothing (RT-INDIRECT-DRAW-UNFILLED-COUNT). Before, each was cut to 2^24 and charged that, so eight of them used up
4376 the budget and every later draw in the list ran empty; a census in a VIctory fork found 90 such records in one
4377 list. A dispatch record's groups per dimension follow the device (#2230): the title's tile
4378 passes ask for 67 440 groups in x at 2560x1440 (found in the VIctory-Belobug-AMD fork of VIctory,
4379 `crates/victory-gpu/src/indirect.rs`), RADV runs 2^32 - 1 in x in one dispatch, and the cut at 65 535 dropped the
4380 last 1 905 tiles of the pass. A device that allows less (llvmpipe: 65 535) still gets the record cut at its
4381 limit: running the rest would take more dispatches with a group-ID base the translated shader does not read. The
4382 counters' `indirect clamp dispatch:` line (every 10 s while dispatch records are clamped) gives the records, those
4383 wider than 65 535 in x, the widest x that ran and those cut at the device's limits, so a run shows which case it
4384 is. The indirect command reads that scratch. A draw emits the pass before its rendering scope opens: `vkCmdCopyBuffer` and a
4106 memory barrier with a transfer access are not allowed inside a dynamic-rendering scope. The records are 4385 memory barrier with a transfer access are not allowed inside a dynamic-rendering scope. The records are
4107 bit-identical to the application's when they are within the limits, the argument and count buffers are left 4386 bit-identical to the application's when they are within the limits, the argument and count buffers are left
4108 untouched, and the scratch comes from a per-submission pool (`vulkan_scratch.h`) that a list with many indirect 4387 untouched, and the scratch comes from a per-submission pool (`vulkan_scratch.h`) that a list with many indirect