diff --git a/.github/workflows/runtime.yml b/.github/workflows/runtime.yml index e355ca32be..4af6bfa221 100644 --- a/.github/workflows/runtime.yml +++ b/.github/workflows/runtime.yml @@ -29,6 +29,7 @@ on: - "tools/cfg_structure.py" - "tools/conformance/**" - "tools/cpu_ref.py" + - "tools/descriptor_sources.py" - "tools/f32_fuzz.py" - "tools/file_mode.py" - "tools/first_light.py" @@ -38,6 +39,7 @@ on: - "tools/gen_bcpack_runtime_tables.py" - "tools/gen_d3d12_stubs.py" - "tools/gfx10_formats.json" + - "tools/heap_index_census.py" - "tools/lane_masks.py" - "tools/mc_command.py" - "tools/mesh_compute_vs.py" @@ -81,6 +83,7 @@ on: - "tools/cfg_structure.py" - "tools/conformance/**" - "tools/cpu_ref.py" + - "tools/descriptor_sources.py" - "tools/f32_fuzz.py" - "tools/file_mode.py" - "tools/first_light.py" @@ -90,6 +93,7 @@ on: - "tools/gen_bcpack_runtime_tables.py" - "tools/gen_d3d12_stubs.py" - "tools/gfx10_formats.json" + - "tools/heap_index_census.py" - "tools/lane_masks.py" - "tools/mc_command.py" - "tools/mesh_compute_vs.py" diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 3084bf06b8..cbf15a9b12 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -886,7 +886,42 @@ The compute path, end to end: D3D-448); the compute bind point uses it. - **GPU address arena** (section 3.3, when the device has `bufferDeviceAddress`): one host-visible, device-addressable buffer, 256 MiB by default (`LEONIDA_ARENA_MB`, at most 4095 MiB, so every VA fits 32-bit - table pointers). + table pointers). `LEONIDA_ARENA_MB` bounds the address range; with sparse binding it is not memory. + - **Backing blocks** (`runtime/src/arena_backing.h`). Where the device has `sparseBinding`, + `sparseResidencyBuffer`, `residencyNonResidentStrict`, a sparse address space at least as large as the arena and + a queue with the sparse binding bit to spare (`pick_arena_bind_queue`: RADV's sparse-only family), the arena is a + sparse buffer and its memory comes in units bound in 2 MiB blocks: a block is bound when the first allocation + needs it, before the allocation is handed out, and unbound once its last allocation is released and the GPU has + passed the retire ticket of the release (`submitted_retire_ticket() + 1`, checked at the start of every + `ExecuteCommandLists` against `completed_retire_ticket()`), then its memory is freed. Binds go to that queue alone + and are waited for there, so a bind never sits behind a submission that waits for a fence the CPU signals later. + - **Only with signed V# offsets.** A driver can place a sparse buffer anywhere relative to ordinary ones: RADV + (Mesa 26.3.1, natively and under Wine) gives sparse buffers a range of their own 64 TiB above them + (0xffffc00100200000 against 0xffff800100010000), so with a sparse arena every buffer outside it (geometry copies, + title windows and shadows outside it, upload buffers) lies below heap_base, at a negative offset. A shader that + sign-extends a V#'s 48-bit base (docs/design.md, "Heap-relative buffer device addresses") reaches it, since RADV + hands out addresses from one 2^47 half of the 48-bit space, so any two lie within 2^47 of each other. One that + zero-extends does not. The device counts each loaded module's `vsharp_base_sign_extended` marker + (`VsharpBaseCensus`, `runtime/src/shader_library.h`) and logs + `V# bases: signed offsets from heap_base (N of N modules sign-extend)`. The arena is sparse only when every module + sign-extends (or `LEONIDA_IMPORT_BELOW_ARENA=1` says to read bases signed). With older modules it stays one + allocation and one line says why. `TitleBufferWindows::shader_reachable` checks every block made outside the + arena against the same range when it is made, and a block it refuses is logged with both addresses. + `d3d12_title_va_game_device` and `d3d12_geometry_views_game_device` run the title-memory tests on the device the + game makes (with the bind queue), so on RADV their windows and geometry copies are read through negative offsets. + - No allocation crosses a unit: one no larger than a block stays inside one block, a larger one takes whole blocks + of its own. So each allocation is one run of one mapping, and the CPU reaches an arena offset through + `DeviceState::arena_host()` (one table read; null, with a line, for a range without memory), or + `ArenaBacking::with_host()` for an offset the caller does not hold (value writes, `read_arena`). A D3D12 heap in the + arena lends its unit's memory to reserved resources' tiles at the heap's place in that unit. + - The block size is measured, not tuned: a world run had about 5,000 live arena allocations averaging 160 KiB + (790 MiB live, 990 MiB peak end, 4,095 MiB asked). 2 MiB is a multiple of the 64 KiB sparse page, keeps a 4 GiB + arena within the 4,096 memory objects some Windows drivers allow (2,048 at most, about 500 at that peak), and is + amdgpu's large page. + - Without those capabilities (llvmpipe: a 2 GiB sparse address space and one queue) one allocation backs the whole + arena, as before, through the same accessors. `arena_backing_test` (CPU) and `arena_sparse_gpu_test` (a real + device; skipped without sparse binding) check both. The arena's line at device release (and with a console + heap's log) reads `GPU address arena: bound N MiB now (peak P, U units of 2 MiB blocks, sparse)`. - It is also no larger than the device's `maxBufferSize` (Vulkan 1.3) and, counting the buffer's memory requirement, `maxMemoryAllocationSize` (Vulkan 1.1), whichever is smaller (`runtime/src/arena_size.h`). When a limit cuts the request, one log line names the limit and the size used. `arena_size_test` (CPU) checks the @@ -1732,7 +1767,9 @@ The copies: cover (the title remaps its pool frames instead), and the tracker follows the pages. A tracker the window shared with a copy still live keeps its extent (a retirement never splits one). A window that cannot fit between the title's address reservations can use a separate mapped buffer. The buffer's device address - must fit as a positive 47-bit offset from the arena base. The same window cap and dirty-page refresh apply. + must lie within reach of a V# base from the arena base: a positive offset below 2^47, or, when every loaded shader + sign-extends the base, anywhere within 2^47 on either side (`TitleBufferWindows::shader_reachable`). 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 @@ -2140,15 +2177,90 @@ The game can use D3D12 descriptors in three ways, and the layer must handle all Missing console V# backing leaves a zero descriptor in the copy. Each V# half of a console resource heap's copy (the buffer V# and the UAV counter) has a record in host RAM of what it resolved to: the title's base and span, the device address its copy names, and whether it resolved or waits (`src/console_heap_slot_records.h`, written - only by `fix_console_slot`). Two indexes find the halves near a range, by base and by target, per power-of-two - span class and 64 KiB-or-larger granule. Releases (a backing, a title-window or geometry block), alias ranges + only by `fix_console_slot`). Two indexes, by base and by target, hold the halves by their exact range: halves + naming the same range share one group (with a resolved and a waiting list, each half's place in it kept, so a + half moves or goes in O(1)), and the groups are ordered by start per power-of-two class of their length. A change + visits exactly the halves whose range overlaps it; an addition visits the waiting halves whose range starts inside + it, since a V# resolves only through a backing, alias range, copy or title memory that holds its base (title memory + is told as the merged range that holds it); each half once per index in a submission, however many changes name + it. The groups compared to find them are those plus, for a removal, per class, the ones that start less than one + class length before it and end before it. + Releases (a backing, a title-window or geometry block), alias ranges removed or replaced (`TitleVaAliases` tells its listeners as it happens, `forget_copy` included) and additions (a backing, an alias range, title memory) go on an unbounded per-device list; at the next submission each heap fixes again exactly the slots whose records a change touches: a release or removal every half naming it, an - addition the waiting halves over it. Nothing walks the heap or reads the copy for this. A zeroed range, a slot + addition the waiting halves whose base it holds. Nothing walks the heap or reads the copy for this. A zeroed range, a slot the title rewrote and a heap destroyed drop their records. `console_heap_slot_records_test` checks that a release - of a buffer 10 of 60,010 slots name looks at those 10, and compares the copy with a full re-resolution through - random writes, releases, additions and alias changes. + of a buffer 10 of 60,010 slots name looks at those 10, that a 40-byte release among 300,000 slots packed into 74 + blocks of 64 KiB looks at the 3 it overlaps, and compares the copy with a full re-resolution through random + writes, releases, additions and alias changes. + A title-written T# has a record too, under the exact base address it names (`bind_title_image` looks textures up + by that address, or by the other view of texture-pool memory): bound, or waiting for a texture there (no texture, + or one whose type, samples, mips, layers, image or views do not fit the T#), or waiting for room in its bindless + array. A texture registered, replaced or published at an address (`note_image_address`, a title texture's + placement, a streamed texture's image), or gone from it (`forget_image`, a placement removed), goes on the same + list, and the next submission fixes again exactly the T#s naming that address; freed bindless entries fix the + T#s waiting for room. Nothing looks at a waiting T# otherwise: before, a round robin tried the waiting slots again + for 500 µs a submission (`LEONIDA_CONSOLE_RETRY_US`), which in world runs took tens of submissions to come round + and counted every look as a T# "naming no texture" again. A texture that goes takes its T#s out of the descriptor + hash table at once (`forget_image_views_locked`), so a shader reading the slot gets the fallback; the slot then + waits for the next texture at the address, which a texture streamed out and back in needs. A V# half whose + geometry copy was refused for lack of room waits for room the same way: the slots are fixed again when geometry + copies are freed (`GeometryViews::free_generation`), not only when something is added over their base. + A T# with no texture at its address is counted by what the address is (`unbound T#s by reason` in the heap's log + line): title memory, a texture of the layer's own that is gone, an address whose low 32 bits are one of the + layer's texture addresses with other high bits (the texture there with the T#'s shape, with another, or gone), + or none of these. The heap's `slot records` line gives the T#s recorded, those waiting, the T# fixes that left + one waiting and the refills since the last line. `d3d12_tsharp_refill_test` samples, through the last of 60,001 + waiting slots, a texture made after the T# was written, at the first submission after it appears. T#s are a third + index of the same kind, keyed by their address: a texture change visits exactly the T#s recorded for that address, + and the records waiting for room are kept in a list per kind, which a change saying room was made visits whole. + The title rebuilds T#s of the layer's textures from 32 bits: the unbound T#s of one world run named 0x7f0000021400 + for the layer's 0x100021400, and 0x2ef600 for 0x1002ef600 (bits 32-39 clear, 0x7f or 0 in bits 40-47). Such an + address outside the title's memory names the layer's texture with the same low 32 bits (`tsharp_texture_key`, + while fewer than 2^24 texture addresses were handed out): `bind_title_image` looks it up there, and the T# waits + under that address, where the texture's creation is announced. Before, such T#s waited under the title's form, + which no arrival names, and the run showed no refill at all; `d3d12_tsharp_refill_test` writes both forms before + the texture exists and expects them bound at the first submission after it appears. + A V# the title rewrote whose range another half of the heap waits for is answered as that half was + (`ConsoleHeapSlotRecords::waiting_answer`), without walking the alias table, backings, geometry copies and title + memory again: a waiting record is fixed again by every change that could let it resolve, so while it waits its + answer stands. The changes noted since the submission's list was taken are applied to the heap first + (`sync_slot_changes`), and the submission's own changes before the rewritten slots, so an answer is never older + than a change that concerns it. In one world run 70% of the 2,100 rewritten V# halves a submission resolved to + nothing at about 9 µs each. + **A console resource heap read in place.** When the page mirror holds every page of the heap (a reservation xmem + placed in the mirror's range), there is no copy of the whole heap and no page tracker of its own. Its pages have + two homes. At the title's address (the mirror) the home is the title's bytes exactly, as for any page: the title + keeps plain data inline in its heap pages and points V#s at it (run 64w3: four words a compute program reads as + its sizes, `[512 256 1280 720]`), so a V# or a title pointer into those pages must read what the title wrote, and + GPU stores there are written back as for any page. At the table address, below 4 GiB of the arena (25,865 of + 26,503 shaders keep 32 bits of a descriptor-table pointer), each page has a filtered copy of its own + (`TitleMirror::alias`: a second home per page, bound there in the same batches as the mirror's binds, so the one + wait orders a reader of either address), in a range of whole arena blocks with no arena memory behind it; the null + slots after the heap are that range's rest, unbound, which reads zero. The filter writes only that copy + (`filter_heap_page`), refilled when a 256-byte piece of the title's page changed (the upload's sums compare the + title's bytes with the title's) or write-back changed it. Each slot that changed since it was last filtered, or + that a change of the address space touched, is filtered: a V# half whose base lies in the arena, in the mirror + (named to it as any reader names title memory) or in a buffer of ours is kept as the title wrote it + (`reachable_as_written`); a half nothing holds is null whole, all four words (a shader reading it as a V# would + fault at heap_base + its base: the "resolved to nothing" classes of the heap's log line), never three of four; a + T# is kept as written and bound; words that decode as neither are null, as a shader taking them as a V# would + fault. The filter runs inside the mirror's fills, under its lock, so it takes no other lock of ours: a V# the mirror + does not hold reads null until the heap's refresh resolves it as a copied slot was, and a T# is bound there too, + its dword 6 in the copy then taking the bindless index word (`tsharp_index_word`, docs/design.md "Bindless index in + the T#"; 0, the fallback, from the filter until then and while the T# waits; the title's dword 6 stays in its + bytes), each result written into the copy unless the title rewrote the slot meanwhile (`finish_in_place`). Lock + order: `console_heap_mutex`, then the mirror's, then the change list's. Table pointers reach shaders in user SGPRs, + which the layer sets to the table address (`console_descriptor_table_va`) for every module; a table pointer a + shader loads from memory is the title's address and reads the title's bytes there: V#s as written (the mirror + holds what they name, or the read faults as on any unfiltered memory) and T#s without the index word, which a + module of the index-word contract reads as the fallback. A heap the mirror does not hold (a device without the + mirror, memory outside its range) is copied as before. `d3d12_heap_in_place_test` checks that the GPU reads the + filtered slots at the table address while the title's bytes never change, that a rewrite reaches the GPU at the + next refresh, that inline data reads exactly through a V# while the table reads it filtered, that a GPU store into + the heap goes back, and that the null slots read zero; `title_mirror_hooks_test` checks the alias without a GPU + and `vk_heap_alias_test` a second binding on a device. Console resource heap copies and shader-visible CBV/SRV/UAV heaps with at least 65,536 slots request 64 MiB of zeroed padding after their last descriptor. `LEONIDA_HEAP_GUARD_MB` sets the padding in MiB (0 disables it). When arena space is tight, allocation can fall back to the heap alone. Only indices @@ -2174,7 +2286,9 @@ The layer's descriptor model: which is the assumption to verify. If it uses an opaque format, the layer must translate at bind time. - At execution, for each bound table (or the whole bound heap when direct indexing is enabled), the layer walks the declared descriptor range with the heap's stride, parses each T#/S#, and ensures a bindless entry exists: - - image T# → `VkImageView` (format, view type, mip range, array layers) → bindless image index; + - image T# → `VkImageView` (format, view type, mip range, array layers) → bindless image index, which the layer + writes into dword 6 of the T# where shaders read it (the console heap copy's slot, or the layer's own heap), with + the arrays it is bound in (`docs/design.md`, "Bindless index in the T#"); the hash table keeps the key as written; - sampler S# → `VkSampler` (filter, address modes, LOD, compare, anisotropy) → bindless sampler index; - buffer V# / CBV → no Vulkan view; the descriptor already contains a console VA the shader dereferences. - **Buffer UAVs.** `CreateUnorderedAccessView` on a buffer writes a V# in the first 16 bytes of the slot (the rest of @@ -4931,29 +5045,53 @@ order the submissions were recorded. The list keeps the last 64, so its numbers recorded more than that. **AMD breadcrumbs.** NVIDIA's checkpoints say where a queue stopped; RADV has none. With `LEONIDA_DEVICE_MARKERS=1` -as well, on a device with `VK_AMD_buffer_marker`, every numbered dispatch writes its `seq` into its queue's slot of -one persistent buffer twice (`src/vulkan_device_markers.h`): at top of pipe before the dispatch (started) and at -bottom of pipe after it (finished), with `vkCmdWriteBufferMarker2AMD` (or `vkCmdWriteBufferMarkerAMD` without -synchronization2). A bottom-of-pipe write waits for all earlier work on the queue, so the finished value is the last -dispatch before which everything had completed, and the queue's dispatches after it up to the started value are the -ones the GPU began and did not finish. The oldest of them is the likely hang. The buffer is host-visible and -coherent, in system memory where the device has such a type, so it can still be read after a device loss. The loss -and stall reports then add lines like these (the shader names are made up): +as well, on a device with `VK_AMD_buffer_marker`, every numbered dispatch and every draw writes its `seq` into its +queue's slot of one persistent buffer twice (`src/vulkan_device_markers.h`): at top of pipe before the work +(started) and at bottom of pipe after it (finished), with `vkCmdWriteBufferMarker2AMD` (or +`vkCmdWriteBufferMarkerAMD` without synchronization2). Draws and dispatches share the numbering, so the 64-entry +dispatch list has gaps where draws ran. A bottom-of-pipe write waits for all earlier work on the queue, so the +finished value is the last item before which everything had completed, and the queue's items after it up to the +started value are the ones the GPU began and did not finish. The oldest of them is the likely hang. The buffer is +host-visible and coherent, in system memory where the device has such a type, so it can still be read after a device +loss. The loss and stall reports then add lines like these (the shader names are made up): ``` [rt] device-markers: AMD buffer markers, read after the device loss; best-effort: only what the GPU wrote before it stopped, and a reset may have lost the last writes [rt] device-markers: queue 0000000012345678 (compute) finished seq=1203 started seq=1205; started, not finished: 1204 1205 +[rt] device-markers: finished: seq=1203 execute=88 queue=0000000012345678 (compute) list=0 command=16 shader=cs_example_b [rt] device-markers: likely hang: seq=1204 execute=88 queue=0000000012345678 (compute) list=0 command=17 shader=cs_example_a -[rt] device-markers: queue 00000000123456a0 (direct) idle: finished seq=1199, nothing started after it; next submitted seq=1206 not started (waiting, or behind other work of the queue) +[rt] device-markers: in flight: seq=1205 execute=88 queue=0000000012345678 (compute) list=0 command=18 shader=cs_example_a +[rt] device-markers: queue 00000000123456a0 (direct) finished seq=1199 started seq=1200; started, not finished: 1200 +[rt] device-markers: finished: seq=1199 execute=89 queue=00000000123456a0 (direct) list=1 command=1 shader=cs_example_c +[rt] device-markers: likely hang: seq=1200 execute=89 queue=00000000123456a0 (direct) list=1 command=7 draw=indexed count=3480 instances=1 pipeline=vs vs_example ps ps_example pass=draw 4 since command 2 (3 colours + depth, 1920x1080) [rt] device-fault: submitted dispatch seq=1204 execute=88 queue=0000000012345678 (compute) list=0 command=17 shader=cs_example_a groups=64,1,1 <- likely hang (device-markers) ``` -A separate history of the last 16,384 dispatches names the likely hang when it has already left the 64-entry list. -An idle queue (finished equals started) is not called hung: if it still has dispatches submitted, it was waiting -on a semaphore or stuck in work that is not a dispatch (a draw, a copy). The values are what the GPU wrote before -it stopped; after a loss and a ring reset they may be stale, so read them as a pointer, not a proof. The cost with -the switch on is two marker writes per dispatch (a command-processor write and an end-of-pipe event, no wait) plus -one entry in the history; with it off nothing is recorded. Without the extension, or without +A draw line gives its kind (`indexed`, `vertices`, `mesh`, with `-quads` for a quad list and `-indirect` or +`-indirect-count` for arguments from a buffer) and counts (vertex or index count and instances, a mesh dispatch's +`groups`, an indirect draw's `max` records and `stride`), its pipeline named as the `LEONIDA_GPU_PROFILE` lines name +it (`gpu_profile::label`: each stage's tag and entry name, or `pso 0x...`), and its place among the draws of the list +to the same targets: `pass=draw 4 since command 2` is the fourth draw to these targets since command 2. An idle queue +gets a `not started:` line for its next submitted item. When `VK_EXT_device_fault` reports an address, a +`device-fault: last started draw (device-markers):` line per queue follows the address lines, with `(not finished)` +or `(finished)` and `<- likely hang` when it is the queue's likely hang. + +Granularity: a pair per draw, as per dispatch. The replay opens a rendering scope per draw, so the started write goes +before the draw's helper passes (quad index expansion, indirect clamp; a hang there is named as the draw's) and the +finished one after the scope ends, both outside a render pass instance. The extension allows them inside one too +(`vk.xml`: `renderpass="both"`, and conditional rendering does not apply), which the legacy graphics ExecuteIndirect +path, drawing in the caller's scope, uses; `vk_device_markers_test` writes a pair inside an open scope under +validation. RADV (`radv_CmdWriteMarkerToMemoryAMD`) emits the cache flushes already pending, then a top-of-pipe write +as one write-confirmed COPY_DATA (the command processor waits for that write only) and any other stage as one +bottom-of-pipe EOP event (no wait): at most 24 dwords per draw, against the hundreds the draw's own scope and state +take. A pair per run of one pipeline would be cheaper but could not name the draw, so it was not chosen. + +A separate history of the last 65,536 dispatches and draws (about 6 MiB) names the likely hang when it has already +left the 64-entry list, and names every draw. An idle queue (finished equals started) is not called hung: if it +still has work submitted, it was waiting on a semaphore or stuck in work that is neither (a copy, a barrier). The +values are what the GPU wrote before it stopped; after a loss and a ring reset they may be stale, so read them as a +pointer, not a proof. The cost with the switch on is two marker writes per dispatch and per draw plus one entry in +the history; with it off nothing is recorded. Without the extension, or without `LEONIDA_DEVICE_FAULT`, the runtime logs one `device-markers: unavailable` line and runs as before. For a local pre-submit inspection, also set `LEONIDA_COMPUTE_INPUTS` to comma-separated shader name fragments and @@ -4989,6 +5127,12 @@ store, load, mesh, geometry and BVH tests; this layer is the other half. ### 5.1 Descriptor hash table details +Since the T# index word (`docs/design.md`, "Bindless index in the T#") the table serves only what the word does not +reach: every S#, and the T#s a translated module cannot trace to a heap slot (1,062 of the 439,415 T# operands of +the 1.0.2.1 corpus, in 108 modules). A T# loaded from a heap the layer writes carries its index and kind in dword 6 +and is never looked up. Every T# key is still inserted, as the title wrote it: a T# outside the heaps is found by +those words. + The exact layout the shader reads (from `tools/rdna2spirv.py`, `desc_lookup`): ``` diff --git a/docs/d3d12_xs_console_abi.md b/docs/d3d12_xs_console_abi.md index 986acf6802..fc3c75a17b 100644 --- a/docs/d3d12_xs_console_abi.md +++ b/docs/d3d12_xs_console_abi.md @@ -258,15 +258,29 @@ The runtime's model: a gate fence that is signalled once memory compares true. The Vulkan layer holds the queue's later work behind that wait without blocking the submitting thread (`src/queue_holds.h`). The pump only decides; a second thread, the releaser, signals the gates, because that Signal runs the work the layer held behind them (the held - submission, the shadow refresh, a deferred Present), and the pump keeps landing writes and timing gates out - meanwhile. -- A gate opens after `LEONIDA_VALUE_WAIT_TIMEOUT_MS` (default 200) whatever memory holds, counted from when the - gates before it on its queue opened, and logged once per address. An address that timed out three times in a row - (the last 256 addresses are counted) gets 4 ms. Once four gates in a row timed out, so does every wait for an - address no wait was ever met for, until a gate cut short is met within its 4 ms; a wait cut short that memory - meets within the rest of the full timeout gives its address the full timeout from then on. - `LEONIDA_LIST_VALUES=0` drops both methods, as before. After `stop_list_values` (the process is ending) nothing - new is landed or opened. + submission, the shadow refresh, a deferred Present), and the pump keeps landing writes and looking at gates + meanwhile. Other queues' work, which does not wait for the gate, goes on. +- A gate is held until memory compares true, however long that takes: there is no timeout. It goes without its + value only when nothing else can make progress (`src/list_value_progress.h`): the releaser is idle, no title + `ExecuteCommandLists` is in progress, and no write group or remap of the pump runs on the GPU (one whose Signal the + layer holds behind a gate, a relayed wait or a title fence is not running). Then, for a queue's first held gate: + - **cycle**: what would write its value is held behind a gate that depends, through further held writes, on its + own queue: released at once; + - **present**: the title has presented since the gate was held (the present stands behind the held work): the + oldest gate that no held write could meet goes; a gate whose writer is held behind another queue's gate waits for + that one, so a chain unwinds in order; + - **stalled**: the title has made no queue call for 2 s and the gate has stood as long: its threads wait for the + held work (a deadlock through the title's CPU). + At device loss every gate goes. Each release is logged with the gate, its queue, the wait (address, comparison, + reference, memory) and the reason; a released wait is then watched for 10 s and, if memory meets it, counted and + logged with how much later (`met after release`). The periodic `list values so far` line counts gates held, met and + released unmet by reason, and names the oldest gate still held. The rule follows VIctory-Belobug-AMD's queue line + (`crates/victory-gpu/src/queue/behind.rs` `step`, `queue.rs` `release_held`: a held wait is forced only at a present + with nothing else runnable). The fixed 200 ms timeout (`LEONIDA_VALUE_WAIT_TIMEOUT_MS`) and its 4 ms demotions are + gone: at the slow frames of a Linux world run (seconds a frame), 14-63 gates per run timed out with memory one + step below a rising reference, the writer's value not there yet. `LEONIDA_LIST_VALUES=0` drops both methods, as + before. After `stop_list_values` (the process is ending) nothing new is landed or opened, and a held gate does not + delay it. - Queue slot 31 (`CopyPageMappingsBatchX`, section 4) waits at most 16 ms for the queue's earlier work. Work held behind a gate takes longer: the remap is then deferred to the releaser, which runs it once the queue's write fence passes the call's point and only then opens a gate the queue's later work waits on, so the GPU sees the diff --git a/docs/design.md b/docs/design.md index 175e633105..ae88ee5bf2 100644 --- a/docs/design.md +++ b/docs/design.md @@ -302,7 +302,7 @@ How the generated SPIR-V expects the runtime to work: | Null sources in 64-bit integer VALU compares | `v_cmp` and `v_cmpx` relations `eq`, `ne`, `lt`, `le`, `gt`, `ge` on `u64` and `i64` read `null` as the 64-bit value 0 in either source, like immediate `0`. Register pairs and immediates retain their existing semantics; `v_cmp` writes the active lane's comparison to VCC/SGPR, while `v_cmpx` narrows EXEC without changing VCC. Source: RDNA2 ISA special operand `null` reads zero; LLVM `llvm-mc -mcpu=gfx1013` accepts the encoding. CPU-checked by `tests/semantic/test_vcmp64_null_src.py` (both sources, signed/unsigned ordering, equality, e32/e64, EXEC and inactive lanes); **not GPU-verified, no corpus count**. | | `s_load_dword*` with `vcc` 64-bit base pointer | SMEM `s_load_dword*` accepts `vcc` (`{vcc_lo, vcc_hi}`, hardware `s[106:107]`) as its 64-bit base pointer in `Gen.scalar_load`, loading `%vcc` as the low dword and `%vcc_hi` as the high dword; `s_buffer_load*` still requires a 4-dword V# and rejects 2-dword `vcc`. Source: RDNA2 ISA SMEM `SBASE` encoding (`sbase = 53` -> `s[106:107] = vcc`). Confirmed by corpus count over the 2,684-shader pipeline library compute corpus (79 shaders use `vcc` as the `s_load` base: 72 `s_load_dwordx4 sgpr, vcc`, 6 `s_load_dwordx8 sgpr, vcc`, 1 `s_load_dwordx4 slist, vcc`; all 79 translate and pass `spirv-val` under `--wave64-emulate`) and CPU-checked by `tests/semantic/test_sload_vcc_base.py` (`spirv-as` + `spirv-val`) and `tests/semantic/test_scalar_mem_smem.py` (both halves and the resulting addresses); **not GPU-verified**: the synthetic `runtime/test/shaders/cs_smem_vcc_base.asm` reads back eight seeded words through the pair in the standard GPU runner. | | Execution model | One invocation = one lane. Compute and mesh waves derive lanes from the workgroup-local index; other stages use the subgroup lane. A wave = a subgroup, so cross-lane ops (`ds_swizzle`, `v_permlane*`, `v_readlane`/`v_writelane`, `v_mbcnt`) become subgroup shuffles. Wave32 pixel shaders split a 64-lane physical subgroup into two logical waves: lane IDs are `SubgroupLocalInvocationId & 31`, shuffle sources retain the current half (`& 32`), and ballots/votes use that half's 32-bit word. A value the translator knows is uniform (the bindless descriptor index) is read from the half's first running lane, never from a fixed lane, which need not be running (SHADER-1016). Other stage/wave combinations still require subgroup size == wave size or wave64 emulation. **Requires subgroup size == wave size** (wave32 maps directly onto NVIDIA GPUs; wave64 shaders need a 64-wide subgroup or emulation). `v_readlane_b32`/`v_writelane_b32` mask the lane select with 63 in wave64 (`S1[5:0]`) and 31 in wave32 (`S1[4:0]`); until SHADER-52 both used 63, so a wave32 select ≥ 32 pointed past a 32-wide subgroup. GPU-checked with `cs_w32_lane_wrap.asm` (lane 40 → 8). For the fragment-half rule, `ps_bitmask_perm` produced 4096/4096 exact pixels on an AMD Radeon RX 5700 XT; Vulkan reported a default subgroup size of 64 (range 32..64), but does not permit pinning fragment subgroup size on this device. CPU semantic tests compare a 64-lane wave32 pixel subgroup against two 32-lane subgroups for reads/writes, permutations, ballots, and votes. | -| DPP | VOP1/VOP2 `_dpp` applies to src0. DPP16 controls (`quad_perm`, `row_shl/shr/ror/share/xmask/mirror/half_mirror`) and DPP8 (`dpp8` + `fi`) select the source lane, then `row_mask` (one bit per 16-lane row) and `bank_mask` (one bit per 4-lane bank) decide which destination lanes update. A lane whose row/bank is off is not written. A source lane outside the row is invalid: `bound_ctrl` 1 uses 0 as src0, otherwise the lane is not written. Hardware applies src0 float modifiers (`neg`/`abs`) after the invalid-lane zero selection, so `-src0` on an invalid lane yields `-0.0f` (`0x80000000`) and `\|src0\|` yields `+0.0f` (HW-DPP-NEG-INVALID-LANE, measured on RDNA3 (gfx1101) RX 7800 XT, RDNA2 not measured; tested by `tests/semantic/test_dpp_bound_ctrl_modifiers.py`). A source lane inactive under EXEC is used when `fi` is 1; otherwise `bound_ctrl` decides. DPP8 always writes an enabled lane: `fi` 1 reads the inactive source, `fi` 0 uses 0. DPP16/8 never leaves its 16/8-lane group, so this is exact on every subgroup at least that wide; under `--wave64-emulate` the exchange goes through the workgroup buffer like the other cross-lane ops. GPU-checked with `runtime/test/shaders/cs_dpp*.asm` on an RTX 3070 and hardware-measured on an RX 6800. On an RX 6700 XT (gfx1031), `tools/crosslane_fuzz.py --dpp-sweep --oracle hw` checks every DPP16 control × `bound_ctrl` × `fi`, every `row_mask`/`bank_mask` pair and the DPP8 selects in wave32 and wave64: 14,412 cases, all matching these rules (BUILD-162, `docs/shader_validation.md` FUZZ-7). The ballot of the source lanes' EXEC bits and the shuffle are each stored to a Function variable of their own (`Gen.eager`): SPIRV-Cross (MoltenVK) inlines a single-use result into the expression that uses it, which put the ballot on the right of a short-circuiting `&&` and the shuffle in a ternary's arm, so lanes out of their row skipped the ballot and row_shr:1's lane 1 found lane 0 inactive (`cs_dpp_ops` on MoltenVK; SHADER-529). A store is a statement every lane runs. For native FI=0, the source-lane ballot bit also selects the shuffle index: an absent or EXEC-off source is redirected to the current subgroup lane before `OpGroupNonUniformShuffle`, because masking an undefined shuffle result afterwards is not sufficient; FI=1 is unchanged. CPU-checked by `tests/semantic/test_dpp_eager_subgroup.py::test_fi0_shuffle_index_is_ballot_safe` with a hand-written `quad_perm` case whose active lane 6 reads absent lane 7 in a seven-invocation wave; **not GPU-verified**. Checked in SPIRV-Cross 1.3.239's MSL for the `cs_dpp*` tests (each op is now its own statement) and by `tests/semantic/test_dpp_eager_subgroup.py`; not yet run on a Mac. Semantics from the RDNA2 ISA, AMD LLVM modifier syntax and the GPUOpen DPP notes. | +| DPP | VOP1/VOP2 `_dpp` applies to src0. DPP16 controls (`quad_perm`, `row_shl/shr/ror/share/xmask/mirror/half_mirror`) and DPP8 (`dpp8` + `fi`) select the source lane, then `row_mask` (one bit per 16-lane row) and `bank_mask` (one bit per 4-lane bank) decide which destination lanes update. A lane whose row/bank is off is not written. A source lane outside the row is invalid: `bound_ctrl` 1 uses 0 as src0, otherwise the lane is not written. Hardware applies src0 float modifiers (`neg`/`abs`) after the invalid-lane zero selection, so `-src0` on an invalid lane yields `-0.0f` (`0x80000000`) and `\|src0\|` yields `+0.0f` (HW-DPP-NEG-INVALID-LANE, measured on RDNA3 (gfx1101) RX 7800 XT, RDNA2 not measured; tested by `tests/semantic/test_dpp_bound_ctrl_modifiers.py`). A source lane inactive under EXEC is used when `fi` is 1; otherwise `bound_ctrl` decides. DPP8 always writes an enabled lane: `fi` 1 reads the inactive source, `fi` 0 uses 0. DPP16/8 never leaves its 16/8-lane group, so this is exact on every subgroup at least that wide; under `--wave64-emulate` the exchange goes through the workgroup buffer like the other cross-lane ops. GPU-checked with `runtime/test/shaders/cs_dpp*.asm` on an RTX 3070 and hardware-measured on an RX 6800. On an RX 6700 XT (gfx1031), `tools/crosslane_fuzz.py --dpp-sweep --oracle hw` checks every DPP16 control × `bound_ctrl` × `fi`, every `row_mask`/`bank_mask` pair and the DPP8 selects in wave32 and wave64: 14,412 cases, all matching these rules (BUILD-162, `docs/shader_validation.md` FUZZ-7). The ballot of the source lanes' EXEC bits and the shuffle are each stored to a Function variable of their own (`Gen.eager`): SPIRV-Cross (MoltenVK) inlines a single-use result into the expression that uses it, which put the ballot on the right of a short-circuiting `&&` and the shuffle in a ternary's arm, so lanes out of their row skipped the ballot and row_shr:1's lane 1 found lane 0 inactive (`cs_dpp_ops` on MoltenVK; SHADER-529). A store is a statement every lane runs. Out-of-row `in_bounds` clamps `safe_sg` to own subgroup lane `sgl` (never constant lane 0). For native FI=0, the active-lane ballot bit selects the shuffle index (`OpSelect(bit, safe_sg, sgl)`); for native FI=1 on a VGPR source, a `%true` present-lane ballot bit similarly redirects unlaunched/absent lanes in a partial subgroup to `sgl` (treating absent lanes as invalid while still fetching EXEC-off launched lanes). CPU-checked by `tests/semantic/test_dpp_eager_subgroup.py` and `tests/semantic/test_absent_lane_ub.py`, and GPU-checked on a Radeon gfx1036 RDNA2 iGPU (RADV, `tests/test_absent_lane_gpu.py`, partial 5-thread CS and 1×1 PS with `LEONIDA_VK_VALIDATION=1`). Checked in SPIRV-Cross 1.3.239's MSL for the `cs_dpp*` tests (each op is now its own statement) and by `tests/semantic/test_dpp_eager_subgroup.py`; not yet run on a Mac. Semantics from the RDNA2 ISA, AMD LLVM modifier syntax and the GPUOpen DPP notes. | | DPP on a VOPC compare | A VOPC compare whose src0 field is a DPP marker (250 for DPP16, 233/234 for DPP8) takes src0 through the DPP lane selection of the row above and writes VCC: a lane's bit is `compare(src0 of the selected lane, its own src1)`, with 0 for src0 when the selected lane is out of its row or inactive (`bound_ctrl` 1, or DPP8 with `fi` 0). The second word has the layout of a VOP2's DPP word. `llvm-mc` has no decoding for it on gfx10 (LLVM 21.1.8 rejects the first word for `gfx1013`; LLVM defines the form from GFX11 on), so `tools/shader_disasm.py` prints it: it decodes the pair with the first word turned into `v_max_f32` into `v0`, which takes the same second word, and gives the line the compare's name, a `vcc_lo` destination and the real encoding back (`with_vopc_dpp`); `tools/rdna2_decode.py` decodes it directly. **Only the forms where every lane writes its bit are translated**: `row_mask` and `bank_mask` 0xF and either `bound_ctrl` 1 or DPP8. Any other form is refused (`DPP compare with lanes DPP leaves unwritten`), because what such a lane writes is measured only on RDNA3, not on RDNA2. On RDNA3 (gfx1101, RX 7800 XT, `tools/hw_oracle`, wave32 and wave64; [measurement](https://github.com/ubiquitarianism/leonida/issues/1608#issuecomment-7161289307)) a lane DPP leaves unwritten does not keep its bit: `v_cmp` writes 0 to its VCC bit and `v_cmpx` turns it off in EXEC. That holds for an invalid source with `bound_ctrl` 0, and for a lane `row_mask` or `bank_mask` turns off, even with `bound_ctrl` 1. Translating these forms on RDNA2 (gfx1013) would need the same measurement there. `v_cmpx` in DPP form takes the same lane selection and the same forms, and writes EXEC as the plain `v_cmpx` does (a lane that was off stays off); it prints no destination, so its src0 is the first operand (SHADER-VOPCX-DPP). Found in 3 of the 2,684 pipeline-library compute programs of 1.0.2.1: 4 `v_cmp_gt_f32` each, with `quad_perm:[1,0,3,2]`, `quad_perm:[2,3,0,1]`, `row_ror:8` (all `bound_ctrl:1`, masks 0xF) and `dpp8:[4,5,6,7,0,1,2,3]`, beside `v_min/max_f32_dpp` and `v_mov_b32_dpp` on the same lanes. `v_cmpx` in DPP form is in 78 of the 18,837 graphics programs of the pipeline library (all pixel shaders, 113 instructions), all `v_cmpx_gt_f32_dpp vN, -vM quad_perm:[2,3,0,1] row_mask:0xf bank_mask:0xf bound_ctrl:1 fi:1`, a compare against the lane two above or below in its quad. **Not measured on RDNA2 hardware**: the rule follows from the encoding, from LLVM's GFX11 definition of the same form and from the VOP2 DPP rules measured in the row above; the sweep that measured those (`tools/crosslane_fuzz.py --dpp-sweep --oracle hw`) does not cover compares. The RDNA3 measurement above also ran the translated forms (`bound_ctrl` 1, masks 0xF): an invalid source lane gets the compare of a 0 source, as the rule says. Lane values are checked in `tests/semantic/test_dpp_compare.py` (the SPIR-V interpreter) and on a GPU with `runtime/test/shaders/cs_dpp_cmp.asm` and, for `v_cmpx`, `cs_dpp_cmpx.asm` (RTX 4070 Laptop, native wave32 and `--wave64-emulate`). | | EXEC | A per-invocation `active` flag. VALU writes and exports are masked by it, scalar ops aren't, and `v_cmpx`, saveexec and EXEC writes update it. Measured on native gfx1100 (8 threads): a `v_mov_b32` under `EXEC=0x0F` leaves the other lanes untouched, `EXEC=0` writes nothing, a store writes only active lanes and `v_cmpx_gt_u32` narrows EXEC (4 of 4 cases); note that AMD clang 20 rejects `v_add_co_u32`, `v_sub_co_u32`, `v_add_co_ci_u32` and `v_mad_u64_u32` for `gfx1100`, `gfx1101` and `gfx1102`, so this toolchain could not reproduce the RX 7600 result below, which leaves open whether those parts support the opcodes and says only that they could not be assembled here. **A pixel is written when its lane was on in EXEC at the last `exp ... vm` the path executed (if it executed one) and at the last export to the color target; a path with no export at all goes by EXEC at the end.** The `vm` half is the RDNA2 ISA reference guide's rule (30-November-2020, §11.1 and §11.2.1: EXEC at the export is the valid mask and the final one sent is used; an `exp null ... vm` carries only the mask). The color half is measured: an export sends data only for the lanes that are on, a later export to the same target replaces the earlier one for the whole wave, and a lane with no data from the last one is not written even when a later `exp null done vm` marks it valid. So `exp mrt0 done` (no `vm`) with every lane on, followed by an EXEC write, still writes every pixel, and EXEC off at that export and back on afterwards writes none. **Measured on RDNA2** (AMD Radeon iGPU, gfx1036, driver 26.10.1) with the pixel-shader oracle of #3061 (`ps_oracle.py`), hand-written ISA as the pixel shader of a real draw (wave64 stage): 18 programs that cut EXEC to half of the target before, between or after `exp mrt0` (with and without `vm` and `done`) and `exp null done vm`; all 18 fit the rule, 6 of them differed from the translator, which until 2026-11-23 discarded by EXEC at the end on a path without `vm` and kept the older export's value (or the output's initial value) for a lane that was off at the last color export. The latches (`%vm_mask`, `%col_mask_mrtN`) are only emitted where a path can write EXEC after a `vm` or color export; everywhere else EXEC at the end is the same mask and the SPIR-V is unchanged. With several color targets a pixel stays when any target got an export from its lane (Vulkan cannot skip one attachment per pixel; not measured, the oracle's pipeline has one target); `mrtz` is not part of the color mask (not measured). **Measuring exports needs `s_waitcnt expcnt(0)` after each one**: an export is asynchronous, and without the wait the hardware takes the data and the EXEC of a later moment (`v_mov v9, A; exp mrt0 v9 done vm; v_mov v9, B` shows B, and an EXEC write right after the export decides which pixels are written, which looks like "EXEC at the end decides"); 64 `s_nop 15` have the same effect as the wait. Checked on the CPU by `tests/semantic/test_export_valid_mask.py` and on the GPU by `runtime/test/shaders/ps_exp_color_mask.asm` (RTX 5080 and the Radeon). VALU scalar lane-mask destinations (`v_cmp_*`, `v_add_co_u32`, `v_add_co_ci_u32`, `v_sub_co_u32`, `v_sub_co_ci_u32`, `v_subrev_co_u32`, `v_subrev_co_ci_u32`, `v_mad_u64_u32`, `v_mad_i64_i32`) write 0 for lanes off in EXEC (`SDST[lane] = EXEC[lane] ? bit : 0`, AMD RDNA2 ISA). Until 2026-11-22 the six `*_co_*` ops and `v_mad_u64_u32`/`v_mad_i64_i32` did not AND the carry/sign bit with `active`, so inactive lanes leaked 1 bits into `VCC`/SGPR masks (`s_bcnt1`, `s_cbranch_vccz`, `v_cndmask_b32`). Checked on the CPU by `tests/semantic/test_carry_exec_mask.py` (wave32, wave64, and `--wave64-emulate` structure), and **hardware-verified on an AMD RX 7600 (gfx1102)** with `v_add_co_u32` and `v_add_co_ci_u32` carrying on every active lane: VCC reads `0xffffffff` with full EXEC, `0x0000ffff` for the mask `0x0000ffff` and `0xaaaaaaaa` for `0xaaaaaaaa` in wave32, `vcc_lo = 0x0000ffff` with `vcc_hi = 0x0000000f` for the same partial mask in wave64, and `0` when EXEC is 0 even with VCC preloaded to all ones; with one carrying lane under mask `0x0000ffff` VCC is `0x00000001`, and `v_sub_co_u32`/`v_subrev_co_u32` with a borrow under that mask give `0x0000ffff` too. The `*_co_ci_` forms, `v_mad_u64_u32` and `v_mad_i64_i32` share the same path but were not measured separately; it is also GPU-verified on native RDNA2 (gfx1036, AMD Radeon Graphics) with partial EXEC masks (inactive lanes write 0 in sdst for `v_add_co_u32` and `v_mad_u64_u32`). In a shader that writes EXEC, a run of two or more lane-local VALU instructions (no cross-lane read, no lane-mask, SCC, carry or EXEC write) sits inside one `if (active)` and writes its VGPRs directly, instead of an `OpSelect(active, new, old)` per write: the same result, but the driver predicates the run with its own EXEC instead of keeping both values live. On an RX 5700 XT (RADV) a pixel shader with 8 divergent if/else regions of `v_fma`/`v_mul`/`v_add`/`v_min`/`v_max` went from 0.85 ms to 0.69 ms (the same program as native SPIR-V: 0.65 ms). Under `--wave64-emulate` too: a round ends a segment only at a cross-lane exchange, a barrier or a memory-ordering point, none of which a lane-local instruction is, so a run never crosses a segment boundary (`Gen.insns` checks this). Checked by `tests/semantic/test_active_runs.py` (`EmulatedWave64ActiveRuns` for the emulated form). | | `s_*_saveexec_b32/b64`, `s_andn1/andn2_wrexec_b32/b64` | RDNA2 ISA SOP1. saveexec: `D = EXEC; EXEC = f(S0, EXEC); SCC = (EXEC != 0)`. wrexec: `EXEC = f(S0, EXEC); D = EXEC`. `f` is one of `and`, `or`, `xor`, `andn1` (`~S0 & EXEC`), `andn2` (`S0 & ~EXEC`), `orn1` (`~S0 \| EXEC`), `orn2` (`S0 \| ~EXEC`), `nand`, `nor`, `xnor`, the table in `Gen.EXEC_LOGIC`. The definitions match `tools/cf_ref.py` `_SAVEEXEC`, the FUZZ-8 model. Each invocation holds its own lane's bit (0 or ~0), so `f` is the bitwise op on that bit. A lane EXEC had off becomes active when `f` gives 1 for it (`nand`, `nor`, `orn1`, `orn2`, `xnor`, ...), as on hardware, and SCC is the wave vote. Until 2026-11-22 only `and`/`or`/`andn2_saveexec` and `andn2_wrexec` were translated. CPU-checked by `tests/semantic/test_saveexec_variants.py` (all ten saveexec kinds in wave32 and wave64, both wrexec kinds, partial EXEC and S0, an empty result, every lane against `cf_ref._SAVEEXEC`) and by `tools/cf_diff.py` (300 programs × wave32/64 still pass). Hardware-verified on native RDNA2 (`gfx1036`, Windows 11, driver `32.0.21045.29003`, wave32 & wave64, 0 mismatches): all 10 `saveexec` kinds and both `wrexec` kinds (`andn1`/`andn2`) match bit-for-bit on non-symmetric masks (`src0 = 0x0F0F0F0F`, `exec = 0x33333333` in wave32; `0x0F0F0F0F_00FF00FF` / `0x33333333_55555555` in wave64), zero-result `SCC = 0`, wave64 upper-32-bit-only `new_exec = 0x00000001_00000000` setting `SCC = 1`, and `sdst == src0` register aliasing (`s4, s4` and `s[4:5], s[4:5]`) reading original `src0` before writing old `EXEC` to `sdst`. **Not GPU-verified** for the seven new kinds. Measured on native gfx1100 (single 8-lane workgroup, 36 programs): all ten `saveexec` kinds and both `wrexec` forms follow `f` for three `S0`/`EXEC` pairs, including lanes `EXEC` had off being switched back on (`nand` with `S0=0x03`, `EXEC=0x0F` leaves `0xFFFFFFFC`, activating lanes 4-7), `D` holding the old `EXEC` for `saveexec` and the new one for `wrexec`, and `SCC` the `EXEC != 0` vote. | @@ -321,13 +321,15 @@ How the generated SPIR-V expects the runtime to work: | 8/16-bit global stores and d16 loads | `global_store_byte`/`short` write the low 8/16 bits of the data VGPR (the `_d16_hi` forms its high half). `global_load_{u,s}byte_d16` and `global_load_short_d16` write the low 16 bits of `vdst` (the `_hi` forms the high 16) and keep the other half; `ubyte` zero-extends and `sbyte` sign-extends the byte to 16 bits. The address is the `global_load/store` one (`Gen.global_address`). The access goes one byte at a time, so a 16-bit access that crosses a dword (at byte 3) is exact too. A store merges each byte into its dword with atomic and/or, which keeps neighbouring bytes even when another lane writes them, as buffer byte stores do. A load reads each byte. Inactive lanes neither store nor load. The first-read analysis counts a d16 load's `vdst` as read, for the half it keeps. `global_load/store_dword_addtid` (lane-id and M0 addressing) raise `Unsupported`; until 2026-11-22 they crashed with `IndexError`, and the ten sub-dword ops raised `Unsupported`. CPU-checked by `tests/semantic/test_global_sub_dword.py` (every byte offset 0 to 7 for each op, an inactive lane, rejected forms, the first-read analysis). **Hardware-measured natively on `gfx1100`** (RX 7900 XTX, driver 26.10.1) with `tools/hw_oracle`, 16 cases that use the output buffer as scratch memory (seven stores, nine d16 loads), all matching: `b8`/`b16` change only the addressed bytes (`0x11223344` with `0xbeef` stored at offset 2 reads back `0xbeef3344`), `_d16_hi` stores take the data VGPR's high half (`0x12340000` at offset 0 gives `0x11221234`), a 16-bit store at offset 3 splits across the dword exactly (`0xfe223344` then `0x556677ca`), `ubyte`/`sbyte` d16 loads fill the low 16 bits of `vdst` and keep the other half (`0x85` gives `0xbeefff85` from a `0xbeef0000` vdst, `0x7f` gives `0xbeef007f`), `short`/`short_hi` d16 loads fill the low/high 16 and keep the rest, and both dword-crossing loads at offset 3 are exact (`0xbeef8811`, `0x88110000`). Not measured: an inactive lane. GPU-checked by `runtime/test/shaders/cs_global_mem_ext.asm` for two of the ten ops (one lane, `saddr` addressing, on a Radeon 610M (gfx1036, RADV, Mesa 26.2.6) and an RTX 4070 Ti (NVIDIA 620.70.06), Linux): `global_store_short` at byte 3 of a dword changes only its two bytes, across both dwords, and `global_load_sbyte_d16_hi` sign-extends a byte into the high half of `vdst` and keeps the low half. **Not GPU-verified:** the other eight ops and an inactive lane. | | Literal samplers | Some shaders build their S# from immediates (for example `0x92, 0xC00000, 0x14500000, 0`). The runtime registers those in the descriptor hash table too, by scanning the translated shaders' constant S# values, not only S#s the game binds. The translator lists them per shader (`literal_samplers` in the index). `CreateGraphicsPipelineState` and `CreateComputePipelineState` register each stage's list in the descriptor hash table, since no heap slot names these S#s. Until 2026-11-22 nothing called `register_samplers` (#1169) outside its test, so such a shader's lookup found the fallback sampler and sampled with the wrong filter. The game's `$PS_PassthroughCopy` drew a coordinate ramp point-sampled: worst error 0.0078, against 0.00049 once registered. Checked by `d3d12_m2_textured_test` (`ps_m2_literal.asm`: no key before the PSO, a sampler index after it). | | Pipeline-library scalar operands | A scalar load may use VCC as a 64-bit pointer. In wave32 programs using that operand, scalar pair moves and XORs preserve both address words. Read its low and high data words, gathering a native wave's mask bits when a half is mask-valued. An emulated wave64 mask-valued pointer is refused. Where LLVM rejects a scalar, image or buffer tuple ending in VCC, recover the tuple from its original bytes before following branches. Hand-built memory and decoder cases in `test_library_compute_forms.py` and `test_vcc_tuple_fallback.py`. | -| Scalar/buffer memory | `s_load*`, `s_buffer_load*`, `buffer_load*` and `buffer_store*` use buffer device addresses (`PhysicalStorageBuffer64`). LLVM `VCCTuple` scalar register lists ending in `vcc_lo,vcc_hi` (e.g. `[s100,s101,s102,s103,s104,s105,vcc_lo,vcc_hi]`, `[s92,...,s105,vcc_lo,vcc_hi]`, seen in 6 FidelityFX FSPX shaders) are parsed as `slist` operands in `tools/shader_ir.py`, clear `vcc` from the lane-mask state in `tools/lane_masks.py`, and route `sN` slots to `%sgpr` and `vcc_lo`/`vcc_hi` to `%vcc`/`%vcc_hi` across SMEM loads, T#/S#/V# descriptor reads, and `global_*` `saddr`. `src_scc` reads `%scc` (0 or 1, RDNA2 inline constant 253), matching `scc`. `image_atomic_*` and `image_atomic_cmpswap` accept `a16` packed 16-bit unsigned coordinates (low half first, matching `image_store`). CPU-checked by `tests/semantic/test_fspx_rules.py` and validated with `spirv-val` (native and `--wave64-emulate`). **Not GPU-verified.** The base comes from the 64-bit SGPR pointer or the V# (dword0 \ \| dword1[15:0] << 32), and the stride is V# dword1[29:16]. **The runtime must put the game's GPU heap in buffer-device-addressable memory at the same addresses the game writes into descriptors** (or remap them). `s_load*` and `s_buffer_load*` take an immediate or an SGPR offset, or both at once (llvm-mc prints `sOFF offset:IMM`). Rules, measured on AMD Radeon RX 6800 (gfx1030, Windows driver 32.0.21045.29003) by running the instructions as a raw compute kernel, wave32 and wave64 (155 runs, every result either 0 or the stored data, wave32 = wave64 in every dword): **address** = (base & ~3) + (sOFF & ~3) + (IMM & ~3) + 4·i for dword i: base, sOFF and IMM are each truncated to a multiple of 4, then added (`s_buffer_load_dword s9, s[24:27], 0x3` with base & 3 = 1 reads +0, not bytes 4..7; sOFF 3 + IMM 3 reads +0 and sOFF 2 + IMM 6 reads +4, where truncating the sum gives +4 and +8; sOFF 8 + IMM 4 reads +12; the same for `s_load*` with pointer & 3 = 1 or 3). **`s_buffer_load*` bound**: dword i is 0, and memory is not read, when (sOFF & ~3) + (IMM & ~3) + 4·i + 4 > limit, with limit = NUM_RECORDS (V# dword2) bytes when the stride is 0 and NUM_RECORDS × stride bytes when it is not. Per dword (x4 at 0xc with NUM_RECORDS 21: data, data, 0, 0; x8 at 0 with 21: five data, three 0), on the truncated offset (IMM 0x10 with NUM_RECORDS 18: 0; IMM 0x13 with 21: the dword at +0x10; sOFF 0xe + IMM 2 with 16: the dword at +0xc; sOFF 0x10 + IMM 4 with 20: 0), not seeing base & 3 (base & 3 = 3, IMM 0x13, NUM_RECORDS 20: data); with a stride the test is still on bytes (stride 4, NUM_RECORDS 5: IMM 0x10 data, 0x14 0; stride 1, NUM_RECORDS 17: IMM 0x10 is 0, so it is not an index test). IMM is unsigned (0xffffc reads +0xffffc). OOB_SELECT (V# word3[29:28]) 0, 1, 2 and 3 gave the same pattern (7 probes per value). **`s_load*`**: no bound (+0x1ffffc reads the dword there); IMM is sign-extended from 21 bits and added in 64 bits (sOFF 8 + IMM −4 reads +4 where zero-extension reads 4 GiB further; sOFF 0xb + IMM −1 reads +4, so the negative IMM is truncated on its own: −1 → −4). **Negative sums** (SHADER-336), measured on the integrated GPU of a Ryzen 9 9950X3D (gfx1036, RDNA2, Windows driver 32.0.21045.16010) with `tools/smem_neg_probe.py --oracle hw`, wave32 = wave64: `s_load` with IMM −4 or −0x40 and no sOFF, sOFF 4 + IMM −8, sOFF 0xc + IMM −0x20 and the x2 form with sOFF 4 + IMM −0x10 read below the pointer at the 64-bit signed sum, and sOFF 6 + IMM −1 reads +0 (4 + −4, each term truncated on its own). `s_buffer_load` adds sOFF and IMM without wrapping at 32 bits: sOFF 0xfffffffc + IMM 8 and sOFF 0xfffffff0 + IMM 0x20 give 0 (past NUM_RECORDS 0x100), and sOFF 0xfffffffc, 0x80000000 and 0x7ffffffc alone give 0 (the translator has the same rule in both offset forms since #1686). An `s_buffer_load` IMM with bit 20 set (llvm-mc rejects it; −4, −0x10, 0x100000 and 0x100004 were encoded by hand) reads data that is neither 0 nor the buffer's own words, differently in wave32 and wave64: the bound does not hold for that encoding, so no compiler output uses it and the translator does not model it. `SmemHardwareRuleTests` in `tests/semantic/test_scalar_mem_smem.py` runs these rows with sOFF in a register and with sOFF known. **Measured since** on native RDNA2 (gfx1036, the Radeon iGPU of a Ryzen 7 9800X3D, Windows driver 32.0.21042.62) through `tools/hw_oracle`, one raw kernel, wave32 = wave64 in every dword (22 cases): **`x16`** takes the per-dword bound like x8 (`s_buffer_load_dwordx16` at offset 0 with NUM_RECORDS 0x24 gives nine data dwords and seven 0; offset 0x20 with 0x40 gives eight and eight; offset 4 with 0x3d gives fourteen and two; stride 4 with NUM_RECORDS 9 gives nine and seven), and `s_load_dwordx16` reads all sixteen; **NUM_RECORDS ≥ 2^31** is compared unsigned (0x80000000 and 0xffffffff with offset 0x10, and 0x80000000 with an x4 at 0x2f0, all read data); **NUM_RECORDS × stride ≥ 2^32** does not wrap (stride 4 × 0x40000001, stride 0x100 × 0x01000001 and stride 0x40 × 0x04000004 wrap to 4, 0x100 and 0x100 in 32 bits, yet offsets 0x10, 0x200 and 0x2f0 read data), as the translator's 64-bit product assumes; **V# dword1[31:30]** = 1, 2 or 3 changes nothing (a dword at 0x10, an x4 at 0xf8 with NUM_RECORDS 0x100 giving two data and two 0, and the same with stride 8 and NUM_RECORDS 4 at 0x18). Not measured: gfx1013 (PS5) itself. **Bound edges**, measured on the same GPU and driver with `tools/hw_oracle` (wave32 = wave64, every read inside a seeded region): `s_buffer_load_dwordx16` is bounded per dword like x8 (NUM_RECORDS 0x14 gives d0..d4 and 0 for d5..d15; 0x20 with IMM or sOFF 8 gives d0..d5); NUM_RECORDS × stride is not cut to 32 bits (stride 0x1000 × 0x100000 and 0x2000 × 0x80000 = 2^32, stride 8 × 0x20000001 = 2^32 + 8: all four dwords of an x4 at 0 are data; stride 8 × 1 gives two); NUM_RECORDS 0x80000000 and 0xFFFFFFFF are unsigned (an x4 at 0 reads all four). These are the rules the translator already used; `SmemHardwareRuleTests` pins them too (a 32-bit product, a signed NUM_RECORDS or one bound for the whole load each fail a test). Not measured: `x16` (gets the x8 rule), NUM_RECORDS ≥ 2^31 and NUM_RECORDS × stride ≥ 2^32, V# dword1[31:30], and gfx1013 (PS5) itself. `s_load`/`s_buffer_load` with sOFF + IMM < 0 (a negative IMM without sOFF included; the translator uses the 64-bit signed sum, an inference), an `s_buffer_load` IMM with bit 20 set (llvm-mc rejects it) or a negative one (kept as the 32-bit value: for stride 0 that is past any NUM_RECORDS below 4 GiB), `x16` (gets the x8 rule), sOFF ≥ 2^31, NUM_RECORDS ≥ 2^31 and NUM_RECORDS × stride ≥ 2^32, V# dword1[31:30], and gfx1013 (PS5) itself. The translator checks each `s_buffer_load` dword with its own structured `if` and an `OpPhi` with 0, so an out-of-range dword issues no load (when descriptor limit and offset are compile-time constants, in-range dwords fold to straight-line loads and out-of-range dwords emit constant zero without branches); `s_load` stays straight-line. Before this the translator added base + sOFF + IMM unaligned, had no `s_buffer_load` bound and zero-extended a negative `s_load` IMM. Checked by `tests/semantic/test_scalar_mem_smem.py` (`SmemHardwareRuleTests`, the measurement's rows, values and the addresses read; `SmemSoffsetImmTranslatorTests`) and by the GPU tests `runtime/test/shaders/cs_smem_soffset_imm.asm`, `cs_smem_bounds.asm`, `cs_smem_stride_align.asm` and `cs_smem_sload_neg.asm` (never run that one with a translator that zero-extends the immediate: it reads 4 GiB past the heap), all in `check.py` and `scripts/run_gpu_tests.py`, which pass on the RX 6800 (Vulkan, driver 26.11.2). See *Buffer bounds checking* below for the MUBUF `num_records` checks. **A constant SGPR offset** (`s_mov_b32 s12, C`, folded at translate time) is added as the run-time path adds `sOFF`: zero-extended, `& ~3`, after the immediate has been normalised (unsigned for `s_buffer_load`, 21-bit signed for `s_load`), with no 32-bit wrap. Until 2026-11-22 (#1686) the fold added it before the truncation, so `s12 = -4` with `offset:20` read byte 16 instead of being out of range, and an `s_load` `sOFF` of 2^20 or more was sign-extended from 21 bits (found by @Impre-visible; hardware measured by @Pierre-Kookis on gfx1036: 0xFFFFFFFC + 20 reads 0). CPU-checked by `tests/semantic/test_smem_const_offset.py` (each case constant vs run-time offset, and against the measured rule). Where llvm-mc rejects such a tuple, `restore_vcc_tuples` decodes it from the blob, and with it the instructions its junk text swallowed, up to the next instruction llvm-mc printed (corpus count: `docs/shader_library.md`, section 5). | +| Scalar/buffer memory | `s_load*`, `s_buffer_load*`, `buffer_load*` and `buffer_store*` use buffer device addresses (`PhysicalStorageBuffer64`). LLVM `VCCTuple` scalar register lists ending in `vcc_lo,vcc_hi` (e.g. `[s100,s101,s102,s103,s104,s105,vcc_lo,vcc_hi]`, `[s92,...,s105,vcc_lo,vcc_hi]`, seen in 6 FidelityFX FSPX shaders) are parsed as `slist` operands in `tools/shader_ir.py`, clear `vcc` from the lane-mask state in `tools/lane_masks.py`, and route `sN` slots to `%sgpr` and `vcc_lo`/`vcc_hi` to `%vcc`/`%vcc_hi` across SMEM loads, T#/S#/V# descriptor reads, and `global_*` `saddr`. `src_scc` reads `%scc` (0 or 1, RDNA2 inline constant 253), matching `scc`. `image_atomic_*` and `image_atomic_cmpswap` accept `a16` packed 16-bit unsigned coordinates (low half first, matching `image_store`). CPU-checked by `tests/semantic/test_fspx_rules.py` and validated with `spirv-val` (native and `--wave64-emulate`). **Not GPU-verified.** The base comes from the 64-bit SGPR pointer or the V# (dword0 \ \| dword1[15:0] << 32), and the stride is V# dword1[29:16]. **The runtime must put the game's GPU heap in buffer-device-addressable memory at the same addresses the game writes into descriptors** (or remap them). `s_load*` and `s_buffer_load*` take an immediate or an SGPR offset, or both at once (llvm-mc prints `sOFF offset:IMM`). Rules, measured on AMD Radeon RX 6800 (gfx1030, Windows driver 32.0.21045.29003) by running the instructions as a raw compute kernel, wave32 and wave64 (155 runs, every result either 0 or the stored data, wave32 = wave64 in every dword): **address** = (base & ~3) + (sOFF & ~3) + (IMM & ~3) + 4·i for dword i: base, sOFF and IMM are each truncated to a multiple of 4, then added (`s_buffer_load_dword s9, s[24:27], 0x3` with base & 3 = 1 reads +0, not bytes 4..7; sOFF 3 + IMM 3 reads +0 and sOFF 2 + IMM 6 reads +4, where truncating the sum gives +4 and +8; sOFF 8 + IMM 4 reads +12; the same for `s_load*` with pointer & 3 = 1 or 3). **`s_buffer_load*` bound**: dword i is 0, and memory is not read, when (sOFF & ~3) + (IMM & ~3) + 4·i + 4 > limit, with limit = NUM_RECORDS (V# dword2) bytes when the stride is 0 and NUM_RECORDS × stride bytes when it is not. Per dword (x4 at 0xc with NUM_RECORDS 21: data, data, 0, 0; x8 at 0 with 21: five data, three 0), on the truncated offset (IMM 0x10 with NUM_RECORDS 18: 0; IMM 0x13 with 21: the dword at +0x10; sOFF 0xe + IMM 2 with 16: the dword at +0xc; sOFF 0x10 + IMM 4 with 20: 0), not seeing base & 3 (base & 3 = 3, IMM 0x13, NUM_RECORDS 20: data); with a stride the test is still on bytes (stride 4, NUM_RECORDS 5: IMM 0x10 data, 0x14 0; stride 1, NUM_RECORDS 17: IMM 0x10 is 0, so it is not an index test). IMM is unsigned (0xffffc reads +0xffffc). OOB_SELECT (V# word3[29:28]) 0, 1, 2 and 3 gave the same pattern (7 probes per value). **`s_load*`**: no bound (+0x1ffffc reads the dword there); IMM is sign-extended from 21 bits and added in 64 bits (sOFF 8 + IMM −4 reads +4 where zero-extension reads 4 GiB further; sOFF 0xb + IMM −1 reads +4, so the negative IMM is truncated on its own: −1 → −4). **Negative sums** (SHADER-336), measured on the integrated GPU of a Ryzen 9 9950X3D (gfx1036, RDNA2, Windows driver 32.0.21045.16010) with `tools/smem_neg_probe.py --oracle hw`, wave32 = wave64: `s_load` with IMM −4 or −0x40 and no sOFF, sOFF 4 + IMM −8, sOFF 0xc + IMM −0x20 and the x2 form with sOFF 4 + IMM −0x10 read below the pointer at the 64-bit signed sum, and sOFF 6 + IMM −1 reads +0 (4 + −4, each term truncated on its own). `s_buffer_load` adds sOFF and IMM without wrapping at 32 bits: sOFF 0xfffffffc + IMM 8 and sOFF 0xfffffff0 + IMM 0x20 give 0 (past NUM_RECORDS 0x100), and sOFF 0xfffffffc, 0x80000000 and 0x7ffffffc alone give 0 (the translator has the same rule in both offset forms since #1686). An `s_buffer_load` IMM with bit 20 set (llvm-mc rejects it; −4, −0x10, 0x100000 and 0x100004 were encoded by hand) reads data that is neither 0 nor the buffer's own words, differently in wave32 and wave64: the bound does not hold for that encoding, so no compiler output uses it and the translator does not model it. `SmemHardwareRuleTests` in `tests/semantic/test_scalar_mem_smem.py` runs these rows with sOFF in a register and with sOFF known. **Measured since** on native RDNA2 (gfx1036, the Radeon iGPU of a Ryzen 7 9800X3D, Windows driver 32.0.21042.62) through `tools/hw_oracle`, one raw kernel, wave32 = wave64 in every dword (22 cases): **`x16`** takes the per-dword bound like x8 (`s_buffer_load_dwordx16` at offset 0 with NUM_RECORDS 0x24 gives nine data dwords and seven 0; offset 0x20 with 0x40 gives eight and eight; offset 4 with 0x3d gives fourteen and two; stride 4 with NUM_RECORDS 9 gives nine and seven), and `s_load_dwordx16` reads all sixteen; **NUM_RECORDS ≥ 2^31** is compared unsigned (0x80000000 and 0xffffffff with offset 0x10, and 0x80000000 with an x4 at 0x2f0, all read data); **NUM_RECORDS × stride ≥ 2^32** does not wrap (stride 4 × 0x40000001, stride 0x100 × 0x01000001 and stride 0x40 × 0x04000004 wrap to 4, 0x100 and 0x100 in 32 bits, yet offsets 0x10, 0x200 and 0x2f0 read data), as the translator's 64-bit product assumes; **V# dword1[31:30]** = 1, 2 or 3 changes nothing (a dword at 0x10, an x4 at 0xf8 with NUM_RECORDS 0x100 giving two data and two 0, and the same with stride 8 and NUM_RECORDS 4 at 0x18). Not measured: gfx1013 (PS5) itself. **Bound edges**, measured on the same GPU and driver with `tools/hw_oracle` (wave32 = wave64, every read inside a seeded region): `s_buffer_load_dwordx16` is bounded per dword like x8 (NUM_RECORDS 0x14 gives d0..d4 and 0 for d5..d15; 0x20 with IMM or sOFF 8 gives d0..d5); NUM_RECORDS × stride is not cut to 32 bits (stride 0x1000 × 0x100000 and 0x2000 × 0x80000 = 2^32, stride 8 × 0x20000001 = 2^32 + 8: all four dwords of an x4 at 0 are data; stride 8 × 1 gives two); NUM_RECORDS 0x80000000 and 0xFFFFFFFF are unsigned (an x4 at 0 reads all four). These are the rules the translator already used; `SmemHardwareRuleTests` pins them too (a 32-bit product, a signed NUM_RECORDS or one bound for the whole load each fail a test). Not measured: `x16` (gets the x8 rule), NUM_RECORDS ≥ 2^31 and NUM_RECORDS × stride ≥ 2^32, V# dword1[31:30], and gfx1013 (PS5) itself. `s_load`/`s_buffer_load` with sOFF + IMM < 0 (a negative IMM without sOFF included; the translator uses the 64-bit signed sum, an inference), an `s_buffer_load` IMM with bit 20 set (llvm-mc rejects it) or a negative one (kept as the 32-bit value: for stride 0 that is past any NUM_RECORDS below 4 GiB), `x16` (gets the x8 rule), sOFF ≥ 2^31, NUM_RECORDS ≥ 2^31 and NUM_RECORDS × stride ≥ 2^32, V# dword1[31:30], and gfx1013 (PS5) itself. The translator checks each `s_buffer_load` dword with its own structured `if` and an `OpPhi` with 0 when the last dword is out of range (otherwise one wide load, row *Wide scalar loads*), so an out-of-range dword issues no load (when descriptor limit and offset are compile-time constants, in-range dwords fold to straight-line loads and out-of-range dwords emit constant zero without branches); `s_load` stays straight-line. Before this the translator added base + sOFF + IMM unaligned, had no `s_buffer_load` bound and zero-extended a negative `s_load` IMM. Checked by `tests/semantic/test_scalar_mem_smem.py` (`SmemHardwareRuleTests`, the measurement's rows, values and the addresses read; `SmemSoffsetImmTranslatorTests`) and by the GPU tests `runtime/test/shaders/cs_smem_soffset_imm.asm`, `cs_smem_bounds.asm`, `cs_smem_stride_align.asm` and `cs_smem_sload_neg.asm` (never run that one with a translator that zero-extends the immediate: it reads 4 GiB past the heap), all in `check.py` and `scripts/run_gpu_tests.py`, which pass on the RX 6800 (Vulkan, driver 26.11.2). See *Buffer bounds checking* below for the MUBUF `num_records` checks. **A constant SGPR offset** (`s_mov_b32 s12, C`, folded at translate time) is added as the run-time path adds `sOFF`: zero-extended, `& ~3`, after the immediate has been normalised (unsigned for `s_buffer_load`, 21-bit signed for `s_load`), with no 32-bit wrap. Until 2026-11-22 (#1686) the fold added it before the truncation, so `s12 = -4` with `offset:20` read byte 16 instead of being out of range, and an `s_load` `sOFF` of 2^20 or more was sign-extended from 21 bits (found by @Impre-visible; hardware measured by @Pierre-Kookis on gfx1036: 0xFFFFFFFC + 20 reads 0). CPU-checked by `tests/semantic/test_smem_const_offset.py` (each case constant vs run-time offset, and against the measured rule). Where llvm-mc rejects such a tuple, `restore_vcc_tuples` decodes it from the blob, and with it the instructions its junk text swallowed, up to the next instruction llvm-mc printed (corpus count: `docs/shader_library.md`, section 5). | +| Wide scalar loads | `s_load_dwordx2/4/8/16` and `s_buffer_load_dwordx2/4/8/16` read their dwords as the fewest wide loads SPIR-V types allow (`Gen.scalar_load`'s `wide`: `uvec4`, then `uvec2`, each `Aligned 4`), not one `uint` per dword. An `s_buffer_load` whose bound is a run-time value tests its last dword once (off + 4·N ≤ limit; the ends grow with i, so then every dword is in range) and takes the wide loads, else calls an outlined per-width compact counted-loop helper `%sbuf_slow_{ro\|rw}_xN(host, off, lim)` (emitted on demand for each used `(N, ro)` pair with `N ∈ {2, 4, 8, 16}` returning `%arr_sbuf_xN`, with `OpLoopMerge ... DontUnroll`, overflow-safe trip count `lim >= off ? min((lim - off) >> 2, N) : 0`, ONE `OpLoad %uint ... Aligned 4` in the loop body, and a zero-initialized `Function`-scope `%arr_sbuf_xN`, preserving exact per-dword bounds: out-of-range dwords stay 0 and are not read; coherent `glc`/`dlc` loads stay on the inline `MakePointerVisible\|NonPrivatePointer` path). Provably non-aliasing scalar loads go through a `NonWritable` `Block` (`%sl_blk1` / `%sl_blk2` / `%sl_blk4`, including `%sbuf_slow_ro_xN` via `%_ptr_PSB_sl_blk1`) determined per load by `analyse_scalar_load_ro` (read-only modules with no PSB write, descriptor-heap `s_load*` from a 32-bit user SGPR with `hi = 0` whose base is not written and whose loaded dwords are consumed solely as T#/S#/V# descriptors, `s_getpc_b64` loads, loads with no PSB write reachable before or after in the CFG, and loads whose symbolic descriptor/slot origin is disjoint from every PSB write in the module; conservatively disabled whenever `s_dcache_*` appears alongside a write), so RADV/ACO emits SMEM (`s_load_dword..s_load_dwordx16`) on both fast and slow paths even in shaders that also write buffers; loads that may alias a module store/atomic use a mutable `Block` (`%sl_rw_blk2` / `%sl_rw_blk4`) or `%_ptr_PSB_arr` (`%sbuf_slow_rw_xN`) without `NonWritable`, keeping `tools/valu_fuzz.py --family mem` (which stores and loads back through the same base origin) exact. Why: Mesa `spirv_to_nir` always inlines `OpFunctionCall`, so unrolling `N` mutable `OpLoad`s inside `%sbuf_slow_xN` still exploded on wide-load-heavy shaders; a `DontUnroll` single-load loop with `NonWritable` `%sl_blk1` keeps the slow path to one SMEM `s_load_dword` per site (40× `s_buffer_load_dwordx16` synthetic shader on `gfx1036` RADV: 40 `s_load_dwordx16`, 40 `s_load_dword`, 0 `global_load`, 0 `v_readfirstlane`, 0 `scratch_`). **Confirmed** by `tests/semantic/test_wide_scalar_load.py`, `tests/semantic/test_smem_nonwritable_outline.py` (fixture `cs_smem_nonwritable_outline.asm`: per-load `NonWritable` on disjoint CBV/descriptor-heap loads alongside `buffer_store`, mutable fallback on same-root aliasing, mixed RO/RW helpers sharing `%fn_sbuf_slow_x4`, `s_dcache_inv` conservative fallback, partial-OOB and all-OOB read checks, `spirv-val --target-env vulkan1.2`, `check_absent_lane_ub.py`), `SmemHardwareRuleTests` in `tests/semantic/test_scalar_mem_smem.py`, and `tools/valu_fuzz.py --family mem --programs 200` (400/400 wave32+wave64) on the Radeon iGPU (`gfx1036`, RADV). Count over the corpus (1.0.2.1): x2 268,659 in 22,943 modules, x4 550,938 in 24,268, x8 120,295 in 16,539, x16 65,758 in 16,200 (25,878 modules in all); 0 modules have `s_dcache_inv`, `s_gl1_inv` or `s_dcache_wb`. | | 2D array resource dimensions | For `image_get_resinfo` on a 2D array, X/Y are the width/height at the requested mip, Z is the view layer count and W is its mip count. The query reads the sampled array at binding 3. A native gfx1036 kernel returned (19,11,5,3), (9,5,5,3) and (4,2,5,3) for the three mips of a synthetic array. On RTX 5080 and Radeon Graphics the translated query matched those tuples and returned (4,2,3,2) at relative mip 1 with a view starting at mip 1 and covering three layers. The registered `ps_array_resinfo` draw checks all 4096 pixels against (8,8,12,1). | | Images and samplers | `image_sample_l` on 2D arrays used to read its LOD from the array layer; it now reads the LOD after all coordinates. `image_get_lod` and `image_gather4_lz` also work on 2D arrays. With `d16` every sample result is f16, packed two to a VGPR from the low half (the packed D16 of GFX10, as LLVM returns D16 image data); `image_sample_c_lz`/`_c_lz_o` follow it too, and until 2026-11-21 their compare result was written as f32 bits, which read as 0 in the low half. Checked by `tests/test_translate.py` (`test_depth_compare_sample_result_width`) and GPU-checked with `runtime/test/shaders/ps_sample_c_lz.asm` (`vk_texture_test dref`: a D32 texture and a LESS_OR_EQUAL compare sampler) on an NVIDIA GeForce RTX 2060 SUPER (Linux, driver 620.70.06): 4096/4096 pixels exact for f32 and `d16`; with the old translator the `d16` result read 0 in the 2048 pixels whose compare passes. | | Images and samplers (T# dimension) | The hardware addresses an image with the T#'s own TYPE (`SQ_IMG_RSRC_WORD3` [31:28]); an instruction's `DIM` only says which coordinates it supplies. The bindless set therefore gives each image its index in **its** dimension's array (`runtime/src/vulkan_bindless.h`), and an instruction of another dimension must not use that index blindly. Pairs: a **2D-array or cube T# read by a 2D instruction** is its slice 0 (legal; the runtime binds a 2D view of the T#'s first layer at the image's own index in the 2D arrays, `BindlessSet::MirrorViews`, and the entry's kind names 2D; the mirror records that image as its owner, so an image of another dimension at the same slot number does not inherit it); every other mismatch - a **2D T# read by a 2D-array instruction** (it has one layer but no 2D-array view), a **3D T# read by a 2D op**, a 1D T#, a multisample T# read by a single-sample op, a 2D T# read by a 3D op - has no view of the instruction's shape and reads that dimension's fallback (index 0, a 1x1 image of zeros), never another image. So each entry carries a kind word next to its index: the translator reads it from the table (`%desc_lookup_fn` returns (index, kind) as a `uvec2` in a `descriptor_table` tagged module), tests the bit for the array its instruction reads with `OpBitFieldUExtract` and picks index 0 otherwise (`Gen.desc_sampled_index`). A store, atomic or `glc` coherent read follows the storage bits instead (`Gen.desc_storage_index`): a T# of another dimension, or one whose image has only a sampled view, goes to that dimension's storage fallback, where writes and atomics are dropped (a null descriptor with `VK_EXT_robustness2`, else a 1x1 image apart from the sampled fallbacks). Checked by `tests/semantic/test_tsharp_dimension.py` (each dimension's bit, the storage rule, the fallback operand, the plain layout and the meta marker) and by `runtime/test/vk_bindless_test.cpp`, which draws a 2D sampling shader with a 3D T# whose index equals a 2D image's: 0 bad pixels with tagged modules, 4096 per pass with plain ones (that module reads the 2D image at that index); it also binds a 2D-array T# whose mirror it reads, removes it, and puts a 3D T# at the same slot number to show the two index spaces stay separate. GPU-checked on an NVIDIA GeForce RTX 4070 Ti (driver 32.0.16.3020). `image_get_lod`, `image_load_mip` and `image_get_resinfo` name the bit but read the fallback on a mismatch. **Not measured on native RDNA2**: the pair table follows the ISA's TYPE addressing and Mesa's `ac_nir_lower_*` views; `tools/hw_oracle` was not used. | | Images and samplers (core) | Bindless. Set 0: binding 0 = 2D sampled images, 1 = samplers, 2 = descriptor hash table (storage buffer), 3 = 2D-array images (**cube textures are bound here as 6-layer 2D-array views**, cube arrays as 6N layers: the shader already selected the face with `v_cube*`), 4 = r32ui storage images, 5 = 1D, 6 = 3D. A cube sample's s and t come in [1, 2] and its third coordinate is 8·slice + face, as the hardware takes them (Mesa `ac_nir_lower_tex_coords.c`, LLPC `ImageBuilder.cpp`); the view is read at (s − 1, t − 1), layer 6·slice + face. GPU-checked with `runtime/test/shaders/ps_cube_sample.asm` (`vk_texture_test cube`). For a native Metal path, `tools/spirv_metal_set0.py` sizes set 0's runtime arrays from `vulkan_bindless.h` and moves each binding to its own argument-buffer ID range (binding b starts at the capacities of bindings 0..b-1 added up), to convert with SPIRV-Cross `--msl-decoration-binding`: SPIRV-Cross 1.4.363.0 otherwise puts every runtime array at one ID and comments all but one out as "Overlapping binding" (SHADER-161). `cs_imgstore` converted this way writes all 3×64 texels correctly in a native Metal dispatch on an Apple A18 Pro. | | Typed buffer loads | The format is V# word3[18:12] (GFX10_FORMAT, from Mesa's `gfx10-rsrc.json`, saved as `tools\gfx10_formats.json`). Supported: f32 ×1–4, u32 ×1–4, i32 ×1–4 (formats 21/63/73/76), f16 ×1/2/4, unorm8 ×1/2/4, snorm8 ×1/2/4, uint8 ×1/2/4, sint8 ×1/2/4, unorm16 ×1/2/4, snorm16 ×1/2/4, uint16 ×1/2/4, sint16 ×1/2/4, 10-10-10-2 and 2-10-10-10 unorm, and, since 2026-11-22, the other GFX10 buffer codes 1–77 (every USCALED/SSCALED, 10_11_11 and 11_11_10 FLOAT, the 10_10_10_2 and 2_10_10_10 families, 8_8_8_8 and 16_16_16_16 SINT and SCALED; see *Typed buffer formats*). Others (code 0 and 78 up) give 0. The 8- and 16-bit UINT/SINT formats 5, 6, 11, 12, 18, 19, 28, 61 and 70 were missing until 2026-11-22 and read 0: UINT channels zero-extend, SINT channels sign-extend, d16 packs them as 16-bit integers, measured natively on gfx1036 (wave32 and wave64) with `tools/hw_oracle` and checked word for word by `tests/semantic/test_buffer_format_narrow_int.py`; GPU-checked by `runtime/test/shaders/cs_fmt_int_narrow.asm`, whose 136 expected words are the same program run natively on gfx1036 (exact on an RTX 5080 and on the gfx1036 iGPU through Vulkan). Full-width SINT accesses preserve integer bits. D16 SINT loads saturate to signed 16-bit and D16 stores sign-extend, covered by the synthetic `cs_fmt_sint32.asm` readback. DST_SEL swizzle is applied (0→0, 1→1.0f for float/norm or integer 1 for UINT/SINT, 4..7→X..W). Missing channels repeat the format's own (component *c* = *c* mod *n*), measured on an RX 6700 (SHADER-86). UNORM/SNORM give the correctly rounded quotient by (2ⁿ−1), as the hardware does (0 mismatches vs hardware over 395,776 conversions on that GPU). It is built with integer ops (`Gen.norm_bits`): x/(2ⁿ−1) in binary is x's bits repeated, so a 64-bit multiply by the repeat pattern, `FindUMsb` and the round bit give the f32 exactly (the tail never ends, so there are no ties). `OpFDiv` is not enough on the GPU: Vulkan allows it 2.5 ULP, and on an RX 6700 (AMD Windows 26.11.2) and an RTX 5090 it returned the reciprocal-multiply bits (8_UNORM 130/256 exact, #599). Checked against exact values in `tests/semantic/test_norm_decode.py` (every value up to 8 bits, edges and the reciprocal-multiply misses for 10, 15 and 16 bits). 8_SNORM (2), 16_SNORM (8) and 8_8_SNORM (15) were missing until 2026-11-22 and decoded to 0. Format names list the channel widths from the top bit, so `2_10_10_10` (50) is R10G10B10A2 and `10_10_10_2` (44) has a 2-bit x (Mesa `gfx10_format_table.py`, `ac_formats.c`). Until 2026-11-22 the two were swapped, in stores too. Until 2026-11-21 an element that started mid-dword re-read dword 0 for its tail (`need` was `ceil(size/4)` and only the first dword was shifted); loads now take `need = ceil((byte_shift + size) / 4)` dwords and shift the whole window so the packed stream starts at the element (FUZZ-5, leftover from #234). The 10:10:10:2 order is checked by `cs_fmt_1010102` in `tests/semantic/test_value_semantics.py` (the shader decodes the format, so a GPU run can't check it). Mid-dword spanning elements are checked by `tests/semantic/test_buffer_load_format.py` (`CrossingDwordBoundary`); repeat / UNORM / DST_SEL 1 by the SHADER-86 cases in the same file. The `_xy` and `_xyz` forms (buffer and tbuffer) are GPU-checked by `cs_fmt_xy_xyz.asm`, whose words were measured natively on a Radeon 680M (gfx1035, RDNA2): they write only their 2 or 3 VGPRs, and missing channels repeat there too (TEST-185). | | Descriptor hash table | `uint mask; entries[mask+1] of 10 uints: key[0..7], index, kind`. The last word is 0 in an empty slot; otherwise bit 31 marks it occupied and bits 0..5 / 8..11 name the sampled / storage arrays the index is bound in (docs/d3d12_vulkan.md section 5.1, "Images and samplers (T# dimension)" below). A module reads it only when its index entry says `"descriptor_table": "tagged"`; `--descriptor-table plain` leaves the word unread and gives byte-identical modules to the translator before the marker (checked with a 5-instruction pixel shader: old and plain output are the same bytes). The key is a T# or a padded S#. FNV-1a over the eight key words selects the first slot by default. With `--descriptor-hash=fnv1a_fmix32` the shader applies MurmurHash3 fmix32 before masking the slot. Every translated module then records `"descriptor_hash": "fnv1a_fmix32"` in its index entry. An absent key means `fnv1a`. The runtime and shader must select the same hash. The shared SPIR-V lookup probes up to eight slots and returns index 0 on a miss. The runtime supplies a fallback at index 0 and maps live descriptor keys to bindless indices. Outside the wave64 emulation, the lookup's result goes through `OpGroupNonUniformBroadcastFirst` before it indexes the image or sampler array. The lookup key words come from SGPRs, so every invocation in a subgroup has the same index; the broadcast is an identity on all drivers and marks the value uniform for the compiler. It declares `GroupNonUniform` and `GroupNonUniformBallot`, without a shuffle capability or subgroup-lane input. The shader index records the capabilities; its `features` field lists optional Vulkan device features. Mesa ANV 26.2.7 on an Intel Alder Lake-S UHD (Xe-LP, Linux) segfaults in `vkCreate*Pipelines` on a sampler index taken straight from the probe loop when that sampler serves both a float and an integer image (`cs_sample_lz_int_d16`, `ps_ssharp`); with the broadcast both pass. Checked by the unit test `test_lookup_result_is_broadcast_before_use` in `tests/test_desc_cache.py` (standard library only: no GPU, LLVM or SPIRV-Tools). | +| Bindless index in the T# | On the console a texture access loads the T# and samples; the hash-table lookup above made every access hash the eight T# words and probe up to eight table slots (in the tiled-lighting pixel shader, 62 lookups and 19,714 RADV instructions against 3,080 in the native program). **What pack and runtime agree on:** in every heap shaders read, the layer writes dword 6 of each T# as `0xA << 28 \| storage kind << 23 \| sampled kind << 16 \| index`: the tag `0xA` in [31:28], the table's storage kind bits 8..12 in [27:23], its sampled kind bits 0..6 in [22:16] and the bindless index in [15:0] (`runtime/src/gfx10_descriptors.h`, `tsharp_index_word`). **Index 0** is the fallback of the array the instruction reads: the word is 0 while the T# has no entry (no texture at its address yet, a stream pending, no room in its array), for index 0 itself and for an index past 16 bits, and a shader reads index and kind 0 unless the word has the tag **and** dword 3 names an image (TYPE 8..15, bit 31), so a V#, a data slot or a zero slot read as a T# never passes. Then, as for a table entry, the kind bit of the instruction's array decides between the index and that array's fallback. The heaps: the copies of the console resource heaps (`fix_console_slot`, fixed again whenever the texture at the T#'s address comes, goes or is replaced, or the T#'s entry is replaced) and the layer's own heaps (`write_image_descriptor`; `scan_title_table` refreshes bound tables; a view `LEONIDA_PIPELINE_COMPILE=on-demand` defers gets its word when it is made, `materialize_table`). Dword 6 is the hardware's compression metadata, which no Vulkan view uses; the title's own bytes and the T#'s table key keep the title's dword 6 (`tsharp_key` strips the word from bytes read back from the layer's heaps). **Translator** (`Gen.tsharp_index_sgpr`, `tools/descriptor_sources.py`): a forward SGPR dataflow over the basic blocks marks each image instruction whose T# dword 6 is dword 6 of a heap slot: an `s_load` from a 32-bit pointer in a user SGPR (a descriptor table or a directly indexed heap, `docs/d3d12_vulkan.md` section 3.4) at slot position 24 (a static offset is checked; a run-time one is the heap index times 32), followed through copies, joins of two such loads, SGPRs parked in VGPR lanes (`v_writelane`/`v_readlane`) and VCC used as two more SGPRs. Those instructions read index and kind from the word, with no memory access and no lookup. Any other T# keeps the lookup inside a uniform branch taken only when its dword 6 has no tag, so a heap T# the dataflow could not place costs no probe either (`Gen.tsharp_lookup`). S#s keep the lookup: the console sampler heaps are the title's pages read in place, and S#s have no free field. **Older packs** are told apart by the module meta: every module this translator writes has `"tsharp_index": "dword6"` (with its counts `tsharp_index_reads` and `tsharp_lookups`); the runtime counts them (`TsharpIndexCensus`) and writes the word when any module reads it, logging `T# index word: written into the heaps' T#s (all N modules)` or `not read`. A pack without the key keeps working as before: no word is written and its modules find every T# by its words. A library mixing both is logged, since its older modules then miss heap T#s (their copy's dword 6 is not the key). `LEONIDA_CONSOLE_HEAP_GPU`'s pass copies T#s as written, so with an index-word pack the resource heaps are fixed on the CPU (logged once, `runtime/README.md`). Modules change, so pipeline keys change with them. **Counts** (`tools/descriptor_source_census.py`): 1.0.2.1 carve, 26,503 listings: 439,415 image instructions with a T# in 17,540 modules; 437,263 take the whole T# from such a heap load (257,962 static, 179,301 run-time offset), 1,916 are lost at joins or computed, 235 come from another base, 1 from a 64-bit pointer, none from a title buffer through a V#, none built from constants and none edited in dword 6. No scalar instruction reads dword 5, 6 or 7 of a heap T# (dword 1: 8,065, 2: 12,069, 3: 9,177, 4: 3, 0: 1), so the shaders' own maths never sees the word. The translator marks 438,693 (99.84%; 17,474 of the 17,540 modules keep no T# lookup) before the VCC rule, which only adds. Pipeline library, 2,684 programs: 113,585 of 157,410 (72%; 1,649 of 2,235 modules), the rest mostly pointers rebuilt through paths the dataflow does not follow (those run the branch above). Of the carve's 366,628 S# operands, 188,732 come from heap loads, 146,036 are literal and 31,860 from elsewhere. **Cost**, RADV (Mesa 26.3.1) on an RX 7900 XTX, `vk_pipeline_check --stats`: the lighting shader above, instructions 19,714 → 17,568, latency 73,690 → 32,458, inverse throughput 16,453 → 7,468, spilled SGPRs 31 → 17 (its 20 remaining lookups are S#s); a heavy compute shader from the pipeline library (screen-probe ray activation), instructions 40,901 → 36,046, latency 88,291 → 52,359, inverse throughput 20,579 → 13,451, spilled SGPRs 1,007 → 43. **Checked by** `tests/semantic/test_tsharp_index_word.py` (the interpreter reads the image the word names with no table bound; an untagged word, a 3D kind for a 2D load, a dword 3 that names no image and a zero slot read the fallback; a 64-bit-pointer T# looks the table up only without the word; the fixture `ps_tsharp_index_word.s` with a T# loaded in either arm of a branch; the dataflow's static and run-time offsets, a slot read as two halves, VGPR-lane spills, VCC, and the sources that keep the lookup), `runtime/test/gfx10_descriptors_test.cpp` (the word's bits and the key), `shader_library_test` (the census) and the Wine suite's d3d12 tests, which read the word back through `bindless_hash_lookup`. GPU-checked on the Ryzen 9 7950X3D's integrated GPU (RADV RAPHAEL_MENDOCINO, Mesa 26.3.1): `ps_texture_sample` and `ps_table_fetch` load their T# through a table pointer as the title's shaders do and `vk_texture_test` writes the word: the gradient sample and 4096 exact pixels each for SINT, UINT and the miss control (a dword 6 without the tag reads index 0), with no T# lookup in either module. | | Run-time format decode cost | A `buffer_load_format_*` whose format comes from the V# is decoded by table, without a branch: one shared function, `%fmt_dec(format, element, component)`, reads the format's kind, channel count and channel widths from the module table `%fmt_desc_tab`, and the kind picks the conversion with `OpSelect`; the exact UNORM/SNORM quotient comes from the shared `%fmt_norm_bits`, whose width's 64-bit repeat constant is read from `%fmt_norm_rep_tab`. A code outside the table gives zeros, a format with fewer channels repeats its own (component *c* = *c* mod *n*), and the element size is selected from the format alone (`%fmt_size_tab`), the per-lane byte offset added once. Until 2026-11-23 the shared function instead held every format's decode and a binary search over the codes (`OpSelectionMerge` with `DontFlatten`): 3,498 instructions and 306 branches in the module of a shader with one dynamic-format load (250,869 bytes). Then four functions, one per output component, held 565 instructions and no branch, and that module was 56,763 bytes; every load called all four. Over the 1.0.2.1 corpus the 11,400 shaders that use this path all translate and pass \spirv-val\ (the previous translator included), and their modules shrink from 11,163,872,428 to 10,454,474,528 bytes (-6.35%). The 15,103 shaders without a run-time FORMAT come out byte for byte identical (checked on a 297-shader sample, every 51st of them). The values are unchanged: every one of the 128 codes gives the same words as the branch search, checked by `tests/semantic/test_format_decode_table.py` (each code against a reference decoded from the raw bits with exact quotients, plus the branch-free and shared shape). The old translation was confirmed on an RTX 4090 (621.01) against the decode-everything translation: identical output buffers for all 128 codes in four configurations (four byte alignments, out-of-range records, constant DST_SEL), xyzw and d16_xyzw. Since 2026-11-27 the component is the function's last parameter (154 instructions), and a load calls it once per register it writes, with the component that register's DST_SEL picks (DST_SEL − 4; a register whose DST_SEL is 0, 1 or reserved discards the call's value): `buffer_load_format_x` makes one call, not four. The values are the same by construction (the four components' channel width and offset are computed as before and the parameter selects one), checked against the previous translator by the mini interpreter on 22,528 loads (`_x` … `_xyzw` and `d16_x` … `d16_xyzw`, all 128 codes, random DST_SEL, byte alignments and out-of-range records) and on an RTX 4070 Laptop (621.40) by the typed-load GPU tests; `tests/semantic/test_buffer_format_decode_one.py` counts the calls. The function takes the format code, the element's four dwords as a `v4uint` and the component, so its function type has a structure of its own: a type of `uint` × 5 repeats the type of the `x_round` helpers, and SPIR-V forbids two non-aggregate types with the same structure. The branch-free decode costs more ALU per load than the search (every kind's conversion is computed and one is kept), so it trades run time for module size and compile time. | | 3D explicit-gradient texture samples | For `image_sample_d` and `image_sample_d_cl` on a 3D view, the first six address VGPRs contain dP/dx.xyz and dP/dy.xyz. XYZ and the optional minimum LOD follow. With `a16`, the six derivative VGPRs still hold f32; the following two words contain packed f16 coordinates and the optional clamp. The hand-written `tests/semantic/fixtures/volume_gradients.asm` checks the source registers of both gradients, coordinates and clamp. LLVM gfx1030 assembles all four forms and their modules validate for Vulkan 1.2. [LLVM GFX10 address sizing](https://reviews.llvm.org/D102231) and [SPIR-V Grad operands](https://registry.khronos.org/SPIR-V/specs/unified1/SPIRV.html#Image_Operands) | | `image_sample_c_l` | Scalar 2D depth comparison (`dmask:0x1`) takes the f32 reference, XY coordinates and explicit mip in that order. Under A16 the reference stays full-width; XY share a VGPR and LOD uses the next low half. D16 returns the comparison in the low half of the destination. Confirmed against LLVM AMDGPU's `llvm.amdgcn.image.sample[.a16].dim.ll` lowering and synthetic Vulkan 1.2 modules in `test_explicit_mip_depth_compare`. | @@ -439,6 +441,7 @@ How the generated SPIR-V expects the runtime to work: | Workgroup memory limit (SHADER-309) | A compute shader's Workgroup variables, the LDS array plus `%x_buf` (the wave64 exchange, 2·L + 6·W + 7 dwords, or the 3 barrier-round counts, which move into the LDS array when they would push the total past 16,384 B: see "Barrier-round count in LDS (SHADER-579)"), must fit in the device's `maxComputeSharedMemorySize`. `spirv-val` does not check device limits, and RADV (Mesa 27.0.0-devel, RX 7600) dies with SIGFPE in `vkCreateComputePipelines` on a module 4 bytes over 64 KiB (#1721, hand-built repro by YaBulochka). The limit differs per device: 65536 on RADV and NVIDIA, 32768 on the AMD Windows driver (RX 9070 XT, 32.0.32029.2010) and Intel (UHD 770, 101.7092), measured by towade in #1745; the Vulkan minimum is 16384. The translator runs offline, so it has two parts. (1) `rdna2spirv.py` keeps every module under a hard cap, `MAX_SHARED_BYTES` (`--max-shared-memory`, default 65536): the LDS array is the program's need (RSRC2 LDS_SIZE, or the end of the furthest constant-offset access, counted exactly from the offset and the access width: a b32 at offset 65,532 ends at 16,384 dwords) rounded up to a power of two; when that plus `%x_buf` is over the cap but the need still fits, the array shrinks to the RSRC2 allocation and its accesses are bounds-checked (below); when the need itself does not fit (a 64 KiB LDS under `--wave64-emulate`) the shader is refused (`Unsupported`, with the byte counts). The array is clipped to 16,384 dwords, but an RSRC2 allocation over the cap (LDS_SIZE above 128 units, so 66,048 B or more) is counted at its full size and refused, native or emulated, instead of being cut. LDS bounds: RDNA2 LDS does not wrap, and an access outside the workgroup's allocation reads 0 and its write is dropped (RDNA2 ISA sections 3.6.1 and 3.6.6). The wrapped power-of-two array aliases such an access onto a valid word, so when a program's constant offsets reach past its RSRC2 allocation, or the array was shrunk, the array is the allocation and `Gen.lds_access` checks every dword (`index < allocation`, else a read or an atomic's old value is 0 and the write or atomic is skipped): `ds_read*`/`ds_write*` of every width (b64/b96/b128 and read2/write2 per dword), the sub-dword reads and writes, every LDS atomic, `ds_cmpst`, `ds_mskor`, `ds_wrxchg*`. `ds_swizzle`/`ds_bpermute`/`ds_permute` do not use `%lds`; `ds_append`/`ds_consume` were already refused. Every other shader keeps the wrapped array and emits no check, as before. **No game shader takes this path.** Counted over a 1.0.2.1 corpus by towade (#1882, counts only), and again at `main` `aa2988cc` by running `translate()` on every CS: with the exact need (offset + access width), none of the 485 LDS-using CS reaches past its RSRC2 allocation with a constant offset, and none is shrunk, natively or with `--wave64-emulate`. So none gets a bounds check (no `OpULessThan` added), and only the synthetic tests below exercise it. The earlier "16 of 486" came from the older offset + 4-dword estimate; at `aa2988cc` that bound flags 37 of the 485, all inside their allocation. Hypothesis, not yet counted over the corpus: the 16 of 486 LDS-using CS that index past LDS_SIZE with constant offsets (the Compute shaders row) now read 0 there, as the ISA says, where they used to read the wrapped word. Counted over a 1.0.2.1 corpus by towade (#1882, counts only): with the exact need (offset + access width) none of the 485 LDS-using CS reaches past its RSRC2 allocation with a constant offset, so none gets a bounds check (no `OpULessThan` added, native or emulated); the "16 of 486" in the Compute shaders row came from the older offset + 4-dword estimate. `%x_buf` is already sized to the workgroup's waves, so it has nothing to give back. `lds_bytes` in `index.json` is the module's whole Workgroup total (LDS, `%x_buf`, a mesh shader's `%ms_counts`). (2) The D3D12 shim's `create_compute` compares `lds_bytes` with the device's `maxComputeSharedMemorySize` and refuses the pipeline with a log line (`E_NOTIMPL`) instead of creating an invalid one. Pinned by `tests/semantic/test_cs_shared_memory_limit.py` (Workgroup bytes counted from the emitted SPIR-V: under the cap unchanged, shrunk to the 51,200 B allocation and bounds-checked, the exact-cap boundary, an access ending at 64 KiB counted exactly, a 64 KiB LDS refused when emulated and accepted natively, a native 66,048 B allocation refused, run through `spirv_mini_interp`: an out-of-range write dropped with the word it would wrap to intact, out-of-range reads (b32, u16) giving 0, a b64 write straddling the allocation's end, out-of-range atomics returning 0 and changing nothing, and an in-range shader with no check; `lds_bytes` equal to the SPIR-V total) and `shader_library_test` (`lds_bytes` read from the index). Confirmed by those CPU tests only; GPU runs (RADV; AMD Windows and Intel at 32 KiB) are pending. Not covered: mesh shaders against `maxMeshSharedMemorySize`. | | Wave64 leading-bit scans | With `--wave64-emulate`, `s_flbit_i32_b32` and `s_flbit_i32` of a lane mask use the same wave-wide exchange as `s_bcnt1` and `s_ff1`. These reads prevent lane-local EXEC-zero folding and require synchronized scheduling in wave-divergent blocks. Plain scalar inputs still allow the fold. Hand-written compute shaders in `tests/semantic/test_wave64_emulate_opt.py` check EXECZ at 64 and 128 threads and a branch on SCC taken by just one wave at 128 threads. The strict CPU workgroup interpreter observes the unsigned scan of VCC_LO = 8 returning 28 in the expected invocations. Both scan forms pass `spirv-val --target-env vulkan1.2`. | | Wave64 emulation: scalar exits from a folded EXECZ region | A folded lane-local `s_cbranch_execz`/`execnz` region may leave to its join from inside, for example `s_cmp` + `s_cbranch_scc0/scc1` straight to the label that restores EXEC. The ISA then skips the rest of the region for the whole wave. `find_local_exec_folds` in `tools/wave64_emulate_opt.py` builds the region's sub-CFG with an exit node for every edge to the join, so `cfg_structure.structure` puts each later block of the region behind a `%pc` guard; the exit node itself emits nothing. Before this the edge was dropped and the block after the branch ran whenever the lane was active. Confirmed on the CPU against the native wave64 translation and the ISA: `tests/semantic/test_wave64_emulate_opt.py` `test_folded_region_scalar_branch_to_join_skips_the_rest` (taken and not-taken `scc0`/`scc1`, 64 and 128 threads, the region still folded) fails before the change on the four taken cases. **Not GPU-verified.** | +| Pure scalar-spill VGPRs (`v_writelane_b32` / `v_readlane_b32`) | A VGPR touched only by immediate-lane `v_writelane_b32` (non-VGPR source) and immediate-lane `v_readlane_b32` (never read or written as a vector operand, never aliased by `v_movrel*`/`v_swaprel_b32`, and with every read lane definitely written on all CFG paths before it is read) is lowered to parked `%sgpr` slots (`lane_masks.scalar_spills`, `Gen.scalar_spills`) across all stages and wave sizes (wave32 and wave64), instead of emitting `OpGroupNonUniformShuffle`. On RDNA2 hardware `v_writelane_b32`/`v_readlane_b32` ignore `EXEC` and access physical lane `K` even when lane `K` is inactive; in Vulkan SPIR-V, `OpGroupNonUniformShuffle` from an inactive or unlaunched invocation (e.g. a small fragment triangle or post-discard wave) is undefined and returns stale VGPR bits, which corrupted spilled V# base addresses in wave32 fragment shaders. Confirmed by corpus count over the full 1.0.2.1 shader corpus (`1,031` wave32 and `385` wave64 pure scalar-spill VGPRs, `0` mixed; all `1,173` `v_writelane_b32` shaders translate and pass `spirv-val`), CPU-checked by `tests/semantic/test_wave32_pixel_subgroup64.py` (`test_scalar_spill_vgpr_survives_absent_lanes`, absent lanes `0..3` and single-quad waves on 32- and 64-lane subgroups), and GPU-confirmed on an AMD Radeon RX 7900 XTX (RADV Mesa 26.3.1, two 240 s fast-load runs at `0.0 s` warm graphics PSO compile time, zero GPUVM faults). | | Wave64 emulation: cross-lane reads of missing lanes | With `--wave64-emulate`, a read of another lane's exchange slot (`ds_swizzle_b32`, `ds_bpermute_b32`, `ds_permute_b32`'s targets and data, `v_readlane_b32`, `v_readfirstlane_b32`, DPP and the other reads behind `Gen.x_round`) gives 0 when the source lane doesn't exist in a partial last wave (`Gen.x_lane_word`: `x_wbase + lane < threads`, else 0), as a source lane that isn't running reads 0 on the hardware. The prologue still zeroes those slots, but a read must not depend on it: RADV (Mesa 26.3.1, gfx1036 iGPU and RX 7900 XTX) compiled the store, barrier and load of an exchange behind a branch into `masked_swizzle_amd` with `fetch_inactive` (`RADV_DEBUG=shaders`), so in a 40-thread group lanes 32-39 of `ds_swizzle_b32 offset:swizzle(SWAP,8)` read the missing lanes' registers, garbage that changed between runs. Workgroups whose size is a multiple of 64 emit the same module as before. Confirmed by `runtime/test/shaders/cs_w64x_partial_swizzle.asm` (40 threads: SWAP 8, BROADCAST 16,15 and `ds_bpermute_b32` from lanes 40-47; its 8 words measured natively on gfx1036 through `tools/hw_oracle`): emulated at subgroup 32 (RADV, Mesa 26.3.1), words 2 and 3 wrong before in 20 of 20 runs on the gfx1036 iGPU and 19 of 20 on the RX 7900 XTX, and all 8 words right in 20 of 20 runs on both after; native wave64 and emulated at subgroup 64 right both times. `scripts/run_gpu_tests.py` runs the partial-wave fixtures emulated at subgroup 32, as `check.py` does, since at RADV's default of 64 this fixture passed before the change too; by `crosslane_fuzz.py --wave 64 --ext --dpp --no-maskdata --programs 1000 --seed 48315`, emulated: on the gfx1036 iGPU 993 match and 7 hyp_only (all 40-thread groups, lanes 32-39 reading a swizzle source of 40-47) before, 1000/1000 after, and on the RX 7900 XTX 995 match and 5 hyp_only before, 1000/1000 after; and by `tests/semantic/test_w64x_partial_swizzle.py` (fixture `w64x_partial_swizzle.asm`, 40 and 104 threads, the prologue's zero stores replaced by a poison word in the workgroup interpreter; both cases fail before the change). | | Barycentric fallback (`--bary-fallback`) | For devices without `VK_KHR_fragment_shader_barycentric` (NVIDIA Pascal, for one), and for Mesa ANV's known BaryCoordKHR.i bug (SHADER-925). The raw pair a PS reads comes from an ordinary vec3 input, `%bary`, at the lowest location none of the shader's attributes uses, instead of `BuiltIn BaryCoordKHR`. The module needs neither the `FragmentBarycentricKHR` capability nor the extension, and the index records the location as `bary_fallback_input`. `tools/bary_fallback_gs.py` writes a pass-through geometry shader that supplies (1,0,0), (0,1,0), (0,0,1) at the triangle vertices. GPU-checked on NVIDIA Pascal and Intel Arc B580/Mesa ANV: ANV native `ps_uniform_branch` and `ps_scc_mask32` fail with i=0.0, while the fallback passes and `ps_bary` passes natively. `make_game.py` and `scripts/run_gpu_tests.py` select the fallback automatically for Mesa ANV. `LEONIDA_BARY_FALLBACK=1` forces fallback and `LEONIDA_BARY_FALLBACK=0` forces native barycentrics consistently in both entry points; explicit `--bary-fallback` also forces the fallback in `make_game.py`. The standalone `build.py`/`check.py` path follows the same variable/probe rule. Checked in `tests/semantic/test_bary_fallback.py` and the builder/runner wiring tests. | | Wave64 emulation: a folded region at most one lane runs (SHADER-W64-ONE-LANE-FOLD) | A compute shader picks one thread for a tail (clear LDS, then after a barrier sum it up and store) with `v_cmpx_eq_u32 c, v0` or `v_cmp_eq_u32 m, c, v0` + `s_and_saveexec_b64 _, m`. `v0` is LocalInvocationId.x and a wave is 64 consecutive threads, so no two lanes of a wave share it when the group is one row (`size_y * size_z == 1`) or a row is whole waves (`size_x % 64 == 0`); then the compare is true in at most one lane. `_one_lane_in` in `tools/wave64_emulate_opt.py` proves per block, forward over the CFG with intersection at joins, that EXEC is at most one lane: `v0` must not have been written since entry, and the mask goes on through `s_mov_b64`, `s_and_b64` with anything, `s_andn2_b64` of it, a saveexec of it and any later compare (a compare is 0 in inactive lanes). A write of one half of EXEC (`exec_lo`/`exec_hi`, which the emitter writes as that half only) keeps the fact only when EXEC already had it and the half written is within it (a compare): the other half keeps its lanes, so `v_cmp_eq_u32 exec_lo, 0, v0` from a full EXEC leaves lanes 32-63 on. The assembler's short form `v_add_co_ci_u32 vD, src0, src1` (also `sub`, `subrev`) gets its VCC carry-out and carry-in operands when the listing is read (`explicit_carry_vcc` in `tools/rdna2spirv.py`), so every analysis sees the VCC it writes. Where `run` of an `s_cbranch_execz` region is proved so, `find_local_exec_folds` drops the one-store-per-domain and acyclic limits and marks the fold `one_lane` (the region's EXEC writes already must keep a skipped lane inactive, so it stays at most one lane): with one lane the lane's own order of its accesses is the wave's, so `x_memory_order` orders nothing inside it. A one-block region that branches back to itself is emitted as a loop through `cfg_structure.structure` like a multi-block region; emitted straight it ran once (also for a read-only loop, before this row). A `v_readfirstlane_b32` is allowed in such a fold when the region writes no EXEC at all: the lane runs the fold only when active, so it is the first lane of EXEC and the result is its own value (also into `vcc_lo`/`vcc_hi`). Confirmed on the CPU against the plain round emulation in both invocation orders: `tests/semantic/test_wave64_one_lane_fold.py` (128 threads; LDS writes, a barrier, first-lane reads and two stores to one address; a lane of wave 0, of wave 1, or none; the negatives `v_cmpx_eq` of a non-id VGPR, `v0` overwritten, `v_cmpx_gt`, and a 32 x 4 group are not marked one-lane; picks in lanes 32-63 of either wave; a one-block self-loop with and without a store, which ran once before; `v_cmp_eq_u32_e64 exec_lo, 0, v0` from a full EXEC, which was marked one-lane before; and the short and explicit `v_add_co_ci_u32` carry into VCC after a one-lane compare, whose short form was marked one-lane before). One 1024-thread library compute shader goes from 639 to 33 `OpSwitch` cases and passes `spirv-val`. **Not GPU-verified.** | @@ -448,7 +451,8 @@ How the generated SPIR-V expects the runtime to work: | Wave-uniform branches | VCC and EXEC are wave-wide registers, but one invocation holds only its own lane's bit. `s_cbranch_vccz/vccnz/execz/execnz` therefore reduce the condition across the subgroup (`OpGroupNonUniformAny`), so the whole wave takes the branch together, as on hardware. Before this, each lane decided alone. A lane could skip scalar instructions that the hardware wave executes (its SGPRs went stale for later code), and cross-lane ops or barriers inside the block saw a split wave. `v_cmp`/`v_cmp_class`/64-bit compares now write 0 for inactive lanes (hardware VOPC behaviour), so the reduction sees the true mask. GPU-checked with `runtime/test/shaders/ps_uniform_branch.asm`: lanes whose own VCC bit is 0 run the block's scalar add when their wave has any set bit. `s_cbranch_scc0/1` stay per lane; SCC is uniform as long as the SGPRs feeding it are. | | Compute shaders | FSSM header word **0x138 = `COMPUTE_PGM_RSRC2`**: USER_SGPR [5:1], TGID_X/Y/Z_EN [9:7], TG_SIZE_EN [10], TIDIG_COMP_CNT [12:11], LDS_SIZE [23:15] in 512-byte units. Words **0x13C/0x140/0x144 = thread-group size**. Counted over all 2,689 CS listings of 1.0.2.1 by the SGPRs each reads before writing (operand roles from `shader_meta._split_operands`, over the code `translate()` keeps; in wave64 code a lane mask printed as one SGPR covers the pair; an earlier check gave 2,281 exact): 2,540 read nothing past the user SGPRs and enabled TGIDs (2,193 up to the last of them, 342 fewer, 5 none), and the other 149 overshoot only through loop-carried registers in the straight-line check: every extra read follows a branch, and the register is written later in program order. Followed through the CFG (written on every path before the read), 22 still overshoot; each extra register is written on some other path (only loop-carried ones in 15), so these are values undefined on some path, not a missing input. Read raw, 268 overshoot: the other 119 are listings with embedded data words, decoded as instructions. 0x110, which looked similar, doesn't match. Layout: s0..user−1 = user data (push constants), then the enabled workgroup IDs (`WorkgroupId`), and v0/v1/v2 = thread ID x/y/z (`LocalInvocationId`, separate VGPRs on GFX10). Example: the 1,013 shaders with RSRC2 `0x998` have 12 user SGPRs, group ID x/y in s12/s13, and compute x = s12·32 + v0. With TG_SIZE_EN (none of the 2,689; 91 compute programs of the pipeline library, [shader_library.md](shader_library.md)) the next SGPR is the thread-group word, which the prologue writes: the number of waves in the group in bits [5:0] and this wave's index in it in bits [11:6], the wave index again in bits [24:20] and bit 31 set in the group's first wave (measured on gfx1036 through `tools/hw_oracle`, #6446: wave32 x 128 threads gives `80000004 00100044 00200084 003000c4`; one library program reads [24:20]; not measured on gfx1013) (Mesa `ac_nir_lower_intrinsics_to_args.c`, GFX6-10: `load_num_subgroups` and `load_subgroup_id` read those fields, and a wave64 compute shader's local invocation index is `mbcnt(~0, tg_size & 0xfc0)`; the library programs read it as `s_and_b32 sN, sTG, 0xfc0`, most of them then `v_mbcnt_lo_u32_b32`). Thread i is in wave i / W, as for `s_get_waveid_in_workgroup`. CPU-checked by `tests/semantic/test_cs_tg_size.py`, including the gfx1036 words. GPU-checked with `runtime/test/shaders/cs_lds.asm` through `runtime/test/vk_compute_test.cpp`: 4 groups × 64 threads, LDS exchange between the two waves of a group behind `s_barrier`, store through a V# into the device-address heap, 0 mismatches. | | Scalar copies through VCC | SGPRs 106 and 107 can hold two data words, including a buffer descriptor's count and format. A 64-bit move through VCC preserves both when its reads within the block use them as data. Predicate users and live-out VCC constrain this inference. A wide scalar load into a tuple ending in VCC writes both physical words. The synthetic descriptor fixture checks numeric copies, a round trip, and a subsequent tuple load on wave32 and emulated wave64. | -| Signed-byte dot products | `v_dot4_i32_i8 D, S0, S1, S2` (VOP3P) is S2 plus the sum of the four products of the sign-extended bytes of S0 and S1, modulo 2^32; `v_dot4c_i32_i8 D, S0, S1` (VOP2) adds the same sum to D. Emitted as four pairs of `OpBitFieldSExtract`, `OpIMul` and `OpIAdd`. **Confirmed on RDNA2 hardware** (gfx1036, raw kernels through `tools/hw_oracle`): 10 operand sets, both instructions and both source orders of the accumulating one, with sign-mixed bytes and sums that wrap; the measured words are the table in `tests/semantic/test_alu_dot4_i8.py`. `clamp` and `op_sel`/`op_sel_hi` are translated and checked against the same `gfx1036` hardware table: `clamp` saturates `v_dot4_i32_i8` to signed 32-bit `[-2^31, 2^31-1]` (both overflowing sets), and `op_sel`/`op_sel_hi` pick the 16-bit half of S0/S1 for byte pairs 0..1 and 2..3 (e.g. `op_sel` 2 / `op_sel_hi` 5 exchanges the 16-bit halves of S1, matching all 5 measured sets — the form of the 89 words `llvm-mc` does not decode, [fspx.md](fspx.md)); non-default S2 half selection stays refused. 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). | +| 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 one `OpSDot` (row *Packed 4x8-bit dot products as SPV_KHR_integer_dot_product*), or with `--integer-dot-fallback` 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). | +| Packed 4x8-bit dot products as SPV_KHR_integer_dot_product | `v_dot4_i32_i8`, `v_dot4c_i32_i8`, `v_dot4_u32_u8` and `v_dot4c_u32_u8` are one instruction of SPV_KHR_integer_dot_product on the two dwords read as `PackedVectorFormat4x8Bit` (`Gen.packed_dot4`): `OpSDot` on `%int` operands for the signed bytes, `OpUDot` for the unsigned ones, and the addend (S2, or the old D of the VOP2 forms) added with `OpIAdd`, which wraps at 32 bits as the instructions do; under `clamp`, `OpSDotAccSat` / `OpUDotAccSat`, which saturate the addend plus the exact sum to the result's signed or unsigned range, as the hardware does (the *Signed-byte dot products* and *Packed integer dot products* rows; the spec computes both "with enough precision to avoid overflow", so the plain forms are the low 32 bits of the exact sum). `op_sel` / `op_sel_hi` on S0 and S1 of `v_dot4_i32_i8` pick 16-bit halves (measured, row above): `Gen.dot4_halves` puts the two halves together into one dword first (two `OpBitFieldUExtract` and one `OpBitFieldInsert`; nothing for the default). Capabilities `DotProductKHR` and `DotProductInput4x8BitPackedKHR`, extension `SPV_KHR_integer_dot_product`, index feature `shaderIntegerDotProduct`, which Vulkan 1.3 requires and the runtime enables (`runtime/src/vulkan13_features.h`; it logs `the GPU has no shaderIntegerDotProduct` without it). The 16-bit forms (`v_dot2_*`) match `OpSDot` / `OpUDot` on 16-bit vectors too, but need `Int16` and `DotProductInputAllKHR` and no module of the corpus has one, so they keep the expanded form, as `v_dot8_*` (4-bit elements have no SPIR-V form). **`--integer-dot-fallback`** keeps the expanded form (four extracts, multiplies and adds) for a device without the feature: `tools/vk_subgroup_info.py` reports `integer_dot_product`, and `make_game.py` turns the flag on where it is false (a Vulkan 1.2 device such as MoltenVK's), as it does `--f16-interp-fallback`. Why: RADV (Mesa 26.3.1) does not re-form `v_dot4` from the expansion, so each one was about 16 VALU instructions. **Confirmed** by `tests/semantic/test_packed_dot4.py` (fixtures `packed_dot4_i8.asm` and `packed_dot4_u8.asm`: the gfx1036-measured words of `test_alu_dot4_i8.py`, both saturations, `op_sel` against the measured rule, the same words under the fallback), `tools/dot_diff.py` (767 of 767 programs on the four ops, 30/34 and 54/57 saturated / wrapped edge results), a wave32 compute program on the GPU with both forms on the Radeon iGPU (gfx1036, RADV 26.3.1) and the RX 7900 XTX: the same eight words, seven of them the gfx1036 hardware measurements (wrapping and clamped sums, `v_dot4c_i32_i8`, mixed-sign bytes) and the eighth the unsigned reference. RADV statistics (`vk_pipeline_check --stats`, RX 7900 XTX) for the FidelityFX passes: `amd_fidelityfx_upscaler_xbox_04` 16,166 → 7,463 instructions, 216 → 96 VGPRs, 7 → 16 waves per SIMD; `_09` 106,348 → 74,888, `_06` 164,387 → 116,896 and `_08` 108,503 → 75,465 instructions with 192 → 120 VGPRs and 8 → 12 waves (static counts with this rule and the *Wide scalar loads* one, which include the per-dword path that row keeps for partly out-of-range loads; the dot products alone gave 105,726 for `_06`); `_27`, without `v_dot4`, 10,019 → 10,027. A synthetic program of 1,024 `v_dot4c_i32_i8` with distinct weights runs in 0.55 ms instead of 5.45 ms on the RX 7900 XTX (the same output words) per 65,536 groups. Count over the corpus (1.0.2.1): the four ops are in 13 modules, all FidelityFX DLL programs (`v_dot4c_i32_i8` 25,813, `v_dot4_i32_i8` 1,458 plain and 89 with `op_sel`; no `clamp`, no `u8` form); translating the 25,878 modules either rule touches gives 25,877 translated and 25,877 passing `spirv-val` before and after (the one left is a pipeline-library program that fails the same way before). | | 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. | @@ -535,11 +539,11 @@ How the generated SPIR-V expects the runtime to work: | `v_cmp_class_f16`, `v_cmpx_class_f16`, `v_cmp_class_f64`, `v_cmpx_class_f64` | IEEE-754 floating-point class tests against the 10-bit class mask (`0: sNaN, 1: qNaN, 2: -inf, 3: -normal, 4: -denormal, 5: -0, 6: +0, 7: +denormal, 8: +normal, 9: +inf`), writing VCC/SGPR or narrowing EXEC (`v_cmpx`). Computed bit-exactly on integer words (so `sNaN` is never quieted by float ops and `v_cmp(x)_class_f64` does not require `OpCapability Float64`): `f16` reads both the value operand (`op_sel[0]`) and the class mask operand via `src_h` (so float inline constants like `0.5`, `1.0`, `-2.0`, `0.15915494` take their 16-bit binary16 value over a zero high half before SDWA selection, matching `tools/sdwa_diff.py --oracle hw` on RDNA2 `gfx1036`; until 2026-11-23 `cmp_class` read the mask with `src_u`, turning inline float constants into 32-bit binary32 bits and failing `sdwa_diff --ops v_cmp_class_f16` 12/500) and applies `abs`/`neg` on bits `[15:0]`; `f16` reads the selected half (`op_sel[0]`, inline f16 constants via `src_h`) and applies `abs`/`neg` on bits `[15:0]`; `f64` reads the `(lo, hi)` pair (32-bit literals placed in the upper word with `lo = 0` per RDNA2 ISA) and applies `abs`/`neg` on `hi`. Output modifiers (`clamp`, `mul:*`, `div:*`) and unsupported `op_sel` bits raise `Unsupported`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) (VOPC `V_CMP_CLASS_F16/F64`, `V_CMPX_CLASS_F16/F64`). Checked bit-for-bit across all 10 classes on the CPU (`spirv_mini_interp`) and with `spirv-val` by `tests/semantic/test_alu_cmp_class_f16_f64.py`, and across 500 SDWA programs (`v_cmp_class_f16`, 0 mismatches) via `tools/sdwa_diff.py`; **not GPU-verified** and not run on the shader corpus. . **Hardware-measured natively on `gfx1100`** (RX 7900 XTX, driver 26.10.1) with `tools/hw_oracle`, 85 cases, all matching the operand's own bits: the ten classes on ten `f16` words (`0x7c01` sNaN, `0x7e00` qNaN, `0xfc00` -inf, `0xbc00` -normal, `0x8001` -denormal, `0x8000` -0, `0x0000` +0, `0x0001` +denormal, `0x3c00` +normal, `0x7c00` +inf) and on ten `f64` pairs, each against its own class bit, all ten bits, no bits and the nine other bits (80), plus both `v_cmpx` forms on the launched lane (5). Not measured: `abs`/`neg`/`op_sel`, an inactive lane's `vdst`/`EXEC` under `v_cmpx`, wave64, and the shader corpus. | | Float-to-byte pack | `v_cvt_pk_u8_f32` rounds to nearest even (the default MODE round mode; the hardware follows the MODE register's f32 round mode, which the translator ignores, see #358), clamps to [0, 255], and gives 0 for NaN and negative values, then inserts the byte at `src1[1:0]` of `src2` and keeps the other three. NaN is replaced by +0 before `FClamp`, which is undefined for a NaN operand. **Measured natively** on RDNA2 (gfx1036, the Ryzen 7 9800X3D iGPU, AMD driver 25.10, the instruction run through inline assembly): all 256 inputs k + 0.5 round to even, 0.5 gives 0, 0x3f000001 gives 1, +inf and 300.0 give 255, -inf, -1.0, ±0, denormals and quiet, signalling and negative NaNs give 0 (#358). `cs_cvt_pk_u8.asm` holds eight of these words, checked by `check.py`/`run_gpu_tests.py` and bit-for-bit by `tests/semantic/test_cvt_pk_u8.py`. | | Known approximations | `v_cvt_pkrtz_f16_f32` is now **exact round-toward-zero** (finite overflow gives ±65504, not inf). The GPU smoke test caught the old round-to-nearest version producing inf in `PS_ImposterShadow`. The other f16 packs (`v_cvt_f16_f32`, d16 results, mix ops) round to nearest, which matches the default mode; the ALU ones follow a MODE toward-zero write (see the f16 rounding row). `v_fma_mixlo/mixhi_f16` round the exact `x*y+z` once in every mode (measured on an RDNA2 iGPU, gfx1036, 7 of 7 discriminating tie inputs, SHADER-135); the translator does that in both modes through `Gen.fma_mix_odd`; the ALU ones follow a MODE toward-zero write (below; `v_fma_mixlo/mixhi_f16` round the exact `x*y+z` once in every mode (measured on an RDNA2 iGPU, gfx1036, 7 of 7 discriminating tie inputs, SHADER-135); toward zero the translator does that already, while in nearest-even mode it still narrows an f32 `Fma`, which is 1 f16 ulp off on ties until #1774 (SHADER-296) lands; the ALU ones follow a MODE toward-zero write (below; ALU sites: see the f16 rounding row). MODE: `s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2)` (f16/f64 rounding) is tracked in a per-invocation variable, the only MODE field the corpus writes (9,417 writes in 6,333 shaders: 6,694 toward zero, 2,723 back to nearest even). While it is toward zero, every VALU f16 result except the transcendentals listed below (`v_cvt_f16_f32`, f16 arithmetic, `v_pk_*_f16`, `v_fma_mix{lo,hi}_f16`, `v_interp_p2_f16`) rounds toward zero exactly, with the integer conversion `v_cvt_pkrtz_f16_f32` uses (`f16_bits(rtz=True)`, see the f16 rounding row), and `v_add_f64` steps back one ulp when the TwoSum error shows it rounded away from zero; finite overflow gives the largest finite value. The `v_add_f64` output modifiers apply after that step and round to nearest, so an omod that overflows or lands on a subnormal is not toward zero. **omod versus denormal mode is unmodelled:** the translator applies `mul:2`/`mul:4`/`div:2` regardless of the MODE denormal fields (as before this change), whereas hardware ignores omod when denormals are kept (denorm fields = 3) and applies it when they are flushed (both measured on an RX 6800: `v_add_f64 (1 - 2^-60) mul:2` with denormals kept gave 3ff00000:00000000 nearest and 3fefffff:ffffffff toward zero, unscaled; mul:2 was applied with denormals flushed); the tests therefore claim no omod order. CPU-checked by `tests/test_mode_round.py` (the RX 6800 words for f16 add/sub, `v_fma_mix`, the transcendentals, f64 overflow). f16 add and sub (f16 operands) and `v_pk_add_f16` take the exact TwoSum error of the f32 result into account, so they are exact toward zero too (f32 then f16 rounding alone would be wrong: 2 - 2^-24 is an f32 tie that rounds up to 2.0); f16 FMAs need nothing extra, since their round-to-odd f32 value (SHADER-55) narrows exactly in either mode. `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, in both nearest-even and toward-zero modes (measured on AMD RDNA2 gfx1036, finding 7079901079; an RX 6800 gave 0x3fff for 1 * 2 - 2^-30, where rounding to f32 first and then narrowing gives 0x4000): `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, in both nearest-even and toward-zero modes (measured on AMD RDNA2 gfx1036 across 7 of 7 discriminating tie inputs with `tools/fma_mix_probe.py --oracle hw`, SHADER-135, finding 7079901079, and on an RX 6800 where toward zero gave 0x3fff for 1 * 2 - 2^-30 vs 0x4000 with double rounding; fixed for nearest mode in SHADER-296 / #1774; see docs/shader_validation.md, "`v_fma_mix*` f16 rounding in nearest mode"): `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, toward zero (an RX 6800 gave 0x3fff for 1 * 2 - 2^-30, where rounding to f32 first and then narrowing gives 0x4000): `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, in both nearest-even and toward-zero modes (measured on AMD RDNA2 gfx1036 and verified by `tools/fma_mix_probe.py`; finding 7079901079; toward zero an RX 6800 gave 0x3fff for 1 * 2 - 2^-30, where rounding to f32 first and then narrowing gives 0x4000): `Gen.fma_mix_odd` corrects the f32 `Fma` to round-to-odd by the sign of its exact residual (product error by `Fma(x, y, -x*y)`, TwoSum of the sum), which narrows exactly in either direction; the nearest-even path is unchanged (f32 `Fma`, then narrow). `fma_mix_odd` also handles a tiny product ( \| a x*y \| >= < 2^-64: its error underflows or is flushed, so the residual sign is sign(x) xor sign(y), independent of the driver's denormal mode) and an f32 overflow with finite operands (toward zero gives ±FLT_MAX, so f16 ±65504). `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`, `v_exp_f16` and `v_log_f16` ignore the rounding mode on hardware, so they always narrow to nearest even; all seven are measured (an RX 6700 XT gave the same words with FP_ROUND round-toward-zero and round-to-nearest on every input of each; see the f16 transcendentals row). `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`, `v_exp_f16` and `v_log_f16` ignore the rounding mode on hardware (RX 6800 for the first four, plus an exhaustive 65,536-input RNE vs RTZ sweep of all seven in wave32 and wave64 on native `gfx1036` via `tools/mode_round_probe.py`, SHADER-132: 0/65,536 inputs differ on every op; the same probe also confirmed all 17 f16/f64 RNE vs RTZ cases including `v_cvt_f16_f32`, `v_add/sub/mul/fma_f16`, `v_pk_add/fma_f16`, `v_fma_mix{lo,hi}_f16` and `v_add_f64` overflow saturation in both wave32 and wave64), so they always narrow to nearest even. In nearest mode the hardware rounds once as well: `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`, `v_exp_f16` and `v_log_f16` ignore the rounding mode on hardware, so they always narrow to nearest even; all seven are measured (an RX 6700 XT gave the same words with FP_ROUND round-toward-zero and round-to-nearest on every input of each, see the f16 transcendentals row; independently confirmed by an exhaustive 65,536-input RNE vs RTZ sweep of all seven in wave32 and wave64 on native `gfx1036` via `tools/mode_round_probe.py`, SHADER-132: `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16` and `v_sin_f16` ignore the rounding mode on hardware (RX 6800: the same words in every mode), so they always narrow to nearest even; `v_cos_f16`, `v_exp_f16` and `v_log_f16` are unmeasured, assumed like those four and treated the same. The "every VALU f16 result rounds toward zero" sentence above therefore excludes these seven; the f16 results of `v_floor/ceil/trunc/rndne/fract_f16` are exact and need no rounding. `tools/fma_mix_probe.py --oracle hw` on an RDNA2 iGPU (gfx1036, SHADER-135) gave the single-rounded word for all seven inputs where the two rules differ by one f16 ulp, as `Gen.fma_mix_odd` produces (docs/shader_validation.md, "`v_fma_mix*` f16 rounding in nearest mode"). In nearest mode the translator still rounds `v_fma_mix{lo,hi}_f16` twice (f32 `Fma`, then narrow), but the hardware rounds once there as well: `tools/fma_mix_probe.py --oracle hw` on an RDNA2 iGPU (gfx1036, SHADER-135) gave the single-rounded word for all seven inputs where the two rules differ by one f16 ulp, so the translator, which rounded twice there (f32 `Fma`, then narrow) until #1774, was one f16 ulp off on exactly those ties (docs/shader_validation.md, "`v_fma_mix*` f16 rounding in nearest mode"; the fix is `Gen.fma_mix_odd` in nearest mode too, SHADER-296). Nearest-mode `v_fma_mix*` still rounds twice (f32 `Fma`, then narrow): main's behaviour, unmeasured. `tools/fma_mix_probe.py --oracle hw` measures it on an AMD GPU, with seven inputs where the two rules differ by one f16 ulp (docs/shader_validation.md). The `v_add_f64` step needs f64 denormals preserved (not flushed) by the driver for subnormal sums. Shaders that never write MODE emit the same code as without this. Writes to other MODE bits (f32 rounding, denormals), directed rounding (+inf/-inf) and register-valued writes are refused, so nothing changes silently; none occur in the corpus. Denormal behaviour is still Vulkan's default. Format conversions in memory and texture units don't follow MODE. `v_mul_legacy_f32` now keeps the `0 × anything = 0` rule like `v_mad_legacy_f32` (GPU-checked with `runtime/test/shaders/ps_legacy_mul.asm` on AMD Radeon RX 9070 XT). \| b \| `, `FastTwoSum`: `bb = r - a`, `e = b - bb`) and steps back one ulp when the rounding error shows it rounded away from zero; finite overflow gives the largest finite value (unordered `TwoSum` `r - x` can overflow to `±inf` and yield `NaN` error for opposite-sign finite operands with ` \| x \| < \| y \| ` near `±DBL_MAX`, e.g. `0x7fdd9bb47daa1333 + 0xffefffffffffffff` found by `@Jolymmiles`; GPU-checked with `runtime/test/shaders/ps_f64_round.asm` on NVIDIA GeForce RTX 5060 Ti, 4096/4096 pixels exact). The `v_add_f64` output modifiers apply after that step and round to nearest, so an omod that overflows or lands on a subnormal is not toward zero. **omod versus denormal mode is unmodelled:** the translator applies `mul:2`/`mul:4`/`div:2` regardless of the MODE denormal fields (as before this change), whereas hardware ignores omod when denormals are kept (denorm fields = 3) and applies it when they are flushed (both measured on an RX 6800: `v_add_f64 (1 - 2^-60) mul:2` with denormals kept gave 3ff00000:00000000 nearest and 3fefffff:ffffffff toward zero, unscaled; mul:2 was applied with denormals flushed); the tests therefore claim no omod order. CPU-checked by `tests/test_mode_round.py` (the RX 6800 words for f16 add/sub, `v_fma_mix`, the transcendentals, f64 overflow). f16 add and sub (f16 operands) and `v_pk_add_f16` take the exact TwoSum error of the f32 result into account, so they are exact toward zero too (f32 then f16 rounding alone would be wrong: 2 - 2^-24 is an f32 tie that rounds up to 2.0); f16 FMAs need nothing extra, since their round-to-odd f32 value (SHADER-55) narrows exactly in either mode. `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, in both nearest-even and toward-zero modes (measured on AMD RDNA2 gfx1036 across 7 of 7 discriminating tie inputs with `tools/fma_mix_probe.py --oracle hw`, SHADER-135, finding 7079901079, and on an RX 6800 where toward zero gave 0x3fff for 1 * 2 - 2^-30 vs 0x4000 with double rounding; fixed for nearest mode in SHADER-296 / #1774; see docs/shader_validation.md, "`v_fma_mix*` f16 rounding in nearest mode"): `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, toward zero (an RX 6800 gave 0x3fff for 1 * 2 - 2^-30, where rounding to f32 first and then narrowing gives 0x4000): `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, in both nearest-even and toward-zero modes (measured on AMD RDNA2 gfx1036 and verified by `tools/fma_mix_probe.py`; finding 7079901079; toward zero an RX 6800 gave 0x3fff for 1 * 2 - 2^-30, where rounding to f32 first and then narrowing gives 0x4000): `Gen.fma_mix_odd` corrects the f32 `Fma` to round-to-odd by the sign of its exact residual (product error by `Fma(x, y, -x*y)`, TwoSum of the sum), which narrows exactly in either direction; the nearest-even path is unchanged (f32 `Fma`, then narrow). `fma_mix_odd` also handles a tiny product ( \| x*y \| < 2^-64: its error underflows or is flushed, so the residual sign is sign(x) xor sign(y), independent of the driver's denormal mode) and an f32 overflow with finite operands (toward zero gives ±FLT_MAX, so f16 ±65504). `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`, `v_exp_f16` and `v_log_f16` ignore the rounding mode on hardware (RX 6800 for the first four, plus an exhaustive 65,536-input RNE vs RTZ sweep of all seven in wave32 and wave64 on native `gfx1036` via `tools/mode_round_probe.py`, SHADER-132: 0/65,536 inputs differ on every op; the same probe also confirmed all 17 f16/f64 RNE vs RTZ cases including `v_cvt_f16_f32`, `v_add/sub/mul/fma_f16`, `v_pk_add/fma_f16`, `v_fma_mix{lo,hi}_f16` and `v_add_f64` overflow saturation in both wave32 and wave64), so they always narrow to nearest even. In nearest mode the hardware rounds once as well: `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`, `v_exp_f16` and `v_log_f16` ignore the rounding mode on hardware, so they always narrow to nearest even; all seven are measured (an RX 6700 XT gave the same words with FP_ROUND round-toward-zero and round-to-nearest on every input of each; see the f16 transcendentals row). `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16` and `v_sin_f16` ignore the rounding mode on hardware (RX 6800: the same words in every mode), so they always narrow to nearest even; `v_cos_f16`, `v_exp_f16` and `v_log_f16` are unmeasured, assumed like those four and treated the same. The "every VALU f16 result rounds toward zero" sentence above therefore excludes these seven; the f16 results of `v_floor/ceil/trunc/rndne/fract_f16` are exact and need no rounding. In nearest mode the translator still rounds `v_fma_mix{lo,hi}_f16` twice (f32 `Fma`, then narrow), but the hardware rounds once there as well: `tools/fma_mix_probe.py --oracle hw` on an RDNA2 iGPU (gfx1036, SHADER-135) gave the single-rounded word for all seven inputs where the two rules differ by one f16 ulp, so the translator, which rounded twice there (f32 `Fma`, then narrow) until #1774, was one f16 ulp off on exactly those ties (docs/shader_validation.md, "`v_fma_mix*` f16 rounding in nearest mode"; the fix is `Gen.fma_mix_odd` in nearest mode too, SHADER-296). Nearest-mode `v_fma_mix*` still rounds twice (f32 `Fma`, then narrow): main's behaviour, unmeasured. `tools/fma_mix_probe.py --oracle hw` measures it on an AMD GPU, with seven inputs where the two rules differ by one f16 ulp (docs/shader_validation.md). The `v_add_f64` step needs f64 denormals preserved (not flushed) by the driver for subnormal sums. Shaders that never write MODE emit the same code as without this. Writes to other MODE bits (f32 rounding, denormals), directed rounding (+inf/-inf) and register-valued writes are refused, so nothing changes silently; none occur in the corpus. Denormal behaviour is still Vulkan's default. Format conversions in memory and texture units don't follow MODE. `v_mul_legacy_f32` now keeps the `0 × anything = 0` rule like `v_mad_legacy_f32` (GPU-checked with `runtime/test/shaders/ps_legacy_mul.asm` on AMD Radeon RX 9070 XT). | -| Denormal flush in `v_mad_f32`, `v_mac_f32`, `v_mad_legacy_f32` (SHADER-118) | The three have no f32 denormal support: a subnormal operand, the rounded product or the result reads as signed zero, whatever the MODE register says. `Gen.flush_f32` emits ` \| x \| < FLT_MIN → copysign(0, x)` on the three operands, after the product rounding and (via `Gen.flush_f32_mods`) both before and after `omod`/`clamp`; inf and NaN compare false and pass through, and 0 keeps its sign. Source: LLVM AMDGPU `SIISelLowering.cpp`, `SITargetLowering::isFMADLegal` (llvm-project `1922c0c`), which forms `v_mad_f32`/`v_mac_f32` only when f32 denormals are flushed. Corpus count with `tools/shader_profile.py` over the 26,503 gfx1013 shaders: `v_mad_f32` in 7,298 shaders (139,287 occurrences), `v_mac_f32` in 5,889 (276,806: 265,901 `_e32`, 10,811 `_e64`, 94 `_dpp`), `v_mad_legacy_f32` in 6,059 (24,765); 9,297 shaders (35.1%) use at least one, 440,858 occurrences (0.99% of the corpus's 44,406,870 instructions). **Measured natively on RDNA1** (`AMD Radeon RX 5600 XT`, `gfx1010`, Windows driver `32.0.21045.29003`, `tools/mad_denorm_probe.py --oracle hw`, SHADER-340): 48 of 48 cases match in wave32 and wave64 across `game` (`IEEE=0`, `denorm32=0`), `dx10_clamp=0` and `denorm32=3` (`v_mul_f32(FLT_MIN, 0.5)` confirms `denorm32=3` keeps subnormals on the GPU while the mad/mac ops still flush them), and all 40 non-`omod` cases match under `IEEE=1` (where hardware ignores `mul:2`/`mul:4`/`div:2` as for other f32 VALU ops). Before SHADER-340 the translator ran `flush_f32` only after `clamp_mods`, which gave `FLT_MIN` (`0x00800000`) instead of `+0` (`0x00000000`) on `(1.5*2^-126 - 2^-126) mul:2` (and `0x01000000` on `mul:4`), whereas hardware flushes the sum before `omod` (`+0`) as well as after (`FLT_MIN div:2` → `+0`, `-FLT_MIN div:2` → `-0`). Checked on the CPU by `tests/semantic/test_valu_f32_min3_max3_mad.py` (`DenormalFlushTests`: the flush column, pre- and post-`omod` cases, NaN/inf/zero pass-through, and a sabotaged pass-through that fails) and `tests/test_mad_denorm_probe.py`. No RDNA2 part has these opcodes, and on gfx103x the encodings of `v_mad_legacy_f32` (VOP3 0x140) and `v_mac_legacy_f32` (VOP2 0x06) are the fused `v_fma_legacy_f32` / `v_fmac_legacy_f32`, so a raw-encoding run on a gfx1036 oracle would measure a different instruction (see the GFX10.1/GFX10.3 opcode row). | +| Denormal flush in `v_mad_f32`, `v_mac_f32`, `v_mad_legacy_f32` (SHADER-118) | The three have no f32 denormal support: a subnormal operand, the rounded product or the result reads as signed zero, whatever the MODE register says. By default (when `FLOAT_CONTROLS` and `FTZ32` are on and the shader has no `v_div_scale_f32`, `v_div_fmas_f32`, `s_denorm_mode`, or `s_setreg*` writing non-zero or non-constant bits into `HW_REG_MODE[5:4]` `FP_DENORM.fp32`), modules declare `OpCapability DenormFlushToZero` + `OpExecutionMode %main DenormFlushToZero 32` (core in SPIR-V 1.4, recorded as `"shaderDenormFlushToZeroFloat32"` in `meta["float_controls"]` alongside `DenormPreserve 16` and `SignedZeroInfNanPreserve 32`), eliding the software `Gen.flush_f32` wrapper and lowering `v_mul_legacy_f32` (and `v_mad_legacy_f32`/`v_mac_legacy_f32`'s product) to the canonical Mesa NIR `fmulz` pattern `OpSelect %float (OpLogicalOr (OpFOrdEqual x %f0) (OpFOrdEqual y %f0)) %f0 (OpFMul x y)` so RADV/ACO fuses it into a single native `v_mul_legacy_f32`. `_disables_ftz32` parses `hwreg(HW_REG_MODE[, offset[, size]])` (default `offset=0, size=32`): writes to disjoint bit ranges such as `hwreg(HW_REG_MODE, 2, 2)` (`FP_ROUND.fp64_fp16`, seen in 6,293 of 28,447 shaders) or `s_setreg_imm32_b32` writing `0` into overlapped `[5:4]` bits keep FTZ32 enabled, while non-zero immediate bits in `[5:4]`, register-valued `s_setreg_b32` overlapping `[5:4]`, or unparseable `HW_REG_MODE` forms conservatively disable FTZ32. Under `--no-ftz32` (or when gated off by `v_div_scale_f32`, `v_div_fmas_f32`, `s_denorm_mode`, `s_setreg*` modifying `HW_REG_MODE[5:4]`, or `--no-float-controls`), `Gen.flush_f32` emits ` \| x \| < FLT_MIN → copysign(0, x)` on the three operands, after the product rounding and (via `Gen.flush_f32_mods`) both before and after `omod`/`clamp`; inf and NaN compare false and pass through, and 0 keeps its sign. Source: LLVM AMDGPU `SIISelLowering.cpp`, `SITargetLowering::isFMADLegal` (llvm-project `1922c0c`), which forms `v_mad_f32`/`v_mac_f32` only when f32 denormals are flushed. Corpus count with `tools/shader_profile.py` over the 26,503 gfx1013 shaders: `v_mad_f32` in 7,298 shaders (139,287 occurrences), `v_mac_f32` in 5,889 (276,806: 265,901 `_e32`, 10,811 `_e64`, 94 `_dpp`), `v_mad_legacy_f32` in 6,059 (24,765); 9,297 shaders (35.1%) use at least one, 440,858 occurrences (0.99% of the corpus's 44,406,870 instructions). **Measured natively on RDNA1** (`AMD Radeon RX 5600 XT`, `gfx1010`, Windows driver `32.0.21045.29003`, `tools/mad_denorm_probe.py --oracle hw`, SHADER-340): 48 of 48 cases match in wave32 and wave64 across `game` (`IEEE=0`, `denorm32=0`), `dx10_clamp=0` and `denorm32=3` (`v_mul_f32(FLT_MIN, 0.5)` confirms `denorm32=3` keeps subnormals on the GPU while the mad/mac ops still flush them), and all 40 non-`omod` cases match under `IEEE=1` (where hardware ignores `mul:2`/`mul:4`/`div:2` as for other f32 VALU ops). Before SHADER-340 the translator ran `flush_f32` only after `clamp_mods`, which gave `FLT_MIN` (`0x00800000`) instead of `+0` (`0x00000000`) on `(1.5*2^-126 - 2^-126) mul:2` (and `0x01000000` on `mul:4`), whereas hardware flushes the sum before `omod` (`+0`) as well as after (`FLT_MIN div:2` → `+0`, `-FLT_MIN div:2` → `-0`). Checked on the CPU and with `spirv-val --target-env vulkan1.2` by `tests/semantic/test_ftz32_fmulz.py` (fixture `ftz32_fmulz.asm`, `HW_REG_MODE` bit-range overlap and gate-off checks, `v_mul_legacy_f32` edge cases in both FTZ32 and `--no-ftz32` modes), `tests/semantic/test_valu_mul_legacy_denorm.py`, `tests/semantic/test_valu_f32_min3_max3_mad.py`, and `tests/test_mad_denorm_probe.py`. No RDNA2 part has these opcodes, and on gfx103x the encodings of `v_mad_legacy_f32` (VOP3 0x140) and `v_mac_legacy_f32` (VOP2 0x06) are the fused `v_fma_legacy_f32` / `v_fmac_legacy_f32`, so a raw-encoding run on a gfx1036 oracle would measure a different instruction (see the GFX10.1/GFX10.3 opcode row). | | 16-bit high-half reads (`Gen.u16_half` / `Gen.i16_half`, #1506) | Reading the high 16 bits of a 32-bit word emits `OpShiftRightLogical %uint u 16` (`u16_half`) or `OpShiftRightArithmetic %int (as_int(u)) 16` (`i16_half`) alone, without a trailing `OpBitwiseAnd ... 0xFFFF` or `OpBitFieldSExtract ... 0 16` (used for the low half only). On 32-bit inputs `>> 16` already zero- or sign-extends bits 31..16, and AMD's Windows LLPC compiler (measured on RDNA2, drivers 22.40.84.06 in #1506 and 24.10.24 on Ryzen 5 7600 iGPU) miscompiles both `(u >> 16) & 0xFFFF` and `OpBitFieldSExtract (u >> 16) 0 16` after two partial-half writes to `u` by dropping the `>> 16` when the result feeds `OpIAdd`, `OpIMul`, or `OpShiftLeftLogical` (e.g. `(0x41b1 << 1) & 0xFFFF` became `0x0000` instead of `0x8362` in `cs_f16fuzz_s2_163_w64`, `s_bitreplicate`'s `((0x41b1 << 8) \| 0x41b1) & 0x00ff00ff` became `0xb10000` instead of `0x4100b1`, and `SExtract(0x91b1138b >> 16, 0, 16) + 1` became `0x91b10001` instead of `0xffff91b2`). Applies across all 16-bit half readers (`v_*_b16`/`u16`/`i16`, `v_mad_{u,i}16`, `v_min3/max3/med3_{u,i}16`, `v_cvt_f16_{u,i}16`, `v_pack_b32_f16`, `v_frexp_*_f16`, `v_ldexp_f16`, `s_bitreplicate_b64_b32`, and `buffer_store_format_d16_*`). Checked by the unit tests in `tests/test_u16_high_half.py` and `tools/valu_fuzz.py --family f16 --seed 2 --programs 200 --wave both` on AMD Ryzen 5 7600 iGPU (driver 24.10.24: 400/400 native, up from 399/400; 200/200 wave64 emulated on both AMD and NVIDIA). **The packed 16-bit shifts follow the same rule** (`v_pk_lshlrev_b16`, `v_pk_lshrrev_b16`, `v_pk_ashrrev_i16`, since 2026-11-23): the shift amount comes from `OpShiftRightLogical %uint s0 16` then `& 15`, and the value from `OpShiftRight{Logical,Arithmetic} %uint s1 16`, where the code used `OpBitField{S,U}Extract … 16 16`. A field extract at offset 16 is what an AMD Windows driver 25.10.36 on a gfx1036 iGPU reads with the offset taken mod 16, so both result halves got the **low** half of the source: 5 of 2,000 `tools/valu_fuzz.py --family f16 --programs 2000 --seed 1 --wave 32` programs, all in wave32 and none in native wave64 (@Darkz0rz, reported in the coordination issue as SHADER-777). The same 2,000 programs match 2000/2000 on a second gfx1036 (Radeon iGPU of a Ryzen 7 7800X3D, driver 31.0.24002.92), where the field-extract form was already correct, and its SPIR-V does contain the offset-16 extracts, so the change is a lowering that survives both drivers, not a value change: `OpBitField{S,U}Extract(x, 16, 16)` equals `x >> 16` with the matching right shift and `OpBitFieldUExtract(x, 16, 4)` equals `(x >> 16) & 15`, checked for 200,010 inputs including 0, 1, 0xFFFF, 0x10000, 0x80000000, 0xFFFFFFFF, 0x7FFFFFFF and 0x8000. Counted over the 26,503 listings: 1 `v_pk_lshlrev_b16` in 1 compute listing (`op_sel_hi:[0,1]`) and 1 `v_pk_lshrrev_b16` in 1 other (`op_sel:[1,0] op_sel_hi:[0,0]`), no `v_pk_ashrrev_i16` and no `_sdwa` form; those two modules are the only ones whose output changes. Values are checked by the unit tests in `tests/test_pk16_diff.py` and the `ps_ops4` / `ps_ops6` fixtures. **All remaining 16-bit high-half readers follow the same rule (`SHADER-HIGH-HALF-SHARED-READERS`)**: `v_cmp(x)_*_{u16,i16}`, `sdwa_src` `WORD_1` (with and without `sext()`), `v_pk_{add,sub,mul_lo,mad,max,min}_{u16,i16}`, `v_qsad_pk_u16_u8`/`v_mqsad_pk_u16_u8`, `v_sad_u16`, `v_mad_{u32_u16,i32_i16}`, and `image_store d16` now route through `Gen.u16_half` / `Gen.i16_half` so no 16-bit half reader emits `OpBitField{S,U}Extract ... 16 16`. CPU-checked by `tests/semantic/test_high_half_shared_readers.py` (structural + `spirv_mini_interp` parity); not yet GPU-verified. | | `v_mac_legacy_f32` | The GFX10.1 VOP2 form of `v_mad_legacy_f32` with D as the addend: D = legacy(S0 * S1) + D, where 0 times anything (inf and NaN included) is +0, with the same denormal flush and VOP3 modifiers. D is read before it is written, as for `v_mac_f32` (LLVM `VOP2Instructions.td`: `V_MAC_LEGACY_F32` has `$src2` tied to `$vdst`). Until 2026-11-22 it raised `Unsupported`. CPU-checked by `MacLegacyF32Tests` in `tests/semantic/test_valu_f32_min3_max3_mad.py` (a 15x8x6 grid against the `v_mad_legacy_f32` reference, the zero rule, clamp/neg, D aliased as a source). **Not GPU-verified**: like the other mad opcodes it exists on gfx1010-1013 only, so no RDNA2 desktop part runs it. | | `v_cmp_*_f64`, `v_cmpx_*_f64` | All 16 binary64 vector compare predicates (`f`, `lt`, `eq`, `le`, `gt`, `lg`, `ge`, `o`, `u`, `nge`, `nlg`, `ngt`, `nle`, `neq`, `nlt`, `tru`) for both `v_cmp_` (VCC/SGPR lane mask) and `v_cmpx_` (EXEC narrowing), lowered in `Gen.compare_f64_cond` via pure 32-bit `%uint` IEEE-754 ordering (NaN detection, `-0.0` canonicalized to `+0.0`, sign-magnitude to monotonic unsigned 64-bit key) with no `Float64` capability required and no denormal flushing. Supports VGPR/SGPR pairs, `fimm`, sign-extended inline integers (`-16..64`), 32-bit upper-half literals, and VOP3 `abs`/`neg` sign-bit modifiers on both sources; inactive lanes write 0 for `v_cmp_*_f64` and stay inactive for `v_cmpx_*_f64`. Source: AMD RDNA2 ISA VOPC/VOP3 binary64 compares. CPU-checked by `tests/semantic/test_cmp_f64.py` (all 16 predicates across full IEEE-754 edge grid including subnormals/1-ULP pairs/±0/±inf/sNaN/qNaN, SGPR pairs, constants, `abs`/`neg`, `v_cmpx_*_f64`, inactive lanes, no `Float64` capability, bad-operand rejections). GPU-checked by `runtime/test/shaders/cs_w32_cmp_f64.asm`: all 16 predicates of both forms on 256 memory-fed pairs (the product of 16 values: ±inf, ±max, the 1-ULP neighbours of ±1, the smallest subnormals, ±0, the smallest normal, a NaN with its payload in the low dword only, a negative quiet NaN), `tru` with the odd threads off (an inactive lane gets VCC 0 and stays off through `v_cmpx_`), and `lt`/`nge` with `abs`/`neg`, all 1536 heap words exact on an RTX 4070 Ti (NVIDIA 620.70.06, Linux) and on llvmpipe (subgroup 8). That run checks the translated SPIR-V on a driver against IEEE-754, not RDNA2 itself; SGPR-pair and constant operands are not in it. Measured on native gfx1100 (single thread, 116 cases): all 16 predicates return IEEE-754 results (`eq` on `NaN` is 0 while `neq`/`nlt`/`nge`/`ngt` are 1, `lg` is 0 for `NaN` with `o`/`u` splitting on it, `eq(+0.0, -0.0)` is 1, `inf` compares equal to itself) and `v_cmpx_*_f64` narrows `EXEC` instead of writing `VCC`. | -| Whole-quad mode (`s_wqm_b64` / `s_wqm_b32`) | A lane mask register holds only this lane's bit, so WQM on one (EXEC, VCC, an SGPR the mask analysis found) ORs the bit of the lane's quad, lanes 4n..4n+3 of the wave: two `OpGroupNonUniformQuadSwap` (horizontal, then vertical; capability `GroupNonUniformQuad`) in the default mode in fragment and compute shaders (quad operations are only guaranteed there; vertex, geometry and mesh shaders shuffle from the quad's four lanes), or the four lanes' values read through `%x_buf` under `--wave64-emulate` (no subgroup operation there). A quad never crosses lane 31/32, so the mask bits are exact per half on a 32-wide subgroup; SCC is a wave vote, so on wave64 it needs a 64-wide subgroup or `--wave64-emulate` (as every wave-wide mask op). The result goes to EXEC, VCC or an SGPR pair as a mask, SCC = the wave-wide any of it (same vote as the other mask ops). A 32-bit form in wave64 (`exec_lo`/`exec_hi`, `vcc_lo`/`vcc_hi`, a half-mask SGPR) writes only its own half (`exec_half_write`) and votes SCC over that half only (`cs_wqm_w64_half`). A source that is not a lane mask (a value loaded from memory, a literal) is data: `((x \| x>>1 \| x>>2 \| x>>3) & 0x11111111) * 15` per 32-bit word and SCC = result != 0, no subgroup operation. Assumptions: in compute and mesh shaders the subgroup lane is `LocalInvocationIndex` mod the subgroup size (as for every cross-lane op); a hardware quad is four consecutive lanes of a wave, and in a pixel shader Vulkan's quad (the 2x2 pixels, helper invocations included) is the same four lanes; GPU-checked on both AMD and NVIDIA with `ps_wqm.asm` (every 2x2 block of a 64x64 target, fully covered). **Helper lanes at a triangle edge, measured on RDNA2** (gfx1036, wave64, raw ISA through `tools/ps_oracle.py` on RADV; `tools/ps_helper_probe.py`, docs/shader_validation.md): a pixel wave's entry EXEC is exactly its covered pixels (helpers off); `s_wqm_b64 exec, exec` turns on exactly the quads with a covered pixel, which are packed from lane 0 (a quad with no covered pixel isn't in the wave); lane % 4 = (x & 1) + 2 (y & 1), so lanes 0-3 are top-left, top-right, bottom-left, bottom-right; a helper's `v_interp` gives its own pixel centre (extrapolated, as precisely as a covered pixel), and its v0/v1 hold its own I/J before `s_wqm` too; without `s_wqm` its VGPRs aren't written; an `exp ... vm` with helpers on in EXEC writes no pixel outside the triangle. Not covered: helper-invocation behaviour at triangle edges is untested, and in native mode an absent invocation in a partial quad (a compute group whose size is not a multiple of 4) gives an undefined value (emulated, the missing lanes of a partial wave read as 0). Before this the instruction was the identity, so helper lanes stayed off (#156 SHADER-34: `s_wqm_b64` appears in 4,285 pixel shaders). GPU-checked with `runtime/test/shaders/cs_wqm_w64.asm`, `cs_wqm_w64_half.asm`, `cs_wqm_w32.asm` and `ps_wqm.asm` on AMD Radeon 880M (subgroup 64) and NVIDIA GeForce RTX 5070 Laptop (subgroup 32; `cs_wqm_w64` there needs `LEONIDA_W64_EMULATE=1`), with and without `--wave64-emulate`. | +| Whole-quad mode (`s_wqm_b64` / `s_wqm_b32`) | A lane mask register holds only this lane's bit, so WQM on one (EXEC, VCC, an SGPR the mask analysis found) ORs the bit of the lane's quad, lanes 4n..4n+3 of the wave: two `OpGroupNonUniformQuadSwap` (horizontal, then vertical; capability `GroupNonUniformQuad`) in fragment shaders (where Vulkan guarantees complete 2×2 pixel quads including helper invocations), `OpGroupNonUniformBallot` plus 4-bit quad-nibble extraction in compute, vertex, geometry and mesh shaders (exact on partial quads of any size up to 128 lanes without needing `GroupNonUniformQuad` or shuffles), or the four lanes' values read through `%x_buf` under `--wave64-emulate` (no subgroup operation there). A quad never crosses lane 31/32, so the mask bits are exact per half on a 32-wide subgroup; SCC is a wave vote, so on wave64 it needs a 64-wide subgroup or `--wave64-emulate` (as every wave-wide mask op). The result goes to EXEC, VCC or an SGPR pair as a mask, SCC = the wave-wide any of it (same vote as the other mask ops). A 32-bit form in wave64 (`exec_lo`/`exec_hi`, `vcc_lo`/`vcc_hi`, a half-mask SGPR) writes only its own half (`exec_half_write`) and votes SCC over that half only (`cs_wqm_w64_half`). A source that is not a lane mask (a value loaded from memory, a literal) is data: `((x \| x>>1 \| x>>2 \| x>>3) & 0x11111111) * 15` per 32-bit word and SCC = result != 0, no subgroup operation. Assumptions: in compute and mesh shaders the subgroup lane is `LocalInvocationIndex` mod the subgroup size (as for every cross-lane op); a hardware quad is four consecutive lanes of a wave, and in a pixel shader Vulkan's quad (the 2x2 pixels, helper invocations included) is the same four lanes; GPU-checked on both AMD and NVIDIA with `ps_wqm.asm` (every 2x2 block of a 64x64 target, fully covered). **Helper lanes at a triangle edge, measured on RDNA2** (gfx1036, wave64, raw ISA through `tools/ps_oracle.py` on RADV; `tools/ps_helper_probe.py`, docs/shader_validation.md): a pixel wave's entry EXEC is exactly its covered pixels (helpers off); `s_wqm_b64 exec, exec` turns on exactly the quads with a covered pixel, which are packed from lane 0 (a quad with no covered pixel isn't in the wave); lane % 4 = (x & 1) + 2 (y & 1), so lanes 0-3 are top-left, top-right, bottom-left, bottom-right; a helper's `v_interp` gives its own pixel centre (extrapolated, as precisely as a covered pixel), and its v0/v1 hold its own I/J before `s_wqm` too; without `s_wqm` its VGPRs aren't written; an `exp ... vm` with helpers on in EXEC writes no pixel outside the triangle. Partial quads in CS/VS/GS/MS are now exact natively via ballot nibble extraction (`tests/semantic/test_absent_lane_ub.py`, `tests/test_absent_lane_gpu.py`). Before this the instruction was the identity, so helper lanes stayed off (#156 SHADER-34: `s_wqm_b64` appears in 4,285 pixel shaders). GPU-checked with `runtime/test/shaders/cs_wqm_w64.asm`, `cs_wqm_w64_half.asm`, `cs_wqm_w32.asm` and `ps_wqm.asm` on AMD Radeon 880M (subgroup 64) and NVIDIA GeForce RTX 5070 Laptop (subgroup 32; `cs_wqm_w64` there needs `LEONIDA_W64_EMULATE=1`), with and without `--wave64-emulate`. | | `buffer_atomic_{and,or,xor,swap}_x2` | `M = op(M, DATA)` on the 64-bit element at the MUBUF address (two dwords, low first); with `glc` the old 64 bits are returned in `vdata[0:1]`. A bitwise op or an exchange leaves the same memory done one dword at a time, so each dword is its own 32-bit `OpAtomic*` and no Int64 atomics are needed. **Approximation:** the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done. Each dword is its own 32-bit `OpAtomic*`, so no Int64 atomics are needed; a bitwise op leaves the same memory that way, since its bits are independent. **Approximation:** an exchange can tear, since two lanes swapping into one element at once can leave one's low dword with the other's high dword (A.lo, B.lo, B.hi, A.hi), and the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done. **Bounds:** the check covers the whole 8-byte element, all or nothing, as for a typed 32_32 element (`buffer_address(elem="fmt")`). An out-of-range or inactive lane leaves memory alone and returns 0, as `buffer_atomic` does. How hardware treats a 64-bit atomic that is only partly in range is **not measured**. Still `Unsupported`: `add/sub/min/max_x2` and `cmpswap_x2`. Until 2026-11-22 every `_x2` buffer atomic was rejected. CPU-checked by `tests/semantic/test_buffer_atomics_x2.py` (the four ops with and without `glc`, an element ending exactly at `num_records`, half and fully out of range, seeded values, rejected forms). **Not GPU-verified.** | | Per-lane descriptor selection | The translator executes the first-active-lane read, EXEC selection, scalar descriptor load and remaining-lane retry as ordinary wave instructions. The hand-written `waterfall_table_offset.asm` fixture reads four different buffers and checks every lane on wave32, native wave64 and emulated wave64. The graphics partition analysis accepts an unmodified full-word integer equality as evidence that selected lanes hold the first lane's word. A float comparison accepts both signs of zero. The signed-zero execution fixture produces different raw outputs when a 64-lane group is split and therefore requires tier C. See Marvis's VIctory waterfall analysis (b1c8306, ffe310e) for the distinction between comparing descriptor words and comparing the offset of a descriptor load. | | Wave64 graphics: partition invariance (SHADER-10) | A wave64 VS/PS/GS on a 32-wide subgroup is exact **iff its observable results do not change when the wave is cut into two 32-lane halves** (the host forms the subgroups of graphics stages, so there is no partner half to exchange with). `tools/wave64_halves.py` decides it from the code (forward taint dataflow over the basic blocks, plus control dependence on wave-wide votes) and the translator records it in `index.json` as `wave64_graphics` (`A`/`B`/`C`), `wave64_graphics_reasons` (tier C) and `wave64_graphics_idioms` (tier B). **A**: only per-lane arithmetic, votes that skip lane-masked work (`s_cbranch_execz/execnz`; `vccz/vccnz` whose run side starts by narrowing EXEC to that VCC and whose other side is the join, with no code of its own: a half that votes no runs that side, the wave does not; the same holds for `s_cbranch_execz/execnz`: the side that runs when EXEC is zero is taken by a half with no active lane, so it must be the join (or only jumps to it) or the exit of a loop the vote closes, else tier C `unsafe-execz-branch`; `s_cbranch_scc*` after a vote is the same kind of skip, any other reader of that SCC, `s_cselect`/`s_cmov`/`s_addc`, is tier C; a vote is on the mask register's value when it was taken, so a new value in that register before the branch (`v_cmp` into the pair or VCC, `s_mov_b64`, `s_cselect_b64`: none of them writes SCC) ends it, and the branch is judged as a plain SCC branch, SHADER-820), whole-quad masks, `ds_bpermute`/`ds_permute`/`v_permlane16`/`v_permlanex16`/`ds_swizzle` (they stay inside a half), a `ds_bpermute`/`ds_permute` address made from the lane id (`v_mbcnt_lo` then `v_mbcnt_hi` of -1) when it is the same modulo 128 bytes in the wave and in a half (the id is 0..63 there and 0..31 here, equal modulo 32 lanes; sums, differences and bitwise ops with invariant values keep that, a left shift by c multiplies the modulus by 2^c, and the permute uses address bits 2..6 of its half only: `(id ^ 1) << 2` is exact, `id << 1`, a right shift of the id or the low count alone stay tier C `lane-id`), loops closed by `execnz` with no scalar state carried, and the early exit of a pixel kill: `s_cbranch_scc0/scc1` (or `vccz/vccnz`) on a lane mask's own "not empty" (the last SCC writer is a 64-bit logic op into that mask, e.g. `s_andn2_b64 live, live, exec`, or `s_cmp_lg_u64 mask, 0`, and nothing rewrites the mask before the branch) to a block that only sets EXEC from that mask or 0 (`s_mov_b64 exec`, or `s_and_b64 exec` with it), may then export with that EXEC (an export is allowed, not required), and ends (no other code, store or successor), while the run side narrows EXEC into the mask's whole quads before anything but mask arithmetic (`s_mov_b64`, `s_and_b64`, `s_wqm_b64`) runs, the narrowing itself possibly an `s_and_saveexec_b64` / `s_andn2_saveexec_b64` (or `_wrexec_`) whose source is inside, and keeps it inside on every path from there, loops included (a must-dataflow: an EXEC write keeps it inside only when it is provably a subset: `v_cmpx`, `s_and_b64` with one operand known inside, `s_andn2_b64` / `s_andn2_saveexec_b64` whose first operand is, `s_and_saveexec_b64` while inside or from one that is, `s_andn1`/`s_or`/`s_xor_saveexec_b64` only while inside (the latter two also from one that is), and copies, `s_wqm_b64`, `s_or_b64` and `s_xor_b64` of operands known to be inside (0 counts as inside); a saveexec destination holds the old EXEC and a wrexec one the new, each inside only if that EXEC was), and no `exp ... vm` can run before the vote. A half whose mask is empty then writes nothing and discards its pixels in the exit, and in the wave its lanes are off to the end, so the wave discards them too; an exit shared by several kills reads a mask redefined behind the earlier votes and stays tier C. GPU-checked by `ps_w64_a_discard` (below). `s_cbranch_scc*` after a vote is the same kind of skip, any other reader of that SCC, `s_cselect`/`s_cmov`/`s_addc`, is tier C; a vote is on the mask register's value when it was taken, so a new value in that register before the branch (`v_cmp` into the pair or VCC, `s_mov_b64`, `s_cselect_b64`: none of them writes SCC) ends it, and the branch is judged as a plain SCC branch, SHADER-820), whole-quad masks, `ds_bpermute`/`v_permlane16` (they stay inside a half, not GPU-tested here: no fixture; `s_cbranch_scc*` after a vote is the same kind of skip, any other reader of that SCC, `s_cselect`/`s_cmov`/`s_addc`, is tier C), whole-quad masks, `ds_bpermute`/`v_permlane16` (they stay inside a half, not GPU-tested here: no fixture; `ds_swizzle` and `v_permlanex16` likewise; GPU-checked at required 64 and 32 lanes by `ps_w64_a_bpermute`, `ps_w64_a_permlane` (`v_permlane16` and `v_permlanex16`) and `ps_w64_a_swizzle` in `w64_graphics.py`, TEST-433), loops closed by `execnz` with no scalar state carried. `ds_swizzle` and `v_permlanex16` likewise), loops closed by `execnz` with no scalar state carried. A `vccz`/`vccnz` on a wave-uniform compare is no lane vote and is tier A too: a `v_cmp` made while EXEC is the launch mask from untainted immediates, scalars that are no lane mask and VGPRs written from them (optionally ANDed with EXEC, the LLVM form `s_and_b64 vcc, exec, s[..]`) gives every launch lane or none, so each half votes as the wave does and both sides may have code and scalars of their own (if/else, a uniform loop back edge; the mask itself read as data, e.g. exported, is still tier C `cross-lane`), while the same compare under a narrowed EXEC (a half with no active lane votes no and keeps its own scalars) or on a tainted value (`v_readfirstlane` of a varying VGPR, a lane count, an AND with a lane mask) stays tier C; confirmed on the wave interpreter (`UniformVote` in `tests/semantic/test_wave64_halves.py`: 64 lanes against two waves of 32, equal for the accepted forms with s4 = 9 and s4 = 1, different for each near miss) and by `ps_w64_a_uniform_vote`, which gives its derived words on an NVIDIA GeForce RTX 5080 (Linux, driver 580.65.06, 32 only). **B**: also a waterfall loop (`v_readfirstlane` of a varying value, `v_cmp_eq` against the same VGPR, `saveexec`, body, `s_xor exec`, `execnz`; the scalar only used inside the body), a wave-aggregated atomic (`s_bcnt1` of EXEC, `v_mbcnt` rank of that same EXEC, one `buffer_atomic_add` of that count (the count of the mask the rank ranks) by the rank-0 lane only, at a wave-uniform address (a uniform VGPR, or one the elected lane wrote from scalars and constants since EXEC last changed; a per-lane address such as a pixel coordinate is tier C `elected-lane`, since each half elects its own lane and bumps another counter), `v_readfirstlane` of the result with EXEC restored, base + rank as a store address, the rank counting the very mask the atomic's count was taken of (a rank of the entry EXEC or of a saved copy next to a base of the narrowed one is tier C `lane-rank`); the rank alone or the base alone is not a slot: exact as a set of slots, **the order of the slots within a wave is not preserved**, a 64-lane wave takes one run of slots, two halves take two), `v_readfirstlane` / `v_readlane` of a VGPR written from scalars and constants while EXEC was the launch mask (the same in every lane), a `v_writelane` / `v_readlane` spill pair on one constant lane below 32. **C**: anything else that reaches an export, a store's data, a branch or EXEC: lane count / rank / first-lane index / raw lane id (`v_mbcnt` of -1), `v_readlane` of a varying value at any lane (on a wave64 every lane gets hardware lane N, in halves each half gets its own lane N, so lane 7 is as wrong as lane 40; the research note's row 9 is too generous here); an analysis failure is tier C with reason `analysis-error` (the translation does not fail), `v_writelane` to a non-constant or >= 32 lane, a 32-bit access to half of a lane mask (`exec_hi`, `vcc_hi`, a mask pair's odd register), a mask read as data (including a mask combined by `s_and/or/andn2_b64` with a register that is not one: a user value, a loaded mask), a scalar defined behind a wave-wide vote and read where it may not have run (`s_add s5, s5, 1` after `s_cbranch_vccz`; a trip count in an SGPR of a divergent loop: the halves vote differently), a branch on a count, an elected-lane side effect that is not a count, `ds_append`/`ds_consume`. The check is conservative: unknown means C. `--wave64-graphics=warn` (default) marks tier C and counts it in the summary line, `error` refuses it (`Unsupported`), `off` skips the analysis; `python tools/wave64_halves.py --census /index.json` prints tier, reason and idiom counts (no names); it complements `tools/wave64_graphics_scan.py` (#1132), which counts candidate cross-half opcodes in the disassembly before translation and decides nothing. **Corpus census** (1.0.2.1, all 26,503 shaders translated at `main` `f847748c` with `--wave64-emulate`, `--census` over that index): 13,405 wave64 graphics shaders (2,236 VS, 10,974 PS, 195 GS, the FSSM header's wave size, see *Wave size*); tier A 4,033 (30.1%), B 85 (0.6%), C 9,287 (69.3%): VS 1,455/79/702, PS 2,383/6/8,585, GS 195/0/0. Tier C reasons (a shader can have several): unsafe-vote-branch 8,285, tainted-branch 6,547, tainted-exec 5,189, cross-lane 4,764, stale-scalar 3,415, mask-half 759, unsafe-execz-branch 583, first-lane 353, waterfall-scalar 161, lane-id 152, lane-count 1. Idiom tags, counted on every shader that carries one whatever its tier (`--census` prints them as "tier B idioms"; 85 shaders are tier B): readfirstlane-uniform 626, lane-spill 287, waterfall 35. (Earlier censuses counted 11,405 shaders, from when the wave size came from code markers: TEST-319 had A 1,919, B 17, C 9,469 with all 195 GS in C; its re-run with the GS ring rule below and #1982 had A 2,117, B 17, C 9,271 with all 195 GS in A.) The lane-id bpermute rule moves no corpus shader. (The TEST-319 census, from when the wave size came from code markers and before the GS ring-address rule below, counted 11,405 shaders: A 1,919, B 17, C 9,469, with all 195 GS in C.) The lane-id bpermute rule moves no corpus shader. **Corpus census** (TEST-319, 1.0.2.1, `--census` over the translated index, re-run with the GS ring rule below and #1982): 11,405 wave64 graphics shaders (1,179 VS, 10,031 PS, 195 GS); tier A 2,117 (18.6%), B 17 (0.1%), C 9,271 (81.3%): VS 479/14/686, PS 1,443/3/8,585, GS 195/0/0. Tier C reasons (a shader can have several): unsafe-vote-branch 8,285, tainted-branch 6,550, tainted-exec 5,189, cross-lane 4,760, stale-scalar 3,415, mask-half 758, unsafe-execz-branch 583, first-lane 353, waterfall-scalar 161, lane-id 152, lane-count 1. 11,405 wave64 graphics shaders (1,179 VS, 10,031 PS, 195 GS); tier A 1,919 (16.8%), B 17 (0.1%), C 9,469 (83.0%): VS 465/14/700, PS 1,454/3/8,574, GS 0/0/195. Tier C reasons (a shader can have several): unsafe-vote-branch 8,175, tainted-branch 6,582, cross-lane 6,111, tainted-exec 4,959, stale-scalar 3,162, mask-half 758, unsafe-execz-branch 583, first-lane 353, lane-id 277, waterfall-scalar 167, lane-count 1. Tier B idioms: readfirstlane-uniform 558, lane-spill 287, waterfall 35. The lane-id bpermute rule moves no corpus shader. **Corpus coverage is not measured here**: it needs a run over the game's shaders by someone who has them. **Rewrite (the only one the emission needs)**: `v_readlane_b32` of a proven-uniform VGPR reads the lane's own copy instead of shuffling from lane N, because a subgroup shuffle from lane >= 32 of a 32-wide subgroup is undefined (143 of 144 test shaders translate byte-identically to origin/main, only `ps_w64_b_readlane_uniform` changed). Everything else tier B needs is what the translator already emits per subgroup: the ballot/count/rank/first-lane words of `wave_mask` are the subgroup's own (the high word is 0), `v_readfirstlane` is the subgroup's first active lane, a waterfall runs once per distinct value of the subgroup. GPU-checked on AMD Radeon 880M (driver 26.11.2; `requiredSubgroupSizeStages` has FRAGMENT, size 32..64) with `runtime/test/shaders/w64_graphics.py`: each `ps_w64_*` fixture drawn with the fragment subgroup size required to 64 (one hardware wave) and to 32 (two halves). `ps_w64_a_skip`, `_b_waterfall`, `_b_readfirstlane`, `_b_readlane_uniform` and `_b_ballot_atomic` (counter 1024 and the 1024 slot words as a set; slot order differs) match each other and the words their headers derive; `_c_bcnt_export`, `_c_lane_id`, `_c_readlane`, `_c_vote_stale`, `_c_vote_else`, `_c_scc_vote`, `_c_execz_sgpr` (an SGPR written on the exec-zero side and exported) and `_c_waterfall_count` differ between 64 and 32 (the detector is right). `ps_w64_a_one_lane` is the case where only one pixel votes yes (so one half votes and the other does not, in the wave and in the halves): its skip regions (`execz`, `vccz`, `vccnz` with a jump-only fall-through) give equal images at 64 and 32; `_c_vote_else` (code on the vote's no side) and `_c_scc_vote` (SCC of a vote as data) differ. `ps_w64_a_discard` (three kills, two of them dropping whole regions so that some halves lose every pixel while the other half of their wave lives) was drawn on an AMD Radeon RX 580 (RADV, Mesa 26.0.8, required size 64, saved with `W64G_SAVE_REF`) and an NVIDIA GeForce RTX 5070 (32 only, driver 620.73.04, compared with `W64G_REF`): both equal the derived words, discarded pixels keeping the clear value, and each other. NVIDIA GeForce RTX 5070 Laptop (32 only, driver 617.42): tier A/B fixtures equal the derived words and the 880M@64 images (`W64G_SAVE_REF` / `W64G_REF`), tier C fixtures differ from the 880M@64 images. `ps_w64_a_permlane`, `_a_swizzle` and `_a_bpermute` (TEST-319: permlane16 neighbour selects, permlanex16 there and back, swizzle quad-permute, swap and broadcast modes, bpermute from lane-id addresses; every read stays in the pixel's 2x2 quad or comes back, so the words do not depend on how pixels are packed into lanes) give the derived words on an NVIDIA GeForce RTX 5070 (Linux, driver 620.73.04, 32 only). With an AMD Radeon RX 580 (Polaris, RADV Mesa 26.0.8) as the 64-lane reference (`W64G_SAVE_REF`; GCN has one subgroup size, 64, in every stage but no FRAGMENT in `requiredSubgroupSizeStages`, so `vk_harness` counts a requested size equal to a device's only size as applied), the RTX 5070 run of every fixture (`W64G_REF`) equals the reference for all 13 tier A/B fixtures and differs from it for all 11 tier C ones, pixel and vertex; the same reads in a vertex shader run on the wave interpreter (64 lanes against two waves of 32, equal) because a GPU's partial vertex waves leave the lanes they would read empty. Vertex shaders: the VS stage cannot be forced on the 880M (no VERTEX in `requiredSubgroupSizeStages`), so VS is covered by the strict wave interpreter (`tests/semantic/test_wave64_halves.py`: 64 lanes against two waves of 32; tier A/B equal, tier C differs); geometry shaders are not tested (the corpus ones are wave64, see *Wave size*; no fixture). 64 lanes against two waves of 32; tier A/B equal, tier C differs), and on RADV also on the GPU (TEST-251): RADV runs the VS stage (NGG) as wave64 by default and as wave32 with `RADV_PERFTEST=gewave32` (GFX10+, seen in the `RADV_DEBUG=shaders` dump: 64-bit EXEC operations against `exec_lo`), so `w64_graphics.py` draws each `vs_w64_*` fixture both ways, 960 zero-area vertices (`VKH_VERTICES`) that store four words each to the heap, with `vs_w64_c_lane_id` as the probe that the wave size changed (largest lane id 63, then 31). RADV packs 62 or 64 vertices into a wave64 and 30 or 32 into a wave32, and the wave32 waves are the two halves of the wave64 ones: each vertex's wave32 lane is its wave64 lane & 31 (`vs_w64_c_lane_id`, all 960 vertices: waves of 64, 62, 64, 62 ... vertices starting at 0, 64, 126, 190 ... against 32, 32, 32, 30 ... starting at 0, 32, 64, 96, 126 ..., a period of 126 both ways; RADV Mesa 26.3.1 on a gfx1036 iGPU (Raphael, found by sskver) and an RX 7900 XTX (NAVI31, RDNA3); TEST-1700. GFX12 gives the same waves and starts, with every wave32 wave inside one half of a wave64 wave: RX 9070 XT, GFX1201, RDNA4, RADV Mesa 26.2.6, sperm's old upstream PR 7354 (GFX1201 data)), so the 32-lane run is the cut into halves that the tiers describe, not a repacking; tier A/B words are keyed on the vertex index. `vs_w64_a_skip`, `_b_waterfall`, `_b_readlane_uniform` (readfirstlane and readlane 40/63 of uniform VGPRs) and `_b_ballot_atomic` (240 slots as a set) give the derived words at both sizes; `_c_bcnt_export`, `_c_readlane` and `_c_lane_id` differ (the detector is right), on an RX 9070 XT (GFX1201) and a Ryzen 9800X3D iGPU (GFX1036, RDNA2), RADV Mesa 26.3.1; geometry shaders are not tested (no fixture; the corpus has 195 wave64 geometry shaders, all tier C, see the census). `_c_bcnt_export`, `_c_readlane` and `_c_lane_id` differ (the detector is right), on an RX 9070 XT (GFX1201) and a Ryzen 9800X3D iGPU (GFX1036, RDNA2), RADV Mesa 26.3.1; geometry shaders likewise (TEST-251): RADV runs the GS stage (NGG) as wave64 by default and as wave32 with `gewave32`, and `w64_graphics.py` draws each `gs_w64_*` fixture after `vs_ids` (960 vertices, 320 triangles, `VKH_GS`), each invocation finding its triangle from `vs_ids`'s vertex number and storing four words to the heap, with `gs_w64_c_lane_id` as the probe (largest lane id 41, RADV puts at most 42 GS invocations in a wave64, then 31). **LDS writes of a legacy GS:** `rdna2spirv.gs_ds` maps one to an output slot from its offset alone and drops the VGPR address (the lane's GSVS area), so `wave64_halves.py` checks only the data a GS `ds_write` writes, not its address; before, a lane id that only formed the GSVS base made the shader tier C `lane-id`. Confirmed three ways: a hand-written GS with the base `lane id * 96` translates, after `spirv-opt -O`, to the same instructions as without it; `gs_w64_a_ring` (that shape) gives the derived records at wave64 and wave32 on both GPUs; and `tests/semantic/test_wave64_halves.py` (`GeometryRing`) keeps the lane id in the written data, or in a memory store's address, tier C. The corpus GS were that false tier C: all 195 contain `v_mbcnt_hi`, all 195 were tier C in the TEST-319 census, and `wave64_halves.py --census` on the corpus translated at `f847748c` puts all 195 in tier A. `_c_bcnt_export`, `_c_readlane` and `_c_lane_id` differ (the detector is right), on an RX 9070 XT (GFX1201) and a Ryzen 9800X3D iGPU (GFX1036, RDNA2), RADV Mesa 26.3.1; geometry shaders are not tested (the corpus ones are wave64, see *Wave size*; no fixture). The corpus GS form their GSVS base from `v_mbcnt_lo/hi` (all 195 contain `v_mbcnt_hi`): they were all a false tier C, and the census above has all 195 at tier A. `wave64_halves.py --census` on a translated corpus shows it. `_c_bcnt_export`, `_c_readlane` and `_c_lane_id` differ (the detector is right), on an RX 9070 XT (GFX1201) and a Ryzen 9800X3D iGPU (GFX1036, RDNA2), RADV Mesa 26.3.1; geometry shaders are not tested (the corpus ones are wave32; no fixture). Not checked: helper lanes of partial quads; `VK_KHR_shader_maximal_reconvergence` is assumed for waterfall and election loops. Tiers A and B assume subgroups of at least 32 lanes: a fragment stage may run fewer live lanes than the subgroup size it reports (Intel UHD 770: gl_SubgroupSize 32, ballot count 16, a shuffle from lane L^16 returns garbage; measured by kapitche, TEST-433), so `w64_graphics.py` skips the tier A/B pixel fixtures on a device whose minimum subgroup size is below 32 when neither the 64 nor the 32 run took effect; deriving the skip from a measured live fragment width (ballot count) in `vk_harness` is a follow-up. **ADD_TID_ENABLE** (SHADER-833, finding by @shdann in #4571): an access with no `idxen` through a V# whose word3 is a literal (`s_mov_b32` earlier in the block, the notion `rdna2spirv` uses for `sgpr_imm`) with bit 23 set takes the wave lane as its index (`idxen` ignores the bit, see *Swizzled buffer addressing*), so its `buffer_load*`/`tbuffer_load*` result and its `buffer_store*`/`tbuffer_store*`/`buffer_atomic*` address carry the raw lane id: tier C `lane-id`. A literal with the bit clear, and every access with `idxen`, are unchanged. **Assumption**: through a run-time V# (loaded from memory or user data) tiers A and B take ADD_TID_ENABLE as 0 for an access without `idxen`; the code cannot say otherwise. The literal is tracked with the same folds `rdna2spirv` applies to `sgpr_imm` (mirrored in `Analysis.literal_sgpr`: `s_mov_b32/b64`, `s_movk_i32`, `s_pack_*`, `s_bfm_b32`, `s_not_b32`, `s_and/lshl/lshr_b32`, `s_mul_i32`; other folded ops count as run-time). The corpus census was not re-measured with this rule: its tier counts above are from before it and may change. Follow-up, needs the game: count the bound V#s with word3 bit 23 set at run time, and re-run `--census`. | @@ -563,6 +567,11 @@ How the generated SPIR-V expects the runtime to work: | Out-of-bounds typed buffer loads and `DST_SEL=1` | When a MUBUF `buffer_load_format_{x,xy,xyz,xyzw}` or `buffer_load_format_d16_{x,xy,xyz,xyzw}` is out of bounds (`OOB_SELECT` 0–3, `num_records == 0`, partial-element spill, or swizzled OOB), memory is not accessed and raw data channels (`DST_SEL` 4..7) read 0, while the V# `DST_SEL` swizzle still runs: `DST_SEL=0` returns 0 and `DST_SEL=1` returns `1.0f` (`0x3F800000`, `d16` `0x3C00`) iff V# `FORMAT[6:0]` is a valid float, normalized or scaled buffer format (`1..77` ending in `_UNORM`, `_SNORM`, `_USCALED`, `_SSCALED`, or `_FLOAT`), and integer `1` (`0x00000001`, `d16` `0x0001`) for `UINT`/`SINT`, `INVALID` (`0`), and reserved codes (`78..127`). `d16_x` and `d16_xyz` preserve the unaddressed upper 16 bits of the final destination VGPR, and MTBUF `tbuffer_load_format_*` ignores V# `DST_SEL` on both out-of-bounds and `FORMAT=0` loads (returning 0 in addressed channels). Until 2026-11-22 `Gen.buffer_load_format` clamped the post-swizzle result to 0 when `in_b` was false (`SHADER-429`), dropping `DST_SEL=1` on out-of-bounds loads and returning `1.0f` instead of `1` for `DST_SEL=1` with `FORMAT=0`. For a dynamic MUBUF FORMAT with no decoded data channels (INVALID or reserved), the shader skips the physical load even when the descriptor has a nonempty, in-range span. DST_SEL constants still apply. The interpreter read-log fixture and RTX 4070 readback cover FORMAT 0, 78, 127 and valid control 20. **Hardware-verified on RDNA2** (`gfx1036`, Windows 11, driver `32.0.21042.62`, wave32 and wave64, 746 kernels via `tools/hw_oracle`: all 41 `Gen.FORMATS` across `xyzw`/`d16_xyzw`/`d16_xyz`/`d16_x`, all 128 7-bit `FORMAT` codes `0..127` for both `f32` and `d16`, `OOB_SELECT` 0–3, partial spill, swizzled OOB, MTBUF controls, and inactive EXEC lanes), Vulkan GPU-checked across all 128 7-bit `FORMAT` codes (`xyzw`, `d16_xyzw`, `d16_xyz`, `d16_x`) and the `cs_fmt_*`/`cs_oob_*`/`cs_bounds`/`cs_buf_*` fixtures on NVIDIA GeForce RTX 5090 (driver `32.0.16.1088`) and AMD Radeon Graphics (`gfx1036`, driver `32.0.21042.62`), and CPU/`spirv-val`-checked by `tests/semantic/test_buffer_oob_dst_sel.py`. | | `v_div_fixup_f32` | Measured natively on an AMD Radeon(TM) Graphics RDNA2 GPU (`gfx1036`, not the console's `gfx1013`; Windows driver 32.0.21042.62, `tools/hw_oracle`, wave32 and wave64 identical on every case: 256 seeded triples across 4 MODEs plus 73 targeted special-case/modifier rows, 0 mismatches). Computes `div_fixup_f32(S0=quotient, S1=denom, S2=numer)` with pure integer SPIR-V ops under the game's inferred MODE (`IEEE=0`, `denorm32=0`, `DX10_CLAMP=1`): VOP3 `abs` (clear bit 31) then `neg` (flip bit 31) apply bitwise to `S0`/`S1`/`S2` before classification (including NaN payloads); `S1`/`S2` subnormals flush to signed zero (`exp == 0`) while `S0` subnormals are preserved; priority order is (1) `NaN(S2) → S2`, (2) `NaN(S1) → S1` (signalling NaNs pass unchanged under `IEEE=0`, quieted only when `IEEE=1`), (3) `0/0` or `±inf/±inf → 0xFFC00000` (`-qNaN`), (4) `zero(S2) ∨ inf(S1) → ±0.0`, (5) `zero(S1) ∨ inf(S2) → ±inf`, (6) `exp(S2) − exp(S1) ≤ −151 → ±0.0` (pure biased-exponent check, beats `NaN(S0)` and `inf(S0)`; no overflow check), (7) `NaN(S0) → ±inf`, (8) `copysign(S0, sign(S1) ⊕ sign(S2))`. Output modifiers `mul:2`/`mul:4`/`div:2` apply before `clamp`, and `clamp` maps NaN to `+0.0` (`DX10_CLAMP=1`) before `FClamp` to `[0, 1]`. Not modelled: `IEEE=1` sNaN quieting, `denorm32=3` keeping `S1`/`S2` subnormals, and the hardware `omod` `-0 → +0` quirk (same as the other f32 ops). Checked bit-for-bit against 73 measured `gfx1036` words in `tests/semantic/test_alu_div_fixup_f32.py`. | | Atomic natural alignment, 64-bit bounds, and `buffer_atomic_{fmin,fmax}` | Measured natively on RDNA2 (AMD Radeon(TM) Graphics, `gfx1036`, Windows driver `32.0.21042.62`, wave32 and wave64 via `tools/hw_oracle/`): **natural alignment** is enforced on every 32-bit and 64-bit buffer/global atomic (`buffer_atomic*`, `buffer_atomic*_x2`, `global_atomic*`, `global_atomic*_x2`), even under `OOB_SELECT = 2` (DISABLED). A 32-bit atomic requires `(addr & 3) == 0` (`offset = 1, 2` and `base + 2, offset = 0` are dropped; `base + 2, offset = 2` succeeds) and a 64-bit `_x2` atomic requires `(addr & 7) == 0` (`offset = 2, 4` and `base + 4, offset = 0` are dropped; `base + 4, offset = 4` succeeds). When dropped (OOB or unaligned), memory is untouched, an active `glc` lane receives `0` (32-bit) or `(0, 0)` (64-bit) in `vdst`/`vdata`, and an inactive lane (`EXEC = 0`) preserves `vdst`/`vdata`. Independently confirmed on a second `gfx1036` (driver `24.10.24`): without the alignment guard, an unaligned SPIR-V `OpAtomicAdd` corrupts the aligned dword (`100 -> 0xDEADBEF3`), whereas with the guard memory stays untouched and `0` is returned. `Gen.atomic_aligned` guards all six atomic emitters on `addr & 3 == 0` / `addr & 7 == 0`, merges `0` via `OpPhi` on skipped paths, and writes through `Gen.dst` so inactive lanes keep their prior register value while active unaligned/OOB lanes receive `0`. **64-bit partial bounds (`buffer_atomic*_x2`)**: the same `gfx1036` wave32/wave64 measurements confirm the all-or-nothing 8-byte bounds rule (`fixed_fmt = 62`) across all four `OOB_SELECT` modes (answering the unmeasured note in the `buffer_atomic_{and,or,xor,swap}_x2` row): mode 3 (RAW) requires `offs + 8 <= num_records` (`0/8` and `8/16` succeed; `0/7`, `0/5`, `0/4`, `8/15`, `8/12` drop cleanly); mode 0 (STRUCTURED_WITH_OFFSET) requires `idx < num_records` and `off + 8 <= stride` (`stride = 8, off = 0`, `stride = 16, off = 8`, `stride = 12, off = 0` succeed; `stride = 7, off = 0` and `stride = 12, off = 8` drop); mode 1 (STRUCTURED) checks `idx < num_records`; mode 2 (DISABLED) checks `num_records != 0`. **`buffer_atomic_{fmin,fmax}`**: lowered via `Gen.buffer_atomic_float` sharing `Gen._emit_atomic_fminmax_cas` (relaxed Device-scope `OpAtomicLoad` seed + `OpAtomicCompareExchange` + `GLSL.std.450` `NMin`/`NMax` CAS loop, no float-atomic extension required), enforcing V# bounds, 4-byte alignment, and `glc` return (`lds` and non-1-VGPR `vdata` raise `Unsupported`). On `gfx1036`, normal floats, `±inf`, `-0` vs `+0` (`fmin(-0, +0) = -0`, `fmax(-0, +0) = +0`), and `qNaN` (returns the non-NaN operand) match `NMin`/`NMax`; **known approximation**: the `gfx1036` L2 atomic unit quiets `sNaN` (`0x7f800001 -> 0x7fc00001`) regardless of `MODE`, while f32 subnormal handling follows the wave's `MODE.denorm32` and preserves sign (independently verified on a second `gfx1036`, wave32/wave64: under `denorm32 = 0`, subnormals flush to signed zero — `fmax(0x80000001, 0x80000002) -> 0x80000000 (-0)`, `fmax(0x00000001, 0x00000002) -> +0` — whereas under `denorm32 = 3`, subnormals are preserved and `NMin`/`NMax` is exact); `NMin`/`NMax` does not model `sNaN` quieting or `denorm32 = 0` subnormal flushing. CPU-checked by `tests/semantic/test_buffer_atomic_fminmax_and_align.py` (value grid, multi-lane CAS contention, OOB/partial-bounds matrix, inactive vs active-unaligned distinction across all six atomic families, and SPIR-V structural checks). | +| Absent-lane subgroup safety | Every native `OpGroupNonUniformShuffle` and `OpGroupNonUniformBroadcast` emitted by `tools/rdna2spirv.py` passes a physical lane index statically proven to name a running invocation in the current subgroup (never constant `%uint_0` or an unguarded lane, which is SPIR-V UB on partial waves and reads stale VGPR bits on RADV that can fault downstream BDA `OpConvertUToPtr` loads): (1) `wave32_first_running_lane()` falls back to `wave_lane()` instead of `0` when the half's `%true` ballot word is empty, and `subgroup_first_running_lane()` (`OpGroupNonUniformBallotFindLSB` + `OpGroupNonUniformAny(%true)` on non-VS stages and `ballot_lsb_by_words` on VS for MoltenVK compatibility, falling back to `subgroup_lane()`) supplies the `EXEC == 0` fallback for `v_readfirstlane_b32` in all non-`wave32_fragment` stages (MS, VS, GS, CS, wave64 PS); (2) `lane_masks.definite_spill_reads()` generalizes `scalar_spills()` to mixed-VGPR constant-lane `v_writelane_b32`/`v_readlane_b32` reloads dominated on all CFG paths with no intervening write to the VGPR (parking them in `%sgpr` with zero shuffles), and remaining native `v_readlane_b32` shuffles check `OpGroupNonUniformBallot(%true)` + `BallotBitExtract` and redirect absent targets to the wave's first running lane (preserving SGPR wave uniformity); (3) native `v_permlane16_b32`/`v_permlanex16_b32` (`FI=1` as well as `FI=0`) and `dpp_insn` (`fi:1` as well as `fi:0`, with out-of-row `in_bounds` clamping to `sgl` instead of `0`) redirect unlaunched/absent lanes to `subgroup_lane()` before `OpGroupNonUniformShuffle` (using bitwise masking + `Gen.eager` to preserve SHADER-529); (4) `ds_append`/`ds_consume` guards its broadcast shuffle against `EXEC == 0` and absent lanes with `subgroup_lane()`, and `ds_permute`/`ds_lane_read` always redirect absent lanes to `subgroup_lane()`; (5) `quad_any` (`s_wqm_b32`/`b64`) uses `OpGroupNonUniformBallot` + quad-nibble extraction in CS/VS/GS/MS (eliminating partial-quad `QuadSwap` and unguarded 4× shuffle UB), keeping `OpGroupNonUniformQuadSwap` only in Fragment shaders where Vulkan guarantees complete 2×2 quads. Confirmed by static SPIR-V invariant checker `tests/semantic/check_absent_lane_ub.py`, strict partial-wave CPU suite `tests/semantic/test_absent_lane_ub.py` (wave32/wave64 PS, VS, CS, MS, `s_load` after `v_readfirstlane_b32`, mixed spills, `v_permlane16`/`x16` `FI=1`, DPP `fi:1`/OOB, `s_wqm`, `ds_append`, negative controls, `spirv-val`, and all hand-written subgroup fixtures), and GPU-checked by `tests/test_absent_lane_gpu.py` on an AMD Ryzen 9 7950X3D RDNA2 iGPU (`gfx1036`, RADV, `LEONIDA_VK_VALIDATION=1`, 5-thread partial CS + 1×1 partial-quad wave32/wave64 PS: 0 faults, 0 validation errors, exact readback). | +| Coherent `glc`/`dlc` buffer and global memory | Buffer, global, and scalar memory loads/stores carrying `glc` or `dlc` emit `OpCapability VulkanMemoryModel`, `OpCapability VulkanMemoryModelDeviceScope`, `OpExtension "SPV_KHR_vulkan_memory_model"`, and `OpMemoryModel PhysicalStorageBuffer64 Vulkan`, tagging coherent loads with `Aligned\|MakePointerVisible\|NonPrivatePointer 4 %c1` (Device scope) and coherent stores with `Aligned\|MakePointerAvailable\|NonPrivatePointer 4 %c1` (and upgrading any coherent storage-image ops in the same module to `MakeTexelVisible`/`MakeTexelAvailable\|NonPrivateTexel %c1` instead of the banned `Coherent` decoration). Modules with any coherent buffer/global/scalar load emit `reads_glc_buffer: true` in `shader_meta` so the runtime inserts a cross-dispatch compute barrier. Confirmed against the SPIR-V Vulkan Memory Model spec and validated with `spirv-val --target-env vulkan1.2` + `spirv_mini_interp` in `tests/semantic/test_coherent_buffer_vmm.py`. | +| Literal S# sampler specialization | For each compile-time literal S# in `meta["literal_samplers"]` (exact sorted list order), `tools/rdna2spirv.py` declares `%lit_smp_ = OpSpecConstant %uint 4294967295` with `SpecId i` and emits `meta["literal_sampler_spec_base"] = 0`. At each sample/gather/get_lod site using that literal S#, `%lit_smp_ != 0xFFFFFFFF` selects the specialized bindless sampler index directly (bypassing the FNV-1a `%desc_lookup_fn` probe); when unspecialized (`0xFFFFFFFF`), execution falls back to `%desc_lookup_fn`. Checked with `spirv-val --target-env vulkan1.2` and both specialized and fallback path checks in `tests/semantic/test_literal_sampler_spec.py`. | +| Float-only `image_read_typed` elision and table-driven `buffer_store_format` | `Gen.image_read_typed` elides dead `uint`/`sint` runtime branches, format-mask lookups, and `%itx1`/`%itx2` descriptor aliases whenever an `image_load*` or `image_sample*` is provably float-only (every reachable consumer of its dest VGPRs is a pure f32/f16 float op with at least one float consumer, or a literal S# on `image_sample*` enables bilinear/aniso XY or linear mip filtering); `image_gather4*` and integer-consumed ops always keep all three typed branches. Dynamic `buffer_store_format_*` replaces the 77-way `OpSwitch` with a branch-free `%fmt_enc_desc_tab` lookup and shared `%fmt_enc_chan` helper. Checked for bit-for-bit parity across all 77 `Gen.FORMATS` codes (plus BGRA `0xf2e`, 2-component `DST_SEL`, `d16` signedness, and unknown codes) and `spirv-val --target-env vulkan1.2` in `tests/semantic/test_image_float_elide_and_store_table.py`. | +| Buffer-write metadata (`writes_buffer` and `buffer_write_slots`) | `tools/shader_meta.py` and `rdna2spirv.shader_meta` always emit `writes_buffer` (`true` iff the shader contains any buffer/tbuffer/global/flat/scalar buffer store or atomic; `false` for read-only, `image_store`/`image_atomic`-only, or LDS-only shaders) and `buffer_write_slots` (`[]` when `writes_buffer` is `false`, a sorted list of root user-SGPR or constant descriptor-table byte offsets when every buffer write is statically traceable, or `"dynamic"` otherwise) so the runtime can gate CPU write-back. Checked by `tests/semantic/test_writes_buffer_meta.py`. | ### System values confirmed on the corpus (SHADER-4) diff --git a/docs/running.md b/docs/running.md index 3b71966d95..a2aee7fe8b 100644 --- a/docs/running.md +++ b/docs/running.md @@ -68,7 +68,7 @@ reasons behind each step: [linux_proton.md](linux_proton.md#amd-on-linux-what-go | `LEONIDA_RT_AS=off`, `LEONIDA_SKIP_COMPUTE=` | the large ray-tracing programs, left out at play as in our longest runs ([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_ARENA_MB=4095`, `LEONIDA_TITLE_WINDOWS_MB=4096`, `LEONIDA_GEOMETRY_MB=6144` | room for the title's buffers in the world (with sparse binding the arena's size is address range; memory is bound as it is used) | | `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 | diff --git a/make_game.py b/make_game.py index 35f291d6b0..0b7fb75a2a 100644 --- a/make_game.py +++ b/make_game.py @@ -1863,10 +1863,11 @@ def exe_shaders(game: str, work: str, mc_signature: str, jobs: int = 1, emulate: WAVE64_MODES = ("auto", "on", "off") # The translator's fallback flags make_game.py can forward, and the argparse attribute each one reads. -FALLBACK_FLAGS = (("--no-float-controls", "no_float_controls"), ("--bary-fallback", "bary_fallback"), +FALLBACK_FLAGS = (("--no-float-controls", "no_float_controls"), ("--no-ftz32", "no_ftz32"), + ("--bary-fallback", "bary_fallback"), ("--texel-offset-fallback", "texel_offset_fallback"), ("--mesh-compute", "mesh_compute"), ("--f16-interp-fallback", "f16_interp_fallback"), ("--pc-tail-ubo", "pc_tail_ubo"), - ("--compact-spirv", "compact_spirv")) + ("--compact-spirv", "compact_spirv"), ("--integer-dot-fallback", "integer_dot_fallback")) def fallback_flags(a) -> tuple[str, ...]: @@ -2028,6 +2029,13 @@ def runtime_gpu_per_vertex(): return None +def runtime_gpu_integer_dot_product(): + """shaderIntegerDotProduct as tools/vk_subgroup_info.py answers for the GPU the runtime would use (required by + Vulkan 1.3, so False only on a Vulkan 1.2 device such as MoltenVK's), or None when it can't be told.""" + v = runtime_gpu_info().get("integer_dot_product") + return v if isinstance(v, bool) else None + + def runtime_gpu_barycentric_fallback(): """Whether the selected Vulkan GPU's driver has a known BaryCoordKHR bug (Mesa ANV, AMD Windows on gfx90c), or None when it can't be told.""" @@ -2072,7 +2080,7 @@ def runtime_gpu_max_push_constants(): # Source and data files that produce the translated modules, metadata, partner stubs and native PSO catalog. -TRANSLATION_SOURCES = ("rdna2spirv.py", "shader_ir.py", "cfg_structure.py", "file_mode.py", "fssm_header.py", "lane_masks.py", "wave64_halves.py", +TRANSLATION_SOURCES = ("rdna2spirv.py", "descriptor_sources.py", "heap_index_census.py", "shader_ir.py", "cfg_structure.py", "file_mode.py", "fssm_header.py", "lane_masks.py", "wave64_halves.py", "wave64_emulate_opt.py", "spirv_loop_guard.py", "shader_meta.py", "spirv_stubs.py", "spirv_asm.py", "spirv_asm_tables.py", "spirv_opt.py", "report_paths.py", "replace_retry.py", "fssm_unpack.py", "shader_stage_manifest.py", "rdna2_decode.py", "rdna2_isa_tables.py", "gfx10_formats.json", @@ -3191,9 +3199,10 @@ def main() -> int: ap.add_argument("--compact-spirv", action="store_true", help="run the translator's compact binary pass on all shader libraries (requires spirv-opt)") ap.add_argument("--no-float-controls", action="store_true", - help="translate without SignedZeroInfNanPreserve and DenormPreserve (Depends on: #664), for " - "devices whose vk_pipeline_check skips a shader without " - "shaderSignedZeroInfNanPreserveFloat32 or shaderDenormPreserveFloat16") + help="translate without SignedZeroInfNanPreserve, DenormPreserve and DenormFlushToZero (Depends on: " + "#664), for devices whose vk_pipeline_check skips a shader without float-control properties") + ap.add_argument("--no-ftz32", action="store_true", + help="translate without DenormFlushToZero 32 (keep software f32 denormal flushes, e.g. llvmpipe)") ap.add_argument("--bary-fallback", action="store_true", help="translate raw barycentric reads from an interpolated vec3 input (with a pass-through " "geometry shader the runtime draws), for devices without " @@ -3211,6 +3220,10 @@ def main() -> int: ap.add_argument("--native-mesh", action="store_true", help="keep native mesh shaders on Intel's Windows Vulkan driver instead of turning on " "--mesh-compute (for a driver that fixes BUILD-2202's crash)") + ap.add_argument("--integer-dot-fallback", action="store_true", + help="translate the 4x8-bit dot products (v_dot4_*) as extracts, multiplies and adds instead of " + "SPV_KHR_integer_dot_product; on by itself when the runtime's GPU has no " + "shaderIntegerDotProduct (a Vulkan 1.2 device)") ap.add_argument("--pc-tail-ubo", action="store_true", help="keep s0..s31 in 128 push-constant bytes and move heap/code base to a set-1 uniform " "block; on by itself when the runtime's GPU reports maxPushConstantsSize below what " @@ -3328,6 +3341,14 @@ def main() -> int: log(f"shaders: the GPU the runtime would use reports maxPushConstantsSize = {max_pc} (< {need_pc}): " "translating with --pc-tail-ubo") a.pc_tail_ubo = True + if "shaders" in stages and not a.integer_dot_fallback: + integer_dot = runtime_gpu_integer_dot_product() + if integer_dot is False: + log("shaders: the GPU the runtime would use has no shaderIntegerDotProduct (a Vulkan 1.2 device): " + "translating with --integer-dot-fallback") + a.integer_dot_fallback = True + elif integer_dot is None: + a.integer_dot_fallback = keep_recorded_fallback("--integer-dot-fallback", work) fallbacks = fallback_flags(a) if "shaders" in stages else () overlap = True use_tui = leonida_tui.tui_eligible(a.no_tui) diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 9c433257d3..fa7c8aeacf 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -16,6 +16,17 @@ if(NOT CMAKE_SIZEOF_VOID_P EQUAL 8) message(FATAL_ERROR "gta6rt must be built for x64 (run from an x64 Native Tools prompt or vcvars64.bat)") endif() +# Target x86-64-v3 (AVX2, BMI1/2, FMA, F16C, LZCNT, POPCNT, MOVBE) on x86-64 hosts so SIMD hot paths +# (shadow_keep::sum_of, descriptor-slot scans, texture hashing) and auto-vectorization emit 256-bit code. +# Kept C/C++-only so ml64 does not receive an unknown switch, and skipped on non-x86-64 portable builds. +if(CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64|amd64)$") + if(MSVC) + add_compile_options($<$:/arch:AVX2>) + elseif(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") + add_compile_options($<$:-march=x86-64-v3>) + endif() +endif() + # Portable root-signature model + packer to user SGPRs (no d3d12.h, no windows.h), and the host CPU preflight of # --init/--run (src/host_cpu.h). Built on every OS, so their tests run in the Linux and macOS jobs as well as with the # Windows runtime. @@ -1553,8 +1564,9 @@ 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) + # When a held console memory wait may go without its value (src/list_value_progress.h), on hand-built states. + add_executable(list_value_progress_test test/list_value_progress_test.cpp) + add_test(NAME list_value_progress COMMAND list_value_progress_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) @@ -2186,6 +2198,22 @@ if(TARGET Vulkan::Headers) add_test(NAME vk_queue_query_sync COMMAND vk_queue_query_sync_test) set_tests_properties(vk_queue_query_sync PROPERTIES SKIP_RETURN_CODE 77) endif() + # The "submit frame" and "submit floor" lines (src/submit_phases.h): a scripted run on the CPU, then empty + # submissions through VulkanQueue whose floor sums must equal the phase totals (that part needs a Vulkan device). + add_executable(submit_frame_test test/submit_frame_test.cpp) + target_link_libraries(submit_frame_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) + if(WIN32) + target_compile_definitions(submit_frame_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + else() + find_package(Threads REQUIRED) + target_link_libraries(submit_frame_test PRIVATE Threads::Threads) + endif() + if(MSVC) + target_compile_options(submit_frame_test PRIVATE /W4 /permissive- /utf-8) + endif() + if(BUILD_TESTING) + add_test(NAME submit_frame COMMAND submit_frame_test) + endif() # Fence and queue teardown with submissions pending: a fence released after an unheld Signal, the bindless upload # queue destroyed before another queue submits, the device-fault submit ring forgetting destroyed semaphores. add_executable(vk_semaphore_lifetime_test test/vk_semaphore_lifetime_test.cpp) @@ -2203,6 +2231,65 @@ if(TARGET Vulkan::Headers) add_test(NAME vk_semaphore_lifetime COMMAND vk_semaphore_lifetime_test) set_tests_properties(vk_semaphore_lifetime PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) endif() + # The sparse GPU address arena on a real device: bound bytes follow the allocations, a released block stays bound + # until the submission that read it has retired, and binds go to a queue of their own (src/arena_backing.h). + add_executable(arena_sparse_gpu_test test/arena_sparse_gpu_test.cpp) + target_link_libraries(arena_sparse_gpu_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) + if(WIN32) + target_compile_definitions(arena_sparse_gpu_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + endif() + if(MSVC) + target_compile_options(arena_sparse_gpu_test PRIVATE /W4 /permissive- /utf-8) + endif() + if(BUILD_TESTING) + add_test(NAME arena_sparse_gpu COMMAND arena_sparse_gpu_test) + set_tests_properties(arena_sparse_gpu PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + endif() + # A console heap read in place: one home bound into a mirror chunk and into the arena shows the same bytes through + # both, CPU and GPU writes alike, and the unbound guard after the heap reads zero. + add_executable(vk_heap_alias_test test/vk_heap_alias_test.cpp) + target_link_libraries(vk_heap_alias_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) + if(WIN32) + target_compile_definitions(vk_heap_alias_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + endif() + if(MSVC) + target_compile_options(vk_heap_alias_test PRIVATE /W4 /permissive- /utf-8) + endif() + if(BUILD_TESTING) + add_test(NAME vk_heap_alias COMMAND vk_heap_alias_test) + set_tests_properties(vk_heap_alias PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + endif() + # The page mirror on a real device (src/title_mirror.h): a title-written V# read through a buffer reaches its page at + # heap_base + its title address; remaps, writes and unmaps reach the next dispatch that waits for the bind. + add_executable(vk_title_mirror_test test/vk_title_mirror_test.cpp) + target_link_libraries(vk_title_mirror_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) + if(WIN32) + target_compile_definitions(vk_title_mirror_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + endif() + if(MSVC) + target_compile_options(vk_title_mirror_test PRIVATE /W4 /permissive- /utf-8) + endif() + find_program(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE glslangValidator HINTS "$ENV{VULKAN_SDK}/Bin" "$ENV{VULKAN_SDK}/bin") + if(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) + set(_title_mirror_spv ${CMAKE_CURRENT_BINARY_DIR}/generated/cs_title_mirror_read.spv) + add_custom_command(OUTPUT ${_title_mirror_spv} + COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${_title_mirror_spv} + ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_title_mirror_read.comp + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_title_mirror_read.comp + COMMENT "Compiling the page mirror test shader" VERBATIM) + target_sources(vk_title_mirror_test PRIVATE ${_title_mirror_spv}) + target_compile_definitions(vk_title_mirror_test PRIVATE LEONIDA_TEST_TITLE_MIRROR_SPV="${_title_mirror_spv}") + endif() + if(BUILD_TESTING) + add_test(NAME vk_title_mirror COMMAND vk_title_mirror_test) + set_tests_properties(vk_title_mirror PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + endif() + # A measurement, not a test: what page-sized sparse binds cost on the device (the page mirror's layout). + add_executable(vk_sparse_bind_bench test/vk_sparse_bind_bench.cpp) + target_link_libraries(vk_sparse_bind_bench PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) + if(WIN32) + target_compile_definitions(vk_sparse_bind_bench PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + endif() # The AMD breadcrumbs (LEONIDA_DEVICE_MARKERS) on a real device: after a few dispatches and a wait, the queue's # started and finished markers hold the last dispatch's seq. SKIP without VK_AMD_buffer_marker. add_executable(vk_device_markers_test test/vk_device_markers_test.cpp) @@ -2257,6 +2344,34 @@ if(TARGET Vulkan::Headers) set_tests_properties(vk_overlapping_occlusion vk_overlapping_occlusion_no_statistics PROPERTIES SKIP_RETURN_CODE 77) endif() + # LEONIDA_GPU_PROFILE (src/vulkan_gpu_profile.h): known dispatches and a draw through VulkanQueue, each pipeline + # reported under its name with its calls, runs and a GPU time that grows with its work; prints the cost when on. + add_executable(vk_gpu_profile_test test/vk_gpu_profile_test.cpp) + target_link_libraries(vk_gpu_profile_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) + if(WIN32) + target_compile_definitions(vk_gpu_profile_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + else() + find_package(Threads REQUIRED) + target_link_libraries(vk_gpu_profile_test PRIVATE Threads::Threads) + endif() + if(MSVC) + target_compile_options(vk_gpu_profile_test PRIVATE /W4 /permissive- /utf-8) + endif() + foreach(stage comp vert) + set(source "${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/gpu_profile_spin.${stage}") + set(output "${CMAKE_CURRENT_BINARY_DIR}/gpu_profile_spin.${stage}.spv") + add_custom_command(OUTPUT "${output}" + COMMAND "${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE}" -V --target-env vulkan1.0 + -o "${output}" "${source}" + DEPENDS "${source}" VERBATIM) + target_sources(vk_gpu_profile_test PRIVATE "${output}") + endforeach() + if(BUILD_TESTING) + add_test(NAME vk_gpu_profile COMMAND vk_gpu_profile_test + "${CMAKE_CURRENT_BINARY_DIR}/gpu_profile_spin.comp.spv" + "${CMAKE_CURRENT_BINARY_DIR}/gpu_profile_spin.vert.spv") + set_tests_properties(vk_gpu_profile PROPERTIES SKIP_RETURN_CODE 77) + endif() endif() # CPU-only: the ranking that makes these harnesses prefer a native ICD over Mesa's Dozen (#915). No GPU needed. add_executable(vk_device_pick_test test/vk_device_pick_test.cpp) @@ -2277,6 +2392,19 @@ if(TARGET Vulkan::Headers) add_test(NAME vk_bc_zero_init COMMAND vk_bc_zero_init_test) set_tests_properties(vk_bc_zero_init PROPERTIES SKIP_RETURN_CODE 77) endif() + # GPU detile compute shader & linear direct copy parity against CPU console texture detiler (src/vulkan_title_detile.h). + add_executable(vk_title_detile_test test/vk_title_detile_test.cpp) + target_link_libraries(vk_title_detile_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) + if(WIN32) + target_compile_definitions(vk_title_detile_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + endif() + if(MSVC) + target_compile_options(vk_title_detile_test PRIVATE /W4 /permissive- /utf-8) + endif() + if(BUILD_TESTING) + add_test(NAME vk_title_detile COMMAND vk_title_detile_test) + set_tests_properties(vk_title_detile PROPERTIES SKIP_RETURN_CODE 77) + endif() # FenceWaitDispatcher concurrency and device-lost regressions (re-entrant callbacks, wakeup on device lost, counter error drain). add_executable(vk_fence_dispatcher_sync_test test/vk_fence_dispatcher_sync_test.cpp) target_link_libraries(vk_fence_dispatcher_sync_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) @@ -2967,6 +3095,25 @@ if(TARGET Vulkan::Headers) LEONIDA_TEST_CS_R9G9B9E5_UAV_SPV="${LEONIDA_TEST_CS_R9G9B9E5_UAV}") endif() + # The page mirror in the game's device over xmem's pages (src/title_mirror.h): a stream pool's GPU-only pages, + # their twins and the title's own view at heap_base + their address, after slot-31 copies, title writes and remaps. + add_executable(d3d12_page_mirror_test test/d3d12_page_mirror_test.cpp shims/xmem.cpp shims/registry.cpp) + target_link_libraries(d3d12_page_mirror_test PRIVATE gta6rt_d3d12_com d3d12 dxgi psapi) + target_compile_definitions(d3d12_page_mirror_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_page_mirror_test PRIVATE /W4 /permissive- /utf-8) + target_link_options(d3d12_page_mirror_test PRIVATE /OPT:NOREF) + add_test(NAME d3d12_page_mirror COMMAND d3d12_page_mirror_test) + set_tests_properties(d3d12_page_mirror PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) + # A console heap read in place through the page mirror: the GPU reads the filtered slots below 4 GiB of the arena, + # the title's bytes never change, a rewrite reaches the GPU at the next refresh, zeros after the heap. + add_executable(d3d12_heap_in_place_test test/d3d12_heap_in_place_test.cpp shims/xmem.cpp shims/registry.cpp) + target_link_libraries(d3d12_heap_in_place_test PRIVATE gta6rt_d3d12_com d3d12 dxgi psapi) + target_compile_definitions(d3d12_heap_in_place_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_heap_in_place_test PRIVATE /W4 /permissive- /utf-8) + target_link_options(d3d12_heap_in_place_test PRIVATE /OPT:NOREF) + add_test(NAME d3d12_heap_in_place COMMAND d3d12_heap_in_place_test) + set_tests_properties(d3d12_heap_in_place PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) + # Debug markers as VK_EXT_debug_utils labels, and private data on every object (D3D-24). add_executable(d3d12_debug_markers_test test/d3d12_debug_markers_test.cpp) target_link_libraries(d3d12_debug_markers_test PRIVATE gta6rt_d3d12_com) @@ -2985,7 +3132,7 @@ if(TARGET Vulkan::Headers) add_test(NAME d3d12_host_prefix COMMAND d3d12_existing_heap_test --host-prefix-only) set_tests_properties(d3d12_host_prefix PROPERTIES SKIP_RETURN_CODE 77) set_tests_properties(d3d12_existing_heap PROPERTIES SKIP_RETURN_CODE 77) - # LEONIDA_TEXTURE_REFRESH_ASYNC=1 (set by the test itself): a mapped plane's first submission reads its bytes. + # A mapped plane's first submission reads its bytes. add_test(NAME d3d12_mapped_plane_async COMMAND d3d12_existing_heap_test --mapped-plane-async) set_tests_properties(d3d12_mapped_plane_async PROPERTIES SKIP_RETURN_CODE 77) # The same with write watching off: the guarded cases only, the concurrent writers among them. @@ -2996,6 +3143,14 @@ if(TARGET Vulkan::Headers) add_test(NAME d3d12_existing_heap_write_watch COMMAND d3d12_existing_heap_test) set_tests_properties(d3d12_existing_heap_write_watch PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_WRITE_WATCH=1") + # What a guard costs on this host (fault, VirtualProtect, re-arming, write watch, soft-dirty): prints a table for + # the tracking policy (src/title_write_policy.h). + add_executable(guard_fault_bench test/guard_fault_bench.cpp) + target_compile_definitions(guard_fault_bench PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + # The page mirror's hot/cold tracking (src/title_mirror_hot_cold.h) on real guards. + add_executable(title_mirror_hot_cold_test test/title_mirror_hot_cold_test.cpp) + target_compile_definitions(title_mirror_hot_cold_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + add_test(NAME title_mirror_hot_cold COMMAND title_mirror_hot_cold_test) # Slot 133 on untouched xmem physical pages: committed through the pages hook, then imported. xmem.cpp and # registry.cpp are compiled in, as xmem_test does, to reach the registered XMem* exports. add_executable(d3d12_xmem_placed_test test/d3d12_xmem_placed_test.cpp shims/xmem.cpp shims/registry.cpp) @@ -4032,6 +4187,14 @@ if(TARGET Vulkan::Headers) set_tests_properties(d3d12_title_va_shadow PROPERTIES ENVIRONMENT "LEONIDA_TEST_CONSOLE_SHADOW=1;LEONIDA_GEOMETRY_MB=0" SKIP_RETURN_CODE 77) add_test(NAME d3d12_geometry_views COMMAND d3d12_title_va_test) set_tests_properties(d3d12_geometry_views PROPERTIES ENVIRONMENT "LEONIDA_GEOMETRY_MB=16" SKIP_RETURN_CODE 77) + # The same two on the device the game makes (create_vulkan_device_standalone, with the arena's bind queue): where + # the GPU can, the arena is sparse, and on RADV every buffer outside it then lies 64 TiB below heap_base, so + # title windows, shadows and geometry copies are reached through negative (sign-extended) V# offsets. + add_test(NAME d3d12_title_va_game_device COMMAND d3d12_title_va_test --game-device) + set_tests_properties(d3d12_title_va_game_device PROPERTIES ENVIRONMENT "LEONIDA_ARENA_MB=1024" SKIP_RETURN_CODE 77) + add_test(NAME d3d12_geometry_views_game_device COMMAND d3d12_title_va_test --game-device) + set_tests_properties(d3d12_geometry_views_game_device PROPERTIES + ENVIRONMENT "LEONIDA_GEOMETRY_MB=16;LEONIDA_ARENA_MB=1024" SKIP_RETURN_CODE 77) set_tests_properties(d3d12_title_va PROPERTIES SKIP_RETURN_CODE 77) # Past LEONIDA_TITLE_WINDOWS_MB a view of the title's memory is never its raw VA (#1537): with no other backing it # is written zero-size, and a dispatch through it reads zeros. @@ -4324,6 +4487,16 @@ if(TARGET Vulkan::Headers) target_compile_options(d3d12_set0_compute_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_set0_compute COMMAND d3d12_set0_compute_test) set_tests_properties(d3d12_set0_compute PROPERTIES SKIP_RETURN_CODE 77) + # A T# written into a console heap before its texture exists samples the texture at the first submission after + # it appears (the heap's slot records), and leaves the hash table when it goes. + add_executable(d3d12_tsharp_refill_test test/d3d12_tsharp_refill_test.cpp shims/d3d12_xs_device.cpp + shims/d3d12_xs_pso_stream.cpp ${LEONIDA_TEST_CS_SET0_SAMPLE}) + target_link_libraries(d3d12_tsharp_refill_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_tsharp_refill_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_CS_SET0_SAMPLE_SPV="${LEONIDA_TEST_CS_SET0_SAMPLE}") + target_compile_options(d3d12_tsharp_refill_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_tsharp_refill COMMAND d3d12_tsharp_refill_test) + set_tests_properties(d3d12_tsharp_refill PROPERTIES SKIP_RETURN_CODE 77) set(depth_uav_shader ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_depth_stencil_uav.comp) foreach(variant IN ITEMS DEPTH_STENCIL_2D DEPTH_STENCIL_ARRAY DEPTH16_2D DEPTH16_ARRAY) set(spv ${CMAKE_CURRENT_BINARY_DIR}/generated/cs_depth_uav_${variant}.spv) @@ -4858,6 +5031,14 @@ 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 GPU address arena's backing blocks with fake hooks: placement, binding, unbinding after the release ticket, + # the constant-time accessor and the bind queue choice (src/arena_backing.h). + add_executable(arena_backing_test test/arena_backing_test.cpp) + target_link_libraries(arena_backing_test PRIVATE Vulkan::Headers) + if(WIN32 AND MSVC) + target_compile_options(arena_backing_test PRIVATE /W4 /permissive- /utf-8) + endif() + add_test(NAME arena_backing COMMAND arena_backing_test) # The mem probe's breakdown line: the tally by consumer, the owner scopes and the text (src/memory_breakdown.h). add_executable(memory_breakdown_test test/memory_breakdown_test.cpp) if(WIN32 AND MSVC) @@ -4887,7 +5068,33 @@ if(TARGET Vulkan::Headers) target_compile_options(shadow_keep_test PRIVATE /W4 /permissive- /utf-8) endif() add_test(NAME shadow_keep COMMAND shadow_keep_test) + # The host's reads of title pages only xmem's frame table holds (src/title_frames.h). + add_executable(title_frames_test test/title_frames_test.cpp) + if(WIN32 AND MSVC) + target_compile_options(title_frames_test PRIVATE /W4 /permissive- /utf-8) + endif() + add_test(NAME title_frames COMMAND title_frames_test) + # The page mirror's hooks for descriptor heaps read in place: a second binding of a range's pages, and a filter on + # the fill path (src/title_mirror.h). No GPU. + add_executable(title_mirror_hooks_test test/title_mirror_hooks_test.cpp) + target_link_libraries(title_mirror_hooks_test PRIVATE Vulkan::Headers) + if(WIN32 AND MSVC) + target_compile_options(title_mirror_hooks_test PRIVATE /W4 /permissive- /utf-8) + endif() + add_test(NAME title_mirror_hooks COMMAND title_mirror_hooks_test) + # The XMemAlloc heap in the page mirror's range (src/title_heap.h). + add_executable(title_heap_test test/title_heap_test.cpp) + if(WIN32 AND MSVC) + target_compile_options(title_heap_test PRIVATE /W4 /permissive- /utf-8) + endif() + add_test(NAME title_heap COMMAND title_heap_test) # Queue construction cleans its Vulkan handles if holder registration runs out of host memory. + # Which title textures the refresh looks at: only those something says changed (src/title_texture_watch.h). + add_executable(title_texture_watch_test test/title_texture_watch_test.cpp) + add_test(NAME title_texture_watch COMMAND title_texture_watch_test) + # Hot pages copied every submission, cold ones guarded (src/title_write_policy.h): nothing missed. + add_executable(title_write_policy_test test/title_write_policy_test.cpp) + add_test(NAME title_write_policy COMMAND title_write_policy_test) add_executable(vk_host_texture_order_test test/vk_host_texture_order_test.cpp) target_link_libraries(vk_host_texture_order_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) if(WIN32) @@ -4914,6 +5121,26 @@ if(TARGET Vulkan::Headers) endif() add_test(NAME vk_xdxr_postbuild_readback COMMAND vk_xdxr_postbuild_readback_test) set_tests_properties(vk_xdxr_postbuild_readback PROPERTIES SKIP_RETURN_CODE 77) + # Round 3B runtime hooks: LiteralSamplerSpec, reads_glc_buffer barrier, writes_buffer hook, VulkanMemoryModel. + add_executable(r3b_runtime_hooks_test test/r3b_runtime_hooks_test.cpp) + target_link_libraries(r3b_runtime_hooks_test PRIVATE Vulkan::Headers Threads::Threads ${CMAKE_DL_LIBS}) + if(WIN32) + target_compile_definitions(r3b_runtime_hooks_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + if(MSVC) + target_compile_options(r3b_runtime_hooks_test PRIVATE /W4 /permissive- /EHsc /utf-8) + endif() + endif() + add_test(NAME r3b_runtime_hooks COMMAND r3b_runtime_hooks_test) + # Stage 5b replay state caching: redundant bind/push/dynamic-state elision, helper invalidation, throughput & GPU validation. + add_executable(replay_state_cache_test test/replay_state_cache_test.cpp) + target_link_libraries(replay_state_cache_test PRIVATE Vulkan::Headers Threads::Threads ${CMAKE_DL_LIBS}) + if(WIN32) + target_compile_definitions(replay_state_cache_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + if(MSVC) + target_compile_options(replay_state_cache_test PRIVATE /W4 /permissive- /EHsc /utf-8) + endif() + endif() + add_test(NAME replay_state_cache COMMAND replay_state_cache_test) # Title-placed buffer VAs (device slot 133) and the console VA shaders reach them by (src/title_va_alias.h). add_executable(title_va_alias_test test/title_va_alias_test.cpp) diff --git a/runtime/README.md b/runtime/README.md index 1a3d18f429..27ba611923 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -352,18 +352,14 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_BIG_COMPILE_BUDGET_MB` | unset | The budget, in MiB: a fixed number (`0`: one large pipeline at a time) instead of three quarters of the memory that is free at the moment, which is the smaller of the free RAM and the room under the commit limit, read again for each pipeline. Text that is not a number is ignored. | | `LEONIDA_CONSOLE_FORMATS` | on | Texture descriptions the console accepts and a PC GPU may not (an R9G9B9E5 render target, an sRGB RGBA8 or BGRA8 texture with unordered access) get a host format that can do the job. `0` refuses them, as a PC D3D12 runtime does. | | `LEONIDA_CONSOLE_HEAP_SHADOW` | on | A console descriptor heap has a copy in the descriptor arena that the shaders read. `0` keeps its bytes in the title's memory only (the comparison for a run that misbehaves with the copy). | -| `LEONIDA_IMPORT_BELOW_ARENA` | unset | `1` keeps a host-memory import that the driver put below the GPU address arena. By default such an import is not used and the shadow buffer in the arena answers, because a V# cannot name an address below the arena. | +| `LEONIDA_IMPORT_BELOW_ARENA` | unset | `1` keeps a host-memory import that the driver put below the GPU address arena. By default such an import is not used and the shadow buffer in the arena answers. `1` also makes the runtime read V# bases as signed offsets even when a loaded module does not declare that it sign-extends them; without it, the modules' own `vsharp_base_sign_extended` markers decide (all of them: signed, and the arena may be sparse). | | `LEONIDA_HOST_IMAGE_COPY` | `auto` | Whether `WriteToSubresource`/`ReadFromSubresource` copy on the CPU with `VK_EXT_host_image_copy`. `auto` (unset, or any text other than `0` and `1`) uses it where the device has it, except on NVIDIA (vendor `0x10DE`), where a real boot lost the device; `1` uses it wherever the device has it; `0` never enables the extension, so every CPU texture copy takes the staging submit. Device creation logs one `[rt] d3d12: host image copy:` line with the choice and why (`docs/d3d12_vulkan.md`). | -| `LEONIDA_ORDER_TEXTURE_UPLOADS` | on | A title texture in a host-transfer image is filled through the ordered host copy (`write_host_texture`). `0` fills it with `WriteToSubresource`. | +| `LEONIDA_PAGE_MIRROR` | on | Mirrors title GPU-readable pages in place at `heap_base + title_va` via sparse aliased buffers (`src/title_mirror.h`, `src/title_mirror_space.h`), so shaders read title memory and in-place console heaps without per-view copies. `0` disables the mirror and keeps ordinary host reservations and copies. | +| `LEONIDA_GPU_DETILE` | on | Uploads mirrored title textures directly from `TitleMirror` via GPU linear copy or GPU compute detile (`src/vulkan_title_detile.h`, `shims/d3d12_title_image_upload.h`). `0` forces the CPU read/detile staging path for A/B parity testing. | | `LEONIDA_PLACED_IMAGE_KEYS` | on | A texture the title placed at its own address (device slot 133) and that the GPU writes keeps its own image address as its T# key. `0` re-keys it to the title address, like a texture the GPU does not write. | | `LEONIDA_PLACED_TEXTURE_UAV` | on | Device slot 71 writes an unordered-access view of a texture in the title's placed memory. `0` writes a null descriptor. | | `LEONIDA_REFRESH_MAPPED_TEXTURES` | on | A mapped slot-133 texture is refilled outside the fill budget, and its pages are committed before they are read. `0` treats it like any other title texture. | | `LEONIDA_TEXTURE_PAGE_CHECK` | on | The pages of a title texture are checked for being readable before they are hashed or copied. `0` checks only a texture whose check is already pending. | -| `LEONIDA_TITLE_TEXTURE_PERIOD_MS` | `16` | The shortest time between two passes over the textures filled from the title's memory. | -| `LEONIDA_TITLE_TEXTURE_CHECK_KB` | `4096` | How many KiB of those textures one pass hashes to find changed ones. | -| `LEONIDA_TITLE_TEXTURE_FILL_MB` | `32` | How many MiB of changed textures one pass fills again; the rest waits for the next pass. | -| `LEONIDA_TEXTURE_HASH_BUDGET_US` | `400` | Microseconds a pass may spend hashing before it stops at a texture boundary. `0` leaves the byte budget alone to bound it. | -| `LEONIDA_TEXTURE_SWEEP_BUDGET_US` | `400` | Microseconds a pass may spend on residency checks and uploads between textures. | | `LEONIDA_TITLE_BUFFERS_MB` | `512` | The most memory, in MiB, of buffers made over the title's own memory for vertex and index views that name it. | | `LEONIDA_TITLE_BUFFER_COVERAGE` | on | Such a view counts as covered only when a known buffer spans all its bytes. `0` asks for the first byte only. | | `LEONIDA_SHADOW_FULL_WALK` | unset | *Diagnostic.* `1` queries every page of the title-memory shadows at every refresh, as before unchanged generations were skipped. | @@ -399,18 +395,18 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_WINDOW` | unset | `WxH` resizes the title's window when the presenter attaches to it. | | `LEONIDA_PRESENT_DUMP` | unset | *Diagnostic.* `DIR` or `DIR,N` writes every Nth presented frame (60 by default) as a PNG into `DIR` (`src/present_dump.h`). The files are pictures of the title: keep them out of commits, issues and pull requests. | | `LEONIDA_LOCAL_SPEECH` | unset | `1` forwards the title's speech-synthesis calls to the host's installed `xgameruntime.dll` where there is one. Unset, and wherever that library is missing, the silent voice answers. No profile sets it. | -| `LEONIDA_CONSOLE_FIX_US` | `0` | Microseconds one submission may spend fixing the changed slots of a console descriptor heap's copy; `0` sets no limit. Past it, each further changed slot is written as a null descriptor and queued for `LEONIDA_CONSOLE_RETRY_US`, so a shader reads it as empty until its turn comes: a limit changes results, and can hang the GPU. | -| `LEONIDA_CONSOLE_RETRY_US` | `500` | Microseconds one submission may spend retrying, round robin, the console heap slots not settled yet (a T# whose texture does not exist yet, or one deferred by `LEONIDA_CONSOLE_FIX_US`). `0` retries all of them at every submission. | +| `LEONIDA_VSHARP_NOTHING_DETAIL` | unset | *Diagnostic.* `1` queries host memory (`VirtualQuery`) for console-heap V# bases that resolved to nothing (`arena offset` or `not title memory`) to break them down by host region kind (`image`, `mapped`, `private`, `reserved`, `free`) in the heap's periodic log. | +| `LEONIDA_CONSOLE_FIX_US` | `0` | Microseconds one submission may spend fixing the changed slots of a console descriptor heap's copy; `0` sets no limit. Past it, each further changed slot is written as a null descriptor and fixed first at the next submission, under the same limit, so a shader reads it as empty until then: a limit changes results, and can hang the GPU. | +| `LEONIDA_CONSOLE_RETRY_US` | `500` | `LEONIDA_CONSOLE_HEAP_GPU` only: microseconds one submission may spend retrying, round robin, the T#s of a heap the GPU pass translates whose texture does not exist yet. `0` retries all of them at every submission. The CPU copy (the default) has no retries: a T# waiting for its texture is fixed when a texture appears at its address (docs/d3d12_vulkan.md section 3.4). | | `LEONIDA_SHADOW_ALIAS_MS` | `0` | The shortest time, in milliseconds, between two copies of the title-memory pages that XMem maps at two addresses into the slot-133 shadows and title windows: pages a write reached since they were guarded at every address, or every time while they can't be (a page pinned for a kernel write). `0` copies them at every submission; a larger value lets a GPU read of them be up to that many milliseconds behind the title's writes. | | `LEONIDA_SHADOW_KEEP` | on | The slot-133 shadows and title windows copy a page only in the 256-byte pieces where the title's bytes changed since the last copy, so what a shader stored in the copy stays, also on pages copied without a sign that the title wrote them (aliased while they can't be guarded at every address, unguarded, pinned). A title writing the same bytes again to reset such a value is not seen. `0` copies those pages whole, as before, overwriting the GPU's writes. | | `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_BEFORE_EXECUTE_COALESCE` | on | Single-flights and coalesces identical `before-execute` memory-sync passes across submissions when no new CPU writes or page mappings have occurred, while still draining any pending page-mirror remap feed (`shims/d3d12_vulkan_device.cpp`). `0` runs the full pass on every submission. | +| `LEONIDA_CLWB_PATCH` | on | Rewrites trapping `CLWB` instructions in title code in place to `CLFLUSHOPT` (or a same-length `NOP` when the host CPU lacks `CLFLUSHOPT`) on the first `#UD` fault instead of trapping on every execution (`src/cpu_emulation.h`). `0` keeps emulating every `CLWB` through the exception handler. | | `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_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. | -| `LEONIDA_TITLE_TEXTURE_FILL_MS` | `8` | Milliseconds one pass over the textures filled from the title's memory may spend filling; a texture already started is finished. `0` removes the time limit and leaves `LEONIDA_TITLE_TEXTURE_FILL_MB` to bound the pass. | | `LEONIDA_TITLE_PARTIAL_MIPS` | unset | `1`: a 2D texture of one slice the title keeps in its own memory, whose larger mips are not readable, is filled from the first mip that is when its last slot-70 view starts there or later. Views that start above keep the fallback until a later fill has their mips. Unset, a texture waits for all its mips. | | `LEONIDA_TITLE_PARTIAL_MIPS_MB` | `2048` | With `LEONIDA_TITLE_PARTIAL_MIPS=1`, the image memory the textures filled in part may hold, in MiB: each has memory for all its mips. A texture past it keeps the fallback. | | `LEONIDA_MAP_READBACK` | unset | `1` writes the GPU's texels of a small render or unordered-access target the title placed into the title's pages when the title maps it, so a CPU read of the target sees what the GPU rendered (the title reads its exposure statistics that way). Only a single-row, single-mip, single-layer, single-sample 2D target of at most 4 KiB a row; the copy waits for the GPU's work already submitted, and a page that is not writable is left as it is. Unset, the title reads its own pages, which the GPU never writes. | @@ -425,11 +421,13 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_TITLE_HEAP` | unset | `1` makes the title's `XMemAlloc` blocks come from a Win32 heap of their own instead of the CRT heap (`shims/xmem.cpp`), so a GPU store through a slot-133 import past a buffer's end, or into a freed block, cannot corrupt the runtime's own objects on the same page. | | `LEONIDA_XMEM_SEC_COMMIT` | on under Wine | XMem's physical-page sections are committed whole under Wine; `0` reserves them and commits each page at its first touch, as on Windows, where the variable has no effect (`shims/xmem.cpp`). | | `LEONIDA_HANG_EXIT_S` | `0` | `s` seconds with work pending on the queues and no submission retired counts as a GPU hang the driver may recover from without reporting the device lost: the stall is reported (with checkpoints under `LEONIDA_STALL_CHECKPOINTS=1`) and the process ends with exit code `0x47` (`src/vulkan_backend.h`), so a boot does not sit until its time limit. `0` or unset never ends the process. | -| `LEONIDA_DEVICE_MARKERS` | unset | *Diagnostic.* `1`, with `LEONIDA_DEVICE_FAULT=1` or `2`, on a device with `VK_AMD_buffer_marker` (RADV, AMD's drivers): every dispatch the device-fault report numbers writes its `seq` into a small host-visible buffer at top of pipe (started) and bottom of pipe (finished), one slot per queue (`src/vulkan_device_markers.h`). A loss or stall report then prints each queue's last finished and started `seq` and marks the oldest started, unfinished dispatch as the likely hang, the AMD counterpart of NVIDIA's checkpoints; the values are best-effort after a loss. Two marker writes per dispatch while on; nothing when unset. Without the extension it logs one line saying the markers are unavailable ([docs/d3d12_vulkan.md](../docs/d3d12_vulkan.md) section 4.11). | +| `LEONIDA_DEVICE_MARKERS` | unset | *Diagnostic.* `1`, with `LEONIDA_DEVICE_FAULT=1` or `2`, on a device with `VK_AMD_buffer_marker` (RADV, AMD's drivers): every dispatch and every draw the device-fault report numbers writes its `seq` into a small host-visible buffer at top of pipe (started) and bottom of pipe (finished), one slot per queue (`src/vulkan_device_markers.h`); a draw's pair goes around its helper passes and its rendering scope. A loss or stall report then prints each queue's last finished and started `seq`, marks the oldest started, unfinished dispatch or draw as the likely hang, and names the last finished item, the ones in flight and an idle queue's next one not started: a draw with its kind and counts (indexed, indirect, mesh groups), its pipeline as `LEONIDA_GPU_PROFILE` names it, its execute, list and command, and its place among the draws to the same targets. With a device-fault address it also prints the last draw each queue started. The AMD counterpart of NVIDIA's checkpoints; the values are best-effort after a loss. Two marker writes per dispatch and per draw while on (RADV: a write-confirmed command-processor write and an end-of-pipe event, at most 24 dwords per pair, no wait for earlier work) and a 6 MiB history of the last 65,536 items; nothing when unset. Without the extension it logs one line saying the markers are unavailable ([docs/d3d12_vulkan.md](../docs/d3d12_vulkan.md) section 4.11). | | `LEONIDA_STALL_CHECKPOINTS` | unset | *Diagnostic.* `1` makes a device-stall report also collect the NVIDIA checkpoints of every queue (`src/vulkan_device_fault.h`), which name the programs in flight. The extension only promises them for a lost device, so outside that state the call is outside its contract. | | `LEONIDA_PASS_TRACE` | unset | *Diagnostic.* `n`, with `LEONIDA_DEVICE_FAULT=1`: in the frame after every `n`-th present, each submission logs its compute programs in order, repeats folded (`src/vulkan_backend.h`), for the frame's pass order. | | `LEONIDA_GPU_LATENCY` | unset | *Diagnostic.* `1` logs, every 10 s for each queue kind, how long the GPU took from a submission's `vkQueueSubmit` to it being seen done, and the share of the wall time the queue had work (`src/vulkan_backend.h`). | +| `LEONIDA_GPU_PROFILE` | unset | *Diagnostic.* `1` measures the GPU time of each pipeline (`src/vulkan_gpu_profile.h`). Each submission on a queue whose family has `timestampValidBits` writes a bottom-of-pipe timestamp after its opening barrier, before each run of consecutive draws or dispatches of one pipeline, after a run that another command follows (barrier, copy, clear, query) and at its end; the timestamps are read once the submission is done, never waited for. A bottom-of-pipe timestamp lands when everything before it has finished, so the difference between two consecutive ones is how much what lies between them extended the queue's work. On a GPU that runs a queue in order (a desktop GPU without tiling) that is the GPU time of the run, but work that overlaps the run before it (no barrier between) counts only for its tail, and the layer's helper passes for a draw or dispatch (index expansion, indirect clamp, counted dispatch) count for it. Every 10 s `[rt] gpu profile` lines give, per presented frame: the compute, graphics and mesh totals, calls and runs, and "other" (intervals with no draw or dispatch); per queue kind the busy time (measured on the CPU as `LEONIDA_GPU_LATENCY` does) against the time from each submission's first to its last timestamp and the share in draws and dispatches, so what lies outside the timestamps (semaphore waits, the gap before a submission starts, the opening barrier and bindless upload, the completion being seen late) is busy minus that span; and the 20 pipelines with the most GPU time, with ms per frame, share, kind, calls per frame and ms per call, named by their stages' ShaderLibrary entries as the pass trace names them (`cs `, `vs ps `, `ms ps `), or `pso 0x` without names. Queues run at the same time, so the direct and compute sums can add up to more than a frame. The first timestamp marks when the queue reached the submission (its previous work done), not when it was submitted. A run's calls include draws a false predicate discards. The names come from the title's shader library, so keep the log local. Cost when on: a query reset per submission, a timestamp per run boundary (about 1 µs each on a Raphael iGPU, submit to idle, `vk_gpu_profile_test`), a name lookup per run and the read on the fence thread; when off, one test per submission and per command. | | `LEONIDA_SUBMIT_PHASES_SECONDS` | `5` | *Diagnostic.* The period, in seconds, of the always-on line that says how many submissions there were and where their CPU time went, phase by phase (`src/submit_phases.h`). `0` turns the line off. | +| `LEONIDA_SUBMIT_FRAME_SECONDS` | `10` | *Diagnostic.* The period, in seconds, of two always-on lines beside the phase line (`src/submit_phases.h`); `0` turns them off. `[rt] submit frame`: frames presented, then per frame (the window's totals when none was presented) the submissions by queue kind and the milliseconds the title's threads spent in the layer: the phases of the phase line (wait, heaps, shadows, geometry, textures, pipes, replay), counted per frame instead of per submission, plus what that line leaves out: `lists` (an `ExecuteCommandLists` outside the phases: list unwrapping, the console's list-value waits and writes, the queue lock), `fences` (the queues' `Signal` and `Wait`, a fence's CPU `Signal`) and `present` (with its wait for a swapchain image; a present's time falls in the frame after the one it ends). Inside those, `vkQueueSubmit` and `lock waits` (for a contended lock of the submission path) are given apart and not added again. Then the worst frame of the window and the milliseconds per frame of our own threads, by thread: the submit worker (`LEONIDA_SUBMIT_ASYNC`, whose phases are then its time and not the title's), the texture read threads and filler, the console heap resolver, the geometry refresher (`LEONIDA_GEOMETRY_ASYNC`), the list values' pump and releaser and the fence thread's callbacks. `[rt] submit floor`: of the window's submissions, those in which nothing had to be brought up to date (no console heap slot or page, no shadow page, no geometry, no texture fill, no pipeline build; counted process-wide, so another thread's change during a submission takes it out too), with their average and least cost and their average by phase, against the average of all submissions. Cost: two counters per phase and per title call, and a clock read pair around each `vkQueueSubmit` and each contended lock. | | `LEONIDA_DEV_OVERLAY` | unset | *Diagnostic, Windows.* `1` draws what the runtime is doing over the top left corner of the title's window (`src/dev_overlay.h`): frame and submission rate, a submission's CPU time by phase, the phase running now, pipeline builds, indirect draws, cores, free RAM, and the private memory and GPU memory (`src/memory_figures.h`, shared with `LEONIDA_TITLE_HUD`; the GPU figure is the device's `VK_EXT_memory_budget`, `VRAM n/a` without it). | | `LEONIDA_SAMPLE_MS` | unset | *Diagnostic.* `ms` starts the thread sampler (`src/thread_sampler.h`): every `ms` milliseconds each thread of the process that used CPU since the last look is suspended just long enough to copy its context, its stack is unwound afterwards, and a periodic report lists the busiest threads and their most frequent call chains (eight frames, innermost first). | | `LEONIDA_SAMPLE_REPORT_S` | `10` | *Diagnostic.* Seconds between two reports of the thread sampler (`LEONIDA_SAMPLE_MS`). | @@ -439,7 +437,6 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_AFTERMATH_SHADER_ERRORS` | unset | *Diagnostic.* With `LEONIDA_AFTERMATH=1`, `1` also sets `VK_DEVICE_DIAGNOSTICS_CONFIG_ENABLE_SHADER_ERROR_REPORTING_BIT_NV` (`src/vulkan_aftermath.cpp`): the driver reports more shader errors, so a run can fault where it otherwise does not. | | `LEONIDA_AFTERMATH_KEEP_SPIRV` | unset | *Diagnostic.* With `LEONIDA_AFTERMATH=1`, `1` keeps a copy of every SPIR-V module created, for the crash-dump decoder. Off by default because the title creates gigabytes of them; the decoder then reads `/.spv` back when its hash matches the module's. The runtime's own modules are always kept. | | `LEONIDA_AUDIO` | unset | `silent` (any case) makes the title's `MMDeviceEnumerator` answer every render question with the runtime's silent output endpoint, even on a host that has an output (`shims/silent_audio.cpp`, read at each `CoCreateInstance`): no host audio device is opened and every sample is thrown away, for muted test runs. Unset, or any other value, the host's endpoint answers when there is one and the silent endpoint only when the host has none. Capture keeps the host's answer either way. See [docs/runtime_imports.md](../docs/runtime_imports.md#audio-output-off-the-console-wasapi). | -| `LEONIDA_TEXTURE_REFRESH_ASYNC` | unset | `1` moves the before-submission refresh of the title textures (`refresh_title_textures`) to a worker: a submission only wakes it, and fills by itself only the mapped textures that were never filled, so their first draw has their bytes. Persistent mappings are hashed whole on the worker every pass; the rest is swept 128 textures at a time. A texture changed since may be sampled a frame behind. | | `LEONIDA_SUBMIT_ASYNC` | `0` | ``: each queue's `ExecuteCommandLists`, `Signal`, `Wait` and markers run in call order on a worker of the queue's own (`src/vulkan_backend.h`), at most n batches queued; the caller of the next one waits for room. The replay, the before-submission refreshes and `vkQueueSubmit` then leave the title's thread. A batch that fails is reported as a held one is. `0`: on the caller's thread. | | `LEONIDA_COMPUTE_WARMUP_LIVE_MAX_BYTES` | unset | ``: a compute warm-up of a module over n bytes of SPIR-V is not started while the title submits (a submission in the last second); the pipeline is built at its first use instead (docs/d3d12_vulkan.md, "Pipelines still being built"). Unset or `0`: every warm-up runs, ordered behind a submission's compiles by the large-compile gate. | | `LEONIDA_COMPILE_GATE` | `auto` (adaptive or classic, by calibration) | The compile gate (`SubmitMutex::CompileTurn`, `src/vulkan_device_fault.h`): a queue submission (or a present or device wait) does not enter the driver while a pipeline create is in it, and waits in the runtime instead, since on NVIDIA 630.20 a `vkQueueSubmit` that entered during a long `vkCreateComputePipelines` waited 10 s in the driver and lost the device. Creates pass together; one that arrives while a submission waits queues behind it. Unset or `auto`: the device measures the driver once, before the title has it (`src/compile_gate_calibration.h`, `docs/d3d12_vulkan.md`): a worker thread creates a synthetic compute pipeline that takes about a second to compile while the queue gets empty submissions, each waited for. Submissions back in under 50 ms with the create still in the driver give the adaptive gate; one held until the create leaves, a create too fast to tell, a submission slow for another reason or any failure give the classic gate. The verdict is kept per GPU and driver (vendor, device, driver version, pipeline cache UUID) in `compile_gate_calibration.txt` beside the pipeline cache, so the measurement runs once per driver (a failed or unclear calibration is not kept: the next launch measures again), and is logged once: `[rt] compile-gate: auto: adaptive (calibrated on NVIDIA 621.40 in 0.7 s: 115 submissions came back in <= 0.5 ms beside a 722 ms create; cached in ...)`, or `auto: classic (...)`, or `(cached calibration of ...)`. Only gta6rt's title process calibrates: `--precompile-pipelines`, `--compile-server` and tests keep the classic gate. `classic`: compute creates only, waited for however long they take (`LEONIDA_COMPILE_GATE_WAIT_MS` can bound it), no probes, the default before `auto`. `adaptive`: the adaptive gate whatever the calibration says; on a driver that holds submissions (630.20) its first probe of a kind enters the driver after the probe budget and loses the device if that create stays 10 s more. The adaptive gate's wait is bounded by `LEONIDA_COMPILE_GATE_WAIT_MS`. Each submission that enters the driver next to a create the gate went past (at that limit, or earlier at the probe budget, `LEONIDA_COMPILE_GATE_PROBE_MS`) is a probe; two that come back in under 250 ms, at least 1 s apart, with the create still in the driver turn the gate off for the rest of the run (NVIDIA 621.40: 0-11 ms), and one that stays 2 s or more keeps it on; both are logged once. The verdict is kept per kind of create, compute and graphics (mesh included; graphics creates pass the gate since then, only compute ones did before): on NVIDIA 621.40 submissions came back in 0-12 ms beside compute creates, but one sat 54 s in the driver beside a 56 s mesh create and the device was lost. A kind that is off is still timed, and a submission that stays 2 s beside one of its creates turns it back on. A submission never goes ahead, at the limit or the budget, beside a create of a kind whose verdict is that it holds submissions: it waits for that create up to `LEONIDA_COMPILE_GATE_HELD_WAIT_MS`. On a device loss the log names the creates in the driver (kind, program, size, how long) and each kind's gate. `1`: always gate, graphics creates too, with no limit unless `LEONIDA_COMPILE_GATE_WAIT_MS` sets one, never probe or turn it off, and a compute pipeline build also holds the submit lock for its driver calls (`compute_driver_turn`, `shims/d3d12_vulkan_device.cpp`). `0`: no gate. | @@ -451,7 +448,7 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_COMPILE_THREADS` | half the logical processors, 2-8 | ``: the compile workers of the asynchronous builds (`LEONIDA_ASYNC_PIPELINES=1`), the compute warm-up and the cache checkpoint (`shims/d3d12_pipeline_compile.h`, `CompilePool`). A demanded build goes before warm-ups; large and speculative builds take at most n-1 workers, so one stays free for a small build a submission waits for; one build of a PSO at a time; warm-ups one at a time, and none while a demanded build is queued or running. `1`: one general worker plus the graphics-only one (`LEONIDA_GRAPHICS_COMPILE_WORKER`), the layout before the pool. | | `LEONIDA_COMPILE_HEAVY_MAX` | threads-1 (`1` with `LEONIDA_SERIAL_BIG_COMPILES=1`) | ``: at most n builds of large modules (compute over 128 KiB, graphics of 1 MiB of SPIR-V or more) on the compile workers at once, 1 to threads-1. They also keep within the memory budget of `LEONIDA_BIG_COMPILE_BUDGET_MB`. | | `LEONIDA_GRAPHICS_COMPILE_WORKER` | on | With `LEONIDA_COMPILE_THREADS=1`: a second compile worker that takes graphics pipeline builds only, so a long compute build does not hold them up (`shims/d3d12_pipeline_compile.h`). `0`: the one general worker builds everything. With more workers it is not used. | -| `LEONIDA_CONSOLE_HEAP_GPU` | unset | `1`: the V#s of the console descriptor heaps are rebased by a compute pass at the start of each submission (`src/console_heap_gpu.h`) instead of on the CPU. The CPU still finds the changed slots and registers the T#s; a V# the pass cannot answer is resolved after its submission and its slot queued again. | +| `LEONIDA_CONSOLE_HEAP_GPU` | unset | `1`: the V#s of the console descriptor heaps are rebased by a compute pass at the start of each submission (`src/console_heap_gpu.h`) instead of on the CPU. The CPU still finds the changed slots and registers the T#s; a V# the pass cannot answer is resolved after its submission and its slot queued again. The pass copies T#s as the title wrote them and does not write the bindless index word into their dword 6 (docs/design.md, "Bindless index in the T#"), so with a shader pack whose modules read that word (index.json `"tsharp_index": "dword6"`, every pack translated since) the setting does not apply to resource heaps: they are fixed on the CPU as without it, and the log says so once (`LEONIDA_CONSOLE_HEAP_GPU: the pass does not write the T# index word ...`). An older pack still gets the pass. | | `LEONIDA_CONSOLE_HEAP_ARENA` | unset | With `LEONIDA_CONSOLE_HEAP_GPU=1`, `1` puts a console heap's GPU copy and its guard in the arena (device-local where the device has ReBAR) instead of an import of host memory. No room in the arena: the import. | | `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. | diff --git a/runtime/cmake/translator_deps.cmake b/runtime/cmake/translator_deps.cmake index 0cb1ecdf86..2f0d42ec93 100644 --- a/runtime/cmake/translator_deps.cmake +++ b/runtime/cmake/translator_deps.cmake @@ -10,10 +10,12 @@ set(LEONIDA_TRANSLATOR_DEPS ${_leonida_repo}/runtime/test/shaders/compute_fixture.py ${_leonida_repo}/tools/bary_fallback_gs.py ${_leonida_repo}/tools/cfg_structure.py + ${_leonida_repo}/tools/descriptor_sources.py ${_leonida_repo}/tools/file_mode.py ${_leonida_repo}/tools/fssm_header.py ${_leonida_repo}/tools/fssm_unpack.py ${_leonida_repo}/tools/gfx10_formats.json + ${_leonida_repo}/tools/heap_index_census.py ${_leonida_repo}/tools/lane_masks.py ${_leonida_repo}/tools/mc_command.py ${_leonida_repo}/tools/native_pso_hashes.py diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 472e2c62f0..c0a6b3f238 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -219,22 +219,23 @@ class GraphicsCommandList final allocator_ = allocator; } - const leonida::CommandList& commands() const { return list_; } + const leonida::CommandList& commands() const { return *list_; } + std::shared_ptr commands_shared() const { return list_; } // The descriptor tables this recording binds (console VAs), for the scan before a submission. const std::vector>& tables() const { return tables_; } + // Explicit GPU buffer-write destinations recorded in this list (VA, bytes), noted for write-back at execution. + const std::vector>& write_ranges() const { return write_ranges_; } + // Resources transitioned into shader-resource states in this list, for prepare_sample_table at execution. + const std::vector& sampled_barrier_resources() const { return sampled_barrier_resources_; } + bool has_timestamp_queries() const { return has_timestamp_queries_; } // The pipeline states and root signatures the recording names (it holds a reference to each until Reset), and // the objects a shim handed it with hold_until_reset. const std::vector& pinned() const { return held_; } // rt::d3d12::hold_until_reset: an object the recording uses that its caller does not keep (a shim's own scratch). void hold_for_recording(IUnknown* object) { hold(object); } bool needs_all_sampled_views() const { - if (directly_indexed_) return true; - for (const auto& command : list_.commands()) { - if (std::holds_alternative(command)) return true; - if (tables_.empty() && (std::holds_alternative(command) || - std::holds_alternative(command))) return true; - } - return false; + if (directly_indexed_ || has_console_table_ || has_execute_indirect_) return true; + return tables_.empty() && has_draw_or_dispatch_; } UINT front_stencil_ref() const { return front_stencil_ref_; } UINT back_stencil_ref() const { return back_stencil_ref_; } @@ -252,8 +253,8 @@ class GraphicsCommandList final // reports it. HRESULT STDMETHODCALLTYPE Close() override { constexpr auto method = "ID3D12GraphicsCommandList::Close"; - if (list_.queries_open()) invalid_ = true; - if (!list_.close()) return d3d12_trace::result(method, E_FAIL); + if (list_->queries_open()) invalid_ = true; + if (!list_->close()) return d3d12_trace::result(method, E_FAIL); stop_recording(); return d3d12_trace::result(method, invalid_ ? E_INVALIDARG : S_OK); } @@ -266,12 +267,26 @@ class GraphicsCommandList final // Another list recording into the allocator: E_INVALIDARG, as on the PC runtime (D3D-51). if (command_allocator->recording() && command_allocator->recording() != this) return d3d12_trace::result(method, E_INVALIDARG); - if (!list_.reset()) return d3d12_trace::result(method, E_FAIL); // D3D12 resets only closed lists + if (!list_->closed()) return d3d12_trace::result(method, E_FAIL); // D3D12 resets only closed lists + if (list_.use_count() == 1) { + // Pair with the release refcount decrement when the queue dropped its last shared_ptr. + std::atomic_thread_fence(std::memory_order_acquire); + if (!list_->reset()) return d3d12_trace::result(method, E_FAIL); + } else { + // An async or held submission still holds a read-only snapshot of the old recording: allocate fresh storage. + list_ = std::make_shared(); + } record_into(command_allocator); invalid_ = false; calls_.clear(); tables_.clear(); + write_ranges_.clear(); + sampled_barrier_resources_.clear(); + has_timestamp_queries_ = false; + has_execute_indirect_ = false; + has_draw_or_dispatch_ = false; directly_indexed_ = false; + has_console_table_ = false; release_held(); // what the old recording used: it was replayed at ExecuteCommandLists reset_state(state); // Reset returns every list state to its default if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) set_initial_pipeline(state); // reset_state holds it @@ -289,11 +304,11 @@ class GraphicsCommandList final void STDMETHODCALLTYPE ExecuteBundle(ID3D12GraphicsCommandList* command_list) override { d3d12_trace::record("ID3D12GraphicsCommandList::ExecuteBundle"); - if (list_.closed()) return; + if (list_->closed()) return; if (type_ != D3D12_COMMAND_LIST_TYPE_DIRECT) return check(false); GraphicsCommandList* bundle = from(command_list); if (!bundle || bundle->attached_device() != attached_device() || - bundle->type_ != D3D12_COMMAND_LIST_TYPE_BUNDLE || bundle->invalid_ || !bundle->list_.closed()) + bundle->type_ != D3D12_COMMAND_LIST_TYPE_BUNDLE || bundle->invalid_ || !bundle->list_->closed()) return check(false); // The bundle's state calls and draws play on this list through the members the application would have // called, so a draw sees this list's state plus what the bundle set, and what the bundle set stays here @@ -301,11 +316,19 @@ class GraphicsCommandList final // were recorded in the bundle's own list and are copied between them, in order. std::size_t copied = 0; for (const BundleCall& call : bundle->calls_) { - if (!list_.execute_bundle(bundle->list_, copied, call.commands)) return check(false); + if (!list_->execute_bundle(*bundle->list_, copied, call.commands)) return check(false); copied = call.commands; call.run(*this); } - check(list_.execute_bundle(bundle->list_, copied)); + check(list_->execute_bundle(*bundle->list_, copied)); + write_ranges_.insert(write_ranges_.end(), bundle->write_ranges_.begin(), bundle->write_ranges_.end()); + sampled_barrier_resources_.insert(sampled_barrier_resources_.end(), bundle->sampled_barrier_resources_.begin(), + bundle->sampled_barrier_resources_.end()); + has_timestamp_queries_ |= bundle->has_timestamp_queries_; + has_execute_indirect_ |= bundle->has_execute_indirect_; + has_draw_or_dispatch_ |= bundle->has_draw_or_dispatch_; + directly_indexed_ |= bundle->directly_indexed_; + has_console_table_ |= bundle->has_console_table_; } // Root signatures, pipeline state and root arguments. The arguments are packed into the 32 user-data dwords @@ -321,7 +344,7 @@ class GraphicsCommandList final void STDMETHODCALLTYPE SetPipelineState(ID3D12PipelineState* state) override { d3d12_trace::record("ID3D12GraphicsCommandList::SetPipelineState"); - if (list_.closed()) return; + if (list_->closed()) return; if (defer([=](GraphicsCommandList& l) { l.set_pipeline(state); })) return hold(state); set_pipeline(state); } @@ -336,6 +359,8 @@ class GraphicsCommandList final ID3D12DescriptorHeap* smp = nullptr; D3D12_GPU_VIRTUAL_ADDRESS cbv_base = 0; D3D12_GPU_VIRTUAL_ADDRESS smp_base = 0; + UINT cbv_slots = 0; + UINT smp_slots = 0; IUnknown* const owner = this->attached_device(); for (UINT i = 0; i < num; ++i) { ID3D12DescriptorHeap* raw = heaps[i]; @@ -350,10 +375,12 @@ class GraphicsCommandList final if (cbv) return check(false); cbv = raw; cbv_base = base; + cbv_slots = desc.NumDescriptors; } else if (desc.Type == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) { if (smp) return check(false); smp = raw; smp_base = base; + smp_slots = desc.NumDescriptors; } else { return check(false); } @@ -361,7 +388,7 @@ class GraphicsCommandList final hold(cbv); hold(smp); if (defer([=](GraphicsCommandList& l) { l.verify_bundle_descriptor_heaps(cbv, smp); })) return; - set_descriptor_heaps(cbv, cbv_base, smp, smp_base); + set_descriptor_heaps(cbv, cbv_base, cbv_slots, smp, smp_base, smp_slots); } void STDMETHODCALLTYPE SetComputeRoot32BitConstant(UINT index, UINT value, UINT offset) override { @@ -371,13 +398,13 @@ class GraphicsCommandList final constants(compute_, index, count, data, offset); } void STDMETHODCALLTYPE SetComputeRootConstantBufferView(UINT index, D3D12_GPU_VIRTUAL_ADDRESS va) override { - address(compute_, index, va, rt::rootsig::ParamType::Descriptor); + address(compute_, index, va, rt::rootsig::ParamType::Descriptor, false); } void STDMETHODCALLTYPE SetComputeRootShaderResourceView(UINT index, D3D12_GPU_VIRTUAL_ADDRESS va) override { - address(compute_, index, va, rt::rootsig::ParamType::Descriptor); + address(compute_, index, va, rt::rootsig::ParamType::Descriptor, false); } void STDMETHODCALLTYPE SetComputeRootUnorderedAccessView(UINT index, D3D12_GPU_VIRTUAL_ADDRESS va) override { - address(compute_, index, va, rt::rootsig::ParamType::Descriptor); + address(compute_, index, va, rt::rootsig::ParamType::Descriptor, true); } void STDMETHODCALLTYPE SetComputeRootDescriptorTable(UINT index, D3D12_GPU_DESCRIPTOR_HANDLE table) override { address(compute_, index, table.ptr, rt::rootsig::ParamType::Table); @@ -389,13 +416,13 @@ class GraphicsCommandList final constants(graphics_, index, count, data, offset); } void STDMETHODCALLTYPE SetGraphicsRootConstantBufferView(UINT index, D3D12_GPU_VIRTUAL_ADDRESS va) override { - address(graphics_, index, va, rt::rootsig::ParamType::Descriptor); + address(graphics_, index, va, rt::rootsig::ParamType::Descriptor, false); } void STDMETHODCALLTYPE SetGraphicsRootShaderResourceView(UINT index, D3D12_GPU_VIRTUAL_ADDRESS va) override { - address(graphics_, index, va, rt::rootsig::ParamType::Descriptor); + address(graphics_, index, va, rt::rootsig::ParamType::Descriptor, false); } void STDMETHODCALLTYPE SetGraphicsRootUnorderedAccessView(UINT index, D3D12_GPU_VIRTUAL_ADDRESS va) override { - address(graphics_, index, va, rt::rootsig::ParamType::Descriptor); + address(graphics_, index, va, rt::rootsig::ParamType::Descriptor, true); } void STDMETHODCALLTYPE SetGraphicsRootDescriptorTable(UINT index, D3D12_GPU_DESCRIPTOR_HANDLE table) override { d3d12_trace::record("ID3D12GraphicsCommandList::SetGraphicsRootDescriptorTable"); @@ -411,15 +438,15 @@ class GraphicsCommandList final // ClearState returns every piece of list state to its default, as Reset does (stencil references and predication // included). void STDMETHODCALLTYPE ClearState(ID3D12PipelineState* state) override { - if (list_.closed()) return; + if (list_->closed()) return; if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); - if (!list_.closed()) check(list_.set_predication({0, 0, 0})); + if (!list_->closed()) check(list_->set_predication({0, 0, 0})); reset_state(state); } // Graphics state. Draws record a copy of it (command_list.h, Draw). void STDMETHODCALLTYPE IASetPrimitiveTopology(D3D12_PRIMITIVE_TOPOLOGY topology) override { - if (list_.closed()) return; + if (list_->closed()) return; if (defer([=](GraphicsCommandList& l) { l.topology_ = u(topology); })) return; topology_ = u(topology); } @@ -438,7 +465,7 @@ class GraphicsCommandList final } void STDMETHODCALLTYPE IASetIndexBuffer(const D3D12_INDEX_BUFFER_VIEW* view) override { - if (list_.closed()) return; + if (list_->closed()) return; const std::optional copy = view ? std::optional(*view) : std::nullopt; if (defer([=](GraphicsCommandList& l) { l.set_index_buffer(copy ? &*copy : nullptr); })) return; set_index_buffer(view); @@ -508,7 +535,7 @@ class GraphicsCommandList final } void STDMETHODCALLTYPE OMSetBlendFactor(const FLOAT factor[4]) override { - if (list_.closed()) return; + if (list_->closed()) return; const std::array value = factor ? std::array{factor[0], factor[1], factor[2], factor[3]} : std::array{1, 1, 1, 1}; // null means { 1, 1, 1, 1 } if (defer([=](GraphicsCommandList& l) { l.blend_factor_ = value; })) return; @@ -518,14 +545,14 @@ class GraphicsCommandList final // ID3D12GraphicsCommandList1: the depth-bounds test's range for the draws after it, read by pipelines that enable // the test (DEPTH_STENCIL1/2). D3D12's default is [0, 1]. void STDMETHODCALLTYPE OMSetDepthBounds(FLOAT min, FLOAT max) override { - if (list_.closed()) return; + if (list_->closed()) return; const std::array value{min, max}; if (defer([=](GraphicsCommandList& l) { l.depth_bounds_ = value; })) return; depth_bounds_ = value; } void STDMETHODCALLTYPE OMSetStencilRef(UINT reference) override { - if (list_.closed()) return; + if (list_->closed()) return; if (defer([=](GraphicsCommandList& l) { l.front_stencil_ref_ = l.back_stencil_ref_ = reference; })) return; front_stencil_ref_ = back_stencil_ref_ = reference; } @@ -584,7 +611,8 @@ class GraphicsCommandList final draw.viewports = draw_viewports(); draw.depth_bounds = depth_bounds_; request_draw_pipeline(); - check(list_.draw(std::move(draw))); + if (list_->draw(std::move(draw))) has_draw_or_dispatch_ = true; + else check(false); } void STDMETHODCALLTYPE ResourceBarrier(UINT count, const D3D12_RESOURCE_BARRIER* barriers) override { @@ -604,17 +632,26 @@ class GraphicsCommandList final check(copy_depth_storage(logical, pair, storage, {t.Subresource})); before = D3D12_RESOURCE_STATE_COPY_DEST; } - check(list_.transition({pair.colour && storage ? pair.colour : logical, t.Subresource, - u(before), u(t.StateAfter)}, u(b.Flags))); + const auto target_res = pair.colour && storage ? pair.colour : logical; + if (list_->transition({target_res, t.Subresource, + u(before), u(t.StateAfter)}, u(b.Flags))) { + if ((t.StateAfter & + (D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE | + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE)) && + target_res) + sampled_barrier_resources_.push_back(target_res); + } else { + check(false); + } break; } case D3D12_RESOURCE_BARRIER_TYPE_ALIASING: - check(!b.Flags && list_.aliasing_barrier({resource_id(b.Aliasing.pResourceBefore), + check(!b.Flags && list_->aliasing_barrier({resource_id(b.Aliasing.pResourceBefore), resource_id(b.Aliasing.pResourceAfter)})); break; case D3D12_RESOURCE_BARRIER_TYPE_UAV: { const auto pair = xbox_depth_storage(b.UAV.pResource); - check(!b.Flags && list_.uav_barrier({pair.colour ? pair.colour : resource_id(b.UAV.pResource)})); + check(!b.Flags && list_->uav_barrier({pair.colour ? pair.colour : resource_id(b.UAV.pResource)})); break; } default: @@ -631,7 +668,7 @@ class GraphicsCommandList final switch (group[g].Type) { case D3D12_BARRIER_TYPE_GLOBAL: { const auto& b = group[g].pGlobalBarriers[i]; - if (!list_.barrier(leonida::GlobalBarrier{u(b.SyncBefore), u(b.SyncAfter), u(b.AccessBefore), + if (!list_->barrier(leonida::GlobalBarrier{u(b.SyncBefore), u(b.SyncAfter), u(b.AccessBefore), u(b.AccessAfter)}) && reject()) std::fprintf(stderr, "[rt] d3d12: global barrier sync 0x%x->0x%x access 0x%x->0x%x\n", @@ -640,7 +677,7 @@ class GraphicsCommandList final } case D3D12_BARRIER_TYPE_BUFFER: { const auto& b = group[g].pBufferBarriers[i]; - if (!list_.barrier(leonida::BufferBarrier{u(b.SyncBefore), u(b.SyncAfter), u(b.AccessBefore), + if (!list_->barrier(leonida::BufferBarrier{u(b.SyncBefore), u(b.SyncAfter), u(b.AccessBefore), u(b.AccessAfter), resource_id(b.pResource)}) && reject()) { std::fprintf(stderr, "[rt] d3d12: buffer barrier sync 0x%x->0x%x access 0x%x->0x%x offset " @@ -672,7 +709,10 @@ class GraphicsCommandList final } if (storage) barrier.resource = pair.colour; } - if (!list_.barrier(barrier) && reject()) { + if (list_->barrier(barrier)) { + if ((b.AccessAfter & D3D12_BARRIER_ACCESS_SHADER_RESOURCE) && barrier.resource) + sampled_barrier_resources_.push_back(barrier.resource); + } else if (reject()) { std::fprintf(stderr, "[rt] d3d12: texture barrier sync 0x%x->0x%x access 0x%x->0x%x layout %u->%u " "mips %u+%u layers %u+%u planes %u+%u flags 0x%x\n", @@ -695,7 +735,8 @@ class GraphicsCommandList final UINT64 src_offset, UINT64 bytes) override { d3d12_trace::record("ID3D12GraphicsCommandList::CopyBufferRegion"); if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); - check(list_.copy_buffer({resource_id(dst), dst_offset, resource_id(src), src_offset, bytes})); + if (dst && bytes) note_write_resource(dst, dst_offset, bytes); + check(list_->copy_buffer({resource_id(dst), dst_offset, resource_id(src), src_offset, bytes})); } void STDMETHODCALLTYPE CopyTiles(ID3D12Resource* tiled, const D3D12_TILED_RESOURCE_COORDINATE* start, @@ -720,6 +761,7 @@ class GraphicsCommandList final return check(false); constexpr auto shape = leonida::element_tile_shape(false, 4); const leonida::CopyLocation image{tiled_id, false, 0, 0, 0, 0, 0, 0}; + const UINT64 linear_start = linear_offset; for (const auto& region : regions) { for (std::uint64_t tile = region.first; tile < region.first + region.count; ++tile) { const auto x = std::uint32_t(tile % grid.columns) * shape.width; @@ -732,16 +774,19 @@ class GraphicsCommandList final ? leonida::CopyTexture{footprint, 0, 0, 0, image, true, {x, y, 0, x + width, y + height, 1}} : leonida::CopyTexture{image, x, y, 0, footprint, true, {0, 0, 0, width, height, 1}}; copy.tile_footprint = true; - check(list_.copy_texture(copy)); + check(list_->copy_texture(copy)); linear_offset += leonida::tile_size_in_bytes; } } + if (to_linear && linear_offset > linear_start) + note_write_resource(linear, linear_start, linear_offset - linear_start); return; } const auto& region = regions.front(); const auto tiled_offset = region.first * leonida::tile_size_in_bytes; const auto bytes = region.count * leonida::tile_size_in_bytes; - check(list_.copy_buffer(to_linear + if (bytes) note_write_resource(to_linear ? linear : tiled, to_linear ? linear_offset : tiled_offset, bytes); + check(list_->copy_buffer(to_linear ? leonida::CopyBuffer{linear_id, linear_offset, tiled_id, tiled_offset, bytes, tiled_id} : leonida::CopyBuffer{tiled_id, tiled_offset, linear_id, linear_offset, bytes, tiled_id})); } @@ -753,7 +798,21 @@ class GraphicsCommandList final if (!dst || !src) return check(false); leonida::CopyTexture copy{location(*dst), x, y, z, location(*src), box != nullptr, {}}; if (box) copy.box = {box->left, box->top, box->front, box->right, box->bottom, box->back}; - if (!list_.copy_texture(copy) && reject()) { + if (dst->Type == D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT && dst->pResource) { + const auto desc = dst->pResource->GetDesc(); + const auto& fp = dst->PlacedFootprint; + if (desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && desc.Width > fp.Offset) { + const UINT64 max_bytes = desc.Width - fp.Offset; + const UINT64 pitch = fp.Footprint.RowPitch; + const UINT64 rows = std::max(1, fp.Footprint.Height); + const UINT64 depth = std::max(1, fp.Footprint.Depth); + UINT64 bytes = max_bytes; + if (pitch && rows <= max_bytes / pitch && depth <= max_bytes / (pitch * rows)) + bytes = pitch * rows * depth; + note_write_resource(dst->pResource, fp.Offset, bytes); + } + } + if (!list_->copy_texture(copy) && reject()) { for (const auto* l : {dst, src}) { const char* side = l == dst ? "dst" : "src"; if (l->Type != D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT) { @@ -784,7 +843,12 @@ class GraphicsCommandList final if (FAILED(dst->GetHeapProperties(&properties, nullptr)) || properties.Type != D3D12_HEAP_TYPE_DEFAULT) return check(false); } - check(list_.copy_resource({resource_id(dst), resource_id(src)})); + if (dst && dst != src) { + const auto desc = dst->GetDesc(); + if (desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && desc.Width) + note_write_va(dst->GetGPUVirtualAddress(), desc.Width); + } + check(list_->copy_resource({resource_id(dst), resource_id(src)})); } // The format picks the member of a typeless family to resolve as; the textures' own format is used. @@ -802,7 +866,7 @@ class GraphicsCommandList final note_once("ResolveSubresource refused: integer colour formats cannot be resolved"); return check(false); } - check(list_.resolve_subresource({resource_id(dst), dst_subresource, resource_id(src), src_subresource})); + check(list_->resolve_subresource({resource_id(dst), dst_subresource, resource_id(src), src_subresource})); } void STDMETHODCALLTYPE ResolveSubresourceRegion(ID3D12Resource* dst, UINT dst_subresource, UINT x, UINT y, @@ -823,7 +887,7 @@ class GraphicsCommandList final : leonida::d3d12_resolve_mode::average; } if (rect) region.src_rect = leonida::Rect{rect->left, rect->top, rect->right, rect->bottom}; - check(list_.resolve_subresource({resource_id(dst), dst_subresource, resource_id(src), src_subresource, region})); + check(list_->resolve_subresource({resource_id(dst), dst_subresource, resource_id(src), src_subresource, region})); } // A null buffer turns predication off (docs/d3d12_vulkan.md section 4.7). Bundles and copy lists may not set it. @@ -834,7 +898,7 @@ class GraphicsCommandList final if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE || type_ == D3D12_COMMAND_LIST_TYPE_COPY) return check(false); if (!buffer) { if (offset != 0 || op != D3D12_PREDICATION_OP_EQUAL_ZERO) return check(false); - return check(list_.set_predication({0, 0, 0})); + return check(list_->set_predication({0, 0, 0})); } const auto desc = buffer->GetDesc(); if (desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) return check(false); @@ -844,7 +908,7 @@ class GraphicsCommandList final D3D12_HEAP_PROPERTIES heap{}; if (SUCCEEDED(buffer->GetHeapProperties(&heap, nullptr)) && heap.Type == D3D12_HEAP_TYPE_READBACK) return check(false); - check(list_.set_predication({resource_id(buffer), offset, u(op)})); + check(list_->set_predication({resource_id(buffer), offset, u(op)})); } void STDMETHODCALLTYPE ClearRenderTargetView(D3D12_CPU_DESCRIPTOR_HANDLE view, const FLOAT color[4], UINT count, @@ -863,7 +927,7 @@ class GraphicsCommandList final t.first_layer, t.layer_count, color[0], color[1], color[2], color[3], count); } } - check(list_.clear_render_target(*reinterpret_cast(view.ptr), + check(list_->clear_render_target(*reinterpret_cast(view.ptr), {color[0], color[1], color[2], color[3]}, to_rects(count, rects))); } @@ -873,16 +937,16 @@ class GraphicsCommandList final d3d12_trace::record("ID3D12GraphicsCommandList::ClearDepthStencilView"); if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); if (!view.ptr) return check(false); - check(list_.clear_depth_stencil(*reinterpret_cast(view.ptr), u(flags), depth, + check(list_->clear_depth_stencil(*reinterpret_cast(view.ptr), u(flags), depth, stencil, to_rects(count, rects))); } // A null region discards the whole resource. Not allowed in a bundle. void STDMETHODCALLTYPE DiscardResource(ID3D12Resource* resource, const D3D12_DISCARD_REGION* region) override { if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); - if (!region) return check(list_.discard({resource_id(resource), 0, 0, false, true})); + if (!region) return check(list_->discard({resource_id(resource), 0, 0, false, true})); if (region->NumRects && !region->pRects) return check(false); - check(list_.discard({resource_id(resource), region->FirstSubresource, region->NumSubresources, + check(list_->discard({resource_id(resource), region->FirstSubresource, region->NumSubresources, region->NumRects != 0})); } @@ -891,8 +955,10 @@ class GraphicsCommandList final void STDMETHODCALLTYPE WriteBufferImmediate(UINT count, const D3D12_WRITEBUFFERIMMEDIATE_PARAMETER* params, const D3D12_WRITEBUFFERIMMEDIATE_MODE* modes) override { if (count && !params) return check(false); - for (UINT i = 0; i < count; ++i) - check(list_.write_immediate({params[i].Dest, params[i].Value, modes ? u(modes[i]) : 0})); + for (UINT i = 0; i < count; ++i) { + note_write_va(params[i].Dest, sizeof(std::uint32_t)); + check(list_->write_immediate({params[i].Dest, params[i].Value, modes ? u(modes[i]) : 0})); + } } // GCL1. Not allowed in a bundle, as no copy is. @@ -938,24 +1004,36 @@ class GraphicsCommandList final // at ExecuteCommandLists, when the heap and the buffer are known. void STDMETHODCALLTYPE BeginQuery(ID3D12QueryHeap* heap, D3D12_QUERY_TYPE type, UINT index) override { if (!query_allowed(type)) return check(false); - check(list_.begin_query({query_heap_id(heap), u(type), index})); + if (type == D3D12_QUERY_TYPE_TIMESTAMP) has_timestamp_queries_ = true; + check(list_->begin_query({query_heap_id(heap), u(type), index})); } void STDMETHODCALLTYPE EndQuery(ID3D12QueryHeap* heap, D3D12_QUERY_TYPE type, UINT index) override { if (!query_allowed(type)) return check(false); - check(list_.end_query({query_heap_id(heap), u(type), index})); + if (type == D3D12_QUERY_TYPE_TIMESTAMP) has_timestamp_queries_ = true; + check(list_->end_query({query_heap_id(heap), u(type), index})); } void STDMETHODCALLTYPE ResolveQueryData(ID3D12QueryHeap* heap, D3D12_QUERY_TYPE type, UINT first, UINT count, ID3D12Resource* dst, UINT64 offset) override { if (!query_allowed(type)) return check(false); - check(list_.resolve_queries({query_heap_id(heap), u(type), first, count, resource_id(dst), offset})); + if (type == D3D12_QUERY_TYPE_TIMESTAMP && count) has_timestamp_queries_ = true; + if (dst && count) { + const std::uint64_t stride = + type == D3D12_QUERY_TYPE_PIPELINE_STATISTICS + ? sizeof(D3D12_QUERY_DATA_PIPELINE_STATISTICS) + : (type >= D3D12_QUERY_TYPE_SO_STATISTICS_STREAM0 && type <= D3D12_QUERY_TYPE_SO_STATISTICS_STREAM3) + ? sizeof(D3D12_QUERY_DATA_SO_STATISTICS) + : sizeof(std::uint64_t); + note_write_resource(dst, offset, std::uint64_t(count) * stride); + } + check(list_->resolve_queries({query_heap_id(heap), u(type), first, count, resource_id(dst), offset})); } // GCL8. Each draw applies the two faces with vkCmdSetStencilReference(VK_STENCIL_FACE_FRONT_BIT / BACK_BIT). void STDMETHODCALLTYPE OMSetFrontAndBackStencilRef(UINT front, UINT back) override { d3d12_trace::record("ID3D12GraphicsCommandList8::OMSetFrontAndBackStencilRef"); - if (list_.closed()) return check(false); + if (list_->closed()) return check(false); if (defer([=](GraphicsCommandList& l) { l.front_stencil_ref_ = front; l.back_stencil_ref_ = back; @@ -969,15 +1047,15 @@ class GraphicsCommandList final // names the call only, never the label. void STDMETHODCALLTYPE SetMarker(UINT metadata, const void* data, UINT size) override { d3d12_trace::record("ID3D12GraphicsCommandList::SetMarker"); - check(list_.marker(leonida::DebugMarker::Kind::set, event_label(metadata, data, size))); + check(list_->marker(leonida::DebugMarker::Kind::set, event_label(metadata, data, size))); } void STDMETHODCALLTYPE BeginEvent(UINT metadata, const void* data, UINT size) override { d3d12_trace::record("ID3D12GraphicsCommandList::BeginEvent"); - check(list_.marker(leonida::DebugMarker::Kind::begin, event_label(metadata, data, size))); + check(list_->marker(leonida::DebugMarker::Kind::begin, event_label(metadata, data, size))); } void STDMETHODCALLTYPE EndEvent() override { d3d12_trace::record("ID3D12GraphicsCommandList::EndEvent"); - check(list_.marker(leonida::DebugMarker::Kind::end)); + check(list_->marker(leonida::DebugMarker::Kind::end)); } void STDMETHODCALLTYPE ExecuteIndirect(ID3D12CommandSignature* signature, UINT max_command_count, @@ -1040,7 +1118,7 @@ class GraphicsCommandList final // Compound draw emission is not yet supported. Reset the written bindings even if no // records execute. Bundle nesting and prefixes were already rejected above for bundles. leonida::indirect_stats::skip(leonida::indirect_stats::Event::record_skip, leonida::indirect_stats::compound); - if (!list_.closed()) reset_indirect_graphics_bindings(sig->graphics_writes()); + if (!list_->closed()) reset_indirect_graphics_bindings(sig->graphics_writes()); return; } const leonida::IndirectDrawArgs args{resource_id(argument_buffer), argument_buffer_offset, stride, @@ -1133,7 +1211,7 @@ class GraphicsCommandList final // build out, with its postbuild values: the list stays valid, nothing is written through heap_base + a title // address, and the destination keeps what it had. if (!resolve_acceleration_structure_build(attached_device(), cmd)) return; - const bool recorded = list_.build_acceleration_structure(std::move(cmd)); + const bool recorded = list_->build_acceleration_structure(std::move(cmd)); check(recorded); if (!recorded) return; // The postbuild values of the structure just built, after it (D3D12 orders them after the build). @@ -1144,7 +1222,7 @@ class GraphicsCommandList final info.sources = {built}; if (!info.dest_va || info.dest_va % 8) return check(false); if (!resolve_acceleration_structure_postbuild(attached_device(), info)) continue; - const bool ok = list_.acceleration_structure_postbuild(std::move(info)); + const bool ok = list_->acceleration_structure_postbuild(std::move(info)); check(ok); if (!ok) return; } @@ -1163,7 +1241,7 @@ class GraphicsCommandList final for (const auto va : info.sources) if (!va || va % 256) return check(false); if (!resolve_acceleration_structure_postbuild(attached_device(), info)) return; // logged; left out - check(list_.acceleration_structure_postbuild(std::move(info))); + check(list_->acceleration_structure_postbuild(std::move(info))); } void STDMETHODCALLTYPE CopyRaytracingAccelerationStructure(D3D12_GPU_VIRTUAL_ADDRESS dest, @@ -1174,10 +1252,10 @@ class GraphicsCommandList final leonida::CopyAccelerationStructure copy{dest, source, static_cast(mode)}; if (!copy.dst_va || !copy.src_va || copy.dst_va % 256 || copy.src_va % 256) return check(false); if (!resolve_acceleration_structure_copy(attached_device(), copy)) return; // logged; left out - check(list_.copy_acceleration_structure(copy)); + check(list_->copy_acceleration_structure(copy)); } - bool xbox_label(const leonida::label::Write& op) { return list_.write_gpu_label(op); } + bool xbox_label(const leonida::label::Write& op) { return list_->write_gpu_label(op); } static GraphicsCommandList* from(IUnknown* object) { return Child::from(object); } private: @@ -1195,18 +1273,18 @@ class GraphicsCommandList final const auto from = to_storage ? depth : pair.colour, to = to_storage ? pair.colour : depth; // The two images can be in GENERAL for bindless use. Order prior depth writes, unordered writes and // readers of the destination even when Vulkan does not need a layout transition. - if (!list_.barrier(leonida::GlobalBarrier{sync::all, sync::copy, + if (!list_->barrier(leonida::GlobalBarrier{sync::all, sync::copy, access::depth_stencil_write | access::depth_stencil_read | access::unordered_access | access::shader_resource | access::copy_source | access::copy_dest, access::copy_source | access::copy_dest})) return false; if (!r.mip_count && r.index_or_first_mip == D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES) - return list_.copy_resource({to, from}); + return list_->copy_resource({to, from}); const auto one = [&](UINT subresource) { leonida::CopyTexture copy{}; copy.src.resource = from; copy.dst.resource = to; copy.src.subresource = copy.dst.subresource = subresource; - return list_.copy_texture(copy); + return list_->copy_texture(copy); }; if (!r.mip_count) return r.index_or_first_mip < pair.mips * pair.layers && one(r.index_or_first_mip); if (r.first_plane || r.plane_count != 1 || !r.layer_count || @@ -1362,7 +1440,8 @@ class GraphicsCommandList final } copy.dependencies.push_back({resource_id(dep), r.Subresource, begin, end}); } - check(list_.atomic_copy(copy)); + note_write_va(dst->GetGPUVirtualAddress() + dst_offset, bytes); + check(list_->atomic_copy(copy)); } void clear_unordered_access(D3D12_CPU_DESCRIPTOR_HANDLE view, ID3D12Resource* resource, bool is_float, @@ -1371,7 +1450,8 @@ class GraphicsCommandList final return check(false); leonida::UavView target{}; if (!view.ptr || !resource || !unordered_access_view(view, resource, target)) return check(false); - check(list_.clear_unordered_access(target, is_float, values, to_rects(count, rects))); + if (target.buffer && target.size) note_write_va(resource->GetGPUVirtualAddress() + target.offset, target.size); + check(list_->clear_unordered_access(target, is_float, values, to_rects(count, rects))); } // The Vulkan format a descriptor's FORMAT and DST_SEL name: a UAV has no component mapping of its own, so its @@ -1458,7 +1538,7 @@ class GraphicsCommandList final // signature that is already bound changes nothing: "existing root signature bindings do not become stale" // (D3D12, "Using a Root Signature"), and engines rebind routinely. void bind_root(RootState& state, ID3D12RootSignature* signature) { - if (list_.closed()) return; + if (list_->closed()) return; const RootArgumentLayout* layout = root_signature_layout(signature); if (signature && !layout) { stub("ID3D12GraphicsCommandList::Set*RootSignature(foreign root signature)"); @@ -1507,7 +1587,7 @@ class GraphicsCommandList final } void constants(RootState& state, UINT index, UINT count, const void* data, UINT offset) { - if (list_.closed()) return; + if (list_->closed()) return; if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) { // The layout is the executing list's, so the range is checked when it runs; no signature takes more // than D3D12_MAX_ROOT_COST dwords, which bounds what is copied from the caller's memory. @@ -1540,10 +1620,20 @@ class GraphicsCommandList final "array is not written yet)\n"); } - void address(RootState& state, UINT index, std::uint64_t va, rt::rootsig::ParamType type) { - if (list_.closed()) return; + static bool table_scan_diag() { + static const bool on = [] { + const char* desc = std::getenv("LEONIDA_DESC_PROBE"); + const char* comp = std::getenv("LEONIDA_COMPUTE_INPUTS"); + return (desc && *desc == '1') || (comp && *comp) || + leonida::fsdraw::enabled() || leonida::fsdraw::poke_enabled(); + }(); + return on; + } + + void address(RootState& state, UINT index, std::uint64_t va, rt::rootsig::ParamType type, bool writable = true) { + if (list_->closed()) return; if (defer([=, compute = &state == &compute_](GraphicsCommandList& l) { - l.address(compute ? l.compute_ : l.graphics_, index, va, type); + l.address(compute ? l.compute_ : l.graphics_, index, va, type, writable); })) return; const RootArgumentLayout::Parameter* p = parameter(state, index, type); @@ -1552,18 +1642,35 @@ class GraphicsCommandList final // copy of it, so the shader's heap_base + VA reaches it (src/title_va_alias.h). A descriptor table is in one // of the layer's heaps: kept, and its buffer V#s are rewritten the same way before each submission. // A table in a console descriptor heap is read from the heap's arena copy (console_descriptor_table_va). + bool console_heap_table = false; if (type == rt::rootsig::ParamType::Descriptor) { const std::uint64_t raw = va; - va = leonida::title_va_aliases().resolve(va, kRootViewBytes, leonida::TitleVaAliases::root_view); + va = leonida::title_va_aliases().resolve(va, kRootViewBytes, leonida::TitleVaAliases::root_view, writable); // No copy for the title's memory: the root view is 0, so the shader reads the arena's zero page instead // of storing at heap_base + a raw title address. if (!va && raw) leonida::note_unbacked_view("root view", raw, kRootViewBytes); } else { + const std::uint64_t raw = va; if (descriptor_ring_diagnostics()) note_table_slots(va, p->table_descriptors); - va = console_descriptor_table_va(va); + if (cbv_srv_uav_shader_va_ != cbv_srv_uav_base_ && cbv_srv_uav_num_descriptors_ && + va >= cbv_srv_uav_base_ && + va - cbv_srv_uav_base_ < std::uint64_t(cbv_srv_uav_num_descriptors_) * descriptor_size) { + va = cbv_srv_uav_shader_va_ + (va - cbv_srv_uav_base_); + } else if (sampler_shader_va_ != sampler_base_ && sampler_num_descriptors_ && va >= sampler_base_ && + va - sampler_base_ < std::uint64_t(sampler_num_descriptors_) * descriptor_size) { + va = sampler_shader_va_ + (va - sampler_base_); + } else { + va = console_descriptor_table_va(va); + } + console_heap_table = (va != raw); + } + if (type != rt::rootsig::ParamType::Descriptor && va && p->table_descriptors) { + // Console descriptor heaps (including in-place TitleMirror heaps) are filtered and refreshed in + // before_execute_(), not via visible_heaps / scan_title_table(). Skip recording per-draw table offsets + // unless a table-scan diagnostic is active, while keeping needs_all_sampled_views() accurate. + if (console_heap_table && !table_scan_diag()) has_console_table_ = true; + else remember_table(va, p->table_descriptors); } - if (type != rt::rootsig::ParamType::Descriptor && va && p->table_descriptors) - remember_table(va, p->table_descriptors); const std::uint32_t first = first_dword(state, *p); if (first == rt::rootsig::kNoSgpr) return spilled(); write(state, first, std::uint32_t(va)); @@ -1575,7 +1682,7 @@ class GraphicsCommandList final D3D12_COMMAND_LIST_TYPE type_; CommandAllocator* allocator_ = nullptr; // referenced while the list is open - leonida::CommandList list_; + std::shared_ptr list_ = std::make_shared(); bool invalid_ = false; UINT front_stencil_ref_ = 0; UINT back_stencil_ref_ = 0; @@ -1589,15 +1696,37 @@ class GraphicsCommandList final ID3D12DescriptorHeap* sampler_heap_ = nullptr; D3D12_GPU_VIRTUAL_ADDRESS cbv_srv_uav_base_ = 0; D3D12_GPU_VIRTUAL_ADDRESS sampler_base_ = 0; + D3D12_GPU_VIRTUAL_ADDRESS cbv_srv_uav_shader_va_ = 0; + D3D12_GPU_VIRTUAL_ADDRESS sampler_shader_va_ = 0; + UINT cbv_srv_uav_num_descriptors_ = 0; + UINT sampler_num_descriptors_ = 0; + bool direct_cbv_table_recorded_ = false; UINT heap_slots_[2]{}; // NumDescriptors of the bound view and sampler heaps std::uint64_t table_high_[3]{}; // this list's descriptor-ring marks: view, sampler, console heap (note_table_slots) std::uint64_t console_high_base_ = 0; // the console heap table_high_[2] is for std::uint32_t topology_ = 0; // D3D_PRIMITIVE_TOPOLOGY_UNDEFINED std::array vertex_buffers_{}; leonida::IndexBufferView index_{}; + void note_write_va(std::uint64_t va, std::uint64_t bytes) { + if (va && bytes) write_ranges_.emplace_back(va, bytes); + } + void note_write_resource(ID3D12Resource* dst, std::uint64_t offset, std::uint64_t bytes) { + if (!dst || !bytes) return; + const auto desc = dst->GetDesc(); + if (desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || offset >= desc.Width) return; + const std::uint64_t base = dst->GetGPUVirtualAddress(); + if (base) write_ranges_.emplace_back(base + offset, std::min(bytes, desc.Width - offset)); + } + // SetGraphicsRootDescriptorTable / SetComputeRootDescriptorTable: VA, CBV/SRV/UAV slots the signature declares std::vector> tables_; + std::vector> write_ranges_; + std::vector sampled_barrier_resources_; + bool has_timestamp_queries_ = false; + bool has_execute_indirect_ = false; + bool has_draw_or_dispatch_ = false; bool directly_indexed_ = false; + bool has_console_table_ = false; // The span a root view may read: D3D12's largest constant buffer (4096 x 16 bytes). static constexpr std::uint64_t kRootViewBytes = 65536; leonida::Viewport viewport_{}; @@ -1641,16 +1770,18 @@ class GraphicsCommandList final // the list invalid. bool defer(std::function run, bool command = false) { if (type_ != D3D12_COMMAND_LIST_TYPE_BUNDLE) return false; - if (list_.closed()) { + if (list_->closed()) { if (command) check(false); return true; } - calls_.push_back({list_.commands().size(), std::move(run)}); + calls_.push_back({list_->commands().size(), std::move(run)}); return true; } void hold(IUnknown* object) { - if (!object || std::find(held_.begin(), held_.end(), object) != held_.end()) return; + if (!object) return; + if (!held_.empty() && held_.back() == object) return; + if (std::find(held_.begin(), held_.end(), object) != held_.end()) return; object->AddRef(); held_.push_back(object); } @@ -1676,19 +1807,22 @@ class GraphicsCommandList final stub("ID3D12GraphicsCommandList::SetPipelineState(pipeline from another device)"); } - void set_descriptor_heaps(ID3D12DescriptorHeap* cbv, D3D12_GPU_VIRTUAL_ADDRESS cbv_base, - ID3D12DescriptorHeap* smp, D3D12_GPU_VIRTUAL_ADDRESS smp_base) { + void set_descriptor_heaps(ID3D12DescriptorHeap* cbv, D3D12_GPU_VIRTUAL_ADDRESS cbv_base, UINT cbv_slots, + ID3D12DescriptorHeap* smp, D3D12_GPU_VIRTUAL_ADDRESS smp_base, UINT smp_slots) { cbv_srv_uav_heap_ = cbv; cbv_srv_uav_base_ = cbv_base; + cbv_srv_uav_num_descriptors_ = cbv_slots; + cbv_srv_uav_shader_va_ = cbv_base ? console_descriptor_table_va(cbv_base) : 0; + direct_cbv_table_recorded_ = false; sampler_heap_ = smp; sampler_base_ = smp_base; + sampler_num_descriptors_ = smp_slots; + sampler_shader_va_ = smp_base ? console_descriptor_table_va(smp_base) : 0; if (!descriptor_ring_diagnostics()) return; - for (int h = 0; h < 2; ++h) { - D3D12_DESCRIPTOR_HEAP_DESC desc{}; - D3D12_GPU_VIRTUAL_ADDRESS base = 0; - heap_slots_[h] = descriptor_heap_info(h ? smp : cbv, desc, base) ? desc.NumDescriptors : 0; - table_high_[h] = 0; - } + heap_slots_[0] = cbv_slots; + heap_slots_[1] = smp_slots; + table_high_[0] = 0; + table_high_[1] = 0; } // note_table_slots runs on every descriptor-table bind of the title's recording threads, and takes a global lock @@ -1784,8 +1918,12 @@ class GraphicsCommandList final if (!cbv_srv_uav_heap_) once(0, "draw/dispatch uses CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED with no CBV/SRV/UAV heap bound"); else { - const auto shader_va = console_descriptor_table_va(cbv_srv_uav_base_); - remember_table(shader_va, cbv_srv_uav_heap_->GetDesc().NumDescriptors); + if (!direct_cbv_table_recorded_) { + direct_cbv_table_recorded_ = true; + const bool console_heap = cbv_srv_uav_shader_va_ != cbv_srv_uav_base_; + if (console_heap && !table_scan_diag()) has_console_table_ = true; + else remember_table(cbv_srv_uav_shader_va_, cbv_srv_uav_num_descriptors_); + } once(1, "CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED heap base tracked on list"); } } @@ -1805,6 +1943,11 @@ class GraphicsCommandList final sampler_heap_ = nullptr; cbv_srv_uav_base_ = 0; sampler_base_ = 0; + cbv_srv_uav_shader_va_ = 0; + sampler_shader_va_ = 0; + cbv_srv_uav_num_descriptors_ = 0; + sampler_num_descriptors_ = 0; + direct_cbv_table_recorded_ = false; topology_ = 0; vertex_buffers_ = {}; index_ = {}; @@ -1891,12 +2034,10 @@ class GraphicsCommandList final std::array& data) const { const auto flags = state.layout->flags; if ((flags & D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED) && slot < data.size()) { - const D3D12_GPU_VIRTUAL_ADDRESS va = console_descriptor_table_va(cbv_srv_uav_base_); - data[slot++] = static_cast(va); + data[slot++] = static_cast(cbv_srv_uav_shader_va_); } if ((flags & D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED) && slot < data.size()) { - const D3D12_GPU_VIRTUAL_ADDRESS va = console_descriptor_table_va(sampler_base_); - data[slot] = static_cast(va); + data[slot] = static_cast(sampler_shader_va_); } } @@ -2006,7 +2147,8 @@ class GraphicsCommandList final std::fputc('\n', stderr); } } - check(list_.dispatch({compute_pipeline_, compute_user_data(), x, y, z})); + if (list_->dispatch({compute_pipeline_, compute_user_data(), x, y, z})) has_draw_or_dispatch_ = true; + else check(false); } // The views block a draw records. Rebuilt only when the render targets or the bound vertex buffers change. @@ -2073,8 +2215,11 @@ class GraphicsCommandList final draw.mesh = true; draw.depth_bounds = depth_bounds_; request_draw_pipeline(); - const bool recorded = list_.draw_indirect(std::move(draw), args); - if (recorded) stats::note(stats::Event::recorded); + const bool recorded = list_->draw_indirect(std::move(draw), args); + if (recorded) { + has_draw_or_dispatch_ = true; + stats::note(stats::Event::recorded); + } return check(recorded); } if (kind == leonida::IndirectKind::draw || kind == leonida::IndirectKind::draw_indexed) { @@ -2085,7 +2230,7 @@ class GraphicsCommandList final // Compound signatures already applied their root/IA postconditions in ExecuteIndirect. if (indirect_draws_disabled()) { leonida::indirect_stats::skip(leonida::indirect_stats::Event::record_skip, leonida::indirect_stats::disabled); - return check(!list_.closed()); + return check(!list_->closed()); } const bool indexed = kind == leonida::IndirectKind::draw_indexed; // Only single-operation signatures inherit all graphics state. A padded stride alone cannot @@ -2118,7 +2263,8 @@ class GraphicsCommandList final cmd.pipeline = compute_pipeline_; cmd.user_data = compute_user_data(); } - check(list_.execute_indirect(cmd)); + if (list_->execute_indirect(cmd)) has_execute_indirect_ = true; + else check(false); } // A draw needs a graphics pipeline, a graphics root signature and a topology. @@ -2227,8 +2373,11 @@ class GraphicsCommandList final draw.viewports = draw_viewports(); draw.depth_bounds = depth_bounds_; request_draw_pipeline(); - const bool recorded = indirect ? list_.draw_indirect(std::move(draw), *indirect) : list_.draw(std::move(draw)); - if (indirect && recorded) leonida::indirect_stats::note(leonida::indirect_stats::Event::recorded); + const bool recorded = indirect ? list_->draw_indirect(std::move(draw), *indirect) : list_->draw(std::move(draw)); + if (recorded) { + has_draw_or_dispatch_ = true; + if (indirect) leonida::indirect_stats::note(leonida::indirect_stats::Event::recorded); + } check(recorded); } }; @@ -2249,6 +2398,7 @@ class Fence final bool ok() const { return fence_.semaphore() != VK_NULL_HANDLE; } VkSemaphore semaphore() const { return fence_.semaphore(); } const leonida::VulkanContext* context() const { return &context_; } + leonida::VulkanContext* mutable_context() { return &context_; } // A Vulkan timeline only increases; D3D12 allows setting a fence lower. Such a signal is reported and dropped. // A queue's claim also records the value as one the GPU will signal, which a later CPU signal must not overtake. @@ -2260,6 +2410,8 @@ class Fence final UINT64 STDMETHODCALLTYPE GetCompletedValue() override { return context_.is_device_lost() ? UINT64_MAX : fence_.completed(); } + // A Signal of at least `value` went to the GPU (or the CPU set it), not held (fence_signal_submitted). + bool signal_submitted(UINT64 value) { return !context_.holds().pending(fence_.semaphore(), value); } D3D12_FENCE_FLAGS STDMETHODCALLTYPE GetCreationFlags() override { return flags_; } // vkSignalSemaphore must stay below every signal still pending on the GPU @@ -2268,16 +2420,24 @@ class Fence final // value, in the order the signals were made. Until then GetCompletedValue reads the GPU's progress, where D3D12 // would already read `value`. HRESULT STDMETHODCALLTYPE Signal(UINT64 value) override { + const leonida::submit_phases::TitleCall call(leonida::submit_phases::part_fences); // "submit frame" line + return signal_impl(value, true); + } + + HRESULT signal_gpu_relay(UINT64 value) { return signal_impl(value, false); } + + HRESULT signal_impl(UINT64 value, bool bump_vis_seq) { std::lock_guard lock(claim_mutex_); if (!claim_locked(value, false)) return S_OK; const UINT64 queued = queued_; - if (held_->load() == 0 && fence_.completed() >= queued) return fence_.signal(value) ? S_OK : E_FAIL; + if (held_->load() == 0 && fence_.completed() >= queued) + return (bump_vis_seq ? fence_.signal(value) : fence_.signal_gpu_relay(value)) ? S_OK : E_FAIL; held_->fetch_add(1); // The callback must not touch the fence, which may be released first. Released (cancel) or device lost, // the queue value may not be reached, and signalling then would break the same rule: the signal is dropped. leonida::VulkanContext* context = &context_; const VkSemaphore semaphore = fence_.semaphore(); - context_.enqueue_fence_callback(semaphore, queued, [context, semaphore, queued, value, held = held_] { + context_.enqueue_fence_callback(semaphore, queued, [context, semaphore, queued, value, bump_vis_seq, held = held_] { std::uint64_t now = 0; bool signaled = false; if (context->observe_result(context->vk.vkGetSemaphoreCounterValue(context->device(), semaphore, &now), @@ -2291,7 +2451,8 @@ class Fence final } held->fetch_sub(1); if (signaled) { - context->holds().signaled(semaphore, value); + const std::uint64_t vis_seq = bump_vis_seq ? context->next_visibility_seq() : 0; + context->holds().signaled(semaphore, value, vis_seq); context->holds().pump_ready(); } }); @@ -2357,17 +2518,25 @@ class CommandQueue final // lists name, which the application may release and Reset away as soon as ExecuteCommandLists returns. Resources // are not held (a D3D12 application keeps them until the fence it signals; the docs, section 4.4, list this), // except a shim's own the recording uses (hold_until_reset), which are pinned with them. + struct PinnedObjects { + std::vector objects; + ~PinnedObjects() { + for (IUnknown* object : objects) object->Release(); + } + }; + static std::shared_ptr pin_lists(const std::vector& lists) { - auto objects = std::shared_ptr>(new std::vector, [](auto* held) { - for (IUnknown* object : *held) object->Release(); - delete held; - }); + std::size_t total = 0; + for (const GraphicsCommandList* list : lists) total += list->pinned().size(); + if (!total) return {}; + auto pinned = std::make_shared(); + pinned->objects.reserve(total); for (const GraphicsCommandList* list : lists) for (IUnknown* object : list->pinned()) { object->AddRef(); - objects->push_back(object); + pinned->objects.push_back(object); } - return objects; + return pinned; } // A D3D12 queue holds the fences it waits on and signals until the work has been submitted. @@ -2421,15 +2590,29 @@ class CommandQueue final void STDMETHODCALLTYPE ExecuteCommandLists(UINT count, ID3D12CommandList* const* lists) override { constexpr auto method = "ID3D12CommandQueue::ExecuteCommandLists"; - std::lock_guard lock(mutex_); + const leonida::submit_phases::TitleCall call(leonida::submit_phases::part_lists); // "submit frame" line + std::unique_lock lock(mutex_, std::defer_lock); + leonida::submit_phases::lock_timed(lock); if (count > 0 && !lists) { note_once("ExecuteCommandLists: null command list array with non-zero count"); last_result_ = leonida::ReplayResult::unsupported; d3d12_trace::record(method, "failed"); return; } - std::vector recorded; - std::vector graphics; + recorded_scratch_.clear(); + graphics_scratch_.clear(); + struct ScratchRelease { + std::vector>& recorded; + std::vector& graphics; + std::vector>& tables; + ~ScratchRelease() { + recorded.clear(); + graphics.clear(); + tables.clear(); + } + } scratch_guard{recorded_scratch_, graphics_scratch_, tables_scratch_}; + recorded_scratch_.reserve(count); + graphics_scratch_.reserve(count); for (UINT i = 0; i < count; ++i) { const GraphicsCommandList* list = GraphicsCommandList::from(lists[i]); if (!list || list->type() == D3D12_COMMAND_LIST_TYPE_BUNDLE) { @@ -2468,8 +2651,8 @@ class CommandQueue final d3d12_trace::record(method, "failed"); return; } - recorded.push_back(&list->commands()); - graphics.push_back(list); + recorded_scratch_.push_back(list->commands_shared()); + graphics_scratch_.push_back(list); } if (!context_.publish_cpu_textures()) { last_result_=leonida::ReplayResult::unresolved_resource; @@ -2479,13 +2662,40 @@ class CommandQueue final // Buffer V#s the title wrote into a bound table itself may name its own memory: rewritten to a GPU copy's // console VA before the copies are refreshed for this submission (src/title_va_alias.h). { - std::map tables; // each table once, with the most slots it was bound with - for (const GraphicsCommandList* list : graphics) - for (const auto& [table, descriptors] : list->tables()) - tables[table] = std::max(tables[table], descriptors); + tables_scratch_.clear(); + for (const GraphicsCommandList* list : graphics_scratch_) { + for (const auto& [table, descriptors] : list->tables()) { + bool merged = false; + if (tables_scratch_.size() <= 16) { + for (auto& entry : tables_scratch_) { + if (entry.first == table) { + entry.second = (std::max)(entry.second, descriptors); + merged = true; + break; + } + } + } + if (!merged) tables_scratch_.emplace_back(table, descriptors); + } + } + if (tables_scratch_.size() > 16) { + std::sort(tables_scratch_.begin(), tables_scratch_.end(), + [](const auto& a, const auto& b) { return a.first < b.first; }); + std::size_t write = 0; + for (std::size_t i = 0; i < tables_scratch_.size(); ++i) { + if (write && tables_scratch_[write - 1].first == tables_scratch_[i].first) { + tables_scratch_[write - 1].second = + (std::max)(tables_scratch_[write - 1].second, tables_scratch_[i].second); + } else { + if (write != i) tables_scratch_[write] = tables_scratch_[i]; + ++write; + } + } + tables_scratch_.resize(write); + } // LOCAL DIAGNOSTIC (fsdraw): poke experiment, LEONIDA_FSDRAW_POKE_CB=1 if (leonida::fsdraw::poke_enabled()) { - for (const auto& [table, descriptors] : tables) { + for (const auto& [table, descriptors] : tables_scratch_) { const std::uint64_t origin = leonida::fsdraw::table_origin(table); if (origin != table) leonida::fsdraw::poke_cb( @@ -2495,11 +2705,11 @@ class CommandQueue final // LOCAL DIAGNOSTIC (fsdraw): what the bound tables hold when the lists are submitted if (leonida::local_diagnostics()) { static std::atomic submits{0}; - const std::uint64_t n = tables.empty() || !leonida::fsdraw::enabled() ? 0 : ++submits; + const std::uint64_t n = tables_scratch_.empty() || !leonida::fsdraw::enabled() ? 0 : ++submits; if (n && (n <= 6 || n % 300 == 0)) { char tag[48]; std::snprintf(tag, sizeof tag, "submit #%llu", static_cast(n)); - for (const auto& [table, descriptors] : tables) { + for (const auto& [table, descriptors] : tables_scratch_) { const std::uint64_t origin = leonida::fsdraw::table_origin(table); const bool title = origin != table; leonida::fsdraw::describe_table( @@ -2509,9 +2719,9 @@ class CommandQueue final } } } - if (!tables.empty()) { + if (!tables_scratch_.empty()) { const auto start = std::chrono::steady_clock::now(); - for (const auto& [table, descriptors] : tables) { + for (const auto& [table, descriptors] : tables_scratch_) { // A table VA is an offset in this device's arena, so its own scanner reads it; the process-wide // hook belongs to the first device that registered and serves a context without a scanner. if (!context_.scan_table(table, descriptors)) @@ -2527,28 +2737,26 @@ class CommandQueue final .count())); } } - for (const auto* list : graphics) { - for (const auto& command : list->commands().commands()) { - leonida::ResourceId resource = 0; - if (const auto* b=std::get_if(&command)) { - if (b->after & (D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE|D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE)) - resource=b->resource; - } else if (const auto* b=std::get_if(&command)) { - if (b->access_after & D3D12_BARRIER_ACCESS_SHADER_RESOURCE) resource=b->resource; - } - if (resource && !context_.prepare_sample_table(resource,0)) { - last_result_=leonida::ReplayResult::unresolved_resource; - d3d12_trace::record(method,"failed"); + bool need_all_sampled = false; + for (const auto* list : graphics_scratch_) { + for (const leonida::ResourceId resource : list->sampled_barrier_resources()) { + if (resource && !context_.prepare_sample_table(resource, 0)) { + last_result_ = leonida::ReplayResult::unresolved_resource; + d3d12_trace::record(method, "failed"); return; } } - if (list->needs_all_sampled_views() && !context_.prepare_sample_table(0,0)) { - last_result_ = leonida::ReplayResult::unresolved_resource; - d3d12_trace::record(method,"failed"); - return; - } + if (list->needs_all_sampled_views()) need_all_sampled = true; + } + if (need_all_sampled && !context_.prepare_sample_table(0, 0)) { + last_result_ = leonida::ReplayResult::unresolved_resource; + d3d12_trace::record(method, "failed"); + return; } - last_result_ = queue_.execute(recorded, [&graphics] { return pin_lists(graphics); }); + for (const GraphicsCommandList* list : graphics_scratch_) + for (const auto& [va, bytes] : list->write_ranges()) + leonida::title_va_aliases().note_reached(va, bytes); + last_result_ = queue_.execute(recorded_scratch_, [this] { return pin_lists(graphics_scratch_); }); d3d12_trace::record(method, last_result_ == leonida::ReplayResult::success ? "ok" : "failed"); if (last_result_ != leonida::ReplayResult::success) std::fprintf(stderr, "[rt] d3d12: ExecuteCommandLists failed: %s; nothing was submitted\n", @@ -2561,6 +2769,7 @@ class CommandQueue final // A copy list's timestamps go to COPY_QUEUE_TIMESTAMP heaps and every other list's to TIMESTAMP heaps. bool timestamps_fit(const GraphicsCommandList& list) { + if (!list.has_timestamp_queries()) return true; namespace h = leonida::d3d12_query_heap; const auto other = list.type() == D3D12_COMMAND_LIST_TYPE_COPY ? h::timestamp : h::copy_queue_timestamp; for (const auto& command : list.commands().commands()) { @@ -2606,6 +2815,7 @@ class CommandQueue final HRESULT STDMETHODCALLTYPE Signal(ID3D12Fence* fence, UINT64 value) override { constexpr auto method = "ID3D12CommandQueue::Signal"; + const leonida::submit_phases::TitleCall call(leonida::submit_phases::part_fences); // "submit frame" line Fence* f = Fence::from(fence); if (!f || f->context() != &context_ || f->attached_device() != attached_device()) return d3d12_trace::result(method, E_INVALIDARG); @@ -2616,6 +2826,7 @@ class CommandQueue final HRESULT STDMETHODCALLTYPE Wait(ID3D12Fence* fence, UINT64 value) override { constexpr auto method = "ID3D12CommandQueue::Wait"; + const leonida::submit_phases::TitleCall call(leonida::submit_phases::part_fences); // "submit frame" line Fence* f = Fence::from(fence); if (!f || f->context() != &context_ || f->attached_device() != attached_device()) return d3d12_trace::result(method, E_INVALIDARG); @@ -2862,6 +3073,9 @@ class CommandQueue final std::shared_ptr queue_lease_; leonida::VulkanQueue queue_; leonida::ReplayResult last_result_ = leonida::ReplayResult::success; + std::vector> recorded_scratch_; // mutex_ + std::vector graphics_scratch_; // mutex_ + std::vector> tables_scratch_; // mutex_ VkQueue vk_queue_; std::uint32_t family_; QueueClock clock_; @@ -3023,6 +3237,32 @@ bool fence_callback_at(ID3D12Fence* fence, std::uint64_t value, std::functionsignal_submitted(value); +} + +HRESULT fence_signal_gpu_relay(ID3D12Fence* fence, std::uint64_t value) { + if (!fence) return E_INVALIDARG; + if (Fence* f = Fence::from(fence)) return f->signal_gpu_relay(value); + return fence->Signal(value); +} + +bool fence_relay_wait(ID3D12Fence* gate_fence, std::uint64_t gate_value, + std::span replacements) { + Fence* gf = Fence::from(gate_fence); + if (!gf || !gate_value || replacements.empty()) return false; + std::vector::Wait> waits; + waits.reserve(replacements.size()); + for (const FenceRelayTarget& target : replacements) { + Fence* rf = Fence::from(target.fence); + if (!rf || rf->context() != gf->context() || rf->semaphore() == gf->semaphore()) return false; + waits.push_back({rf->semaphore(), target.value, CommandQueue::fence_pin(target.fence)()}); + } + return gf->mutable_context()->holds().relay_wait(gf->semaphore(), gate_value, waits, + /*consume_on_substitute=*/true); +} + leonida::ReplayResult last_execute_result(ID3D12CommandQueue* queue) { if (ID3D12CommandQueue* real = d3d12_xs::queue_proxy_real_queue(queue)) queue = real; // the Xbox-ABI proxy CommandQueue* q = CommandQueue::from(queue); diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index eaea4f648e..39424c3f5d 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -103,6 +103,13 @@ struct VulkanDeviceInfo { std::uint32_t copy_family = UINT32_MAX; std::vector compute_queues; std::vector copy_queues; + // A queue of its own on which the GPU address arena binds and unbinds its memory blocks (src/arena_backing.h), + // so a bind never waits behind the title's work. Null: the arena is one allocation, as without sparse binding. + VkQueue arena_bind_queue = VK_NULL_HANDLE; + // VkPhysicalDeviceLimits::sparseAddressSpaceSize and VkPhysicalDeviceSparseProperties::residencyNonResidentStrict: + // a sparse arena must fit the first, and needs the second (an unbound block reads as zero). + VkDeviceSize sparse_address_space = 0; + bool residency_non_resident_strict = false; bool pipeline_creation_feedback = false; // Vulkan 1.3 pipelineCreationCacheControl, enabled: FAIL_ON_PIPELINE_COMPILE_REQUIRED asks a cache without a compile. // Implies core VkPipelineCreationFeedback, which then needs no extension. @@ -208,6 +215,9 @@ struct VulkanDeviceInfo { // arena and have console VAs (docs section 3.3), and GetGPUVirtualAddress returns those addresses; ray tracing // needs it too. Without it, GetGPUVirtualAddress returns 0 and pipelines cannot be created. bool buffer_device_address = false; + // bufferDeviceAddressCaptureReplay is enabled: a buffer can be made at a device address of the runtime's choosing + // (the page mirror's chunks at heap_base + a title address, src/title_mirror.h). + bool buffer_device_address_capture_replay = false; // Optional VK_KHR_acceleration_structure + VK_KHR_deferred_host_operations + VK_KHR_ray_query are enabled: // GetRaytracingAccelerationStructurePrebuildInfo and BuildRaytracingAccelerationStructure (BLAS + TLAS) work. bool ray_tracing = false; @@ -248,6 +258,10 @@ struct VulkanDeviceInfo { // writes the layer or viewport declares ShaderLayer / ShaderViewportIndex (the index's `features`). bool shader_output_layer = false; bool shader_output_viewport_index = false; + // Vulkan 1.2 vulkanMemoryModel / vulkanMemoryModelDeviceScope enabled on `device`: coherent (glc/dlc) translated + // shaders declare OpCapability VulkanMemoryModel and VulkanMemoryModelDeviceScope. + bool vulkan_memory_model = false; + bool vulkan_memory_model_device_scope = false; // The translator's output folder for pipeline creation. An empty value uses LEONIDA_SHADERS or the packaged path. std::string shader_dir; // VK_EXT_custom_border_color (with customBorderColors and customBorderColorWithoutFormat) is enabled on @@ -310,6 +324,27 @@ HRESULT create_console_descriptor_heap(ID3D12Device* device, const D3D12_DESCRIP // of another kind. For the console fence's slot-12 mirror (d3d12_xs_device.cpp). bool fence_callback_at(ID3D12Fence* fence, std::uint64_t value, std::function fn); +// Whether a Signal of at least `value` has reached the GPU for `fence` (or the CPU set it): false while the layer +// holds that Signal behind a wait it has not seen satisfied (src/queue_holds.h). True for a fence of another kind. For +// the console list values' pump (d3d12_xs_list_values.h): work held that way is not running. +bool fence_signal_submitted(ID3D12Fence* fence, std::uint64_t value); + +// Signals `fence` to `value` from the CPU without bumping the device visibility epoch (vis_seq = 0): for GPU-to-GPU +// relays (e.g. list_values::Pump gates met strictly by GPU writes landed via Pump::land()). Falls back to +// fence->Signal(value) for fences of another kind. +HRESULT fence_signal_gpu_relay(ID3D12Fence* fence, std::uint64_t value); + +// Retroactively redirects any queued, pending, or held wait on `(gate_fence, gate_value)` to GPU waits on +// `replacements` in QueueHolds (never GPU-signaling `gate_fence`), releasing newly-unblocked held operations +// immediately. False when `gate_fence` or any replacement is not a Vulkan fence on the same context, or when +// `gate_fence` has already been signaled to at least `gate_value`. +struct FenceRelayTarget { + ID3D12Fence* fence = nullptr; + std::uint64_t value = 0; +}; +bool fence_relay_wait(ID3D12Fence* gate_fence, std::uint64_t gate_value, + std::span replacements); + // The VkImage behind a texture created by such a device, or VK_NULL_HANDLE. For tests and the swapchain. VkImage vulkan_image(ID3D12Resource* resource); // Resolves the resource that a UAV clear writes. Xbox depth/stencil UAVs name one of two color images by T#. @@ -393,10 +428,47 @@ bool device_sparse_buffer_tiles(ID3D12Device* device); // The size in bytes of the device's GPU address arena, or 0 without one. For tests. std::uint64_t device_arena_size(ID3D12Device* device); +// The GPU address arena's memory: its size (address range), device address (heap_base), the bytes of memory bound +// behind it now (all of it for one allocation), whether it binds memory as allocations need it (sparse), whether the +// device could (sparse_capable), and whether V# bases are read as signed offsets (a buffer below heap_base is +// reachable). All zero without an arena. For tests. +struct ArenaMemoryState { + std::uint64_t size = 0, address = 0, bound = 0; + bool sparse = false, sparse_capable = false, signed_offsets = false; +}; +ArenaMemoryState device_arena_memory(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 page mirror (src/title_mirror.h): whether the device made it (and why not), and what it holds. For tests. +struct PageMirrorState { + bool on = false; + std::uint64_t heap_base = 0, pages = 0, homes = 0, chunks = 0, uploads = 0, binds = 0; +}; +PageMirrorState page_mirror_state(ID3D12Device* device); +// Brings the page mirror up to date as a submission does, then copies `bytes` at heap_base + `title_va` (what a shader +// reads at a title-written address there) into `out` with the GPU, after the mirror's last bind. False when the mirror is +// off or the address is not in one of its chunks. For tests. +bool page_mirror_gpu_read(ID3D12Device* device, std::uint64_t title_va, void* out, std::size_t bytes); +// The same at arena VA `va` (heap_base + va): what a shader reads there, a console heap read in place among it. False +// when the mirror is off. For tests. +bool arena_gpu_read(ID3D12Device* device, std::uint64_t va, void* out, std::size_t bytes); +// Whether the layer writes the T# index word (gfx10_descriptors.h, tsharp_index_word) into the heaps shaders read, as a +// loaded library of modules that read it turns on. Returns what it was. For tests, which load no library. +bool set_tsharp_index_words_for_test(ID3D12Device* device, bool on); +// Whether a draw's or copy's binding of title memory [va, va + size) would be served by the page mirror (VulkanContext's +// mirror lookup): it must have been named before. `size` comes back cut at the chunk's end. For tests. +bool page_mirror_buffer_at(ID3D12Device* device, std::uint64_t va, std::uint64_t& size); +// Names [va, va + bytes) to the page mirror as a reader would (page_mirror_resolve). For tests. +bool page_mirror_name(ID3D12Device* device, std::uint64_t va, std::uint64_t bytes); +// Writes `bytes` (at most 64 KiB) at heap_base + `title_va` with the GPU, as a shader's store into the mirror would, +// and waits for it. For tests. +bool page_mirror_gpu_write(ID3D12Device* device, std::uint64_t title_va, const void* data, std::size_t bytes); +// The copy back of what the GPU wrote into the mirror's homes over [va, va + bytes) to the title's pages, as +// write_back_titles makes it once a submission has retired. Returns the bytes written. For tests. +std::uint64_t page_mirror_write_back(ID3D12Device* device, std::uint64_t va, std::uint64_t bytes); + // The blocks of device memory that textures share (src/image_memory.h): how many, their bytes, and the textures in // them. For tests. struct ImageMemoryStats { @@ -421,7 +493,8 @@ struct BindlessStats { BindlessStats bindless_stats(ID3D12Device* device); VkDescriptorSetLayout bindless_set_layout(ID3D12Device* device); // The bindless index the descriptor hash table holds for the 8 key dwords of a T# (or the 4 of an S# followed by -// 0xFFFFFFFF x4), 0 (the fallback) when it has none or `device` has no such set. For tests. +// 0xFFFFFFFF x4), 0 (the fallback) when it has none or `device` has no such set. A T# read from one of the layer's +// heaps is looked up without its index word (dword 6), and gives 0 unless that word names the same index. For tests. std::uint32_t bindless_hash_lookup(ID3D12Device* device, const std::uint32_t (&key)[8]); // The free indices of that set's 2D image and sampler arrays: how many more distinct 2D T#s and S#s // CreateShaderResourceView and CreateSampler can register before they log that the array is full. Zeros when diff --git a/runtime/shims/d3d12_compute_input_probe.h b/runtime/shims/d3d12_compute_input_probe.h index 70ac61e52c..d03047b459 100644 --- a/runtime/shims/d3d12_compute_input_probe.h +++ b/runtime/shims/d3d12_compute_input_probe.h @@ -4,12 +4,15 @@ #include "../src/fsdraw_probe.h" #include "../src/title_va_alias.h" #include "../src/title_page_watch.h" +#include "../src/title_mirror_space.h" +#include "../src/title_mirror.h" #include "xmem.h" #include #include #include #include #include +#include #include #include #include @@ -41,7 +44,8 @@ inline bool matches(const char* name) { return false; } -// Each decimal pair selects a table root dword and a 32-byte descriptor index. +// Each decimal pair selects a table root dword and a 32-byte descriptor index; root/first-last selects a run of +// them (at most 64). inline const auto& slots() { static const auto pairs = [] { std::vector> result; @@ -49,12 +53,19 @@ inline const auto& slots() { if (!p) return result; const char* end = p + std::strlen(p); while (p != end && result.size() < 256) { - unsigned root{}, slot{}; + unsigned root{}, slot{}, last{}; auto r = std::from_chars(p, end, root); if (r.ec != std::errc{} || r.ptr == end || *r.ptr != '/') break; auto s = std::from_chars(r.ptr + 1, end, slot); - if (s.ec != std::errc{} || (s.ptr != end && *s.ptr != ',')) break; - if (root < 32 && slot < (1u << 21)) result.emplace_back(root, slot); + if (s.ec != std::errc{}) break; + last = slot; + if (s.ptr != end && *s.ptr == '-') { + s = std::from_chars(s.ptr + 1, end, last); + if (s.ec != std::errc{} || last < slot) break; + last = std::min(last, slot + 63); + } + if (s.ptr != end && *s.ptr != ',') break; + for (unsigned k = slot; k <= last && root < 32 && k < (1u << 21); ++k) result.emplace_back(root, k); p = s.ptr == end ? end : s.ptr + 1; } return result; @@ -86,16 +97,44 @@ inline bool read_backing(Backing b, std::uint64_t offset, void* out, std::size_t // The device owns the arena mapping for its lifetime. Linux cross-process reads can reject a // device mapping even though the current process can read it directly. if (std::string_view(b.kind) == "arena" || std::string_view(b.kind) == "arena-shadow" || - std::string_view(b.kind) == "window-shadow") { + std::string_view(b.kind) == "window-shadow" || std::string_view(b.kind) == "mirror-home") { std::memcpy(out, reinterpret_cast(b.host + offset), size); return true; } return read_cpu(b.host + offset, out, size); } +// The page mirror's home of the title page at `va` (what heap_base + va reads), to the page's end: null when the mirror +// holds no page there. A device-local home is read over the bus (slow; a diagnostic only). +template +const std::uint8_t* mirror_home(State& state, std::uint64_t va, std::uint64_t& room) { + if (!state.page_mirror.mirror) return nullptr; + std::lock_guard lock(state.page_mirror.mutex); + const std::uint8_t* home = state.page_mirror.mirror->home_bytes(va); + if (!home) return nullptr; + room = leonida::TitleMirror::kPage - (va & (leonida::TitleMirror::kPage - 1)); + return home + (va & (leonida::TitleMirror::kPage - 1)); +} + +// What the host has at `va` as an address. +inline const char* host_kind(std::uint64_t va) { + MEMORY_BASIC_INFORMATION info{}; + if (!VirtualQuery(reinterpret_cast(static_cast(va)), &info, sizeof(info)) || + info.State == MEM_FREE) + return "free"; + if (info.State != MEM_COMMIT) return "reserved"; + return info.Type == MEM_IMAGE ? "image" : info.Type == MEM_MAPPED ? "mapped" : "private"; +} + template Backing backing(State& state, std::uint64_t base) { auto& aliases = leonida::title_va_aliases(); + if (base >= state.arena.size && !(base & (1ull << 47))) { + std::uint64_t room = 0; + if (const std::uint8_t* home = mirror_home(state, base, room)) + return {"mirror-home", base, reinterpret_cast(home), room}; + if (leonida::title_mirror_space::contains(base)) return {"mirror-unbound", base}; + } std::uint64_t source{}, room{}; const bool alias = aliases.source_of_vsharp(base, source, room); if (base < state.arena.size) { @@ -104,8 +143,13 @@ Backing backing(State& state, std::uint64_t base) { // block after it starts, without holding an iterator the block map could cut. std::uint64_t block_offset = 0, block_size = 0, next = state.arena.size; if (state.arena.blocks.free_at(base, block_offset, block_size, next)) return {"arena-free"}; - return {alias ? "arena-shadow" : "arena", source, reinterpret_cast(state.arena.mapped) + base, - alias ? std::min(room, next - base) : next - base}; + // The CPU address of base in the backing unit that holds it; the range reported stops at the unit's end. + const std::uint64_t span = std::min(alias ? std::min(room, next - base) + : next - base, + state.arena.backing.room(base)); + if (!span) return {"arena-unbacked"}; + return {alias ? "arena-shadow" : "arena", source, + reinterpret_cast(state.arena.backing.host(base, span)), span}; } if (alias) { std::uint64_t host{}, bytes{}; @@ -257,7 +301,8 @@ void recheck(State& state) { else for (const auto& [offset, heap] : state.visible_heaps) if (heap.type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV && heap.end <= state.arena.size) - scan("arena", offset, state.arena.mapped + offset, heap.end - offset); + if (const std::uint8_t* host = state.arena.backing.host(offset, heap.end - offset)) + scan("arena", offset, host, heap.end - offset); } } @@ -265,6 +310,22 @@ template Backing descriptor(State& state, std::uint64_t seq, std::size_t list, std::size_t cmd, const std::array& roots, unsigned reg, unsigned slot, std::array* words = nullptr) { + // The whole record goes out in one write when the function returns: other threads' probe lines (fsdraw) write to + // stderr too, and a record made of many writes came out cut by theirs. + struct Line { + std::string s; + void f(const char* format, ...) { + char text[1024]; + va_list args; + va_start(args, format); + const int n = std::vsnprintf(text, sizeof(text), format, args); + va_end(args); + if (n > 0) s.append(text, std::min(std::size_t(n), sizeof(text) - 1)); + } + ~Line() { + if (!s.empty()) std::fwrite(s.data(), 1, s.size(), stderr); + } + } line; const auto at = std::uint64_t(roots[reg]) + std::uint32_t(slot * 32u); std::array raw{}, gpu{}; const char* origin = "no-heap"; @@ -300,37 +361,77 @@ Backing descriptor(State& state, std::uint64_t seq, std::size_t list, std::size_ } } } + if (!have_gpu && title_at) { + std::uint64_t room = 0; + if (const std::uint8_t* home = mirror_home(state, title_at, room); home && room >= sizeof(gpu)) { + std::memcpy(gpu.data(), home, sizeof(gpu)); // a heap read in place: the filtered home + have_gpu = true; + } + } if (!have_gpu) have_gpu = leonida::fsdraw::arena_words(at, gpu.data(), gpu.size()); if (have_gpu) remember(at, seq, cmd, reg, slot, gpu); const auto prefix = "[rt] compute-input: execute=%llu list=%zu cmd=%zu s%u/%u "; - std::fprintf(stderr, prefix, (unsigned long long)seq, list, cmd, reg, slot); + line.f(prefix, (unsigned long long)seq, list, cmd, reg, slot); if (!have_gpu) { - std::fprintf(stderr, "table=0x%llx no GPU-visible bytes\n", (unsigned long long)at); + line.f("table=0x%llx no GPU-visible bytes\n", (unsigned long long)at); return {"missing-table"}; } if (words) *words = gpu; - std::fprintf(stderr, "heap-slot=%llu table-title=0x%llx writer=%s words=[%s] ", + line.f("heap-slot=%llu table-title=0x%llx writer=%s words=[%s] ", (unsigned long long)index, (unsigned long long)title_at, origin, leonida::fsdraw::hex_words(gpu.data(), gpu.size()).c_str()); if (table && raw != gpu) - std::fprintf(stderr, "title-words=[%s] ", leonida::fsdraw::hex_words(raw.data(), raw.size()).c_str()); + line.f("title-words=[%s] ", leonida::fsdraw::hex_words(raw.data(), raw.size()).c_str()); if (gpu[3] >> 30) { - std::fprintf(stderr, "texture key=%s\n", leonida::fsdraw::has_tsharp(gpu.data()) ? "registered" : "absent"); + line.f("texture key=%s\n", leonida::fsdraw::has_tsharp(gpu.data()) || + (table && leonida::fsdraw::has_tsharp(raw.data())) ? "registered" : "absent"); return {"texture"}; } - if (!(gpu[0] | gpu[1] | gpu[2] | gpu[3])) { std::fputs("null\n", stderr); return {"null"}; } + if (!(gpu[0] | gpu[1] | gpu[2] | gpu[3])) { + // Null on the GPU side: when the title's slot holds a buffer V#, the layer resolved it to nothing (a heap read + // in place zeroes it). Where its base lies, and the title's bytes there, name the memory that read as zeros. + if (table && (raw[0] | raw[1] | raw[2] | raw[3]) && !(raw[3] >> 30)) { + const auto title_base = std::uint64_t(raw[0]) | (std::uint64_t(raw[1] & 0xffff) << 32); + const auto title_stride = (raw[1] >> 16) & 0x3fffu; + std::array title{}; + const auto t = std::min(std::uint64_t(raw[2]) * (title_stride ? title_stride : 1), sizeof(title)) / 4; + const bool high = title_base & (1ull << 47); + const auto tb = backing(state, title_base); + line.f("null (resolved to nothing) title-V#=0x%llx stride=%u records=%u storage=%s host=%s", + (unsigned long long)title_base, title_stride, raw[2], tb.kind, + high ? "bit47" : host_kind(title_base)); + if (!high && title_base >= state.arena.size && t && read_cpu(title_base, title.data(), 4 * t)) + line.f(" title-sample=[%s]", leonida::fsdraw::hex_words(title.data(), t).c_str()); + line.s += '\n'; + return {"null"}; + } + line.s += "null\n"; + return {"null"}; + } const auto base = std::uint64_t(gpu[0]) | (std::uint64_t(gpu[1] & 0xffff) << 32); const auto stride = (gpu[1] >> 16) & 0x3fffu; const auto span = std::uint64_t(gpu[2]) * (stride ? stride : 1); auto b = backing(state, base); const auto signed_base = (base ^ (1ull << 47)) - (1ull << 47); - std::fprintf(stderr, "V#=0x%llx bda=0x%llx stride=%u records=%u storage=%s title=0x%llx", + line.f("V#=0x%llx bda=0x%llx stride=%u records=%u storage=%s title=0x%llx", (unsigned long long)base, (unsigned long long)(state.arena.address + signed_base), stride, gpu[2], b.kind, (unsigned long long)b.title); std::array data{}; const auto n = std::min({span, b.available, sizeof(data)}) / 4; if (n && read_backing(b, 0, data.data(), 4 * n)) - std::fprintf(stderr, " cpu-sample=[%s]", leonida::fsdraw::hex_words(data.data(), n).c_str()); + line.f(" cpu-sample=[%s]", leonida::fsdraw::hex_words(data.data(), n).c_str()); + // The title's own bytes at the base (as the title wrote them), when the host has the address: against what the + // GPU reads there, the first 16 dwords. + { + std::array title{}; + const auto t = std::min(span ? span : 4, sizeof(title)) / 4; + const bool read = base >= state.arena.size && !(base & (1ull << 47)) && t && read_cpu(base, title.data(), 4 * t); + line.f(" host=%s", base & (1ull << 47) ? "bit47" : host_kind(base)); + if (read) { + line.f(" title-sample=[%s]", leonida::fsdraw::hex_words(title.data(), t).c_str()); + if (n) line.f(" gpu-vs-title=%s", std::memcmp(title.data(), data.data(), 4 * std::min(n, t)) ? "DIFFER" : "same"); + } + } if (std::string_view(b.kind) == "untranslated-title") { std::uint64_t created_at{}; const bool from_cbv = leonida::fsdraw::cbv_origin(base, created_at); @@ -338,15 +439,15 @@ Backing descriptor(State& state, std::uint64_t seq, std::size_t list, std::size_ const auto aliased = leonida::title_va_aliases().shader_va(source); MEMORY_BASIC_INFORMATION region{}; VirtualQuery(reinterpret_cast(source), ®ion, sizeof(region)); - std::fprintf(stderr, " source=0x%llx source-alias=0x%llx state=0x%lx protect=0x%lx", + line.f(" source=0x%llx source-alias=0x%llx state=0x%lx protect=0x%lx", (unsigned long long)source, (unsigned long long)aliased, region.State, region.Protect); - if (from_cbv) std::fprintf(stderr, " recorded-CBV-location=0x%llx", (unsigned long long)created_at); + if (from_cbv) line.f(" recorded-CBV-location=0x%llx", (unsigned long long)created_at); const auto size = std::min(span, sizeof(data)) / 4; if (size && region.State == MEM_COMMIT && !(region.Protect & (PAGE_NOACCESS | PAGE_GUARD)) && read_cpu(source, data.data(), size * 4)) - std::fprintf(stderr, " source-only=[%s]", leonida::fsdraw::hex_words(data.data(), size).c_str()); + line.f(" source-only=[%s]", leonida::fsdraw::hex_words(data.data(), size).c_str()); } - std::fputc('\n', stderr); + line.s += '\n'; b.available = std::min(b.available, span); return b; } diff --git a/runtime/shims/d3d12_geometry_views.h b/runtime/shims/d3d12_geometry_views.h index 58649a29c2..ae473915ee 100644 --- a/runtime/shims/d3d12_geometry_views.h +++ b/runtime/shims/d3d12_geometry_views.h @@ -1,8 +1,10 @@ #pragma once #include "d3d12_title_buffer_windows.h" +#include "../src/command_list_epochs.h" #include "../src/memory_breakdown.h" #include "../src/title_geometry_watch.h" +#include "../src/submit_phases.h" #include #include #include @@ -55,8 +57,9 @@ class GeometryViews { struct Retired { VkDeviceSize va{}; std::size_t size{}; - std::uint64_t ticket{}; // kAfterExecutes until execute_end() stamps it - std::uint64_t epoch{}; // the last execute begun when it was retired (kAfterExecutes only) + std::uint64_t ticket{}; // kAfterExecutes until execute_end() / stamp_retired() stamps it + std::uint64_t epoch{}; // the last execute enqueued when it was retired (kAfterExecutes only) + std::uint64_t lists{}; // the command-list epoch of the retirement (kAfterExecutes only) }; std::uint64_t cap_override_{}; mutable std::mutex mutex_; @@ -112,15 +115,23 @@ class GeometryViews { std::map tiles_; std::vector retired_; std::atomic retired_count_{0}; - // The ExecuteCommandLists replays in progress (execute_begin/execute_end), by the serial each began with. A view - // retired at kAfterExecutes may be named by any of them: by a list recorded before the retirement, or by a console - // heap slot their before_execute_ translated. It gets its retire ticket only once all of them have recorded their - // submissions, so a ticket read then covers them, however many tickets a replay records and on whichever queue. + // The ExecuteCommandLists replays in progress (execute_enqueue/execute_end), by the serial each enqueued with. + // A view retired at kAfterExecutes may be named by any of them (console heap slots their before_execute_ + // translated) or by any live command list recorded before the retirement (src/command_list_epochs.h). It gets + // its retire ticket only once all such replays have recorded their submissions and all such command lists are gone, + // so a ticket read then covers them, however many tickets a replay records and on whichever queue. std::mutex execute_mutex_; // a leaf lock std::uint64_t execute_serial_{}; std::vector executing_; std::atomic unstamped_{false}; leonida::geometry_writes::ReleaseQueue releases_; + leonida::geometry_writes::WriteQueue writes_; + std::unordered_map> peer_to_tiles_; + std::vector
written_queue_scratch_; + std::vector
hot_tiles_scratch_; + std::vector
hot_overlap_tiles_; + std::vector
candidate_vas_; + std::uint64_t hot_gen_seen_ = ~std::uint64_t(0); 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_{}; @@ -141,15 +152,26 @@ class GeometryViews { std::uint64_t cleared_{}; bool retry_{}; + void unregister_peers_locked(Address va, const std::vector>& peers) { // mutex_ held + for (const auto& item : peers) { + const auto pit = peer_to_tiles_.find(item.first); + if (pit == peer_to_tiles_.end()) continue; + std::erase(pit->second, va); + if (pit->second.empty()) peer_to_tiles_.erase(pit); + } + } + void detach_tiles_locked(std::size_t id, Address source, std::size_t size) { // mutex_ held for (auto p = source & ~(tile_size - 1); p < source + size; p += tile_size) { const auto it = tiles_.find(p); if (it == tiles_.end()) continue; std::erase(it->second.views, id); if (it->second.views.empty()) { + unregister_peers_locked(p, it->second.peers); for (auto [peer, cell] : it->second.peers) leonida::geometry_writes::release(peer); if (it->second.primary) leonida::geometry_writes::release(p); tiles_.erase(it); + hot_gen_seen_ = ~std::uint64_t(0); } } } @@ -163,9 +185,14 @@ class GeometryViews { std::vector
others; if (auto aliases = watch::aliases.load(std::memory_order_acquire)) aliases(va, others); auto old = std::move(t.peers); - for (auto peer : others) t.peers.emplace_back(peer, watch::acquire(peer)); + unregister_peers_locked(va, old); + for (auto peer : others) { + t.peers.emplace_back(peer, watch::acquire(peer)); + peer_to_tiles_[peer].push_back(va); + } for (auto [peer, cell] : old) watch::release(peer); t.mapping = mapping; + hot_gen_seen_ = ~std::uint64_t(0); } for (auto [addr, peer] : t.peers) version = (std::max)(version, peer->version.load(std::memory_order_acquire)); @@ -177,6 +204,37 @@ class GeometryViews { retry_ |= t.retry; return !t.retry; } + + // Rebuilds `hot_overlap_tiles_` (sorted, unique primary tile VAs in `tiles_` whose primary or any peer is + // currently hot in geometry_writes) whenever `hot_generation` or `tiles_`/`peer_to_tiles_` changed. mutex_ held. + void sync_hot_overlap_locked() { + auto& s = leonida::geometry_writes::state(); + if (s.hot_count.load(std::memory_order_acquire) == 0) { + hot_overlap_tiles_.clear(); + hot_gen_seen_ = ~std::uint64_t(0); + return; + } + const std::uint64_t gen = s.hot_generation.load(std::memory_order_acquire); + if (gen == hot_gen_seen_) return; + hot_overlap_tiles_.clear(); + if (!tiles_.empty()) { + leonida::geometry_writes::hot_tiles(hot_tiles_scratch_); + for (const Address h : hot_tiles_scratch_) { + if (tiles_.find(h) != tiles_.end()) hot_overlap_tiles_.push_back(h); + if (!peer_to_tiles_.empty()) { + if (const auto pit = peer_to_tiles_.find(h); pit != peer_to_tiles_.end()) { + for (const Address primary : pit->second) hot_overlap_tiles_.push_back(primary); + } + } + } + if (hot_overlap_tiles_.size() > 1) { + std::sort(hot_overlap_tiles_.begin(), hot_overlap_tiles_.end()); + hot_overlap_tiles_.erase(std::unique(hot_overlap_tiles_.begin(), hot_overlap_tiles_.end()), + hot_overlap_tiles_.end()); + } + } + hot_gen_seen_ = gen; + } // The tile's 64 KiB as this refresh read it, or null when it could not be read whole. Read at most once a refresh. template const std::uint8_t* read_tile(Address tile, Copy& copy) { @@ -218,8 +276,12 @@ class GeometryViews { explicit GeometryViews(std::uint64_t cap_override = 0) : cap_override_(cap_override) { pool_.set_system_memory(system_memory_setting()); leonida::geometry_writes::subscribe(releases_); + leonida::geometry_writes::subscribe_writes(writes_); + } + ~GeometryViews() { + leonida::geometry_writes::unsubscribe_writes(writes_); + leonida::geometry_writes::unsubscribe(releases_); } - ~GeometryViews() { leonida::geometry_writes::unsubscribe(releases_); } GeometryViews(const GeometryViews&) = delete; GeometryViews& operator=(const GeometryViews&) = delete; GeometryViews(GeometryViews&&) = delete; @@ -357,7 +419,9 @@ class GeometryViews { bytes_ += bytes; bool ready = true; for (auto p = cpu & ~(tile_size - 1); p < cpu + bytes; p += tile_size) { - auto& tile = tiles_[p]; + auto [tile_it, inserted] = tiles_.try_emplace(p); + auto& tile = tile_it->second; + if (inserted) hot_gen_seen_ = ~std::uint64_t(0); // Previously watched tiles may have other dirty views waiting for refresh(). if (!tile.primary) update(p, tile); tile.views.push_back(id); @@ -374,17 +438,20 @@ class GeometryViews { } // retire_range's ticket for a view that work already in flight may name: the ticket is taken by execute_end() - // once every ExecuteCommandLists replay begun by then has recorded its submissions. + // once every ExecuteCommandLists replay enqueued or begun by then has recorded its submissions. static constexpr std::uint64_t kAfterExecutes = UINT64_MAX; - // An ExecuteCommandLists replay starts (before its before_execute_ work): its serial, for execute_end(). - std::uint64_t execute_begin() { + // Registers an ExecuteCommandLists batch at enqueue time (before it enters VulkanQueue::inbox_ or held_), so any + // view retired with kAfterExecutes while this already-recorded batch waits in an async inbox or behind a fence + // gate cannot be stamped and reaped until this batch has recorded its GPU submission. Paired with execute_end(). + std::uint64_t execute_enqueue() { std::lock_guard lock(execute_mutex_); executing_.push_back(++execute_serial_); return execute_serial_; } - // The last replay begun, and the oldest still in progress (kAfterExecutes when none): what execute_end stamps by, - // for a copy the device retires the same way outside these views (a title window, DeviceState::retire_windows). + // The last replay enqueued, and the oldest still in progress (kAfterExecutes when none): what + // execute_end stamps by, for a copy the device retires the same way outside these views (a title window, + // DeviceState::retire_orphan_windows). std::uint64_t execute_epoch() { std::lock_guard lock(execute_mutex_); return execute_serial_; @@ -395,15 +462,12 @@ class GeometryViews { for (const auto s : executing_) oldest = (std::min)(oldest, s); return oldest; } - // The replay that began with `serial` has recorded its submissions. Views retired while only replays now finished - // were in progress get submitted() (the context's submitted_retire_ticket(), read here, after those replays - // recorded theirs) as their retire ticket. Lock order: mutex_ -> execute_mutex_, as in retire_range. + // Stamps every unstamped retired view whose pre-retirement replays have finished and whose pre-retirement + // command lists are gone (src/command_list_epochs.h) with submitted() (the context's submitted_retire_ticket(), + // read after oldest_list so any list released before that read has had its submissions counted). + // Lock order: mutex_ -> execute_mutex_, as in retire_range. template - void execute_end(std::uint64_t serial, Submitted&& submitted) { - { - std::lock_guard lock(execute_mutex_); - std::erase(executing_, serial); - } + void stamp_retired(Submitted&& submitted) { if (!unstamped_.load(std::memory_order_acquire)) return; std::lock_guard lock(mutex_); std::uint64_t oldest = kAfterExecutes; @@ -411,15 +475,28 @@ class GeometryViews { std::lock_guard execute(execute_mutex_); for (const auto s : executing_) oldest = (std::min)(oldest, s); } + // Before the ticket: a list released after this read has had its submissions counted in it. + const std::uint64_t oldest_list = leonida::command_list_epochs::oldest(); const std::uint64_t ticket = submitted(); bool left = false; for (auto& r : retired_) { if (r.ticket != kAfterExecutes) continue; - if (r.epoch < oldest) r.ticket = ticket; + if (r.epoch < oldest && r.lists <= oldest_list) r.ticket = ticket; else left = true; } unstamped_.store(left, std::memory_order_release); } + // The replay that was enqueued with `serial` has recorded its submissions (or was dropped). Views retired while + // only replays now finished and command lists now gone were live get submitted() as their retire ticket. + template + void execute_end(std::uint64_t serial, Submitted&& submitted) { + if (!serial) return; + { + std::lock_guard lock(execute_mutex_); + std::erase(executing_, serial); + } + stamp_retired(submitted); + } // 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 @@ -474,7 +551,7 @@ class GeometryViews { v.ready = false; } callbacks.push_back({v.source, v.size, v.va}); - retired_.push_back({v.va, v.size, retire_ticket, 0}); + retired_.push_back({v.va, v.size, retire_ticket, 0, 0}); } if (!ids.empty()) { std::unique_lock structure(structure_mutex_); @@ -490,15 +567,19 @@ class GeometryViews { for (const auto id : ids) fast_.erase({views_[id].source, views_[id].size}); for (const auto& k : stale_refused) fast_.erase(k); } - // No resolve() or find() answers these views from here on, so a replay that begins now cannot name them: - // they wait only for the replays begun so far. + // No resolve() or find() answers these views from here on, so a replay or command list whose recording + // begins now cannot name them: they wait only for replays enqueued so far and command lists already alive. if (retire_ticket == kAfterExecutes && !ids.empty()) { std::uint64_t epoch = 0; { std::lock_guard execute(execute_mutex_); epoch = execute_serial_; } - for (std::size_t i = first_retired; i < retired_.size(); ++i) retired_[i].epoch = epoch; + const std::uint64_t lists = leonida::command_list_epochs::advance(); + for (std::size_t i = first_retired; i < retired_.size(); ++i) { + retired_[i].epoch = epoch; + retired_[i].lists = lists; + } } for (const auto& k : stale_refused) refused_.erase(k); for (const auto id : ids) { @@ -565,11 +646,33 @@ class GeometryViews { std::lock_guard serial(refresh_mutex_); std::unique_lock lock(mutex_); ++submissions_; - auto now = leonida::geometry_writes::state().serial.load(std::memory_order_acquire); - if (serial_ == now && !retry_) return; + sync_hot_overlap_locked(); + const bool has_writes = writes_.pending.load(std::memory_order_acquire); + if (!retry_ && !has_writes && hot_overlap_tiles_.empty()) return; + bool overflow = false; + written_queue_scratch_.clear(); + if (has_writes) leonida::geometry_writes::take_written(writes_, written_queue_scratch_, overflow); + candidate_vas_.clear(); + const bool full_walk = retry_ || overflow; + if (!full_walk) { + for (const Address w : written_queue_scratch_) { + if (tiles_.find(w) != tiles_.end()) candidate_vas_.push_back(w); + if (!peer_to_tiles_.empty()) { + if (const auto pit = peer_to_tiles_.find(w); pit != peer_to_tiles_.end()) { + for (const Address primary : pit->second) candidate_vas_.push_back(primary); + } + } + } + for (const Address h : hot_overlap_tiles_) candidate_vas_.push_back(h); + if (candidate_vas_.empty()) return; + if (candidate_vas_.size() > 1) { + std::sort(candidate_vas_.begin(), candidate_vas_.end()); + candidate_vas_.erase(std::unique(candidate_vas_.begin(), candidate_vas_.end()), candidate_vas_.end()); + } + } const auto start = std::chrono::steady_clock::now(); const auto before = uploaded_; - serial_ = now; + serial_ = leonida::geometry_writes::state().serial.load(std::memory_order_acquire); retry_ = false; refreshing_ = true; struct RefreshGuard { @@ -593,24 +696,46 @@ class GeometryViews { // submission fixes its console heap slots then waited for the whole pass (speed-35: 116 ms of fixing a // submission with indirect draws on). So the lock is let go every 64 tiles. Walking by key (lower_bound) // survives both inserts from resolve() and erasures from retire_range() while unlocked. - Address cursor = 0; - bool have_cursor = true; - std::size_t walked = 0; - while (have_cursor) { - auto it = tiles_.lower_bound(cursor); - if (it == tiles_.end()) break; - const Address va = it->first; - Tile& tile = it->second; - const bool written = update(va, tile); - if (tile.retry) - for (auto id : tile.views) - if (id < marks_.size() && views_[id].alive) marks_[id] |= kPinned; - if (written) written_vas_.push_back(va); - if (va > UINTPTR_MAX - tile_size) have_cursor = false; - else cursor = va + tile_size; - if (!(++walked & 63)) { - lock.unlock(); - lock.lock(); + const auto is_hot_overlap = [&](Address va) { + return !hot_overlap_tiles_.empty() && + std::binary_search(hot_overlap_tiles_.begin(), hot_overlap_tiles_.end(), va); + }; + if (full_walk) { + Address cursor = 0; + bool have_cursor = true; + std::size_t walked = 0; + while (have_cursor) { + auto it = tiles_.lower_bound(cursor); + if (it == tiles_.end()) break; + const Address va = it->first; + Tile& tile = it->second; + const bool written = update(va, tile); + if (tile.retry) + for (auto id : tile.views) + if (id < marks_.size() && views_[id].alive) marks_[id] |= kPinned; + if (written || (!tile.retry && is_hot_overlap(va))) written_vas_.push_back(va); + if (va > UINTPTR_MAX - tile_size) have_cursor = false; + else cursor = va + tile_size; + if (!(++walked & 63)) { + lock.unlock(); + lock.lock(); + } + } + } else { + std::size_t walked = 0; + for (const Address va : candidate_vas_) { + auto it = tiles_.find(va); + if (it == tiles_.end()) continue; + Tile& tile = it->second; + const bool written = update(va, tile); + if (tile.retry) + for (auto id : tile.views) + if (id < marks_.size() && views_[id].alive) marks_[id] |= kPinned; + if (written || (!tile.retry && is_hot_overlap(va))) written_vas_.push_back(va); + if (!(++walked & 63)) { + lock.unlock(); + lock.lock(); + } } } const std::size_t changed_tiles = written_vas_.size(); @@ -661,7 +786,10 @@ class GeometryViews { for (std::size_t id = 0; id < marks_.size(); ++id) if ((marks_[id] & (kWhole | kPinned)) == kWhole && views_[id].alive) fill(views_[id], copy); written_vas_.clear(); - if (uploaded_ != before) ++dirty_refreshes_; + if (uploaded_ != before) { + ++dirty_refreshes_; + leonida::submit_phases::note_change(leonida::submit_phases::change_geometry); // not a "submit floor" one + } refilled_ += uploaded_ - before; const auto end = std::chrono::steady_clock::now(); refresh_time_ += end - start; @@ -734,6 +862,9 @@ class GeometryViews { if (tile.primary) leonida::geometry_writes::release(va); } tiles_.clear(); + peer_to_tiles_.clear(); + hot_overlap_tiles_.clear(); + hot_gen_seen_ = ~std::uint64_t(0); { std::unique_lock structure(structure_mutex_); keys_.clear(); diff --git a/runtime/shims/d3d12_title_buffer_windows.h b/runtime/shims/d3d12_title_buffer_windows.h index c85809e8e2..9cdf52e381 100644 --- a/runtime/shims/d3d12_title_buffer_windows.h +++ b/runtime/shims/d3d12_title_buffer_windows.h @@ -37,6 +37,16 @@ class TitleBufferWindows { static constexpr auto kRetryAfter = std::chrono::seconds(2); std::chrono::steady_clock::time_point failed_at_{}; bool failed_ = false; + bool address_logged_ = false; + unsigned failure_lines_ = 0; + // The first failures of each block allocation, with the Vulkan call and its result (the count is in + // GeometryViews' line, `allocation failures`). + void note_block_failure(const char* call, VkResult result, VkDeviceSize bytes) { + if (failure_lines_ >= 4) return; + ++failure_lines_; + std::fprintf(stderr, "[rt] d3d12: title buffer block of %llu KiB: %s failed (VkResult %d)\n", + static_cast(bytes >> 10), call, int(result)); + } 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). @@ -102,6 +112,19 @@ class TitleBufferWindows { } public: + // Whether a block at device address `address` of `capacity` bytes can be named by shaders: its offset from + // heap_base (`base`, the arena's address), as a V#'s 48-bit base holds it. With `signed_offsets` (every loaded + // module sign-extends the base) any block within 2^47 of heap_base on either side; otherwise only one above it, at + // a positive offset below 2^47 (the range both decoder generations read alike). + static bool shader_reachable(VkDeviceAddress address, VkDeviceSize capacity, VkDeviceAddress base, + bool signed_offsets) { + constexpr std::uint64_t k47 = 1ull << 47; + if (!address || !capacity || capacity > k47) return false; + const std::uint64_t offset = address - base; // mod 2^64: a block below heap_base is a negative offset + if (offset < k47) return capacity <= k47 - offset; + // Below heap_base: [offset, offset + capacity) must stay within [-2^47, 2^47). + return signed_offsets && offset >= ~(k47 - 1); + } // 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 @@ -206,7 +229,10 @@ class TitleBufferWindows { info.size = b.capacity; info.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; d.share(info); - if (vk.vkCreateBuffer(d.info.device, &info, nullptr, &b.buffer) != VK_SUCCESS) return failed(); + if (const VkResult made = vk.vkCreateBuffer(d.info.device, &info, nullptr, &b.buffer); made != VK_SUCCESS) { + note_block_failure("vkCreateBuffer", made, b.capacity); + return failed(); + } VkMemoryRequirements req{}; vk.vkGetBufferMemoryRequirements(d.info.device, b.buffer, &req); if (req.size > remaining_cap) { @@ -248,14 +274,20 @@ class TitleBufferWindows { static_cast(req.size >> 10)); } void* host{}; - if (b.memory && vk.vkBindBufferMemory(d.info.device, b.buffer, b.memory, 0) == VK_SUCCESS && - vk.vkMapMemory(d.info.device, b.memory, 0, VK_WHOLE_SIZE, 0, &host) == VK_SUCCESS) { + VkResult bound = VK_ERROR_OUT_OF_DEVICE_MEMORY, mapped_result = VK_ERROR_MEMORY_MAP_FAILED; + if (!b.memory) note_block_failure("vkAllocateMemory (DeviceState::allocate)", bound, req.size); + else if ((bound = vk.vkBindBufferMemory(d.info.device, b.buffer, b.memory, 0)) != VK_SUCCESS) + note_block_failure("vkBindBufferMemory", bound, req.size); + else if ((mapped_result = vk.vkMapMemory(d.info.device, b.memory, 0, VK_WHOLE_SIZE, 0, &host)) != VK_SUCCESS) + note_block_failure("vkMapMemory", mapped_result, req.size); + if (b.memory && bound == VK_SUCCESS && mapped_result == VK_SUCCESS) { VkBufferDeviceAddressInfo address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; address.buffer = b.buffer; b.address = vk.vkGetBufferDeviceAddress(d.info.device, &address); const auto biased = b.address - d.arena.address; - // A positive 47-bit offset works with both generations of the translated V# decoder. - if (b.address && biased < (1ull << 47) && b.capacity <= (1ull << 47) - biased) { + bool signed_offsets = false; + if constexpr (requires { d.vsharp_offsets_signed(); }) signed_offsets = d.vsharp_offsets_signed(); + if (shader_reachable(b.address, b.capacity, d.arena.address, signed_offsets)) { b.mapped = static_cast(host); b.reserved_bytes = req.size; b.free_ranges.emplace(0, b.capacity); @@ -276,6 +308,14 @@ class TitleBufferWindows { static_cast(biased)); return take(blocks_.back()); } + if (!address_logged_) { + address_logged_ = true; + std::fprintf(stderr, "[rt] d3d12: title buffer block refused: its device address 0x%llx is not within " + "reach of a V# base from heap_base 0x%llx (%s offsets; later ones are counted, " + "not logged)\n", + static_cast(b.address), + static_cast(d.arena.address), signed_offsets ? "signed" : "unsigned"); + } vk.vkUnmapMemory(d.info.device, b.memory); } vk.vkDestroyBuffer(d.info.device, b.buffer, nullptr); diff --git a/runtime/shims/d3d12_title_image_upload.h b/runtime/shims/d3d12_title_image_upload.h index 6d5674c0ea..f157ccd612 100644 --- a/runtime/shims/d3d12_title_image_upload.h +++ b/runtime/shims/d3d12_title_image_upload.h @@ -2,24 +2,34 @@ #include "xg_xs_layout.h" #include "../src/vulkan_backend.h" +#include "../src/vulkan_title_detile.h" + +#include +#include +#include +#include +#include namespace rt::d3d12 { -// A ring of upload buffers and command buffers per device, used under the title-texture registry lock. -// A whole image (including arrays and compressed mip tails) is detiled into the mapped buffer of the next slot. -// The transfer never re-enters the D3D12 queue's pre-submit callbacks. +// Upload buffers, GPU detile pipeline, and batched command buffers per device, used under title_upload_mutex. +// +// Supports three upload paths, freely mixed inside a single batched command buffer and a single vkQueueSubmit per +// refresh pass: +// 1. cpu_slot: CPU detiled into a host-visible staging slot -> vkCmdCopyBufferToImage (fallback for unmirrored, +// chunk-straddling, 3D-swizzled, or LEONIDA_GPU_DETILE=0 textures). +// 2. mirror_linear: direct vkCmdCopyBufferToImage from TitleMirror's sparse chunk buffer (zero CPU read/detile/stage). +// 3. mirror_detile: GPU compute detile from TitleMirror's sparse chunk buffer into a device-local scratch buffer -> +// vkCmdCopyBufferToImage (zero CPU read/detile/stage). // -// A write no longer waits for its own transfer: the caller (a title thread creating a slot-70 view) waited for the -// GPU at every texture fill, behind all earlier work on the queue, with tracker_mutex_ and submit_mutex_ held, so -// every other submission waited too (speed-26: a title thread 68-88 % inside slot 70). A slot's buffer is reused, -// resized or freed only after its last transfer completed (the slot's timeline value). The image needs no CPU wait: -// later submissions on the queue are ordered after the transfer, other queues wait for it on the GPU, and a retired -// image is destroyed through the deferred queue, after later submissions retire. +// Nothing here waits for the GPU on the CPU (except if all kMaxSlots / kMaxBatchCmds are in flight). A single +// timeline semaphore (`ready_`) orders all transfers behind prior GPU work (retire tickets + TitleMirror sparse bind +// timeline) and orders all consumer queues behind the batch in one wait-submit per consumer queue. class TitleImageUpload { public: VkDeviceSize capacity() const { VkDeviceSize total = 0; - for (const auto& slot : slots_) total += slot.capacity; + for (const auto& slot : slots_) total += slot->capacity; return total; } @@ -27,25 +37,135 @@ class TitleImageUpload { void release(Device& d) { auto& vk = d.context->vk; wait_all(d); - for (auto& slot : slots_) release_buffer(d, slot); + if (detile_) { + detile_->release(); + detile_.reset(); + } + for (auto& slot : slots_) release_buffer(d, *slot); + batch_cmds_.clear(); if (pool_) vk.vkDestroyCommandPool(d.info.device, pool_, nullptr); - if (ready_) vk.vkDestroySemaphore(d.info.device, ready_, nullptr); + if (ready_) { + { + std::lock_guard lock(d.context->submit_mutex()); + d.context->clear_title_upload_locked(ready_); + d.context->retire_queue_idle_locked(ready_); + } + vk.vkDestroySemaphore(d.info.device, ready_, nullptr); + } pool_ = VK_NULL_HANDLE; - for (auto& slot : slots_) slot.command = VK_NULL_HANDLE; + for (auto& slot : slots_) slot->command = VK_NULL_HANDLE; ready_ = VK_NULL_HANDLE; + detile_init_attempted_ = false; } - // Uploads the mips from `from` on; `tiled` then needs only mip_chain_bytes(layout, from) bytes. + struct Slot; + + // Converts rt::xg_xs::Texture into the portable leonida::TitleDetileDesc consumed by TitleDetilePipeline. + static bool make_detile_desc(const xg_xs::Texture& layout, leonida::TitleDetileDesc& out) { + out = {}; + switch (layout.mode) { + case xg_xs::kLinear: out.mode = leonida::TitleDetileMode::linear; break; + case xg_xs::k4kbS: out.mode = leonida::TitleDetileMode::sw_4kb_s; break; + case xg_xs::k64kbS: out.mode = leonida::TitleDetileMode::sw_64kb_s; break; + case xg_xs::k64kbD: out.mode = leonida::TitleDetileMode::sw_64kb_d; break; + default: return false; + } + if (layout.slab_bytes || layout.tile_depth != 1) return false; + const auto mips = layout.layout.mips; + if (!mips || mips > xg_xs::kMaxMips) return false; + out.dimension = layout.layout.dimension; + out.element_bytes = layout.format.bytes; + out.block_side = layout.format.side; + out.tile_width = layout.tile_width; + out.tile_height = layout.tile_height; + out.array_layers = layout.array; + out.total_size = layout.layout.size; + out.slice_bytes = layout.layout.plane[0].slice_bytes; + out.mips.resize(mips); + const xg_xs::ElementAddress addr(layout); + for (unsigned level = 0; level < mips; ++level) { + const auto& src = layout.layout.plane[0].mips[level]; + auto& dst = out.mips[level]; + dst.offset = src.offset; + dst.width_elements = src.width_elements; + dst.height_elements = src.height_elements; + dst.width_texels = src.width_texels; + dst.height_texels = src.height_texels; + dst.depth = src.depth; + dst.padded_width = src.padded_width; + dst.padded_height = src.padded_height; + dst.pitch_bytes = src.pitch_bytes; + dst.pitch_texels = src.pitch_texels; + dst.in_tail = src.in_tail != 0; + if (dst.in_tail) { + const auto tail = addr.tail_origin(src); + dst.tail_x = tail[0]; + dst.tail_y = tail[1]; + } + } + return true; + } + + enum class UploadKind : std::uint8_t { cpu_slot, mirror_linear, mirror_detile }; + + // Determines whether a mirrored texture in a single TitleMirror chunk can take GPU direct copy or GPU + // compute detile. Returns true and sets `out_kind` when supported; false means use CPU fallback. template - bool write(Device& d, leonida::ResourceId id, const leonida::ResourceBinding& image, - const xg_xs::Texture& layout, const std::uint8_t* tiled, std::vector& columns, - bool inspect, bool& nonzero, unsigned from = 0) { + bool can_gpu_upload(Device& d, const leonida::ResourceBinding& image, const xg_xs::Texture& layout, + VkDeviceSize mirror_offset, VkDeviceSize mirror_chunk_size, UploadKind& out_kind) { + if (!leonida::title_gpu_detile_enabled()) return false; + const auto block = leonida::copy_block_format(image, VK_IMAGE_ASPECT_COLOR_BIT); + if (!block.bytes || block.bytes != layout.format.bytes || block.block != layout.format.side) return false; + leonida::TitleDetileDesc desc; + if (!make_detile_desc(layout, desc)) return false; + if (desc.mode == leonida::TitleDetileMode::linear) { + if (leonida::TitleDetilePipeline::can_direct_linear( + desc, mirror_offset, mirror_chunk_size, image.width, image.height, image.depth, image.mip_levels, + image.array_layers, image.volume)) { + out_kind = UploadKind::mirror_linear; + return true; + } + return false; + } + auto* pipe = ensure_detile(d); + if (pipe && pipe->can_gpu_detile(desc, mirror_offset, mirror_chunk_size, image.width, image.height, + image.mip_levels, image.array_layers, image.volume)) { + out_kind = UploadKind::mirror_detile; + return true; + } + return false; + } + + struct BatchItem { + UploadKind kind = UploadKind::cpu_slot; + leonida::ResourceId id{}; + leonida::ResourceBinding image{}; + const xg_xs::Texture* layout = nullptr; + unsigned from = 0; + // cpu_slot: + Slot* slot = nullptr; + // mirror_linear / mirror_detile: + VkBuffer mirror_buffer = VK_NULL_HANDLE; + VkDeviceSize mirror_offset = 0; + VkDeviceSize mirror_chunk_size = 0; + VkSemaphore mirror_timeline = VK_NULL_HANDLE; + std::uint64_t mirror_value = 0; + // Set by commit_batch(): + bool ok = false; + }; + + // One CPU-staged upload in three steps (uploads the mips from `from` on; `tiled` then needs only + // mip_chain_bytes(layout, from) bytes): + // reserve (serial): the copy regions, a free slot and its buffer; + // fill (any thread, one slot each): the detile into the slot's mapped buffer; + // commit / commit_batch (serial): the transfer recorded and submitted; or unreserve when unchanged. + template + Slot* reserve(Device& d, const leonida::ResourceBinding& image, const xg_xs::Texture& layout, unsigned from = 0) { const auto block = leonida::copy_block_format(image, VK_IMAGE_ASPECT_COLOR_BIT); const auto mips = layout.layout.mips; const auto layers = layout.array; if (!block.bytes || block.bytes != layout.format.bytes || from >= mips || mips > image.mip_levels || - !layers || layers > image.array_layers) return false; - + !layers || layers > image.array_layers) return nullptr; regions_.clear(); VkDeviceSize bytes = 0; for (unsigned layer = 0; layer < layers; ++layer) { @@ -57,21 +177,31 @@ class TitleImageUpload { image.volume ? std::max(1u, image.depth >> level) : 1u}; if (mip.width_elements != (copy.imageExtent.width + block.block - 1) / block.block || mip.height_elements != (copy.imageExtent.height + block.block - 1) / block.block || - (image.volume && mip.depth != copy.imageExtent.depth)) return false; + (image.volume && mip.depth != copy.imageExtent.depth)) return nullptr; // Vulkan requires offsets aligned to four bytes and to the texel block size. const auto align = 4u * block.bytes; copy.bufferOffset = bytes + (align - bytes % align) % align; const VkDeviceSize row = VkDeviceSize(mip.width_elements) * block.bytes; const VkDeviceSize slice = row * mip.height_elements; - if (slice > UINT32_MAX || (UINT64_MAX - copy.bufferOffset) / copy.imageExtent.depth < slice) return false; + if (slice > UINT32_MAX || (UINT64_MAX - copy.bufferOffset) / copy.imageExtent.depth < slice) + return nullptr; bytes = copy.bufferOffset + slice * copy.imageExtent.depth; regions_.push_back(copy); } } - Slot& slot = slots_[next_]; - if (!prepare(d, slot, bytes)) return false; - next_ = (next_ + 1) % kSlots; - for (const auto& copy : regions_) { + Slot* slot = take_slot(d, bytes); + if (!slot || !prepare(d, *slot, bytes)) return nullptr; + slot->regions = regions_; + slot->reserved = true; + return slot; + } + + // Thread-safe for distinct slots: reads only `tiled` and writes only the slot's buffer and `columns`. + static void fill(Slot& slot, const leonida::ResourceBinding& image, const xg_xs::Texture& layout, + const std::uint8_t* tiled, std::vector& columns, bool inspect, bool& nonzero) { + leonida::submit_phases::note_change(leonida::submit_phases::change_textures); // not a "submit floor" one + const auto block = leonida::copy_block_format(image, VK_IMAGE_ASPECT_COLOR_BIT); + for (const auto& copy : slot.regions) { const auto level = copy.imageSubresource.mipLevel; const auto& mip = layout.layout.plane[0].mips[level]; const auto row = mip.width_elements * block.bytes, slice = row * mip.height_elements; @@ -81,37 +211,88 @@ class TitleImageUpload { nonzero = std::any_of(dst, dst + VkDeviceSize(slice) * copy.imageExtent.depth, [](std::uint8_t c) { return c != 0; }); } + } - const VkImageSubresourceRange range{VK_IMAGE_ASPECT_COLOR_BIT, from, mips - from, 0, layers}; - const auto result = d.context->write_staged_title_image(id, range, [&](const leonida::ReplayFunctions& replay, - const leonida::LayoutPieces& pieces) { - auto& vk = d.context->vk; - VkResult r = vk.vkResetCommandBuffer(slot.command, 0); - if (r != VK_SUCCESS) return r; - VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; - begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; - if ((r = vk.vkBeginCommandBuffer(slot.command, &begin)) != VK_SUCCESS) return r; - // All texels of every mip/layer named in range are overwritten. The CPU no longer waits for a transfer, - // so the barrier orders this one after all earlier work on the queue: earlier reads of the image and an - // earlier transfer into it, still running. - leonida::detail::image_barrier(replay, slot.command, image, range, VK_IMAGE_LAYOUT_UNDEFINED, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); - vk.vkCmdCopyBufferToImage(slot.command, slot.buffer, image.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - static_cast(regions_.size()), regions_.data()); - for (const auto& piece : pieces) - leonida::detail::image_barrier(replay, slot.command, image, piece.range, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - piece.layout == VK_IMAGE_LAYOUT_UNDEFINED ? VK_IMAGE_LAYOUT_GENERAL : piece.layout, - VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); - if ((r = vk.vkEndCommandBuffer(slot.command)) != VK_SUCCESS) return r; - return submit(d, slot); - }); + static void unreserve(Slot& slot) { slot.reserved = false; } + + // Commits a single CPU-staged slot (used by fill_title_texture / fill_unlocked). + template + bool commit(Device& d, leonida::ResourceId id, const leonida::ResourceBinding& image, + const xg_xs::Texture& layout, Slot& slot, unsigned from = 0) { + slot.reserved = false; + const VkImageSubresourceRange range{VK_IMAGE_ASPECT_COLOR_BIT, from, layout.layout.mips - from, 0, layout.array}; + const auto result = d.context->write_staged_title_image( + id, range, + [&](const leonida::ReplayFunctions& replay, const leonida::LayoutPieces& pieces) -> VkResult { + auto& vk = d.context->vk; + VkResult r = vk.vkResetCommandBuffer(slot.command, 0); + if (r != VK_SUCCESS) return r; + VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; + begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + if ((r = vk.vkBeginCommandBuffer(slot.command, &begin)) != VK_SUCCESS) return r; + leonida::detail::image_barrier(replay, slot.command, image, range, VK_IMAGE_LAYOUT_UNDEFINED, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, + VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); + vk.vkCmdCopyBufferToImage(slot.command, slot.buffer, image.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + static_cast(slot.regions.size()), slot.regions.data()); + for (const auto& piece : pieces) + leonida::detail::image_barrier(replay, slot.command, image, piece.range, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + piece.layout == VK_IMAGE_LAYOUT_UNDEFINED ? VK_IMAGE_LAYOUT_GENERAL : piece.layout, + VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); + return vk.vkEndCommandBuffer(slot.command); + }, + [&](const auto& waits) -> VkResult { + const VkResult sr = submit_cmd(d, slot.command, waits, VK_NULL_HANDLE, 0); + if (sr == VK_SUCCESS) slot.value = value_; + return sr; + }); return result == VK_SUCCESS; } -private: - static constexpr unsigned kSlots = 4; + // Commits a batch of CPU-staged, linear-mirror, and GPU-detiled uploads into a single command buffer and single + // vkQueueSubmit (+ one wait-submit per consumer queue), with coalesced image and memory barriers. + template + void commit_batch(Device& d, std::vector& items) { + if (items.empty()) return; + for (auto& item : items) { + item.ok = false; + if (item.kind == UploadKind::cpu_slot && item.slot) item.slot->reserved = false; + } + if (!ensure_shared(d)) return; + + // Partition into safe sub-batches: split only if the same VkImage appears twice so all transitions & copies + // within a sub-batch operate on disjoint images and commit atomically under write_staged_title_images(). + std::size_t start = 0; + while (start < items.size()) { + std::size_t end = start; + batch_seen_images_.clear(); + while (end < items.size()) { + const VkImage img = items[end].image.image; + if (end > start && + std::find(batch_seen_images_.begin(), batch_seen_images_.end(), img) != batch_seen_images_.end()) + break; + batch_seen_images_.push_back(img); + ++end; + } + commit_sub_batch(d, items.data() + start, end - start); + start = end; + } + } + + // Uploads the mips from `from` on; `tiled` then needs only mip_chain_bytes(layout, from) bytes. + template + bool write(Device& d, leonida::ResourceId id, const leonida::ResourceBinding& image, + const xg_xs::Texture& layout, const std::uint8_t* tiled, std::vector& columns, + bool inspect, bool& nonzero, unsigned from = 0) { + Slot* slot = reserve(d, image, layout, from); + if (!slot) return false; + fill(*slot, image, layout, tiled, columns, inspect, nonzero); + return commit(d, id, image, layout, *slot, from); + } + + static constexpr std::size_t kMaxSlots = 64; + static constexpr std::size_t kMaxBatchCmds = 64; struct Slot { VkBuffer buffer{}; VkDeviceMemory memory{}; @@ -119,31 +300,391 @@ class TitleImageUpload { VkDeviceSize capacity = 0; VkCommandBuffer command{}; std::uint64_t value = 0; // the ready_ value its last transfer signals; 0: none submitted + bool reserved = false; // between reserve() and commit()/unreserve() + std::vector regions; + }; + +private: + struct BatchCmd { + VkCommandBuffer command = VK_NULL_HANDLE; + std::uint64_t value = 0; + }; + + struct PreparedItem { + std::size_t index = 0; + VkImageSubresourceRange range{}; + VkBuffer src_buffer = VK_NULL_HANDLE; + std::vector owned_regions; // non-empty for mirror_linear / mirror_detile + const std::vector* external_regions = nullptr; // non-null for cpu_slot (slot->regions) + const std::vector& copy_regions() const { + return external_regions ? *external_regions : owned_regions; + } }; - // Waits (outside every lock but the registry's) until the slot's last transfer has completed. template - bool wait_slot(Device& d, Slot& slot) { - if (!slot.value || !ready_) return true; + leonida::TitleDetilePipeline* ensure_detile(Device& d) { + if (detile_) return detile_.get(); + if (detile_init_attempted_) return nullptr; + detile_init_attempted_ = true; + if (!d.info.get_instance_proc || !d.info.instance || !d.info.physical || !d.info.device) return nullptr; + const auto get_dev_proc = reinterpret_cast( + d.info.get_instance_proc(d.info.instance, "vkGetDeviceProcAddr")); + const auto get_props = reinterpret_cast( + d.info.get_instance_proc(d.info.instance, "vkGetPhysicalDeviceProperties")); + if (!get_dev_proc || !get_props) return nullptr; + VkPhysicalDeviceProperties props{}; + get_props(d.info.physical, &props); + detile_ = std::make_unique( + get_dev_proc, d.info.device, props.limits, + [&d](const VkMemoryRequirements& req, VkMemoryPropertyFlags required, VkMemoryPropertyFlags preferred) { + return d.allocate(req, required, preferred); + }); + return detile_.get(); + } + + template + bool ensure_shared(Device& d) { auto& vk = d.context->vk; - std::uint64_t reached = 0; - if (vk.vkGetSemaphoreCounterValue && vk.vkGetSemaphoreCounterValue(d.info.device, ready_, &reached) == VK_SUCCESS && - reached >= slot.value) { - slot.value = 0; - return true; + const auto dev = d.info.device; + if (!pool_) { + VkCommandPoolCreateInfo pool{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; + pool.queueFamilyIndex = d.info.queue_family; + pool.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; + if (vk.vkCreateCommandPool(dev, &pool, nullptr, &pool_) != VK_SUCCESS) return false; + } + if (!ready_) { + VkSemaphoreTypeCreateInfo timeline{VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO}; + timeline.semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE; + VkSemaphoreCreateInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, &timeline}; + if (vk.vkCreateSemaphore(dev, &info, nullptr, &ready_) != VK_SUCCESS) return false; } + return true; + } + + template + std::uint64_t poll_ready(Device& d) const { + if (!ready_) return 0; + auto& vk = d.context->vk; + std::uint64_t reached = 0; + if (vk.vkGetSemaphoreCounterValue && + vk.vkGetSemaphoreCounterValue(d.info.device, ready_, &reached) == VK_SUCCESS) + return reached; + return 0; + } + + template + bool wait_value(Device& d, std::uint64_t target) { + if (!target || !ready_) return true; + if (poll_ready(d) >= target) return true; VkSemaphoreWaitInfo done{VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO}; done.semaphoreCount = 1; done.pSemaphores = &ready_; - done.pValues = &slot.value; - if (vk.vkWaitSemaphores(d.info.device, &done, UINT64_MAX) != VK_SUCCESS) return false; + done.pValues = ⌖ + return d.context->vk.vkWaitSemaphores(d.info.device, &done, UINT64_MAX) == VK_SUCCESS; + } + + template + BatchCmd* take_batch_cmd(Device& d, std::uint64_t& reached) { + reached = poll_ready(d); + BatchCmd* oldest = nullptr; + for (auto& b : batch_cmds_) { + if (!b.value || b.value <= reached) { + b.value = 0; + return &b; + } + if (!oldest || b.value < oldest->value) oldest = &b; + } + if (batch_cmds_.size() < kMaxBatchCmds) { + VkCommandBuffer cmd = VK_NULL_HANDLE; + VkCommandBufferAllocateInfo alloc{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; + alloc.commandPool = pool_; + alloc.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; + alloc.commandBufferCount = 1; + if (d.context->vk.vkAllocateCommandBuffers(d.info.device, &alloc, &cmd) != VK_SUCCESS) return nullptr; + batch_cmds_.push_back({cmd, 0}); + return &batch_cmds_.back(); + } + if (!oldest || !wait_value(d, oldest->value)) return nullptr; + reached = std::max(reached, oldest->value); + oldest->value = 0; + return oldest; + } + + template + void commit_sub_batch(Device& d, BatchItem* items, std::size_t count) { + if (!count) return; + std::uint64_t reached = 0; + BatchCmd* bcmd = take_batch_cmd(d, reached); + if (!bcmd) return; + + // 1. Prepare GPU detile scratch allocations & compute dispatches (if any mirror_detile items). + std::uint32_t detile_sets = 0; + VkDeviceSize total_scratch = 0; + bool has_detile_items = false; + for (std::size_t i = 0; i < count; ++i) { + if (items[i].kind == UploadKind::mirror_detile) { + has_detile_items = true; + break; + } + } + leonida::TitleDetilePipeline* pipe = nullptr; + if (has_detile_items) { + if (batch_descs_.size() < count) batch_descs_.resize(count); + batch_dst_bases_.assign(count, 0); + batch_dst_ends_.assign(count, 0); + if (batch_detile_regions_.size() < count) batch_detile_regions_.resize(count); + for (std::size_t i = 0; i < count; ++i) batch_detile_regions_[i].clear(); + + for (std::size_t i = 0; i < count; ++i) { + if (items[i].kind != UploadKind::mirror_detile) continue; + pipe = ensure_detile(d); + if (!pipe || !items[i].layout || !make_detile_desc(*items[i].layout, batch_descs_[i])) continue; + const VkDeviceSize item_align = + (std::max)(pipe->min_storage_alignment(), VkDeviceSize(4u) * batch_descs_[i].element_bytes); + batch_dst_bases_[i] = leonida::detail::align_up_size(total_scratch, item_align); + if (!leonida::TitleDetilePipeline::build_scratch_regions(batch_descs_[i], batch_dst_bases_[i], + items[i].image.width, items[i].image.height, + batch_detile_regions_[i], + batch_dst_ends_[i])) { + batch_detile_regions_[i].clear(); + continue; + } + total_scratch = batch_dst_ends_[i]; + ++detile_sets; + } + } + + leonida::TitleDetilePipeline::ScratchSlot* scratch_slot = nullptr; + batch_detile_sets_.clear(); + std::size_t next_detile_set = 0; + if (detile_sets > 0 && pipe) { + scratch_slot = pipe->acquire_scratch(reached, total_scratch, detile_sets); + if (!scratch_slot) { + // All scratch slots in flight: wait ONLY for the oldest in-flight scratch slot instead of draining the + // entire upload pipeline (`value_`). + const std::uint64_t oldest_scratch = pipe->oldest_in_flight_scratch_value(); + if (oldest_scratch > reached && wait_value(d, oldest_scratch)) { + reached = (std::max)(reached, oldest_scratch); + scratch_slot = pipe->acquire_scratch(reached, total_scratch, detile_sets); + } + } + if (scratch_slot && !pipe->allocate_descriptor_sets(*scratch_slot, detile_sets, batch_detile_sets_)) { + scratch_slot = nullptr; + } + } + + // 2. Build prepared list of executable items (zero self-referential pointers: copy_regions() resolves safely + // after vector moves/reallocations). + batch_prepared_.clear(); + batch_prepared_.reserve(count); + batch_targets_.clear(); + batch_targets_.reserve(count); + batch_dispatches_.clear(); + batch_descriptor_updates_.clear(); + batch_descriptor_updates_.reserve(detile_sets); + bool any_mirror = false; + bool any_detile = false; + VkSemaphore mirror_sem = VK_NULL_HANDLE; + std::uint64_t mirror_val = 0; + + for (std::size_t i = 0; i < count; ++i) { + BatchItem& item = items[i]; + if (!item.layout) continue; + PreparedItem prep{}; + prep.index = i; + prep.range = {VK_IMAGE_ASPECT_COLOR_BIT, item.from, item.layout->layout.mips - item.from, 0, item.layout->array}; + if (item.kind == UploadKind::cpu_slot) { + if (!item.slot) continue; + prep.src_buffer = item.slot->buffer; + prep.external_regions = &item.slot->regions; + } else if (item.kind == UploadKind::mirror_linear) { + leonida::TitleDetileDesc lin_desc; + if (!make_detile_desc(*item.layout, lin_desc) || + !leonida::TitleDetilePipeline::build_linear_regions(lin_desc, item.mirror_offset, item.image.width, + item.image.height, item.image.depth, + item.image.volume, prep.owned_regions)) + continue; + prep.src_buffer = item.mirror_buffer; + any_mirror = true; + if (item.mirror_timeline && item.mirror_value > mirror_val) { + mirror_sem = item.mirror_timeline; + mirror_val = item.mirror_value; + } + } else { // mirror_detile + if (!scratch_slot || !pipe || batch_detile_regions_[i].empty() || + next_detile_set >= batch_detile_sets_.size()) + continue; + const VkDescriptorSet pre_set = batch_detile_sets_[next_detile_set++]; + const std::size_t disp_start = batch_dispatches_.size(); + if (!pipe->prepare_texture(*scratch_slot, item.mirror_buffer, item.mirror_offset, batch_descs_[i], + batch_dst_bases_[i], batch_dst_ends_[i], batch_detile_regions_[i], + batch_dispatches_, &batch_descriptor_updates_, pre_set)) { + batch_dispatches_.resize(disp_start); + continue; + } + prep.src_buffer = scratch_slot->buffer; + prep.owned_regions = std::move(batch_detile_regions_[i]); + any_mirror = true; + any_detile = true; + if (item.mirror_timeline && item.mirror_value > mirror_val) { + mirror_sem = item.mirror_timeline; + mirror_val = item.mirror_value; + } + } + batch_targets_.push_back({item.id, prep.range}); + batch_prepared_.push_back(std::move(prep)); + } + + if (batch_prepared_.empty()) return; + if (pipe && !batch_descriptor_updates_.empty()) pipe->flush_descriptor_updates(batch_descriptor_updates_); + if (any_mirror) leonida::submit_phases::note_change(leonida::submit_phases::change_textures); + + // 3. Atomically capture all layouts and record under tracker_mutex_ alone (submit_mutex_ is acquired only + // around the single vkQueueSubmit, and LayoutTracker updates ONLY on VK_SUCCESS). + const std::size_t n = batch_prepared_.size(); + const auto r = d.context->write_staged_title_images( + std::span(batch_targets_.data(), batch_targets_.size()), + [&](const leonida::ReplayFunctions&, const std::vector& all_pieces) -> VkResult { + auto& vk = d.context->vk; + VkResult res = vk.vkResetCommandBuffer(bcmd->command, 0); + if (res != VK_SUCCESS) return res; + VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; + begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + if ((res = vk.vkBeginCommandBuffer(bcmd->command, &begin)) != VK_SUCCESS) return res; + + if (any_mirror) { + VkMemoryBarrier mem{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + mem.srcAccessMask = + VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT | VK_ACCESS_MEMORY_WRITE_BIT; + mem.dstAccessMask = + VkAccessFlags(any_detile ? VK_ACCESS_SHADER_READ_BIT : 0u) | VK_ACCESS_TRANSFER_READ_BIT; + const VkPipelineStageFlags dst_stage = + VkPipelineStageFlags(any_detile ? VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT : 0u) | + VK_PIPELINE_STAGE_TRANSFER_BIT; + vk.vkCmdPipelineBarrier(bcmd->command, + VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, + dst_stage, 0, 1, &mem, 0, nullptr, 0, nullptr); + } + + pre_barriers_.clear(); + pre_barriers_.reserve(n); + for (const auto& p : batch_prepared_) { + VkImageMemoryBarrier b{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; + b.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT; + b.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + b.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; + b.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + b.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + b.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + b.image = items[p.index].image.image; + b.subresourceRange = p.range; + pre_barriers_.push_back(b); + } + vk.vkCmdPipelineBarrier(bcmd->command, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, + static_cast(pre_barriers_.size()), pre_barriers_.data()); + + if (any_detile && !batch_dispatches_.empty()) { + detile_->emit_dispatches(bcmd->command, batch_dispatches_); + VkMemoryBarrier cs_to_xfer{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + cs_to_xfer.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; + cs_to_xfer.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; + vk.vkCmdPipelineBarrier(bcmd->command, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1, &cs_to_xfer, 0, nullptr, 0, nullptr); + } + + for (const auto& p : batch_prepared_) { + const auto& regs = p.copy_regions(); + vk.vkCmdCopyBufferToImage(bcmd->command, p.src_buffer, items[p.index].image.image, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + static_cast(regs.size()), regs.data()); + } + + post_barriers_.clear(); + post_barriers_.reserve(n); + for (std::size_t k = 0; k < n; ++k) { + const auto& p = batch_prepared_[k]; + for (const auto& piece : all_pieces[k]) { + VkImageMemoryBarrier b{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; + b.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + b.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; + b.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + b.newLayout = + piece.layout == VK_IMAGE_LAYOUT_UNDEFINED ? VK_IMAGE_LAYOUT_GENERAL : piece.layout; + b.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + b.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + b.image = items[p.index].image.image; + b.subresourceRange = piece.range; + post_barriers_.push_back(b); + } + } + vk.vkCmdPipelineBarrier(bcmd->command, VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 0, nullptr, 0, nullptr, + static_cast(post_barriers_.size()), post_barriers_.data()); + + return vk.vkEndCommandBuffer(bcmd->command); + }, + [&](const auto& waits) -> VkResult { + const VkResult sr = submit_cmd(d, bcmd->command, waits, mirror_sem, mirror_val); + if (sr == VK_SUCCESS) { + bcmd->value = value_; + if (any_detile && scratch_slot) scratch_slot->value = value_; + for (const auto& p : batch_prepared_) { + auto& it = items[p.index]; + if (it.kind == UploadKind::cpu_slot && it.slot) it.slot->value = value_; + } + } + return sr; + }); + if (r == VK_SUCCESS) { + for (const auto& p : batch_prepared_) items[p.index].ok = true; + } + } + + // Waits (outside every lock but title_upload_mutex) until the slot's last transfer has completed. + template + bool wait_slot(Device& d, Slot& slot) { + if (!slot.value || !ready_) return true; + if (!wait_value(d, slot.value)) return false; slot.value = 0; return true; } template void wait_all(Device& d) { - for (auto& slot : slots_) wait_slot(d, slot); + for (auto& slot : slots_) wait_slot(d, *slot); + for (auto& b : batch_cmds_) { + if (b.value && wait_value(d, b.value)) b.value = 0; + } + if (value_ && ready_) wait_value(d, value_); + } + + // Best-fit idle slot with capacity >= bytes (smallest fit to avoid burning large slots on small uploads); + // otherwise the largest idle slot (grown in place so smaller slots stay reusable), a new slot up to kMaxSlots, + // or the oldest in-flight slot waited for. + template + Slot* take_slot(Device& d, VkDeviceSize bytes) { + const std::uint64_t reached = poll_ready(d); + Slot* best_fit = nullptr; + Slot* best_grow = nullptr; + Slot* oldest = nullptr; + for (auto& slot : slots_) { + if (slot->reserved) continue; + if (!slot->value || slot->value <= reached) { + slot->value = 0; + if (slot->capacity >= bytes) { + if (!best_fit || slot->capacity < best_fit->capacity) best_fit = slot.get(); + } else if (!best_grow || slot->capacity > best_grow->capacity) { + best_grow = slot.get(); + } + continue; + } + if (!oldest || slot->value < oldest->value) oldest = slot.get(); + } + if (best_fit) return best_fit; + if (best_grow) return best_grow; + if (slots_.size() < kMaxSlots) return slots_.emplace_back(std::make_unique()).get(); + return oldest && wait_slot(d, *oldest) ? oldest : nullptr; } template @@ -161,12 +702,7 @@ class TitleImageUpload { bool prepare(Device& d, Slot& slot, VkDeviceSize size) { auto& vk = d.context->vk; const auto dev = d.info.device; - if (!pool_) { - VkCommandPoolCreateInfo pool{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; - pool.queueFamilyIndex = d.info.queue_family; - pool.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; - if (vk.vkCreateCommandPool(dev, &pool, nullptr, &pool_) != VK_SUCCESS) return false; - } + if (!ensure_shared(d)) return false; if (!slot.command) { VkCommandBufferAllocateInfo alloc{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; alloc.commandPool = pool_; @@ -174,22 +710,15 @@ class TitleImageUpload { alloc.commandBufferCount = 1; if (vk.vkAllocateCommandBuffers(dev, &alloc, &slot.command) != VK_SUCCESS) return false; } - if (!ready_) { - VkSemaphoreTypeCreateInfo timeline{VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO}; - timeline.semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE; - VkSemaphoreCreateInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, &timeline}; - if (vk.vkCreateSemaphore(dev, &info, nullptr, &ready_) != VK_SUCCESS) return false; - for (const auto* qs : {&d.info.command_queues, &d.info.compute_queues, &d.info.copy_queues}) - for (auto q : *qs) - if (q && q != d.info.queue && std::find(consumers_.begin(), consumers_.end(), q) == consumers_.end()) - consumers_.push_back(q); - } // The slot's buffer and command buffer are rewritten below and in write(): its last transfer must be done. if (!wait_slot(d, slot)) return false; if (size <= slot.capacity) return true; release_buffer(d, slot); + // Round up to power of two (min 256 KiB) to avoid frequent VkBuffer/VkDeviceMemory reallocation churn. + VkDeviceSize alloc_size = std::max(256ull << 10, size); + if (alloc_size < (UINT64_MAX >> 1)) alloc_size = std::bit_ceil(alloc_size); VkBufferCreateInfo buffer{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; - buffer.size = size; + buffer.size = alloc_size; buffer.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; if (vk.vkCreateBuffer(dev, &buffer, nullptr, &slot.buffer) != VK_SUCCESS) return false; VkMemoryRequirements req{}; @@ -202,54 +731,94 @@ class TitleImageUpload { return false; } slot.mapped = static_cast(map); - slot.capacity = size; + slot.capacity = alloc_size; return true; } - // Under tracker_mutex_ and submit_mutex_ (write_staged_title_image): submits the transfer and the other queues' - // GPU-side waits for it, and returns without waiting for it on the CPU. - template - VkResult submit(Device& d, Slot& slot) { - auto& vk = d.context->vk; + // Under tracker_mutex_ and submit_mutex_ (write_staged_title_image): submits `command`, waiting on the GPU for + // `waits` (every queue's submitted work) and optionally `mirror_sem` at `mirror_val` (pending TitleMirror sparse + // binds), signals `ready_`, and queues one GPU-side wait per consumer queue without waiting on the CPU. + template + VkResult submit_cmd(Device& d, VkCommandBuffer command, const Waits& waits, VkSemaphore mirror_sem, + std::uint64_t mirror_val) { ++value_; + wait_semaphores_.clear(); + wait_values_.clear(); + for (const auto& [semaphore, value] : waits) { + wait_semaphores_.push_back(semaphore); + wait_values_.push_back(value); + } + if (mirror_sem) { + // Re-check under submit_mutex_ so any mirror bind published after commit_batch() snapshotted mirror_val + // is waited on before this upload reads from TitleMirror chunks. + VkSemaphore latest_sem = VK_NULL_HANDLE; + std::uint64_t latest_val = 0; + d.context->mirror_bind_locked(latest_sem, latest_val); + if (latest_sem == mirror_sem && latest_val > mirror_val) mirror_val = latest_val; + } + if (mirror_sem && mirror_val) { + bool merged = false; + for (std::size_t i = 0; i < wait_semaphores_.size(); ++i) { + if (wait_semaphores_[i] == mirror_sem) { + if (mirror_val > wait_values_[i]) wait_values_[i] = mirror_val; + merged = true; + break; + } + } + if (!merged) { + wait_semaphores_.push_back(mirror_sem); + wait_values_.push_back(mirror_val); + } + } + wait_stages_.assign(wait_semaphores_.size(), VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); VkTimelineSemaphoreSubmitInfo timeline{VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO}; timeline.signalSemaphoreValueCount = 1; timeline.pSignalSemaphoreValues = &value_; + timeline.waitSemaphoreValueCount = static_cast(wait_values_.size()); + timeline.pWaitSemaphoreValues = wait_values_.data(); VkSubmitInfo transfer{VK_STRUCTURE_TYPE_SUBMIT_INFO, &timeline}; + transfer.waitSemaphoreCount = static_cast(wait_semaphores_.size()); + transfer.pWaitSemaphores = wait_semaphores_.data(); + transfer.pWaitDstStageMask = wait_stages_.data(); transfer.commandBufferCount = 1; - transfer.pCommandBuffers = &slot.command; + transfer.pCommandBuffers = &command; transfer.signalSemaphoreCount = 1; transfer.pSignalSemaphores = &ready_; - // Through the compile gate, as every other submission: it waits here, not in the driver, while a pipeline - // create holds it, and the caller observes a device loss from it. auto r = d.context->queue_submit(d.info.queue, 1, &transfer, VK_NULL_HANDLE); if (r != VK_SUCCESS) { - --value_; // nothing signalled it + --value_; return r; } - // No CPU wait: the slot's buffer is reused only after this value (wait_slot), the image's later reads are - // ordered behind the transfer on the GPU, and a retired image is destroyed through the deferred queue. - slot.value = value_; - // GPU writes become visible to later submissions on every other queue. The primary queue has the image barrier. - VkTimelineSemaphoreSubmitInfo acquire{VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO}; - acquire.waitSemaphoreValueCount = 1; - acquire.pWaitSemaphoreValues = &value_; - VkPipelineStageFlags stages = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; - VkSubmitInfo wait{VK_STRUCTURE_TYPE_SUBMIT_INFO, &acquire}; - wait.waitSemaphoreCount = 1; - wait.pWaitSemaphores = &ready_; - wait.pWaitDstStageMask = &stages; - for (auto q : consumers_) - if ((r = d.context->queue_submit(q, 1, &wait, VK_NULL_HANDLE)) != VK_SUCCESS) return r; + // Record this upload in retire_tickets_ under submit_mutex_ so note_mirror_bind() covers in-flight GPU mirror + // reads and freed TitleMirror homes cannot be reused while this upload is executing, and publish (ready_, value_) + // lazily so each consumer queue waits on it on its next command-buffer submit_multi() (zero empty submits). + d.context->record_submit_locked(ready_, value_); + d.context->note_title_upload_locked(ready_, value_); return VK_SUCCESS; } - Slot slots_[kSlots]; - unsigned next_ = 0; + std::vector> slots_; + std::vector batch_cmds_; + std::unique_ptr detile_; + bool detile_init_attempted_ = false; + std::vector wait_semaphores_; + std::vector wait_values_; + std::vector wait_stages_; + std::vector batch_seen_images_; + std::vector batch_prepared_; + std::vector batch_targets_; + std::vector batch_dispatches_; + std::vector batch_detile_sets_; + std::vector batch_descriptor_updates_; + std::vector batch_descs_; + std::vector batch_dst_bases_; + std::vector batch_dst_ends_; + std::vector> batch_detile_regions_; + std::vector pre_barriers_; + std::vector post_barriers_; VkCommandPool pool_{}; VkSemaphore ready_{}; std::uint64_t value_ = 0; - std::vector consumers_; std::vector regions_; }; diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index de623b6040..d542339e91 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -34,6 +34,7 @@ #include "../src/command_list_epochs.h" #include "../src/value_write_sink.h" #include "../src/address_guard.h" +#include "../src/arena_backing.h" #include "../src/arena_blocks.h" #include "../src/gfx10_descriptors.h" #include "../src/depth24_fragment.h" @@ -62,13 +63,19 @@ #include "../src/resource_detile.h" #include "../src/console_texture_layout.h" #include "../src/shader_library.h" +#include "../src/literal_sampler_spec.h" #include "../src/shadow_keep.h" #include "../src/dstorage_trace.h" #include "../src/title_page_watch.h" +#include "../src/title_mirror.h" +#include "../src/title_mirror_space.h" +#include "../src/title_mirror_tracking.h" +#include "../src/title_mirror_hot_cold.h" #include "../src/guarded_copy.h" #include "../src/title_geometry_watch.h" #include "../src/title_texture_memory.h" #include "../src/title_texture_refresh.h" +#include "../src/title_texture_watch.h" #include "title_gpu_placements.h" #include "../src/spirv_f16_halves.h" #include "../src/spirv_stores.h" @@ -122,6 +129,9 @@ #include #include #include +#if defined(__AVX2__) +#include +#endif #include namespace rt::d3d12 { @@ -182,8 +192,9 @@ bool address_guard_enabled() { return on; } -// Matches the offset interpretation of the selected shader pack. -bool signed_vsharp_offsets() { +// LEONIDA_IMPORT_BELOW_ARENA=1: an import of title memory that the driver put below the arena is kept (and V# bases +// are read as signed offsets whatever the shader pack says). +bool import_below_arena() { static const bool on = [] { wchar_t value[2]{}; return GetEnvironmentVariableW(L"LEONIDA_IMPORT_BELOW_ARENA", value, 2) == 1 && value[0] == L'1'; @@ -191,6 +202,16 @@ bool signed_vsharp_offsets() { return on; } +// Set by the device from its shader library (create_arena): every loaded module sign-extends a V#'s 48-bit base +// (leonida::VsharpBaseCensus), so a buffer below heap_base is named by its negative offset. +std::atomic g_pack_signed_vsharp_offsets{false}; + +// Matches the offset interpretation of the selected shader pack: a V# base is a signed 48-bit offset from heap_base +// (any buffer within 2^47 of it, on either side) or an unsigned one (only buffers above it). +bool signed_vsharp_offsets() { + return import_below_arena() || g_pack_signed_vsharp_offsets.load(std::memory_order_relaxed); +} + // The CBV/SRV/UAV slots a descriptor table declares: the end of its furthest range (D3D12 appends a range at // D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND), an unbounded range limited by the registered heap. 0 for a sampler table or no table. std::uint32_t table_view_descriptors(const rt::rootsig::RootParameter& param) { @@ -232,7 +253,7 @@ __declspec(noinline) LEONIDA_GUARDED_NO_BUILTIN void copy_streaming(std::uint8_t // A copy that a page fault ends instead of killing the process: the title may decommit or remap a page between the // VirtualQuery that saw it committed and the read. No C++ objects here: it is a __try frame. `streaming`: for // write-combined pages (copy_streaming). Paid at every submission. -bool copy_guarded(std::uint8_t* to, const std::uint8_t* from, std::size_t bytes, bool streaming) { +bool copy_guarded_host(std::uint8_t* to, const std::uint8_t* from, std::size_t bytes, bool streaming) { __try { if (streaming) copy_streaming(to, from, bytes); else leonida::guarded::copy(to, from, bytes); @@ -242,62 +263,29 @@ bool copy_guarded(std::uint8_t* to, const std::uint8_t* from, std::size_t bytes, } } -// A 64-bit digest of the bytes of a texture the title keeps in its own memory, to tell whether they changed since its -// image was filled (TitleTextures). Up to 256 KiB every byte; above, 64 bytes at the start and 64 at the middle of -// every 4 KiB page plus the last 64 bytes, about 3% of them: the title's writes into texture memory are whole tiles -// (streaming, file reads, XG copies) or whole planes (video), never a few bytes inside a page. The same sampling as -// OpenScarlett's texture hash before submission (src/gpu/d3d12_xs/device_x.cpp, f8e24d4, MIT), with more samples. -// False when a page faults (the title unmapped it). No C++ objects here: it is a __try frame. -#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) { - 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, 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)); - for (std::size_t i = bytes & ~std::size_t(7); i < bytes; ++i) h = (h ^ p[i]) * 0x100000001b3ull; - } else { - for (std::size_t page = 0; page + 4096 <= bytes; page += 4096) { - h = mix_words(h, p + page, 64); - h = mix_words(h, p + page + 2048, 64); - } - h = mix_words(h, p + bytes - 64, 64); - } - return h; -} -bool hash_guarded(const std::uint8_t* p, std::size_t bytes, std::uint64_t& out, bool every_byte = false) { +// Fused guarded copy + 256-byte piece hashing for cached (non-WC) pages: one __try per 16 KiB strip, single read pass +// from `from` into `to` + in-register AVX2 hash. Intentionally NOT noexcept (SEH under /EHsc). +bool copy_and_sum_guarded_host(std::uint8_t* to, const std::uint8_t* from, std::size_t pieces, std::uint64_t* sums) { __try { - out = hash_bytes(p, bytes, every_byte); + leonida::guarded::copy_and_sum_256(to, from, pieces, sums); return true; } __except (EXCEPTION_EXECUTE_HANDLER) { return false; } } -inline std::uint64_t hashed_bytes(std::uint64_t bytes, bool every_byte = false) { - return bytes <= (256u << 10) || every_byte ? bytes : bytes / 32 + 64; -} -bool async_texture_refresh() { - static const bool enabled = [] { - const char* v = std::getenv("LEONIDA_TEXTURE_REFRESH_ASYNC"); - return v && std::strcmp(v, "1") == 0; - }(); - return enabled; +// The same, reading the title's pages that xmem's frame table holds through their frames: a stream pool's GPU-only +// pages and their CPU twins after queue slot 31's copies have no host view (src/title_frames.h). A frame is a section's +// scratch view, cached memory, so it is not read streaming. +bool copy_guarded(std::uint8_t* to, const std::uint8_t* from, std::size_t bytes, bool streaming) { + const auto at = reinterpret_cast(from); + if (!leonida::title_frames::may_hold(at, at + bytes)) return copy_guarded_host(to, from, bytes, streaming); + return leonida::title_frames::for_each_part(at, bytes, [&](std::uintptr_t part, std::size_t n, std::uint8_t* frame) { + return copy_guarded_host(to + (part - at), frame ? frame : reinterpret_cast(part), n, + streaming && !frame); + }); } + // Set while this thread is inside the title-texture registry (it holds title_texture_mutex): a staged copy it makes // submits through a queue, whose before-submission refresh must then not take the registry again. thread_local bool t_in_title_textures = false; @@ -658,6 +646,7 @@ class ShadowPages { next = std::min(last_, reinterpret_cast(region.BaseAddress) + region.RegionSize); kind = classify(region); } + if (kind == Kind::zero) kind = table_kind(at, next); std::size_t i1 = (next - first_) / kPage; for (std::size_t i = i0 + 1; i < i1; ++i) if (!cover_[i]) { // the region goes on past the pages copies read: the rest is passed over above @@ -868,6 +857,10 @@ class ShadowPages { next = reinterpret_cast(region.BaseAddress) + region.RegionSize; kind = classify(region); } + if (kind == Kind::zero) { // a reservation can be far larger than the new target + next = std::min(next, end); + kind = table_kind(at, next); + } const std::uintptr_t from = std::max(at, begin), to = std::min(next, end); if (kind == Kind::zero) { std::memset(shadow + (from - begin), 0, to - from); @@ -1240,7 +1233,9 @@ class ShadowPages { continue; } b.armed = false; - if (!copy_aliased_ || b.peers.empty()) continue; + // A table page with no host view anywhere (src/title_frames.h) has no other address to guard: its own cell, + // which every change of its frame moves, is all there is. + if (!copy_aliased_ || (b.peers.empty() && !leonida::title_frames::backed(va))) continue; b.armed = watch::arm(va, *b.cell); for (const auto& [other, cell] : b.peers) b.armed = watch::arm(other, *cell) && b.armed; alias_arms_ += 1 + b.peers.size(); @@ -1327,6 +1322,18 @@ class ShadowPages { bool retired = false; // a window nothing answers from, kept until its submissions are copied back }; + // A page VirtualQuery finds unreadable may be one xmem's frame table holds: a stream pool's GPU-only page or its + // CPU twin after queue slot 31's copies, with no host view (src/title_frames.h). It is read through its frame, like + // a read-only page that is not this tracker's: never guarded here (there is nothing to protect), and clean only + // while its geometry watch cells say so, which xmem's table updates and its physical page's host views move (xmem + // marks every table page aliased). `next` is clipped to the run of pages that are alike. + static Kind table_kind(std::uintptr_t at, std::uintptr_t& next) { + if (!leonida::title_frames::may_hold(at, next)) return Kind::zero; + bool backed = false; + next = leonida::title_frames::run_end(at, next, backed); + return backed ? Kind::read_only : Kind::zero; + } + static Kind classify(const MEMORY_BASIC_INFORMATION& region) { if (region.State != MEM_COMMIT || (region.Protect & PAGE_GUARD)) return Kind::zero; switch (region.Protect & 0xff) { @@ -1644,6 +1651,7 @@ const char* fsdraw_backing(std::uint64_t title_va) { } // Installs the handler once. false: it couldn't be, and shadows copy every page at every submission. +bool watch_shadow_writes(); bool watch_shadow_writes() { static const bool installed = [] { if (!AddVectoredExceptionHandler(1, &shadow_write_fault)) return false; @@ -1655,6 +1663,680 @@ bool watch_shadow_writes() { // A ShadowPages the fault handler knows of for its whole life: registered before it protects anything, removed once // its destructor has made every page writable again. +// The geometry watch's cells as TitleTextureWatch uses them: the title texture refresh's own queue of written tiles, +// and arming only while the write-fault handler is installed. Pages not committed are left as they are (xmem's commit +// or mapping of them bumps the cell); a tile pinned for a kernel write is busy until the write ends. +struct TitleTextureCells { + using Cell = leonida::geometry_writes::Cell; + leonida::geometry_writes::WriteQueue queue; + TitleTextureCells() { leonida::geometry_writes::subscribe_writes(queue); } + ~TitleTextureCells() { leonida::geometry_writes::unsubscribe_writes(queue); } + TitleTextureCells(const TitleTextureCells&) = delete; + TitleTextureCells& operator=(const TitleTextureCells&) = delete; + Cell* acquire(std::uintptr_t tile) { return leonida::geometry_writes::acquire(tile); } + void release(std::uintptr_t tile) { leonida::geometry_writes::release(tile); } + int arm(std::uintptr_t tile, Cell& cell) { + bool pinned = false; + leonida::kernel_writes::for_each_pin(tile, tile + leonida::geometry_writes::tile_size, + [&](auto, auto) { pinned = true; }); + if (pinned) return 0; + // Refused otherwise: a write raced the arming (it is in the queue), or VirtualQuery or VirtualProtect failed. + return leonida::geometry_writes::arm(tile, cell) ? 1 : -1; + } + // Batched arming of sorted, unique 64 KiB tiles: coalesces kernel-pin checks, geometry_writes::state().mutex + // acquisitions, a per-tile known-protection cache invalidated via title_memory_map::changes_since() (skipping + // VirtualQuery on repeat tile re-arms), and contiguous VirtualQuery/VirtualProtect runs across all examined + // textures in a pass. + // results[i]: 1 = armed (or hot & unpinned), 0 = busy (pinned), -1 = failed / raced write. + bool is_tile_pinned(std::uintptr_t tile) const noexcept { + constexpr std::uintptr_t kTile = leonida::geometry_writes::tile_size; + const std::uintptr_t tile_hi = (tile <= UINTPTR_MAX - kTile) ? (tile + kTile) : UINTPTR_MAX; + for (const auto& [p_lo, p_hi] : run_pin_ranges_) { + if (tile < p_hi && p_lo < tile_hi) return true; + } + return false; + } + + // True when no title_memory_map change after `since` overlapped [lo, hi). Sets `gen_out` to the generation + // checked up to (leaf SRWLOCK shared read when generation moved). + static bool range_clean_since(std::uint64_t since, std::uintptr_t lo, std::uintptr_t hi, std::uint64_t& gen_out) { + if (since == Cell::kNoMapGen) return false; + const std::uint64_t cur = leonida::title_memory_map::generation(); + if (cur == since) { + gen_out = cur; + return true; + } + bool overlapped = false; + std::uint64_t now = cur; + if (!leonida::title_memory_map::changes_since( + since, now, lo, hi, [&](std::uintptr_t c_from, std::uintptr_t c_to) { + if (c_from < c_to) overlapped = true; + })) { + return false; + } + gen_out = now; + return !overlapped; + } + + static bool restore_uniform(const Cell& c, DWORD expected) noexcept { + if (!expected) return false; + for (const DWORD r : c.restore) + if (r != expected) return false; + return true; + } + + static bool cell_known_writable(const Cell& c, DWORD& kp, DWORD& kg, std::uint64_t& gen) noexcept { + if (c.known_state != MEM_COMMIT || !c.known_protect || !c.known_guarded || c.known_map_gen == Cell::kNoMapGen || + c.known_mapping != c.mapping.load(std::memory_order_acquire)) + return false; + kp = c.known_protect; + kg = c.known_guarded; + gen = c.known_map_gen; + return true; + } + + // Cross-pass no-guard cache for TitleTextureCells: PAGE_NOACCESS ONLY! + // NEVER cache PAGE_READONLY (ShadowPages::reopen() reopens RO->RW without title_memory_map::changed()), and NEVER + // trust cross-pass MEM_RESERVE here (check_mapped_plane may raw VirtualAlloc(MEM_COMMIT) without map change; + // MEM_RESERVE is cached intra-pass only via cached_state). + static bool cell_known_noaccess(const Cell& c, std::uint64_t& gen) noexcept { + if (c.known_state != MEM_COMMIT || c.known_protect != PAGE_NOACCESS || c.known_guarded != 0 || + c.known_map_gen == Cell::kNoMapGen || c.known_mapping != c.mapping.load(std::memory_order_acquire)) + return false; + gen = c.known_map_gen; + return true; + } + + static void clear_cell_known(Cell& c) noexcept { + c.known_state = 0; + c.known_protect = 0; + c.known_guarded = 0; + c.known_map_gen = Cell::kNoMapGen; + } + + static void seed_known_from_armed(Cell& c, DWORD r0) noexcept { + if (c.armed_map_gen == Cell::kNoMapGen) return; + const std::uint64_t cur_map = c.mapping.load(std::memory_order_acquire); + if (c.known_state != 0 && c.known_mapping == cur_map && c.known_map_gen != Cell::kNoMapGen) return; + const DWORD g = leonida::geometry_writes::read_only(r0); + if (g != 0 && !(r0 & PAGE_GUARD)) { + c.known_state = MEM_COMMIT; + c.known_protect = r0; + c.known_guarded = g; + c.known_mapping = cur_map; + c.known_map_gen = c.armed_map_gen; + } + } + + struct ArmStats { + std::uint64_t hot = 0; + std::uint64_t already = 0; + std::uint64_t backed = 0; + std::uint64_t fast_vp = 0; + std::uint64_t bridged = 0; + std::uint64_t vq = 0; + std::uint64_t vq_cache = 0; + std::uint64_t vq_vp = 0; + }; + ArmStats arm_stats; + + void arm_batch(const std::uintptr_t* tiles, Cell* const* cells, std::int8_t* results, std::size_t count) { + constexpr std::size_t kMaxBatchRunPages = 1024; // up to 64 MiB per contiguous VirtualProtect run + constexpr std::size_t kMaxLockBatchPages = 128; // pages per pin check + geometry_writes lock hold + constexpr std::size_t kMaxBridgeGap = 8; // max already-armed cold gap tiles to bridge in one VP + constexpr std::uintptr_t kTile = leonida::geometry_writes::tile_size; + constexpr std::uintptr_t kHostPage = leonida::geometry_writes::page_size; + + if (!count) return; + + // Intra-pass VirtualQuery region cache persisted across outer i..j lock batches (validated via + // range_clean_since). Includes MEM_RESERVE, MEM_FREE, PAGE_NOACCESS, and writable MEM_COMMIT regions; NEVER + // caches PAGE_READONLY / PAGE_EXECUTE_READ (ShadowPages::reopen() reopens RO->RW without map change). + std::uintptr_t cached_lo = 0; + std::uintptr_t cached_hi = 0; + DWORD cached_state = 0; + DWORD cached_protect = 0; + DWORD cached_guarded = 0; + std::uint64_t cached_gen = 0; + + for (std::size_t i = 0; i < count;) { + std::size_t j = i + 1; + while (j < count) { + const bool contiguous = (tiles[j] == tiles[j - 1] + kTile); + const std::size_t len = j - i; + if (len < kMaxLockBatchPages) { + ++j; + } else if (contiguous && len < kMaxBatchRunPages) { + ++j; + } else { + break; + } + } + const std::size_t batch_n = j - i; + const std::uintptr_t* const batch_tiles = tiles + i; + Cell* const* const batch_cells = cells + i; + + run_versions_.resize(batch_n); + run_pinned_.assign(batch_n, 0); + run_eligible_.assign(batch_n, 0); + run_already_armed_.assign(batch_n, 0); + run_failed_.assign(batch_n, 0); + run_pin_ranges_.clear(); + run_need_backed_idx_.clear(); + run_need_backed_vas_.clear(); + + // Snapshot versions BEFORE querying kernel pins or taking geometry_writes::mutex. + for (std::size_t k = 0; k < batch_n; ++k) + run_versions_[k] = batch_cells[k]->version.load(std::memory_order_acquire); + + const std::uintptr_t pin_lo = batch_tiles[0]; + const std::uintptr_t last_tile = batch_tiles[batch_n - 1]; + const std::uintptr_t pin_hi = (last_tile <= UINTPTR_MAX - kTile) ? (last_tile + kTile) : UINTPTR_MAX; + // Querying an OVERLAPPED pin can fault into xmem: NEVER call under geometry_writes::state().mutex. + // Record every overlapping pin interval in run_pin_ranges_ so gap-bridging NEVER bridges a pinned tile. + if (pin_lo < pin_hi) { + leonida::kernel_writes::for_each_pin(pin_lo, pin_hi, [&](std::uintptr_t p_lo, std::uintptr_t p_hi) { + run_pin_ranges_.emplace_back(p_lo, p_hi); + const std::uintptr_t first_tile = p_lo & ~(kTile - 1); + const std::uintptr_t* it = std::lower_bound(batch_tiles, batch_tiles + batch_n, first_tile); + for (; it < batch_tiles + batch_n && *it < p_hi; ++it) + run_pinned_[std::size_t(it - batch_tiles)] = 1; + }); + } + const bool may_hold_frames = pin_lo < pin_hi && leonida::title_frames::may_hold(pin_lo, pin_hi); + + auto& s = leonida::geometry_writes::state(); + { + std::unique_lock lock(s.mutex); + for (std::size_t k = 0; k < batch_n; ++k) { + if (run_pinned_[k]) { + results[i + k] = 0; // busy: kernel write in progress (even on hot tiles) + continue; + } + Cell* const c = batch_cells[k]; + if (c->hot) { + results[i + k] = 1; + ++arm_stats.hot; + continue; + } + if (run_versions_[k] != c->version.load(std::memory_order_relaxed)) { + results[i + k] = -1; // write raced arming + continue; + } + // Zero-syscall fast path: all 16 host pages already guarded read-only (e.g. armed by + // HotColdTracking::CellGuard earlier in this leader pass; guaranteed cleared by reopen(), + // Event::replaced, TitleVirtualProtect, and unmap_page). + const DWORD r0 = c->restore[0]; + bool all_armed = r0 != 0; + bool uniform_restore = all_armed; + for (std::size_t sp = 1; all_armed && sp < c->restore.size(); ++sp) { + if (!c->restore[sp]) { + all_armed = false; + uniform_restore = false; + } else if (c->restore[sp] != r0) { + uniform_restore = false; + } + } + if (all_armed) { + if (uniform_restore) seed_known_from_armed(*c, r0); + run_already_armed_[k] = 1; + results[i + k] = 1; + ++arm_stats.already; + continue; + } + if (may_hold_frames) { + run_need_backed_idx_.push_back(k); + run_need_backed_vas_.push_back(batch_tiles[k]); + } else { + run_eligible_[k] = 1; + } + } + + // Batch-check table-page backing outside geometry_writes::state().mutex ONLY for tiles that are not + // pinned, hot, or already all-armed (never nest g_frame_lock and s.mutex; single g_frame_lock hold + // with zero shared_ptr refcount churn). Re-verify version/hot/all_armed after re-acquiring s.mutex. + if (!run_need_backed_idx_.empty()) { + lock.unlock(); + run_need_backed_out_.resize(run_need_backed_vas_.size()); + leonida::title_frames::backed_batch(run_need_backed_vas_.data(), run_need_backed_out_.data(), + run_need_backed_vas_.size()); + lock.lock(); + for (std::size_t m = 0; m < run_need_backed_idx_.size(); ++m) { + const std::size_t k = run_need_backed_idx_[m]; + Cell* const c = batch_cells[k]; + if (c->hot) { + results[i + k] = 1; + ++arm_stats.hot; + continue; + } + if (run_versions_[k] != c->version.load(std::memory_order_relaxed)) { + results[i + k] = -1; // write/remap/pin raced during backed_batch + continue; + } + const DWORD r0 = c->restore[0]; + bool all_armed = r0 != 0; + bool uniform_restore = all_armed; + for (std::size_t sp = 1; all_armed && sp < c->restore.size(); ++sp) { + if (!c->restore[sp]) { + all_armed = false; + uniform_restore = false; + } else if (c->restore[sp] != r0) { + uniform_restore = false; + } + } + if (all_armed) { + if (uniform_restore) seed_known_from_armed(*c, r0); + run_already_armed_[k] = 1; + results[i + k] = 1; + ++arm_stats.already; + continue; + } + if (run_need_backed_out_[m]) { + results[i + k] = 1; + ++arm_stats.backed; + continue; + } + run_eligible_[k] = 1; + } + } + + for (std::size_t sub_start = 0; sub_start < batch_n;) { + if (!run_eligible_[sub_start]) { + ++sub_start; + continue; + } + std::size_t sub_end = sub_start + 1; + while (sub_end < batch_n && run_eligible_[sub_end] && + batch_tiles[sub_end] == batch_tiles[sub_end - 1] + kTile) { + ++sub_end; + } + + // Gap-bridging fast path: coalesce scattered eligible tiles separated by <= kMaxBridgeGap + // already-armed, unpinned cold tiles sharing identical Cell::known_protect/known_guarded/mapping + // and uniform restore[0..15] == kp. Falls back to eligible-only [sub_start, sub_end) on any + // failure or unexpected old protect (with mandatory VirtualProtect(old) rollback). + DWORD kp = 0, kg = 0; + std::uint64_t gen0 = 0; + if (cell_known_writable(*batch_cells[sub_start], kp, kg, gen0)) { + const std::uintptr_t span_lo = batch_tiles[sub_start]; + std::size_t bridge_end = sub_start + 1; + std::size_t last_eligible = sub_start; + std::uint64_t run_min_gen = gen0; + std::uint64_t last_min_gen = gen0; + while (bridge_end < batch_n && + (run_eligible_[bridge_end] || run_already_armed_[bridge_end])) { + const std::uintptr_t prev_va = batch_tiles[bridge_end - 1]; + const std::uintptr_t next_va = batch_tiles[bridge_end]; + if (prev_va > UINTPTR_MAX - kTile || next_va > UINTPTR_MAX - kTile) break; + const std::uintptr_t prev_end = prev_va + kTile; + if (next_va < prev_end) break; + const std::uintptr_t eligible_gap = next_va - (batch_tiles[last_eligible] + kTile); + if (eligible_gap > kMaxBridgeGap * kTile) break; + if ((next_va + kTile - span_lo) > kMaxBatchRunPages * kTile) break; + const Cell& cn = *batch_cells[bridge_end]; + DWORD nkp = 0, nkg = 0; + std::uint64_t ngen = 0; + if (!cell_known_writable(cn, nkp, nkg, ngen) || nkp != kp || nkg != kg) break; + if (run_already_armed_[bridge_end] && + (run_pinned_[bridge_end] || is_tile_pinned(next_va) || cn.hot || + !restore_uniform(cn, kp))) { + break; + } + std::uint64_t cand_min_gen = (std::min)(run_min_gen, ngen); + bool gap_ok = true; + for (std::uintptr_t gap_va = prev_end; gap_va < next_va; gap_va += kTile) { + if (is_tile_pinned(gap_va)) { + gap_ok = false; + break; + } + const auto cit = s.cells.find(gap_va); + if (cit == s.cells.end()) { + gap_ok = false; + break; + } + const Cell& gc = cit->second; + DWORD gkp = 0, gkg = 0; + std::uint64_t ggen = 0; + if (gc.hot || !restore_uniform(gc, kp) || + !cell_known_writable(gc, gkp, gkg, ggen) || gkp != kp || gkg != kg) { + gap_ok = false; + break; + } + cand_min_gen = (std::min)(cand_min_gen, ggen); + } + if (!gap_ok) break; + run_min_gen = cand_min_gen; + if (run_eligible_[bridge_end]) { + last_eligible = bridge_end; + last_min_gen = run_min_gen; + } + ++bridge_end; + } + const std::size_t bridge_end_eff = last_eligible + 1; + if (bridge_end_eff > sub_end) { + const std::uintptr_t span_hi = batch_tiles[last_eligible] + kTile; + std::uint64_t verified_gen = 0; + if (range_clean_since(last_min_gen, span_lo, span_hi, verified_gen)) { + DWORD old{}; + if (VirtualProtect(reinterpret_cast(span_lo), span_hi - span_lo, kg, &old)) { + if (old == kp || old == kg) { + for (std::size_t k = sub_start; k < bridge_end_eff; ++k) { + if (run_eligible_[k]) { + batch_cells[k]->restore.fill(kp); + batch_cells[k]->armed_map_gen = verified_gen; + batch_cells[k]->known_map_gen = verified_gen; + results[i + k] = 1; + } else { + batch_cells[k]->armed_map_gen = verified_gen; + batch_cells[k]->known_map_gen = verified_gen; + } + } + ++arm_stats.fast_vp; + ++arm_stats.bridged; + if (cached_hi && span_lo >= cached_lo && span_hi <= cached_hi) + cached_lo = span_hi; + sub_start = bridge_end_eff; + continue; + } + // Unexpected prior protection: `old` describes tile 0 (`span_lo`) only. + // Restore eligible tiles individually (tile 0 to `old`, other eligible tiles + // to their verified `kp`), leaving already-armed gap tiles at `kg`. + for (std::size_t k = sub_start; k < bridge_end_eff; ++k) { + if (!run_eligible_[k]) continue; + DWORD dummy{}; + VirtualProtect(reinterpret_cast(batch_tiles[k]), kTile, + k == sub_start ? old : kp, &dummy); + } + } + for (auto cit = s.cells.lower_bound(span_lo); + cit != s.cells.end() && cit->first < span_hi; ++cit) { + clear_cell_known(cit->second); + } + cached_hi = 0; + } + } + } + + const std::uintptr_t sub_lo = batch_tiles[sub_start]; + const std::uintptr_t sub_hi = sub_lo + (sub_end - sub_start) * kTile; + + for (std::uintptr_t p = sub_lo; p < sub_hi;) { + // Fast path: tile-aligned repeat arm with verified uniform protection or cached PAGE_NOACCESS + // (NEVER cross-pass MEM_RESERVE or PAGE_READONLY) -> 0 VirtualQuery syscalls. + if ((p & (kTile - 1)) == 0 && sub_hi - p >= kTile) { + const std::size_t tile_k = sub_start + std::size_t((p - sub_lo) / kTile); + Cell* const c0 = batch_cells[tile_k]; + DWORD fkp = 0, fkg = 0; + std::uint64_t fgen0 = 0; + if (cell_known_writable(*c0, fkp, fkg, fgen0)) { + std::size_t fast_end = tile_k + 1; + std::uint64_t min_gen = fgen0, max_gen = fgen0; + while (fast_end < sub_end) { + DWORD nkp = 0, nkg = 0; + std::uint64_t ngen = 0; + if (!cell_known_writable(*batch_cells[fast_end], nkp, nkg, ngen) || nkp != fkp || + nkg != fkg) + break; + min_gen = (std::min)(min_gen, ngen); + max_gen = (std::max)(max_gen, ngen); + ++fast_end; + } + std::uintptr_t end = p + (fast_end - tile_k) * kTile; + std::uint64_t verified_gen = 0; + bool clean = range_clean_since(min_gen, p, end, verified_gen); + if (!clean && min_gen != max_gen && fast_end > tile_k + 1) { + std::size_t prefix_end = tile_k + 1; + while (prefix_end < fast_end && batch_cells[prefix_end]->known_map_gen == fgen0) + ++prefix_end; + fast_end = prefix_end; + end = p + (fast_end - tile_k) * kTile; + clean = range_clean_since(fgen0, p, end, verified_gen); + } + if (clean) { + DWORD old{}; + if (VirtualProtect(reinterpret_cast(p), end - p, fkg, &old)) { + if (old == fkp || old == fkg) { + for (std::size_t t = tile_k; t < fast_end; ++t) { + batch_cells[t]->restore.fill(fkp); + batch_cells[t]->armed_map_gen = verified_gen; + batch_cells[t]->known_map_gen = verified_gen; + } + ++arm_stats.fast_vp; + if (cached_hi && p >= cached_lo && end <= cached_hi) cached_lo = end; + p = end; + continue; + } + // Unexpected prior protection (caller bypassed title_memory_map::changed): + // `old` describes tile 0 (`p`) only; restore tile 0 to `old` and remaining + // tiles to their verified `fkp` before falling through to VirtualQuery. + for (std::uintptr_t q = p; q < end; q += kTile) { + DWORD dummy{}; + VirtualProtect(reinterpret_cast(q), kTile, q == p ? old : fkp, + &dummy); + } + } + for (std::size_t t = tile_k; t < fast_end; ++t) clear_cell_known(*batch_cells[t]); + cached_hi = 0; + } + } else if (cell_known_noaccess(*c0, fgen0)) { + std::size_t fast_end = tile_k + 1; + std::uint64_t min_gen = fgen0, max_gen = fgen0; + while (fast_end < sub_end) { + std::uint64_t ngen = 0; + if (!cell_known_noaccess(*batch_cells[fast_end], ngen)) break; + min_gen = (std::min)(min_gen, ngen); + max_gen = (std::max)(max_gen, ngen); + ++fast_end; + } + std::uintptr_t end = p + (fast_end - tile_k) * kTile; + std::uint64_t verified_gen = 0; + bool clean = range_clean_since(min_gen, p, end, verified_gen); + if (!clean && min_gen != max_gen && fast_end > tile_k + 1) { + std::size_t prefix_end = tile_k + 1; + while (prefix_end < fast_end && batch_cells[prefix_end]->known_map_gen == fgen0) + ++prefix_end; + fast_end = prefix_end; + end = p + (fast_end - tile_k) * kTile; + clean = range_clean_since(fgen0, p, end, verified_gen); + } + if (clean) { + for (std::size_t t = tile_k; t < fast_end; ++t) + batch_cells[t]->known_map_gen = verified_gen; + arm_stats.vq_cache += (fast_end - tile_k); + if (cached_hi && p >= cached_lo && end <= cached_hi) cached_lo = end; + p = end; + continue; + } + } + } + + std::uintptr_t region_base = 0; + std::uintptr_t region_end = 0; + DWORD state = 0; + DWORD protect = 0; + DWORD guarded = 0; + std::uint64_t query_gen = 0; + bool from_cache = false; + + std::uint64_t cache_now = 0; + if (p >= cached_lo && p < cached_hi && + range_clean_since(cached_gen, p, (std::min)(sub_hi, cached_hi), cache_now)) { + region_base = cached_lo; + region_end = cached_hi; + state = cached_state; + protect = cached_protect; + guarded = cached_guarded; + query_gen = cached_gen; + from_cache = true; + ++arm_stats.vq_cache; + } else { + query_gen = leonida::title_memory_map::generation(); + ++arm_stats.vq; + MEMORY_BASIC_INFORMATION m{}; + if (!VirtualQuery(reinterpret_cast(p), &m, sizeof m)) { + const std::size_t tile_k = sub_start + std::size_t((p - sub_lo) / kTile); + run_failed_[tile_k] = 1; + p = (p & ~(kTile - 1)) + kTile; + continue; + } + region_base = reinterpret_cast(m.BaseAddress); + region_end = region_base + m.RegionSize; + state = m.State; + protect = m.Protect; + guarded = leonida::geometry_writes::read_only(m.Protect); + const DWORD base_prot = protect & 255u; + // Intra-pass region cache: MEM_RESERVE, MEM_FREE, PAGE_NOACCESS, and writable MEM_COMMIT. + // NEVER cache PAGE_READONLY / PAGE_EXECUTE_READ (ShadowPages::reopen() bypasses map_gen). + const bool cacheable_region = + state == MEM_RESERVE || state == MEM_FREE || + (state == MEM_COMMIT && !(protect & PAGE_GUARD) && + (guarded != 0 || base_prot == PAGE_NOACCESS)); + if (cacheable_region && region_end > sub_hi) { + cached_lo = p; + cached_hi = region_end; + cached_state = state; + cached_protect = protect; + cached_guarded = guarded; + cached_gen = query_gen; + } else { + cached_hi = 0; + } + } + + const std::uintptr_t end = (std::min)(sub_hi, region_end); + if (end <= p) { + const std::size_t tile_k = sub_start + std::size_t((p - sub_lo) / kTile); + run_failed_[tile_k] = 1; + cached_hi = 0; + p = (p & ~(kTile - 1)) + kTile; + continue; + } + if (state == MEM_COMMIT && !(protect & PAGE_GUARD) && guarded) { + DWORD old{}; + ++arm_stats.vq_vp; + if (VirtualProtect(reinterpret_cast(p), end - p, guarded, &old)) { + for (std::uintptr_t q = p; q < end; q += kHostPage) { + const std::size_t tile_k = sub_start + std::size_t((q - sub_lo) / kTile); + const std::size_t sub_p = std::size_t((q & (kTile - 1)) / kHostPage); + batch_cells[tile_k]->restore[sub_p] = protect; + batch_cells[tile_k]->armed_map_gen = Cell::kNoMapGen; + } + const std::uintptr_t first_full = (p + kTile - 1) & ~(kTile - 1); + const std::uintptr_t last_full = end & ~(kTile - 1); + std::uint64_t after_gen = 0; + if (first_full < last_full && region_base <= first_full && region_end >= last_full && + range_clean_since(query_gen, first_full, last_full, after_gen)) { + for (std::uintptr_t t = first_full; t < last_full; t += kTile) { + const std::size_t tile_k = sub_start + std::size_t((t - sub_lo) / kTile); + Cell* const c = batch_cells[tile_k]; + c->known_state = MEM_COMMIT; + c->known_protect = protect; + c->known_guarded = guarded; + c->known_mapping = c->mapping.load(std::memory_order_acquire); + c->known_map_gen = after_gen; + c->armed_map_gen = after_gen; + } + } + if (cached_hi && p >= cached_lo && end <= cached_hi) cached_lo = end; + } else if (from_cache) { + cached_hi = 0; + continue; + } else { + cached_hi = 0; + for (std::uintptr_t t = p; t < end;) { + const std::uintptr_t t_end = (std::min)(end, (t & ~(kTile - 1)) + kTile); + const std::size_t tile_k = sub_start + std::size_t((t - sub_lo) / kTile); + ++arm_stats.vq_vp; + if (VirtualProtect(reinterpret_cast(t), t_end - t, guarded, &old)) { + for (std::uintptr_t q = t; q < t_end; q += kHostPage) { + const std::size_t sub_p = std::size_t((q & (kTile - 1)) / kHostPage); + batch_cells[tile_k]->restore[sub_p] = protect; + batch_cells[tile_k]->armed_map_gen = Cell::kNoMapGen; + } + } else { + run_failed_[tile_k] = 1; + } + t = t_end; + } + } + } else { + const std::uintptr_t first_full = (p + kTile - 1) & ~(kTile - 1); + const std::uintptr_t last_full = end & ~(kTile - 1); + if (first_full < last_full) { + const bool is_noaccess = + state == MEM_COMMIT && !(protect & PAGE_GUARD) && (protect & 255u) == PAGE_NOACCESS; + std::uint64_t after_gen = 0; + if (is_noaccess && region_base <= first_full && region_end >= last_full && + range_clean_since(query_gen, first_full, last_full, after_gen)) { + for (std::uintptr_t t = first_full; t < last_full; t += kTile) { + const std::size_t tile_k = sub_start + std::size_t((t - sub_lo) / kTile); + Cell* const c = batch_cells[tile_k]; + c->known_state = MEM_COMMIT; + c->known_protect = PAGE_NOACCESS; + c->known_guarded = 0; + c->known_mapping = c->mapping.load(std::memory_order_acquire); + c->known_map_gen = after_gen; + } + } else { + // Clear stale writable cache without trampling CellGuard's MEM_RESERVE cache. + for (std::uintptr_t t = first_full; t < last_full; t += kTile) { + const std::size_t tile_k = sub_start + std::size_t((t - sub_lo) / kTile); + Cell* const c = batch_cells[tile_k]; + if (!(state == MEM_RESERVE && c->known_state == MEM_RESERVE)) + clear_cell_known(*c); + } + } + } + if (cached_hi && p >= cached_lo && end <= cached_hi) cached_lo = end; + } + p = end; + } + + for (std::size_t k = sub_start; k < sub_end; ++k) + results[i + k] = run_failed_[k] ? -1 : 1; + sub_start = sub_end; + } + } + i = j; + } + } + std::vector run_versions_; + std::vector run_pinned_; + std::vector run_eligible_; + std::vector run_already_armed_; + std::vector run_failed_; + std::vector> run_pin_ranges_; + std::vector run_need_backed_idx_; + std::vector run_need_backed_vas_; + std::vector run_need_backed_out_; + void acquire_batch(const std::uintptr_t* tiles, Cell** out_cells, std::size_t count) { + leonida::geometry_writes::acquire_batch(tiles, out_cells, count); + } + void release_batch(const std::pair* items, std::size_t count) { + leonida::geometry_writes::release_batch(items, count); + } + void aliases(std::uintptr_t tile, std::vector& out) { + if (const auto f = leonida::geometry_writes::aliases.load(std::memory_order_acquire)) f(tile, out); + } + void take_written(std::vector& out, bool& overflow) { + leonida::geometry_writes::take_written(queue, out, overflow); + } + void hot_tiles(std::vector& out) { leonida::geometry_writes::hot_tiles(out); } + bool has_written() const { return queue.pending.load(std::memory_order_acquire); } + std::size_t hot_count() const { + return leonida::geometry_writes::state().hot_count.load(std::memory_order_acquire); + } + std::uint64_t hot_generation() const { + auto& s = leonida::geometry_writes::state(); + if constexpr (requires { s.hot_generation; }) { + return s.hot_generation.load(std::memory_order_acquire); + } else { + return static_cast(s.hot_count.load(std::memory_order_acquire)); + } + } + bool enabled() const { return watch_shadow_writes(); } +}; + struct ShadowPagesDeleter { void operator()(ShadowPages* pages) const { pages->reopen_all(); @@ -2694,45 +3376,100 @@ class Resource; struct DeviceState; // `why`, when given, says what refused a T#: the first refusals are logged with their words (scan_console_slots). TitleImage bind_title_image(DeviceState& device, const leonida::gfx10::ImageWords& words, const char** why = nullptr); +// Why a T# found no room (bind_image_locked): set 0's array of its dimension, or that array's storage range, was full. +// A console heap's slot record keeps such a T# waiting for room (DeviceState::fix_console_slot). +constexpr const char* kTsharpArrayFull = "the bindless array of the T#'s dimension is full"; +constexpr const char* kTsharpStorageFull = "the bindless storage arrays of the T#'s dimension are full"; +// Why a T# found no texture (TitleImage::unknown), by what its address is (bind_title_image): the title's memory (a +// texture the title placed there without any call the layer sees); an address of the layer's own textures +// (Resource::image_address: 1 << 32 and up, 256 apart) whose texture is gone; an address whose low 32 bits are one of +// those (the title rebuilt the T# with other high bits) and whose texture is there with the T#'s shape, there with +// another shape, or gone; or none of these (no memory of the title's or texture of ours: data that decodes as a T#, +// or an address the layer does not know). +constexpr const char* kTsharpNoTextureTitleMemory = "no texture at the T# address: title memory"; +constexpr const char* kTsharpNoTextureGone = "no texture at the T# address: a texture of ours that is gone"; +constexpr const char* kTsharpNoTextureLow32Same = "no texture at the T# address: its low 32 bits name a texture of ours of its shape"; +constexpr const char* kTsharpNoTextureLow32Other = "no texture at the T# address: its low 32 bits name a texture of ours of another shape"; +constexpr const char* kTsharpNoTextureLow32Gone = "no texture at the T# address: its low 32 bits name a texture of ours that is gone"; +constexpr const char* kTsharpNoTextureNothing = "no texture at the T# address: no title memory and no texture of ours"; struct TitleTexture; // a texture the title keeps in its own memory (TitleTexture, after Resource) +// Overload returning the bindless index word under the same descriptor_mutex hold (null to skip). +TitleImage bind_title_image(DeviceState& device, const leonida::gfx10::ImageWords& words, const char** why, + std::uint32_t* out_index_word); // The first refused T#s of each reason, with where they sit in the heap and their words, and counts of the // distinct slots refused overall and per reason (a slot is scanned again every pass over the heap). +// Zero-allocation on the hot path: reasons are matched by pointer identity first (all runtime reasons are static +// literals), with an owned string fallback for synthetic test strings. struct UnboundTsharpTracker { + struct ReasonBucket { + const char* literal = nullptr; + std::string owned; + std::unordered_set slots; + std::uint64_t count = 0; + unsigned logged = 0; + }; + std::mutex mutex; - std::set total_slots; - std::map> slots_by_reason; - std::map counts_by_reason; - std::map logged; + std::unordered_set total_slots; + std::vector buckets; std::uint64_t total_refusals = 0; + std::atomic capped{false}; + + bool is_capped() const noexcept { return capped.load(std::memory_order_acquire); } + + ReasonBucket& bucket_locked(const char* why) { + const char* r = why ? why : "?"; + for (ReasonBucket& b : buckets) { + if (b.literal == r) return b; + } + for (ReasonBucket& b : buckets) { + if (b.owned == r) return b; + } + ReasonBucket& b = buckets.emplace_back(); + b.literal = r; + b.owned = r; + return b; + } void note(std::uint64_t heap_va, std::size_t offset, const leonida::gfx10::ImageWords& words, const char* why) { std::lock_guard lock(mutex); - const std::string reason = why ? why : "?"; + ReasonBucket& b = bucket_locked(why); ++total_refusals; - ++counts_by_reason[reason]; - if (total_slots.size() >= 262144) return; // enough to say how many + ++b.count; + if (total_slots.size() >= 262144) { + capped.store(true, std::memory_order_release); + return; // enough to say how many + } const bool fresh_overall = total_slots.insert(offset).second; - const bool fresh_reason = slots_by_reason[reason].insert(offset).second; - unsigned& n = logged[reason]; - if ((!fresh_overall && !fresh_reason) || n >= 6) return; - ++n; + if (total_slots.size() >= 262144) capped.store(true, std::memory_order_release); + const bool fresh_reason = b.slots.insert(offset).second; + if ((!fresh_overall && !fresh_reason) || b.logged >= 6) return; + ++b.logged; std::fprintf(stderr, "[rt] d3d12: unbound T# in console heap 0x%llx at +0x%zx (%zu distinct slots so far, %zu for '%s'): %s: " "%08x %08x %08x %08x %08x %08x %08x %08x\n", static_cast(heap_va), offset, total_slots.size(), - slots_by_reason[reason].size(), reason.c_str(), reason.c_str(), words[0], + b.slots.size(), b.owned.c_str(), b.owned.c_str(), words[0], words[1], words[2], words[3], words[4], words[5], words[6], words[7]); } + void note_capped(const char* why, std::uint64_t count) { + if (!count) return; + std::lock_guard lock(mutex); + ReasonBucket& b = bucket_locked(why); + total_refusals += count; + b.count += count; + } + UnboundTsharpStats stats() { std::lock_guard lock(mutex); UnboundTsharpStats s; s.total_distinct_slots = total_slots.size(); s.total_refusals = total_refusals; - for (const auto& [reason, slots] : slots_by_reason) { - s.by_reason[reason].distinct_slots = slots.size(); - s.by_reason[reason].total_refusals = counts_by_reason[reason]; + for (const ReasonBucket& b : buckets) { + s.by_reason[b.owned].distinct_slots = b.slots.size(); + s.by_reason[b.owned].total_refusals = b.count; } return s; } @@ -2740,10 +3477,9 @@ struct UnboundTsharpTracker { void reset() { std::lock_guard lock(mutex); total_slots.clear(); - slots_by_reason.clear(); - counts_by_reason.clear(); - logged.clear(); + buckets.clear(); total_refusals = 0; + capped.store(false, std::memory_order_release); } }; @@ -2754,6 +3490,8 @@ UnboundTsharpTracker& unbound_tsharp_tracker() { // What a device's children need from it, kept apart from the COM class so children can hold a plain pointer. class Resource; +leonida::VramBudget read_vram_budget(const VulkanDeviceInfo& info); // VK_EXT_memory_budget (defined below) + struct DeviceState { std::mutex mapped_texture_mutex; std::set mapped_textures; @@ -3197,8 +3935,8 @@ struct DeviceState { probe_census(); // LOCAL DIAGNOSTIC 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 + std::unique_lock lock(shadow_mutex, std::defer_lock); + leonida::submit_phases::lock_timed(lock); if (shadows.empty()) return; const auto start = clock::now(); // LEONIDA_SHADOW_ALIAS_MS (0 by default: every submission): pages xmem maps at two addresses that a write @@ -3214,7 +3952,9 @@ struct DeviceState { if (copy_aliased) shadow_alias_time = start; std::uint64_t copied = 0; for (const ShadowPagesPtr& s : shadows) { - copied += s->refresh(copy_aliased); + const std::uint64_t pages = s->refresh(copy_aliased); + if (pages) leonida::submit_phases::note_change(leonida::submit_phases::change_pages); // not a floor one + copied += pages; shadow_queries += s->refresh_queries(); shadow_protects += s->refresh_protects(); shadow_walks += s->refresh_walked_all(); @@ -3288,9 +4028,75 @@ struct DeviceState { // defined after TitleTexture. std::mutex title_texture_mutex; std::map> title_textures; - leonida::TitleTextureRangeIndex texture_ranges; - std::map> mapped_title_textures; + // Which registered textures may have changed since their last fill (title_texture_watch.h), under + // title_texture_mutex: their tiles are geometry-watch cells, armed read-only. + TitleTextureCells texture_cells; + leonida::TitleTextureWatch texture_watch{texture_cells}; void index_texture(const TitleTexture& t); + struct TitleMirrorCheckItem { + std::uint64_t cpu = 0; + std::uint64_t gpu = 0; + std::uint64_t bytes = 0; + const std::vector* written_tiles = nullptr; // non-null when per-tile sync filtering allowed + const std::vector* tile_cmp_written = nullptr; // non-null when partial-tile mirror cmp allowed + const leonida::TilePieces* pieces = nullptr; + std::uint64_t max_version = 0; + bool ex_armed = false; + bool active = false; + // Outputs filled by page_mirror_check_batch(): + bool full_ok = false; + bool single_chunk = false; + VkBuffer buffer = VK_NULL_HANDLE; + VkDeviceSize offset = 0; + VkDeviceSize chunk_size = 0; + VkSemaphore timeline = VK_NULL_HANDLE; + std::uint64_t value = 0; + std::uint64_t mirror_hash = 0; + int tile_cmp = 0; // +1 unchanged, -1 changed, 0 unknown/fallback + // Why try_full_view() rejected this item (for cpu_fallback_by[6] telemetry): + // 0 = none/accepted, 1 = unmirrored_plain, 2 = unmirrored_other, 3 = in_feed, 4 = pending_bind + std::uint8_t reject_reason = 0; + // Internal scratch for page_mirror_check_batch(): + enum class Mode : std::uint8_t { none, full, partial_tiles } mode = Mode::none; + std::uint64_t mirror_va = 0; + }; + void page_mirror_check_batch(std::vector& items, std::vector& feed_pages, + std::uint64_t mirror_synced_serial = 0, + const std::function)>& parallel_run = {}); + // The CPU-view ranges of the registered GPU-written textures (render targets, depth, unordered access), by their + // registry address. A texture over such memory is not filled from it (index_texture): the title's pages there + // hold what the CPU last put there, never what our GPU renders into the image, and a fill uploaded those old + // bytes, in 64 KiB pieces as write-backs and neighbours' writes marked their tiles written. Under + // title_texture_mutex. + struct GpuOwned { + std::uint64_t address = 0; // the registry address it was placed at + std::uintptr_t begin = 0, end = 0; + }; + std::map gpu_owned; // by the GPU-written resource + std::uint64_t gpu_owned_refusals = 0; + bool over_gpu_owned(std::uintptr_t begin, std::uintptr_t end) const { + for (const auto& [owner, range] : gpu_owned) + if (range.begin < end && begin < range.end) return true; + return false; + } + void add_gpu_owned(const void* owner, std::uint64_t address, std::uintptr_t cpu, std::uint64_t span); + // The GPU-written resource is gone: the texture registered at its address (one kept there while the target + // covered it) is filled from memory again, and the T#s naming the address find it. + void drop_gpu_owned(const void* owner); + // T#s and slot-70 views at an address a GPU-written texture covers: resolved to its image, and the other textures' + // that could not be, by why (bind_title_image, place_title_view). Logged by the title texture refresh. + enum { kOverTargetResolved, kOverTargetFormat, kOverTargetExtent, kOverTargetRange, kOverTargetKinds }; + std::array, kOverTargetKinds> over_gpu_target{}; + // Textures named by their first descriptor since the last refresh (Resource::note_shader_view; any thread, under + // any lock: this one is a leaf). + std::mutex titles_named_mutex; + std::vector titles_named; + std::atomic titles_named_pending{false}; + void title_texture_named(std::uint64_t address) { + std::lock_guard lock(titles_named_mutex); + titles_named.push_back(address); + titles_named_pending.store(true, std::memory_order_release); + } void title_texture_mapped(const void* resource, std::uint64_t address); void title_texture_unmapped(const void* resource, std::uint64_t address); // the title wrote texels void title_texture_gone(const void* resource, std::uint64_t address); @@ -3335,16 +4141,20 @@ struct DeviceState { // 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::atomic has_title_write_back{false}; + std::atomic has_passive_title_write_back{false}; + std::atomic writes_buffer_meta_complete{false}; + 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 std::map title_write_back; // start -> end, of the submission about to run + leonida::PassiveWriteBackTracker passive_write_back{kTitleWriteBackRanges, kTitleWriteBackBytes}; 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 that no other mapping serves yet. A // window goes once no address answers from it (retire_orphan_windows); 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 @@ -3412,6 +4222,7 @@ struct DeviceState { // 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; + geometry.stamp_retired([this] { return context->submitted_retire_ticket(); }); const std::uint64_t completed_ticket = geometry.has_retired() ? context->completed_retire_ticket() : 0; geometry.drain_released( *this, rt::d3d12::GeometryViews::kAfterExecutes, completed_ticket, @@ -3431,17 +4242,25 @@ struct DeviceState { pool_span_count.store(pool_spans.size(), std::memory_order_relaxed); ++pool_spans_retired; } + // Before refresh_shadows (next to drain_geometry_releases): stamps retired windows whose pre-retirement replays + // and command lists have finished, and frees those whose GPU ticket has completed so any target_gone slot changes + // from destroyed external blocks apply during this submission's heap refresh. + void reclaim_retired_windows() { + if (!context || !retired_window_count.load(std::memory_order_acquire)) return; + stamp_retired_windows(); // lists reset or released since the last replay + const std::uint64_t completed = context->completed_retire_ticket(); + std::lock_guard windows(title_window_mutex); + free_retired_windows(completed); + } // After this submission's refresh (the windows' last copy is the one it made): a title window no address range // answers from any more leaves the refresh. Its ranges went because a newer range was entered over them (a // slot-133 buffer placed over the pages, a BVH input's exact copy, src/title_va_alias.h add), and a window nothing // reaches is only cost: its tracker walks its pages at every refresh and its bytes count against // LEONIDA_TITLE_WINDOWS_MB. Its stream-pool extent and its budget go at once; its copy leaves its tracker and its - // memory is freed later (retired_windows), and the retired windows due are freed here. Only windows whose copy a + // memory is freed later (retired_windows, reclaimed in reclaim_retired_windows). Only windows whose copy a // removed range answered from are looked at (alias_changed records those). void retire_orphan_windows() { - if (!context || (!window_alias_removals_pending.load(std::memory_order_acquire) && - !retired_window_count.load(std::memory_order_acquire))) - return; + if (!context || !window_alias_removals_pending.load(std::memory_order_acquire)) return; std::vector> removed; // (shader VA, bytes) bool every = false; { @@ -3451,11 +4270,8 @@ struct DeviceState { window_alias_removals_overflow = false; window_alias_removals_pending.store(false, std::memory_order_release); } - stamp_retired_windows(); // lists reset or released since the last replay - const std::uint64_t completed = context->completed_retire_ticket(); - std::lock_guard windows(title_window_mutex); - free_retired_windows(completed); if (removed.empty() && !every) return; + std::lock_guard windows(title_window_mutex); std::sort(removed.begin(), removed.end()); std::uint64_t longest = 0; for (const auto& r : removed) longest = std::max(longest, r.second); @@ -3534,7 +4350,7 @@ struct DeviceState { for (const RetiredWindow& window : due) { free_retired_shadow(window.mapped, window.start, window.size); if (window.shader_va < arena.size) { - arena_release(window.shader_va, window.size, arena_buffer); + arena_release(window.shader_va, window.size, arena_window); } else { backing(arena.address + window.shader_va, window.size, window.start, false); external_windows.free(*this, window.shader_va, window.size); @@ -3542,8 +4358,8 @@ struct DeviceState { } } // A replay has recorded its submissions, or a refresh runs: retired windows that only replays now finished and - // only lists now gone may name get the submissions recorded so far as their ticket (GeometryViews::execute_end - // does the same for its views, by replays alone). + // only lists now gone may name get the submissions recorded so far as their ticket (GeometryViews::stamp_retired + // does the same for its views). void stamp_retired_windows() { if (!retired_windows_unstamped.load(std::memory_order_acquire)) return; // Under the lock: a window retired by a replay begun after `oldest` was read must not be stamped here. @@ -3560,67 +4376,54 @@ struct DeviceState { } retired_windows_unstamped.store(left, std::memory_order_release); } - // ExecuteCommandLists replays in progress, for GeometryViews::kAfterExecutes (see drain_geometry_releases). - // 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; - } - // Kept with geometry copies off too: a retired title window waits for the same replays (stamp_retired_windows). - void 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 or " - "title window 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() { - auto& serials = geometry_execute_serials(); - 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(); }); - stamp_retired_windows(); - } static rt::d3d12::GeometryCopy copy_geometry(std::uint8_t* to, const std::uint8_t* from, std::size_t size) { using Result = rt::d3d12::GeometryCopy; if (!leonida::texture_memory_readable(reinterpret_cast(from), size)) return Result::unreadable; return copy_guarded(to, from, size, false) ? Result::copied : Result::interrupted; } - std::uint64_t geometry_va(std::uint64_t guest, std::uint64_t span, bool read_only) { - if (!geometry.cap() || !span || !guest || !watch_shadow_writes()) return 0; + // Why geometry_va gave no copy (diagnostics: the classes of V#s that resolve to nothing, fix_vsharp). + enum class NoCopy : std::uint8_t { + none, no_geometry, not_title, past_range, known_buffer, private_pages, refused, pool_alias, count + }; + // `refused` (when given) is set when a copy was asked for and refused (no room under the cap, or no block): it may + // be made once geometry copies are freed (GeometryViews::free_generation). `why`: the reason for an answer of 0. + std::uint64_t geometry_va(std::uint64_t guest, std::uint64_t span, bool read_only, bool* refused = nullptr, + NoCopy* why = nullptr, bool passive = false) { + const auto no = [why](NoCopy reason) { + if (why) *why = reason; + return std::uint64_t(0); + }; + // The page mirror holds the title's bytes at heap_base + the address the GPU names (a GPU-only page reads its + // own physical page there, not its CPU view's), so no copy is made. + if (span && guest && page_mirror.mirror && leonida::title_va_aliases().shader_va(guest, span) == guest && + page_mirror_resolve(guest, span)) { + if (!read_only) { + if (passive) note_passive_title_write(guest, span); + else note_title_write(guest, span); + } + return guest; + } + if (!geometry.cap() || !span || !guest || !watch_shadow_writes()) return no(NoCopy::no_geometry); const auto cpu = leonida::title_gpu_views::to_cpu(guest, span); auto& aliases = leonida::title_va_aliases(); const auto alias = aliases.shader_va(cpu, span); if (alias != cpu) return alias; if (cpu == guest) { std::uint64_t lo{}, hi{}; - if (!aliases.title_memory(guest, lo, hi) || span > hi - guest || context->knows_buffer_va(guest)) - return 0; + if (!aliases.title_memory(guest, lo, hi)) return no(NoCopy::not_title); + if (span > hi - guest) return no(NoCopy::past_range); + if (context->knows_buffer_va(guest)) return no(NoCopy::known_buffer); if (!read_only && !leonida::title_gpu_views::other_view(cpu)) { MEMORY_BASIC_INFORMATION region{}; - if (!VirtualQuery(reinterpret_cast(cpu), ®ion, sizeof region) || region.Type != MEM_MAPPED) - return geometry.find(cpu, span); + if (!VirtualQuery(reinterpret_cast(cpu), ®ion, sizeof region) || region.Type != MEM_MAPPED) { + const std::uint64_t found = geometry.find(cpu, span); + return found ? found : no(NoCopy::private_pages); + } } } - return geometry.resolve(*this, cpu, span, copy_geometry); + const std::uint64_t va = geometry.resolve(*this, cpu, span, copy_geometry); + if (!va && refused) *refused = true; + return va ? va : no(cpu != guest ? NoCopy::pool_alias : NoCopy::refused); } // LEONIDA_STREAM_BUFFER_WINDOWS=0: a window may not come from a block outside the arena. @@ -3632,8 +4435,10 @@ struct DeviceState { return enabled; } - // A committed page the host may read: the title's reservations start uncommitted. + // A committed page the host may read: the title's reservations start uncommitted. A page xmem's frame table holds + // (no host view: src/title_frames.h) is read through its frame. static bool readable_page(std::uint64_t address) { + if (leonida::title_frames::backed(static_cast(address))) return true; MEMORY_BASIC_INFORMATION region{}; return VirtualQuery(reinterpret_cast(static_cast(address)), ®ion, sizeof(region)) && @@ -3645,6 +4450,15 @@ struct DeviceState { static std::uint64_t readable_run_end(std::uint64_t address, std::uint64_t end) { std::uint64_t at = address; while (at < end) { + if (leonida::title_frames::may_hold(static_cast(at), static_cast(end))) { + bool backed = false; + const std::uint64_t run = leonida::title_frames::run_end(static_cast(at), + static_cast(end), backed); + if (backed) { + at = run; + continue; + } + } MEMORY_BASIC_INFORMATION region{}; if (!VirtualQuery(reinterpret_cast(static_cast(at)), ®ion, sizeof(region)) || @@ -3688,8 +4502,8 @@ struct DeviceState { } VkDeviceSize offset = 0; std::uint8_t* mapped{}; - if (arena_allocate(size, kTitleWindowAlign, offset, arena_buffer)) { - mapped = arena.mapped + offset; + if (arena_allocate(size, kTitleWindowAlign, offset, arena_window)) { + mapped = arena_host(offset, size); } else if (leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::windows); stream_windows() && external_windows.allocate(*this, size, offset, mapped)) { external_window_made.store(true, std::memory_order_release); @@ -3724,91 +4538,242 @@ struct DeviceState { title_window_bytes -= window.size; remove_shadow(window.mapped); if (window.shader_va < arena.size) { - arena_release(window.shader_va, window.size, arena_buffer); + arena_release(window.shader_va, window.size, arena_window); } else { backing(arena.address + window.shader_va, window.size, window.start, false); external_windows.free(*this, window.shader_va, window.size); } } - // 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) { + // Merges disjoint [va, end) into `ranges`, absorbing every overlapping or adjacent entry. Returns the net bytes + // added (0 when already covered). + static std::uint64_t merge_write_back_interval(std::map& ranges, std::uint64_t va, + std::uint64_t end) { + auto it = ranges.lower_bound(va); + if (it != ranges.begin() && std::prev(it)->second >= va) --it; + std::uint64_t merged_begin = va, merged_end = end; + std::uint64_t removed_bytes = 0; + std::size_t removed_count = 0; + for (auto scan = it; scan != ranges.end() && scan->first <= merged_end; ++scan) { + merged_begin = std::min(merged_begin, scan->first); + merged_end = std::max(merged_end, scan->second); + removed_bytes += scan->second - scan->first; + ++removed_count; + } + if (removed_count == 1 && merged_begin == it->first && merged_end == it->second) return 0; + for (auto scan = it; scan != ranges.end() && scan->first <= merged_end;) scan = ranges.erase(scan); + ranges.emplace(merged_begin, merged_end); + return (merged_end - merged_begin) - removed_bytes; + } + + static bool title_write_back_enabled() { 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; + return on; + } + + // A binding of the title's memory reached for the coming submission: keep its range for the copy back after it. + // Explicit writes (GPU copies, clears, WriteBufferImmediate, ResolveQueryData, BVH, root UAVs) always enter here. + void note_title_write(std::uint64_t va, std::uint64_t bytes) { + if (!title_write_back_enabled() || !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 (it != title_write_back.begin() && std::prev(it)->second >= va) --it; + std::uint64_t merged_begin = va, merged_end = end; + std::uint64_t removed_bytes = 0; + std::size_t removed_count = 0; + for (auto scan = it; scan != title_write_back.end() && scan->first <= merged_end; ++scan) { + merged_begin = std::min(merged_begin, scan->first); + merged_end = std::max(merged_end, scan->second); + removed_bytes += scan->second - scan->first; + ++removed_count; + } + if (removed_count == 1 && merged_begin == it->first && merged_end == it->second) return; + const std::uint64_t added_bytes = (merged_end - merged_begin) - removed_bytes; + if ((!removed_count && title_write_back.size() >= kTitleWriteBackRanges) || + (added_bytes && title_write_back_bytes + added_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); + for (auto scan = it; scan != title_write_back.end() && scan->first <= merged_end;) + scan = title_write_back.erase(scan); + title_write_back.emplace(merged_begin, merged_end); + title_write_back_bytes += added_bytes; + has_title_write_back.store(true, std::memory_order_release); + } + + static std::vector>& write_back_exec_stack() { + static thread_local std::vector> stack; + return stack; + } + + // Passive V# descriptor-heap range: when every loaded shader carries `writes_buffer` metadata, defer write-back + // until a submission actually executes a shader with `writes_buffer == true` (promote_passive_title_writes). + // Without complete metadata (older shader packs or shader-less tests), fall back to immediate note_title_write. + // On cap pressure across consecutive read-only submissions, evict oldest passive ranges (FIFO by sequence) instead + // of refusing, so newly resolved writable V#s always enter `passive_write_back`. + void note_passive_title_write(std::uint64_t va, std::uint64_t bytes) { + if (!writes_buffer_meta_complete.load(std::memory_order_acquire)) { + note_title_write(va, bytes); + return; + } + if (!title_write_back_enabled() || !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); + passive_write_back.note(va, end); + has_passive_title_write_back.store(!passive_write_back.empty(), std::memory_order_release); + } + + void begin_execute_write_back() { + std::uint64_t id = 0; + { + std::lock_guard lock(title_write_back_mutex); + id = passive_write_back.begin_execute(); + } + write_back_exec_stack().emplace_back(this, id); + } + + void end_execute_write_back() { + auto& stack = write_back_exec_stack(); + std::uint64_t id = 0; + for (std::size_t i = stack.size(); i > 0; --i) { + if (stack[i - 1].first == this) { + id = stack[i - 1].second; + stack.erase(stack.begin() + static_cast(i - 1)); + break; + } + } + if (!id) return; + std::lock_guard lock(title_write_back_mutex); + passive_write_back.end_execute(id); + has_passive_title_write_back.store(!passive_write_back.empty(), std::memory_order_release); + } + + // Called after a submission containing at least one emitted shader with `writes_buffer == true` reaches the GPU: + // promote pending passive console-heap V# ranges relevant to this execute into `title_write_back_pending` at + // `ticket`, stamp newly promoted entries with the max concurrent active execute ID, and prune entries once every + // concurrent execute that needed them has promoted or ended. + void promote_passive_title_writes(std::uint64_t ticket) { + if (!has_passive_title_write_back.load(std::memory_order_acquire)) return; + std::uint64_t exec_id = 0; + const auto& stack = write_back_exec_stack(); + for (std::size_t i = stack.size(); i > 0; --i) { + if (stack[i - 1].first == this) { + exec_id = stack[i - 1].second; + break; + } + } + std::lock_guard lock(title_write_back_mutex); + if (passive_write_back.empty()) { + has_passive_title_write_back.store(false, std::memory_order_release); + return; + } + std::map promoted; + const bool emitted = passive_write_back.promote(exec_id, [&](std::uint64_t begin, std::uint64_t end) { + merge_write_back_interval(promoted, begin, end); + }); + has_passive_title_write_back.store(!passive_write_back.empty(), std::memory_order_release); + if (!emitted) return; + const std::uint64_t stamp = + title_write_back_pending.empty() ? ticket : (std::max)(ticket, title_write_back_pending.back().first); + if (!title_write_back_pending.empty() && title_write_back_pending.back().first == stamp) { + auto& target = title_write_back_pending.back().second; + for (const auto& [begin, end] : promoted) merge_write_back_interval(target, begin, end); + } else { + title_write_back_pending.emplace_back(stamp, std::move(promoted)); + } + has_title_write_back.store(true, std::memory_order_release); } // 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. + // forward copy sees it. Runs FIRST in before_execute_() (before refresh_page_mirror and refresh_console_heaps), + // when pending_ sparse binds are empty and before any map()/upload() mutates homes or agreed sums. Only retired + // batches (ticket <= completed_retire_ticket()) are drained; unretired batches past kTitleWriteBackBatches are + // coalesced into the next unretired batch rather than force-drained early. All drained batches are merged into one + // disjoint sorted list so each mirrored page is read back at most once per call. 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 - { + const bool any_queued = has_title_write_back.load(std::memory_order_acquire); + const bool any_async = page_mirror.readback_async_pending.load(std::memory_order_acquire); + if (!context || (!any_queued && !any_async)) return; + std::vector> raw; + if (any_queued) { + const std::uint64_t done = context->completed_retire_ticket(); 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)}); + const std::uint64_t next_ticket = context->submitted_retire_ticket() + 1; + const std::uint64_t stamp = + title_write_back_pending.empty() + ? next_ticket + : std::max(next_ticket, title_write_back_pending.back().first); + if (!title_write_back_pending.empty() && title_write_back_pending.back().first == stamp) { + for (const auto& [begin, end] : title_write_back) + merge_write_back_interval(title_write_back_pending.back().second, begin, end); + } else { + title_write_back_pending.push_back({stamp, 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; + while (!title_write_back_pending.empty() && title_write_back_pending.front().first <= done) { for (const auto& [begin, end] : title_write_back_pending.front().second) - finished.push_back({begin, end}); + raw.emplace_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; + // Bound pending queue depth without prematurely reading back unretired GPU work: coalesce the oldest + // unretired batch into the second-oldest so it waits until both have retired. + while (title_write_back_pending.size() > kTitleWriteBackBatches) { + auto oldest = std::move(title_write_back_pending.front().second); + title_write_back_pending.pop_front(); + auto& target = title_write_back_pending.front().second; + for (const auto& [begin, end] : oldest) merge_write_back_interval(target, begin, end); + if (!title_write_back_unfenced++) + log_once("more than 64 title write-back batches wait on their submissions: coalescing oldest " + "unretired batches until they retire; batches:", + 1); + } + if (title_write_back.empty() && title_write_back_pending.empty()) + has_title_write_back.store(false, std::memory_order_release); + } + std::vector> finished; + if (!raw.empty()) { + std::sort(raw.begin(), raw.end()); + finished.reserve(raw.size()); + for (const auto& [begin, end] : raw) { + if (!finished.empty() && begin <= finished.back().second) + finished.back().second = std::max(finished.back().second, end); + else + finished.emplace_back(begin, end); + } + } 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; - } + if (!finished.empty()) { + std::unique_lock lock(shadow_mutex, std::defer_lock); + leonida::submit_phases::lock_timed(lock); + if (!shadows.empty()) { + 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; + } + } + } + const std::uint64_t mirrored = page_mirror_write_back_ranges(finished, false); // non-blocking poll/kick + written += mirrored; + ranges += mirrored != 0; title_write_back_total += written; if (!written) return; if (++title_write_back_calls <= 4 || !(title_write_back_calls & (title_write_back_calls - 1))) @@ -3971,6 +4936,8 @@ struct DeviceState { // called with it held. bool device_reachable(std::uint64_t va, bool buffers_checked = false) { if (va < arena.size) return true; + // Title memory the page mirror holds: heap_base + va is its chunk. + if (page_mirror.mirror && page_mirror_resolve(va, 1)) return true; const bool wrapped = va < (1ull << 48) && (va >> 47); const std::uint64_t candidates[2] = {va, wrapped ? va | ~((1ull << 48) - 1) : va}; auto& aliases = leonida::title_va_aliases(); @@ -4010,7 +4977,7 @@ struct DeviceState { // allocated). bool resolve_title_memory(std::uint64_t va, std::uint64_t bytes, std::uint64_t& out) { out = va; - if (!arena.mapped || !context) return false; + if (!arena_ready() || !context) return false; if (context->knows_buffer_va(va)) return false; // an upload or readback buffer's biased VA, say if (va < arena.size) { // Below the arena's size an address is an arena address unless the title's own memory is there (its @@ -4023,7 +4990,8 @@ struct DeviceState { std::uint64_t title_lo = 0, title_hi = 0; if (!aliases.title_memory(va, title_lo, title_hi)) { // Root descriptors carry a pointer without a declared length. Validate the base. - out = vsharp_address(va, 1, leonida::TitleVaAliases::root_view, false); + out = vsharp_address(va, 1, leonida::TitleVaAliases::root_view, false, false, nullptr, nullptr, nullptr, + false); return true; } const std::uint64_t want = std::max(bytes, 1); @@ -4034,6 +5002,18 @@ struct DeviceState { out = made; return true; } + // The page mirror: the address itself (heap_base + va), no window, extent or copy. + // TitleVaAliases::resolve calls note_reached(va, bytes) after we return true iff writable && out != 0. + if (page_mirror_resolve(va, want)) { + out = va; + return true; + } + // Never fall through to make_title_window / ShadowPages over memory covered by the page mirror (e.g. a span + // exceeding kMirrorNameMax): a shadow tracker over mirrored pages fights HotColdTracking's guards. + if (page_mirror.mirror && page_mirror_covers(va, 1)) { + out = 0; + return true; + } // A stream pool's address: one mapping for its readable run, shared by both of its views. if (resolve_pool_memory(va, bytes, out)) return true; if (has_mapping) { @@ -4106,7 +5086,13 @@ struct DeviceState { const std::uint64_t span = std::max(bytes, 1); auto& aliases = leonida::title_va_aliases(); std::uint64_t lo = 0, hi = 0; - if (!geometry.cap() || !watch_shadow_writes() || !aliases.title_memory(va, lo, hi) || span > hi - va) return 0; + if (!aliases.title_memory(va, lo, hi) || span > hi - va) return 0; + // In the page mirror the structure is the title's own pages (their homes keep what the GPU writes). + if (page_mirror_resolve(va, span)) { + note_title_write(va, span); + return va; + } + if (!geometry.cap() || !watch_shadow_writes()) return 0; const auto cpu = leonida::title_gpu_views::to_host_view(static_cast(va), static_cast(span)); if (context->knows_buffer_va(cpu, span)) return 0; @@ -4314,21 +5300,29 @@ struct DeviceState { // past the end. leonida::value_sink::Landing write_arena_value(std::uint64_t va, const void* bytes, unsigned size) { using leonida::value_sink::Landing; - if (!arena.mapped || va >= arena.size) return Landing::elsewhere; + if (!arena_ready() || va >= arena.size) return Landing::elsewhere; std::uint64_t title_lo = 0, title_hi = 0; if (leonida::title_va_aliases().title_memory(va, title_lo, title_hi)) return Landing::elsewhere; if (!bytes || !size || va < arena.first || size > arena.size - va) return Landing::refused; // A sparse resource's memory is bound by the sparse pass, not by the arena's mapping. if (context && context->is_sparse_va(va)) return Landing::refused; + // The value names an arena address, not an allocation this code holds: the store runs under the backing's + // shared lock, so no reclaim frees the memory under it, and an address with no memory behind it is refused. // An aligned value in one store, so a reader never sees half of it. - if (size == 4 && !(va & 3)) - std::atomic_ref(*reinterpret_cast(arena.mapped + va)) - .store(*static_cast(bytes), std::memory_order_relaxed); - else if (size == 8 && !(va & 7)) - std::atomic_ref(*reinterpret_cast(arena.mapped + va)) - .store(*static_cast(bytes), std::memory_order_relaxed); - else - std::memcpy(arena.mapped + va, bytes, size); + const bool stored = arena.backing.with_host(va, size, [&](std::uint8_t* host) { + if (size == 4 && !(va & 3)) + std::atomic_ref(*reinterpret_cast(host)) + .store(*static_cast(bytes), std::memory_order_relaxed); + else if (size == 8 && !(va & 7)) + std::atomic_ref(*reinterpret_cast(host)) + .store(*static_cast(bytes), std::memory_order_relaxed); + else + std::memcpy(host, bytes, size); + }); + if (!stored) { + note_unbacked_arena(va, size); + return Landing::refused; + } return Landing::landed; } @@ -4341,9 +5335,8 @@ struct DeviceState { std::map cpu_view_heaps; bool known_view_heap(std::uintptr_t addr) { std::lock_guard lock(visible_heap_mutex); - const auto mapped = reinterpret_cast(arena.mapped); - if (mapped && addr >= mapped && addr - mapped < arena.size) { - const auto off = addr-mapped; + std::uint64_t off = 0; + if (arena.backing.offset_of(reinterpret_cast(addr), 1, off)) { auto visible = visible_heaps.upper_bound(off); if (visible != visible_heaps.begin()) { --visible; @@ -4356,6 +5349,22 @@ struct DeviceState { --it; return addr < it->second && (addr-it->first) % kDescriptorSize == 0; } + // The T#s of a bound table in one of the layer's heaps get the index word their entry has now (tsharp_index_word): + // Create*View wrote it, but a T# whose view came later (a stream published, a texture made at the address) or went + // since, and one the title wrote raw or copied from where no index was, would otherwise keep the word of then. + void refresh_tsharp_index_words(std::uint8_t* table, VkDeviceSize bytes) { + namespace g = leonida::gfx10; + std::lock_guard lock(descriptor_mutex); + for (VkDeviceSize at = 0; at + kDescriptorSize <= bytes; at += kDescriptorSize) { + g::ImageWords words; + std::memcpy(words.data(), table + at, sizeof(words)); + if (!g::is_image(words)) continue; + const std::uint32_t word = tsharp_index_word_locked(g::tsharp_key(words)); + if (word != words[g::kTsharpIndexDword]) + std::memcpy(table + at + 4 * g::kTsharpIndexDword, &word, sizeof(word)); + } + } + // The buffer V#s of the table at `table_va` whose base is in the title's own memory get the address of a copy, // written in place: the title wrote them itself (or copied them), so no Create*View saw them. Images (T#s) and // null slots are skipped; so is a V# already in the arena, so a rewritten one is left alone next time. @@ -4375,11 +5384,15 @@ struct DeviceState { end = table_va + std::min(heap.end - table_va, VkDeviceSize(slots) * kDescriptorSize); } auto& aliases = leonida::title_va_aliases(); + // The table is in a live shader-visible heap (visible_heaps), one arena allocation: one mapping. + std::uint8_t* const table = arena_host(table_va, end - table_va); + if (!table) return; // Slots the title wrote in its own backing of this heap, if it gave the heap one. - aliases.pull_descriptors(arena.mapped + table_va, std::size_t(end - table_va)); + aliases.pull_descriptors(table, std::size_t(end - table_va)); if (sampler) return; // S# words describe sampling state. They have no buffer address to translate. + if (tsharp_index_words) refresh_tsharp_index_words(table, end - table_va); for (VkDeviceSize at = table_va; at + 16 <= end; at += kDescriptorSize) { - auto* words = reinterpret_cast(arena.mapped + at); + auto* words = reinterpret_cast(table + (at - table_va)); if (words[3] >> 30) continue; if (retry_nulled_table_slot(at, words, aliases)) continue; const std::uint32_t original[3] = {words[0], words[1], words[2]}; @@ -4475,7 +5488,10 @@ struct DeviceState { if (!(w0 | w1 | w2 | w3) || (w3 >> 30)) return false; // null, or not a buffer V# (TYPE, dword 3 bits 30-31) const std::uint64_t base = std::uint64_t(w0) | (std::uint64_t(w1 & 0xFFFFu) << 32); std::uint64_t host{}, remaining{}; - if (base < arena.size || (geometry.cap() && geometry.lookup(arena.address + base, host, remaining))) return false; + // A base already rewritten to a copy below heap_base holds the low 48 bits of a negative offset. + const std::uint64_t written = signed_vsharp_offsets() && (base & (1ull << 47)) ? base | ~((1ull << 48) - 1) : base; + if (base < arena.size || (geometry.cap() && geometry.lookup(arena.address + written, host, remaining))) + return false; const std::uint32_t stride = (w1 >> 16) & 0x3FFFu; const std::uint64_t span = std::uint64_t(w2) * (stride ? stride : 1); // A V# the layer wrote for one of its own buffers that the driver put below the arena (an upload buffer in @@ -4539,12 +5555,14 @@ struct DeviceState { // Nothing is kept before a console resource heap with a CPU copy exists (no slot has a record then). std::mutex slot_change_mutex; std::vector slot_changes; + std::atomic slot_change_count{0}; // slot_changes.size(), readable without the lock std::atomic slot_records_live{false}; void note_slot_change(leonida::SlotChange::Kind kind, std::uint64_t lo, std::uint64_t bytes) { if (!bytes || !slot_records_live.load(std::memory_order_acquire)) return; const std::uint64_t hi = lo + bytes < lo ? UINT64_MAX : lo + bytes; std::lock_guard lock(slot_change_mutex); slot_changes.push_back({kind, lo, hi}); + slot_change_count.store(slot_changes.size(), std::memory_order_release); } // A device range [address, address + bytes) as the V# bases that name it directly: arena offsets in the V#'s 48 // bits (a buffer below the arena, as sign-extended offsets, vsharp_address). Nothing for a range no V# reaches. @@ -4605,32 +5623,15 @@ struct DeviceState { enum class VsharpPath { table, shadow, scratch }; enum class VsharpResult { unchanged, rebased, empty }; - // What fix_vsharp resolved a V# to, for a console heap's slot record (ConsoleHeapSlotRecords::set). - struct VsharpRecord { - leonida::ConsoleHeapSlotRecords::State state = leonida::ConsoleHeapSlotRecords::none; - uint64_t base = 0, span = 0, target = 0; - }; - // A buffer V#'s words, and what fix_vsharp made of them (ConsoleHeap::answers). - struct VsharpWords { - std::uint64_t low = 0, high = 0; - bool operator==(const VsharpWords&) const = default; - }; - struct VsharpWordsHash { - std::size_t operator()(const VsharpWords& words) const noexcept { - return std::hash{}(words.low ^ (words.high * 0x9e3779b97f4a7c15ull)); - } - }; - struct VsharpAnswer { - std::uint32_t words[3]; - VsharpResult result; - VsharpRecord record; - }; // `refused` (when given): for an answer of 0, the copy an alias range named that was not backed (0: none), so the // console heap's slot record is found again when a backing is added there. uint64_t vsharp_address(uint64_t base, uint64_t bytes, leonida::TitleVaAliases::Kind kind = leonida::TitleVaAliases::created_view, - bool make_window = true, bool try_geometry = false, uint64_t* refused = nullptr) { + bool make_window = true, bool try_geometry = false, uint64_t* refused = nullptr, + bool* refused_room = nullptr, NoCopy* no_copy = nullptr, bool writable = true, + bool passive = false) { if (refused) *refused = 0; + if (refused_room) *refused_room = false; if (!base || !bytes) return 0; auto& aliases = leonida::title_va_aliases(); constexpr uint64_t mask = (1ull << 48) - 1; @@ -4669,6 +5670,17 @@ struct DeviceState { aliases.note_translation(kind); return path(0), to; } + // Title memory the page mirror holds: the V# names it as the title wrote it (heap_base + base is the mirror). + if (page_mirror.mirror) { + uint64_t lo{}, hi{}; + if (aliases.title_memory(base, lo, hi) && bytes <= hi - base && page_mirror_resolve(base, bytes)) { + if (writable) { + if (passive) note_passive_title_write(base, bytes); + else note_title_write(base, bytes); // a raw V# has no read/write bit; API CBVs/SRVs pass false + } + return path(6), base; + } + } // An already rewritten descriptor carries only the low 48 bits. uint64_t offset = base; if (signed_vsharp_offsets() && base <= mask && (base & (1ull << 47))) offset |= ~mask; @@ -4676,12 +5688,12 @@ struct DeviceState { // Read the other way: bit 47 as a sign, for a below-arena buffer's V# the layer wrote itself. if (offset == base && base <= mask && (base & (1ull << 47)) && backed(base | ~mask)) return base | ~mask; if (try_geometry) { - to = geometry_va(base, bytes, false); + to = geometry_va(base, bytes, false, refused_room, no_copy, passive); if (to && encodable(to)) return path(3), to; } uint64_t lo{}, hi{}; - if (make_window && aliases.title_memory(base, lo, hi) && bytes <= hi - base) { - to = aliases.resolve(base, bytes, kind); + if (make_window && bytes <= kTitleWindowMax && aliases.title_memory(base, lo, hi) && bytes <= hi - base) { + to = aliases.resolve(base, bytes, kind, writable); uint64_t mapped{}; if (to && aliases.range_of(base, mapped, room) && mapped == to && room >= bytes && backed(to)) return path(4), to; @@ -4690,7 +5702,7 @@ struct DeviceState { return path(5), 0; } // vsharp_address's outcomes (diagnostics): alias hit, alias refused, arena VA, geometry copy, window, none. - static constexpr unsigned kVsharpPathCount = 6; + static constexpr unsigned kVsharpPathCount = 7; std::array, kVsharpPathCount> vsharp_paths{}; // LEONIDA_UNBACKED_VSHARP=1 (diagnostic): the buffer V#s fix_vsharp writes empty because nothing backs their base. @@ -4732,7 +5744,41 @@ struct DeviceState { } } - VsharpResult fix_vsharp(uint32_t* w, VsharpPath path, VsharpRecord* record = nullptr) { + // What fix_vsharp resolved a V# to, for a console heap's slot record (ConsoleHeapSlotRecords::set). + struct VsharpRecord { + leonida::ConsoleHeapSlotRecords::State state = leonida::ConsoleHeapSlotRecords::none; + uint64_t base = 0, span = 0, target = 0; + bool geometry = false; // its resolution asked for a geometry copy + }; + // The classes of the V# halves a console heap resolves to nothing (diagnostics, the heap's log line): what their + // base is, as the lookups found it (note_resolution). + enum Nothing : unsigned { + nothing_refused, // an alias range or window names a copy that is not backed + nothing_arena, // an arena offset nothing backs (freed, or never handed out) + nothing_negative, // bit 47 set: a below-arena form nothing backs + nothing_no_copy, // no geometry copy asked for (no format, a span past the window limit) + nothing_not_title, // not the title's memory and not ours: freed or never allocated + nothing_past_range, // the title's memory, the span past the end of its range + nothing_known_buffer, // the title's memory under a buffer the device has (its V# is the buffer's) + nothing_private, // the title's private pages: a heap's V# finds a copy but makes none + nothing_room, // a copy refused for room or a block + nothing_pool_alias, // the GPU-only view of pool memory whose copy was refused + nothing_other, // no geometry copies at all, or the base is 0 + nothing_classes + }; + static constexpr const char* kNothingNames[nothing_classes] = { + "copy not backed", "arena offset", "bit 47", "no copy asked", "not title memory", "past its range", + "a buffer's", "private pages", "no room", "pool alias", "other"}; + struct ConsoleHeap; + // `heap` (a console heap's slot): its counters (resolutions, their time, the classes of V#s that resolve to + // nothing). `answers` (a slot the title rewrote): a V# whose exact range another half of that heap has a record + // for, made the same way, takes that half's answer (ConsoleHeapSlotRecords::answer) after the changes noted since + // are applied (sync_slot_changes): a record is fixed again by every change that could alter its answer, so a + // current one gives what resolving again would. In the world 63-70% of the changed V# halves carry words seen + // before, and each resolution walked the alias table, the backings, the geometry copies and the title memory + // (VirtualQuery included) again. + VsharpResult fix_vsharp(uint32_t* w, VsharpPath path, VsharpRecord* record = nullptr, ConsoleHeap* heap = nullptr, + bool answers = false) { 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); const uint32_t stride = (w[1] >> 16) & 0x3fffu; @@ -4741,14 +5787,37 @@ struct DeviceState { leonida::gfx10::Buffer desc{}; const bool copy_geometry = leonida::gfx10::decode(words, desc) && (path != VsharpPath::scratch || span <= kTitleWindowMax || (desc.format && leonida::gfx10::encode(desc) == words)); + if (heap && answers && record && answered_by_record(*heap, base, span, copy_geometry, *record)) { + if (record->state == leonida::ConsoleHeapSlotRecords::resolved) { + const uint64_t to = record->target - arena.address; // mod 2^64, as it was recorded + if ((to & ((1ull << 48) - 1)) == base) { + if (page_mirror.mirror && to == base && base >= arena.size) note_passive_title_write(base, span); + return VsharpResult::unchanged; + } + w[0] = uint32_t(to); + w[1] = (w[1] & 0xffff0000u) | uint32_t((to >> 32) & 0xffff); + return VsharpResult::rebased; + } + note_unbacked_vsharp(base, span, stride, w); + w[0] = w[1] = w[2] = 0; + return VsharpResult::empty; + } uint64_t refused = 0; + bool refused_room = false; + NoCopy no_copy = NoCopy::none; + const auto start = heap ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{}; const auto to = vsharp_address(base, span, leonida::TitleVaAliases::table_view, - path != VsharpPath::scratch, copy_geometry, &refused); + path != VsharpPath::scratch, copy_geometry, &refused, &refused_room, &no_copy, + true, true); + if (heap) note_resolution(*heap, start, base, to, refused, copy_geometry, no_copy); if (record) { - // The copy's device address (mod 2^64: a buffer below the arena has a negative offset). - record->state = to ? leonida::ConsoleHeapSlotRecords::resolved : leonida::ConsoleHeapSlotRecords::waiting; + // The copy's device address (mod 2^64: a buffer below the arena has a negative offset). A geometry copy + // refused for room is asked for again when copies are freed (SlotChange::geometry_room). + using Records = leonida::ConsoleHeapSlotRecords; + record->state = to ? Records::resolved : refused_room ? Records::waiting_room : Records::waiting; record->base = base; record->span = span; + record->geometry = copy_geometry; record->target = to ? arena.address + to : refused ? arena.address + refused : 0; } if (!to) { @@ -4783,11 +5852,16 @@ struct DeviceState { // dwords 32-33) is its device address. It is at most 4 GiB, so every VA fits the 32-bit descriptor-table // pointers some shaders use, and no larger than the device's maxBufferSize and maxMemoryAllocationSize // (src/arena_size.h). The first 64 KiB are never handed out, so no resource has VA 0. + // Its memory (src/arena_backing.h): with sparse binding, 2 MiB blocks bound as allocations need them and unbound + // once the GPU is past their last use; without, one allocation over the whole arena (`memory`). The CPU reaches + // an arena offset through arena_host() (or backing.with_host for an offset the caller does not hold), never by + // adding it to one base pointer: a sparse arena has no single mapping. struct Arena { VkBuffer buffer = VK_NULL_HANDLE; bool indirect_arguments = false; - VkDeviceMemory memory = VK_NULL_HANDLE; - std::uint8_t* mapped = nullptr; + VkDeviceMemory memory = VK_NULL_HANDLE; // without sparse binding only + leonida::ArenaBacking backing; + bool memory_type_known = false; VkDeviceAddress address = 0; VkDeviceSize size = 0; VkDeviceSize first = 0; // the first offset handed out: below it are the null region and kArenaReserved @@ -4804,7 +5878,7 @@ struct DeviceState { // most bytes live at once, which differs from it by fragmentation. bool log = false; // LEONIDA_ARENA_LOG=1: one line per VA handed out VkDeviceSize in_use = 0, peak_in_use = 0, peak_end = 0; - VkDeviceSize use_in_use[4] = {}, use_peak[4] = {}; + VkDeviceSize use_in_use[5] = {}, use_peak[5] = {}; std::uint64_t allocations = 0, failures = 0; } arena; @@ -4830,9 +5904,1637 @@ struct DeviceState { return result; } + // The page mirror (src/title_mirror.h): the title's GPU-readable pages at heap_base + their title address, so a V# + // or a pointer the title wrote into its own memory reads them unchanged. Made once the sparse arena exists + // (create_page_mirror), fed by xmem (src/title_frames.h, Feed), brought up to date before every submission + // (refresh_page_mirror). Off (nothing made, every path as before) without bufferDeviceAddressCaptureReplay, aliased + // strict sparse residency, the arena's bind queue, a sparse arena or signed V# offsets, or with LEONIDA_PAGE_MIRROR=0. + struct PageMirror { + std::mutex mutex; // everything below but `feed` + std::unique_ptr mirror; + std::vector chunks; + VkSemaphore timeline = VK_NULL_HANDLE; // signalled by each bind batch + std::uint64_t value = 0; + std::uint64_t space_generation = ~std::uint64_t(0); + // xmem's feed, queued under its own lock on the runtime's heap (xmem calls it with its locks held). + struct Change { + std::uintptr_t page; + std::uint8_t* frame; + std::shared_ptr keep; + }; + SRWLOCK feed_lock = SRWLOCK_INIT; + leonida::host_heap::vector feed; + std::atomic feed_pending{false}; + std::atomic space_gen_atomic{0}; + std::atomic in_place_pending{false}; + std::atomic refresh_in_flight{0}; + std::atomic flush_in_flight{0}; + std::atomic fast_refreshes{0}; + std::atomic resolved_fast{0}; + std::atomic clipped_fast{0}; + std::atomic since_ns_atomic{ + std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()) + .count()}; + // Read-mostly snapshot of chunk coverage (base -> VkBuffer) + plain/ensured intervals so title recording + // threads calling page_mirror_resolve() / page_mirror_buffer() take a shared lock and never contend on + // page_mirror.mutex against async workers. + // Lock order: page_mirror.mutex -> resolve_cache.mutex (never reversed). + struct ResolveCache { + std::shared_mutex mutex; + std::uint64_t space_generation = 0; + std::vector> chunks; + std::map plain, ensured; + } resolve_cache; + std::vector taken; + struct FeedOrder { + std::uintptr_t page = 0; + std::uint32_t seq = 0; + }; + struct FeedCollapsed { + std::uint32_t seq = 0; + bool had_prior = false; + }; + std::vector feed_order; + std::vector feed_collapsed; + std::vector feed_unwatch; + std::vector feed_watch; + // Which mirrored pages the host wrote (src/title_mirror_tracking.h): a policy behind a small interface, the + // plainest correct one (a guard on every page) until a measured one replaces it. + std::unique_ptr tracking; + std::vector written; + std::vector fed_now; // pages a change of this refresh mapped (sorted when non-empty) + // Ordinary title memory (not physical pages) in the mirror's range: base -> end of each such reservation, the + // runs of it whose pages are mirrored (merged: begin -> end), and those pages. Mirrored as readers name it + // (page_mirror_resolve): each page its own home, filled from the page itself. A release or decommit there + // (geometry_writes::note_released) unmaps them. + std::map plain, ensured; + std::set identity; + leonida::geometry_writes::ReleaseQueue released; + std::vector> released_ranges; + // Since the last log line. + std::uint64_t refreshes = 0, fed = 0, dirty = 0, uploads = 0, batches = 0, binds = 0, arm_failures = 0; + std::uint64_t resolved = 0, resolve_refused = 0, identity_mapped = 0, identity_released = 0, clipped = 0; + std::uint64_t written_back = 0, buffers = 0; + std::uint64_t units_local = 0, units_host = 0; // home units by memory, all so far + bool last_local = true; + std::uint64_t presents = 0; // present serial at the last log line + std::uint64_t faults_seen = 0, hot_seen = 0, cold_seen = 0; // the tracking's counters at the last log line + std::uint64_t uploaded_seen = 0, conflicts_seen = 0; // the mirror's, likewise + std::uint64_t unbinds_seen = 0, homes_freed_seen = 0; + // The write-back's GPU copy of the homes it looks at (page_mirror_write_back_ranges): a host-cached buffer of + // kReadbackPages pages, its command buffer and fence, made at the first write-back. Protected by + // `readback_mutex` (lock order: `readback_mutex` -> `mutex`, never the reverse) so `mutex` is released across + // the GPU copy and `vkWaitSemaphores`. And its cost since the last line: calls, milliseconds (the copies' + // waits among them), the most one took, the bytes copied. + std::mutex readback_mutex; + VkBuffer readback = VK_NULL_HANDLE; + VkDeviceMemory readback_memory = VK_NULL_HANDLE; + const std::uint8_t* readback_host = nullptr; + VkCommandPool readback_pool = VK_NULL_HANDLE; + VkCommandBuffer readback_commands = VK_NULL_HANDLE; + VkSemaphore readback_done = VK_NULL_HANDLE; // a timeline: value readback_value once the last copy is done + std::uint64_t readback_value = 0; + bool readback_failed = false; + bool readback_in_flight = false; // under `mutex`: another thread is copying homes out; note mutations below + // Lock order: readback_mutex -> page_mirror.mutex -> readback_submit_mutex -> submit_mutex / arena.mutex. + // Serialises readback copy submission against hooks.bind so vkQueueBindSparse never races ahead of an + // in-flight vkCmdCopyBuffer or waits on an unsubmitted readback_done semaphore value. + std::mutex readback_submit_mutex; + std::atomic readback_active_value{0}; // timeline value on readback_done for the submitted copy + std::unordered_set readback_invalidated; // under `mutex`: physical frames invalidated during copy + std::vector readback_slice_frames; // under `mutex`: sorted unique frames in active slice + std::vector> readback_slice_skip_masks; // under `mutex`: upload()-modified pieces per slice frame + std::unique_ptr readback_hash_pool; // under `readback_mutex`: lock-free Phase 1 hasher + leonida::TitleMirror::PrehashedReadback readback_prehashed; // under `readback_mutex`: reusable Phase 1 sums + std::vector> readback_exec_skip_masks; // under `readback_mutex`: Phase 2 per-slice masks + std::vector readback_exec_skip_page; // under `readback_mutex`: Phase 2 skip flags + struct AsyncReadback { + bool active = false; + std::uint64_t signal_value = 0; + std::vector slice; + std::vector> ranges; + std::vector remaining_refs; + std::size_t remaining_cursor = 0; + double cpu_ms = 0; + double waited_ms = 0; + std::uint64_t read_bytes = 0; + std::uint64_t slice_copied_bytes = 0; + std::uint64_t written = 0; + } readback_async; // under `readback_mutex` + std::vector> readback_queued_ranges; // under `readback_mutex` + std::atomic readback_async_pending{false}; // lock-free hint for write_back_titles() + std::uint64_t write_back_calls = 0, read_back_bytes = 0; + double write_back_ms = 0, write_back_wait_ms = 0, write_back_max_ms = 0; + double ms = 0; + // 7-part sub-split telemetry since the last 10 s log (ns / counts, under `mutex`). + std::uint64_t split_lock_ns = 0, split_feed_ns = 0, split_collect_ns = 0; + std::uint64_t split_arm_ns = 0, split_upload_ns = 0, split_filter_ns = 0, split_other_ns = 0; + std::uint64_t split_vp_calls = 0, split_vq_calls = 0; + std::uint64_t split_fast_tiles = 0, split_slow_tiles = 0, split_skip_tiles = 0; + std::uint64_t split_bridged_runs = 0, split_wc_tiles = 0; + std::uint64_t split_whole_pages = 0, split_inc_pages = 0, split_alias_pages = 0; + std::uint64_t retire_poll_skip = 0; + std::vector resolve_watch; + std::chrono::steady_clock::time_point since = std::chrono::steady_clock::now(); + // The console heaps read in place (add_heap_in_place): their filter state is under this mutex too. + std::vector in_place; + // Reusable 64 KiB scratch buffer for filter_heap_page (under `mutex`; falls back to heap only if reentrant). + std::array filter_scratch{}; + bool filter_scratch_in_use = false; + } page_mirror; + + static void page_mirror_feed(void* context, std::uintptr_t page, std::uint8_t* frame, const std::shared_ptr& keep) { + auto& m = static_cast(context)->page_mirror; + AcquireSRWLockExclusive(&m.feed_lock); + m.feed.push_back({page, frame, keep}); + m.feed_pending.store(true, std::memory_order_release); + ReleaseSRWLockExclusive(&m.feed_lock); + } + + static bool page_mirror_wanted() { + static const bool on = [] { + const char* v = std::getenv("LEONIDA_PAGE_MIRROR"); + return !(v && v[0] == '0'); + }(); + return on; + } + + void create_page_mirror(bool sparse_aliasing) { + const char* why = nullptr; + if (!page_mirror_wanted()) why = "LEONIDA_PAGE_MIRROR=0"; + else if (!sparse_aliasing || !sparse_buffer_memory_types) why = "no aliased strict sparse buffers"; + else if (!info.buffer_device_address_capture_replay) why = "no bufferDeviceAddressCaptureReplay"; + else if (!info.arena_bind_queue) why = "no queue of its own for sparse binds"; + else if (!arena.backing.sparse()) why = "the arena is one allocation"; + else if (!signed_vsharp_offsets()) why = "the shaders read V# bases unsigned"; + else if (!leonida::title_frames::attach_fn.load(std::memory_order_acquire)) why = "xmem is not loaded"; + else if (!watch_shadow_writes()) why = "no write-fault handler to see the title's writes"; + if (why) { + std::fprintf(stderr, "[rt] d3d12: page mirror off: %s; title-written addresses read as before\n", why); + return; + } + auto& vk = context->vk; + VkSemaphoreTypeCreateInfo timeline_type{VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO}; + timeline_type.semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE; + VkSemaphoreCreateInfo semaphore{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, &timeline_type}; + if (vk.vkCreateSemaphore(info.device, &semaphore, nullptr, &page_mirror.timeline) != VK_SUCCESS) { + std::fprintf(stderr, "[rt] d3d12: page mirror off: no timeline semaphore\n"); + return; + } + leonida::TitleMirrorHooks hooks; + hooks.make_chunk = [this](std::uint64_t title_base, std::uint64_t bytes, VkBuffer& out) { + auto& f = context->vk; + VkBufferOpaqueCaptureAddressCreateInfo at{VK_STRUCTURE_TYPE_BUFFER_OPAQUE_CAPTURE_ADDRESS_CREATE_INFO}; + const std::uint64_t want = arena.address + title_base; + at.opaqueCaptureAddress = want; + VkBufferCreateInfo create = sparse_buffer_info(bytes); + create.flags |= VK_BUFFER_CREATE_DEVICE_ADDRESS_CAPTURE_REPLAY_BIT; + at.pNext = create.pNext; + create.pNext = &at; + if (f.vkCreateBuffer(info.device, &create, nullptr, &out) != VK_SUCCESS) return false; + VkBufferDeviceAddressInfo address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; + address.buffer = out; + const std::uint64_t got = f.vkGetBufferDeviceAddress(info.device, &address); + if (got != want) { + std::fprintf(stderr, "[rt] d3d12: page mirror: the chunk for title 0x%llx came at 0x%llx, not 0x%llx\n", + static_cast(title_base), static_cast(got), + static_cast(want)); + f.vkDestroyBuffer(info.device, out, nullptr); + out = VK_NULL_HANDLE; + return false; + } + page_mirror.chunks.push_back(out); + return true; + }; + // Where a unit of homes goes, decided per unit as it is made: device-local memory while the device's budget + // (VK_EXT_memory_budget) keeps room for the title's textures and render targets after it (kHomeHeadroom, or an + // eighth of the budget if more), host memory otherwise; the GPU then reads those homes over the bus. A + // device without the budget extension, or with every heap device-local (an integrated GPU), keeps device-local. + hooks.make_unit = [this](VkDeviceMemory& out, std::uint8_t*& host) { + VkMemoryRequirements requirements{}; + requirements.size = leonida::TitleMirror::kUnitBytes; + requirements.alignment = leonida::TitleMirror::kPage; + requirements.memoryTypeBits = sparse_buffer_memory_types; + std::uint32_t host_types = 0; // the sparse buffers' memory types outside device-local heaps + for (std::uint32_t t = 0; t < memory.memoryTypeCount; ++t) + if ((sparse_buffer_memory_types >> t & 1) && + !(memory.memoryTypes[t].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)) + host_types |= 1u << t; + bool local = true; + if (host_types) { + const leonida::VramBudget budget = read_vram_budget(info); + if (budget.available) { + constexpr std::uint64_t kHomeHeadroom = std::uint64_t(1536) << 20; + const std::uint64_t headroom = std::max(kHomeHeadroom, budget.local_budget / 8); + local = budget.local_usage + leonida::TitleMirror::kUnitBytes + headroom <= budget.local_budget; + } + } + if (!local) requirements.memoryTypeBits = host_types; + leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::mirror); + out = allocate(requirements, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, + local ? VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT : VK_MEMORY_PROPERTY_HOST_CACHED_BIT); + if (out) { + ++(local ? page_mirror.units_local : page_mirror.units_host); + if (local != page_mirror.last_local) { + page_mirror.last_local = local; + std::fprintf(stderr, "[rt] d3d12: page mirror: homes go to %s from now on (%llu units in device-local " + "memory, %llu in host memory so far)\n", + local ? "device-local memory again: the budget has room" + : "host memory (the GPU reads them over the bus): device-local memory is near " + "its budget", + static_cast(page_mirror.units_local), + static_cast(page_mirror.units_host)); + } + } + void* mapped = nullptr; + if (!out || context->vk.vkMapMemory(info.device, out, 0, VK_WHOLE_SIZE, 0, &mapped) != VK_SUCCESS) { + if (out) context->vk.vkFreeMemory(info.device, out, nullptr); + out = VK_NULL_HANDLE; + return false; + } + host = static_cast(mapped); + return true; + }; + hooks.free_unit = [this](VkDeviceMemory memory) { context->vk.vkFreeMemory(info.device, memory, nullptr); }; + // On the arena's bind queue, under the arena's lock (its external synchronisation, see create_arena). + hooks.bind = [this](const std::vector& binds, std::uint64_t value) { + std::lock_guard readback_submit_guard(page_mirror.readback_submit_mutex); + const std::uint64_t wait_readback = + (page_mirror.readback_in_flight && page_mirror.readback_done) + ? page_mirror.readback_active_value.load(std::memory_order_acquire) + : 0; + VkTimelineSemaphoreSubmitInfo signal{VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO}; + signal.waitSemaphoreValueCount = wait_readback ? 1u : 0u; + signal.pWaitSemaphoreValues = &wait_readback; + signal.signalSemaphoreValueCount = 1; + signal.pSignalSemaphoreValues = &value; + VkBindSparseInfo bind{VK_STRUCTURE_TYPE_BIND_SPARSE_INFO, &signal}; + bind.waitSemaphoreCount = wait_readback ? 1u : 0u; + bind.pWaitSemaphores = &page_mirror.readback_done; + bind.bufferBindCount = std::uint32_t(binds.size()); + bind.pBufferBinds = binds.data(); + bind.signalSemaphoreCount = 1; + bind.pSignalSemaphores = &page_mirror.timeline; + std::lock_guard lock(arena.mutex); + const VkResult result = context->observe_result( + context->vk.vkQueueBindSparse(info.arena_bind_queue, 1, &bind, VK_NULL_HANDLE), "vkQueueBindSparse (page mirror)"); + if (result == VK_ERROR_DEVICE_LOST) context->mark_device_lost(); + return result == VK_SUCCESS; + }; + hooks.copy = [this](std::uint8_t* to, const std::uint8_t* from, std::size_t bytes) { + const bool streaming = + page_mirror.tracking && page_mirror.tracking->is_wc_page(reinterpret_cast(from)); + return copy_guarded_host(to, from, bytes, streaming); + }; + hooks.copy_and_sum = [this](std::uint8_t* to, const std::uint8_t* from, std::size_t pieces, + std::uint64_t* sums) { + const bool streaming = + page_mirror.tracking && page_mirror.tracking->is_wc_page(reinterpret_cast(from)); + if (streaming) { + if (!copy_guarded_host(to, from, pieces * leonida::shadow_keep::kPiece, true)) return false; + leonida::shadow_keep::sum_of_batch_256(to, pieces, sums); + return true; + } + return copy_and_sum_guarded_host(to, from, pieces, sums); + }; + // The pages of a console heap read in place (add_heap_in_place): their home holds the filtered slots. + hooks.filter = [this](std::uint64_t va, std::uint8_t* to, const std::uint8_t* from, std::size_t bytes, bool fresh) { + return filter_heap_page(va, to, from, bytes, fresh); + }; + hooks.filter_pieces = [this](std::uint64_t va, std::uint8_t* to, const std::uint8_t* scratch, std::size_t bytes, + bool fresh, const std::array& changed_pieces) { + return filter_heap_page_pieces(va, to, scratch, bytes, fresh, changed_pieces); + }; + page_mirror.mirror = std::make_unique(std::move(hooks)); + page_mirror.tracking = std::make_unique(); + leonida::geometry_writes::subscribe(page_mirror.released); + // A vertex, index, copy or indirect-argument address no buffer of ours holds is looked up in the mirror. + context->set_mirror_buffer([this](std::uint64_t va, std::uint64_t& size, VkBuffer& buffer, VkDeviceSize& offset) { + return page_mirror_buffer(va, size, buffer, offset); + }); + leonida::title_frames::attach_fn.load(std::memory_order_acquire)(this, &page_mirror_feed); + std::fprintf(stderr, "[rt] d3d12: page mirror on: the title's reservations in [0x%llx, 0x%llx) at heap_base + " + "their address (0x%llx up), bound to one home per physical page\n", + static_cast(leonida::title_mirror_space::kLow), + static_cast(leonida::title_mirror_space::kHigh), + static_cast(arena.address + leonida::title_mirror_space::kLow)); + } + + // For the readers that move onto the mirror (descriptor heaps read in place, geometry, shadows): whether every + // page of [va, va + bytes) lies in a chunk of the mirror (a page with nothing bound reads zero there), and the + // device address that holds the title address `va`. Every submission of command lists waits for the mirror's last + // bind (VulkanContext::note_mirror_bind), so a reader recorded after refresh_page_mirror sees what it bound. + bool page_mirror_covers(std::uint64_t va, std::uint64_t bytes) { + if (!page_mirror.mirror || !bytes || va + bytes < va) return false; + std::lock_guard lock(page_mirror.mutex); + sync_mirror_space_locked(); // a reservation made just now (a heap in it, say) is covered at once + for (std::uint64_t c = va & ~(leonida::TitleMirror::kChunk - 1); c < va + bytes; c += leonida::TitleMirror::kChunk) + if (!page_mirror.mirror->covers(c)) return false; + return true; + } + std::uint64_t page_mirror_address(std::uint64_t va) const { return arena.address + va; } + + // Whether a V# naming [base, base + span) can be read as the title wrote it, by a heap read in place: heap_base + + // its base lies in the sparse arena (where nothing is bound reads zero), in title memory the mirror holds (named + // to it as vsharp_address's mirror path does, page_mirror_resolve_locked: ordinary memory is mirrored then; + // `mirrored` says so, for the write-back of what shaders store there), or in a non-sparse buffer or geometry copy + // of ours (including below-arena bit-47 V#s regardless of signed_vsharp_offsets(), matching vsharp_address; when + // `tracked_target` is given, it receives the backing's device address so the slot records a resolved target and + // is re-filtered on target_gone). page_mirror.mutex held: only the in-place filter asks. + bool reachable_as_written(std::uint64_t base, std::uint64_t span, bool& mirrored, + std::uint64_t* tracked_target = nullptr) { + constexpr std::uint64_t mask = (1ull << 48) - 1; + mirrored = false; + if (tracked_target) *tracked_target = 0; + if (!base) return false; + if (!span) span = 1; + const auto encodable = [&](std::uint64_t offset) { + const std::uint64_t limit = signed_vsharp_offsets() ? mask / 2 : mask; + if (offset <= limit) return span - 1 <= limit - offset; + return offset >= UINT64_MAX - mask / 2 && span - 1 <= mask / 2 - offset; + }; + const auto backed_direct = [&](std::uint64_t offset) { + if (!encodable(offset)) return false; + const VkDeviceAddress bda = arena.address + offset; + bool ok = false; + { + std::lock_guard lock(backing_mutex); + ok = gpu_backings.covers(bda, span); + } + if (!ok && geometry.cap()) { + std::uint64_t host{}, room{}; + ok = geometry.lookup(bda, host, room) && room >= span; + } + if (ok && tracked_target) *tracked_target = bda; + return ok; + }; + std::uint64_t offset = base; + if (signed_vsharp_offsets() && base <= mask && (base & (1ull << 47))) offset |= ~mask; + if (offset < arena.size && span <= arena.size - offset) return true; + if (page_mirror.mirror && offset == base && page_mirror_resolve_locked(base, span, true)) return mirrored = true; + if (backed_direct(offset)) return true; + // Read the other way: bit 47 as a sign, for a below-arena buffer's V# the layer wrote itself (vsharp_address). + if (offset == base && base <= mask && (base & (1ull << 47)) && backed_direct(base | ~mask)) return true; + return false; + } + + // Title memory [va, va + bytes) as a reader names it (a V#, a root view, a vertex or index view, a stream-pool + // range): true when the mirror holds all of it, and then the shader VA of the range is `va` itself (heap_base + + // va). Physical pages are in the mirror as xmem maps them; ordinary memory is mirrored here, page by page, the first + // time a reader names it (watched first, then filled; bound at this submission's flush). False (the caller keeps + // its old backing) when the mirror is off, a page lies outside every chunk, or more than kMirrorNameMax of + // ordinary memory not mirrored yet is named at once (a V# with a wild size: counted). + static constexpr std::uint64_t kMirrorNameMax = std::uint64_t(256) << 20; + bool page_mirror_resolve(std::uint64_t va, std::uint64_t bytes) { + if (!page_mirror.mirror || !bytes || va + bytes < va) return false; + // Fast shared-lock check for already-covered & already-ensured ranges (avoids page_mirror.mutex contention + // between title recording threads and async queue submit workers). + { + auto& rc = page_mirror.resolve_cache; + std::shared_lock shared(rc.mutex); + if (rc.space_generation == leonida::title_mirror_space::generation() && !rc.chunks.empty()) { + constexpr std::uint64_t kChunk = leonida::TitleMirror::kChunk; + constexpr std::uint64_t kPage = leonida::TitleMirror::kPage; + const std::uint64_t end = va + bytes; + bool covered = true; + for (std::uint64_t c = va & ~(kChunk - 1); c < end; c += kChunk) { + const auto it = std::lower_bound( + rc.chunks.begin(), rc.chunks.end(), c, + [](const auto& entry, std::uint64_t key) { return entry.first < key; }); + if (it == rc.chunks.end() || it->first != c) { + covered = false; + break; + } + if (c > UINT64_MAX - kChunk) break; + } + if (covered) { + bool all_ensured = true; + auto it = rc.plain.upper_bound(va); + if (it != rc.plain.begin() && std::prev(it)->second > va) --it; + for (; it != rc.plain.end() && it->first < end; ++it) { + const std::uint64_t from = (std::max)(it->first, va) & ~(kPage - 1); + const std::uint64_t to = ((std::min)(it->second, end) + kPage - 1) & ~(kPage - 1); + auto eit = rc.ensured.upper_bound(from); + if (eit == rc.ensured.begin() || std::prev(eit)->first > from || std::prev(eit)->second < to) { + all_ensured = false; + break; + } + } + if (all_ensured) { + page_mirror.resolved_fast.fetch_add(1, std::memory_order_relaxed); + return true; + } + } else { + return false; + } + } + } + std::lock_guard lock(page_mirror.mutex); + return page_mirror_resolve_locked(va, bytes, true); + } + // The reservations xmem placed since the last look get chunks, and the ordinary ones are known as such + // (page_mirror.mutex held). + void sync_mirror_space_locked() { + auto& m = page_mirror; + const std::uint64_t g = leonida::title_mirror_space::generation(); + if (g == m.space_generation) return; + m.space_generation = g; + m.plain.clear(); + std::vector> covered_chunks; + leonida::title_mirror_space::for_each_taken([&](std::uint64_t base, std::uint64_t end, bool plain) { + m.mirror->cover(base, end); + if (plain) m.plain[base] = end; + constexpr std::uint64_t kChunk = leonida::TitleMirror::kChunk; + for (std::uint64_t c = base & ~(kChunk - 1); c < end; c += kChunk) { + VkBuffer buf = VK_NULL_HANDLE; + VkDeviceSize off = 0; + if (m.mirror->chunk_at(c, buf, off)) covered_chunks.emplace_back(c, buf); + if (c > UINT64_MAX - kChunk) break; + } + }); + std::sort(covered_chunks.begin(), covered_chunks.end(), + [](const auto& a, const auto& b) { return a.first < b.first; }); + covered_chunks.erase( + std::unique(covered_chunks.begin(), covered_chunks.end(), + [](const auto& a, const auto& b) { return a.first == b.first; }), + covered_chunks.end()); + { + std::unique_lock rc_lock(m.resolve_cache.mutex); + // TitleMirror never removes covered chunks until destroy_page_mirror(), so union monotonically to keep + // resolve_cache.chunks 100% identical to m.mirror->covers()/chunk_at() even if a reservation is released. + m.resolve_cache.chunks.insert(m.resolve_cache.chunks.end(), covered_chunks.begin(), covered_chunks.end()); + std::sort(m.resolve_cache.chunks.begin(), m.resolve_cache.chunks.end(), + [](const auto& a, const auto& b) { return a.first < b.first; }); + m.resolve_cache.chunks.erase( + std::unique(m.resolve_cache.chunks.begin(), m.resolve_cache.chunks.end(), + [](const auto& a, const auto& b) { return a.first == b.first; }), + m.resolve_cache.chunks.end()); + m.resolve_cache.plain = m.plain; + m.resolve_cache.ensured = m.ensured; + m.resolve_cache.space_generation = g; + } + m.space_gen_atomic.store(g, std::memory_order_release); + } + bool page_mirror_resolve_locked(std::uint64_t va, std::uint64_t bytes, bool make, bool defer_fill = false) { + auto& m = page_mirror; + if (!bytes || va + bytes < va) return false; + sync_mirror_space_locked(); + constexpr std::uint64_t kPage = leonida::TitleMirror::kPage; + const std::uint64_t end = va + bytes; + for (std::uint64_t c = va & ~(leonida::TitleMirror::kChunk - 1); c < end; c += leonida::TitleMirror::kChunk) + if (!m.mirror->covers(c)) return false; + auto it = m.plain.upper_bound(va); + if (it != m.plain.begin() && std::prev(it)->second > va) --it; + for (; it != m.plain.end() && it->first < end; ++it) { + const std::uint64_t from = (std::max)(it->first, va) & ~(kPage - 1); + const std::uint64_t to = ((std::min)(it->second, end) + kPage - 1) & ~(kPage - 1); + if (ensured_covers(from, to)) continue; + if (!make) return false; + if (to - from > kMirrorNameMax) { + ++m.resolve_refused; + return false; + } + m.resolve_watch.clear(); + for (std::uint64_t page = from; page < to; page += kPage) { + if (!m.mirror->mirrored(page)) m.resolve_watch.push_back(page); + } + if (!m.resolve_watch.empty()) { + // Watch before filling so any write after the fill is in the next collect. + m.tracking->watch_batch(m.resolve_watch.data(), m.resolve_watch.size()); + for (const std::uint64_t page : m.resolve_watch) { + auto* const frame = reinterpret_cast(static_cast(page)); + note_readback_frame_invalidated_locked(frame); + m.mirror->map(page, frame, nullptr, leonida::TitleMirror::kUnstamped, defer_fill); + m.identity.insert(page); + ++m.identity_mapped; + } + } + ensure_run(from, to); + } + ++m.resolved; + return true; + } + // The merged runs of mirrored ordinary memory (page_mirror.mutex held). + bool ensured_covers(std::uint64_t from, std::uint64_t to) const { + const auto& e = page_mirror.ensured; + auto it = e.upper_bound(from); + if (it == e.begin()) return false; + --it; + return it->first <= from && it->second >= to; + } + void ensure_run(std::uint64_t from, std::uint64_t to) { + auto& e = page_mirror.ensured; + auto it = e.upper_bound(from); + if (it != e.begin() && std::prev(it)->second >= from) --it; + while (it != e.end() && it->first <= to) { + from = std::min(from, it->first); + to = std::max(to, it->second); + it = e.erase(it); + } + e[from] = to; + std::unique_lock rc_lock(page_mirror.resolve_cache.mutex); + page_mirror.resolve_cache.ensured = e; + } + // A slot-133 buffer over mirrored title memory (Resource::create_mirror_buffer): the chunk and offset that hold + // all of [va, va + bytes), naming it to the mirror first. False when the mirror does not hold all of it or it + // spans two chunks (one buffer binding cannot): the buffer then gets its old backing. + bool page_mirror_chunk(std::uint64_t va, std::uint64_t bytes, VkBuffer& buffer, VkDeviceSize& offset) { + if (!page_mirror.mirror || !bytes) return false; + std::lock_guard lock(page_mirror.mutex); + if (!page_mirror_resolve_locked(va, bytes, true, /*defer_fill=*/true) || + !page_mirror.mirror->chunk_at(va, buffer, offset) || + bytes > leonida::TitleMirror::kChunk - offset) + return false; + ++page_mirror.buffers; + return true; + } + + // VulkanContext's mirror lookup (set_mirror_buffer): the chunk and offset that hold [va, va + size), when the mirror + // holds all of it already (named before: nothing is mirrored during a replay, whose binds would land after it). A + // range that runs past its chunk is cut at the chunk's end (counted): a buffer binding cannot span two chunks. + bool page_mirror_buffer(std::uint64_t va, std::uint64_t& size, VkBuffer& buffer, VkDeviceSize& offset) { + if (!page_mirror.mirror || !size || va + size < va) return false; + // Shared-lock fast path via resolve_cache so concurrent queue replays never stall behind + // refresh_page_mirror()'s page_mirror.mutex hold. + { + auto& rc = page_mirror.resolve_cache; + std::shared_lock shared(rc.mutex); + if (rc.space_generation == leonida::title_mirror_space::generation() && !rc.chunks.empty()) { + constexpr std::uint64_t kChunk = leonida::TitleMirror::kChunk; + constexpr std::uint64_t kPage = leonida::TitleMirror::kPage; + const std::uint64_t end = va + size; + VkBuffer first_chunk = VK_NULL_HANDLE; + for (std::uint64_t c = va & ~(kChunk - 1); c < end; c += kChunk) { + const auto it = std::lower_bound( + rc.chunks.begin(), rc.chunks.end(), c, + [](const auto& entry, std::uint64_t key) { return entry.first < key; }); + if (it == rc.chunks.end() || it->first != c || !it->second) return false; + if (!first_chunk) first_chunk = it->second; + if (c > UINT64_MAX - kChunk) break; + } + auto it = rc.plain.upper_bound(va); + if (it != rc.plain.begin() && std::prev(it)->second > va) --it; + for (; it != rc.plain.end() && it->first < end; ++it) { + const std::uint64_t from = (std::max)(it->first, va) & ~(kPage - 1); + const std::uint64_t to = ((std::min)(it->second, end) + kPage - 1) & ~(kPage - 1); + auto eit = rc.ensured.upper_bound(from); + if (eit == rc.ensured.begin() || std::prev(eit)->first > from || std::prev(eit)->second < to) + return false; + } + buffer = first_chunk; + offset = va & (kChunk - 1); + const std::uint64_t room = kChunk - offset; + if (size > room) { + size = room; + page_mirror.clipped_fast.fetch_add(1, std::memory_order_relaxed); + } + page_mirror.resolved_fast.fetch_add(1, std::memory_order_relaxed); + return true; + } + } + std::lock_guard lock(page_mirror.mutex); + if (!page_mirror_resolve_locked(va, size, false) || !page_mirror.mirror->chunk_at(va, buffer, offset)) return false; + const std::uint64_t room = leonida::TitleMirror::kChunk - offset; + if (size > room) { + size = room; + ++page_mirror.clipped; + } + return true; + } + // What the GPU wrote into the homes of mirrored pages of [begin, end) goes back to the title's pages + // (TitleMirror::write_back: merged at the 256-byte piece, a piece only the GPU changed goes back, one both changed + // keeps the title's bytes), once the submissions that could write them have retired (write_back_titles). The homes + // are copied out by the GPU into host-cached memory first, kReadbackPages at a time: the CPU never reads a home, + // which in device-local memory is an uncached read over the bus (run 64w: 14.5 s for one submission's 64 MiB). + // Written through kernel_writes, which opens and pins the page and every other address of its physical page, so + // the readers over them take the bytes. Returns the bytes written. + static constexpr std::size_t kReadbackPages = 1024; // 64 MiB a copy + bool readback_use_copy_queue() const noexcept { + return !info.copy_queues.empty() && info.copy_family != UINT32_MAX; + } + std::uint32_t readback_queue_family() const noexcept { + return readback_use_copy_queue() ? info.copy_family : info.queue_family; + } + VkQueue readback_queue_handle() const noexcept { + return readback_use_copy_queue() ? info.copy_queues.back() : info.queue; + } + bool make_readback_locked() { + auto& m = page_mirror; + if (m.readback) return true; + if (m.readback_failed) return false; + auto& vk = context->vk; + const VkDevice dev = info.device; + m.readback_failed = true; + VkBufferCreateInfo buffer{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; + buffer.size = kReadbackPages * leonida::TitleMirror::kPage; + buffer.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT; + if (vk.vkCreateBuffer(dev, &buffer, nullptr, &m.readback) != VK_SUCCESS) return false; + VkMemoryRequirements requirements{}; + vk.vkGetBufferMemoryRequirements(dev, m.readback, &requirements); + m.readback_memory = allocate(requirements, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, + VK_MEMORY_PROPERTY_HOST_CACHED_BIT); + void* mapped = nullptr; + VkCommandPoolCreateInfo pool{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; + pool.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; + pool.queueFamilyIndex = readback_queue_family(); + VkCommandBufferAllocateInfo commands{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; + commands.commandBufferCount = 1; + VkSemaphoreTypeCreateInfo timeline{VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO}; + timeline.semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE; + VkSemaphoreCreateInfo semaphore{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, &timeline}; + const bool ok = m.readback_memory && vk.vkBindBufferMemory(dev, m.readback, m.readback_memory, 0) == VK_SUCCESS && + vk.vkMapMemory(dev, m.readback_memory, 0, VK_WHOLE_SIZE, 0, &mapped) == VK_SUCCESS && + vk.vkCreateCommandPool(dev, &pool, nullptr, &m.readback_pool) == VK_SUCCESS && + (commands.commandPool = m.readback_pool, + vk.vkAllocateCommandBuffers(dev, &commands, &m.readback_commands) == VK_SUCCESS) && + vk.vkCreateSemaphore(dev, &semaphore, nullptr, &m.readback_done) == VK_SUCCESS; + if (!ok) { + destroy_readback_locked(); + std::fprintf(stderr, "[rt] d3d12: page mirror: no buffer to copy homes out for the write-back: the GPU's " + "writes into mirrored pages do not go back to the title\n"); + return false; + } + m.readback_host = static_cast(mapped); + m.readback_failed = false; + return true; + } + void destroy_readback_locked() { + auto& m = page_mirror; + auto& vk = context->vk; + const VkDevice dev = info.device; + if (m.readback_done) vk.vkDestroySemaphore(dev, m.readback_done, nullptr); + if (m.readback_pool) vk.vkDestroyCommandPool(dev, m.readback_pool, nullptr); + if (m.readback) vk.vkDestroyBuffer(dev, m.readback, nullptr); + if (m.readback_memory) vk.vkFreeMemory(dev, m.readback_memory, nullptr); + m.readback_done = VK_NULL_HANDLE; + m.readback_value = 0; + m.readback_pool = VK_NULL_HANDLE; + m.readback_commands = VK_NULL_HANDLE; + m.readback = VK_NULL_HANDLE; + m.readback_memory = VK_NULL_HANDLE; + m.readback_host = nullptr; + } + // Submits the GPU copy of `refs` (at most kReadbackPages, page_mirror.readback_mutex held, page_mirror.mutex NOT + // held) into the host-cached readback buffer after mirror bind batch `wait`, signalling `m.readback_done` at `done` + // without blocking on the CPU. Emits 256-byte-aligned sub-page VkBufferCopy regions matching sorted disjoint + // `ranges` while preserving exact `dstOffset = i * kPage + sub_off` staging layout. + bool submit_homes_copy_locked(const leonida::TitleMirror::HomeRef* refs, std::size_t count, + const std::vector>& ranges, + std::uint64_t wait, std::uint64_t done, std::uint64_t& copied_bytes_out) { + auto& m = page_mirror; + auto& vk = context->vk; + constexpr std::uint64_t kPage = leonida::TitleMirror::kPage; + constexpr std::uint64_t kPiece = leonida::shadow_keep::kPiece; + copied_bytes_out = 0; + VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; + begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + if (vk.vkResetCommandBuffer(m.readback_commands, 0) != VK_SUCCESS || + vk.vkBeginCommandBuffer(m.readback_commands, &begin) != VK_SUCCESS) + return false; + // One copy command per run of pages/sub-pages in one chunk; adjacent regions in both src and dst are joined. + std::vector regions; + VkBuffer source = VK_NULL_HANDLE; + const auto emit = [&] { + if (source && !regions.empty()) + vk.vkCmdCopyBuffer(m.readback_commands, source, m.readback, std::uint32_t(regions.size()), regions.data()); + regions.clear(); + }; + const auto push_region = [&](VkDeviceSize src_off, VkDeviceSize dst_off, VkDeviceSize len) { + if (!len) return; + copied_bytes_out += len; + if (!regions.empty() && regions.back().srcOffset + regions.back().size == src_off && + regions.back().dstOffset + regions.back().size == dst_off) + regions.back().size += len; + else + regions.push_back({src_off, dst_off, len}); + }; + std::size_t cursor = 0; + for (std::size_t i = 0; i < count; ++i) { + const std::uint64_t page = refs[i].page; + const VkBuffer chunk = refs[i].chunk; + const VkDeviceSize offset = refs[i].offset; + if (!chunk) { + vk.vkEndCommandBuffer(m.readback_commands); + return false; + } + if (chunk != source) { + emit(); + source = chunk; + } + if (ranges.empty()) { + push_region(offset, i * kPage, kPage); + continue; + } + if (i > 0 && page < refs[i - 1].page) cursor = 0; + while (cursor < ranges.size() && ranges[cursor].second <= page) ++cursor; + if (cursor >= ranges.size() || ranges[cursor].first >= page + kPage) continue; + // Coalesce 256-byte-aligned sub-ranges on this page so no two VkBufferCopy regions overlap. + std::uint64_t run_lo = kPage, run_hi = kPage; + for (std::size_t r = cursor; r < ranges.size() && ranges[r].first < page + kPage; ++r) { + const std::uint64_t lo = (std::max)(ranges[r].first, page); + const std::uint64_t hi = (std::min)(ranges[r].second, page + kPage); + if (lo >= hi) continue; + const std::uint64_t sub_lo = (lo - page) & ~(kPiece - 1); + const std::uint64_t sub_hi = ((hi - page) + kPiece - 1) & ~(kPiece - 1); + if (run_lo == kPage) { + run_lo = sub_lo; + run_hi = sub_hi; + } else if (sub_lo <= run_hi) { + if (sub_hi > run_hi) run_hi = sub_hi; + } else { + push_region(offset + run_lo, i * kPage + run_lo, run_hi - run_lo); + run_lo = sub_lo; + run_hi = sub_hi; + } + } + if (run_lo < run_hi) push_region(offset + run_lo, i * kPage + run_lo, run_hi - run_lo); + } + emit(); + VkMemoryBarrier barrier{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + barrier.dstAccessMask = VK_ACCESS_HOST_READ_BIT; + vk.vkCmdPipelineBarrier(m.readback_commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, 1, + &barrier, 0, nullptr, 0, nullptr); + if (vk.vkEndCommandBuffer(m.readback_commands) != VK_SUCCESS) return false; + VkTimelineSemaphoreSubmitInfo values{VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO}; + values.waitSemaphoreValueCount = wait ? 1u : 0u; + values.pWaitSemaphoreValues = &wait; + values.signalSemaphoreValueCount = 1; + values.pSignalSemaphoreValues = &done; + const VkPipelineStageFlags stage = VK_PIPELINE_STAGE_TRANSFER_BIT; + VkSubmitInfo submit{VK_STRUCTURE_TYPE_SUBMIT_INFO, &values}; + submit.waitSemaphoreCount = wait ? 1u : 0u; + submit.pWaitSemaphores = &m.timeline; + submit.pWaitDstStageMask = &stage; + submit.commandBufferCount = 1; + submit.pCommandBuffers = &m.readback_commands; + submit.signalSemaphoreCount = 1; + submit.pSignalSemaphores = &m.readback_done; + VkResult result; + { + std::unique_lock lock(context->submit_mutex(), std::defer_lock); + leonida::submit_phases::lock_timed(lock); + result = context->observe_result(vk.vkQueueSubmit(readback_queue_handle(), 1, &submit, VK_NULL_HANDLE), + "vkQueueSubmit (page mirror write-back copy)"); + } + if (result == VK_ERROR_DEVICE_LOST) context->mark_device_lost(); + return result == VK_SUCCESS; + } + bool poll_readback_locked(std::uint64_t done, bool& ready) { + auto& m = page_mirror; + std::uint64_t current = 0; + const VkResult result = context->observe_result( + context->vk.vkGetSemaphoreCounterValue(info.device, m.readback_done, ¤t), + "vkGetSemaphoreCounterValue (page mirror write-back copy)"); + if (result == VK_ERROR_DEVICE_LOST) context->mark_device_lost(); + ready = result == VK_SUCCESS && current >= done; + return result == VK_SUCCESS; + } + bool wait_readback_locked(std::uint64_t done) { + auto& m = page_mirror; + VkSemaphoreWaitInfo until{VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO}; + until.semaphoreCount = 1; + until.pSemaphores = &m.readback_done; + until.pValues = &done; + const VkResult result = context->observe_result( + context->vk.vkWaitSemaphores(info.device, &until, UINT64_MAX), + "vkWaitSemaphores (page mirror write-back copy)"); + if (result == VK_ERROR_DEVICE_LOST) context->mark_device_lost(); + return result == VK_SUCCESS; + } + // Records whole-frame invalidation only if `frame` is actually in the currently active readback slice + // (`page_mirror.mutex` held). Avoids poisoning `readback_invalidated` with unrelated hot/feed pages. + void note_readback_frame_invalidated_locked(std::uint8_t* frame) { + auto& m = page_mirror; + if (!m.readback_in_flight || !frame || m.readback_slice_frames.empty()) return; + if (std::binary_search(m.readback_slice_frames.begin(), m.readback_slice_frames.end(), frame)) + m.readback_invalidated.insert(frame); + } + // Records piece-level upload() overwrites for frames in the active readback slice (`page_mirror.mutex` held). + // For any piece the CPU just uploaded, CPU wins under TitleMirror's conflict rule so Phase 2 simply skips those + // pieces without invalidating the whole page or pushing hot pages into an infinite retry_pages loop. + void note_readback_pieces_uploaded_locked(std::uint8_t* frame, + const std::array& changed_pieces) { + auto& m = page_mirror; + if (!m.readback_in_flight || !frame || m.readback_slice_frames.empty()) return; + const auto it = std::lower_bound(m.readback_slice_frames.begin(), m.readback_slice_frames.end(), frame); + if (it == m.readback_slice_frames.end() || *it != frame) return; + const std::size_t idx = static_cast(it - m.readback_slice_frames.begin()); + for (std::size_t w = 0; w < 4; ++w) m.readback_slice_skip_masks[idx][w] |= changed_pieces[w]; + } + void clear_readback_in_flight_locked() { + auto& m = page_mirror; + m.readback_in_flight = false; + m.readback_active_value.store(0, std::memory_order_release); + m.readback_invalidated.clear(); + m.readback_slice_frames.clear(); + m.readback_slice_skip_masks.clear(); + } + + // Launches the next valid slice (<= kReadbackPages) from `refs[cursor..]` asynchronously (page_mirror.readback_mutex + // held, page_mirror.mutex NOT held). Returns true if a copy is now in flight; false if no valid pages remained. + bool kick_async_readback_locked(std::vector&& refs, std::size_t cursor, + std::vector>&& ranges, + double cpu_ms, double waited_ms, + std::uint64_t read_bytes, std::uint64_t batch_written, std::uint64_t& written_out) { + auto& m = page_mirror; + using clock = std::chrono::steady_clock; + const auto kick_start = clock::now(); + std::vector slice; + slice.reserve(kReadbackPages); + while (cursor < refs.size()) { + const std::size_t count = (std::min)(kReadbackPages, refs.size() - cursor); + const std::size_t next_cursor = cursor + count; + slice.clear(); + std::uint64_t wait = 0; + std::uint64_t done = 0; + std::unique_lock submit_lock(m.readback_submit_mutex, std::defer_lock); + { + std::unique_lock mirror_lock(m.mutex, std::defer_lock); + leonida::submit_phases::lock_timed(mirror_lock); + if (!m.mirror) return false; + for (std::size_t i = 0; i < count; ++i) { + const auto& r = refs[cursor + i]; + if (m.mirror->has_pending(r.page) || m.mirror->frame_at(r.page) != r.frame) continue; + slice.push_back(r); + } + if (slice.empty()) { + cursor = next_cursor; + continue; + } + wait = m.value; + done = ++m.readback_value; + // Mark in_flight and take readback_submit_mutex before releasing m.mutex (lock order: + // readback_mutex -> m.mutex -> readback_submit_mutex) so hooks.bind cannot submit + // vkQueueBindSparse while submit_homes_copy_locked is submitting vkCmdCopyBuffer. + m.readback_in_flight = true; + m.readback_active_value.store(0, std::memory_order_release); + m.readback_invalidated.clear(); + m.readback_slice_frames.clear(); + m.readback_slice_frames.reserve(slice.size()); + for (const auto& r : slice) m.readback_slice_frames.push_back(r.frame); + std::sort(m.readback_slice_frames.begin(), m.readback_slice_frames.end()); + m.readback_slice_frames.erase( + std::unique(m.readback_slice_frames.begin(), m.readback_slice_frames.end()), + m.readback_slice_frames.end()); + m.readback_slice_skip_masks.assign(m.readback_slice_frames.size(), {}); + submit_lock.lock(); + } + std::uint64_t slice_copied_bytes = 0; + const bool submitted = + submit_homes_copy_locked(slice.data(), slice.size(), ranges, wait, done, slice_copied_bytes); + if (submitted) m.readback_active_value.store(done, std::memory_order_release); + submit_lock.unlock(); + if (!submitted) { + std::unique_lock mirror_lock(m.mutex, std::defer_lock); + leonida::submit_phases::lock_timed(mirror_lock); + clear_readback_in_flight_locked(); + return false; + } + m.readback_async.active = true; + m.readback_async.signal_value = done; + m.readback_async.slice = std::move(slice); + m.readback_async.ranges = std::move(ranges); + m.readback_async.remaining_refs = std::move(refs); + m.readback_async.remaining_cursor = next_cursor; + m.readback_async.cpu_ms = + cpu_ms + std::chrono::duration(clock::now() - kick_start).count(); + m.readback_async.waited_ms = waited_ms; + m.readback_async.read_bytes = read_bytes; + m.readback_async.slice_copied_bytes = slice_copied_bytes; + m.readback_async.written = batch_written; + return true; + } + // All slices of this batch finished (or were skipped due to pending/remap). + const double ms = cpu_ms + std::chrono::duration(clock::now() - kick_start).count(); + { + std::unique_lock mirror_lock(m.mutex, std::defer_lock); + leonida::submit_phases::lock_timed(mirror_lock); + m.read_back_bytes += read_bytes; + ++m.write_back_calls; + m.write_back_ms += ms; + m.write_back_wait_ms += waited_ms; + m.write_back_max_ms = (std::max)(m.write_back_max_ms, ms); + m.written_back += batch_written; + } + written_out += batch_written; + return false; + } + // Polls or waits on `m.readback_async` (page_mirror.readback_mutex held, page_mirror.mutex NOT held). + // Returns true when no async readback remains in flight; false when `!wait_blocking` and a GPU copy is still running. + bool finish_async_readback_locked(bool wait_blocking, std::vector& retry_pages, + std::uint64_t& written_out) { + auto& m = page_mirror; + using clock = std::chrono::steady_clock; + constexpr std::uint64_t kPage = leonida::TitleMirror::kPage; + struct PageWriteBackWriter { + struct PageGuard { + std::uint64_t pin = 0; + bool scratch_frame = false; + bool table_fallback = false; + PageGuard() = default; + PageGuard(std::uint64_t p, bool scratch, bool fallback) + : pin(p), scratch_frame(scratch), table_fallback(fallback) {} + PageGuard(const PageGuard&) = delete; + PageGuard& operator=(const PageGuard&) = delete; + PageGuard(PageGuard&& o) noexcept + : pin(std::exchange(o.pin, 0)), + scratch_frame(o.scratch_frame), + table_fallback(o.table_fallback) {} + ~PageGuard() { + if (pin) leonida::kernel_writes::end_write(pin, false); + } + }; + PageGuard begin_page(std::uint64_t page_va, std::uint8_t* frame, std::size_t first_off, + std::size_t span_bytes) const { + // xmem physical-page scratch views (frame != page_va) are unguarded host-mapped scratch: bypass + // kernel_writes::begin_write/end_write completely and copy directly via move_guarded. + if (reinterpret_cast(frame) != static_cast(page_va)) + return PageGuard(0, true, false); + void* const dst = frame + first_off; + const auto dst_va = reinterpret_cast(dst); + if (leonida::title_frames::may_hold(dst_va, dst_va + span_bytes)) return PageGuard(0, false, true); + const std::uint64_t pin = leonida::kernel_writes::begin_write(dst, span_bytes, nullptr); + return PageGuard(pin, false, false); + } + bool write(const PageGuard& guard, std::uint64_t at, const std::uint8_t* bytes, std::size_t n) const { + if (!n) return true; + void* const dst = reinterpret_cast(static_cast(at)); + if (guard.scratch_frame) return leonida::kernel_writes::detail::move_guarded(dst, bytes, n); + if (guard.table_fallback) return leonida::kernel_writes::write(dst, bytes, n); + if (leonida::kernel_writes::detail::move_guarded(dst, bytes, n)) return true; + return leonida::kernel_writes::reopen(dst, n) && + leonida::kernel_writes::detail::move_guarded(dst, bytes, n); + } + } write; + while (m.readback_async.active) { + if (!wait_blocking) { + bool ready = false; + if (!poll_readback_locked(m.readback_async.signal_value, ready)) { + std::unique_lock mirror_lock(m.mutex, std::defer_lock); + leonida::submit_phases::lock_timed(mirror_lock); + clear_readback_in_flight_locked(); + m.readback_async = {}; + return true; + } + if (!ready) return false; // GPU copy still running; return non-blockingly + } else { + const auto wait_start = clock::now(); + const bool ok = wait_readback_locked(m.readback_async.signal_value); + const double wms = std::chrono::duration(clock::now() - wait_start).count(); + m.readback_async.waited_ms += wms; + m.readback_async.cpu_ms += wms; + if (!ok) { + std::unique_lock mirror_lock(m.mutex, std::defer_lock); + leonida::submit_phases::lock_timed(mirror_lock); + clear_readback_in_flight_locked(); + m.readback_async = {}; + return true; + } + } + const auto work_start = clock::now(); + std::uint64_t slice_written = 0; + const std::size_t slice_pages = m.readback_async.slice.size(); + // Phase 1 (lock-free with respect to page_mirror.mutex): compute 256-byte GPU piece hashes across the + // host-cached readback buffer in parallel using m.readback_hash_pool (owned solely by readback_mutex). + if (slice_pages >= leonida::TitleMirror::kParallelThreshold && !m.readback_hash_pool) + m.readback_hash_pool = leonida::TitleMirror::make_worker_pool(); + leonida::TitleMirror::prehash_readback_slice(m.readback_async.slice.data(), slice_pages, + m.readback_async.ranges, m.readback_host, m.readback_prehashed, + m.readback_hash_pool.get()); + // Phase 2 (short page_mirror.mutex hold): O(pieces) uint64 compare + coalesced write-back runs. + { + std::unique_lock mirror_lock(m.mutex, std::defer_lock); + leonida::submit_phases::lock_timed(mirror_lock); + if (!m.mirror) { + clear_readback_in_flight_locked(); + m.readback_async = {}; + return true; + } + bool any_skip_page = false; + bool any_skip_mask = false; + if (!m.readback_invalidated.empty()) { + m.readback_exec_skip_page.assign(slice_pages, 0); + for (std::size_t i = 0; i < slice_pages; ++i) { + const auto& r = m.readback_async.slice[i]; + if (m.readback_invalidated.count(r.frame)) { + m.readback_exec_skip_page[i] = 1; + any_skip_page = true; + if (!m.mirror->has_pending(r.page) && m.mirror->frame_at(r.page) == r.frame) + retry_pages.push_back(r.page); + } + } + } + if (!m.readback_slice_frames.empty()) { + bool any_nonzero_mask = false; + for (const auto& mask : m.readback_slice_skip_masks) { + if (mask[0] | mask[1] | mask[2] | mask[3]) { + any_nonzero_mask = true; + break; + } + } + if (any_nonzero_mask) { + m.readback_exec_skip_masks.assign(slice_pages, {}); + for (std::size_t i = 0; i < slice_pages; ++i) { + if (any_skip_page && m.readback_exec_skip_page[i]) continue; + const auto it = std::lower_bound(m.readback_slice_frames.begin(), + m.readback_slice_frames.end(), + m.readback_async.slice[i].frame); + if (it != m.readback_slice_frames.end() && *it == m.readback_async.slice[i].frame) { + const std::size_t idx = + static_cast(it - m.readback_slice_frames.begin()); + const auto& mask = m.readback_slice_skip_masks[idx]; + if (mask[0] | mask[1] | mask[2] | mask[3]) { + m.readback_exec_skip_masks[i] = mask; + any_skip_mask = true; + } + } + } + } + } + clear_readback_in_flight_locked(); + slice_written = m.mirror->write_back_prehashed( + m.readback_async.slice.data(), slice_pages, m.readback_prehashed, m.readback_host, + any_skip_mask ? m.readback_exec_skip_masks.data() : nullptr, + any_skip_page ? m.readback_exec_skip_page.data() : nullptr, write); + } + const double slice_cpu_ms = + std::chrono::duration(clock::now() - work_start).count(); + auto refs = std::move(m.readback_async.remaining_refs); + const std::size_t cursor = m.readback_async.remaining_cursor; + auto ranges = std::move(m.readback_async.ranges); + const double cpu_ms = m.readback_async.cpu_ms + slice_cpu_ms; + const double waited_ms = m.readback_async.waited_ms; + const std::uint64_t read_bytes = m.readback_async.read_bytes + m.readback_async.slice_copied_bytes; + const std::uint64_t batch_written = m.readback_async.written + slice_written; + m.readback_async = {}; + const bool launched_next = kick_async_readback_locked(std::move(refs), cursor, std::move(ranges), cpu_ms, + waited_ms, read_bytes, batch_written, written_out); + if (!wait_blocking && launched_next) return false; + } + return true; + } + std::uint64_t page_mirror_write_back_ranges(const std::vector>& ranges, + bool blocking = true) { + auto& m = page_mirror; + if (!m.mirror || (ranges.empty() && !m.readback_async_pending.load(std::memory_order_acquire))) return 0; + constexpr std::uint64_t kPage = leonida::TitleMirror::kPage; + std::vector retry_pages; + std::uint64_t written = 0; + { + // Lock order: readback_mutex -> page_mirror.mutex. Release page_mirror.mutex around the GPU copy and wait + // so concurrent refreshes and descriptor filtering never stall on vkWaitSemaphores. + std::unique_lock readback_lock(m.readback_mutex, std::defer_lock); + leonida::submit_phases::lock_timed(readback_lock); + bool idle = !m.readback_async.active || finish_async_readback_locked(blocking, retry_pages, written); + if (!idle) { + // An async GPU copy is still running and caller requested non-blocking poll: queue incoming ranges and + // only fall back to blocking if the pending range queue reaches its cap. + if (!ranges.empty()) { + m.readback_queued_ranges.insert(m.readback_queued_ranges.end(), ranges.begin(), ranges.end()); + if (m.readback_queued_ranges.size() > kTitleWriteBackRanges) { + // Compact first; only block if distinct disjoint ranges still exceed the cap. + std::sort(m.readback_queued_ranges.begin(), m.readback_queued_ranges.end()); + std::vector> compacted; + compacted.reserve(m.readback_queued_ranges.size()); + for (const auto& [b, e] : m.readback_queued_ranges) { + if (!compacted.empty() && b <= compacted.back().second) + compacted.back().second = (std::max)(compacted.back().second, e); + else + compacted.emplace_back(b, e); + } + m.readback_queued_ranges = std::move(compacted); + } + if (m.readback_queued_ranges.size() > kTitleWriteBackRanges) { + idle = finish_async_readback_locked(true, retry_pages, written); + } + } + if (!idle) { + m.readback_async_pending.store(true, std::memory_order_release); + } + } + if (idle) { + std::vector> work; + if (!m.readback_queued_ranges.empty()) { + work = std::move(m.readback_queued_ranges); + m.readback_queued_ranges.clear(); + } + if (!ranges.empty()) work.insert(work.end(), ranges.begin(), ranges.end()); + if (!work.empty()) { + std::sort(work.begin(), work.end()); + std::vector> merged; + merged.reserve(work.size()); + for (const auto& [b, e] : work) { + if (!merged.empty() && b <= merged.back().second) + merged.back().second = (std::max)(merged.back().second, e); + else + merged.emplace_back(b, e); + } + std::vector refs; + { + std::unique_lock mirror_lock(m.mutex, std::defer_lock); + leonida::submit_phases::lock_timed(mirror_lock); + if (m.mirror) refs = m.mirror->homes_in_ranges(merged); + } + if (!refs.empty() && make_readback_locked()) { + if (kick_async_readback_locked(std::move(refs), 0, std::move(merged), 0.0, 0.0, 0, 0, + written) && + blocking) { + finish_async_readback_locked(true, retry_pages, written); + } + } + } + m.readback_async_pending.store(m.readback_async.active || !m.readback_queued_ranges.empty(), + std::memory_order_release); + } + } + for (const std::uint64_t page : retry_pages) note_title_write(page, kPage); + return written; + } + std::uint64_t page_mirror_write_back(std::uint64_t begin, std::uint64_t end) { + if (begin >= end) return 0; + const std::vector> one{{begin, end}}; + return page_mirror_write_back_ranges(one, true); + } + + // Last in the before-execute hook, once every reader of this submission has named what it reads: the binds noted + // since the last batch go in one, and every queue's next submission waits for it (the ordering rule). + void flush_page_mirror() { + auto& m = page_mirror; + if (!m.mirror) return; + // O(1) lock-free clean fast-path: verify BOTH no pending binds AND no concurrent flush in flight (seq_cst + // after reading has_pending_binds() ensures another queue cannot slip past before note_mirror_bind() runs). + if (!m.mirror->has_pending_binds() && m.flush_in_flight.load(std::memory_order_seq_cst) == 0) return; + std::unique_lock lock(m.mutex, std::defer_lock); + leonida::submit_phases::lock_timed(lock); + m.flush_in_flight.fetch_add(1, std::memory_order_seq_cst); + struct FlushGuard { + std::atomic& n; + ~FlushGuard() { n.fetch_sub(1, std::memory_order_release); } + } in_flight{m.flush_in_flight}; + if (m.mirror->flush(m.value + 1)) { + ++m.value; + ++m.batches; + m.binds += m.mirror->last_batch(); + const std::uint64_t retire_ticket = context->note_mirror_bind(m.timeline, m.value); + m.mirror->stamp_freed(retire_ticket); + } + } + + // Lightweight feed-only drain for coalesced submissions: applies any pending CopyPageMappingsBatchX / xmem + // remaps and lazy 2 GiB chunk creations + sparse binds without running write_back, arm_batch, incremental + // upload, shadow refresh, or title texture refresh (avoiding full-pass single-flight convoys). + // Returns true if any slow-path work ran under page_mirror.mutex. + bool drain_page_mirror_feed_only() { + auto& m = page_mirror; + if (!m.mirror) return false; + if (!m.feed_pending.load(std::memory_order_acquire) && + leonida::title_mirror_space::generation() == m.space_gen_atomic.load(std::memory_order_acquire) && + !m.mirror->has_pending_binds() && + m.refresh_in_flight.load(std::memory_order_seq_cst) == 0 && + m.flush_in_flight.load(std::memory_order_seq_cst) == 0) { + return false; + } + std::unique_lock lock(m.mutex, std::defer_lock); + leonida::submit_phases::lock_timed(lock); + m.refresh_in_flight.fetch_add(1, std::memory_order_seq_cst); + m.flush_in_flight.fetch_add(1, std::memory_order_seq_cst); + struct FeedDrainGuard { + std::atomic& r; + std::atomic& f; + ~FeedDrainGuard() { + f.fetch_sub(1, std::memory_order_release); + r.fetch_sub(1, std::memory_order_release); + } + } in_flight{m.refresh_in_flight, m.flush_in_flight}; + sync_mirror_space_locked(); + m.taken.clear(); + AcquireSRWLockExclusive(&m.feed_lock); + for (auto& change : m.feed) m.taken.push_back(std::move(change)); + m.feed.clear(); + m.feed_pending.store(false, std::memory_order_release); + ReleaseSRWLockExclusive(&m.feed_lock); + bool did_work = false; + if (!m.taken.empty()) { + did_work = true; + m.fed += m.taken.size(); + if (m.readback_in_flight) { + for (const auto& change : m.taken) { + note_readback_frame_invalidated_locked(m.mirror->frame_at(change.page)); + note_readback_frame_invalidated_locked(change.frame); + } + } + if (m.taken.size() == 1) { + auto& change = m.taken[0]; + if (!change.frame) m.tracking->unwatch(change.page); + else if (m.mirror->covers(change.page)) m.tracking->watch(change.page); + // defer_fill=false so newly created homes and aliased pages are filled/filtered before flush(). + m.mirror->map(change.page, change.frame, std::move(change.keep), leonida::TitleMirror::kUnstamped, + false); + } else { + m.feed_order.resize(m.taken.size()); + for (std::size_t idx = 0; idx < m.taken.size(); ++idx) + m.feed_order[idx] = {m.taken[idx].page, static_cast(idx)}; + std::sort(m.feed_order.begin(), m.feed_order.end(), [](const auto& a, const auto& b) { + return a.page != b.page ? (a.page < b.page) : (a.seq < b.seq); + }); + m.feed_collapsed.clear(); + m.feed_unwatch.clear(); + m.feed_watch.clear(); + for (std::size_t r = 0; r < m.feed_order.size();) { + std::size_t r_end = r + 1; + while (r_end < m.feed_order.size() && m.feed_order[r_end].page == m.feed_order[r].page) ++r_end; + const std::uint32_t last_seq = m.feed_order[r_end - 1].seq; + const bool had_prior = (r_end - r) > 1; + const auto& final_change = m.taken[last_seq]; + m.feed_collapsed.push_back({last_seq, had_prior}); + if (!final_change.frame) m.feed_unwatch.push_back(final_change.page); + else if (m.mirror->covers(final_change.page)) m.feed_watch.push_back(final_change.page); + r = r_end; + } + if (!m.feed_unwatch.empty()) m.tracking->unwatch_batch(m.feed_unwatch.data(), m.feed_unwatch.size()); + if (!m.feed_watch.empty()) m.tracking->watch_batch(m.feed_watch.data(), m.feed_watch.size()); + std::sort(m.feed_collapsed.begin(), m.feed_collapsed.end(), + [](const auto& a, const auto& b) { return a.seq < b.seq; }); + for (const auto& entry : m.feed_collapsed) { + auto& change = m.taken[entry.seq]; + const bool same_frame_after_churn = + entry.had_prior && change.frame && m.mirror->frame_at(change.page) == change.frame; + m.mirror->map(change.page, change.frame, std::move(change.keep), leonida::TitleMirror::kUnstamped, + false); + if (same_frame_after_churn && m.mirror->dirty(change.page)) ++m.dirty; + } + } + m.taken.clear(); + } + if (m.mirror->has_pending_binds() && m.mirror->flush(m.value + 1)) { + did_work = true; + ++m.value; + ++m.batches; + m.binds += m.mirror->last_batch(); + const std::uint64_t retire_ticket = context->note_mirror_bind(m.timeline, m.value); + m.mirror->stamp_freed(retire_ticket); + } + return did_work; + } + + void destroy_page_mirror() { + if (!page_mirror.mirror) return; + if (const auto attach = leonida::title_frames::attach_fn.load(std::memory_order_acquire)) attach(this, nullptr); + context->set_mirror_buffer({}); + leonida::geometry_writes::unsubscribe(page_mirror.released); + std::lock_guard readback_lock(page_mirror.readback_mutex); + if (page_mirror.readback_async.active && page_mirror.readback_done) { + wait_readback_locked(page_mirror.readback_async.signal_value); + } + page_mirror.readback_async = {}; + page_mirror.readback_queued_ranges.clear(); + page_mirror.readback_async_pending.store(false, std::memory_order_release); + page_mirror.readback_hash_pool.reset(); + page_mirror.readback_prehashed = {}; + page_mirror.readback_exec_skip_masks.clear(); + page_mirror.readback_exec_skip_page.clear(); + std::lock_guard lock(page_mirror.mutex); + clear_readback_in_flight_locked(); + { + std::unique_lock rc_lock(page_mirror.resolve_cache.mutex); + page_mirror.resolve_cache.chunks.clear(); + page_mirror.resolve_cache.plain.clear(); + page_mirror.resolve_cache.ensured.clear(); + page_mirror.resolve_cache.space_generation = 0; + } + page_mirror.mirror.reset(); + page_mirror.tracking.reset(); + destroy_readback_locked(); + for (VkBuffer chunk : page_mirror.chunks) context->vk.vkDestroyBuffer(info.device, chunk, nullptr); + page_mirror.chunks.clear(); + if (page_mirror.timeline) context->vk.vkDestroySemaphore(info.device, page_mirror.timeline, nullptr); + page_mirror.timeline = VK_NULL_HANDLE; + } + + // Before every submission (the before-execute hook, after write_back_titles): the reservations placed since get + // chunks, xmem's changes are bound, the pages written since are filled again, and the binds go in one batch that + // every queue's next submission waits for (VulkanContext::note_mirror_bind). A page is armed before its home is + // filled, so a write after the fill faults and is in the next refresh. + void refresh_page_mirror() { + auto& m = page_mirror; + if (!m.mirror) return; + const auto start = std::chrono::steady_clock::now(); + const std::int64_t start_ns = + std::chrono::duration_cast(start.time_since_epoch()).count(); + // O(1) lock-free clean-submission fast-path: skip locking page_mirror.mutex when no reservations, feeds, + // releases, hot/dirty pages, retired homes, or in-place heap slot changes are pending and the 10 s log is not + // due. + { + const bool log_due = (start_ns - m.since_ns_atomic.load(std::memory_order_acquire)) >= 10'000'000'000ll; + const bool in_place_dirty = + in_place_heaps.load(std::memory_order_acquire) != 0 && + (slot_change_count.load(std::memory_order_acquire) != 0 || + m.in_place_pending.load(std::memory_order_acquire)); + if (!log_due && !in_place_dirty && + leonida::title_mirror_space::generation() == m.space_gen_atomic.load(std::memory_order_acquire) && + !m.feed_pending.load(std::memory_order_acquire) && + !leonida::geometry_writes::has_released(m.released) && !m.tracking->has_pending_work() && + !m.mirror->has_dirty() && !m.mirror->has_retired_homes() && + m.refresh_in_flight.load(std::memory_order_seq_cst) == 0) { + m.fast_refreshes.fetch_add(1, std::memory_order_relaxed); + return; + } + } + const std::int64_t t_start = leonida::submit_phases::now_ns(); + std::unique_lock lock(m.mutex, std::defer_lock); + leonida::submit_phases::lock_timed(lock); + const std::int64_t t_lock = leonida::submit_phases::now_ns(); + m.refresh_in_flight.fetch_add(1, std::memory_order_seq_cst); + struct RefreshGuard { + std::atomic& n; + ~RefreshGuard() { n.fetch_sub(1, std::memory_order_release); } + } in_flight{m.refresh_in_flight}; + sync_mirror_space_locked(); + m.taken.clear(); + AcquireSRWLockExclusive(&m.feed_lock); + for (auto& change : m.feed) m.taken.push_back(std::move(change)); + m.feed.clear(); + m.feed_pending.store(false, std::memory_order_release); + ReleaseSRWLockExclusive(&m.feed_lock); + m.fed_now.clear(); + if (!m.taken.empty()) { + m.fed += m.taken.size(); + // 1. Invalidate readback_in_flight frames across ALL raw m.taken entries BEFORE collapsing. + if (m.readback_in_flight) { + for (const auto& change : m.taken) { + note_readback_frame_invalidated_locked(m.mirror->frame_at(change.page)); + note_readback_frame_invalidated_locked(change.frame); + } + } + if (m.taken.size() == 1) { + auto& change = m.taken[0]; + m.fed_now.push_back(change.page); + if (!change.frame) m.tracking->unwatch(change.page); + else if (m.mirror->covers(change.page)) m.tracking->watch(change.page); + m.mirror->map(change.page, change.frame, std::move(change.keep), leonida::TitleMirror::kUnstamped, + true); + } else { + // 2. Collapse m.taken by change.page keeping only the final entry per page (avoiding redundant + // unwatch+watch churn on xmem unmap+remap pairs), then batch unwatch/watch under single lock holds + // and execute map() in final chronological order. + m.feed_order.resize(m.taken.size()); + for (std::size_t idx = 0; idx < m.taken.size(); ++idx) + m.feed_order[idx] = {m.taken[idx].page, static_cast(idx)}; + std::sort(m.feed_order.begin(), m.feed_order.end(), [](const auto& a, const auto& b) { + return a.page != b.page ? (a.page < b.page) : (a.seq < b.seq); + }); + m.feed_collapsed.clear(); + m.feed_unwatch.clear(); + m.feed_watch.clear(); + m.fed_now.reserve(m.taken.size()); + for (std::size_t r = 0; r < m.feed_order.size();) { + std::size_t r_end = r + 1; + while (r_end < m.feed_order.size() && m.feed_order[r_end].page == m.feed_order[r].page) ++r_end; + const std::uint32_t last_seq = m.feed_order[r_end - 1].seq; + const bool had_prior = (r_end - r) > 1; + const auto& final_change = m.taken[last_seq]; + m.fed_now.push_back(final_change.page); + m.feed_collapsed.push_back({last_seq, had_prior}); + if (!final_change.frame) m.feed_unwatch.push_back(final_change.page); + else if (m.mirror->covers(final_change.page)) m.feed_watch.push_back(final_change.page); + r = r_end; + } + if (!m.feed_unwatch.empty()) m.tracking->unwatch_batch(m.feed_unwatch.data(), m.feed_unwatch.size()); + if (!m.feed_watch.empty()) m.tracking->watch_batch(m.feed_watch.data(), m.feed_watch.size()); + std::sort(m.feed_collapsed.begin(), m.feed_collapsed.end(), + [](const auto& a, const auto& b) { return a.seq < b.seq; }); + for (const auto& entry : m.feed_collapsed) { + auto& change = m.taken[entry.seq]; + // Guardrail: if {p, nullptr} was followed by {p, same_old_frame}, map() would see + // old_frame == change.frame and return early; still mark dirty(p) so changed bytes upload. + const bool same_frame_after_churn = + entry.had_prior && change.frame && m.mirror->frame_at(change.page) == change.frame; + m.mirror->map(change.page, change.frame, std::move(change.keep), leonida::TitleMirror::kUnstamped, + true); + if (same_frame_after_churn && m.mirror->dirty(change.page)) ++m.dirty; + } + } + } + m.taken.clear(); + // Ordinary memory released or decommitted: its mirrored pages leave (named again, they are mirrored again). + leonida::geometry_writes::take_released(m.released, m.released_ranges); + bool ensured_changed = false; + // Only pages the range holds whole: a freed heap block leaves the rest of its page to the blocks around it. + for (const auto& [from, to] : m.released_ranges) { + constexpr std::uint64_t kPage = leonida::TitleMirror::kPage; + for (auto page = m.identity.lower_bound((from + kPage - 1) & ~(kPage - 1)); + page != m.identity.end() && *page + kPage <= to;) { + if (m.readback_in_flight) note_readback_frame_invalidated_locked(m.mirror->frame_at(*page)); + m.tracking->unwatch(*page); + m.mirror->map(*page, nullptr, nullptr); + ++m.identity_released; + page = m.identity.erase(page); + } + if (to - from >= kPage) // a run that lost a page is named again (pages still there map to themselves) + for (auto run = m.ensured.begin(); run != m.ensured.end();) { + if (run->first < to && from < run->second) { + run = m.ensured.erase(run); + ensured_changed = true; + } else { + ++run; + } + } + } + if (ensured_changed) { + std::unique_lock rc_lock(m.resolve_cache.mutex); + m.resolve_cache.ensured = m.ensured; + } + const std::int64_t t_feed = leonida::submit_phases::now_ns(); + m.tracking->collect(m.written); // re-watched before the copies below + const bool have_fed = !m.fed_now.empty(); + for (const std::uint64_t page : m.written) + if ((!have_fed || !std::binary_search(m.fed_now.begin(), m.fed_now.end(), std::uintptr_t(page))) && + m.mirror->dirty(page)) { + ++m.dirty; + } + m.arm_failures += m.tracking->take_refused(); + const std::int64_t t_collect = leonida::submit_phases::now_ns(); + // The changes noted since (a buffer released, a texture come): the slots of heaps read in place they touch are + // filtered again into their homes now, before the pages written since are. + for (ConsoleHeap* heap : m.in_place) apply_in_place_changes(*heap); + m.in_place_pending.store(false, std::memory_order_release); + const std::int64_t t_in_place = leonida::submit_phases::now_ns(); + std::uint64_t filter_batch_ns = 0; + const auto filter_batch = [&](leonida::TitleMirror::AliasedPageJob* jobs, std::size_t count, + leonida::TitleMirror::WorkerPool* pool, std::uint8_t* ok_out) { + const std::int64_t fb0 = leonida::submit_phases::now_ns(); + filter_heap_pages_batch_locked(jobs, count, pool, ok_out); + const std::int64_t fb1 = leonida::submit_phases::now_ns(); + if (fb1 > fb0) filter_batch_ns += std::uint64_t(fb1 - fb0); + }; + if (m.readback_in_flight && !m.readback_slice_frames.empty()) { + m.uploads += m.mirror->upload( + [&](std::uint8_t* frame, const std::array& changed_pieces) { + note_readback_pieces_uploaded_locked(frame, changed_pieces); + }, + filter_batch); + } else { + m.uploads += m.mirror->upload([](std::uint8_t*, const std::array&) {}, filter_batch); + } + const std::int64_t t_upload = leonida::submit_phases::now_ns(); + if (m.mirror->last_upload_bytes() != 0 || !m.fed_now.empty()) + leonida::submit_phases::note_change(leonida::submit_phases::change_pages); + if (m.mirror->has_retired_homes() && !m.readback_in_flight) { + std::uint64_t completed = context->cached_completed_retire_ticket(); + if (m.mirror->has_retired_homes(completed)) { + m.mirror->retire(completed); + m.retire_poll_skip = 0; + } else if (++m.retire_poll_skip >= 16) { + completed = context->completed_retire_ticket(); + m.mirror->retire(completed); + m.retire_poll_skip = 0; + } + } + const std::int64_t t_end = leonida::submit_phases::now_ns(); + { + const auto arm_s = m.tracking->last_arm_stats(); + const std::uint64_t lock_ns = std::uint64_t((std::max)(std::int64_t(0), t_lock - t_start)); + const std::uint64_t feed_ns = std::uint64_t((std::max)(std::int64_t(0), t_feed - t_lock)); + const std::uint64_t collect_total_ns = std::uint64_t((std::max)(std::int64_t(0), t_collect - t_feed)); + const std::uint64_t arm_ns = (std::min)(arm_s.ns, collect_total_ns); + const std::uint64_t collect_ns = collect_total_ns - arm_ns; + const std::uint64_t in_place_ns = std::uint64_t((std::max)(std::int64_t(0), t_in_place - t_collect)); + const std::uint64_t upload_total_ns = std::uint64_t((std::max)(std::int64_t(0), t_upload - t_in_place)); + const std::uint64_t fb_clamped = (std::min)(filter_batch_ns, upload_total_ns); + const std::uint64_t filter_ns = in_place_ns + fb_clamped; + const std::uint64_t upload_ns = upload_total_ns - fb_clamped; + const std::uint64_t other_ns = std::uint64_t((std::max)(std::int64_t(0), t_end - t_upload)); + m.split_lock_ns += lock_ns; + m.split_feed_ns += feed_ns; + m.split_collect_ns += collect_ns; + m.split_arm_ns += arm_ns; + m.split_upload_ns += upload_ns; + m.split_filter_ns += filter_ns; + m.split_other_ns += other_ns; + m.split_vp_calls += arm_s.vp_calls; + m.split_vq_calls += arm_s.vq_calls; + m.split_fast_tiles += arm_s.fast_tiles; + m.split_slow_tiles += arm_s.slow_tiles; + m.split_skip_tiles += arm_s.skip_tiles; + m.split_bridged_runs += arm_s.bridged_runs; + m.split_wc_tiles += arm_s.wc_tiles; + m.split_whole_pages += m.mirror->last_whole_pages(); + m.split_inc_pages += m.mirror->last_inc_pages(); + m.split_alias_pages += m.mirror->last_aliased_pages(); + } + ++m.refreshes; + const auto now = std::chrono::steady_clock::now(); + m.ms += std::chrono::duration(now - start).count(); + if (now - m.since >= std::chrono::seconds(10)) { + m.refreshes += m.fast_refreshes.exchange(0, std::memory_order_relaxed); + m.resolved += m.resolved_fast.exchange(0, std::memory_order_relaxed); + m.clipped += m.clipped_fast.exchange(0, std::memory_order_relaxed); + const auto c = m.mirror->counters(); + const auto policy = m.tracking->stats(); + const std::uint64_t presents = + leonida::submit_phases::totals().present_serial.load(std::memory_order_relaxed); + const std::uint64_t frames = presents - m.presents; + std::fprintf(stderr, + "[rt] d3d12: page mirror: %llu pages mirrored, %llu homes in %llu units (%llu MiB), %llu chunks " + "(%llu not placed); in %.0f s: %llu refreshes, %llu changes fed, %llu pages written, %llu " + "uploads, %llu binds (%llu unbinds, %llu homes freed) in %llu batches, %llu arms refused, " + "%.3f ms a refresh; changes outside the chunks %llu; readers: %llu ranges resolved into it, " + "%llu refused, %llu ordinary pages mirrored and %llu released, %llu buffer bindings cut at a " + "chunk's end; %llu slot-133 buffers made on it, %llu KiB of GPU writes copied back (%llu KiB " + "total); homes in device-local memory %llu units, in host memory %llu; tracking: %zu pages " + "hot, %zu cold, %llu write faults, %llu hot and %llu cold copies; uploaded %.1f KiB a " + "submission and %.1f KiB a frame; written back %.1f KiB a submission and %.1f KiB a frame; " + "%llu pieces written on both sides (the title's kept); write-back: %llu calls, %.3f ms each " + "(%.3f of it the GPU's copy of the homes and its wait), %.3f ms the longest, %.1f MiB of " + "homes copied out\n", + static_cast(c.pages), static_cast(c.homes), + static_cast(c.units), + static_cast(c.units * (leonida::TitleMirror::kUnitBytes >> 20)), + static_cast(c.chunks), static_cast(c.chunk_failures), + std::chrono::duration(now - m.since).count(), static_cast(m.refreshes), + static_cast(m.fed), static_cast(m.dirty), + static_cast(m.uploads), static_cast(m.binds), + static_cast(c.unbinds - m.unbinds_seen), + static_cast(c.homes_freed - m.homes_freed_seen), + static_cast(m.batches), static_cast(m.arm_failures), + m.refreshes ? m.ms / double(m.refreshes) : 0.0, + static_cast(c.unmirrored_changes), + static_cast(m.resolved), static_cast(m.resolve_refused), + static_cast(m.identity_mapped), + static_cast(m.identity_released), static_cast(m.clipped), + static_cast(m.buffers), static_cast(m.written_back >> 10), + static_cast(c.written_back_bytes >> 10), + static_cast(m.units_local), static_cast(m.units_host), + policy.hot, policy.cold, static_cast(policy.faults - m.faults_seen), + static_cast(policy.hot_copies - m.hot_seen), + static_cast(policy.cold_copies - m.cold_seen), + m.refreshes ? double(c.uploaded_bytes - m.uploaded_seen) / 1024.0 / double(m.refreshes) : 0.0, + frames ? double(c.uploaded_bytes - m.uploaded_seen) / 1024.0 / double(frames) : 0.0, + m.refreshes ? double(m.written_back) / 1024.0 / double(m.refreshes) : 0.0, + frames ? double(m.written_back) / 1024.0 / double(frames) : 0.0, + static_cast(c.conflicts - m.conflicts_seen), + static_cast(m.write_back_calls), + m.write_back_calls ? m.write_back_ms / double(m.write_back_calls) : 0.0, + m.write_back_calls ? m.write_back_wait_ms / double(m.write_back_calls) : 0.0, + m.write_back_max_ms, double(m.read_back_bytes) / double(1 << 20)); + const double denom = m.refreshes ? double(m.refreshes) : 1.0; + const double ns_to_ms = m.refreshes ? (1.0 / (1e6 * double(m.refreshes))) : 0.0; + const double split_total_ms = + double(m.split_lock_ns + m.split_feed_ns + m.split_collect_ns + m.split_arm_ns + m.split_upload_ns + + m.split_filter_ns + m.split_other_ns) * + ns_to_ms; + std::fprintf(stderr, + "[rt] d3d12: page mirror split (ms/refresh): total %.3f = lock %.3f + feed %.3f + collect " + "%.3f + arm %.3f + upload %.3f + filter %.3f + other %.3f; arm: %.1f VP, %.1f VQ, %.1f fast/" + "%.1f slow/%.1f skip, %.1f bridged, %.1f WC; upload: %.1f whole + %.1f inc (%.1f alias) " + "pages\n", + split_total_ms, double(m.split_lock_ns) * ns_to_ms, double(m.split_feed_ns) * ns_to_ms, + double(m.split_collect_ns) * ns_to_ms, double(m.split_arm_ns) * ns_to_ms, + double(m.split_upload_ns) * ns_to_ms, double(m.split_filter_ns) * ns_to_ms, + double(m.split_other_ns) * ns_to_ms, + m.refreshes ? double(m.split_vp_calls) / denom : 0.0, + m.refreshes ? double(m.split_vq_calls) / denom : 0.0, + m.refreshes ? double(m.split_fast_tiles) / denom : 0.0, + m.refreshes ? double(m.split_slow_tiles) / denom : 0.0, + m.refreshes ? double(m.split_skip_tiles) / denom : 0.0, + m.refreshes ? double(m.split_bridged_runs) / denom : 0.0, + m.refreshes ? double(m.split_wc_tiles) / denom : 0.0, + m.refreshes ? double(m.split_whole_pages) / denom : 0.0, + m.refreshes ? double(m.split_inc_pages) / denom : 0.0, + m.refreshes ? double(m.split_alias_pages) / denom : 0.0); + m.split_lock_ns = m.split_feed_ns = m.split_collect_ns = 0; + m.split_arm_ns = m.split_upload_ns = m.split_filter_ns = m.split_other_ns = 0; + m.split_vp_calls = m.split_vq_calls = 0; + m.split_fast_tiles = m.split_slow_tiles = m.split_skip_tiles = 0; + m.split_bridged_runs = m.split_wc_tiles = 0; + m.split_whole_pages = m.split_inc_pages = m.split_alias_pages = 0; + m.write_back_calls = m.read_back_bytes = 0; + m.write_back_ms = m.write_back_wait_ms = m.write_back_max_ms = 0; + m.uploaded_seen = c.uploaded_bytes; + m.conflicts_seen = c.conflicts; + m.unbinds_seen = c.unbinds; + m.homes_freed_seen = c.homes_freed; + m.faults_seen = policy.faults; + m.hot_seen = policy.hot_copies; + m.cold_seen = policy.cold_copies; + m.presents = presents; + m.refreshes = m.fed = m.dirty = m.uploads = m.batches = m.binds = m.arm_failures = 0; + m.resolved = m.resolve_refused = m.identity_mapped = m.identity_released = m.clipped = 0; + m.written_back = m.buffers = 0; + m.ms = 0; + m.since = now; + m.since_ns_atomic.store( + std::chrono::duration_cast(now.time_since_epoch()).count(), + std::memory_order_release); + } + } + // What an arena range holds, for the high-water report (D3D-55). - enum ArenaUse { arena_buffer, arena_descriptor_heap, arena_shader, arena_heap }; - static constexpr const char* kArenaUseNames[4] = {"buffer", "descriptor heap", "shader", "heap"}; + enum ArenaUse { arena_buffer, arena_descriptor_heap, arena_shader, arena_heap, arena_window, arena_use_count }; + static_assert(arena_use_count == 5); + static constexpr const char* kArenaUseNames[arena_use_count] = { + "buffer", "descriptor heap", "shader", "heap", "title window/shadow"}; // A fault line about the arena is rate-limited to this interval: the walk behind it costs a pass over every // free block, and a persistent fault would otherwise print on every allocation of a streaming frame. static constexpr ULONGLONG kArenaReportMs = 5000; @@ -4880,18 +7582,78 @@ struct DeviceState { arena_report_suppressed(what); } + bool arena_ready() const { return arena.backing.ready(); } + // How the shaders read a V#'s 48-bit base: signed, a buffer outside the arena may lie on either side of heap_base + // within 2^47 (TitleBufferWindows::allocate); unsigned, only above it. + bool vsharp_offsets_signed() const { return signed_vsharp_offsets(); } + // The device could bind the arena's memory as it is used (create_arena): sparse binding and residency, strict + // non-resident reads, and a queue of its own for the binds. + bool arena_sparse_capable = false; + + // The CPU address of [offset, offset + bytes) of the arena, inside an allocation the caller holds (its unit + // cannot go while it lives), in constant time (src/arena_backing.h). Null, with a rate-limited line, when no + // memory is behind that range or it crosses a backing unit: a caller's bug, never a silent write elsewhere. + std::uint8_t* arena_host(VkDeviceSize offset, VkDeviceSize bytes) { + std::uint8_t* host = arena.backing.host(offset, bytes); + if (!host) note_unbacked_arena(offset, bytes); + return host; + } + void note_unbacked_arena(VkDeviceSize offset, VkDeviceSize bytes) { + static std::atomic refusals{0}; + const std::uint64_t n = refusals.fetch_add(1, std::memory_order_relaxed); + if (n < 16 || !(n & (n - 1))) + std::fprintf(stderr, "[rt] d3d12: GPU address arena: no memory behind VA 0x%llx + 0x%llx; refused (%llu " + "so far)\n", + static_cast(offset), static_cast(bytes), + static_cast(n + 1)); + } + + // Unbinds and frees the arena's backing units whose last allocation is gone and whose release ticket the GPU has + // passed (src/arena_backing.h). Called at the start of every ExecuteCommandLists, holding nothing: the completed + // ticket is read first (it takes the submit lock), then the arena's lock is taken. + void reclaim_arena() { + if (!context || !arena.backing.sparse()) return; + { + // Non-blocking fast path: skip reclaiming on this submission if arena.mutex is currently held by another + // thread's allocation or sparse bind, and return immediately when no backing units are pending. + std::unique_lock lock(arena.mutex, std::try_to_lock); + if (!lock.owns_lock() || !arena.backing.has_pending()) return; + } + const std::uint64_t completed = context->completed_retire_ticket(); + std::lock_guard lock(arena.mutex); + arena.backing.reclaim(completed); + } + // A zero-size range is refused: it would share its offset with the next range, and its release would collide // with that range's free entry. The fit test cannot wrap: free blocks lie inside the arena (below 4 GiB). - bool arena_allocate(VkDeviceSize bytes, VkDeviceSize alignment, VkDeviceSize& out, ArenaUse use) { - if (!bytes || bytes > arena.size) return false; + bool arena_allocate(VkDeviceSize asked, VkDeviceSize alignment, VkDeviceSize& out, ArenaUse use) { + if (!asked || asked > arena.size) return false; std::lock_guard lock(arena.mutex); + // With sparse binding no allocation crosses a backing unit: one larger than a block takes whole blocks of its + // own (src/arena_backing.h). arena_release rounds the same way. + const VkDeviceSize bytes = arena.backing.footprint(asked); + alignment = arena.backing.alignment(asked, alignment); // Not over a range of the title's own memory: the title's heap can lie below the arena's size, and a view // that names an address there must mean the title's bytes (TitleVaAliases::want_buffer). The walk holds no // iterator across this call, so a cut made under it cannot invalidate it (src/arena_blocks.h). - const bool found = arena.blocks.allocate( + bool found = arena.blocks.allocate( bytes, alignment, - [](std::uint64_t lo, std::uint64_t hi) { return leonida::title_va_aliases().title_overlap_end(lo, hi); }, + [this](std::uint64_t lo, std::uint64_t hi) { + const std::uint64_t title = leonida::title_va_aliases().title_overlap_end(lo, hi); + const std::uint64_t unit = arena.backing.keep_out(lo, hi); + return std::max(title, unit); + }, out); + // Memory behind it before anyone can name it: bound now if its block has none. + if (found && !arena.backing.acquire(out, bytes)) { + arena.blocks.release(out, bytes); + found = false; + if (arena_report_due()) + std::fprintf(stderr, "[rt] d3d12: GPU address arena: no memory could be bound for a %llu KiB " + "allocation (%llu MiB bound)\n", + static_cast(bytes >> 10), + static_cast(arena.backing.stats().bound >> 20)); + } if (!found) { ++arena.failures; if (arena.log) @@ -4938,15 +7700,24 @@ struct DeviceState { std::lock_guard lock(arena.mutex); if (!arena.size) return; const double mib = 1.0 / (1 << 20); + const auto bound = arena.backing.stats(); + std::fprintf(stderr, + "[rt] d3d12: GPU address arena: bound %.1f MiB now (peak %.1f, %llu units of %.0f MiB blocks, %s), " + "%llu binds, %llu unbind batches, %llu bind failures\n", + bound.bound * mib, bound.peak_bound * mib, static_cast(bound.units), + arena.backing.block() * mib, arena.backing.sparse() ? "sparse" : "one allocation", + static_cast(bound.binds), static_cast(bound.unbinds), + static_cast(bound.bind_failures)); std::fprintf(stderr, "[rt] d3d12: GPU address arena: peak end %.1f of %.1f MiB (%.1f%%), peak live %.1f MiB " - "(buffers %.1f, descriptor heaps %.1f of which null guards %.1f now, shaders %.1f, heaps %.1f), %llu " - "allocations, %llu refused; %zu free blocks (largest %.1f MiB, %.1f MiB free)\n", + "(buffers %.1f, descriptor heaps %.1f of which null guards %.1f now, shaders %.1f, heaps %.1f, " + "windows/shadows %.1f), %llu allocations, %llu refused; %zu free blocks (largest %.1f MiB, %.1f " + "MiB free)\n", arena.peak_end * mib, arena.size * mib, 100.0 * double(arena.peak_end) / double(arena.size), arena.peak_in_use * mib, arena.use_peak[arena_buffer] * mib, arena.use_peak[arena_descriptor_heap] * mib, double(arena_guard_bytes.load(std::memory_order_relaxed)) * mib, arena.use_peak[arena_shader] * mib, - arena.use_peak[arena_heap] * mib, + arena.use_peak[arena_heap] * mib, arena.use_peak[arena_window] * mib, (unsigned long long)arena.allocations, (unsigned long long)arena.failures, arena.blocks.count(), arena.blocks.largest().size * mib, arena.blocks.free_bytes() * mib); } @@ -4970,12 +7741,17 @@ struct DeviceState { } } - void arena_release(VkDeviceSize offset, VkDeviceSize bytes, ArenaUse use) { - if (!bytes) return; + void arena_release(VkDeviceSize offset, VkDeviceSize asked, ArenaUse use) { + if (!asked) return; + // Every submission made so far, and the one being recorded now, may name the range: its block is unbound only + // once the GPU is past the next ticket (as VulkanContext::defer_destroy). An atomic read: no lock is taken. + const std::uint64_t ticket = context ? context->submitted_retire_ticket() + 1 : 0; std::lock_guard lock(arena.mutex); + const VkDeviceSize bytes = arena.backing.footprint(asked); // The range is validated and merged before the live-byte counters move: a release of a range the arena never // had must not change them, and a double free must not count the bytes twice. const auto fault = arena.blocks.release(offset, bytes); + if (fault == leonida::ArenaBlocks::Fault::none) arena.backing.release(offset, bytes, ticket); if (fault != leonida::ArenaBlocks::Fault::outside_arena) { backing(arena.address + offset, bytes, offset, false); arena.in_use -= bytes; @@ -5014,7 +7790,8 @@ struct DeviceState { // the console VA of a GPU copy (rebase_title_vsharp), and an unregistered T# is bound (bind_title_image). // The tracker copies into a host mirror of the title's bytes, and only the slots whose bytes differ from what // their arena slot was made from (a second host copy) are fixed and written there again; a T# that found no - // texture and a V# into title memory with no copy yet are tried at every submission until they do. Pages xmem + // texture and a V# that found no backing are recorded as waiting (ConsoleHeap::records) and fixed again when a + // texture, backing, alias or room comes for them (apply_slot_changes), never by looking again. Pages xmem // maps at two addresses are copied at every submission, and fixing all their slots each time, reading the // arena (uncached device memory) to do it, cost more than a frame (295 ms a submission for the 4 MiB of the // retail heap in use, RTX 4070 Ti). @@ -5047,15 +7824,49 @@ struct DeviceState { ShadowPagesPtr pages; std::vector mirror; // the title's bytes as the tracker last copied them std::vector made; // the title's bytes each arena slot was last made from - std::vector retry; // per slot: not settled yet (fix_console_slot), in `retries` - // A resource heap's V# halves: what each resolved to (fix_console_slot), so a change of the address space - // re-fixes the slots it touches (apply_slot_changes), and a V# whose buffer comes later is fixed when it does. + // Per slot: in `retries`. On the CPU path a slot LEONIDA_CONSOLE_FIX_US deferred (fix_deferred_slots); in the + // GPU mode (refresh_console_heap_gpu) also a T# whose texture is still to come (retry_console_tsharps). + std::vector retry; + // A resource heap's V# halves and T#s: what each resolved to or waits for (fix_console_slot), so a change of + // the address space or of the textures re-fixes the slots it touches (apply_slot_changes), and a V# whose + // buffer or a T# whose texture comes later is fixed when it does. leonida::ConsoleHeapSlotRecords records; std::vector retries; - std::size_t retry_at = 0; // where retry_console_slots goes on - // fix_vsharp's answers during one pass over the heap's slots (fix_heap_vsharp), cleared after it. - std::unordered_map answers; - bool answering = false; + std::size_t retry_at = 0; // where retry_console_tsharps goes on (GPU mode) + // Since the last log line: T# fixes left waiting (for a texture at their address, or room), and T#s that + // waited and are bound now. + std::uint64_t texture_waits = 0, texture_refills = 0; + // V# halves answered by a waiting half of the same range (fix_vsharp), and how many of slot_changes this + // heap has applied since refresh_console_heaps took the list (sync_slot_changes). + std::uint64_t vsharps_answered = 0, vsharps_answered_resolved = 0; + std::size_t changes_seen = 0; + // Since the last log line: the full resolutions of its V# halves and their time, the classes of those that + // resolved to nothing, and the longest refresh with its parts (pages, changes applied, slots fixed). + std::uint64_t resolutions = 0; + double resolution_ms = 0; + std::uint64_t nothing[nothing_classes] = {}; + // For the arena-offset and not-title-memory classes: what the host has at the base as an address + // (nothing_where_kind), so a log names the memory a V# resolved to nothing names. + std::uint64_t nothing_where[2][5] = {}; + double max_ms = 0, max_pages_ms = 0, max_changes_ms = 0, max_fix_ms = 0; + // Read in place (add_heap_in_place): the page mirror holds the title's heap pages, bound a second time into the + // arena at shader_va, and fills their home through filter_heap_page. No copy, no page tracker of its own. + // Under page_mirror.mutex, not console_heap_mutex (the filter runs inside the mirror's fills): `previous` (the + // title's bytes each slot was last filtered from), the records, `deferred` (the slots whose V#s the mirror does + // not hold or whose T# is to be bound: done outside the mirror's lock, finish_in_place), the title ranges its + // V#s name in the mirror (for the write-back), `pending_changes` (noted after the mirror's last look at the + // change list) and the counters since the last log line: pages filtered, slots that changed, the time, V# + // halves read as written and halves deferred, and the presents in between (per-frame figures). + bool in_place = false; + std::atomic in_place_work_pending{false}; // lock-free hint: deferred, mirror_ranges, or pending_changes + std::vector deferred; + std::vector deferred_mark; + std::vector> mirror_ranges; + std::vector pending_changes; + std::vector touched_scratch; + std::uint64_t pages_filtered = 0, slots_filtered = 0, present_mark = 0; + std::uint64_t vsharps_as_written = 0, vsharps_deferred = 0, vsharps_rejected = 0; + double filter_ms = 0, deferred_ms = 0; // fix_console_slots' budget, for the current refresh, and the slots it nulled since the last log line std::chrono::steady_clock::time_point fix_start{}; bool fix_over = false; @@ -5064,9 +7875,14 @@ struct DeviceState { std::uint64_t refreshes = 0, logged = 0; std::chrono::steady_clock::time_point log_time{}; // Since the last log line. - std::uint64_t copied = 0, vsharps = 0, unbacked = 0, retried = 0, reused = 0; + std::uint64_t copied = 0, vsharps = 0, unbacked = 0, retried = 0; std::uint64_t images[5] = {}; // by TitleImage - std::map refused_reasons; + struct ReasonLess { + bool operator()(const char* a, const char* b) const noexcept { + return a != b && std::strcmp(a, b) < 0; + } + }; + std::map refused_reasons; double ms = 0, pages_ms = 0, fix_ms = 0, retry_ms = 0; // ms: all; the others its parts // Changed slots by class (before the fix budget), since the last log line: all-zero, V# pair, T#, other // words; V# halves whose 16 bytes were seen before (a direct-mapped memo of 65536 keys, so a lower bound of @@ -5088,6 +7904,17 @@ struct DeviceState { }; std::mutex console_heap_mutex; // taken before title_window_mutex, shadow_mutex and descriptor_mutex std::vector> console_heaps; + std::atomic console_heap_signature{0xcbf29ce484222325ull}; + void update_console_heap_signature_locked() { // console_heap_mutex held + std::uint64_t sig = 0xcbf29ce484222325ull; + 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; + sig = (sig ^ begin) * 0x100000001b3ull; + sig = (sig ^ end) * 0x100000001b3ull; + } + console_heap_signature.store(sig, std::memory_order_release); + } // Null slots after a shader-visible resource heap's GPU copy. A directly indexed heap is read at // heap VA + index * 32 with the index from data (docs/d3d12_vulkan.md section 3.4), and nothing bounds it: an @@ -5136,10 +7963,18 @@ struct DeviceState { // [start, start + bytes) of the arena, exactly. False when any of it is taken or past the arena. - bool arena_allocate_at(VkDeviceSize start, VkDeviceSize bytes, ArenaUse use) { - if (!bytes || start > arena.size || bytes > arena.size - start) return false; + bool arena_allocate_at(VkDeviceSize start, VkDeviceSize asked, ArenaUse use) { + if (!asked || start > arena.size || asked > arena.size - start) return false; std::lock_guard lock(arena.mutex); - if (!arena.blocks.allocate_at(start, bytes)) return false; + // At `start` exactly, rounded as arena_allocate rounds (so arena_release gives back the same bytes): it must lie + // in one unit, or over blocks that have none yet. + const VkDeviceSize bytes = arena.backing.footprint(asked); + if (bytes > arena.size - start) return false; + if (!arena.backing.placeable(start, bytes) || !arena.blocks.allocate_at(start, bytes)) return false; + if (!arena.backing.acquire(start, bytes)) { + arena.blocks.release(start, bytes); + return false; + } backing(arena.address + start, bytes, start, true); ++arena.allocations; arena.in_use += bytes; @@ -5150,32 +7985,24 @@ struct DeviceState { return true; } - // fix_vsharp, asked once for each distinct V# in a pass over a heap's slots (heap.answering). The title writes the - // same words into thousands of slots, many of them data that reads as a V# into title memory with no copy, and - // each such answer costs VirtualQuery calls: under Wine a third of the submitting thread's time in the world. - VsharpResult fix_heap_vsharp(ConsoleHeap& heap, std::uint32_t* w, VsharpPath path, VsharpRecord* record) { - if (!heap.answering || (w[3] >> 30) || !w[2]) return fix_vsharp(w, path, record); - const VsharpWords key{w[0] | std::uint64_t(w[1]) << 32, w[2] | std::uint64_t(w[3]) << 32}; - if (const auto it = heap.answers.find(key); it != heap.answers.end()) { - std::memcpy(w, it->second.words, sizeof(it->second.words)); - *record = it->second.record; - ++heap.reused; - return it->second.result; - } - const VsharpResult result = fix_vsharp(w, path, record); - heap.answers.emplace(key, VsharpAnswer{{w[0], w[1], w[2]}, result, *record}); - return result; - } - // Slot `slot` of a heap copy, as the title wrote it, fixed up as described above, and the only writer of a - // resource heap's slot records. True when it is settled: not a T# whose texture is still to come. A sampler heap - // holds S#s: copied as written. - bool fix_console_slot(ConsoleHeap& heap, std::size_t slot) { + // resource heap's slot records. A T# that found no texture, or one that does not fit it, is recorded as waiting + // for the texture at its address (or for room in its bindless array): a texture registered, replaced or gone there + // fixes the slot again (apply_slot_changes), and nothing looks at it before. A sampler heap holds S#s: copied as + // written. + // `answers`: the title rewrote the slot (fix_console_slots), so a waiting V# of the same range may answer for it + // (fix_vsharp). A slot fixed again because a change touched it is always resolved anew. + // `out`: where the fixed slot goes, the heap's copy by default; for a heap read in place, its page's home in the + // page mirror (filter_heap_page, refilter_slot). + void fix_console_slot(ConsoleHeap& heap, std::size_t slot, bool answers = false, std::uint8_t* out = nullptr) { std::uint32_t w[kDescriptorSize / 4]; std::memcpy(w, heap.previous + slot * kDescriptorSize, kDescriptorSize); - bool settled = true, vsharp = false; + bool vsharp = false; + using Records = leonida::ConsoleHeapSlotRecords; + Records::State texture = Records::none; + std::uint64_t texture_address = 0; VsharpRecord halves[2]; - const VsharpPath path = heap.scratch ? VsharpPath::scratch : VsharpPath::shadow; + const VsharpPath path = (heap.scratch || heap.in_place) ? VsharpPath::scratch : VsharpPath::shadow; if (!heap.resource_heap || !(w[0] | w[1] | w[2] | w[3])) { // A sampler heap holds S#s (copied as written); an all-zero slot stays null. } else if (!(w[3] >> 30)) { @@ -5184,28 +8011,48 @@ struct DeviceState { // and recorded as waiting: a backing, alias range or title memory added over it fixes the slot again // (apply_slot_changes). vsharp = true; - const VsharpResult result = fix_heap_vsharp(heap, w, path, &halves[0]); + const VsharpResult result = fix_vsharp(w, path, &halves[0], &heap, answers); if (result == VsharpResult::rebased) ++heap.vsharps; // Only the GPU copy changes; the title's bytes (heap.previous) stay as written. if (result == VsharpResult::empty) ++heap.unbacked; // The slot's second V# is a UAV counter (raw, 4 bytes, in the descriptor's upper 16 bytes): a store to it at // heap_base + a raw title address loses the device just as one through the buffer V# does. A counter with // no backing is nulled and waits as the buffer V# does. - if (fix_heap_vsharp(heap, w + 4, path, &halves[1]) == VsharpResult::empty) ++heap.unbacked; + if (fix_vsharp(w + 4, path, &halves[1], &heap, answers) == VsharpResult::empty) ++heap.unbacked; } else { leonida::gfx10::ImageWords words; std::memcpy(words.data(), w, sizeof(words)); if (leonida::gfx10::is_image(words)) { const char* why = nullptr; - const TitleImage result = bind_title_image(*this, words, &why); - if (result == TitleImage::unknown || result == TitleImage::refused) { + std::uint32_t index_word = 0; + const TitleImage result = + bind_title_image(*this, words, &why, tsharp_index_words ? &index_word : nullptr); + const bool unbound = result == TitleImage::unknown || result == TitleImage::refused; + if (unbound) { note_refused_tsharp(heap, slot * kDescriptorSize, words, why); - if (result == TitleImage::refused) - ++heap.refused_reasons[why ? why : "?"]; + ++heap.refused_reasons[why ? why : "?"]; } ++heap.images[unsigned(result)]; - settled = result != TitleImage::unknown && result != TitleImage::refused; - if (result == TitleImage::not_tsharp) std::memset(w, 0, 16); + if (result == TitleImage::not_tsharp) { + std::memset(w, 0, 16); + } else { + leonida::gfx10::Image image{}; + leonida::gfx10::decode(words, image); + // Waits under the address its texture is registered and announced at (note_texture_change). + texture_address = tsharp_texture_key(image.address); + texture = !unbound ? Records::texture_bound + : why == kTsharpArrayFull || why == kTsharpStorageFull ? Records::texture_waiting_room + : Records::texture_waiting; + if (unbound) ++heap.texture_waits; + else if (Records::is_waiting(heap.records.state(slot, 0)) && + heap.records.base(slot, 0) == texture_address) + ++heap.texture_refills; // the T# waited for this address and is bound now + // The copy's dword 6 is the index shaders take (gfx10_descriptors.h, tsharp_index_word), or 0 while + // the T# waits: a texture coming, going or being replaced at its address fixes the slot again + // (apply_slot_changes), so the word follows the texture the T# names. The title's bytes and the + // T#'s key keep the title's dword 6. + if (tsharp_index_words) w[leonida::gfx10::kTsharpIndexDword] = unbound ? 0u : index_word; + } } else { // Neither a buffer V# (TYPE is not 0) nor a T# the layer can decode: data the title keeps in the slot. // No image is found by these words (the bindless lookup misses, as for a null T#), but a shader that @@ -5215,16 +8062,55 @@ struct DeviceState { std::memset(w, 0, 16); } } - std::memcpy(heap.copy + slot * kDescriptorSize, w, kDescriptorSize); + std::memcpy(out ? out : heap.copy + slot * kDescriptorSize, w, kDescriptorSize); if (heap.resource_heap) { if (vsharp) for (unsigned half = 0; half < 2; ++half) heap.records.set(slot, half, halves[half].state, halves[half].base, halves[half].span, - halves[half].target); + halves[half].target, halves[half].geometry); + else if (texture != Records::none) + heap.records.set_texture(slot, texture, texture_address); else heap.records.clear(slot); } - return settled; + } + + static constexpr std::size_t kSeenKeysMask = 511u; // 512 entries (8 KiB): fits in L1d instead of thrashing 1 MiB L2/L3 + + static bool slots_equal_32(const std::uint8_t* a, const std::uint8_t* b) noexcept { +#if defined(__AVX2__) + const __m256i va = _mm256_loadu_si256(reinterpret_cast(a)); + const __m256i vb = _mm256_loadu_si256(reinterpret_cast(b)); + const __m256i diff = _mm256_xor_si256(va, vb); + return _mm256_testz_si256(diff, diff) != 0; +#else + std::uint64_t a0 = 0, a1 = 0, a2 = 0, a3 = 0; + std::uint64_t b0 = 0, b1 = 0, b2 = 0, b3 = 0; + std::memcpy(&a0, a + 0, 8); + std::memcpy(&a1, a + 8, 8); + std::memcpy(&a2, a + 16, 8); + std::memcpy(&a3, a + 24, 8); + std::memcpy(&b0, b + 0, 8); + std::memcpy(&b1, b + 8, 8); + std::memcpy(&b2, b + 16, 8); + std::memcpy(&b3, b + 24, 8); + return ((a0 ^ b0) | (a1 ^ b1) | (a2 ^ b2) | (a3 ^ b3)) == 0; +#endif + } + + static void note_changed_vsharp_words(ConsoleHeap& heap, const std::uint32_t* w) { + ++heap.changed[1]; + if (heap.seen_keys.size() != kSeenKeysMask + 1) heap.seen_keys.assign(kSeenKeysMask + 1, {}); + for (int half = 0; half < 2; ++half) { + const std::uint32_t* k = w + 4 * half; + if (!k[2]) continue; // no records: nothing to translate + ++heap.vsharp_halves; + std::uint32_t h = 2166136261u; + for (int i = 0; i < 4; ++i) h = (h ^ k[i]) * 16777619u; + auto& entry = heap.seen_keys[h & kSeenKeysMask]; + if (entry[0] == k[0] && entry[1] == k[1] && entry[2] == k[2] && entry[3] == k[3]) ++heap.vsharp_repeats; + else entry = {k[0], k[1], k[2], k[3]}; + } } // Diagnostics only: the class of a changed slot, and whether its V# halves were seen before (ConsoleHeap::changed). @@ -5241,24 +8127,13 @@ struct DeviceState { ++heap.changed[leonida::gfx10::is_image(words) ? 2 : 3]; return; } - ++heap.changed[1]; - if (heap.seen_keys.empty()) heap.seen_keys.resize(65536); - for (int half = 0; half < 2; ++half) { - const std::uint32_t* k = w + 4 * half; - if (!k[2]) continue; // no records: nothing to translate - ++heap.vsharp_halves; - std::uint32_t h = 2166136261u; - for (int i = 0; i < 4; ++i) h = (h ^ k[i]) * 16777619u; - auto& entry = heap.seen_keys[h & 0xffffu]; - if (entry[0] == k[0] && entry[1] == k[1] && entry[2] == k[2] && entry[3] == k[3]) ++heap.vsharp_repeats; - else entry = {k[0], k[1], k[2], k[3]}; - } + note_changed_vsharp_words(heap, w); } // The slots on [offset, offset + bytes) of a heap copy's mirror, just brought up to date: each that differs from // what its arena slot was made from is written there and fixed up. // LEONIDA_CONSOLE_FIX_US limits the fixing in one submission (0, the default: no limit). Past it a changed slot is - // written as a null descriptor and left to retry_console_slots: after the story load the title rewrote up to + // written as a null descriptor and fixed at a later submission (fix_deferred_slots): after the story load the title rewrote up to // 3.7 MiB of its heap at once and one submission spent 28 s fixing it (speed-8). A shader reads such a slot as // empty until its turn comes, so a limit changes results: at the first world frame lib_cs_01144 read the size it // divides by from a nulled buffer slot and its loops never ended, which lost the device. @@ -5296,70 +8171,1547 @@ struct DeviceState { heap.retry[slot] = 1; heap.retries.push_back(std::uint32_t(slot)); } - continue; + continue; + } + heap.retry[slot] = 0; + fix_console_slot(heap, slot, true); + } + } + + // The slots LEONIDA_CONSOLE_FIX_US deferred at an earlier submission (null in the copy meanwhile): fixed first, + // under the same budget; those past it wait for the next submission. Nothing else is in the list on this path. + void fix_deferred_slots(ConsoleHeap& heap) { + static const std::uint64_t budget_us = [] { + char text[16] = {}; + const DWORD n = GetEnvironmentVariableA("LEONIDA_CONSOLE_FIX_US", text, sizeof(text)); + return n > 0 && n < sizeof(text) ? std::strtoull(text, nullptr, 10) : 0ull; + }(); + std::size_t done = 0; + for (; done < heap.retries.size(); ++done) { + if (budget_us && !(++heap.fix_count & 15) && + std::chrono::steady_clock::now() - heap.fix_start >= std::chrono::microseconds(budget_us)) { + heap.fix_over = true; + break; + } + const std::uint32_t slot = heap.retries[done]; + if (!heap.retry[slot]) continue; // rewritten or zeroed since + heap.retry[slot] = 0; + fix_console_slot(heap, slot); + ++heap.retried; + } + heap.retries.erase(heap.retries.begin(), heap.retries.begin() + std::ptrdiff_t(done)); + } + + // The changes since the last submission (slot_changes), applied to a resource heap's copy: each slot whose record + // a change touches is fixed again - a V# whose backing, copy or alias range went, so the copy never names freed + // memory, a waiting V# over which a backing, alias range or title memory was added or for which geometry room was + // made, and a T# whose texture was registered, replaced or went at its address, or that waited for room in its + // bindless array when entries were freed. Only the slots the changes name are looked at + // (ConsoleHeapSlotRecords::touched); nothing reads the copy. + std::vector slot_change_scratch; // console_heap_mutex + std::uint64_t geometry_room_seen = 0; // geometry.free_generation() at the last refresh (console_heap_mutex) + void apply_slot_changes(ConsoleHeap& heap, const std::vector& changes) { + if (!heap.resource_heap || changes.empty()) return; + const auto start = std::chrono::steady_clock::now(); + const std::uint64_t looked = heap.records.looked_at(); + heap.records.touched(changes.data(), changes.size(), slot_change_scratch); + heap.record_changes += changes.size(); + heap.record_looked += heap.records.looked_at() - looked; + heap.record_refixed += slot_change_scratch.size(); + // A slot deferred by the fix budget (null in the copy) is fixed from its list, not here. + for (const std::uint32_t slot : slot_change_scratch) + if (!heap.retry[slot]) fix_console_slot(heap, slot); + heap.record_ms += std::chrono::duration(std::chrono::steady_clock::now() - start).count(); + } + + // ---- Console heaps read in place (add_heap_in_place) ---- + // Lock order: console_heap_mutex, then page_mirror.mutex, then slot_change_mutex. The filter runs inside the + // mirror's fills (page_mirror.mutex held, console_heap_mutex not), so under the mirror's lock it does only what + // needs no other lock of ours: reachability (reachable_as_written), nulls, and the list of slots to finish. The rest + // - a V# the mirror does not hold resolved as before, a T# bound - is finish_in_place's, in the heap's refresh + // (console_heap_mutex held), outside the mirror's lock, its result written into the home under it. + + // Per-page stack-local cache used while page_mirror.mutex is continuously held across filter_heap_page / + // filter_heap_page_pieces / apply_in_place_changes. Deduplicates repeated V# (base, span) classifications within + // the same page fill so repeated descriptors avoid redundant backing_mutex / title_va_aliases / TitleMirror lookups + // while preserving 100% exact ConsoleHeapSlotRecords state (every cached resolved/waiting/deferred slot still + // updates heap.records / heap.deferred, so concurrent SlotChanges refilter all of them in apply_in_place_changes). + struct FilterPageCache { + enum class Outcome : std::uint8_t { empty = 0, mirrored, backed, waiting, defer }; + struct Entry { + std::uint64_t base = 0; + std::uint64_t span = 0; + std::uint64_t target = 0; + ConsoleHeap* mirror_range_heap = nullptr; + std::uint32_t gen = 0; + Outcome outcome = Outcome::empty; + }; + static constexpr std::size_t kSize = 1024; + std::array entries{}; + std::uint32_t gen = 0; + bool signed_vsharp = false; + bool has_mirror = false; + bool has_geometry = false; + std::uint64_t arena_size = 0; + + void reset() noexcept { + if (++gen == 0) { + entries = {}; + gen = 1; + } + } + static std::size_t bucket(std::uint64_t base, std::uint64_t span) noexcept { + const std::uint64_t h = (base >> 4) ^ (span * 0x9e3779b97f4a7c15ull); + return static_cast((h ^ (h >> 17) ^ (h >> 31)) & (kSize - 1)); + } + Entry* find(std::uint64_t base, std::uint64_t span) noexcept { + Entry& e = entries[bucket(base, span)]; + return (e.gen == gen && e.outcome != Outcome::empty && e.base == base && e.span == span) ? &e : nullptr; + } + void put(std::uint64_t base, std::uint64_t span, Outcome outcome, std::uint64_t target = 0, + ConsoleHeap* mr_heap = nullptr) noexcept { + entries[bucket(base, span)] = {base, span, target, mr_heap, gen, outcome}; + } + }; + + // Acquires the hoisted thread-local FilterPageCache for this DeviceState under page_mirror.mutex. A re-entrant + // fill triggered by page_mirror_resolve_locked() -> map() reuses the live batch cache without resetting it. + struct FilterCacheScope { + FilterPageCache* cache = nullptr; + std::unique_ptr fallback; + bool owns_active = false; + const DeviceState** owner_slot = nullptr; + + explicit FilterCacheScope(DeviceState& dev) { + thread_local std::unique_ptr tls_cache; + thread_local const DeviceState* tls_owner = nullptr; + if (!tls_cache) tls_cache = std::make_unique(); + if (tls_owner == &dev) { + cache = tls_cache.get(); + return; + } + if (tls_owner == nullptr) { + tls_owner = &dev; + owner_slot = &tls_owner; + owns_active = true; + cache = tls_cache.get(); + } else { + fallback = std::make_unique(); + cache = fallback.get(); + } + cache->reset(); + cache->signed_vsharp = signed_vsharp_offsets(); + cache->has_mirror = dev.page_mirror.mirror != nullptr; + cache->has_geometry = dev.geometry.cap() != 0; + cache->arena_size = dev.arena.size; + if (cache->has_mirror) dev.sync_mirror_space_locked(); + } + ~FilterCacheScope() { + if (owns_active && owner_slot) *owner_slot = nullptr; + } + FilterCacheScope(const FilterCacheScope&) = delete; + FilterCacheScope& operator=(const FilterCacheScope&) = delete; + }; + + // Coalesces contiguous changed 32-byte descriptor slots across a 64 KiB page (2048 slots = 32 x 64-bit mask words) + // from cached host RAM `out_buf` into WC PCIe BAR VRAM `to`. Never reads from `to` and never overwrites unchanged + // slots (preserving previously bound T#s / resolved V#s in untouched slots). + static void flush_written_slot_runs(std::uint8_t* to, const std::uint8_t* out_buf, + const std::array& written_slots, + std::size_t written_count) noexcept { + constexpr std::size_t kSlotsPerPage = leonida::TitleMirror::kPage / kDescriptorSize; + if (!written_count) return; + if (written_count == kSlotsPerPage) { + std::memcpy(to, out_buf, leonida::TitleMirror::kPage); + return; + } + std::size_t run_start = kSlotsPerPage; + for (std::size_t w = 0; w < 32; ++w) { + const std::uint64_t word = written_slots[w]; + if (!word) { + if (run_start < kSlotsPerPage) { + const std::size_t run_end = w * 64; + std::memcpy(to + run_start * kDescriptorSize, out_buf + run_start * kDescriptorSize, + (run_end - run_start) * kDescriptorSize); + run_start = kSlotsPerPage; + } + continue; + } + if (word == ~std::uint64_t(0)) { + if (run_start == kSlotsPerPage) run_start = w * 64; + continue; + } + std::size_t bit = 0; + while (bit < 64) { + const std::uint64_t rem = word >> bit; + if (!rem) { + if (run_start < kSlotsPerPage) { + const std::size_t run_end = w * 64 + bit; + std::memcpy(to + run_start * kDescriptorSize, out_buf + run_start * kDescriptorSize, + (run_end - run_start) * kDescriptorSize); + run_start = kSlotsPerPage; + } + break; + } + const std::size_t zeros = std::size_t(std::countr_zero(rem)); + if (zeros > 0) { + if (run_start < kSlotsPerPage) { + const std::size_t run_end = w * 64 + bit; + std::memcpy(to + run_start * kDescriptorSize, out_buf + run_start * kDescriptorSize, + (run_end - run_start) * kDescriptorSize); + run_start = kSlotsPerPage; + } + bit += zeros; + } + const std::size_t ones = std::size_t(std::countr_one(word >> bit)); + if (run_start == kSlotsPerPage) run_start = w * 64 + bit; + bit += ones; + } + } + if (run_start < kSlotsPerPage) { + std::memcpy(to + run_start * kDescriptorSize, out_buf + run_start * kDescriptorSize, + (kSlotsPerPage - run_start) * kDescriptorSize); + } + } + + // Pure read-only check equivalent to page_mirror_resolve_locked(va, bytes, /*make=*/false) after + // sync_mirror_space_locked(). Safe to call concurrently from parallel Phase A workers while page_mirror.mutex is + // held continuously by the calling thread (zero mutations to chunks_, homes_, plain, ensured, or counters). + bool page_mirror_is_resolved_readonly(std::uint64_t va, std::uint64_t bytes) const noexcept { + if (!bytes || va + bytes < va) return false; + constexpr std::uint64_t kChunk = leonida::TitleMirror::kChunk; + constexpr std::uint64_t kPage = leonida::TitleMirror::kPage; + const std::uint64_t end = va + bytes; + for (std::uint64_t c = va & ~(kChunk - 1); c < end; c += kChunk) { + if (!page_mirror.mirror->covers(c)) return false; + if (c > UINT64_MAX - kChunk) break; + } + auto it = page_mirror.plain.upper_bound(va); + if (it != page_mirror.plain.begin() && std::prev(it)->second > va) --it; + for (; it != page_mirror.plain.end() && it->first < end; ++it) { + const std::uint64_t from = (std::max)(it->first, va) & ~(kPage - 1); + const std::uint64_t to = ((std::min)(it->second, end) + kPage - 1) & ~(kPage - 1); + if (!ensured_covers(from, to)) return false; + } + return true; + } + + // Reusable cached 64 KiB host scratch buffer for single-page filter writes (avoids scattered 32B WC BAR writes and + // avoids putting a 64 KiB array on a Windows/Wine thread stack). Falls back to heap allocation on re-entry. + struct OutScratchGuard { + std::uint8_t* ptr = nullptr; + std::unique_ptr overflow; + bool* in_use = nullptr; + OutScratchGuard() { + thread_local std::unique_ptr tls_buf; + thread_local bool tls_in_use = false; + if (!tls_in_use) { + if (!tls_buf) tls_buf.reset(new std::uint8_t[leonida::TitleMirror::kPage]); + tls_in_use = true; + in_use = &tls_in_use; + ptr = tls_buf.get(); + } else { + overflow.reset(new std::uint8_t[leonida::TitleMirror::kPage]); + ptr = overflow.get(); + } + } + ~OutScratchGuard() { + if (in_use) *in_use = false; + } + OutScratchGuard(const OutScratchGuard&) = delete; + OutScratchGuard& operator=(const OutScratchGuard&) = delete; + }; + + // Slot `slot` of a heap read in place, from its title bytes as last filtered (`previous`), into `out` (either a + // cached 64 KiB scratch buffer or its place in the page's home). page_mirror.mutex held. + void filter_slot_locked(ConsoleHeap& heap, std::size_t slot, std::uint8_t* out, + FilterPageCache* cache = nullptr, bool count_changed = false) { + using Records = leonida::ConsoleHeapSlotRecords; + std::uint32_t w[kDescriptorSize / 4]; + std::memcpy(w, heap.previous + slot * kDescriptorSize, kDescriptorSize); + bool defer = false; + bool added_mirror_range = false; + if (!(w[0] | w[1] | w[2] | w[3])) { + if (count_changed) ++heap.changed[(w[4] | w[5] | w[6] | w[7]) ? 1 : 0]; + heap.records.clear(slot); // a null slot stays null + } else if (!(w[3] >> 30)) { + if (count_changed) note_changed_vsharp_words(heap, w); + const bool signed_vsharp = cache ? cache->signed_vsharp : signed_vsharp_offsets(); + const std::uint64_t arena_size = cache ? cache->arena_size : arena.size; + const bool has_geometry = cache ? cache->has_geometry : (geometry.cap() != 0); + // A buffer V# and its UAV counter: each read as written when heap_base + its base holds its bytes, else + // null until finish_in_place resolves it (recorded as waiting meanwhile, so a change finds it). + for (unsigned half = 0; half < 2; ++half) { + std::uint32_t* h = w + 4 * half; + if ((h[3] >> 30) || !h[2]) { + heap.records.set(slot, half, Records::none, 0, 0, 0); + continue; + } + const std::uint64_t base = std::uint64_t(h[0]) | (std::uint64_t(h[1] & 0xffff) << 32); + const std::uint32_t stride = (h[1] >> 16) & 0x3fffu; + const std::uint64_t span = std::uint64_t(h[2]) * (stride ? stride : 1); + // Fast inline arena hit: skips reachable_as_written(), mirror lookups, and cache hashing. + if (base && (!signed_vsharp || !(base & (1ull << 47))) && base < arena_size && + (span ? span : 1) <= arena_size - base) { + heap.records.set(slot, half, Records::none, 0, 0, 0); + ++heap.vsharps_as_written; + continue; + } + if (cache) { + if (FilterPageCache::Entry* cached = cache->find(base, span)) { + switch (cached->outcome) { + case FilterPageCache::Outcome::mirrored: + heap.records.set(slot, half, Records::none, 0, 0, 0); + if (cached->mirror_range_heap != &heap) { + heap.mirror_ranges.emplace_back(base, span); + cached->mirror_range_heap = &heap; + added_mirror_range = true; + } + ++heap.vsharps_as_written; + continue; + case FilterPageCache::Outcome::backed: + heap.records.set(slot, half, Records::resolved, base, span, cached->target, false); + ++heap.vsharps_as_written; + continue; + case FilterPageCache::Outcome::waiting: + heap.records.set(slot, half, Records::waiting, base, span, 0, true); + h[0] = h[1] = h[2] = h[3] = 0; + ++heap.vsharps_rejected; + continue; + case FilterPageCache::Outcome::defer: + heap.records.set(slot, half, Records::none, 0, 0, 0); + h[0] = h[1] = h[2] = h[3] = 0; + ++heap.vsharps_deferred; + defer = true; + continue; + default: + break; + } + } + } + bool mirrored = false; + std::uint64_t target = 0; + if (reachable_as_written(base, span, mirrored, &target)) { + if (target) { + heap.records.set(slot, half, Records::resolved, base, span, target, false); + if (cache) cache->put(base, span, FilterPageCache::Outcome::backed, target); + } else { + heap.records.set(slot, half, Records::none, 0, 0, 0); + if (mirrored) { + heap.mirror_ranges.emplace_back(base, span); + added_mirror_range = true; + if (cache) cache->put(base, span, FilterPageCache::Outcome::mirrored, 0, &heap); + } + } + ++heap.vsharps_as_written; + continue; + } + // Classify V# halves that reachable_as_written did not accept, maintaining exact semantic parity with + // finish_in_place -> vsharp_address (VsharpPath::scratch): + // - permanently impossible (null base, unbacked bit-47, or arena offset whose span exceeds arena.size + // and is neither in title_memory, aliased, nor a stream-pool GPU view): null with Records::none; + // - unresolvable right now (base >= arena.size, not in title_memory within span, no alias, and no + // stream-pool GPU view): null and record Records::waiting directly without deferring, so a later + // SlotChange::source_added (backing, alias, or title_memory) still wakes and re-filters it; + // - otherwise: clear any stale record, null temporarily, and defer to finish_in_place. + auto& aliases = leonida::title_va_aliases(); + bool permanent_impossible = !base || (base & (1ull << 47)) != 0; + bool in_title = false, has_alias = false, is_gpu_view = false; + if (!permanent_impossible) { + std::uint64_t lo = 0, hi = 0; + in_title = aliases.title_memory(base, lo, hi) && span <= hi - base; + if (!in_title) { + std::uint64_t alias_to = 0, alias_room = 0; + has_alias = aliases.range_of(base, alias_to, alias_room); + if (!has_alias) { + is_gpu_view = has_geometry && leonida::title_gpu_views::to_cpu(base, span) != base; + if (!is_gpu_view && base < arena_size) permanent_impossible = true; + } + } + } + if (permanent_impossible) { + heap.records.set(slot, half, Records::none, 0, 0, 0); + h[0] = h[1] = h[2] = h[3] = 0; // null whole: no three words of four + ++heap.vsharps_rejected; + continue; + } + if (!in_title && !has_alias && !is_gpu_view) { + // `!in_title && !has_alias && !is_gpu_view` proves geometry_va cannot succeed either, so + // `geometry = true` is exact and lets answer() serve both geometry=true/false queries until a + // SlotChange::source_added refilters this slot. + heap.records.set(slot, half, Records::waiting, base, span, 0, true); + if (cache) cache->put(base, span, FilterPageCache::Outcome::waiting); + h[0] = h[1] = h[2] = h[3] = 0; // null whole: no three words of four + ++heap.vsharps_rejected; + continue; + } + // Clear any stale record before deferring so finish_in_place's record-answer lookup never mistakes a + // placeholder for a resolved or settled waiting record. + heap.records.set(slot, half, Records::none, 0, 0, 0); + if (cache) cache->put(base, span, FilterPageCache::Outcome::defer); + h[0] = h[1] = h[2] = h[3] = 0; // null whole: no three words of four (a stride or format left over) + ++heap.vsharps_deferred; + defer = true; + } + } else { + leonida::gfx10::ImageWords words; + std::memcpy(words.data(), w, sizeof(words)); + leonida::gfx10::Image image{}; + const bool is_img = leonida::gfx10::is_image(words); + if (count_changed) ++heap.changed[is_img ? 2 : 3]; + if (is_img && leonida::gfx10::decode(words, image)) { + // As the title wrote it, bound by finish_in_place, which writes its bindless index into dword 6 + // (gfx10_descriptors.h, tsharp_index_word; the entry's index needs descriptor_mutex, not taken under + // the mirror's lock). Until then dword 6 is 0, the fallback: the title's own dword 6 (compression + // metadata) is never read as an index. The title's bytes keep it. + if (tsharp_index_words) w[leonida::gfx10::kTsharpIndexDword] = 0; + defer = true; + } else { + heap.records.clear(slot); + std::memset(w, 0, 16); // data where a V# or T# is read: null + } + } + std::memcpy(out, w, kDescriptorSize); + if (defer && !heap.deferred_mark[slot]) { + heap.deferred_mark[slot] = 1; + heap.deferred.push_back(std::uint32_t(slot)); + } + if (defer || added_mirror_range) heap.in_place_work_pending.store(true, std::memory_order_release); + } + + // The changes noted since the mirror last looked (and those refresh_console_heaps kept for it): the slots they + // touch are filtered again straight into their homes. page_mirror.mutex held (refresh_page_mirror). + void apply_in_place_changes(ConsoleHeap& heap) { + { + std::lock_guard taken(slot_change_mutex); + if (heap.changes_seen < slot_changes.size()) + heap.pending_changes.insert(heap.pending_changes.end(), + slot_changes.begin() + std::ptrdiff_t(heap.changes_seen), slot_changes.end()); + heap.changes_seen = slot_changes.size(); + } + if (heap.pending_changes.empty()) return; + if (bindless && bindless->total_free_images() == 0) { + // No free bindless slot in any dimension: waking room_[1] (texture_waiting_room) cannot succeed and would + // only re-refuse every waiting slot on this submission. + std::erase_if(heap.pending_changes, + [](const leonida::SlotChange& c) { return c.kind == leonida::SlotChange::texture_room; }); + if (heap.pending_changes.empty()) return; + } + const auto start = std::chrono::steady_clock::now(); + const std::uint64_t looked = heap.records.looked_at(); + heap.records.touched(heap.pending_changes.data(), heap.pending_changes.size(), heap.touched_scratch); + heap.record_changes += heap.pending_changes.size(); + heap.record_looked += heap.records.looked_at() - looked; + heap.record_refixed += heap.touched_scratch.size(); + heap.pending_changes.clear(); + if (!heap.touched_scratch.empty()) { + FilterCacheScope cache_scope(*this); + OutScratchGuard out_guard; + std::array written_slots{}; + std::size_t written_count = 0; + constexpr std::uint64_t kPageMask = ~(leonida::TitleMirror::kPage - 1); + constexpr std::uint64_t kOffMask = leonida::TitleMirror::kPage - 1; + std::uint64_t last_page = UINT64_MAX; + std::uint8_t* last_copy = nullptr; + std::uint8_t* last_frame = nullptr; + const bool readback = page_mirror.readback_in_flight; + const auto flush_page = [&] { + if (last_copy && written_count) { + flush_written_slot_runs(last_copy, out_guard.ptr, written_slots, written_count); + written_slots = {}; + written_count = 0; + } + }; + for (const std::uint32_t slot : heap.touched_scratch) { + const std::uint64_t va = heap.console_va + std::uint64_t(slot) * kDescriptorSize; + const std::uint64_t page_va = va & kPageMask; + if (page_va != last_page) { + flush_page(); + last_page = page_va; + last_copy = page_mirror.mirror->copy_bytes(page_va); + last_frame = (last_copy && readback) ? page_mirror.mirror->frame_at(page_va) : nullptr; + if (last_frame) note_readback_frame_invalidated_locked(last_frame); + } + if (last_copy) { + using Records = leonida::ConsoleHeapSlotRecords; + const auto st = heap.records.state(slot, 0); + if (st == Records::texture_waiting || st == Records::texture_waiting_room) { + std::uint32_t w[kDescriptorSize / 4]; + std::memcpy(w, heap.previous + std::size_t(slot) * kDescriptorSize, kDescriptorSize); + if ((w[0] | w[1] | w[2] | w[3]) && (w[3] >> 30)) { + leonida::gfx10::ImageWords words; + std::memcpy(words.data(), w, sizeof(words)); + leonida::gfx10::Image image{}; + if (leonida::gfx10::is_image(words) && leonida::gfx10::decode(words, image)) { + // Waiting T# already has filtered dword 6 == 0 in `last_copy`: enqueue directly for + // finish_in_place() without rewriting identical bytes to WC BAR VRAM. + if (!heap.deferred_mark[slot]) { + heap.deferred_mark[slot] = 1; + heap.deferred.push_back(slot); + } + heap.in_place_work_pending.store(true, std::memory_order_release); + continue; + } + } + } + const std::size_t at = std::size_t(va & kOffMask); + const std::size_t page_slot = at >> 5; + filter_slot_locked(heap, slot, out_guard.ptr + at, cache_scope.cache, false); + const std::uint64_t bit = std::uint64_t(1) << (page_slot & 63); + if (!(written_slots[page_slot >> 6] & bit)) { + written_slots[page_slot >> 6] |= bit; + ++written_count; + } + } + // A page not mapped is filtered whole when it is. + } + flush_page(); + } + heap.record_ms += std::chrono::duration(std::chrono::steady_clock::now() - start).count(); + } + + // TitleMirrorHooks::filter for the pages of console heaps read in place: the title's page at `from` (shown at + // `va`) in, the home `to` out. Each slot whose title bytes differ from what it was last filtered from (all of them + // on a fresh fill) is filtered (filter_slot_locked) into a cached host scratch buffer and bulk-flushed to WC BAR + // VRAM in contiguous runs; the others keep what the home holds. page_mirror.mutex held. + bool filter_heap_page(std::uint64_t va, std::uint8_t* to, const std::uint8_t* from, std::size_t bytes, bool fresh) { + ConsoleHeap* heap = nullptr; + for (ConsoleHeap* h : page_mirror.in_place) + if (va - h->console_va < h->bytes) heap = h; + if (!heap) return copy_guarded_host(to, from, bytes, false); + const auto start = std::chrono::steady_clock::now(); + std::unique_ptr overflow; + std::uint8_t* title = nullptr; + struct ScratchGuard { + bool* in_use = nullptr; + ~ScratchGuard() { + if (in_use) *in_use = false; + } + } scratch_guard; + if (!page_mirror.filter_scratch_in_use && bytes <= page_mirror.filter_scratch.size()) { + page_mirror.filter_scratch_in_use = true; + scratch_guard.in_use = &page_mirror.filter_scratch_in_use; + title = page_mirror.filter_scratch.data(); + } else { + overflow.reset(new std::uint8_t[bytes]); // a fill may come inside another + title = overflow.get(); + } + if (!copy_guarded_host(title, from, bytes, false)) return false; + FilterCacheScope cache_scope(*this); + std::size_t changed = 0; + const std::uint64_t heap_base_va = heap->console_va; + const std::uint64_t heap_bytes = heap->bytes; + std::uint8_t* const heap_prev = heap->previous; + const bool use_scratch_flush = bytes <= leonida::TitleMirror::kPage; + OutScratchGuard out_guard; + std::array written_slots{}; + std::size_t written_count = 0; + for (std::size_t at = 0; at + kDescriptorSize <= bytes; at += kDescriptorSize) { + const std::uint64_t slot_va = va + at; + const std::size_t page_slot = at >> 5; + if (slot_va - heap_base_va >= heap_bytes) { // past the heap's end on its last page: as it is + if (use_scratch_flush) { + std::memcpy(out_guard.ptr + at, title + at, kDescriptorSize); + written_slots[page_slot >> 6] |= std::uint64_t(1) << (page_slot & 63); + ++written_count; + } else { + std::memcpy(to + at, title + at, kDescriptorSize); + } + continue; + } + const std::size_t slot = std::size_t((slot_va - heap_base_va) / kDescriptorSize); + std::uint8_t* previous = heap_prev + slot * kDescriptorSize; + const bool same = slots_equal_32(previous, title + at); + if (same && !fresh) continue; + if (!same) { + std::memcpy(previous, title + at, kDescriptorSize); + ++changed; + } + if (use_scratch_flush) { + filter_slot_locked(*heap, slot, out_guard.ptr + at, cache_scope.cache, !same); + written_slots[page_slot >> 6] |= std::uint64_t(1) << (page_slot & 63); + ++written_count; + } else { + filter_slot_locked(*heap, slot, to + at, cache_scope.cache, !same); + } + } + if (use_scratch_flush && written_count) flush_written_slot_runs(to, out_guard.ptr, written_slots, written_count); + heap->slots_filtered += changed; + ++heap->pages_filtered; + heap->copied += changed * kDescriptorSize; + heap->filter_ms += std::chrono::duration(std::chrono::steady_clock::now() - start).count(); + return true; + } + + // Fast path for TitleMirrorHooks::filter_pieces: `scratch` already holds the title's 64 KiB page copied by + // TitleMirror::fill(), and `changed_pieces` (256 bits, one per 256-byte piece = 8 descriptor slots) marks the + // pieces that changed. Pass 1 reads `scratch` and snapshots changed slots into `heap->previous` BEFORE Pass 2 + // calls filter_slot_locked(), so a re-entrant TitleMirror::fill() triggered by page_mirror_resolve_locked() + // cannot overwrite `scratch` while we are still reading it. Filtered outputs go to a cached 64 KiB host scratch + // buffer and flush in coalesced runs to WC BAR VRAM `to`. page_mirror.mutex held. + bool filter_heap_page_pieces(std::uint64_t va, std::uint8_t* to, const std::uint8_t* scratch, std::size_t bytes, + bool fresh, const std::array& changed_pieces) { + if (bytes > leonida::TitleMirror::kPage) return filter_heap_page(va, to, scratch, bytes, fresh); + ConsoleHeap* heap = nullptr; + for (ConsoleHeap* h : page_mirror.in_place) + if (va - h->console_va < h->bytes) heap = h; + if (!heap) { + std::memcpy(to, scratch, bytes); + return true; + } + const auto start = std::chrono::steady_clock::now(); + constexpr std::size_t kPiece = 256; + // Pack offset (bits 0..14) + changed flag (bit 15): kPage = 65536 is 32-byte aligned, so `at >> 5` fits in 11 bits. + std::array to_filter; + std::size_t to_filter_count = 0; + std::size_t changed = 0; + const std::uint64_t heap_base_va = heap->console_va; + const std::uint64_t heap_bytes = heap->bytes; + std::uint8_t* const heap_prev = heap->previous; + OutScratchGuard out_guard; + std::array written_slots{}; + std::size_t written_count = 0; + for (std::size_t word = 0; word < 4; ++word) { + std::uint64_t mask = fresh ? ~std::uint64_t(0) : changed_pieces[word]; + while (mask) { + const unsigned bit = static_cast(std::countr_zero(mask)); + mask &= mask - 1; + const std::size_t piece_begin = (word * 64 + bit) * kPiece; + if (piece_begin >= bytes) break; + const std::size_t piece_end = (std::min)(piece_begin + kPiece, bytes); + for (std::size_t at = piece_begin; at + kDescriptorSize <= piece_end; at += kDescriptorSize) { + const std::uint64_t slot_va = va + at; + if (slot_va - heap_base_va >= heap_bytes) { // past the heap's end on its last page: as it is + const std::size_t page_slot = at >> 5; + std::memcpy(out_guard.ptr + at, scratch + at, kDescriptorSize); + written_slots[page_slot >> 6] |= std::uint64_t(1) << (page_slot & 63); + ++written_count; + continue; + } + const std::size_t slot = std::size_t((slot_va - heap_base_va) / kDescriptorSize); + std::uint8_t* previous = heap_prev + slot * kDescriptorSize; + const bool same = slots_equal_32(previous, scratch + at); + if (same && !fresh) continue; + if (!same) { + std::memcpy(previous, scratch + at, kDescriptorSize); + ++changed; + } + to_filter[to_filter_count++] = + static_cast((at >> 5) | (same ? 0u : 0x8000u)); + } + } + } + if (to_filter_count) { + FilterCacheScope cache_scope(*this); + for (std::size_t i = 0; i < to_filter_count; ++i) { + const std::uint16_t packed = to_filter[i]; + const std::size_t page_slot = std::size_t(packed & 0x7fffu); + const std::size_t at = page_slot << 5; + const bool slot_changed = (packed & 0x8000u) != 0; + const std::size_t slot = std::size_t((va + at - heap_base_va) / kDescriptorSize); + filter_slot_locked(*heap, slot, out_guard.ptr + at, cache_scope.cache, slot_changed); + written_slots[page_slot >> 6] |= std::uint64_t(1) << (page_slot & 63); + ++written_count; + } + } + if (written_count) flush_written_slot_runs(to, out_guard.ptr, written_slots, written_count); + heap->slots_filtered += changed; + ++heap->pages_filtered; + heap->copied += changed * kDescriptorSize; + heap->filter_ms += std::chrono::duration(std::chrono::steady_clock::now() - start).count(); + return true; + } + + // Batched filtered-heap refresh invoked once per TitleMirror::upload() under page_mirror.mutex: + // - Hoists one 1024-entry FilterPageCache across all pages in the batch (deduping V# lookups and mirror_ranges). + // - Phase A (parallel across TitleMirror::WorkerPool, 100% READ-ONLY on shared page_mirror, homes_, heap.records, + // heap.deferred, heap.mirror_ranges, and heap.seen_keys): diffs disjoint 64 KiB page slices of heap->previous, + // classifies null slots, T# decodes, inline arena V#s, and already-resolved read-only mirror V#s into cached + // host 64 KiB scratch buffers, and flushes pages with zero Phase B misses directly to WC BAR VRAM in parallel. + // - Phase B (sequential on calling thread under page_mirror.mutex): commits records/deferred/mirror_ranges, runs + // filter_slot_locked() for cache misses into the same host scratch buffer, and bulk-flushes changed slot runs. + void filter_heap_pages_batch_locked(leonida::TitleMirror::AliasedPageJob* jobs, std::size_t count, + leonida::TitleMirror::WorkerPool* pool, std::uint8_t* ok_out) { + if (!count) return; + FilterCacheScope cache_scope(*this); + constexpr std::size_t kPage = leonida::TitleMirror::kPage; + constexpr std::size_t kPiece = 256; + constexpr std::size_t kMaxBufferedPages = 64; + if (count == 1) { + ok_out[0] = filter_heap_page_pieces(jobs[0].va, jobs[0].to, jobs[0].scratch, kPage, jobs[0].fresh, + jobs[0].mask) + ? 1 + : 0; + return; + } + const auto batch_start = std::chrono::steady_clock::now(); + + struct ClearOp { + std::uint32_t slot = 0; + std::uint8_t halves = 0; // bit 0: half 0, bit 1: half 1 + }; + struct PageWork { + ConsoleHeap* heap = nullptr; + std::uint8_t* out_buf = nullptr; + bool persistent_buf = false; + bool flushed = false; + std::array written_slots{}; + std::size_t written_count = 0; + std::size_t changed = 0; + std::uint64_t changed_class[4] = {}; + std::uint64_t vsharp_halves = 0; + std::uint64_t vsharps_as_written = 0; + std::uint64_t vsharps_rejected = 0; + std::uint64_t resolved = 0; + std::vector clear_ops; + std::vector defer_slots; + std::vector> mirror_ranges; + std::vector phase_b_full; + void reset() noexcept { + heap = nullptr; + out_buf = nullptr; + persistent_buf = false; + flushed = false; + written_slots = {}; + written_count = 0; + changed = 0; + changed_class[0] = changed_class[1] = changed_class[2] = changed_class[3] = 0; + vsharp_halves = 0; + vsharps_as_written = 0; + vsharps_rejected = 0; + resolved = 0; + clear_ops.clear(); + defer_slots.clear(); + mirror_ranges.clear(); + phase_b_full.clear(); + } + }; + + // Pre-Phase A (sequential under page_mirror.mutex): reuse thread-local PageWork storage (keeping inner vector + // capacities warm across batches; falls back to stack vector on re-entry), resolve heaps and confirm disjoint + // page VAs. + thread_local std::vector tls_page_work; + thread_local bool tls_page_work_in_use = false; + std::vector fallback_page_work; + struct PageWorkGuard { + bool* in_use = nullptr; + ~PageWorkGuard() { + if (in_use) *in_use = false; + } + } work_guard; + std::vector* work_ptr = &fallback_page_work; + if (!tls_page_work_in_use) { + tls_page_work_in_use = true; + work_guard.in_use = &tls_page_work_in_use; + work_ptr = &tls_page_work; + } + std::vector& work = *work_ptr; + if (work.size() < count) work.resize(count); + for (std::size_t p = 0; p < count; ++p) work[p].reset(); + bool duplicate_va = false; + for (std::size_t p = 0; p < count; ++p) { + ConsoleHeap* heap = nullptr; + for (ConsoleHeap* h : page_mirror.in_place) + if (jobs[p].va - h->console_va < h->bytes) heap = h; + work[p].heap = heap; + for (std::size_t q = 0; q < p && !duplicate_va; ++q) + if (jobs[q].va == jobs[p].va) duplicate_va = true; + } + if (duplicate_va) { + for (std::size_t p = 0; p < count; ++p) { + ok_out[p] = filter_heap_page_pieces(jobs[p].va, jobs[p].to, jobs[p].scratch, kPage, jobs[p].fresh, + jobs[p].mask) + ? 1 + : 0; + } + return; + } + + // Reusable per-page host scratch buffers (up to kMaxBufferedPages = 4 MiB) so Phase A + Phase B merge into one + // coalesced WC BAR VRAM write burst per page. + thread_local std::vector tls_batch_bufs; + const std::size_t buffered_pages = (std::min)(count, kMaxBufferedPages); + if (tls_batch_bufs.size() < buffered_pages * kPage) tls_batch_bufs.resize(buffered_pages * kPage); + for (std::size_t p = 0; p < buffered_pages; ++p) { + work[p].out_buf = tls_batch_bufs.data() + p * kPage; + work[p].persistent_buf = true; + } + + const bool signed_vsharp = cache_scope.cache->signed_vsharp; + const bool has_mirror = cache_scope.cache->has_mirror; + const std::uint64_t arena_size = cache_scope.cache->arena_size; + const bool has_tsharp_index = tsharp_index_words; + + // Phase A (parallel when pool != nullptr, strictly read-only on all shared page_mirror / heap structures). + const auto run_phase_a = [&](std::size_t b, std::size_t e, std::size_t tid) { + using Records = leonida::ConsoleHeapSlotRecords; + struct LocalMirrorEntry { + std::uint64_t base = 0; + std::uint64_t span = 0; + std::uint32_t gen = 0; + }; + std::array local_mirror{}; + std::uint32_t local_gen = 0; + ConsoleHeap* prev_heap = nullptr; + + std::uint8_t* const worker_fallback_buf = pool ? pool->scratch(tid) : nullptr; + std::unique_ptr serial_fallback_buf; + + for (std::size_t p = b; p < e; ++p) { + const auto& job = jobs[p]; + PageWork& pw = work[p]; + ConsoleHeap* const heap = pw.heap; + if (!heap) { + std::memcpy(job.to, job.scratch, kPage); + pw.flushed = true; + continue; + } + std::uint8_t* out_buf = pw.out_buf; + if (!out_buf) { + if (worker_fallback_buf) { + out_buf = worker_fallback_buf; + } else { + if (!serial_fallback_buf) serial_fallback_buf.reset(new std::uint8_t[kPage]); + out_buf = serial_fallback_buf.get(); + } + } + // Persist `local_mirror` across consecutive pages of the same ConsoleHeap* so repeated mirror V#s + // avoid redundant page_mirror_is_resolved_readonly() walks and duplicate mirror_ranges pushes; reset + // immediately when ConsoleHeap* changes so each heap receives all of its own mirror_ranges. + if (heap != prev_heap) { + prev_heap = heap; + if (++local_gen == 0) { + local_mirror = {}; + local_gen = 1; + } + } + + const std::uint64_t heap_base_va = heap->console_va; + const std::uint64_t heap_bytes = heap->bytes; + std::uint8_t* const heap_prev = heap->previous; + const auto& records = heap->records; + + for (std::size_t word = 0; word < 4; ++word) { + std::uint64_t mask = job.fresh ? ~std::uint64_t(0) : job.mask[word]; + while (mask) { + const unsigned bit = static_cast(std::countr_zero(mask)); + mask &= mask - 1; + const std::size_t piece_begin = (word * 64 + bit) * kPiece; + const std::size_t piece_end = piece_begin + kPiece; + for (std::size_t at = piece_begin; at < piece_end; at += kDescriptorSize) { + const std::uint64_t slot_va = job.va + at; + const std::size_t page_slot = at >> 5; + if (slot_va - heap_base_va >= heap_bytes) { + std::memcpy(out_buf + at, job.scratch + at, kDescriptorSize); + pw.written_slots[page_slot >> 6] |= std::uint64_t(1) << (page_slot & 63); + ++pw.written_count; + continue; + } + const std::size_t slot = std::size_t((slot_va - heap_base_va) / kDescriptorSize); + std::uint8_t* const previous = heap_prev + slot * kDescriptorSize; + const bool same = slots_equal_32(previous, job.scratch + at); + if (same && !job.fresh) continue; + if (!same) { + std::memcpy(previous, job.scratch + at, kDescriptorSize); + ++pw.changed; + } + + std::uint32_t w[kDescriptorSize / 4]; + std::memcpy(w, job.scratch + at, kDescriptorSize); + if (!(w[0] | w[1] | w[2] | w[3])) { + if (!same) ++pw.changed_class[(w[4] | w[5] | w[6] | w[7]) ? 1 : 0]; + std::memcpy(out_buf + at, w, kDescriptorSize); + pw.written_slots[page_slot >> 6] |= std::uint64_t(1) << (page_slot & 63); + ++pw.written_count; + const std::uint8_t clr = + (records.state(slot, 0) != Records::none ? 1u : 0u) | + (records.state(slot, 1) != Records::none ? 2u : 0u); + if (clr) pw.clear_ops.push_back({std::uint32_t(slot), clr}); + } else if (!(w[3] >> 30)) { + // Pure read-only check for both V# halves; commit Phase A only if BOTH halves resolve. + const bool has_h0 = (w[2] != 0); + const bool has_h1 = (w[6] != 0); + bool half_ok[2] = {false, false}; + bool half_as_written[2] = {false, false}; + bool half_rejected[2] = {false, false}; + bool half_mirrored[2] = {false, false}; + bool half_resolved_new[2] = {false, false}; + std::uint64_t half_base[2] = {0, 0}; + std::uint64_t half_span[2] = {0, 0}; + std::uint8_t clr = 0; + + for (unsigned half = 0; half < 2; ++half) { + std::uint32_t* const h = w + 4 * half; + if ((h[3] >> 30) || !h[2]) { + half_ok[half] = true; + if (records.state(slot, half) != Records::none) + clr |= static_cast(1u << half); + continue; + } + const std::uint64_t base = + std::uint64_t(h[0]) | (std::uint64_t(h[1] & 0xffff) << 32); + const std::uint32_t stride = (h[1] >> 16) & 0x3fffu; + const std::uint64_t span = std::uint64_t(h[2]) * (stride ? stride : 1); + if (!base) { + h[0] = h[1] = h[2] = h[3] = 0; + half_ok[half] = true; + half_rejected[half] = true; + if (records.state(slot, half) != Records::none) + clr |= static_cast(1u << half); + continue; + } + if (!signed_vsharp || !(base & (1ull << 47))) { + if (base < arena_size && (span ? span : 1) <= arena_size - base) { + half_ok[half] = true; + half_as_written[half] = true; + if (records.state(slot, half) != Records::none) + clr |= static_cast(1u << half); + continue; + } + if (has_mirror) { + const std::size_t lb = + static_cast(((base >> 4) ^ (span * 0x9e3779b97f4a7c15ull)) & + 1023u); + LocalMirrorEntry& le = local_mirror[lb]; + if (le.gen == local_gen && le.base == base && le.span == span) { + half_ok[half] = true; + half_as_written[half] = true; + if (records.state(slot, half) != Records::none) + clr |= static_cast(1u << half); + continue; + } + if (page_mirror_is_resolved_readonly(base, span ? span : 1)) { + le = {base, span, local_gen}; + half_ok[half] = true; + half_as_written[half] = true; + half_mirrored[half] = true; + half_resolved_new[half] = true; + half_base[half] = base; + half_span[half] = span; + if (records.state(slot, half) != Records::none) + clr |= static_cast(1u << half); + continue; + } + } + } + break; // half missed Phase A -> defer entire slot to Phase B + } + + if (half_ok[0] && half_ok[1]) { + if (!same) { + ++pw.changed_class[1]; + if (has_h0) ++pw.vsharp_halves; + if (has_h1) ++pw.vsharp_halves; + } + for (unsigned half = 0; half < 2; ++half) { + if (half_as_written[half]) ++pw.vsharps_as_written; + if (half_rejected[half]) ++pw.vsharps_rejected; + if (half_resolved_new[half]) ++pw.resolved; + if (half_mirrored[half]) pw.mirror_ranges.emplace_back(half_base[half], half_span[half]); + } + if (clr) pw.clear_ops.push_back({std::uint32_t(slot), clr}); + std::memcpy(out_buf + at, w, kDescriptorSize); + pw.written_slots[page_slot >> 6] |= std::uint64_t(1) << (page_slot & 63); + ++pw.written_count; + } else { + pw.phase_b_full.push_back( + static_cast(page_slot | (same ? 0u : 0x8000u))); + } + } else { + leonida::gfx10::ImageWords words; + std::memcpy(words.data(), w, sizeof(words)); + leonida::gfx10::Image image{}; + const bool is_img = leonida::gfx10::is_image(words); + if (!same) ++pw.changed_class[is_img ? 2 : 3]; + if (is_img && leonida::gfx10::decode(words, image)) { + if (has_tsharp_index) w[leonida::gfx10::kTsharpIndexDword] = 0; + pw.defer_slots.push_back(std::uint32_t(slot)); + } else { + const std::uint8_t clr = + (records.state(slot, 0) != Records::none ? 1u : 0u) | + (records.state(slot, 1) != Records::none ? 2u : 0u); + if (clr) pw.clear_ops.push_back({std::uint32_t(slot), clr}); + std::memset(w, 0, 16); + } + std::memcpy(out_buf + at, w, kDescriptorSize); + pw.written_slots[page_slot >> 6] |= std::uint64_t(1) << (page_slot & 63); + ++pw.written_count; + } + } + } + } + + // Always flush Phase A's own written_slots to WC BAR VRAM in parallel (disjoint from phase_b_full) and + // reset them so Phase B flushes only the few remaining phase_b_full slots. + if (pw.written_count) { + flush_written_slot_runs(job.to, out_buf, pw.written_slots, pw.written_count); + pw.written_slots = {}; + pw.written_count = 0; + } + if (pw.phase_b_full.empty()) pw.flushed = true; + } + }; + + if (pool) { + const std::size_t workers = pool->worker_count(); + const std::size_t chunk = (std::max)(std::size_t(1), (std::min)(std::size_t(4), count / (workers * 2))); + pool->run(count, chunk, run_phase_a); + } else { + run_phase_a(0, count, 0); + } + + // Phase B (sequential on calling thread under page_mirror.mutex, in exact page order). + using Records = leonida::ConsoleHeapSlotRecords; + OutScratchGuard overflow_phase_b_guard; + for (std::size_t p = 0; p < count; ++p) { + const auto& job = jobs[p]; + PageWork& pw = work[p]; + ConsoleHeap* const heap = pw.heap; + if (!heap) { + ok_out[p] = 1; + continue; + } + heap->slots_filtered += pw.changed; + ++heap->pages_filtered; + heap->copied += pw.changed * kDescriptorSize; + heap->vsharps_as_written += pw.vsharps_as_written; + heap->vsharps_rejected += pw.vsharps_rejected; + heap->vsharp_halves += pw.vsharp_halves; + for (int c = 0; c < 4; ++c) heap->changed[c] += pw.changed_class[c]; + page_mirror.resolved += pw.resolved; + + bool work_pending = false; + for (const auto& [base, span] : pw.mirror_ranges) { + FilterPageCache::Entry* cached = cache_scope.cache->find(base, span); + if (cached && cached->outcome == FilterPageCache::Outcome::mirrored) { + if (cached->mirror_range_heap != heap) { + heap->mirror_ranges.emplace_back(base, span); + cached->mirror_range_heap = heap; + work_pending = true; + } + } else { + heap->mirror_ranges.emplace_back(base, span); + cache_scope.cache->put(base, span, FilterPageCache::Outcome::mirrored, 0, heap); + work_pending = true; + } + } + for (const ClearOp& op : pw.clear_ops) { + if (op.halves == 3u) { + heap->records.clear(op.slot); + } else { + if (op.halves & 1u) heap->records.set(op.slot, 0, Records::none, 0, 0, 0); + if (op.halves & 2u) heap->records.set(op.slot, 1, Records::none, 0, 0, 0); + } + } + for (const std::uint32_t slot : pw.defer_slots) { + if (!heap->deferred_mark[slot]) { + heap->deferred_mark[slot] = 1; + heap->deferred.push_back(slot); + } + work_pending = true; + } + if (work_pending) heap->in_place_work_pending.store(true, std::memory_order_release); + + if (!pw.phase_b_full.empty()) { + const std::uint64_t heap_base_va = heap->console_va; + std::uint8_t* const phase_b_buf = pw.persistent_buf ? pw.out_buf : overflow_phase_b_guard.ptr; + std::array phase_b_slots{}; + std::size_t phase_b_written = 0; + for (const std::uint16_t packed : pw.phase_b_full) { + const std::size_t page_slot = std::size_t(packed & 0x7fffu); + const std::size_t at = page_slot << 5; + const bool slot_changed = (packed & 0x8000u) != 0; + const std::size_t slot = std::size_t((job.va + at - heap_base_va) / kDescriptorSize); + filter_slot_locked(*heap, slot, phase_b_buf + at, cache_scope.cache, slot_changed); + phase_b_slots[page_slot >> 6] |= std::uint64_t(1) << (page_slot & 63); + ++phase_b_written; + } + if (phase_b_written) + flush_written_slot_runs(job.to, phase_b_buf, phase_b_slots, phase_b_written); + pw.flushed = true; + } + ok_out[p] = 1; + } + const double total_ms = + std::chrono::duration(std::chrono::steady_clock::now() - batch_start).count(); + ConsoleHeap* first_heap = nullptr; + for (std::size_t p = 0; p < count; ++p) { + if (work[p].heap) { + first_heap = work[p].heap; + break; + } + } + if (first_heap) first_heap->filter_ms += total_ms; + } + + // Reusable finish_in_place() scratch storage (guarded by console_heap_mutex). + struct InPlaceJob { + std::uint32_t slot = 0; + std::uint32_t words[kDescriptorSize / 4]{}; + bool reachable[2] = {false, false}; + std::uint64_t reachable_target[2] = {0, 0}; + bool answered[2] = {false, false}; + VsharpRecord answer[2]{}; + }; + struct InPlaceDone { + std::uint32_t out[kDescriptorSize / 4]{}; + VsharpRecord halves[2]{}; + leonida::ConsoleHeapSlotRecords::State texture = leonida::ConsoleHeapSlotRecords::none; + std::uint64_t texture_address = 0; + }; + struct InPlaceVsharpKey { + std::uint64_t base = 0, span = 0; + bool geometry = false; + bool operator==(const InPlaceVsharpKey&) const = default; + }; + struct InPlaceVsharpKeyHash { + std::size_t operator()(const InPlaceVsharpKey& k) const noexcept { + std::size_t h = std::hash{}(k.base); + h ^= std::hash{}(k.span) + 0x9e3779b97f4a7c15ull + (h << 6) + (h >> 2); + return h ^ std::size_t(k.geometry); + } + }; + struct InPlaceTsharpKeyHash { + std::size_t operator()(const leonida::gfx10::ImageWords& w) const noexcept { + std::uint64_t h = 14695981039346656037ull; + for (const std::uint32_t x : w) h = (h ^ x) * 1099511628211ull; + return static_cast(h); + } + }; + struct InPlaceTsharpCached { + TitleImage result = TitleImage::not_tsharp; + const char* why = nullptr; + std::uint64_t texture_address = 0; + std::uint32_t index_word = 0; + std::uint64_t capped_hits = 0; + }; + std::vector in_place_jobs_scratch; + std::vector in_place_done_scratch; + std::vector> in_place_ranges_scratch; + std::unordered_map in_place_vsharp_cache; + std::unordered_map in_place_tsharp_cache; + + // What the filter left to do, done outside the mirror's lock: the V#s the mirror does not hold resolved as a + // copied slot's were (an interim, until every title allocation is in the mirror; they read null meanwhile), the + // T#s bound, and the write-back noted for the mirror ranges the heap's V#s name. Each result goes into the home + // under the lock, unless the title rewrote the slot since (then the filter has it again). console_heap_mutex held, + // page_mirror.mutex not. + void finish_in_place(ConsoleHeap& heap) { + // O(1) lock-free skip when no filter work, mirror ranges, pending_changes, or new slot_changes exist: + // avoids contending on page_mirror.mutex while holding console_heap_mutex on clean submissions. + if (!heap.in_place_work_pending.load(std::memory_order_acquire) && + slot_change_count.load(std::memory_order_acquire) == 0) + return; + using Records = leonida::ConsoleHeapSlotRecords; + const VsharpPath path = (heap.scratch || heap.in_place) ? VsharpPath::scratch : VsharpPath::shadow; + const auto wants_geometry = [path](const std::uint32_t* h, std::uint64_t span) { + const leonida::gfx10::BufferWords words{h[0], h[1], h[2], h[3]}; + leonida::gfx10::Buffer desc{}; + return leonida::gfx10::decode(words, desc) && + (path != VsharpPath::scratch || span <= kTitleWindowMax || + (desc.format && leonida::gfx10::encode(desc) == words)); + }; + auto& jobs = in_place_jobs_scratch; + auto& ranges = in_place_ranges_scratch; + jobs.clear(); + ranges.clear(); + { + std::unique_lock lock(page_mirror.mutex, std::defer_lock); + leonida::submit_phases::lock_timed(lock); + // Apply any pending slot changes first under page_mirror.mutex so heap.records is current before + // consulting heap.records.answer() for repeated V# halves. + apply_in_place_changes(heap); + const std::uint64_t room_gen = geometry.free_generation(); + if (!heap.deferred.empty()) { + FilterCacheScope reach_scope(*this); + FilterPageCache& reach_cache = *reach_scope.cache; + jobs.reserve(heap.deferred.size()); + for (const std::uint32_t slot : heap.deferred) { + heap.deferred_mark[slot] = 0; + InPlaceJob& job = jobs.emplace_back(); + job.slot = slot; + std::memcpy(job.words, heap.previous + std::size_t(slot) * kDescriptorSize, kDescriptorSize); + if (!(job.words[3] >> 30)) { + // Batch-check reachability and existing slot records under the single mirror lock acquisition. + for (unsigned half = 0; half < 2; ++half) { + const std::uint32_t* h = job.words + 4 * half; + if ((h[3] >> 30) || !h[2]) continue; + const std::uint64_t base = std::uint64_t(h[0]) | (std::uint64_t(h[1] & 0xffff) << 32); + const std::uint32_t stride = (h[1] >> 16) & 0x3fffu; + const std::uint64_t span = std::uint64_t(h[2]) * (stride ? stride : 1); + if (const FilterPageCache::Entry* cached = reach_cache.find(base, span)) { + if (cached->outcome == FilterPageCache::Outcome::mirrored) { + job.reachable[half] = true; + job.reachable_target[half] = 0; + heap.mirror_ranges.emplace_back(base, span); + continue; + } + if (cached->outcome == FilterPageCache::Outcome::backed) { + job.reachable[half] = true; + job.reachable_target[half] = cached->target; + continue; + } + } else { + bool mirrored = false; + std::uint64_t reach_target = 0; + if (reachable_as_written(base, span, mirrored, &reach_target)) { + job.reachable[half] = true; + job.reachable_target[half] = reach_target; + if (mirrored) { + heap.mirror_ranges.emplace_back(base, span); + reach_cache.put(base, span, FilterPageCache::Outcome::mirrored); + } else { + reach_cache.put(base, span, FilterPageCache::Outcome::backed, reach_target); + } + continue; + } + reach_cache.put(base, span, FilterPageCache::Outcome::defer); + } + const bool copy_geometry = wants_geometry(h, span); + Records::State state{}; + std::uint64_t target = 0; + if (heap.records.answer(base, span, copy_geometry, state, target) && + !(state == Records::waiting_room && room_gen != geometry_room_seen)) { + job.answered[half] = true; + job.answer[half] = {state, base, span, target, copy_geometry}; + ++(state == Records::resolved ? heap.vsharps_answered_resolved : heap.vsharps_answered); + } + } + } + } + heap.deferred.clear(); + } + ranges.swap(heap.mirror_ranges); + heap.in_place_work_pending.store(false, std::memory_order_release); + } + if (ranges.size() > 1) { + // Deduplicate identical-base mirrored V# ranges (keeping the largest span per base) so repeated + // descriptors do not hammer title_va_aliases() and title_write_back_mutex; never merge across distinct + // bases because note_passive_title_write() clamps each call to the single title_memory region at `base`. + std::sort(ranges.begin(), ranges.end()); + std::size_t write = 0; + for (std::size_t i = 0; i < ranges.size(); ++i) { + if (write && ranges[write - 1].first == ranges[i].first) { + ranges[write - 1].second = (std::max)(ranges[write - 1].second, ranges[i].second); + } else { + if (write != i) ranges[write] = ranges[i]; + ++write; + } + } + ranges.resize(write); + } + if (!ranges.empty()) { + if (!writes_buffer_meta_complete.load(std::memory_order_acquire)) { + for (const auto& [base, span] : ranges) note_title_write(base, span); + } else if (title_write_back_enabled()) { + // Clamp each range against title_memory outside title_write_back_mutex, then batch all notes under one + // lock hold. + auto& aliases = leonida::title_va_aliases(); + std::size_t valid = 0; + for (const auto& [base, span] : ranges) { + if (!base || !span) continue; + std::uint64_t lo = 0, hi = 0; + if (!aliases.title_memory(base, lo, hi) || base >= hi) continue; + ranges[valid++] = {base, base + (std::min)(span, hi - base)}; + } + if (valid) { + std::lock_guard wb_lock(title_write_back_mutex); + for (std::size_t i = 0; i < valid; ++i) + passive_write_back.note(ranges[i].first, ranges[i].second); + has_passive_title_write_back.store(!passive_write_back.empty(), std::memory_order_release); + } + } + } + if (jobs.empty()) return; + const auto start = std::chrono::steady_clock::now(); + auto& batch_answers = in_place_vsharp_cache; + auto& tsharp_cache = in_place_tsharp_cache; + if (!batch_answers.empty()) batch_answers.clear(); + if (!tsharp_cache.empty()) tsharp_cache.clear(); + const auto apply_answer = [&](std::uint32_t* h, const VsharpRecord& rec, VsharpRecord& out_rec) { + out_rec = rec; + if (rec.state == Records::resolved) { + const std::uint64_t to = rec.target - arena.address; // mod 2^64, as recorded + if ((to & ((1ull << 48) - 1)) != rec.base) { + h[0] = std::uint32_t(to); + h[1] = (h[1] & 0xffff0000u) | std::uint32_t((to >> 32) & 0xffff); + ++heap.vsharps; + } else if (page_mirror.mirror && to == rec.base && rec.base >= arena.size) { + note_passive_title_write(rec.base, rec.span); + } + } else { + const std::uint32_t stride = (h[1] >> 16) & 0x3fffu; + note_unbacked_vsharp(rec.base, rec.span, stride, h); + h[0] = h[1] = h[2] = h[3] = 0; + ++heap.unbacked; + } + }; + auto& done = in_place_done_scratch; + done.assign(jobs.size(), InPlaceDone{}); + auto& refusal_tracker = unbound_tsharp_tracker(); + bool any_capped_hits = false; + for (std::size_t i = 0; i < jobs.size(); ++i) { + std::uint32_t* w = done[i].out; + std::memcpy(w, jobs[i].words, kDescriptorSize); + if (!(w[3] >> 30)) { + for (unsigned half = 0; half < 2; ++half) { + std::uint32_t* h = w + 4 * half; + if ((h[3] >> 30) || !h[2] || jobs[i].reachable[half]) continue; + if (jobs[i].answered[half]) { + apply_answer(h, jobs[i].answer[half], done[i].halves[half]); + continue; + } + const std::uint64_t base = std::uint64_t(h[0]) | (std::uint64_t(h[1] & 0xffff) << 32); + const std::uint32_t stride = (h[1] >> 16) & 0x3fffu; + const std::uint64_t span = std::uint64_t(h[2]) * (stride ? stride : 1); + const InPlaceVsharpKey key{base, span, wants_geometry(h, span)}; + if (const auto it = batch_answers.find(key); it != batch_answers.end()) { + ++(it->second.state == Records::resolved ? heap.vsharps_answered_resolved + : heap.vsharps_answered); + apply_answer(h, it->second, done[i].halves[half]); + continue; + } + const VsharpResult result = fix_vsharp(h, path, &done[i].halves[half], &heap, false); + if (done[i].halves[half].state != Records::none) batch_answers.emplace(key, done[i].halves[half]); + if (result == VsharpResult::rebased) ++heap.vsharps; + if (result == VsharpResult::empty) { + ++heap.unbacked; + h[3] = 0; // null whole in the filtered copy, never three words of four + } + } + } else { + leonida::gfx10::ImageWords words; + std::memcpy(words.data(), w, sizeof(words)); + if (const auto cached = tsharp_cache.find(words); cached != tsharp_cache.end()) { + InPlaceTsharpCached& entry = cached->second; + const bool unbound = entry.result == TitleImage::unknown || entry.result == TitleImage::refused; + if (unbound) { + if (refusal_tracker.is_capped()) { + ++entry.capped_hits; + any_capped_hits = true; + } else { + note_refused_tsharp(heap, std::size_t(jobs[i].slot) * kDescriptorSize, words, entry.why); + } + ++heap.refused_reasons[entry.why ? entry.why : "?"]; + ++heap.texture_waits; + } + ++heap.images[unsigned(entry.result)]; + if (entry.result == TitleImage::not_tsharp) { + std::memset(w, 0, 16); + } else { + done[i].texture_address = entry.texture_address; + done[i].texture = !unbound ? Records::texture_bound + : entry.why == kTsharpArrayFull || entry.why == kTsharpStorageFull + ? Records::texture_waiting_room + : Records::texture_waiting; + if (tsharp_index_words) w[leonida::gfx10::kTsharpIndexDword] = entry.index_word; + } + continue; + } + if (leonida::gfx10::is_image(words)) { + const char* why = nullptr; + std::uint32_t index_word = 0; + const TitleImage result = + bind_title_image(*this, words, &why, tsharp_index_words ? &index_word : nullptr); + const bool unbound = result == TitleImage::unknown || result == TitleImage::refused; + bool counted_capped = false; + if (unbound) { + if (refusal_tracker.is_capped()) { + counted_capped = true; + any_capped_hits = true; + } else { + note_refused_tsharp(heap, std::size_t(jobs[i].slot) * kDescriptorSize, words, why); + } + ++heap.refused_reasons[why ? why : "?"]; + ++heap.texture_waits; + } + ++heap.images[unsigned(result)]; + InPlaceTsharpCached entry{result, why, 0, 0, counted_capped ? 1ull : 0ull}; + if (result == TitleImage::not_tsharp) { + std::memset(w, 0, 16); + } else { + leonida::gfx10::Image image{}; + leonida::gfx10::decode(words, image); + entry.texture_address = tsharp_texture_key(image.address); + done[i].texture_address = entry.texture_address; + done[i].texture = !unbound ? Records::texture_bound + : why == kTsharpArrayFull || why == kTsharpStorageFull + ? Records::texture_waiting_room + : Records::texture_waiting; + // The home's dword 6 is the index shaders take (tsharp_index_word), 0 while the T# waits; a + // texture coming, going or replaced at its address touches the slot (apply_in_place_changes), + // which is filtered and finished again, so the word follows the texture the T# names. The heap + // copy's write (fix_console_slot) is for heaps not read in place. + if (tsharp_index_words) { + entry.index_word = unbound ? 0u : index_word; + w[leonida::gfx10::kTsharpIndexDword] = entry.index_word; + } + } + tsharp_cache.emplace(words, entry); + } else { + ++heap.images[unsigned(TitleImage::not_tsharp)]; + std::memset(w, 0, 16); + tsharp_cache.emplace(words, InPlaceTsharpCached{TitleImage::not_tsharp, nullptr, 0, 0, 0}); + } + } + } + if (any_capped_hits) { + for (const auto& kv : tsharp_cache) { + if (kv.second.capped_hits) refusal_tracker.note_capped(kv.second.why, kv.second.capped_hits); + } + } + std::unique_lock lock(page_mirror.mutex, std::defer_lock); + leonida::submit_phases::lock_timed(lock); + OutScratchGuard out_guard; + std::array written_slots{}; + std::size_t written_count = 0; + constexpr std::uint64_t kPageMask = ~(leonida::TitleMirror::kPage - 1); + constexpr std::uint64_t kOffMask = leonida::TitleMirror::kPage - 1; + std::uint64_t last_page = UINT64_MAX; + std::uint8_t* last_home = nullptr; + const bool has_mirror = page_mirror.mirror != nullptr; + const bool readback = page_mirror.readback_in_flight; + const auto flush_page = [&] { + if (last_home && written_count) { + flush_written_slot_runs(last_home, out_guard.ptr, written_slots, written_count); + written_slots = {}; + written_count = 0; + } + }; + for (std::size_t i = 0; i < jobs.size(); ++i) { + const std::uint32_t slot = jobs[i].slot; + if (!slots_equal_32(heap.previous + std::size_t(slot) * kDescriptorSize, + reinterpret_cast(jobs[i].words))) + continue; // rewritten since: filtered again, and deferred again if it needs this + const std::uint64_t va = heap.console_va + std::uint64_t(slot) * kDescriptorSize; + const std::uint64_t page_va = va & kPageMask; + if (page_va != last_page) { + flush_page(); + last_page = page_va; + last_home = has_mirror ? page_mirror.mirror->copy_bytes(page_va) : nullptr; + if (last_home && readback) { + if (std::uint8_t* frame = page_mirror.mirror->frame_at(page_va)) + note_readback_frame_invalidated_locked(frame); + } + } + if (!last_home) continue; + const InPlaceDone& d = done[i]; + if (d.texture != Records::none) { + if (Records::is_waiting(heap.records.state(slot, 0)) && heap.records.base(slot, 0) == d.texture_address && + d.texture == Records::texture_bound) + ++heap.texture_refills; + heap.records.set_texture(slot, d.texture, d.texture_address); + } else if (jobs[i].words[3] >> 30) { + heap.records.clear(slot); + } else { + for (unsigned half = 0; half < 2; ++half) { + const std::uint32_t* h = jobs[i].words + 4 * half; + if (jobs[i].reachable[half]) { + if (jobs[i].reachable_target[half]) { + const std::uint64_t base = std::uint64_t(h[0]) | (std::uint64_t(h[1] & 0xffff) << 32); + const std::uint32_t stride = (h[1] >> 16) & 0x3fffu; + const std::uint64_t span = std::uint64_t(h[2]) * (stride ? stride : 1); + heap.records.set(slot, half, Records::resolved, base, span, jobs[i].reachable_target[half], + false); + } else { + heap.records.set(slot, half, Records::none, 0, 0, 0); + } + } else if (d.halves[half].state != Records::none) { + heap.records.set(slot, half, d.halves[half].state, d.halves[half].base, d.halves[half].span, + d.halves[half].target, d.halves[half].geometry); + } else if ((h[3] >> 30) || !h[2]) { + heap.records.set(slot, half, Records::none, 0, 0, 0); + } + } } - if (fix_console_slot(heap, slot)) { - heap.retry[slot] = 0; - } else if (!heap.retry[slot]) { - heap.retry[slot] = 1; - heap.retries.push_back(std::uint32_t(slot)); + // filter_slot_locked / Phase A already wrote every deferred T# slot to the home with dword 6 = 0 (when + // tsharp_index_words) or raw words (otherwise). Skip the WC BAR write when d.out matches those bytes + // (e.g. repeated zero-index refusal or !tsharp_index_words). + if (d.texture != Records::none && + (!tsharp_index_words || d.out[leonida::gfx10::kTsharpIndexDword] == 0)) + continue; + const std::size_t at = std::size_t(va & kOffMask); + const std::size_t page_slot = at >> 5; + std::memcpy(out_guard.ptr + at, d.out, kDescriptorSize); + const std::uint64_t bit = std::uint64_t(1) << (page_slot & 63); + if (!(written_slots[page_slot >> 6] & bit)) { + written_slots[page_slot >> 6] |= bit; + ++written_count; } } + flush_page(); + heap.deferred_ms += std::chrono::duration(std::chrono::steady_clock::now() - start).count(); } - // The changes since the last submission (slot_changes), applied to a resource heap's copy: each slot whose record - // a change touches is fixed again - a V# whose backing, copy or alias range went, so the copy never names freed - // memory, and a waiting V# over which a backing, alias range or title memory was added. Only the slots near the - // changed ranges are looked at (ConsoleHeapSlotRecords::touched); nothing reads the copy. - std::vector slot_change_scratch; // console_heap_mutex - void apply_slot_changes(ConsoleHeap& heap, const std::vector& changes) { - if (!heap.resource_heap || changes.empty()) return; - const auto start = std::chrono::steady_clock::now(); - const std::uint64_t looked = heap.records.looked_at(); - heap.records.touched(changes.data(), changes.size(), slot_change_scratch); - heap.record_changes += changes.size(); - heap.record_looked += heap.records.looked_at() - looked; - heap.record_refixed += slot_change_scratch.size(); - for (const std::uint32_t slot : slot_change_scratch) - if (!fix_console_slot(heap, slot) && !heap.retry[slot]) { - heap.retry[slot] = 1; - heap.retries.push_back(slot); - } - heap.record_ms += std::chrono::duration(std::chrono::steady_clock::now() - start).count(); + // The changes noted since refresh_console_heaps took the list (a window this pass made, a buffer another thread + // released), applied to `heap` now: they stay in the list for the next submission too (applying one twice only + // fixes its slots twice). + std::vector slot_change_tail; // console_heap_mutex + void sync_slot_changes(ConsoleHeap& heap) { + if (slot_change_count.load(std::memory_order_acquire) == heap.changes_seen) return; + { + std::lock_guard lock(slot_change_mutex); + slot_change_tail.assign(slot_changes.begin() + std::ptrdiff_t(std::min(heap.changes_seen, slot_changes.size())), + slot_changes.end()); + heap.changes_seen = slot_changes.size(); + } + apply_slot_changes(heap, slot_change_tail); + } + // fix_vsharp's answer from a record of the same range in `heap`, current with every change noted so far. + bool answered_by_record(ConsoleHeap& heap, std::uint64_t base, std::uint64_t span, bool copy_geometry, + VsharpRecord& record) { + if (heap.in_place) return false; // in-place heaps answer under page_mirror.mutex in finish_in_place + sync_slot_changes(heap); + using Records = leonida::ConsoleHeapSlotRecords; + Records::State state{}; + std::uint64_t target = 0; + if (!heap.records.answer(base, span, copy_geometry, state, target)) return false; + // Room for geometry copies is seen once a refresh (refresh_console_heaps): freed since, resolve anew. + if (state == Records::waiting_room && geometry.free_generation() != geometry_room_seen) return false; + record = {state, base, span, target, copy_geometry}; + ++(state == Records::resolved ? heap.vsharps_answered_resolved : heap.vsharps_answered); + return true; } - // The slots of a heap copy not settled yet: fixed again, and kept while they are still not. Round robin, for at - // most LEONIDA_CONSOLE_RETRY_US a submission (500 by default, 0: all of them every time): during the story load - // thousands of T#s name textures that come much later, and trying them all at every submission cost hundreds of - // milliseconds each. One not reached waits a few submissions more for its texture. - void retry_console_slots(ConsoleHeap& heap) { - static const std::uint64_t budget_us = [] { - char text[16] = {}; - const DWORD n = GetEnvironmentVariableA("LEONIDA_CONSOLE_RETRY_US", text, sizeof(text)); - return n > 0 && n < sizeof(text) ? std::strtoull(text, nullptr, 10) : 500ull; - }(); - const auto start = std::chrono::steady_clock::now(); - std::size_t i = heap.retry_at, visited = 0; - const std::size_t total = heap.retries.size(); - while (visited < total && !heap.retries.empty()) { - if (i >= heap.retries.size()) i = 0; - const std::uint32_t slot = heap.retries[i]; - ++visited; - // Rewritten or zeroed since, or settled now: out of the list (the last one takes its place, seen later). - const bool settled = !heap.retry[slot] || fix_console_slot(heap, slot); - if (settled) { - heap.retry[slot] = 0; - heap.retries[i] = heap.retries.back(); - heap.retries.pop_back(); - } else { - ++i; - } - if (budget_us && !(visited & 31) && - std::chrono::steady_clock::now() - start >= std::chrono::microseconds(budget_us)) - break; + // A console heap's full resolution of a V# half (fix_vsharp): counted, timed, and for an answer of nothing, its + // class. + void note_resolution(ConsoleHeap& heap, std::chrono::steady_clock::time_point start, std::uint64_t base, + std::uint64_t to, std::uint64_t refused, bool copy_geometry, NoCopy no_copy) { + ++heap.resolutions; + heap.resolution_ms += std::chrono::duration(std::chrono::steady_clock::now() - start).count(); + if (to) return; + Nothing kind = nothing_other; + if (refused) kind = nothing_refused; + else if (base < arena.size) kind = nothing_arena; + else if (base & (1ull << 47)) kind = nothing_negative; + else if (!copy_geometry) kind = nothing_no_copy; + else + switch (no_copy) { + case NoCopy::not_title: kind = nothing_not_title; break; + case NoCopy::past_range: kind = nothing_past_range; break; + case NoCopy::known_buffer: kind = nothing_known_buffer; break; + case NoCopy::private_pages: kind = nothing_private; break; + case NoCopy::refused: kind = nothing_room; break; + case NoCopy::pool_alias: kind = nothing_pool_alias; break; + default: break; + } + ++heap.nothing[kind]; + if (kind == nothing_arena || kind == nothing_not_title) { + static const bool detail = [] { + const char* v = std::getenv("LEONIDA_VSHARP_NOTHING_DETAIL"); + return v && v[0] == '1'; + }(); + if (detail) ++heap.nothing_where[kind == nothing_not_title][nothing_where_kind(base)]; } - heap.retry_at = i; - heap.retried += visited; + } + // What the host has at `base` taken as an address: 0 image, 1 mapped, 2 private committed, 3 reserved, 4 free. + static unsigned nothing_where_kind(std::uint64_t base) { + MEMORY_BASIC_INFORMATION info{}; + if (!VirtualQuery(reinterpret_cast(static_cast(base)), &info, sizeof(info)) || + info.State == MEM_FREE) + return 4; + if (info.State != MEM_COMMIT) return 3; + return info.Type == MEM_IMAGE ? 0 : info.Type == MEM_MAPPED ? 1 : 2; } void note_refused_tsharp(ConsoleHeap& heap, std::size_t offset, const leonida::gfx10::ImageWords& words, @@ -5372,6 +9724,14 @@ struct DeviceState { void refresh_console_heap(ConsoleHeap& heap, const std::vector* changes) { // console_heap_mutex held if (heap.imported) return; // directly imported sampler heap if (heap.gpu >= 0) return refresh_console_heap_gpu(heap); + // Read in place: filtered as the page mirror fills its pages (refresh_page_mirror, before this); what the filter + // left (V#s the mirror does not hold, T#s to bind) is finished here, outside the mirror's lock. + if (heap.in_place) { + const auto start = std::chrono::steady_clock::now(); + finish_in_place(heap); + heap.fix_ms += std::chrono::duration(std::chrono::steady_clock::now() - start).count(); + return; + } using clock = std::chrono::steady_clock; const auto ms = [](clock::time_point a, clock::time_point b) { return std::chrono::duration(b - a).count(); @@ -5390,26 +9750,42 @@ struct DeviceState { heap.fix_start = t1; heap.fix_over = false; heap.fix_count = 0; - heap.answering = true; - heap.pages->for_each_copied([&](std::size_t offset, std::size_t bytes) { fix_console_slots(heap, offset, bytes); }); - heap.answers.clear(); // the changes below can release what an answer of the pass above named - // Even an unchanged title slot may name a buffer released since the last submission: the slots the changes - // touch are fixed again, found by their records. + // Even an unchanged title slot may name a buffer released since the last submission, or wait for a buffer or + // texture that came: the slots the changes touch are fixed again, found by their records. First, so the + // records the rewritten slots below are answered by are current (answered_by_record). if (changes) apply_slot_changes(heap, *changes); - heap.answering = false; - heap.answers.clear(); const auto t2 = clock::now(); - // T#s whose texture is not there yet, and slots the fix budget deferred. - if (!heap.retries.empty()) retry_console_slots(heap); + // Slots the fix budget deferred at an earlier submission (LEONIDA_CONSOLE_FIX_US; none without it). + if (!heap.retries.empty()) fix_deferred_slots(heap); const auto t3 = clock::now(); + heap.pages->for_each_copied([&](std::size_t offset, std::size_t bytes) { fix_console_slots(heap, offset, bytes); }); + const auto t4 = clock::now(); heap.pages_ms += ms(t0, t1); - heap.fix_ms += ms(t1, t2); heap.retry_ms += ms(t2, t3); + heap.fix_ms += ms(t1, t2) + ms(t3, t4); + if (ms(t0, t4) > heap.max_ms) { + heap.max_ms = ms(t0, t4); + heap.max_pages_ms = ms(t0, t1); + heap.max_changes_ms = ms(t1, t2); + heap.max_fix_ms = ms(t2, t4); + } } // Before every submission, ahead of the slot-133 shadows. + // The time a submission waited for console_heap_mutex (another queue's refresh holds it), since the last log line. + double heap_lock_wait_ms = 0, heap_lock_wait_max_ms = 0; // console_heap_mutex + std::uint64_t heap_lock_waits = 0; void refresh_console_heaps() { - std::lock_guard lock(console_heap_mutex); + const auto asked = std::chrono::steady_clock::now(); + std::unique_lock lock(console_heap_mutex, std::defer_lock); + leonida::submit_phases::lock_timed(lock); + { + const double waited = + std::chrono::duration(std::chrono::steady_clock::now() - asked).count(); + heap_lock_wait_ms += waited; + heap_lock_wait_max_ms = (std::max)(heap_lock_wait_max_ms, waited); + ++heap_lock_waits; + } const bool heap_pass = heap_gpu && console_heap_gpu_enabled(); if (heap_pass) console_heap_gpu_begin(); else if (heap_gpu) heap_gpu->drain(context->completed_retire_ticket(), [](int, std::uint32_t, std::uint32_t) {}, [](int) {}); @@ -5423,31 +9799,70 @@ struct DeviceState { // Every change since the last submission, for every heap; one made from now on (by another thread, or by a // fix below making a window) is applied at the next submission. std::vector changes; - { - std::lock_guard taken(slot_change_mutex); - changes.swap(slot_changes); + const bool have_slot_changes = slot_change_count.load(std::memory_order_acquire) != 0; + const std::uint64_t freed_gen = geometry.free_generation(); + if (have_slot_changes || freed_gen != geometry_room_seen) { + // A heap read in place reads the list in the mirror's refresh (apply_in_place_changes, under the mirror's + // lock): the list is taken under that lock too, so the entries it has not read yet are kept for it. + // Always swap slot_changes whenever entering this block so heap->changes_seen = 0 stays consistent with + // slot_changes and never skips a trailing geometry_room change. + std::unique_lock mirror(page_mirror.mutex, std::defer_lock); + if (in_place_heaps.load(std::memory_order_acquire)) leonida::submit_phases::lock_timed(mirror); + { + std::lock_guard taken(slot_change_mutex); + changes.swap(slot_changes); + slot_change_count.store(0, std::memory_order_release); + } + // Geometry copies freed since (GeometryViews::reap): the V# halves refused a copy for lack of room ask + // again. + if (freed_gen != geometry_room_seen) { + geometry_room_seen = freed_gen; + changes.push_back({leonida::SlotChange::geometry_room, 0, 1}); + } + bool pushed_in_place = false; + for (const auto& heap : console_heaps) { + if (heap->in_place && mirror.owns_lock()) { + const std::size_t from = (std::min)(heap->changes_seen, changes.size()); + if (from < changes.size()) { + heap->pending_changes.insert(heap->pending_changes.end(), + changes.begin() + std::ptrdiff_t(from), changes.end()); + heap->in_place_work_pending.store(true, std::memory_order_release); + pushed_in_place = true; + } + } + heap->changes_seen = 0; // of the list noted from now on + } + if (pushed_in_place) page_mirror.in_place_pending.store(true, std::memory_order_release); + if (mirror.owns_lock()) mirror.unlock(); } for (const auto& heap : console_heaps) { const auto start = std::chrono::steady_clock::now(); + const std::uint64_t copied_before = heap->copied, retried_before = heap->retried; refresh_console_heap(*heap, &changes); + // A heap slot or page brought up to date: this submission is not one of the "submit floor" line's. + if (heap->copied != copied_before || heap->retried != retried_before || !changes.empty()) + leonida::submit_phases::note_change(leonida::submit_phases::change_slots); heap->ms += std::chrono::duration(std::chrono::steady_clock::now() - start).count(); ++heap->refreshes; // A line at the first and 64th submission, then every 10 s (a crawl logs as often as a fast run). const bool logged = heap->refreshes == 1 || heap->refreshes == 64 || (heap->refreshes > 64 && start - heap->log_time >= std::chrono::seconds(10)); if (!logged) continue; + // A heap read in place has its filter's counters under the mirror's lock (console_heap_mutex, then it). + std::unique_lock in_place_counters(page_mirror.mutex, std::defer_lock); + if (heap->in_place) leonida::submit_phases::lock_timed(in_place_counters); const double count = double(std::max(1, heap->refreshes - heap->logged)); heap->logged = heap->refreshes; heap->log_time = start; std::fprintf(stderr, "[rt] d3d12: console descriptor heap 0x%llx (%s): submissions up to %llu %s %.1f KiB each " - "in %.3f ms on average (pages %.3f, fixing copied slots %.3f, %llu left to retries past the " - "budget, retrying %.3f: %.1f slots a " - "submission, %zu waiting), %llu write faults; %llu title V#s rebased, %llu with no copy given " - "no records (%zu V# halves waiting for a backing), %llu answered by an earlier slot of the pass, " - "T#s %llu known, %llu bound, %llu naming no texture, %llu refused, %llu words that are no " - "V# or T# (data, null in the copy)\n", - static_cast(heap->console_va), heap->imported ? "imported" : "copy", + "in %.3f ms on average (pages %.3f, fixing slots %.3f, %llu deferred past the budget, " + "deferred ones %.3f: %.1f slots a submission, %zu left), %llu write faults; %llu title V#s " + "rebased, %llu with no copy given no records (%zu V# halves waiting for a backing), T#s %llu " + "known, %llu bound, %llu naming no texture, %llu refused, %llu words that are no V# or T# " + "(data, null in the copy)\n", + static_cast(heap->console_va), + heap->in_place ? "in place" : heap->imported ? "imported" : "copy", static_cast(heap->refreshes), "copied", double(heap->copied) / 1024.0 / count, heap->ms / count, heap->pages_ms / count, heap->fix_ms / count, @@ -5456,7 +9871,6 @@ struct DeviceState { static_cast(heap->pages ? heap->pages->faults() : 0), static_cast(heap->vsharps), static_cast(heap->unbacked), heap->records.waiting_count(), - static_cast(heap->reused), static_cast(heap->images[unsigned(TitleImage::known)]), static_cast(heap->images[unsigned(TitleImage::bound)]), static_cast(heap->images[unsigned(TitleImage::unknown)]), @@ -5470,7 +9884,7 @@ struct DeviceState { "[rt] d3d12: console descriptor heap 0x%llx changed slots per submission: %.1f zero, %.1f " "V# pairs, %.1f T#s, %.1f other; V# halves %.1f, %.1f%% seen before; V# resolutions since " "the last line: alias %llu, alias refused %llu, arena %llu, geometry %llu, window %llu, " - "none %llu\n", + "none %llu, page mirror %llu\n", static_cast(heap->console_va), double(heap->changed[0]) / count, double(heap->changed[1]) / count, double(heap->changed[2]) / count, double(heap->changed[3]) / count, double(heap->vsharp_halves) / count, @@ -5478,29 +9892,101 @@ struct DeviceState { : 0.0, static_cast(paths[0]), static_cast(paths[1]), static_cast(paths[2]), static_cast(paths[3]), - static_cast(paths[4]), static_cast(paths[5])); + static_cast(paths[4]), static_cast(paths[5]), + static_cast(paths[6])); // What releases, alias changes and additions cost: per submission, the changes taken, the record // entries looked at to find their slots, and the slots fixed again (apply_slot_changes). + // T#s: those in the heap now, those of them waiting (for a texture at their address, or room), and + // since the last line the T# fixes that left one waiting and the waiting ones bound by a texture that + // came (refills). std::fprintf(stderr, "[rt] d3d12: console descriptor heap 0x%llx slot records per submission: %.1f changes, " - "%.1f slots looked at, %.1f fixed again, %.3f ms; %zu V# halves recorded\n", + "%.1f slots looked at, %.1f fixed again, %.3f ms; %zu V# halves recorded; T#s %zu " + "recorded, %zu waiting for a texture; since the last line %llu T# fixes left waiting, " + "%llu refills, %llu V# halves answered by a waiting one of their range\n", static_cast(heap->console_va), double(heap->record_changes) / count, double(heap->record_looked) / count, double(heap->record_refixed) / count, - heap->record_ms / count, heap->records.recorded()); + heap->record_ms / count, heap->records.recorded(), heap->records.textures(), + heap->records.textures_waiting(), static_cast(heap->texture_waits), + static_cast(heap->texture_refills), + static_cast(heap->vsharps_answered)); + // Where a submission's V# fixing goes: halves answered by a current record of their range (resolved + // or waiting) and halves resolved anew with their time; the classes of those that resolved to + // nothing; the longest refresh and its parts; the waits for the heap lock (in the heaps phase too). + std::string classes; + for (unsigned i = 0; i < nothing_classes; ++i) + if (heap->nothing[i]) + classes += (classes.empty() ? "" : ", ") + std::string(kNothingNames[i]) + " " + + std::to_string(heap->nothing[i]); + // Where the host has those bases (nothing_where_kind). + for (unsigned c = 0; c < 2; ++c) { + const std::uint64_t* w = heap->nothing_where[c]; + if (!(w[0] | w[1] | w[2] | w[3] | w[4])) continue; + char text[200]; + std::snprintf(text, sizeof(text), + " (%s bases as host addresses: image %llu, mapped %llu, private %llu, reserved " + "%llu, free %llu)", + c ? "not title memory" : "arena offset", static_cast(w[0]), + static_cast(w[1]), static_cast(w[2]), + static_cast(w[3]), static_cast(w[4])); + classes += text; + } + std::memset(heap->nothing_where, 0, sizeof(heap->nothing_where)); + std::fprintf(stderr, + "[rt] d3d12: console descriptor heap 0x%llx V# halves per submission: %.1f answered by a " + "resolved record of their range, %.1f by a waiting one, %.1f resolved anew (%.3f ms, %.2f " + "us each); resolved to nothing since the last line: %s; longest refresh %.3f ms (pages " + "%.3f, changes %.3f, slots %.3f); heap lock waited %.3f ms on average, %.3f the longest\n", + static_cast(heap->console_va), + double(heap->vsharps_answered_resolved) / count, double(heap->vsharps_answered) / count, + double(heap->resolutions) / count, heap->resolution_ms / count, + heap->resolutions ? 1000.0 * heap->resolution_ms / double(heap->resolutions) : 0.0, + classes.empty() ? "none" : classes.c_str(), heap->max_ms, heap->max_pages_ms, + heap->max_changes_ms, heap->max_fix_ms, + heap_lock_waits ? heap_lock_wait_ms / double(heap_lock_waits) : 0.0, + heap_lock_wait_max_ms); + heap_lock_wait_ms = heap_lock_wait_max_ms = 0; + heap_lock_waits = 0; + heap->vsharps_answered_resolved = heap->resolutions = 0; + heap->resolution_ms = 0; + for (auto& n : heap->nothing) n = 0; + heap->max_ms = heap->max_pages_ms = heap->max_changes_ms = heap->max_fix_ms = 0; for (auto& n : heap->changed) n = 0; + heap->texture_waits = heap->texture_refills = heap->vsharps_answered = 0; heap->vsharp_halves = heap->vsharp_repeats = 0; heap->record_changes = heap->record_looked = heap->record_refixed = 0; heap->record_ms = 0; } if (heap->gpu >= 0) log_console_heap_gpu(*heap, count); + if (heap->in_place) { + // What filtering its pages cost (filter_heap_page): pages and changed slots, per submission and per + // frame (presents since the last line), and the V# halves read as the title wrote them. + const std::uint64_t presents = phases_present_serial(); + const double frames = double(std::max(1, presents - heap->present_mark)); + std::fprintf(stderr, + "[rt] d3d12: console descriptor heap 0x%llx read in place: per submission %.1f pages " + "filtered, %.1f slots changed, %.3f ms, and %.3f ms finishing what the filter left; per " + "frame %.1f pages, %.3f ms (%llu frames); V# halves a submission: %.1f read as the title " + "wrote them, %.1f rejected in filter, %.1f resolved outside the mirror\n", + static_cast(heap->console_va), double(heap->pages_filtered) / count, + double(heap->slots_filtered) / count, heap->filter_ms / count, heap->deferred_ms / count, + double(heap->pages_filtered) / frames, (heap->filter_ms + heap->deferred_ms) / frames, + static_cast(presents - heap->present_mark), + double(heap->vsharps_as_written) / count, double(heap->vsharps_rejected) / count, + double(heap->vsharps_deferred) / count); + heap->present_mark = presents; + heap->pages_filtered = heap->slots_filtered = heap->vsharps_as_written = heap->vsharps_deferred = + heap->vsharps_rejected = 0; + heap->filter_ms = heap->deferred_ms = 0; + } std::string refused_breakdown; for (const auto& [reason, count] : heap->refused_reasons) - refused_breakdown += (refused_breakdown.empty() ? "" : "; ") + reason + " " + std::to_string(count); + refused_breakdown += (refused_breakdown.empty() ? "" : "; ") + std::string(reason) + " " + std::to_string(count); if (!refused_breakdown.empty()) std::fprintf(stderr, "[rt] d3d12: console descriptor heap 0x%llx unbound T#s by reason: %s\n", static_cast(heap->console_va), refused_breakdown.c_str()); heap->refused_reasons.clear(); - heap->copied = heap->vsharps = heap->unbacked = heap->retried = heap->reused = heap->deferred_fixes = 0; + heap->copied = heap->vsharps = heap->unbacked = heap->retried = heap->deferred_fixes = 0; for (auto& n : heap->images) n = 0; heap->ms = heap->pages_ms = heap->fix_ms = heap->retry_ms = 0; if (start - arena_log_time >= std::chrono::seconds(60)) { @@ -5592,10 +10078,96 @@ struct DeviceState { return true; } + // A console resource heap read in place (stage 2 of the CPU plan): when the page mirror holds every page of it, + // shaders read the title's heap through the mirror's homes, with no copy and no page tracker of the heap's own. + // 25,865 of the corpus's 26,503 shaders keep 32 bits of a descriptor-table pointer, so the pages are bound a second + // time into the arena below 4 GiB (TitleMirror::alias), at a range of whole blocks with no arena memory behind it; + // the guard after them is that range's rest, unbound, which reads zero. The homes are filled through the filter + // (filter_heap_page): the title's bytes in, the GPU's bytes out, never the other way. False (with `heap` given back) + // when the mirror does not hold the heap, or the arena has no room: it is copied as before. Never under + // console_heap_mutex (takes page_mirror.mutex). + std::atomic in_place_heaps{0}; + static std::uint64_t phases_present_serial() { + return leonida::submit_phases::totals().present_serial.load(std::memory_order_relaxed); + } + bool add_heap_in_place(std::unique_ptr&& heap, VkDeviceSize guard, std::uint64_t& shader_va) { + constexpr std::uint64_t page = leonida::TitleMirror::kPage; + const std::uint64_t console_va = heap->console_va, bytes = heap->bytes; + if (!page_mirror.mirror || (heap_gpu && console_heap_gpu_enabled()) || (console_va % page) || (bytes % page) || + !page_mirror_covers(console_va, bytes)) + return false; + VkDeviceSize offset = 0, reserved = 0; + if (!arena_reserve_unbacked(bytes + guard, offset, reserved)) return false; + auto owned = std::move(heap); + ConsoleHeap& h = *owned; + h.in_place = true; + h.imported = false; + h.shader_va = offset; + h.guard = reserved - bytes; + h.made.assign(std::size_t(bytes), 0); + h.previous = h.made.data(); + h.retry.assign(std::size_t(bytes / kDescriptorSize), 0); + h.deferred_mark.assign(std::size_t(bytes / kDescriptorSize), 0); + h.records.set_texture_live_callback(&DeviceState::on_console_texture_live, this); + h.records.reset(std::size_t(bytes / kDescriptorSize)); + h.present_mark = phases_present_serial(); + slot_records_live.store(true, std::memory_order_release); + shader_va = offset; + console_heap_ranges().add(console_va, bytes, offset); + arena_guard_bytes.fetch_add(h.guard, std::memory_order_relaxed); + { + std::lock_guard lock(console_heap_mutex); + { + std::unique_lock ranges(console_copy_ranges_mutex); // views keep the title's addresses there too + console_copy_ranges.emplace_back(console_va, bytes); + } + in_place_heaps.fetch_add(1, std::memory_order_release); + // Its pages keep the title's bytes at the title's address; at the table address in the arena each has a + // filtered copy of its own (TitleMirror::alias), bound with the mirror's next batch. + std::lock_guard mirror(page_mirror.mutex); + page_mirror.in_place.push_back(&h); + page_mirror.mirror->alias(console_va, console_va + bytes, arena.buffer, offset); + page_mirror_resolve_locked(console_va, bytes, true); + console_heaps.push_back(std::move(owned)); + console_heap_count.fetch_add(1, std::memory_order_release); + update_console_heap_signature_locked(); + } + std::fprintf(stderr, + "[rt] d3d12: console CBV/SRV/UAV descriptor heap 0x%llx (%llu KiB): read in place, its pages the " + "title's bytes in the page mirror and a filtered copy of each at heap_base + 0x%llx (the table " + "address), refilled as they change; %llu KiB of null slots after it with nothing bound\n", + static_cast(console_va), static_cast(bytes >> 10), + static_cast(offset), static_cast((reserved - bytes) >> 10)); + return true; + } + + // [out, out + reserved) of the arena, whole blocks, with no memory of the arena's behind it: for binds of other + // memory there (TitleMirror::alias). Its pages read zero where nothing is bound. False without room. + bool arena_reserve_unbacked(VkDeviceSize asked, VkDeviceSize& out, VkDeviceSize& reserved) { + if (!asked || !arena.backing.sparse()) return false; + const VkDeviceSize block = leonida::kArenaBlockBytes; + reserved = (asked + block - 1) & ~(block - 1); + if (reserved > arena.size) return false; + std::lock_guard lock(arena.mutex); + // Whole blocks no unit has (keep_out), so the arena never binds its own memory over them. + return arena.blocks.allocate( + reserved, block, + [this](std::uint64_t lo, std::uint64_t hi) { + const std::uint64_t title = leonida::title_va_aliases().title_overlap_end(lo, hi); + const std::uint64_t unit = arena.backing.keep_out(lo, hi); + return std::max(title, unit); + }, + out); + } + void arena_release_unbacked(VkDeviceSize offset, VkDeviceSize reserved) { + std::lock_guard lock(arena.mutex); + arena.blocks.release(offset, reserved); + } + // Gives the console heap at `console_va` a GPU view: `shader_va` is where shaders read it. False when there is // none (the heap then stays where only the CPU sees it, as without this). bool add_console_heap(std::uint64_t console_va, VkDeviceSize bytes, std::uint64_t& shader_va, bool resource_heap) { - if (!arena.mapped || !context || !bytes || console_va > UINTPTR_MAX - bytes) return false; + if (!arena_ready() || !context || !bytes || console_va > UINTPTR_MAX - bytes) return false; auto heap = std::make_unique(); heap->console_va = console_va; heap->bytes = bytes; @@ -5609,6 +10181,9 @@ struct DeviceState { const VkDeviceSize requested = resource_heap ? heap_guard_bytes() : 0; const VkDeviceSize guard = requested && bytes + requested <= (1ull << 32) ? ((bytes + requested + 65535) & ~VkDeviceSize(65535)) - bytes : 0; + // Read in place when the page mirror holds the heap's pages: no copy (add_heap_in_place). + if (resource_heap && add_heap_in_place(std::move(heap), guard, shader_va)) return true; + if (!heap) return false; // LEONIDA_CONSOLE_HEAP_ARENA=1 (with LEONIDA_CONSOLE_HEAP_GPU): the copy and its guard in the arena, which is // device-local where the device has it (ReBAR), not in an import of host memory: every draw's descriptor // fetch and the pass's writes stay on the card. The CPU never writes the copy then (the pass does); [input | @@ -5625,7 +10200,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 = arena_host(offset, size); heap->guard = guard; heap->imported = false; in_arena = true; @@ -5685,7 +10260,8 @@ 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; + heap->copy = arena_host(offset, bytes + heap->guard); + if (!heap->copy) return false; } std::memset(heap->copy, 0, std::size_t(bytes + heap->guard)); if (!heap->input) { @@ -5696,6 +10272,7 @@ struct DeviceState { } heap->retry.assign(std::size_t(bytes / kDescriptorSize), 0); if (resource_heap) { + heap->records.set_texture_live_callback(&DeviceState::on_console_texture_live, this); heap->records.reset(std::size_t(bytes / kDescriptorSize)); // Changes are kept from now on, before the first refresh writes a record. slot_records_live.store(true, std::memory_order_release); @@ -5708,8 +10285,16 @@ struct DeviceState { const bool imported = heap->imported; const VkDeviceSize guarded = heap->guard; arena_guard_bytes.fetch_add(guarded, std::memory_order_relaxed); - if (heap_gpu && console_heap_gpu_enabled() && heap->scratch && resource_heap && !imported) - attach_console_heap_gpu(*heap); + // The pass copies a T#'s words as the title wrote them; it does not write the index word the library's modules + // read (tsharp_index_words), so such a library's heaps are fixed on the CPU, which writes it. + if (heap_gpu && console_heap_gpu_enabled() && heap->scratch && resource_heap && !imported) { + if (!tsharp_index_words) + attach_console_heap_gpu(*heap); + else + log_once("LEONIDA_CONSOLE_HEAP_GPU: the pass does not write the T# index word the shaders read; console " + "descriptor heaps are fixed on the CPU; slots", + int(std::min(bytes / kDescriptorSize, INT_MAX))); + } { std::lock_guard lock(console_heap_mutex); if (heap->gpu >= 0) gpu_heaps[std::size_t(heap->gpu)] = heap.get(); @@ -5718,7 +10303,10 @@ struct DeviceState { std::unique_lock ranges(console_copy_ranges_mutex); console_copy_ranges.emplace_back(heap->console_va, heap->bytes); } + const bool is_resource_heap = heap->resource_heap; console_heaps.push_back(std::move(heap)); + if (is_resource_heap) console_heap_count.fetch_add(1, std::memory_order_release); + update_console_heap_signature_locked(); } std::fprintf(stderr, "[rt] d3d12: console %s descriptor heap 0x%llx (%llu KiB): shaders read it at heap_base + 0x%llx, " @@ -5753,6 +10341,8 @@ struct DeviceState { if (it == console_heaps.end()) return; heap = std::move(*it); console_heaps.erase(it); + if (heap->resource_heap) console_heap_count.fetch_sub(1, std::memory_order_acq_rel); + update_console_heap_signature_locked(); std::unique_lock ranges(console_copy_ranges_mutex); std::erase_if(console_copy_ranges, [console_va](const auto& r) { return r.first == console_va; }); if (heap->gpu >= 0) { @@ -5762,6 +10352,23 @@ struct DeviceState { } console_heap_ranges().remove(console_va); heap->pages.reset(); + if (heap->in_place) { + // Its pages leave the arena (unbound in the mirror's next batch, flushed here) and their filtered copies are + // freed; the arena range is free once what was submitted, which may read it, has retired. + in_place_heaps.fetch_sub(1, std::memory_order_acq_rel); + { + std::lock_guard lock(page_mirror.mutex); + std::erase(page_mirror.in_place, heap.get()); + if (page_mirror.mirror) + page_mirror.mirror->unalias(console_va); + } + refresh_page_mirror(); + flush_page_mirror(); + context->wait_retire_ticket(context->submitted_retire_ticket()); + arena_release_unbacked(heap->shader_va, heap->bytes + heap->guard); + arena_guard_bytes.fetch_sub(heap->guard, std::memory_order_relaxed); + return; + } if (heap->gpu >= 0) { // A pass recorded before remove_heap may still be on its way to the queue, and then reads `input` and // writes the copy: wait for it to be submitted, then for everything submitted. @@ -5951,9 +10558,9 @@ struct DeviceState { } // Where [to, to + n) is on the GPU: the arena, a title-window block outside it, or a shadow's own buffer. bool copy_destination(const std::uint8_t* to, std::size_t n, VkBuffer& buffer, VkDeviceSize& offset) { - if (arena.mapped && to >= arena.mapped && to + n <= arena.mapped + arena.size) { + if (std::uint64_t at = 0; arena.backing.offset_of(to, n, at)) { buffer = arena.buffer; - offset = VkDeviceSize(to - arena.mapped); + offset = at; return true; } if (external_windows.find_mapped(to, n, buffer, offset)) return true; @@ -6121,6 +10728,7 @@ struct DeviceState { batch.swap(r->requests); tsharps.swap(r->tsharps); } + const leonida::submit_phases::WorkerScope busy(leonida::submit_phases::worker_heap_resolver); for (const auto& w : tsharps) if (!r->registered.count(words_hash(w))) bind(w); // Those still waiting for a texture, again every 500 ms, at most 256 a round. @@ -6561,7 +11169,7 @@ struct DeviceState { // 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; + if (!context || !arena_ready() || arena.size < ag::kGuardEnd) return false; auto& vk = context->vk; guard.table = std::make_unique(); VkBufferCreateInfo create{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; @@ -6587,8 +11195,11 @@ struct DeviceState { 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)); + // Below arena.first: the arena's permanent head, always backed. + std::uint8_t* const guard_page = arena_host(ag::kGuardHeader, ag::kGuardEnd - ag::kGuardHeader); + if (!guard_page) return false; + auto* header = reinterpret_cast(guard_page); + std::memset(guard_page, 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); @@ -6615,14 +11226,30 @@ struct DeviceState { void update_address_guard() { namespace ag = leonida::address_guard; if (!guard.words) return; + const std::uint64_t generation = backing_generation.load(std::memory_order_acquire); + const std::uint64_t blocks = geometry.pool().layout_generation() + external_windows.layout_generation(); + std::uint64_t heap_signature = console_heap_signature.load(std::memory_order_acquire); + // Lock-free clean fast path: skip console_heap_mutex, heap_spans allocation, and guard.mutex when backings, + // blocks, console heaps, and refusal counter are unchanged. + if (generation == std::atomic_ref(guard.generation).load(std::memory_order_acquire) && + blocks == std::atomic_ref(guard.blocks).load(std::memory_order_acquire) && + heap_signature == std::atomic_ref(guard.heaps).load(std::memory_order_acquire)) { + auto* header = + reinterpret_cast(arena_host(ag::kGuardHeader, sizeof(ag::AddressGuardHeader))); + if (!header || std::atomic_ref(header->refused).load(std::memory_order_relaxed) == 0) 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; - { + const bool need_table_update = + generation != std::atomic_ref(guard.generation).load(std::memory_order_acquire) || + blocks != std::atomic_ref(guard.blocks).load(std::memory_order_acquire) || + heap_signature != std::atomic_ref(guard.heaps).load(std::memory_order_acquire); + if (need_table_update) { + heap_signature = 0xcbf29ce484222325ull; std::lock_guard heaps(console_heap_mutex); for (const auto& h : console_heaps) { if (!h || !h->bytes) continue; @@ -6633,12 +11260,10 @@ struct DeviceState { } } 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; + if (need_table_update && + (generation != std::atomic_ref(guard.generation).load(std::memory_order_relaxed) || + blocks != std::atomic_ref(guard.blocks).load(std::memory_order_relaxed) || + heap_signature != std::atomic_ref(guard.heaps).load(std::memory_order_relaxed))) { std::vector> spans = heap_spans; { std::lock_guard backing_lock(backing_mutex); @@ -6659,6 +11284,11 @@ struct DeviceState { std::atomic_ref(guard.words[i]).store(v, std::memory_order_relaxed); }); ++guard.updates; + // Publish updated generation/blocks/heaps with release semantics AFTER guard.words is updated so + // concurrent threads taking the lock-free fast path never observe stale page-table words. + std::atomic_ref(guard.generation).store(generation, std::memory_order_release); + std::atomic_ref(guard.blocks).store(blocks, std::memory_order_release); + std::atomic_ref(guard.heaps).store(heap_signature, std::memory_order_release); 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 " @@ -6666,7 +11296,8 @@ struct DeviceState { guard.overflow_logged, guard.table->blocks_used()); } } - auto* header = reinterpret_cast(arena.mapped + ag::kGuardHeader); + auto* header = reinterpret_cast(arena_host(ag::kGuardHeader, sizeof(ag::AddressGuardHeader))); + if (!header) return; 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)) { @@ -6709,6 +11340,7 @@ struct DeviceState { probed = true; int ok = 0; for (const std::uintptr_t va : pages) { + if (leonida::title_frames::backed(va)) continue; // a table page has no host view to import VkBuffer buffer = VK_NULL_HANDLE; VkDeviceMemory imported = VK_NULL_HANDLE; VkDeviceAddress address = 0; @@ -7166,7 +11798,7 @@ struct DeviceState { char what[96] = "no texture at that address"; { std::lock_guard lock(descriptor_mutex); - if (image_entries.count(words)) { + if (image_entries.count(words) || image_entries.count(g::tsharp_key(words))) { kind = 3; std::snprintf(what, sizeof(what), "key registered"); } else if (const auto it = images_by_address.find(image.address); it != images_by_address.end()) { @@ -7254,8 +11886,7 @@ struct DeviceState { std::uint64_t copy_differs = 0, copy_differs_unrebased = 0; // A copy lies in the arena; an import never does (its device address is outside the arena's). const std::uint8_t* copy = - p->shadowed && p->shader_va + p->slots * kDescriptorSize <= arena.size ? arena.mapped + p->shader_va - : nullptr; + p->shadowed ? arena.backing.host(p->shader_va, p->slots * kDescriptorSize) : nullptr; for (std::size_t i = 0; i < p->slots; ++i) { const auto* bytes = reinterpret_cast(static_cast(p->console_va + i * kDescriptorSize)); @@ -7368,6 +11999,8 @@ struct DeviceState { else if (!shader_library.load(dir, &error)) std::fprintf(stderr, "[rt] d3d12: %s\n", error.c_str()); else { + writes_buffer_meta_complete.store(shader_library.all_have_writes_buffer_meta(), + std::memory_order_release); const auto path = shader_library.directory().u8string(); // fspx counts library/ too (shader_library.h, load()). std::fprintf(stderr, "[rt] d3d12: %zu translated shaders (%zu fspx, %zu fspx_compute, " @@ -7707,6 +12340,10 @@ struct DeviceState { // True when the loaded library's modules read the table's kind word (create_bindless, descriptor_table.h): the // image inserts then record which arrays each index is bound in. bool descriptor_table_tagged = false; + // True when the loaded library's modules read a T#'s bindless index from its dword 6 (create_bindless, + // gfx10_descriptors.h tsharp_index_word): every T# the layer writes into a heap shaders read then carries it, in + // the console heaps' copies (fix_console_slot) and in its own heaps (write_image_descriptor, scan_title_table). + bool tsharp_index_words = false; std::mutex descriptor_mutex; // the set and the containers below // vkDeviceWaitIdle calls made for the bindless set (none, unless LEONIDA_BINDLESS_IDLE_WAIT restores the old wait). std::atomic bindless_idle_waits{0}; @@ -7714,14 +12351,135 @@ struct DeviceState { std::atomic bindless_cap_logged{false}; std::size_t bindless_logged_table_bytes = 0; // descriptor_mutex: the table size last logged bool bindless_host_logged = false; // descriptor_mutex - std::map image_entries; + struct DescriptorKeyHash { + std::size_t operator()(const leonida::DescriptorKey& k) const noexcept { + std::uint64_t h = 14695981039346656037ull; + for (const std::uint32_t x : k) h = (h ^ x) * 1099511628211ull; + return static_cast(h); + } + }; + // Deduplication key for Vulkan image views + bindless slots across distinct T# keys whose post-pending_image_keys + // Vulkan view state is identical (differing only in non-semantic T# metadata, CPU/GPU alias addresses, or shared + // zero_sampled_image for pending streams). + struct ViewKey { + VkImage vk_image = VK_NULL_HANDLE; + leonida::ImageDimension dimension = leonida::ImageDimension::dim_2d; + VkImageViewType view_type = VK_IMAGE_VIEW_TYPE_2D; + VkFormat view_format = VK_FORMAT_UNDEFINED; + VkFormat storage_format = VK_FORMAT_UNDEFINED; + std::uint32_t sampled_class = 0; + VkComponentSwizzle swizzle_r = VK_COMPONENT_SWIZZLE_IDENTITY; + VkComponentSwizzle swizzle_g = VK_COMPONENT_SWIZZLE_IDENTITY; + VkComponentSwizzle swizzle_b = VK_COMPONENT_SWIZZLE_IDENTITY; + VkComponentSwizzle swizzle_a = VK_COMPONENT_SWIZZLE_IDENTITY; + VkImageAspectFlags aspect_mask = 0; + std::uint32_t base_mip = 0; + std::uint32_t mip_count = 0; + std::uint32_t base_layer = 0; + std::uint32_t layer_count = 0; + std::uint32_t min_lod_bits = 0; + std::uint32_t slice_first = 0; + std::uint32_t slice_count = 0; + std::uint32_t mirror_layer = 0; + std::uint64_t api_owner_address = 0; // distinguishes D3D12 API views on shared deferred/placeholder images + bool sampled_only = false; + bool sampled = false; + bool storage = false; + bool has_min_lod = false; + bool operator==(const ViewKey&) const = default; + }; + struct ViewKeyHash { + std::size_t operator()(const ViewKey& k) const noexcept { + auto mix = [](std::uint64_t h, std::uint64_t v) noexcept { + h ^= v + 0x9e3779b97f4a7c15ull + (h << 6) + (h >> 2); + return h; + }; + std::uint64_t h = static_cast(std::hash{}(k.vk_image)); + h = mix(h, k.api_owner_address); + h = mix(h, (std::uint64_t(k.dimension) << 32) | std::uint64_t(k.view_type)); + h = mix(h, (std::uint64_t(k.view_format) << 32) | std::uint64_t(k.storage_format)); + h = mix(h, (std::uint64_t(k.sampled_class) << 32) | std::uint64_t(k.aspect_mask)); + h = mix(h, (std::uint64_t(k.swizzle_r) << 48) | (std::uint64_t(k.swizzle_g) << 32) | + (std::uint64_t(k.swizzle_b) << 16) | std::uint64_t(k.swizzle_a)); + h = mix(h, (std::uint64_t(k.base_mip) << 32) | std::uint64_t(k.mip_count)); + h = mix(h, (std::uint64_t(k.base_layer) << 32) | std::uint64_t(k.layer_count)); + h = mix(h, (std::uint64_t(k.min_lod_bits) << 32) | std::uint64_t(k.mirror_layer)); + h = mix(h, (std::uint64_t(k.slice_first) << 32) | std::uint64_t(k.slice_count)); + const std::uint64_t flags = (k.sampled_only ? 1ull : 0ull) | (k.sampled ? 2ull : 0ull) | + (k.storage ? 4ull : 0ull) | (k.has_min_lod ? 8ull : 0ull); + h = mix(h, flags); + return static_cast(h); + } + }; + struct SharedViewEntry { + ImageEntry entry{}; + std::uint32_t refcount = 0; + std::uint32_t api_refcount = 0; // pinned keys (API / known_heap / UAV / MS); never GC-evicted + std::uint64_t last_seen_gen = 0; + std::uint64_t last_touch_ticket = 0; // submitted_retire_ticket() + 1 when last created or hit + bool pinned_by_upgrade = false; // kept in replaced_images when refcount hits 0 until texture goes + std::uint64_t pinned_address = 0; + bool is_zero_view = false; // shared pending_image_keys->zero fallback view + std::vector keys; + }; + struct ImageKeyEntry : ImageEntry { + ViewKey view_key{}; + std::size_t sv_key_pos = 0; + bool from_title_heap = false; // true when evictable (bind_title_image or eligible !known_heap console view) + std::uint64_t last_seen_gen = 0; + }; + std::unordered_map image_entries; + std::unordered_map shared_views; + bool binding_from_title_heap = false; // descriptor_mutex: true while inside bind_title_image() + std::uint64_t tsharp_use_gen = 0; // descriptor_mutex: monotonic LRU touch counter + std::size_t title_heap_image_keys = 0; // descriptor_mutex: count of image_entries with from_title_heap == true + std::atomic console_heap_count{0}; // live console resource heaps (add/remove_console_heap) + // Pure leaf mutex tracking live kTexture kSettled addresses across console resource heaps (NEVER takes another lock). + std::mutex live_console_textures_mutex; + std::unordered_map live_console_textures; + static void on_console_texture_live(void* user, std::uint64_t addr, bool bound) { + auto* self = static_cast(user); + std::lock_guard lock(self->live_console_textures_mutex); + if (bound) { + ++self->live_console_textures[addr]; + } else { + const auto it = self->live_console_textures.find(addr); + if (it != self->live_console_textures.end()) { + if (it->second <= 1) self->live_console_textures.erase(it); + else --it->second; + } + } + } + // Declared after live_console_textures[_mutex] so ~DeviceState() detaches callbacks before destroying them, + // even if a ConsoleHeap remains in console_heaps (declared earlier in DeviceState). + struct LiveConsoleTexturesDetach { + DeviceState* owner = nullptr; + ~LiveConsoleTexturesDetach() { + if (!owner) return; + for (auto& h : owner->console_heaps) + if (h) h->records.set_texture_live_callback(nullptr, nullptr); + } + } live_console_textures_detach{this}; + std::array evictable_views_in_dim{}; // descriptor_mutex: SharedViewEntrys with is_evictable_sv + std::array gc_last_submit_ticket{}; // descriptor_mutex + std::array gc_last_attempt_ns{}; // descriptor_mutex + std::array gc_cooldown_ns{}; // descriptor_mutex + std::vector> gc_candidates_scratch; // descriptor_mutex + std::vector gc_winners_scratch; // descriptor_mutex + std::vector gc_touched_addrs_scratch; // descriptor_mutex + std::vector gc_live_addrs_scratch; // descriptor_mutex + std::uint64_t gc_runs = 0, gc_evicted_slots = 0, gc_evicted_keys = 0; // descriptor_mutex // A pending stream has a console descriptor immediately. Keep its keys (including aliases) // until the first complete upload. A shader hash miss selects the existing fallback image. // Once the smaller mips are filled (publish_streamed_texture), only the views that start above first_mip wait. + struct PendingImageKey { + leonida::gfx10::Image image{}; + bool evictable = false; + }; struct PendingImage { VkImage zero = VK_NULL_HANDLE; std::uint32_t first_mip = UINT32_MAX; - std::map keys; + std::map keys; }; std::unordered_map pending_image_keys; using ZeroShape = std::tuple; @@ -7731,7 +12489,11 @@ struct DeviceState { VkImage zero_sampled_image(const D3D12_RESOURCE_DESC&, const Format&, VkDeviceSize); std::multimap image_keys; // by the texture's address std::vector replaced_images; // kept until their texture goes: work in flight may still use them - std::map sampler_entries; + struct SamplerEntry { + VkSampler sampler = VK_NULL_HANDLE; + std::uint32_t index = 0; + }; + std::map sampler_entries; struct CustomBorderColor { bool is_int = false; VkClearColorValue value{}; @@ -7801,6 +12563,238 @@ struct DeviceState { context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image_view, entry.mirror_storage); } + static bool is_evictable_sv(const SharedViewEntry& sv) noexcept { + return sv.api_refcount == 0 && !sv.pinned_by_upgrade && !sv.is_zero_view; + } + void adjust_evictable_sv_locked(leonida::ImageDimension dim, bool was, bool now) noexcept { + if (was == now) return; + const std::uint32_t d = std::uint32_t(dim); + if (d >= evictable_views_in_dim.size()) return; + if (now) ++evictable_views_in_dim[d]; + else if (evictable_views_in_dim[d] > 0) --evictable_views_in_dim[d]; + } + + // Detaches one T# key from its refcounted SharedViewEntry (descriptor_mutex held). Releases the VkImageViews and + // bindless slot ONLY when refcount drops to 0; if the SharedViewEntry was replaced by a storage upgrade, moves it + // to replaced_images instead so already-recorded command lists keep valid descriptors until the texture goes. + void detach_view_key_locked(const ViewKey& vk_key, std::size_t key_pos, bool was_from_title_heap, bool upgrading, + std::uint64_t upgrade_address) { + const auto sv_it = shared_views.find(vk_key); + if (sv_it == shared_views.end()) return; + SharedViewEntry& sv = sv_it->second; + const bool was_evictable = is_evictable_sv(sv); + if (key_pos < sv.keys.size()) { + const leonida::DescriptorKey back_key = sv.keys.back(); + sv.keys[key_pos] = back_key; + sv.keys.pop_back(); + if (key_pos < sv.keys.size()) { + if (const auto moved = image_entries.find(back_key); moved != image_entries.end()) + moved->second.sv_key_pos = key_pos; + } + } + if (upgrading && !sv.pinned_by_upgrade) { + sv.pinned_by_upgrade = true; + sv.pinned_address = upgrade_address; + } + if (!was_from_title_heap && sv.api_refcount > 0) --sv.api_refcount; + if (sv.refcount > 0) --sv.refcount; + if (sv.refcount == 0) { + adjust_evictable_sv_locked(sv.entry.dimension, was_evictable, false); + if (sv.pinned_by_upgrade && images_by_address.count(sv.pinned_address)) { + ImageEntry kept = sv.entry; + kept.address = sv.pinned_address; + replaced_images.push_back(kept); + } else { + release(sv.entry); + } + shared_views.erase(sv_it); + } else { + adjust_evictable_sv_locked(sv.entry.dimension, was_evictable, is_evictable_sv(sv)); + } + } + + // Diagnostic breakdown of dim-2D live slots, shared ViewKeys, and evictable vs pinned keys (descriptor_mutex held). + std::string bindless_diag_summary_locked() const { + if (!bindless) return {}; + const std::uint32_t cap_2d = bindless->image_capacity(leonida::ImageDimension::dim_2d); + const std::uint32_t free_2d = bindless->free_images(leonida::ImageDimension::dim_2d); + const std::uint32_t live_2d = cap_2d > 1 + free_2d ? cap_2d - 1 - free_2d : 0; + const std::size_t api_keys = + image_entries.size() >= title_heap_image_keys ? image_entries.size() - title_heap_image_keys : 0; + return std::to_string(live_2d) + "/" + std::to_string(cap_2d > 0 ? cap_2d - 1 : 0) + " dim2D live, " + + std::to_string(shared_views.size()) + " ViewKeys (" + std::to_string(evictable_views_in_dim[0]) + + " dim2D evictable; " + std::to_string(title_heap_image_keys) + " evictable, " + + std::to_string(api_keys) + " pinned keys)"; + } + + // Two-phase zero-churn pressure-triggered bindless GC (descriptor_mutex held): + // Phase 1 (Dead-Key Sweep): evicts retired evictable SharedViewEntrys whose texture address is NOT live in any + // console heap's ConsoleHeapSlotRecords (emits ZERO SlotChange::texture_gone -> zero filter/shadows churn). + // Phase 2 (Emergency Live-LRU): ONLY when hard_full and Phase 1 found 0 (or heap_gpu active): evicts oldest + // retired evictable entries, emitting texture_gone so live console heap slots re-bind cleanly on demand. + void gc_bindless_title_views_locked(leonida::ImageDimension dimension, bool need_storage, + std::uint32_t sampled_class, const ViewKey* skip_view_key = nullptr) { + const std::uint32_t d = std::uint32_t(dimension); + if (!bindless || d >= evictable_views_in_dim.size() || evictable_views_in_dim[d] == 0) return; + const bool hard_full = !bindless->has_free_image(dimension, need_storage, sampled_class); + constexpr std::uint64_t kNormalCooldownNs = 250ull * 1000000ull; + constexpr std::uint64_t kBackoffCooldownNs = 1000ull * 1000000ull; + const std::uint64_t now_ns = static_cast( + std::chrono::duration_cast( + std::chrono::steady_clock::now().time_since_epoch()) + .count()); + if (!hard_full && gc_last_attempt_ns[d] != 0) { + const std::uint64_t cooldown = gc_cooldown_ns[d] ? gc_cooldown_ns[d] : kNormalCooldownNs; + if (now_ns >= gc_last_attempt_ns[d] && (now_ns - gc_last_attempt_ns[d]) < cooldown) return; + } + const std::uint64_t submitted = context ? context->submitted_retire_ticket() : 0; + const std::uint64_t wait_ticket = gc_last_submit_ticket[d]; + // NEVER bypass wait_ticket even on hard_full: slots on DeferredDeletionQueue cannot return before retirement. + if (wait_ticket != 0 && submitted < wait_ticket) return; + const std::uint64_t completed = context ? context->completed_retire_ticket() : 0; + if (wait_ticket != 0 && completed < wait_ticket) return; + + const std::uint32_t storage_cap = bindless->storage_capacity(dimension); + const bool use_live_tracking = !(heap_gpu && console_heap_gpu_enabled()); + bool phase2_live_lru = false; + gc_candidates_scratch.clear(); + if (use_live_tracking) { + // Snapshot live console-heap texture addresses under the pure leaf mutex (no nested locks). + gc_live_addrs_scratch.clear(); + { + std::lock_guard live_lock(live_console_textures_mutex); + gc_live_addrs_scratch.reserve(live_console_textures.size()); + for (const auto& [live_addr, cnt] : live_console_textures) + if (cnt > 0) gc_live_addrs_scratch.push_back(live_addr); + } + std::sort(gc_live_addrs_scratch.begin(), gc_live_addrs_scratch.end()); + const auto addr_is_live = [&](std::uint64_t addr) -> bool { + if (gc_live_addrs_scratch.empty()) return false; + if (std::binary_search(gc_live_addrs_scratch.begin(), gc_live_addrs_scratch.end(), addr)) return true; + if (const std::uint64_t key = tsharp_texture_key(addr); + key != addr && std::binary_search(gc_live_addrs_scratch.begin(), gc_live_addrs_scratch.end(), key)) + return true; + if (const std::uint64_t other = leonida::title_gpu_views::other_view(addr); + other && std::binary_search(gc_live_addrs_scratch.begin(), gc_live_addrs_scratch.end(), other)) + return true; + return false; + }; + const auto sv_is_live = [&](const SharedViewEntry& sv) -> bool { + if (gc_live_addrs_scratch.empty()) return false; + if (addr_is_live(sv.entry.address)) return true; + for (const auto& k : sv.keys) { + if (const auto e_it = image_entries.find(k); e_it != image_entries.end()) { + if (e_it->second.address != sv.entry.address && addr_is_live(e_it->second.address)) + return true; + } + } + return false; + }; + for (const auto& [vk_key, sv] : shared_views) { + if (sv.entry.dimension != dimension) continue; + if (!is_evictable_sv(sv)) continue; + if (sv.last_touch_ticket > completed) continue; + if (skip_view_key && vk_key == *skip_view_key) continue; + if (need_storage && sv.entry.index >= storage_cap) continue; + if (sv_is_live(sv)) continue; + gc_candidates_scratch.emplace_back(&vk_key, sv.last_seen_gen); + } + } + if (gc_candidates_scratch.empty() && hard_full) { + phase2_live_lru = true; + for (const auto& [vk_key, sv] : shared_views) { + if (sv.entry.dimension != dimension) continue; + if (!is_evictable_sv(sv)) continue; + if (sv.last_touch_ticket > completed) continue; + if (skip_view_key && vk_key == *skip_view_key) continue; + if (need_storage && sv.entry.index >= storage_cap) continue; + gc_candidates_scratch.emplace_back(&vk_key, sv.last_seen_gen); + } + } + // ALWAYS stamp ticket + wall-clock cooldown even when candidates is empty (prevents repeat scan storms). + gc_last_submit_ticket[d] = submitted + 1; + gc_last_attempt_ns[d] = now_ns; + if (gc_candidates_scratch.empty()) { + gc_cooldown_ns[d] = kBackoffCooldownNs; + return; + } + const std::size_t dim_cap = std::size_t(bindless->image_capacity(dimension)); + const std::size_t batch_cap = (std::min)(std::size_t(8192), (std::max)(std::size_t(64), dim_cap / 8)); + const std::size_t target = (std::min)(gc_candidates_scratch.size(), batch_cap); + if (target < gc_candidates_scratch.size()) { + std::nth_element( + gc_candidates_scratch.begin(), gc_candidates_scratch.begin() + std::ptrdiff_t(target), + gc_candidates_scratch.end(), + [](const auto& a, const auto& b) { return a.second < b.second; }); + } + gc_winners_scratch.clear(); + gc_winners_scratch.reserve(target); + for (std::size_t i = 0; i < target; ++i) gc_winners_scratch.push_back(*gc_candidates_scratch[i].first); + gc_candidates_scratch.clear(); + + if (phase2_live_lru) { + gc_touched_addrs_scratch.clear(); + gc_touched_addrs_scratch.reserve(target); + } + std::size_t evicted_slots = 0, evicted_keys = 0; + for (const ViewKey& win_key : gc_winners_scratch) { + const auto sv_it = shared_views.find(win_key); + if (sv_it == shared_views.end()) continue; + if (!is_evictable_sv(sv_it->second)) continue; + adjust_evictable_sv_locked(sv_it->second.entry.dimension, true, false); + const ImageEntry entry = sv_it->second.entry; + const std::vector keys = std::move(sv_it->second.keys); + shared_views.erase(sv_it); + for (const auto& k : keys) { + if (const auto e_it = image_entries.find(k); e_it != image_entries.end()) { + const std::uint64_t addr = e_it->second.address; + if (phase2_live_lru) gc_touched_addrs_scratch.push_back(addr); + const auto [first, last] = image_keys.equal_range(addr); + for (auto kit = first; kit != last; ++kit) { + if (kit->second == k) { + image_keys.erase(kit); + break; + } + } + if (e_it->second.from_title_heap && title_heap_image_keys > 0) --title_heap_image_keys; + image_entries.erase(e_it); + } + bindless->erase_key(k); + ++evicted_keys; + } + release(entry); + ++evicted_slots; + } + gc_cooldown_ns[d] = evicted_slots < 64 ? kBackoffCooldownNs : kNormalCooldownNs; + if (!evicted_slots) return; + ++gc_runs; + gc_evicted_slots += evicted_slots; + gc_evicted_keys += evicted_keys; + std::size_t notified_textures = 0; + if (phase2_live_lru && !gc_touched_addrs_scratch.empty()) { + std::sort(gc_touched_addrs_scratch.begin(), gc_touched_addrs_scratch.end()); + gc_touched_addrs_scratch.erase( + std::unique(gc_touched_addrs_scratch.begin(), gc_touched_addrs_scratch.end()), + gc_touched_addrs_scratch.end()); + notified_textures = gc_touched_addrs_scratch.size(); + for (const std::uint64_t addr : gc_touched_addrs_scratch) { + note_texture_change(leonida::SlotChange::texture_gone, addr); + if (const std::uint64_t key = tsharp_texture_key(addr); key != addr) + note_texture_change(leonida::SlotChange::texture_gone, key); + } + } + if ((gc_runs & (gc_runs - 1)) == 0) { + constexpr const char* names[] = {"2D", "2D array", "3D", "1D", "1D array", "2D MS", "2D MS array"}; + std::fprintf(stderr, + "[rt] d3d12: bindless GC #%llu [%s] dim %d (%s%s): evicted %zu slots (%zu keys, %zu " + "textures notified); %s, %u free in dim\n", + static_cast(gc_runs), phase2_live_lru ? "live-lru" : "dead-sweep", + int(dimension), names[int(dimension)], need_storage ? " storage" : "", evicted_slots, + evicted_keys, notified_textures, bindless_diag_summary_locked().c_str(), + bindless->free_images(dimension)); + } + } + struct PendingSample { Resource* owner = nullptr; leonida::gfx10::Image image{}; @@ -7811,6 +12805,7 @@ struct DeviceState { std::atomic pending_sample_count{}; bool materialize_sample(const leonida::DescriptorKey& key); bool materialize_table(std::uint64_t address,std::uint32_t slots); + void write_tsharp_index_words(const std::vector& keys); void remember_sample(const leonida::DescriptorKey& key, const PendingSample& sample) { std::lock_guard lock(pending_view_mutex); if (pending_samples.try_emplace(key,sample).second) { @@ -7835,22 +12830,27 @@ struct DeviceState { // alone otherwise (no view could be made for the T#). bool bind_image(const leonida::gfx10::ImageWords& words, const leonida::gfx10::Image& image, VkImage vk_image, VkFormat image_format, VkImageAspectFlags aspects, bool storage, - bool allow_channel_cast = false, VkFormat uint_backed = VK_FORMAT_UNDEFINED) { + bool allow_channel_cast = false, VkFormat uint_backed = VK_FORMAT_UNDEFINED, + bool evictable = false) { std::lock_guard lock(descriptor_mutex); return bind_image_locked(words, image, vk_image, image_format, aspects, storage, allow_channel_cast, - uint_backed); + uint_backed, nullptr, evictable); } bool bind_image_locked(const leonida::gfx10::ImageWords& words, const leonida::gfx10::Image& image, VkImage vk_image, VkFormat image_format, VkImageAspectFlags aspects, bool storage, bool allow_channel_cast = false, VkFormat uint_backed = VK_FORMAT_UNDEFINED, - const char** why = nullptr) { + const char** why = nullptr, bool evictable = false) { namespace g = leonida::gfx10; if (!bindless) return false; + const bool effective_evictable = evictable || binding_from_title_heap; + bool is_zero_view = false; auto pending = pending_image_keys.find(vk_image); if (pending != pending_image_keys.end() && image.first_mip < pending->second.first_mip) { - pending->second.keys.try_emplace(words, image); + auto [it, inserted] = pending->second.keys.try_emplace(words, PendingImageKey{image, effective_evictable}); + if (!inserted && !effective_evictable) it->second.evictable = false; if (!pending->second.zero) return true; vk_image = pending->second.zero; + is_zero_view = true; } const bool depth_or_stencil = (aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) != 0; // A T# of 8_UINT on a depth-stencil image is a view of its stencil plane (image_descriptor, D3D-75). Vulkan @@ -7888,34 +12888,67 @@ struct DeviceState { const bool sampled_only = uint_backed || (view_format != image_format && view_format != VK_FORMAT_UNDEFINED); return bind_image_views_locked(words, image, vk_image, view_format, channels_format, uint_backed ? image_format : view_format, aspects, true, storage, {}, - sampled_only, why); + sampled_only, why, effective_evictable, is_zero_view); } // The same for a view whose formats the caller has worked out: `view_format` of the sampled view (made when // `sampled`), `channels_format` whose channels the T#'s swizzle selects from, `storage_format` of the storage view. bool bind_image(const leonida::gfx10::ImageWords& words, const leonida::gfx10::Image& image, VkImage vk_image, VkFormat view_format, VkFormat channels_format, VkFormat storage_format, - VkImageAspectFlags aspects, bool sampled, bool storage, VolumeSlices slices) { + VkImageAspectFlags aspects, bool sampled, bool storage, VolumeSlices slices, + const void* evictable_owner = nullptr) { std::lock_guard lock(descriptor_mutex); + bool evictable = false; + if (evictable_owner) { + const auto it = images_by_address.find(image.address); + evictable = (it != images_by_address.end() && it->second == evictable_owner); + } return bind_image_views_locked(words, image, vk_image, view_format, channels_format, storage_format, aspects, - sampled, storage, slices, true); + sampled, storage, slices, true, nullptr, evictable, false); } bool bind_image_views_locked(const leonida::gfx10::ImageWords& words, const leonida::gfx10::Image& image, VkImage vk_image, VkFormat view_format, VkFormat channels_format, VkFormat storage_format, VkImageAspectFlags aspects, bool sampled, bool storage, - VolumeSlices slices, bool sampled_only, const char** why = nullptr) { + VolumeSlices slices, bool sampled_only, const char** why = nullptr, + bool evictable = false, bool is_zero_view = false) { namespace g = leonida::gfx10; if (!bindless) { if (storage) log_once("unordered-access view needs the Vulkan bindless set; type", int(image.type)); return false; } - if (const auto pending = pending_image_keys.find(vk_image); - pending != pending_image_keys.end() && image.first_mip < pending->second.first_mip) { - pending->second.keys.try_emplace(words, image); - if (!pending->second.zero) return true; - vk_image = pending->second.zero; + const bool effective_evictable = evictable || binding_from_title_heap; + if (!is_zero_view) { + if (const auto pending = pending_image_keys.find(vk_image); + pending != pending_image_keys.end() && image.first_mip < pending->second.first_mip) { + auto [it, inserted] = + pending->second.keys.try_emplace(words, PendingImageKey{image, effective_evictable}); + if (!inserted && !effective_evictable) it->second.evictable = false; + if (!pending->second.zero) return true; + vk_image = pending->second.zero; + is_zero_view = true; + } } const auto existing = image_entries.find(words); - if (existing != image_entries.end() && (existing->second.storage || !storage)) return true; + if (existing != image_entries.end() && (existing->second.storage || !storage)) { + const std::uint64_t gen = ++tsharp_use_gen; + existing->second.last_seen_gen = gen; + const auto sv_it = shared_views.find(existing->second.view_key); + if (sv_it != shared_views.end()) { + const bool was_evictable = is_evictable_sv(sv_it->second); + if (!effective_evictable && existing->second.from_title_heap) { + existing->second.from_title_heap = false; + if (title_heap_image_keys > 0) --title_heap_image_keys; + ++sv_it->second.api_refcount; + } + adjust_evictable_sv_locked(sv_it->second.entry.dimension, was_evictable, + is_evictable_sv(sv_it->second)); + sv_it->second.last_seen_gen = gen; + sv_it->second.last_touch_ticket = context ? context->submitted_retire_ticket() + 1 : 0; + } else if (!effective_evictable && existing->second.from_title_heap) { + existing->second.from_title_heap = false; + if (title_heap_image_keys > 0) --title_heap_image_keys; + } + return true; + } leonida::ImageDimension dimension; switch (image.type) { @@ -7960,6 +12993,8 @@ struct DeviceState { view_info.format = view_format; auto swizzle = image.swizzle; VkImageViewMinLodCreateInfoEXT clamp{VK_STRUCTURE_TYPE_IMAGE_VIEW_MIN_LOD_CREATE_INFO_EXT}; + bool has_min_lod = false; + std::uint32_t min_lod_bits = 0; const bool supports_lod_clamp = image.type == g::ImageType::image_1d || image.type == g::ImageType::image_2d || image.type == g::ImageType::image_2d_array || image.type == g::ImageType::cube || image.type == g::ImageType::image_3d; @@ -7977,6 +13012,8 @@ struct DeviceState { } clamp.pNext = view_info.pNext; view_info.pNext = &clamp; + has_min_lod = true; + min_lod_bits = std::bit_cast(clamp.minLod); } } view_info.components = g::vulkan_swizzle(swizzle, channels_format); @@ -7984,6 +13021,143 @@ struct DeviceState { image, stencil ? VK_IMAGE_ASPECT_STENCIL_BIT : (aspects & VK_IMAGE_ASPECT_DEPTH_BIT) ? VK_IMAGE_ASPECT_DEPTH_BIT : VK_IMAGE_ASPECT_COLOR_BIT); + + // Deduplicate identical Vulkan views across distinct T# keys via refcounted ViewKey sharing. + ViewKey vk_key{}; + vk_key.vk_image = vk_image; + vk_key.dimension = dimension; + vk_key.view_type = view_info.viewType; + vk_key.view_format = view_info.format; + vk_key.storage_format = storage ? storage_format : VK_FORMAT_UNDEFINED; + vk_key.sampled_class = sampled_class; + vk_key.swizzle_r = view_info.components.r; + vk_key.swizzle_g = view_info.components.g; + vk_key.swizzle_b = view_info.components.b; + vk_key.swizzle_a = view_info.components.a; + vk_key.aspect_mask = view_info.subresourceRange.aspectMask; + vk_key.base_mip = view_info.subresourceRange.baseMipLevel; + vk_key.mip_count = view_info.subresourceRange.levelCount; + vk_key.base_layer = view_info.subresourceRange.baseArrayLayer; + vk_key.layer_count = view_info.subresourceRange.layerCount; + vk_key.min_lod_bits = min_lod_bits; + vk_key.slice_first = storage ? slices.first : 0u; + vk_key.slice_count = storage ? slices.count : 0u; + vk_key.mirror_layer = dimension == leonida::ImageDimension::dim_2d_array ? image.first_layer : 0u; + vk_key.api_owner_address = + (is_zero_view && console_heap_count.load(std::memory_order_acquire) == 0) ? image.address : 0u; + vk_key.sampled_only = sampled_only; + vk_key.sampled = sampled; + vk_key.storage = storage; + vk_key.has_min_lod = has_min_lod; + + const auto commit_key_to_shared = [&](SharedViewEntry& sv, bool is_new) { + const bool was_evictable = !is_new && is_evictable_sv(sv); + const std::uint64_t gen = ++tsharp_use_gen; + sv.last_seen_gen = gen; + sv.last_touch_ticket = context ? context->submitted_retire_ticket() + 1 : 0; + if (existing != image_entries.end()) { + const bool old_from_title = existing->second.from_title_heap; + const bool new_from_title = effective_evictable ? old_from_title : false; + const ViewKey old_vk_key = existing->second.view_key; + const std::size_t old_pos = existing->second.sv_key_pos; + const std::uint64_t old_addr = existing->second.address; + if (old_from_title && !new_from_title && title_heap_image_keys > 0) --title_heap_image_keys; + ++sv.refcount; + if (!new_from_title) ++sv.api_refcount; + adjust_evictable_sv_locked(sv.entry.dimension, was_evictable, is_evictable_sv(sv)); + const std::size_t new_pos = sv.keys.size(); + sv.keys.push_back(words); + static_cast(existing->second) = sv.entry; + existing->second.address = old_addr; + existing->second.view_key = vk_key; + existing->second.sv_key_pos = new_pos; + existing->second.from_title_heap = new_from_title; + existing->second.last_seen_gen = gen; + detach_view_key_locked(old_vk_key, old_pos, old_from_title, /*upgrading=*/true, old_addr); + // The console heap slots holding these words carry the read-only entry's index in their dword 6 + // (tsharp_index_words): fixed again at the next submission (a texture_gone change re-fixes bound T#s, + // under the address their records keep, tsharp_texture_key), they take this one, with its storage views. + if (tsharp_index_words) + note_texture_change(leonida::SlotChange::texture_gone, tsharp_texture_key(image.address)); + } else { + const bool from_title = effective_evictable; + if (from_title) ++title_heap_image_keys; + ++sv.refcount; + if (!from_title) ++sv.api_refcount; + adjust_evictable_sv_locked(sv.entry.dimension, was_evictable, is_evictable_sv(sv)); + const std::size_t new_pos = sv.keys.size(); + sv.keys.push_back(words); + ImageKeyEntry key_entry{}; + static_cast(key_entry) = sv.entry; + key_entry.address = image.address; + key_entry.view_key = vk_key; + key_entry.sv_key_pos = new_pos; + key_entry.from_title_heap = from_title; + key_entry.last_seen_gen = gen; + image_entries.emplace(words, std::move(key_entry)); + image_keys.emplace(image.address, words); + } + // The set derives the entry's kind from what it bound at this index (BindlessSet::image_kind_at); a plain + // library's modules do not read it, so they get 0 as before. + bindless->insert_key(words, sv.entry.index, + descriptor_table_tagged ? bindless->image_kind_at(dimension, sv.entry.index) : 0u); + leonida::fsdraw::note_tsharp(words.data()); // LOCAL DIAGNOSTIC + }; + + if (const auto sv_it = shared_views.find(vk_key); sv_it != shared_views.end()) { + commit_key_to_shared(sv_it->second, /*is_new=*/false); + return true; + } + + // Need a new bindless slot. Trigger safe pressure GC of stale evictable entries before checking room. + const std::uint32_t dim_cap = bindless->image_capacity(dimension); + const std::uint32_t gc_threshold = (std::min)(std::uint32_t(4096), dim_cap / 8); + if (!bindless->has_free_image(dimension, storage, sampled_class) || + bindless->free_images(dimension) < gc_threshold) { + const ViewKey* skip_vk = existing != image_entries.end() ? &existing->second.view_key : nullptr; + gc_bindless_title_views_locked(dimension, storage, sampled_class, skip_vk); + } + + const auto report_bindless_refusal = [&](bool needed_storage) { + using Refusal = leonida::BindlessSet::ImageRefusal; + const Refusal refusal = bindless->image_refusal(dimension, needed_storage, sampled_class); + if (why) + *why = refusal == Refusal::no_array ? "set 0 has no array for the T#'s dimension" + : refusal == Refusal::storage_full ? kTsharpStorageFull + : kTsharpArrayFull; + if (refusal != Refusal::no_array && + first_diagnostic("a bindless image array is full; dimension", int(dimension))) { + std::size_t entries = 0, replaced = 0, most = 0, registered = 0, dim_view_keys = 0; + std::map per_texture; + for (const auto& kv : image_entries) + if (kv.second.dimension == dimension) { + ++entries; + most = (std::max)(most, ++per_texture[kv.second.address]); + } + for (const auto& kv : shared_views) + if (kv.second.entry.dimension == dimension) ++dim_view_keys; + for (const auto& texture : per_texture) registered += images_by_address.count(texture.first); + for (const auto& held : replaced_images) replaced += held.dimension == dimension; + constexpr const char* names[] = {"2D", "2D array", "3D", "1D", "1D array", "2D MS", "2D MS array"}; + std::fprintf(stderr, + "[rt] d3d12: a bindless image array is full; dimension %d (%s)%s: %u indices, %u in the " + "storage arrays, %zu T#s (%zu shared ViewKeys) of %zu textures (%zu registered at their " + "address, at most %zu T#s of one), %zu replaced views kept [%s]; further T#s of this " + "dimension read the fallback\n", + int(dimension), names[int(dimension)], + refusal == Refusal::storage_full ? ", its storage range" : "", + bindless->image_capacity(dimension), bindless->storage_capacity(dimension), entries, + dim_view_keys, per_texture.size(), registered, most, replaced, + bindless_diag_summary_locked().c_str()); + } + }; + + // Pre-check bindless room BEFORE vkCreateImageView so zero driver views are created/destroyed when full. + if (!bindless->has_free_image(dimension, storage, sampled_class)) { + report_bindless_refusal(storage); + return false; + } + ImageEntry entry{dimension, 0, VK_NULL_HANDLE, VK_NULL_HANDLE, image.address}; if (sampled) { const VkResult result = vk.vkCreateImageView(info.device, &view_info, nullptr, &entry.sampled); @@ -8052,63 +13226,42 @@ struct DeviceState { entry.index = bindless->add_image(dimension, entry.sampled, VK_IMAGE_LAYOUT_GENERAL, views, sampled_class, mirror.sampled ? &mirror : nullptr); if (!entry.index) { - vk.vkDestroyImageView(info.device, entry.mirror_sampled, nullptr); - entry.mirror_sampled = VK_NULL_HANDLE; + if (entry.mirror_sampled) { + vk.vkDestroyImageView(info.device, entry.mirror_sampled, nullptr); + entry.mirror_sampled = VK_NULL_HANDLE; + } if (entry.mirror_storage) { vk.vkDestroyImageView(info.device, entry.mirror_storage, nullptr); entry.mirror_storage = VK_NULL_HANDLE; } - using Refusal = leonida::BindlessSet::ImageRefusal; - const Refusal refusal = bindless->image_refusal(dimension, entry.storage != VK_NULL_HANDLE, sampled_class); - if (why) - *why = refusal == Refusal::no_array ? "set 0 has no array for the T#'s dimension" - : refusal == Refusal::storage_full ? "the bindless storage arrays of the T#'s dimension are full" - : "the bindless array of the T#'s dimension is full"; - if (refusal != Refusal::no_array && - first_diagnostic("a bindless image array is full; dimension", int(dimension))) { - // Whether the array holds live textures or stale views: the T#s it holds, the textures they name, - // the most T#s of one texture (a texture whose T#s keep changing, a streamed mip clamp say, keeps an - // index for each until it goes), and how many of those textures are still the one registered at - // their address (a texture leaves the set when the one registered there goes: forget_image). - std::size_t entries = 0, replaced = 0, most = 0, registered = 0; - std::map per_texture; - for (const auto& [key, held] : image_entries) - if (held.dimension == dimension) { - ++entries; - most = std::max(most, ++per_texture[held.address]); - } - for (const auto& texture : per_texture) registered += images_by_address.count(texture.first); - for (const auto& held : replaced_images) replaced += held.dimension == dimension; - constexpr const char* names[] = {"2D", "2D array", "3D", "1D", "1D array", "2D MS", "2D MS array"}; - std::fprintf(stderr, - "[rt] d3d12: a bindless image array is full; dimension %d (%s)%s: %u indices, %u in the " - "storage arrays, %zu T#s of %zu textures (%zu registered at their address, at most %zu " - "T#s of one), %zu replaced views kept; further T#s of this dimension read the " - "fallback\n", - int(dimension), names[int(dimension)], - refusal == Refusal::storage_full ? ", its storage range" : "", - bindless->image_capacity(dimension), bindless->storage_capacity(dimension), entries, - per_texture.size(), registered, most, replaced); - } + report_bindless_refusal(entry.storage != VK_NULL_HANDLE); if (entry.sampled) vk.vkDestroyImageView(info.device, entry.sampled, nullptr); if (entry.storage) vk.vkDestroyImageView(info.device, entry.storage, nullptr); return false; } - if (existing != image_entries.end()) { - replaced_images.push_back(existing->second); // the read-only entry of the same bytes - existing->second = entry; - } else { - image_entries.emplace(words, entry); - image_keys.emplace(image.address, words); - } - // The set derives the entry's kind from what it bound at this index (BindlessSet::image_kind_at); a plain - // library's modules do not read it, so they get 0 as before. - bindless->insert_key(words, entry.index, - descriptor_table_tagged ? bindless->image_kind_at(dimension, entry.index) : 0u); - leonida::fsdraw::note_tsharp(words.data()); // LOCAL DIAGNOSTIC + SharedViewEntry& sv = shared_views[vk_key]; + sv.entry = entry; + sv.is_zero_view = is_zero_view; + commit_key_to_shared(sv, /*is_new=*/true); return true; } + // The dword 6 that the T# `words` (its key: the descriptor as the title or Create*View wrote it) gets in a heap + // shaders read (gfx10_descriptors.h, tsharp_index_word): its entry's index and the arrays that index is bound in, + // which the set derives from what it bound there (image_kind_at); 0, the fallback, while the T# has no entry (no + // texture yet, a stream still pending, no room). descriptor_mutex held. + std::uint32_t tsharp_index_word_locked(const leonida::gfx10::ImageWords& words) const { + if (!bindless) return 0; + const auto it = image_entries.find(words); + if (it == image_entries.end()) return 0; + return leonida::gfx10::tsharp_index_word(it->second.index, + bindless->image_kind_at(it->second.dimension, it->second.index)); + } + std::uint32_t tsharp_index_word(const leonida::gfx10::ImageWords& words) { + std::lock_guard lock(descriptor_mutex); + return tsharp_index_word_locked(words); + } + // Textures by the address their T#s name them by (Resource::image_address), for the T#s a title writes into a // console descriptor heap itself (bind_title_image). Under descriptor_mutex: a texture leaves it in forget_image, // before its image goes. @@ -8117,6 +13270,31 @@ struct DeviceState { void note_image_address(std::uint64_t address, const void* resource) { std::lock_guard lock(descriptor_mutex); images_by_address[address] = resource; + note_texture_change(leonida::SlotChange::texture_added, address); + } + // A texture registered, replaced or gone at `address`: the console heaps' T#s naming it (by that address or by + // the other view of texture-pool memory, title_gpu_views) are fixed again at the next submission. + void note_texture_change(leonida::SlotChange::Kind kind, std::uint64_t address) { + if (!address) return; + note_slot_change(kind, address, 1); + if (const std::uint64_t other = leonida::title_gpu_views::other_view(address)) + note_slot_change(kind, other, 1); + } + // Why no texture answers a T# (bind_title_image; descriptor_mutex held): the kTsharpNoTexture* reasons. + const char* no_texture_reason_locked(const leonida::gfx10::Image& image); + // The address a title-written T# names a texture by. The title rebuilds T#s of the layer's textures (1 << 32 and + // up, 256 apart: Resource::image_address) from 32 bits: run 58's unbound T#s name 0x7f0000021400 for 0x100021400 + // and 0x2ef600 for 0x1002ef600 (bits 32-39 clear, 0x7f or 0 in bits 40-47). Such an address outside the title's + // memory is the layer's texture address with the same low 32 bits, before or after that texture exists, while the + // layer has handed out fewer than 2^24 addresses (so the low bits name one); any other address is itself. + std::uint64_t tsharp_texture_key(std::uint64_t address) const { + constexpr std::uint64_t ours = std::uint64_t(1) << 32; + const std::uint64_t high = address >> 40, mid = (address >> 32) & 0xff, low = address & 0xffffffffull; + if (mid || !low || (high && high != 0x7f)) return address; + if (next_image_address.load(std::memory_order_relaxed) >= ours + ours) return address; + std::uint64_t lo = 0, hi = 0; + if (leonida::title_va_aliases().title_memory(address, lo, hi)) return address; + return ours | low; } // LEONIDA_TRACE_TEXTURE=
[,
...] (hex, the base a T# names): the resource id of an image registered // at that address, so a draw's T# can be followed to the passes that write it (fsdraw rt0, UAV views, copies). @@ -8151,14 +13329,34 @@ struct DeviceState { images_by_address.erase(address); forget_image_views_locked(address); } + // The same for a texture that is going, only while `owner` is the texture registered at `address`: one that took + // the address over since (a slot-133 texture placed where a slot-70 view had made one, place_at_title_address) + // keeps it, and the views of the one going left with that takeover. + void forget_image_of(std::uint64_t address, const void* owner) { + std::lock_guard lock(descriptor_mutex); + const auto it = images_by_address.find(address); + if (it == images_by_address.end() || it->second != owner) return; + images_by_address.erase(it); + forget_image_views_locked(address); + } + // Its T#s stop naming it at once (a shader's lookup of their words misses from the next table flush on); the + // console heap slots that held them wait for the next texture at the address (note_texture_change). Actual + // SlotChange::texture_room is emitted only once the deferred slots actually return to free in set_bindless_release + // or set_bindless_prepare (flush), avoiding premature wake storms while slots are still in flight. void forget_image_views_locked(std::uint64_t address) { + note_texture_change(leonida::SlotChange::texture_gone, address); if (!bindless) return; const auto [first, last] = image_keys.equal_range(address); for (auto it = first; it != last; ++it) { const auto entry = image_entries.find(it->second); + if (entry == image_entries.end()) continue; bindless->erase_key(it->second); - release(entry->second); + const ViewKey vk_key = entry->second.view_key; + const std::size_t key_pos = entry->second.sv_key_pos; + const bool from_title = entry->second.from_title_heap; + if (from_title && title_heap_image_keys > 0) --title_heap_image_keys; image_entries.erase(entry); + detach_view_key_locked(vk_key, key_pos, from_title, /*upgrading=*/false, 0); } image_keys.erase(first, last); std::erase_if(replaced_images, [&](const ImageEntry& entry) { @@ -8169,12 +13367,17 @@ struct DeviceState { } // Gives the S# `words` a sampler in set 0 and an entry in the hash table, unless it has them. - bool bind_sampler(const leonida::gfx10::SamplerWords& words) { + // When `out_index` is given, receives the bindless sampler index on success or 0xFFFFFFFFu on failure. + bool bind_sampler(const leonida::gfx10::SamplerWords& words, std::uint32_t* out_index = nullptr) { + if (out_index) *out_index = leonida::LiteralSamplerSpec::kFallbackIndex; namespace g = leonida::gfx10; std::lock_guard lock(descriptor_mutex); if (!bindless) return false; const leonida::DescriptorKey key = leonida::make_ssharp_key(words.data()); - if (sampler_entries.count(key)) return true; + if (const auto it = sampler_entries.find(key); it != sampler_entries.end()) { + if (out_index) *out_index = it->second.index; + return true; + } const g::Sampler sampler = g::decode(words); VkSamplerCreateInfo sampler_info = g::vulkan_sampler(sampler, max_sampler_lod_bias); // What vulkan_sampler leaves to its caller, and features this device may not have enabled. @@ -8230,8 +13433,9 @@ struct DeviceState { context->vk.vkDestroySampler(info.device, vk_sampler, nullptr); return false; } - sampler_entries.emplace(key, vk_sampler); + sampler_entries.emplace(key, SamplerEntry{vk_sampler, index}); bindless->insert_key(key, index); + if (out_index) *out_index = index; return true; } @@ -8742,7 +13946,7 @@ class DescriptorHeap final desc_.NumDescriptors, shadowed_); return; } - if ((desc_.Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) && device.arena.mapped) { + if ((desc_.Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) && device.arena_ready()) { // A bindless-sized resource heap (64Ki slots or more: what a shader indexes directly) is followed by null // slots, as a console heap's copy is (DeviceState::heap_guard_bytes); a smaller one, or one the arena has // no room for with them, is not. @@ -8759,7 +13963,7 @@ class DescriptorHeap final return; } in_arena_ = true; - cpu_ = device.arena.mapped + arena_offset_; + cpu_ = device.arena_host(arena_offset_, bytes + guard_); std::memset(cpu_, 0, std::size_t(bytes + guard_)); if (desc.Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV || desc.Type == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) { std::lock_guard lock(device.visible_heap_mutex); @@ -8918,7 +14122,7 @@ class Resource final std::lock_guard lock(device_.descriptor_mutex); device_.pending_image_keys.erase(image_); } - if (image_address_ && device_.image_owner(image_address_) == this) device_.forget_image(image_address_); + if (image_address_) device_.forget_image_of(image_address_, this); device_.context->remove_resource(id()); // Before the memory goes to the deferred queue: no submission copies into it after this. if (shadow_) device_.remove_shadow(shadow_); @@ -8939,7 +14143,9 @@ class Resource final buffer_ = VK_NULL_HANDLE; memory_ = VK_NULL_HANDLE; } - if (in_arena_) device_.arena_release(arena_offset_, desc_.Width, DeviceState::arena_buffer); + if (in_arena_) + device_.arena_release(arena_offset_, desc_.Width, + shadow_ ? DeviceState::arena_window : DeviceState::arena_buffer); if (pooled_image_) device_.context->defer_destroy(leonida::DeferredDeletionQueue::Kind::pooled_title_image, pooled_image_.release()); else if (image_ && !sparse_image_) @@ -9000,42 +14206,26 @@ class Resource final bool is_shadow() const { return shadow_ != nullptr; } // create_shadow_buffer: a copy of title pages const DeviceState& device_state() const { return device_; } void* title_address() const { return title_address_; } // place_at_title_address, or null - HRESULT upload_title_subresource(UINT subresource, void* data, UINT row, UINT slice, bool allow_staging) { - static const bool ordered = [] { - const char* value = std::getenv("LEONIDA_ORDER_TEXTURE_UPLOADS"); - return !value || std::strcmp(value, "0"); - }(); - if (ordered && host_transfer_) { - Region r{}; - if (!region(subresource, nullptr, r) || row != r.row_bytes || slice != row * r.rows) return E_INVALIDARG; - const auto result = device_.context->write_host_texture(id(), subresource, [&] { return host_copy(true, r, data); }); - if (result == VK_SUCCESS) return S_OK; - if (result != VK_NOT_READY) return E_FAIL; - // Layout changed after the pass checked the subresources. Never submit recursively. - if (!allow_staging) return DXGI_ERROR_WAS_STILL_DRAWING; - return cpu_copy(true, subresource, nullptr, data, row, slice, false); - } - return WriteToSubresource(subresource, nullptr, data, row, slice); - } - bool replay_seen() const { return replay_seen_.load(std::memory_order_relaxed); } bool staged_title() const { return staged_title_; } + // The image as the title upload writes it (TitleImageUpload::reserve, fill and commit). + const leonida::ResourceBinding& title_binding() const { return binding_; } bool upload_staged_title(const rt::xg_xs::Texture& layout, const std::uint8_t* tiled, - std::vector& columns, bool inspect, bool& nonzero, unsigned from) { + std::vector& columns, bool inspect, bool& nonzero, unsigned from = 0) { std::lock_guard lock(device_.title_upload_mutex); return device_.title_upload.write(device_, id(), binding_, layout, tiled, columns, inspect, nonzero, from); } // Map and the destructor notify the registry for a slot-133 placement. void mark_title_texture() { title_texture_ = true; } - void note_shader_view() const { shader_views_.fetch_add(1, std::memory_order_relaxed); } + // Every descriptor of the texture (a D3D12 view, a slot-70 view, a T# the title wrote into a console heap) comes + // here. The first one of a title texture tells the registry, which fills it from memory only from then on. + void note_shader_view() const { + if (!shader_views_.fetch_add(1, std::memory_order_relaxed) && title_texture_ && title_address_) + device_.title_texture_named(reinterpret_cast(title_address_)); + } std::uint32_t shader_views() const { return shader_views_.load(std::memory_order_relaxed); } // The element a CPU copy moves (a 4x4 block for block-compressed formats), as WriteToSubresource takes it. leonida::BlockFormat copy_element() const { return leonida::copy_block_format(binding_, VK_IMAGE_ASPECT_COLOR_BIT); } - // WriteToSubresource of this subresource is a host copy now (VK_EXT_host_image_copy, image in GENERAL), not a - // staged copy through a queue: the only kind a refresh before a submission may do. - bool host_copy_now(UINT subresource) const { - return host_transfer_ && device_.context->layout(id(), subresource) == VK_IMAGE_LAYOUT_GENERAL; - } // Default-heap buffers are ranges of the GPU address arena: console VA = offset, zeroed through the arena's host // mapping. Upload and readback buffers keep their own host memory; with buffer device addresses their console @@ -9047,14 +14237,14 @@ class Resource final const bool host = cpu_visible(); leonida::ResourceBinding binding{}; // a buffer: no image binding.size = desc_.Width; - const bool use_arena = !host && device_.arena.mapped; + const bool use_arena = !host && device_.arena_ready(); if (use_arena && desc_.Width > device_.arena.size) return E_OUTOFMEMORY; // An otherwise valid committed buffer can outgrow the largest free slice. Give it its own // addressable VkBuffer below, so the title can still use its arena-relative GPU VA. if (use_arena && device_.arena_allocate(desc_.Width, D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT, arena_offset_, DeviceState::arena_buffer)) { in_arena_ = true; - std::memset(device_.arena.mapped + arena_offset_, 0, std::size_t(desc_.Width)); + std::memset(device_.arena_host(arena_offset_, desc_.Width), 0, std::size_t(desc_.Width)); va_ = arena_offset_; binding.va = va_; binding.buffer = device_.arena.buffer; @@ -9341,7 +14531,7 @@ class Resource final // logs the same wrap). Such an import is not used: the shadow buffer in the arena answers, as when the // import is refused. LEONIDA_IMPORT_BELOW_ARENA=1 keeps the import (for a shader library whose programs // sign-extend the address). - if (buffer_va_ && buffer_va_ < device_.arena.address && !signed_vsharp_offsets()) { + if (buffer_va_ && buffer_va_ < device_.arena.address && !import_below_arena()) { static std::atomic logged{0}; if (logged.fetch_add(1, std::memory_order_relaxed) < 8) std::fprintf(stderr, @@ -9401,6 +14591,33 @@ class Resource final // of command lists the pages the title wrote since are copied again (ShadowPages, DeviceState::refresh_shadows). // One way only: what the GPU writes to the shadow is NOT copied back to the title's pages, and the next copy of // a page overwrites it. A title that reads GPU output at `address` needs the import. + // A buffer on title memory the page mirror holds (step C): bound to the mirror's chunk at heap_base + the title's + // address, so the GPU reads and writes the pages' homes, every view of the same pages shares them, and the + // per-submission shadow copy, its walk and its guards go. Its VA is the title's address; V#s and root views naming + // it keep that address (heap_base + it is the chunk). The CPU's Map answers the title's pages, as an import does; + // the GPU's writes go back to them after the submission (DeviceState::page_mirror_write_back). E_NOTIMPL when the + // mirror is off or does not hold the range in one chunk: an import or a shadow then answers, as before. + HRESULT create_mirror_buffer(void* address) { + const auto start = reinterpret_cast(address); + if (!address || !desc_.Width || desc_.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) return E_NOTIMPL; + VkBuffer chunk = VK_NULL_HANDLE; + VkDeviceSize offset = 0; + if (!device_.page_mirror_chunk(start, desc_.Width, chunk, offset)) return E_NOTIMPL; + mapped_ = address; + va_ = start; + buffer_va_ = gpu_va_ = device_.page_mirror_address(start); + leonida::ResourceBinding binding{}; + binding.buffer = chunk; + binding.indirect_arguments = true; // the chunks carry every buffer usage (sparse_buffer_info) + binding.buffer_offset = offset; + binding.size = desc_.Width; + binding.host = static_cast(address); + binding.host_readable = true; + binding.va = va_; + device_.context->add_resource(id(), binding); + return S_OK; + } + HRESULT create_shadow_buffer(void* address) { auto& vk = device_.context->vk; if (!address || !desc_.Width || desc_.Width > ~UINT64(0) - D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT) @@ -9411,10 +14628,10 @@ class Resource final // any buffer of the layer's; the root views and V#s the layer writes for that VA name the arena offset // instead (src/title_va_alias.h), a VA below 4 GiB that a root view and a V#'s 48 bits both hold. The arena // is host-visible, so the per-submission copy writes it in place. - if (device_.arena.mapped && device_.arena_allocate(desc_.Width, D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT, - arena_offset_, DeviceState::arena_buffer)) { + if (device_.arena_ready() && device_.arena_allocate(desc_.Width, D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT, + arena_offset_, DeviceState::arena_window)) { in_arena_ = true; - shadow_ = device_.arena.mapped + arena_offset_; + shadow_ = device_.arena_host(arena_offset_, desc_.Width); device_.add_shadow(pages, shadow_, std::size_t(desc_.Width)); mapped_ = address; va_ = reinterpret_cast(address); @@ -9575,17 +14792,20 @@ class Resource final // A placed buffer is a range of the heap's arena memory: it has no VkBuffer of its own and its console VA is // where it sits in the arena. The arena is host-visible, so an upload or readback place maps that same range. HRESULT create_placed_buffer(std::shared_ptr heap_range) { - if (!device_.arena.mapped) return E_OUTOFMEMORY; + if (!device_.arena_ready()) return E_OUTOFMEMORY; + // Inside its heap's arena range, which is one allocation: one mapping. + std::uint8_t* const host = device_.arena_host(va_, desc_.Width); + if (!host) return E_OUTOFMEMORY; heap_range_ = std::move(heap_range); - if (cpu_visible()) mapped_ = device_.arena.mapped + va_; - std::memset(device_.arena.mapped + va_, 0, std::size_t(desc_.Width)); // a fresh place reads as zeroed + if (cpu_visible()) mapped_ = host; + std::memset(host, 0, std::size_t(desc_.Width)); // a fresh place reads as zeroed leonida::ResourceBinding binding{}; binding.size = desc_.Width; binding.buffer = device_.arena.buffer; binding.indirect_arguments = device_.arena.indirect_arguments; binding.buffer_offset = va_; binding.va = va_; - binding.host = cpu_writable() ? device_.arena.mapped + va_ : nullptr; + binding.host = cpu_writable() ? host : nullptr; binding.host_readable = (heap_.Type == D3D12_HEAP_TYPE_READBACK || (heap_.Type == D3D12_HEAP_TYPE_CUSTOM && heap_.CPUPageProperty == D3D12_CPU_PAGE_PROPERTY_WRITE_BACK)); @@ -9944,10 +15164,10 @@ class Resource final DeviceState::PendingImage ready; if (const auto pending = device_.pending_image_keys.find(image_); pending != device_.pending_image_keys.end()) { ready = pending->second; - std::erase_if(ready.keys, [&](const auto& key) { return key.second.first_mip < from; }); + std::erase_if(ready.keys, [&](const auto& key) { return key.second.image.first_mip < from; }); if (from) { pending->second.first_mip = from; - std::erase_if(pending->second.keys, [&](const auto& key) { return key.second.first_mip >= from; }); + std::erase_if(pending->second.keys, [&](const auto& key) { return key.second.image.first_mip >= from; }); } else { device_.pending_image_keys.erase(pending); } @@ -9955,9 +15175,11 @@ class Resource final const auto owner = device_.images_by_address.find(image_address_); if (owner != device_.images_by_address.end() && owner->second == this) { if (ready.zero) device_.forget_image_views_locked(image_address_); - for (const auto& [words, image] : ready.keys) - device_.bind_image_locked(words, image, image_, format_, aspects_, false, has_view_format_list(), - uint_backed_); + for (const auto& [words, pending_key] : ready.keys) + device_.bind_image_locked(words, pending_key.image, image_, format_, aspects_, false, + has_view_format_list(), uint_backed_, nullptr, pending_key.evictable); + // Its image is there now: title-written T#s refused while it had none are fixed again. + device_.note_texture_change(leonida::SlotChange::texture_added, image_address_); } if (!from) deferred_stream_ = false; } @@ -9965,14 +15187,17 @@ class Resource final bool deferred_stream() const { return deferred_stream_; } VkDeviceSize unbound_bytes() const { return image_backing_bytes() ? 0 : deferred_bytes_; } + bool pooled_image() const { return pooled_image_ != nullptr; } private: bool bind_placed_memory() { VkMemoryRequirements requirements{}; std::uint32_t type = UINT32_MAX; - if (!image_backing_bytes_ && !bind_texture_memory(false, deferred_types_, requirements, type)) { + const bool pool = !(desc_.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | + D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)); + if (!image_backing_bytes_ && !bind_texture_memory(pool, deferred_types_, requirements, type)) { if (!(requirements.memoryTypeBits & ~deferred_types_) || - !bind_texture_memory(false, ~deferred_types_, requirements, type)) return false; + !bind_texture_memory(pool, ~deferred_types_, requirements, type)) return false; } if (shared_zero_) { if (host_transfer_ && !host_initialize()) return false; @@ -10658,6 +15883,7 @@ class Resource final device_.info.queue_family); } staging_queue->make_synchronous(); // submitted inline, then waited for (wait_submitted below) + staging_queue->set_skip_before_execute(true); // internal staging copy only; never reads world heaps/mirror } if (staging_queue->ok()) { const leonida::CommandList* lists[] = {&list}; @@ -10971,6 +16197,7 @@ bool DeviceState::materialize_table(std::uint64_t address, std::uint32_t slots) for (const auto& [key,view]:pending_samples) if (view.owner->id() == address) keys.push_back(key); } for (const auto& key:keys) if (!materialize_sample(key)) return false; + write_tsharp_index_words(keys); return true; } std::uint64_t end = 0; @@ -10990,19 +16217,60 @@ bool DeviceState::materialize_table(std::uint64_t address, std::uint32_t slots) std::vector all; {std::lock_guard lock(pending_view_mutex);for(const auto& [key,v]:pending_samples) all.push_back(key);} for(const auto& key:all) if(!materialize_sample(key)) return false; + write_tsharp_index_words(all); return true; } const auto refreshed = std::min(end-address, std::uint64_t(kViewScanLimit)*kDescriptorSize); + std::uint8_t* const table = arena_host(address, end-address); // a live heap's table: one allocation + if (!table) return false; if (end-address>refreshed) - leonida::title_va_aliases().pull_descriptors(arena.mapped+address+refreshed,std::size_t(end-address-refreshed)); + leonida::title_va_aliases().pull_descriptors(table+refreshed,std::size_t(end-address-refreshed)); for (auto at=address; at& keys) { + if (!tsharp_index_words || keys.empty()) return; + namespace g = leonida::gfx10; + const std::set wanted(keys.begin(), keys.end()); + std::vector> ranges; + { + std::lock_guard lock(visible_heap_mutex); + for (const auto& [offset, heap] : visible_heaps) + if (heap.type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) + if (std::uint8_t* host = arena_host(offset, heap.end - offset)) + ranges.emplace_back(host, std::size_t(heap.end - offset)); + for (const auto& [begin, end] : cpu_view_heaps) + ranges.emplace_back(reinterpret_cast(begin), std::size_t(end - begin)); + } + std::lock_guard lock(descriptor_mutex); + for (const auto& [base, bytes] : ranges) + for (std::size_t at = 0; at + kDescriptorSize <= bytes; at += kDescriptorSize) { + g::ImageWords words; + std::memcpy(words.data(), base + at, sizeof(words)); + if (!g::is_image(words)) continue; + const g::ImageWords key = g::tsharp_key(words); + if (!wanted.count(key)) continue; + const std::uint32_t word = tsharp_index_word_locked(key); + std::memcpy(base + at + 4 * g::kTsharpIndexDword, &word, sizeof(word)); + } +} + class Heap final : public Child { public: @@ -11011,14 +16279,24 @@ class Heap final Heap(DeviceState& device, const D3D12_HEAP_DESC& desc) : device_(device), desc_(desc) { VkDeviceSize offset = 0; - if (device_.arena.mapped && + leonida::ArenaBacking::Location place; + if (device_.arena_ready() && device_.arena_allocate(desc_.SizeInBytes, D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT, offset, DeviceState::arena_heap)) { + // The heap is one arena allocation, so one backing unit: its tiles are that unit's memory, at the heap's + // place in it. A reserved resource binds them (vulkan_backend.h bind_tiles), so `offset` is the memory + // offset; the arena VA stays in arena_offset_. + if (!device_.arena.backing.locate(offset, desc_.SizeInBytes, place)) { + device_.note_unbacked_arena(offset, desc_.SizeInBytes); + device_.arena_release(offset, desc_.SizeInBytes, DeviceState::arena_heap); + return; + } + arena_offset_ = offset; allocation_ = std::shared_ptr( - new leonida::TileHeapAllocation{device_.arena.memory, offset, desc_.SizeInBytes, + new leonida::TileHeapAllocation{place.memory, place.memory_offset, desc_.SizeInBytes, device_.arena.memory_type}, - [&device](const leonida::TileHeapAllocation* allocation) { - device.arena_release(allocation->offset, allocation->size, DeviceState::arena_heap); + [&device, offset](const leonida::TileHeapAllocation* allocation) { + device.arena_release(offset, allocation->size, DeviceState::arena_heap); delete allocation; }); } @@ -11053,7 +16331,7 @@ class Heap final // An existing heap: the caller's memory, not an arena range, so offset() is not a place in the arena. const void* host_address() const { return host_address_; } const std::shared_ptr& arena_range() const { return allocation_; } - VkDeviceSize offset() const { return allocation_->offset; } + VkDeviceSize offset() const { return arena_offset_; } // the heap's arena VA (an arena heap only) UINT64 bytes() const { return desc_.SizeInBytes; } UINT64 alignment() const { return desc_.Alignment ? desc_.Alignment : D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; } const D3D12_HEAP_PROPERTIES& properties() const { return desc_.Properties; } @@ -11106,6 +16384,7 @@ class Heap final D3D12_HEAP_DESC desc_; const void* host_address_ = nullptr; std::shared_ptr allocation_; + VkDeviceSize arena_offset_ = 0; std::mutex backing_mutex_; std::shared_ptr tile_allocation_; bool placed_buffer_ = false; @@ -11117,13 +16396,21 @@ class Heap final // The S#s a shader builds from immediates (literal_samplers in its index entry) are named by no heap slot, so // nothing else gives them a sampler and a hash-table key: without this their lookup finds the fallback sampler // (index 0) and the shader samples with the wrong filter and address modes (docs/design.md, Literal samplers). -// Registering is idempotent and also runs when the pipeline is created again. -void register_literal_samplers(DeviceState& device, const leonida::ShaderEntry& entry) { - for (const leonida::gfx10::SamplerWords& words : entry.literal_samplers) - if (!device.bind_sampler(words)) +// Registering is idempotent and also runs when the pipeline is created again. Returns one bindless sampler index per +// entry in `entry.literal_samplers` (or 0xFFFFFFFFu when a sampler failed to bind so a specialized shader falls back +// to the hash probe). +std::vector register_literal_samplers(DeviceState& device, const leonida::ShaderEntry& entry) { + std::vector indices; + indices.reserve(entry.literal_samplers.size()); + for (const leonida::gfx10::SamplerWords& words : entry.literal_samplers) { + std::uint32_t idx = leonida::LiteralSamplerSpec::kFallbackIndex; + if (!device.bind_sampler(words, &idx)) log_once("a shader's literal S# got no sampler (no bindless set, or its sampler array is full); " "literal S#s in that shader:", int(entry.literal_samplers.size())); + indices.push_back(idx); + } + return indices; } // Among index entries for one program (containers with the same FSSM program; 789 groups in the 26,503-shader @@ -11788,10 +17075,16 @@ ComputeBuild build_compute_pipeline(DeviceState& device, const leonida::ShaderEn } const std::size_t bytes = words.size() * sizeof(std::uint32_t); out.bytes = bytes; + leonida::LiteralSamplerSpec literal_spec; + if (entry->binding_count && entry->literal_sampler_spec_base && !entry->literal_samplers.empty()) { + const auto indices = register_literal_samplers(device, *entry); + literal_spec.build(*entry->literal_sampler_spec_base, indices); + } VkComputePipelineCreateInfo pipeline_info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; pipeline_info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; pipeline_info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; pipeline_info.stage.pName = "main"; + pipeline_info.stage.pSpecializationInfo = literal_spec.ptr(); VkPipelineShaderStageRequiredSubgroupSizeCreateInfo required_size{}; leonida::apply_subgroup_request(subgroup, required_size, pipeline_info.stage); pipeline_info.layout = layout; @@ -11815,6 +17108,12 @@ ComputeBuild build_compute_pipeline(DeviceState& device, const leonida::ShaderEn key.value(std::uint32_t(pipeline_info.stage.pNext == &required_size ? required_size.requiredSubgroupSize : 0)); key.value(std::uint32_t(sizeof(leonida::ShaderUserData))); key.value(std::uint32_t(entry->binding_count != 0)); + if (literal_spec.active()) { + key.text("literal-samplers"); + key.value(*entry->literal_sampler_spec_base); + key.value(std::uint32_t(literal_spec.values.size())); + key.bytes(literal_spec.values.data(), literal_spec.values.size() * sizeof(std::uint32_t)); + } // NVIDIA's diagnostics config (LEONIDA_DEVICE_FAULT=1, Aftermath) compiles with shader debug info: other // pipelines, kept apart so switching it on and off does not rewrite every file. Absent when off, so the // names of ordinary boots stay as they were. @@ -11836,7 +17135,9 @@ ComputeBuild build_compute_pipeline(DeviceState& device, const leonida::ShaderEn // where the driver's lock it holds stops the title's submissions. The helper process compiles it into the file // instead, and the create below is a hit. Asked without waiting, the build answers deferred and is asked // again at the pipeline's next use; waited for, nothing of ours is in the driver meanwhile. - if (!journal.has_file_data() && options.use_helper && compile_helper::wanted(bytes)) { + // Skip the out-of-process helper when literal-sampler specialization constants are bound, because bindless + // sampler indices are process-local and would not match the helper's journal key. + if (!journal.has_file_data() && options.use_helper && !literal_spec.active() && compile_helper::wanted(bytes)) { auto& helper = compile_helper::Client::instance(); std::string why; if (!options.helper_wait) { @@ -12272,7 +17573,7 @@ class PipelineState final } if (desc.NodeMask & ~1u) return E_INVALIDARG; if (static_cast(desc.Flags) & ~kKnownPipelineStateFlags) return E_INVALIDARG; - if (!device_.arena.mapped) { + if (!device_.arena_ready()) { return stream_unsupported("pipelines need the GPU address arena (bufferDeviceAddress); stage", 1); } if (!push_constants_fit()) return stream_unsupported("graphics push-constant limit"); @@ -12370,6 +17671,7 @@ class PipelineState final const leonida::ShaderEntry* entry = nullptr; std::vector fssm; std::vector words; + std::vector literal_sampler_indices; }; Stage stages[3] = {mesh ? Stage{"ms", VK_SHADER_STAGE_MESH_BIT_EXT, *ms} : Stage{"vs", VK_SHADER_STAGE_VERTEX_BIT, desc.VS}, @@ -12378,6 +17680,8 @@ class PipelineState final // stage_infos.size() indexes the recipe's per-stage required-size structs: one for every table entry. static_assert(std::size(stages) <= std::size(decltype(recipe_.required_sizes){}), "Recipe::required_sizes needs an entry per graphics stage"); + static_assert(std::size(stages) <= std::extent_v, + "Recipe::literal_sampler_specs needs an entry per graphics stage"); unsigned packed_color_mask=0; // A LEONIDA_STUB_PIPELINES=color stub turns blending and logic ops off (below), so the packed fallback's refusal // of them waits until it is known whether this pipeline is such a stub. @@ -12489,7 +17793,7 @@ class PipelineState final return stream_unsupported("graphics shader requires a bindless descriptor set"); } uses_bindless = true; - register_literal_samplers(device_, *stage.entry); + stage.literal_sampler_indices = register_literal_samplers(device_, *stage.entry); } if (stage.bit == VK_SHADER_STAGE_MESH_BIT_EXT) { // The SPIR-V's output arrays are sized from PSV0 (the index's max_vertices / max_primitives); Vulkan @@ -12610,8 +17914,12 @@ class PipelineState final graphics_.rectangle_variant_topology = leonida::topology_rect_list; std::uint64_t spirv_bytes = 0; + bool graphics_writes_buffer = false; + bool graphics_reads_glc_buffer = false; for (Stage& stage : stages) { if (!stage.entry) continue; + if (stage.entry->writes_buffer) graphics_writes_buffer = true; + if (stage.entry->reads_glc_buffer) graphics_reads_glc_buffer = true; // After the f16 link above, which can also edit the pixel shader's words. if (depth24_fragment && stage.bit == VK_SHADER_STAGE_FRAGMENT_BIT) { std::string why; @@ -12647,6 +17955,12 @@ class PipelineState final info.stage = stage.bit; info.module = module; info.pName = "main"; + if (stage.entry->binding_count && stage.entry->literal_sampler_spec_base && + !stage.literal_sampler_indices.empty()) { + auto& spec = recipe_.literal_sampler_specs[stage_infos.size()]; + spec.build(*stage.entry->literal_sampler_spec_base, stage.literal_sampler_indices); + info.pSpecializationInfo = spec.ptr(); + } subgroup_size_for(*stage.entry, required_sizes[stage_infos.size()], info); stage_infos.push_back(info); } @@ -13013,6 +18327,8 @@ class PipelineState final // Kept for variants: a draw that leaves a slot unbound needs this pipeline with that format undefined. graphics_.mesh = mesh; graphics_.depth_bounds = depth_bounds; + graphics_.reads_glc_buffer = graphics_reads_glc_buffer; + graphics_.writes_buffer = graphics_writes_buffer; recipe_.mesh = mesh; recipe_.stages = std::move(stage_infos); recipe_.attributes = std::move(attributes); @@ -13060,7 +18376,8 @@ class PipelineState final if (code_stage) { VkDeviceSize offset = 0; if (!device_.arena_allocate(code_stage->fssm.size(), 256, offset, DeviceState::arena_shader)) return E_OUTOFMEMORY; - std::memcpy(device_.arena.mapped + offset, code_stage->fssm.data(), code_stage->fssm.size()); + std::memcpy(device_.arena_host(offset, code_stage->fssm.size()), code_stage->fssm.data(), + code_stage->fssm.size()); code_bytes_ = code_stage->fssm.size(); code_base_ = offset; graphics_.code_base = offset; @@ -13087,7 +18404,7 @@ class PipelineState final leonida::fsdraw::note_pipeline(id(), text); } order_install(graphics_.requested, graphics_.request_context, graphics_.mesh ? 'm' : 'g'); - if (device_.info.device_checkpoints) { + if (device_.info.device_checkpoints || leonida::gpu_profile::enabled()) { // names for both reports leonida::CheckpointShaders shaders{}; for (std::size_t i = 0; i < std::size(stages); ++i) if (stages[i].entry) shaders[i] = stages[i].entry->name.c_str(); @@ -13107,7 +18424,7 @@ class PipelineState final if (!desc.CS.pShaderBytecode || !desc.CS.BytecodeLength) return E_INVALIDARG; if (desc.NodeMask & ~1u) return E_INVALIDARG; if (static_cast(desc.Flags) & ~kKnownPipelineStateFlags) return E_INVALIDARG; - if (!device_.arena.mapped) { + if (!device_.arena_ready()) { return stream_unsupported("pipelines need the GPU address arena (bufferDeviceAddress); stage", 0); } if (!push_constants_fit()) return stream_unsupported("compute push-constant limit"); @@ -13187,6 +18504,8 @@ class PipelineState final compute_entry_ = entry; stage_bytes_ = spirv_bytes; pipeline_.estimate = leonida::large_module_estimate(spirv_bytes); + pipeline_.reads_glc_buffer = entry->reads_glc_buffer; + pipeline_.writes_buffer = entry->writes_buffer; // The title creates hundreds of compute pipelines from job threads during startup and one of its init tasks // waits for all of them; some modules (wave64-emulated ray-tracing resolves, 4 MiB of SPIR-V) take the driver // minutes each. So the Vulkan pipeline is built on first use (build_compute): at the first dispatch that names @@ -13232,13 +18551,15 @@ class PipelineState final if (entry->uses_code_base || !entry->code_base_known) { const auto& code = program.bytes; if (!device_.arena_allocate(code.size(), 256, code_base_, DeviceState::arena_shader)) return E_OUTOFMEMORY; - std::memcpy(device_.arena.mapped + code_base_, code.data(), code.size()); + std::memcpy(device_.arena_host(code_base_, code.size()), code.data(), code.size()); code_bytes_ = code.size(); pipeline_.code_base = code_base_; } if (!pipeline_.skipped) order_install(pipeline_.requested, pipeline_.request_context, 'c', entry->name); device_.context->add_pipeline(id(), pipeline_, - device_.info.device_fault_diagnostics ? entry->name.c_str() : nullptr); + device_.info.device_fault_diagnostics || leonida::gpu_profile::enabled() + ? entry->name.c_str() + : nullptr); registered_ = true; if (pipeline_.build && !pipeline_.skipped) warmup_enqueue(this, spirv_bytes); return S_OK; @@ -13530,6 +18851,7 @@ class PipelineState final std::vector stages; // One per entry of create_graphics's stage table (VS, GS, PS), static_assert there; what `stages` chain. VkPipelineShaderStageRequiredSubgroupSizeCreateInfo required_sizes[3]{}; + leonida::LiteralSamplerSpec literal_sampler_specs[3]{}; std::vector attributes; std::vector bindings; std::vector divisors; @@ -14420,7 +19742,6 @@ struct TitleTexture { bool layout_known = false; bool layout_guessed = false; // a slot-133 texture's own description (Layout 0), no slot-70 view yet bool layout_from_xg = false; // the title's XG computer of its shape (title_xg_layout) - std::chrono::steady_clock::time_point view_checked{}; // refresh_title_texture's last look (a view's), throttled Resource* resource = nullptr; // Snapshot at registration. A diagnostic census then need not fault in each Resource to count its image memory. VkDeviceSize backing_bytes = 0, unbound_bytes = 0; @@ -14430,6 +19751,7 @@ struct TitleTexture { backing_bytes = r->image_backing_bytes(); unbound_bytes = r->unbound_bytes(); device_local = (r->memory_flags() & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) != 0; + invalidate_gpu_upload_cache(); } bool owned = false; // made here for slot-70 views (a reference is held); else slot 133's bool attachment_4k = false; // slot 133: 3840x2160 color or depth attachment @@ -14438,20 +19760,41 @@ struct TitleTexture { bool stale = false; // changed bytes not uploaded yet (budget, or no host copy then) leonida::TextureReadability memory; // protected by title_texture_mutex std::vector formats; // owned: the image's format and castable view formats - std::uint64_t hash = 0; // hash_guarded (sampled) of the bytes the image was last filled from + std::uint64_t hash = 0; // combined TilePieces hash of the bytes the image was last filled from + leonida::TilePieces pieces; // and of its part in each 64 KiB tile (the refresh's reads) bool hashed = false; - // A mapped texture up to 4 MiB is also hashed in full, every few passes: the title writes into it in small - // pieces (a glyph in a font cache, measured: Map once, many writes, no Unmap between them) that the sampling hash - // misses. Video planes, rewritten whole every frame, are caught by the sampled one first. - std::uint64_t full_hash = 0; - bool full_hashed = false; - bool every_byte() const { return mapped && (async_texture_refresh() || layout.layout.size <= (4u << 20)); } + bool write_combined = false; // cached PAGE_WRITECOMBINE from VirtualQuery; invalidated on remap + bool write_combined_known = false; + bool gpu_uploaded = false; // last upload came directly from TitleMirror (GPU detile/copy) + std::uint64_t mirror_hash = 0; // TitleMirror::range_sum() as of the last upload (GPU or 256B-aligned CPU) + std::uint64_t mirror_hash_span = 0; // byte span covered by mirror_hash + bool mirror_hash_valid = false; + std::uint64_t gpu_upload_cached_offset = UINT64_MAX; // cached can_gpu_upload() key (mirror_offset) + VkDeviceSize gpu_upload_cached_chunk = 0; + bool gpu_upload_cached_ok = false; + rt::d3d12::TitleImageUpload::UploadKind gpu_upload_cached_kind = rt::d3d12::TitleImageUpload::UploadKind::cpu_slot; + void invalidate_gpu_upload_cache() { + gpu_upload_cached_offset = UINT64_MAX; + gpu_upload_cached_chunk = 0; + gpu_upload_cached_ok = false; + } std::uint64_t fills = 0; unsigned view_mip = 0; // first mip of the last slot-70 view // The last probe: the first mip readable with every smaller one (the mip count: none; only a 2D texture of one // slice has other values than 0 and the mip count). memory.pending(): above fill_limit, no use yet. unsigned readable_from = 0; unsigned filled_from = 0; // fills > 0: the image holds the mips from here on + + bool is_write_combined() { + if (!write_combined_known) { + MEMORY_BASIC_INFORMATION region{}; + write_combined = VirtualQuery(reinterpret_cast(static_cast(cpu)), ®ion, + sizeof(region)) && + (region.Protect & PAGE_WRITECOMBINE) != 0; + write_combined_known = true; + } + return write_combined; + } }; // The layout of a slot-133 texture as the title's own XG computer for its shape says (title_xg_layouts): how the title @@ -14481,9 +19824,275 @@ bool title_xg_layout(const Resource& r, rt::xg_xs::Texture& out, std::array over; + texture_watch.for_each_over(cpu, cpu + span, [&](std::uint64_t k) { over.push_back(k); }); + for (const std::uint64_t k : over) { + const auto it = title_textures.find(k); + if (it != title_textures.end() && over_gpu_owned(it->second->cpu, it->second->cpu + it->second->layout.layout.size)) + texture_watch.untrack(k); + } +} + +void DeviceState::drop_gpu_owned(const void* owner) { + const auto it = gpu_owned.find(owner); + if (it == gpu_owned.end()) return; + const std::uint64_t address = it->second.address; + gpu_owned.erase(it); + for (const std::uint64_t at : {address, std::uint64_t(leonida::title_gpu_views::other_view(address))}) { + const auto t = at ? title_textures.find(at) : title_textures.end(); + if (t != title_textures.end() && t->second->resource && t->second->resource != owner) index_texture(*t->second); + } +} + +// Not one nothing names yet either: a texture no descriptor names is not read, uploaded or watched (the title may +// fill it over many passes before its first view); its first descriptor (title_texture_named) brings it in, and it is +// read whole and uploaded before the submission that made that descriptor. An image made for slot-70 views is named +// by the view it is made for. +void DeviceState::index_texture(const TitleTexture& t) { + const bool filled = !t.gpu_written && t.layout_known && t.resource && (t.owned || t.resource->shader_views()) && + !((t.layout_guessed || t.layout_from_xg) && !t.mapped && !t.stale); + if (filled && over_gpu_owned(t.cpu, t.cpu + t.layout.layout.size)) { + ++gpu_owned_refusals; + texture_watch.untrack(t.address); + return; + } + if (filled) { + texture_watch.track(t.address, t.cpu, t.layout.layout.size); + if (!t.hashed || t.stale) texture_watch.touch(t.address); // never filled, or known changed: read it + } else { + texture_watch.untrack(t.address); + } +} + +// Set on the current thread by refresh_title_textures(true) right after refresh_page_mirror() + flush_page_mirror() +// ran in the same BeforeExecuteCoalescer leader pass so page_mirror_check_batch() can skip re-dirtying hot pages +// that were just uploaded (while NEVER skipping cold pages that faulted after refresh_page_mirror()). +static thread_local bool t_page_mirror_just_synced = false; // trivially destructible (no TLS callback) + +// Single-lock batched TitleMirror check & sync for all examined textures of a refresh_title_textures() pass: +// - Acquires page_mirror.mutex ONCE per pass (eliminating per-texture lock contention with refresh_page_mirror and +// write_back_batch). +// - Snapshots pending xmem remaps from page_mirror.feed under shared feed_lock (lock order: title_texture_mutex -> +// page_mirror.mutex -> feed_lock) and rejects ONLY textures whose own pages overlap an unapplied remap, instead of +// aborting the whole pass on unrelated buffer remaps. +// - Marks all dirty/hot mirror pages across all eligible textures (deduplicated automatically per physical frame by +// TitleMirror::dirty()), runs ONE batched parallel TitleMirror::upload(), and evaluates range_sum() + chunk_at() +// (or partial-tile range_sum() comparison) for every texture in the same lock hold. +void DeviceState::page_mirror_check_batch( + std::vector& items, std::vector& feed_pages, + std::uint64_t mirror_synced_serial, + const std::function)>& parallel_run) { + if (!page_mirror.mirror || items.empty()) return; + constexpr std::uint64_t kPage = leonida::TitleMirror::kPage; + constexpr std::uint64_t kPiece = leonida::shadow_keep::kPiece; + const bool mirror_just_synced = t_page_mirror_just_synced; + + std::lock_guard lock(page_mirror.mutex); + + feed_pages.clear(); + if (page_mirror.feed_pending.load(std::memory_order_acquire)) { + AcquireSRWLockShared(&page_mirror.feed_lock); + feed_pages.reserve(page_mirror.feed.size()); + for (const auto& c : page_mirror.feed) feed_pages.push_back(static_cast(c.page) & ~(kPage - 1)); + ReleaseSRWLockShared(&page_mirror.feed_lock); + if (feed_pages.size() > 1) { + std::sort(feed_pages.begin(), feed_pages.end()); + feed_pages.erase(std::unique(feed_pages.begin(), feed_pages.end()), feed_pages.end()); + } + } + const auto page_in_feed = [&](std::uint64_t p) -> bool { + return !feed_pages.empty() && std::binary_search(feed_pages.begin(), feed_pages.end(), p); + }; + + bool need_upload = false; + auto& mirror = *page_mirror.mirror; + auto* const tracking = page_mirror.tracking.get(); + const bool any_pending = mirror.has_pending_binds(); + + const auto mark_dirty_page = [&](std::uint64_t p) { + if (mirror.dirty(p)) need_upload = true; + }; + + const auto record_reject = [](TitleMirrorCheckItem& item, std::uint8_t reason) { + // Priority: in_feed (3) / pending_bind (4) > unmirrored_plain (1) > unmirrored_other (2). + if (item.reject_reason == 0 || item.reject_reason == 2 || (item.reject_reason == 1 && reason >= 3)) + item.reject_reason = reason; + }; + + const auto try_full_view = [&](TitleMirrorCheckItem& item, std::uint64_t va, bool is_cpu_view) -> bool { + if (!va || !item.bytes || va + item.bytes < va) return false; + const std::uint64_t end = va + item.bytes; + for (std::uint64_t p = va & ~(kPage - 1); p < end; p += kPage) { + if (page_in_feed(p)) { + record_reject(item, 3); + return false; + } + if (!mirror.mirrored(p)) { + auto pit = page_mirror.plain.upper_bound(p); + const bool in_plain = (pit != page_mirror.plain.begin() && std::prev(pit)->second > p); + record_reject(item, in_plain ? 1 : 2); + return false; + } + if (any_pending && mirror.has_pending(p)) { + record_reject(item, 4); + return false; + } + if (p > UINT64_MAX - kPage) break; + } + const bool serial_clean = mirror_just_synced && mirror_synced_serial != 0 && item.ex_armed && + item.max_version <= mirror_synced_serial; + if (!serial_clean) { + const bool filter_written = is_cpu_view && item.written_tiles && !item.written_tiles->empty(); + for (std::uint64_t p = va & ~(kPage - 1); p < end; p += kPage) { + if (filter_written && + !std::binary_search(item.written_tiles->begin(), item.written_tiles->end(), + static_cast(p))) { + if (p > UINT64_MAX - kPage) break; + continue; + } + const bool clean_cpu = + is_cpu_view && tracking && (tracking->unwritten(p) || (mirror_just_synced && tracking->hot(p))); + if (!clean_cpu) mark_dirty_page(p); + if (p > UINT64_MAX - kPage) break; + } + } + item.mode = TitleMirrorCheckItem::Mode::full; + item.mirror_va = va; + return true; + }; + + // Pass 1: classify each active item (full mirror vs partial-tile mirror vs CPU fallback) and mark dirty pages. + std::uint64_t pass3_bytes = 0; + std::vector pass3_indices; + pass3_indices.reserve(items.size()); + for (std::size_t i = 0; i < items.size(); ++i) { + TitleMirrorCheckItem& item = items[i]; + item.full_ok = false; + item.single_chunk = false; + item.tile_cmp = 0; + item.reject_reason = 0; + item.mode = TitleMirrorCheckItem::Mode::none; + item.mirror_va = 0; + if (!item.active || !item.bytes) continue; + if (try_full_view(item, item.cpu, true)) { + pass3_bytes += item.bytes; + pass3_indices.push_back(i); + continue; + } + if (item.gpu && item.gpu != item.cpu && try_full_view(item, item.gpu, false)) { + pass3_bytes += item.bytes; + pass3_indices.push_back(i); + continue; + } + + if (item.tile_cmp_written && !item.tile_cmp_written->empty() && item.pieces && + (item.cpu & (kPiece - 1)) == 0 && (item.bytes & (kPiece - 1)) == 0) { + const std::uintptr_t base_tile = static_cast(item.cpu) & ~(leonida::TilePieces::kTile - 1); + bool all_ok = true; + for (const std::uintptr_t tile : *item.tile_cmp_written) { + if (tile < base_tile) { + all_ok = false; + break; + } + const std::size_t idx = (tile - base_tile) / leonida::TilePieces::kTile; + if (idx >= item.pieces->hashes.size()) { + all_ok = false; + break; + } + const std::uint64_t p = static_cast(tile) & ~(kPage - 1); + if (page_in_feed(p) || !mirror.mirrored(p) || (any_pending && mirror.has_pending(p))) { + all_ok = false; + break; + } + } + if (all_ok) { + item.mode = TitleMirrorCheckItem::Mode::partial_tiles; + const bool serial_clean = mirror_just_synced && mirror_synced_serial != 0 && item.ex_armed && + item.max_version <= mirror_synced_serial; + if (!serial_clean) { + for (const std::uintptr_t tile : *item.tile_cmp_written) { + const std::uint64_t p = static_cast(tile) & ~(kPage - 1); + const bool clean_cpu = + tracking && (tracking->unwritten(p) || (mirror_just_synced && tracking->hot(p))); + if (!clean_cpu) mark_dirty_page(p); + } + } + pass3_bytes += std::uint64_t(item.tile_cmp_written->size()) * kPage; + pass3_indices.push_back(i); + } + } + } + + // Pass 2: ONE batched parallel upload across all dirty mirror pages of the pass. + if (need_upload) { + const std::uint64_t failures_before = mirror.counters().upload_failures; + if (page_mirror.readback_in_flight) { + page_mirror.uploads += mirror.upload([this](std::uint8_t* frame, + const std::array& changed) { + note_readback_pieces_uploaded_locked(frame, changed); + }); + } else { + page_mirror.uploads += mirror.upload(); + } + // Do not upload zeroed fallback pieces or poison mirror_hash when hooks_.copy failed mid-sync. + if (mirror.counters().upload_failures != failures_before) return; + } + + // Pass 3: read-only mirror range_sum / chunk_at / partial-tile comparison into disjoint per-item outputs. + // Safe to fan out across title_read_pool() while holding page_mirror.mutex: only reads immutable mirror maps/sums. + const VkSemaphore mirror_timeline = page_mirror.timeline; + const std::uint64_t mirror_value = page_mirror.value; + const auto eval_item = [&](std::size_t slot_idx) { + TitleMirrorCheckItem& item = items[pass3_indices[slot_idx]]; + if (item.mode == TitleMirrorCheckItem::Mode::full) { + std::uint64_t m_hash = 0; + if (!mirror.range_sum(item.mirror_va, item.bytes, m_hash)) return; + VkBuffer buf = VK_NULL_HANDLE; + VkDeviceSize off = 0; + const bool has_chunk = mirror.chunk_at(item.mirror_va, buf, off); + const bool in_one_chunk = has_chunk && item.bytes <= leonida::TitleMirror::kChunk - off; + item.full_ok = true; + item.single_chunk = in_one_chunk; + if (in_one_chunk) { + item.buffer = buf; + item.offset = off; + item.chunk_size = leonida::TitleMirror::kChunk; + item.timeline = mirror_timeline; + item.value = mirror_value; + } + item.mirror_hash = m_hash; + } else if (item.mode == TitleMirrorCheckItem::Mode::partial_tiles) { + const std::uintptr_t base_tile = static_cast(item.cpu) & ~(leonida::TilePieces::kTile - 1); + int cmp = 1; + for (const std::uintptr_t tile : *item.tile_cmp_written) { + const std::size_t idx = (tile - base_tile) / leonida::TilePieces::kTile; + const auto [offset, length] = + leonida::TilePieces::part(static_cast(item.cpu), item.bytes, tile); + if (!length) continue; + std::uint64_t h = 0; + if (!mirror.range_sum(item.cpu + offset, length, h)) { + cmp = 0; + break; + } + if (h != item.pieces->hashes[idx]) { + cmp = -1; + break; + } + } + item.tile_cmp = cmp; + } + }; + constexpr std::uint64_t kParallelRangeSumBytes = 8ull << 20; + if (parallel_run && pass3_indices.size() > 1 && pass3_bytes >= kParallelRangeSumBytes) { + parallel_run(pass3_indices.size(), eval_item); + } else { + for (std::size_t k = 0; k < pass3_indices.size(); ++k) eval_item(k); + } } void DeviceState::title_texture_mapped(const void* resource, std::uint64_t address) { @@ -14492,14 +20101,17 @@ void DeviceState::title_texture_mapped(const void* resource, std::uint64_t addre if (it == title_textures.end() || it->second->resource != resource) return; TitleTexture& t = *it->second; t.mapped = true; - if (async_texture_refresh() && !t.gpu_written) mapped_title_textures[address] = it->second; + t.write_combined_known = false; t.memory.retry(); + index_texture(t); // watched from now on, and looked at by the next refresh // The title computes the layout of what it writes right before it maps: take it when no view gave one. if (!t.gpu_written && (t.layout_guessed || !t.layout_known) && title_xg_layout(*static_cast(resource), t.layout, t.desc)) { t.layout_known = true; t.layout_guessed = false; t.layout_from_xg = true; + t.mirror_hash_valid = false; + t.invalidate_gpu_upload_cache(); index_texture(t); t.hashed = false; } @@ -14528,7 +20140,10 @@ void DeviceState::title_texture_unmapped(const void* resource, std::uint64_t add const auto it = title_textures.find(address); if (it != title_textures.end() && it->second->resource == resource) { it->second->stale = true; + it->second->write_combined_known = false; it->second->memory.retry(); + index_texture(*it->second); + texture_watch.touch(address); } } @@ -14539,9 +20154,14 @@ void DeviceState::title_texture_gone(const void* resource, std::uint64_t address // reads gpu_placements under descriptor_mutex alone, so the placement must not outlive the resource. std::lock_guard descriptors(descriptor_mutex); gpu_placements.remove(address, resource); + note_texture_change(leonida::SlotChange::texture_gone, address); } const auto it = title_textures.find(address); - if (it != title_textures.end() && it->second->resource == resource) it->second->resource = nullptr; + if (it != title_textures.end() && it->second->resource == resource) { + it->second->resource = nullptr; + texture_watch.untrack(address); + } + drop_gpu_owned(resource); titles_gone.push_back({resource, address}); titles_gone_pending.store(true, std::memory_order_release); return; @@ -14550,14 +20170,15 @@ void DeviceState::title_texture_gone(const void* resource, std::uint64_t address { std::lock_guard descriptors(descriptor_mutex); gpu_placements.remove(address, resource); + note_texture_change(leonida::SlotChange::texture_gone, address); } const auto it = title_textures.find(address); if (it != title_textures.end() && it->second->resource == resource) { - texture_ranges.erase(address); - mapped_title_textures.erase(address); + texture_watch.untrack(address); it->second->resource = nullptr; title_textures.erase(it); } + drop_gpu_owned(resource); } void DeviceState::drain_titles_gone() { @@ -14631,8 +20252,59 @@ void note_unknown_tsharp(const leonida::gfx10::ImageWords& words, const leonida: } } -TitleImage bind_title_image(DeviceState& device, const leonida::gfx10::ImageWords& words, const char** why) { +const char* DeviceState::no_texture_reason_locked(const leonida::gfx10::Image& image) { + std::uint64_t lo = 0, hi = 0; + if (leonida::title_va_aliases().title_memory(image.address, lo, hi)) return kTsharpNoTextureTitleMemory; + // The layer's own texture addresses: 1 << 32 and up, 256 apart (Resource::image_address). + constexpr std::uint64_t ours = std::uint64_t(1) << 32; + const std::uint64_t next = next_image_address.load(std::memory_order_relaxed); + if (image.address >= ours && image.address < next) return kTsharpNoTextureGone; + const std::uint64_t low = ours | (image.address & 0xffffffffull); + if (low >= next) return kTsharpNoTextureNothing; + const auto found = images_by_address.find(low); + if (found == images_by_address.end()) return kTsharpNoTextureLow32Gone; + const auto& owner = *static_cast(found->second); + return TitleGpuPlacements::matches(image, owner.desc()) ? kTsharpNoTextureLow32Same + : kTsharpNoTextureLow32Other; +} + +// bind_title_image's binding of the T# to `r`'s image; false with the reason. descriptor_mutex held. +bool bind_title_image_to(DeviceState& device, const leonida::gfx10::ImageWords& words, leonida::gfx10::Image image, + const Resource& r, const char*& reason, leonida::ResourceId& sparse) { + namespace g = leonida::gfx10; + image.address = r.image_address(); // release this key with its actual owner + const D3D12_RESOURCE_DESC& d = r.desc(); + const bool volume = d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; + const bool line = d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D; + const bool msaa = d.SampleDesc.Count > 1; + const UINT layers = volume ? 1 : d.DepthOrArraySize; + const bool type_fits = image.type == g::ImageType::image_3d ? volume + : image.type == g::ImageType::image_1d ? line && image.layer_count == 1 + : g::multisampled(image.type) + ? msaa && !volume && !line && image.samples == d.SampleDesc.Count + : !volume && !line && !msaa; + if (!r.descriptor_image()) return reason = "the texture has no image", false; + if (!type_fits) return reason = "T# type or samples do not fit the texture", false; + if (!msaa && image.first_mip + image.mip_count > d.MipLevels) return reason = "T# names mips the texture lacks", false; + if (image.type == g::ImageType::cube && !(r.format() && layers >= 6)) + return reason = "cube T# on fewer than six layers", false; + if (!volume && image.first_layer + image.layer_count > layers) + return reason = "T# names layers the texture lacks", false; + const bool storage = (d.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) && !msaa && + r.aspects() == VK_IMAGE_ASPECT_COLOR_BIT; + reason = "no view for the T#'s format or range"; // unless set 0 has no room (bind_image) + if (!device.bind_image_locked(words, image, r.descriptor_image(), r.format(), r.aspects(), storage, + r.has_view_format_list(), r.uint_backed(), &reason)) + return false; + r.note_shader_view(); // Include descriptors written directly into title heaps. + if (r.sparse_image()) sparse = r.id(); + return true; +} + +TitleImage bind_title_image(DeviceState& device, const leonida::gfx10::ImageWords& words, const char** why, + std::uint32_t* out_index_word) { namespace g = leonida::gfx10; + if (out_index_word) *out_index_word = 0; const auto refuse = [why](const char* reason) { if (why) *why = reason; return TitleImage::refused; @@ -14646,7 +20318,19 @@ TitleImage bind_title_image(DeviceState& device, const leonida::gfx10::ImageWord { std::lock_guard lock(device.descriptor_mutex); if (!device.bindless) return refuse("no bindless set"); - if (device.image_entries.count(words)) return TitleImage::known; + if (const auto it = device.image_entries.find(words); it != device.image_entries.end()) { + const std::uint64_t gen = ++device.tsharp_use_gen; + it->second.last_seen_gen = gen; + if (const auto sv_it = device.shared_views.find(it->second.view_key); sv_it != device.shared_views.end()) { + sv_it->second.last_seen_gen = gen; + sv_it->second.last_touch_ticket = + device.context ? device.context->submitted_retire_ticket() + 1 : 0; + } + if (out_index_word) + *out_index_word = g::tsharp_index_word( + it->second.index, device.bindless->image_kind_at(it->second.dimension, it->second.index)); + return TitleImage::known; + } if (g::has_hardware_volume_uav_slice_offset(words, image)) return refuse("a title-written 3D UAV with a slice offset is not supported"); auto found = device.images_by_address.find(image.address); @@ -14655,50 +20339,67 @@ TitleImage bind_title_image(DeviceState& device, const leonida::gfx10::ImageWord if (found == device.images_by_address.end()) if (const std::uint64_t other = leonida::title_gpu_views::other_view(image.address)) found = device.images_by_address.find(other); + // A T# the title rebuilt from the low 32 bits of the layer's texture address (tsharp_texture_key): taken only + // with the texture's shape, as those bits alone are a weaker sign than the whole address. + bool by_low_bits = false; + if (found == device.images_by_address.end()) + if (const std::uint64_t key = device.tsharp_texture_key(image.address); key != image.address) { + found = device.images_by_address.find(key); + by_low_bits = true; + } const Resource* owner = found == device.images_by_address.end() ? nullptr : static_cast(found->second); const auto matches = [&](const Resource& r) { return TitleGpuPlacements::matches(image, r.desc()); }; - if (!owner || !matches(*owner)) { - const auto alias = leonida::title_gpu_views::other_view(image.address); - if (auto* candidate = device.gpu_placements.find(image.address, alias, matches)) owner = candidate; + if (owner && by_low_bits && !matches(*owner)) owner = nullptr; + // A GPU-written texture placed at the address (a render target, depth or UAV texture) answers before any + // other texture there: its image holds what the GPU rendered, and the title's pages under it do not, so a + // texture filled from them shows nothing the GPU drew. Compatible: the T#'s extent and samples, and mips and + // layers within the target's (TitleGpuPlacements::matches); the format is any the target's image takes a view + // in (bind_image_locked: its own, a castable one, or one of the same block size its view list allows). With + // none, the other texture answers as before (counted by reason in the title texture refresh's line). + const auto alias = leonida::title_gpu_views::other_view(image.address); + Resource* gpu = by_low_bits ? nullptr : device.gpu_placements.find(image.address, alias, matches); + const Resource* plain = owner && owner != gpu ? owner : nullptr; + if (gpu) { + owner = gpu; + } else if (plain && !by_low_bits) { + if (const Resource* any = device.gpu_placements.find(image.address, alias, [](const Resource&) { return true; })) { + const D3D12_RESOURCE_DESC& d = any->desc(); + const bool extent = d.Width != image.width || d.Height != image.height || + (d.SampleDesc.Count > 1) != g::multisampled(image.type); + ++device.over_gpu_target[extent ? DeviceState::kOverTargetExtent : DeviceState::kOverTargetRange]; + } } if (!owner) { - if (why) *why = "no texture at T# address"; + if (why) *why = device.no_texture_reason_locked(image); note_unknown_tsharp(words, image); return TitleImage::unknown; } - const Resource& r = *owner; - image.address = r.image_address(); // release this key with its actual owner - const D3D12_RESOURCE_DESC& d = r.desc(); - const bool volume = d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; - const bool line = d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D; - const bool msaa = d.SampleDesc.Count > 1; - const UINT layers = volume ? 1 : d.DepthOrArraySize; - const bool type_fits = image.type == g::ImageType::image_3d ? volume - : image.type == g::ImageType::image_1d ? line && image.layer_count == 1 - : g::multisampled(image.type) - ? msaa && !volume && !line && image.samples == d.SampleDesc.Count - : !volume && !line && !msaa; - if (!r.descriptor_image()) return refuse("the texture has no image"); - if (!type_fits) return refuse("T# type or samples do not fit the texture"); - if (!msaa && image.first_mip + image.mip_count > d.MipLevels) return refuse("T# names mips the texture lacks"); - if (image.type == g::ImageType::cube && !(r.format() && layers >= 6)) - return refuse("cube T# on fewer than six layers"); - if (!volume && image.first_layer + image.layer_count > layers) - return refuse("T# names layers the texture lacks"); - const bool storage = (d.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) && !msaa && - r.aspects() == VK_IMAGE_ASPECT_COLOR_BIT; - const char* unbound = "no view for the T#'s format or range"; // unless set 0 has no room (bind_image) - if (!device.bind_image_locked(words, image, r.descriptor_image(), r.format(), r.aspects(), storage, - r.has_view_format_list(), r.uint_backed(), &unbound)) - return refuse(unbound); - r.note_shader_view(); // Include descriptors written directly into title heaps. - if (r.sparse_image()) sparse = r.id(); + struct TitleHeapBindGuard { + bool& flag; + bool prev; + explicit TitleHeapBindGuard(bool& f) : flag(f), prev(f) { flag = true; } + ~TitleHeapBindGuard() { flag = prev; } + } title_guard(device.binding_from_title_heap); + const char* reason = nullptr; + if (bind_title_image_to(device, words, image, *owner, reason, sparse)) { + if (owner == gpu && plain) ++device.over_gpu_target[DeviceState::kOverTargetResolved]; + } else if (owner == gpu && plain) { + ++device.over_gpu_target[DeviceState::kOverTargetFormat]; + if (!bind_title_image_to(device, words, image, *plain, reason, sparse)) return refuse(reason); + } else { + return refuse(reason); + } + if (out_index_word) *out_index_word = device.tsharp_index_word_locked(words); } if (sparse) device.context->note_shader_image(sparse); return TitleImage::bound; } +TitleImage bind_title_image(DeviceState& device, const leonida::gfx10::ImageWords& words, const char** why) { + return bind_title_image(device, words, why, nullptr); +} + bool image_descriptor(const Resource& resource, const TextureView& asked, bool storage, leonida::gfx10::Image& out, VkFormat& view_format, DeviceState::VolumeSlices& slices) { TextureView view = asked; @@ -15311,10 +21012,55 @@ class Device final if (auto* fault = state_.context->device_fault()) fault->set_lost_hook([this] { rt::compute_probe::recheck(state_); }); } - if (async_texture_refresh()) start_title_filler(); state_.setup_console_heap_gpu(get_device); // LEONIDA_CONSOLE_HEAP_GPU: the context's prelude - state_.context->set_after_execute([this] { state_.geometry_execute_end(); }); - state_.context->set_before_execute([this] { + state_.context->set_on_enqueue_execute([this] { + return state_.geometry.execute_enqueue(); + }); + state_.context->set_on_finish_execute([this](std::uint64_t serial) { + if (serial) { + state_.geometry.execute_end(serial, [this] { return state_.context->submitted_retire_ticket(); }); + state_.stamp_retired_windows(); + } + }); + state_.context->set_on_buffer_write_submitted([this](std::uint64_t ticket) { + state_.promote_passive_title_writes(ticket); + }); + state_.context->set_after_execute([this] { state_.end_execute_write_back(); }); + // Cross-queue single-flight visibility coalescer for before_execute_(): + // Only one queue worker at a time runs the global refresh sequence (eliminating page_mirror.mutex <-> + // console_heap_mutex <-> title_texture_mutex lock convoys across Direct + 4 Compute queues), and any + // concurrent or back-to-back submission whose required visibility epoch `req_seq` (captured at enqueue time + // and updated on any queue/CPU fence Signal) was already covered by a refresh pass that STARTED at + // `pass_seq >= req_seq` skips the redundant global refresh completely while keeping begin/end_execute_write_back + // paired for every submission. Disable with LEONIDA_BEFORE_EXECUTE_COALESCE=0. + struct BeforeExecuteCoalescer { + std::mutex mutex; + std::condition_variable cv; + bool in_flight = false; + std::uint64_t completed_seq = 0; + std::uint64_t ran = 0; + std::uint64_t coalesced = 0; + std::uint64_t wait_count = 0; + std::uint64_t wait_ns = 0; + std::uint64_t wb_ns = 0; + std::uint64_t mirror_ns = 0; + std::uint64_t shadows_ns = 0; + std::uint64_t flush_ns = 0; + std::uint64_t tex_ns = 0; + std::atomic feed_drains{0}; + std::atomic feed_drain_ns{0}; + std::chrono::steady_clock::time_point since = std::chrono::steady_clock::now(); + }; + auto before_coalescer = std::make_shared(); + state_.context->set_before_execute([this, coalescer = std::move(before_coalescer)] { + state_.begin_execute_write_back(); + static thread_local bool t_in_before_execute = false; // trivially destructible (no TLS callback) + if (t_in_before_execute) return; + struct ReentryGuard { + bool& flag; + explicit ReentryGuard(bool& f) noexcept : flag(f) { flag = true; } + ~ReentryGuard() { flag = false; } + } reentry_guard{t_in_before_execute}; namespace phases = leonida::submit_phases; // LEONIDA_REFRESH_PER_FRAME (for runs that only need the title to go on): 1 = the slot-133 shadows, title // windows and geometry copies are brought up to date only by the first submission after each present, @@ -15326,13 +21072,145 @@ class Device final const char* v = std::getenv("LEONIDA_REFRESH_PER_FRAME"); return v && *v ? std::atoi(v) : 0; }(); - state_.geometry_execute_begin(); + static const bool coalesce_enabled = [] { + const char* v = std::getenv("LEONIDA_BEFORE_EXECUTE_COALESCE"); + return !(v && v[0] == '0' && v[1] == '\0'); + }(); + const std::uint64_t req_seq = leonida::VulkanContext::current_before_execute_seq(); + const bool use_coalesce = coalesce_enabled && !per_frame && req_seq != 0; + std::uint64_t pass_seq = 0; + struct LeaderGuard { + BeforeExecuteCoalescer* c = nullptr; + std::uint64_t pass_seq = 0; + std::uint64_t wb_ns = 0; + std::uint64_t mirror_ns = 0; + std::uint64_t shadows_ns = 0; + std::uint64_t flush_ns = 0; + std::uint64_t tex_ns = 0; + bool completed = false; + ~LeaderGuard() { + if (!c) return; + bool log = false; + std::uint64_t ran = 0, coalesced = 0, waits = 0, wait_ns = 0; + std::uint64_t s_wb = 0, s_mirror = 0, s_shadows = 0, s_flush = 0, s_tex = 0; + std::uint64_t fd_cnt = 0, fd_ns = 0; + double secs = 0.0; + { + std::lock_guard lock(c->mutex); + if (completed && pass_seq > c->completed_seq) c->completed_seq = pass_seq; + ++c->ran; + c->wb_ns += wb_ns; + c->mirror_ns += mirror_ns; + c->shadows_ns += shadows_ns; + c->flush_ns += flush_ns; + c->tex_ns += tex_ns; + c->in_flight = false; + const auto now = std::chrono::steady_clock::now(); + secs = std::chrono::duration(now - c->since).count(); + if (secs >= 10.0 && c->ran > 0) { + ran = c->ran; + coalesced = c->coalesced; + waits = c->wait_count; + wait_ns = c->wait_ns; + s_wb = c->wb_ns; + s_mirror = c->mirror_ns; + s_shadows = c->shadows_ns; + s_flush = c->flush_ns; + s_tex = c->tex_ns; + fd_cnt = c->feed_drains.exchange(0, std::memory_order_relaxed); + fd_ns = c->feed_drain_ns.exchange(0, std::memory_order_relaxed); + c->ran = c->coalesced = c->wait_count = c->wait_ns = 0; + c->wb_ns = c->mirror_ns = c->shadows_ns = c->flush_ns = c->tex_ns = 0; + c->since = now; + log = true; + } + } + c->cv.notify_all(); + if (log) { + const std::uint64_t total = ran + coalesced; + const double inv_ran = ran ? 1e-6 / double(ran) : 0.0; + const double sum_ms = double(s_wb + s_mirror + s_shadows + s_flush + s_tex) * inv_ran; + std::fprintf(stderr, + "[rt] before-execute: %llu ran, %llu coalesced (%.0f%% skipped) in %.1f s; " + "%llu single-flight waits (%.2f ms avg); %llu feed-only drains (%.2f ms avg); " + "leader avg %.2f ms (wb %.2f, mirror %.2f, shadows %.2f, flush %.2f, tex %.2f)\n", + static_cast(ran), static_cast(coalesced), + total ? 100.0 * double(coalesced) / double(total) : 0.0, secs, + static_cast(waits), + waits ? double(wait_ns) * 1e-6 / double(waits) : 0.0, + static_cast(fd_cnt), + fd_cnt ? double(fd_ns) * 1e-6 / double(fd_cnt) : 0.0, sum_ms, + double(s_wb) * inv_ran, double(s_mirror) * inv_ran, double(s_shadows) * inv_ran, + double(s_flush) * inv_ran, double(s_tex) * inv_ran); + } + } + } leader_guard{}; + if (use_coalesce) { + std::unique_lock lock(coalescer->mutex); + while (coalescer->in_flight && coalescer->completed_seq < req_seq) { + const std::int64_t wait_start = phases::now_ns(); + coalescer->cv.wait(lock, [&] { return !coalescer->in_flight || coalescer->completed_seq >= req_seq; }); + const std::uint64_t waited = std::uint64_t(phases::now_ns() - wait_start); + phases::add_part(phases::part_lock_wait, waited); + ++coalescer->wait_count; + coalescer->wait_ns += waited; + } + if (coalescer->completed_seq >= req_seq) { + ++coalescer->coalesced; + lock.unlock(); + const std::int64_t fd0 = phases::now_ns(); + if (state_.drain_page_mirror_feed_only()) { + const std::uint64_t fd_ns = std::uint64_t((std::max)(std::int64_t(0), phases::now_ns() - fd0)); + coalescer->feed_drains.fetch_add(1, std::memory_order_relaxed); + coalescer->feed_drain_ns.fetch_add(fd_ns, std::memory_order_relaxed); + } + return; + } + coalescer->in_flight = true; + leader_guard.c = coalescer.get(); + leader_guard.pass_seq = req_seq; + } + const std::int64_t t0 = phases::now_ns(); + std::int64_t t1 = t0, t2 = t0; + std::uint64_t mirror_serial = 0; + { + const phases::Scope timed(phases::shadows); + // First, while pending_ sparse binds are empty and before any map()/upload() mutates homes or agreed + // sums: copy retired GPU writes back to their physical frames. + state_.write_back_titles(); + t1 = phases::now_ns(); + if (use_coalesce) { + // Acquire current visibility epoch AFTER write_back_titles() and immediately BEFORE + // refresh_page_mirror() so batches enqueued during write_back_titles() coalesce into this single + // pass. + pass_seq = (std::max)(req_seq, state_.context->current_visibility_seq()); + leader_guard.pass_seq = pass_seq; + } + mirror_serial = leonida::geometry_writes::state().serial.load(std::memory_order_acquire); + state_.refresh_page_mirror(); // what this submission's title-written addresses read + t2 = phases::now_ns(); + } + // Flush sparse binds and run title texture refresh immediately after refresh_page_mirror() so concurrent + // xmem remaps during refresh_shadows()/geometry.refresh() do not force in_feed CPU fallbacks, and so + // newly-published streamed textures bind on the same submission in refresh_shadows() below. + { + const phases::Scope timed(phases::shadows); + state_.flush_page_mirror(); + } + const std::int64_t t_flush1 = phases::now_ns(); + { + const phases::Scope timed(phases::textures); + refresh_title_textures(/*mirror_just_synced=*/true, mirror_serial); + } + const std::int64_t t_tex1 = phases::now_ns(); bool full = true; if (per_frame) { const std::uint64_t serial = phases::totals().present_serial.load(std::memory_order_relaxed); full = refreshed_present_.exchange(serial, std::memory_order_relaxed) != serial; } state_.drain_geometry_releases(); + state_.reclaim_retired_windows(); + state_.reclaim_arena(); state_.refresh_shadows(full || per_frame < 2, full); state_.retire_orphan_windows(); // LEONIDA_GEOMETRY_ASYNC=1 (for runs that only need the title to go on): the geometry copies are brought @@ -15351,15 +21229,29 @@ class Device final } // 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) { - fill_first_mapped_textures(); - request_title_refresh(); + const std::int64_t t_shadows = phases::now_ns(); + // Mandatory 2nd O(1) flush for any plain-page sparse binds added by finish_in_place() -> fix_vsharp(). + { + const phases::Scope timed(phases::shadows); + state_.flush_page_mirror(); + } + const std::int64_t t_flush2 = phases::now_ns(); + std::uint64_t tex2_ns = 0; + // Mandatory trailing texture refresh only if refresh_shadows() newly named a first-time slot-133 texture. + if (state_.titles_named_pending.load(std::memory_order_acquire)) { + const std::int64_t t_tex2_start = phases::now_ns(); + { + const phases::Scope timed(phases::textures); + refresh_title_textures(/*mirror_just_synced=*/true, mirror_serial); } - } else { - refresh_title_textures(); - } + tex2_ns = std::uint64_t(phases::now_ns() - t_tex2_start); + } + leader_guard.wb_ns = std::uint64_t(t1 - t0); + leader_guard.mirror_ns = std::uint64_t(t2 - t1); + leader_guard.shadows_ns = std::uint64_t(t_shadows - t_tex1); + leader_guard.flush_ns = std::uint64_t(t_flush1 - t2) + std::uint64_t(t_flush2 - t_shadows); + leader_guard.tex_ns = std::uint64_t(t_tex1 - t_flush1) + tex2_ns; + leader_guard.completed = true; }); { char text[16] = {}; @@ -15378,8 +21270,96 @@ class Device final if (!threads.valid) std::fprintf(stderr, "[rt] d3d12: LEONIDA_PIPELINE_THREADS=%s is not a number; using %u\n", text, threads.count); - if (threads.count) - state_.context->set_pipeline_workers(std::make_unique(threads.count)); + if (present) { + if (threads.count) + state_.context->set_pipeline_workers(std::make_unique(threads.count)); + } else { + // Default (LEONIDA_PIPELINE_THREADS unset): fan out batch-parallel synchronous pipeline compiles + // concurrently onto PipelineCompiler::instance() worker threads (with work-stealing on the calling + // thread and deadlock-free RAII fallback if PipelineCompiler::closed() or cancel()/stop_for_exit() + // races), avoiding an extra idle thread pool while giving full multi-core cold-compile scaling. + state_.context->set_batch_compile_runner( + [device_key = static_cast(&state_)](std::size_t count, + const std::function& job) { + if (!count) return; + auto& compiler = PipelineCompiler::instance(); + if (count == 1 || compiler.closed()) { + for (std::size_t i = 0; i < count; ++i) job(i); + return; + } + struct BatchState { + std::atomic next{0}; + std::size_t count = 0; + const std::function* job = nullptr; + std::vector owner_tags; + std::mutex mutex; + std::condition_variable cv; + std::size_t pending_helpers = 0; + std::exception_ptr error{}; + std::size_t error_index = SIZE_MAX; + }; + auto run_work = [](BatchState& s) { + for (;;) { + const std::size_t i = s.next.fetch_add(1, std::memory_order_relaxed); + if (i >= s.count) break; + try { + (*s.job)(i); + } catch (...) { + std::lock_guard lock(s.mutex); + if (!s.error || i < s.error_index) { + s.error = std::current_exception(); + s.error_index = i; + } + } + } + }; + struct HelperDone { + std::shared_ptr state; + explicit HelperDone(std::shared_ptr s) : state(std::move(s)) { + std::lock_guard lock(state->mutex); + ++state->pending_helpers; + } + ~HelperDone() { + if (!state) return; + std::lock_guard lock(state->mutex); + if (--state->pending_helpers == 0) state->cv.notify_all(); + } + }; + auto state = std::make_shared(); + state->count = count; + state->job = &job; + const std::size_t helpers = + (std::min)(count - 1, std::size_t(leonida::PipelineWorkers::kMaxThreads)); + state->owner_tags.resize(helpers, 0); + { + struct WaitHelpers { + PipelineCompiler& compiler; + std::shared_ptr state; + std::size_t submitted_helpers = 0; + ~WaitHelpers() { + // Drop any unstarted helper lambdas immediately so we never stall behind unrelated + // long compiles in PipelineCompiler::jobs_; only wait on helpers already running + // a job from this batch. + for (std::size_t k = 0; k < submitted_helpers; ++k) + compiler.cancel(&state->owner_tags[k]); + std::unique_lock lock(state->mutex); + state->cv.wait(lock, [&] { return state->pending_helpers == 0; }); + } + } wait_guard{compiler, state, 0}; + for (std::size_t k = 0; k < helpers; ++k) { + auto done = std::make_shared(state); + const bool queued = compiler.submit( + &state->owner_tags[k], device_key, 0, + [done = std::move(done), run_work] { run_work(*done->state); }, + /*graphics=*/true, /*large=*/false); + if (!queued) break; + ++wait_guard.submitted_helpers; + } + run_work(*state); + } + if (state->error) std::rethrow_exception(state->error); + }); + } if (big_compiles() == BigCompiles::budget) state_.context->set_large_compiles( [] { return big_compile_gate().budget(); }, @@ -15488,22 +21468,24 @@ class Device final std::lock_guard lock(d.shadow_mutex); shadows = d.shadows.size(); } - VkDeviceSize in_use = 0, peak = 0, use[4] = {}; + VkDeviceSize in_use = 0, peak = 0, use[DeviceState::arena_use_count] = {}; { std::lock_guard lock(d.arena.mutex); in_use = d.arena.in_use; peak = d.arena.peak_end; - for (int i = 0; i < 4; ++i) use[i] = d.arena.use_in_use[i]; + for (int i = 0; i < DeviceState::arena_use_count; ++i) use[i] = d.arena.use_in_use[i]; } char text[512]; std::snprintf(text, sizeof text, "pipeline cache %.0f MiB; arena %.0f MiB (type %u), in use %.0f MiB (buffer %.0f, " - "descriptor heap %.0f, shader %.0f, heap %.0f), peak end %.0f MiB; title memory %llu " - "ranges %.0f MiB reserved/committed VA; shadows %llu; fsdraw pipeline notes %zu", + "descriptor heap %.0f, shader %.0f, heap %.0f, windows/shadows %.0f), peak end %.0f MiB; " + "title memory %llu ranges %.0f MiB reserved/committed VA; shadows %llu; fsdraw pipeline " + "notes %zu", leonida::mem_probe::mib(cache), leonida::mem_probe::mib(d.arena.size), d.arena.memory_type, leonida::mem_probe::mib(in_use), leonida::mem_probe::mib(use[0]), leonida::mem_probe::mib(use[1]), leonida::mem_probe::mib(use[2]), - leonida::mem_probe::mib(use[3]), leonida::mem_probe::mib(peak), + leonida::mem_probe::mib(use[3]), + leonida::mem_probe::mib(use[DeviceState::arena_window]), leonida::mem_probe::mib(peak), (unsigned long long)title_ranges, leonida::mem_probe::mib(title), (unsigned long long)shadows, leonida::fsdraw::pipeline_count()); return std::string(text); @@ -15515,9 +21497,20 @@ class Device final share.arena = true; std::lock_guard lock(d.arena.mutex); share.arena_reserved = d.arena.size; - share.arena_bound = d.arena.size; // one allocation behind the whole range + share.arena_bound = d.arena.backing.stats().bound; share.arena_in_use = d.arena.in_use; for (std::size_t i = 0; i < share.arena_use.size(); ++i) share.arena_use[i] = d.arena.use_in_use[i]; + share.arena_windows = d.arena.use_in_use[DeviceState::arena_window]; + } + if (d.page_mirror.mirror) { + std::lock_guard held(d.page_mirror.mutex); + const auto c = d.page_mirror.mirror->counters(); + share.mirror = true; + share.mirror_homes = c.homes; + share.mirror_pages = c.pages; + share.mirror_chunks = c.chunks; + share.mirror_units_local = d.page_mirror.units_local; + share.mirror_units_host = d.page_mirror.units_host; } std::lock_guard lock(d.descriptor_mutex); // the bindless set's lock (ExecuteCommandLists' flush) if (const auto* bindless = d.bindless.get()) share.bindless_table_bytes = bindless->table_buffer_bytes(); @@ -15619,6 +21612,7 @@ class Device final const bool can_resolve = (family.queueFlags & (VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT)) != 0; state_.timestamp_bits.push_back(can_resolve ? family.timestampValidBits : 0); } + state_.context->set_timestamp_bits(state_.timestamp_bits); // the queues LEONIDA_GPU_PROFILE can time if (info.queue_family < family_count) { const auto& family = families[info.queue_family]; if (family.timestampValidBits) @@ -15663,7 +21657,7 @@ class Device final info.queue_family < family_count && (families[info.queue_family].queueFlags & VK_QUEUE_SPARSE_BINDING_BIT); state_.sparse_image_tiles = sparse_aliasing && info.features.sparseResidencyImage2D && state_.context->vk.vkGetImageSparseMemoryRequirements; - if (sparse_aliasing && state_.arena.memory && info.features.sparseResidencyBuffer) { + if (sparse_aliasing && state_.arena_ready() && info.features.sparseResidencyBuffer) { auto& vk = state_.context->vk; const auto sparse_info = state_.sparse_buffer_info(leonida::tile_size_in_bytes); VkBuffer sample = VK_NULL_HANDLE; @@ -15675,6 +21669,7 @@ class Device final state_.sparse_buffer_memory_types = requirements.memoryTypeBits; } } + state_.create_page_mirror(sparse_aliasing && info.features.sparseResidencyBuffer); } // Set 0 of every translated shader that declares bindings: images, samplers and the descriptor hash table @@ -15745,6 +21740,25 @@ class Device final leonida::descriptor_table_layout_name(descriptor_table), table_modules.total()); } state_.descriptor_table_tagged = descriptor_table == leonida::DescriptorTableLayout::tagged; + // Whether the loaded modules read a T#'s index from its dword 6 (shader_library.h, TsharpIndexCensus): one such + // module needs the word in every heap. Older modules find heap T#s by their words in the hash table, which the + // word changes, so a library with both kinds is reported: its older modules read the fallback for those T#s. + if (const leonida::ShaderLibrary* library = state_.library()) { + const leonida::TsharpIndexCensus& census = library->tsharp_index_census(); + state_.tsharp_index_words = census.dword6 > 0; + if (census.dword6 && census.none) + std::fprintf(stderr, + "[rt] d3d12: T# index word: %zu modules read it, %zu older ones look heap T#s up in the " + "hash table and miss them (the heaps carry the word); translate the library again\n", + census.dword6, census.none); + else + std::fprintf(stderr, "[rt] d3d12: T# index word: %s (all %zu modules)\n", + census.dword6 ? "written into the heaps' T#s" : "not read", census.total()); + const leonida::WritesBufferCensus& wb_census = library->writes_buffer_census(); + std::fprintf(stderr, "[rt] d3d12: writes_buffer metadata: %s (%zu of %zu modules)\n", + wb_census.all_present() ? "gating passive mirror write-back" : "incomplete (conservative write-back)", + wb_census.present, wb_census.total()); + } const auto get_properties = reinterpret_cast( state_.info.get_instance_proc(state_.info.instance, "vkGetPhysicalDeviceProperties2")); if (get_properties) { @@ -15806,12 +21820,37 @@ class Device final state_.context->set_bindless_release( [](void* user, std::uint32_t dim, std::uint32_t idx) { auto* st = static_cast(user); - std::lock_guard lock(st->descriptor_mutex); - if (st->bindless) st->bindless->remove_image(static_cast(dim), idx); + bool notify_room = false; + { + std::lock_guard lock(st->descriptor_mutex); + if (st->bindless) { + const auto dimension = static_cast(dim); + const bool check_2d_mirror = dimension != leonida::ImageDimension::dim_2d; + const bool was_sampled_full = st->bindless->free_images(dimension) == 0; + const bool was_storage_full = st->bindless->storage_capacity(dimension) > 0 && + st->bindless->free_storage_images(dimension) == 0; + const bool was_2d_sampled_full = + check_2d_mirror && st->bindless->free_images(leonida::ImageDimension::dim_2d) == 0; + const bool was_2d_storage_full = + check_2d_mirror && + st->bindless->storage_capacity(leonida::ImageDimension::dim_2d) > 0 && + st->bindless->free_storage_images(leonida::ImageDimension::dim_2d) == 0; + st->bindless->remove_image(dimension, idx); + notify_room = + (was_sampled_full && st->bindless->free_images(dimension) > 0) || + (was_storage_full && st->bindless->free_storage_images(dimension) > 0) || + (was_2d_sampled_full && st->bindless->free_images(leonida::ImageDimension::dim_2d) > 0) || + (was_2d_storage_full && + st->bindless->free_storage_images(leonida::ImageDimension::dim_2d) > 0); + } + } + if (notify_room) st->note_slot_change(leonida::SlotChange::texture_room, 0, 1); }, &state_); state_.context->set_bindless_prepare([this](VkCommandBuffer command_buffer) { + if (!state_.bindless->needs_prepare()) return true; std::unique_lock lock(state_.descriptor_mutex); + if (!state_.bindless->needs_prepare()) return true; if (!state_.bindless->fallbacks_ready()) state_.bindless->record_fallback_init(command_buffer); auto& context = *state_.context; if (state_.bindless_legacy_idle && state_.bindless->flush_replaces_table()) { @@ -15852,8 +21891,10 @@ class Device final // and retries, rewrites the table in place when nothing runs, or keeps the previous table (vulkan_bindless.h). auto& set = *state_.bindless; const std::uint64_t host_fallbacks = set.table_host_fallbacks(); + const std::uint32_t free_before_flush = set.total_free_images(); const bool flushed = set.flush(command_buffer, context.submitted_retire_ticket(), [&context] { return context.completed_retire_ticket(); }); + const bool freed_by_flush = flushed && set.total_free_images() > free_before_flush; if (flushed && set.last_flush_replaced()) context.note_bindless_upload(); const auto table_state = [&] { return std::to_string(set.table().size()) + " of " + std::to_string(set.table().capacity()) + @@ -15861,7 +21902,8 @@ class Device final (set.table_in_device_local_memory() ? "device-local" : "host") + " memory; " + std::to_string(set.generations_made()) + " generations made, " + std::to_string(set.retired_count()) + " retired, " + std::to_string(set.spare_count()) + - " spare, " + std::to_string(set.spares_reused()) + " reused"; + " spare, " + std::to_string(set.spares_reused()) + " reused; " + + state_.bindless_diag_summary_locked(); }; if (set.table_buffer_bytes() != state_.bindless_logged_table_bytes) { state_.bindless_logged_table_bytes = set.table_buffer_bytes(); @@ -15882,11 +21924,12 @@ class Device final set.last_failure() ? set.last_failure() : "?", int(set.last_failure_result()), static_cast(n), table_state().c_str()); } + lock.unlock(); + if (freed_by_flush) state_.note_slot_change(leonida::SlotChange::texture_room, 0, 1); return flushed; }); state_.context->set_bindless_current([this]() { - std::lock_guard lock(state_.descriptor_mutex); - return state_.bindless ? state_.bindless->set() : VK_NULL_HANDLE; + return state_.bindless ? state_.bindless->current_set() : VK_NULL_HANDLE; }); { char text[8] = {}; @@ -15895,6 +21938,7 @@ class Device final text[0] != '0'; } state_.context->set_bindless_commit([this](bool submitted) { + if (!state_.bindless || !state_.bindless->needs_commit()) return; std::lock_guard lock(state_.descriptor_mutex); if (state_.bindless) state_.bindless->table_upload_result(submitted); }); @@ -15917,11 +21961,49 @@ class Device final set = n > 0 && n < sizeof(text); if (set) std::fprintf(stderr, "[rt] d3d12: LEONIDA_ARENA_MB was read from the process environment, not the CRT's\n"); } - const leonida::ArenaLimits limits{state_.info.max_buffer_size, state_.info.max_memory_allocation_size}; + // A sparse buffer where the device can bind one on a queue of its own (src/arena_backing.h): memory is then + // bound in blocks as allocations need it, and maxMemoryAllocationSize bounds a block, not the arena. A device + // without it, or whose sparse address space is smaller than the arena (llvmpipe: 2 GiB), keeps one + // allocation behind the whole arena, reached through the same accessors. + // + // Every buffer outside the arena that a shader reaches (geometry copies, title windows and shadows outside it, + // upload and readback buffers) is named by its device address minus heap_base, in a V#'s 48 bits and in root + // views. A driver may place a sparse buffer anywhere relative to ordinary ones: RADV gives sparse buffers a + // range of their own 64 TiB above them (Mesa 26.3.1: 0xffffc00100200000 against 0xffff800100010000), so with a + // sparse arena every other buffer has a negative offset. Shaders that sign-extend the 48-bit base reach it + // (every address RADV hands out lies in one 2^47 half of the 48-bit space, so any two are within 2^47 of + // each other); older ones, which zero-extend, do not. So the arena is sparse only when every loaded module + // sign-extends (VsharpBaseCensus), and each block outside it is checked against that range when it is made. + leonida::VsharpBaseCensus bases{}; + if (const leonida::ShaderLibrary* library = state_.library()) bases = library->vsharp_base_census(); + g_pack_signed_vsharp_offsets.store(bases.signed_offsets(), std::memory_order_relaxed); + std::fprintf(stderr, "[rt] d3d12: V# bases: %s offsets from heap_base (%zu of %zu modules sign-extend)%s\n", + signed_vsharp_offsets() ? "signed" : "unsigned", bases.sign_extended, bases.total(), + import_below_arena() && !bases.signed_offsets() ? " (LEONIDA_IMPORT_BELOW_ARENA)" : ""); + const bool sparse_capable = state_.info.arena_bind_queue && state_.info.features.sparseBinding && + state_.info.features.sparseResidencyBuffer && + state_.info.residency_non_resident_strict && vk.vkQueueBindSparse; + state_.arena_sparse_capable = sparse_capable; + if (sparse_capable && !signed_vsharp_offsets()) + std::fprintf(stderr, "[rt] d3d12: GPU address arena: one allocation, not sparse: %zu of the %zu loaded " + "modules read a V# base unsigned, so no buffer may lie below the arena (translate the " + "shaders again to bind the arena's memory as it is used)\n", + bases.zero_extended, bases.total()); + const leonida::ArenaLimits sparse_limits{state_.info.max_buffer_size, 0}; + const bool sparse = + sparse_capable && signed_vsharp_offsets() && + leonida::decide_arena_size(set ? text : nullptr, sparse_limits).bytes <= state_.info.sparse_address_space; + const leonida::ArenaLimits limits = + sparse ? sparse_limits + : leonida::ArenaLimits{state_.info.max_buffer_size, state_.info.max_memory_allocation_size}; leonida::ArenaSize size = leonida::decide_arena_size(set ? text : nullptr, limits); auto& arena = state_.arena; VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; info.size = size.bytes; + if (sparse) + info.flags = VK_BUFFER_CREATE_SPARSE_BINDING_BIT | VK_BUFFER_CREATE_SPARSE_RESIDENCY_BIT | + // A D3D12 heap in the arena lends its blocks' memory to reserved resources' tiles too. + (state_.info.features.sparseResidencyAliased ? VK_BUFFER_CREATE_SPARSE_ALIASED_BIT : 0); info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT | @@ -15959,8 +22041,9 @@ class Device final } } // With Resizable BAR, keep the arena where its buffer may still use DEVICE_LOCAL | HOST_VISIBLE memory - // A large buffer can exclude that type, or require more bytes than its heap can hold. - if (leonida::resizable_bar(state_.memory)) { + // A large buffer can exclude that type, or require more bytes than its heap can hold. (A sparse arena's memory + // comes in blocks, which any heap holds.) + if (!sparse && leonida::resizable_bar(state_.memory)) { const VkDeviceSize asked = info.size; const VkDeviceSize fitted = leonida::device_local_arena_bytes(asked, [&](VkDeviceSize bytes) { if (bytes == asked) return leonida::device_local_arena_fits(state_.memory, requirements); @@ -15987,25 +22070,86 @@ class Device final "device's %s\n", static_cast(size.bytes >> 20), static_cast(size.requested >> 20), leonida::arena_cap_name(size.capped)); - { - leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::arena); - arena.memory = state_.allocate(requirements, leonida::kArenaRequiredMemory, - leonida::kArenaPreferredMemory, nullptr, true, &arena.memory_type); - } - void* mapped = nullptr; - if (!arena.memory || vk.vkBindBufferMemory(state_.info.device, arena.buffer, arena.memory, 0) != VK_SUCCESS || - vk.vkMapMemory(state_.info.device, arena.memory, 0, VK_WHOLE_SIZE, 0, &mapped) != VK_SUCCESS) { - // Without an arena every buffer keeps its own memory; a leftover handle would make them addressable - // with heap base 0, so their VAs would be raw device addresses above 4 GiB. - vk.vkDestroyBuffer(state_.info.device, arena.buffer, nullptr); - if (arena.memory) vk.vkFreeMemory(state_.info.device, arena.memory, nullptr); - arena.buffer = VK_NULL_HANDLE; - arena.memory = VK_NULL_HANDLE; - return false; + if (sparse) { + DeviceState* const st = &state_; + leonida::ArenaBackingHooks hooks; + // A unit's memory: the arena's memory type (the first unit picks it, as the one allocation did), with a + // device address, mapped once for its life. + hooks.make = [st, requirements](VkDeviceSize bytes, VkDeviceMemory& memory, std::uint8_t*& host) { + VkMemoryRequirements unit = requirements; + unit.size = bytes; + if (st->arena.memory_type_known) unit.memoryTypeBits &= 1u << st->arena.memory_type; + std::uint32_t type = 0; + { + leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::arena); + memory = st->allocate(unit, leonida::kArenaRequiredMemory, leonida::kArenaPreferredMemory, + nullptr, true, &type); + } + void* mapped = nullptr; + if (!memory) return false; + if (st->context->vk.vkMapMemory(st->info.device, memory, 0, VK_WHOLE_SIZE, 0, &mapped) != VK_SUCCESS) { + st->context->vk.vkFreeMemory(st->info.device, memory, nullptr); + memory = VK_NULL_HANDLE; + return false; + } + host = static_cast(mapped); + if (!st->arena.memory_type_known) { + st->arena.memory_type = type; + st->arena.memory_type_known = true; + } + return true; + }; + hooks.destroy = [st](VkDeviceMemory memory) { + st->context->vk.vkFreeMemory(st->info.device, memory, nullptr); + }; + // On the arena's own queue, which nothing else uses (VulkanDeviceInfo::arena_bind_queue): idle means + // this bind is done, so the range is bound (or unbound) before the allocation is handed out (or the + // memory freed). Under the arena's lock, the only place binds are made, which is the queue's external + // synchronisation. + hooks.bind = [st](const VkSparseMemoryBind* binds, std::uint32_t count) { + auto& f = st->context->vk; + const VkSparseBufferMemoryBindInfo buffer_binds{st->arena.buffer, count, binds}; + VkBindSparseInfo bind{VK_STRUCTURE_TYPE_BIND_SPARSE_INFO}; + bind.bufferBindCount = 1; + bind.pBufferBinds = &buffer_binds; + VkResult result = st->context->observe_result( + f.vkQueueBindSparse(st->info.arena_bind_queue, 1, &bind, VK_NULL_HANDLE), "vkQueueBindSparse (arena)"); + if (result == VK_SUCCESS) + result = st->context->observe_result(f.vkQueueWaitIdle(st->info.arena_bind_queue), + "vkQueueWaitIdle (arena binds)"); + if (result == VK_ERROR_DEVICE_LOST) st->context->mark_device_lost(); + return result == VK_SUCCESS; + }; + if (!arena.backing.init_sparse(info.size, leonida::kArenaBlockBytes, std::move(hooks))) { + vk.vkDestroyBuffer(state_.info.device, arena.buffer, nullptr); + arena.buffer = VK_NULL_HANDLE; + return false; + } + } else { + { + leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::arena); + arena.memory = state_.allocate(requirements, leonida::kArenaRequiredMemory, + leonida::kArenaPreferredMemory, nullptr, true, &arena.memory_type); + } + void* mapped = nullptr; + if (!arena.memory || + vk.vkBindBufferMemory(state_.info.device, arena.buffer, arena.memory, 0) != VK_SUCCESS || + vk.vkMapMemory(state_.info.device, arena.memory, 0, VK_WHOLE_SIZE, 0, &mapped) != VK_SUCCESS) { + // Without an arena every buffer keeps its own memory; a leftover handle would make them addressable + // with heap base 0, so their VAs would be raw device addresses above 4 GiB. + vk.vkDestroyBuffer(state_.info.device, arena.buffer, nullptr); + if (arena.memory) vk.vkFreeMemory(state_.info.device, arena.memory, nullptr); + arena.buffer = VK_NULL_HANDLE; + arena.memory = VK_NULL_HANDLE; + return false; + } + arena.memory_type_known = true; + arena.backing.init_fixed(info.size, arena.memory, static_cast(mapped)); } - arena.mapped = static_cast(mapped); - std::fprintf(stderr, "[rt] d3d12: GPU address arena: %llu MiB (LEONIDA_ARENA_MB %s)\n", - static_cast(info.size >> 20), set ? text : "unset"); + std::fprintf(stderr, "[rt] d3d12: GPU address arena: %llu MiB of address range (LEONIDA_ARENA_MB %s), %s\n", + static_cast(info.size >> 20), set ? text : "unset", + sparse ? "sparse: memory bound in 2 MiB blocks as allocations need it" + : "one allocation behind all of it"); // LEONIDA_ARENA_NULL_MB= (for compute-on boots): the first n MiB of the arena, at heap_base + 0, are zeroed // and never handed out, and the zero page and the quad indices move above them. A translated shader whose // address arithmetic starts from a null base (a scalar or flat load the translator does not bounds-check) @@ -16018,9 +22162,28 @@ class Device final const VkDeviceSize bytes = VkDeviceSize(std::strtoull(text, nullptr, 10)) << 20; return bytes + kArenaReserved < info.size / 2 ? bytes : VkDeviceSize(0); }(); - std::memset(arena.mapped, 0, std::size_t(null_bytes + kZeroPage)); // the null region and the zero page + // The head of the arena (the null region, the zero page, the quad indices and the address guard's page), + // which shaders read and nothing allocates: backed for the arena's life. + const VkDeviceSize head = std::max(null_bytes + kArenaReserved, + address_guard_enabled() ? leonida::address_guard::kGuardEnd : 0); + std::uint8_t* head_host = nullptr; + { + std::lock_guard lock(arena.mutex); + if (arena.backing.acquire(0, head, true)) head_host = arena.backing.host(0, head); + } + if (!head_host) { + std::fprintf(stderr, "[rt] d3d12: GPU address arena: no memory for its first %llu KiB\n", + static_cast(head >> 10)); + arena.backing.clear(); + vk.vkDestroyBuffer(state_.info.device, arena.buffer, nullptr); + if (arena.memory) vk.vkFreeMemory(state_.info.device, arena.memory, nullptr); + arena.buffer = VK_NULL_HANDLE; + arena.memory = VK_NULL_HANDLE; + return false; + } + std::memset(head_host, 0, std::size_t(null_bytes + kZeroPage)); // the null region and the zero page { - auto* indices = reinterpret_cast(arena.mapped + null_bytes + kZeroPage); + auto* indices = reinterpret_cast(head_host + null_bytes + kZeroPage); for (std::uint32_t i = 0; i < kQuadIndexCount; i += kQuadIndicesPerQuad) { const std::uint32_t base = i / kQuadIndicesPerQuad * 4; std::transform(leonida::quad_triangle_indices.begin(), leonida::quad_triangle_indices.end(), indices + i, @@ -16036,18 +22199,18 @@ class Device final arena.address = vk.vkGetBufferDeviceAddress(state_.info.device, &address); arena.size = info.size; // The GPU address arena is the console's address space: the title names it by offset, so the label path - // has to find it (src/gpu_label_memory.h). Its address space starts at 0. - if (arena.mapped) - leonida::label::memory().track(0, static_cast(arena.size), - reinterpret_cast(arena.mapped), true); + // has to find it (src/gpu_label_memory.h). Its address space starts at 0. A label store to it goes through + // value_sink::arena (write_arena_value), which resolves the offset itself, so the region's allocation base is + // only its identity: the arena's device address, not a host pointer. + leonida::label::memory().track(0, static_cast(arena.size), + static_cast(arena.address), true); { // 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); // 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.first = head; arena.blocks.reset(arena.first, arena.size); char check[2] = {}; size_t check_length = 0; @@ -16062,7 +22225,9 @@ class Device final length = 0; arena.log = getenv_s(&length, log, "LEONIDA_ARENA_LOG") == 0 && length > 1 && log[0] != '0'; state_.context->set_heap_base(arena.address, arena.size); - leonida::fsdraw::note_arena(arena.mapped, arena.size); // LOCAL DIAGNOSTIC + leonida::fsdraw::note_arena(&state_, arena.size, [st = &state_](std::uint64_t va, void* out, std::size_t n) { + return st->arena.backing.with_host(va, n, [&](const std::uint8_t* host) { std::memcpy(out, host, n); }); + }); leonida::fsdraw::backing_hook().store(&fsdraw_backing, std::memory_order_release); state_.context->set_zero_page(arena.buffer, null_bytes, kZeroPage); state_.context->set_quad_indices(arena.buffer, null_bytes + kZeroPage, kQuadIndexCount); @@ -16070,12 +22235,20 @@ class Device final // until that submission's timeline value completes; a large indexed frame cannot wrap over itself. state_.context->set_geometry_provider([st=&state_](std::uint64_t va,std::uint64_t bytes, leonida::VulkanContext::GeometryUpload& result) { - if (!va || !bytes || bytes>UINTPTR_MAX-va || !st->arena.mapped || bytes>st->arena.size) return false; + if (!va || !bytes || bytes>UINTPTR_MAX-va || !st->arena_ready() || bytes>st->arena.size) return false; std::uint64_t lo{},hi{}; if (!leonida::title_va_aliases().title_memory(va,lo,hi) || bytes>hi-va) { return false; } for(std::uint64_t at=va;at(at),®ion,sizeof(region)) || region.State!=MEM_COMMIT || (region.Protect & (PAGE_NOACCESS|PAGE_GUARD)) || @@ -16090,9 +22263,14 @@ class Device final auto lease=std::make_shared(); if (!st->arena_allocate(bytes,256,lease->offset,DeviceState::arena_buffer)) return false; lease->state=st;lease->bytes=bytes; - SIZE_T copied{}; - if (!ReadProcessMemory(GetCurrentProcess(),reinterpret_cast(va),st->arena.mapped+lease->offset, - SIZE_T(bytes),&copied) || copied!=bytes) return false; + std::uint8_t* const host=st->arena_host(lease->offset,bytes); + if (!host || !leonida::title_frames::for_each_part(std::uintptr_t(va), std::size_t(bytes), + [&](std::uintptr_t at, std::size_t n, std::uint8_t* frame) { + if (frame) return copy_guarded_host(host + (at - va), frame, n, false); + SIZE_T copied{}; + return ReadProcessMemory(GetCurrentProcess(), reinterpret_cast(at), + host + (at - va), SIZE_T(n), &copied) && copied == n; + })) return false; result={va,bytes,st->arena.buffer,lease->offset,std::move(lease)}; return true; }); @@ -16116,6 +22294,7 @@ class Device final // cache checkpoint may also be queued or running. cancel() drops what is queued and waits for both. The last // device then stops and joins the compiler's thread. { + if (state_.context) state_.context->set_batch_compile_runner({}); auto& compiler = PipelineCompiler::instance(); if (compiler.running_here(&state_)) { // A build job of this device released the device's last reference from inside the build, which @@ -16161,17 +22340,22 @@ class Device final if (state_.context && state_.bindless) { // Every texture is gone by now (each held this device), and its views with it; samplers remain. std::lock_guard lock(state_.descriptor_mutex); - for (const auto& [key, sampler] : state_.sampler_entries) - state_.context->vk.vkDestroySampler(state_.info.device, sampler, nullptr); + for (const auto& [key, entry] : state_.sampler_entries) + state_.context->vk.vkDestroySampler(state_.info.device, entry.sampler, nullptr); state_.sampler_entries.clear(); state_.bindless.reset(); } state_.report_arena(); state_.destroy_address_guard(); + if (state_.context) state_.destroy_page_mirror(); if (state_.context && state_.arena.buffer) { - leonida::fsdraw::forget_arena(state_.arena.mapped); + leonida::fsdraw::forget_arena(&state_); auto& vk = state_.context->vk; vk.vkDestroyBuffer(state_.info.device, state_.arena.buffer, nullptr); + { + std::lock_guard lock(state_.arena.mutex); + state_.arena.backing.clear(); // a sparse arena's blocks; the buffer that used them is gone + } if (state_.arena.memory) vk.vkFreeMemory(state_.info.device, state_.arena.memory, nullptr); } state_.finish_heavy_cache(); @@ -16357,7 +22541,7 @@ class Device final if (!srv.Shader4ComponentMapping) srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; std::array words{}; std::memcpy(words.data(), resource_words, sizeof(words)); - words[2] = words[3] = 0; // the alignment says nothing about the texels + words[1] = words[2] = words[3] = words[13] = 0; // struct padding and alignment say nothing about the texels bool written = false; { std::lock_guard lock(state_.title_texture_mutex); @@ -16423,7 +22607,7 @@ class Device final if (!leonida::gfx10::is_image(result)) return false; std::lock_guard descriptors(state_.descriptor_mutex); if (!state_.bindless) return true; - const auto entry = state_.image_entries.find(result); + const auto entry = state_.image_entries.find(leonida::gfx10::tsharp_key(result)); if (entry != state_.image_entries.end() && entry->second.storage) return true; std::memset(reinterpret_cast(dest.ptr), 0, kDescriptorSize); return false; @@ -16460,311 +22644,926 @@ class Device final entry->layout_known = entry->layout_guessed = title_layout(d, entry->layout, why) && title_layout_fits(entry->layout, d, *texture, why); std::memcpy(entry->desc.data(), &d, sizeof(d)); + entry->desc[1] = entry->desc[2] = entry->desc[3] = entry->desc[13] = 0; } } + // The memory a GPU-written texture covers: what the console's GPU renders there, our GPU renders into the image + // instead. Its console footprint (XG's default layout), or its image's size if larger or unknown. + std::uint64_t gpu_span = 0; + if (entry->gpu_written) { + rt::xg_xs::ResourceDesc d{}; + d.dimension = std::uint32_t(desc.Dimension); + d.width = desc.Width; + d.height = desc.Height; + d.depth_or_array = desc.DepthOrArraySize; + d.mips = desc.MipLevels; + d.format = std::uint32_t(desc.Format); + d.samples = 1; + rt::xg_xs::Texture layout{}; + const char* why = nullptr; + gpu_span = std::max(title_layout(d, layout, why) ? layout.layout.size : 0, + texture->image_backing_bytes()); + } texture->mark_title_texture(); { std::lock_guard lock(state_.title_texture_mutex); + if (gpu_span) state_.add_gpu_owned(texture, address, entry->cpu, gpu_span); if (entry->gpu_written && !(address & 0xff) && texture->image_address() != address) { std::lock_guard descriptors(state_.descriptor_mutex); state_.gpu_placements.add(address, texture); + state_.note_texture_change(leonida::SlotChange::texture_added, address); } auto& slot = state_.title_textures[address]; + if (entry->gpu_written && slot && slot->resource && !slot->owned && !slot->gpu_written) { + // A render target placed over a texture the title placed first: the texture keeps its entry (it is + // filled from memory again once the target goes, drop_gpu_owned), and its T#s are bound again, to + // the target's image where they fit (bind_title_image). + std::lock_guard descriptors(state_.descriptor_mutex); + state_.forget_image_views_locked(slot->resource->image_address()); + ++title_stats_.registered; + return; + } if (slot && slot->owned) retire_title_texture(*slot); - state_.mapped_title_textures.erase(address); state_.index_texture(*entry); slot = std::move(entry); ++title_stats_.registered; } } - // Before every submission (VulkanContext::set_before_execute), at most once per LEONIDA_TITLE_TEXTURE_PERIOD_MS - // (16 by default, about a frame): the bytes of the textures filled from the title's memory are hashed, round - // robin, until LEONIDA_TITLE_TEXTURE_CHECK_KB have been read (4096 by default; all of a small texture, about 3% - // of a large one, hash_guarded), mapped slot-133 textures first and every pass; a texture whose bytes changed is - // filled again, up - // to LEONIDA_TITLE_TEXTURE_FILL_MB a pass (32 by default, OpenScarlett's batch cap), the rest at the next pass. - // Host copies and the private full-image uploader are safe here. Generic staging re-enters submission. No write - // watch on the title's pages: streaming memory would fault once a page. - void refresh_title_textures() { + // Before every submission (VulkanContext::set_before_execute), on the submitting thread: the textures something + // says may have changed since their last fill are read and, when their bytes differ from that fill's, uploaded + // (fill_title_texture). What says so (TitleTextureWatch, title_texture_watch.h): a write to their pages (a fault + // on a tile armed read-only, at every address it is mapped at), a mapping change over them, their creation or a + // new layout, the title's Unmap, and the writes XG and DirectStorage note (title_texel_writes). A texture nobody + // wrote costs nothing here. Memory a guard cannot watch (not committed, or no write-fault handler) is the one + // fallback: its textures are read at every refresh and uploaded only when their bytes differ. + // + // Ordering: a write the title finished before it called ExecuteCommandLists is in this pass, and its upload is + // submitted before this submission's command buffers, behind all earlier work on every queue on the GPU and with + // no CPU wait (TitleImageUpload, write_staged_title_image); this submission's draws, on whichever queue, see it. + // Every changed texture of the pass goes in, with no budget: the planes of a video frame land together. + void refresh_title_textures(bool mirror_just_synced = false, std::uint64_t mirror_synced_serial = 0) { if (t_in_title_textures) return; using clock = std::chrono::steady_clock; - static const auto setting = [](const char* name, std::uint64_t fallback) { - char text[16] = {}; - size_t length = 0; - return getenv_s(&length, text, name) == 0 && length > 1 ? std::strtoull(text, nullptr, 10) : fallback; - }; - static const auto period = std::chrono::milliseconds(setting("LEONIDA_TITLE_TEXTURE_PERIOD_MS", 16)); - static const std::uint64_t check_budget = setting("LEONIDA_TITLE_TEXTURE_CHECK_KB", 4096) << 10; - static const std::uint64_t fill_budget = setting("LEONIDA_TITLE_TEXTURE_FILL_MB", 32) << 20; - // And at most this long filling a pass (0: no limit); a texture already started is finished. - static const std::uint64_t fill_budget_ns = setting("LEONIDA_TITLE_TEXTURE_FILL_MS", 8) * 1000000; - // Stop the background sweep at a texture boundary. Zero keeps the byte budget alone. - static const std::uint64_t hash_budget_us = setting("LEONIDA_TEXTURE_HASH_BUDGET_US", 400); - // Residency checks and uploads also cost time. Limit background work between textures; - // mapped textures and notified writes have already been serviced when this timer starts. - static const auto sweep_budget_us = setting("LEONIDA_TEXTURE_SWEEP_BUDGET_US", 400); const auto now = clock::now(); - const std::int64_t ticks = now.time_since_epoch().count(); - if (ticks - title_refreshed_.load(std::memory_order_relaxed) < - std::chrono::duration_cast(period).count()) - return; - std::unique_lock lock(state_.title_texture_mutex, std::try_to_lock); - if (!lock.owns_lock()) return; // a slot-70 view is filling one; next time - title_refreshed_.store(ticks, std::memory_order_relaxed); + const std::int64_t now_ns = + std::chrono::duration_cast(now.time_since_epoch()).count(); + // O(1) lock-free dirty fast-path: return immediately without locking title_texture_mutex or scanning when + // nothing changed since the last pass, no retired textures are due, and the 10-second log is not due. + { + const std::int64_t due_retire = retired_earliest_ns_.load(std::memory_order_acquire); + const std::int64_t last_log = title_last_log_ns_.load(std::memory_order_acquire); + const bool log_due = (now_ns - last_log) >= 10'000'000'000ll; + if (!log_due && (due_retire == 0 || now_ns < due_retire) && !state_.texture_watch.may_have_work() && + !leonida::title_texel_writes::state().pending.load(std::memory_order_acquire) && + leonida::title_memory_map::generation() == + title_map_generation_atomic_.load(std::memory_order_acquire) && + !state_.titles_named_pending.load(std::memory_order_acquire) && + !state_.titles_gone_pending.load(std::memory_order_acquire) && + title_refresh_in_flight_.load(std::memory_order_seq_cst) == 0) { + title_fast_passes_.fetch_add(1, std::memory_order_relaxed); + return; + } + } + // Waits for a slot-70 view that is filling a texture: skipping would leave this submission a write behind. + // No deadlock: before_execute holds no lock, and the registry's holders never wait for this thread. + std::unique_lock lock(state_.title_texture_mutex); + const auto locked = clock::now(); + title_refresh_in_flight_.fetch_add(1, std::memory_order_seq_cst); + struct TitleRefreshGuard { + std::atomic& n; + ~TitleRefreshGuard() { n.fetch_sub(1, std::memory_order_release); } + } in_flight{title_refresh_in_flight_}; std::optional inside(std::in_place); TitleTextureStats& stats = title_stats_; - ++stats.passes; - // A fill this pass makes can submit, and a submission destroys a retired image, whose destructor reaches - // title_texture_gone while this thread holds the registry mutex: the entry stops naming the resource and is - // erased by drain_titles_gone after the pass. Every walk below visits a snapshot, never an iterator into the - // registry, and skips an entry without a resource. - // The worker gives journal hits priority. Rotate a small slice for direct writes with no notification. - const bool async = async_texture_refresh(); - const auto entries = async ? leonida::title_texture_snapshot(state_.title_textures, title_slice_, 128) - : leonida::title_texture_snapshot(state_.title_textures); - if (async) title_slice_ = entries.size() == 128 ? entries.back().first + 1 : 0; + stats.lock_wait_ns += std::uint64_t(std::chrono::duration_cast(locked - now).count()); + auto& watch = state_.texture_watch; + const std::uint64_t fast_skips = title_fast_passes_.exchange(0, std::memory_order_relaxed); + stats.fast_passes += fast_skips; + stats.passes += fast_skips + 1; + title_split_passes_ += fast_skips + 1; title_pass_ = true; - title_partial_bytes_ = 0; - for (const auto& entry : entries) - if (entry.second->fills && entry.second->filled_from) title_partial_bytes_ += entry.second->backing_bytes; - std::uint64_t checked = 0, filled = 0, fill_pass_ns = 0; - const auto visit = [&](TitleTexture& t) { - // A slot-133 texture's guessed layout (no slot-70 view yet) is only used once the title maps it. - if (t.gpu_written || !t.layout_known || !t.resource || - ((t.layout_guessed || t.layout_from_xg) && !t.mapped && !t.stale)) - return; - std::uint64_t span = fill_bytes(t); - const bool always = t.mapped && refresh_mapped_pages(); - // Out of this pass's fill budget (bytes or time): a texture known to need a fill (stale) waits for the - // next pass unprobed and unhashed; hashing it now would only find it changed again (measured: 10,000 - // deferred textures, 600 MiB hashed a pass, during the story load). - const auto out_of_budget = [&] { - return (filled && filled + span > fill_budget) || (fill_budget_ns && fill_pass_ns >= fill_budget_ns); - }; - if (t.stale && !always && out_of_budget()) { - ++stats.deferred; - return; + // A fill this pass makes can retire an image (title_texture_gone while this thread holds the registry): the + // entry stops naming the resource and is erased by drain_titles_gone after the pass. Entries are looked up by + // key each time, and one without a resource is passed over. + if (partial_mips()) { + title_partial_bytes_ = 0; + for (const auto& [address, entry] : state_.title_textures) + if (entry->fills && entry->filled_from) title_partial_bytes_ += entry->backing_bytes; + } + bool overflow = false; + auto written = leonida::title_texel_writes::take(overflow); + stats.written_ranges += written.size(); + title_map_changes_.clear(); + std::uint64_t map_now = 0; + const bool map_all = !leonida::title_memory_map::changes_since( + title_map_generation_, map_now, 0, UINTPTR_MAX, + [&](std::uintptr_t from, std::uintptr_t to) { title_map_changes_.emplace_back(from, to); }); + title_map_generation_ = map_now; + title_map_generation_atomic_.store(map_now, std::memory_order_release); + stats.map_ranges += title_map_changes_.size(); + stats.map_all += map_all; + // A mapping change: the textures over it probe their memory again (TextureReadability) and invalidate cached + // write_combined status. + const auto remapped = [&](std::uint64_t key) { + const auto it = state_.title_textures.find(key); + if (it != state_.title_textures.end()) { + TitleTexture& t = *it->second; + t.memory.retry(); + t.write_combined_known = false; + if (partial_mips() && !t.gpu_written && t.layout_known && !t.stale && t.resource && + !t.layout_guessed && !t.layout_from_xg && (!t.fills || t.filled_from) && + title_texture_readable(t) && (!t.fills || t.readable_from < t.filled_from)) + t.stale = true; + } + }; + // A pure texel write (XG CopyIntoSubresource / DirectStorage / slot-31 copy): do NOT invalidate cached + // readability on already-filled full-mip textures; only retry when pending, partially filled, or never filled + // (preserves check_pending_stream_views and partial mip chain promotion). + const auto texel_written = [&](std::uint64_t key) { + const auto it = state_.title_textures.find(key); + if (it != state_.title_textures.end()) { + TitleTexture& t = *it->second; + if (t.memory.pending() || t.filled_from != 0 || !t.fills) { + t.memory.retry(); + if (partial_mips() && !t.gpu_written && t.layout_known && !t.stale && t.resource && + !t.layout_guessed && !t.layout_from_xg && (!t.fills || t.filled_from) && + title_texture_readable(t) && (!t.fills || t.readable_from < t.filled_from)) + t.stale = true; + } + } + }; + if (map_all) { + watch.note_changed_and_for_each(0, UINTPTR_MAX, remapped, true); + } else { + if (!title_map_changes_.empty()) { + leonida::merge_title_writes(title_map_changes_); + for (const auto& [from, to] : title_map_changes_) + watch.note_changed_and_for_each(from, to, remapped, false); + } + if (overflow) { + watch.note_changed_and_for_each(0, UINTPTR_MAX, texel_written, false); + } else if (!written.empty()) { + leonida::merge_title_writes(written); + for (const auto& [from, to] : written) + watch.note_changed_and_for_each(from, to, texel_written, false); + } + } + if (state_.titles_named_pending.load(std::memory_order_acquire)) { + std::vector named; + { + std::lock_guard named_lock(state_.titles_named_mutex); + named.swap(state_.titles_named); + state_.titles_named_pending.store(false, std::memory_order_release); + } + for (const std::uint64_t address : named) { + const auto it = state_.title_textures.find(address); + if (it != state_.title_textures.end() && it->second->resource && !watch.tracked(address)) { + state_.index_texture(*it->second); + ++stats.first_named; + } + } + } + title_named_.clear(); + watch.collect([&](std::uint64_t key) { title_named_.push_back(key); }); + const auto collected = clock::now(); + stats.collect_ns += std::uint64_t(std::chrono::duration_cast(collected - locked).count()); + // Not filled: with no backing yet or after a failed upload it is looked at again next pass. Memory not + // readable yet waits for its mapping (xmem's change names it), except a texture the title mapped, whose + // pages may be committed under the pointer Map gave without xmem (the probe answers each pass). Its tiles + // are armed again then: pages committed since the last arming have no guard yet. + const auto not_filled = [&](TitleTexture& t) { + if ((t.stale || !t.hashed) && t.resource) { + if (t.mapped) + watch.note_changed(t.cpu, t.cpu + t.layout.layout.size, true); + else if (!t.memory.pending()) + watch.touch(t.address); + } + }; + // Batched texture refresh: + // 1. Filter eligible textures and batch-arm all dirty tiles in one watch.examine_batch() call. + // 2. Batch all TitleMirror checks/uploads in ONE page_mirror.mutex hold + ONE parallel TitleMirror::upload() + // (skipping unchanged textures in ~15 ns, rejecting only pages overlapping pending xmem remaps). + // 3. Hash-before-reserve for remaining CPU-checked textures on TitleReadPool using 4-lane piece hashing + // (comparing both t.hash and t.mirror_hash so CPU fallback after GPU upload never re-uploads unchanged). + // 4. Only reserve staging slots & detile on CPU for CPU jobs whose bytes actually changed. + // 5. Record and submit all uploads of the batch in ONE batched command buffer + ONE vkQueueSubmit. + std::uint64_t filled = 0; + title_job_count_ = 0; + std::size_t cpu_job_count = 0; + std::uint64_t cpu_batch_bytes = 0; + std::uint64_t gpu_scratch_bytes = 0; + const auto next_title_job = [&]() -> TitleJob& { + if (title_job_count_ == title_jobs_.size()) title_jobs_.emplace_back(); + TitleJob& job = title_jobs_[title_job_count_++]; + job.entry.reset(); + job.resource = nullptr; + job.slot = nullptr; + job.from = 0; + job.span = 0; + job.hash = 0; + job.previous.reset(); + job.previous_mirror_hash.reset(); + job.pieces.hashes.clear(); + job.piece_sums.clear(); + job.written.clear(); + job.compare = job.whole = job.precopied = false; + job.failed.store(false, std::memory_order_relaxed); + job.detile_ns = 0; + job.write_combined = job.trace = job.copied = job.unchanged = job.nonzero = false; + job.gpu_mirror = false; + job.gpu_kind = rt::d3d12::TitleImageUpload::UploadKind::cpu_slot; + job.mirror_buffer = VK_NULL_HANDLE; + job.mirror_offset = job.mirror_chunk_size = 0; + job.mirror_timeline = VK_NULL_HANDLE; + job.mirror_value = 0; + job.mirror_hash = 0; + job.mirror_hash_valid = false; + return job; + }; + const auto fill_start = clock::now(); + const std::uint64_t read_before = stats.read_ns, staged_before = stats.staged_ns; + const auto run_batch = [&] { + if (!title_job_count_) return; + const auto read_start = clock::now(); + TitleReadPool& pool = title_read_pool(); + title_cpu_check_indices_.clear(); + for (std::size_t i = 0; i < title_job_count_; ++i) { + const TitleJob& job = title_jobs_[i]; + if (!job.gpu_mirror || job.compare) title_cpu_check_indices_.push_back(i); + } + if (!title_cpu_check_indices_.empty()) { + pool.run(title_cpu_check_indices_.size(), + [this](std::size_t k) { read_title_job(title_jobs_[title_cpu_check_indices_[k]]); }); + } + // Whole CPU reads in pieces of up to kTitleChunkTiles tiles, spread over the threads (never for GPU-mirror + // jobs or jobs already copied/found unchanged in read_title_job). + title_chunks_.clear(); + bool any_whole = false; + for (std::size_t i = 0; i < title_job_count_; ++i) { + TitleJob& job = title_jobs_[i]; + if (!job.whole || job.gpu_mirror) continue; + any_whole = true; + if (job.precopied) { + stats.read_bytes += job.span; + continue; + } + job.tiled.resize(std::size_t(job.span)); + job.pieces.reset(job.entry->cpu, job.span); + const bool mirror_aligned = (job.entry->cpu & (leonida::shadow_keep::kPiece - 1)) == 0 && + (job.span & (leonida::shadow_keep::kPiece - 1)) == 0; + if (mirror_aligned) + job.piece_sums.resize(std::size_t(job.span / leonida::shadow_keep::kPiece)); + else + job.piece_sums.clear(); + job.failed.store(false, std::memory_order_relaxed); + const std::size_t tiles = job.pieces.hashes.size(); + for (std::size_t first = 0; first < tiles; first += kTitleChunkTiles) + title_chunks_.push_back({i, first, (std::min)(tiles, first + kTitleChunkTiles)}); + stats.read_bytes += job.span; + } + if (!title_chunks_.empty()) { + pool.run(title_chunks_.size(), [this](std::size_t c) { + const TitleChunk& chunk = title_chunks_[c]; + read_title_chunk(title_jobs_[chunk.job], chunk.first, chunk.end); + }); + } + // Finalize hashes inline on calling thread BEFORE reserving any upload slots (pure integer mixing, avoids + // a full thread-pool wakeup barrier). + if (any_whole) { + for (std::size_t i = 0; i < title_job_count_; ++i) hash_title_job(title_jobs_[i]); + } + // Reserve staging slots ONLY for CPU jobs whose bytes actually changed (eliminating >87% wasted reserves). + title_detile_indices_.clear(); + { + std::lock_guard upload(state_.title_upload_mutex); + for (std::size_t i = 0; i < title_job_count_; ++i) { + TitleJob& job = title_jobs_[i]; + if (job.gpu_mirror || !job.copied || job.unchanged) continue; + job.slot = state_.title_upload.reserve(state_, job.resource->title_binding(), job.entry->layout, job.from); + if (job.slot) title_detile_indices_.push_back(i); + } + } + if (!title_detile_indices_.empty()) { + pool.run(title_detile_indices_.size(), + [this](std::size_t k) { detile_title_job(title_jobs_[title_detile_indices_[k]]); }); + } + stats.read_ns += std::uint64_t( + std::chrono::duration_cast(clock::now() - read_start).count()); + for (std::size_t i = 0; i < title_job_count_; ++i) stats.detile_ns += title_jobs_[i].detile_ns; + + // Build one batch of all changed CPU slots + GPU-mirror direct/detile uploads and commit in one submit. + title_batch_items_.clear(); + title_batch_job_indices_.clear(); + for (std::size_t i = 0; i < title_job_count_; ++i) { + TitleJob& job = title_jobs_[i]; + TitleTexture& t = *job.entry; + if (job.gpu_mirror) { + if (job.unchanged) { + ++stats.unchanged_parts; + t.stale = false; + continue; + } + rt::d3d12::TitleImageUpload::BatchItem item{}; + item.kind = job.gpu_kind; + item.id = job.resource->id(); + item.image = job.resource->title_binding(); + item.layout = &t.layout; + item.mirror_buffer = job.mirror_buffer; + item.mirror_offset = job.mirror_offset; + item.mirror_chunk_size = job.mirror_chunk_size; + item.mirror_timeline = job.mirror_timeline; + item.mirror_value = job.mirror_value; + title_batch_items_.push_back(item); + title_batch_job_indices_.push_back(i); + continue; + } + if (!job.copied) { // the section changed after VirtualQuery: keep the last upload and retry + if (job.slot) rt::d3d12::TitleImageUpload::unreserve(*job.slot); + t.memory.defer(); + t.stale = true; + not_filled(t); + continue; + } + if (job.whole) ++stats.read_whole; + if (job.unchanged) { + if (job.slot) rt::d3d12::TitleImageUpload::unreserve(*job.slot); + ++(job.whole ? stats.unchanged : stats.unchanged_parts); + if (job.whole) { + t.pieces = std::move(job.pieces); + t.hash = job.hash; + t.hashed = true; + t.gpu_uploaded = false; + if (job.mirror_hash_valid) { + t.mirror_hash = job.mirror_hash; + t.mirror_hash_span = job.span; + t.mirror_hash_valid = true; + } + } + t.stale = false; + continue; + } + if (!job.slot) { + log_once("staged title texture upload failed, format", int(job.resource->format())); + ++stats.fill_failures; + t.stale = true; + t.mirror_hash_valid = false; + not_filled(t); + continue; + } + rt::d3d12::TitleImageUpload::BatchItem item{}; + item.kind = rt::d3d12::TitleImageUpload::UploadKind::cpu_slot; + item.id = job.resource->id(); + item.image = job.resource->title_binding(); + item.layout = &t.layout; + item.from = job.from; + item.slot = job.slot; + title_batch_items_.push_back(item); + title_batch_job_indices_.push_back(i); + } + + if (!title_batch_items_.empty()) { + const auto start = clock::now(); + { + std::lock_guard upload(state_.title_upload_mutex); + state_.title_upload.commit_batch(state_, title_batch_items_); + } + stats.staged_ns += + std::uint64_t(std::chrono::duration_cast(clock::now() - start).count()); + + for (std::size_t b = 0; b < title_batch_items_.size(); ++b) { + const auto& item = title_batch_items_[b]; + TitleJob& job = title_jobs_[title_batch_job_indices_[b]]; + TitleTexture& t = *job.entry; + if (!item.ok) { + log_once("staged title texture upload failed, format", int(job.resource->format())); + ++stats.fill_failures; + t.stale = true; + t.mirror_hash_valid = false; + not_filled(t); + continue; + } + if (job.gpu_mirror) { + if (job.gpu_kind == rt::d3d12::TitleImageUpload::UploadKind::mirror_linear) + ++stats.gpu_linear_fills; + else + ++stats.gpu_detile_fills; + note_filled_from(t, 0); + t.gpu_uploaded = true; + t.mirror_hash = job.mirror_hash; + t.mirror_hash_span = job.span; + t.mirror_hash_valid = true; + t.hashed = true; + t.pieces.hashes.clear(); + t.stale = false; + ++t.fills; + ++stats.fills; + ++stats.changed; + stats.fill_bytes += job.span; + filled += job.span; + } else { + ++stats.staged_fills; + if (job.trace) + std::fprintf(stderr, "[rt] ds-pool-fill cpu=%llx size=%llu staged=1 nonzero=%d\n", + static_cast(t.cpu), + static_cast(job.span), int(job.nonzero)); + note_filled_from(t, job.from); + t.gpu_uploaded = false; + if (job.whole) t.pieces = std::move(job.pieces); + t.mirror_hash = job.mirror_hash; + t.mirror_hash_span = job.mirror_hash_valid ? job.span : 0; + t.mirror_hash_valid = job.mirror_hash_valid; + t.hash = job.hash; + t.hashed = true; + t.stale = false; + ++t.fills; + ++stats.fills; + ++stats.changed; + stats.fill_bytes += job.span; + filled += job.span; + } + } } - std::uint64_t hash = 0; - if (!title_texture_readable(t)) return; - span = fill_bytes(t); // the probe may have found more mips, or fewer - const bool full_mapped = async && always; - checked += full_mapped ? span : hashed_bytes(span); - ++stats.checked; - const auto* bytes = reinterpret_cast(static_cast(t.cpu)); - const auto timed_hash = [&](std::uint64_t& out, bool all = false) { - const auto start = clock::now(); - // Every byte of write-combined memory goes through a streaming copy (copy_guarded): ordinary loads - // from it are not cached, and hashing a 4 MiB mapped texture in place took 36 ms on average and up to - // 78 ms each sixth pass, one to two frames of a title that paces itself for 30 Hz. - bool ok; - if (all && title_memory_write_combined(t.cpu)) { - title_tiled_.resize(std::size_t(span)); - ok = copy_guarded(title_tiled_.data(), bytes, std::size_t(span), true) && - hash_guarded(title_tiled_.data(), std::size_t(span), out, true); - } else { - ok = hash_guarded(bytes, std::size_t(span), out, all); + for (std::size_t i = 0; i < title_job_count_; ++i) { + TitleJob& job = title_jobs_[i]; + job.entry.reset(); + job.resource = nullptr; + job.slot = nullptr; + const std::size_t tiled_cap = (i < 4) ? (16ull << 20) : (2ull << 20); + if (job.tiled.capacity() > tiled_cap) std::vector{}.swap(job.tiled); + if (job.piece_sums.capacity() > 8192) std::vector{}.swap(job.piece_sums); + } + title_job_count_ = 0; + cpu_job_count = 0; + cpu_batch_bytes = 0; + gpu_scratch_bytes = 0; + }; + const bool gpu_detile_on = leonida::title_gpu_detile_enabled(); + + // Stage 1: filter eligible textures once from title_named_ (no repeated std::map lookups). + title_candidate_keys_.clear(); + title_candidates_.clear(); + for (const std::uint64_t key : title_named_) { + const auto it = state_.title_textures.find(key); + if (it == state_.title_textures.end() || !it->second->resource) continue; + TitleTexture& t = *it->second; + if (t.gpu_written || !t.layout_known) continue; + title_candidate_keys_.push_back(key); + title_candidates_.push_back({it->second, 0, 0, 0, false}); + } + + auto t_after_mirror = fill_start; + if (!title_candidates_.empty()) { + // Stage 2: batch-arm all dirty tiles across all candidates in ONE watch.examine_batch() call, then run + // readability, partial-mip budget, and image-backing checks. + watch.examine_batch(title_candidate_keys_, title_examine_results_); + const auto t_after_arm = clock::now(); + stats.examine_arm_ns += + std::uint64_t(std::chrono::duration_cast(t_after_arm - fill_start).count()); + const bool have_mirror = state_.page_mirror.mirror != nullptr; + if (have_mirror) title_mirror_checks_.resize(title_candidates_.size()); + bool any_mirror_active = false; + leonida::TextureVqCache stage2_vq_cache; + const std::uint64_t probes_before = stats.probes[0]; + std::uint64_t pass_back_ns = 0; + + // Skip VirtualQuery in Stage 2b ONLY when `!t.mapped` AND every 64 KiB tile of `[t.cpu, t.cpu + size)` + // has all 16 `Cell::restore[0..15] != 0` under `geometry_writes::state().mutex` (proving MEM_COMMIT + + // readable; Look::armed alone also covers MEM_RESERVE/PAGE_NOACCESS and is never sufficient). + std::vector tile_proven_readable; + if (check_pages_before_read()) { + bool any_need_probe = false; + for (std::size_t idx = 0; idx < title_candidates_.size(); ++idx) { + if (title_examine_results_[idx].look == leonida::TitleTextureWatch::Look::busy) + continue; + const TitleTexture& t = *title_candidates_[idx].entry; + if (!t.mapped && t.memory.needs_probe(0, true, true)) { + any_need_probe = true; + break; + } } - stats.hash_ns += std::chrono::duration_cast(clock::now() - start).count(); - return ok; - }; - if (full_mapped) { - // Direct writes through a persistent Map have no journal entry. Check every byte on the - // worker. A large mapped plane must not hold up view creation while its hash is computed. - const auto address = t.address, fills = t.fills; - const auto start = clock::now(); - title_pass_ = false; - lock.unlock(); - const bool ok = hash_guarded(bytes, std::size_t(span), hash, true); - lock.lock(); - title_pass_ = true; - stats.hash_ns += std::chrono::duration_cast(clock::now() - start).count(); - const auto it = state_.title_textures.find(address); - if (it == state_.title_textures.end() || it->second.get() != &t || !t.resource || - !t.layout_known || fill_bytes(t) != span || t.fills != fills) return; - ++stats.mapped_checks; - if (!ok) { - t.memory.defer(); - t.stale = true; - return; + if (any_need_probe) { + tile_proven_readable.assign(title_candidates_.size(), 0); + auto& gs = leonida::geometry_writes::state(); + std::lock_guard gs_lock(gs.mutex); + constexpr std::uintptr_t kTile = leonida::geometry_writes::tile_size; + for (std::size_t idx = 0; idx < title_candidates_.size(); ++idx) { + if (title_examine_results_[idx].look == + leonida::TitleTextureWatch::Look::busy) + continue; + const TitleTexture& t = *title_candidates_[idx].entry; + if (t.mapped || !t.memory.needs_probe(0, true, true)) continue; + const std::uintptr_t cpu = static_cast(t.cpu); + const std::uint64_t size = t.layout.layout.size; + if (!cpu || !size || size > (std::numeric_limits::max)() - cpu) continue; + const std::uintptr_t first_tile = cpu & ~(kTile - 1); + const std::uintptr_t last_tile = (cpu + static_cast(size) - 1) & ~(kTile - 1); + const std::size_t n_tiles = std::size_t((last_tile - first_tile) / kTile) + 1; + auto it = gs.cells.lower_bound(first_tile); + std::uintptr_t tile = first_tile; + bool all_restored = true; + for (std::size_t ti = 0; ti < n_tiles; ++ti, tile += kTile, ++it) { + if (it == gs.cells.end() || it->first != tile) { + all_restored = false; + break; + } + for (const DWORD r : it->second.restore) { + if (!r) { + all_restored = false; + break; + } + } + if (!all_restored) break; + } + if (all_restored) tile_proven_readable[idx] = 1; + } } - if (t.hashed && t.full_hashed && t.full_hash == hash && !t.stale) return; - ++stats.mapped_changed; - } else if (!timed_hash(hash)) { - t.memory.defer(); - return; } - if (!full_mapped && t.hashed && hash == t.hash && !t.stale) { - if (!t.every_byte() || stats.passes % 6) return; - std::uint64_t full = 0; - checked += span; - if (!timed_hash(full, true)) { - t.memory.defer(); - return; + + for (std::size_t idx = 0; idx < title_candidates_.size(); ++idx) { + TitleCandidate& cand = title_candidates_[idx]; + TitleTexture& t = *cand.entry; + const auto& ex = title_examine_results_[idx]; + if (ex.look == leonida::TitleTextureWatch::Look::busy) { + ++stats.busy; + if (have_mirror) title_mirror_checks_[idx].active = false; + continue; + } + ++stats.checked; + bool readable = false; + if (!tile_proven_readable.empty() && tile_proven_readable[idx]) { + t.readable_from = 0; + readable = t.memory.check(0, true, [&] { return true; }, true); + } else { + readable = title_texture_readable(t, &stage2_vq_cache); + } + if (!readable) { + not_filled(t); + if (have_mirror) title_mirror_checks_[idx].active = false; + continue; + } + const unsigned from = fill_from(t); + const std::uint64_t span = fill_bytes(t); + if (from && t.unbound_bytes && title_partial_bytes_ + t.unbound_bytes > partial_mips_budget()) { + ++stats.partial_refused; + t.stale = false; + if (have_mirror) title_mirror_checks_[idx].active = false; + continue; + } + if (t.unbound_bytes) { + const auto back_start = clock::now(); + bool did_back = false, did_raw = false; + const bool backed_ok = back_title_texture(t, &did_back, &did_raw); + pass_back_ns += std::uint64_t( + std::chrono::duration_cast(clock::now() - back_start).count()); + if (did_back) { + ++stats.stage2_backed; + if (did_raw) ++stats.stage2_raw_allocs; + } + if (!backed_ok) { + not_filled(t); + if (have_mirror) title_mirror_checks_[idx].active = false; + continue; + } + } + const std::size_t tiles = std::size_t(((t.cpu + span + 0xffff) & ~std::uint64_t(0xffff)) - + (t.cpu & ~std::uint64_t(0xffff))) >> + 16; + cand.from = from; + cand.span = span; + cand.tiles = tiles; + cand.active = true; + + if (have_mirror) { + const bool allow_filter = ex.look == leonida::TitleTextureWatch::Look::armed; + auto& mc = title_mirror_checks_[idx]; + mc.cpu = t.cpu; + mc.gpu = t.address; + mc.bytes = span; + mc.written_tiles = (allow_filter && !t.stale) ? &ex.written : nullptr; + const bool can_tile_cmp = !t.stale && t.fills && !t.gpu_uploaded && from == t.filled_from && + t.pieces.valid_for(t.cpu, span) && !ex.written.empty() && + ex.written.size() <= tiles; + mc.tile_cmp_written = can_tile_cmp ? &ex.written : nullptr; + mc.pieces = can_tile_cmp ? &t.pieces : nullptr; + mc.max_version = ex.max_version; + mc.ex_armed = allow_filter; + mc.active = true; + any_mirror_active = true; } - if (t.full_hashed && full == t.full_hash) return; } - ++stats.changed; - if (!always && out_of_budget()) { - t.stale = true; - ++stats.deferred; - return; + const auto t_after_probe = clock::now(); + const std::uint64_t probe_total_ns = + std::uint64_t(std::chrono::duration_cast(t_after_probe - t_after_arm).count()); + stats.examine_probe_ns += probe_total_ns; + stats.examine_back_ns += pass_back_ns; + stats.examine_readable_ns += probe_total_ns > pass_back_ns ? probe_total_ns - pass_back_ns : 0; + stats.stage2_probes += stats.probes[0] - probes_before; + + // Stage 3: ONE page_mirror.mutex lock + ONE batched parallel TitleMirror::upload() for all candidates. + if (have_mirror && any_mirror_active) { + struct MirrorJustSyncedGuard { + bool prev; + explicit MirrorJustSyncedGuard(bool v) noexcept : prev(t_page_mirror_just_synced) { + t_page_mirror_just_synced = v; + } + ~MirrorJustSyncedGuard() { t_page_mirror_just_synced = prev; } + } mirror_sync_guard{mirror_just_synced}; + state_.page_mirror_check_batch( + title_mirror_checks_, title_mirror_feed_pages_, mirror_synced_serial, + [this](std::size_t count, std::function work) { + title_read_pool().run(count, std::move(work)); + }); } - const auto fill_start = clock::now(); - const auto uploaded = fill_title_texture(t, false); - filled += uploaded; - if (full_mapped && uploaded) ++stats.mapped_fills; - if (async && t.stale) queue_title_fill(t.address); // generic staging needs an outer fill - const std::uint64_t fill_ns = - std::chrono::duration_cast(clock::now() - fill_start).count(); - stats.fill_ns += fill_ns; - fill_pass_ns += fill_ns; - }; - bool overflow = false; - auto written = leonida::title_texel_writes::take(overflow); - // What the title memory map changed since the last pass: a texture over a change is probed again (its pages - // may have come or gone), the others keep their last answer (TextureReadability). Every kRetryAll, or when the - // journal lost some changes, all are probed again, for whatever no change reports. - constexpr auto kRetryAll = std::chrono::seconds(30); - title_map_changes_.clear(); - std::uint64_t map_now = 0; - bool map_all = !leonida::title_memory_map::changes_since( - title_map_generation_, map_now, 0, UINTPTR_MAX, - [&](std::uintptr_t from, std::uintptr_t to) { title_map_changes_.emplace_back(from, to); }); - title_map_generation_ = map_now; - if (now - title_retry_all_ >= kRetryAll) map_all = true; - if (map_all) title_retry_all_ = now; - leonida::merge_title_writes(title_map_changes_); - stats.map_ranges += title_map_changes_.size(); - stats.map_all += map_all; - if (!written.empty() || overflow || map_all || !title_map_changes_.empty()) { - stats.written_ranges += written.size(); - leonida::merge_title_writes(written); - const auto invalidate = [&](TitleTexture& t, bool write, bool remapped) { - if (t.gpu_written || !t.layout_known) return; - t.memory.retry(); - // Pages that came without a noted write: a texture not filled, or not all of it, is filled in this - // pass's round of stale ones; the sweep reached it many passes later. - if (partial_mips() && remapped && !t.stale && t.resource && !t.layout_guessed && - !t.layout_from_xg && (!t.fills || t.filled_from) && title_texture_readable(t) && - (!t.fills || t.readable_from < t.filled_from)) - t.stale = true; - if (write) t.stale = true; - if (overflow) t.hashed = false; - }; - if (!async || overflow || map_all) { - // No fills or callbacks during invalidation; registry iterators stay valid. - for (const auto& [key, ptr] : state_.title_textures) { - auto& t = *ptr; - const auto end = t.cpu + t.layout.layout.size; - const bool write = leonida::title_write_overlaps(written, t.cpu, end); - const bool remapped = leonida::title_write_overlaps(title_map_changes_, t.cpu, end); - if (write || map_all || overflow || remapped) invalidate(t, write, remapped || map_all); + t_after_mirror = clock::now(); + stats.examine_mirror_ns += std::uint64_t( + std::chrono::duration_cast(t_after_mirror - t_after_probe).count()); + + // Stage 4: dispatch unchanged skips, GPU mirror jobs, and CPU jobs into batched upload passes. + for (std::size_t idx = 0; idx < title_candidates_.size(); ++idx) { + TitleCandidate& cand = title_candidates_[idx]; + if (!cand.active || !cand.entry->resource) continue; + TitleTexture& t = *cand.entry; + const auto& ex = title_examine_results_[idx]; + const unsigned from = cand.from; + const std::uint64_t span = cand.span; + const std::size_t tiles = cand.tiles; + bool mirror_proved_changed = false; + + if (have_mirror) { + const auto& mc = title_mirror_checks_[idx]; + if (mc.full_ok) { + const bool had_mirror_hash = + t.fills && t.mirror_hash_valid && from == t.filled_from && span == t.mirror_hash_span; + if (had_mirror_hash && mc.mirror_hash == t.mirror_hash) { + ++stats.unchanged_parts; + ++stats.gpu_unchanged; + t.stale = false; + continue; + } + if (had_mirror_hash) mirror_proved_changed = true; + if (gpu_detile_on && from == 0 && mc.single_chunk) { + rt::d3d12::TitleImageUpload::UploadKind kind{}; + bool gpu_ok = false; + if (t.gpu_upload_cached_offset == mc.offset && t.gpu_upload_cached_chunk == mc.chunk_size) { + gpu_ok = t.gpu_upload_cached_ok; + kind = t.gpu_upload_cached_kind; + } else { + { + std::lock_guard upload(state_.title_upload_mutex); + gpu_ok = state_.title_upload.can_gpu_upload(state_, t.resource->title_binding(), + t.layout, mc.offset, mc.chunk_size, + kind); + } + t.gpu_upload_cached_offset = mc.offset; + t.gpu_upload_cached_chunk = mc.chunk_size; + t.gpu_upload_cached_ok = gpu_ok; + t.gpu_upload_cached_kind = kind; + } + if (gpu_ok) { + TitleJob& job = next_title_job(); + job.entry = cand.entry; + job.resource = t.resource; + job.span = span; + job.previous = (t.hashed && t.fills && !t.gpu_uploaded && t.filled_from == 0) + ? std::optional(t.hash) + : std::nullopt; + job.gpu_mirror = true; + job.gpu_kind = kind; + job.mirror_buffer = mc.buffer; + job.mirror_offset = mc.offset; + job.mirror_chunk_size = mc.chunk_size; + job.mirror_timeline = mc.timeline; + job.mirror_value = mc.value; + job.mirror_hash = mc.mirror_hash; + job.mirror_hash_valid = true; + if (!t.stale && !mirror_proved_changed && tiles > 1 && job.previous && + t.pieces.valid_for(t.cpu, job.span) && !ex.written.empty() && + ex.written.size() < tiles) { + job.compare = true; + job.written = ex.written; + } + if (kind == rt::d3d12::TitleImageUpload::UploadKind::mirror_detile) + gpu_scratch_bytes += job.span; + if (title_job_count_ >= kTitleGpuBatch || gpu_scratch_bytes >= kTitleGpuBatchBytes) + run_batch(); + continue; + } + } + } else if (mc.tile_cmp > 0) { + ++stats.unchanged_parts; + ++stats.gpu_unchanged; + t.stale = false; + continue; + } else if (mc.tile_cmp < 0) { + mirror_proved_changed = true; + } } - } else { - const auto apply = [&](const auto& ranges, bool write) { - for (const auto& [from, to] : ranges) - state_.texture_ranges.overlapping(from, to, [&](auto key) { - auto& t = *state_.title_textures.at(key); - invalidate(t, write, !write); - if (t.stale) queue_title_fill(key); - }); - }; - apply(title_map_changes_, false); - apply(written, true); - } - } - const auto every_start = clock::now(); - stats.written_ns += std::chrono::duration_cast(every_start - now).count(); - // LEONIDA_TITLE_EVERY_BUDGET_US (0, the default: no limit, as before) limits the synchronous pass, the one that - // runs before a submission on the title's submitting thread: the mapped and stale textures are visited for at - // most this long a pass, in address order from where the last pass stopped, instead of all of them every pass - // (thousands during a streaming burst on retail, 30-75 ms a pass). The texture that crosses the limit is - // finished; one not reached keeps its mark and waits for a later pass. With LEONIDA_TEXTURE_REFRESH_ASYNC the - // pass runs on the refresh worker, and the limit does not apply. - static const std::uint64_t every_budget_us = setting("LEONIDA_TITLE_EVERY_BUDGET_US", 0); - if (async) { - // Poll every persistent mapping each pass, independently of the bounded stale sweep. - const auto mapped = leonida::title_texture_snapshot(state_.mapped_title_textures); - for (const auto& [address, entry] : mapped) { - if (!entry->resource) continue; - const auto it = state_.title_textures.find(address); - if (it == state_.title_textures.end() || it->second != entry) continue; - ++stats.every_pass_visits; - visit(*entry); - } - for (const auto& entry : entries) - if (!entry.second->mapped && entry.second->stale) { - const auto it = state_.title_textures.find(entry.first); - if (it == state_.title_textures.end() || it->second != entry.second) continue; - ++stats.every_pass_visits; - visit(*entry.second); + + // CPU upload path: record fallback reason for telemetry, hash-before-reserve for ALL textures + // including tiles == 1 (`<= tiles`), and compare t.mirror_hash on whole reads so CPU fallback after a + // GPU upload never re-uploads unchanged bytes. + if (have_mirror) { + const auto& mc = title_mirror_checks_[idx]; + std::size_t bucket = 1; // unmirrored_other + if (mc.full_ok) { + bucket = mc.single_chunk ? 5 : 4; // can_gpu_rejected : multi_chunk + } else if (mc.reject_reason == 1) { + bucket = 0; // unmirrored_plain + } else if (mc.reject_reason == 3) { + bucket = 2; // in_feed + } else if (mc.reject_reason == 4) { + bucket = 3; // pending_bind + } + ++stats.cpu_fallback_by[bucket]; + } else { + ++stats.cpu_fallback_by[1]; // unmirrored_other } - } else if (!every_budget_us) { - for (const auto& entry : entries) - if (entry.second->mapped || entry.second->stale) { - ++stats.every_pass_visits; - visit(*entry.second); + TitleJob& job = next_title_job(); + job.entry = cand.entry; + job.resource = t.resource; + job.from = from; + job.span = span; + job.previous = (t.hashed && t.fills && !t.gpu_uploaded && from == t.filled_from) + ? std::optional(t.hash) + : std::nullopt; + job.previous_mirror_hash = + (t.fills && t.mirror_hash_valid && from == t.filled_from && span == t.mirror_hash_span) + ? std::optional(t.mirror_hash) + : std::nullopt; + job.compare = !t.stale && !mirror_proved_changed && job.previous && + t.pieces.valid_for(t.cpu, job.span) && !ex.written.empty() && + ex.written.size() <= tiles; + if (job.compare) { + job.written = ex.written; + } else if (!mirror_proved_changed) { + ++stats.whole_by[!job.previous && !job.previous_mirror_hash ? 0 + : !t.pieces.valid_for(t.cpu, job.span) ? 1 + : tiles == 1 ? 2 + : !ex.written.empty() ? 3 + : 4]; } + job.write_combined = t.is_write_combined(); + job.trace = leonida::dstorage::trace_enabled() && leonida::title_gpu_views::other_view(t.cpu); + ++cpu_job_count; + cpu_batch_bytes += job.span; + if (cpu_job_count >= kTitleBatch || cpu_batch_bytes >= kTitleBatchBytes || + title_job_count_ >= kTitleGpuBatch) + run_batch(); + } + title_candidates_.clear(); } else { - leonida::visit_marked_title_textures( - entries, title_every_cursor_, - [&](TitleTexture& t) { - ++stats.every_pass_visits; - visit(t); - }, - // A mapped texture never filled yet does not wait for its turn: the title has written it and the GPU - // has nothing of it (a video plane of #1827 would show frozen until its turn came). - [](const TitleTexture& t) { return t.mapped && !t.fills; }, - [&] { return clock::now() - every_start >= std::chrono::microseconds(every_budget_us); }); - } - stats.every_pass_ns += std::chrono::duration_cast(clock::now() - every_start).count(); - // The budget is the round robin's: mapped and stale textures above are checked every pass whatever it is - // (unless LEONIDA_TITLE_EVERY_BUDGET_US limits them). - const auto first_bytes = checked, first_hash_ns = stats.hash_ns; - if (check_budget) { - const auto sweep_start = clock::now(); - // The normal hash sweep has its own cursor: a byte/time cutoff in a slice must not - // skip the remainder next time just because the stale-texture sweep moved ahead. - decltype(leonida::title_texture_snapshot(state_.title_textures)) background; - if (async) { - if (!state_.title_textures.empty() && title_refresh_cursor_ > state_.title_textures.rbegin()->first) - title_refresh_cursor_ = 0; - background = leonida::title_texture_snapshot(state_.title_textures, title_refresh_cursor_, 128); - } - leonida::poll_title_textures(async ? background : entries, title_refresh_cursor_, visit, [&] { - if (checked - first_bytes >= check_budget || - (hash_budget_us && (stats.hash_ns - first_hash_ns) / 1000 >= hash_budget_us)) return true; - if (!sweep_budget_us) return false; - const auto elapsed = std::chrono::duration_cast(clock::now() - sweep_start); - return std::uint64_t(elapsed.count()) >= sweep_budget_us; - }); + t_after_mirror = clock::now(); + stats.examine_arm_ns += + std::uint64_t(std::chrono::duration_cast(t_after_mirror - fill_start).count()); + } + run_batch(); + watch.update_idle_hint(); + { + const auto fill_end = clock::now(); + const auto pass_fill = + std::uint64_t(std::chrono::duration_cast(fill_end - fill_start).count()); + const auto stage4_total = + std::uint64_t(std::chrono::duration_cast(fill_end - t_after_mirror).count()); + stats.fill_ns += pass_fill; + // What is not reading or submitting: naming, arming, mirror batch sync, readability, slot reservation. + const std::uint64_t other = (stats.read_ns - read_before) + (stats.staged_ns - staged_before); + stats.examine_publish_ns += stage4_total > other ? stage4_total - other : 0; + stats.examine_ns += pass_fill > other ? pass_fill - other : 0; } - stats.hashed += checked; stats.filled_bytes += filled; - stats.max_pass_bytes = std::max(stats.max_pass_bytes, filled); + stats.max_pass_bytes = (std::max)(stats.max_pass_bytes, filled); std::vector release; - std::erase_if(retired_title_textures_, [&](const auto& r) { - if (now - r.first < std::chrono::seconds(3)) return false; // descriptors may still be in flight - retired_backing_ -= r.second->image_backing_bytes(); - release.push_back(r.second); - return true; - }); + if (!retired_title_textures_.empty()) { + std::int64_t next_due = 0; + std::erase_if(retired_title_textures_, [&](const auto& r) { + if (now - r.first < std::chrono::seconds(3)) { + const std::int64_t due = std::chrono::duration_cast( + (r.first + std::chrono::seconds(3)).time_since_epoch()) + .count(); + if (next_due == 0 || due < next_due) next_due = due; + return false; + } + retired_backing_ -= r.second->image_backing_bytes(); + release.push_back(r.second); + return true; + }); + retired_earliest_ns_.store(next_due, std::memory_order_release); + } title_pass_ = false; const std::uint64_t pass_ns = std::chrono::duration_cast(clock::now() - now).count(); stats.refresh_ns += pass_ns; - stats.max_refresh_ns = std::max(stats.max_refresh_ns, pass_ns); + stats.max_refresh_ns = (std::max)(stats.max_refresh_ns, pass_ns); if (now - stats.last_log >= std::chrono::seconds(10)) { stats.last_log = now; - if (async) { - std::fprintf(stderr, "[rt] async texture refresh: %llu mapped checks, %llu changed or stale, %llu uploaded in pass\n", - static_cast(stats.mapped_checks), - static_cast(stats.mapped_changed), - static_cast(stats.mapped_fills)); - stats.mapped_checks = stats.mapped_changed = stats.mapped_fills = 0; - } + title_last_log_ns_.store(now_ns, std::memory_order_release); + const auto& w = watch.stats(); + const auto& l = title_watch_logged_; + std::size_t unnamed = 0; + for (const auto& [address, entry] : state_.title_textures) + unnamed += entry->resource && !entry->gpu_written && entry->layout_known && !entry->owned && + !entry->resource->shader_views(); + std::fprintf(stderr, + "[rt] d3d12: title texture refresh: %llu passes (%llu fast-path skipped); %llu textures " + "written or new, %llu read whole, %llu found unchanged by their written parts alone (%llu " + "GPU mirror-hashed), %llu " + "left for a kernel write in progress, %llu named over tiles not armed; %llu uploaded " + "(%.1f MiB; %llu CPU staged, %llu GPU linear, %llu GPU detiled), %llu read whole and " + "unchanged; %llu named for the first time, %zu not named by any descriptor (not read); %llu " + "written tiles, %llu arms (%llu busy, %llu refused), %llu queue overflows; %zu textures over " + "%zu tiles watched, %zu tiles not armed; %.3f ms a pass, %.3f at most\n", + static_cast(stats.passes), + static_cast(stats.fast_passes), + static_cast(stats.checked), + static_cast(stats.read_whole), + static_cast(stats.unchanged_parts), + static_cast(stats.gpu_unchanged), + static_cast(stats.busy), + static_cast(w.unarmed_named - l.unarmed_named), + static_cast(stats.changed), double(stats.filled_bytes) / 1048576.0, + static_cast(stats.staged_fills - stats.staged_fills_logged), + static_cast(stats.gpu_linear_fills), + static_cast(stats.gpu_detile_fills), + static_cast(stats.unchanged), + static_cast(stats.first_named), unnamed, + static_cast(w.written_tiles - l.written_tiles), + static_cast(w.arms - l.arms), + static_cast(w.arm_busy - l.arm_busy), + static_cast(w.arm_failures - l.arm_failures), + static_cast(w.overflows - l.overflows), watch.textures(), watch.tiles(), + watch.unarmed(), double(stats.refresh_ns) * 1e-6 / double((std::max)(std::uint64_t(1), stats.passes)), + double(stats.max_refresh_ns) * 1e-6); + const auto& o = state_.over_gpu_target; + std::fprintf(stderr, + "[rt] d3d12: textures over GPU-written memory: %llu views resolved to the GPU-written image; " + "not resolved: %llu format, %llu extent or samples, %llu mips or layers; %llu textures not " + "filled from it\n", + static_cast(o[DeviceState::kOverTargetResolved].load()), + static_cast(o[DeviceState::kOverTargetFormat].load()), + static_cast(o[DeviceState::kOverTargetExtent].load()), + static_cast(o[DeviceState::kOverTargetRange].load()), + static_cast(state_.gpu_owned_refusals)); + title_watch_logged_ = w; if (leonida::fsdraw::enabled()) log_title_census("refresh"); + stats.passes = stats.fast_passes = stats.checked = stats.busy = stats.changed = stats.unchanged = + stats.filled_bytes = 0; + stats.staged_fills_logged = stats.staged_fills; + stats.gpu_linear_fills = stats.gpu_detile_fills = 0; + std::fprintf(stderr, + "[rt] d3d12: title textures read whole, by why: %llu never filled, %llu with no part hashes, " + "%llu of one tile, %llu with every tile written, %llu with no tile written\n", + static_cast(stats.whole_by[0]), + static_cast(stats.whole_by[1]), + static_cast(stats.whole_by[2]), + static_cast(stats.whole_by[3]), + static_cast(stats.whole_by[4])); + stats.read_whole = stats.unchanged_parts = stats.gpu_unchanged = stats.first_named = 0; + stats.whole_by = {}; + const double per_pass = 1e-6 / double((std::max)(std::uint64_t(1), title_split_passes_)); + std::fprintf(stderr, + "[rt] d3d12: title texture pass split, ms a pass: %.3f finding what to look at (%.3f lock " + "wait), %.3f naming, arming and reserving (%.3f arm, %.3f readable (%llu probes), %.3f back " + "(%llu backed, %llu raw), %.3f mirror, %.3f publish), %.3f reading on %u threads (%.3f of it " + "detiling, summed over them; %.1f MiB read whole a pass), %.3f recording and submitting the " + "transfers\n", + double(stats.collect_ns) * per_pass, double(stats.lock_wait_ns) * per_pass, + double(stats.examine_ns) * per_pass, double(stats.examine_arm_ns) * per_pass, + double(stats.examine_readable_ns) * per_pass, + static_cast(stats.stage2_probes), + double(stats.examine_back_ns) * per_pass, + static_cast(stats.stage2_backed), + static_cast(stats.stage2_raw_allocs), + double(stats.examine_mirror_ns) * per_pass, + double(stats.examine_publish_ns) * per_pass, double(stats.read_ns) * per_pass, + title_read_pool_ ? title_read_pool_->threads() + 1 : 1, + double(stats.detile_ns) * per_pass, + double(stats.read_bytes) / 1048576.0 / double((std::max)(std::uint64_t(1), title_split_passes_)), + double(stats.staged_ns) * per_pass); + const auto arm_s = state_.texture_cells.arm_stats; + state_.texture_cells.arm_stats = {}; + std::fprintf(stderr, + "[rt] d3d12: title texture arm split: %llu hot, %llu already, %llu backed, %llu fast_vp " + "(%llu bridged), %llu vq (%llu cache_hit), %llu vq_vp; cpu fallback by: %llu " + "unmirrored_plain, %llu unmirrored_other, %llu in_feed, %llu pending_bind, %llu multi_chunk, " + "%llu can_gpu_rejected\n", + static_cast(arm_s.hot), static_cast(arm_s.already), + static_cast(arm_s.backed), static_cast(arm_s.fast_vp), + static_cast(arm_s.bridged), static_cast(arm_s.vq), + static_cast(arm_s.vq_cache), static_cast(arm_s.vq_vp), + static_cast(stats.cpu_fallback_by[0]), + static_cast(stats.cpu_fallback_by[1]), + static_cast(stats.cpu_fallback_by[2]), + static_cast(stats.cpu_fallback_by[3]), + static_cast(stats.cpu_fallback_by[4]), + static_cast(stats.cpu_fallback_by[5])); + stats.collect_ns = stats.lock_wait_ns = stats.examine_ns = stats.examine_arm_ns = stats.examine_probe_ns = + stats.examine_readable_ns = stats.examine_back_ns = stats.examine_mirror_ns = + stats.examine_publish_ns = stats.read_ns = stats.detile_ns = stats.read_bytes = 0; + stats.stage2_probes = stats.stage2_backed = stats.stage2_raw_allocs = 0; + stats.cpu_fallback_by = {}; + stats.staged_ns = 0; + title_split_passes_ = 0; + stats.refresh_ns = stats.max_refresh_ns = stats.max_pass_bytes = 0; } inside.reset(); lock.unlock(); @@ -16780,11 +23579,25 @@ class Device final std::map refused; // why a view is a null view -> views std::uint64_t views = 0, null_views = 0, of_slot133 = 0, of_cache = 0, made = 0, retired = 0, registered = 0, refusals = 0, written_ranges = 0, unmaps = 0, unreadable = 0, pending_views = 0; - std::uint64_t fills = 0, fill_bytes = 0, fill_failures = 0; + std::uint64_t fills = 0, fill_bytes = 0, fill_failures = 0, unchanged = 0, busy = 0; // Fills of some mips only; textures whose first fill was one; those that got larger mips later; first fills // refused by LEONIDA_TITLE_PARTIAL_MIPS_MB. std::uint64_t partial_fills = 0, partial_textures = 0, partial_upgrades = 0, partial_refused = 0; - std::uint64_t staged_fills = 0, staged_ns = 0; + std::uint64_t read_whole = 0, unchanged_parts = 0, first_named = 0; + std::array whole_by{}; // why read whole: first, no parts, one tile, all written, none + // Why Stage 4 fell back to CPU instead of GPU mirror: unmirrored_plain, unmirrored_other, in_feed, + // pending_bind, multi_chunk, can_gpu_rejected. + std::array cpu_fallback_by{}; + // Split of refresh_ns: waiting on title_texture_mutex (lock_wait_ns), up to the textures to look at (map + // changes, notes, the watch's queue), naming and arming them (examine, mirror batch, readability, slot + // reservation), the read threads' work (and of it the detile, summed over the threads), and the transfers' + // recording and submission (staged_ns); bytes read whole. + std::uint64_t lock_wait_ns = 0, collect_ns = 0, examine_ns = 0, read_ns = 0, detile_ns = 0, read_bytes = 0; + std::uint64_t examine_arm_ns = 0, examine_probe_ns = 0, examine_readable_ns = 0, examine_back_ns = 0, + examine_mirror_ns = 0, examine_publish_ns = 0; + std::uint64_t stage2_probes = 0, stage2_backed = 0, stage2_raw_allocs = 0; + std::uint64_t staged_fills = 0, staged_fills_logged = 0, staged_ns = 0; + std::uint64_t gpu_linear_fills = 0, gpu_detile_fills = 0, gpu_unchanged = 0, fast_passes = 0; // refresh_title_textures, since the last log line std::uint64_t passes = 0, checked = 0, hashed = 0, changed = 0, deferred = 0, filled_bytes = 0, max_pass_bytes = 0, hash_ns = 0, refresh_ns = 0, max_refresh_ns = 0; @@ -16800,7 +23613,73 @@ class Device final }; TitleTextureStats title_stats_; // under title_texture_mutex bool title_pass_ = false; // in refresh_title_textures, likewise - std::atomic title_refreshed_{0}; // steady_clock ticks of the last pass + struct TitleCandidate { + std::shared_ptr entry; + unsigned from = 0; + std::uint64_t span = 0; + std::size_t tiles = 0; + bool active = false; + }; + std::vector title_named_; // refresh scratch, under title_texture_mutex + std::vector title_candidate_keys_; // likewise + std::vector title_candidates_; // likewise + std::vector::BatchExamine> title_examine_results_; // likewise + std::vector title_mirror_checks_; // likewise + std::vector title_mirror_feed_pages_; // likewise + std::uint64_t title_split_passes_ = 0; // passes since the split's last log line + // One texture of a refresh batch: what the serial part found (the slot reserved for it, the last fill's hash) and + // what a TitleReadPool thread read (read_title_job). + struct TitleJob { + std::shared_ptr entry; + Resource* resource = nullptr; // the texture's, held by the registry for the pass + rt::d3d12::TitleImageUpload::Slot* slot = nullptr; + unsigned from = 0; + std::uint64_t span = 0, hash = 0; + std::optional previous; + std::optional previous_mirror_hash; + leonida::TilePieces pieces; // the texture's, then (read whole) the new ones + std::vector written; // its tiles written since its last read (compare) + bool compare = false, whole = false, precopied = false; + std::atomic failed{false}; // a piece of a whole read could not be copied + std::uint64_t detile_ns = 0; + bool write_combined = false, trace = false, copied = false, unchanged = false, nonzero = false; + // GPU mirror upload fields: + bool gpu_mirror = false; + rt::d3d12::TitleImageUpload::UploadKind gpu_kind = rt::d3d12::TitleImageUpload::UploadKind::cpu_slot; + VkBuffer mirror_buffer = VK_NULL_HANDLE; + VkDeviceSize mirror_offset = 0, mirror_chunk_size = 0; + VkSemaphore mirror_timeline = VK_NULL_HANDLE; + std::uint64_t mirror_value = 0; + std::uint64_t mirror_hash = 0; + bool mirror_hash_valid = false; + std::vector tiled; + std::vector piece_sums; + std::vector columns; + }; + static constexpr std::size_t kTitleBatch = 64; // CPU jobs processed together (<= kMaxSlots) + static constexpr std::size_t kTitleGpuBatch = 512; // total jobs (incl. GPU-mirror) per commit_batch + static constexpr std::uint64_t kTitleBatchBytes = 64ull << 20; // CPU-read bytes per batch + static constexpr std::uint64_t kTitleGpuBatchBytes = 128ull << 20; // GPU detile scratch bytes per batch + std::deque title_jobs_; // reusable job pool, under title_texture_mutex + std::size_t title_job_count_ = 0; // active jobs in current batch + std::vector title_cpu_check_indices_; // indices of jobs needing CPU read_title_job + std::vector title_detile_indices_; // indices of changed CPU jobs to detile + std::vector title_batch_items_; + std::vector title_batch_job_indices_; + std::atomic title_map_generation_atomic_{0}; + std::atomic retired_earliest_ns_{0}; + std::atomic title_last_log_ns_{0}; + std::atomic title_fast_passes_{0}; + std::atomic title_refresh_in_flight_{0}; + struct TitleChunk { + std::size_t job, first, end; // tiles [first, end) of title_jobs_[job] + }; + static constexpr std::size_t kTitleChunkTiles = 16; // 1 MiB of a texture a read thread copies at a time + std::vector title_chunks_; // likewise + class TitleReadPool; + std::unique_ptr title_read_pool_; + std::once_flag title_read_pool_once_; + leonida::TitleTextureWatch::Stats title_watch_logged_; // as of the last log line, likewise std::atomic refreshed_present_{~std::uint64_t(0)}; // LEONIDA_REFRESH_PER_FRAME: present of the last full refresh // LEONIDA_TITLE_FILL_ASYNC=1 (for runs that only need the title to go on): slot-70 views no longer fill or hash @@ -16819,7 +23698,7 @@ class Device final std::condition_variable wake; std::deque queue; // texture addresses std::unordered_set queued; - bool stop = false, refresh = false; + bool stop = false; std::thread thread; std::uint64_t filled = 0, skipped = 0; std::vector tiled; // the worker's own snapshot of a texture's bytes (fill_unlocked) @@ -16842,40 +23721,6 @@ class Device final f->thread = std::thread([this, f] { run_title_filler(*f); }); }); } - // LEONIDA_TEXTURE_REFRESH_ASYNC=1, before a submission: a mapped texture that has never been filled (a video plane - // the title maps, writes and draws right away) is filled here, on the submitting thread, so its first draw does not - // sample an empty image while the worker has not come to it yet. Everything else stays on the worker. Only when - // the registry is free: the worker may hold it for a fill that needs this queue, so waiting here could deadlock. - void fill_first_mapped_textures() { - std::unique_lock lock(state_.title_texture_mutex, std::try_to_lock); - if (!lock.owns_lock()) return; - std::vector> first; - for (const auto& [address, t] : state_.mapped_title_textures) - if (t->resource && !t->fills && !t->gpu_written && t->layout_known) first.push_back(t); - if (first.empty()) return; - { - const InTitleTextures inside; - for (const auto& t : first) { - // A fill can submit and retire an image (title_texture_gone): look each one up again. - const auto it = state_.title_textures.find(t->address); - if (it == state_.title_textures.end() || it->second != t || !t->resource || t->fills) continue; - fill_title_texture(*t, false); - if (t->stale) queue_title_fill(t->address); // generic staging needs an outer fill (the worker's) - } - } - lock.unlock(); - state_.drain_titles_gone(); - } - - void request_title_refresh() { - { - // A busy queue can take the next submission's request. Dirty entries stay on the worker. - std::unique_lock lock(title_filler_->mutex, std::try_to_lock); - if (!lock.owns_lock() || title_filler_->refresh) return; - title_filler_->refresh = true; - } - title_filler_->wake.notify_one(); - } void queue_title_fill(std::uint64_t address) { start_title_filler(); { @@ -16890,12 +23735,11 @@ class Device final auto since = clock::now(); for (;;) { std::uint64_t address = 0; - bool refresh = false, fill = false; + bool fill = false; { std::unique_lock lock(f.mutex); - f.wake.wait(lock, [&] { return f.stop || f.refresh || !f.queue.empty(); }); + f.wake.wait(lock, [&] { return f.stop || !f.queue.empty(); }); if (f.stop) return; - refresh = std::exchange(f.refresh, false); fill = !f.queue.empty(); if (fill) { address = f.queue.front(); @@ -16903,8 +23747,8 @@ class Device final f.queued.erase(address); } } - if (refresh) refresh_title_textures(); if (!fill) continue; + const leonida::submit_phases::WorkerScope busy(leonida::submit_phases::worker_texture_fill); bool filled = false; // A staged texture is filled without the registry lock (the title's threads creating views wait for // it: speed-31, 12 % of the main thread): its bytes, layout and resource are taken under the lock, the @@ -16914,7 +23758,6 @@ class Device final rt::xg_xs::Texture layout{}; std::uint64_t cpu = 0, fills = 0; unsigned from = 0; - bool every_byte = false; { std::lock_guard lock(state_.title_texture_mutex); const InTitleTextures inside; @@ -16931,16 +23774,15 @@ class Device final cpu = t.cpu; fills = t.fills; from = fill_from(t); - every_byte = t.every_byte(); } else { - filled = fill_title_texture(t, true) != 0; + filled = fill_title_texture(t) != 0; if (!filled) t.stale = true; } } } } if (r) { - filled = fill_unlocked(address, *r, layout, cpu, fills, from, every_byte, f); + filled = fill_unlocked(address, *r, layout, cpu, fills, from, f); r->Release(); } std::size_t left = 0; @@ -16964,17 +23806,19 @@ class Device final // The fill worker's fill of a staged texture: copy, hash and upload without the registry lock, then the result // under it, if the registry still names `r` at `address` and nobody filled it meanwhile. bool fill_unlocked(std::uint64_t address, Resource& r, const rt::xg_xs::Texture& layout, std::uint64_t cpu, - std::uint64_t fills, unsigned from, bool every_byte, TitleFiller& f) { + std::uint64_t fills, unsigned from, TitleFiller& f) { const std::uint64_t span = rt::xg_xs::mip_chain_bytes(layout, from); f.tiled.resize(std::size_t(span)); const bool copied = copy_guarded(f.tiled.data(), reinterpret_cast(cpu), std::size_t(span), title_memory_write_combined(cpu)); - std::uint64_t hash = 0, full = 0; - bool full_hashed = false, ok = false, nonzero = false; + std::uint64_t hash = 0, mirror_hash = 0; + bool ok = false, nonzero = false, mirror_hash_valid = false; + leonida::TilePieces pieces; std::uint64_t staged_ns = 0; if (copied) { - hash_guarded(f.tiled.data(), f.tiled.size(), hash); - full_hashed = every_byte && hash_guarded(f.tiled.data(), f.tiled.size(), full, true); + compute_pieces_and_mirror_hash(static_cast(cpu), span, f.tiled.data(), pieces, mirror_hash, + mirror_hash_valid); + hash = pieces.combined(); const auto start = std::chrono::steady_clock::now(); ok = r.upload_staged_title(layout, f.tiled.data(), f.columns, false, nonzero, from); staged_ns = std::chrono::duration_cast(std::chrono::steady_clock::now() - start) @@ -17000,10 +23844,13 @@ class Device final ++title_stats_.staged_fills; if (t.fills != fills) return true; // another fill recorded itself in between: its hash is as good note_filled_from(t, from); + t.gpu_uploaded = false; + t.mirror_hash = mirror_hash; + t.mirror_hash_span = mirror_hash_valid ? span : 0; + t.mirror_hash_valid = mirror_hash_valid; t.hash = hash; t.hashed = true; - t.full_hash = full; - t.full_hashed = full_hashed; + t.pieces = std::move(pieces); ++t.fills; ++title_stats_.fills; title_stats_.fill_bytes += span; @@ -17039,6 +23886,7 @@ class Device final if (r->stop) return; r->kick = false; } + const leonida::submit_phases::WorkerScope busy(leonida::submit_phases::worker_geometry); state_.geometry.refresh(DeviceState::copy_geometry); } }); @@ -17049,11 +23897,7 @@ class Device final } geometry_refresher_->wake.notify_one(); } - std::uint64_t title_slice_ = 0; // next registry slice on the async worker - std::uint64_t title_refresh_cursor_ = 0; // under title_texture_mutex - std::uint64_t title_every_cursor_ = 0; // likewise: LEONIDA_TITLE_EVERY_BUDGET_US's resume point - std::uint64_t title_map_generation_ = 0; // likewise: the map changes the passes have seen - std::chrono::steady_clock::time_point title_retry_all_{}; // likewise + std::uint64_t title_map_generation_ = 0; // under title_texture_mutex: the map changes seen leonida::TitleWriteRanges title_map_changes_; // likewise, scratch VkDeviceSize retired_backing_ = 0; VkDeviceSize title_partial_bytes_ = 0; // likewise: image memory of the textures filled in part, as of this pass @@ -17112,6 +23956,39 @@ class Device final }); } + // Exact physical layout equivalence between two built console layouts (mode, size, mips, array, slice_bytes, + // tile/block dimensions, and per-mip offsets/pitches/extents). Used so a format-compatible slot-70 view on an + // already-confirmed slot-133 texture does not invalidate hashed/mirror_hash_valid/gpu_uploaded. + static bool title_layout_equal(const rt::xg_xs::Texture& a, const rt::xg_xs::Texture& b) { + if (a.mode != b.mode || a.tile_width != b.tile_width || a.tile_height != b.tile_height || + a.tile_depth != b.tile_depth || a.array != b.array || a.slab_bytes != b.slab_bytes || + a.format.bytes != b.format.bytes || a.format.side != b.format.side || + a.layout.dimension != b.layout.dimension || a.layout.size != b.layout.size || + a.layout.alignment != b.layout.alignment || a.layout.mips != b.layout.mips || + a.layout.planes != b.layout.planes) + return false; + const auto& pa = a.layout.plane[0]; + const auto& pb = b.layout.plane[0]; + if (pa.size != pb.size || pa.slice_bytes != pb.slice_bytes || pa.standard_mips != pb.standard_mips || + pa.tail_mips != pb.tail_mips) + return false; + for (unsigned m = 0; m < a.layout.mips && m < rt::xg_xs::kMaxMips; ++m) { + const auto& ma = pa.mips[m]; + const auto& mb = pb.mips[m]; + if (ma.offset != mb.offset || ma.size != mb.size || ma.slice_bytes != mb.slice_bytes || + ma.pitch_texels != mb.pitch_texels || ma.pitch_bytes != mb.pitch_bytes || + ma.padded_width != mb.padded_width || ma.padded_height != mb.padded_height || + ma.padded_depth != mb.padded_depth || ma.width_elements != mb.width_elements || + ma.height_elements != mb.height_elements || ma.depth != mb.depth || ma.in_tail != mb.in_tail || + ma.swizzle != mb.swizzle || ma.tile_depth != mb.tile_depth || + a.volume_mips[m].macro_offset != b.volume_mips[m].macro_offset || + a.volume_mips[m].tail_x != b.volume_mips[m].tail_x || + a.volume_mips[m].tail_y != b.volume_mips[m].tail_y) + return false; + } + return true; + } + bool place_title_view(const rt::xg_xs::ResourceDesc& d, const std::array& words, const D3D12_SHADER_RESOURCE_VIEW_DESC& srv, std::uint64_t address, D3D12_CPU_DESCRIPTOR_HANDLE destination) { @@ -17126,11 +24003,16 @@ class Device final const auto it = textures.find(address); // An entry without a resource is one destroyed inside the registry, waiting for drain_titles_gone. TitleTexture* t = it == textures.end() || !it->second->resource ? nullptr : it->second.get(); - if (!t || !TitleGpuPlacements::matches(d, *t->resource)) { - if (Resource* gpu = matching_gpu_placement(d, address)) { - ++title_stats_.of_slot133; - return write_title_srv(*gpu, srv, destination, d, address); + // A GPU-written texture placed at the address with this description answers before the texture registered + // there (bind_title_image says why); with no view of it in the view's format, the registered one does. + if (Resource* gpu = matching_gpu_placement(d, address); gpu && (!t || t->resource != gpu)) { + ++title_stats_.of_slot133; + if (!t) return write_title_srv(*gpu, srv, destination, d, address); + if (write_title_srv(*gpu, srv, destination, d, address)) { + ++state_.over_gpu_target[DeviceState::kOverTargetResolved]; + return true; } + ++state_.over_gpu_target[DeviceState::kOverTargetFormat]; } if (t && !t->owned) { // the title's slot-133 texture ++title_stats_.of_slot133; @@ -17138,20 +24020,30 @@ class Device final const char* why = nullptr; rt::xg_xs::Texture layout; if (title_layout(d, layout, why) && title_layout_fits(layout, d, *t->resource, why)) { - static std::atomic logged{0}; - if (t->mapped && logged.fetch_add(1, std::memory_order_relaxed) < 32) - std::fprintf(stderr, - "[rt] d3d12: a slot-70 view gives mapped slot-133 texture 0x%llx its layout: Layout " - "0x%x (XG mode %u; was %s)\n", - static_cast(address), d.layout, layout.mode, - t->layout_guessed ? "guessed" : "unknown"); - t->memory.retry(); - t->layout = layout; - t->desc = words; - t->layout_known = true; - state_.index_texture(*t); - t->layout_guessed = t->layout_from_xg = false; - t->hashed = false; + const bool same_layout = t->layout_known && !t->layout_guessed && !t->layout_from_xg && + title_layout_equal(t->layout, layout); + if (same_layout) { + t->desc = words; + } else { + static std::atomic logged{0}; + if (t->mapped && logged.fetch_add(1, std::memory_order_relaxed) < 32) + std::fprintf(stderr, + "[rt] d3d12: a slot-70 view gives mapped slot-133 texture 0x%llx its layout: " + "Layout 0x%x (XG mode %u; was %s)\n", + static_cast(address), d.layout, layout.mode, + t->layout_guessed ? "guessed" : "unknown"); + t->memory.retry(); + t->write_combined_known = false; + t->gpu_uploaded = false; + t->mirror_hash_valid = false; + t->invalidate_gpu_upload_cache(); + t->layout = layout; + t->desc = words; + t->layout_known = true; + state_.index_texture(*t); + t->layout_guessed = t->layout_from_xg = false; + t->hashed = false; + } } else { refuse_title_view(why, d, address); // counted; the view of its image is still written } @@ -17163,12 +24055,13 @@ class Device final std::vector formats = t->formats; const bool same_shape = [&] { auto a = t->desc, b = words; - a[8] = b[8] = 0; // the format + a[1] = a[2] = a[3] = a[8] = a[13] = 0; // padding, alignment and format + b[1] = b[2] = b[3] = b[8] = b[13] = 0; return a == b && rt::xg_xs::format_info(t->desc[8]).bytes == rt::xg_xs::format_info(words[8]).bytes && rt::xg_xs::format_info(t->desc[8]).side == rt::xg_xs::format_info(words[8]).side; }(); retire_title_texture(*t); - state_.texture_ranges.erase(address); + state_.texture_watch.untrack(address); textures.erase(address); t = make_title_texture(d, words, srv, address, view_mip, same_shape ? formats : std::vector{}); } else if (t) { @@ -17184,11 +24077,16 @@ class Device final return t && write(*t); } - // An image made for slot-70 views serves another view when it has the description and the view's format. + // An image made for slot-70 views serves another view when all non-format/non-padding/non-alignment description + // words match and the image's mutable format list already covers both the resource format and the view's format. static bool title_texture_matches(const TitleTexture& t, const std::array& words, const D3D12_SHADER_RESOURCE_VIEW_DESC& srv) { + auto a = t.desc, b = words; + a[1] = a[2] = a[3] = a[8] = a[13] = 0; + b[1] = b[2] = b[3] = b[8] = b[13] = 0; + if (a != b) return false; const auto has = [&](DXGI_FORMAT f) { return std::find(t.formats.begin(), t.formats.end(), f) != t.formats.end(); }; - return t.desc == words && (srv.Format == DXGI_FORMAT_UNKNOWN || has(srv.Format)); + return has(DXGI_FORMAT(words[8])) && (srv.Format == DXGI_FORMAT_UNKNOWN || has(srv.Format)); } TitleTexture* make_title_texture(const rt::xg_xs::ResourceDesc& d, const std::array& words, @@ -17267,27 +24165,34 @@ class Device final entry->view_mip = view_mip; if (entry->memory.pending() && entry->readable_from <= fill_limit(*entry)) entry->memory.retry(); // some mips do for this view - const bool readable = title_texture_readable(*entry); - if (title_fill_async()) { - entry->stale = true; // filled by the fill worker (queued below, once it is in the registry) - } else if (readable) { - fill_title_texture(*entry, true); - } + // Defer slot-70 uploads to batched refresh_title_textures() (GPU detile + single batched vkQueueSubmit + // before GPU submission) instead of running a synchronous single-texture CPU upload inside CreateSRV. + // state_.index_texture(*entry) tracks and touches the watch since entry->stale == true. + entry->stale = true; + const bool readable = title_fill_async() && title_texture_readable(*entry); ++title_stats_.made; TitleTexture* t = entry.get(); state_.index_texture(*entry); state_.title_textures[address] = std::move(entry); - if (title_fill_async() && readable) queue_title_fill(address); + if (readable) queue_title_fill(address); return t; } void retire_title_texture(TitleTexture& t) { if (!t.owned || !t.resource) return; // Its T#s leave the hash table now (a later texture at the address takes them over); the image itself goes - // a few seconds later, when no submission can still read it. - if (t.resource->image_address()) state_.forget_image(t.resource->image_address()); + // a few seconds later, when no submission can still read it. Only while it still holds the address: a + // slot-133 texture placed there since (register_title_texture retires this entry right after the placement + // took the address over) keeps it, or every T# naming the address would find no texture. + if (t.resource->image_address()) state_.forget_image_of(t.resource->image_address(), t.resource); retired_backing_ += t.resource->image_backing_bytes(); - retired_title_textures_.emplace_back(std::chrono::steady_clock::now(), t.resource); + const auto retired_at = std::chrono::steady_clock::now(); + retired_title_textures_.emplace_back(retired_at, t.resource); + const std::int64_t due = std::chrono::duration_cast( + (retired_at + std::chrono::seconds(3)).time_since_epoch()) + .count(); + const std::int64_t prev = retired_earliest_ns_.load(std::memory_order_acquire); + if (prev == 0 || due < prev) retired_earliest_ns_.store(due, std::memory_order_release); t.resource = nullptr; ++title_stats_.retired; } @@ -17361,10 +24266,12 @@ class Device final // texture_memory_readable_bytes, timed and counted (TitleTextureStats::probes). // True when a fill can use what is readable; t.readable_from says what that is. - bool probe_title_texture(TitleTexture& t, bool waited, leonida::TexturePageCommitter commit = nullptr) { + bool probe_title_texture(TitleTexture& t, bool waited, leonida::TexturePageCommitter commit = nullptr, + leonida::TextureVqCache* vq_cache = nullptr) { const auto start = std::chrono::steady_clock::now(); t.readable_from = rt::xg_xs::first_mip_within( - t.layout, leonida::texture_memory_readable_bytes(std::uintptr_t(t.cpu), t.layout.layout.size, commit)); + t.layout, leonida::texture_memory_readable_bytes(std::uintptr_t(t.cpu), t.layout.layout.size, commit, + vq_cache)); const bool readable = t.readable_from <= fill_limit(t); const std::size_t where = title_pass_ ? 0 : 1; TitleTextureStats& s = title_stats_; @@ -17377,63 +24284,61 @@ class Device final } // A mapped texture can lose its pages between views or between refreshes. - bool title_texture_readable(TitleTexture& t) { + bool title_texture_readable(TitleTexture& t, leonida::TextureVqCache* vq_cache = nullptr) { 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) + if (!title_pass_ && guard) 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 - // retry of refresh_title_textures asks again. + // retry of refresh_title_textures asks again. Keep cache_failure = guard && !mapped (a mapped plane may commit + // via raw VirtualAlloc without notifying title_memory_map), while enabling cache_success = guard (unmaps + // notify title_memory_map and reads are SEH-guarded). return t.memory.check(0, guard && !mapped, - [&] { return probe_title_texture(t, waited, commit); }, - guard && !mapped); + [&] { return probe_title_texture(t, waited, commit, mapped ? nullptr : vq_cache); }, + guard); } - // LEONIDA_TITLE_VIEW_REFRESH_MS (0 by default: at every view): a texture's bytes are checked when a slot-70 view of - // it is written at most this often (the refresh pass still looks at it on its own period, and a stale texture is - // checked at once). After the load a title thread spent a fifth of its time hashing textures here, view by view - // (speed-24 wait sampler: refresh_title_texture < write_placed_texture_view < slot 70). + // At a slot-70 view of a texture: defer uploads to the batched refresh_title_textures() pass before GPU + // submission (setting stale = true AND touching texture_watch so the O(1) fast-path never skips it). void refresh_title_texture(TitleTexture& t) { - // LEONIDA_TITLE_FILL_ASYNC=1: a view neither hashes nor fills. A texture never filled or known stale goes to - // the fill worker; later changes are found by the periodic pass and the write journal, as before. + // LEONIDA_TITLE_FILL_ASYNC=1: a view does not fill; the texture goes to the fill worker. if (title_fill_async()) { if (!t.hashed || t.stale) queue_title_fill(t.address); return; } - static const auto period = std::chrono::milliseconds([] { - const char* v = std::getenv("LEONIDA_TITLE_VIEW_REFRESH_MS"); - return v && *v ? std::strtoll(v, nullptr, 10) : 0ll; - }()); - if (period.count() && t.hashed && !t.stale) { - const auto now = std::chrono::steady_clock::now(); - if (now - t.view_checked < period) return; - t.view_checked = now; + // If a deferred pending_stream image's pages have now arrived, back its VkImage and publish its views + // immediately so existing and new slot-70 descriptors get their bindless indices, while still deferring the + // texel upload to the batched refresh_title_textures() pass before GPU submission. + bool checked_readable = false; + bool is_readable = false; + if (t.unbound_bytes || (t.resource && t.resource->deferred_stream())) { + checked_readable = true; + is_readable = title_texture_readable(t); + if (is_readable) { + const unsigned from = fill_from(t); + if ((!from || !t.unbound_bytes || title_partial_bytes_ + t.unbound_bytes <= partial_mips_budget()) && + back_title_texture(t)) { + if (t.resource && t.resource->deferred_stream()) t.resource->publish_streamed_texture(from); + } + } } - std::uint64_t hash = 0; - if (!title_texture_readable(t)) return; - if (!hash_guarded(reinterpret_cast(static_cast(t.cpu)), - std::size_t(fill_bytes(t)), hash)) { - t.memory.defer(); - return; + if ((!t.hashed || t.stale) && + (!t.memory.pending() || (checked_readable ? is_readable : title_texture_readable(t)))) { + t.stale = true; + state_.texture_watch.touch(t.address); } - if (!t.hashed || hash != t.hash || t.stale) fill_title_texture(t, true); } - // Snapshot the footprint (that of the mips the fill is for) before uploading any subresource. A concurrent unmap - // defers the fill. - // Private title staging bypasses the D3D12 submit callbacks. Generic staged copies require an outer fill. - std::uint64_t fill_title_texture(TitleTexture& t, bool staged) { + // Snapshot the footprint (that of the mips the fill is for), then upload it through the title upload + // (TitleImageUpload): the transfer is submitted at once, ordered on the GPU after all earlier work and before every + // later submission, and nothing waits for the GPU on the CPU (VulkanContext::write_staged_title_image). It never + // re-enters the D3D12 submit callbacks, so the refresh before a submission may use it. A concurrent unmap defers + // the fill. + std::uint64_t fill_title_texture(TitleTexture& t) { const rt::xg_xs::Texture& layout = t.layout; - const std::uint32_t mips = layout.layout.mips, slices = layout.array; - if (!staged && !t.unbound_bytes && !t.resource->staged_title()) - for (UINT sub = 0; sub < mips * slices; ++sub) - if (!t.resource->host_copy_now(sub)) { - t.stale = true; - return 0; - } if (!title_texture_readable(t)) return 0; const unsigned from = fill_from(t); const std::uint64_t span = fill_bytes(t); @@ -17444,71 +24349,57 @@ class Device final } title_tiled_.resize(std::size_t(span)); if (!copy_guarded(title_tiled_.data(), reinterpret_cast(t.cpu), std::size_t(span), - title_memory_write_combined(t.cpu))) { + t.is_write_combined())) { // The section changed after VirtualQuery. Preserve the last complete upload and retry. t.memory.defer(); t.stale = true; return 0; } - if (!t.owned && t.unbound_bytes) { - if (!t.resource->image()) { - t.stale = true; - return 0; - } - t.set_resource(t.resource); - } - if (t.owned && t.unbound_bytes) { - if (!t.resource->back_streamed_texture()) { - t.stale = true; - return 0; - } - t.set_resource(t.resource); + if (!back_title_texture(t)) return 0; + // Every byte: a texture is read only when something says it changed, so this is its one read; bytes equal to + // the last fill's (a write to another texture in the same 64 KiB tile, or the same texels again) are not + // uploaded again. Uses 4-lane 256-byte piece hashing so both per-tile hashes and the full-texture mirror_hash + // are computed in one pass and match TitleMirror::range_sum() bit-for-bit on 256B-aligned textures. + leonida::TilePieces new_pieces; + std::uint64_t mirror_hash = 0; + bool mirror_hash_valid = false; + compute_pieces_and_mirror_hash(static_cast(t.cpu), span, title_tiled_.data(), new_pieces, + mirror_hash, mirror_hash_valid); + const std::uint64_t hash = new_pieces.combined(); + if (t.hashed && t.fills && !t.gpu_uploaded && from == t.filled_from && hash == t.hash) { + ++title_stats_.unchanged; + t.pieces = std::move(new_pieces); + if (mirror_hash_valid) { + t.mirror_hash = mirror_hash; + t.mirror_hash_span = span; + t.mirror_hash_valid = true; + } + t.stale = false; + return 0; } - std::uint64_t hash = 0; - hash_guarded(title_tiled_.data(), title_tiled_.size(), hash); - t.full_hashed = t.every_byte() && hash_guarded(title_tiled_.data(), title_tiled_.size(), t.full_hash, true); - const bool volume = layout.layout.dimension == rt::xg_xs::kTexture3D; const bool trace_pool = leonida::dstorage::trace_enabled() && leonida::title_gpu_views::other_view(t.cpu); bool nonzero = false; - bool ok = true; - if (t.resource->staged_title()) { - const auto start = std::chrono::steady_clock::now(); - ok = t.resource->upload_staged_title(layout, title_tiled_.data(), title_columns_, trace_pool, nonzero, from); - title_stats_.staged_ns += std::chrono::duration_cast( - std::chrono::steady_clock::now() - start).count(); - if (ok) ++title_stats_.staged_fills; - if (!ok) log_once("staged title texture upload failed, format", int(t.resource->format())); - } else { - for (std::uint32_t slice = 0; slice < slices && ok; ++slice) { - for (std::uint32_t level = from; level < mips && ok; ++level) { - const auto& mip = layout.layout.plane[0].mips[level]; - const std::uint32_t row_pitch = mip.width_elements * layout.format.bytes; - const std::uint32_t slice_pitch = row_pitch * mip.height_elements; - title_linear_.resize(std::size_t(slice_pitch) * (volume ? mip.depth : 1)); - rt::xg_xs::copy_elements(layout, level, slice, title_tiled_.data(), title_linear_.data(), - row_pitch, slice_pitch, title_columns_); - if (trace_pool && !nonzero) - nonzero = std::any_of(title_linear_.begin(), title_linear_.end(), [](auto byte) { return byte != 0; }); - const HRESULT hr = - t.resource->upload_title_subresource(level + slice * mips, title_linear_.data(), row_pitch, - slice_pitch, staged); - if (FAILED(hr)) { - log_once("a title texture's subresource could not be filled; HRESULT", int(hr)); - ok = false; - } - } - } - } + const auto start = std::chrono::steady_clock::now(); + const bool ok = + t.resource->upload_staged_title(layout, title_tiled_.data(), title_columns_, trace_pool, nonzero, from); + title_stats_.staged_ns += std::chrono::duration_cast( + std::chrono::steady_clock::now() - start).count(); + if (ok) ++title_stats_.staged_fills; + if (!ok) log_once("staged title texture upload failed, format", int(t.resource->format())); if (!ok) { ++title_stats_.fill_failures; t.stale = true; return 0; } if (trace_pool) - std::fprintf(stderr, "[rt] ds-pool-fill cpu=%llx size=%llu staged=%d nonzero=%d\n", - static_cast(t.cpu), static_cast(span), - int(staged), int(nonzero)); + std::fprintf(stderr, "[rt] ds-pool-fill cpu=%llx size=%llu staged=1 nonzero=%d\n", + static_cast(t.cpu), static_cast(span), int(nonzero)); note_filled_from(t, from); + t.gpu_uploaded = false; + t.mirror_hash = mirror_hash; + t.mirror_hash_span = mirror_hash_valid ? span : 0; + t.mirror_hash_valid = mirror_hash_valid; + t.pieces = std::move(new_pieces); t.hash = hash; t.hashed = true; t.stale = false; @@ -17518,6 +24409,262 @@ class Device final return span; } + // A texture whose image has no memory yet gets it before its first fill. False (and stale) when it cannot. + bool back_title_texture(TitleTexture& t, bool* did_back = nullptr, bool* did_raw_alloc = nullptr) { + if (!t.unbound_bytes) return true; + if (t.owned ? !t.resource->back_streamed_texture() : !t.resource->image()) { + t.stale = true; + return false; + } + if (did_back) *did_back = true; + if (did_raw_alloc && t.resource) *did_raw_alloc = !t.resource->pooled_image(); + t.mirror_hash_valid = false; + t.set_resource(t.resource); + return true; + } + + // Computes TilePieces (per-tile 256-byte piece-sum digests) and, when 256B-aligned, the full-texture + // TitleMirror::range_sum()-compatible digest in a single pass over `tiled` (4-lane ~18 GB/s). + static void compute_pieces_and_mirror_hash(std::uintptr_t cpu, std::uint64_t span, const std::uint8_t* tiled, + leonida::TilePieces& pieces, std::uint64_t& out_mirror_hash, + bool& out_mirror_valid) { + constexpr std::uint64_t kPiece = leonida::shadow_keep::kPiece; + const bool mirror_aligned = (cpu & (kPiece - 1)) == 0 && (span & (kPiece - 1)) == 0 && span != 0; + out_mirror_valid = mirror_aligned; + std::uint64_t full_h = mirror_aligned ? (14695981039346656037ull ^ span) : 0; + pieces.cpu = cpu; + pieces.span = span; + pieces.hashes.clear(); + pieces.hashes.reserve(leonida::TilePieces::tiles(cpu, span)); + for (std::uintptr_t tile = cpu & ~(leonida::TilePieces::kTile - 1); tile < cpu + span; + tile += leonida::TilePieces::kTile) { + const auto [offset, length] = leonida::TilePieces::part(cpu, span, tile); + std::uint64_t tile_h = 14695981039346656037ull ^ length; + for (std::uint64_t off = 0; off < length; off += kPiece) { + const std::size_t n = static_cast((std::min)(kPiece, length - off)); + const std::uint64_t s = leonida::shadow_keep::sum_of(tiled + offset + off, n); + tile_h = (tile_h ^ s) * 1099511628211ull; + tile_h ^= tile_h >> 29; + if (mirror_aligned) { + full_h = (full_h ^ s) * 1099511628211ull; + full_h ^= full_h >> 29; + } + } + pieces.hashes.push_back(tile_h); + } + out_mirror_hash = full_h; + } + + // Guarded 256-byte piece-sum digest for title memory: copies the written tile slice (<= 64 KiB, hot in L1/L2) via + // copy_guarded (SEH-safe under clang-cl/Wine, MOVNTDQA for write-combined pages, and handles xmem title_frames) + // and delegates directly to leonida::mirror_range_sum_bytes() -> shadow_keep::sum_of(). That keeps CPU tile + // hashes 100% bit-for-bit identical to TitleMirror::range_sum() regardless of SIMD implementation (scalar, SSE2, + // or AVX2) in shadow_keep::sum_of(). + static bool hash_title_piece_guarded(std::uintptr_t from, std::uint64_t bytes, bool write_combined, + std::uint64_t& out) { + if (!bytes) { + out = 0; + return true; + } + static thread_local std::vector scratch; + if (scratch.size() < bytes) scratch.resize(std::size_t(bytes)); + if (!copy_guarded(scratch.data(), reinterpret_cast(from), std::size_t(bytes), + write_combined)) + return false; + out = leonida::mirror_range_sum_bytes(scratch.data(), bytes); + return true; + } + + // A pass's first-stage hash check of one texture, on a TitleReadPool thread (before any staging slot is reserved): + // hashes only the written tiles (including 1-tile textures!). If unchanged, no staging reserve happens. For all + // 1-tile CPU-compared textures (cached or write-combined), copies once into the reusable job.tiled buffer so a + // changed 1-tile texture is never read twice and skips read_title_chunk completely. Reads job.entry->pieces + // directly without deep-copying its hash vector. + void read_title_job(TitleJob& job) { + const TitleTexture& t = *job.entry; + job.whole = false; + job.precopied = false; + if (job.gpu_mirror && !job.compare) return; + if (job.compare) { + if (!job.gpu_mirror && job.written.size() == 1 && t.pieces.hashes.size() == 1 && + job.span <= leonida::TilePieces::kTile) { + job.tiled.resize(std::size_t(job.span)); + if (!copy_guarded(job.tiled.data(), reinterpret_cast(t.cpu), std::size_t(job.span), + job.write_combined)) { + job.copied = false; + return; + } + const std::uint64_t h = leonida::mirror_range_sum_bytes(job.tiled.data(), job.span); + if (h == t.pieces.hashes[0]) { + job.copied = job.unchanged = true; + return; + } + job.pieces.reset(t.cpu, job.span); + job.pieces.hashes[0] = h; + const bool mirror_aligned = (t.cpu & (leonida::shadow_keep::kPiece - 1)) == 0 && + (job.span & (leonida::shadow_keep::kPiece - 1)) == 0; + job.mirror_hash = mirror_aligned ? h : 0; + job.mirror_hash_valid = mirror_aligned; + job.copied = true; + job.precopied = true; + job.whole = true; + return; + } + if (t.pieces.unchanged(job.written, [&](std::uintptr_t from, std::uint64_t bytes) { + std::uint64_t h = 0; + return hash_title_piece_guarded(from, bytes, job.write_combined, h) ? std::optional(h) + : std::nullopt; + })) { + job.copied = job.unchanged = true; + return; + } + } + if (!job.gpu_mirror) job.whole = true; + } + + // The bytes of tiles [first, end) of a texture read whole (its parts), and their hashes: a texture of many tiles + // is read by several threads at once (a 4K video plane, a streamed texture), not by one. Computes each 256-byte + // piece sum once into job.piece_sums (when 256B-aligned) and mixes each tile's hash simultaneously. + void read_title_chunk(TitleJob& job, std::size_t first, std::size_t end) { + const TitleTexture& t = *job.entry; + const std::uintptr_t base = t.cpu & ~std::uintptr_t(0xffff); + const auto [from, unused] = leonida::TilePieces::part(t.cpu, job.span, base + first * 0x10000); + const auto [last_offset, last_length] = leonida::TilePieces::part(t.cpu, job.span, base + (end - 1) * 0x10000); + const std::uint64_t to = last_offset + last_length; + if (!copy_guarded(job.tiled.data() + from, reinterpret_cast(t.cpu + from), + std::size_t(to - from), job.write_combined)) { + job.failed.store(true, std::memory_order_relaxed); + return; + } + constexpr std::uint64_t kPiece = leonida::shadow_keep::kPiece; + const bool store_sums = !job.piece_sums.empty(); + for (std::size_t i = first; i < end; ++i) { + const auto [offset, length] = leonida::TilePieces::part(t.cpu, job.span, base + i * 0x10000); + std::uint64_t tile_h = 14695981039346656037ull ^ length; + std::size_t piece_idx = store_sums ? static_cast(offset / kPiece) : 0; + for (std::uint64_t off = 0; off < length; off += kPiece) { + const std::size_t n = static_cast((std::min)(kPiece, length - off)); + const std::uint64_t s = leonida::shadow_keep::sum_of(job.tiled.data() + offset + off, n); + tile_h = (tile_h ^ s) * 1099511628211ull; + tile_h ^= tile_h >> 29; + if (store_sums) job.piece_sums[piece_idx++] = s; + } + job.pieces.hashes[i] = tile_h; + } + } + + // After whole-read chunks finish: combine the piece hashes (and mirror_hash from precomputed 256-byte sums) and + // determine if bytes changed (BEFORE reserving any staging slot). Runs inline on the calling thread. + void hash_title_job(TitleJob& job) { + if (!job.whole || job.gpu_mirror) return; + if (!job.precopied) { + job.copied = !job.failed.load(std::memory_order_relaxed); + if (!job.copied) return; + if (!job.piece_sums.empty()) { + job.mirror_hash = + leonida::mirror_range_sum_from_pieces(job.piece_sums.data(), job.piece_sums.size(), job.span); + job.mirror_hash_valid = true; + } + } + job.hash = job.pieces.combined(); + const bool same_hash = job.previous && *job.previous == job.hash; + const bool same_mirror = + job.previous_mirror_hash && job.mirror_hash_valid && *job.previous_mirror_hash == job.mirror_hash; + job.unchanged = same_hash || same_mirror; + } + + // Parallel CPU detile into the staging slot reserved ONLY for changed CPU jobs. + void detile_title_job(TitleJob& job) { + const auto detile_start = std::chrono::steady_clock::now(); + job.nonzero = false; + rt::d3d12::TitleImageUpload::fill(*job.slot, job.resource->title_binding(), job.entry->layout, job.tiled.data(), + job.columns, job.trace, job.nonzero); + job.detile_ns = std::uint64_t(std::chrono::duration_cast( + std::chrono::steady_clock::now() - detile_start) + .count()); + } + + // A few threads of ours for the refresh's reads: run(n, f) calls f(0..n-1) on them and on the calling thread, + // and returns when all are done. Runs count <= 1 directly inline with zero mutex/condvar/wakeup overhead. + class TitleReadPool { + public: + explicit TitleReadPool(unsigned threads) { + for (unsigned i = 0; i < threads; ++i) threads_.emplace_back([this] { serve(); }); + } + ~TitleReadPool() { + { + std::lock_guard lock(mutex_); + stop_ = true; + } + wake_.notify_all(); + for (auto& thread : threads_) thread.join(); + } + TitleReadPool(const TitleReadPool&) = delete; + TitleReadPool& operator=(const TitleReadPool&) = delete; + void run(std::size_t count, std::function work) { + if (!count) return; + if (count == 1 || threads_.empty()) { + for (std::size_t i = 0; i < count; ++i) work(i); + return; + } + { + std::lock_guard lock(mutex_); + work_ = std::move(work); + count_ = count; + next_.store(0, std::memory_order_relaxed); + busy_ = threads_.size(); + ++generation_; + } + wake_.notify_all(); + drain(work_); + std::unique_lock lock(mutex_); + done_.wait(lock, [&] { return busy_ == 0; }); + work_ = nullptr; + } + + private: + void drain(const std::function& work) { + for (std::size_t i; (i = next_.fetch_add(1, std::memory_order_relaxed)) < count_;) work(i); + } + void serve() { + std::uint64_t seen = 0; + for (;;) { + std::function work; + { + std::unique_lock lock(mutex_); + wake_.wait(lock, [&] { return stop_ || generation_ != seen; }); + if (stop_) return; + seen = generation_; + work = work_; + } + { + const leonida::submit_phases::WorkerScope busy(leonida::submit_phases::worker_texture_reads); + drain(work); + } + std::lock_guard lock(mutex_); + if (!--busy_) done_.notify_all(); + } + } + std::mutex mutex_; + std::condition_variable wake_, done_; + std::function work_; + std::size_t count_ = 0, busy_ = 0; + std::atomic next_{0}; + std::uint64_t generation_ = 0; + bool stop_ = false; + std::vector threads_; + + public: + unsigned threads() const { return unsigned(threads_.size()); } + }; + TitleReadPool& title_read_pool() { + std::call_once(title_read_pool_once_, [this] { + const unsigned cores = std::max(1u, std::thread::hardware_concurrency()); + title_read_pool_ = std::make_unique(std::clamp(cores / 4, 1u, 7u)); + }); + return *title_read_pool_; + } + static bool title_memory_write_combined(std::uint64_t address) { MEMORY_BASIC_INFORMATION region{}; return VirtualQuery(reinterpret_cast(static_cast(address)), ®ion, @@ -17621,10 +24768,7 @@ class Device final static_cast(s.partial_upgrades), static_cast(s.partial_refused)); } - const auto host = state_.context->host_texture_stats(); - std::fprintf(stderr, "[rt] d3d12: ordered title host copies %llu, GPU waits %llu; " - "slot-70 views awaiting readable memory: %llu\n", - static_cast(host.copies), static_cast(host.waits), + std::fprintf(stderr, "[rt] d3d12: slot-70 views awaiting readable memory: %llu\n", static_cast(s.pending_views)); std::fprintf(stderr, "[rt] d3d12: title textures census (format/Layout/dimension/mips:views): %s\n", census.c_str()); @@ -17679,7 +24823,9 @@ class Device final static_cast(s.probes[1]), double(s.probe_ns[1]) * 1e-6, static_cast(s.rechecks[1]), static_cast(s.readable_now[1])); - s.passes = s.checked = s.hashed = s.changed = s.deferred = s.filled_bytes = s.max_pass_bytes = 0; + // passes, checked, changed and filled_bytes belong to the refresh's own 10 s line, which resets them: reset + // here too (LEONIDA_FSDRAW_PROBE prints this census far more often) they read 0 uploads there (run 64). + s.hashed = s.deferred = 0; std::fprintf(stderr, "[rt] title texture pass split: written ranges and map changes %.3f ms/pass (%.1f map ranges a " "pass, %llu passes probed all), mapped and stale textures %.3f ms/pass (%.1f visited a pass), " @@ -17729,9 +24875,15 @@ class Device final const auto available = std::min(block_size, size_ - base); auto* window = cache_.data() + slot * block_size; if (tags_[slot] != block) { - SIZE_T copied{}; - if (!ReadProcessMemory(GetCurrentProcess(),reinterpret_cast(address_+base), - window,available,&copied) || copied!=available) return false; + // A page xmem's frame table holds (no host view: src/title_frames.h) is read through its frame. + const auto from = static_cast(address_ + base); + if (!leonida::title_frames::for_each_part(from, available, + [&](std::uintptr_t at, std::size_t n, std::uint8_t* frame) { + if (frame) return copy_guarded_host(window + (at - from), frame, n, false); + SIZE_T copied{}; + return ReadProcessMemory(GetCurrentProcess(), reinterpret_cast(at), + window + (at - from), n, &copied) && copied == n; + })) return false; tags_[slot]=block; } const auto n=std::min(bytes,available-(offset-base)); @@ -18850,7 +26002,9 @@ class Device final return !(GetEnvironmentVariableW(L"LEONIDA_CBV_RAW", value, 2) == 1 && value[0] == L'1'); }(); const uint64_t rows = (uint64_t(desc->SizeInBytes) + 15) / 16; - buffer.address = state_.vsharp_address(buffer.address, console_form ? rows * 16 : desc->SizeInBytes); + buffer.address = state_.vsharp_address(buffer.address, console_form ? rows * 16 : desc->SizeInBytes, + leonida::TitleVaAliases::created_view, true, false, nullptr, nullptr, + nullptr, false); // No backing for the title's memory: a zero-size V# (loads 0, stores dropped), never the raw address. const bool backed = buffer.address != 0; if (!backed) { @@ -18954,7 +26108,8 @@ class Device final if (!state_.has_console_descriptor_copy(destination.ptr)) buffer.address = copy; } else { const std::uint64_t target = buffer.address; - buffer.address = state_.vsharp_address(buffer.address, bytes); + buffer.address = state_.vsharp_address(buffer.address, bytes, leonida::TitleVaAliases::created_view, true, + false, nullptr, nullptr, nullptr, false); // No backing: no records, so loads return 0 and stores are dropped (never a raw title base). if (!buffer.address) { buffer.stride = 0, buffer.num_records = 0; @@ -19716,6 +26871,8 @@ class Device final // LEONIDA_TITLE_BUFFERS_MB (512 by default). void make_title_buffer(std::uint64_t va, std::uint64_t bytes) { if (!&context()) return; + // The page mirror holds these pages: the draw reads them there (VulkanContext's mirror lookup), no buffer. + if (state_.page_mirror_resolve(va, std::max(bytes, 1))) return; static const bool check_size = [] { wchar_t flag[2]{}; return !(GetEnvironmentVariableW(L"LEONIDA_TITLE_BUFFER_COVERAGE", flag, 2) == 1 && flag[0] == L'0'); @@ -19743,6 +26900,13 @@ class Device final const std::uint64_t start = std::max(va & ~(align - 1), lo); std::uint64_t end = std::min(hi, (va + std::clamp(bytes, 1, most) + align - 1) & ~(align - 1)); for (std::uint64_t at = start; at < end;) { // the committed, readable part only + // A page xmem's frame table holds (no host view: src/title_frames.h) is read through its frame. + bool table = false; + const std::uint64_t run = leonida::title_frames::run_end(std::uintptr_t(at), std::uintptr_t(end), table); + if (table) { + at = run; + continue; + } MEMORY_BASIC_INFORMATION region{}; if (!VirtualQuery(reinterpret_cast(static_cast(at)), ®ion, sizeof(region)) || region.State != MEM_COMMIT || !region.Protect || (region.Protect & (PAGE_NOACCESS | PAGE_GUARD))) { @@ -19886,6 +27050,8 @@ class Device final heap.MemoryPoolPreference = D3D12_MEMORY_POOL_L0; auto* resource = new Resource(state_, desc, heap, D3D12_HEAP_FLAG_NONE); resource->attach_device(identity()); + // Title memory the page mirror holds: the buffer is the mirror's chunk there (no import, no shadow). + if (SUCCEEDED(resource->create_mirror_buffer(address))) return d3d12_trace::result(method, hand_out(resource, riid, out)); const HRESULT hr = resource->create_host_buffer(address); if (hr == E_INVALIDARG) { resource->Release(); @@ -19947,7 +27113,7 @@ class Device final log_once((std::string("CreateHeap refused (") + why + "), heap type").c_str(), int(desc->Properties.Type)); return E_INVALIDARG; } - if (!state_.arena.mapped) { + if (!state_.arena_ready()) { log_once("heaps need the GPU address arena (bufferDeviceAddress); heap size in KiB:", int(desc->SizeInBytes / 1024)); return E_NOTIMPL; @@ -21320,6 +28486,8 @@ class Device final log_once("shader access to 1D and 3D UAVs requires robustImageAccess; type", int(view.type)); } else { const bool known_heap = state_.known_view_heap(destination.ptr); + // A deferred view has no index yet: its slot gets the index word when the view is made + // (materialize_table, write_tsharp_index_words). if (!storage && resource.deferrable_sample() && state_.info.prepare_on_bind && known_heap && !g::multisampled(image.type)) { state_.remember_sample(words,{const_cast(&resource),image,view_format,channels_format}); @@ -21328,11 +28496,21 @@ class Device final } const auto bound = const_cast(resource).bound_image(); if (!bound) { log_once("unable to make a placed shader image resident; format", int(resource.desc().Format)); return; } + const bool maybe_evictable = + !storage && !known_heap && !g::multisampled(image.type) && + state_.console_heap_count.load(std::memory_order_acquire) > 0 && + !(resource.desc().Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); const bool registered = state_.bind_image(words, image, bound, view_format, channels_format, storage_format, resource.aspects(), - sampled, storage, slices); + sampled, storage, slices, + maybe_evictable ? static_cast(&resource) : nullptr); if (registered && (resource.sparse_image() || storage_plane)) state_.context->note_shader_image(resource.id()); if (!registered && (g::multisampled(image.type) || storage_plane)) return; + // In the layer's own heaps the bytes written here are what shaders load: dword 6 carries the index + // (gfx10_descriptors.h, tsharp_index_word; 0 while the T# has none). A console heap (the title's memory) + // is left as the title's own write would be: its copy gets the word when the slot is fixed. + if (state_.tsharp_index_words && known_heap) + words[g::kTsharpIndexDword] = state_.tsharp_index_word(words); } // The CPU UAV used by ClearUnorderedAccessView is independent of set 0. std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); @@ -22242,6 +29420,228 @@ std::uint64_t device_arena_size(ID3D12Device* device) { return d ? d->state().arena.size : 0; } +PageMirrorState page_mirror_state(ID3D12Device* device) { + if (!device) return {}; + ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); + if (!real) real = device; + const Device* d = Device::from(real); + if (!d) return {}; + auto& state = const_cast(d->state()); + std::lock_guard lock(state.page_mirror.mutex); + PageMirrorState out; + if (!state.page_mirror.mirror) return out; + const auto c = state.page_mirror.mirror->counters(); + out.on = true; + out.heap_base = state.arena.address; + out.pages = c.pages; + out.homes = c.homes; + out.chunks = c.chunks; + out.uploads = c.uploads; + out.binds = c.binds; + return out; +} + +namespace { +// `bytes` of `buffer` at `offset` into `out`, copied by the GPU after the page mirror's bind `wait`. For tests. +bool gpu_buffer_read(DeviceState& state, VkBuffer chunk, VkDeviceSize offset, std::uint64_t wait, void* out, + std::size_t bytes) { + auto& vk = state.context->vk; + const VkDevice dev = state.info.device; + VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; + info.size = bytes; + info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT; + VkBuffer readback = VK_NULL_HANDLE; + if (vk.vkCreateBuffer(dev, &info, nullptr, &readback) != VK_SUCCESS) return false; + VkMemoryRequirements requirements{}; + vk.vkGetBufferMemoryRequirements(dev, readback, &requirements); + VkDeviceMemory memory = state.allocate(requirements, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | + VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, 0); + VkCommandPool pool = VK_NULL_HANDLE; + VkCommandBuffer commands = VK_NULL_HANDLE; + bool ok = memory && vk.vkBindBufferMemory(dev, readback, memory, 0) == VK_SUCCESS; + VkCommandPoolCreateInfo pool_info{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; + pool_info.queueFamilyIndex = state.info.queue_family; + ok = ok && vk.vkCreateCommandPool(dev, &pool_info, nullptr, &pool) == VK_SUCCESS; + VkCommandBufferAllocateInfo allocate{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; + allocate.commandPool = pool; + allocate.commandBufferCount = 1; + ok = ok && vk.vkAllocateCommandBuffers(dev, &allocate, &commands) == VK_SUCCESS; + if (ok) { + VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; + vk.vkBeginCommandBuffer(commands, &begin); + const VkBufferCopy region{offset, 0, bytes}; + vk.vkCmdCopyBuffer(commands, chunk, readback, 1, ®ion); + vk.vkEndCommandBuffer(commands); + VkTimelineSemaphoreSubmitInfo values{VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO}; + values.waitSemaphoreValueCount = 1; + values.pWaitSemaphoreValues = &wait; + const VkPipelineStageFlags stage = VK_PIPELINE_STAGE_TRANSFER_BIT; + VkSubmitInfo submit{VK_STRUCTURE_TYPE_SUBMIT_INFO, &values}; + submit.waitSemaphoreCount = 1; + submit.pWaitSemaphores = &state.page_mirror.timeline; + submit.pWaitDstStageMask = &stage; + submit.commandBufferCount = 1; + submit.pCommandBuffers = &commands; + std::lock_guard lock(state.context->submit_mutex()); + ok = vk.vkQueueSubmit(state.info.queue, 1, &submit, VK_NULL_HANDLE) == VK_SUCCESS && + vk.vkQueueWaitIdle(state.info.queue) == VK_SUCCESS; + } + void* mapped = nullptr; + if (ok && vk.vkMapMemory(dev, memory, 0, VK_WHOLE_SIZE, 0, &mapped) == VK_SUCCESS) { + std::memcpy(out, mapped, bytes); + vk.vkUnmapMemory(dev, memory); + } else { + ok = false; + } + if (pool) vk.vkDestroyCommandPool(dev, pool, nullptr); + vk.vkDestroyBuffer(dev, readback, nullptr); + if (memory) vk.vkFreeMemory(dev, memory, nullptr); + return ok; +} +DeviceState* mirror_state(ID3D12Device* device) { + if (!device) return nullptr; + ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); + if (!real) real = device; + const Device* d = Device::from(real); + if (!d) return nullptr; + auto& state = const_cast(d->state()); + return state.page_mirror.mirror && state.context ? &state : nullptr; +} +} // namespace + +bool page_mirror_gpu_read(ID3D12Device* device, std::uint64_t title_va, void* out, std::size_t bytes) { + DeviceState* state = mirror_state(device); + if (!state || !out || !bytes) return false; + state->refresh_page_mirror(); + state->flush_page_mirror(); + VkBuffer chunk = VK_NULL_HANDLE; + VkDeviceSize offset = 0; + std::uint64_t wait = 0; + { + std::lock_guard lock(state->page_mirror.mutex); + if (!state->page_mirror.mirror->chunk_at(title_va, chunk, offset)) return false; + wait = state->page_mirror.value; + } + return gpu_buffer_read(*state, chunk, offset, wait, out, bytes); +} + +bool arena_gpu_read(ID3D12Device* device, std::uint64_t va, void* out, std::size_t bytes) { + DeviceState* state = mirror_state(device); + if (!state || !out || !bytes || va > state->arena.size || bytes > state->arena.size - va) return false; + // As a submission does: the mirror (heaps read in place filtered as their pages fill), the heaps (what the filter + // left), then the binds. + state->refresh_page_mirror(); + state->refresh_console_heaps(); + state->flush_page_mirror(); + std::uint64_t wait = 0; + { + std::lock_guard lock(state->page_mirror.mutex); + wait = state->page_mirror.value; + } + return gpu_buffer_read(*state, state->arena.buffer, va, wait, out, bytes); +} + +bool set_tsharp_index_words_for_test(ID3D12Device* device, bool on) { + DeviceState* state = mirror_state(device); + if (!state) return false; + const bool was = state->tsharp_index_words; + state->tsharp_index_words = on; + return was; +} + +bool page_mirror_buffer_at(ID3D12Device* device, std::uint64_t va, std::uint64_t& size) { + ID3D12Device* real = device ? rt::d3d12_xs::device_proxy_real_device(device) : nullptr; + if (!real) real = device; + const Device* d = real ? Device::from(real) : nullptr; + if (!d) return false; + VkBuffer buffer = VK_NULL_HANDLE; + VkDeviceSize offset = 0; + return const_cast(d->state()).page_mirror_buffer(va, size, buffer, offset); +} + +bool page_mirror_gpu_write(ID3D12Device* device, std::uint64_t title_va, const void* data, std::size_t bytes) { + ID3D12Device* real = device ? rt::d3d12_xs::device_proxy_real_device(device) : nullptr; + if (!real) real = device; + const Device* d = real ? Device::from(real) : nullptr; + if (!d || !data || !bytes || bytes > 65536 || (bytes & 3) || (title_va & 3)) return false; + auto& state = const_cast(d->state()); + if (!state.page_mirror.mirror || !state.context) return false; + state.refresh_page_mirror(); + state.flush_page_mirror(); + VkBuffer chunk = VK_NULL_HANDLE; + VkDeviceSize offset = 0; + std::uint64_t wait = 0; + { + std::lock_guard lock(state.page_mirror.mutex); + if (!state.page_mirror.mirror->chunk_at(title_va, chunk, offset)) return false; + wait = state.page_mirror.value; + } + auto& vk = state.context->vk; + const VkDevice dev = state.info.device; + VkCommandPool pool = VK_NULL_HANDLE; + VkCommandBuffer commands = VK_NULL_HANDLE; + VkCommandPoolCreateInfo pool_info{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; + pool_info.queueFamilyIndex = state.info.queue_family; + bool ok = vk.vkCreateCommandPool(dev, &pool_info, nullptr, &pool) == VK_SUCCESS; + VkCommandBufferAllocateInfo allocate{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; + allocate.commandPool = pool; + allocate.commandBufferCount = 1; + ok = ok && vk.vkAllocateCommandBuffers(dev, &allocate, &commands) == VK_SUCCESS; + if (ok) { + VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; + vk.vkBeginCommandBuffer(commands, &begin); + vk.vkCmdUpdateBuffer(commands, chunk, offset, bytes, data); + vk.vkEndCommandBuffer(commands); + VkTimelineSemaphoreSubmitInfo values{VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO}; + values.waitSemaphoreValueCount = 1; + values.pWaitSemaphoreValues = &wait; + const VkPipelineStageFlags stage = VK_PIPELINE_STAGE_TRANSFER_BIT; + VkSubmitInfo submit{VK_STRUCTURE_TYPE_SUBMIT_INFO, &values}; + submit.waitSemaphoreCount = 1; + submit.pWaitSemaphores = &state.page_mirror.timeline; + submit.pWaitDstStageMask = &stage; + submit.commandBufferCount = 1; + submit.pCommandBuffers = &commands; + std::lock_guard lock(state.context->submit_mutex()); + ok = vk.vkQueueSubmit(state.info.queue, 1, &submit, VK_NULL_HANDLE) == VK_SUCCESS && + vk.vkQueueWaitIdle(state.info.queue) == VK_SUCCESS; + } + if (pool) vk.vkDestroyCommandPool(dev, pool, nullptr); + return ok; +} + +std::uint64_t page_mirror_write_back(ID3D12Device* device, std::uint64_t va, std::uint64_t bytes) { + ID3D12Device* real = device ? rt::d3d12_xs::device_proxy_real_device(device) : nullptr; + if (!real) real = device; + const Device* d = real ? Device::from(real) : nullptr; + return d ? const_cast(d->state()).page_mirror_write_back(va, va + bytes) : 0; +} + +bool page_mirror_name(ID3D12Device* device, std::uint64_t va, std::uint64_t bytes) { + ID3D12Device* real = device ? rt::d3d12_xs::device_proxy_real_device(device) : nullptr; + if (!real) real = device; + const Device* d = real ? Device::from(real) : nullptr; + return d && const_cast(d->state()).page_mirror_resolve(va, bytes); +} + +ArenaMemoryState device_arena_memory(ID3D12Device* device) { + if (!device) return {}; + ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); + if (!real) real = device; + const Device* d = Device::from(real); + if (!d) return {}; + auto& state = const_cast(d->state()); // the arena's mutex + ArenaMemoryState out; + std::lock_guard lock(state.arena.mutex); + out.size = state.arena.size; + out.address = state.arena.address; + out.bound = state.arena.backing.stats().bound; + out.sparse = state.arena.backing.sparse(); + out.sparse_capable = state.arena_sparse_capable; + out.signed_offsets = state.vsharp_offsets_signed(); + return out; +} + ImageMemoryStats image_memory_stats(ID3D12Device* device) { if (!device) return {}; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); @@ -22257,9 +29657,9 @@ bool read_arena(ID3D12Device* device, std::uint64_t va, void* out, std::size_t b ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); if (!real) real = device; const Device* d = Device::from(real); - if (!d || !d->state().arena.mapped || va > d->state().arena.size || bytes > d->state().arena.size - va) return false; - std::memcpy(out, d->state().arena.mapped + va, bytes); - return true; + // Any arena address (a diagnostic's): read under the backing's shared lock, refused where no memory is. + if (!d || !d->state().arena_ready()) return false; + return d->state().arena.backing.with_host(va, bytes, [&](const std::uint8_t* host) { std::memcpy(out, host, bytes); }); } namespace { @@ -22295,7 +29695,16 @@ VkDescriptorSetLayout bindless_set_layout(ID3D12Device* device) { std::uint32_t bindless_hash_lookup(ID3D12Device* device, const std::uint32_t (&key)[8]) { const leonida::BindlessSet* set = bindless_of(device); - return set ? set->table().lookup(key) : 0; + if (!set) return 0; + // A T# read back from one of the layer's heaps carries its index in dword 6 (tsharp_index_word): its key is the + // descriptor without it, and the word must name the index the table holds, which is what a shader reads. + namespace g = leonida::gfx10; + g::ImageWords words; + std::memcpy(words.data(), key, sizeof(words)); + if (!g::is_image(words) || !g::has_tsharp_index(words)) return set->table().lookup(key); + const g::ImageWords stripped = g::tsharp_key(words); + const std::uint32_t index = set->table().lookup(stripped.data()); + return index == g::tsharp_index_of(words) ? index : 0; } BindlessRoom bindless_room(ID3D12Device* device) { @@ -22840,6 +30249,9 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin 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); + if (!v13.integer_dot_product) + std::fprintf(stderr, "[rt] d3d12: the GPU has no shaderIntegerDotProduct; shaders that use the 4x8-bit dot " + "products need make_game.py's --integer-dot-fallback\n"); // D3D-78 uses the core robustness and format-feature flags. Leave the Vulkan 1.2 extension path unchanged. if (v13.core) { VkPhysicalDeviceVulkan13Features supported{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES}; @@ -22884,10 +30296,16 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin info.shader_output_viewport_index = chosen12.shaderOutputViewportIndex == VK_TRUE; enable12.shaderOutputLayer = info.shader_output_layer; enable12.shaderOutputViewportIndex = info.shader_output_viewport_index; + info.vulkan_memory_model = chosen12.vulkanMemoryModel == VK_TRUE; + info.vulkan_memory_model_device_scope = info.vulkan_memory_model && chosen12.vulkanMemoryModelDeviceScope == VK_TRUE; + enable12.vulkanMemoryModel = info.vulkan_memory_model ? VK_TRUE : VK_FALSE; + enable12.vulkanMemoryModelDeviceScope = info.vulkan_memory_model_device_scope ? VK_TRUE : VK_FALSE; if (!info.bindless) std::fprintf(stderr, "[rt] d3d12: the GPU lacks a descriptor-indexing feature the bindless set needs\n"); enable12.bufferDeviceAddress = VK_TRUE; info.buffer_device_address = true; + info.buffer_device_address_capture_replay = chosen12.bufferDeviceAddressCaptureReplay == VK_TRUE; + enable12.bufferDeviceAddressCaptureReplay = info.buffer_device_address_capture_replay ? VK_TRUE : VK_FALSE; std::uint32_t family_count = 0; vkGetPhysicalDeviceQueueFamilyProperties(info.physical, &family_count, nullptr); std::vector families(family_count); @@ -22934,6 +30352,36 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin queue_infos.push_back(q); } } + // The GPU address arena binds its memory blocks on a queue nothing else submits to (src/arena_backing.h): a bind + // then never waits behind a submission that waits for a fence the CPU signals later. A family with the sparse + // binding bit and a queue to spare, a sparse-only family first (RADV has one). None: the arena stays one + // allocation. + std::uint32_t arena_bind_family = UINT32_MAX, arena_bind_index = 0; + if (chosen_features.sparseBinding && chosen_features.sparseResidencyBuffer && chosen12.bufferDeviceAddress) { + std::vector used(family_count, 0); + for (const auto& q : queue_infos) used[q.queueFamilyIndex] = q.queueCount; + const auto picked_bind = leonida::pick_arena_bind_queue(families.data(), family_count, used.data(), + std::uint32_t(priorities.size())); + arena_bind_family = picked_bind.family; + arena_bind_index = picked_bind.index; + if (arena_bind_family != UINT32_MAX) { + bool listed = false; + for (auto& q : queue_infos) + if (q.queueFamilyIndex == arena_bind_family) { + ++q.queueCount; + listed = true; + } + if (!listed) { + VkDeviceQueueCreateInfo q{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}; + q.queueFamilyIndex = arena_bind_family; + q.queueCount = 1; + q.pQueuePriorities = priorities.data(); + queue_infos.push_back(q); + } + } + } + info.sparse_address_space = chosen.limits.sparseAddressSpaceSize; + info.residency_non_resident_strict = chosen.sparseProperties.residencyNonResidentStrict == VK_TRUE; VkPhysicalDeviceFeatures enable{}; enable.sparseBinding = chosen_features.sparseBinding; enable.sparseResidencyBuffer = chosen_features.sparseResidencyBuffer; @@ -23402,6 +30850,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin info.copy_queues.push_back(q); } info.queue = info.command_queues[0]; + if (arena_bind_family != UINT32_MAX) get_queue(owned.device, arena_bind_family, arena_bind_index, &info.arena_bind_queue); info.max_push_constants_size = chosen.limits.maxPushConstantsSize; info.push_constants_need_fallback = (info.max_push_constants_size < 144); std::fprintf(stderr, "[rt] d3d12: Vulkan device: %s (maxPushConstantsSize: %u bytes)\n", chosen.deviceName, diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 26dd5e7f70..d4a9be3f59 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -29,6 +29,7 @@ #ifdef LEONIDA_VULKAN_DEVICE #include "d3d12_com.h" // rt::d3d12::create_console_descriptor_heap for slot 14 #include "../src/vulkan_gpu_labels.h" +#include "../src/submit_phases.h" #endif #include "d3d12_xs_placed_depth.h" #include "d3d12_trace.h" @@ -1480,7 +1481,14 @@ void arm_mirror_callback(const std::shared_ptr& link, ID3D12Fence* f } void wait_for_fence_progress(FenceMirror* mirror) { +#ifdef LEONIDA_VULKAN_DEVICE + // Vulkan timeline semaphores are monotonic (cannot rewind); when SetEventOnCompletion succeeded, use a 1000 ms + // safety-net timeout instead of a 10 ms rewind poll to avoid thousands of idle Wine threadpool wakeups/s. + const LONGLONG poll_ms = mirror->arm_failed.load(std::memory_order_relaxed) ? 10 : 1000; + const LONGLONG kRewindPollInterval = -poll_ms * 10'000; // relative 100 ns units +#else constexpr LONGLONG kRewindPollInterval = -10 * 10'000; // 10 ms in relative 100 ns units +#endif ULARGE_INTEGER due{}; due.QuadPart = static_cast(kRewindPollInterval); FILETIME timeout{due.LowPart, due.HighPart}; @@ -2056,6 +2064,10 @@ bool execute_with_values(ChildProxy* self, UINT count, void* const* lists); // list proxy replaced by its real list (a bundle on the list side unwraps the same way at the console's // ExecuteBundle); the real queue never sees a proxy. std::uint64_t queue_execute_command_lists(ChildProxy* self, std::uint64_t count_word, std::uint64_t lists_word) { + // The "submit frame" line: the console call as a whole, its list-value waits and writes included (outermost). + const leonida::submit_phases::TitleCall frame_call(leonida::submit_phases::part_lists); + // While the title submits, a held list-value wait is not released for want of progress: this may carry its write. + const list_values::Pump::TitleCall title_call; if (lists_word && execute_with_values(self, static_cast(count_word), reinterpret_cast(lists_word))) return 0; @@ -2274,16 +2286,29 @@ AsyncMapper& async_mapper() { // CopyPageMappingsBatchX's batches, copied: the remap of a deferred call runs after the caller freed its arrays. struct PageMappingCopy { std::vector batches; - std::vector> ranges; + std::vector range_storage; std::uintptr_t pool = 0; UINT pages = 0, flags = 0; + PageMappingCopy(const PageMappingCopy&) = delete; + PageMappingCopy& operator=(const PageMappingCopy&) = delete; + PageMappingCopy(PageMappingCopy&&) = delete; + PageMappingCopy& operator=(PageMappingCopy&&) = delete; + PageMappingCopy(UINT count, const xmem::PageBatch* in, std::uintptr_t pool_, UINT pages_, UINT flags_) - : batches(in, in + count), ranges(count), pool(pool_), pages(pages_), flags(flags_) { + : batches(in, in + count), pool(pool_), pages(pages_), flags(flags_) { + std::size_t total_ranges = 0; + for (UINT b = 0; b < count; ++b) + if (in[b].ranges) total_ranges += in[b].count; + range_storage.reserve(total_ranges); for (UINT b = 0; b < count; ++b) { - if (!in[b].ranges) continue; // xmem refuses a batch with ranges but no array; it still sees none - ranges[b].assign(in[b].ranges, in[b].ranges + in[b].count); - batches[b].ranges = ranges[b].data(); + if (!in[b].ranges || !in[b].count) { + batches[b].ranges = nullptr; + continue; // xmem refuses a batch with ranges but no array; zero-count batches need no dangling ptr + } + const std::size_t offset = range_storage.size(); + range_storage.insert(range_storage.end(), in[b].ranges, in[b].ranges + in[b].count); + batches[b].ranges = range_storage.data() + offset; } } }; @@ -2503,11 +2528,24 @@ HRESULT queue_copy_page_mappings(ChildProxy* self, UINT count, const xmem::PageB stats.max = (std::max)(stats.max, t2 - t0); if (t2 - stats.since >= std::chrono::seconds(10)) { const auto ms = [](clock::duration d) { return std::chrono::duration(d).count(); }; + // Pages changed by a table update alone (GPU-only pages with a CPU pair, and those pairs' CPU pages) and + // by a host map or unmap (a wineserver round trip each under Wine), since the last line, by path + // (rt::xmem::Slot31Counts). + static rt::xmem::Slot31Counts before{}; + rt::xmem::Slot31Counts now{}; + if (rt::xmem::slot31_mapping_counts_fn) rt::xmem::slot31_mapping_counts_fn(now); + const auto since = [](std::uint64_t a, std::uint64_t b) { return static_cast(a - b); }; std::fprintf(stderr, "[rt] d3d12_xs: queue slot 31: %llu calls (%llu batches) in %.0f s: %.1f ms waiting " - "for the queue, %.1f ms mapping, %.1f ms the longest call\n", + "for the queue, %.1f ms mapping, %.1f ms the longest call; pages %llu by table, %llu " + "by host remap (table: %llu GPU-only, %llu CPU twins; %llu twins the title mapped " + "kept; host: %llu with no CPU pair, %llu views replaced)\n", static_cast(stats.calls), static_cast(stats.ranges), std::chrono::duration(t2 - stats.since).count(), ms(stats.wait), ms(stats.map), - ms(stats.max)); + ms(stats.max), since(now.table(), before.table()), since(now.host(), before.host()), + since(now.gpu_pages, before.gpu_pages), since(now.twin_pages, before.twin_pages), + since(now.twins_kept, before.twins_kept), since(now.unpaired_pages, before.unpaired_pages), + since(now.views_replaced, before.views_replaced)); + before = now; stats = {}; stats.since = t2; } @@ -2704,6 +2742,9 @@ std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_ const unsigned present_x_slot = newer && !qroutes.present_x_set ? qroutes.present_x + 2 : qroutes.present_x; if (Slot >= self->slot_count) { + // A present stands behind the work held so far, which may then go without its values once nothing + // else can run (d3d12_xs_list_values.h). Noted before it, whichever presentation takes it. + if (Slot == present_x_slot) list_values::Pump::get().note_present(); HRESULT hr = S_OK; bool external_queue = false; if (call_presentation(self->device, [&](const PresentationHandler& p) { @@ -4002,7 +4043,9 @@ IUnknown* list_real_or_null(const void* object) { // lock, so the fence values rise in submission order. class ValueSubmission { public: - explicit ValueSubmission(ChildProxy* queue) : queue_(queue) {} + explicit ValueSubmission(ChildProxy* queue, UINT reserve_lists = 0) : queue_(queue) { + if (reserve_lists) group_.reserve(reserve_lists); + } void add(ID3D12CommandList* list) { group_.push_back(list); } @@ -4010,9 +4053,18 @@ class ValueSubmission { const std::vector& gate, const std::vector& writes) { // Pre-writes land with the group before the gate: behind the work submitted so far, before the queue stands // at the gate (stand_at submits the group first when a wait is unmet). A met gate is no gate: they then land - // behind the part, with its writes. The memory is read once here, for both. + // behind the part, with its writes. Evaluate each wait once into unmet_scratch_ so stand_at avoids repeating + // ReadProcessMemory loops when flush() has no prior group or writes to submit. bool met = true; - for (const list_values::Wait& w : gate) met = met && list_values::met_now(w); + if (!gate.empty()) { + unmet_scratch_.clear(); + for (const list_values::Wait& w : gate) { + if (!list_values::met_now(w)) { + unmet_scratch_.push_back(w); + met = false; + } + } + } for (const list_values::Write& write : pre_writes) { writes_.push_back(write); // Landing before the part has run, a GPU timestamp of the part's would not be written yet: the CPU's @@ -4025,7 +4077,8 @@ class ValueSubmission { } void flush() { - if (!group_.empty()) { + const bool bare = group_.empty(); + if (!bare) { using ExecuteFn = void(WINAPI*)(void*, std::uint64_t, ID3D12CommandList* const*); reinterpret_cast(queue_->real_vtable[kQueueExecuteCommandLists])( queue_->real, static_cast(group_.size()), group_.data()); @@ -4037,7 +4090,7 @@ class ValueSubmission { const std::uint64_t value = ++values->written_value; if (SUCCEEDED(signal(values->written, value))) { values->written->SetEventOnCompletion(value, list_values::Pump::get().wake()); - list_values::Pump::get().add_writes(queue_->values, value, std::move(writes_)); + list_values::Pump::get().add_writes(queue_->values, value, std::move(writes_), bare); } else { // Nothing would ever say when they may land: dropped, as without fences. list_values::bump(list_values::counters().writes_failed, writes_.size()); @@ -4065,13 +4118,18 @@ class ValueSubmission { list_values::bump(counters.waits_met_at_submit, waits.size()); return; } + // Count the subset of waits in `waits` that already compared true in part(). + if (waits.size() > unmet_scratch_.size()) + list_values::bump(counters.waits_met_at_submit, waits.size() - unmet_scratch_.size()); // The work before the wait goes first; its writes are in flight from here on, so a relay can find them. - flush(); + const bool had_work = !group_.empty() || !writes_.empty(); + if (had_work) flush(); list_values::QueueValues* values = queue_->values.get(); if (!values) return; // no fences: the wait runs on, as before std::vector unmet; - for (const list_values::Wait& w : waits) { - if (list_values::met_now(w)) { + unmet.reserve(unmet_scratch_.size()); + for (const list_values::Wait& w : unmet_scratch_) { + if (had_work && list_values::met_now(w)) { list_values::bump(counters.waits_met_at_submit); continue; } @@ -4090,13 +4148,14 @@ class ValueSubmission { if (unmet.empty()) return; const std::uint64_t value = ++values->gate_value; list_values::bump(counters.gates_held); - list_values::Pump::get().add_gate(queue_->values, value, std::move(unmet)); wait(values->gate, value); + list_values::Pump::get().add_gate(queue_->values, value, std::move(unmet)); } ChildProxy* queue_; std::vector group_; std::vector writes_; + std::vector unmet_scratch_; }; bool execute_with_values(ChildProxy* self, UINT count, void* const* lists) { @@ -4112,7 +4171,7 @@ bool execute_with_values(ChildProxy* self, UINT count, void* const* lists) { std::fprintf(stderr, "[rt] d3d12_xs: no fences for list memory writes and waits: their parts run " "without them\n"); } - ValueSubmission submission(self); + ValueSubmission submission(self, count); for (UINT i = 0; i < count; ++i) { if (!is_list_proxy_impl(lists[i])) { const std::uint64_t entry = unwrap_object(reinterpret_cast(lists[i])); @@ -7090,8 +7149,9 @@ const char* list_tail_slot_name(unsigned slot, unsigned char console_layout) { // Every counter of list_values::Counters, by name: the stats and their reset stay in step. #define LEONIDA_LIST_VALUE_COUNTERS(X) \ X(writes_recorded) X(writes_landed) X(writes_failed) X(waits_recorded) X(waits_met_at_submit) \ - X(waits_relayed) X(gates_held) X(gates_met) X(gates_timed_out) X(cuts) X(cuts_deferred) X(cut_failures) \ - X(gates_short) X(demotions) X(late_met) X(bundle_ops) X(releases) X(release_us) X(release_us_max) \ + X(waits_relayed) X(gates_held) X(gates_met) X(gates_released) X(released_present) X(released_cycle) \ + X(released_stalled) X(released_lost) X(met_after_release) X(cuts) X(cuts_deferred) X(cut_failures) \ + X(bundle_ops) X(releases) X(release_us) X(release_us_max) \ X(pass_us_max) X(release_stalls) X(remaps_now) X(remaps_deferred) X(remaps_failed) X(remap_wait_us_max) \ X(stamps_gpu) X(stamps_cpu) X(labels_handed) X(writes_arena) X(writes_title_pages) @@ -7109,10 +7169,16 @@ void reset_list_value_stats() { #define LEONIDA_RESET(name) c.name.store(0, std::memory_order_relaxed); LEONIDA_LIST_VALUE_COUNTERS(LEONIDA_RESET) #undef LEONIDA_RESET + c.gpu_relay_downgraded_bare.store(0, std::memory_order_relaxed); + c.gpu_relay_downgraded_val.store(0, std::memory_order_relaxed); } #undef LEONIDA_LIST_VALUE_COUNTERS -void set_list_value_wait_timeout_ms(unsigned ms) { list_values::Pump::get().set_timeout_ms(ms); } +void set_list_value_signal_submitted_hook(bool (*hook)(ID3D12Fence*, std::uint64_t)) { + list_values::signal_submitted_hook() = hook; +} + +void note_list_value_present() { list_values::Pump::get().note_present(); } void set_list_values_enabled(bool on) { list_values::set_enabled(on); } diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h index 67097a7d4a..2eb6a336f4 100644 --- a/runtime/shims/d3d12_xs_device.h +++ b/runtime/shims/d3d12_xs_device.h @@ -475,9 +475,11 @@ inline constexpr bool console_value_met(std::uint32_t comparison, std::uint64_t struct ListValueStats { std::uint64_t writes_recorded, writes_landed, writes_failed; std::uint64_t waits_recorded, waits_met_at_submit, waits_relayed; // relayed: a GPU wait on a write in flight - std::uint64_t gates_held, gates_met, gates_timed_out; // gate: opened from the CPU + std::uint64_t gates_held, gates_met, gates_released; // gate: opened from the CPU; released unmet + // Released unmet because nothing else could run with a present queued, in a cycle, with the title stalled, at + // device loss (part of gates_released); released waits that memory met afterwards. + std::uint64_t released_present, released_cycle, released_stalled, released_lost, met_after_release; std::uint64_t cuts, cuts_deferred, cut_failures; // a list split at a wait after work - std::uint64_t gates_short, demotions, late_met; // short timeouts, every wait demoted, short waits met later std::uint64_t bundle_ops; // writes and waits on bundles, not modelled std::uint64_t releases, release_us, release_us_max, pass_us_max; // the releaser's signals, the pump's passes std::uint64_t release_stalls; // gate Signals still running after a second @@ -488,8 +490,11 @@ struct ListValueStats { }; ListValueStats list_value_stats(); void reset_list_value_stats(); -// How long a queue stands at an unmet wait before it runs on (LEONIDA_VALUE_WAIT_TIMEOUT_MS, default 200 ms). -void set_list_value_wait_timeout_ms(unsigned ms); +// Test helper: whether a Signal of the value reached the GPU (null: the layer answers; without it, always). A test +// says "held" for a fence whose Signal the real layer would hold behind a wait. +void set_list_value_signal_submitted_hook(bool (*hook)(ID3D12Fence*, std::uint64_t)); +// The title called PresentX (the queue proxy calls it; a test may too): a present stands behind the held work. +void note_list_value_present(); // Test helper: LEONIDA_LIST_VALUES as if set to 0 (false) or unset (true), for lists made afterwards. void set_list_values_enabled(bool on); // Before the process exits: the threads that land list writes and open gates finish and end (up to `ms`). diff --git a/runtime/shims/d3d12_xs_list_values.h b/runtime/shims/d3d12_xs_list_values.h index b4f24bbbbe..6ac25588b0 100644 --- a/runtime/shims/d3d12_xs_list_values.h +++ b/runtime/shims/d3d12_xs_list_values.h @@ -25,21 +25,18 @@ // - A wait that is met when its part is submitted costs nothing. One that a write still in flight will meet is // turned into a GPU wait on that write's fence (relay: the queue waits on the writer's `written` value, so the // GPU orders the two queues without a CPU round trip). Any other wait makes the queue wait on its `gate` fence, -// which is signalled from the CPU once the memory compares true or the wait has timed out. The Vulkan layer -// holds a queue's later work, Signals included, behind an unsatisfied fence wait without blocking the caller -// (src/queue_holds.h), so the submitting thread never waits here. +// which is signalled from the CPU once the memory compares true. The Vulkan layer holds a queue's later work, +// Signals included, behind an unsatisfied fence wait without blocking the caller (src/queue_holds.h), so the +// submitting thread never waits here, and the other queues' work, which does not wait for the gate, goes on. // - 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) 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 -// timeout: met in that time, its address keeps the full timeout from then on. A gate cut short that is met within -// its short timeout gives every wait the full timeout again. +// writes keep landing and other gates keep being looked at while held work runs. +// A gate is held until its value is in memory, with no timeout: the console's queue would stand there as long, and +// the work behind it reads what the writer produces. It goes without its value only when nothing else can make +// progress (src/list_value_progress.h: its writer is held behind a wait on its own queue, a cycle; a present is queued +// behind it; the title made no queue call while nothing ran), when the device is lost, and not at all once the +// process ends (stop()). Each such release is logged with the gate, the wait and the reason, and a wait released that +// way is watched for a while: met later, it is counted and logged with how much later. // LEONIDA_LIST_VALUES=0 drops both methods (the behaviour before this file). #include @@ -63,12 +60,85 @@ #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/list_value_progress.h" // leonida::list_value_progress: which held gate may go without its value +#include "../src/queue_holds.h" // leonida::queue_holds::any_progress: async/active/GPU queue work #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 +#include "../src/submit_phases.h" // the pump's and releaser's time in the "submit frame" line +#ifdef LEONIDA_VULKAN_DEVICE +#include "d3d12_com.h" // rt::d3d12::fence_signal_submitted, fence_signal_gpu_relay, fence_relay_wait +#endif namespace rt::d3d12_xs::list_values { +// Whether a Signal of `value` on `fence` reached the GPU (else the layer holds it behind a wait: that work is not +// running). Without the Vulkan layer (the mock tests) every Signal goes through, unless a test says otherwise. +inline bool (*&signal_submitted_hook())(ID3D12Fence*, std::uint64_t) { + static bool (*hook)(ID3D12Fence*, std::uint64_t) = nullptr; + return hook; +} +inline bool signal_submitted(ID3D12Fence* fence, std::uint64_t value) { + if (auto* hook = signal_submitted_hook()) return hook(fence, value); +#ifdef LEONIDA_VULKAN_DEVICE + return rt::d3d12::fence_signal_submitted(fence, value); +#else + (void)fence, (void)value; + return true; +#endif +} + +// GPU-met gate signal (vis_seq = 0): skips bumping visibility_seq_ strictly when every wait of a memory gate +// transitioned false -> true via Pump::land() in the same pass. Test hookable for mock tests. +inline HRESULT (*&signal_gpu_relay_hook())(ID3D12Fence*, std::uint64_t) { + static HRESULT (*hook)(ID3D12Fence*, std::uint64_t) = nullptr; + return hook; +} +inline HRESULT signal_gate_fence(ID3D12Fence* fence, std::uint64_t value, bool gpu_relay) { + if (gpu_relay) { + if (auto* hook = signal_gpu_relay_hook()) return hook(fence, value); +#ifdef LEONIDA_VULKAN_DEVICE + return rt::d3d12::fence_signal_gpu_relay(fence, value); +#endif + } + return fence->Signal(value); +} + +// Retroactive GPU-to-GPU wait redirect (substituting a pending gate wait in QueueHolds onto writer->written fences, +// never GPU-signaling values->gate). Test hookable for mock tests. +struct RelayTarget { + ID3D12Fence* fence = nullptr; + std::uint64_t value = 0; +}; +inline bool (*&relay_wait_hook())(ID3D12Fence*, std::uint64_t, std::span) { + static bool (*hook)(ID3D12Fence*, std::uint64_t, std::span) = nullptr; + return hook; +} +inline bool can_relay_wait() { + if (relay_wait_hook()) return true; +#ifdef LEONIDA_VULKAN_DEVICE + return true; +#else + return false; +#endif +} +inline bool relay_gate_wait(ID3D12Fence* gate, std::uint64_t value, std::span targets) { + if (auto* hook = relay_wait_hook()) return hook(gate, value, targets); +#ifdef LEONIDA_VULKAN_DEVICE + rt::d3d12::FenceRelayTarget inline_targets[8]; + std::vector large; + rt::d3d12::FenceRelayTarget* dst = inline_targets; + if (targets.size() > 8) { + large.resize(targets.size()); + dst = large.data(); + } + for (std::size_t i = 0; i < targets.size(); ++i) dst[i] = {targets[i].fence, targets[i].value}; + return rt::d3d12::fence_relay_wait(gate, value, std::span(dst, targets.size())); +#else + (void)gate, (void)value, (void)targets; + return false; +#endif +} + struct Wait { std::uint64_t address; std::uint64_t reference; @@ -163,11 +233,15 @@ struct Write { struct Counters { std::atomic writes_recorded{0}, writes_landed{0}, writes_failed{0}; std::atomic waits_recorded{0}, waits_met_at_submit{0}, waits_relayed{0}; - std::atomic gates_held{0}, gates_met{0}, gates_timed_out{0}; + // Gates held, met, and released without their value (all reasons; the ones below are part of it). + std::atomic gates_held{0}, gates_met{0}, gates_released{0}; + // Released because nothing else could run with a present queued behind them, because their writer was held behind + // them (a cycle), because the title stopped calling while nothing ran, at device loss; released waits met later. + std::atomic released_present{0}, released_cycle{0}, released_stalled{0}, released_lost{0}; + std::atomic met_after_release{0}; std::atomic cuts{0}, cuts_deferred{0}, cut_failures{0}; - // Gates given the short timeout, times every wait was demoted to it, short waits met in the rest of the full - // timeout (late), writes and waits on bundles (not modelled: a bundle is never cut). - std::atomic gates_short{0}, demotions{0}, late_met{0}, bundle_ops{0}; + // Writes and waits on bundles (not modelled: a bundle is never cut). + std::atomic bundle_ops{0}; // The releaser's gate signals and the time they took (the held work they ran), the pump's longest pass. std::atomic releases{0}, release_us{0}, release_us_max{0}, pass_us_max{0}, release_stalls{0}; // Queue slot 31 (CopyPageMappingsBatchX): applied at the call, deferred behind held work, deferred ones that @@ -181,6 +255,9 @@ struct Counters { // stored to as a host address), and through xmem's own mapping of a page the title's view keeps PAGE_NOACCESS. // Both are also counted in writes_landed. std::atomic writes_arena{0}, writes_title_pages{0}; + // Memory gates whose GPU-relay (vis_seq = 0) release was downgraded to a CPU-visibility Fence::Signal because a + // landed write came from a bare write group (no ExecuteCommandLists) or failed the exact-address/width/value check. + std::atomic gpu_relay_downgraded_bare{0}, gpu_relay_downgraded_val{0}; }; inline Counters& counters() { @@ -216,14 +293,46 @@ inline bool enabled() { } inline void set_enabled(bool on) { enabled_state().store(on ? 1 : 0, std::memory_order_relaxed); } -// The value a wait looks at, read through the kernel: memory that is not there is reported instead of faulting (a -// fault would run every vectored handler of the process, the D3D12 layer's write-fault handler among them, from a -// thread that may hold the pump's lock). The kernel's copy is not one access, so a value read while another thread -// stores it could mix the two: it is read until two reads agree. +#if defined(_MSC_VER) +// Out-of-line aligned volatile load: clang-cl without /EHa only catches SEH faults raised by a call inside __try. +// MUST omit `noexcept` (see src/guarded_copy.h): under /EHsc, clang-cl tags `noexcept` callees `nounwind` and emits a +// plain `call` instead of `invoke`, stripping the __except handler so an access violation crashes the process. +__declspec(noinline) inline std::uint64_t load_aligned_volatile(std::uintptr_t address, bool wide) { + return wide ? *reinterpret_cast(address) + : static_cast(*reinterpret_cast(address)); +} + +// Separate __try frame (no C++ objects with destructors) for aligned reads in read_value(). +__declspec(noinline) inline bool read_aligned_volatile_seh(std::uintptr_t address, bool wide, std::uint64_t& out) { + __try { + out = load_aligned_volatile(address, wide); + return true; + } __except (EXCEPTION_EXECUTE_HANDLER) { + return false; + } +} +#endif + +// The value a wait looks at: aligned reads go through the frame table or an SEH-guarded volatile load (one atomic +// access, no syscall), falling back to ReadProcessMemory on unaligned or faulted addresses. The kernel's copy is not +// one access, so a value read while another thread stores it could mix the two: it is read until two reads agree. inline bool read_value(std::uint64_t address, bool wide, std::uint64_t& value) { value = 0; if (!address) return false; const SIZE_T bytes = wide ? 8 : 4; + // A page xmem's frame table holds (no host view: src/title_frames.h) is read in its frame, in one access when the + // value is aligned (it then lies inside one page). + leonida::title_frames::Frame frame; + if (address % bytes == 0 && leonida::title_frames::find(static_cast(address), frame)) { + value = wide ? reinterpret_cast(frame.bytes)[0] + : reinterpret_cast(frame.bytes)[0]; + return true; + } +#if defined(_MSC_VER) + if (address % bytes == 0 && read_aligned_volatile_seh(static_cast(address), wide, value)) { + return true; + } +#endif const auto* at = reinterpret_cast(static_cast(address)); std::uint64_t last = 0; for (int attempt = 0; attempt < 4; ++attempt) { @@ -362,31 +471,70 @@ class Pump { // Writes that land once `queue->written` reaches `value`. The caller signalled that value on the queue and // asked the fence to set wake() on it (SetEventOnCompletion), so the pump needs no polling for writes. - void add_writes(std::shared_ptr queue, std::uint64_t value, std::vector writes) { + // `bare` is true when flushed with no ExecuteCommandLists (signal-only pre-writes): such writes cannot satisfy + // a held consumer via vis_seq = 0 relay because no execute pass covered earlier CPU writes/page remaps. + void add_writes(std::shared_ptr queue, std::uint64_t value, std::vector writes, + bool bare = false) { if (writes.empty() || exiting_.load(std::memory_order_relaxed)) return; // stop(): see there + std::vector relays; { std::lock_guard lock(mutex_); const std::uint64_t after_gate = max_pending_gate_locked(queue.get()); - writes_.push_back({std::move(queue), value, std::move(writes), after_gate}); + writes_.push_back({std::move(queue), value, std::move(writes), after_gate, bare}); + collect_retroactive_relays_locked(relays); } + apply_retroactive_relays(relays); start_or_settle(); } - // The queue waits on `queue->gate` for `value`: signalled once every wait is met, or the gate timed out. Its - // time starts when the gates before it on its queue have opened (start_gate). + // The queue waits on `queue->gate` for `value`: signalled once every wait is met, or when nothing else can make + // progress (take_open, src/list_value_progress.h). Callers MUST submit queue->Wait(queue->gate, value) BEFORE + // calling add_gate() so retroactive relays always see the wait registered in QueueHolds. void add_gate(std::shared_ptr queue, std::uint64_t value, std::vector waits) { if (exiting_.load(std::memory_order_relaxed)) return; // stop(): never signalled, see there + std::vector relays; { std::lock_guard lock(mutex_); Gate gate; gate.queue = std::move(queue); gate.value = value; + gate.wait_met.assign(waits.size(), 0); gate.waits = std::move(waits); + gate.since = Clock::now(); + gate.held_ms = GetTickCount64(); + gate.presents_at_hold = presents_.load(std::memory_order_relaxed); gates_.push_back(std::move(gate)); + collect_retroactive_relays_locked(relays); } + apply_retroactive_relays(relays); start_or_settle(); } + // The title called PresentX: a present now stands behind the work held so far (src/queue_holds.h, after_held). + void note_present() { + presents_.fetch_add(1, std::memory_order_relaxed); + title_call_ms_.store(GetTickCount64(), std::memory_order_relaxed); + if (wake_ && started_.load(std::memory_order_relaxed)) SetEvent(wake_); + } + + // A title queue call (ExecuteCommandLists) in progress: what it submits may meet a held wait. Calls that do not + // submit work count as the title's activity only (note_present). + class TitleCall { + public: + TitleCall() { + Pump& pump = get(); + pump.title_calls_.fetch_add(1, std::memory_order_relaxed); + pump.title_call_ms_.store(GetTickCount64(), std::memory_order_relaxed); + } + ~TitleCall() { + Pump& pump = get(); + pump.title_call_ms_.store(GetTickCount64(), std::memory_order_relaxed); + pump.title_calls_.fetch_sub(1, std::memory_order_relaxed); + } + TitleCall(const TitleCall&) = delete; + TitleCall& operator=(const TitleCall&) = delete; + }; + // The queue waits on `queue->gate` for `value`, which the releaser signals after running `action`, once // `queue->written` reaches `after` (the caller signalled it on the queue and set wake() on it): something the // CPU does at a point of the queue's timeline, after the work before it and before the work after it. No @@ -399,9 +547,9 @@ class Pump { Gate gate; gate.queue = std::move(queue); gate.value = value; - gate.started = true; gate.since = Clock::now(); - gate.last_tick = gate.since; + gate.held_ms = GetTickCount64(); + gate.presents_at_hold = presents_.load(std::memory_order_relaxed); gate.after = after; gate.action = std::move(action); gates_.push_back(std::move(gate)); @@ -411,18 +559,16 @@ class Pump { } // A write still in flight that will meet `wait` when it lands: the fence and value whose completion lands it - // (the earliest such write). False when there is none. + // (the earliest such write with `after_gate == 0`, so a wait never relays onto a write held behind an unresolved + // gate and hides a cycle from list_value_progress). False when there is none. bool relay(const Wait& wait, ID3D12Fence*& fence, std::uint64_t& value) { std::lock_guard lock(mutex_); - const std::uint8_t need = wait.wide ? 8 : 4; for (const WriteGroup& group : writes_) - for (const Write& write : group.writes) - if (write.kind == WriteKind::value && write.address == wait.address && write.bytes >= need && - console_value_met(wait.comparison, write.value, wait.reference, wait.wide)) { - fence = group.queue->written; - value = group.value; - return true; - } + if (group.after_gate == 0 && group_meets_value(group, wait)) { + fence = group.queue->written; + value = group.value; + return true; + } return false; } @@ -450,13 +596,12 @@ class Pump { "writes land at submission and waits run on\n", GetLastError()); else std::fprintf(stderr, "[rt] d3d12_xs: list memory writes land after their part ran, waits hold their " - "queue (timeout %u ms)\n", timeout_ms_.load(std::memory_order_relaxed)); + "queue until met (released unmet only when nothing else can make progress)\n"); + started_.store(releaser_ != nullptr, std::memory_order_relaxed); }); return releaser_ && !stop_.load(std::memory_order_relaxed); } - void set_timeout_ms(unsigned ms) { timeout_ms_.store(ms ? ms : 1, std::memory_order_relaxed); } - // Test helper: true once nothing is in flight, polling for up to `ms`. bool idle(unsigned ms) { const auto until = Clock::now() + std::chrono::milliseconds(ms); @@ -476,7 +621,7 @@ class Pump { // say) and end, waiting up to `ms` for them. Gates not signalled yet stay shut and their actions do not run, and // writes and gates added afterwards are dropped: signalling any of them from another thread could open a gate // whose remap was skipped, or signal a gate value above one still to come. The queues' held work is not run at - // exit. + // exit. A gate held at the time (nothing ever wrote its value) does not delay this: the pump never blocks on one. void stop(unsigned ms) { if (exiting_.exchange(true, std::memory_order_relaxed)) return; stop_.store(true, std::memory_order_relaxed); @@ -489,18 +634,70 @@ class Pump { DWORD count = 0; if (thread_) threads[count++] = thread_; if (releaser_) threads[count++] = releaser_; - if (count && WaitForMultipleObjects(count, threads, TRUE, ms) == WAIT_TIMEOUT) + if (count && WaitForMultipleObjects(count, threads, TRUE, ms) == WAIT_TIMEOUT) { std::fprintf(stderr, "[rt] d3d12_xs: list value threads still busy after %u ms at exit\n", ms); + return; + } + // The threads have ended: what they left (gates that stay shut, writes that never land) lets go of its queues + // and fences now, unsignalled and unlanded. Destroyed outside the locks. + std::deque gates; + std::deque writes; + std::deque releases; + { + std::lock_guard lock(mutex_); + gates.swap(gates_); + writes.swap(writes_); + } + { + std::lock_guard release(release_mutex_); + releases.swap(releases_); + } + if (!gates.empty()) + std::fprintf(stderr, "[rt] d3d12_xs: %zu list value gates still held at exit stay shut\n", gates.size()); + } + + enum class LandedMatch : std::uint8_t { none, gpu_met, bare, val_mismatch }; + + struct LandedRange { + std::uint64_t address = 0; + std::uint64_t value = 0; + std::uint8_t bytes = 0; + bool exact_value = false; // true for WriteKind::value (false for timestamps) + bool bare = false; // true when flushed with no ExecuteCommandLists + }; + + // Classifies how `landed` (in chronological landing order) overlaps `wait`: + // - `none`: no landed range overlaps `[wait.address, wait.address + need)`. + // - `bare`: at least one overlapping landed range came from a bare write group (no ExecuteCommandLists). + // - `gpu_met`: no overlapping range is bare, and the latest overlapping landed write has exact address, exact + // width, `exact_value`, and satisfies `console_value_met`. + // - `val_mismatch`: an overlapping non-bare write landed, but the latest one was a timestamp, differed in + // address/width, or did not satisfy `console_value_met`. + static LandedMatch match_landed(const Wait& wait, std::span landed) { + const std::uint64_t need = wait.wide ? 8u : 4u; + if (!wait.address || wait.address > UINT64_MAX - need) return LandedMatch::none; + const std::uint64_t wait_end = wait.address + need; + const LandedRange* latest = nullptr; + for (std::size_t i = landed.size(); i-- > 0;) { + const LandedRange& r = landed[i]; + if (!r.bytes || r.address > UINT64_MAX - r.bytes) continue; + if (r.address >= wait_end || wait.address >= r.address + r.bytes) continue; + if (r.bare) return LandedMatch::bare; + if (!latest) latest = &r; + } + if (!latest) return LandedMatch::none; + if (latest->exact_value && latest->address == wait.address && latest->bytes == need && + console_value_met(wait.comparison, latest->value, wait.reference, wait.wide)) + return LandedMatch::gpu_met; + return LandedMatch::val_mismatch; } private: using Clock = std::chrono::steady_clock; - static constexpr unsigned kDemoteAfter = 3; // timeouts in a row before an address gets the short timeout - static constexpr unsigned kDemoteAllAfter = 4; // gates timed out in a row before every wait gets it - static constexpr unsigned kDemotedTimeoutMs = 4; static constexpr unsigned kPollMs = 1; // while a gate waits for memory nobody tells us about - static constexpr std::size_t kMaxStreaks = 256; // addresses whose timeouts are counted (least recently used go) - static constexpr std::size_t kMaxLate = 64; // waits cut short watched for the rest of the full timeout + static constexpr unsigned kLostCheckMs = 25; // throttle take_open() device-loss GetCompletedValue() polling + static constexpr std::size_t kMaxLate = 64; // waits released unmet, watched for whether memory meets them + static constexpr unsigned kLateWatchMs = 10000; // ... for this long after the release (a measurement only) static constexpr std::uint64_t kStallMs = 1000; // a gate Signal this long is reported (watch_releaser) struct WriteGroup { @@ -508,16 +705,18 @@ class Pump { std::uint64_t value; std::vector writes; std::uint64_t after_gate = 0; // highest pending gate value on `queue` ahead of this write group + bool bare = false; // true when flushed with no ExecuteCommandLists (signal-only pre-write) }; struct Gate { std::shared_ptr queue; std::uint64_t value = 0; std::vector waits; - leonida::list_value_wait::GateTimeoutState timeout{}; // work-aware timeout clock (set by start_gate) - Clock::time_point last_tick{}; + std::vector wait_met; // per-wait met tracking: transitions 0->1 checked against Pump::land() + bool cpu_met = false; // true if any wait became met without a qualifying non-bare GPU write + bool relaying = false; // true while add_writes()/add_gate() is applying a retroactive relay 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 held_ms = 0; // GetTickCount64 when it was held + std::uint64_t presents_at_hold = 0; // the title's present count then std::uint64_t after = 0; // action gates: the queue's `written` value the action runs behind std::function action; // null: a memory wait }; @@ -525,31 +724,111 @@ class Pump { std::shared_ptr queue; std::uint64_t value; std::function action; + bool gpu_relay = false; // true strictly when every wait transitioned false->true via a qualifying GPU write }; - struct Streak { - std::uint64_t address; - unsigned timeouts; // in a row - bool logged; - bool met; // a wait for it was met once (in time or late): it keeps the full timeout when every - // wait is demoted - std::uint64_t used; // use_clock_ at its last use + struct PendingRelay { + std::shared_ptr gate_queue; + std::uint64_t gate_value = 0; + std::size_t unmet_waits = 0; + std::vector> writer_queues; + std::vector targets; }; struct Late { Wait wait; - Clock::time_point until; + Clock::time_point released; }; + static bool group_meets_value(const WriteGroup& group, const Wait& wait) { + 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 Write& w = group.writes[i]; + if (!w.bytes || w.address > UINT64_MAX - w.bytes) continue; + if (w.address >= wait_end || wait.address >= w.address + w.bytes) continue; + return w.kind == WriteKind::value && w.address == wait.address && w.bytes >= need && + console_value_met(wait.comparison, w.value, wait.reference, wait.wide); + } + return false; + } + + // Finds pending memory gates whose unmet waits ALL match in-flight non-bare WriteGroups with + // `group.after_gate == 0 && group.queue.get() != gate.queue.get()` (strictly cycle-free) and marks them + // `relaying = true` so they can be redirected in QueueHolds outside mutex_. Called with mutex_ held. + void collect_retroactive_relays_locked(std::vector& out) { + if (!can_relay_wait() || exiting_.load(std::memory_order_relaxed) || gates_.empty() || writes_.empty()) return; + for (Gate& gate : gates_) { + if (gate.action || gate.cpu_met || gate.relaying || gate.waits.empty()) continue; + std::vector> writer_queues; + std::vector targets; + std::size_t unmet_count = 0; + bool all_matched = true; + for (std::size_t wi = 0; wi < gate.waits.size(); ++wi) { + if (wi < gate.wait_met.size() && gate.wait_met[wi]) { + if (met_now(gate.waits[wi])) continue; + gate.wait_met[wi] = 0; + } + ++unmet_count; + const WriteGroup* matched = nullptr; + for (const WriteGroup& group : writes_) { + if (group.bare || group.after_gate != 0 || group.queue.get() == gate.queue.get()) continue; + if (group_meets_value(group, gate.waits[wi])) { + matched = &group; + break; + } + } + if (!matched) { + all_matched = false; + break; + } + ID3D12Fence* rep_fence = matched->queue->written; + const std::uint64_t rep_val = matched->value; + bool merged = false; + for (RelayTarget& t : targets) { + if (t.fence == rep_fence) { + if (rep_val > t.value) t.value = rep_val; + merged = true; + break; + } + } + if (!merged) { + writer_queues.push_back(matched->queue); + targets.push_back({rep_fence, rep_val}); + } + } + if (all_matched && unmet_count > 0 && !targets.empty()) { + gate.relaying = true; + out.push_back({gate.queue, gate.value, unmet_count, std::move(writer_queues), std::move(targets)}); + } + } + } + + // Applies collected retroactive wait redirects outside mutex_, removing succeeded gates from `gates_` so + // choose_release() never treats them as stuck, and restoring `relaying = false` if a redirect was declined. + void apply_retroactive_relays(std::vector& relays) { + if (relays.empty()) return; + for (PendingRelay& r : relays) { + const bool ok = relay_gate_wait(r.gate_queue->gate, r.gate_value, r.targets); + std::lock_guard lock(mutex_); + for (auto it = gates_.begin(); it != gates_.end(); ++it) { + if (it->queue.get() == r.gate_queue.get() && it->value == r.gate_value) { + if (ok) { + gates_.erase(it); + bump(counters().waits_relayed, r.unmet_waits); + bump(counters().gates_met); + last_progress_ms_ = GetTickCount64(); + } else { + it->relaying = false; + } + break; + } + } + } + } + Pump() { wake_ = CreateEventW(nullptr, FALSE, FALSE, nullptr); timer_ = CreateWaitableTimerExW(nullptr, nullptr, CREATE_WAITABLE_TIMER_HIGH_RESOLUTION, TIMER_ALL_ACCESS); - unsigned timeout = 200; - char text[16] = {}; - std::size_t length = 0; - if (getenv_s(&length, text, sizeof(text), "LEONIDA_VALUE_WAIT_TIMEOUT_MS") == 0 && text[0]) { - const unsigned long parsed = std::strtoul(text, nullptr, 10); - if (parsed > 0 && parsed < 600000) timeout = static_cast(parsed); - } - timeout_ms_.store(timeout, std::memory_order_relaxed); } // Without the threads (none could be made, or stop() ran) nothing could land later: what is queued is settled @@ -595,6 +874,7 @@ class Pump { WaitForSingleObject(wake_, polling ? kPollMs : writes ? 50 : releasing ? 500 : INFINITE); } if (stop_.load(std::memory_order_relaxed)) break; + const leonida::submit_phases::WorkerScope busy(leonida::submit_phases::worker_value_pump); pass(false); watch_releaser(); summarize(); @@ -639,6 +919,8 @@ class Pump { releasing_ = true; } SetEvent(wake_); // the pump may be in an untimed wait: it watches the Signals from here on + // Our thread: its Signals (and the batches they release) are not the title's, in the "submit frame" line. + const leonida::submit_phases::WorkerScope busy(leonida::submit_phases::worker_value_pump); struct PendingReleaseGuard { std::atomic* count; std::size_t remaining; @@ -664,7 +946,7 @@ class Pump { static void signal(const Release& release) { const auto started = Clock::now(); if (release.action) release.action(); - release.queue->gate->Signal(release.value); + signal_gate_fence(release.queue->gate, release.value, release.gpu_relay); const auto us = static_cast( std::chrono::duration_cast(Clock::now() - started).count()); Counters& c = counters(); @@ -673,32 +955,13 @@ class Pump { raise_to(c.release_us_max, us); } - Streak* find_streak(std::uint64_t address) { - for (Streak& streak : streaks_) - if (streak.address == address) { - streak.used = ++use_clock_; - return &streak; - } - return nullptr; - } - - Streak* add_streak(std::uint64_t address) { - if (streaks_.size() < kMaxStreaks) { - streaks_.push_back({address, 0, false, false, ++use_clock_}); - return &streaks_.back(); - } - Streak* oldest = &*std::min_element(streaks_.begin(), streaks_.end(), - [](const Streak& a, const Streak& b) { return a.used < b.used; }); - *oldest = {address, 0, false, false, ++use_clock_}; - return oldest; - } - // Write groups whose fence was reached, taken off the list in submission order (per queue, up to the first one // not reached). The fences are read newest group first, a fence again for an older group its last reading does // not cover: if a group's work waited for an older group's (on another queue), the older group's reading comes // later than the newer one's, so it cannot read as not done while the newer one reads as done. Called with // mutex_ held. - void take_landed(bool force, std::vector& landing) { + void take_landed(bool force, std::vector& landing, bool& saw_lost) { + saw_lost = false; const std::size_t count = writes_.size(); if (!count) return; std::vector reached(count, force ? 1 : 0); @@ -718,6 +981,7 @@ class Pump { } else if (it->completed < group.value) { it->completed = group.queue->written->GetCompletedValue(); } + if (it->completed == UINT64_MAX) saw_lost = true; reached[i] = it->completed >= group.value; } } @@ -745,100 +1009,120 @@ class Pump { 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). 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) { + // The gates whose waits are met 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). A memory gate has no timeout: when no gate opens and nothing else can make progress, one held + // gate may go without its value by the rules of src/list_value_progress.h, and every gate goes once the device is + // lost. `force` (no threads): every gate, now. Called with mutex_ held. + void take_open(bool force, bool landed_any, bool saw_lost, std::span landed_ranges, + std::vector& opening) { if (gates_.empty()) return; const auto now = Clock::now(); - 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}); + // Device loss: the fences read UINT64_MAX and no write lands for real any more; nothing held can be met. + // Throttled to kLostCheckMs (and deduplicated per queue) when take_landed() did not already report loss. + bool lost = saw_lost; + if (!force && !lost && + (last_lost_check_ == Clock::time_point{} || + now - last_lost_check_ >= std::chrono::milliseconds(kLostCheckMs))) { + last_lost_check_ = now; + std::vector checked_queues; + for (const Gate& gate : gates_) { + const QueueValues* q = gate.queue.get(); + if (std::find(checked_queues.begin(), checked_queues.end(), q) != checked_queues.end()) continue; + checked_queues.push_back(q); + if (q->written->GetCompletedValue() == UINT64_MAX) { + lost = true; + break; } - 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); + bool any_relaying = 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 (std::find(blocked.begin(), blocked.end(), queue) != blocked.end()) { + // Record GPU-landed wait transitions on blocked later gates so they are not misclassified as CPU-met + // once an earlier gate on the same queue opens on a subsequent pass (and record bare/value downgrades). + if (!force && !lost && !gate.action && !gate.relaying && !landed_ranges.empty()) { + if (gate.wait_met.size() != gate.waits.size()) gate.wait_met.assign(gate.waits.size(), 0); + for (std::size_t wi = 0; wi < gate.waits.size(); ++wi) { + if (gate.wait_met[wi]) continue; + const LandedMatch match = match_landed(gate.waits[wi], landed_ranges); + if (match != LandedMatch::none && met_now(gate.waits[wi])) { + gate.wait_met[wi] = 1; + if (match != LandedMatch::gpu_met) { + if (!gate.cpu_met) { + if (match == LandedMatch::bare) + bump(counters().gpu_relay_downgraded_bare); + else + bump(counters().gpu_relay_downgraded_val); + } + gate.cpu_met = true; + } + } + } + } + continue; + } + if (!force && !lost && gate.relaying) { + any_relaying = true; + blocked.push_back(queue); + continue; + } + bool open = force || lost; + bool gpu_relay = false; if (gate.action) { open = open || queue->written->GetCompletedValue() >= gate.after; } else { - if (!gate.started) start_gate(gate, now); + if (gate.wait_met.size() != gate.waits.size()) gate.wait_met.assign(gate.waits.size(), 0); bool met = true; - 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); + for (std::size_t wi = 0; wi < gate.waits.size(); ++wi) { + const Wait& wait = gate.waits[wi]; + if (met_now(wait)) { + if (!gate.wait_met[wi]) { + gate.wait_met[wi] = 1; + const LandedMatch match = match_landed(wait, landed_ranges); + if (match != LandedMatch::gpu_met) { + if (!gate.cpu_met) { + if (match == LandedMatch::bare) + bump(counters().gpu_relay_downgraded_bare); + else if (match == LandedMatch::val_mismatch) + bump(counters().gpu_relay_downgraded_val); + } + gate.cpu_met = true; + } + } + } else { + gate.wait_met[wi] = 0; + met = false; } - 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 (met || force) + note_met_gate(gate, now); + else if (lost) + note_released(gate, Reason::lost, now); + open = open || met; + // Strictly vis_seq = 0 only when every wait transitioned false -> true via Pump::land(). + gpu_relay = !force && !lost && !gate.action && !gate.waits.empty() && !gate.cpu_met; } if (open) { - opening.push_back({std::move(gate.queue), gate.value, std::move(gate.action)}); + opening.push_back({std::move(gate.queue), gate.value, std::move(gate.action), gpu_relay}); opened[idx] = true; } else { blocked.push_back(queue); } } + // Nothing opened: may a held gate go without its value? Only when nothing else can make progress. + if (opening.empty() && !force && !lost && !any_relaying) { + const std::size_t chosen = choose_release(landed_any); + if (chosen < gates_.size()) { + Gate& gate = gates_[chosen]; + opening.push_back({std::move(gate.queue), gate.value, nullptr, false}); + opened[chosen] = true; + } + } if (!opening.empty()) { std::deque rest; for (std::size_t idx = 0; idx < gates_.size(); ++idx) @@ -847,23 +1131,112 @@ class Pump { } } + // The progress rules over what is in flight (src/list_value_progress.h): the index of the gate that goes, noted + // and logged, or gates_.size(). Called with mutex_ held, after a pass that opened nothing. + std::size_t choose_release(bool landed_any) { + namespace lvp = leonida::list_value_progress; + const std::uint64_t now_ms = GetTickCount64(); + lvp::Activity activity; + activity.releasing = landed_any || pending_releases_.load(std::memory_order_acquire) != 0; + activity.title_submitting = + title_calls_.load(std::memory_order_relaxed) != 0 || leonida::queue_holds::any_progress(); + if (activity.releasing || activity.title_submitting) { + last_progress_ms_ = now_ms; + return gates_.size(); // the cheap answer first + } + activity.presents = presents_.load(std::memory_order_relaxed); + activity.now_ms = now_ms; + activity.title_call_ms = (std::max)(title_call_ms_.load(std::memory_order_relaxed), last_progress_ms_); + + std::size_t total_writes = 0; + for (const WriteGroup& wg : writes_) total_writes += wg.writes.size(); + std::vector flat_writes; + std::vector groups; + flat_writes.reserve(total_writes); + groups.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}); + // Running or already completed (waiting for the next pass to land): its Signal reached the GPU, or the + // GPU retired it between take_landed() and here. Either way progress is guaranteed; if already done, wake + // the pump immediately so take_landed() lands it before considering any unmet release. + const UINT64 done = wg.queue->written->GetCompletedValue(); + if (done != UINT64_MAX && (done >= wg.value || signal_submitted(wg.queue->written, wg.value))) { + last_progress_ms_ = now_ms; + if (done >= wg.value && wake_) SetEvent(wake_); + return gates_.size(); + } + groups.push_back({wg.queue.get(), wg.after_gate, false, + std::span(flat_writes).subspan(start, wg.writes.size())}); + } + std::size_t total_waits = 0; + for (const Gate& g : gates_) total_waits += g.waits.size(); + std::vector flat_waits; + flat_waits.reserve(total_waits); + std::vector> ranges; + ranges.reserve(gates_.size()); + for (const Gate& g : gates_) { + const std::size_t start = flat_waits.size(); + for (const Wait& w : g.waits) + if (!met_now(w)) flat_waits.push_back({w.address, w.reference, w.comparison, w.wide}); + ranges.emplace_back(start, flat_waits.size() - start); + } + std::vector view; + view.reserve(gates_.size()); + for (std::size_t i = 0; i < gates_.size(); ++i) { + const Gate& g = gates_[i]; + const bool action = static_cast(g.action); + if (action) { + const UINT64 done = g.queue->written->GetCompletedValue(); + if (done != UINT64_MAX && (done >= g.after || signal_submitted(g.queue->written, g.after))) { + last_progress_ms_ = now_ms; + if (done >= g.after && wake_) SetEvent(wake_); + return gates_.size(); + } + } + view.push_back({g.queue.get(), g.value, action, false, + std::span(flat_waits).subspan(ranges[i].first, ranges[i].second), + g.presents_at_hold, g.held_ms}); + } + const lvp::Decision decision = lvp::decide(groups, view, activity, console_value_met); + if (decision.reason == lvp::Reason::hold || decision.gate >= gates_.size()) return gates_.size(); + // Gate ONLY Reason::present on a short quiet window after the last observed progress (leaving + // list_value_progress::decide() pure for unit tests) so sub-ms races from deferred CPU Fence::Signal + // callbacks or post-PresentX CPU writes settle before releasing a gate unmet. + constexpr std::uint64_t kPresentQuietMs = 10; + if (decision.reason == lvp::Reason::present && now_ms >= last_progress_ms_ && + now_ms - last_progress_ms_ < kPresentQuietMs) { + return gates_.size(); + } + const Reason reason = gates_[decision.gate].queue->written->GetCompletedValue() == UINT64_MAX + ? Reason::lost + : decision.reason == lvp::Reason::cycle ? Reason::cycle + : decision.reason == lvp::Reason::present ? Reason::present + : Reason::stalled; + note_released(gates_[decision.gate], reason, Clock::now()); + return decision.gate; + } + // Writes landed, then gates opened: the pump's one step. `force` runs on the caller's thread when the threads do // not, and signals there too. void pass(bool force) { const auto started = Clock::now(); std::vector landing; + bool saw_lost = false; { std::lock_guard lock(mutex_); busy_ = true; - take_landed(force, landing); + take_landed(force, landing, saw_lost); } const bool landed_any = !landing.empty(); - for (const WriteGroup& group : landing) land(group); + std::vector landed_ranges; + for (const WriteGroup& group : landing) land(group, landed_ranges); std::vector opening; { std::lock_guard lock(mutex_); watch_late(); - take_open(force, landed_any, opening); + take_open(force, landed_any, saw_lost, landed_ranges, opening); if (!force && !opening.empty()) pending_releases_.fetch_add(opening.size(), std::memory_order_release); } @@ -895,21 +1268,29 @@ class Pump { const auto get = [](const std::atomic& v) { return static_cast(v.load(std::memory_order_relaxed)); }; + char oldest[160]; + { + std::lock_guard lock(mutex_); + describe_oldest(oldest, sizeof(oldest)); + } std::fprintf(stderr, "[rt] d3d12_xs: list values so far: %llu writes recorded, %llu landed, %llu failed; %llu waits " - "recorded, %llu met at submission, %llu relayed; %llu gates held, %llu met, %llu timed out " - "(%llu short, %llu demotions, %llu met late); %llu cuts (%llu deferred to a query's end, %llu " + "recorded, %llu met at submission, %llu relayed; %llu gates held, %llu met, %llu released unmet " + "(%llu because nothing else could run at a present, %llu in a cycle, %llu with the title stalled, " + "%llu at device loss; %llu met after release); %llu cuts (%llu deferred to a query's end, %llu " "failed), %llu on bundles; releaser %llu signals, %.1f ms, longest %.2f ms, %llu stalls; longest pump pass " "%.2f ms; %llu page remaps at the call (longest wait %.2f ms), %llu deferred (%llu failed); " - "timestamps %llu from the GPU, %llu from the CPU clock\n", + "timestamps %llu from the GPU, %llu from the CPU clock; gpu-relay downgraded %llu bare, %llu value%s\n", get(c.writes_recorded), get(c.writes_landed), get(c.writes_failed), get(c.waits_recorded), get(c.waits_met_at_submit), get(c.waits_relayed), get(c.gates_held), get(c.gates_met), - get(c.gates_timed_out), get(c.gates_short), get(c.demotions), get(c.late_met), get(c.cuts), + get(c.gates_released), get(c.released_present), get(c.released_cycle), get(c.released_stalled), + get(c.released_lost), get(c.met_after_release), get(c.cuts), get(c.cuts_deferred), get(c.cut_failures), get(c.bundle_ops), get(c.releases), get(c.release_us) / 1000.0, get(c.release_us_max) / 1000.0, get(c.release_stalls), get(c.pass_us_max) / 1000.0, get(c.remaps_now), get(c.remap_wait_us_max) / 1000.0, get(c.remaps_deferred), - get(c.remaps_failed), get(c.stamps_gpu), get(c.stamps_cpu)); + get(c.remaps_failed), get(c.stamps_gpu), get(c.stamps_cpu), + get(c.gpu_relay_downgraded_bare), get(c.gpu_relay_downgraded_val), oldest); } // A timestamp write's value: the GPU's timestamp for the write's place in its list when the GPU wrote one, else @@ -972,7 +1353,7 @@ class Pump { // - the title's memory: kernel_writes::store, as before. // - a page of xmem's that the title's view keeps PAGE_NOACCESS, where that store faults: xmem writes its own // mapping of the physical page. - void land(const WriteGroup& group) { + void land(const WriteGroup& group, std::vector& landed_ranges) { note_stamps(*group.queue, group); for (const Write& write : group.writes) { const std::uint64_t value = write.kind == WriteKind::value ? write.value : stamp(*group.queue, write); @@ -989,6 +1370,9 @@ class Pump { } if (landed) { bump(counters().writes_landed); + if (write.bytes && write.address <= UINT64_MAX - write.bytes) + landed_ranges.push_back( + {write.address, value, write.bytes, write.kind == WriteKind::value, group.bare}); continue; } bump(counters().writes_failed); @@ -999,60 +1383,78 @@ class Pump { } } - // The gates before it on its queue have opened: its time starts now. The short timeout goes to a gate with an - // address that timed out three times in a row, and, while every wait is demoted, to one with an address no wait - // was ever met for (an address the title waits on and some write does meet keeps its full timeout). Called with - // mutex_ held. - void start_gate(Gate& gate, Clock::time_point now) { - const unsigned full = timeout_ms_.load(std::memory_order_relaxed); - bool cut_short = false, unknown = false; + enum class Reason : std::uint8_t { cycle, present, stalled, lost }; + + static const char* reason_text(Reason reason) { + namespace lvp = leonida::list_value_progress; + switch (reason) { + case Reason::cycle: return lvp::reason_text(lvp::Reason::cycle); + case Reason::present: return lvp::reason_text(lvp::Reason::present); + case Reason::stalled: return lvp::reason_text(lvp::Reason::stalled); + default: return "the device is lost"; + } + } + + // A memory gate's waits compare true. Called with mutex_ held. + void note_met_gate(const Gate& gate, Clock::time_point now) { + bump(counters().gates_met); + 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(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); + } + } + + // A memory gate goes without its value: counted, logged (the first 32, then every 64th) with the gate, the wait + // and the reason, and one of its unmet waits watched for whether memory meets it later. Called with mutex_ held. + void note_released(const Gate& gate, Reason reason, Clock::time_point now) { + Counters& c = counters(); + bump(c.gates_released); + bump(reason == Reason::cycle ? c.released_cycle + : reason == Reason::present ? c.released_present + : reason == Reason::stalled ? c.released_stalled + : c.released_lost); + const double held = std::chrono::duration(now - gate.since).count(); + const std::uint64_t n = ++logged_released_; + bool watched = false; for (const Wait& wait : gate.waits) { - const Streak* streak = find_streak(wait.address); - if (streak && streak->timeouts >= kDemoteAfter) cut_short = true; - if (!streak || !streak->met) unknown = true; + if (met_now(wait)) continue; + if (!watched && reason != Reason::lost) { + if (late_.size() >= kMaxLate) late_.erase(late_.begin()); + late_.push_back({wait, now}); + watched = true; + } + if (n > 32 && n % 64 != 0) continue; + std::uint64_t current = 0; + read_value(wait.address, wait.wide, current); + std::fprintf(stderr, + "[rt] d3d12_xs: released gate %llu of queue %p unmet after %.1f ms: wait for 0x%llx (%u-bit, " + "comparison %u, reference 0x%llx, memory 0x%llx); %s (release %llu)\n", + static_cast(gate.value), static_cast(gate.queue.get()), held, + static_cast(wait.address), wait.wide ? 64u : 32u, wait.comparison, + static_cast(wait.reference), static_cast(current), + reason_text(reason), static_cast(n)); } - cut_short = (cut_short || (demoted_ && unknown)) && kDemotedTimeoutMs < full; - if (cut_short) bump(counters().gates_short); - gate.started = true; - gate.cut_short = cut_short; - gate.since = now; - 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. - // Called with mutex_ held. - void note_met(std::uint64_t address) { - Streak* streak = find_streak(address); - if (!streak) streak = add_streak(address); - streak->met = true; - streak->timeouts = 0; - } - - // A gate cut short by the demotion of every wait was met within its short timeout: waits are met again, every - // wait gets the full timeout. (Not a gate with the full timeout, nor a late meet: those leave the waits that - // nothing meets cut short.) Called with mutex_ held. - void lift_demotion(std::uint64_t address) { - if (!demoted_) return; - demoted_ = false; - static std::atomic logged{0}; - if (logged.fetch_add(1, std::memory_order_relaxed) < 8) - std::fprintf(stderr, "[rt] d3d12_xs: a wait for 0x%llx cut short was met: waits get %u ms again\n", - static_cast(address), timeout_ms_.load(std::memory_order_relaxed)); } - // The waits cut short, watched until their full timeout would have run out. Called with mutex_ held. + // The waits released unmet, watched for kLateWatchMs: met in that time, counted and (the first 16) logged with + // how long after the release. A measurement only: whether released waits reach across the title's presents. + // Called with mutex_ held. void watch_late() { if (late_.empty()) return; const auto now = Clock::now(); for (auto it = late_.begin(); it != late_.end();) { if (met_now(it->wait)) { - bump(counters().late_met); - note_met(it->wait.address); + bump(counters().met_after_release); + static std::atomic logged{0}; + if (logged.fetch_add(1, std::memory_order_relaxed) < 16) + std::fprintf(stderr, "[rt] d3d12_xs: the wait for 0x%llx released unmet was met %.1f ms after " + "its release\n", + static_cast(it->wait.address), + std::chrono::duration(now - it->released).count()); it = late_.erase(it); - } else if (now >= it->until) { + } else if (now - it->released >= std::chrono::milliseconds(kLateWatchMs)) { it = late_.erase(it); } else { ++it; @@ -1060,64 +1462,17 @@ class Pump { } } - // Called with mutex_ held. - 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 && !gate.waits.empty()) { // the first few, to show the model at work in a boot log - ++logged_met_; - 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); - } + // The oldest memory gate still held, for the summary: how long, and for what. Called with mutex_ held. + void describe_oldest(char* text, std::size_t size) const { + text[0] = 0; + for (const Gate& gate : gates_) { + if (gate.action || gate.waits.empty()) continue; + const double held = std::chrono::duration(Clock::now() - gate.since).count(); + std::snprintf(text, size, "; oldest held gate %llu of queue %p, %.0f ms, for 0x%llx", + static_cast(gate.value), static_cast(gate.queue.get()), + held, static_cast(gate.waits.front().address)); return; } - bump(counters().gates_timed_out); - const unsigned full = timeout_ms_.load(std::memory_order_relaxed); - if (++timeouts_in_a_row_ >= kDemoteAllAfter && !demoted_ && kDemotedTimeoutMs < full) { - demoted_ = true; - bump(counters().demotions); - static std::atomic logged{0}; - if (logged.fetch_add(1, std::memory_order_relaxed) < 8) - std::fprintf(stderr, "[rt] d3d12_xs: %u waits in a row timed out: every wait gets %u ms until one " - "cut short is met (addresses met before keep %u ms)\n", timeouts_in_a_row_, - kDemotedTimeoutMs, full); - } - bool watched = false; - for (const Wait& wait : gate.waits) { - if (met_now(wait)) continue; - if (gate.cut_short && !watched && late_.size() < kMaxLate) { - 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 current = 0; - read_value(wait.address, wait.wide, current); - if (!streak->logged) { - streak->logged = true; - static std::atomic addresses{0}; - if (addresses.fetch_add(1, std::memory_order_relaxed) < 16) - std::fprintf(stderr, - "[rt] d3d12_xs: a queue stood %u ms at a wait for 0x%llx (%u-bit, comparison %u, " - "reference 0x%llx, memory 0x%llx); it runs on (logged once per address)\n", - gate.cut_short ? kDemotedTimeoutMs : full, - static_cast(wait.address), wait.wide ? 64u : 32u, - wait.comparison, static_cast(wait.reference), - static_cast(current)); - } - if (streak->timeouts == kDemoteAfter) { - static std::atomic demoted{0}; - if (demoted.fetch_add(1, std::memory_order_relaxed) < 16) - std::fprintf(stderr, "[rt] d3d12_xs: the wait for 0x%llx timed out %u times in a row; it gets " - "%u ms until it is met again\n", - static_cast(wait.address), kDemoteAfter, kDemotedTimeoutMs); - } - } } std::mutex mutex_; // the lists below; never held while a fence is signalled or a write lands @@ -1126,16 +1481,18 @@ class Pump { HANDLE timer_ = nullptr; HANDLE thread_ = nullptr; HANDLE releaser_ = nullptr; - std::atomic timeout_ms_{200}; + std::atomic started_{false}; std::deque writes_; std::deque gates_; - std::vector streaks_; std::vector late_; - std::uint64_t use_clock_ = 0; - unsigned timeouts_in_a_row_ = 0; // gates that timed out since one was met - bool demoted_ = false; // every wait gets the short timeout until one is met bool busy_ = false; // a pass is landing or handing over what it took off the lists unsigned logged_met_ = 0; + std::uint64_t logged_released_ = 0; + std::uint64_t last_progress_ms_ = 0; // pump thread only (mutex_): latest tick progress was observed + Clock::time_point last_lost_check_{}; // pump thread only (mutex_): throttled device-loss poll timestamp + std::atomic presents_{0}; // the title's PresentX calls so far + std::atomic title_call_ms_{0}; // GetTickCount64 at the start or end of its latest queue call + std::atomic title_calls_{0}; // title ExecuteCommandLists calls in progress Clock::time_point next_summary_ = Clock::now() + std::chrono::seconds(10); // the pump thread's only std::mutex release_mutex_; // releases_ and releasing_ std::condition_variable release_ready_; diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp index fca6f6f474..21a24aed0e 100644 --- a/runtime/shims/xmem.cpp +++ b/runtime/shims/xmem.cpp @@ -45,6 +45,9 @@ #include "placed_image_map_note.h" #include "../src/dstorage_trace.h" #include "../src/gpu_label_memory.h" +#include "../src/title_frames.h" +#include "../src/title_heap.h" +#include "../src/title_mirror_space.h" #include "../src/title_page_watch.h" #include "../src/title_geometry_watch.h" #include "../src/title_va_alias.h" @@ -81,12 +84,77 @@ void note_attributes(const char* api, uint64_t attributes, size_t size, const vo // The title's XMemAlloc blocks come from a heap of their own instead of the CRT heap (LEONIDA_TITLE_HEAP=0: not). Slot-133 // imports pin title memory page by page for the GPU, and on the CRT heap a pinned page also holds the runtime's own // objects (g_pages' nodes among them): a GPU store past a buffer's end, or into a block freed while its import still -// lived, then corrupted the runtime (speed-30/41/49-52: g_pages found corrupt under g_phys_mutex). Each block keeps its -// size and the heap allocation it sits in just below it. +// lived, then corrupted the runtime (speed-30/41/49-52: g_pages found corrupt under g_phys_mutex). +// +// The heap is the runtime's own (src/title_heap.h) over a reservation in the page mirror's range +// (src/title_mirror_space.h), so a V# or pointer the title writes into a block reaches the mirror at heap_base + the +// block's address, and its committed pages are fed to the mirror as they are committed (they read the title's bytes +// there, not zeros). RtlCreateHeap over a given base faults under Wine. Where the range cannot take the reservation, a +// heap the host places, as before (each block keeps its size and the heap allocation it sits in just below it). struct TitleHeapHeader { void* raw; size_t size; }; +constexpr size_t kTitleHeapBytes = size_t(32) << 30; // address range only: pages are committed as blocks need them + +// Tells the page mirror that the pages of [at, at + bytes) of the heap are committed (each shows itself) or not any +// more (defined with the feed, below). +void feed_heap_pages(uintptr_t at, size_t bytes, bool committed); + +leonida::TitleHeap& mirror_heap() { + static leonida::TitleHeap heap; + return heap; +} +bool mirror_heap_ready() { + static const bool ready = [] { + const char* v = std::getenv("LEONIDA_TITLE_HEAP"); + if (v && std::strcmp(v, "0") == 0) return false; + uintptr_t base = 0; + bool write_watched = false; + const bool want_watch = leonida::title_write_watch::enabled(); + // Not "plain": every committed page is fed to the mirror as it is committed, so a pointer the title wrote reads + // its bytes without anything naming the range first. Try MEM_WRITE_WATCH on this private reservation (never + // combined with MEM_LARGE_PAGES, MEM_PHYSICAL, or section views), falling back silently to MEM_RESERVE. + leonida::title_mirror_space::take(kTitleHeapBytes, 0x10000, false, [&](std::uint64_t at) { + base = leonida::TitleHeap::reserve( + [&](bool try_ww) -> uintptr_t { + if (try_ww && !want_watch) return 0; + void* const made = + VirtualAlloc(reinterpret_cast(static_cast(at)), kTitleHeapBytes, + MEM_RESERVE | (try_ww ? MEM_WRITE_WATCH : 0), PAGE_READWRITE); + return reinterpret_cast(made); + }, + write_watched); + return base != 0; + }); + if (base && write_watched) leonida::title_write_watch::add(base, kTitleHeapBytes); + leonida::TitleHeap::Hooks hooks; + hooks.commit = [write_watched](uintptr_t at, size_t bytes) { + if (!VirtualAlloc(reinterpret_cast(at), bytes, MEM_COMMIT, PAGE_READWRITE)) return false; + leonida::title_memory_map::changed(at, at + bytes); + if (write_watched) leonida::title_write_watch::mark(at, at + bytes); + feed_heap_pages(at, bytes, true); + return true; + }; + hooks.decommit = [write_watched](uintptr_t at, size_t bytes) { + VirtualFree(reinterpret_cast(at), bytes, MEM_DECOMMIT); + leonida::title_memory_map::changed(at, at + bytes); + leonida::geometry_writes::notify(at, at + bytes, leonida::geometry_writes::Event::replaced); + feed_heap_pages(at, bytes, false); + if (write_watched) leonida::title_write_watch::mark(at, at + bytes); + }; + const bool ok = base && mirror_heap().init(base, kTitleHeapBytes, std::move(hooks), write_watched); + if (!ok && base) { + if (write_watched) leonida::title_write_watch::remove(base); + VirtualFree(reinterpret_cast(base), 0, MEM_RELEASE); + } + std::fprintf(stderr, "[rt] xmem: XMemAlloc blocks come from %s%s\n", + ok ? "the runtime's heap in the page mirror's range" : "a heap the host places", + ok && write_watched ? " (MEM_WRITE_WATCH)" : ""); + return ok; + }(); + return ready; +} HANDLE title_heap() { static const HANDLE heap = [] { // Set LEONIDA_TITLE_HEAP=0 to use the CRT heap. @@ -100,8 +168,10 @@ HANDLE title_heap() { } void* allocate_block(size_t size) { size = size ? size : 1; + if (mirror_heap_ready()) + if (void* p = mirror_heap().allocate(size)) return p; // full: the host's heap, as before const HANDLE heap = title_heap(); - if (!heap) return _aligned_malloc(size, kAlign); + if (!heap) return _aligned_malloc(size, kAlign); // LEONIDA_TITLE_HEAP=0 const size_t extra = kAlign + sizeof(TitleHeapHeader); if (size > SIZE_MAX - extra) return nullptr; void* raw = HeapAlloc(heap, 0, size + extra); @@ -114,14 +184,23 @@ void* allocate_block(size_t size) { } size_t block_size(void* p) { if (!p) return 0; + if (mirror_heap_ready() && mirror_heap().owns(p)) return mirror_heap().size_of(p); if (!title_heap()) return _aligned_msize(p, kAlign, 0); return (reinterpret_cast(p) - 1)->size; } -void free_block(void* p) { - if (!p) return; +bool free_block(void* p) { + if (!p) return false; + if (mirror_heap_ready() && mirror_heap().owns(p)) { + mirror_heap().release(p); + return true; + } const HANDLE heap = title_heap(); - if (!heap) return _aligned_free(p); + if (!heap) { + _aligned_free(p); + return false; + } HeapFree(heap, 0, (reinterpret_cast(p) - 1)->raw); + return false; } // Every block and range the title gets here is recorded as the title's memory (src/title_va_alias.h): a shader @@ -145,11 +224,13 @@ void free_title_block(void* p) { if(p)leonida::label::memory().release_heap(reinterpret_cast(p)); if (p) leonida::title_va_aliases().remove_title_memory(reinterpret_cast(p)); const size_t size = block_size(p); - free_block(p); + const bool from_mirror_heap = free_block(p); if (p) { const auto from = reinterpret_cast(p); const size_t bytes = size ? size : 1; - leonida::title_memory_map::changed(p, bytes); + // mirror_heap() reports actual OS commit/decommit via TitleHeap::Hooks; releasing a sub-block does not alter + // OS page mappings or protections. + if (!from_mirror_heap) leonida::title_memory_map::changed(p, bytes); leonida::geometry_writes::note_released(from, from + bytes); } } @@ -533,6 +614,37 @@ using HostUnorderedMap = using AddressSet = std::set, leonida::host_heap::Allocator>; HostUnorderedMap g_mapped; // mapped 64 KiB address -> page number HostUnorderedMap g_page_addresses; // page number -> the addresses it is mapped at +// Pages of a GPU-only range that the console queue's CopyPageMappingsBatchX gave a physical page: in g_mapped, with no +// host view. The title's CPU never touches such a page (the range is PAGE_NOACCESS on the console), and the host reads +// and writes it through its frame (g_table_frames, src/title_frames.h), as the runtime reads a page by its number +// through the section's scratch view (host_page). So the copy there is a table update, as it is on the console, where +// it edits GPU page tables only. With g_phys_mutex held. +// A table page is not one of its physical page's host addresses (note_mapping, g_page_addresses): no host write can +// come through it and no host guard can be set on it, so it never makes those addresses aliased. It is aliased itself +// (note_table_page), with those addresses as its peers: a write through any of them changes its bytes, and the +// slot-133 shadows, geometry copies and title texture watch guard it there. +AddressSet g_table_pages; +// The paired CPU page of a GPU-only destination (title_gpu_views) is a table page too, when the title has not mapped +// a page there itself (title_mapped_twin): the D3D12 layer and DirectStorage read and write the GPU-only range there, +// and they reach it through the frame table (src/title_frames.h), not through a host view. So a slot-31 copy onto a +// paired range makes no host call at all. +// +// Each table page's frame, for readers that must not wait behind g_phys_mutex (title_frames' lookup, table_frame): +// written with g_phys_mutex held under g_frame_lock exclusive, read under it shared. Nothing under it allocates on the +// process heap, faults or logs. The entry keeps its section, so the scratch view a reader was given stays mapped. +SRWLOCK g_frame_lock = SRWLOCK_INIT; +struct TableFrame { + std::shared_ptr
section; + uint64_t offset = 0; +}; +// The physical page each table page holds is in g_mapped; and per physical page, its table pages (g_phys_mutex held), +// whose alias peers follow the page's host addresses (note_mapping). +HostUnorderedMap g_page_tables; +// Queue slot 31's page changes by path (rt::xmem::Slot31Counts): GPU-only pages and paired CPU pages by table, +// paired CPU pages the title mapped itself and left as they are, and host maps or unmaps: a destination with no CPU +// pair, and a view found at a page the table takes over (unmapped once). +std::atomic g_slot31_table_pages{0}, g_slot31_twin_pages{0}, g_slot31_twins_kept{0}, + g_slot31_host_pages{0}, g_slot31_views_replaced{0}; // The same aliases, for readers that must not wait behind g_phys_mutex (geometry_aliases, from the D3D12 layer's // submission thread: speed-16 and re-1 had it waiting there behind the streaming workers' scatter batches and the // render thread's queue slot 31, which hold g_phys_mutex through every MapViewOfFile3). Only addresses whose page is @@ -541,6 +653,49 @@ HostUnorderedMap g_page_addresses; // page number -> the std::shared_mutex g_alias_lock; using AddressList = std::vector>; HostUnorderedMap g_alias_peers; +// The frames of g_table_frames, under g_frame_lock (declared with it). +HostUnorderedMap g_table_frames; + +// The page mirror's feed (src/title_frames.h, Feed), under g_phys_mutex. +leonida::title_frames::Feed g_mirror_feed = nullptr; +void* g_mirror_context = nullptr; + +// The heap's committed pages show themselves (title_heap): fed to the page mirror as they are committed and +// decommitted, under g_phys_mutex like every other change of the feed. Called with the heap's lock held (heap, then +// g_phys_mutex; attach_mirror takes the heap's lock only after releasing g_phys_mutex). +void feed_heap_pages(uintptr_t at, size_t bytes, bool committed) { + const std::lock_guard lock(g_phys_mutex); + if (!g_mirror_feed) return; + for (uintptr_t page = at & ~uintptr_t(kPhysicalPageSize - 1); page < at + bytes; page += kPhysicalPageSize) + g_mirror_feed(g_mirror_context, page, committed ? reinterpret_cast(page) : nullptr, {}); +} + +// With g_phys_mutex held: the page at `address` shows physical page `page` now (0: nothing), for the page mirror. +void feed_mirror(uintptr_t address, uint64_t page) { + if (!g_mirror_feed || !leonida::title_mirror_space::contains(address)) return; + if (page) { + if (const auto backing = g_pages.find(page); backing != g_pages.end() && backing->second.section && + backing->second.section->scratch) { + g_mirror_feed(g_mirror_context, address, + static_cast(backing->second.section->scratch) + backing->second.offset, + backing->second.section); + return; + } + } + g_mirror_feed(g_mirror_context, address, nullptr, {}); +} + +// With g_phys_mutex held, and g_alias_lock exclusive: the table page `table`'s alias peers are the host addresses of +// its physical page (`addresses`). A table page is not one of those addresses itself (no write can come through it), +// but a write through any of them changes its bytes: the shadows and the watches guard it there. +void set_table_peers_locked(uintptr_t table, const AddressSet* addresses) { + if (!addresses || addresses->empty()) { + g_alias_peers.erase(table); + return; + } + AddressList& peers = g_alias_peers[table]; + peers.assign(addresses->begin(), addresses->end()); +} // With g_phys_mutex held. Keeps leonida::title_page_aliases in step: a page mapped at two or more addresses is // aliased at each of them (the D3D12 layer's slot-133 shadows guard those pages at every address, since a write @@ -567,16 +722,117 @@ void note_mapping(uint64_t page, uintptr_t address, bool mapped) { for (const uintptr_t other : addresses) if (other != at) peers.push_back(other); } + // The page's table pages are written through every one of its host addresses. + const auto tables = g_page_tables.find(page); + if (tables != g_page_tables.end()) + for (const uintptr_t table : tables->second) set_table_peers_locked(table, &addresses); // After the peers: a cell's watcher that sees the new mapping asks geometry_aliases for the addresses again. using namespace leonida::geometry_writes; if (state().count.load(std::memory_order_acquire)) { notify(address, address + kPhysicalPageSize, Event::mapping); for (auto other : addresses) if (other != address) notify(other, other + kPhysicalPageSize, Event::mapping); + if (tables != g_page_tables.end()) + for (const uintptr_t table : tables->second) notify(table, table + kPhysicalPageSize, Event::mapping); } + feed_mirror(address, mapped ? page : 0); if (addresses.empty()) g_page_addresses.erase(page); } +// With g_phys_mutex held. The table page at `table` held physical page `was` (0: none) and holds `page` now (0: it +// leaves the table): its frame for the readers (g_table_frames), its physical page's list of table pages, and its alias +// mark and peers. A table page is always aliased: its bytes change through other addresses (its physical page's host +// views) or through the table, never through a write at its own address, so a reader guards it with the geometry +// watch's cells there and at the peers. The caller raises the remap itself (title_memory_map, geometry_writes). +void note_table_page(uintptr_t table, uint64_t was, uint64_t page) { + if (was && was != page) { + if (const auto it = g_page_tables.find(was); it != g_page_tables.end()) { + it->second.erase(table); + if (it->second.empty()) g_page_tables.erase(it); + } + } + TableFrame frame; + if (page) { + if (const auto backing = g_pages.find(page); backing != g_pages.end()) + frame = TableFrame{backing->second.section, backing->second.offset}; + g_page_tables[page].insert(table); + leonida::title_frames::note_page(table); + } + { + AcquireSRWLockExclusive(&g_frame_lock); + if (frame.section) + std::swap(g_table_frames[table], frame); // the old frame is released after the lock + else if (const auto it = g_table_frames.find(table); it != g_table_frames.end()) { + frame = std::move(it->second); + g_table_frames.erase(it); + } + ReleaseSRWLockExclusive(&g_frame_lock); + } + leonida::title_page_aliases::set(table, page != 0); + feed_mirror(table, page); + const std::unique_lock aliases(g_alias_lock); + const auto addresses = page ? g_page_addresses.find(page) : g_page_addresses.end(); + set_table_peers_locked(table, addresses != g_page_addresses.end() ? &addresses->second : nullptr); +} + +// title_frames' lookup (src/title_frames.h): the frame of the table page at `page`. From any thread, with any lock of +// the D3D12 layer's held: only g_frame_lock is taken. +bool table_frame(std::uintptr_t page, leonida::title_frames::Frame& out) { + std::shared_ptr
section; + uint64_t offset = 0; + AcquireSRWLockShared(&g_frame_lock); + if (const auto it = g_table_frames.find(page); it != g_table_frames.end()) { + section = it->second.section; + offset = it->second.offset; + } + ReleaseSRWLockShared(&g_frame_lock); + if (!section || !section->scratch) return false; + out.bytes = static_cast(section->scratch) + offset; + out.keep = std::move(section); + return true; +} + +// Single-lock, zero-shared_ptr run_end over g_table_frames (src/title_frames.h). +std::uintptr_t table_frame_run_end(std::uintptr_t from, std::uintptr_t to, bool& is_backed) { + constexpr std::uintptr_t kPage = leonida::title_frames::kPage; + if (from >= to) { + is_backed = false; + return to; + } + AcquireSRWLockShared(&g_frame_lock); + const auto has = [](std::uintptr_t p) -> bool { + const auto it = g_table_frames.find(p); + return it != g_table_frames.end() && it->second.section && it->second.section->scratch; + }; + const std::uintptr_t first_page = from & ~(kPage - 1); + is_backed = has(first_page); + if (!is_backed && g_table_frames.empty()) { + ReleaseSRWLockShared(&g_frame_lock); + return to; + } + std::uintptr_t at = first_page + kPage; + while (at < to && at > from && has(at) == is_backed) at += kPage; + ReleaseSRWLockShared(&g_frame_lock); + return at < to && at > from ? at : to; +} + +// Single-lock, zero-shared_ptr batch existence check over g_table_frames (src/title_frames.h). +void table_frame_backed_batch(const std::uintptr_t* pages, std::uint8_t* out_backed, std::size_t count) { + constexpr std::uintptr_t kPage = leonida::title_frames::kPage; + if (!count) return; + AcquireSRWLockShared(&g_frame_lock); + if (g_table_frames.empty()) { + ReleaseSRWLockShared(&g_frame_lock); + for (std::size_t k = 0; k < count; ++k) out_backed[k] = 0; + return; + } + for (std::size_t k = 0; k < count; ++k) { + const auto it = g_table_frames.find(pages[k] & ~(kPage - 1)); + out_backed[k] = (it != g_table_frames.end() && it->second.section && it->second.section->scratch) ? 1u : 0u; + } + ReleaseSRWLockShared(&g_frame_lock); +} + // Appends `value` in hex (with 0x) or decimal at `at`, which has room for it: no CRT, so no lock and no allocation. char* append_number(char* at, unsigned long long value, bool hex) { char digits[24]; @@ -917,8 +1173,21 @@ void* xmem_virtual_alloc(void* address, SIZE_T size, DWORD allocation_type, ULON record_window(address, size, host_prot, caller, true); return address; } + // A reservation the title lets the host place goes into the page mirror's range (src/title_mirror_space.h), so a V# + // or pointer the title writes with its address reaches the mirror at heap_base + the address. `reserve(at)` makes + // the reservation at `at`; null when the range is spent or the host refused every address tried (then the host + // places it, as before). + const auto in_mirror_space = [&](auto&& reserve) -> void* { + void* made = nullptr; + leonida::title_mirror_space::take(size, base_granularity, !(new_placeholder || window), [&](std::uint64_t at) { + made = reserve(reinterpret_cast(static_cast(at))); + return made != nullptr; + }); + return made; + }; if (new_placeholder || window) { - void* const result = reserve_placeholder(address, size, base_granularity); + void* placed = address ? nullptr : in_mirror_space([&](void* at) { return reserve_placeholder(at, size, base_granularity); }); + void* const result = placed ? placed : reserve_placeholder(address, size, base_granularity); if (result && window) { const std::lock_guard lock(g_phys_mutex); record_window(result, size, host_prot, caller, false); @@ -943,6 +1212,12 @@ void* xmem_virtual_alloc(void* address, SIZE_T size, DWORD allocation_type, ULON return result; } if (page_mode == kXmemLargePages && address == nullptr) { + if (void* placed = in_mirror_space([&](void* at) { + return reserve_watched(host_type | MEM_RESERVE, at, size, [&](DWORD type) { + return placeholder_api().virtual_alloc2(GetCurrentProcess(), at, size, type, host_prot, nullptr, 0); + }); + })) + return placed; MEM_ADDRESS_REQUIREMENTS requirements{}; requirements.Alignment = kXmemPageSize2m; MEM_EXTENDED_PARAMETER parameter{}; @@ -952,6 +1227,13 @@ void* xmem_virtual_alloc(void* address, SIZE_T size, DWORD allocation_type, ULON return placeholder_api().virtual_alloc2(GetCurrentProcess(), nullptr, size, type, host_prot, ¶meter, 1); }); } + // A reservation (or a commit at no given address, which reserves too) the host would place. + if (!address && (host_type & (MEM_RESERVE | MEM_COMMIT))) + if (void* placed = in_mirror_space([&](void* at) { + return reserve_watched(host_type | MEM_RESERVE, at, size, + [&](DWORD type) { return VirtualAlloc(at, size, type, host_prot); }); + })) + return placed; return reserve_watched(host_type, address, size, [&](DWORD type) { return VirtualAlloc(address, size, type, host_prot); }); } @@ -1047,6 +1329,19 @@ struct UnmapCause { // sees the failure. bool unmap_range_locked(uintptr_t start, uintptr_t end) { g_unmaps[g_unmap_count++ % kUnmapRecords] = {start, end, GetTickCount64(), t_unmap_cause}; + // Table pages (g_table_pages) have no view: they leave the table here, and their readers are told as of an unmap. + for (auto table = g_table_pages.lower_bound(start); table != g_table_pages.end() && *table < end;) { + const uintptr_t at = *table; + uint64_t was = 0; + if (const auto mapped = g_mapped.find(at); mapped != g_mapped.end()) { + was = mapped->second; + g_mapped.erase(mapped); + } + table = g_table_pages.erase(table); + note_table_page(at, was, 0); + leonida::title_memory_map::changed(at, at + kPhysicalPageSize); + leonida::geometry_writes::notify(at, at + kPhysicalPageSize, leonida::geometry_writes::Event::replaced); + } auto it = g_views.upper_bound(start); if (it != g_views.begin()) { const auto prev = std::prev(it); @@ -2024,6 +2319,135 @@ bool title_mapped_twin(uintptr_t address, uintptr_t gpu, bool unmap) { return true; } +// Batched table-page update used by copy_page_mappings() so slot-31 ranges take g_frame_lock, title_page_aliases, +// g_alias_lock, title_memory_map::changed(), and geometry_writes::notify() once per contiguous range instead of once +// per 64 KiB page. Called with g_phys_mutex held. +struct TablePageUpdate { + uintptr_t address = 0; + uint64_t page = 0; + TableFrame frame; +}; + +bool prepare_table_page(uintptr_t address, uint64_t page, std::vector& batch) { + if (page && !g_pages.contains(page)) { + SetLastError(ERROR_INVALID_PARAMETER); + return false; + } + uint64_t was = 0; + if (const auto table = g_table_pages.find(address); table != g_table_pages.end()) { + const auto mapped = g_mapped.find(address); + // Unchanged only when the frame it holds is the memory behind the number now: a number the title freed comes + // back with its next allocation (g_free_slots, last in first out) naming another page, while the table entry + // still holds the freed one's frame. (g_table_frames is written with g_phys_mutex held, so it is read here + // without g_frame_lock.) + if (mapped != g_mapped.end() && mapped->second == page) { + const auto frame = g_table_frames.find(address); + const auto backing = page ? g_pages.find(page) : g_pages.end(); + if (!page || (frame != g_table_frames.end() && backing != g_pages.end() && + frame->second.section == backing->second.section && + frame->second.offset == backing->second.offset)) + return true; + } + if (mapped != g_mapped.end()) { + was = mapped->second; + g_mapped.erase(mapped); + } + g_table_pages.erase(table); + } else { + bool viewed; + { + const FaultLockShared faults; + viewed = view_covers(address); + } + if (viewed) { + if (!unmap_page(address)) return false; // also drops its g_mapped entry + g_slot31_views_replaced.fetch_add(1, std::memory_order_relaxed); + } + } + if (page) { + g_mapped[address] = page; + g_table_pages.insert(address); + } + if (was && was != page) { + if (const auto it = g_page_tables.find(was); it != g_page_tables.end()) { + it->second.erase(address); + if (it->second.empty()) g_page_tables.erase(it); + } + } + TableFrame frame; + if (page) { + if (const auto backing = g_pages.find(page); backing != g_pages.end()) + frame = TableFrame{backing->second.section, backing->second.offset}; + g_page_tables[page].insert(address); + leonida::title_frames::note_page(address); + } + batch.push_back({address, page, std::move(frame)}); + return true; +} + +// With g_phys_mutex held. Publishes a batch of prepared table-page updates across g_frame_lock (releasing old +// TableFrame shared_ptrs outside the lock), title_page_aliases, feed_mirror, g_alias_lock, and per-contiguous-range +// title_memory_map::changed() + geometry_writes::notify(Event::replaced). +void commit_table_page_batch(std::vector& batch) { + if (batch.empty()) return; + std::vector old_frames; + old_frames.reserve(batch.size()); + { + AcquireSRWLockExclusive(&g_frame_lock); + for (TablePageUpdate& u : batch) { + if (u.frame.section) { + TableFrame prev = std::move(u.frame); + std::swap(g_table_frames[u.address], prev); + if (prev.section) old_frames.push_back(std::move(prev)); + } else if (const auto it = g_table_frames.find(u.address); it != g_table_frames.end()) { + old_frames.push_back(std::move(it->second)); + g_table_frames.erase(it); + } + } + ReleaseSRWLockExclusive(&g_frame_lock); + } + old_frames.clear(); // release old TableFrame shared_ptrs outside g_frame_lock + { + auto& alias_state = leonida::title_page_aliases::state(); + std::unique_lock alias_lock(alias_state.mutex); + bool any_changed = false; + for (const TablePageUpdate& u : batch) { + const uintptr_t va = u.address & ~(leonida::title_page_aliases::kPageSize - 1); + const bool ch = u.page != 0 ? alias_state.aliased.insert(va).second + : (alias_state.aliased.erase(va) != 0); + any_changed = any_changed || ch; + } + if (any_changed) alias_state.generation.fetch_add(1, std::memory_order_release); + } + if (g_mirror_feed) { + for (const TablePageUpdate& u : batch) feed_mirror(u.address, u.page); + } + { + const std::unique_lock aliases(g_alias_lock); + for (const TablePageUpdate& u : batch) { + const auto addresses = u.page ? g_page_addresses.find(u.page) : g_page_addresses.end(); + set_table_peers_locked(u.address, addresses != g_page_addresses.end() ? &addresses->second : nullptr); + } + } + std::vector addrs; + addrs.reserve(batch.size()); + for (const TablePageUpdate& u : batch) addrs.push_back(u.address); + std::sort(addrs.begin(), addrs.end()); + addrs.erase(std::unique(addrs.begin(), addrs.end()), addrs.end()); + for (std::size_t i = 0; i < addrs.size();) { + const uintptr_t run_lo = addrs[i]; + uintptr_t run_hi = run_lo + kPhysicalPageSize; + ++i; + while (i < addrs.size() && addrs[i] == run_hi) { + run_hi += kPhysicalPageSize; + ++i; + } + leonida::title_memory_map::changed(run_lo, run_hi); + leonida::geometry_writes::notify(run_lo, run_hi, leonida::geometry_writes::Event::replaced); + } + batch.clear(); +} + 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); @@ -2039,19 +2463,39 @@ bool copy_page_mappings(void* destination, const void* source, uint64_t pages, b } const std::lock_guard lock(g_phys_mutex); // 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. + // (title_gpu_views::to_cpu); that view gets the same pages in the table (prepare_table_page), or it would never be + // readable. Both are table updates: the host reads them through their frames (src/title_frames.h). 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; + std::vector table_batch; + if (cpu_window && pages) table_batch.reserve(static_cast(pages) * 2); + struct TableBatchCommit { + std::vector& batch; + ~TableBatchCommit() { commit_table_page_batch(batch); } + } commit_guard{table_batch}; + // The paired CPU page follows the GPU-only one unless the title mapped a page there itself. + const auto twin = [&](uintptr_t cpu, uintptr_t gpu, uint64_t page, bool unmap) { + if (title_mapped_twin(cpu, gpu, unmap)) { + g_slot31_twins_kept.fetch_add(1, std::memory_order_relaxed); + return true; + } + if (!prepare_table_page(cpu, page, table_batch)) return false; + g_slot31_twin_pages.fetch_add(1, std::memory_order_relaxed); + return true; + }; if (!source) { for (uint64_t i = 0; i < pages; ++i) { const uintptr_t gpu = to + i * kPhysicalPageSize, cpu = cpu_to + i * kPhysicalPageSize; - { - const UnmapCause cause("CopyPageMappingsBatchX (unmap)"); + const UnmapCause cause("CopyPageMappingsBatchX (unmap)"); + // A page of a paired range leaves the table; any other destination is unmapped on the host. + if (!cpu_window) { if (!unmap_page(gpu)) return false; + g_slot31_host_pages.fetch_add(1, std::memory_order_relaxed); + continue; } - if (!cpu_window || title_mapped_twin(cpu, gpu, true)) continue; - const UnmapCause cause("CopyPageMappingsBatchX (unmap paired CPU page)"); - if (!unmap_page(cpu)) return false; + if (!prepare_table_page(gpu, 0, table_batch)) return false; + g_slot31_table_pages.fetch_add(1, std::memory_order_relaxed); + if (!twin(cpu, gpu, 0, true)) return false; } return true; } @@ -2071,18 +2515,26 @@ bool copy_page_mappings(void* destination, const void* source, uint64_t pages, b if (it != g_mapped.end()) found[static_cast(i)] = it->second; } const DWORD protect = view_protect(*window); - 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)]; 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; + // Both pages of a paired range are table entries (prepare_table_page); a destination without a CPU pair (an + // independent-pages range, LEONIDA_SLOT31_RUNS) is read where it is, so it is mapped on the host as before. + if (!cpu_window) { + if (!map_page(gpu, page, protect, MapOwner::slot31)) return false; + g_slot31_host_pages.fetch_add(1, std::memory_order_relaxed); + continue; + } + if (!prepare_table_page(gpu, page, table_batch)) return false; + g_slot31_table_pages.fetch_add(1, std::memory_order_relaxed); + if (!twin(cpu, gpu, page, false)) return false; } return true; } [[maybe_unused]] const bool g_copy_page_mappings_set =(rt::xmem::copy_page_mappings_fn = ©_page_mappings, true); +[[maybe_unused]] const bool g_slot31_mapping_counts_set = + (rt::xmem::slot31_mapping_counts_fn = &rt::xmem::slot31_mapping_counts, true); // The title's write watching, on reservations it made with MEM_WRITE_WATCH. One xmem write-watched for the shadows // (reserve_watched) is refused as the host refuses a region that is not write-watched ((UINT)-1, @@ -2165,8 +2617,21 @@ constexpr DWORD kMemTitle = 0x40000000; LPVOID WINAPI TitleVirtualAlloc(LPVOID address, SIZE_T size, DWORD allocation_type, DWORD protect) { const DWORD type = allocation_type & ~(kMemGraphics | kMemTitle); const DWORD host_prot = host_protect(protect); - LPVOID result = - reserve_watched(type, address, size, [&](DWORD t) { return VirtualAlloc(address, size, t, host_prot); }); + LPVOID result = nullptr; + // A reservation the host would place goes into the page mirror's range too (src/title_mirror_space.h), as an + // XMemVirtualAlloc one does: a V# or pointer the title writes with its address reaches the mirror. + if (!address && size && (type & (MEM_RESERVE | MEM_COMMIT)) && !(type & (MEM_PHYSICAL | MEM_LARGE_PAGES))) { + SIZE_T rounded = 0; + if (round_up_size(size, kXmemPageSize64k, rounded)) + leonida::title_mirror_space::take(rounded, kXmemPageSize64k, true, [&](std::uint64_t at) { + void* const there = reinterpret_cast(static_cast(at)); + result = reserve_watched(type | MEM_RESERVE, there, size, + [&](DWORD t) { return VirtualAlloc(there, size, t, host_prot); }); + return result != nullptr; + }); + } + if (!result) + result = reserve_watched(type, address, size, [&](DWORD t) { return VirtualAlloc(address, size, t, host_prot); }); if (result) { leonida::title_memory_map::changed(result, size); leonida::title_va_aliases().add_title_memory(reinterpret_cast(result), size); @@ -2276,9 +2741,15 @@ BOOL title_free_impl(LPVOID address, SIZE_T size, DWORD free_type) { } else { result = VirtualFree(address, size, free_type); } - // A release of size 0 frees the whole reservation, whose extent is not known here: a change anywhere. - if (result && size) leonida::title_memory_map::changed(address, size); - else if (result) leonida::title_memory_map::changed(); + // Report the exact released/decommitted extent whenever known so CellGuard::sync_known_protect() only invalidates + // overlapping tiles instead of wiping all cached page protections across the entire address space. + if (result) { + if (size) leonida::title_memory_map::changed(address, size); + else if (releases && release_end > start) leonida::title_memory_map::changed(start, release_end); + else if ((free_type & MEM_DECOMMIT) && decommit_end > start) + leonida::title_memory_map::changed(start, decommit_end); + else leonida::title_memory_map::changed(); + } if (result && (free_type & MEM_DECOMMIT)) note_unwatched_change(address, size, 0, true); if (result && (free_type & MEM_RELEASE) && !(free_type & MEM_PRESERVE_PLACEHOLDER)) leonida::title_write_watch::remove(reinterpret_cast(address)); @@ -2335,7 +2806,13 @@ BOOL WINAPI TitleVirtualProtect(LPVOID address, SIZE_T size, DWORD protect, PDWO const auto start = reinterpret_cast(address); // Before the call: a fault on another thread in between must not take the title's protection for a lost guard. note_title_protect(start, size, protect); + // Our guards over the range (the slot-133 shadows', the geometry and title texture watches' cells) come off first + // and stay off while the call runs, as for a kernel write (a pin: no refresh guards a pinned page): the protection + // the call returns in `old` is the title's own, never one of our read-only guards. A title that saved such an `old` + // and set it back later left the page read-only with no guard to answer for it, and its next write faulted. + const std::uint64_t pin = leonida::kernel_writes::begin_write(address, size, nullptr); const BOOL result = VirtualProtect(address, size, protect, old); + leonida::kernel_writes::end_write(pin, false); if (result) { leonida::title_memory_map::changed(start, start + size); leonida::geometry_writes::notify(start, start + size, leonida::geometry_writes::Event::replaced); @@ -2652,6 +3129,56 @@ void geometry_aliases(std::uintptr_t va, std::vector& addresses) std::uint64_t zero_pages_taken() { return g_zero_pages.next; } +void slot31_mapping_counts(Slot31Counts& out) { + out.gpu_pages = g_slot31_table_pages.load(std::memory_order_relaxed); + out.twin_pages = g_slot31_twin_pages.load(std::memory_order_relaxed); + out.twins_kept = g_slot31_twins_kept.load(std::memory_order_relaxed); + out.unpaired_pages = g_slot31_host_pages.load(std::memory_order_relaxed); + out.views_replaced = g_slot31_views_replaced.load(std::memory_order_relaxed); +} + +// The D3D12 layer and DirectStorage reach table pages through their frames (src/title_frames.h), and guard them at +// their physical pages' host addresses. +// title_frames' Attach (src/title_frames.h): the page mirror's feed from now on, after every page of the mirror's range +// mapped now (the views, then the table pages), all under g_phys_mutex. +void attach_mirror_locked(void* context, leonida::title_frames::Feed feed); +void attach_mirror(void* context, leonida::title_frames::Feed feed) { + attach_mirror_locked(context, feed); + if (!feed || !mirror_heap_ready()) return; + // The heap's committed pages, after g_phys_mutex (the heap takes it under its own lock). A page committed or + // decommitted meanwhile was fed by the heap itself; one fed twice is mapped twice to the same bytes. + std::vector> committed; + mirror_heap().for_each_committed([&](uintptr_t at, size_t bytes) { committed.emplace_back(at, bytes); }); + for (const auto& [at, bytes] : committed) feed_heap_pages(at, bytes, true); +} +void attach_mirror_locked(void* context, leonida::title_frames::Feed feed) { + const std::lock_guard lock(g_phys_mutex); + g_mirror_feed = feed; + g_mirror_context = context; + if (!feed) return; + { + const FaultLockShared faults; + for (const auto& [base, view] : g_views) { + if (view.zero || !view.section || !view.section->scratch) continue; + for (uint64_t i = 0; i < view.count; ++i) { + const uintptr_t at = base + i * kPhysicalPageSize; + if (!leonida::title_mirror_space::contains(at)) continue; + feed(context, at, static_cast(view.section->scratch) + view.offset + i * kPhysicalPageSize, + view.section); + } + } + } + for (const auto& [at, frame] : g_table_frames) + if (leonida::title_mirror_space::contains(at) && frame.section && frame.section->scratch) + feed(context, at, static_cast(frame.section->scratch) + frame.offset, frame.section); +} +[[maybe_unused]] const bool g_mirror_attach_set = (leonida::title_frames::attach_fn = &attach_mirror, true); + +[[maybe_unused]] const bool g_title_frames_set = + (leonida::title_frames::set_lookup(&table_frame, &geometry_aliases, &table_frame_run_end, + &table_frame_backed_batch), + true); + void set_fault_race_hook(FaultRaceHook hook) { g_fault_race_hook.store(hook, std::memory_order_release); } std::uint64_t fault_exits(FaultExit exit) { @@ -2864,6 +3391,10 @@ bool transfer_physical(std::span pages, uint16_t offset, std::sp const size_t bytes = (std::min)(left, size_t(kPhysicalPageSize - at)); if (auto mapped = g_page_addresses.find(page); mapped != g_page_addresses.end()) for (uintptr_t address : mapped->second) ranges.emplace_back(address + at, bytes); + // Its table pages too: the shadows and watches over them guard them at the host addresses above, but a + // pin on the table page itself makes them copy it until the write is done. + if (auto tables = g_page_tables.find(page); tables != g_page_tables.end()) + for (uintptr_t address : tables->second) ranges.emplace_back(address + at, bytes); left -= bytes; at = 0; } @@ -2889,16 +3420,18 @@ bool transfer_physical(std::span pages, uint16_t offset, std::sp const size_t bytes = (std::min)(staging.size(), size_t(kPhysicalPageSize - offset)); if (write) { std::memcpy(ptr, staging.data(), bytes); - if (auto mapped = g_page_addresses.find(page); mapped != g_page_addresses.end()) { - for (uintptr_t address : mapped->second) { - leonida::geometry_writes::notify(address + offset, address + offset + bytes, leonida::geometry_writes::Event::write); - leonida::title_texel_writes::note(reinterpret_cast(address + offset), bytes); - if (leonida::dstorage::trace_enabled()) - std::fprintf(stderr, "[rt] ds-scatter cpu=%llx bytes=%zu page=%llu\n", - static_cast(address + offset), bytes, - static_cast(page)); - } - } + const auto told = [&](uintptr_t address) { + leonida::geometry_writes::notify(address + offset, address + offset + bytes, leonida::geometry_writes::Event::write); + leonida::title_texel_writes::note(reinterpret_cast(address + offset), bytes); + if (leonida::dstorage::trace_enabled()) + std::fprintf(stderr, "[rt] ds-scatter cpu=%llx bytes=%zu page=%llu\n", + static_cast(address + offset), bytes, + static_cast(page)); + }; + if (auto mapped = g_page_addresses.find(page); mapped != g_page_addresses.end()) + for (uintptr_t address : mapped->second) told(address); + if (auto tables = g_page_tables.find(page); tables != g_page_tables.end()) + for (uintptr_t address : tables->second) told(address); } else { std::memcpy(staging.data(), ptr, bytes); } diff --git a/runtime/shims/xmem.h b/runtime/shims/xmem.h index 6e0017f2ba..3fabb95692 100644 --- a/runtime/shims/xmem.h +++ b/runtime/shims/xmem.h @@ -24,6 +24,20 @@ static_assert(sizeof(PageRange) == 12 && sizeof(PageBatch) == 24 && offsetof(Pag // Record the two measured stream-pool reservation return sites; other callers are ignored. void note_stream_reservation(std::uintptr_t base, std::size_t size, std::uintptr_t caller_rva); bool queue_page_mappings_enabled(); +// Pages the console queue's CopyPageMappingsBatchX (the range form, copy_page_mappings_fn) changed so far, by path. By a +// table update alone: a GPU-only page with a CPU pair, and that pair's CPU page (both read through their frames, +// src/title_frames.h). Left as they are: paired CPU pages the title mapped itself. By a host map or unmap, each a +// MapViewOfFile3/UnmapViewOfFile2 pair and a wineserver round trip under Wine: a destination with no CPU pair (an +// independent-pages range), and a view found at a page the table takes over (unmapped once). +struct Slot31Counts { + std::uint64_t gpu_pages = 0, twin_pages = 0, twins_kept = 0, unpaired_pages = 0, views_replaced = 0; + std::uint64_t table() const { return gpu_pages + twin_pages; } + std::uint64_t host() const { return unpaired_pages + views_replaced; } +}; +void slot31_mapping_counts(Slot31Counts& out); +// The same, for the command-object proxy, which is also compiled into tests without xmem: null there. +using Slot31MappingCountsFn = void (*)(Slot31Counts& out); +inline Slot31MappingCountsFn slot31_mapping_counts_fn = nullptr; bool slot31_runs(); bool copy_page_mappings(std::uint32_t count, const PageBatch* batches, std::uintptr_t pool, std::uint32_t pool_pages, std::uint32_t flags); diff --git a/runtime/src/arena_backing.h b/runtime/src/arena_backing.h new file mode 100644 index 0000000000..efc8309a03 --- /dev/null +++ b/runtime/src/arena_backing.h @@ -0,0 +1,398 @@ +#pragma once +// The GPU address arena's memory (docs/d3d12_vulkan.md section 3.3, "Backing blocks"): which arena offsets have +// memory behind them, where the CPU reaches it, and when it is bound and unbound. +// +// With sparse binding the arena is a sparse VkBuffer that reserves the address range only. Its memory comes in +// backing units: a unit is one VkDeviceMemory, mapped once, bound over one or more whole blocks of the arena. A unit +// of one block holds any number of allocations no larger than a block; an allocation larger than a block gets a +// unit of its own, sized to whole blocks. No allocation crosses a unit, so every allocation is one contiguous run +// of one mapping, and the CPU reaches it through host(): an offset resolves to its unit through the block table in +// constant time. +// +// Without sparse binding (or when the sparse address space is smaller than the arena) there is one permanent unit +// over the whole arena: the arena's one allocation, as before. Every caller goes through the same accessors. +// +// Lifetime of a unit: +// - bound when the first allocation needs a block it covers (acquire), before the allocation is handed out; +// - when its last allocation is released it becomes pending, with the retire ticket that every submission which +// could still name it is at or below (the caller passes the submitted ticket + 1, as defer_destroy does); +// - an allocation that lands in a pending unit's block revives it (no rebinding); +// - reclaim(completed) unbinds pending units whose ticket the GPU has passed, then frees their memory. A unit's +// table entries are cleared under the exclusive lock before its memory is freed, so with_host() and +// offset_of() never see freed memory. +// +// Threading: acquire, release, reclaim and keep_out run under the device's arena mutex. host() takes no lock: it is +// for an offset inside an allocation the caller holds, whose unit cannot be freed while the allocation lives. +// with_host() and offset_of() take the shared lock, for callers that name an offset or a pointer they do not own. +// +// The class makes no Vulkan call itself: the device (or a test) passes the hooks that allocate, bind and free. + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace leonida { + +// Chosen from the arena's measured use (a world run: about 5,000 live allocations averaging 160 KiB, 790 MiB live +// over a 990 MiB peak end) and the device: a multiple of the 64 KiB sparse page, few enough units that a 4 GiB arena +// stays within the 4,096 memory objects some Windows drivers allow (2,048 at most, about 500 at that peak), and the +// size of amdgpu's large page. +constexpr VkDeviceSize kArenaBlockBytes = VkDeviceSize(2) << 20; + +// The queue the arena binds on: one nothing else submits to, so a bind (and the wait for it) never sits behind a +// submission that waits for a fence the CPU signals later. A family with the sparse binding bit and a queue to spare, +// a sparse-only family first (RADV has one). `used[f]` is how many queues of family f the device already takes; +// `cap` the most it may take of one. No family: {UINT32_MAX, 0}, and the arena stays one allocation. +struct ArenaBindQueue { + std::uint32_t family = UINT32_MAX; + std::uint32_t index = 0; +}; +inline ArenaBindQueue pick_arena_bind_queue(const VkQueueFamilyProperties* families, std::uint32_t count, + const std::uint32_t* used, std::uint32_t cap) { + constexpr VkQueueFlags work = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT | VK_QUEUE_TRANSFER_BIT; + for (const bool sparse_only : {true, false}) + for (std::uint32_t f = 0; f < count; ++f) { + const VkQueueFlags flags = families[f].queueFlags; + if (!(flags & VK_QUEUE_SPARSE_BINDING_BIT) || (sparse_only && (flags & work))) continue; + if (used[f] >= families[f].queueCount || used[f] >= cap) continue; + return {f, used[f]}; + } + return {}; +} + +struct ArenaBackingHooks { + // A unit's memory, mapped: false when there is none (the allocation is refused). + std::function make; + // Frees a unit's memory (which unmaps it). Called only after the unit is unbound. + std::function destroy; + // Binds (memory set) or unbinds (memory null) these ranges of the arena buffer, and returns once the binds have + // completed. False when the bind failed. + std::function bind; +}; + +class ArenaBacking { +public: + struct Location { + VkDeviceMemory memory = VK_NULL_HANDLE; + VkDeviceSize memory_offset = 0; // the offset's place in `memory` + std::uint8_t* host = nullptr; + }; + struct Stats { + VkDeviceSize bound = 0, peak_bound = 0; + std::uint64_t units = 0, pending = 0, binds = 0, unbinds = 0, bind_failures = 0; + }; + + ArenaBacking() = default; + ArenaBacking(const ArenaBacking&) = delete; + ArenaBacking& operator=(const ArenaBacking&) = delete; + ~ArenaBacking() { clear(); } + + // One permanent unit over [0, size): the arena's single allocation (no sparse binding). `memory` stays the + // caller's to free. + void init_fixed(VkDeviceSize size, VkDeviceMemory memory, std::uint8_t* host) { + clear(); + size_ = size; + block_ = size; + shift_ = 63; // every offset below 2^63 is block 0 + slots_ = std::make_unique[]>(1); + auto* unit = new Unit{0, size, memory, host, 0, 0, false, true, false}; + slots_[0].store(unit, std::memory_order_release); + units_by_host_[reinterpret_cast(host)] = unit; + stats_.bound = stats_.peak_bound = size; + stats_.units = 1; + } + + // A sparse arena of `size` bytes in blocks of `block` (a power of two). Nothing is bound yet. + bool init_sparse(VkDeviceSize size, VkDeviceSize block, ArenaBackingHooks hooks) { + clear(); + if (!size || !block || (block & (block - 1)) || !hooks.make || !hooks.destroy || !hooks.bind) return false; + size_ = size; + block_ = block; + shift_ = 0; + while ((VkDeviceSize(1) << shift_) < block) ++shift_; + count_ = std::size_t((size + block - 1) >> shift_); + slots_ = std::make_unique[]>(count_); + for (std::size_t i = 0; i < count_; ++i) slots_[i].store(nullptr, std::memory_order_relaxed); + hooks_ = std::move(hooks); + sparse_ = true; + return true; + } + + bool ready() const { return size_ != 0; } + bool sparse() const { return sparse_; } + VkDeviceSize size() const { return size_; } + VkDeviceSize block() const { return block_; } + Stats stats() const { return stats_; } // arena mutex held + + // The bytes an allocation of `bytes` takes in the free-block map: larger than a block, it is rounded up to whole + // blocks, so no other allocation shares its unit. + VkDeviceSize footprint(VkDeviceSize bytes) const { + if (!sparse_ || bytes <= block_) return bytes; + return (bytes + block_ - 1) & ~(block_ - 1); + } + // The alignment an allocation of `bytes` needs: a block's for one larger than a block. + VkDeviceSize alignment(VkDeviceSize bytes, VkDeviceSize alignment) const { + return sparse_ && bytes > block_ ? std::max(alignment, block_) : alignment; + } + + // For ArenaBlocks::allocate's keep-out: the end of a range [lo, hi) may not take, or 0. An allocation no larger + // than a block may not cross a block boundary, nor share a block with a pending unit of several blocks (it would + // keep all of them bound). A larger one (block-aligned, whole blocks) may not cover a block that still has a unit. + // Arena mutex held. + std::uint64_t keep_out(std::uint64_t lo, std::uint64_t hi) const { + if (!sparse_ || hi <= lo) return 0; + const std::size_t first = std::size_t(lo >> shift_), last = std::size_t((hi - 1) >> shift_); + if (hi - lo <= block_) { + if (first != last) return VkDeviceSize(last) << shift_; // move up to the next block + const Unit* unit = slots_[first].load(std::memory_order_relaxed); + if (unit && unit->pending && unit->bytes > block_) return unit->base + unit->bytes; + return 0; + } + for (std::size_t i = last + 1; i-- > first;) + if (const Unit* unit = slots_[i].load(std::memory_order_relaxed)) return unit->base + unit->bytes; + return 0; + } + + // Whether [offset, offset + bytes) can be acquired as placed (allocate_at): inside one unit that exists, or over + // blocks that have none. Arena mutex held. + bool placeable(std::uint64_t offset, std::uint64_t bytes) const { + if (!sparse_) return true; + if (!bytes || offset >= size_ || bytes > size_ - offset) return false; + const std::size_t first = std::size_t(offset >> shift_), last = std::size_t((offset + bytes - 1) >> shift_); + const Unit* unit = slots_[first].load(std::memory_order_relaxed); + if (unit) return offset + bytes <= unit->base + unit->bytes; + for (std::size_t i = first; i <= last; ++i) + if (slots_[i].load(std::memory_order_relaxed)) return false; + return true; + } + + // Memory behind [offset, offset + bytes), bound before this returns. The range was just taken from the free-block + // map under keep_out() (or checked with placeable()). False when no memory could be made or bound: the caller + // gives the range back. `permanent`: never released (the reserved head of the arena). Arena mutex held. + bool acquire(std::uint64_t offset, std::uint64_t bytes, bool permanent = false) { + if (!sparse_) return true; + if (!bytes || offset >= size_ || bytes > size_ - offset) return false; + const std::size_t first = std::size_t(offset >> shift_), last = std::size_t((offset + bytes - 1) >> shift_); + if (Unit* unit = slots_[first].load(std::memory_order_relaxed)) { + if (offset + bytes > unit->base + unit->bytes) return false; // would cross its unit + if (unit->pending) revive(unit); + ++unit->live; + unit->permanent = unit->permanent || permanent; + return true; + } + for (std::size_t i = first; i <= last; ++i) + if (slots_[i].load(std::memory_order_relaxed)) return false; + const VkDeviceSize base = VkDeviceSize(first) << shift_; + const VkDeviceSize unit_bytes = std::min(VkDeviceSize(last - first + 1) << shift_, size_ - base); + VkDeviceMemory memory = VK_NULL_HANDLE; + std::uint8_t* host = nullptr; + if (!hooks_.make(unit_bytes, memory, host) || !memory || !host) { + ++stats_.bind_failures; + return false; + } + const VkSparseMemoryBind bind{base, unit_bytes, memory, 0, 0}; + if (!hooks_.bind(&bind, 1)) { + hooks_.destroy(memory); + ++stats_.bind_failures; + return false; + } + ++stats_.binds; + auto* unit = new Unit{base, unit_bytes, memory, host, 1, 0, false, permanent, false}; + { + std::unique_lock lock(table_mutex_); + for (std::size_t i = first; i <= last; ++i) slots_[i].store(unit, std::memory_order_release); + units_by_host_[reinterpret_cast(host)] = unit; + } + stats_.bound += unit_bytes; + stats_.peak_bound = std::max(stats_.peak_bound, stats_.bound); + ++stats_.units; + return true; + } + + // The allocation at [offset, offset + bytes) is gone. When it was its unit's last, the unit is pending until + // `ticket` has retired (reclaim). Arena mutex held. + void release(std::uint64_t offset, std::uint64_t bytes, std::uint64_t ticket) { + if (!sparse_ || !bytes || offset >= size_) return; + Unit* unit = slots_[std::size_t(offset >> shift_)].load(std::memory_order_relaxed); + if (!unit || !unit->live) return; + if (--unit->live || unit->permanent) return; + unit->pending = true; + unit->ticket = ticket; + if (!unit->listed) { + unit->listed = true; + pending_.push_back(unit); + } + ++stats_.pending; + } + + bool has_pending() const { return stats_.pending != 0; } // arena mutex held + + // Unbinds and frees every pending unit whose ticket `completed` has reached; the rest stay pending. Returns the + // bytes unbound. Arena mutex held. + VkDeviceSize reclaim(std::uint64_t completed) { + if (!sparse_ || pending_.empty()) return 0; + std::vector retired; + std::vector unbinds; + for (auto it = pending_.begin(); it != pending_.end();) { + Unit* unit = *it; + if (!unit->pending) { // revived since + unit->listed = false; + it = pending_.erase(it); + continue; + } + if (unit->ticket > completed) { + ++it; + continue; + } + retired.push_back(unit); + unbinds.push_back({unit->base, unit->bytes, VK_NULL_HANDLE, 0, 0}); + it = pending_.erase(it); + } + if (retired.empty()) return 0; + // The GPU has passed every submission that could name these units: unbind them, then let them go. + if (!hooks_.bind(unbinds.data(), std::uint32_t(unbinds.size()))) { + ++stats_.bind_failures; // keep them bound and pending; the next reclaim tries again + pending_.insert(pending_.end(), retired.begin(), retired.end()); + return 0; + } + ++stats_.unbinds; + VkDeviceSize freed = 0; + { + std::unique_lock lock(table_mutex_); + for (Unit* unit : retired) { + const std::size_t first = std::size_t(unit->base >> shift_); + const std::size_t last = std::size_t((unit->base + unit->bytes - 1) >> shift_); + for (std::size_t i = first; i <= last; ++i) slots_[i].store(nullptr, std::memory_order_release); + units_by_host_.erase(reinterpret_cast(unit->host)); + } + } + for (Unit* unit : retired) { + hooks_.destroy(unit->memory); + freed += unit->bytes; + stats_.bound -= unit->bytes; + --stats_.units; + --stats_.pending; + delete unit; + } + return freed; + } + + // The CPU address of [offset, offset + bytes), or null when that range has no memory or crosses a unit. No lock: + // for a range inside an allocation the caller holds. Constant time: one table read. + std::uint8_t* host(std::uint64_t offset, std::uint64_t bytes) const { + if (!bytes || offset >= size_ || bytes > size_ - offset) return nullptr; + const Unit* unit = slots_[std::size_t(offset >> shift_)].load(std::memory_order_acquire); + if (!unit || offset + bytes > unit->base + unit->bytes) return nullptr; + return unit->host + (offset - unit->base); + } + + // The bytes from `offset` to the end of the unit that holds it (0: none does). As host(). + VkDeviceSize room(std::uint64_t offset) const { + if (offset >= size_) return 0; + const Unit* unit = slots_[std::size_t(offset >> shift_)].load(std::memory_order_acquire); + return unit && offset >= unit->base ? unit->base + unit->bytes - offset : 0; + } + + // The memory behind [offset, offset + bytes) (a D3D12 heap's tiles bind it to reserved resources). As host(). + bool locate(std::uint64_t offset, std::uint64_t bytes, Location& out) const { + if (!bytes || offset >= size_ || bytes > size_ - offset) return false; + const Unit* unit = slots_[std::size_t(offset >> shift_)].load(std::memory_order_acquire); + if (!unit || offset + bytes > unit->base + unit->bytes) return false; + out = {unit->memory, offset - unit->base, unit->host + (offset - unit->base)}; + return true; + } + + // Calls `f(pointer)` with the CPU address of [offset, offset + bytes) while no reclaim can free it; false (and no + // call) when the range has no memory or crosses a unit. For a caller that names an offset it does not hold. + template + bool with_host(std::uint64_t offset, std::uint64_t bytes, F&& f) const { + std::shared_lock lock(table_mutex_); + std::uint8_t* p = host(offset, bytes); + if (!p) return false; + f(p); + return true; + } + + // The arena offset of the CPU range [p, p + n), if it lies inside one unit's mapping. Shared lock; O(log units). + bool offset_of(const void* p, std::size_t n, std::uint64_t& offset) const { + const auto address = reinterpret_cast(p); + std::shared_lock lock(table_mutex_); + auto it = units_by_host_.upper_bound(address); + if (it == units_by_host_.begin()) return false; + --it; + const Unit* unit = it->second; + const std::uintptr_t begin = reinterpret_cast(unit->host); + if (address - begin > unit->bytes || n > unit->bytes - (address - begin)) return false; + offset = unit->base + (address - begin); + return true; + } + + // Calls `f(base, bytes, host)` for every unit, in offset order, under the shared lock. + template + void for_each_unit(F&& f) const { + std::shared_lock lock(table_mutex_); + std::map order; + for (const auto& [address, unit] : units_by_host_) order.emplace(unit->base, unit); + for (const auto& [base, unit] : order) f(unit->base, unit->bytes, unit->host); + } + + // Frees every unit of a sparse arena (the device is idle: it is being destroyed). A fixed arena's memory stays + // the caller's. + void clear() { + std::vector all; + { + std::unique_lock lock(table_mutex_); + for (const auto& [address, unit] : units_by_host_) all.push_back(unit); + units_by_host_.clear(); + for (std::size_t i = 0; slots_ && i < count_; ++i) slots_[i].store(nullptr, std::memory_order_relaxed); + } + for (Unit* unit : all) { + if (sparse_ && hooks_.destroy) hooks_.destroy(unit->memory); + delete unit; + } + pending_.clear(); + slots_.reset(); + count_ = 1; + size_ = block_ = 0; + sparse_ = false; + stats_ = {}; + } + +private: + struct Unit { + VkDeviceSize base, bytes; + VkDeviceMemory memory; + std::uint8_t* host; + std::uint64_t live; // allocations in it + std::uint64_t ticket; // pending: unbind once this retire ticket is complete + bool pending; + bool permanent; + bool listed; // in pending_ + }; + + void revive(Unit* unit) { + unit->pending = false; // stays in pending_ until the next reclaim drops it + --stats_.pending; + } + + VkDeviceSize size_ = 0, block_ = 0; + unsigned shift_ = 63; + std::size_t count_ = 1; + bool sparse_ = false; + std::unique_ptr[]> slots_; // one per block: the unit over it + mutable std::shared_mutex table_mutex_; // slots_ stores and units_by_host_, against freeing + std::map units_by_host_; // by mapping address, for offset_of + std::vector pending_; + ArenaBackingHooks hooks_; + Stats stats_; +}; + +} // namespace leonida diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h index 8b79c987e9..996e659c49 100644 --- a/runtime/src/command_list.h +++ b/runtime/src/command_list.h @@ -976,6 +976,18 @@ class CommandList { bool close() { if (closed_) return false; closed_ = true; + predication_captures_ = 0; + runs_shaders_ = false; + has_rt_ds_clear_ = false; + for (const Command& command : commands_) { + if (std::holds_alternative(command) || + std::holds_alternative(command)) + has_rt_ds_clear_ = true; + if (const auto* p = std::get_if(&command); p && p->buffer) ++predication_captures_; + if (std::holds_alternative(command) || draw_command(command).state || + std::holds_alternative(command)) + runs_shaders_ = true; + } return true; } @@ -984,12 +996,18 @@ class CommandList { commands_.clear(); active_.clear(); closed_ = false; + predication_captures_ = 0; + runs_shaders_ = false; + has_rt_ds_clear_ = false; stamp_.restamp(); return true; } bool closed() const { return closed_; } std::span commands() const { return commands_; } + std::uint64_t predication_captures() const noexcept { return predication_captures_; } + bool runs_shaders() const noexcept { return runs_shaders_; } + bool has_rt_ds_clear() const noexcept { return has_rt_ds_clear_; } private: static bool valid(const TargetView& target) { return target.resource && target.layer_count; } @@ -1028,6 +1046,9 @@ class CommandList { std::vector commands_; std::vector active_; // queries begun and not yet ended bool closed_ = false; + std::uint64_t predication_captures_ = 0; + bool runs_shaders_ = false; + bool has_rt_ds_clear_ = false; command_list_epochs::Stamp stamp_; // when this recording began: a copy the layer retires waits for it }; diff --git a/runtime/src/console_heap_gpu.h b/runtime/src/console_heap_gpu.h index b3a4c0ba4c..66876084fc 100644 --- a/runtime/src/console_heap_gpu.h +++ b/runtime/src/console_heap_gpu.h @@ -352,7 +352,9 @@ class ConsoleHeapGpu { ConsoleHeapGpu(PFN_vkGetDeviceProcAddr get, VkDevice device, const VkPhysicalDeviceMemoryProperties& memory, std::uint32_t log2_keys = 20) - : get_(get), device_(device), memory_(memory), keys_(log2_keys) {} + : get_(get), device_(device), memory_(memory), keys_(log2_keys) { + load_procs(); + } ~ConsoleHeapGpu() { std::lock_guard lock(mutex_); for (auto& pass : in_flight_) free_buffer(pass.buffer); @@ -365,8 +367,8 @@ class ConsoleHeapGpu { if (t.current) free_buffer(*t.current); } free_buffer(key_table_); - if (pipeline_) fn("vkDestroyPipeline")(device_, pipeline_, nullptr); - if (layout_) fn("vkDestroyPipelineLayout")(device_, layout_, nullptr); + if (pipeline_ && vk_.destroy_pipeline) vk_.destroy_pipeline(device_, pipeline_, nullptr); + if (layout_ && vk_.destroy_pipeline_layout) vk_.destroy_pipeline_layout(device_, layout_, nullptr); } ConsoleHeapGpu(const ConsoleHeapGpu&) = delete; ConsoleHeapGpu& operator=(const ConsoleHeapGpu&) = delete; @@ -551,16 +553,16 @@ class ConsoleHeapGpu { const VkDeviceAddress update_address = base + at * 4; if (!updates.empty()) std::memcpy(words + at, updates.data(), updates.size() * 4); at += updates.size(); - const auto barrier = fn("vkCmdPipelineBarrier"); - const auto dispatch = fn("vkCmdDispatch"); - const auto push = fn("vkCmdPushConstants"); + const auto barrier = vk_.cmd_pipeline_barrier; + const auto dispatch = vk_.cmd_dispatch; + const auto push = vk_.cmd_push_constants; // The copies first (another kind of work in the same prelude), then what reads their destinations may run. if (!copies_.empty()) { std::sort(copies_.begin(), copies_.end(), [](const Copy& a, const Copy& b) { return a.src != b.src ? a.src < b.src : a.dst < b.dst; }); std::vector regions; - const auto copy = fn("vkCmdCopyBuffer"); + const auto copy = vk_.cmd_copy_buffer; for (std::size_t i = 0; i < copies_.size();) { std::size_t j = i; regions.clear(); @@ -587,7 +589,7 @@ class ConsoleHeapGpu { // before it to finish. // The pass may then rewrite a slot an earlier submission still reads, as the CPU path's memcpy into the copy // always could. - fn("vkCmdBindPipeline")(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_); + vk_.cmd_bind_pipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_); Push p{}; const auto address = [&](TableKind kind) { return tables_[kind].current ? tables_[kind].current->address : 0; }; p.ranges = address(range_table); @@ -601,7 +603,7 @@ class ConsoleHeapGpu { p.flags = (signed_offsets_ ? 1u : 0u) | (use_ask_ ? 2u : 0u); p.key_mask = keys_.mask(); if (clear_keys_) { - fn("vkCmdFillBuffer")(cb, key_table_.buffer, 0, VK_WHOLE_SIZE, 0); + vk_.cmd_fill_buffer(cb, key_table_.buffer, 0, VK_WHOLE_SIZE, 0); VkMemoryBarrier filled{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; filled.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; filled.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; @@ -612,7 +614,7 @@ class ConsoleHeapGpu { bool meta_filled = false; for (Heap& h : heaps_) if (h.meta_clear && h.meta.buffer) { - fn("vkCmdFillBuffer")(cb, h.meta.buffer, 0, VK_WHOLE_SIZE, 0); + vk_.cmd_fill_buffer(cb, h.meta.buffer, 0, VK_WHOLE_SIZE, 0); h.meta_clear = false; meta_filled = true; pass.filled.push_back(int(&h - heaps_.data())); @@ -869,9 +871,62 @@ class ConsoleHeapGpu { std::vector pool; }; - template - T fn(const char* name) const { - return reinterpret_cast(get_(device_, name)); + struct VkFns { + PFN_vkCreateBuffer create_buffer = nullptr; + PFN_vkDestroyBuffer destroy_buffer = nullptr; + PFN_vkGetBufferMemoryRequirements get_buffer_memory_requirements = nullptr; + PFN_vkAllocateMemory allocate_memory = nullptr; + PFN_vkFreeMemory free_memory = nullptr; + PFN_vkBindBufferMemory bind_buffer_memory = nullptr; + PFN_vkMapMemory map_memory = nullptr; + PFN_vkGetBufferDeviceAddress get_buffer_device_address = nullptr; + PFN_vkCreateShaderModule create_shader_module = nullptr; + PFN_vkDestroyShaderModule destroy_shader_module = nullptr; + PFN_vkCreatePipelineLayout create_pipeline_layout = nullptr; + PFN_vkDestroyPipelineLayout destroy_pipeline_layout = nullptr; + PFN_vkCreateComputePipelines create_compute_pipelines = nullptr; + PFN_vkDestroyPipeline destroy_pipeline = nullptr; + PFN_vkCmdPipelineBarrier cmd_pipeline_barrier = nullptr; + PFN_vkCmdBindPipeline cmd_bind_pipeline = nullptr; + PFN_vkCmdPushConstants cmd_push_constants = nullptr; + PFN_vkCmdDispatch cmd_dispatch = nullptr; + PFN_vkCmdFillBuffer cmd_fill_buffer = nullptr; + PFN_vkCmdCopyBuffer cmd_copy_buffer = nullptr; + + bool complete() const { + return create_buffer && destroy_buffer && get_buffer_memory_requirements && allocate_memory && + free_memory && bind_buffer_memory && map_memory && get_buffer_device_address && + create_shader_module && destroy_shader_module && create_pipeline_layout && + destroy_pipeline_layout && create_compute_pipelines && destroy_pipeline && cmd_pipeline_barrier && + cmd_bind_pipeline && cmd_push_constants && cmd_dispatch && cmd_fill_buffer && cmd_copy_buffer; + } + }; + + void load_procs() { + if (!get_ || !device_) return; + const auto load = [this](T& out, const char* name) { + out = reinterpret_cast(get_(device_, name)); + }; + load(vk_.create_buffer, "vkCreateBuffer"); + load(vk_.destroy_buffer, "vkDestroyBuffer"); + load(vk_.get_buffer_memory_requirements, "vkGetBufferMemoryRequirements"); + load(vk_.allocate_memory, "vkAllocateMemory"); + load(vk_.free_memory, "vkFreeMemory"); + load(vk_.bind_buffer_memory, "vkBindBufferMemory"); + load(vk_.map_memory, "vkMapMemory"); + load(vk_.get_buffer_device_address, "vkGetBufferDeviceAddress"); + load(vk_.create_shader_module, "vkCreateShaderModule"); + load(vk_.destroy_shader_module, "vkDestroyShaderModule"); + load(vk_.create_pipeline_layout, "vkCreatePipelineLayout"); + load(vk_.destroy_pipeline_layout, "vkDestroyPipelineLayout"); + load(vk_.create_compute_pipelines, "vkCreateComputePipelines"); + load(vk_.destroy_pipeline, "vkDestroyPipeline"); + load(vk_.cmd_pipeline_barrier, "vkCmdPipelineBarrier"); + load(vk_.cmd_bind_pipeline, "vkCmdBindPipeline"); + load(vk_.cmd_push_constants, "vkCmdPushConstants"); + load(vk_.cmd_dispatch, "vkCmdDispatch"); + load(vk_.cmd_fill_buffer, "vkCmdFillBuffer"); + load(vk_.cmd_copy_buffer, "vkCmdCopyBuffer"); } void queue_locked(int heap, std::uint32_t item) { @@ -932,13 +987,16 @@ class ConsoleHeapGpu { bool make_buffer(VkDeviceSize bytes, bool host, Buffer& out, bool host_device_local = false) { out = {}; + if (!vk_.create_buffer || !vk_.get_buffer_memory_requirements || !vk_.allocate_memory || + !vk_.bind_buffer_memory || (host && !vk_.map_memory) || !vk_.get_buffer_device_address) + return false; VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; info.size = bytes; info.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; - if (fn("vkCreateBuffer")(device_, &info, nullptr, &out.buffer) != VK_SUCCESS) return false; + if (vk_.create_buffer(device_, &info, nullptr, &out.buffer) != VK_SUCCESS) return false; VkMemoryRequirements requirements{}; - fn("vkGetBufferMemoryRequirements")(device_, out.buffer, &requirements); + vk_.get_buffer_memory_requirements(device_, out.buffer, &requirements); const VkMemoryPropertyFlags required = host ? VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT : 0; const VkMemoryPropertyFlags preferred = host ? 0 : VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; @@ -963,22 +1021,21 @@ class ConsoleHeapGpu { } else { order = memory_type_order(memory_, requirements.memoryTypeBits, required, preferred, requirements.size); } - const auto allocate_memory = fn("vkAllocateMemory"); for (const std::uint32_t type : order) { allocate.memoryTypeIndex = type; - if (allocate_memory(device_, &allocate, nullptr, &out.memory) == VK_SUCCESS) break; + if (vk_.allocate_memory(device_, &allocate, nullptr, &out.memory) == VK_SUCCESS) break; out.memory = VK_NULL_HANDLE; } if (!out.memory || - fn("vkBindBufferMemory")(device_, out.buffer, out.memory, 0) != VK_SUCCESS || - (host && fn("vkMapMemory")(device_, out.memory, 0, VK_WHOLE_SIZE, 0, &out.mapped) != + vk_.bind_buffer_memory(device_, out.buffer, out.memory, 0) != VK_SUCCESS || + (host && vk_.map_memory(device_, out.memory, 0, VK_WHOLE_SIZE, 0, &out.mapped) != VK_SUCCESS)) { free_buffer(out); return false; } VkBufferDeviceAddressInfo address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; address.buffer = out.buffer; - out.address = fn("vkGetBufferDeviceAddress")(device_, &address); + out.address = vk_.get_buffer_device_address(device_, &address); out.size = bytes; if (!out.address) { free_buffer(out); @@ -987,46 +1044,37 @@ class ConsoleHeapGpu { return true; } void free_buffer(Buffer& b) { - if (b.buffer) fn("vkDestroyBuffer")(device_, b.buffer, nullptr); - if (b.memory) fn("vkFreeMemory")(device_, b.memory, nullptr); // unmaps + if (b.buffer && vk_.destroy_buffer) vk_.destroy_buffer(device_, b.buffer, nullptr); + if (b.memory && vk_.free_memory) vk_.free_memory(device_, b.memory, nullptr); // unmaps b = {}; } bool make_pipeline() { - for (const char* name : - {"vkCreateBuffer", "vkDestroyBuffer", "vkGetBufferMemoryRequirements", "vkAllocateMemory", "vkFreeMemory", - "vkBindBufferMemory", "vkMapMemory", "vkGetBufferDeviceAddress", "vkCreateShaderModule", - "vkDestroyShaderModule", "vkCreatePipelineLayout", "vkDestroyPipelineLayout", "vkCreateComputePipelines", - "vkDestroyPipeline", "vkCmdPipelineBarrier", "vkCmdBindPipeline", "vkCmdPushConstants", "vkCmdDispatch", - "vkCmdFillBuffer", "vkCmdCopyBuffer"}) - if (!get_(device_, name)) return false; + if (!vk_.complete()) return false; VkShaderModule module = VK_NULL_HANDLE; VkShaderModuleCreateInfo shader{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; shader.codeSize = sizeof(console_heap_fix_spirv); shader.pCode = console_heap_fix_spirv; const aftermath::ShaderName aftermath_name("(runtime) console_heap_fix"); - bool ok = - fn("vkCreateShaderModule")(device_, &shader, nullptr, &module) == VK_SUCCESS; + bool ok = vk_.create_shader_module(device_, &shader, nullptr, &module) == VK_SUCCESS; const VkPushConstantRange range{VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(Push)}; VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; layout_info.pushConstantRangeCount = 1; layout_info.pPushConstantRanges = ⦥ VkPipelineLayout layout = VK_NULL_HANDLE; VkPipeline pipeline = VK_NULL_HANDLE; - ok = ok && fn("vkCreatePipelineLayout")(device_, &layout_info, nullptr, &layout) == - VK_SUCCESS; + ok = ok && vk_.create_pipeline_layout(device_, &layout_info, nullptr, &layout) == VK_SUCCESS; VkComputePipelineCreateInfo info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; info.stage.module = module; info.stage.pName = "main"; info.layout = layout; - ok = ok && fn("vkCreateComputePipelines")(device_, VK_NULL_HANDLE, 1, &info, - nullptr, &pipeline) == VK_SUCCESS; - if (module) fn("vkDestroyShaderModule")(device_, module, nullptr); + ok = ok && vk_.create_compute_pipelines(device_, VK_NULL_HANDLE, 1, &info, nullptr, &pipeline) == VK_SUCCESS; + if (module) vk_.destroy_shader_module(device_, module, nullptr); if (!ok) { - if (pipeline) fn("vkDestroyPipeline")(device_, pipeline, nullptr); - if (layout) fn("vkDestroyPipelineLayout")(device_, layout, nullptr); + if (pipeline) vk_.destroy_pipeline(device_, pipeline, nullptr); + if (layout) vk_.destroy_pipeline_layout(device_, layout, nullptr); return false; } layout_ = layout; @@ -1036,6 +1084,7 @@ class ConsoleHeapGpu { PFN_vkGetDeviceProcAddr get_; VkDevice device_; + VkFns vk_{}; VkPhysicalDeviceMemoryProperties memory_; std::mutex mutex_; VkPipelineLayout layout_ = VK_NULL_HANDLE; diff --git a/runtime/src/console_heap_slot_records.h b/runtime/src/console_heap_slot_records.h index 4ab3c3b9d9..d66732fefd 100644 --- a/runtime/src/console_heap_slot_records.h +++ b/runtime/src/console_heap_slot_records.h @@ -1,21 +1,43 @@ #pragma once -// What each buffer V# of a console resource heap's GPU copy resolved to (docs/d3d12_vulkan.md section 3.4), kept in -// host RAM so that a change of the address space re-fixes exactly the slots it touches. +// What each buffer V# and title-written T# of a console resource heap's GPU copy resolved to (docs/d3d12_vulkan.md +// section 3.4), kept in host RAM so that a change of the address space re-fixes exactly the slots it touches. // -// A slot of the copy is the title's descriptor with its V# bases rewritten (DeviceState::fix_console_slot). What a -// base became depends on things that change after the slot was written: a buffer or window released, an alias range -// removed, a geometry copy retired, or (for a base nothing backed yet) a buffer, alias or title memory added. Without -// a record of which slot resolved into which range, a change could only be applied by walking every live slot. Here -// each V# half (the buffer V# and the UAV counter V# of a slot) records: -// - base and span: the bytes the title's V# names, [base, base + span) (the base is the V#'s 48 bits); -// - target: the device address its GPU copy names, [target, target + span); for a half that resolved to nothing, -// the device address of a copy that was found but refused (not backed yet), or 0; -// - state: resolved, waiting (written with no base and no records until something backs it) or none. -// Two indexes find the halves a change touches: by base ("source") and by target. Each holds a half once, under the -// power-of-two class of its span and the granule of its start (a granule is at least 64 KiB and at least the class), -// so a range [lo, hi) is answered by visiting, per class in use, the granules from lo - 2^class to hi: the cost is the -// halves near the range, never the heap. An entry is checked against the record when visited (a half that moved -// leaves a stale entry behind; a bucket drops its stale entries whenever it has doubled since it was last cleaned). +// A slot of the copy is the title's descriptor with its V# bases rewritten and its T# bound (DeviceState:: +// fix_console_slot). What a base became depends on things that change after the slot was written: a buffer or window +// released, an alias range removed, a geometry copy retired, a texture registered, replaced or gone at an address, or +// (for a base nothing backed yet) a buffer, alias or title memory added. Without a record of which slot resolved into +// which range, a change could only be applied by walking every live slot. Here each V# half (the buffer V# and the +// UAV counter V# of a slot) records: +// - source: the bytes the title's V# names, [base, base + span) (the base is the V#'s 48 bits); +// - target: the device addresses its GPU copy names, [target, target + span); for a half that resolved to nothing, +// those of a copy that was found but refused (not backed yet), or none; +// - state: resolved, waiting (written with no base and no records until something backs it), waiting_room (as +// waiting, and its geometry copy was refused for lack of room) or none. +// The T# of a slot has a record too (set_texture), in the first half: the address it names (its base), and whether a +// texture bound it or it waits for one (texture_waiting_room: refused because its bindless array was full). Title- +// written T#s are looked up by their exact base address (bind_title_image), so a third index holds them by that +// address alone. +// +// The three indexes (V# source, V# target, T# address) hold the records by their exact range (a T#'s is its address +// and the byte after it). The records that name the same range share one group (the title writes the same descriptor +// into thousands of slots), which keeps them in two lists, settled (resolved, bound) and waiting, with each record's +// place in its list, so a record moves or goes in O(1) and no list holds a stale entry. The groups are ordered by +// start, separately for each power-of-two class of their length: a group of class c (length at most 2^c) overlaps +// [lo, hi) only if it starts in (lo - 2^c, hi), so a query searches each class in use once and walks only the groups +// that start there. Records waiting for room are also kept in one list per kind (V# halves, T#s), with their place, +// which a change saying room was made visits whole. +// +// The bound: a change visits exactly the records it concerns - a release or removal the V# halves whose recorded +// range overlaps it, an addition the waiting ones whose range starts inside it (a V# resolves only through a range +// that holds its base or its refused target, so an addition that does not hold the start cannot settle it; the +// groups with waiting records are kept by start a second time for this), a texture gone the T#s naming its address, +// a texture added the waiting ones, room made the records waiting for that room - and each of them once an index a +// touched() call (a V# half at most twice: by source and by target), however many of the call's changes name it. +// looked_at() counts those and nothing else. The groups walked to +// find them are the ones visited plus, for a removal, per class, those that start less than 2^c before the change and +// end before it: each costs one comparison, never a slot. Memory: 32 bytes a half (64 a slot, +// allocated with calloc, so pages of slots never written are never touched), and per distinct range a group (two lists +// of 4 bytes a record, a hash entry and an ordered-map entry). // Portable, standard library only: console_heap_slot_records_test exercises it without a GPU. #include #include @@ -23,6 +45,7 @@ #include #include #include +#include #include #include #include @@ -32,10 +55,14 @@ namespace leonida { // One change since the last submission, as a range; hi is exclusive and greater than lo. struct SlotChange { enum Kind : std::uint8_t { - target_gone, // device addresses: a backing released, a copy's block destroyed, an alias range's copy gone - source_gone, // V# bases: an alias range removed or replaced, or a copy that answered for it gone - target_added, // device addresses: a backing added (a refused alias target may be backed now) - source_added, // V# bases: an alias range or title memory added, or a backing added at those arena offsets + target_gone, // device addresses: a backing released, a copy's block destroyed, an alias range's copy gone + source_gone, // V# bases: an alias range removed or replaced, or a copy that answered for it gone + target_added, // device addresses: a backing added (a refused alias target may be backed now) + source_added, // V# bases: an alias range or title memory added, or a backing added at those arena offsets + texture_gone, // a T# address (lo; hi = lo + 1): the texture registered there went or was replaced + texture_added, // a T# address: a texture registered or replaced there, or its image published + geometry_room, // geometry copies were freed: halves refused a copy for lack of room may get one (no range) + texture_room, // bindless image entries were freed: T#s refused for a full array may bind (no range) }; Kind kind; std::uint64_t lo, hi; @@ -43,185 +70,487 @@ struct SlotChange { class ConsoleHeapSlotRecords { public: - enum State : std::uint8_t { none = 0, resolved = 1, waiting = 2 }; + // V# halves: resolved, waiting (for a backing over its base or target), waiting_room (and for geometry room). + // T#s (the first half): texture_bound, texture_waiting (for a texture at its address), texture_waiting_room (and + // for room in its bindless array). + enum State : std::uint8_t { + none = 0, + resolved = 1, + waiting = 2, + waiting_room = 3, + texture_bound = 4, + texture_waiting = 5, + texture_waiting_room = 6, + }; + static bool is_vsharp(State s) { return s >= resolved && s <= waiting_room; } + static bool is_texture(State s) { return s >= texture_bound; } + static bool is_waiting(State s) { return s == waiting || s == waiting_room || s >= texture_waiting; } + + // Optional observer notified ONLY on kTexture kSettled 0 <-> 1 transitions per address for this heap + // (`bound == true` when the first slot in this heap binds `address`, `bound == false` when the last leaves, + // including across reset() and destruction). + using TextureLiveCallback = void (*)(void* user, std::uint64_t address, bool bound); + + ConsoleHeapSlotRecords() = default; + ~ConsoleHeapSlotRecords() { notify_all_textures_unbound(); } + ConsoleHeapSlotRecords(const ConsoleHeapSlotRecords&) = delete; + ConsoleHeapSlotRecords& operator=(const ConsoleHeapSlotRecords&) = delete; + ConsoleHeapSlotRecords(ConsoleHeapSlotRecords&& other) noexcept + : slots_(other.slots_), + halves_(std::move(other.halves_)), + indexes_(std::move(other.indexes_)), + room_(std::move(other.room_)), + groups_(std::move(other.groups_)), + free_groups_(std::move(other.free_groups_)), + recorded_(other.recorded_), + waiting_(other.waiting_), + textures_count_(other.textures_count_), + textures_waiting_(other.textures_waiting_), + looked_at_(other.looked_at_), + groups_looked_at_(other.groups_looked_at_), + epoch_(other.epoch_), + texture_live_cb_(other.texture_live_cb_), + texture_live_user_(other.texture_live_user_) { + other.slots_ = 0; + other.texture_live_cb_ = nullptr; + other.texture_live_user_ = nullptr; + } + ConsoleHeapSlotRecords& operator=(ConsoleHeapSlotRecords&& other) noexcept { + if (this == &other) return *this; + notify_all_textures_unbound(); + slots_ = other.slots_; + halves_ = std::move(other.halves_); + indexes_ = std::move(other.indexes_); + room_ = std::move(other.room_); + groups_ = std::move(other.groups_); + free_groups_ = std::move(other.free_groups_); + recorded_ = other.recorded_; + waiting_ = other.waiting_; + textures_count_ = other.textures_count_; + textures_waiting_ = other.textures_waiting_; + looked_at_ = other.looked_at_; + groups_looked_at_ = other.groups_looked_at_; + epoch_ = other.epoch_; + texture_live_cb_ = other.texture_live_cb_; + texture_live_user_ = other.texture_live_user_; + other.slots_ = 0; + other.texture_live_cb_ = nullptr; + other.texture_live_user_ = nullptr; + return *this; + } + + void set_texture_live_callback(TextureLiveCallback cb, void* user) noexcept { + texture_live_cb_ = cb; + texture_live_user_ = user; + } void reset(std::size_t slots) { + notify_all_textures_unbound(); slots_ = slots; // calloc: the pages of slots never written are never touched (the retail heap uses a tenth of its slots). halves_.reset(slots ? static_cast(std::calloc(slots * 2, sizeof(Half))) : nullptr); if (slots && !halves_) slots_ = 0; for (auto& index : indexes_) index = Index{}; - recorded_ = waiting_ = 0; - looked_at_ = 0; + for (auto& room : room_) room.clear(); + groups_.clear(); + free_groups_.clear(); + recorded_ = waiting_ = textures_count_ = textures_waiting_ = 0; + looked_at_ = groups_looked_at_ = 0; } std::size_t slots() const { return slots_; } - std::size_t recorded() const { return recorded_; } // halves in state resolved or waiting - std::size_t waiting_count() const { return waiting_; } // halves in state waiting - std::uint64_t looked_at() const { return looked_at_; } // index entries visited by touched(), all calls + std::size_t recorded() const { return recorded_; } // V# halves resolved or waiting + std::size_t waiting_count() const { return waiting_; } // V# halves waiting (for a backing or room) + std::size_t textures() const { return textures_count_; } // T# records, bound or waiting + std::size_t textures_waiting() const { return textures_waiting_; } // T#s waiting for a texture or room + std::size_t ranges() const { return groups_.size() - free_groups_.size(); } // distinct ranges, all indexes + std::uint64_t looked_at() const { return looked_at_; } // records visited by touched(), all calls + std::uint64_t ranges_looked_at() const { return groups_looked_at_; } // groups compared by touched(), all calls // Half `half` (0: the buffer V#, 1: the UAV counter V#) of `slot` now names [base, base + span) and resolved as - // `state` says, its copy at `target` (see above). span 0 counts as 1. + // `state` says (none or a V# state), its copy at `target` (0: none; see above). span 0 counts as 1. `geometry`: + // its resolution asked for a geometry copy (fix_vsharp's copy_geometry), which answer() tells apart. void set(std::size_t slot, unsigned half, State state, std::uint64_t base, std::uint64_t span, - std::uint64_t target) { - if (slot >= slots_ || half > 1) return; - if (state == none) base = span = target = 0; + std::uint64_t target, bool geometry = false) { + if (slot >= slots_ || half > 1 || is_texture(state)) return; + const std::uint32_t key = std::uint32_t(slot * 2 + half); + if (state == none) { + if (halves_[key].state == none) return; + drop(key); + return; + } if (!span) span = 1; - if (span > kMaxSpan) span = kMaxSpan; - const std::size_t key = slot * 2 + half; - Half& h = halves_[key]; - const Half old = h; - count(old.state(), -1); - h.base = base; - h.target = target; - h.span_state = span | (std::uint64_t(state) << 56); - count(state, +1); - if (state == none) return; // entries left behind are stale now - const auto add = [&](int which, std::uint64_t start, std::uint64_t old_start) { - const unsigned c = span_class(span); - const std::uint64_t granule = start >> granule_shift(c); - // Unchanged key: the entry already there stands for it. - if (old.state() != none && (which == kSource || old.target) && span_class(old.span()) == c && - (old_start >> granule_shift(c)) == granule) - return; - push(which, c, granule, std::uint32_t(key)); - }; - add(kSource, base, old.base); - if (target) add(kTarget, target, old.target); + const Range ranges[2] = {range(base, span), target ? range(target, span) : Range{}}; + place(key, state, geometry ? kGeometry : 0, base, ranges); + } + + // The T# of `slot` names `address` (its base) and is bound or waits as `state` (a T# state) says. The slot's + // second half is no V# then: its record goes. + void set_texture(std::size_t slot, State state, std::uint64_t address) { + if (slot >= slots_ || !is_texture(state)) return; + const std::uint32_t k1 = std::uint32_t(slot * 2 + 1); + if (halves_[k1].state != none) drop(k1); + const Range ranges[2] = {range(address, 1), Range{}}; + place(std::uint32_t(slot * 2), state, 0, address, ranges); + } + + // What a V# naming [base, base + span) resolves to while another half of the same range has a record made the + // same way (`geometry`: both asked for a geometry copy, or neither): the same answer, `state` and `target` as that + // half has them. Sound because a record is fixed again by every change that could alter its answer (touched): a + // resolved one by every release or removal of its range or its copy, a waiting one also by every addition that + // could back it. While it is current, the same lookups give the same answer. The caller applies the changes noted + // since first (they may not be on a record yet). A waiting answer is also taken from a half that asked for a copy + // when this one does not (it looked further and found nothing). + bool answer(std::uint64_t base, std::uint64_t span, bool geometry, State& state, std::uint64_t& target) { + if (!span) span = 1; + const auto it = indexes_[kSource].by_range.find(range(base, span)); + if (it == indexes_[kSource].by_range.end()) return false; + const Group& g = groups_[it->second]; + const int geo = geometry ? 1 : 0; + const std::vector* list = + !g.keys[kSettled + geo].empty() ? &g.keys[kSettled + geo] + : !g.keys[kWaiting + 1].empty() ? &g.keys[kWaiting + 1] + : !geometry && !g.keys[kWaiting].empty() ? &g.keys[kWaiting] : nullptr; + if (!list) return false; + const Half& h = halves_[list->front()]; + // One that asks for no copy waits for a backing only, not for geometry room. + state = !geometry && h.state == waiting_room ? waiting : State(h.state); + target = h.group[kTarget] ? groups_[h.group[kTarget] - 1].start : 0; + return true; } void clear(std::size_t slot) { - set(slot, 0, none, 0, 0, 0); - set(slot, 1, none, 0, 0, 0); + if (slot >= slots_) return; + const std::uint32_t k0 = std::uint32_t(slot * 2); + if (halves_[k0].state != none) drop(k0); + if (halves_[k0 + 1].state != none) drop(k0 + 1); } void clear_range(std::size_t first, std::size_t end) { end = (std::min)(end, slots_); for (std::size_t slot = first; slot < end; ++slot) for (unsigned half = 0; half < 2; ++half) - if (halves_[slot * 2 + half].state() != none) set(slot, half, none, 0, 0, 0); + if (halves_[slot * 2 + half].state != none) drop(std::uint32_t(slot * 2 + half)); } + std::uint64_t base(std::size_t slot, unsigned half) const { + return slot < slots_ && half < 2 ? halves_[slot * 2 + half].base : 0; + } State state(std::size_t slot, unsigned half) const { - return slot < slots_ && half < 2 ? halves_[slot * 2 + half].state() : none; + return slot < slots_ && half < 2 ? State(halves_[slot * 2 + half].state) : none; } std::uint64_t target(std::size_t slot, unsigned half) const { - return slot < slots_ && half < 2 ? halves_[slot * 2 + half].target : 0; + if (slot >= slots_ || half > 1) return 0; + const Half& h = halves_[slot * 2 + half]; + return is_vsharp(State(h.state)) && h.group[1] ? groups_[h.group[1] - 1].start : 0; } // The slots `changes` touch, each once, ascending, appended to `out` (cleared first): - // target_gone: halves whose [target, target + span) overlaps the range (whatever their state); - // source_gone: halves whose [base, base + span) overlaps it; - // target_added, source_added: the same, waiting halves only (a resolved one stays valid until something goes). + // target_gone: V# halves whose [target, target + span) overlaps the range (whatever their state); + // source_gone: V# halves whose [base, base + span) overlaps it; + // target_added, source_added: the same, waiting halves only (a resolved one stays valid until something goes); + // texture_gone: T#s naming the address lo, bound or waiting; texture_added: those waiting; + // geometry_room: V# halves waiting for room; texture_room: T#s waiting for room (each list once a call). + // An addition finds the waiting records whose range starts inside it: a V# resolves only through a backing, + // alias range, copy or title memory that holds its base (or a backing that holds its refused target), so one + // that does not hold the start cannot settle it. A removal finds every record whose range overlaps it. + // A record is looked at once an index a call at most, however many of the changes name it. void touched(const SlotChange* changes, std::size_t count, std::vector& out) { out.clear(); + if (!++epoch_) { // after 2^32 calls: no group may look visited + for (auto& g : groups_) + for (auto& seen : g.seen) seen = 0; + epoch_ = 1; + } + bool room[2] = {}; for (std::size_t i = 0; i < count; ++i) { const SlotChange& change = changes[i]; + switch (change.kind) { + case SlotChange::geometry_room: room[0] = true; continue; + case SlotChange::texture_room: room[1] = true; continue; + case SlotChange::texture_gone: + if (change.lo != UINT64_MAX) find(kTexture, change.lo, change.lo + 1, out); + continue; + case SlotChange::texture_added: + if (change.lo != UINT64_MAX) find_waiting(kTexture, change.lo, change.lo + 1, out); + continue; + default: break; + } if (change.hi <= change.lo) continue; - const bool target = change.kind == SlotChange::target_gone || change.kind == SlotChange::target_added; - const bool waiting_only = change.kind == SlotChange::target_added || change.kind == SlotChange::source_added; - find(target ? kTarget : kSource, change.lo, change.hi, waiting_only, out); + switch (change.kind) { + case SlotChange::target_gone: find(kTarget, change.lo, change.hi, out); break; + case SlotChange::source_gone: find(kSource, change.lo, change.hi, out); break; + case SlotChange::target_added: find_waiting(kTarget, change.lo, change.hi, out); break; + default: find_waiting(kSource, change.lo, change.hi, out); break; + } } + for (int which = 0; which < 2; ++which) + if (room[which]) + for (const std::uint32_t key : room_[which]) { + ++looked_at_; + out.push_back(key >> 1); + } std::sort(out.begin(), out.end()); out.erase(std::unique(out.begin(), out.end()), out.end()); } private: - static constexpr int kSource = 0, kTarget = 1; + static constexpr int kSource = 0, kTarget = 1, kTexture = 2; + static constexpr std::uint8_t kGeometry = 1; // Half::flags: the resolution asked for a geometry copy + static constexpr int kSettled = 0, kWaiting = 2; // Group::keys: + 1 for the records with kGeometry static constexpr std::uint64_t kMaxSpan = (std::uint64_t(1) << 56) - 1; - static constexpr unsigned kMinGranule = 16; // 64 KiB - static constexpr unsigned kClasses = 57; + static constexpr unsigned kClasses = 65; + struct Range { + std::uint64_t start = 0, end = 0; // end exclusive, saturated at 2^64 - 1; end 0: no range + bool operator==(const Range&) const = default; + }; + struct RangeHash { + std::size_t operator()(const Range& r) const noexcept { + return std::hash{}(r.start ^ (r.end * 0x9e3779b97f4a7c15ull)); + } + }; + // Zero-initialised by calloc: no group (ids are 1-based), state none. A V# half is in the source index (group[0]) + // and, with a target, the target index (group[1]); a T# in the texture index (group[0]). struct Half { - std::uint64_t base, target, span_state; - std::uint64_t span() const { return span_state & kMaxSpan; } - State state() const { return State(span_state >> 56); } + std::uint64_t base; // the V#'s base or the T#'s address, as given + std::uint32_t group[2]; // id + 1, 0: none + std::uint32_t place[2]; // the record's place in that group's list for its state + std::uint32_t room; // its place in room_ while it waits for room + std::uint8_t state; + std::uint8_t flags; // kGeometry }; struct Free { void operator()(Half* p) const { std::free(p); } }; - struct Bucket { - std::vector keys; - std::size_t clean = 0; // its size when it was last cleaned + using ByStart = std::multimap; // start -> group id + struct Group { + std::uint64_t start = 0, end = 0; + // [0] settled records (resolved, bound), [1] settled V# halves that asked for a geometry copy, [2] waiting + // records, [3] waiting V# halves that asked for a geometry copy + std::vector keys[4]; + int index = 0; + unsigned cls = 0; + ByStart::iterator at{}; // in by_start[cls] + ByStart::iterator waiting_at{}; // in waiting_by_start, while keys[2] or keys[3] is not empty + std::uint32_t seen[4] = {}; // the touched() call that last visited each list (epoch_) + bool waits() const { return !keys[kWaiting].empty() || !keys[kWaiting + 1].empty(); } + bool empty() const { return keys[kSettled].empty() && keys[kSettled + 1].empty() && !waits(); } }; struct Index { - std::array, kClasses> classes; - std::uint64_t used = 0; // a bit per class that ever held an entry + std::unordered_map by_range; // -> group id + std::array by_start; + std::uint64_t used[2] = {}; // a bit per class that holds a group (classes 0-63, 64) + ByStart waiting_by_start; // the groups with waiting records, by start }; - // The smallest c with span <= 2^c. - static unsigned span_class(std::uint64_t span) { - return span <= 1 ? 0u : unsigned(64 - std::countl_zero(span - 1)); + static Range range(std::uint64_t start, std::uint64_t span) { + if (span > kMaxSpan) span = kMaxSpan; + return {start, start + span < start ? UINT64_MAX : start + span}; + } + // The smallest c with length <= 2^c. + static unsigned length_class(std::uint64_t length) { + return length <= 1 ? 0u : unsigned(64 - std::countl_zero(length - 1)); } - static unsigned granule_shift(unsigned c) { return c < kMinGranule ? kMinGranule : c; } + static int list_of(State state, std::uint8_t flags) { + return (is_waiting(state) ? kWaiting : kSettled) + ((flags & kGeometry) ? 1 : 0); + } + // The index group[n] of a record in `state` is in. + static int index_of(State state, int n) { return is_texture(state) ? kTexture : n; } + // The room list a record in `state` is in, or -1. + static int room_of(State state) { return state == waiting_room ? 0 : state == texture_waiting_room ? 1 : -1; } void count(State state, int delta) { - if (state != none) recorded_ += std::size_t(std::ptrdiff_t(delta)); - if (state == waiting) waiting_ += std::size_t(std::ptrdiff_t(delta)); + const std::size_t d = std::size_t(std::ptrdiff_t(delta)); + if (is_vsharp(state)) recorded_ += d; + if (state == waiting || state == waiting_room) waiting_ += d; + if (is_texture(state)) textures_count_ += d; + if (state == texture_waiting || state == texture_waiting_room) textures_waiting_ += d; + } + + // Records `key` in `state` under ranges[0] (and ranges[1], a V#'s target); what is unchanged stays where it is. + void place(std::uint32_t key, State state, std::uint8_t flags, std::uint64_t base, const Range (&ranges)[2]) { + Half& h = halves_[key]; + const State old = State(h.state); + if (old == state && h.flags == flags && h.base == base) { + bool all_same = true; + for (int n = 0; n < 2; ++n) { + const std::uint32_t group = h.group[n]; + if (ranges[n].end == 0) { + if (group != 0) { + all_same = false; + break; + } + } else if (!group || groups_[group - 1].start != ranges[n].start || + groups_[group - 1].end != ranges[n].end) { + all_same = false; + break; + } + } + if (all_same) return; + } + for (int n = 0; n < 2; ++n) { + const std::uint32_t group = h.group[n]; + const bool keep = group && list_of(old, h.flags) == list_of(state, flags) && + index_of(old, n) == index_of(state, n) && groups_[group - 1].start == ranges[n].start && + groups_[group - 1].end == ranges[n].end; + if (keep) continue; + detach(n, key); // in the list of the old state, which h.state and h.flags still hold + if (ranges[n].end) attach(n, index_of(state, n), key, ranges[n], list_of(state, flags)); + } + h.flags = flags; + if (room_of(old) != room_of(state)) { + leave_room(key); + if (room_of(state) >= 0) { + auto& room = room_[room_of(state)]; + h.room = std::uint32_t(room.size()); + room.push_back(key); + } + } + count(old, -1); + h.state = state; + h.base = base; + count(state, +1); } - // Whether index `which` still holds `key` under (c, granule). - bool current(int which, std::uint32_t key, unsigned c, std::uint64_t granule) const { - const Half& h = halves_[key]; - if (h.state() == none || span_class(h.span()) != c) return false; - if (which == kTarget && !h.target) return false; - return ((which == kSource ? h.base : h.target) >> granule_shift(c)) == granule; + void drop(std::uint32_t key) { + Half& h = halves_[key]; + if (h.state == none) return; + for (int n = 0; n < 2; ++n) detach(n, key); + leave_room(key); + count(State(h.state), -1); + h.state = none; + h.flags = 0; + h.base = 0; } - void push(int which, unsigned c, std::uint64_t granule, std::uint32_t key) { - Index& index = indexes_[which]; - index.used |= std::uint64_t(1) << c; - Bucket& bucket = index.classes[c][granule]; - bucket.keys.push_back(key); - if (bucket.keys.size() < 32 || bucket.keys.size() < 2 * bucket.clean) return; - auto& keys = bucket.keys; - keys.erase(std::remove_if(keys.begin(), keys.end(), - [&](std::uint32_t k) { return !current(which, k, c, granule); }), - keys.end()); - std::sort(keys.begin(), keys.end()); - keys.erase(std::unique(keys.begin(), keys.end()), keys.end()); - bucket.clean = keys.size(); - } - - void find(int which, std::uint64_t lo, std::uint64_t hi, bool waiting_only, std::vector& out) { + void leave_room(std::uint32_t key) { + Half& h = halves_[key]; + const int which = room_of(State(h.state)); + if (which < 0) return; + auto& room = room_[which]; + const std::uint32_t last = room.back(); + room[h.room] = last; + halves_[last].room = h.room; + room.pop_back(); + } + + void attach(int n, int which, std::uint32_t key, Range r, int list_index) { Index& index = indexes_[which]; - for (std::uint64_t used = index.used; used; used &= used - 1) { - const unsigned c = unsigned(std::countr_zero(used)); - auto& buckets = index.classes[c]; - if (buckets.empty()) continue; - const unsigned shift = granule_shift(c); - // A half of this class overlaps [lo, hi) only if it starts in (lo - 2^c, hi). - const std::uint64_t reach = std::uint64_t(1) << c; - const std::uint64_t first = (lo >= reach ? lo - reach + 1 : 0) >> shift; - const std::uint64_t last = (hi - 1) >> shift; - const auto visit = [&](std::uint64_t granule, const Bucket& bucket) { - for (const std::uint32_t key : bucket.keys) { - ++looked_at_; - if (!current(which, key, c, granule)) continue; - const Half& h = halves_[key]; - if (waiting_only && h.state() != waiting) continue; - const std::uint64_t start = which == kSource ? h.base : h.target; - const std::uint64_t span = h.span(); - const std::uint64_t end = start + span < start ? UINT64_MAX : start + span; - if (start < hi && end > lo) out.push_back(key >> 1); - } - }; - if (last - first >= buckets.size()) { - for (const auto& [granule, bucket] : buckets) - if (granule >= first && granule <= last) visit(granule, bucket); + auto [it, made] = index.by_range.try_emplace(r, 0); + if (made) { + std::uint32_t id; + if (!free_groups_.empty()) { + id = free_groups_.back(); + free_groups_.pop_back(); } else { - for (std::uint64_t granule = first;; ++granule) { - const auto it = buckets.find(granule); - if (it != buckets.end()) visit(granule, it->second); - if (granule == last) break; - } + id = std::uint32_t(groups_.size()); + groups_.emplace_back(); } + Group& g = groups_[id]; + g.start = r.start; + g.end = r.end; + g.index = which; + g.cls = length_class(r.end - r.start); + g.at = index.by_start[g.cls].emplace(r.start, id); + index.used[g.cls >> 6] |= std::uint64_t(1) << (g.cls & 63); + it->second = id; + } + Group& g = groups_[it->second]; + const bool waited = g.waits(); + auto& list = g.keys[list_index]; + const bool became_settled = which == kTexture && list_index == kSettled && list.empty(); + Half& h = halves_[key]; + h.group[n] = it->second + 1; + h.place[n] = std::uint32_t(list.size()); + list.push_back(key); + if (list_index >= kWaiting && !waited) g.waiting_at = index.waiting_by_start.emplace(g.start, it->second); + if (became_settled && texture_live_cb_) texture_live_cb_(texture_live_user_, g.start, true); + } + + // Takes `key` out of its group[n], from the list of its current state. + void detach(int n, std::uint32_t key) { + Half& h = halves_[key]; + if (!h.group[n]) return; + const std::uint32_t id = h.group[n] - 1; + Group& g = groups_[id]; + Index& index = indexes_[g.index]; + const int which_list = list_of(State(h.state), h.flags); + auto& list = g.keys[which_list]; + const std::uint32_t at = h.place[n], last = list.back(); + list[at] = last; + halves_[last].place[n] = at; + list.pop_back(); + h.group[n] = 0; + const bool became_unsettled = g.index == kTexture && which_list == kSettled && list.empty(); + const std::uint64_t addr = g.start; + if (which_list >= kWaiting && !g.waits()) index.waiting_by_start.erase(g.waiting_at); + if (g.empty()) { + index.by_range.erase(Range{g.start, g.end}); + index.by_start[g.cls].erase(g.at); + if (index.by_start[g.cls].empty()) index.used[g.cls >> 6] &= ~(std::uint64_t(1) << (g.cls & 63)); + for (auto& keys : g.keys) std::vector().swap(keys); + free_groups_.push_back(id); } + if (became_unsettled && texture_live_cb_) texture_live_cb_(texture_live_user_, addr, false); + } + + void notify_all_textures_unbound() { + if (!texture_live_cb_) return; + for (const auto& [r, id] : indexes_[kTexture].by_range) { + if (!groups_[id].keys[kSettled].empty()) texture_live_cb_(texture_live_user_, r.start, false); + } + } + + // A list of `g` into `out`, unless this call has visited it already. + void visit(Group& g, int list, std::vector& out) { + if (g.seen[list] == epoch_) return; + g.seen[list] = epoch_; + for (const std::uint32_t key : g.keys[list]) { + ++looked_at_; + out.push_back(key >> 1); + } + } + + // The waiting records of index `which` whose range starts in [lo, hi): only groups that hold some are walked. + void find_waiting(int which, std::uint64_t lo, std::uint64_t hi, std::vector& out) { + const Index& index = indexes_[which]; + for (auto it = index.waiting_by_start.lower_bound(lo); it != index.waiting_by_start.end() && it->first < hi; + ++it) { + ++groups_looked_at_; + visit(groups_[it->second], kWaiting, out); + visit(groups_[it->second], kWaiting + 1, out); + } + } + + // Every record of index `which` whose range overlaps [lo, hi). + void find(int which, std::uint64_t lo, std::uint64_t hi, std::vector& out) { + const Index& index = indexes_[which]; + for (unsigned word = 0; word < 2; ++word) + for (std::uint64_t used = index.used[word]; used; used &= used - 1) { + const unsigned c = word * 64 + unsigned(std::countr_zero(used)); + const ByStart& groups = index.by_start[c]; + // A group of this class (length at most 2^c) overlaps [lo, hi) only if it starts in (lo - 2^c, hi). + const std::uint64_t reach = c >= 64 ? UINT64_MAX : (std::uint64_t(1) << c); + const std::uint64_t first = lo >= reach ? lo - reach + 1 : 0; + for (auto it = groups.lower_bound(first); it != groups.end() && it->first < hi; ++it) { + Group& g = groups_[it->second]; + ++groups_looked_at_; + if (g.end <= lo) continue; + for (int list = 0; list < 4; ++list) visit(g, list, out); + } + } } std::size_t slots_ = 0; std::unique_ptr halves_; - std::array indexes_; - std::size_t recorded_ = 0, waiting_ = 0; - std::uint64_t looked_at_ = 0; + std::array indexes_; + std::array, 2> room_; // 0: V# halves in waiting_room, 1: T#s in texture_waiting_room + std::vector groups_; + std::vector free_groups_; + std::size_t recorded_ = 0, waiting_ = 0, textures_count_ = 0, textures_waiting_ = 0; + std::uint64_t looked_at_ = 0, groups_looked_at_ = 0; + std::uint32_t epoch_ = 0; // touched() calls, for Group::seen + TextureLiveCallback texture_live_cb_ = nullptr; + void* texture_live_user_ = nullptr; }; } // namespace leonida diff --git a/runtime/src/fsdraw_probe.h b/runtime/src/fsdraw_probe.h index 367f793cb6..5be874a20a 100644 --- a/runtime/src/fsdraw_probe.h +++ b/runtime/src/fsdraw_probe.h @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -25,8 +26,9 @@ struct State { std::mutex mutex; std::unordered_map pipelines; // graphics PSO id -> description std::set> tsharps; // T#s that have a bindless entry - const std::uint8_t* arena = nullptr; // the GPU address arena's host mapping + const void* arena = nullptr; // the device whose GPU address arena `read_arena` reads std::uint64_t arena_size = 0; + std::function read_arena; // false: no memory there std::vector readback; // render targets of fullscreen draws (besides the presented source) std::uint64_t presented_source = 0; std::unordered_map table_origin; // translated table VA -> title VA @@ -89,19 +91,22 @@ inline bool has_tsharp(const std::uint32_t* words) { return state().tsharps.count(key) != 0; } -inline void note_arena(const std::uint8_t* mapped, std::uint64_t size) { +inline void note_arena(const void* device, std::uint64_t size, + std::function read) { std::lock_guard lock(state().mutex); - state().arena = mapped; + state().arena = device; state().arena_size = size; + state().read_arena = std::move(read); } // A test or application may create multiple devices. Never inspect a released // mapping; destroying an older device must leave the current mapping alone. -inline void forget_arena(const std::uint8_t* mapped) { +inline void forget_arena(const void* device) { std::lock_guard lock(state().mutex); - if (state().arena == mapped) { + if (state().arena == device) { state().arena = nullptr; state().arena_size = 0; + state().read_arena = nullptr; } } @@ -168,9 +173,8 @@ inline std::string hex_words(const std::uint32_t* w, std::size_t n) { inline bool arena_words(std::uint64_t va, std::uint32_t* out, std::size_t n) { std::lock_guard lock(state().mutex); const State& s = state(); - if (!s.arena || va + n * 4 > s.arena_size || va + n * 4 < va) return false; - std::memcpy(out, s.arena + va, n * 4); - return true; + if (!s.arena || !s.read_arena || va + n * 4 > s.arena_size || va + n * 4 < va) return false; + return s.read_arena(va, out, n * 4); } inline std::uint64_t arena_size() { diff --git a/runtime/src/gfx10_descriptors.h b/runtime/src/gfx10_descriptors.h index acfa590f8e..5773c8734f 100644 --- a/runtime/src/gfx10_descriptors.h +++ b/runtime/src/gfx10_descriptors.h @@ -179,6 +179,45 @@ inline constexpr bool partial_volume_uav(const ImageWords& words, const Image& i return range.first_w != 0 || range.w_size != (mip_depth ? mip_depth : 1u); } +// The bindless index in the T# (docs/design.md, "Bindless index in the T#"). In the heaps shaders read (the copies of +// the console resource heaps and the layer's own shader-visible heaps) the layer writes dword 6 of every T# as +// TAG [31:28] | storage kind [27:23] | sampled kind [22:16] | index [15:0] +// where the kinds are descriptor_table.h's kind bits 8..12 and 0..6 for that index. A translated shader that loaded +// the T# from such a heap takes the index from this word and no hash-table lookup (tools/rdna2spirv.py, +// tsharp_index_word), and reads index 0 (the fallback) unless the word has the tag and dword 3 names an image (TYPE +// 8..15, bit 31). Dword 6 is the hardware's compression metadata (META_DATA_ADDRESS, COMPRESSION_EN and friends), +// which no Vulkan view uses; over the 1.0.2.1 corpus no shader reads dword 6 or 7 of a heap T# with a scalar +// instruction (tools/descriptor_source_census.py). The title's own bytes keep their dword 6, and a T#'s table key +// stays the descriptor as the title or Create*View wrote it (tsharp_key strips the word from the layer's heaps). +inline constexpr unsigned kTsharpIndexDword = 6; +inline constexpr std::uint32_t kTsharpIndexTag = 0xA; +inline constexpr std::uint32_t kTsharpIndexLimit = 0x10000; // an index past 16 bits gets no word (the fallback) + +// The word for `index` bound in the arrays `kind` names (descriptor_table.h's kind bits); 0 for index 0 or one that +// does not fit, which every shader reads as the fallback. +inline constexpr std::uint32_t tsharp_index_word(std::uint32_t index, std::uint32_t kind) { + if (!index || index >= kTsharpIndexLimit) return 0; + return (kTsharpIndexTag << 28) | (((kind >> 8) & 0x1Fu) << 23) | ((kind & 0x7Fu) << 16) | index; +} +inline constexpr bool has_tsharp_index(const ImageWords& words) { + return (words[kTsharpIndexDword] >> 28) == kTsharpIndexTag; +} +// The index and kind a shader reads from `words` (0 and 0 without the tag or when dword 3 names no image). +inline constexpr std::uint32_t tsharp_index_of(const ImageWords& words) { + return has_tsharp_index(words) && (words[3] >> 31) ? words[kTsharpIndexDword] & 0xFFFFu : 0u; +} +inline constexpr std::uint32_t tsharp_kind_of(const ImageWords& words) { + if (!has_tsharp_index(words) || !(words[3] >> 31)) return 0; + const std::uint32_t w = words[kTsharpIndexDword]; + return ((w >> 16) & 0x7Fu) | (((w >> 23) & 0x1Fu) << 8); +} +// The key of a T# the layer wrote into one of its own heaps: dword 6 as encode() writes it (0) when it carries the +// index. Only for words read back from the layer's heaps; a title's T# keeps whatever its dword 6 holds. +inline constexpr ImageWords tsharp_key(ImageWords words) { + if (has_tsharp_index(words)) words[kTsharpIndexDword] = 0; + return words; +} + inline constexpr float image_min_lod(const ImageWords& words) { return float(detail::get(words[1], 8, 12)) / 256.0f; } diff --git a/runtime/src/guarded_copy.h b/runtime/src/guarded_copy.h index 60914d1691..640d9f336d 100644 --- a/runtime/src/guarded_copy.h +++ b/runtime/src/guarded_copy.h @@ -10,6 +10,7 @@ // - clang-cl, without /EHa, catches only what a call inside the __try raises, not an inline load or store. // So the bytes move here: never inlined, and no_builtin keeps the compiler from turning a loop back into a call to // memcpy or memmove. +#include "shadow_keep.h" #include #include #include @@ -56,4 +57,12 @@ __declspec(noinline) inline std::uintptr_t read_word(const void* at) { return *static_cast(at); } +// Fused copy + 256-byte piece hashing for a __try frame: never inlined and no_builtin so clang-cl (/EHsc) and Wine +// unwind any access violation on `from` into the caller's __except instead of a CRT memcpy. +// Intentionally NOT noexcept (SEH under /EHsc). +__declspec(noinline) LEONIDA_GUARDED_NO_BUILTIN inline void copy_and_sum_256( + std::uint8_t* to, const std::uint8_t* from, std::size_t pieces, std::uint64_t* out) { + leonida::shadow_keep::copy_and_sum_256(to, from, pieces, out); +} + } // namespace leonida::guarded diff --git a/runtime/src/list_value_progress.h b/runtime/src/list_value_progress.h new file mode 100644 index 0000000000..4afe64e5bd --- /dev/null +++ b/runtime/src/list_value_progress.h @@ -0,0 +1,198 @@ +#pragma once +// When a held console memory wait may go without its value (runtime/shims/d3d12_xs_list_values.h, +// docs/d3d12_xs_console_abi.md §5.5). +// +// A queue that stands at a wait for a value no write has met yet is held until the value is in memory: the console's +// command processor would stand there as long, and work that reads what the writer produces must not run before it. +// There is no timeout. A held wait goes without its value only when nothing else can make progress, and then only by +// one of three rules, each about progress, never about how long the wait has stood: +// - cycle: the wait's value is written by work that is itself held behind a wait that depends, through further held +// writes, on the waiting queue. Nothing modelled can ever meet it. +// - present: the title has presented since the wait was held. A wait is not kept across frames: the present stands +// behind the held work (src/queue_holds.h, after_held), and the title's next frame would otherwise never be shown. +// - stalled: the title has made no queue call at all for kStalledMs while nothing ran. Its threads wait for something +// behind the held work (a fence the held part signals, say): a deadlock through the title's CPU, which no write +// can end. Not a timeout of the wait: one held for a minute while the title keeps calling stays held. +// "Nothing else can make progress" is: the releaser has no gate to signal and is not inside a Signal, nothing landed +// or opened in this pass, no title ExecuteCommandLists is in progress, and no write group or action is running on the +// GPU (its Signal submitted and its fence not reached: work held in the layer, behind a gate, a relayed wait or a +// title fence, is not running). +// The candidate is a queue's first held gate (each queue's gates open in order). With several, the rules go to the +// oldest gate whose wait no held write could meet ("root"); a gate whose writer is held behind another queue's root +// waits for that root, so the chain unwinds in order. Device loss and the end of the process are handled by the pump. +// +// The release rule follows VIctory-Belobug-AMD (GPL-3.0-or-later): crates/victory-gpu/src/queue/behind.rs, `step` +// (a held wait is forced only when a present is in the line and nothing else can run) and +// crates/victory-gpu/src/queue.rs, `release_held` ("a wait is not kept across frames"). Written anew for this +// runtime's queues; no code is copied. +// +// Pure C++20 standard library only, so the policy is tested portably (test/list_value_progress_test.cpp). + +#include +#include +#include +#include +#include + +namespace leonida::list_value_progress { + +// The title's queues called nothing for this long while nothing ran: its threads wait for held work. +inline constexpr std::uint64_t kStalledMs = 2000; + +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: the value is known only at landing +}; + +struct PendingWriteGroup { + const void* queue = nullptr; + std::uint64_t after_gate = 0; // highest gate value pending on `queue` when the group was submitted (0: none) + bool running = false; // its Signal reached the GPU and its fence is not reached yet + std::span writes; +}; + +struct PendingGate { + const void* queue = nullptr; + std::uint64_t value = 0; + bool is_action = false; // a CPU action at a point of the queue's timeline, not a memory wait + bool action_running = false; // action: the work before it is on the GPU and not done yet + std::span unmet_waits; + std::uint64_t presents_at_hold = 0; // the title's present count when the gate was held + std::uint64_t held_ms = 0; // when it was held +}; + +struct Activity { + bool releasing = false; // the releaser has gates to signal or is inside a Signal, or this pass moved + bool title_submitting = false; // a title ExecuteCommandLists is in progress + std::uint64_t presents = 0; // the title's presents so far + std::uint64_t now_ms = 0; + std::uint64_t title_call_ms = 0; // when the title's latest queue call began or ended +}; + +enum class Reason : std::uint8_t { hold, cycle, present, stalled }; + +inline const char* reason_text(Reason reason) { + switch (reason) { + case Reason::cycle: return "its writer is held behind a wait on this queue (a cycle)"; + case Reason::present: return "a present is queued behind it and nothing else can run"; + case Reason::stalled: return "the title made no queue call while nothing ran (it waits for held work)"; + default: return "held"; + } +} + +struct Decision { + std::size_t gate = SIZE_MAX; // index into the gates given to decide() + Reason reason = Reason::hold; +}; + +namespace detail { + +// True when `group`'s last write touching [wait.address, wait.address + need) lands a value that meets `wait` (or is a +// timestamp written to that address, whose value is not known before it lands). +template +bool group_meets(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; + if (w.address >= wait_end || wait.address >= w.address + w.bytes) continue; + return w.address == wait.address && w.bytes >= need && + (w.timestamp || met(wait.comparison, w.value, wait.reference, wait.wide)); + } + return false; +} + +// True when `gates[from]` waits, directly or through the writers of what it waits for, on a gate of `target`. +template +bool reaches(std::size_t from, const void* target, std::span writes, + std::span gates, MetFn&& met, std::vector& visiting) { + const PendingGate& g = gates[from]; + if (g.queue == target) return true; + if (g.is_action || std::find(visiting.begin(), visiting.end(), from) != visiting.end()) return false; + visiting.push_back(from); + for (const WaitPredicate& wait : g.unmet_waits) + for (const PendingWriteGroup& w : writes) { + if (!w.after_gate || !group_meets(w, wait, met)) continue; + for (std::size_t b = 0; b < gates.size(); ++b) + if (gates[b].queue == w.queue && gates[b].value <= w.after_gate && + reaches(b, target, writes, gates, met, visiting)) { + visiting.pop_back(); + return true; + } + } + visiting.pop_back(); + return false; +} + +} // namespace detail + +// Something can still make progress: what it does may meet a held wait, or show that it cannot be met. +inline bool can_progress(std::span writes, std::span gates, + const Activity& activity) { + if (activity.releasing || activity.title_submitting) return true; + for (const PendingWriteGroup& w : writes) + if (w.running) return true; + for (const PendingGate& g : gates) + if (g.is_action && g.action_running) return true; + return false; +} + +// Which held gate goes now without its value, if any. `gates` are the pending gates in the order they were held +// (each queue's in rising value); `met(comparison, value, reference, wide)` is console_value_met. +template +Decision decide(std::span writes, std::span gates, + const Activity& activity, MetFn&& met) { + if (can_progress(writes, gates, activity)) return {}; + std::vector seen; + std::vector roots, chained, cycles; + std::vector visiting; + for (std::size_t i = 0; i < gates.size(); ++i) { + const PendingGate& g = gates[i]; + if (std::find(seen.begin(), seen.end(), g.queue) != seen.end()) continue; + seen.push_back(g.queue); // only a queue's first gate can open + if (g.is_action) continue; + bool matched = false, behind_gate = false, cyclic = false; + for (const WaitPredicate& wait : g.unmet_waits) + for (const PendingWriteGroup& w : writes) { + if (!detail::group_meets(w, wait, met)) continue; + matched = true; + if (!w.after_gate) continue; + for (std::size_t b = 0; b < gates.size() && !cyclic; ++b) { + if (gates[b].queue != w.queue || gates[b].value > w.after_gate) continue; + behind_gate = true; + visiting.clear(); + cyclic = detail::reaches(b, g.queue, writes, gates, met, visiting); + } + } + if (cyclic) + cycles.push_back(i); + else if (matched && behind_gate) + chained.push_back(i); // waits for another queue's held gate, which goes first + else + roots.push_back(i); // no held write meets it, or its writer is held behind something not modelled here + } + if (!cycles.empty()) return {cycles.front(), Reason::cycle}; + const std::vector& candidates = roots.empty() ? chained : roots; + for (std::size_t i : candidates) + if (activity.presents > gates[i].presents_at_hold) return {i, Reason::present}; + const auto quiet = [&](std::uint64_t since) { + return activity.now_ms >= since && activity.now_ms - since >= kStalledMs; + }; + if (quiet(activity.title_call_ms)) + for (std::size_t i : candidates) + if (quiet(gates[i].held_ms)) return {i, Reason::stalled}; + return {}; +} + +} // namespace leonida::list_value_progress diff --git a/runtime/src/list_value_wait_budget.h b/runtime/src/list_value_wait_budget.h deleted file mode 100644 index 8e1fd52190..0000000000 --- a/runtime/src/list_value_wait_budget.h +++ /dev/null @@ -1,251 +0,0 @@ -#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/literal_sampler_spec.h b/runtime/src/literal_sampler_spec.h new file mode 100644 index 0000000000..39e11cb9d5 --- /dev/null +++ b/runtime/src/literal_sampler_spec.h @@ -0,0 +1,60 @@ +#pragma once + +// Builds a VkSpecializationInfo binding literal-sampler SPIR-V specialization constants (SpecId spec_base + i) +// to their uint32_t bindless sampler array indices (or 0xFFFFFFFFu when a sampler failed to bind so the shader +// safely falls back to the descriptor-table hash probe). + +#include + +#include +#include +#include +#include + +namespace leonida { + +struct LiteralSamplerSpec { + static constexpr std::uint32_t kFallbackIndex = 0xFFFFFFFFu; + + std::vector entries; + std::vector values; + VkSpecializationInfo info{}; + + LiteralSamplerSpec() = default; + LiteralSamplerSpec(const LiteralSamplerSpec&) = delete; + LiteralSamplerSpec& operator=(const LiteralSamplerSpec&) = delete; + LiteralSamplerSpec(LiteralSamplerSpec&&) = delete; + LiteralSamplerSpec& operator=(LiteralSamplerSpec&&) = delete; + + void clear() { + entries.clear(); + values.clear(); + info = {}; + } + + // Populates entries/values/info for SpecId [spec_base, spec_base + indices.size()). + // Leaves the specialization empty if `indices` is empty or `spec_base + indices.size() - 1` would overflow uint32. + void build(std::uint32_t spec_base, std::span indices) { + clear(); + if (indices.empty()) return; + const std::size_t max_count = + std::size_t(std::numeric_limits::max() - spec_base) + 1u; + if (indices.size() > max_count) return; + entries.reserve(indices.size()); + values.assign(indices.begin(), indices.end()); + for (std::size_t i = 0; i < values.size(); ++i) { + entries.push_back({spec_base + static_cast(i), + static_cast(i * sizeof(std::uint32_t)), + sizeof(std::uint32_t)}); + } + info.mapEntryCount = static_cast(entries.size()); + info.pMapEntries = entries.data(); + info.dataSize = values.size() * sizeof(std::uint32_t); + info.pData = values.data(); + } + + const VkSpecializationInfo* ptr() const noexcept { return entries.empty() ? nullptr : &info; } + bool active() const noexcept { return !entries.empty(); } +}; + +} // namespace leonida diff --git a/runtime/src/memory_breakdown.h b/runtime/src/memory_breakdown.h index 7e2ae70577..f7963b1f58 100644 --- a/runtime/src/memory_breakdown.h +++ b/runtime/src/memory_breakdown.h @@ -32,6 +32,7 @@ enum class Consumer : std::uint8_t { image_blocks, // blocks that hold many textures (ImageMemory, TitleImagePool) sampled, // dedicated memory of a texture that is not an attachment render_target, // dedicated memory of a colour or depth/stencil attachment + mirror, // the page mirror's homes: one per physical page the GPU reads (src/title_mirror.h) count }; @@ -48,6 +49,7 @@ inline const char* consumer_name(Consumer c) { case Consumer::image_blocks: return "texture blocks"; case Consumer::sampled: return "sampled textures"; case Consumer::render_target: return "render targets and depth"; + case Consumer::mirror: return "page mirror"; default: return "?"; } } @@ -111,7 +113,11 @@ struct DeviceShare { std::uint64_t arena_in_use = 0; // bytes allocations hold // arena_in_use by kind, as DeviceState::ArenaUse: buffers, descriptor heaps, shader code, heaps std::array arena_use{}; + std::uint64_t arena_windows = 0; // arena_in_use held by title windows and slot-133 shadows std::uint64_t bindless_table_bytes = 0; // allocated by BindlessSet through its own function table + bool mirror = false; // the page mirror is on: its homes, the pages bound to them, its chunks + std::uint64_t mirror_homes = 0, mirror_pages = 0, mirror_chunks = 0; + std::uint64_t mirror_units_local = 0, mirror_units_host = 0; // its units of homes by memory }; inline double mib(std::uint64_t bytes) { return double(bytes) / 1048576.0; } @@ -131,12 +137,34 @@ inline std::string format(const Tally& tally, const DeviceShare& device, std::ui out += item; first = false; if (Consumer(c) == Consumer::arena && device.arena) { + if (device.arena_windows) { + std::snprintf(item, sizeof item, + " [reserved %.0f, bound %.0f, in use %.0f: buffers %.0f, descriptor heaps %.0f, shader " + "code %.0f, heaps %.0f, windows/shadows %.0f]", + mib(device.arena_reserved), mib(device.arena_bound), mib(device.arena_in_use), + mib(device.arena_use[0]), mib(device.arena_use[1]), mib(device.arena_use[2]), + mib(device.arena_use[3]), mib(device.arena_windows)); + } else { + std::snprintf(item, sizeof item, + " [reserved %.0f, bound %.0f, in use %.0f: buffers %.0f, descriptor heaps %.0f, shader " + "code %.0f, heaps %.0f]", + mib(device.arena_reserved), mib(device.arena_bound), mib(device.arena_in_use), + mib(device.arena_use[0]), mib(device.arena_use[1]), mib(device.arena_use[2]), + mib(device.arena_use[3])); + } + out += item; + } + if (Consumer(c) == Consumer::windows && device.arena_windows) { + std::snprintf(item, sizeof item, " [in arena %.0f MiB]", mib(device.arena_windows)); + out += item; + } + if (Consumer(c) == Consumer::mirror && device.mirror) { std::snprintf(item, sizeof item, - " [reserved %.0f, bound %.0f, in use %.0f: buffers %.0f, descriptor heaps %.0f, shader code " - "%.0f, heaps %.0f]", - mib(device.arena_reserved), mib(device.arena_bound), mib(device.arena_in_use), - mib(device.arena_use[0]), mib(device.arena_use[1]), mib(device.arena_use[2]), - mib(device.arena_use[3])); + " [homes bound %.0f MiB (%llu), pages mirrored %llu, chunks %llu, units %llu device-local %llu " + "host]", + mib(device.mirror_homes * 0x10000), (unsigned long long)device.mirror_homes, + (unsigned long long)device.mirror_pages, (unsigned long long)device.mirror_chunks, + (unsigned long long)device.mirror_units_local, (unsigned long long)device.mirror_units_host); out += item; } } diff --git a/runtime/src/queue_holds.h b/runtime/src/queue_holds.h index 40cc331170..b495adc326 100644 --- a/runtime/src/queue_holds.h +++ b/runtime/src/queue_holds.h @@ -1,15 +1,68 @@ #pragma once #include +#include #include #include #include +#include #include +#include +#include +#include #include #include namespace leonida { +namespace queue_holds { + +// Process-wide registry of live QueueHolds instances and their active CPU/async queue work count. +// Queried by the console list-value progress pump (shims/d3d12_xs_list_values.h) so held waits are never +// released unmet while any queue has queued async inbox calls, an active worker/executing submission, a pending +// held-release request, an active pump_ready() pass, or unretired GPU work. +struct Registry { + struct Entry { + const void* owner = nullptr; + bool (*has_progress)(const void* owner) = nullptr; + }; + + std::atomic active_work{0}; + mutable std::mutex mutex; + std::vector entries; + + static Registry& get() { + static Registry* r = new Registry; // immortal: may be queried during teardown + return *r; + } + + void add(const void* owner, bool (*fn)(const void*)) { + std::lock_guard lock(mutex); + entries.push_back({owner, fn}); + } + + void remove(const void* owner) { + std::lock_guard lock(mutex); + for (auto it = entries.begin(); it != entries.end(); ++it) + if (it->owner == owner) { + entries.erase(it); + return; + } + } + + bool any_progress() const { + if (active_work.load(std::memory_order_acquire) > 0) return true; + std::lock_guard lock(mutex); + for (const Entry& e : entries) + if (e.has_progress && e.has_progress(e.owner)) return true; + return false; + } +}; + +inline bool any_progress() { return Registry::get().any_progress(); } + +} // namespace queue_holds + // Cross-queue Wait-before-Signal (docs section 4.4, "Wait before Signal across queues"). // // A queue replays its ExecuteCommandLists against one device-wide layout tracker, in the order the calls reach the @@ -36,22 +89,99 @@ namespace leonida { template class QueueHolds { public: + // Replacement wait target for retroactive GPU-to-GPU wait relays. `pin` keeps the underlying fence object alive + // until the substituted submission retires on the GPU. + struct Wait { + Semaphore semaphore{}; + std::uint64_t value = 0; + std::shared_ptr pin; + }; + // A queue that can hold batches. The calls take the queue's own lock; none is made with it held. struct Holder { // Releases the held operations at the front of the queue whose waits are satisfied. True if any was. virtual bool release_ready() = 0; // Drops the held operations that wait on `semaphore` (its fence is gone), reporting each. virtual void discard_waiting_on(Semaphore semaphore) = 0; - // Sequence number (next_seq()) of the oldest held operation, 0 when nothing is held. + // Sequence number (next_seq()) of the oldest held operation, 0 when nothing is held. Read-only query. virtual std::uint64_t oldest_held_seq() = 0; + // Notifies the holder that a real after_held() barrier was registered at `seq` so batches at or before `seq` + // will not coalesce with batches enqueued after `seq`. Called with no queue lock held. + virtual void note_barrier(std::uint64_t /*seq*/) {} + // Substitutes any queued/pending/held waits matching `(gate_sem, gate_val)` with `replacements`. + // Sets `any_substituted = true` when at least one matching wait was replaced; returns true when at least one + // held operation was updated (and may now be ready to release). Called with no QueueHolds lock held. + virtual bool apply_wait_relay(Semaphore /*gate_sem*/, std::uint64_t /*gate_val*/, + std::span /*replacements*/, bool& /*any_substituted*/) { + return false; + } + // True when this queue has submitted GPU work that has not retired yet. Must not take any QueueHolds or + // queue lock (called under holders_use_mutex_ shared lock from any_progress()). + virtual bool has_pending_gpu_work() const { return false; } protected: ~Holder() = default; }; + QueueHolds() { queue_holds::Registry::get().add(this, &has_progress_thunk); } + ~QueueHolds() { + queue_holds::Registry::get().remove(this); + { + std::lock_guard bl(barrier_mutex_); + barrier_stop_ = true; + } + barrier_cv_.notify_all(); + if (barrier_thread_.joinable()) barrier_thread_.join(); + } + QueueHolds(const QueueHolds&) = delete; + QueueHolds& operator=(const QueueHolds&) = delete; + + // Tracks active CPU-side queue progress (async inbox items, busy worker turns, pending async release requests, + // actively executing submissions, and active pump_ready() passes). Balanced in pairs / via WorkGuard. + void work_changed(std::int64_t delta) { + active_work_.fetch_add(delta, std::memory_order_acq_rel); + queue_holds::Registry::get().active_work.fetch_add(delta, std::memory_order_acq_rel); + } + + class WorkGuard { + public: + WorkGuard() = default; + explicit WorkGuard(QueueHolds& holds) { arm(holds); } + ~WorkGuard() { release(); } + void arm(QueueHolds& holds) { + if (holds_) return; + holds_ = &holds; + holds_->work_changed(1); + } + void release() { + if (!holds_) return; + QueueHolds* h = holds_; + holds_ = nullptr; + h->work_changed(-1); + } + WorkGuard(const WorkGuard&) = delete; + WorkGuard& operator=(const WorkGuard&) = delete; + + private: + QueueHolds* holds_ = nullptr; + }; + + // True when this device has active CPU/async queue work, an unpumped signal for held work, or unretired GPU + // work on any attached queue. Lock order: Registry::mutex (optional) -> holders_use_mutex_ (shared) -> mutex_ + // (leaf, released before querying each holder's lock-free GPU progress). + bool has_progress() const { + if (active_work_.load(std::memory_order_acquire) > 0) return true; + if (any_held() && signaled_unpumped_.load(std::memory_order_acquire)) return true; + std::shared_lock use(holders_use_mutex_); + const auto list = snapshot(); + for (const Holder* holder : list) + if (holder->has_pending_gpu_work()) return true; + return false; + } + void add_fence(Semaphore semaphore, std::uint64_t initial) { std::lock_guard lock(mutex_); - fences_[semaphore] = initial; + fences_[semaphore] = FenceState{initial}; } // The fence is gone. Operations that still reference it are dropped and reported (the COM layer keeps a fence @@ -59,10 +189,33 @@ class QueueHolds { // from inside a release: the releasing thread already holds the lock, and what it is releasing cannot // reference a fence whose last reference it is dropping, since that reference is the one it holds. void remove_fence(Semaphore semaphore) { + std::vector> dropped_pins; { std::lock_guard lock(mutex_); fences_.erase(semaphore); + if (!relays_.empty()) { + for (auto it = relays_.begin(); it != relays_.end();) { + bool match = (it->gate_sem == semaphore); + if (!match) { + for (const Wait& w : it->replacements) { + if (w.semaphore == semaphore) { + match = true; + break; + } + } + } + if (match) { + for (Wait& w : it->replacements) + if (w.pin) dropped_pins.push_back(std::move(w.pin)); + it = relays_.erase(it); + } else { + ++it; + } + } + relay_count_.store(relays_.size(), std::memory_order_release); + } } + dropped_pins.clear(); if (held_.load(std::memory_order_acquire) == 0 || in_pump()) return; { std::lock_guard pump(pump_mutex_); @@ -75,10 +228,146 @@ class QueueHolds { // A Signal of `value` was submitted to the GPU (or the CPU set the fence). Call after the submission, with no // queue lock held; then pump_ready() to release what it satisfied. - void signaled(Semaphore semaphore, std::uint64_t value) { + // `vis_seq` is non-zero for CPU-side Fence::Signal edges (establishing a happens-before edge for CPU memory + // written before the signal) and 0 for GPU-only queue Signals, tracked per `(semaphore, value)` so waiters on + // unrelated fences or GPU-only signals never force redundant global visibility refreshes. + void signaled(Semaphore semaphore, std::uint64_t value, std::uint64_t vis_seq = 0) { + bool advanced = false; + std::vector> dropped_pins; + { + std::lock_guard lock(mutex_); + const auto it = fences_.find(semaphore); + if (it != fences_.end()) { + FenceState& fs = it->second; + if (fs.value < value) { + fs.value = value; + advanced = true; + } + if (vis_seq) { + if (vis_seq > fs.max_cpu_vis_seq) fs.max_cpu_vis_seq = vis_seq; + if (!fs.cpu_vis.empty() && fs.cpu_vis.back().first == value) { + if (vis_seq > fs.cpu_vis.back().second) fs.cpu_vis.back().second = vis_seq; + } else { + if (fs.cpu_vis.size() >= kMaxFenceVisHistory) fs.cpu_vis.pop_front(); + fs.cpu_vis.emplace_back(value, vis_seq); + } + } + } + if (!relays_.empty()) { + for (auto rit = relays_.begin(); rit != relays_.end();) { + if (rit->gate_sem == semaphore && rit->gate_val <= value) { + for (Wait& w : rit->replacements) + if (w.pin) dropped_pins.push_back(std::move(w.pin)); + rit = relays_.erase(rit); + } else { + ++rit; + } + } + relay_count_.store(relays_.size(), std::memory_order_release); + } + } + dropped_pins.clear(); + if (advanced && any_held()) signaled_unpumped_.store(true, std::memory_order_release); + } + + // Retroactively redirects any queued, pending, or held wait on `(gate_sem, gate_val)` to `replacements` + // (GPU-to-GPU timeline waits, never GPU-signaling `gate_sem`), then calls pump_ready() so newly-unblocked held + // ops release immediately. When `consume_on_substitute` is true (single-owner gate fences), the redirect entry is + // pruned immediately once substituted (or once consumed by an in-transit lookup_relay). Returns true iff at least + // one existing wait was substituted; when no wait matched yet, the redirect entry remains registered for an + // in-transit lookup_relay() and this call returns false so callers preserve the fallback gate. + bool relay_wait(Semaphore gate_sem, std::uint64_t gate_val, std::span replacements, + bool consume_on_substitute = false) { + if (!gate_sem || !gate_val || replacements.empty()) return false; + for (const Wait& w : replacements) { + if (!w.semaphore || w.semaphore == gate_sem) return false; + } + std::vector> dropped_pins; + { + std::lock_guard lock(mutex_); + const auto fit = fences_.find(gate_sem); + if (fit != fences_.end() && fit->second.value >= gate_val) return false; + for (const WaitRelay& existing : relays_) { + if (existing.gate_sem == gate_sem && existing.gate_val == gate_val) return false; + } + while (relays_.size() >= kMaxRelays) { + for (Wait& w : relays_.front().replacements) + if (w.pin) dropped_pins.push_back(std::move(w.pin)); + relays_.pop_front(); + } + relays_.push_back(WaitRelay{gate_sem, gate_val, + std::vector(replacements.begin(), replacements.end()), + consume_on_substitute}); + relay_count_.store(relays_.size(), std::memory_order_release); + } + dropped_pins.clear(); + + WorkGuard relaying(*this); + bool any_held_updated = false; + bool any_substituted = false; + { + std::shared_lock use(holders_use_mutex_); + for (Holder* holder : snapshot()) { + bool sub = false; + if (holder->apply_wait_relay(gate_sem, gate_val, replacements, sub)) any_held_updated = true; + if (sub) any_substituted = true; + } + } + if (consume_on_substitute && any_substituted) { + { + std::lock_guard lock(mutex_); + for (auto it = relays_.begin(); it != relays_.end(); ++it) { + if (it->gate_sem == gate_sem && it->gate_val == gate_val) { + for (Wait& w : it->replacements) + if (w.pin) dropped_pins.push_back(std::move(w.pin)); + relays_.erase(it); + relay_count_.store(relays_.size(), std::memory_order_release); + break; + } + } + } + dropped_pins.clear(); + } + if (any_held_updated || (any_substituted && any_held())) { + if (any_held()) signaled_unpumped_.store(true, std::memory_order_release); + pump_ready(); + } + return any_substituted; + } + + // Checks whether `(gate_sem, gate_val)` has an active wait redirect (catching waits in transit between an async + // inbox pop and state_mutex_). Lock-free fast path when no redirects are active. + bool lookup_relay(Semaphore gate_sem, std::uint64_t gate_val, std::vector& out) { + if (!gate_sem || !gate_val || relay_count_.load(std::memory_order_acquire) == 0) return false; + std::lock_guard lock(mutex_); + for (auto it = relays_.begin(); it != relays_.end(); ++it) { + if (it->gate_sem == gate_sem && it->gate_val == gate_val) { + if (it->consume_on_substitute) { + out = std::move(it->replacements); + relays_.erase(it); + relay_count_.store(relays_.size(), std::memory_order_release); + } else { + out = it->replacements; + } + return true; + } + } + return false; + } + + std::size_t active_relay_count() const noexcept { return relay_count_.load(std::memory_order_acquire); } + + // Minimum CPU visibility epoch established by a CPU Fence::Signal that reached `wait_value` on `semaphore` + // (0 when `semaphore` has never received a CPU signal). + std::uint64_t signaled_vis_seq(Semaphore semaphore, std::uint64_t wait_value) const { std::lock_guard lock(mutex_); const auto it = fences_.find(semaphore); - if (it != fences_.end() && it->second < value) it->second = value; + if (it == fences_.end() || it->second.max_cpu_vis_seq == 0) return 0; + const FenceState& fs = it->second; + for (const auto& [sig_val, seq] : fs.cpu_vis) { + if (sig_val >= wait_value) return seq; + } + return fs.max_cpu_vis_seq; } // A queue is about to submit a Signal of `value`; call inside the device submit lock, and record the value with @@ -90,21 +379,21 @@ class QueueHolds { bool would_signal(Semaphore semaphore, std::uint64_t value) const { std::lock_guard lock(mutex_); const auto it = fences_.find(semaphore); - return it == fences_.end() || it->second < value; + return it == fences_.end() || it->second.value < value; } // The highest Signal submitted for the fence (or set by the CPU); 0 for an unknown semaphore. std::uint64_t submitted_value(Semaphore semaphore) const { std::lock_guard lock(mutex_); const auto it = fences_.find(semaphore); - return it == fences_.end() ? 0 : it->second; + return it == fences_.end() ? 0 : it->second.value; } // true when no submitted Signal reaches `value` yet. Unknown semaphores are satisfied. bool pending(Semaphore semaphore, std::uint64_t value) const { std::lock_guard lock(mutex_); const auto it = fences_.find(semaphore); - return it != fences_.end() && it->second < value; + return it != fences_.end() && it->second.value < value; } void attach(Holder* holder) { @@ -116,12 +405,16 @@ class QueueHolds { void detach(Holder* holder) { { std::lock_guard pump(pump_mutex_); - std::lock_guard lock(mutex_); - for (auto it = holders_.begin(); it != holders_.end(); ++it) - if (*it == holder) { - holders_.erase(it); - break; - } + { + std::lock_guard lock(mutex_); + for (auto it = holders_.begin(); it != holders_.end(); ++it) + if (*it == holder) { + holders_.erase(it); + break; + } + } + // Wait for any concurrent has_progress() reader holding a snapshot that still names `holder`. + std::unique_lock use(holders_use_mutex_); } pump_ready(); } @@ -134,39 +427,83 @@ class QueueHolds { // last of them, or right here if none is held. Callbacks of one owner run in registration order. Used by the // presenter: a Present queued behind held work shows what that work draws. void after_held(const void* owner, std::function fn) { + const std::uint64_t seq = current_seq(); { std::lock_guard lock(mutex_); - barriers_.push_back({owner, current_seq(), std::move(fn)}); + barriers_.push_back({owner, seq, std::move(fn)}); barrier_count_.fetch_add(1, std::memory_order_acq_rel); } + if (seq) { + std::shared_lock use(holders_use_mutex_); + for (Holder* holder : snapshot()) holder->note_barrier(seq); + } pump_ready(); } - // Drops the callbacks of `owner` that have not run, and waits for one that is running. + // Drops the callbacks of `owner` that have not run, and waits for any in-flight callback on the barrier thread. + // Lock order: pump_mutex_ -> barrier_mutex_ -> mutex_ (mutex_ is always leaf; barrier callbacks run unlocked). void cancel_after(const void* owner) { + std::int64_t removed_ready = 0; { - std::lock_guard pump(pump_mutex_); + std::lock_guard bl(barrier_mutex_); std::lock_guard lock(mutex_); - for (auto it = barriers_.begin(); it != barriers_.end();) - if (it->owner == owner) { - it = barriers_.erase(it); - barrier_count_.fetch_sub(1, std::memory_order_acq_rel); - } else { - ++it; + auto erase_from = [&](std::deque& q, bool is_ready) { + for (auto it = q.begin(); it != q.end();) { + if (it->owner == owner) { + it = q.erase(it); + barrier_count_.fetch_sub(1, std::memory_order_acq_rel); + if (is_ready) ++removed_ready; + } else { + ++it; + } } + }; + erase_from(barriers_, false); + erase_from(ready_barriers_, true); + if (removed_ready) update_active_barrier_min_seq_locked(); + } + if (removed_ready) { + barrier_drained_cv_.notify_all(); + work_changed(-removed_ready); + } + // Wait for any already-popped callback currently running on the dedicated barrier thread. + if (!in_barrier()) { + std::unique_lock bl(barrier_mutex_); + barrier_drained_cv_.wait(bl, [this] { return !barrier_running_; }); } pump_ready(); } + // Waits until every satisfied barrier with `barrier.seq <= seq` that is queued in ready_barriers_ or currently + // running on the dedicated barrier thread has finished executing. Lock-free fast path when no matching barrier is + // active. Never waits on unsatisfied barriers still in barriers_. + void wait_barriers_drained(std::uint64_t seq) { + if (in_barrier()) return; + const std::uint64_t min_p1 = active_barrier_min_seq_.load(std::memory_order_acquire); + if (min_p1 == 0 || (min_p1 - 1) > seq) return; + std::unique_lock bl(barrier_mutex_); + barrier_drained_cv_.wait(bl, [this, seq] { + std::lock_guard lock(mutex_); + if (barrier_running_ && running_barrier_seq_ <= seq) return false; + if (!ready_barriers_.empty() && ready_barriers_.front().seq <= seq) return false; + return true; + }); + } + // Held operations over all queues, for the cheap "is there anything to do" test. void held_changed(std::int64_t delta) { held_.fetch_add(delta, std::memory_order_acq_rel); } bool any_held() const { return held_.load(std::memory_order_acquire) > 0; } // Releases every held operation that has become ready, in dependency order: a release can submit a Signal - // that makes another queue's front ready, so passes repeat until one finds nothing new. Then the callbacks - // whose held work is all gone. + // that makes another queue's front ready, so passes repeat until one finds nothing new. Satisfied barriers + // (Present / after_held()) are handed off in strict FIFO order to the dedicated barrier-drain thread (keeping + // active_work_ +1 until executed) so callers such as the list-value releaser never stall on Present. void pump_ready() { - if (!any_held() && barrier_count_.load(std::memory_order_acquire) == 0) return; + if (!any_held() && barrier_count_.load(std::memory_order_acquire) == 0) { + signaled_unpumped_.store(false, std::memory_order_release); + return; + } + WorkGuard pumping(*this); dirty_.store(true, std::memory_order_release); if (in_pump()) return; // a release on this thread submitted a Signal: the running pass will go again for (;;) { @@ -174,12 +511,23 @@ class QueueHolds { if (!pump) return; // another thread is releasing and will see dirty_ in_pump() = true; while (dirty_.exchange(false, std::memory_order_acq_rel)) { + signaled_unpumped_.store(false, std::memory_order_release); bool progress = true; while (progress) { progress = false; - for (Holder* holder : snapshot()) progress |= holder->release_ready(); + for (Holder* holder : snapshot()) { + if (holder->release_ready()) { + progress = true; + if (collect_ready_barriers()) { + // Satisfied barriers were handed to the barrier thread; yield to let post-barrier + // work drain on the next pass (which waits via wait_barriers_drained()). + dirty_.store(true, std::memory_order_release); + break; + } + } + } } - run_barriers(); + (void)collect_ready_barriers(); } in_pump() = false; pump.unlock(); @@ -188,9 +536,25 @@ class QueueHolds { } private: + static constexpr std::size_t kMaxFenceVisHistory = 32; + static constexpr std::size_t kMaxRelays = 256; + + struct WaitRelay { + Semaphore gate_sem{}; + std::uint64_t gate_val = 0; + std::vector replacements; + bool consume_on_substitute = false; + }; + + struct FenceState { + std::uint64_t value = 0; + std::uint64_t max_cpu_vis_seq = 0; + std::deque> cpu_vis; // (signaled_value, vis_seq) + }; + struct Barrier { - const void* owner; - std::uint64_t seq; + const void* owner = nullptr; + std::uint64_t seq = 0; std::function fn; }; @@ -199,44 +563,145 @@ class QueueHolds { return pumping; } + static bool& in_barrier() { + static thread_local bool running = false; + return running; + } + std::vector snapshot() const { std::lock_guard lock(mutex_); return holders_; } - // Called with pump_mutex_ held. A callback runs when no held operation is older than the moment it was asked. - void run_barriers() { + // Called with both barrier_mutex_ and mutex_ held. Stores (min_seq + 1) of any running/ready barrier, or 0 if none. + void update_active_barrier_min_seq_locked() noexcept { + bool any = false; + std::uint64_t min_seq = UINT64_MAX; + if (barrier_running_) { + any = true; + min_seq = running_barrier_seq_; + } + if (!ready_barriers_.empty()) { + if (!any || ready_barriers_.front().seq < min_seq) min_seq = ready_barriers_.front().seq; + any = true; + } + active_barrier_min_seq_.store(any ? (min_seq == UINT64_MAX ? UINT64_MAX : min_seq + 1) : 0, + std::memory_order_release); + } + + // Called with pump_mutex_ held. Moves every satisfied barrier from barriers_ to ready_barriers_ in strict FIFO + // order, increments active_work_ (+1 per ready barrier so has_progress() stays true until executed), and wakes the + // dedicated barrier thread. True when at least one barrier became ready. + bool collect_ready_barriers() { + bool moved = false; for (;;) { - Barrier front; + const void* owner = nullptr; + std::uint64_t seq = 0; { std::lock_guard lock(mutex_); - if (barriers_.empty()) return; - front = barriers_.front(); + if (barriers_.empty()) break; + owner = barriers_.front().owner; + seq = barriers_.front().seq; } + bool blocked = false; for (Holder* holder : snapshot()) { const std::uint64_t oldest = holder->oldest_held_seq(); - if (oldest && oldest <= front.seq) return; + if (oldest && oldest <= seq) { + blocked = true; + break; + } } + if (blocked) break; { + std::lock_guard bl(barrier_mutex_); std::lock_guard lock(mutex_); - if (barriers_.empty() || barriers_.front().seq != front.seq || barriers_.front().owner != front.owner) + if (barriers_.empty() || barriers_.front().seq != seq || barriers_.front().owner != owner) continue; // cancelled meanwhile + ready_barriers_.push_back(std::move(barriers_.front())); barriers_.pop_front(); + work_changed(1); + update_active_barrier_min_seq_locked(); + if (!barrier_thread_.joinable() && !barrier_stop_) { + barrier_thread_ = std::thread([this] { barrier_worker(); }); + } + moved = true; + } + } + if (moved) barrier_cv_.notify_one(); + return moved; + } + + // Dedicated thread that executes satisfied ready_barriers_ in strict FIFO order without blocking pump_ready() or + // the list-value releaser. Keeps active_work_ +1 across each barrier and signals barrier_drained_cv_ on completion. + void barrier_worker() { + in_barrier() = true; + struct InBarrierGuard { + ~InBarrierGuard() { in_barrier() = false; } + } guard; + for (;;) { + Barrier next; + { + std::unique_lock bl(barrier_mutex_); + barrier_cv_.wait(bl, [this] { + std::lock_guard lock(mutex_); + return !ready_barriers_.empty() || barrier_stop_; + }); + std::lock_guard lock(mutex_); + if (ready_barriers_.empty()) { + if (barrier_stop_) return; + continue; + } + next = std::move(ready_barriers_.front()); + ready_barriers_.pop_front(); barrier_count_.fetch_sub(1, std::memory_order_acq_rel); + barrier_running_ = true; + running_barrier_seq_ = next.seq; + update_active_barrier_min_seq_locked(); + } + try { + if (next.fn) next.fn(); + } catch (...) { } - front.fn(); + next.fn = {}; // release captured objects outside locks + { + std::lock_guard bl(barrier_mutex_); + std::lock_guard lock(mutex_); + barrier_running_ = false; + running_barrier_seq_ = 0; + update_active_barrier_min_seq_locked(); + } + barrier_drained_cv_.notify_all(); + work_changed(-1); } } - mutable std::mutex mutex_; // leaf: fences_, holders_ and barriers_ - std::mutex pump_mutex_; // one releasing thread; held across release_ready(), so detach() waits for it - std::unordered_map fences_; + static bool has_progress_thunk(const void* owner) { + return static_cast(owner)->has_progress(); + } + + mutable std::mutex mutex_; // leaf: fences_, holders_, barriers_, ready_barriers_ + std::mutex pump_mutex_; // one releasing thread; held across release_ready(), never across barrier callbacks + std::mutex barrier_mutex_; // guards barrier_thread_, barrier_running_, barrier_stop_, and barrier CVs + std::condition_variable barrier_cv_; + std::condition_variable barrier_drained_cv_; + std::thread barrier_thread_; + bool barrier_running_ = false; + bool barrier_stop_ = false; + std::uint64_t running_barrier_seq_ = 0; + std::atomic active_barrier_min_seq_{0}; // 0 if none, else min(seq)+1 of running/ready barriers + mutable std::shared_mutex holders_use_mutex_; // shared by has_progress(), unique in detach() after erasing holder + std::unordered_map fences_; + std::deque relays_; + std::atomic relay_count_{0}; std::vector holders_; std::deque barriers_; + std::deque ready_barriers_; std::atomic held_{0}; std::atomic barrier_count_{0}; std::atomic seq_{0}; std::atomic dirty_{false}; + std::atomic active_work_{0}; + std::atomic signaled_unpumped_{false}; }; } // namespace leonida diff --git a/runtime/src/shader_library.h b/runtime/src/shader_library.h index 7699dfbb0d..9210e9cfc5 100644 --- a/runtime/src/shader_library.h +++ b/runtime/src/shader_library.h @@ -22,6 +22,7 @@ #include #include #include +#include #include #include #include @@ -876,6 +877,20 @@ struct ShaderEntry { // The S#s the shader builds from immediates (the index's literal_samplers): no heap slot names them, so a // pipeline that uses the shader registers them in the bindless set itself (docs/design.md, Literal samplers). std::vector> literal_samplers; + // Optional SPIR-V SpecId base for literal_samplers (index.json `literal_sampler_spec_base`). Absent when the + // shader was translated without literal-sampler specialization constants. + std::optional literal_sampler_spec_base; + // Whether the shader performs coherent (glc/dlc) buffer/global loads (index.json `reads_glc_buffer`). False when + // absent (older shader packs). + bool reads_glc_buffer = false; + // Whether the shader can write buffer/global/flat memory (index.json `writes_buffer`). Defaults to true when + // absent so older shader packs conservatively keep full mirror write-back. + bool has_writes_buffer = false; + bool writes_buffer = true; + // Optional descriptor slot list written by buffer stores (index.json `buffer_write_slots`: array of ints or + // `"dynamic"`). + bool buffer_write_slots_dynamic = false; + std::vector buffer_write_slots; // Mesh shaders: the output array sizes the SPIR-V declares (OutputVertices / OutputPrimitivesEXT), checked // against the device's maxMeshOutputVertices / maxMeshOutputPrimitives when a pipeline is created. 0: not given. std::uint32_t max_vertices = 0; @@ -923,6 +938,19 @@ inline DescriptorTableLayout majority_descriptor_table_layout(const DescriptorTa return census.tagged > 0 ? DescriptorTableLayout::tagged : DescriptorTableLayout::plain; } +// Which modules read a T#'s bindless index from its dword 6 (gfx10_descriptors.h, tsharp_index_word; tools/rdna2spirv.py +// TSHARP_INDEX): index.json meta `"tsharp_index": "dword6"`. Such a module takes the index of a T# it loaded from a +// heap from that word and nothing else, so the layer must write it into every heap it keeps; a module translated +// before has no key and finds its T#s by their words in the hash table, which the written word changes (the copy's +// dword 6 is no longer the title's). The device writes the word when any module reads it, and says so when modules +// of both kinds are loaded: the older ones then miss the T#s of the heaps and read the fallback, so a library is to be +// translated by one translator. +struct TsharpIndexCensus { + std::size_t dword6 = 0; + std::size_t none = 0; + std::size_t total() const { return dword6 + none; } +}; + // LEONIDA_DESCRIPTOR_TABLE=plain|tagged overrides the modules' vote. False when `value` is null, empty or not one // of the two layouts (an unrecognised value is ignored rather than failing startup). inline bool descriptor_table_layout_from_env(const char* value, DescriptorTableLayout* layout) { @@ -953,6 +981,29 @@ inline bool descriptor_hash_kind_from_env(const char* value, DescriptorHashKind* return false; } +// How the loaded modules read a buffer V#'s 48-bit base (docs/design.md, "Heap-relative buffer device addresses"): a +// module translated since the marker sign-extends it (index.json meta `"vsharp_base_sign_extended": true`), so a base +// may name a buffer on either side of heap_base, within 2^47; an older module zero-extends it, so only a positive +// offset below 2^48 reaches the right address. One zero-extending module is enough to forbid a negative offset: the +// runtime has one heap_base and one V# encoding for every shader. +struct VsharpBaseCensus { + std::size_t sign_extended = 0; + std::size_t zero_extended = 0; + std::size_t total() const { return sign_extended + zero_extended; } + // Every loaded module reads the base sign-extended (true with none loaded: nothing reads it the old way). + bool signed_offsets() const { return zero_extended == 0; } +}; + +// Whether every loaded module declared `"writes_buffer"` in its index.json metadata. Passive write-back gating is +// enabled only when at least one module is loaded and none omits the key, preserving conservative write-back for +// older shader packs and shader-less tests. +struct WritesBufferCensus { + std::size_t present = 0; + std::size_t missing = 0; + std::size_t total() const { return present + missing; } + bool all_present() const { return present > 0 && missing == 0; } +}; + class ShaderLibrary { public: // Reads /index.json, then the indexes of the programs make_game.py translates from the package's DLLs and the @@ -1015,6 +1066,9 @@ class ShaderLibrary { exe_count_ = 0; descriptor_hash_census_ = {}; descriptor_table_census_ = {}; + tsharp_index_census_ = {}; + vsharp_base_census_ = {}; + writes_buffer_census_ = {}; for (const char* folder : {"fspx", "fspx_gfx"}) { try { const auto ignore = [](const std::string&) { return false; }; @@ -1043,6 +1097,14 @@ class ShaderLibrary { DescriptorTableLayout descriptor_table_layout() const { return majority_descriptor_table_layout(descriptor_table_census_); } + // The modules that read a T#'s index from its dword 6 (TsharpIndexCensus) and those that do not. + const TsharpIndexCensus& tsharp_index_census() const { return tsharp_index_census_; } + // How the loaded modules read a V#'s 48-bit base: the device names buffers below heap_base (negative offsets) only + // when every one of them sign-extends it. + const VsharpBaseCensus& vsharp_base_census() const { return vsharp_base_census_; } + // Whether every loaded module declared `"writes_buffer"` in its index.json metadata. + const WritesBufferCensus& writes_buffer_census() const { return writes_buffer_census_; } + bool all_have_writes_buffer_meta() const { return writes_buffer_census_.all_present(); } // Entries loaded from /fspx/index.json and /library/index.json. A corpus of RPF containers never // reaches these: their programs come from FidelityFX DLLs and the pipeline library, so callers comparing reached // entries with size() must leave them out. @@ -1105,7 +1167,9 @@ class ShaderLibrary { const auto first = spirv(*all.front()); const auto runtime_metadata = [](const ShaderEntry& e) { return std::tie(e.binding_count, e.push_constant_bytes, e.local_size, e.lds_bytes, e.uses_code_base, - e.wave64, e.subgroup_size, e.wave64_exchange, e.literal_samplers); + e.wave64, e.subgroup_size, e.wave64_exchange, e.literal_samplers, + e.literal_sampler_spec_base, e.reads_glc_buffer, e.has_writes_buffer, e.writes_buffer, + e.buffer_write_slots_dynamic, e.buffer_write_slots); }; for (std::size_t i = 1; i < all.size(); ++i) { if (first.empty() || runtime_metadata(*all[i]) != runtime_metadata(*all.front()) || @@ -1223,6 +1287,9 @@ class ShaderLibrary { exe_count_ = 0; descriptor_hash_census_ = {}; descriptor_table_census_ = {}; + tsharp_index_census_ = {}; + vsharp_base_census_ = {}; + writes_buffer_census_ = {}; } for (const auto& [name, meta] : root.object) { const Json* hash = meta.find("fssm_sha256"); @@ -1309,6 +1376,27 @@ class ShaderLibrary { e.literal_samplers.push_back(words); } } + if (const Json* lsb = meta.find("literal_sampler_spec_base"); + lsb && lsb->kind == Json::Kind::number && lsb->number >= 0 && lsb->number <= 4294967295.0) + e.literal_sampler_spec_base = u32(lsb); + if (const Json* glc = meta.find("reads_glc_buffer"); glc && glc->kind == Json::Kind::boolean) + e.reads_glc_buffer = glc->boolean; + if (const Json* wb = meta.find("writes_buffer"); wb && wb->kind == Json::Kind::boolean) { + e.has_writes_buffer = true; + e.writes_buffer = wb->boolean; + ++writes_buffer_census_.present; + } else { + ++writes_buffer_census_.missing; + } + if (const Json* bws = meta.find("buffer_write_slots")) { + if (bws->kind == Json::Kind::string && bws->string == "dynamic") { + e.buffer_write_slots_dynamic = true; + } else if (bws->kind == Json::Kind::array) { + for (const Json& item : bws->array) + if (item.kind == Json::Kind::number && item.number >= 0 && item.number <= 4294967295.0) + e.buffer_write_slots.push_back(u32(&item)); + } + } e.max_vertices = u32(meta.find("max_vertices")); e.max_primitives = u32(meta.find("max_primitives")); // Which finalizer this module's shader probes the descriptor table with (descriptor_table.h). Absent, or not @@ -1325,6 +1413,16 @@ class ShaderLibrary { ++descriptor_table_census_.tagged; else ++descriptor_table_census_.plain; + // Whether this module reads a T#'s index from its dword 6 (TsharpIndexCensus). Absent is the hash lookup. + if (const Json* ti = meta.find("tsharp_index"); ti && ti->kind == Json::Kind::string && ti->string == "dword6") + ++tsharp_index_census_.dword6; + else + ++tsharp_index_census_.none; + // How this module reads a V#'s 48-bit base (VsharpBaseCensus). Absent is the old zero extension. + if (const Json* sx = meta.find("vsharp_base_sign_extended"); sx && sx->kind == Json::Kind::boolean && sx->boolean) + ++vsharp_base_census_.sign_extended; + else + ++vsharp_base_census_.zero_extended; if (by_fspx) fspx_entries_[{e.stage, e.fspx_code_sha256}].push_back(e); if (by_fssm) entries_[{e.stage, e.fssm_sha256}].push_back(std::move(e)); if (by_fspx && (prefix == "fspx/" || prefix == "library/")) ++fspx_count_; @@ -1349,6 +1447,9 @@ class ShaderLibrary { Entries fspx_entries_; DescriptorHashCensus descriptor_hash_census_; DescriptorTableCensus descriptor_table_census_; + TsharpIndexCensus tsharp_index_census_; + VsharpBaseCensus vsharp_base_census_; + WritesBufferCensus writes_buffer_census_; }; } // namespace leonida diff --git a/runtime/src/shadow_keep.h b/runtime/src/shadow_keep.h index a59752b494..1d74e5b658 100644 --- a/runtime/src/shadow_keep.h +++ b/runtime/src/shadow_keep.h @@ -10,17 +10,166 @@ #include #include #include +#if defined(__AVX2__) +#include +#elif defined(__x86_64__) || defined(_M_X64) +#include +#endif namespace leonida::shadow_keep { inline constexpr std::size_t kPiece = 256; // The sum of `n` bytes, never 0 (0 is "not known": the piece is copied at its next look). -// Four independent lanes over 32 bytes a step, so the multiplies do not wait on each other: about the speed of a -// copy (one chained lane read about 3.6 GB/s on an RTX 5080 machine's CPU, a copy about 18 GB/s). +// On AVX2 (x86-64-v3): 4 x 256-bit accumulators (128 bytes/step, XXH3-style vpmuludq + vpaddq with distinct evolving +// per-lane keys — 2 iterations per 256-byte piece). +// On baseline x86-64 (SSE2): 4 x 128-bit accumulators (64 bytes/step). +// Portable fallback: four independent 64-bit lanes over 32 bytes a step. inline std::uint64_t sum_of(const std::uint8_t* bytes, std::size_t n) { constexpr std::uint64_t k = 0xff51afd7ed558ccdull; const auto rotl = [](std::uint64_t x, int r) { return (x << r) | (x >> (64 - r)); }; +#if defined(__AVX2__) + const __m256i k_step = _mm256_set_epi32( + static_cast(0x9e3779b1u), static_cast(0x85ebca77u), static_cast(0xc2b2ae3du), + static_cast(0x27d4eb2fu), static_cast(0x165667b1u), static_cast(0x9e3779f9u), + static_cast(0x85ebca87u), static_cast(0xc2b2ae63u)); + __m256i k0 = _mm256_set_epi32( + static_cast(0x165667b1u), static_cast(0x9e3779f9u), static_cast(0x85ebca87u), + static_cast(0xc2b2ae63u), static_cast(0x27d4eb4fu), static_cast(0x165667c5u), + static_cast(0xff51afd7u), static_cast(0xed558ccdu)); + __m256i k1 = _mm256_set_epi32( + static_cast(0xc4ceb9feu), static_cast(0x1a85ec53u), static_cast(0x94d049bbu), + static_cast(0x133111ebu), static_cast(0xbf58476du), static_cast(0x1ce4e5b9u), + static_cast(0x9e3779b9u), static_cast(0x7f4a7c15u)); + __m256i k2 = _mm256_set_epi32( + static_cast(0xa0761d65u), static_cast(0xe7037ed1u), static_cast(0x8ebc6af1u), + static_cast(0x589965cbu), static_cast(0x1d8e4e27u), static_cast(0xeb44accbu), + static_cast(0x2d358dcdu), static_cast(0x75567b7bu)); + __m256i k3 = _mm256_set_epi32( + static_cast(0xd6e8feb9u), static_cast(0x6659fd93u), static_cast(0xb492b66fu), + static_cast(0x3c79ac49u), static_cast(0xf1357aeau), static_cast(0x60642e2bu), + static_cast(0x49d4f7b3u), static_cast(0xc8b86a9du)); + + __m256i s0 = _mm256_set_epi64x( + static_cast(0x27d4eb2f165667c5ull), static_cast(0x165667b19e3779f9ull), + static_cast(0xc2b2ae3d27d4eb4full), static_cast(0x9e3779b97f4a7c15ull ^ n)); + __m256i s1 = _mm256_set_epi64x( + static_cast(0x94d049bb133111ebull), static_cast(0xc4ceb9fe1a85ec53ull), + static_cast(0xff51afd7ed558ccdull), static_cast(0x85ebca77c2b2ae63ull)); + __m256i s2 = _mm256_set_epi64x( + static_cast(0xbf58476d1ce4e5b9ull), static_cast(0xa0761d6478bd642full), + static_cast(0xe7037ed1a0b428dbull), static_cast(0x8ebc6af09c88c6e3ull)); + __m256i s3 = _mm256_set_epi64x( + static_cast(0x589965cc75374cc3ull), static_cast(0x1d8e4e27c47d124full), + static_cast(0xeb44accab455d165ull), static_cast(0xd6e8feb86659fd93ull)); + + const auto lane = [](__m256i acc, __m256i data, __m256i key) -> __m256i { + const __m256i x = _mm256_xor_si256(data, key); + const __m256i x_hi = _mm256_srli_epi64(x, 32); + const __m256i prod = _mm256_mul_epu32(x, x_hi); + const __m256i d_swap = _mm256_shuffle_epi32(data, _MM_SHUFFLE(1, 0, 3, 2)); + return _mm256_add_epi64(_mm256_add_epi64(acc, d_swap), prod); + }; + + std::size_t i = 0; + for (; i + 128 <= n; i += 128) { + const auto* p = reinterpret_cast(bytes + i); + s0 = lane(s0, _mm256_loadu_si256(p + 0), k0); + s1 = lane(s1, _mm256_loadu_si256(p + 1), k1); + s2 = lane(s2, _mm256_loadu_si256(p + 2), k2); + s3 = lane(s3, _mm256_loadu_si256(p + 3), k3); + k0 = _mm256_add_epi32(k0, k_step); + k1 = _mm256_add_epi32(k1, k_step); + k2 = _mm256_add_epi32(k2, k_step); + k3 = _mm256_add_epi32(k3, k_step); + } + + const __m256i m0 = _mm256_xor_si256(s0, _mm256_shuffle_epi32(s2, _MM_SHUFFLE(1, 0, 3, 2))); + const __m256i m1 = _mm256_xor_si256(s1, _mm256_shuffle_epi32(s3, _MM_SHUFFLE(1, 0, 3, 2))); + const __m128i f0 = _mm_xor_si128(_mm256_castsi256_si128(m0), + _mm_shuffle_epi32(_mm256_extracti128_si256(m0, 1), _MM_SHUFFLE(1, 0, 3, 2))); + const __m128i f1 = _mm_xor_si128(_mm256_castsi256_si128(m1), + _mm_shuffle_epi32(_mm256_extracti128_si256(m1, 1), _MM_SHUFFLE(1, 0, 3, 2))); + std::uint64_t a[4]; + _mm_storeu_si128(reinterpret_cast<__m128i*>(a), f0); + _mm_storeu_si128(reinterpret_cast<__m128i*>(a + 2), f1); + + for (; i < n; i += 8) { + std::uint64_t v = 0; + std::memcpy(&v, bytes + i, n - i < 8 ? n - i : 8); + a[0] = rotl(a[0] ^ v, 31) * k; + } + std::uint64_t h = (a[0] * k) ^ rotl(a[1] * 0xc4ceb9fe1a85ec53ull, 17) ^ + rotl(a[2] * 0x94d049bb133111ebull, 29) ^ rotl(a[3] * 0xbf58476d1ce4e5b9ull, 47); + h ^= h >> 33; + h *= 0xc4ceb9fe1a85ec53ull; + h ^= h >> 29; + return h | 1; // 0: not known +#elif defined(__x86_64__) || defined(_M_X64) + const __m128i k_step = + _mm_set_epi32(static_cast(0x9e3779b1u), static_cast(0x85ebca77u), static_cast(0xc2b2ae3du), + static_cast(0x27d4eb2fu)); + __m128i k0 = + _mm_set_epi32(static_cast(0x165667b1u), static_cast(0x9e3779f9u), static_cast(0x85ebca87u), + static_cast(0xc2b2ae63u)); + __m128i k1 = + _mm_set_epi32(static_cast(0x27d4eb4fu), static_cast(0x165667c5u), static_cast(0xff51afd7u), + static_cast(0xed558ccdu)); + __m128i k2 = + _mm_set_epi32(static_cast(0xc4ceb9feu), static_cast(0x1a85ec53u), static_cast(0x94d049bbu), + static_cast(0x133111ebu)); + __m128i k3 = + _mm_set_epi32(static_cast(0xbf58476du), static_cast(0x1ce4e5b9u), static_cast(0x9e3779b9u), + static_cast(0x7f4a7c15u)); + + __m128i s0 = _mm_set_epi64x(static_cast(0xc2b2ae3d27d4eb4full), + static_cast(0x9e3779b97f4a7c15ull ^ n)); + __m128i s1 = _mm_set_epi64x(static_cast(0x165667b19e3779f9ull), + static_cast(0x27d4eb2f165667c5ull)); + __m128i s2 = _mm_set_epi64x(static_cast(0x85ebca77c2b2ae63ull), + static_cast(0xff51afd7ed558ccdull)); + __m128i s3 = _mm_set_epi64x(static_cast(0xc4ceb9fe1a85ec53ull), + static_cast(0x94d049bb133111ebull)); + + const auto lane = [](__m128i acc, __m128i data, __m128i key) -> __m128i { + const __m128i x = _mm_xor_si128(data, key); + const __m128i x_hi = _mm_srli_epi64(x, 32); + const __m128i prod = _mm_mul_epu32(x, x_hi); + const __m128i d_swap = _mm_shuffle_epi32(data, _MM_SHUFFLE(1, 0, 3, 2)); + return _mm_add_epi64(_mm_add_epi64(acc, d_swap), prod); + }; + + std::size_t i = 0; + for (; i + 64 <= n; i += 64) { + const auto* p = reinterpret_cast(bytes + i); + s0 = lane(s0, _mm_loadu_si128(p + 0), k0); + s1 = lane(s1, _mm_loadu_si128(p + 1), k1); + s2 = lane(s2, _mm_loadu_si128(p + 2), k2); + s3 = lane(s3, _mm_loadu_si128(p + 3), k3); + k0 = _mm_add_epi32(k0, k_step); + k1 = _mm_add_epi32(k1, k_step); + k2 = _mm_add_epi32(k2, k_step); + k3 = _mm_add_epi32(k3, k_step); + } + + const __m128i m0 = _mm_xor_si128(s0, _mm_shuffle_epi32(s2, _MM_SHUFFLE(1, 0, 3, 2))); + const __m128i m1 = _mm_xor_si128(s1, _mm_shuffle_epi32(s3, _MM_SHUFFLE(1, 0, 3, 2))); + std::uint64_t a[4]; + _mm_storeu_si128(reinterpret_cast<__m128i*>(a), m0); + _mm_storeu_si128(reinterpret_cast<__m128i*>(a + 2), m1); + + for (; i < n; i += 8) { + std::uint64_t v = 0; + std::memcpy(&v, bytes + i, n - i < 8 ? n - i : 8); + a[0] = rotl(a[0] ^ v, 31) * k; + } + std::uint64_t h = (a[0] * k) ^ rotl(a[1] * 0xc4ceb9fe1a85ec53ull, 17) ^ + rotl(a[2] * 0x94d049bb133111ebull, 29) ^ rotl(a[3] * 0xbf58476d1ce4e5b9ull, 47); + h ^= h >> 33; + h *= 0xc4ceb9fe1a85ec53ull; + h ^= h >> 29; + return h | 1; // 0: not known +#else std::uint64_t a0 = 0x9e3779b97f4a7c15ull ^ n, a1 = 0xc2b2ae3d27d4eb4full, a2 = 0x165667b19e3779f9ull, a3 = 0x27d4eb2f165667c5ull; std::size_t i = 0; @@ -42,6 +191,377 @@ inline std::uint64_t sum_of(const std::uint8_t* bytes, std::size_t n) { h *= 0xc4ceb9fe1a85ec53ull; h ^= h >> 29; return h | 1; // 0: not known +#endif +} + +// Computes `count` consecutive 256-byte piece hashes `out[i] = sum_of(base + i * kPiece, kPiece)` with hoisted SIMD +// constants. Guaranteed bit-for-bit identical to calling `sum_of(base + i * kPiece, kPiece)` in a loop. +inline void sum_of_batch_256(const std::uint8_t* base, std::size_t count, std::uint64_t* out) { + if (!count) return; + constexpr std::uint64_t k = 0xff51afd7ed558ccdull; + const auto rotl = [](std::uint64_t x, int r) { return (x << r) | (x >> (64 - r)); }; +#if defined(__AVX2__) + const __m256i k_step = _mm256_set_epi32( + static_cast(0x9e3779b1u), static_cast(0x85ebca77u), static_cast(0xc2b2ae3du), + static_cast(0x27d4eb2fu), static_cast(0x165667b1u), static_cast(0x9e3779f9u), + static_cast(0x85ebca87u), static_cast(0xc2b2ae63u)); + const __m256i k0_0 = _mm256_set_epi32( + static_cast(0x165667b1u), static_cast(0x9e3779f9u), static_cast(0x85ebca87u), + static_cast(0xc2b2ae63u), static_cast(0x27d4eb4fu), static_cast(0x165667c5u), + static_cast(0xff51afd7u), static_cast(0xed558ccdu)); + const __m256i k1_0 = _mm256_set_epi32( + static_cast(0xc4ceb9feu), static_cast(0x1a85ec53u), static_cast(0x94d049bbu), + static_cast(0x133111ebu), static_cast(0xbf58476du), static_cast(0x1ce4e5b9u), + static_cast(0x9e3779b9u), static_cast(0x7f4a7c15u)); + const __m256i k2_0 = _mm256_set_epi32( + static_cast(0xa0761d65u), static_cast(0xe7037ed1u), static_cast(0x8ebc6af1u), + static_cast(0x589965cbu), static_cast(0x1d8e4e27u), static_cast(0xeb44accbu), + static_cast(0x2d358dcdu), static_cast(0x75567b7bu)); + const __m256i k3_0 = _mm256_set_epi32( + static_cast(0xd6e8feb9u), static_cast(0x6659fd93u), static_cast(0xb492b66fu), + static_cast(0x3c79ac49u), static_cast(0xf1357aeau), static_cast(0x60642e2bu), + static_cast(0x49d4f7b3u), static_cast(0xc8b86a9du)); + const __m256i k0_1 = _mm256_add_epi32(k0_0, k_step); + const __m256i k1_1 = _mm256_add_epi32(k1_0, k_step); + const __m256i k2_1 = _mm256_add_epi32(k2_0, k_step); + const __m256i k3_1 = _mm256_add_epi32(k3_0, k_step); + + const __m256i s0_init = _mm256_set_epi64x( + static_cast(0x27d4eb2f165667c5ull), static_cast(0x165667b19e3779f9ull), + static_cast(0xc2b2ae3d27d4eb4full), static_cast(0x9e3779b97f4a7c15ull ^ kPiece)); + const __m256i s1_init = _mm256_set_epi64x( + static_cast(0x94d049bb133111ebull), static_cast(0xc4ceb9fe1a85ec53ull), + static_cast(0xff51afd7ed558ccdull), static_cast(0x85ebca77c2b2ae63ull)); + const __m256i s2_init = _mm256_set_epi64x( + static_cast(0xbf58476d1ce4e5b9ull), static_cast(0xa0761d6478bd642full), + static_cast(0xe7037ed1a0b428dbull), static_cast(0x8ebc6af09c88c6e3ull)); + const __m256i s3_init = _mm256_set_epi64x( + static_cast(0x589965cc75374cc3ull), static_cast(0x1d8e4e27c47d124full), + static_cast(0xeb44accab455d165ull), static_cast(0xd6e8feb86659fd93ull)); + + const auto lane = [](__m256i acc, __m256i data, __m256i key) -> __m256i { + const __m256i x = _mm256_xor_si256(data, key); + const __m256i x_hi = _mm256_srli_epi64(x, 32); + const __m256i prod = _mm256_mul_epu32(x, x_hi); + const __m256i d_swap = _mm256_shuffle_epi32(data, _MM_SHUFFLE(1, 0, 3, 2)); + return _mm256_add_epi64(_mm256_add_epi64(acc, d_swap), prod); + }; + + for (std::size_t idx = 0; idx < count; ++idx) { + const auto* p = reinterpret_cast(base + idx * kPiece); + __m256i s0 = lane(s0_init, _mm256_loadu_si256(p + 0), k0_0); + __m256i s1 = lane(s1_init, _mm256_loadu_si256(p + 1), k1_0); + __m256i s2 = lane(s2_init, _mm256_loadu_si256(p + 2), k2_0); + __m256i s3 = lane(s3_init, _mm256_loadu_si256(p + 3), k3_0); + + s0 = lane(s0, _mm256_loadu_si256(p + 4), k0_1); + s1 = lane(s1, _mm256_loadu_si256(p + 5), k1_1); + s2 = lane(s2, _mm256_loadu_si256(p + 6), k2_1); + s3 = lane(s3, _mm256_loadu_si256(p + 7), k3_1); + + const __m256i m0 = _mm256_xor_si256(s0, _mm256_shuffle_epi32(s2, _MM_SHUFFLE(1, 0, 3, 2))); + const __m256i m1 = _mm256_xor_si256(s1, _mm256_shuffle_epi32(s3, _MM_SHUFFLE(1, 0, 3, 2))); + const __m128i f0 = _mm_xor_si128( + _mm256_castsi256_si128(m0), + _mm_shuffle_epi32(_mm256_extracti128_si256(m0, 1), _MM_SHUFFLE(1, 0, 3, 2))); + const __m128i f1 = _mm_xor_si128( + _mm256_castsi256_si128(m1), + _mm_shuffle_epi32(_mm256_extracti128_si256(m1, 1), _MM_SHUFFLE(1, 0, 3, 2))); + std::uint64_t a[4]; + _mm_storeu_si128(reinterpret_cast<__m128i*>(a), f0); + _mm_storeu_si128(reinterpret_cast<__m128i*>(a + 2), f1); + + std::uint64_t h = (a[0] * k) ^ rotl(a[1] * 0xc4ceb9fe1a85ec53ull, 17) ^ + rotl(a[2] * 0x94d049bb133111ebull, 29) ^ rotl(a[3] * 0xbf58476d1ce4e5b9ull, 47); + h ^= h >> 33; + h *= 0xc4ceb9fe1a85ec53ull; + h ^= h >> 29; + out[idx] = h | 1; + } +#elif defined(__x86_64__) || defined(_M_X64) + const __m128i k_step = + _mm_set_epi32(static_cast(0x9e3779b1u), static_cast(0x85ebca77u), static_cast(0xc2b2ae3du), + static_cast(0x27d4eb2fu)); + const __m128i k0_init = + _mm_set_epi32(static_cast(0x165667b1u), static_cast(0x9e3779f9u), static_cast(0x85ebca87u), + static_cast(0xc2b2ae63u)); + const __m128i k1_init = + _mm_set_epi32(static_cast(0x27d4eb4fu), static_cast(0x165667c5u), static_cast(0xff51afd7u), + static_cast(0xed558ccdu)); + const __m128i k2_init = + _mm_set_epi32(static_cast(0xc4ceb9feu), static_cast(0x1a85ec53u), static_cast(0x94d049bbu), + static_cast(0x133111ebu)); + const __m128i k3_init = + _mm_set_epi32(static_cast(0xbf58476du), static_cast(0x1ce4e5b9u), static_cast(0x9e3779b9u), + static_cast(0x7f4a7c15u)); + + const __m128i s0_init = _mm_set_epi64x(static_cast(0xc2b2ae3d27d4eb4full), + static_cast(0x9e3779b97f4a7c15ull ^ kPiece)); + const __m128i s1_init = _mm_set_epi64x(static_cast(0x165667b19e3779f9ull), + static_cast(0x27d4eb2f165667c5ull)); + const __m128i s2_init = _mm_set_epi64x(static_cast(0x85ebca77c2b2ae63ull), + static_cast(0xff51afd7ed558ccdull)); + const __m128i s3_init = _mm_set_epi64x(static_cast(0xc4ceb9fe1a85ec53ull), + static_cast(0x94d049bb133111ebull)); + + const auto lane = [](__m128i acc, __m128i data, __m128i key) -> __m128i { + const __m128i x = _mm_xor_si128(data, key); + const __m128i x_hi = _mm_srli_epi64(x, 32); + const __m128i prod = _mm_mul_epu32(x, x_hi); + const __m128i d_swap = _mm_shuffle_epi32(data, _MM_SHUFFLE(1, 0, 3, 2)); + return _mm_add_epi64(_mm_add_epi64(acc, d_swap), prod); + }; + + for (std::size_t idx = 0; idx < count; ++idx) { + const auto* p = reinterpret_cast(base + idx * kPiece); + __m128i k0 = k0_init, k1 = k1_init, k2 = k2_init, k3 = k3_init; + __m128i s0 = s0_init, s1 = s1_init, s2 = s2_init, s3 = s3_init; + for (std::size_t step = 0; step < 4; ++step, p += 4) { + s0 = lane(s0, _mm_loadu_si128(p + 0), k0); + s1 = lane(s1, _mm_loadu_si128(p + 1), k1); + s2 = lane(s2, _mm_loadu_si128(p + 2), k2); + s3 = lane(s3, _mm_loadu_si128(p + 3), k3); + k0 = _mm_add_epi32(k0, k_step); + k1 = _mm_add_epi32(k1, k_step); + k2 = _mm_add_epi32(k2, k_step); + k3 = _mm_add_epi32(k3, k_step); + } + const __m128i m0 = _mm_xor_si128(s0, _mm_shuffle_epi32(s2, _MM_SHUFFLE(1, 0, 3, 2))); + const __m128i m1 = _mm_xor_si128(s1, _mm_shuffle_epi32(s3, _MM_SHUFFLE(1, 0, 3, 2))); + std::uint64_t a[4]; + _mm_storeu_si128(reinterpret_cast<__m128i*>(a), m0); + _mm_storeu_si128(reinterpret_cast<__m128i*>(a + 2), m1); + + std::uint64_t h = (a[0] * k) ^ rotl(a[1] * 0xc4ceb9fe1a85ec53ull, 17) ^ + rotl(a[2] * 0x94d049bb133111ebull, 29) ^ rotl(a[3] * 0xbf58476d1ce4e5b9ull, 47); + h ^= h >> 33; + h *= 0xc4ceb9fe1a85ec53ull; + h ^= h >> 29; + out[idx] = h | 1; + } +#else + constexpr std::uint64_t a0_init = 0x9e3779b97f4a7c15ull ^ kPiece; + constexpr std::uint64_t a1_init = 0xc2b2ae3d27d4eb4full; + constexpr std::uint64_t a2_init = 0x165667b19e3779f9ull; + constexpr std::uint64_t a3_init = 0x27d4eb2f165667c5ull; + for (std::size_t idx = 0; idx < count; ++idx) { + const std::uint8_t* bytes = base + idx * kPiece; + std::uint64_t a0 = a0_init, a1 = a1_init, a2 = a2_init, a3 = a3_init; + for (std::size_t i = 0; i < kPiece; i += 32) { + std::uint64_t v[4]; + std::memcpy(v, bytes + i, 32); + a0 = rotl(a0 ^ v[0], 31) * k; + a1 = rotl(a1 ^ v[1], 31) * k; + a2 = rotl(a2 ^ v[2], 31) * k; + a3 = rotl(a3 ^ v[3], 31) * k; + } + std::uint64_t h = a0 ^ rotl(a1, 17) ^ rotl(a2, 29) ^ rotl(a3, 47); + h ^= h >> 33; + h *= 0xc4ceb9fe1a85ec53ull; + h ^= h >> 29; + out[idx] = h | 1; + } +#endif +} + +// Fused copy + 256-byte piece hashing: copies `count * kPiece` bytes from `from` to `to` while computing +// `out[i] = sum_of(from + i * kPiece, kPiece)` in registers (one read pass over `from`, zero second pass over `to`). +// Guaranteed bit-for-bit identical to `std::memcpy(to, from, count * kPiece)` + `sum_of_batch_256(to, count, out)`. +// Intentionally NOT noexcept so SEH wrappers under /EHsc can invoke it inside a __try frame. +inline void copy_and_sum_256(std::uint8_t* to, const std::uint8_t* from, std::size_t count, std::uint64_t* out) { + if (!count) return; + constexpr std::uint64_t k = 0xff51afd7ed558ccdull; + const auto rotl = [](std::uint64_t x, int r) { return (x << r) | (x >> (64 - r)); }; +#if defined(__AVX2__) + const __m256i k_step = _mm256_set_epi32( + static_cast(0x9e3779b1u), static_cast(0x85ebca77u), static_cast(0xc2b2ae3du), + static_cast(0x27d4eb2fu), static_cast(0x165667b1u), static_cast(0x9e3779f9u), + static_cast(0x85ebca87u), static_cast(0xc2b2ae63u)); + const __m256i k0_0 = _mm256_set_epi32( + static_cast(0x165667b1u), static_cast(0x9e3779f9u), static_cast(0x85ebca87u), + static_cast(0xc2b2ae63u), static_cast(0x27d4eb4fu), static_cast(0x165667c5u), + static_cast(0xff51afd7u), static_cast(0xed558ccdu)); + const __m256i k1_0 = _mm256_set_epi32( + static_cast(0xc4ceb9feu), static_cast(0x1a85ec53u), static_cast(0x94d049bbu), + static_cast(0x133111ebu), static_cast(0xbf58476du), static_cast(0x1ce4e5b9u), + static_cast(0x9e3779b9u), static_cast(0x7f4a7c15u)); + const __m256i k2_0 = _mm256_set_epi32( + static_cast(0xa0761d65u), static_cast(0xe7037ed1u), static_cast(0x8ebc6af1u), + static_cast(0x589965cbu), static_cast(0x1d8e4e27u), static_cast(0xeb44accbu), + static_cast(0x2d358dcdu), static_cast(0x75567b7bu)); + const __m256i k3_0 = _mm256_set_epi32( + static_cast(0xd6e8feb9u), static_cast(0x6659fd93u), static_cast(0xb492b66fu), + static_cast(0x3c79ac49u), static_cast(0xf1357aeau), static_cast(0x60642e2bu), + static_cast(0x49d4f7b3u), static_cast(0xc8b86a9du)); + const __m256i k0_1 = _mm256_add_epi32(k0_0, k_step); + const __m256i k1_1 = _mm256_add_epi32(k1_0, k_step); + const __m256i k2_1 = _mm256_add_epi32(k2_0, k_step); + const __m256i k3_1 = _mm256_add_epi32(k3_0, k_step); + + const __m256i s0_init = _mm256_set_epi64x( + static_cast(0x27d4eb2f165667c5ull), static_cast(0x165667b19e3779f9ull), + static_cast(0xc2b2ae3d27d4eb4full), static_cast(0x9e3779b97f4a7c15ull ^ kPiece)); + const __m256i s1_init = _mm256_set_epi64x( + static_cast(0x94d049bb133111ebull), static_cast(0xc4ceb9fe1a85ec53ull), + static_cast(0xff51afd7ed558ccdull), static_cast(0x85ebca77c2b2ae63ull)); + const __m256i s2_init = _mm256_set_epi64x( + static_cast(0xbf58476d1ce4e5b9ull), static_cast(0xa0761d6478bd642full), + static_cast(0xe7037ed1a0b428dbull), static_cast(0x8ebc6af09c88c6e3ull)); + const __m256i s3_init = _mm256_set_epi64x( + static_cast(0x589965cc75374cc3ull), static_cast(0x1d8e4e27c47d124full), + static_cast(0xeb44accab455d165ull), static_cast(0xd6e8feb86659fd93ull)); + + const auto lane = [](__m256i acc, __m256i data, __m256i key) -> __m256i { + const __m256i x = _mm256_xor_si256(data, key); + const __m256i x_hi = _mm256_srli_epi64(x, 32); + const __m256i prod = _mm256_mul_epu32(x, x_hi); + const __m256i d_swap = _mm256_shuffle_epi32(data, _MM_SHUFFLE(1, 0, 3, 2)); + return _mm256_add_epi64(_mm256_add_epi64(acc, d_swap), prod); + }; + + for (std::size_t idx = 0; idx < count; ++idx) { + const auto* p = reinterpret_cast(from + idx * kPiece); + auto* d = reinterpret_cast<__m256i*>(to + idx * kPiece); + const __m256i v0 = _mm256_loadu_si256(p + 0); + const __m256i v1 = _mm256_loadu_si256(p + 1); + const __m256i v2 = _mm256_loadu_si256(p + 2); + const __m256i v3 = _mm256_loadu_si256(p + 3); + _mm256_storeu_si256(d + 0, v0); + _mm256_storeu_si256(d + 1, v1); + _mm256_storeu_si256(d + 2, v2); + _mm256_storeu_si256(d + 3, v3); + __m256i s0 = lane(s0_init, v0, k0_0); + __m256i s1 = lane(s1_init, v1, k1_0); + __m256i s2 = lane(s2_init, v2, k2_0); + __m256i s3 = lane(s3_init, v3, k3_0); + + const __m256i v4 = _mm256_loadu_si256(p + 4); + const __m256i v5 = _mm256_loadu_si256(p + 5); + const __m256i v6 = _mm256_loadu_si256(p + 6); + const __m256i v7 = _mm256_loadu_si256(p + 7); + _mm256_storeu_si256(d + 4, v4); + _mm256_storeu_si256(d + 5, v5); + _mm256_storeu_si256(d + 6, v6); + _mm256_storeu_si256(d + 7, v7); + s0 = lane(s0, v4, k0_1); + s1 = lane(s1, v5, k1_1); + s2 = lane(s2, v6, k2_1); + s3 = lane(s3, v7, k3_1); + + const __m256i m0 = _mm256_xor_si256(s0, _mm256_shuffle_epi32(s2, _MM_SHUFFLE(1, 0, 3, 2))); + const __m256i m1 = _mm256_xor_si256(s1, _mm256_shuffle_epi32(s3, _MM_SHUFFLE(1, 0, 3, 2))); + const __m128i f0 = _mm_xor_si128( + _mm256_castsi256_si128(m0), + _mm_shuffle_epi32(_mm256_extracti128_si256(m0, 1), _MM_SHUFFLE(1, 0, 3, 2))); + const __m128i f1 = _mm_xor_si128( + _mm256_castsi256_si128(m1), + _mm_shuffle_epi32(_mm256_extracti128_si256(m1, 1), _MM_SHUFFLE(1, 0, 3, 2))); + std::uint64_t a[4]; + _mm_storeu_si128(reinterpret_cast<__m128i*>(a), f0); + _mm_storeu_si128(reinterpret_cast<__m128i*>(a + 2), f1); + + std::uint64_t h = (a[0] * k) ^ rotl(a[1] * 0xc4ceb9fe1a85ec53ull, 17) ^ + rotl(a[2] * 0x94d049bb133111ebull, 29) ^ rotl(a[3] * 0xbf58476d1ce4e5b9ull, 47); + h ^= h >> 33; + h *= 0xc4ceb9fe1a85ec53ull; + h ^= h >> 29; + out[idx] = h | 1; + } +#elif defined(__x86_64__) || defined(_M_X64) + const __m128i k_step = + _mm_set_epi32(static_cast(0x9e3779b1u), static_cast(0x85ebca77u), static_cast(0xc2b2ae3du), + static_cast(0x27d4eb2fu)); + const __m128i k0_init = + _mm_set_epi32(static_cast(0x165667b1u), static_cast(0x9e3779f9u), static_cast(0x85ebca87u), + static_cast(0xc2b2ae63u)); + const __m128i k1_init = + _mm_set_epi32(static_cast(0x27d4eb4fu), static_cast(0x165667c5u), static_cast(0xff51afd7u), + static_cast(0xed558ccdu)); + const __m128i k2_init = + _mm_set_epi32(static_cast(0xc4ceb9feu), static_cast(0x1a85ec53u), static_cast(0x94d049bbu), + static_cast(0x133111ebu)); + const __m128i k3_init = + _mm_set_epi32(static_cast(0xbf58476du), static_cast(0x1ce4e5b9u), static_cast(0x9e3779b9u), + static_cast(0x7f4a7c15u)); + + const __m128i s0_init = _mm_set_epi64x(static_cast(0xc2b2ae3d27d4eb4full), + static_cast(0x9e3779b97f4a7c15ull ^ kPiece)); + const __m128i s1_init = _mm_set_epi64x(static_cast(0x165667b19e3779f9ull), + static_cast(0x27d4eb2f165667c5ull)); + const __m128i s2_init = _mm_set_epi64x(static_cast(0x85ebca77c2b2ae63ull), + static_cast(0xff51afd7ed558ccdull)); + const __m128i s3_init = _mm_set_epi64x(static_cast(0xc4ceb9fe1a85ec53ull), + static_cast(0x94d049bb133111ebull)); + + const auto lane = [](__m128i acc, __m128i data, __m128i key) -> __m128i { + const __m128i x = _mm_xor_si128(data, key); + const __m128i x_hi = _mm_srli_epi64(x, 32); + const __m128i prod = _mm_mul_epu32(x, x_hi); + const __m128i d_swap = _mm_shuffle_epi32(data, _MM_SHUFFLE(1, 0, 3, 2)); + return _mm_add_epi64(_mm_add_epi64(acc, d_swap), prod); + }; + + for (std::size_t idx = 0; idx < count; ++idx) { + const auto* p = reinterpret_cast(from + idx * kPiece); + auto* d = reinterpret_cast<__m128i*>(to + idx * kPiece); + __m128i k0 = k0_init, k1 = k1_init, k2 = k2_init, k3 = k3_init; + __m128i s0 = s0_init, s1 = s1_init, s2 = s2_init, s3 = s3_init; + for (std::size_t step = 0; step < 4; ++step, p += 4, d += 4) { + const __m128i v0 = _mm_loadu_si128(p + 0); + const __m128i v1 = _mm_loadu_si128(p + 1); + const __m128i v2 = _mm_loadu_si128(p + 2); + const __m128i v3 = _mm_loadu_si128(p + 3); + _mm_storeu_si128(d + 0, v0); + _mm_storeu_si128(d + 1, v1); + _mm_storeu_si128(d + 2, v2); + _mm_storeu_si128(d + 3, v3); + s0 = lane(s0, v0, k0); + s1 = lane(s1, v1, k1); + s2 = lane(s2, v2, k2); + s3 = lane(s3, v3, k3); + k0 = _mm_add_epi32(k0, k_step); + k1 = _mm_add_epi32(k1, k_step); + k2 = _mm_add_epi32(k2, k_step); + k3 = _mm_add_epi32(k3, k_step); + } + const __m128i m0 = _mm_xor_si128(s0, _mm_shuffle_epi32(s2, _MM_SHUFFLE(1, 0, 3, 2))); + const __m128i m1 = _mm_xor_si128(s1, _mm_shuffle_epi32(s3, _MM_SHUFFLE(1, 0, 3, 2))); + std::uint64_t a[4]; + _mm_storeu_si128(reinterpret_cast<__m128i*>(a), m0); + _mm_storeu_si128(reinterpret_cast<__m128i*>(a + 2), m1); + + std::uint64_t h = (a[0] * k) ^ rotl(a[1] * 0xc4ceb9fe1a85ec53ull, 17) ^ + rotl(a[2] * 0x94d049bb133111ebull, 29) ^ rotl(a[3] * 0xbf58476d1ce4e5b9ull, 47); + h ^= h >> 33; + h *= 0xc4ceb9fe1a85ec53ull; + h ^= h >> 29; + out[idx] = h | 1; + } +#else + constexpr std::uint64_t a0_init = 0x9e3779b97f4a7c15ull ^ kPiece; + constexpr std::uint64_t a1_init = 0xc2b2ae3d27d4eb4full; + constexpr std::uint64_t a2_init = 0x165667b19e3779f9ull; + constexpr std::uint64_t a3_init = 0x27d4eb2f165667c5ull; + for (std::size_t idx = 0; idx < count; ++idx) { + const std::uint8_t* bytes = from + idx * kPiece; + std::uint8_t* dst = to + idx * kPiece; + std::uint64_t a0 = a0_init, a1 = a1_init, a2 = a2_init, a3 = a3_init; + for (std::size_t i = 0; i < kPiece; i += 32) { + std::uint64_t v[4]; + std::memcpy(v, bytes + i, 32); + std::memcpy(dst + i, v, 32); + a0 = rotl(a0 ^ v[0], 31) * k; + a1 = rotl(a1 ^ v[1], 31) * k; + a2 = rotl(a2 ^ v[2], 31) * k; + a3 = rotl(a3 ^ v[3], 31) * k; + } + std::uint64_t h = a0 ^ rotl(a1, 17) ^ rotl(a2, 29) ^ rotl(a3, 47); + h ^= h >> 33; + h *= 0xc4ceb9fe1a85ec53ull; + h ^= h >> 29; + out[idx] = h | 1; + } +#endif } // `bytes` holds the title's bytes [va, va + n) as read now. sums[k] is the sum of the piece at base + k * kPiece @@ -51,7 +571,7 @@ template void copy_changed(const std::uint8_t* bytes, std::uintptr_t va, std::size_t n, std::uint64_t* sums, std::uintptr_t base, Copy&& copy) { for (std::size_t off = 0; off < n;) { - const std::size_t piece = std::min(n - off, kPiece - ((va + off) & (kPiece - 1))); + const std::size_t piece = (std::min)(n - off, std::size_t(kPiece - ((va + off) & (kPiece - 1)))); std::uint64_t& known = sums[(va + off - base) / kPiece]; const std::uint64_t sum = sum_of(bytes + off, piece); if (sum != known) { diff --git a/runtime/src/submit_phases.h b/runtime/src/submit_phases.h index dfaf8ce959..ce4572af06 100644 --- a/runtime/src/submit_phases.h +++ b/runtime/src/submit_phases.h @@ -42,6 +42,7 @@ struct Totals { std::atomic last_log{0}; std::atomic presents{0}; // frames the presenter showed (VulkanPresenter), since the last line std::atomic present_serial{0}; // the same, never reset (LEONIDA_REFRESH_PER_FRAME) + std::atomic present_calls{0}; // TitleCall(part_present) entries: splits async submit merging at Present // Threads whose innermost Scope is this phase now, and when the first of them entered it (steady_clock). Counted // per phase, since queues submit from several threads: one value would go stale when their scopes overlap. std::atomic active[kCount]{}; @@ -80,12 +81,186 @@ inline std::int64_t period_ns() { return value; } +// ---- The per-frame line ("submit frame") and the floor ("submit floor"), every LEONIDA_SUBMIT_FRAME_SECONDS -------- +// +// The phases above, summed per presented frame instead of per submission, and split by who spent them: the title's +// threads (whoever calls into the layer) or our own (a WorkerScope marks a stretch of one of our threads). Added to +// them, what the phase line leaves out, from title calls timed where they enter the layer (TitleCall, the outermost +// one on a thread): the time of an ExecuteCommandLists outside the phases (list unwrapping, the console's list-value +// waits and writes, the queue lock), of the queue's Signal and Wait, and of the present. Inside those, two parts are +// also counted on their own: the vkQueueSubmit calls and the waits for a contended lock (lock_wait), which lie inside +// the phases or the calls above and are not added again. A frame ends at each present the presenter takes. +// +// The floor: the submissions in which nothing changed - no console heap slot or page copied, no shadow page copied, +// no geometry uploaded, no texture filled and no pipeline built (note_change, counted process-wide, so a change made +// by another thread during a submission takes it out of the floor too) - with their phases, average and least. +enum Part : unsigned { + part_lists, // ExecuteCommandLists outside the phases + part_fences, // queue Signal and Wait, fence Signal from the CPU + part_present, // the present (with its wait for a swapchain image) + part_submit_call, // inside the above: vkQueueSubmit + part_lock_wait, // inside the above: waiting for a contended lock of the submission path + kParts +}; +inline constexpr unsigned kOuterParts = part_present + 1; // the parts that add to the title threads' total +enum Worker : unsigned { + worker_submit, // LEONIDA_SUBMIT_ASYNC: the queue's worker (the replay leaves the title's thread) + worker_texture_reads, // the title texture refresh's read threads + worker_texture_fill, // the slot-70 texture filler + worker_heap_resolver, // the console heap resolver (LEONIDA_CONSOLE_HEAP_GPU) + worker_geometry, // LEONIDA_GEOMETRY_ASYNC: the geometry refresher + worker_value_pump, // the console list values' pump and releaser + worker_fence_thread, // the fence dispatcher's callbacks + kWorkers +}; +enum Change : unsigned { change_slots, change_pages, change_geometry, change_textures, change_pipelines, kChanges }; + +inline const char* part_name(unsigned p) { + static const char* const names[kParts] = {"lists", "fences", "present", "vkQueueSubmit", "lock waits"}; + return p < kParts ? names[p] : "?"; +} +inline const char* worker_name(unsigned w) { + static const char* const names[kWorkers] = {"submit", "texture-reads", "texture-fill", "heap-resolver", + "geometry", "value-pump", "fence-thread"}; + return w < kWorkers ? names[w] : "?"; +} + +struct FrameTotals { + std::atomic phase_ns[kCount]{}; // title threads + std::atomic part_ns[kParts]{}; // title threads + std::atomic worker_ns[kWorkers]{}; + std::atomic worker_lock_wait_ns{0}; // contended lock_timed / single-flight waits on our threads + std::atomic submissions[3]{}; // by queue kind: direct, compute, copy + std::atomic frames{0}; + std::atomic current_ns{0}; // the title threads' time since the last present + std::atomic worst_ns{0}; // the most of a frame in this window + std::atomic last_log{0}; + std::atomic changes[kChanges]{}; // never reset: a submission compares them before and after + // The floor: submissions with no change, their phases and their least total; and every submission's total. + std::atomic floor_count{0}, floor_ns[kCount]{}, floor_min_ns{UINT64_MAX}; + std::atomic all_count{0}, all_ns{0}; +}; +inline FrameTotals& frame_totals() { + static FrameTotals t; + return t; +} + +// What one thread is doing, for the split above. Trivially destructible (no TLS callback in gta6rt.exe). +struct ThreadState { + int worker = -1; // a WorkerScope's worker, -1 on a title thread + unsigned calls = 0; // TitleCalls open on this thread + unsigned submissions = 0; // execute_now calls open on this thread (begin_submission) + std::uint64_t phase_ns = 0; // phases this thread added since it started, for TitleCall + std::uint64_t submission_ns[kCount] = {}; // the outermost open submission's phases + std::uint64_t changes_at = 0; // the change count when it began +}; +inline ThreadState& thread_state() { + thread_local ThreadState state; + return state; +} + +inline std::uint64_t change_count() { + std::uint64_t n = 0; + for (const auto& c : frame_totals().changes) n += c.load(std::memory_order_relaxed); + return n; +} +// Something a submission had to bring up to date: the submissions running now leave the floor. +inline void note_change(Change c) { frame_totals().changes[c].fetch_add(1, std::memory_order_relaxed); } + +// Time a title thread spent in the layer outside the phases (an outer part), or inside them (an inner part). +inline void add_part(Part p, std::uint64_t ns) { + ThreadState& s = thread_state(); + if (s.worker >= 0) { + if (p == part_lock_wait) frame_totals().worker_lock_wait_ns.fetch_add(ns, std::memory_order_relaxed); + return; // ours: a worker's time is its WorkerScope's + } + FrameTotals& f = frame_totals(); + f.part_ns[p].fetch_add(ns, std::memory_order_relaxed); + if (p < kOuterParts) f.current_ns.fetch_add(ns, std::memory_order_relaxed); +} + +// The title's call into the layer this thread is in, timed when it is the outermost: its time less the phases inside +// it is `part`'s. +struct TitleCall { + Part part; + std::int64_t start = 0; + std::uint64_t phases_at = 0; + explicit TitleCall(Part p) : part(p) { + if (p == part_present) totals().present_calls.fetch_add(1, std::memory_order_release); + ThreadState& s = thread_state(); + if (s.calls++ || s.worker >= 0) return; + start = now_ns(); + phases_at = s.phase_ns; + } + ~TitleCall() { + ThreadState& s = thread_state(); + --s.calls; + if (!start) return; + const std::uint64_t all = std::uint64_t(now_ns() - start), inside = s.phase_ns - phases_at; + add_part(part, all > inside ? all - inside : 0); + } + TitleCall(const TitleCall&) = delete; + TitleCall& operator=(const TitleCall&) = delete; +}; + +// A stretch of one of our own threads: its time is `worker`'s, and the phases inside it are not the title's. +struct WorkerScope { + Worker worker; + int outer; + std::int64_t start = now_ns(); + explicit WorkerScope(Worker w) : worker(w), outer(thread_state().worker) { thread_state().worker = int(w); } + ~WorkerScope() { + thread_state().worker = outer; + if (outer < 0) frame_totals().worker_ns[worker].fetch_add(std::uint64_t(now_ns() - start), std::memory_order_relaxed); + } + WorkerScope(const WorkerScope&) = delete; + WorkerScope& operator=(const WorkerScope&) = delete; +}; + +// Locks `lock`, and counts the wait as part_lock_wait when it was held by someone else. +template +inline void lock_timed(Lock& lock) { + if (lock.try_lock()) return; + const std::int64_t start = now_ns(); + lock.lock(); + add_part(part_lock_wait, std::uint64_t(now_ns() - start)); +} + +inline void frame_add_phase(Phase p, std::uint64_t ns) { + ThreadState& s = thread_state(); + s.phase_ns += ns; + if (s.submissions) s.submission_ns[p] += ns; + if (s.worker >= 0) return; + FrameTotals& f = frame_totals(); + f.phase_ns[p].fetch_add(ns, std::memory_order_relaxed); + f.current_ns.fetch_add(ns, std::memory_order_relaxed); +} + +// At each present the presenter takes: the frame's title-thread time so far, and the window's worst. +inline void frame_presented() { + FrameTotals& f = frame_totals(); + f.frames.fetch_add(1, std::memory_order_relaxed); + const std::uint64_t ns = f.current_ns.exchange(0, std::memory_order_relaxed); + std::uint64_t worst = f.worst_ns.load(std::memory_order_relaxed); + while (ns > worst && !f.worst_ns.compare_exchange_weak(worst, ns, std::memory_order_relaxed)) { + } +} + +// At the start of VulkanQueue::execute_now, before its first phase: the floor's per-submission sums begin. +inline void begin_submission() { + ThreadState& s = thread_state(); + if (s.submissions++) return; + for (auto& ns : s.submission_ns) ns = 0; + s.changes_at = change_count(); +} + inline void add(Phase p, std::uint64_t ns) { Totals& t = totals(); t.ns[p].fetch_add(ns, std::memory_order_relaxed); std::uint64_t m = t.max_ns[p].load(std::memory_order_relaxed); while (ns > m && !t.max_ns[p].compare_exchange_weak(m, ns, std::memory_order_relaxed)) { } + frame_add_phase(p, ns); } // Times its own lifetime into a phase. @@ -134,6 +309,104 @@ inline Running running() { return r; } +inline std::int64_t frame_period_ns() { + static const std::int64_t value = [] { + const char* text = std::getenv("LEONIDA_SUBMIT_FRAME_SECONDS"); + const unsigned long long s = text && *text ? std::strtoull(text, nullptr, 10) : 10; + return std::int64_t(s) * 1000000000; + }(); + return value; +} + +// The two lines over the window since the last ones, and a new window. `seconds`: the window's length. +inline void frame_lines(double seconds) { + FrameTotals& f = frame_totals(); + const std::uint64_t frames = f.frames.exchange(0, std::memory_order_relaxed); + const double per = frames ? double(frames) : 1.0; // per frame, or the window's totals when none was presented + const char* unit = frames ? "per frame" : "in the window (no frame presented)"; + std::uint64_t subs[3]; + for (unsigned k = 0; k < 3; ++k) subs[k] = f.submissions[k].exchange(0, std::memory_order_relaxed); + double phase[kCount], part[kParts], worker[kWorkers], title = 0, own = 0; + for (unsigned p = 0; p < kCount; ++p) title += phase[p] = double(f.phase_ns[p].exchange(0, std::memory_order_relaxed)) * 1e-6 / per; + for (unsigned p = 0; p < kParts; ++p) { + part[p] = double(f.part_ns[p].exchange(0, std::memory_order_relaxed)) * 1e-6 / per; + if (p < kOuterParts) title += part[p]; + } + for (unsigned w = 0; w < kWorkers; ++w) own += worker[w] = double(f.worker_ns[w].exchange(0, std::memory_order_relaxed)) * 1e-6 / per; + const double worker_lock_wait = + double(f.worker_lock_wait_ns.exchange(0, std::memory_order_relaxed)) * 1e-6 / per; + const double worst = double(f.worst_ns.exchange(0, std::memory_order_relaxed)) * 1e-6; + std::fprintf(stderr, + "[rt] submit frame t=%.0fs: %llu frames in %.1f s; %s: %.1f submissions (direct %.1f, compute %.1f, " + "copy %.1f); title threads %.2f ms: %s %.2f %s %.2f %s %.2f %s %.2f %s %.2f %s %.2f %s %.2f, %s %.2f, " + "%s %.2f, %s %.2f (inside these: %s %.2f, %s %.2f); worst frame %.1f ms; own threads %.2f ms: %s %.2f " + "%s %.2f %s %.2f %s %.2f %s %.2f %s %.2f %s %.2f (lock waits %.2f)\n", + process_age(), static_cast(frames), seconds, unit, + double(subs[0] + subs[1] + subs[2]) / per, double(subs[0]) / per, double(subs[1]) / per, + double(subs[2]) / per, title, name(0), phase[0], name(1), phase[1], name(2), phase[2], name(3), + phase[3], name(4), phase[4], name(5), phase[5], name(6), phase[6], part_name(0), part[0], + part_name(1), part[1], part_name(2), part[2], part_name(3), part[3], part_name(4), part[4], worst, own, + worker_name(0), worker[0], worker_name(1), worker[1], worker_name(2), worker[2], worker_name(3), + worker[3], worker_name(4), worker[4], worker_name(5), worker[5], worker_name(6), worker[6], + worker_lock_wait); + const std::uint64_t floor = f.floor_count.exchange(0, std::memory_order_relaxed); + const std::uint64_t all = f.all_count.exchange(0, std::memory_order_relaxed); + const double all_ms = double(f.all_ns.exchange(0, std::memory_order_relaxed)) * 1e-6; + const std::uint64_t least = f.floor_min_ns.exchange(UINT64_MAX, std::memory_order_relaxed); + double floor_phase[kCount], floor_ms = 0; + for (unsigned p = 0; p < kCount; ++p) + floor_ms += floor_phase[p] = + floor ? double(f.floor_ns[p].exchange(0, std::memory_order_relaxed)) * 1e-6 / double(floor) : 0; + std::fprintf(stderr, + "[rt] submit floor t=%.0fs: %llu of %llu submissions changed nothing (no heap slot, shadow page, " + "geometry, texture or pipeline), %.3f ms each on average (all submissions %.3f), %.3f the least: " + "%s %.3f %s %.3f %s %.3f %s %.3f %s %.3f %s %.3f %s %.3f\n", + process_age(), static_cast(floor), static_cast(all), floor_ms, + all ? all_ms / double(all) : 0.0, floor ? double(least) * 1e-6 : 0.0, name(0), floor_phase[0], + name(1), floor_phase[1], name(2), floor_phase[2], name(3), floor_phase[3], name(4), floor_phase[4], + name(5), floor_phase[5], name(6), floor_phase[6]); +} + +// The end of an execute_now: the submission is counted for the frame line (by queue kind: 0 direct, 1 compute, +// 2 copy) and, when nothing changed while it ran, for the floor; the lines are printed when the period has passed. +inline void frame_submitted(int kind) { + FrameTotals& f = frame_totals(); + f.submissions[kind < 0 || kind > 2 ? 0 : kind].fetch_add(1, std::memory_order_relaxed); + ThreadState& s = thread_state(); + if (s.submissions && !--s.submissions) { + std::uint64_t ns = 0; + for (const std::uint64_t n : s.submission_ns) ns += n; + f.all_count.fetch_add(1, std::memory_order_relaxed); + f.all_ns.fetch_add(ns, std::memory_order_relaxed); + if (change_count() == s.changes_at) { + f.floor_count.fetch_add(1, std::memory_order_relaxed); + for (unsigned p = 0; p < kCount; ++p) f.floor_ns[p].fetch_add(s.submission_ns[p], std::memory_order_relaxed); + std::uint64_t least = f.floor_min_ns.load(std::memory_order_relaxed); + while (ns < least && !f.floor_min_ns.compare_exchange_weak(least, ns, std::memory_order_relaxed)) { + } + } + } + const std::int64_t period = frame_period_ns(); + if (!period) return; + const std::int64_t now = now_ns(); + std::int64_t last = f.last_log.load(std::memory_order_relaxed); + if (!last) { + f.last_log.compare_exchange_strong(last, now, std::memory_order_relaxed); + return; + } + if (now - last < period || !f.last_log.compare_exchange_strong(last, now, std::memory_order_relaxed)) return; + frame_lines(double(now - last) * 1e-9); +} + +// The whole of one VulkanQueue::execute_now, from before its first phase to after its last. +struct Submission { + int kind; + explicit Submission(int k) : kind(k) { begin_submission(); } + ~Submission() { frame_submitted(kind); } + Submission(const Submission&) = delete; + Submission& operator=(const Submission&) = delete; +}; + // After each submission: counts it, and prints the line when the period has passed. One thread wins the line. inline void submitted() { Totals& t = totals(); diff --git a/runtime/src/title_frames.h b/runtime/src/title_frames.h new file mode 100644 index 0000000000..5dc074989b --- /dev/null +++ b/runtime/src/title_frames.h @@ -0,0 +1,180 @@ +#pragma once +// Title memory whose bytes only xmem's frame table holds (title_frames): the host reads and writes it through the +// physical page's own mapping, never through a view at the title's address. +// +// The console queue's CopyPageMappingsBatchX (queue slot 31) remaps physical pages under the stream pool's GPU-only +// alias. On the console it edits GPU page tables only. xmem does the same: the GPU-only page, and the page of the CPU +// view paired with it (title_gpu_views, which the D3D12 layer and DirectStorage read and write in its place), get the +// physical page in xmem's table alone, with no host view (rt::xmem's map_table_page). A host remap there was two +// wineserver round trips per page under Wine. So a host reader of such a page finds it reserved, and reads it here +// instead: the page's address in its section's scratch view, which xmem maps once per allocation. +// +// What changes such a page's bytes, and how its readers learn of it: +// - a remap of the page itself: xmem raises title_memory_map::changed and geometry_writes::notify(replaced) at it, as +// a host remap does; +// - the title's CPU, through any host view of the same physical page: xmem marks a table page aliased +// (title_page_aliases) with those views as its other addresses (geometry_writes::aliases), so the slot-133 +// shadows, the geometry copies and the title texture watch guard it there, as #1867's alias cells do for a page +// mapped twice; +// - a host writer (DirectStorage, the console's value writes): through kernel_writes (title_page_watch.h), which +// writes the frame here and pins and opens the page and its other addresses first, as for a kernel write. +// +// No Windows header: the lookup is xmem's (set_lookup), and the layer's copies only split their ranges here. +#include +#include +#include +#include +#include + +namespace leonida::title_frames { + +constexpr std::uintptr_t kPage = 0x10000; // xmem's physical page + +// A table page's bytes: the page's first byte in its section's scratch view, and what keeps that view mapped. +struct Frame { + std::uint8_t* bytes = nullptr; + std::shared_ptr keep; +}; + +// xmem's side: the frame the 64 KiB page at `page` holds in its table alone (no host view there), or false. Must not +// wait for the process heap, fault or log: the D3D12 layer calls it with its trackers' locks held. +using Lookup = bool (*)(std::uintptr_t page, Frame& out); +// xmem's side: the host addresses the page's physical page is mapped at (its other addresses), appended to `out`. +using Peers = void (*)(std::uintptr_t page, std::vector& out); +// xmem's side: single-lock, zero-shared_ptr run_end and batch-backed checks over g_table_frames. +using RunEnd = std::uintptr_t (*)(std::uintptr_t from, std::uintptr_t to, bool& is_backed); +using BackedBatch = void (*)(const std::uintptr_t* pages, std::uint8_t* out_backed, std::size_t count); + +struct State { + std::atomic lookup{nullptr}; + std::atomic peers{nullptr}; + std::atomic run_end{nullptr}; + std::atomic backed_batch{nullptr}; + // Every page ever given a table entry lies in [lo, hi): a range outside costs a reader two loads, not a lookup. + std::atomic lo{UINTPTR_MAX}, hi{0}; +}; + +inline State& state() { + static State s; + return s; +} + +inline void set_lookup(Lookup lookup, Peers peers, RunEnd run_end_fn = nullptr, BackedBatch backed_batch_fn = nullptr) { + State& s = state(); + s.peers.store(peers, std::memory_order_release); + s.run_end.store(run_end_fn, std::memory_order_release); + s.backed_batch.store(backed_batch_fn, std::memory_order_release); + s.lookup.store(lookup, std::memory_order_release); +} + +// xmem, before the page at `page` gets a table entry: the bounds grow to hold it (they never shrink). +inline void note_page(std::uintptr_t page) { + State& s = state(); + const std::uintptr_t end = page <= UINTPTR_MAX - kPage ? page + kPage : UINTPTR_MAX; + std::uintptr_t lo = s.lo.load(std::memory_order_relaxed); + while (page < lo && !s.lo.compare_exchange_weak(lo, page, std::memory_order_acq_rel)) { + } + std::uintptr_t hi = s.hi.load(std::memory_order_relaxed); + while (end > hi && !s.hi.compare_exchange_weak(hi, end, std::memory_order_acq_rel)) { + } +} + +// Whether [from, to) may hold a table page at all. +inline bool may_hold(std::uintptr_t from, std::uintptr_t to) { + const State& s = state(); + return from < to && s.lookup.load(std::memory_order_acquire) && from < s.hi.load(std::memory_order_acquire) && + s.lo.load(std::memory_order_acquire) < to; +} + +// The byte at `va` of a table page: out.bytes points at it (the rest of its 64 KiB page follows). False when the page +// is not a table page (the host reads it at `va` itself). +inline bool find(std::uintptr_t va, Frame& out) { + out = {}; + if (!may_hold(va, va + 1)) return false; + const Lookup lookup = state().lookup.load(std::memory_order_acquire); + const std::uintptr_t page = va & ~(kPage - 1); + if (!lookup(page, out) || !out.bytes) { + out = {}; + return false; + } + out.bytes += va - page; + return true; +} + +inline bool backed(std::uintptr_t va) { + Frame frame; + return find(va, frame); +} + +// The other host addresses of the table page at `va` (64 KiB-aligned, one per view of its physical page). +inline void peers(std::uintptr_t va, std::vector& out) { + if (const Peers f = state().peers.load(std::memory_order_acquire)) f(va & ~(kPage - 1), out); +} + +// Sets out_backed[k] = 1 iff the 64 KiB page holding pages[k] is a backed table page, else 0. +// Uses xmem's single-lock, zero-shared_ptr batch hook when registered; falls back to backed() otherwise. +inline void backed_batch(const std::uintptr_t* pages, std::uint8_t* out_backed, std::size_t count) { + if (!count) return; + const State& s = state(); + if (!s.lookup.load(std::memory_order_acquire) || + s.lo.load(std::memory_order_acquire) >= s.hi.load(std::memory_order_acquire)) { + for (std::size_t k = 0; k < count; ++k) out_backed[k] = 0; + return; + } + if (const BackedBatch fn = s.backed_batch.load(std::memory_order_acquire)) { + fn(pages, out_backed, count); + return; + } + for (std::size_t k = 0; k < count; ++k) out_backed[k] = backed(pages[k]) ? 1u : 0u; +} + +// The end of the run that starts at `from`, at most `to`, whose pages are all table pages or all not; `is_backed` +// says which. At least one page, or up to `to`. +inline std::uintptr_t run_end(std::uintptr_t from, std::uintptr_t to, bool& is_backed) { + if (!may_hold(from, to)) { + is_backed = false; + return to; + } + if (const RunEnd fn = state().run_end.load(std::memory_order_acquire)) { + return fn(from, to, is_backed); + } + is_backed = backed(from); + std::uintptr_t at = (from & ~(kPage - 1)) + kPage; + while (at < to && at > from && backed(at) == is_backed) at += kPage; + return at < to && at > from ? at : to; +} + +// f(at, n, bytes) for each part of [from, from + size), in order: a table page's part (inside one 64 KiB page) with +// `bytes` its first byte in the frame, or a run of other pages with `bytes` null (the host reads them at `at`). Stops +// at the first f that returns false, and returns false then. +template +bool for_each_part(std::uintptr_t from, std::size_t size, F&& f) { + if (!size) return true; + const std::uintptr_t to = size > UINTPTR_MAX - from ? UINTPTR_MAX : from + size; + if (!may_hold(from, to)) return f(from, std::size_t(to - from), static_cast(nullptr)); + std::uintptr_t host = from; // the start of the host run not handed out yet + for (std::uintptr_t at = from; at < to;) { + const std::uintptr_t page_end = (at & ~(kPage - 1)) + kPage; + const std::uintptr_t end = page_end > at && page_end < to ? page_end : to; + Frame frame; + if (find(at, frame)) { + if (host < at && !f(host, std::size_t(at - host), static_cast(nullptr))) return false; + if (!f(at, std::size_t(end - at), frame.bytes)) return false; + host = end; + } + at = end; + } + return host >= to || f(host, std::size_t(to - host), static_cast(nullptr)); +} + +// The page mirror's change feed (src/title_mirror.h): xmem tells it of every change of what a 64 KiB page of +// src/title_mirror_space.h's range shows, in the order the changes are made: the page shows the physical page whose +// bytes are at `frame` (its section's scratch view, kept alive by `keep`), or nothing (`frame` null). Called with xmem's +// locks held (g_phys_mutex, sometimes the fault lock): the feed only queues, on memory that is not the process heap's. +using Feed = void (*)(void* context, std::uintptr_t page, std::uint8_t* frame, const std::shared_ptr& keep); +// xmem's side: from now on every change goes to `feed` (null: none any more); the pages mapped now are fed first, under +// the same lock as the changes, so none is missed or fed twice. +using Attach = void (*)(void* context, Feed feed); +inline std::atomic attach_fn{nullptr}; + +} // namespace leonida::title_frames diff --git a/runtime/src/title_geometry_watch.h b/runtime/src/title_geometry_watch.h index 7283eccd81..7681ab8999 100644 --- a/runtime/src/title_geometry_watch.h +++ b/runtime/src/title_geometry_watch.h @@ -13,18 +13,56 @@ using Aliases = void (*)(std::uintptr_t, std::vector&); inline std::atomic aliases{}; struct Cell { + static constexpr std::uint64_t kNoMapGen = ~std::uint64_t(0); std::atomic version{1}, mapping{1}; std::array restore{}; + // title_memory_map::generation() observed when `restore` was uniformly armed across all 16 sub-pages (under + // State::mutex). When title_memory_map::generation() still equals armed_map_gen and `restore` is uniform, reopen() + // skips VirtualQuery and calls VirtualProtect directly (falling back on unexpected `old`). + std::uint64_t armed_map_gen = kNoMapGen; + // Shared per-tile uniform protection/state cache (under State::mutex), populated by CellGuard::arm_batch(), + // TitleTextureCells::arm_batch(), and xmem::map_view(). Valid only while `known_mapping == mapping` and no + // title_memory_map change after `known_map_gen` overlapped this tile. + // - `known_state == MEM_COMMIT && known_protect != 0 && known_guarded != 0`: uniform writable tile. + // - `known_state == MEM_COMMIT && known_protect == PAGE_NOACCESS && known_guarded == 0`: uniform no-access tile. + // - `known_state == MEM_RESERVE && known_protect == 0 && known_guarded == 0`: uniform reserved tile (CellGuard + // only; TitleTextureCells must NOT rely on cross-pass MEM_RESERVE because mapped planes may raw-commit). + // NEVER store PAGE_READONLY / PAGE_EXECUTE_READ here (ShadowPages::reopen() reopens RO->RW without map change). + std::uint64_t known_mapping = 0; + std::uint64_t known_map_gen = kNoMapGen; + DWORD known_state = 0; + DWORD known_protect = 0; + DWORD known_guarded = 0; unsigned refs = 0; + // Owners that leave the tile writable and copy it at every submission instead (the page mirror's hot pages, + // src/title_write_policy.h). While it is nonzero the cell guards nothing (arm() does not protect it) and its tile + // counts as written at every look: a subscriber asks for the hot tiles (hot_tiles()) as it takes its queue. One + // guard per page, owned here, whatever the number of copies that read it: an owner that stopped guarding a page + // without saying so left every other copy of it blind (run 64: video planes uploaded until the mirror found their + // pages hot, then never again). + unsigned hot = 0; }; struct ReleaseQueue { std::mutex mutex; host_heap::vector> ranges; std::atomic pending{false}; }; +// A subscriber's list of the tiles notify() changed since it last took them (the title texture refresh's: it +// examines only textures over these tiles). Past kMaxTiles it keeps only `overflow`: every tile counts as changed. +struct WriteQueue { + static constexpr std::size_t kMaxTiles = 65536; + std::mutex mutex; // a leaf lock, taken under State::mutex (in notify) + host_heap::vector tiles; + bool overflow = false; + std::atomic pending{false}; +}; struct State { std::mutex mutex; host_heap::map cells; + host_heap::vector hot; // the tiles of the cells with hot > 0, under mutex + std::atomic hot_count{0}; + std::atomic hot_generation{0}; + host_heap::vector writers; // under mutex std::atomic serial{1}; std::atomic count{0}; // Union of every tile passed to acquire(): [watched_lo, watched_hi). Monotonic; updated under mutex. @@ -48,6 +86,31 @@ inline void unsubscribe(ReleaseQueue& queue) { std::erase(s.subscribers, &queue); } +inline void subscribe_writes(WriteQueue& queue) { + auto& s = state(); + std::lock_guard lock(s.mutex); + if (std::find(s.writers.begin(), s.writers.end(), &queue) == s.writers.end()) s.writers.push_back(&queue); +} + +inline void unsubscribe_writes(WriteQueue& queue) { + auto& s = state(); + std::lock_guard lock(s.mutex); + std::erase(s.writers, &queue); +} + +// The tiles changed since the last call (`overflow`: some were not kept, so every tile counts as changed). +template +inline void take_written(WriteQueue& queue, Out& out, bool& overflow) { + out.clear(); + overflow = false; + if (!queue.pending.load(std::memory_order_acquire)) return; + std::lock_guard lock(queue.mutex); + out.assign(queue.tiles.begin(), queue.tiles.end()); + queue.tiles.clear(); + overflow = std::exchange(queue.overflow, false); + queue.pending.store(false, std::memory_order_release); +} + inline bool has_released(const ReleaseQueue& queue) { return queue.pending.load(std::memory_order_acquire); } @@ -128,6 +191,34 @@ inline Cell* acquire(std::uintptr_t va) { return &c; } +// Acquires one reference per tile in `vas[0..count)` under a single State::mutex hold. +inline void acquire_batch(const std::uintptr_t* vas, Cell** out_cells, std::size_t count) { + if (!count) return; + auto& s = state(); + std::lock_guard lock(s.mutex); + std::uintptr_t lo = s.watched_lo.load(std::memory_order_relaxed); + std::uintptr_t hi = s.watched_hi.load(std::memory_order_relaxed); + bool lo_changed = false, hi_changed = false; + for (std::size_t i = 0; i < count; ++i) { + const std::uintptr_t va = vas[i]; + auto& c = s.cells[va]; + ++c.refs; + out_cells[i] = &c; + const std::uintptr_t tile_end = va <= UINTPTR_MAX - tile_size ? va + tile_size : UINTPTR_MAX; + if (va < lo) { + lo = va; + lo_changed = true; + } + if (tile_end > hi) { + hi = tile_end; + hi_changed = true; + } + } + if (lo_changed) s.watched_lo.store(lo, std::memory_order_release); + if (hi_changed) s.watched_hi.store(hi, std::memory_order_release); + s.count.store(s.cells.size(), std::memory_order_release); +} + // Restore only protections this watch installed. A guest remap or explicit new protection supersedes them. inline DWORD read_only(DWORD protection) { switch (protection & 255u) { @@ -137,32 +228,210 @@ inline DWORD read_only(DWORD protection) { } } // True when it made a page writable again. -inline bool reopen(std::uintptr_t va, Cell& c) { +// Pages that are to get the same protection back are reopened together, a VirtualQuery and a VirtualProtect for each +// region the query reports, not for each page: under Wine each call goes to the server, and a fault on a whole guarded +// tile cost 16 us page by page against 2.6 us for one call (runtime/test/guard_fault_bench.cpp). +// Fast path: when `c.restore` is uniform across all 16 sub-pages and no title_memory_map change after +// `c.armed_map_gen` overlapped [va, va + tile_size), skip VirtualQuery and call VirtualProtect directly (verifying +// `old == read_only(restore) || old == restore`, else restoring `old` and falling back to the slow path). +// When `fault_page_opened` is non-null, sets it to true if VirtualProtect restored a writable, non-guard protection on +// the 4 KiB page `fault_page`, allowing notify(Event::fault) to skip a redundant second VirtualQuery. +inline bool reopen(std::uintptr_t va, Cell& c, std::uintptr_t fault_page = UINTPTR_MAX, + bool* fault_page_opened = nullptr) { + const DWORD r0 = c.restore[0]; + if (r0 && c.armed_map_gen != Cell::kNoMapGen) { + bool uniform = true; + for (std::size_t i = 1; i < c.restore.size(); ++i) { + if (c.restore[i] != r0) { + uniform = false; + break; + } + } + if (uniform) { + const std::uintptr_t tile_end = va <= UINTPTR_MAX - tile_size ? va + tile_size : UINTPTR_MAX; + bool range_clean = (title_memory_map::generation() == c.armed_map_gen); + if (!range_clean) { + std::uint64_t now = 0; + bool overlapped = false; + if (title_memory_map::changes_since(c.armed_map_gen, now, va, tile_end, + [&](std::uintptr_t c_from, std::uintptr_t c_to) { + if (c_from < c_to) overlapped = true; + })) { + range_clean = !overlapped; + } + } + if (range_clean) { + const DWORD ro = read_only(r0); + const bool writable_restore = !(r0 & PAGE_GUARD) && ro != 0; + if (ro) { + DWORD old{}; + if (VirtualProtect(reinterpret_cast(va), tile_size, r0, &old)) { + if (old == ro || old == r0) { + c.restore.fill(0); + c.armed_map_gen = Cell::kNoMapGen; + if (fault_page_opened && writable_restore && fault_page >= va && fault_page < tile_end) + *fault_page_opened = true; + return true; + } + // Unexpected prior protection (caller bypassed title_memory_map::changed): restore `old` and + // fall back to the VirtualQuery slow path. + DWORD dummy{}; + VirtualProtect(reinterpret_cast(va), tile_size, old, &dummy); + } + } + } + } + } + c.armed_map_gen = Cell::kNoMapGen; bool opened = false; - for (std::size_t i = 0; i < c.restore.size(); ++i) { - if (!c.restore[i]) continue; - void* p = reinterpret_cast(va + i * page_size); - MEMORY_BASIC_INFORMATION m{}; - DWORD old{}; - if (!VirtualQuery(p, &m, sizeof m)) continue; - if (m.State == MEM_COMMIT && m.Protect == read_only(c.restore[i])) { - if (!VirtualProtect(p, page_size, c.restore[i], &old)) continue; - opened = true; + for (std::size_t i = 0; i < c.restore.size();) { + if (!c.restore[i]) { + ++i; + continue; + } + std::size_t j = i + 1; + while (j < c.restore.size() && c.restore[j] == c.restore[i]) ++j; + const DWORD restore = c.restore[i]; + const bool writable_restore = !(restore & PAGE_GUARD) && read_only(restore) != 0; + for (std::uintptr_t at = va + i * page_size, end = va + j * page_size; at < end;) { + MEMORY_BASIC_INFORMATION m{}; + if (!VirtualQuery(reinterpret_cast(at), &m, sizeof m)) { + at += page_size; + continue; + } + const std::uintptr_t next = (std::min)(end, reinterpret_cast(m.BaseAddress) + m.RegionSize); + const std::uintptr_t until = next > at ? next : at + page_size; + bool done = true; + if (m.State == MEM_COMMIT && m.Protect == read_only(restore)) { + DWORD old{}; + if (VirtualProtect(reinterpret_cast(at), until - at, restore, &old)) { + opened = true; + if (fault_page_opened && writable_restore && fault_page >= at && fault_page < until) + *fault_page_opened = true; + } else { + done = false; // kept: tried again by the next reopen + } + } + if (done) + for (std::uintptr_t p = at; p < until; p += page_size) c.restore[(p - va) / page_size] = 0; + at = until; } - c.restore[i] = 0; + i = j; } return opened; } -inline void release(std::uintptr_t va) { +// Releases one owner's reference to `va`. When `was_hot` is true, drops that owner's hot count in the same lock hold +// (avoiding a separate set_hot(false) lock and avoiding a bogus WriteQueue push when the cell's last ref goes). +inline void release(std::uintptr_t va, bool was_hot = false) { auto& s = state(); std::lock_guard lock(s.mutex); auto it = s.cells.find(va); - if (it != s.cells.end() && !--it->second.refs) { + if (it == s.cells.end()) return; + Cell& c = it->second; + if (!--c.refs) { + if (c.hot) { + std::erase(s.hot, va); + s.hot_count.store(s.hot.size(), std::memory_order_release); + s.hot_generation.fetch_add(1, std::memory_order_release); + } // A page reopened here may also be one a slot-133 shadow keeps read-only (both guard the title's geometry): // it is writable now with no fault to tell that shadow, which then walks its pages again. - if (reopen(va, it->second)) title_memory_map::changed(va, va + tile_size); + if (reopen(va, c)) title_memory_map::changed(va, va + tile_size); s.cells.erase(it); s.count.store(s.cells.size(), std::memory_order_release); + return; + } + if (was_hot && c.hot && !--c.hot) { + std::erase(s.hot, va); + // Other owners still hold this cell: writes made while it was hot faulted nowhere, so notify subscribers once + // as set_hot(false) does. + const auto version = s.serial.load(std::memory_order_relaxed) + 1; + c.version.store(version, std::memory_order_release); + for (WriteQueue* q : s.writers) { + std::lock_guard queue_lock(q->mutex); + if (q->overflow) continue; + if (q->tiles.size() < WriteQueue::kMaxTiles) + q->tiles.push_back(va); + else + q->overflow = true, q->tiles.clear(); + q->pending.store(true, std::memory_order_release); + } + s.serial.store(version, std::memory_order_release); + s.hot_count.store(s.hot.size(), std::memory_order_release); + s.hot_generation.fetch_add(1, std::memory_order_release); + } +} + +// Releases one reference per {va, was_hot} item under a single State::mutex hold. +inline void release_batch(const std::pair* items, std::size_t count) { + if (!count) return; + auto& s = state(); + std::lock_guard lock(s.mutex); + bool hot_changed = false; + bool cells_erased = false; + host_heap::vector cooled_shared; + std::uintptr_t reopened_lo = 0, reopened_hi = 0; + const auto flush_reopened = [&] { + if (reopened_lo < reopened_hi) { + title_memory_map::changed(reopened_lo, reopened_hi); + reopened_lo = reopened_hi = 0; + } + }; + for (std::size_t i = 0; i < count; ++i) { + const std::uintptr_t va = items[i].first; + const bool was_hot = items[i].second; + auto it = s.cells.find(va); + if (it == s.cells.end()) continue; + Cell& c = it->second; + if (!--c.refs) { + if (c.hot) { + std::erase(s.hot, va); + hot_changed = true; + } + if (reopen(va, c)) { + const std::uintptr_t tile_end = va <= UINTPTR_MAX - tile_size ? va + tile_size : UINTPTR_MAX; + if (reopened_lo < reopened_hi && va == reopened_hi) { + reopened_hi = tile_end; + } else { + flush_reopened(); + reopened_lo = va; + reopened_hi = tile_end; + } + } + s.cells.erase(it); + cells_erased = true; + continue; + } + if (was_hot && c.hot && !--c.hot) { + std::erase(s.hot, va); + hot_changed = true; + cooled_shared.push_back(va); + } + } + flush_reopened(); + if (!cooled_shared.empty()) { + const auto version = s.serial.load(std::memory_order_relaxed) + 1; + for (const std::uintptr_t va : cooled_shared) { + auto it = s.cells.find(va); + if (it != s.cells.end()) it->second.version.store(version, std::memory_order_release); + } + for (WriteQueue* q : s.writers) { + std::lock_guard queue_lock(q->mutex); + if (q->overflow) continue; + if (q->tiles.size() + cooled_shared.size() <= WriteQueue::kMaxTiles) { + q->tiles.insert(q->tiles.end(), cooled_shared.begin(), cooled_shared.end()); + } else { + q->overflow = true; + q->tiles.clear(); + } + q->pending.store(true, std::memory_order_release); + } + s.serial.store(version, std::memory_order_release); + } + if (cells_erased) s.count.store(s.cells.size(), std::memory_order_release); + if (hot_changed) { + s.hot_count.store(s.hot.size(), std::memory_order_release); + s.hot_generation.fetch_add(1, std::memory_order_release); } } enum class Event { write, open, fault, mapping, replaced }; @@ -176,18 +445,27 @@ inline bool notify(std::uintptr_t begin, std::uintptr_t end, Event event, bool* auto it = s.cells.lower_bound(begin & ~(tile_size - 1)); if (it == s.cells.end() || it->first >= end) return false; const auto version = s.serial.load(std::memory_order_relaxed) + 1; + const std::uintptr_t fault_page = begin & ~(page_size - 1); bool opened = false; for (; it != s.cells.end() && it->first < end; ++it) { auto& cell = it->second; if (event == Event::open || event == Event::fault) { - if (reopen(it->first, cell) && restored) *restored = true; + bool fault_opened = false; + const bool any = reopen(it->first, cell, event == Event::fault ? fault_page : UINTPTR_MAX, + event == Event::fault ? &fault_opened : nullptr); + if (any && restored) *restored = true; if (event == Event::fault) { - MEMORY_BASIC_INFORMATION m{}; - opened = VirtualQuery(reinterpret_cast(begin), &m, sizeof m) && - m.State == MEM_COMMIT && !(m.Protect & PAGE_GUARD) && read_only(m.Protect); + if (fault_opened) { + opened = true; + } else if (!opened) { + MEMORY_BASIC_INFORMATION m{}; + opened = VirtualQuery(reinterpret_cast(begin), &m, sizeof m) && + m.State == MEM_COMMIT && !(m.Protect & PAGE_GUARD) && read_only(m.Protect); + } } } if (event == Event::replaced) { + cell.armed_map_gen = Cell::kNoMapGen; for (unsigned i = 0; i < cell.restore.size(); ++i) { auto p = it->first + i * page_size; if (p < end && p + page_size > begin) cell.restore[i] = 0; @@ -195,12 +473,131 @@ inline bool notify(std::uintptr_t begin, std::uintptr_t end, Event event, bool* } if (event == Event::mapping || event == Event::replaced) cell.mapping.store(version, std::memory_order_release); cell.version.store(version, std::memory_order_release); + for (WriteQueue* q : s.writers) { + std::lock_guard queue_lock(q->mutex); + if (q->overflow) continue; + if (q->tiles.size() < WriteQueue::kMaxTiles) + q->tiles.push_back(it->first); + else + q->overflow = true, q->tiles.clear(); + q->pending.store(true, std::memory_order_release); + } } s.serial.store(version, std::memory_order_release); return opened; } +// The tile at `va` is hot for one more owner (`hot`) or one fewer: while any owner holds it hot, its guard is off and +// it is not armed again, and hot_tiles() lists it for every subscriber. The cell must be acquired. +inline void set_hot(std::uintptr_t va, bool hot) { + auto& s = state(); + std::lock_guard lock(s.mutex); + const auto it = s.cells.find(va); + if (it == s.cells.end()) return; + Cell& c = it->second; + if (hot) { + if (c.hot++) return; + reopen(va, c); + s.hot.push_back(va); + } else { + if (!c.hot || --c.hot) return; + std::erase(s.hot, va); + // Writes made while it was hot faulted nowhere and the subscribers that looked before this saw it in + // hot_tiles(): it counts as written once more, for all of them, as a write does. + const auto version = s.serial.load(std::memory_order_relaxed) + 1; + c.version.store(version, std::memory_order_release); + for (WriteQueue* q : s.writers) { + std::lock_guard queue_lock(q->mutex); + if (q->overflow) continue; + if (q->tiles.size() < WriteQueue::kMaxTiles) + q->tiles.push_back(va); + else + q->overflow = true, q->tiles.clear(); + q->pending.store(true, std::memory_order_release); + } + s.serial.store(version, std::memory_order_release); + } + s.hot_count.store(s.hot.size(), std::memory_order_release); + s.hot_generation.fetch_add(1, std::memory_order_release); +} + +// Batched set_hot: updates `vas[0..count)` under a single State::mutex hold (eliminating per-tile mutex + WriteQueue +// churn on TitleWritePolicy::kProbe cycles and hot-page promotion batches). +inline void set_hot_batch(const std::uintptr_t* vas, std::size_t count, bool hot) { + if (!count) return; + if (count == 1) { + set_hot(vas[0], hot); + return; + } + auto& s = state(); + std::lock_guard lock(s.mutex); + bool hot_changed = false; + if (hot) { + for (std::size_t i = 0; i < count; ++i) { + const std::uintptr_t va = vas[i]; + const auto it = s.cells.find(va); + if (it == s.cells.end()) continue; + Cell& c = it->second; + if (c.hot++) continue; + reopen(va, c); + s.hot.push_back(va); + hot_changed = true; + } + } else { + host_heap::vector cooled; + cooled.reserve(count); + for (std::size_t i = 0; i < count; ++i) { + const std::uintptr_t va = vas[i]; + const auto it = s.cells.find(va); + if (it == s.cells.end()) continue; + Cell& c = it->second; + if (!c.hot || --c.hot) continue; + cooled.push_back(va); + hot_changed = true; + } + if (!cooled.empty()) { + std::sort(cooled.begin(), cooled.end()); + cooled.erase(std::unique(cooled.begin(), cooled.end()), cooled.end()); + std::erase_if(s.hot, [&](std::uintptr_t x) { + return std::binary_search(cooled.begin(), cooled.end(), x); + }); + const auto version = s.serial.load(std::memory_order_relaxed) + 1; + for (const std::uintptr_t va : cooled) { + const auto it = s.cells.find(va); + if (it != s.cells.end()) it->second.version.store(version, std::memory_order_release); + } + for (WriteQueue* q : s.writers) { + std::lock_guard queue_lock(q->mutex); + if (q->overflow) continue; + if (q->tiles.size() + cooled.size() <= WriteQueue::kMaxTiles) { + q->tiles.insert(q->tiles.end(), cooled.begin(), cooled.end()); + } else { + q->overflow = true; + q->tiles.clear(); + } + q->pending.store(true, std::memory_order_release); + } + s.serial.store(version, std::memory_order_release); + } + } + if (hot_changed) { + s.hot_count.store(s.hot.size(), std::memory_order_release); + s.hot_generation.fetch_add(1, std::memory_order_release); + } +} + +// The tiles some owner holds hot: written, for every subscriber, at every look. +template +inline void hot_tiles(Out& out) { + out.clear(); + auto& s = state(); + if (!s.hot_count.load(std::memory_order_acquire)) return; + std::lock_guard lock(s.mutex); + out.assign(s.hot.begin(), s.hot.end()); +} + // Arm under the same lock as the write-fault path. A kernel destination may only be guarded again after its pin ends. +// A hot cell is not protected (true: its writes reach every subscriber through hot_tiles()). inline bool arm(std::uintptr_t va, Cell& c) { auto& s = state(); // Querying an OVERLAPPED can fault into xmem. Never do it with the watch lock held. @@ -208,9 +605,12 @@ inline bool arm(std::uintptr_t va, Cell& c) { bool pinned = false; kernel_writes::for_each_pin(va, va + tile_size, [&](auto, auto) { pinned = true; }); std::lock_guard lock(s.mutex); + if (c.hot) return true; if (pinned || version != c.version.load(std::memory_order_relaxed)) return false; + c.armed_map_gen = Cell::kNoMapGen; for (std::size_t i = 0; i < c.restore.size();) { auto p = va + i * page_size; + const std::uint64_t query_gen = title_memory_map::generation(); MEMORY_BASIC_INFORMATION m{}; if (!VirtualQuery(reinterpret_cast(p), &m, sizeof m)) return false; const auto end = (std::min)(va + tile_size, reinterpret_cast(m.BaseAddress) + m.RegionSize); @@ -226,6 +626,8 @@ inline bool arm(std::uintptr_t va, Cell& c) { // and they stayed read-only with no guard to answer for them: title writes and kernel writes into them // failed for good. Such a page has two guards now; reopening it tells the shadows (notify's `restored`). for (auto j = i; j < next; ++j) c.restore[j] = m.Protect; + if (i == 0 && next == c.restore.size() && title_memory_map::generation() == query_gen) + c.armed_map_gen = query_gen; } i = next; } diff --git a/runtime/src/title_heap.h b/runtime/src/title_heap.h new file mode 100644 index 0000000000..29af88c88b --- /dev/null +++ b/runtime/src/title_heap.h @@ -0,0 +1,276 @@ +#pragma once +// The XMemAlloc heap (title_heap): the title's XMemAlloc / XMemAllocDefault blocks, carved from one reservation that +// xmem places in the page mirror's range (src/title_mirror_space.h), so a V# or pointer the title writes into a block +// reaches the mirror at heap_base + the block's address. Windows' RtlCreateHeap over a given base faults under Wine +// (it writes into the reserved base), so the heap is the runtime's own. +// +// What the title sees, as before: every block 64-byte aligned, a size of zero one byte, blocks that never overlap, +// XMemFree of a block from either entry point. There is no realloc and no size query in the title's ABI; size_of +// answers xmem's own bookkeeping (the bytes a free tells the readers about). +// +// The layout: +// - the reservation is handed out in 64 KiB pages by a first-fit list of free runs, coalesced on free; +// - blocks up to kSmallMax come from spans of kSpan bytes, one size class a span (multiples of 64 bytes up to 1 KiB, +// then powers of two), each class with a stack of free blocks kept outside the title's memory (a freed block's +// bytes are never written by the heap); +// - larger blocks are runs of whole pages, committed when handed out and decommitted when freed (they read zero when +// handed out again, as HeapAlloc's large blocks do). +// Pages are committed through the hooks (xmem: VirtualAlloc, then the page mirror's feed). One lock, taken for every +// call; nothing the title's memory holds is read or written under it. Portable: the hooks do the system calls. +#include +#include +#include +#include +#include +#include +#include + +namespace leonida { + +class TitleHeap { +public: + static constexpr std::size_t kAlign = 64; + static constexpr std::size_t kPage = 0x10000; + static constexpr std::size_t kSpan = std::size_t(1) << 20; + static constexpr std::size_t kSmallMax = 32768; + + struct Hooks { + std::function commit; // [at, at + bytes) usable from now on + std::function decommit; // [at, at + bytes) given back (reads zero later) + }; + struct Stats { + std::size_t committed = 0, spans = 0, large = 0, live = 0; + bool write_watched = false; + }; + + // Tries reserving the heap's virtual range with MEM_WRITE_WATCH first (`try_reserve(true)`), falling back silently + // to an ordinary reservation (`try_reserve(false)`) when the host/Wine rejects write-watching. Sets + // `write_watched` to reflect which reservation succeeded. + template + static std::uintptr_t reserve(TryReserve&& try_reserve, bool& write_watched) { + if (const std::uintptr_t at = try_reserve(true)) { + write_watched = true; + return at; + } + write_watched = false; + return try_reserve(false); + } + + bool init(std::uintptr_t base, std::size_t bytes, Hooks hooks, bool write_watched = false) { + std::lock_guard lock(mutex_); + if (!base || bytes < kSpan || (base % kPage)) return false; + base_ = base; + bytes_ = bytes - bytes % kPage; + write_watched_ = write_watched; + hooks_ = std::move(hooks); + free_runs_.clear(); + free_runs_[base_] = bytes_; + large_.clear(); + for (auto& cls : classes_) cls.free.clear(); + span_class_.assign(bytes_ / kSpan, kNoClass); + span_live_.assign(bytes_ / kSpan, {}); + stats_ = {}; + stats_.write_watched = write_watched_; + return true; + } + bool write_watched() const { + std::lock_guard lock(mutex_); + return write_watched_; + } + std::uintptr_t base() const { + std::lock_guard lock(mutex_); + return base_; + } + std::size_t capacity() const { + std::lock_guard lock(mutex_); + return bytes_; + } + bool owns(const void* p) const { + const auto at = reinterpret_cast(p); + return base_ && at >= base_ && at - base_ < bytes_; + } + + void* allocate(std::size_t size) { + if (!size) size = 1; + std::lock_guard lock(mutex_); + if (!base_) return nullptr; + if (size <= kSmallMax) { + const unsigned c = class_of(size); + Class& cls = classes_[c]; + if (cls.free.empty() && !grow(c)) return nullptr; + const std::uintptr_t at = cls.free.back(); + cls.free.pop_back(); + const std::size_t rel = at - base_; + const std::size_t s = rel / kSpan; + const std::size_t slot = (rel % kSpan) / class_size(c); + span_live_[s][slot / 64] |= std::uint64_t(1) << (slot % 64); + ++stats_.live; + return reinterpret_cast(at); + } + const std::size_t bytes = (size + kPage - 1) & ~(kPage - 1); + if (bytes < size) return nullptr; + const std::uintptr_t at = take_run(bytes); + if (!at) return nullptr; + if (hooks_.commit && !hooks_.commit(at, bytes)) { + give_run(at, bytes); + return nullptr; + } + large_[at] = bytes; + stats_.committed += bytes; + ++stats_.large; + ++stats_.live; + return reinterpret_cast(at); + } + + // The bytes the block at `p` holds (its class's size, or its pages): 0 for a pointer that is not a live block's. + std::size_t size_of(const void* p) const { + const auto at = reinterpret_cast(p); + std::lock_guard lock(mutex_); + if (!owns(p)) return 0; + if (const auto it = large_.find(at); it != large_.end()) return it->second; + const std::size_t rel = at - base_; + const std::size_t s = rel / kSpan; + if (s >= span_class_.size()) return 0; + const unsigned c = span_class_[s]; + if (c == kNoClass) return 0; + const std::size_t size = class_size(c); + const std::size_t in_span = rel % kSpan; + if (in_span % size != 0) return 0; + const std::size_t slot = in_span / size; + if (slot >= kSpan / size) return 0; + return (span_live_[s][slot / 64] & (std::uint64_t(1) << (slot % 64))) ? size : 0; + } + + // Frees a block allocate() returned. False (nothing done) for any other pointer or an already-freed block. + bool release(void* p) { + const auto at = reinterpret_cast(p); + std::lock_guard lock(mutex_); + if (!owns(p)) return false; + if (const auto it = large_.find(at); it != large_.end()) { + const std::size_t bytes = it->second; + large_.erase(it); + if (hooks_.decommit) hooks_.decommit(at, bytes); + stats_.committed -= bytes; + --stats_.large; + --stats_.live; + give_run(at, bytes); + return true; + } + const std::size_t rel = at - base_; + const std::size_t s = rel / kSpan; + if (s >= span_class_.size()) return false; + const unsigned c = span_class_[s]; + if (c == kNoClass) return false; + const std::size_t size = class_size(c); + const std::size_t in_span = rel % kSpan; + if (in_span % size != 0) return false; + const std::size_t slot = in_span / size; + if (slot >= kSpan / size) return false; + std::uint64_t& word = span_live_[s][slot / 64]; + const std::uint64_t bit = std::uint64_t(1) << (slot % 64); + if ((word & bit) == 0) return false; + word &= ~bit; + classes_[c].free.push_back(at); + --stats_.live; + return true; + } + + // f(at, bytes) for each maximal contiguous committed extent (coalescing adjacent spans and large blocks; + // never includes uncommitted holes), for a reader that starts late. Exact complement of free_runs_ in + // [base_, base_ + bytes_). + template + void for_each_committed(F&& f) const { + std::lock_guard lock(mutex_); + if (!base_ || !bytes_) return; + std::uintptr_t cursor = base_; + const std::uintptr_t limit = base_ + bytes_; + for (const auto& [free_at, free_bytes] : free_runs_) { + if (free_at > cursor) f(cursor, free_at - cursor); + cursor = free_at + free_bytes; + } + if (cursor < limit) f(cursor, limit - cursor); + } + + Stats stats() const { + std::lock_guard lock(mutex_); + return stats_; + } + + static constexpr unsigned kClasses = 16 + 5; // 64..1024 by 64, then 2, 4, 8, 16, 32 KiB + static std::size_t class_size(unsigned c) { return c < 16 ? (c + 1) * 64 : std::size_t(1024) << (c - 15); } + static unsigned class_of(std::size_t size) { + if (size <= 1024) return unsigned((size + 63) / 64 - 1); + unsigned c = 16; + while (class_size(c) < size) ++c; + return c; + } + +private: + static constexpr unsigned kNoClass = 0xff; + struct Class { + std::vector free; + }; + + // A new span for class `c`: committed, cut into blocks pushed on its stack (in address order: the lowest first). + bool grow(unsigned c) { + const std::uintptr_t at = take_run(kSpan, kSpan); + if (!at) return false; + if (hooks_.commit && !hooks_.commit(at, kSpan)) { + give_run(at, kSpan); + return false; + } + const std::size_t s = (at - base_) / kSpan; + span_class_[s] = std::uint8_t(c); + const std::size_t size = class_size(c); + const std::size_t slots = kSpan / size; + span_live_[s].assign((slots + 63) / 64, 0); + stats_.committed += kSpan; + ++stats_.spans; + for (std::size_t off = slots * size; off >= size; off -= size) classes_[c].free.push_back(at + off - size); + return true; + } + // The first free run that holds `bytes` at an offset from the base aligned to `align` (spans are numbered from the + // base, which is only page-aligned). + std::uintptr_t take_run(std::size_t bytes, std::size_t align = kPage) { + for (auto it = free_runs_.begin(); it != free_runs_.end(); ++it) { + const std::uintptr_t start = base_ + ((it->first - base_ + align - 1) & ~(std::uintptr_t(align) - 1)); + const std::uintptr_t end = it->first + it->second; + if (start >= end || end - start < bytes) continue; + const std::uintptr_t run = it->first, run_end = end; + free_runs_.erase(it); + if (start > run) free_runs_[run] = start - run; + if (start + bytes < run_end) free_runs_[start + bytes] = run_end - (start + bytes); + return start; + } + return 0; + } + void give_run(std::uintptr_t at, std::size_t bytes) { + auto next = free_runs_.lower_bound(at); + if (next != free_runs_.end() && at + bytes == next->first) { + bytes += next->second; + next = free_runs_.erase(next); + } + if (next != free_runs_.begin()) { + const auto previous = std::prev(next); + if (previous->first + previous->second == at) { + previous->second += bytes; + return; + } + } + free_runs_[at] = bytes; + } + + mutable std::mutex mutex_; + std::uintptr_t base_ = 0; + std::size_t bytes_ = 0; + bool write_watched_ = false; + Hooks hooks_; + std::map free_runs_; // start -> bytes + std::map large_; // a large block -> its bytes + std::vector span_class_; // per span: its class, or kNoClass + std::vector> span_live_; // per active span: 1 bit per slot (1 = live, 0 = free) + Class classes_[kClasses]; + Stats stats_; +}; + +} // namespace leonida diff --git a/runtime/src/title_mirror.h b/runtime/src/title_mirror.h new file mode 100644 index 0000000000..d73a91e696 --- /dev/null +++ b/runtime/src/title_mirror.h @@ -0,0 +1,1934 @@ +#pragma once +// The page mirror (title_mirror): one GPU copy of the title's GPU-readable pages, at heap_base + the title's address. +// +// A V# or a 64-bit pointer the title writes into its own memory names a title address, and the translated shaders reach +// heap_base + sext48(address) (docs/design.md, "Heap-relative buffer device addresses"). The mirror makes that address +// hold the title's bytes: +// - the address range: sparse buffers ("chunks", kChunk each) created at heap_base + the title's address with +// bufferDeviceAddressCaptureReplay, over every reservation xmem placed in src/title_mirror_space.h. A page with +// nothing bound reads zero and drops stores (residencyNonResidentStrict), so a title address in a reservation that +// is not mirrored, or a page not mapped, never faults; +// - one home per physical page: 64 KiB of a 32 MiB unit (one VkDeviceMemory, host-visible, mapped once). Every title +// page that shows the physical page (a CPU view, a GPU-only alias, a CopyPageMappingsBatchX copy) is bound to that +// one home, so aliases share the bytes and the GPU's writes, and a remap is a rebind, never a copy; +// - the change feed: xmem reports every change of what a page of the mirror's range shows (src/title_frames.h, +// Feed), in order; map() takes it; +// - the dirty list: a home is filled from its physical page when it is made, and again when the caller says the page +// was written (dirty(): the geometry watch's cells say so: a guard fault, a kernel write, a remap); +// - flush(): the binds noted since the last one go in one batch, which signals a value the next submission of every +// queue waits for (the ordering rule: a submission after a remap in call order never reads a page whose bind has +// not landed). A home unbound everywhere is freed once the submissions that could read it have retired; +// - aliases (alias()): a range of title pages also bound at an address of the caller's (a console descriptor heap's +// table address below 4 GiB), each page there with a home of its own, the filtered copy, which hooks.filter fills +// from the title's bytes whenever they change. The page's own home stays the title's bytes exactly: a V# or a +// pointer of the title into those pages reads what the title wrote, and only the alias reads filtered bytes. +// +// No Vulkan call here: the device (or a test) passes hooks, as for src/arena_backing.h. Not thread-safe: the caller +// serialises (the device under its mirror mutex). +#include + +#include "shadow_keep.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#if defined(_M_X64) || defined(_M_IX86) || defined(__x86_64__) || defined(__i386__) +#include +#endif + +namespace leonida { + +struct TitleMirrorHooks { + // A sparse buffer of `bytes` at device address heap_base + title_base; its handle. False: not placed there. + std::function make_chunk; + // One unit of home memory, mapped: kUnitBytes of device memory and its host address. + std::function make_unit; + std::function free_unit; + // The binds in one batch (per chunk: VkSparseMemoryBind with resourceOffset inside it); signals `value`. + std::function& binds, std::uint64_t value)> bind; + // Copies a physical page's 64 KiB into its home; false when its bytes cannot be read (the home keeps zeros). + // May be called concurrently from internal worker threads during batched upload(); must be thread-safe. + std::function copy; + // Optional fused strip copy + 256-byte piece hashing: copies `pieces * 256` bytes from `from` into `to` and fills + // `sums[0..pieces)` with bit-for-bit identical `shadow_keep::sum_of(..., 256)` hashes in one pass; false when any + // byte cannot be read (falls back to per-piece `copy`). Must be thread-safe. + std::function + copy_and_sum; + // Fills the filtered copy of a page in an aliased range (alias): the title's bytes at `from` (the page shown at + // title address `va`) in, what the GPU reads at the alias into `to`. Called after the page's own home took the + // title's bytes, when they changed. `fresh`: the copy holds nothing of an earlier fill (made now, or a failed fill + // zeroed it), so every byte must be written; otherwise `to` still holds this filter's last output for the same page. + // The title's bytes and the page's own home are never written. False as for `copy` (the copy is zeroed). + std::function filter; + // Optional fast path for `filter`: called whenever `filter_pieces` is set, passing the already-copied 64 KiB + // `scratch` buffer (no duplicate guarded copy; synced with `home` and `home.sums[]`) and the 256-bit + // `changed_pieces` mask (bit k set when piece [k*256, (k+1)*256) changed; all bits set when `fresh` or after a + // write-back refilter). Falls back to `filter` (still receiving the same `scratch` snapshot) when `filter_pieces` + // is not set. + std::function& changed_pieces)> + filter_pieces; +}; + +class TitleMirror { +public: + static constexpr std::uint64_t kPage = 0x10000; + static constexpr std::uint64_t kChunk = std::uint64_t(2) << 30; + static constexpr std::size_t kChunkPages = std::size_t(kChunk / kPage); + static constexpr std::uint64_t kUnitBytes = std::uint64_t(32) << 20; + static constexpr std::uint32_t kUnitPages = std::uint32_t(kUnitBytes / kPage); + static constexpr std::size_t kStripBytes = 16384; + static constexpr std::size_t kStripPieces = kStripBytes / shadow_keep::kPiece; + static constexpr std::size_t kParallelThreshold = 16; + static constexpr std::size_t kMaxWorkers = 8; + // Sentinel ticket for freed homes waiting for flush() + note_mirror_bind() to publish the sparse unbind before + // stamping their retire ticket via stamp_freed(). + static constexpr std::uint64_t kUnstamped = UINT64_MAX; + + struct Counters { + std::uint64_t chunks = 0, chunk_failures = 0, homes = 0, units = 0, pages = 0; // now + std::uint64_t binds = 0, unbinds = 0, batches = 0, uploads = 0, upload_failures = 0, homes_freed = 0; // so far + std::uint64_t unmirrored_changes = 0; // feed entries outside every chunk + std::uint64_t filtered = 0; // fills of an alias's filtered copy through hooks.filter + // Bytes the uploads copied into homes, bytes write_back() copied to the title's pages, and 256-byte pieces + // both sides had changed (the title's bytes kept), so far. + std::uint64_t uploaded_bytes = 0, written_back_bytes = 0, conflicts = 0; + }; + + // Reusable thread pool for batched upload(), write_back_batch(), and lock-free readback pre-hashing. Synchronous + // barrier: every worker finishes before run() returns, so callers' state remains single-owner with zero lock-order + // issues. + class WorkerPool { + public: + explicit WorkerPool(std::size_t bg_threads) : scratches_(bg_threads + 1) { + threads_.reserve(bg_threads); + try { + for (std::size_t t = 0; t < bg_threads; ++t) { + threads_.emplace_back([this, tid = t + 1] { worker_loop(tid); }); + } + } catch (...) { + shutdown(); + throw; + } + } + ~WorkerPool() { shutdown(); } + WorkerPool(const WorkerPool&) = delete; + WorkerPool& operator=(const WorkerPool&) = delete; + + std::size_t worker_count() const noexcept { return threads_.size() + 1; } + std::uint8_t* scratch(std::size_t worker_id) noexcept { return scratches_[worker_id].bytes.data(); } + + template + void run(std::size_t count, std::size_t chunk_size, Fn&& fn) { + if (!count) return; + if (threads_.empty()) { + fn(0, count, 0); + return; + } + using RawFn = std::remove_reference_t; + auto thunk = [](void* ctx, std::size_t b, std::size_t e, std::size_t tid) { + (*static_cast(ctx))(b, e, tid); + }; + void* const ctx = const_cast(static_cast(&fn)); + { + std::lock_guard lock(mutex_); + task_fn_ = thunk; + task_ctx_ = ctx; + task_count_ = count; + task_chunk_ = chunk_size; + next_index_.store(0, std::memory_order_relaxed); + remaining_workers_.store(threads_.size(), std::memory_order_release); + generation_.fetch_add(1, std::memory_order_release); + } + work_cv_.notify_all(); + struct JoinGuard { + WorkerPool& pool; + ~JoinGuard() { + if (pool.remaining_workers_.load(std::memory_order_acquire) != 0) { + std::unique_lock lock(pool.mutex_); + pool.done_cv_.wait(lock, [this] { + return pool.remaining_workers_.load(std::memory_order_acquire) == 0; + }); + } + pool.task_fn_ = nullptr; + pool.task_ctx_ = nullptr; + } + } join_guard{*this}; + drain_work(thunk, ctx, count, chunk_size, 0); + } + + private: + struct alignas(64) Scratch { + std::array bytes{}; + }; + using Thunk = void (*)(void*, std::size_t, std::size_t, std::size_t); + + static void cpu_pause() noexcept { +#if defined(_M_X64) || defined(_M_IX86) || defined(__x86_64__) || defined(__i386__) + _mm_pause(); +#elif defined(__aarch64__) + asm volatile("yield"); +#endif + } + + void shutdown() noexcept { + { + std::lock_guard lock(mutex_); + stop_ = true; + generation_.fetch_add(1, std::memory_order_release); + } + work_cv_.notify_all(); + for (std::thread& t : threads_) + if (t.joinable()) t.join(); + threads_.clear(); + } + + void drain_work(Thunk fn, void* ctx, std::size_t count, std::size_t chunk, std::size_t tid) { + for (;;) { + const std::size_t b = next_index_.fetch_add(chunk, std::memory_order_relaxed); + if (b >= count) break; + const std::size_t e = (std::min)(b + chunk, count); + fn(ctx, b, e, tid); + } + } + + void worker_loop(std::size_t tid) { + std::uint64_t seen = 0; + for (;;) { + std::uint64_t gen = generation_.load(std::memory_order_acquire); + if (gen == seen && seen != 0) { + // Brief ~50 us spin before sleeping to avoid Wine/OS condvar wakeup latency between back-to-back + // WorkerPool::run() dispatches (e.g. upload() -> filter_heap_pages_batch_locked()). + const auto spin_deadline = std::chrono::steady_clock::now() + std::chrono::microseconds(50); + for (;;) { + for (int p = 0; p < 64; ++p) { + gen = generation_.load(std::memory_order_acquire); + if (gen != seen) break; + cpu_pause(); + } + if (gen != seen || std::chrono::steady_clock::now() >= spin_deadline) break; + } + } + if (gen == seen) { + std::unique_lock lock(mutex_); + work_cv_.wait(lock, [this, seen] { return generation_.load(std::memory_order_acquire) != seen; }); + gen = generation_.load(std::memory_order_acquire); + } + seen = gen; + if (stop_) return; + const Thunk fn = task_fn_; + void* const ctx = task_ctx_; + const std::size_t count = task_count_; + const std::size_t chunk = task_chunk_; + struct DoneGuard { + WorkerPool& pool; + ~DoneGuard() { + if (pool.remaining_workers_.fetch_sub(1, std::memory_order_acq_rel) == 1) { + std::lock_guard lock(pool.mutex_); + pool.done_cv_.notify_one(); + } + } + } done_guard{*this}; + drain_work(fn, ctx, count, chunk, tid); + } + } + + std::vector scratches_; + std::vector threads_; + std::mutex mutex_; + std::condition_variable work_cv_; + std::condition_variable done_cv_; + Thunk task_fn_ = nullptr; + void* task_ctx_ = nullptr; + std::size_t task_count_ = 0; + std::size_t task_chunk_ = 1; + bool stop_ = false; + alignas(64) std::atomic generation_{0}; + alignas(64) std::atomic remaining_workers_{0}; + alignas(64) std::atomic next_index_{0}; + }; + + static std::unique_ptr make_worker_pool() { + const unsigned hw = std::thread::hardware_concurrency(); + const std::size_t total = (hw >= 4) ? (std::min)(std::size_t(hw / 2), kMaxWorkers) + : ((hw >= 2) ? std::size_t(hw) : std::size_t(1)); + if (total <= 1) return nullptr; + try { + return std::make_unique(total - 1); + } catch (...) { + return nullptr; + } + } + + explicit TitleMirror(TitleMirrorHooks hooks) : hooks_(std::move(hooks)) {} + ~TitleMirror() { + pool_.reset(); + for (const Unit& u : units_) + if (u.memory && hooks_.free_unit) hooks_.free_unit(u.memory); + } + TitleMirror(const TitleMirror&) = delete; + TitleMirror& operator=(const TitleMirror&) = delete; + + // Enables or disables internal worker-pool parallelisation for large batches (enabled by default; tests toggle it + // to compare single-threaded vs parallel output and timings directly). + void set_parallel(bool enabled) noexcept { parallel_enabled_ = enabled; } + bool parallel_enabled() const noexcept { return parallel_enabled_; } + + // The chunks over [base, end) of the title's address space (a reservation xmem placed). False when one could not + // be placed: its pages stay unmirrored (a title address there reads what heap_base + it names: the caller logs). + bool cover(std::uint64_t base, std::uint64_t end) { + bool ok = true; + for (std::uint64_t c = base / kChunk; c * kChunk < end; ++c) { + if (chunks_.count(c)) continue; + VkBuffer buffer = VK_NULL_HANDLE; + if (!hooks_.make_chunk || !hooks_.make_chunk(c * kChunk, kChunk, buffer)) { + ++counters_.chunk_failures; + ok = false; + chunks_[c].buffer = VK_NULL_HANDLE; // tried once + continue; + } + Chunk& ch = chunks_[c]; + ch.buffer = buffer; + ch.pages = std::make_unique(kChunkPages); + insert_chunk_dir(c, ch); + ++counters_.chunks; + } + return ok; + } + bool covers(std::uint64_t va) const { + return find_chunk_dir(va / kChunk) != nullptr; + } + + // The feed: the 64 KiB page at `va` shows the physical page whose 64 KiB are at `frame` (its section's scratch view, + // kept alive by `keep`), or nothing (`frame` null). The bind is noted for the next flush(); a new home is filled + // immediately unless `defer_fill` is true (and the page is not aliased), in which case it is queued in `dirty_` for + // parallel batched filling by the upcoming upload(). + // Freed homes default to kUnstamped and wait for stamp_freed() after flush() publishes the sparse unbind. + void map(std::uint64_t va, std::uint8_t* frame, std::shared_ptr keep, + std::uint64_t ticket = kUnstamped, bool defer_fill = false) { + va &= ~(kPage - 1); + const std::uint64_t chunk_idx = va / kChunk; + const ChunkDirEntry* const dir = find_chunk_dir(chunk_idx); + if (!dir) { + ++counters_.unmirrored_changes; + return; + } + Chunk* const chunk = dir->chunk; + PageSlot* const slot = &dir->pages[std::size_t((va - chunk_idx * kChunk) / kPage)]; + if (slot->frame) { + std::uint8_t* const old_frame = slot->frame; + Home* const old_home = slot->home; + if (old_frame == frame) return; + // A filtered copy made for this page: another aliased page showing the same home takes it over (filled + // whole for that page), else it goes with this page. Only scan aliases when refs > 1; save `old_frame` + // and `old_home` by value before sync_and_fill_copy(), which may re-entrantly insert into `homes_`. + if (old_home && old_home->copy && old_home->filter_va == va) { + std::uint64_t other_va = 0; + if (old_home->refs > 1) { + for (const auto& [alo, alias] : aliases_) { + for_each_mapped_in(alo, alias.hi, [&](std::uint64_t other, const PageSlot& s) { + if (other != va && s.frame == old_frame) other_va = other; + }); + } + } + if (other_va) { + old_home->filter_va = other_va; + old_home->fresh = true; + sync_and_fill_copy(*old_home, old_frame, true); + } else { + drop_copy(*old_home, ticket); + } + } + slot->frame = nullptr; + slot->home = nullptr; + --chunk->mapped_count; + --pages_count_; + release_home(old_frame, ticket); + } + if (!frame) { + note_bind(va, VK_NULL_HANDLE, 0); + note_alias_bind(va, VK_NULL_HANDLE, 0); + ++counters_.unbinds; + return; + } + bool created = false; + Home* home = home_of(frame, std::move(keep), created); + if (!home) { + note_bind(va, VK_NULL_HANDLE, 0); + note_alias_bind(va, VK_NULL_HANDLE, 0); + return; + } + ++home->refs; + slot->frame = frame; + slot->home = home; + ++chunk->mapped_count; + ++pages_count_; + note_bind(va, units_[home->unit].memory, VkDeviceSize(home->slot) * kPage); + const bool is_aliased = aliased(va); + if (created) { + if (is_aliased) { + if (take_slot(home->copy_unit, home->copy_slot)) { + home->copy = true; + home->filter_va = va; + home->fresh = true; + note_alias_bind(va, units_[home->copy_unit].memory, VkDeviceSize(home->copy_slot) * kPage); + } else { + ++counters_.upload_failures; + note_alias_bind(va, VK_NULL_HANDLE, 0); // no room: the alias reads zero there + } + fill(*home, frame, true); + } else if (defer_fill) { + home->whole_fill = true; + home->dirty = true; + dirty_.push_back(frame); + dirty_count_.store(dirty_.size(), std::memory_order_release); + } else { + fill(*home, frame, true); + } + } else if (is_aliased) { + if (!home->copy) make_copy(*home, frame, va); + if (home->copy) note_alias_bind(va, units_[home->copy_unit].memory, VkDeviceSize(home->copy_slot) * kPage); + else note_alias_bind(va, VK_NULL_HANDLE, 0); // no room: the alias reads zero there + } + ++counters_.binds; + } + + // [lo, hi) of the title's address space (whole pages) is also bound into `buffer` at `offset` + (va - lo), each page + // there with a home of its own, the filtered copy: hooks.filter fills it from the title's bytes now and whenever the + // page is filled again, it follows the page's remaps and unmaps, and its binds go in the same batches as the chunk + // binds, so the same wait orders a reader of either address. The page's own home, at the title's address, keeps + // the title's bytes. A console descriptor heap uses it to be read filtered at an offset below 4 GiB of the arena + // (32-bit descriptor-table pointers). Pages not mapped are left unbound there (they read zero). + void alias(std::uint64_t lo, std::uint64_t hi, VkBuffer buffer, VkDeviceSize offset) { + aliases_[lo] = {hi, buffer, offset}; + struct Matched { + std::uint64_t va; + std::uint8_t* frame; + Home* home; + }; + std::vector matched; + for_each_mapped_in(lo, hi, [&](std::uint64_t va, const PageSlot& s) { + matched.push_back({va, s.frame, s.home}); + }); + for (const auto& m : matched) { + if (!m.home) continue; + Home& h = *m.home; // node reference survives re-entrant homes_ rehash inside make_copy() + if (!h.copy) make_copy(h, m.frame, m.va); + if (h.copy) note_alias_bind(m.va, units_[h.copy_unit].memory, VkDeviceSize(h.copy_slot) * kPage); + } + } + // The alias at `lo` goes: its pages are unbound there, and their filtered copies are freed after `ticket` + // (kUnstamped: wait for stamp_freed() after flush() publishes the sparse unbind). + void unalias(std::uint64_t lo, std::uint64_t ticket = kUnstamped) { + const auto it = aliases_.find(lo); + if (it == aliases_.end()) return; + const Alias alias = it->second; + for_each_mapped_in(lo, alias.hi, [&](std::uint64_t va, const PageSlot& s) { + alias_pending_[alias.buffer][alias.offset + (va - lo)] = + {alias.offset + (va - lo), kPage, VK_NULL_HANDLE, 0, 0}; + has_pending_binds_.store(true, std::memory_order_release); + if (s.home && s.home->copy && s.home->filter_va == va) drop_copy(*s.home, ticket); + }); + aliases_.erase(it); + } + // The filtered copy of the aliased page at `va`, mapped (its host bytes): what a filter's caller writes one + // changed slot into between fills. Null when the page is not mapped or has no copy. + std::uint8_t* copy_bytes(std::uint64_t va) { + const PageSlot* const slot = find_slot(va); + if (!slot || !slot->home || !slot->home->copy) return nullptr; + return units_[slot->home->copy_unit].host + std::size_t(slot->home->copy_slot) * kPage; + } + + // The page at `va` was written (its physical page's bytes changed): its home is filled again, once however many + // pages show it. True when `va` is a mirrored page. + bool dirty(std::uint64_t va) { + const PageSlot* const slot = find_slot(va); + if (!slot || !slot->home) return false; + if (!slot->home->dirty) { + slot->home->dirty = true; + dirty_.push_back(slot->frame); + dirty_count_.store(dirty_.size(), std::memory_order_release); + } + return true; + } + // One aliased (filtered) page produced by upload() and handed to a batched filter callback. + struct AliasedPageJob { + std::uint64_t va = 0; + std::uint8_t* frame = nullptr; + std::uint8_t* to = nullptr; + const std::uint8_t* scratch = nullptr; + std::array mask{}; + bool fresh = false; + }; + + // Fills the homes dirty() (and deferred map()) named. Returns how many. + // For batches >= kParallelThreshold, fans out per-page guarded copy + 256-byte piece hashing + coalesced home + // writes across the internal worker pool (each worker owns disjoint homes and scratch slots), then accumulates + // counters, notifies `on_changed(frame, changed_pieces)` for each home that actually modified >= 1 piece, and runs + // filtered-heap callbacks sequentially on the calling thread in dirty_ order. + template + std::size_t upload(OnChanged&& on_changed) { + return upload_impl(std::forward(on_changed), nullptr); + } + // Batched-filter overload: collects every aliased home that needs filtering into `AliasedPageJob[]` (with its + // 64 KiB synced host snapshot in `scratch`) and invokes `filter_batch(jobs, count, pool, ok_out)` once for the + // entire upload batch so callers can hoist caches, run read-only Phase A in parallel across `pool`, and run + // mutating Phase B sequentially under their mirror lock. + template + std::size_t upload(OnChanged&& on_changed, FilterBatch&& filter_batch) { + return upload_impl(std::forward(on_changed), &filter_batch); + } + std::size_t upload() { + return upload([](std::uint8_t*, const std::array&) {}); + } + + // A mirrored page snapshotted for GPU write-back readback: carries its chunk location and the physical frame it + // showed at snapshot time, so the caller can release the mirror mutex during the GPU copy and write_back_batch() + // can skip any page remapped or given a pending bind meanwhile. + struct HomeRef { + std::uint64_t page = 0; + VkBuffer chunk = VK_NULL_HANDLE; + VkDeviceSize offset = 0; + std::uint8_t* frame = nullptr; + }; + + // True when the 64 KiB page at `va` has an unflushed bind/unbind in pending_: the sparse chunk on the GPU does not + // yet reflect pages_[va], so reading back from chunk_at(va) would read the previous binding (or zeros). + bool has_pending(std::uint64_t va) const { + if (!has_pending_binds() || pending_.empty()) return false; + const std::uint64_t page = va & ~(kPage - 1); + const std::uint64_t chunk = page / kChunk; + const auto it = pending_.find(chunk); + return it != pending_.end() && it->second.count(page - chunk * kChunk) != 0; + } + + // The mirrored pages of [begin, end) that have a flushed home, in address order: what write_back reads. Pages with + // an unflushed bind in pending_ are skipped so the caller never copies a stale chunk binding. + void homes_in(std::uint64_t begin, std::uint64_t end, std::vector& out) const { + if (begin >= end) return; + const bool any_pending = has_pending_binds() && !pending_.empty(); + for (std::uint64_t page = begin & ~(kPage - 1); page < end;) { + const std::uint64_t c = page / kChunk; + const ChunkDirEntry* const dir = find_chunk_dir(c); + const std::uint64_t chunk_end = (c < UINT64_MAX / kChunk) ? ((c + 1) * kChunk) : UINT64_MAX; + if (!dir || dir->chunk->mapped_count == 0) { + if (chunk_end >= end || chunk_end <= page) break; + page = chunk_end; + continue; + } + const std::uint64_t limit = (std::min)(end, chunk_end); + const PageSlot* const slots = dir->pages; + for (; page < limit; page += kPage) { + const PageSlot& s = slots[std::size_t((page - c * kChunk) / kPage)]; + if (s.home && (!any_pending || !has_pending(page))) out.push_back(page); + if (page > UINT64_MAX - kPage) return; + } + } + } + + // Deduplicated, page-sorted HomeRefs for every flushed mirrored page overlapping any [begin, end) in `ranges`. + std::vector homes_in_ranges(const std::vector>& ranges) const { + std::vector out; + if (ranges.empty()) return out; + std::vector> owned; + const auto& merged = is_sorted_disjoint_ranges(ranges) ? ranges : (owned = merge_ranges(ranges)); + const bool any_pending = has_pending_binds() && !pending_.empty(); + for (const auto& [begin, end] : merged) { + for (std::uint64_t page = begin & ~(kPage - 1); page < end;) { + const std::uint64_t c = page / kChunk; + const ChunkDirEntry* const dir = find_chunk_dir(c); + const std::uint64_t chunk_end = (c < UINT64_MAX / kChunk) ? ((c + 1) * kChunk) : UINT64_MAX; + if (!dir || dir->chunk->mapped_count == 0) { + if (chunk_end >= end || chunk_end <= page) break; + page = chunk_end; + continue; + } + const std::uint64_t limit = (std::min)(end, chunk_end); + const PageSlot* const slots = dir->pages; + const VkBuffer buf = dir->buffer; + const std::uint64_t chunk_base = c * kChunk; + for (; page < limit; page += kPage) { + if (out.empty() || page > out.back().page) { + const PageSlot& s = slots[std::size_t((page - chunk_base) / kPage)]; + if (s.home && (!any_pending || !has_pending(page))) + out.push_back({page, buf, page - chunk_base, s.frame}); + } + if (page > UINT64_MAX - kPage) return out; + } + } + } + return out; + } + + // Lock-free Phase 1 output for async readback: per-page scan mask and precomputed 256-byte GPU piece hashes over + // the readback staging buffer. Computed entirely outside `page_mirror.mutex`, then consumed in O(pages) under the + // mirror lock by write_back_prehashed(). + struct PrehashedReadback { + struct PagePlan { + std::array scan_mask{}; + bool full_page = false; + bool any_piece = false; + }; + std::vector plans; + std::vector sums; // count * kPieces + }; + + static void prehash_readback_slice(const HomeRef* slice, std::size_t count, + const std::vector>& ranges, + const std::uint8_t* staged, PrehashedReadback& out, + WorkerPool* pool = nullptr) { + out.plans.clear(); + if (!slice || !count || !staged || ranges.empty()) return; + std::vector> owned; + const auto& merged = is_sorted_disjoint_ranges(ranges) ? ranges : (owned = merge_ranges(ranges)); + if (merged.empty()) return; + + out.plans.assign(count, PrehashedReadback::PagePlan{}); + std::size_t active_pages = 0; + std::size_t cursor = 0; + for (std::size_t i = 0; i < count; ++i) { + const HomeRef& ref = slice[i]; + if (i > 0 && ref.page < slice[i - 1].page) cursor = 0; + while (cursor < merged.size() && merged[cursor].second <= ref.page) ++cursor; + if (cursor >= merged.size()) break; + if (merged[cursor].first >= ref.page + kPage) continue; + auto& plan = out.plans[i]; + std::size_t next_k = 0; + std::size_t piece_count = 0; + for (std::size_t r = cursor; r < merged.size() && merged[r].first < ref.page + kPage; ++r) { + const std::uint64_t lo = (std::max)(merged[r].first, ref.page); + const std::uint64_t hi = (std::min)(merged[r].second, ref.page + kPage); + if (lo >= hi) continue; + const std::size_t k0 = (std::max)(next_k, std::size_t((lo - ref.page) / kPiece)); + const std::size_t k1 = std::size_t((hi - ref.page + kPiece - 1) / kPiece); + if (k0 < k1) { + set_piece_range(plan.scan_mask, k0, k1); + piece_count += k1 - k0; + next_k = k1; + } + } + if (piece_count) { + plan.any_piece = true; + plan.full_page = (piece_count == kPieces); + ++active_pages; + } + } + if (!active_pages) return; + + const std::size_t need_sums = count * kPieces; + if (out.sums.size() < need_sums) out.sums.resize(need_sums); + + const auto hash_range = [&](std::size_t b, std::size_t e) { + for (std::size_t i = b; i < e; ++i) { + const auto& plan = out.plans[i]; + if (!plan.any_piece) continue; + const std::uint8_t* const gpu = staged + i * kPage; + std::uint64_t* const dst = out.sums.data() + i * kPieces; + if (plan.full_page) { + shadow_keep::sum_of_batch_256(gpu, kPieces, dst); + } else { + std::size_t run_start = kPieces; + for (std::size_t w = 0; w < 4; ++w) { + const std::uint64_t word = plan.scan_mask[w]; + if (!word) { + if (run_start < kPieces) { + shadow_keep::sum_of_batch_256(gpu + run_start * kPiece, w * 64 - run_start, + dst + run_start); + run_start = kPieces; + } + continue; + } + if (word == ~std::uint64_t(0)) { + if (run_start == kPieces) run_start = w * 64; + continue; + } + std::size_t bit = 0; + while (bit < 64) { + const std::uint64_t rem = word >> bit; + if (!rem) { + if (run_start < kPieces) { + shadow_keep::sum_of_batch_256(gpu + run_start * kPiece, w * 64 + bit - run_start, + dst + run_start); + run_start = kPieces; + } + break; + } + const std::size_t zeros = std::size_t(std::countr_zero(rem)); + if (zeros > 0) { + if (run_start < kPieces) { + shadow_keep::sum_of_batch_256(gpu + run_start * kPiece, w * 64 + bit - run_start, + dst + run_start); + run_start = kPieces; + } + bit += zeros; + } + const std::size_t ones = std::size_t(std::countr_one(word >> bit)); + if (run_start == kPieces) run_start = w * 64 + bit; + bit += ones; + } + } + if (run_start < kPieces) { + shadow_keep::sum_of_batch_256(gpu + run_start * kPiece, kPieces - run_start, dst + run_start); + } + } + } + }; + + if (pool && active_pages >= kParallelThreshold) { + const std::size_t workers = pool->worker_count(); + const std::size_t chunk = (std::max)(std::size_t(1), (std::min)(std::size_t(4), count / (workers * 2))); + pool->run(count, chunk, [&](std::size_t b, std::size_t e, std::size_t) { hash_range(b, e); }); + } else { + hash_range(0, count); + } + } + + // Phase 2 of lock-free readback: compares precomputed GPU piece sums against live `home.sums[]` under the mirror + // lock (O(pieces) uint64 compares, zero GPU-buffer hashing) and writes back coalesced non-conflicting runs. + // `skip_masks` (optional, size `count`): per-slice 256-bit masks of pieces concurrently overwritten by upload() + // while the GPU copy was in flight (CPU wins under the conflict rule; skipped without retrying the page). + // `skip_page` (optional, size `count`): non-zero entries are skipped whole (e.g. externally invalidated frames). + template + std::uint64_t write_back_prehashed(const HomeRef* slice, std::size_t count, const PrehashedReadback& prehashed, + const std::uint8_t* staged, const std::array* skip_masks, + const std::uint8_t* skip_page, Write&& write) { + if (!slice || !count || !staged || prehashed.plans.size() < count) return 0; + std::uint64_t written = 0; + std::vector refilter_frames; + for (std::size_t i = 0; i < count; ++i) { + if (skip_page && skip_page[i]) continue; + const auto& plan = prehashed.plans[i]; + if (!plan.any_piece) continue; + const HomeRef& ref = slice[i]; + if (has_pending(ref.page)) continue; + const PageSlot* const slot = find_slot(ref.page); + if (!slot || slot->frame != ref.frame || !slot->home) continue; + + const std::uint64_t* const gpu_sums = prehashed.sums.data() + i * kPieces; + const std::uint64_t* const agreed = home_sums(*slot->home); + const std::array* const sm = skip_masks ? &skip_masks[i] : nullptr; + + std::array diff_mask{}; + std::size_t diff_count = 0; + if (plan.full_page && (!sm || ((*sm)[0] | (*sm)[1] | (*sm)[2] | (*sm)[3]) == 0)) { + for (std::size_t k = 0; k < kPieces; ++k) { + if (gpu_sums[k] != agreed[k]) { + diff_mask[k >> 6] |= std::uint64_t(1) << (k & 63); + ++diff_count; + } + } + } else { + for (std::size_t w = 0; w < 4; ++w) { + std::uint64_t m = plan.scan_mask[w] & ~(sm ? (*sm)[w] : 0ull); + while (m) { + const unsigned bit = static_cast(std::countr_zero(m)); + m &= m - 1; + const std::size_t k = w * 64 + bit; + if (gpu_sums[k] != agreed[k]) { + diff_mask[w] |= std::uint64_t(1) << bit; + ++diff_count; + } + } + } + } + if (!diff_count) continue; + written += write_back_diff_coalesced(*slot->home, ref.page, slot->frame, staged + i * kPage, gpu_sums, + diff_mask, diff_count, write, refilter_frames); + } + finish_write_back(written, refilter_frames); + return written; + } + + // The home of the page at `va`, mapped (its host bytes): the title's bytes as the GPU reads them at the title's + // address. Null when the page is not mapped. + std::uint8_t* home_bytes(std::uint64_t va) { + const PageSlot* const slot = find_slot(va); + if (!slot || !slot->home) return nullptr; + return units_[slot->home->unit].host + std::size_t(slot->home->slot) * kPage; + } + + // What the GPU wrote into the homes of the mirrored pages of [begin, end) goes back to each page's physical frame, + // merged at the 256-byte piece against the sums both sides last agreed on: a piece only the GPU changed is written + // back with `write(frame_dst, bytes, n)` (and agreed on again); a piece only the title changed waits for the + // upload; a piece both changed keeps the title's bytes and is counted. `write` receives the physical frame address + // (`slot->frame + k * kPiece`, identical to the title VA for ordinary memory and the writable scratch view for + // xmem physical pages), so a concurrent CPU remap of `va` never receives the previous mapping's bytes. Pages with + // an unflushed bind in pending_ are skipped. `staged(page)` gives the page's home as the GPU left it, or nullptr to + // skip the page. Returns the bytes written back. + // The same, reading each home where it lies (host memory: the tests' homes; the device copies its homes out first). + template + std::uint64_t write_back(std::uint64_t begin, std::uint64_t end, Write&& write) { + return write_back(begin, end, [this](std::uint64_t page) -> const std::uint8_t* { return home_bytes(page); }, + std::forward(write)); + } + template + std::uint64_t write_back(std::uint64_t begin, std::uint64_t end, Staged&& staged, Write&& write) { + if (begin >= end) return 0; + std::uint64_t written = 0; + std::vector refilter_frames; + for (std::uint64_t page = begin & ~(kPage - 1); page < end; page += kPage) { + if (!has_pending(page)) { + const PageSlot* const slot = find_slot(page); + if (slot && slot->home) { + if (const std::uint8_t* gpu = staged(page)) { + const std::size_t k0 = std::size_t(((std::max)(begin, page) - page) / kPiece); + const std::size_t k1 = std::size_t(((std::min)(end, page + kPage) - page + kPiece - 1) / kPiece); + written += write_back_pieces(*slot->home, page, slot->frame, gpu, k0, k1, write, + refilter_frames); + } + } + } + if (page > UINT64_MAX - kPage) break; + } + finish_write_back(written, refilter_frames); + return written; + } + + // Batched multi-range write-back over `count` snapshotted HomeRefs whose GPU copies lie contiguously at + // `staged + i * kPage`. Skips any page that now has a pending bind or was remapped to a different physical frame + // since `homes_in_ranges()` snapshotted it. + // For batches >= kParallelThreshold, scans 256-byte piece hashes read-only across the internal worker pool, then + // applies only changed pieces (conflict checks, write() callbacks, stats, and refilters) sequentially in exact + // batch order on the calling thread. + template + std::uint64_t write_back_batch(const HomeRef* batch, std::size_t count, + const std::vector>& ranges, + const std::uint8_t* staged, Write&& write) { + if (!batch || !count || !staged || ranges.empty()) return 0; + std::vector> owned; + const auto& merged = is_sorted_disjoint_ranges(ranges) ? ranges : (owned = merge_ranges(ranges)); + if (merged.empty()) return 0; + std::uint64_t written = 0; + std::vector refilter_frames; + if (!parallel_enabled_ || count < kParallelThreshold) { + std::size_t cursor = 0; + for (std::size_t i = 0; i < count; ++i) { + const HomeRef& ref = batch[i]; + if (i > 0 && ref.page < batch[i - 1].page) cursor = 0; + while (cursor < merged.size() && merged[cursor].second <= ref.page) ++cursor; + if (cursor >= merged.size()) break; + if (merged[cursor].first >= ref.page + kPage) continue; + if (has_pending(ref.page)) continue; + const PageSlot* const slot = find_slot(ref.page); + if (!slot || slot->frame != ref.frame || !slot->home) continue; + const std::uint8_t* gpu = staged + i * kPage; + std::size_t next_k = 0; + for (std::size_t r = cursor; r < merged.size() && merged[r].first < ref.page + kPage; ++r) { + const std::uint64_t lo = (std::max)(merged[r].first, ref.page); + const std::uint64_t hi = (std::min)(merged[r].second, ref.page + kPage); + if (lo >= hi) continue; + const std::size_t k0 = (std::max)(next_k, std::size_t((lo - ref.page) / kPiece)); + const std::size_t k1 = std::size_t((hi - ref.page + kPiece - 1) / kPiece); + if (k0 < k1) { + written += write_back_pieces(*slot->home, ref.page, slot->frame, gpu, k0, k1, write, + refilter_frames); + next_k = k1; + } + } + } + finish_write_back(written, refilter_frames); + return written; + } + + wb_jobs_.clear(); + wb_jobs_.reserve(count); + bool any_shared_home = false; + std::size_t cursor = 0; + for (std::size_t i = 0; i < count; ++i) { + const HomeRef& ref = batch[i]; + if (i > 0 && ref.page < batch[i - 1].page) cursor = 0; + while (cursor < merged.size() && merged[cursor].second <= ref.page) ++cursor; + if (cursor >= merged.size()) break; + if (merged[cursor].first >= ref.page + kPage) continue; + if (has_pending(ref.page)) continue; + const PageSlot* const slot = find_slot(ref.page); + if (!slot || slot->frame != ref.frame || !slot->home) continue; + + WriteBackJob job; + job.home = slot->home; + job.page = ref.page; + job.frame = slot->frame; + job.gpu = staged + i * kPage; + job.sums = home_sums(*slot->home); + if (slot->home->refs > 1) any_shared_home = true; + + std::size_t next_k = 0; + std::size_t piece_count = 0; + for (std::size_t r = cursor; r < merged.size() && merged[r].first < ref.page + kPage; ++r) { + const std::uint64_t lo = (std::max)(merged[r].first, ref.page); + const std::uint64_t hi = (std::min)(merged[r].second, ref.page + kPage); + if (lo >= hi) continue; + const std::size_t k0 = (std::max)(next_k, std::size_t((lo - ref.page) / kPiece)); + const std::size_t k1 = std::size_t((hi - ref.page + kPiece - 1) / kPiece); + if (k0 < k1) { + set_piece_range(job.scan_mask, k0, k1); + piece_count += k1 - k0; + next_k = k1; + } + } + if (!piece_count) continue; + job.full_page = (piece_count == kPieces); + wb_jobs_.push_back(job); + } + + const std::size_t n_jobs = wb_jobs_.size(); + if (!n_jobs) return 0; + + if (n_jobs < kParallelThreshold || !ensure_pool()) { + for (const WriteBackJob& job : wb_jobs_) { + written += write_back_masked(*job.home, job.page, job.frame, job.gpu, job.scan_mask, job.full_page, + write, refilter_frames); + } + finish_write_back(written, refilter_frames); + return written; + } + + // Phase 1 (parallel, read-only over staged and home.sums[]): compute 256-bit diff_mask per page. + const std::size_t workers = pool_->worker_count(); + const std::size_t chunk = (std::max)(std::size_t(1), (std::min)(std::size_t(4), n_jobs / (workers * 2))); + pool_->run(n_jobs, chunk, [this](std::size_t b, std::size_t e, std::size_t) { + std::uint64_t tmp_sums[kPieces]; + for (std::size_t i = b; i < e; ++i) { + WriteBackJob& job = wb_jobs_[i]; + std::uint16_t diffs = 0; + if (job.full_page) { + shadow_keep::sum_of_batch_256(job.gpu, kPieces, tmp_sums); + for (std::size_t k = 0; k < kPieces; ++k) { + if (tmp_sums[k] != job.sums[k]) { + job.diff_mask[k >> 6] |= std::uint64_t(1) << (k & 63); + ++diffs; + } + } + } else { + for (std::size_t w = 0; w < 4; ++w) { + std::uint64_t m = job.scan_mask[w]; + while (m) { + const unsigned bit = static_cast(std::countr_zero(m)); + m &= m - 1; + const std::size_t k = w * 64 + bit; + if (shadow_keep::sum_of(job.gpu + k * kPiece, kPiece) != job.sums[k]) { + job.diff_mask[w] |= std::uint64_t(1) << bit; + ++diffs; + } + } + } + } + job.diff_count = diffs; + } + }); + + // Phase 2 (sequential on calling thread in exact batch order): apply only changed pieces. + // If two HomeRefs in the batch alias the same physical frame and an earlier one updated home.sums[], fall back + // to scanning the later alias's scan_mask sequentially so conflict resolution matches single-threaded order. + std::vector modified_shared_frames; + for (const WriteBackJob& job : wb_jobs_) { + const bool frame_modified_earlier = + any_shared_home && !modified_shared_frames.empty() && + std::find(modified_shared_frames.begin(), modified_shared_frames.end(), job.frame) != + modified_shared_frames.end(); + if (!job.diff_count && !frame_modified_earlier) continue; + const std::uint64_t page_written = + frame_modified_earlier + ? write_back_masked(*job.home, job.page, job.frame, job.gpu, job.scan_mask, job.full_page, write, + refilter_frames) + : write_back_masked(*job.home, job.page, job.frame, job.gpu, job.diff_mask, false, write, + refilter_frames); + if (page_written) { + written += page_written; + if (any_shared_home && job.home->refs > 1 && !frame_modified_earlier) + modified_shared_frames.push_back(job.frame); + } + } + finish_write_back(written, refilter_frames); + return written; + } + template + std::uint64_t write_back_batch(const std::vector& batch, + const std::vector>& ranges, + const std::uint8_t* staged, Write&& write) { + return write_back_batch(batch.data(), batch.size(), ranges, staged, std::forward(write)); + } + + // The binds noted since the last flush, as one batch signalling `value`. False when there were none (nothing to + // wait for) or the bind failed (counted; the caller logs). + bool flush(std::uint64_t value) { + if (pending_.empty() && alias_pending_.empty()) return false; + std::size_t binds = 0; + for (const auto& [chunk, by_offset] : pending_) binds += by_offset.size(); + for (const auto& [buffer, by_offset] : alias_pending_) binds += by_offset.size(); + last_batch_ = binds; + // The last bind of a page in this batch is the one that counts: binds of one range in one batch are not + // ordered by the API. + std::vector> lists; + std::vector infos; + lists.reserve(pending_.size() + alias_pending_.size()); + for (auto& [chunk, by_offset] : pending_) { + auto& list = lists.emplace_back(); + list.reserve(by_offset.size()); + for (const auto& [offset, bind] : by_offset) list.push_back(bind); + infos.push_back({chunks_[chunk].buffer, std::uint32_t(list.size()), list.data()}); + } + // The aliases' binds in the same batch, so the one wait orders a reader of either address. + for (auto& [buffer, by_offset] : alias_pending_) { + auto& list = lists.emplace_back(); + list.reserve(by_offset.size()); + for (const auto& [offset, bind] : by_offset) list.push_back(bind); + infos.push_back({buffer, std::uint32_t(list.size()), list.data()}); + } + const bool ok = hooks_.bind && hooks_.bind(infos, value); + ++counters_.batches; + pending_.clear(); + alias_pending_.clear(); + has_pending_binds_.store(false, std::memory_order_release); + return ok; + } + + // Stamps every unstamped freed home (queued by map()/unalias() with kUnstamped) with `ticket`, taken after + // flush() published the sparse unbind via note_mirror_bind(). Unstamped homes are never retired until stamped. + void stamp_freed(std::uint64_t ticket) { + if (unstamped_freed_.empty()) return; + for (const auto& [unit, slot] : unstamped_freed_) freed_.push_back({unit, slot, ticket}); + unstamped_freed_.clear(); + sync_freed_atomics(); + } + std::size_t unstamped_freed_count() const noexcept { return unstamped_freed_.size(); } + + // Frees the homes no page binds any more whose last reader has retired (`completed` ticket). + void retire(std::uint64_t completed) { + if (freed_.empty()) return; + bool popped = false; + while (!freed_.empty() && freed_.front().ticket <= completed) { + const auto [unit, slot, ticket] = freed_.front(); + freed_.pop_front(); + units_[unit].free.push_back(slot); + ++counters_.homes_freed; + popped = true; + } + if (popped) sync_freed_atomics(); + } + + // Lock-free O(1) clean fast-path queries so before_execute_() / flush_page_mirror() skip taking page_mirror.mutex + // and completed_retire_ticket() when nothing is pending. + bool has_pending_binds() const noexcept { return has_pending_binds_.load(std::memory_order_acquire); } + bool has_dirty() const noexcept { return dirty_count_.load(std::memory_order_acquire) != 0; } + bool has_pending_work() const noexcept { return has_pending_binds() || has_dirty(); } + bool has_retired_homes() const noexcept { return freed_count_.load(std::memory_order_acquire) != 0; } + bool has_retired_homes(std::uint64_t completed) const noexcept { + return freed_count_.load(std::memory_order_acquire) != 0 && + oldest_freed_ticket_.load(std::memory_order_acquire) <= completed; + } + std::uint64_t last_upload_bytes() const noexcept { return last_upload_bytes_; } + std::size_t last_whole_pages() const noexcept { return last_whole_pages_; } + std::size_t last_inc_pages() const noexcept { return last_inc_pages_; } + std::size_t last_aliased_pages() const noexcept { return last_aliased_pages_; } + + // The home's memory and offset of the mirrored page at `va` (tests and diagnostics). + bool home_at(std::uint64_t va, VkDeviceMemory& memory, VkDeviceSize& offset, std::uint8_t** host = nullptr) const { + const PageSlot* const slot = find_slot(va); + if (!slot || !slot->home) return false; + memory = units_[slot->home->unit].memory; + offset = VkDeviceSize(slot->home->slot) * kPage; + if (host) *host = units_[slot->home->unit].host + offset; + return true; + } + bool mirrored(std::uint64_t va) const { + const PageSlot* const slot = find_slot(va); + return slot && slot->frame != nullptr; + } + // Mixes the cached 256-byte piece hashes (Home::sums[]) for every 256-byte piece overlapping [va, va + bytes). + // Returns false when bytes == 0, the range overflows, or any 64 KiB page in [va, va + bytes) is not mirrored or + // has no home. Zero reads of title or device memory: O(overlapping 256-byte pieces). + bool range_sum(std::uint64_t va, std::uint64_t bytes, std::uint64_t& out_hash) const { + if (!bytes || va + bytes < va) return false; + const std::uint64_t end = va + bytes; + std::uint64_t h = 14695981039346656037ull ^ bytes; + for (std::uint64_t page = va & ~(kPage - 1); page < end;) { + const std::uint64_t c = page / kChunk; + const ChunkDirEntry* const dir = find_chunk_dir(c); + if (!dir) return false; + const std::uint64_t chunk_base = c * kChunk; + const std::uint64_t chunk_end = (c < UINT64_MAX / kChunk) ? ((c + 1) * kChunk) : UINT64_MAX; + const std::uint64_t limit = (std::min)(end, chunk_end); + const PageSlot* const slots = dir->pages; + for (; page < limit; page += kPage) { + const PageSlot& s = slots[std::size_t((page - chunk_base) / kPage)]; + if (!s.home || s.home->whole_fill) return false; + const std::uint64_t page_end = (page <= UINT64_MAX - kPage) ? (page + kPage) : UINT64_MAX; + const std::uint64_t lo = (std::max)(va, page); + const std::uint64_t hi = (std::min)(end, page_end); + const std::size_t k0 = std::size_t((lo - page) / kPiece); + const std::size_t k1 = std::size_t((hi - page + kPiece - 1) / kPiece); + const std::uint64_t* const sums = home_sums(*s.home); + for (std::size_t k = k0; k < k1; ++k) { + h = (h ^ sums[k]) * 1099511628211ull; + h ^= h >> 29; + } + if (page > UINT64_MAX - kPage) break; + } + if (page > UINT64_MAX - kPage) break; + } + out_hash = h; + return true; + } + // The physical page's bytes the mirrored page at `va` shows (its frame; for ordinary memory the page itself). + std::uint8_t* frame_at(std::uint64_t va) const { + const PageSlot* const slot = find_slot(va); + return slot ? slot->frame : nullptr; + } + // The chunk over `va` and the offset of `va` in it (tests and diagnostics). + bool chunk_at(std::uint64_t va, VkBuffer& buffer, VkDeviceSize& offset) const { + const std::uint64_t c = va / kChunk; + const ChunkDirEntry* const dir = find_chunk_dir(c); + if (!dir) return false; + buffer = dir->buffer; + offset = va - c * kChunk; + return true; + } + + Counters counters() const { + Counters c = counters_; + c.homes = homes_.size(); + c.units = units_.size(); + c.pages = pages_count_; + return c; + } + +private: + // A home and the sum of each of its 256-byte pieces as both sides last agreed on it (src/shadow_keep.h): what was + // filled from the title's page, or written back to it. A piece whose home differs from its sum was written by the + // GPU, one whose title page differs by the title. + static constexpr std::size_t kPiece = shadow_keep::kPiece, kPieces = kPage / kPiece; + struct Home { + std::uint32_t unit = 0, slot = 0, refs = 0; + std::shared_ptr keep; + bool dirty = false; + bool whole_fill = false; // deferred initial fill from map(..., defer_fill=true) + // The filtered copy (alias): its own slot, bound at the alias of `filter_va`, the aliased page it was made for. + bool copy = false; + std::uint32_t copy_unit = 0, copy_slot = 0; + std::uint64_t filter_va = 0; + bool fresh = true; // the copy's next fill writes every byte (hooks.filter's `fresh`) + bool refilter = false; // the title's bytes changed outside an upload (write_back): fill the copy + }; + struct Alias { + std::uint64_t hi; + VkBuffer buffer; + VkDeviceSize offset; + }; + struct Unit { + VkDeviceMemory memory = VK_NULL_HANDLE; + std::uint8_t* host = nullptr; + std::unique_ptr sums; // contiguous slab: kUnitPages * kPieces (0 heap allocs per Home) + std::vector free; + }; + + std::uint64_t* home_sums(const Home& h) noexcept { + return units_[h.unit].sums.get() + std::size_t(h.slot) * kPieces; + } + const std::uint64_t* home_sums(const Home& h) const noexcept { + return units_[h.unit].sums.get() + std::size_t(h.slot) * kPieces; + } + struct Freed { + std::uint32_t unit, slot; + std::uint64_t ticket; + }; + + static bool is_sorted_disjoint_ranges(const std::vector>& ranges) noexcept { + for (std::size_t i = 0; i < ranges.size(); ++i) { + if (ranges[i].first >= ranges[i].second) return false; + if (i > 0 && ranges[i].first <= ranges[i - 1].second) return false; + } + return true; + } + + static std::vector> merge_ranges( + const std::vector>& ranges) { + std::vector> sorted; + sorted.reserve(ranges.size()); + for (const auto& [b, e] : ranges) + if (b < e) sorted.emplace_back(b, e); + if (sorted.size() <= 1) return sorted; + std::sort(sorted.begin(), sorted.end()); + std::vector> merged; + merged.reserve(sorted.size()); + for (const auto& [b, e] : sorted) { + if (!merged.empty() && b <= merged.back().second) { + if (e > merged.back().second) merged.back().second = e; + } else { + merged.emplace_back(b, e); + } + } + return merged; + } + + static void set_piece_range(std::array& mask, std::size_t k0, std::size_t k1) noexcept { + if (k0 >= k1) return; + const std::size_t w0 = k0 >> 6; + const std::size_t w1 = (k1 - 1) >> 6; + const std::uint64_t lo_mask = ~std::uint64_t(0) << (k0 & 63); + const std::size_t hi_bits = k1 & 63; + const std::uint64_t hi_mask = hi_bits ? ((std::uint64_t(1) << hi_bits) - 1) : ~std::uint64_t(0); + if (w0 == w1) { + mask[w0] |= lo_mask & hi_mask; + } else { + mask[w0] |= lo_mask; + for (std::size_t w = w0 + 1; w < w1; ++w) mask[w] = ~std::uint64_t(0); + mask[w1] |= hi_mask; + } + } + + // Conflict-checks the GPU-differing pieces in `diff_mask` against the title's physical frame (using a single + // whole-page guarded copy when >= 2 pieces differ on the page) and coalesces contiguous non-conflicting pieces + // into single `write(frame_dst, gpu_src, run_bytes)` calls (falling back piece-by-piece if a multi-piece write + // fails). `pre_sums` holds the already-computed GPU piece sums for every bit set in `diff_mask`. + // Supports either a plain callable `write(dst, bytes, n)` or a page-aware writer providing + // `begin_page(page_va, frame, first_off, span_bytes)` + `write(guard, dst, bytes, n)`. + template + std::uint64_t write_back_diff_coalesced(Home& home, std::uint64_t page_va, std::uint8_t* frame, + const std::uint8_t* gpu, const std::uint64_t* pre_sums, + const std::array& diff_mask, std::size_t diff_count, + Write&& write, std::vector& refilter_frames) { + if (!diff_count) return 0; + std::uint64_t* const sums = home_sums(home); + bool whole_title_ok = false; + if (diff_count >= 2) { + whole_title_ok = hooks_.copy ? hooks_.copy(fill_scratch_.data(), frame, kPage) + : (std::memcpy(fill_scratch_.data(), frame, kPage), true); + } + std::array write_mask{}; + std::size_t write_count = 0; + alignas(64) std::uint8_t title_piece[kPiece]; + for (std::size_t w = 0; w < 4; ++w) { + std::uint64_t m = diff_mask[w]; + while (m) { + const unsigned bit = static_cast(std::countr_zero(m)); + m &= m - 1; + const std::size_t k = w * 64 + bit; + const std::uint64_t agreed = sums[k]; + if (pre_sums[k] == agreed) continue; + const std::uint8_t* title_ptr = nullptr; + if (whole_title_ok) { + title_ptr = fill_scratch_.data() + k * kPiece; + } else { + const std::uint8_t* from = frame + k * kPiece; + if (!(hooks_.copy ? hooks_.copy(title_piece, from, kPiece) + : (std::memcpy(title_piece, from, kPiece), true))) + continue; // the title's page went away + title_ptr = title_piece; + } + if (shadow_keep::sum_of(title_ptr, kPiece) != agreed) { + ++counters_.conflicts; // both changed it: the title's bytes win at the next upload + continue; + } + write_mask[w] |= std::uint64_t(1) << bit; + ++write_count; + } + } + if (!write_count) return 0; + + std::uint64_t written = 0; + const auto frame_base = reinterpret_cast(frame); + const auto emit_runs = [&](auto&& do_write) { + const auto flush_run = [&](std::size_t run_start, std::size_t run_end) { + const std::size_t run_pieces = run_end - run_start; + if (do_write(static_cast(frame_base + run_start * kPiece), gpu + run_start * kPiece, + run_pieces * kPiece)) { + for (std::size_t k = run_start; k < run_end; ++k) sums[k] = pre_sums[k]; + written += std::uint64_t(run_pieces) * kPiece; + return; + } + if (run_pieces == 1) return; + for (std::size_t k = run_start; k < run_end; ++k) { + if (do_write(static_cast(frame_base + k * kPiece), gpu + k * kPiece, kPiece)) { + sums[k] = pre_sums[k]; + written += kPiece; + } + } + }; + + std::size_t run_start = kPieces; + for (std::size_t w = 0; w < 4; ++w) { + const std::uint64_t word = write_mask[w]; + if (!word) { + if (run_start < kPieces) { + flush_run(run_start, w * 64); + run_start = kPieces; + } + continue; + } + if (word == ~std::uint64_t(0)) { + if (run_start == kPieces) run_start = w * 64; + continue; + } + std::size_t bit = 0; + while (bit < 64) { + const std::uint64_t rem = word >> bit; + if (!rem) { + if (run_start < kPieces) { + flush_run(run_start, w * 64 + bit); + run_start = kPieces; + } + break; + } + const std::size_t zeros = std::size_t(std::countr_zero(rem)); + if (zeros > 0) { + if (run_start < kPieces) { + flush_run(run_start, w * 64 + bit); + run_start = kPieces; + } + bit += zeros; + } + const std::size_t ones = std::size_t(std::countr_one(word >> bit)); + if (run_start == kPieces) run_start = w * 64 + bit; + bit += ones; + } + } + if (run_start < kPieces) flush_run(run_start, kPieces); + }; + + constexpr bool kPageAware = requires(Write& wr, std::uint64_t va, std::uint8_t* fr, std::size_t off, + std::size_t len, const std::uint8_t* src) { + wr.write(wr.begin_page(va, fr, off, len), va, src, len); + }; + if constexpr (kPageAware) { + std::size_t first_piece = kPieces; + std::size_t last_piece = 0; + for (std::size_t w = 0; w < 4; ++w) { + if (!write_mask[w]) continue; + const std::size_t lo = w * 64 + std::size_t(std::countr_zero(write_mask[w])); + const std::size_t hi = w * 64 + 64 - std::size_t(std::countl_zero(write_mask[w])); + if (first_piece == kPieces) first_piece = lo; + last_piece = hi; + } + const auto page_guard = + write.begin_page(page_va, frame, first_piece * kPiece, (last_piece - first_piece) * kPiece); + emit_runs([&](std::uint64_t dst, const std::uint8_t* bytes, std::size_t n) { + return write.write(page_guard, dst, bytes, n); + }); + } else { + emit_runs( + [&](std::uint64_t dst, const std::uint8_t* bytes, std::size_t n) { return write(dst, bytes, n); }); + } + + if (written && home.copy && !home.refilter) { + home.refilter = true; // the title's bytes changed: its filtered copy follows + refilter_frames.push_back(frame); + } + return written; + } + + template + std::uint64_t write_back_pieces(Home& home, std::uint64_t page_va, std::uint8_t* frame, const std::uint8_t* gpu, + std::size_t k0, std::size_t k1, Write&& write, + std::vector& refilter_frames) { + std::array diff_mask{}; + std::uint64_t gpu_sums[kPieces]; + std::size_t diff_count = 0; + const std::uint64_t* const agreed = home_sums(home); + if (k0 < k1) shadow_keep::sum_of_batch_256(gpu + k0 * kPiece, k1 - k0, gpu_sums + k0); + for (std::size_t k = k0; k < k1; ++k) { + if (gpu_sums[k] != agreed[k]) { + diff_mask[k >> 6] |= std::uint64_t(1) << (k & 63); + ++diff_count; + } + } + if (!diff_count) return 0; + return write_back_diff_coalesced(home, page_va, frame, gpu, gpu_sums, diff_mask, diff_count, write, + refilter_frames); + } + + template + std::uint64_t write_back_masked(Home& home, std::uint64_t page_va, std::uint8_t* frame, const std::uint8_t* gpu, + const std::array& mask, bool full_page, Write&& write, + std::vector& refilter_frames) { + if (full_page) return write_back_pieces(home, page_va, frame, gpu, 0, kPieces, write, refilter_frames); + std::array diff_mask{}; + std::uint64_t gpu_sums[kPieces]; + std::size_t diff_count = 0; + const std::uint64_t* const agreed = home_sums(home); + for (std::size_t w = 0; w < 4; ++w) { + std::uint64_t m = mask[w]; + while (m) { + const unsigned bit = static_cast(std::countr_zero(m)); + m &= m - 1; + const std::size_t k = w * 64 + bit; + const std::uint64_t now = shadow_keep::sum_of(gpu + k * kPiece, kPiece); + if (now != agreed[k]) { + gpu_sums[k] = now; + diff_mask[w] |= std::uint64_t(1) << bit; + ++diff_count; + } + } + } + if (!diff_count) return 0; + return write_back_diff_coalesced(home, page_va, frame, gpu, gpu_sums, diff_mask, diff_count, write, + refilter_frames); + } + + void finish_write_back(std::uint64_t written, const std::vector& refilter_frames) { + counters_.written_back_bytes += written; + for (std::uint8_t* frame : refilter_frames) { + const auto it = homes_.find(frame); + if (it != homes_.end() && it->second.refilter) sync_and_fill_copy(it->second, frame, false); + } + } + + // Stateless per-page copy + 256-byte piece hash + coalesced WC home flush (safe to run across worker threads on + // disjoint homes and scratch buffers). Processes each 64 KiB page in 16 KiB (64 x 256 B) L1-hot strips through + // `hooks_.copy` + hoisted `shadow_keep::sum_of_batch_256()` + immediate L1-to-WC flush so non-aliased pages + // (`scratch == nullptr`) stay L1d-resident while cutting `hooks_.copy` calls 4x and mapping 1 uint64_t mask word + // per strip; aliased pages (`scratch != nullptr`) populate the full 64 KiB snapshot in `scratch` at the same time. + bool sync_page_into_scratch(std::uint8_t* to, std::uint8_t* scratch, std::uint64_t* sums, + const std::uint8_t* frame, bool whole, + std::array& changed_pieces, std::size_t& changed) const { + static_assert(kPage % kStripBytes == 0 && kStripPieces == 64 && kPage / kStripBytes == 4); + constexpr std::size_t kStrips = kPage / kStripBytes; + alignas(64) std::uint8_t local_strip[kStripBytes]; + std::uint64_t strip_sums[kStripPieces]; + + bool failed = false; + changed_pieces = {}; + changed = 0; + + for (std::size_t strip = 0; strip < kStrips; ++strip) { + const std::size_t strip_off = strip * kStripBytes; + const std::size_t base_k = strip * kStripPieces; + std::uint8_t* const strip_buf = scratch ? (scratch + strip_off) : local_strip; + std::uint64_t* const target_sums = whole ? (sums + base_k) : strip_sums; + + bool sums_ready = false; + bool strip_ok = false; + if (hooks_.copy_and_sum) { + strip_ok = hooks_.copy_and_sum(strip_buf, frame + strip_off, kStripPieces, target_sums); + sums_ready = strip_ok; + } else if (hooks_.copy) { + strip_ok = hooks_.copy(strip_buf, frame + strip_off, kStripBytes); + } else { + shadow_keep::copy_and_sum_256(strip_buf, frame + strip_off, kStripPieces, target_sums); + strip_ok = true; + sums_ready = true; + } + if (!strip_ok) { + for (std::size_t p = 0; p < kStripPieces; ++p) { + std::uint8_t* const piece = strip_buf + p * kPiece; + if (!hooks_.copy || !hooks_.copy(piece, frame + strip_off + p * kPiece, kPiece)) { + std::memset(piece, 0, kPiece); + failed = true; + } + } + sums_ready = false; + } + if (!sums_ready) shadow_keep::sum_of_batch_256(strip_buf, kStripPieces, target_sums); + + if (whole) { + std::memcpy(to + strip_off, strip_buf, kStripBytes); + } else { + std::uint64_t strip_mask = 0; + for (std::size_t p = 0; p < kStripPieces; ++p) { + if (strip_sums[p] != sums[base_k + p]) { + sums[base_k + p] = strip_sums[p]; + strip_mask |= std::uint64_t(1) << p; + ++changed; + } + } + if (strip_mask) { + changed_pieces[strip] = strip_mask; + if (strip_mask == ~std::uint64_t(0)) { + std::memcpy(to + strip_off, strip_buf, kStripBytes); + } else { + std::uint64_t m = strip_mask; + while (m) { + const unsigned r0 = static_cast(std::countr_zero(m)); + const unsigned ones = static_cast(std::countr_one(m >> r0)); + std::memcpy(to + strip_off + std::size_t(r0) * kPiece, + strip_buf + std::size_t(r0) * kPiece, std::size_t(ones) * kPiece); + const std::uint64_t run_mask = + (ones >= 64) ? ~std::uint64_t(0) : (((std::uint64_t(1) << ones) - 1) << r0); + m &= ~run_mask; + } + } + } + } + } + if (whole) { + changed = kPieces; + changed_pieces = kAllPieces; + } + return failed; + } + + // Brings the home up to date with the title's page, piece by piece: `whole` (a new home) copies every piece, and + // otherwise only a piece the title changed since both sides last agreed, so a piece only the GPU wrote keeps the + // GPU's bytes (and goes back with write_back). A piece both changed takes the title's bytes. Uses 16 KiB L1-hot + // strips (populating `fill_scratch_` only when the home has a filtered copy). Never reads from `to`. Returns + // whether any piece copy failed. + bool sync_home_from_frame(Home& home, const std::uint8_t* frame, bool whole, + std::array& changed_pieces, std::size_t& changed) { + std::uint8_t* const to = units_[home.unit].host + std::size_t(home.slot) * kPage; + std::uint8_t* const scratch = home.copy ? fill_scratch_.data() : nullptr; + const bool failed = + sync_page_into_scratch(to, scratch, home_sums(home), frame, whole, changed_pieces, changed); + counters_.uploaded_bytes += std::uint64_t(changed) * kPiece; + return failed; + } + + void fill_with_mask(Home& home, const std::uint8_t* frame, bool whole, + std::array& changed_pieces, std::size_t& changed) { + const bool failed = sync_home_from_frame(home, frame, whole, changed_pieces, changed); + // The filtered copy follows the title's bytes from the exact same `fill_scratch_` snapshot so `home.sums[]` + // and the filtered copy never diverge. + if (home.copy && (changed || home.fresh || home.refilter)) + fill_copy(home, fill_scratch_.data(), false, &changed_pieces); + if (failed) ++counters_.upload_failures; + ++counters_.uploads; + } + + void fill(Home& home, const std::uint8_t* frame, bool whole) { + std::array changed_pieces{}; + std::size_t changed = 0; + fill_with_mask(home, frame, whole, changed_pieces, changed); + } + + // Refreshes `home` and `home.sums[]` for any CPU-changed pieces (preserving GPU-only pieces) and filters the + // copy from that exact same snapshot (used by make_copy, alias handoff, and finish_write_back). + void sync_and_fill_copy(Home& home, const std::uint8_t* frame, bool whole_copy) { + const bool whole_home = std::exchange(home.whole_fill, false); + if (whole_home) home.dirty = false; + std::array changed_pieces{}; + std::size_t changed = 0; + const bool failed = sync_home_from_frame(home, frame, whole_home, changed_pieces, changed); + if (failed) ++counters_.upload_failures; + if (whole_home) ++counters_.uploads; + fill_copy(home, fill_scratch_.data(), whole_copy, &changed_pieces); + } + + Home* home_of(std::uint8_t* frame, std::shared_ptr keep, bool& created) { + if (const auto it = homes_.find(frame); it != homes_.end()) { + created = false; + return &it->second; + } + std::uint32_t unit = 0, slot = 0; + if (!take_slot(unit, slot)) return nullptr; + Home& home = homes_[frame]; + home.unit = unit; + home.slot = slot; + home.keep = std::move(keep); + std::memset(home_sums(home), 0, kPieces * sizeof(std::uint64_t)); + created = true; + return &home; + } + + bool aliased(std::uint64_t va) const { + auto it = aliases_.upper_bound(va); + if (it == aliases_.begin()) return false; + --it; + return va < it->second.hi; + } + // A filtered copy for an existing `home`, made for the aliased page at `va` and synced/filled whole now from one + // snapshot so `home`, `home.sums[]`, and the filtered copy stay in sync. No room: none (counted). + void make_copy(Home& home, const std::uint8_t* frame, std::uint64_t va) { + if (!take_slot(home.copy_unit, home.copy_slot)) { + ++counters_.upload_failures; + return; + } + home.copy = true; + home.filter_va = va; + home.fresh = true; + sync_and_fill_copy(home, frame, true); + } + static constexpr std::array kAllPieces = {~std::uint64_t(0), ~std::uint64_t(0), + ~std::uint64_t(0), ~std::uint64_t(0)}; + // Fills the filtered copy from the synced `scratch` snapshot through hooks.filter_pieces (preferred) or + // hooks.filter (`whole`: every byte). + void fill_copy(Home& home, const std::uint8_t* scratch, bool whole, + const std::array* changed_pieces = nullptr) { + const bool had_refilter = home.refilter; + home.refilter = false; + if (!home.copy) return; + std::uint8_t* to = units_[home.copy_unit].host + std::size_t(home.copy_slot) * kPage; + const bool fresh = whole || home.fresh; + home.fresh = false; + bool ok = false; + if (hooks_.filter_pieces) { + const auto& mask = (fresh || had_refilter || !changed_pieces) ? kAllPieces : *changed_pieces; + ok = hooks_.filter_pieces(home.filter_va, to, scratch, kPage, fresh, mask); + } else if (hooks_.filter) { + ok = hooks_.filter(home.filter_va, to, scratch, kPage, fresh); + } else { + std::memcpy(to, scratch, kPage); + ok = true; + } + if (!ok) { + std::memset(to, 0, kPage); + home.fresh = true; // zeros now: the next fill writes all again + ++counters_.upload_failures; + } + ++counters_.filtered; + } + // The filtered copy goes, after `ticket` (the submissions that could read it at the alias). + void drop_copy(Home& home, std::uint64_t ticket) { + if (!home.copy) return; + push_freed(home.copy_unit, home.copy_slot, ticket); + home.copy = false; + home.filter_va = 0; + home.fresh = true; + home.refilter = false; + } + // The bind of the page at `va` into every alias over it, into the next batch. + void note_alias_bind(std::uint64_t va, VkDeviceMemory memory, VkDeviceSize offset) { + if (aliases_.empty()) return; + auto it = aliases_.upper_bound(va); + if (it == aliases_.begin()) return; + --it; + if (va >= it->second.hi) return; + const VkDeviceSize at = it->second.offset + (va - it->first); + alias_pending_[it->second.buffer][at] = {at, kPage, memory, offset, 0}; + has_pending_binds_.store(true, std::memory_order_release); + } + bool take_slot(std::uint32_t& unit, std::uint32_t& slot) { + for (std::uint32_t u = 0; u < units_.size(); ++u) + if (!units_[u].free.empty()) { + unit = u; + slot = units_[u].free.back(); + units_[u].free.pop_back(); + return true; + } + Unit made; + if (!hooks_.make_unit || !hooks_.make_unit(made.memory, made.host)) return false; + made.sums = std::make_unique(std::size_t(kUnitPages) * kPieces); + for (std::uint32_t s = kUnitPages; s-- > 0;) made.free.push_back(s); + units_.push_back(std::move(made)); + unit = std::uint32_t(units_.size() - 1); + slot = units_.back().free.back(); + units_.back().free.pop_back(); + return true; + } + // A page no longer shows `frame`: the home goes once no page shows it, after `ticket` (the submissions that could + // read it) has retired. + void release_home(std::uint8_t* frame, std::uint64_t ticket) { + const auto it = homes_.find(frame); + if (it == homes_.end() || --it->second.refs) return; + drop_copy(it->second, ticket); + push_freed(it->second.unit, it->second.slot, ticket); + homes_.erase(it); + } + // One bind (memory null: unbind) of the page at `va`, in every chunk it lies in, into the next batch. + void note_bind(std::uint64_t va, VkDeviceMemory memory, VkDeviceSize offset) { + const std::uint64_t chunk = va / kChunk; + pending_[chunk][va - chunk * kChunk] = {va - chunk * kChunk, kPage, memory, offset, 0}; + has_pending_binds_.store(true, std::memory_order_release); + } + void push_freed(std::uint32_t unit, std::uint32_t slot, std::uint64_t ticket) { + if (ticket == kUnstamped) { + unstamped_freed_.push_back({unit, slot}); + return; + } + freed_.push_back({unit, slot, ticket}); + if (ticket < oldest_freed_ticket_.load(std::memory_order_relaxed)) + oldest_freed_ticket_.store(ticket, std::memory_order_release); + freed_count_.store(freed_.size(), std::memory_order_release); + } + void sync_freed_atomics() noexcept { + if (freed_.empty()) { + oldest_freed_ticket_.store(UINT64_MAX, std::memory_order_release); + freed_count_.store(0, std::memory_order_release); + return; + } + std::uint64_t oldest = freed_.front().ticket; + for (const Freed& f : freed_) + if (f.ticket < oldest) oldest = f.ticket; + oldest_freed_ticket_.store(oldest, std::memory_order_release); + freed_count_.store(freed_.size(), std::memory_order_release); + } + + static constexpr std::size_t kNoAliasedSlot = ~std::size_t(0); + struct UploadJob { + std::uint8_t* frame = nullptr; + std::uint8_t* to = nullptr; + std::uint64_t* sums = nullptr; + std::size_t aliased_slot = kNoAliasedSlot; + std::array changed_pieces{}; + std::size_t changed = 0; + bool whole = false; + bool failed = false; + }; + template + std::size_t upload_impl(OnChanged&& on_changed, FilterBatchPtr filter_batch) { + constexpr bool kHasFilterBatch = !std::is_same_v, std::nullptr_t>; + const std::uint64_t uploaded_before = counters_.uploaded_bytes; + last_whole_pages_ = 0; + last_inc_pages_ = 0; + last_aliased_pages_ = 0; + if (dirty_.empty()) { + last_upload_bytes_ = 0; + return 0; + } + std::vector batch_frames; + batch_frames.swap(dirty_); + dirty_count_.store(0, std::memory_order_release); + + upload_jobs_.clear(); + upload_jobs_.reserve(batch_frames.size()); + std::size_t aliased_count = 0; + for (std::uint8_t* frame : batch_frames) { + const auto home = homes_.find(frame); + if (home == homes_.end() || !home->second.dirty) continue; + home->second.dirty = false; + UploadJob job; + job.frame = frame; + job.to = units_[home->second.unit].host + std::size_t(home->second.slot) * kPage; + job.sums = home_sums(home->second); + job.whole = std::exchange(home->second.whole_fill, false); + if (job.whole) ++last_whole_pages_; + else ++last_inc_pages_; + if (home->second.copy) job.aliased_slot = aliased_count++; + upload_jobs_.push_back(job); + } + last_aliased_pages_ = aliased_count; + const std::size_t n = upload_jobs_.size(); + const bool run_parallel_sync = parallel_enabled_ && n >= kParallelThreshold && ensure_pool(); + + if (!run_parallel_sync && !kHasFilterBatch) { + for (const UploadJob& job : upload_jobs_) { + const auto it = homes_.find(job.frame); + if (it == homes_.end()) continue; + std::array changed_pieces{}; + std::size_t changed = 0; + fill_with_mask(it->second, job.frame, job.whole, changed_pieces, changed); + if (changed) on_changed(job.frame, changed_pieces); + } + } else { + if (aliased_count > 0) { + const std::size_t need_bytes = aliased_count * kPage; + if (aliased_scratch_.size() < need_bytes) aliased_scratch_.resize(need_bytes); + } + if (run_parallel_sync) { + const std::size_t workers = pool_->worker_count(); + const std::size_t chunk = (std::max)(std::size_t(1), (std::min)(std::size_t(4), n / (workers * 2))); + pool_->run(n, chunk, [this](std::size_t b, std::size_t e, std::size_t) { + for (std::size_t i = b; i < e; ++i) { + UploadJob& job = upload_jobs_[i]; + std::uint8_t* const scratch = + (job.aliased_slot != kNoAliasedSlot) + ? (aliased_scratch_.data() + job.aliased_slot * kPage) + : nullptr; + job.failed = sync_page_into_scratch(job.to, scratch, job.sums, job.frame, job.whole, + job.changed_pieces, job.changed); + } + }); + } else { + for (UploadJob& job : upload_jobs_) { + std::uint8_t* const scratch = (job.aliased_slot != kNoAliasedSlot) + ? (aliased_scratch_.data() + job.aliased_slot * kPage) + : nullptr; + job.failed = sync_page_into_scratch(job.to, scratch, job.sums, job.frame, job.whole, + job.changed_pieces, job.changed); + } + } + + if constexpr (kHasFilterBatch) { + aliased_jobs_.clear(); + if (aliased_count > 0) aliased_jobs_.reserve(aliased_count); + for (const UploadJob& job : upload_jobs_) { + counters_.uploaded_bytes += std::uint64_t(job.changed) * kPiece; + if (job.failed) ++counters_.upload_failures; + ++counters_.uploads; + if (job.changed) on_changed(job.frame, job.changed_pieces); + if (job.aliased_slot != kNoAliasedSlot) { + const auto it = homes_.find(job.frame); + if (it != homes_.end() && it->second.copy && + (job.changed || it->second.fresh || it->second.refilter)) { + Home& h = it->second; + const bool had_refilter = h.refilter; + h.refilter = false; + const bool fresh = h.fresh; + h.fresh = false; + const auto& mask = (fresh || had_refilter) ? kAllPieces : job.changed_pieces; + aliased_jobs_.push_back( + {h.filter_va, job.frame, + units_[h.copy_unit].host + std::size_t(h.copy_slot) * kPage, + aliased_scratch_.data() + job.aliased_slot * kPage, mask, fresh}); + } + } + } + if (!aliased_jobs_.empty()) { + aliased_ok_.assign(aliased_jobs_.size(), 1); + WorkerPool* const batch_pool = + (parallel_enabled_ && aliased_jobs_.size() >= 2 && ensure_pool()) ? pool_.get() : nullptr; + (*filter_batch)(aliased_jobs_.data(), aliased_jobs_.size(), batch_pool, aliased_ok_.data()); + for (std::size_t i = 0; i < aliased_jobs_.size(); ++i) { + ++counters_.filtered; + if (!aliased_ok_[i]) { + std::memset(aliased_jobs_[i].to, 0, kPage); + const auto it = homes_.find(aliased_jobs_[i].frame); + if (it != homes_.end()) it->second.fresh = true; + ++counters_.upload_failures; + } + } + } + } else { + for (const UploadJob& job : upload_jobs_) { + counters_.uploaded_bytes += std::uint64_t(job.changed) * kPiece; + if (job.failed) ++counters_.upload_failures; + ++counters_.uploads; + if (job.changed) on_changed(job.frame, job.changed_pieces); + if (job.aliased_slot != kNoAliasedSlot) { + // Re-lookup by frame key: filter_pieces may re-entrantly map() and rehash homes_. + const auto it = homes_.find(job.frame); + if (it != homes_.end() && it->second.copy && + (job.changed || it->second.fresh || it->second.refilter)) { + fill_copy(it->second, aliased_scratch_.data() + job.aliased_slot * kPage, false, + &job.changed_pieces); + } + } + } + } + } + if (dirty_.empty()) { + batch_frames.clear(); + dirty_.swap(batch_frames); // keep vector capacity for the next refresh + } + last_upload_bytes_ = counters_.uploaded_bytes - uploaded_before; + return n; + } + + struct WriteBackJob { + Home* home = nullptr; + std::uint64_t page = 0; + std::uint8_t* frame = nullptr; + const std::uint8_t* gpu = nullptr; + const std::uint64_t* sums = nullptr; + std::array scan_mask{}; + std::array diff_mask{}; + std::uint16_t diff_count = 0; + bool full_page = false; + }; + + struct PageSlot { + std::uint8_t* frame = nullptr; + Home* home = nullptr; + }; + struct Chunk { + VkBuffer buffer = VK_NULL_HANDLE; + std::unique_ptr pages; // kChunkPages (32768) direct slots per 2 GiB chunk + std::size_t mapped_count = 0; + }; + struct ChunkDirEntry { + std::uint64_t index = 0; + VkBuffer buffer = VK_NULL_HANDLE; + PageSlot* pages = nullptr; + Chunk* chunk = nullptr; + }; + + void insert_chunk_dir(std::uint64_t index, Chunk& ch) { + const ChunkDirEntry entry{index, ch.buffer, ch.pages.get(), &ch}; + const auto pos = std::lower_bound( + chunk_dir_.begin(), chunk_dir_.end(), index, + [](const ChunkDirEntry& e, std::uint64_t key) { return e.index < key; }); + chunk_dir_.insert(pos, entry); + } + const ChunkDirEntry* find_chunk_dir(std::uint64_t chunk_idx) const noexcept { + const std::size_t n = chunk_dir_.size(); + if (n <= 16) { + for (std::size_t i = 0; i < n; ++i) + if (chunk_dir_[i].index == chunk_idx) return &chunk_dir_[i]; + return nullptr; + } + const auto it = std::lower_bound( + chunk_dir_.begin(), chunk_dir_.end(), chunk_idx, + [](const ChunkDirEntry& e, std::uint64_t key) { return e.index < key; }); + return (it != chunk_dir_.end() && it->index == chunk_idx) ? &(*it) : nullptr; + } + PageSlot* find_slot(std::uint64_t va) noexcept { + const std::uint64_t c = va / kChunk; + const ChunkDirEntry* const dir = find_chunk_dir(c); + if (!dir) return nullptr; + return &dir->pages[std::size_t((va - c * kChunk) / kPage)]; + } + const PageSlot* find_slot(std::uint64_t va) const noexcept { + const std::uint64_t c = va / kChunk; + const ChunkDirEntry* const dir = find_chunk_dir(c); + if (!dir) return nullptr; + return &dir->pages[std::size_t((va - c * kChunk) / kPage)]; + } + template + void for_each_mapped_in(std::uint64_t lo, std::uint64_t hi, Fn&& fn) const { + if (lo >= hi || chunk_dir_.empty()) return; + const std::uint64_t start_c = lo / kChunk; + auto it = std::lower_bound( + chunk_dir_.begin(), chunk_dir_.end(), start_c, + [](const ChunkDirEntry& e, std::uint64_t key) { return e.index < key; }); + for (; it != chunk_dir_.end(); ++it) { + const std::uint64_t chunk_base = it->index * kChunk; + if (chunk_base >= hi) break; + if (it->chunk->mapped_count == 0) continue; + const std::uint64_t chunk_end = + (it->index < UINT64_MAX / kChunk) ? ((it->index + 1) * kChunk) : UINT64_MAX; + const std::uint64_t from = (std::max)(lo, chunk_base) & ~(kPage - 1); + const std::uint64_t until = (std::min)(hi, chunk_end); + const PageSlot* const slots = it->pages; + for (std::uint64_t va = from; va < until; va += kPage) { + const PageSlot& s = slots[std::size_t((va - chunk_base) / kPage)]; + if (s.frame) fn(va, s); + if (va > UINT64_MAX - kPage) return; + } + } + } + + bool ensure_pool() { + if (pool_) return true; + pool_ = make_worker_pool(); + return pool_ != nullptr; + } + + TitleMirrorHooks hooks_; + std::map chunks_; // chunk index -> buffer + 32768 direct page slots + std::vector chunk_dir_; // sorted flat directory of valid chunks for O(1) lookup + std::size_t pages_count_ = 0; // live mapped pages across all chunks + std::unordered_map homes_; // physical page (its scratch bytes) -> home + std::vector units_; + std::vector dirty_; + std::vector> unstamped_freed_; + std::deque freed_; + std::map> pending_; // chunk -> offset -> next bind + std::map aliases_; // title address -> [it, hi) also bound there, filtered + std::map> alias_pending_; // buffer -> offset -> next bind + Counters counters_; + std::size_t last_batch_ = 0; + std::uint64_t last_upload_bytes_ = 0; + std::size_t last_whole_pages_ = 0; + std::size_t last_inc_pages_ = 0; + std::size_t last_aliased_pages_ = 0; + std::atomic has_pending_binds_{false}; + std::atomic dirty_count_{0}; + std::atomic freed_count_{0}; + std::atomic oldest_freed_ticket_{UINT64_MAX}; + alignas(64) std::array fill_scratch_{}; + std::vector upload_jobs_; + std::vector aliased_scratch_; + std::vector aliased_jobs_; + std::vector aliased_ok_; + std::vector wb_jobs_; + std::unique_ptr pool_; + bool parallel_enabled_ = true; + +public: + std::size_t last_batch() const { return last_batch_; } // binds in the last flush() +}; + +} // namespace leonida diff --git a/runtime/src/title_mirror_hot_cold.h b/runtime/src/title_mirror_hot_cold.h new file mode 100644 index 0000000000..2a2dfe8955 --- /dev/null +++ b/runtime/src/title_mirror_hot_cold.h @@ -0,0 +1,1238 @@ +#pragma once +// HotColdTracking: the page mirror's tracking (TitleMirrorTracking, src/title_mirror_tracking.h) with the hot/cold +// policy of src/title_write_policy.h over the geometry watch's cells, plus region-batched zero-fault MEM_WRITE_WATCH +// tracking (title_write_watch) for pages inside write-watched private reservations. +// +// - Guarded pages (sections / ordinary pages without MEM_WRITE_WATCH): watched through geometry_writes cells, with +// contiguous 64 KiB re-arms batched into single VirtualProtect syscalls in CellGuard::arm_batch(). One collect() is +// one submission interval; only pages written in >= 6 of 8 submissions stay unguarded. +// - Write-watched pages (title_write_watch::contains): queried via cached region-batched runs in +// title_write_watch::ask() (GetWriteWatch with WRITE_WATCH_FLAG_RESET) in O(regions + dirty) without walking +// ww_pages_ on steady-state submissions, with zero guard faults, zero VirtualProtect syscalls, and zero interference +// with geometry_writes::hot_tiles(). Uncommitted holes inside a reservation are never bridged. +#include "submit_phases.h" +#include "title_mirror_tracking.h" +#include "title_write_policy.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace leonida { + +class HotColdTracking final : public TitleMirrorTracking { +public: + struct ArmStats { + std::uint64_t ns = 0; + std::uint64_t vp_calls = 0; + std::uint64_t vq_calls = 0; + std::uint64_t fast_tiles = 0; + std::uint64_t slow_tiles = 0; + std::uint64_t skip_tiles = 0; + std::uint64_t already_armed_skips = 0; + std::uint64_t table_skips = 0; + std::uint64_t bridged_runs = 0; + std::uint64_t wc_tiles = 0; + }; + + HotColdTracking() : policy_(guard_) { + geometry_writes::subscribe_writes(queue_); + } + ~HotColdTracking() override { + geometry_writes::unsubscribe_writes(queue_); + if (ww_reader_) title_write_watch::close_reader(ww_reader_); + for (const auto& [page, tc] : guard_.cells) { + geometry_writes::release(std::uintptr_t(page), tc.is_hot); + } + } + HotColdTracking(const HotColdTracking&) = delete; + HotColdTracking& operator=(const HotColdTracking&) = delete; + + void watch(std::uint64_t page) override { + const std::uintptr_t addr = std::uintptr_t(page) & ~(Policy::kPage - 1); + if (guard_.cells.count(addr) || ww_pages_.count(addr)) return; + if (title_write_watch::enabled() && title_write_watch::contains(addr)) { + if (!ww_reader_) ww_reader_ = title_write_watch::open_reader(); + ww_pages_.insert(addr); + ww_initial_.push_back(addr); + ww_runs_dirty_ = true; + sync_pending_atomics(); + return; + } + watch_guarded(addr); + sync_pending_atomics(); + } + void unwatch(std::uint64_t page) override { + const std::uintptr_t addr = std::uintptr_t(page) & ~(Policy::kPage - 1); + if (ww_pages_.erase(addr)) { + ww_runs_dirty_ = true; + if (ww_pages_.empty()) { + ww_runs_.clear(); + ww_initial_.clear(); + } + sync_pending_atomics(); + return; + } + const auto it = guard_.cells.find(addr); + if (it == guard_.cells.end()) return; + const bool was_hot = it->second.is_hot; + // Erase from guard_.cells BEFORE policy_.remove() so remove()'s guard_.disarm(addr) is a 0-lock no-op + // instead of toggling set_hot(true) -> set_hot(false) (2 extra locks + 1 extra reopen + bogus WriteQueue push). + // geometry_writes::release(addr, was_hot) drops our ref (and hot count if was_hot) in a single lock hold. + guard_.cells.erase(it); + guard_.note_wc_page(addr, false); + policy_.remove(addr, addr + Policy::kPage); + geometry_writes::release(addr, was_hot); + sync_pending_atomics(); + } + + // Batched watch: acquires all new guarded cells under one geometry_writes::state().mutex hold + one atomic sync. + void watch_batch(const std::uint64_t* pages, std::size_t count) { + if (!count) return; + if (count == 1) { + watch(pages[0]); + return; + } + const bool ww_on = title_write_watch::enabled(); + batch_watch_addrs_.clear(); + batch_watch_tcs_.clear(); + for (std::size_t i = 0; i < count; ++i) { + const std::uintptr_t addr = std::uintptr_t(pages[i]) & ~(Policy::kPage - 1); + if (guard_.cells.count(addr) || ww_pages_.count(addr)) continue; + if (ww_on && title_write_watch::contains(addr)) { + if (!ww_reader_) ww_reader_ = title_write_watch::open_reader(); + ww_pages_.insert(addr); + ww_initial_.push_back(addr); + ww_runs_dirty_ = true; + continue; + } + auto [it, fresh] = guard_.cells.try_emplace(addr); + if (fresh) { + batch_watch_addrs_.push_back(addr); + batch_watch_tcs_.push_back(&it->second); + } + } + if (!batch_watch_addrs_.empty()) { + batch_watch_cells_.resize(batch_watch_addrs_.size()); + geometry_writes::acquire_batch(batch_watch_addrs_.data(), batch_watch_cells_.data(), + batch_watch_addrs_.size()); + for (std::size_t k = 0; k < batch_watch_addrs_.size(); ++k) { + batch_watch_tcs_[k]->cell = batch_watch_cells_[k]; + policy_.add(batch_watch_addrs_[k], batch_watch_addrs_[k] + Policy::kPage); + } + } + sync_pending_atomics(); + } + + // Batched unwatch: releases all guarded cells under one geometry_writes::state().mutex hold + one atomic sync. + void unwatch_batch(const std::uint64_t* pages, std::size_t count) { + if (!count) return; + if (count == 1) { + unwatch(pages[0]); + return; + } + batch_unwatch_items_.clear(); + bool erased_ww = false; + for (std::size_t i = 0; i < count; ++i) { + const std::uintptr_t addr = std::uintptr_t(pages[i]) & ~(Policy::kPage - 1); + if (ww_pages_.erase(addr)) { + ww_runs_dirty_ = true; + erased_ww = true; + continue; + } + const auto it = guard_.cells.find(addr); + if (it == guard_.cells.end()) continue; + const bool was_hot = it->second.is_hot; + guard_.cells.erase(it); + guard_.note_wc_page(addr, false); + policy_.remove(addr, addr + Policy::kPage); + batch_unwatch_items_.emplace_back(addr, was_hot); + } + if (erased_ww && ww_pages_.empty()) { + ww_runs_.clear(); + ww_initial_.clear(); + } + if (!batch_unwatch_items_.empty()) { + geometry_writes::release_batch(batch_unwatch_items_.data(), batch_unwatch_items_.size()); + } + sync_pending_atomics(); + } + + void collect(std::vector& out) override { + out.clear(); + guard_.arm_stats = {}; + bool overflow = false; + geometry_writes::take_written(queue_, tiles_, overflow); + if (overflow) + for (const auto& [page, tc] : guard_.cells) policy_.written(std::uintptr_t(page)); + else + for (const std::uintptr_t tile : tiles_) { + const auto it = guard_.cells.find(tile); + if (it == guard_.cells.end()) continue; + const auto& tc = it->second; + // A guarded page whose cell has not moved since it was armed was not written since: the entry is + // older than the arming, or this tracking's own turn of the page from hot to cold. + if (tc.is_armed && tc.armed_version == tc.cell->version.load(std::memory_order_acquire)) + continue; + policy_.written(tile); + } + policy_.collect([&](std::uintptr_t page) { out.push_back(page); }); + policy_.frame(); // one submission interval a collect + + if (!ww_pages_.empty()) collect_write_watched(out); + sync_pending_atomics(); + } + + // Lock-free O(1) clean-submission check: false when no write faults are queued, no guarded pages are hot, dirty, + // or decaying in history_active_, and no write-watched pages are active. + bool has_pending_work() const noexcept { + if (queue_.pending.load(std::memory_order_acquire)) return true; + if (active_work_.load(std::memory_order_acquire) != 0) return true; + return ww_count_.load(std::memory_order_acquire) != 0; + } + + std::uint64_t take_refused() override { + const std::uint64_t now = policy_.stats().arm_failures; + return now - std::exchange(refused_seen_, now); + } + const auto& stats() const noexcept { return policy_.stats(); } + const ArmStats& last_arm_stats() const noexcept { return guard_.arm_stats; } + // Read-only during TitleMirror::upload() worker threads (mutated only under page_mirror.mutex in arm_batch/unwatch). + bool is_wc_page(std::uintptr_t addr) const noexcept { + return guard_.is_wc_page(addr); + } + bool hot(std::uint64_t page) const { return policy_.hot(std::uintptr_t(page)); } + // A cold page whose guard no write has reached since it was armed (TitleMirrorTracking::unwritten). A hot or + // write-watched page returns false (conservative). + bool unwritten(std::uint64_t page) override { + const std::uintptr_t addr = std::uintptr_t(page) & ~(Policy::kPage - 1); + if (ww_pages_.count(addr) || policy_.hot(addr)) return false; + const auto it = guard_.cells.find(addr); + return it != guard_.cells.end() && it->second.is_armed && + it->second.cell->version.load(std::memory_order_acquire) == it->second.armed_version; + } + +private: + static constexpr std::uintptr_t kWwMergeGap = 0x100000; // bridge committed gaps <= 1 MiB inside a reservation + static constexpr std::uintptr_t kMaxWwRunBytes = 0x4000000; // cap each GetWriteWatch call at 64 MiB (16k 4K pages) + + void watch_guarded(std::uintptr_t addr) { + if (guard_.cells.count(addr)) return; + CellGuard::TrackedCell tc{}; + tc.cell = geometry_writes::acquire(addr); + guard_.cells.emplace(addr, tc); + policy_.add(addr, addr + Policy::kPage); // copied (and armed) at the next collect + } + + // Advances across contiguous MEM_COMMIT regions starting at `from`, capped at `limit`. + static std::uintptr_t committed_end_from(std::uintptr_t from, std::uintptr_t limit) { + std::uintptr_t p = from; + while (p < limit) { + MEMORY_BASIC_INFORMATION m{}; + if (!VirtualQuery(reinterpret_cast(p), &m, sizeof m) || m.State != MEM_COMMIT) break; + const std::uintptr_t region_end = reinterpret_cast(m.BaseAddress) + m.RegionSize; + if (region_end <= p) break; + p = (std::min)(limit, region_end); + } + return p; + } + + // Rebuilds cached region-batched runs from ww_pages_. Called only when ww_pages_ or title_write_watch reservations + // change; steady-state collect() reuses ww_runs_ directly in O(runs + dirty). + void rebuild_ww_runs() { + ww_runs_.clear(); + ww_runs_dirty_ = false; + ww_gen_ = title_write_watch::generation(); + if (ww_pages_.empty()) return; + + ww_sorted_.assign(ww_pages_.begin(), ww_pages_.end()); + std::sort(ww_sorted_.begin(), ww_sorted_.end()); + + std::uintptr_t run_from = 0, run_to = 0; + std::uintptr_t reg_end = 0; // end of current title_write_watch reservation + std::uintptr_t run_commit_end = 0; // verified unbroken MEM_COMMIT end starting from run_from + + for (const std::uintptr_t page : ww_sorted_) { + const std::uintptr_t page_end = page + Policy::kPage; + if (page_end <= page) { + ww_refused_.push_back(page); + continue; + } + if (page >= reg_end) { + if (run_from != run_to) { + ww_runs_.emplace_back(run_from, run_to); + run_from = run_to = run_commit_end = 0; + } + reg_end = title_write_watch::end_of(page); + } + if (!reg_end || page_end > reg_end) { + ww_refused_.push_back(page); + continue; + } + if (run_from != run_to) { + const std::uintptr_t gap = page - run_to; + const std::uintptr_t merged_bytes = page_end - run_from; + if (merged_bytes <= kMaxWwRunBytes && gap <= kWwMergeGap) { + if (run_commit_end < page_end && run_commit_end >= run_to) { + const std::uintptr_t cap = + reg_end - run_from > kMaxWwRunBytes ? run_from + kMaxWwRunBytes : reg_end; + run_commit_end = committed_end_from(run_commit_end, cap); + } + if (run_commit_end >= page_end) { + run_to = page_end; + continue; + } + } + ww_runs_.emplace_back(run_from, run_to); + run_from = run_to = run_commit_end = 0; + } + run_from = page; + run_to = page_end; + const std::uintptr_t cap = reg_end - run_from > kMaxWwRunBytes ? run_from + kMaxWwRunBytes : reg_end; + run_commit_end = committed_end_from(run_from, cap); + } + if (run_from != run_to) ww_runs_.emplace_back(run_from, run_to); + } + + void collect_write_watched(std::vector& out) { + ww_dirty_.clear(); + ww_refused_.clear(); + ww_retry_runs_.clear(); + + if (ww_runs_dirty_ || ww_gen_ != title_write_watch::generation()) rebuild_ww_runs(); + + const auto record_dirty = [&](std::uintptr_t from, std::uintptr_t to) { + for (std::uintptr_t p = from & ~(Policy::kPage - 1); p < to;) { + if (ww_pages_.count(p)) ww_dirty_.push_back(p); + if (to - p <= Policy::kPage) break; + p += Policy::kPage; + } + }; + + if (!ww_runs_.empty()) { + title_write_watch::ask( + ww_reader_, ww_runs_, record_dirty, + [&](std::uintptr_t from, std::uintptr_t to) { + // A multi-page run whose reservation still exists may have acquired an uncommitted hole since + // ww_runs_ was cached: split and retry its watched pages before falling back to guards. + if (to - from > Policy::kPage && title_write_watch::contains(from)) { + ww_retry_runs_.emplace_back(from, to); + return; + } + for (std::uintptr_t p = from & ~(Policy::kPage - 1); p < to;) { + if (ww_pages_.count(p)) ww_refused_.push_back(p); + if (to - p <= Policy::kPage) break; + p += Policy::kPage; + } + }); + } + + if (!ww_retry_runs_.empty()) { + ww_runs_dirty_ = true; + ww_split_runs_.clear(); + for (const auto& [from, to] : ww_retry_runs_) { + // The first ask() already advanced ww_reader_'s journal cursor, so any write journaled by another + // reader or title_write_watch::mark() before it would be skipped by a second ask(). Mark every + // watched page in the refused run dirty conservatively, then split-ask to reset kernel bits and find + // any individual page that genuinely lost write-watching. + record_dirty(from, to); + for (std::uintptr_t p = from & ~(Policy::kPage - 1); p < to;) { + if (ww_pages_.count(p)) ww_split_runs_.emplace_back(p, p + Policy::kPage); + if (to - p <= Policy::kPage) break; + p += Policy::kPage; + } + } + if (!ww_split_runs_.empty()) { + title_write_watch::ask( + ww_reader_, ww_split_runs_, [](std::uintptr_t, std::uintptr_t) {}, + [&](std::uintptr_t from, std::uintptr_t to) { + for (std::uintptr_t p = from & ~(Policy::kPage - 1); p < to;) { + if (ww_pages_.count(p)) ww_refused_.push_back(p); + if (to - p <= Policy::kPage) break; + p += Policy::kPage; + } + }); + } + } + + for (const std::uintptr_t p : ww_initial_) + if (ww_pages_.count(p)) ww_dirty_.push_back(p); + ww_initial_.clear(); + + // Any page whose MEM_WRITE_WATCH reservation disappeared falls back to guarded tracking without losing a write. + if (!ww_refused_.empty()) { + ww_runs_dirty_ = true; + for (const std::uintptr_t p : ww_refused_) { + if (ww_pages_.erase(p)) { + watch_guarded(p); + ww_dirty_.push_back(p); + } + } + if (ww_pages_.empty()) ww_runs_.clear(); + } + if (!ww_dirty_.empty()) { + std::sort(ww_dirty_.begin(), ww_dirty_.end()); + ww_dirty_.erase(std::unique(ww_dirty_.begin(), ww_dirty_.end()), ww_dirty_.end()); + const bool had_guarded = !out.empty(); + for (const std::uintptr_t p : ww_dirty_) out.push_back(p); + if (had_guarded) { + std::sort(out.begin(), out.end()); + out.erase(std::unique(out.begin(), out.end()), out.end()); + } + } + } + + struct CellGuard { + static constexpr std::size_t kMaxBatchRunPages = 1024; // up to 64 MiB per contiguous VirtualProtect run + static constexpr std::size_t kMaxLockBatchPages = 128; // pages per pin check + geometry_writes lock hold + static constexpr std::size_t kMaxBridgeGap = 64; // max already-armed cold gap tiles to bridge (4 MiB) + + struct TrackedCell { + geometry_writes::Cell* cell = nullptr; + std::uint64_t armed_version = 0; + bool is_armed = false; + bool is_hot = false; + }; + + std::unordered_map cells; + ArmStats arm_stats{}; + // Guarded tiles observed with PAGE_WRITECOMBINE; mutated only under page_mirror.mutex, read-only during upload(). + std::unordered_set wc_pages; + std::atomic wc_page_count{0}; + + void note_wc_page(std::uintptr_t tile, bool is_wc) { + tile &= ~(geometry_writes::tile_size - 1); + if (is_wc) { + if (wc_pages.insert(tile).second) + wc_page_count.store(wc_pages.size(), std::memory_order_release); + } else if (wc_page_count.load(std::memory_order_relaxed) != 0) { + if (wc_pages.erase(tile)) + wc_page_count.store(wc_pages.size(), std::memory_order_release); + } + } + + bool is_wc_page(std::uintptr_t addr) const noexcept { + if (wc_page_count.load(std::memory_order_acquire) == 0) return false; + return wc_pages.count(addr & ~(geometry_writes::tile_size - 1)) != 0; + } + + template + static void check_table_backed(const StateT& s, const std::uintptr_t* pages, std::uint8_t* out, + std::size_t count) { + if constexpr (requires { s.backed_batch.load(std::memory_order_acquire)(pages, out, count); }) { + if (const auto fn = s.backed_batch.load(std::memory_order_acquire)) { + fn(pages, out, count); + return; + } + } + for (std::size_t k = 0; k < count; ++k) out[k] = title_frames::backed(pages[k]) ? 1 : 0; + } + + bool is_tile_pinned(std::uintptr_t tile) const noexcept { + constexpr std::uintptr_t kTile = geometry_writes::tile_size; + const std::uintptr_t tile_hi = (tile <= UINTPTR_MAX - kTile) ? (tile + kTile) : UINTPTR_MAX; + for (const auto& [p_lo, p_hi] : run_pin_ranges_) { + if (tile < p_hi && p_lo < tile_hi) return true; + } + return false; + } + + // True when no title_memory_map change after `since` overlapped [lo, hi). Sets `gen_out` to the generation + // checked up to (leaf SRWLOCK shared read when generation moved). + static bool range_clean_since(std::uint64_t since, std::uintptr_t lo, std::uintptr_t hi, + std::uint64_t& gen_out) { + if (since == geometry_writes::Cell::kNoMapGen) return false; + const std::uint64_t cur = title_memory_map::generation(); + if (cur == since) { + gen_out = cur; + return true; + } + bool overlapped = false; + std::uint64_t now = cur; + if (!title_memory_map::changes_since(since, now, lo, hi, + [&](std::uintptr_t c_from, std::uintptr_t c_to) { + if (c_from < c_to) overlapped = true; + })) { + return false; + } + gen_out = now; + return !overlapped; + } + + static bool restore_uniform(const geometry_writes::Cell& c, DWORD expected) noexcept { + if (!expected) return false; + for (const DWORD r : c.restore) + if (r != expected) return false; + return true; + } + + static bool cell_known_writable(const geometry_writes::Cell& c, DWORD& kp, DWORD& kg, + std::uint64_t& gen) noexcept { + if (c.known_state != MEM_COMMIT || !c.known_protect || !c.known_guarded || + c.known_map_gen == geometry_writes::Cell::kNoMapGen || + c.known_mapping != c.mapping.load(std::memory_order_acquire)) + return false; + kp = c.known_protect; + kg = c.known_guarded; + gen = c.known_map_gen; + return true; + } + + // Cross-pass no-guard cache for CellGuard: MEM_RESERVE and PAGE_NOACCESS only (NEVER PAGE_READONLY, because + // ShadowPages::reopen() reopens RO->RW without calling title_memory_map::changed()). + static bool cell_known_noguard(const geometry_writes::Cell& c, DWORD& st, DWORD& kp, + std::uint64_t& gen) noexcept { + if (c.known_guarded != 0 || c.known_map_gen == geometry_writes::Cell::kNoMapGen || + c.known_mapping != c.mapping.load(std::memory_order_acquire)) + return false; + if (c.known_state == MEM_RESERVE || (c.known_state == MEM_COMMIT && c.known_protect == PAGE_NOACCESS)) { + st = c.known_state; + kp = c.known_protect; + gen = c.known_map_gen; + return true; + } + return false; + } + + static void clear_cell_known(geometry_writes::Cell& c) noexcept { + c.known_state = 0; + c.known_protect = 0; + c.known_guarded = 0; + c.known_map_gen = geometry_writes::Cell::kNoMapGen; + } + + // Guarded (cold, or a hot page's probe): no longer hot for this owner, then armed. + bool arm(std::uintptr_t page) { + std::uint8_t ok = 0; + arm_batch(&page, &ok, 1); + return ok != 0; + } + + // Batched arming of sorted 64 KiB pages: coalesces both contiguous runs (up to 64 MiB in one VirtualProtect) + // and scattered pages (bridging up to kMaxBridgeGap already-armed unpinned cold tiles, including already-armed + // tiles in the same batch or watched by another owner) into shared pin checks, shared geometry_writes lock + // holds, shared per-Cell known-protection/state caching validated via title_memory_map::changes_since(), and a + // short-lived VirtualQuery region cache within each lock hold. + void arm_batch(const std::uintptr_t* pages, std::uint8_t* results, std::size_t count) { + using geometry_writes::Cell; + constexpr std::uintptr_t kTile = geometry_writes::tile_size; + constexpr std::uintptr_t kHostPage = geometry_writes::page_size; + + if (!count) return; + const std::int64_t arm_t0 = submit_phases::now_ns(); + struct ArmTimer { + std::int64_t t0; + std::uint64_t& ns; + ~ArmTimer() { + const std::int64_t dt = submit_phases::now_ns() - t0; + if (dt > 0) ns += std::uint64_t(dt); + } + } arm_timer{arm_t0, arm_stats.ns}; + + for (std::size_t i = 0; i < count;) { + // Extend chunk up to kMaxLockBatchPages, or further across one contiguous or bridgeable run up to + // kMaxBatchRunPages so lock-batch cuts never split a bridgeable cluster mid-bridge. + std::size_t j = i + 1; + while (j < count) { + const std::uintptr_t prev_va = pages[j - 1]; + const std::uintptr_t next_va = pages[j]; + const bool ordered = prev_va <= UINTPTR_MAX - kTile && next_va >= prev_va + kTile; + const bool contiguous = ordered && next_va == prev_va + kTile; + const bool bridgeable = ordered && (next_va - (prev_va + kTile)) <= kMaxBridgeGap * kTile; + const std::size_t len = j - i; + if (len < kMaxLockBatchPages) { + ++j; + } else if ((contiguous || bridgeable) && len < kMaxBatchRunPages) { + ++j; + } else { + break; + } + } + const std::size_t batch_n = j - i; + const std::uintptr_t* const batch_pages = pages + i; + + run_entries_.resize(batch_n); + run_versions_.resize(batch_n); + run_pinned_.assign(batch_n, 0); + run_backed_.assign(batch_n, 0); + run_eligible_.assign(batch_n, 0); + run_already_armed_.assign(batch_n, 0); + run_failed_.assign(batch_n, 0); + run_slow_.assign(batch_n, 0); + run_wc_.assign(batch_n, 0); + run_pin_ranges_.clear(); + run_clear_hot_.clear(); + + // Clear hot flags (batched under one geometry_writes::state().mutex hold) BEFORE snapshotting versions, + // querying kernel pins, or querying table-backed frames. + std::uintptr_t pin_lo = UINTPTR_MAX; + std::uintptr_t pin_hi = 0; + for (std::size_t k = 0; k < batch_n; ++k) { + const std::uintptr_t page = batch_pages[k]; + const auto it = cells.find(page); + if (it == cells.end()) { + run_entries_[k] = nullptr; + results[i + k] = 0; + continue; + } + TrackedCell& tc = it->second; + if (tc.is_hot) { + tc.is_hot = false; + run_clear_hot_.push_back(page); + } + run_entries_[k] = &tc; + if (page < pin_lo) pin_lo = page; + const std::uintptr_t page_hi = (page <= UINTPTR_MAX - kTile) ? (page + kTile) : UINTPTR_MAX; + if (page_hi > pin_hi) pin_hi = page_hi; + } + if (!run_clear_hot_.empty()) { + geometry_writes::set_hot_batch(run_clear_hot_.data(), run_clear_hot_.size(), false); + } + for (std::size_t k = 0; k < batch_n; ++k) { + if (run_entries_[k]) { + run_versions_[k] = run_entries_[k]->cell->version.load(std::memory_order_acquire); + } + } + + // One pin check for the entire batch (never under geometry_writes::state().mutex). Record every + // overlapping pin interval in run_pin_ranges_ so gap-bridging NEVER bridges over a pinned tile. + if (pin_lo < pin_hi) { + kernel_writes::for_each_pin(pin_lo, pin_hi, [&](std::uintptr_t p_lo, std::uintptr_t p_hi) { + run_pin_ranges_.emplace_back(p_lo, p_hi); + const std::uintptr_t first_tile = p_lo & ~(kTile - 1); + const std::uintptr_t* it = + std::lower_bound(batch_pages, batch_pages + batch_n, first_tile); + for (; it < batch_pages + batch_n && *it < p_hi; ++it) { + run_pinned_[std::size_t(it - batch_pages)] = 1; + } + }); + // Table-backed pages have no host view (MEM_RESERVE): skip outside geometry_writes::state().mutex + // so g_frame_lock and s.mutex never nest. Any concurrent remap bumps c->version and is caught below. + if (title_frames::may_hold(pin_lo, pin_hi)) { + run_backed_addrs_.clear(); + run_backed_idx_.clear(); + for (std::size_t k = 0; k < batch_n; ++k) { + if (run_entries_[k] && !run_pinned_[k]) { + run_backed_addrs_.push_back(batch_pages[k]); + run_backed_idx_.push_back(k); + } + } + if (!run_backed_addrs_.empty()) { + run_backed_res_.assign(run_backed_addrs_.size(), 0); + check_table_backed(title_frames::state(), run_backed_addrs_.data(), run_backed_res_.data(), + run_backed_addrs_.size()); + for (std::size_t m = 0; m < run_backed_addrs_.size(); ++m) { + if (run_backed_res_[m]) run_backed_[run_backed_idx_[m]] = 1; + } + } + } + } + + auto& s = geometry_writes::state(); + { + std::lock_guard lock(s.mutex); + for (std::size_t k = 0; k < batch_n; ++k) { + TrackedCell* tc = run_entries_[k]; + if (!tc) continue; + Cell* c = tc->cell; + if (c->hot) { + results[i + k] = 1; + tc->is_armed = true; + tc->armed_version = run_versions_[k]; + ++arm_stats.skip_tiles; + continue; + } + if (run_pinned_[k] || run_versions_[k] != c->version.load(std::memory_order_relaxed)) { + results[i + k] = 0; + tc->is_armed = false; + continue; + } + // Zero-syscall fast path: all 16 sub-pages already armed read-only (e.g. by another owner). + const DWORD r0 = c->restore[0]; + bool all_armed = r0 != 0; + bool uniform_restore = all_armed; + for (std::size_t sp = 1; all_armed && sp < c->restore.size(); ++sp) { + if (!c->restore[sp]) { + all_armed = false; + uniform_restore = false; + } else if (c->restore[sp] != r0) { + uniform_restore = false; + } + } + if (all_armed) { + if (uniform_restore && c->armed_map_gen != Cell::kNoMapGen) { + const std::uint64_t cur_map = c->mapping.load(std::memory_order_acquire); + if (c->known_state == 0 || c->known_mapping != cur_map || + c->known_map_gen == Cell::kNoMapGen) { + const DWORD g = geometry_writes::read_only(r0); + if (g != 0 && !(r0 & PAGE_GUARD)) { + c->known_state = MEM_COMMIT; + c->known_protect = r0; + c->known_guarded = g; + c->known_mapping = cur_map; + c->known_map_gen = c->armed_map_gen; + } + } + } + run_already_armed_[k] = 1; + results[i + k] = 1; + tc->is_armed = true; + tc->armed_version = run_versions_[k]; + ++arm_stats.already_armed_skips; + ++arm_stats.skip_tiles; + if (r0 & PAGE_WRITECOMBINE) { + ++arm_stats.wc_tiles; + note_wc_page(batch_pages[k], true); + } + continue; + } + if (run_backed_[k]) { + results[i + k] = 1; + tc->is_armed = true; + tc->armed_version = run_versions_[k]; + ++arm_stats.table_skips; + ++arm_stats.skip_tiles; + continue; + } + run_eligible_[k] = 1; + } + + // Short-lived VirtualQuery cache within this lock hold: if a uniform MEM_COMMIT (writable or + // PAGE_NOACCESS — never PAGE_READONLY/PAGE_EXECUTE_READ), MEM_RESERVE, or MEM_FREE region extends + // past the current sub-run into subsequent pages in the same batch and no title map change + // overlapped it, reuse its state/protection instead of issuing a redundant VirtualQuery syscall. + std::uintptr_t cached_lo = 0; + std::uintptr_t cached_hi = 0; + DWORD cached_state = 0; + DWORD cached_protect = 0; + DWORD cached_guarded = 0; + std::uint64_t cached_gen = 0; + + // Protect each contiguous (or gap-bridged) sub-run of eligible cells with batched VirtualProtect + // (skipping VirtualQuery when shared Cell::known_* is valid). + for (std::size_t sub_start = 0; sub_start < batch_n;) { + if (!run_eligible_[sub_start]) { + ++sub_start; + continue; + } + std::size_t sub_end = sub_start + 1; + while (sub_end < batch_n && run_eligible_[sub_end] && + batch_pages[sub_end] == batch_pages[sub_end - 1] + kTile) { + ++sub_end; + } + + // Gap-bridging fast path: coalesce scattered eligible tiles separated by <= kMaxBridgeGap + // already-armed, unpinned cold tiles (both batch `run_already_armed_` skips and intermediate + // tiles in `cells` or `s.cells`) sharing identical Cell::known_protect/known_guarded/mapping + // and uniform restore[0..15] == kp. Falls back to eligible-only [sub_start, sub_end) on any + // failure or unexpected old protect. + DWORD kp = 0, kg = 0; + std::uint64_t gen0 = 0; + if (cell_known_writable(*run_entries_[sub_start]->cell, kp, kg, gen0)) { + const std::uintptr_t span_lo = batch_pages[sub_start]; + std::size_t bridge_end = sub_start + 1; + std::size_t last_eligible = sub_start; + std::uint64_t run_min_gen = gen0; + std::uint64_t last_min_gen = gen0; + while (bridge_end < batch_n && + (run_eligible_[bridge_end] || run_already_armed_[bridge_end])) { + const std::uintptr_t prev_va = batch_pages[bridge_end - 1]; + const std::uintptr_t next_va = batch_pages[bridge_end]; + if (prev_va > UINTPTR_MAX - kTile || next_va > UINTPTR_MAX - kTile) break; + const std::uintptr_t prev_end = prev_va + kTile; + if (next_va < prev_end) break; + const std::uintptr_t eligible_gap = next_va - (batch_pages[last_eligible] + kTile); + if (eligible_gap > kMaxBridgeGap * kTile) break; + if ((next_va + kTile - span_lo) > kMaxBatchRunPages * kTile) break; + const Cell& cn = *run_entries_[bridge_end]->cell; + DWORD nkp = 0, nkg = 0; + std::uint64_t ngen = 0; + if (!cell_known_writable(cn, nkp, nkg, ngen) || nkp != kp || nkg != kg) break; + if (run_already_armed_[bridge_end] && + (run_pinned_[bridge_end] || is_tile_pinned(next_va) || cn.hot || + !restore_uniform(cn, kp))) { + break; + } + std::uint64_t cand_min_gen = (std::min)(run_min_gen, ngen); + bool gap_ok = true; + for (std::uintptr_t gap_va = prev_end; gap_va < next_va; gap_va += kTile) { + if (is_tile_pinned(gap_va)) { + gap_ok = false; + break; + } + const Cell* gc = nullptr; + if (const auto git = cells.find(gap_va); git != cells.end()) { + gc = git->second.cell; + } else if (const auto sit = s.cells.find(gap_va); sit != s.cells.end()) { + gc = &sit->second; + } + if (!gc || gc->hot || !restore_uniform(*gc, kp)) { + gap_ok = false; + break; + } + DWORD gkp = 0, gkg = 0; + std::uint64_t ggen = 0; + if (!cell_known_writable(*gc, gkp, gkg, ggen) || gkp != kp || gkg != kg) { + gap_ok = false; + break; + } + cand_min_gen = (std::min)(cand_min_gen, ggen); + } + if (!gap_ok) break; + run_min_gen = cand_min_gen; + if (run_eligible_[bridge_end]) { + last_eligible = bridge_end; + last_min_gen = run_min_gen; + } + ++bridge_end; + } + const std::size_t bridge_end_eff = last_eligible + 1; + if (bridge_end_eff > sub_end) { + const std::uintptr_t span_hi = batch_pages[last_eligible] + kTile; + std::uint64_t verified_gen = 0; + if (range_clean_since(last_min_gen, span_lo, span_hi, verified_gen)) { + DWORD old{}; + ++arm_stats.vp_calls; + if (VirtualProtect(reinterpret_cast(span_lo), span_hi - span_lo, kg, &old)) { + if (old == kp || old == kg) { + std::size_t n_bridged = 0; + for (std::size_t k = sub_start; k < bridge_end_eff; ++k) { + TrackedCell* const tc = run_entries_[k]; + if (run_eligible_[k]) { + tc->cell->restore.fill(kp); + tc->cell->armed_map_gen = verified_gen; + tc->cell->known_map_gen = verified_gen; + results[i + k] = 1; + tc->is_armed = true; + tc->armed_version = run_versions_[k]; + ++n_bridged; + } else { + tc->cell->armed_map_gen = verified_gen; + tc->cell->known_map_gen = verified_gen; + } + } + ++arm_stats.bridged_runs; + arm_stats.fast_tiles += n_bridged; + if (kp & PAGE_WRITECOMBINE) arm_stats.wc_tiles += n_bridged; + if (cached_hi && span_lo >= cached_lo && span_hi <= cached_hi) + cached_lo = span_hi; + sub_start = bridge_end_eff; + continue; + } + // Unexpected prior protection: `old` describes tile 0 (`span_lo`) only. + // Restore eligible tiles individually (tile 0 to `old`, other eligible tiles + // to their verified `kp`), leaving already-armed gap tiles at `kg`. + for (std::size_t k = sub_start; k < bridge_end_eff; ++k) { + if (!run_eligible_[k]) continue; + DWORD dummy{}; + ++arm_stats.vp_calls; + VirtualProtect(reinterpret_cast(batch_pages[k]), kTile, + k == sub_start ? old : kp, &dummy); + } + } + for (auto cit = s.cells.lower_bound(span_lo); + cit != s.cells.end() && cit->first < span_hi; ++cit) { + clear_cell_known(cit->second); + } + cached_hi = 0; + } + } + } + + const std::uintptr_t sub_lo = batch_pages[sub_start]; + const std::uintptr_t sub_hi = sub_lo + (sub_end - sub_start) * kTile; + + for (std::uintptr_t p = sub_lo; p < sub_hi;) { + // Fast path: tile-aligned repeat arm with verified uniform protection or cached no-guard + // state (MEM_RESERVE / PAGE_NOACCESS only; NEVER PAGE_READONLY) and no overlapping map + // change -> 0 VirtualQuery syscalls. + if ((p & (kTile - 1)) == 0 && sub_hi - p >= kTile) { + const std::size_t tile_k = sub_start + std::size_t((p - sub_lo) / kTile); + Cell* const c_fast = run_entries_[tile_k]->cell; + DWORD fkp = 0, fkg = 0; + std::uint64_t fgen0 = 0; + if (cell_known_writable(*c_fast, fkp, fkg, fgen0)) { + std::size_t fast_end = tile_k + 1; + std::uint64_t min_gen = fgen0, max_gen = fgen0; + while (fast_end < sub_end) { + DWORD nkp = 0, nkg = 0; + std::uint64_t ngen = 0; + if (!cell_known_writable(*run_entries_[fast_end]->cell, nkp, nkg, ngen) || + nkp != fkp || nkg != fkg) + break; + min_gen = (std::min)(min_gen, ngen); + max_gen = (std::max)(max_gen, ngen); + ++fast_end; + } + std::uintptr_t end = p + (fast_end - tile_k) * kTile; + std::uint64_t verified_gen = 0; + bool clean = range_clean_since(min_gen, p, end, verified_gen); + if (!clean && min_gen != max_gen && fast_end > tile_k + 1) { + std::size_t prefix_end = tile_k + 1; + while (prefix_end < fast_end && + run_entries_[prefix_end]->cell->known_map_gen == fgen0) + ++prefix_end; + fast_end = prefix_end; + end = p + (fast_end - tile_k) * kTile; + clean = range_clean_since(fgen0, p, end, verified_gen); + } + if (clean) { + DWORD old{}; + ++arm_stats.vp_calls; + if (VirtualProtect(reinterpret_cast(p), end - p, fkg, &old)) { + if (old == fkp || old == fkg) { + const std::size_t n_fast = fast_end - tile_k; + arm_stats.fast_tiles += n_fast; + if (fkp & PAGE_WRITECOMBINE) arm_stats.wc_tiles += n_fast; + for (std::size_t t = tile_k; t < fast_end; ++t) { + Cell* const ct = run_entries_[t]->cell; + ct->restore.fill(fkp); + ct->armed_map_gen = verified_gen; + ct->known_map_gen = verified_gen; + } + if (cached_hi && p >= cached_lo && end <= cached_hi) cached_lo = end; + p = end; + continue; + } + // Unexpected prior protection (caller bypassed title_memory_map::changed): + // `old` describes tile 0 (`p`) only; restore tile 0 to `old` and remaining + // tiles to their verified `fkp` before falling through to VirtualQuery. + for (std::uintptr_t q = p; q < end; q += kTile) { + DWORD dummy{}; + ++arm_stats.vp_calls; + VirtualProtect(reinterpret_cast(q), kTile, q == p ? old : fkp, + &dummy); + } + } + // Unexpected protection or VirtualProtect failure: invalidate cached protection + // for these tiles and fall through to VirtualQuery + VirtualProtect. + for (std::size_t t = tile_k; t < fast_end; ++t) + clear_cell_known(*run_entries_[t]->cell); + cached_hi = 0; + } + } else { + DWORD ng_st = 0, ng_kp = 0; + std::uint64_t ng_gen0 = 0; + if (cell_known_noguard(*c_fast, ng_st, ng_kp, ng_gen0)) { + std::size_t fast_end = tile_k + 1; + std::uint64_t min_gen = ng_gen0, max_gen = ng_gen0; + while (fast_end < sub_end) { + DWORD nst = 0, nkp = 0; + std::uint64_t ngen = 0; + if (!cell_known_noguard(*run_entries_[fast_end]->cell, nst, nkp, ngen) || + nst != ng_st || nkp != ng_kp) + break; + min_gen = (std::min)(min_gen, ngen); + max_gen = (std::max)(max_gen, ngen); + ++fast_end; + } + std::uintptr_t end = p + (fast_end - tile_k) * kTile; + std::uint64_t verified_gen = 0; + bool clean = range_clean_since(min_gen, p, end, verified_gen); + if (!clean && min_gen != max_gen && fast_end > tile_k + 1) { + std::size_t prefix_end = tile_k + 1; + while (prefix_end < fast_end && + run_entries_[prefix_end]->cell->known_map_gen == ng_gen0) + ++prefix_end; + fast_end = prefix_end; + end = p + (fast_end - tile_k) * kTile; + clean = range_clean_since(ng_gen0, p, end, verified_gen); + } + if (clean) { + for (std::size_t t = tile_k; t < fast_end; ++t) + run_entries_[t]->cell->known_map_gen = verified_gen; + arm_stats.skip_tiles += (fast_end - tile_k); + if (cached_hi && p >= cached_lo && end <= cached_hi) cached_lo = end; + p = end; + continue; + } + } + } + } + + std::uintptr_t region_base = 0; + std::uintptr_t region_end = 0; + DWORD state = 0; + DWORD protect = 0; + DWORD guarded = 0; + std::uint64_t query_gen = 0; + bool from_cache = false; + + std::uint64_t cache_now = 0; + if (p >= cached_lo && p < cached_hi && + range_clean_since(cached_gen, p, (std::min)(sub_hi, cached_hi), cache_now)) { + region_base = cached_lo; + region_end = cached_hi; + state = cached_state; + protect = cached_protect; + guarded = cached_guarded; + query_gen = cached_gen; + from_cache = true; + } else { + query_gen = title_memory_map::generation(); + MEMORY_BASIC_INFORMATION m{}; + ++arm_stats.vq_calls; + if (!VirtualQuery(reinterpret_cast(p), &m, sizeof m)) { + const std::size_t tile_k = sub_start + std::size_t((p - sub_lo) / kTile); + run_failed_[tile_k] = 1; + if (!run_slow_[tile_k]) { + run_slow_[tile_k] = 1; + ++arm_stats.slow_tiles; + } + p = (p & ~(kTile - 1)) + kTile; + continue; + } + region_base = reinterpret_cast(m.BaseAddress); + region_end = region_base + m.RegionSize; + state = m.State; + protect = m.Protect; + guarded = geometry_writes::read_only(m.Protect); + const DWORD base_prot = protect & 255u; + // Intra-pass region cache: MEM_RESERVE, MEM_FREE, PAGE_NOACCESS, and writable + // MEM_COMMIT. NEVER cache PAGE_READONLY / PAGE_EXECUTE_READ (ShadowPages::reopen() + // bypasses map_gen, so a concurrent RO -> RW reopen could mark a writable tile armed). + const bool cacheable_region = + state == MEM_RESERVE || state == MEM_FREE || + (state == MEM_COMMIT && !(protect & PAGE_GUARD) && + (guarded != 0 || base_prot == PAGE_NOACCESS)); + if (cacheable_region && region_end > sub_hi) { + cached_lo = p; + cached_hi = region_end; + cached_state = state; + cached_protect = protect; + cached_guarded = guarded; + cached_gen = query_gen; + } else { + cached_hi = 0; + } + } + + const std::uintptr_t end = (std::min)(sub_hi, region_end); + if (end <= p) { + const std::size_t tile_k = sub_start + std::size_t((p - sub_lo) / kTile); + run_failed_[tile_k] = 1; + if (!run_slow_[tile_k]) { + run_slow_[tile_k] = 1; + ++arm_stats.slow_tiles; + } + cached_hi = 0; + p = (p & ~(kTile - 1)) + kTile; + continue; + } + for (std::uintptr_t t = p & ~(kTile - 1); t < end; t += kTile) { + const std::size_t tile_k = sub_start + std::size_t((t - sub_lo) / kTile); + if (!run_slow_[tile_k]) { + run_slow_[tile_k] = 1; + ++arm_stats.slow_tiles; + } + if (state == MEM_COMMIT) { + if (protect & PAGE_WRITECOMBINE) { + if (!run_wc_[tile_k]) { + run_wc_[tile_k] = 1; + ++arm_stats.wc_tiles; + } + note_wc_page(t, true); + } else if (!run_wc_[tile_k]) { + note_wc_page(t, false); + } + } + if (t > UINTPTR_MAX - kTile) break; + } + if (state == MEM_COMMIT && !(protect & PAGE_GUARD) && guarded) { + DWORD old{}; + ++arm_stats.vp_calls; + if (VirtualProtect(reinterpret_cast(p), end - p, guarded, &old)) { + for (std::uintptr_t q = p; q < end; q += kHostPage) { + const std::size_t tile_k = sub_start + std::size_t((q - sub_lo) / kTile); + const std::size_t sub_p = std::size_t((q & (kTile - 1)) / kHostPage); + run_entries_[tile_k]->cell->restore[sub_p] = protect; + run_entries_[tile_k]->cell->armed_map_gen = Cell::kNoMapGen; + } + // Cache uniform whole-tile protections on shared Cell when no map change + // overlapped [first_full, last_full) between query_gen and VirtualProtect. + const std::uintptr_t first_full = (p + kTile - 1) & ~(kTile - 1); + const std::uintptr_t last_full = end & ~(kTile - 1); + std::uint64_t after_gen = 0; + if (first_full < last_full && region_base <= first_full && + region_end >= last_full && + range_clean_since(query_gen, first_full, last_full, after_gen)) { + for (std::uintptr_t t = first_full; t < last_full; t += kTile) { + const std::size_t tile_k = + sub_start + std::size_t((t - sub_lo) / kTile); + Cell* const c = run_entries_[tile_k]->cell; + c->known_state = MEM_COMMIT; + c->known_protect = protect; + c->known_guarded = guarded; + c->known_mapping = c->mapping.load(std::memory_order_acquire); + c->known_map_gen = after_gen; + c->armed_map_gen = after_gen; + } + } + if (cached_hi && p >= cached_lo && end <= cached_hi) cached_lo = end; + } else if (from_cache) { + // Cached region is stale: invalidate and retry this address with a fresh query. + cached_hi = 0; + continue; + } else { + // Multi-tile VirtualProtect failed: fall back per-tile so healthy neighbors arm. + cached_hi = 0; + for (std::uintptr_t t = p; t < end;) { + const std::uintptr_t t_end = (std::min)(end, (t & ~(kTile - 1)) + kTile); + const std::size_t tile_k = sub_start + std::size_t((t - sub_lo) / kTile); + ++arm_stats.vp_calls; + if (VirtualProtect(reinterpret_cast(t), t_end - t, guarded, &old)) { + for (std::uintptr_t q = t; q < t_end; q += kHostPage) { + const std::size_t sub_p = std::size_t((q & (kTile - 1)) / kHostPage); + run_entries_[tile_k]->cell->restore[sub_p] = protect; + } + run_entries_[tile_k]->cell->armed_map_gen = Cell::kNoMapGen; + } else { + run_failed_[tile_k] = 1; + } + t = t_end; + } + } + } else { + const std::uintptr_t first_full = (p + kTile - 1) & ~(kTile - 1); + const std::uintptr_t last_full = end & ~(kTile - 1); + if (first_full < last_full) { + const bool cacheable_noguard = + state == MEM_RESERVE || + (state == MEM_COMMIT && !(protect & PAGE_GUARD) && + (protect & 255u) == PAGE_NOACCESS); + std::uint64_t after_gen = 0; + if (cacheable_noguard && region_base <= first_full && region_end >= last_full && + range_clean_since(query_gen, first_full, last_full, after_gen)) { + for (std::uintptr_t t = first_full; t < last_full; t += kTile) { + const std::size_t tile_k = + sub_start + std::size_t((t - sub_lo) / kTile); + Cell* const c = run_entries_[tile_k]->cell; + c->known_state = state; + c->known_protect = (state == MEM_COMMIT) ? PAGE_NOACCESS : 0; + c->known_guarded = 0; + c->known_mapping = c->mapping.load(std::memory_order_acquire); + c->known_map_gen = after_gen; + } + } else { + // NEVER cache PAGE_READONLY / PAGE_EXECUTE_READ (or MEM_FREE / PAGE_GUARD) + // as no-guard: ShadowPages::reopen() reopens RO->RW without map change. + for (std::uintptr_t t = first_full; t < last_full; t += kTile) { + const std::size_t tile_k = + sub_start + std::size_t((t - sub_lo) / kTile); + clear_cell_known(*run_entries_[tile_k]->cell); + } + } + } + if (cached_hi && p >= cached_lo && end <= cached_hi) cached_lo = end; + } + p = end; + } + + for (std::size_t k = sub_start; k < sub_end; ++k) { + TrackedCell* const tc = run_entries_[k]; + if (!run_failed_[k]) { + results[i + k] = 1; + tc->is_armed = true; + tc->armed_version = run_versions_[k]; + } else { + results[i + k] = 0; + tc->is_armed = false; + } + } + sub_start = sub_end; + } + } + i = j; + } + } + + // Hot: the cell is held hot (writable, and written at every look for every other copy of the page), not + // just reopened behind the other copies' backs (which left them blind: run 64's frozen video). + void disarm(std::uintptr_t page) { + const auto it = cells.find(page); + if (it == cells.end()) return; + it->second.is_armed = false; + if (!it->second.is_hot) { + it->second.is_hot = true; + geometry_writes::set_hot(page, true); + } + } + + // Batched disarm for TitleWritePolicy::frame() (kProbe cycles & hot-promotion batches): sets hot on all newly + // hot tiles under a single geometry_writes::state().mutex hold. + void disarm_batch(const std::uintptr_t* pages, std::size_t count) { + if (!count) return; + if (count == 1) { + disarm(pages[0]); + return; + } + run_disarm_hot_.clear(); + for (std::size_t i = 0; i < count; ++i) { + const auto it = cells.find(pages[i]); + if (it == cells.end()) continue; + it->second.is_armed = false; + if (!it->second.is_hot) { + it->second.is_hot = true; + run_disarm_hot_.push_back(pages[i]); + } + } + if (!run_disarm_hot_.empty()) { + geometry_writes::set_hot_batch(run_disarm_hot_.data(), run_disarm_hot_.size(), true); + } + } + + std::vector run_entries_; + std::vector run_versions_; + std::vector run_pinned_; + std::vector run_backed_; + std::vector run_eligible_; + std::vector run_already_armed_; + std::vector run_failed_; + std::vector run_slow_; + std::vector run_wc_; + std::vector run_clear_hot_; + std::vector run_disarm_hot_; + std::vector run_backed_addrs_; + std::vector run_backed_idx_; + std::vector run_backed_res_; + std::vector> run_pin_ranges_; + }; + using Policy = TitleWritePolicy; + + void sync_pending_atomics() noexcept { + active_work_.store(policy_.hot_count() + policy_.dirty_count() + policy_.history_count() + ww_initial_.size(), + std::memory_order_release); + ww_count_.store(ww_pages_.size(), std::memory_order_release); + } + + CellGuard guard_; + Policy policy_; + geometry_writes::WriteQueue queue_; + std::vector tiles_; + std::uint64_t refused_seen_ = 0; + std::atomic active_work_{0}; + std::atomic ww_count_{0}; + + // Write-watched private pages (MEM_WRITE_WATCH via title_write_watch): zero guard faults, zero VirtualProtect. + std::uint64_t ww_reader_ = 0; + std::uint64_t ww_gen_ = 0; + bool ww_runs_dirty_ = false; + std::unordered_set ww_pages_; + std::vector ww_sorted_; + std::vector ww_initial_; + std::vector> ww_runs_; + std::vector> ww_retry_runs_; + std::vector> ww_split_runs_; + std::vector ww_dirty_; + std::vector ww_refused_; + std::vector batch_watch_addrs_; + std::vector batch_watch_tcs_; + std::vector batch_watch_cells_; + std::vector> batch_unwatch_items_; +}; + +} // namespace leonida diff --git a/runtime/src/title_mirror_space.h b/runtime/src/title_mirror_space.h new file mode 100644 index 0000000000..bb18abfd28 --- /dev/null +++ b/runtime/src/title_mirror_space.h @@ -0,0 +1,106 @@ +#pragma once +// Where xmem puts the title's GPU-readable reservations (title_mirror_space): a fixed range of the title's address space +// that the D3D12 layer's page mirror can cover (src/title_mirror.h). +// +// The translated shaders read a V# base or a 64-bit pointer as heap_base + sext48(address) (docs/design.md, +// "Heap-relative buffer device addresses"). A V# or pointer the title wrote into its own memory names a title address, +// so it reaches the title's bytes only if the GPU memory at heap_base + that address holds them. The mirror puts sparse +// buffers exactly there (bufferDeviceAddressCaptureReplay) and binds each page to its physical page's GPU home. RADV +// honours a chosen address only inside its sparse range, the top 64 TiB of the address space (vk_sparse_bind_bench), and +// heap_base, the sparse arena's address, lies at its bottom: so heap_base + address stays inside it for addresses below +// about 64 TiB. Under Wine and on Windows the host puts large reservations near the top of the 128 TiB user space +// (0x7fb3... in a world run), out of reach. So xmem picks the address of every XMemVirtualAlloc reservation the title lets +// it place (address null) from [kLow, kHigh), which the host leaves free, and the title only ever sees that address. +// +// The range is handed out in order and not reused: a released reservation's addresses are never given out again +// (32 TiB lasts any run measured; a reservation that does not fit is placed by the host, as before, and counted). +#include +#include +#include +#include +#include +#include + +namespace leonida::title_mirror_space { + +constexpr std::uint64_t kLow = 0x100000000000ull; // 16 TiB +constexpr std::uint64_t kHigh = 0x300000000000ull; // 48 TiB +constexpr std::uint64_t kChunk = std::uint64_t(2) << 30; // the mirror's sparse buffers: 2 GiB each, aligned + +struct State { + std::mutex mutex; + std::uint64_t next = kLow; + std::vector> taken; // [base, end), in order + std::vector plain; // per taken range: ordinary memory (not physical-page windows or placeholders) + std::atomic generation{0}; + std::atomic placed_bytes{0}, refused{0}; +}; +inline State& state() { + static State s; + return s; +} + +// LEONIDA_PAGE_MIRROR=0: the host places every reservation, as before. +inline bool enabled() { + static const bool on = [] { + const char* v = std::getenv("LEONIDA_PAGE_MIRROR"); + return !(v && v[0] == '0'); + }(); + return on; +} + +inline bool contains(std::uint64_t va) { return va >= kLow && va < kHigh; } + +// The next free address for `size` bytes aligned to `alignment` (a power of two), or 0 when the range is spent. `reserve` +// tries the host's reservation there: false (the host has something there) moves on by one chunk. A reservation of at +// most one sparse chunk (kChunk, 2 GiB) that would cross a chunk boundary advances to the next chunk boundary so placed +// buffers inside it never straddle two chunks. Under the state's lock: +// `reserve` must not take a lock a reserving thread holds (xmem calls this before taking any of its own). +// `plain`: ordinary memory the title's CPU and GPU read at this address (an XMemVirtualAlloc region of committed or +// reserved pages), mirrored page by page as readers name it; otherwise physical-page windows or placeholders, whose +// pages xmem's feed reports as they are mapped. +template +std::uint64_t take(std::uint64_t size, std::uint64_t alignment, bool plain, Reserve&& reserve) { + State& s = state(); + if (!enabled() || !size) return 0; + if (alignment < 0x10000) alignment = 0x10000; + std::lock_guard lock(s.mutex); + for (int tries = 0; tries < 64; ++tries) { + std::uint64_t at = (s.next + alignment - 1) & ~(alignment - 1); + if (at >= kHigh) break; + if (size <= kChunk) { + const std::uint64_t chunk_end = (at & ~(kChunk - 1)) + kChunk; + if (size > chunk_end - at) at = (chunk_end + alignment - 1) & ~(alignment - 1); + } + if (at >= kHigh || size > kHigh - at) break; + if (reserve(at)) { + s.next = at + ((size + 0xffff) & ~std::uint64_t(0xffff)); + s.taken.emplace_back(at, at + size); + s.plain.push_back(plain); + s.placed_bytes.fetch_add(size, std::memory_order_relaxed); + s.generation.fetch_add(1, std::memory_order_release); + return at; + } + s.next = ((at + kChunk) & ~(kChunk - 1)); // something of the host's is there: past it + } + s.refused.fetch_add(1, std::memory_order_relaxed); + return 0; +} + +inline std::uint64_t generation() { return state().generation.load(std::memory_order_acquire); } + +// The reservations made so far: f(base, end, plain) for each. +template +void for_each_taken(F&& f) { + State& s = state(); + std::vector> copy; + std::vector plain; + { + std::lock_guard lock(s.mutex); + copy = s.taken; + plain = s.plain; + } + for (std::size_t i = 0; i < copy.size(); ++i) f(copy[i].first, copy[i].second, bool(plain[i])); +} + +} // namespace leonida::title_mirror_space diff --git a/runtime/src/title_mirror_tracking.h b/runtime/src/title_mirror_tracking.h new file mode 100644 index 0000000000..b0c4009a23 --- /dev/null +++ b/runtime/src/title_mirror_tracking.h @@ -0,0 +1,103 @@ +#pragma once +// Which mirrored pages the host wrote (title_mirror_tracking): the page mirror's dirty set (src/title_mirror.h). +// +// The interface is all the mirror asks for, so a tracking policy can replace the one here without touching the mirror: +// - watch(page) when a page enters the mirror (before its home is filled: a write after the fill must be seen); +// - unwatch(page) when it leaves; +// - collect(out): the pages written since the last collect, each made watched again before it is returned (clear +// and re-arm first, then the caller copies: a write during the copy is in the next collect). +// Pages are 64 KiB-aligned title addresses. Not thread-safe: the mirror's caller serialises. +// +// GuardTracking, the plainest correct policy: every watched page is guarded with the geometry watch's cell at its +// address (src/title_geometry_watch.h). A host view is made read-only and the title's first write faults; a kernel +// write (kernel_writes) or a remap moves the cell's version too. A page whose guard cannot be set (a kernel write into +// it is in progress) is returned at every collect until it can be. +#include "title_geometry_watch.h" + +#include +#include +#include +#include + +namespace leonida { + +class TitleMirrorTracking { +public: + virtual ~TitleMirrorTracking() = default; + virtual void watch(std::uint64_t page) = 0; + virtual void unwatch(std::uint64_t page) = 0; + virtual void collect(std::vector& out) = 0; + // True when nothing has written the page since it was last watched (watch or collect): the mirror may then copy + // what the GPU wrote into its home back to the title's page. False when not known: no copy back (the title's bytes + // win), which a policy that cannot tell must answer. + virtual bool unwritten(std::uint64_t) { return false; } + // Diagnostics since the last call: guards that could not be set. + virtual std::uint64_t take_refused() { return 0; } +}; + +class GuardTracking final : public TitleMirrorTracking { +public: + GuardTracking() { geometry_writes::subscribe_writes(queue_); } + ~GuardTracking() override { + geometry_writes::unsubscribe_writes(queue_); + for (const auto& [page, cell] : cells_) geometry_writes::release(page); + } + GuardTracking(const GuardTracking&) = delete; + GuardTracking& operator=(const GuardTracking&) = delete; + + void watch(std::uint64_t page) override { + if (cells_.count(page)) return; + geometry_writes::Cell* cell = geometry_writes::acquire(page); + cells_.emplace(page, cell); + arm(page, *cell); + } + void unwatch(std::uint64_t page) override { + const auto it = cells_.find(page); + if (it == cells_.end()) return; + armed_.erase(page); + geometry_writes::release(page); + cells_.erase(it); + } + void collect(std::vector& out) override { + out.clear(); + bool overflow = false; + geometry_writes::take_written(queue_, tiles_, overflow); + if (overflow) { + tiles_.clear(); + for (const auto& [page, cell] : cells_) tiles_.push_back(page); + } + tiles_.insert(tiles_.end(), unarmed_.begin(), unarmed_.end()); + unarmed_.clear(); + for (const std::uintptr_t tile : tiles_) { + const auto it = cells_.find(tile); + if (it == cells_.end()) continue; + arm(tile, *it->second); // re-armed before the caller copies + out.push_back(tile); + } + } + std::uint64_t take_refused() override { return std::exchange(refused_, 0); } + bool unwritten(std::uint64_t page) override { + const auto it = cells_.find(page); + if (it == cells_.end()) return false; + const auto armed = armed_.find(page); + return armed != armed_.end() && it->second->version.load(std::memory_order_acquire) == armed->second; + } + +private: + void arm(std::uint64_t page, geometry_writes::Cell& cell) { + // The version before the guard: a write after this moves it (unwritten() then says no). + armed_[page] = cell.version.load(std::memory_order_acquire); + if (geometry_writes::arm(std::uintptr_t(page), cell)) return; + armed_.erase(page); + ++refused_; + unarmed_.push_back(std::uintptr_t(page)); + } + + geometry_writes::WriteQueue queue_; + std::unordered_map cells_; + std::unordered_map armed_; // page -> its cell's version when it was last armed + std::vector tiles_, unarmed_; + std::uint64_t refused_ = 0; +}; + +} // namespace leonida diff --git a/runtime/src/title_page_watch.h b/runtime/src/title_page_watch.h index 44a19cb1bf..ff75bbcdf6 100644 --- a/runtime/src/title_page_watch.h +++ b/runtime/src/title_page_watch.h @@ -49,6 +49,7 @@ #include #include "guarded_copy.h" +#include "title_frames.h" #include #include @@ -366,7 +367,9 @@ inline std::uintptr_t to_host_view(std::uintptr_t va, std::uintptr_t bytes = 1) if (!view_at(va, bytes, range)) return va; const auto offset = va >= range.gpu && va - range.gpu < range.size ? va - range.gpu : va - range.cpu; const auto cpu = range.cpu + offset, gpu = range.gpu + offset; + // A page xmem's frame table holds (slot 31's copies onto the pair, src/title_frames.h) is readable through it. const auto readable = [](std::uintptr_t address) { + if (title_frames::backed(address)) return true; MEMORY_BASIC_INFORMATION region{}; return VirtualQuery(reinterpret_cast(address), ®ion, sizeof(region)) && region.State == MEM_COMMIT && region.Protect && !(region.Protect & (PAGE_NOACCESS | PAGE_GUARD)); @@ -384,9 +387,11 @@ inline std::uintptr_t to_host_view(std::uintptr_t va, std::uintptr_t bytes = 1) namespace leonida::title_texel_writes { struct State { + static constexpr std::size_t kMaxMerged = 16384; std::mutex mutex; std::vector> ranges; // [begin, end) - bool overflow = false; // too many to keep: check everything + std::size_t compact_at = kMaxMerged; + bool overflow = false; // too many disjoint spans to keep: check everything std::atomic pending{false}; }; @@ -399,9 +404,37 @@ inline void note(const void* begin, std::size_t bytes) { if (!begin || !bytes) return; State& s = state(); std::lock_guard lock(s.mutex); + if (s.overflow) { + s.pending.store(true, std::memory_order_release); + return; + } const auto at = reinterpret_cast(begin); - if (s.ranges.size() < 4096) s.ranges.emplace_back(at, at + bytes); - else s.overflow = true; + const std::uintptr_t end = bytes > UINTPTR_MAX - at ? UINTPTR_MAX : at + bytes; + if (!s.ranges.empty() && at <= s.ranges.back().second && end >= s.ranges.back().first) { + s.ranges.back().first = (std::min)(s.ranges.back().first, at); + s.ranges.back().second = (std::max)(s.ranges.back().second, end); + s.pending.store(true, std::memory_order_release); + return; + } + s.ranges.emplace_back(at, end); + if (s.ranges.size() > s.compact_at) { + std::sort(s.ranges.begin(), s.ranges.end()); + std::size_t kept = 0; + for (std::size_t i = 1; i < s.ranges.size(); ++i) { + if (s.ranges[i].first <= s.ranges[kept].second) + s.ranges[kept].second = (std::max)(s.ranges[kept].second, s.ranges[i].second); + else + s.ranges[++kept] = s.ranges[i]; + } + s.ranges.resize(kept + 1); + if (s.ranges.size() > State::kMaxMerged) { + s.overflow = true; + s.ranges.clear(); + s.compact_at = State::kMaxMerged; + } else { + s.compact_at = (std::max)(State::kMaxMerged, s.ranges.size() + 4096); + } + } s.pending.store(true, std::memory_order_release); } @@ -412,7 +445,8 @@ inline std::vector> take(bool& overflo if (!s.pending.load(std::memory_order_acquire)) return {}; std::lock_guard lock(s.mutex); overflow = std::exchange(s.overflow, false); - s.pending.store(false, std::memory_order_relaxed); + s.compact_at = State::kMaxMerged; + s.pending.store(false, std::memory_order_release); return std::exchange(s.ranges, {}); } @@ -661,45 +695,111 @@ std::uint64_t ask(std::uint64_t reader, const Runs& runs, Dirty&& dirty, Refused const auto me = s.readers.find(reader); const std::uint64_t since = me != s.readers.end() ? me->second : 0; const std::uint64_t now = s.asked.fetch_add(1, std::memory_order_acq_rel) + 1; - s.refusals.assign(runs.size(), 0); - for (std::size_t r = 0; r < runs.size(); ++r) { - const auto [from, to] = runs[r]; - ULONG_PTR count = (to - from) / kPage; - if (s.found.size() < count) s.found.resize(count); - ULONG granularity = 0; - if (GetWriteWatch(WRITE_WATCH_FLAG_RESET, reinterpret_cast(from), to - from, s.found.data(), &count, - &granularity) != 0) { - s.refusals[r] = 1; - continue; - } - for (ULONG_PTR k = 0; k < count; ++k) - s.written[reinterpret_cast(s.found[k]) & ~(kPage - 1)] = now; - } - for (std::size_t r = 0; r < runs.size(); ++r) { - const auto [from, to] = runs[r]; - if (s.refusals[r]) { - refused(from, to); - continue; + + // Single-reader fast path: avoid inserting GetWriteWatch results into s.written (zero host_heap RB-tree node + // allocations per dirty 4 KiB page), while still reporting and erasing any s.written entries within [from, to) + // produced by title_write_watch::mark() or earlier multi-reader askings (leaving entries outside [from, to) alone). + if (me != s.readers.end() && s.readers.size() == 1) { + for (std::size_t r = 0; r < runs.size(); ++r) { + const auto [from, to] = runs[r]; + ULONG_PTR count = (to - from) / kPage; + if (s.found.size() < count) s.found.resize(count); + ULONG granularity = 0; + if (GetWriteWatch(WRITE_WATCH_FLAG_RESET, reinterpret_cast(from), to - from, s.found.data(), &count, + &granularity) != 0) { + refused(from, to); + continue; + } + const std::uint64_t reserved = born(from); + if (since < s.floor || !reserved || reserved > since) { + if (!s.written.empty()) { + auto it = s.written.lower_bound(from); + while (it != s.written.end() && it->first < to) it = s.written.erase(it); + } + dirty(from, to); + continue; + } + if (!s.written.empty()) { + for (auto it = s.written.lower_bound(from); it != s.written.end() && it->first < to;) { + if (it->second > since) { + if (s.found.size() <= count) s.found.resize(count + 1); + s.found[count++] = reinterpret_cast(it->first); + } + it = s.written.erase(it); + } + } + if (!count) continue; + bool sorted = true; + std::uintptr_t prev_p = reinterpret_cast(s.found[0]) & ~(kPage - 1); + for (ULONG_PTR k = 1; k < count; ++k) { + const std::uintptr_t cur_p = reinterpret_cast(s.found[k]) & ~(kPage - 1); + if (cur_p < prev_p) { + sorted = false; + break; + } + prev_p = cur_p; + } + if (!sorted) { + std::sort(s.found.begin(), s.found.begin() + static_cast(count), + [](void* a, void* b) { + return (reinterpret_cast(a) & ~(kPage - 1)) < + (reinterpret_cast(b) & ~(kPage - 1)); + }); + } + std::uintptr_t run_from = 0, run_to = 0; + for (ULONG_PTR k = 0; k < count; ++k) { + const std::uintptr_t p = reinterpret_cast(s.found[k]) & ~(kPage - 1); + if (run_from != run_to && p < run_to) continue; + if (p != run_to) { + if (run_from != run_to) dirty(run_from, run_to); + run_from = p; + } + run_to = p + kPage; + } + if (run_from != run_to) dirty(run_from, run_to); } - // Forgotten before this reader saw it, or a reservation new to it: all of it. Looked up after `now` was - // taken, so a reservation recorded later has a higher number and is all written at the next asking too. - const std::uint64_t reserved = born(from); - if (since < s.floor || !reserved || reserved > since) { - dirty(from, to); - continue; + me->second = now; + } else { + s.refusals.assign(runs.size(), 0); + for (std::size_t r = 0; r < runs.size(); ++r) { + const auto [from, to] = runs[r]; + ULONG_PTR count = (to - from) / kPage; + if (s.found.size() < count) s.found.resize(count); + ULONG granularity = 0; + if (GetWriteWatch(WRITE_WATCH_FLAG_RESET, reinterpret_cast(from), to - from, s.found.data(), &count, + &granularity) != 0) { + s.refusals[r] = 1; + continue; + } + for (ULONG_PTR k = 0; k < count; ++k) + s.written[reinterpret_cast(s.found[k]) & ~(kPage - 1)] = now; } - std::uintptr_t run_from = 0, run_to = 0; - for (auto it = s.written.lower_bound(from); it != s.written.end() && it->first < to; ++it) { - if (it->second <= since) continue; - if (it->first != run_to) { - if (run_from != run_to) dirty(run_from, run_to); - run_from = it->first; + for (std::size_t r = 0; r < runs.size(); ++r) { + const auto [from, to] = runs[r]; + if (s.refusals[r]) { + refused(from, to); + continue; } - run_to = it->first + kPage; + // Forgotten before this reader saw it, or a reservation new to it: all of it. Looked up after `now` was + // taken, so a reservation recorded later has a higher number and is all written at the next asking too. + const std::uint64_t reserved = born(from); + if (since < s.floor || !reserved || reserved > since) { + dirty(from, to); + continue; + } + std::uintptr_t run_from = 0, run_to = 0; + for (auto it = s.written.lower_bound(from); it != s.written.end() && it->first < to; ++it) { + if (it->second <= since) continue; + if (it->first != run_to) { + if (run_from != run_to) dirty(run_from, run_to); + run_from = it->first; + } + run_to = it->first + kPage; + } + if (run_from != run_to) dirty(run_from, run_to); } - if (run_from != run_to) dirty(run_from, run_to); + if (me != s.readers.end()) me->second = now; } - if (me != s.readers.end()) me->second = now; // What every reader has seen goes, once the journal doubled or every kPruneEvery askings (a pruning that dropped // little, readers being behind then, must not stop the next); past kMaxPages, what is more than kKeep askings old // goes too. @@ -890,15 +990,48 @@ inline bool store_guarded(void* destination, std::uint64_t value, std::size_t by } } // namespace detail +namespace detail { +// Pins [to, to + bytes) as a kernel write, and the same bytes at the other addresses of each table page in it (the +// host views of its physical page, src/title_frames.h): a write through the frame faults no guard anywhere, so the +// guards over every address it shows at are lifted first and the copies there take the bytes. The pins go to `pins`. +inline void pin_frames(std::uintptr_t to, std::size_t bytes, std::vector& pins) { + pins.push_back(begin_write(reinterpret_cast(to), bytes, nullptr)); + std::vector peers; + title_frames::for_each_part(to, bytes, [&](std::uintptr_t at, std::size_t n, std::uint8_t* frame) { + if (!frame) return true; + peers.clear(); + title_frames::peers(at, peers); + for (const std::uintptr_t peer : peers) + pins.push_back(begin_write(reinterpret_cast(peer + (at & (title_frames::kPage - 1))), n, nullptr)); + return true; + }); +} +} // namespace detail + // A host thread's copy of `bytes` from `source` into the title's memory at `destination`: pinned and opened as a // kernel write is, so the guards over it are lifted first, the copies take the bytes at the next submission and no // refresh guards it again mid-copy; retried once after reopen() if it faults anyway (not when the two ranges overlap: // the part copied before the fault changed the source). False when it still faults (the destination, or the source, // is not memory it can copy). +// +// Pages xmem's frame table holds (a stream pool's GPU-only pages and their CPU twins after queue slot 31's copies: +// they have no host view, src/title_frames.h) are written through their frames, with their other addresses pinned too. inline bool write(void* destination, const void* source, std::size_t bytes) { if (!bytes) return true; const auto to = reinterpret_cast(destination), from = reinterpret_cast(source); const bool overlap = to < from + bytes && from < to + bytes; + if (title_frames::may_hold(to, to + bytes)) { + std::vector pins; + detail::pin_frames(to, bytes, pins); + const auto* in = static_cast(source); + const bool ok = title_frames::for_each_part(to, bytes, [&](std::uintptr_t at, std::size_t n, std::uint8_t* frame) { + void* const out = frame ? static_cast(frame) : reinterpret_cast(at); + if (detail::move_guarded(out, in + (at - to), n)) return true; + return !frame && !overlap && reopen(out, n) && detail::move_guarded(out, in + (at - to), n); + }); + for (const std::uint64_t pin : pins) end_write(pin, false); + return ok; + } const std::uint64_t pin = begin_write(destination, bytes, nullptr); bool ok = detail::move_guarded(destination, source, bytes); if (!ok && !overlap && reopen(destination, bytes)) ok = detail::move_guarded(destination, source, bytes); @@ -907,10 +1040,19 @@ inline bool write(void* destination, const void* source, std::size_t bytes) { } // write() of a 4- or 8-byte value (the low `bytes` of `value`). Aligned, it is stored in one locked access, so a -// title thread polling it never reads a mix of the old and the new value; pinned and retried the same way. +// title thread polling it never reads a mix of the old and the new value; pinned and retried the same way. A table +// page's value goes into its frame, the same way. inline bool store(void* destination, std::uint64_t value, std::size_t bytes) { const auto to = reinterpret_cast(destination); if ((bytes != 4 && bytes != 8) || to % bytes) return write(destination, &value, bytes); + title_frames::Frame frame; + if (title_frames::find(to, frame)) { + std::vector pins; + detail::pin_frames(to, bytes, pins); + const bool ok = detail::store_guarded(frame.bytes, value, bytes); + for (const std::uint64_t pin : pins) end_write(pin, false); + return ok; + } const std::uint64_t pin = begin_write(destination, bytes, nullptr); bool ok = detail::store_guarded(destination, value, bytes); if (!ok && reopen(destination, bytes)) ok = detail::store_guarded(destination, value, bytes); @@ -918,10 +1060,39 @@ inline bool store(void* destination, std::uint64_t value, std::size_t bytes) { return ok; } +// Whether [buffer, buffer + bytes) holds a page of xmem's frame table (the kernel cannot write such a page: it has no +// host view). +inline bool holds_table_page(const void* buffer, std::size_t bytes) { + const auto at = reinterpret_cast(buffer); + if (!bytes || !title_frames::may_hold(at, at + bytes)) return false; + bool found = false; + title_frames::for_each_part(at, bytes, [&](std::uintptr_t, std::size_t, std::uint8_t* frame) { + found = frame != nullptr; + return !found; + }); + return found; +} + // The file shims' reads into title memory (file_system.cpp): ReadFile, ReadFileEx and ReadFileScatter with their // destination pinned and opened first, and retried once if it fails with ERROR_NOACCESS anyway (after committing // first-touch pages: the title retries such a read forever, `0x314200`, so the retry has to change something). +// +// A destination with pages of xmem's frame table (DirectStorage reading a request straight into a stream pool's +// GPU-only destination, src/title_frames.h) is read into memory of the runtime's first, completed (waited for when it +// is overlapped and pending), and then written through write(): the kernel cannot write a page with no host view. inline BOOL read_file(HANDLE file, LPVOID buffer, DWORD bytes, LPDWORD read, LPOVERLAPPED overlapped) { + if (holds_table_page(buffer, bytes)) { + std::vector bounce(bytes); + DWORD got = 0; + BOOL ok = ::ReadFile(file, bounce.data(), bytes, &got, overlapped); + if (!ok && GetLastError() == ERROR_IO_PENDING && overlapped) ok = GetOverlappedResult(file, overlapped, &got, TRUE); + if (ok && !write(buffer, bounce.data(), got)) { + ok = FALSE; + SetLastError(ERROR_NOACCESS); + } + if (read) *read = ok ? got : 0; + return ok; + } const std::uint64_t pin = begin_write(buffer, bytes, overlapped); BOOL ok = ::ReadFile(file, buffer, bytes, read, overlapped); if (!ok && GetLastError() == ERROR_NOACCESS && reopen(buffer, bytes)) diff --git a/runtime/src/title_texture_memory.h b/runtime/src/title_texture_memory.h index d2c512cecc..f2ba000521 100644 --- a/runtime/src/title_texture_memory.h +++ b/runtime/src/title_texture_memory.h @@ -47,6 +47,11 @@ class TextureReadability { void defer() { pending_ = true; } // mapping disappeared between the probe and the read void retry() { retry_ = true; } bool pending() const { return pending_; } + bool needs_probe(std::uint64_t generation, bool cache_failure, bool cache_success = false) const noexcept { + if (cache_failure && pending_ && !retry_ && generation_ == generation) return false; + if (cache_success && probed_ && !pending_ && !retry_ && generation_ == generation) return false; + return true; + } private: std::uint64_t generation_ = 0; std::uint64_t map_generation_ = 0; @@ -55,12 +60,71 @@ class TextureReadability { using TexturePageCommitter = bool (*)(const void*, std::size_t); -// How many of the bytes from `base` are readable, up to the first page that is not (at most `size`). +// Short-lived per-pass cache of the last VirtualQuery region [lo, hi) (both readable MEM_COMMIT regions and +// non-guard unreadable regions such as MEM_RESERVE / MEM_FREE / PAGE_NOACCESS). Reused across VA-sorted texture +// probes only when `!commit` and no title_memory_map change overlapped [lo, hi). +struct TextureVqCache { + std::uintptr_t lo = 0; + std::uintptr_t hi = 0; + std::uint64_t gen = 0; + bool readable = false; + + void reset() noexcept { + lo = hi = 0; + gen = 0; + readable = false; + } +}; + +// How many of the bytes from `base` are readable, up to the first page that is not (at most `size`). A page xmem's +// frame table holds (a stream pool page queue slot 31 gave a physical page: no host view, src/title_frames.h) is +// readable through its frame. inline std::uint64_t texture_memory_readable_bytes(std::uintptr_t base, std::uint64_t size, - TexturePageCommitter commit = nullptr) { + TexturePageCommitter commit = nullptr, + TextureVqCache* vq_cache = nullptr) { if (!base || !size || size > (std::numeric_limits::max)() - base) return 0; const auto end = base + size; + // Hoist the non-table-frame boundary `[at, host_stop)` outside the VirtualQuery loop so VMA fragmentation + // (64 KiB alternating RO/RW regions) does not re-acquire title_frames' g_frame_lock on every step. + std::uintptr_t host_stop = title_frames::may_hold(base, end) ? base : end; for (auto at = base; at < end;) { + if (at >= host_stop) { + if (title_frames::may_hold(at, end)) { + bool backed = false; + host_stop = title_frames::run_end(at, end, backed); + if (backed) { + at = host_stop; + continue; + } + } else { + host_stop = end; + } + } + const auto stop = host_stop; + if (vq_cache && !commit && at >= vq_cache->lo && at < vq_cache->hi) { + const std::uint64_t cur = title_memory_map::generation(); + bool clean = (cur == vq_cache->gen); + if (!clean) { + std::uint64_t now = cur; + bool overlapped = false; + if (title_memory_map::changes_since(vq_cache->gen, now, vq_cache->lo, vq_cache->hi, + [&](std::uintptr_t c_from, std::uintptr_t c_to) { + if (c_from < c_to) overlapped = true; + }) && + !overlapped) { + vq_cache->gen = now; + clean = true; + } else { + vq_cache->hi = 0; + } + } + if (clean) { + if (!vq_cache->readable) return at - base; + at = (std::min)(stop, vq_cache->hi); + continue; + } + } + const std::uint64_t query_gen = (vq_cache && !commit) ? title_memory_map::generation() : 0; MEMORY_BASIC_INFORMATION region{}; const auto* address = reinterpret_cast(at); if (!VirtualQuery(address, ®ion, sizeof(region))) return at - base; @@ -69,24 +133,39 @@ inline std::uint64_t texture_memory_readable_bytes(std::uintptr_t base, std::uin if (commit && region.State == MEM_RESERVE && region.Type == MEM_MAPPED) { if (!commit(address, end - at) || !VirtualQuery(address, ®ion, sizeof(region))) return at - base; } - if (region.State != MEM_COMMIT || (region.Protect & PAGE_GUARD)) return at - base; - switch (region.Protect & 0xff) { - case PAGE_READONLY: case PAGE_READWRITE: case PAGE_WRITECOPY: - case PAGE_EXECUTE_READ: case PAGE_EXECUTE_READWRITE: case PAGE_EXECUTE_WRITECOPY: break; - default: return at - base; + bool region_readable = (region.State == MEM_COMMIT) && !(region.Protect & PAGE_GUARD); + if (region_readable) { + switch (region.Protect & 0xff) { + case PAGE_READONLY: case PAGE_READWRITE: case PAGE_WRITECOPY: + case PAGE_EXECUTE_READ: case PAGE_EXECUTE_READWRITE: case PAGE_EXECUTE_WRITECOPY: break; + default: region_readable = false; break; + } } const auto start = reinterpret_cast(region.BaseAddress); if (at < start || at - start >= region.RegionSize) return at - base; + const bool cacheable_neg = !(region.State == MEM_COMMIT && (region.Protect & PAGE_GUARD)); + if (vq_cache && !commit && (region_readable || cacheable_neg) && + region.RegionSize <= (std::numeric_limits::max)() - start) { + vq_cache->lo = start; + vq_cache->hi = start + region.RegionSize; + vq_cache->gen = query_gen; + vq_cache->readable = region_readable; + } + if (!region_readable) return at - base; const auto available = region.RegionSize - (at - start); - if (available >= end - at) return size; + if (available >= stop - at) { + at = stop; + continue; + } at += available; } return size; } // Check the whole footprint. A committed first page says nothing about a streamed mip farther on. -inline bool texture_memory_readable(std::uintptr_t base, std::uint64_t size, TexturePageCommitter commit = nullptr) { - return size && texture_memory_readable_bytes(base, size, commit) == size; +inline bool texture_memory_readable(std::uintptr_t base, std::uint64_t size, TexturePageCommitter commit = nullptr, + TextureVqCache* vq_cache = nullptr) { + return size && texture_memory_readable_bytes(base, size, commit, vq_cache) == size; } } // namespace leonida diff --git a/runtime/src/title_texture_refresh.h b/runtime/src/title_texture_refresh.h index b39defdcda..8f2af2f9d8 100644 --- a/runtime/src/title_texture_refresh.h +++ b/runtime/src/title_texture_refresh.h @@ -1,8 +1,11 @@ #pragma once +#include "shadow_keep.h" + #include #include -#include #include +#include +#include #include #include @@ -10,6 +13,258 @@ namespace leonida { using TitleWriteRanges = std::vector>; +// Computes the exact 64-bit piece-sum digest matching TitleMirror::range_sum(va, bytes, out) whenever +// `(va & (shadow_keep::kPiece - 1)) == 0 && (bytes & (shadow_keep::kPiece - 1)) == 0` (256-byte aligned, true for +// virtually all console textures and every 64 KiB tile boundary). Also works for arbitrary byte lengths (hashing any +// trailing partial piece with shadow_keep::sum_of) for fast 4-lane CPU piece hashing (~18 GB/s vs ~3.6 GB/s). +inline std::uint64_t mirror_range_sum_bytes(const std::uint8_t* data, std::uint64_t bytes) { + if (!bytes) return 0; + constexpr std::uint64_t kPiece = shadow_keep::kPiece; + std::uint64_t h = 14695981039346656037ull ^ bytes; + for (std::uint64_t off = 0; off < bytes; off += kPiece) { + const std::size_t n = static_cast((std::min)(kPiece, bytes - off)); + const std::uint64_t s = shadow_keep::sum_of(data + off, n); + h = (h ^ s) * 1099511628211ull; + h ^= h >> 29; + } + return h; +} + +// Same digest built from precomputed 256-byte piece sums (avoids a second pass over texture bytes when both per-tile +// TilePieces hashes and the full-texture mirror_hash are needed). +inline std::uint64_t mirror_range_sum_from_pieces(const std::uint64_t* piece_sums, std::size_t piece_count, + std::uint64_t bytes) { + if (!bytes || !piece_count) return 0; + std::uint64_t h = 14695981039346656037ull ^ bytes; + for (std::size_t i = 0; i < piece_count; ++i) { + h = (h ^ piece_sums[i]) * 1099511628211ull; + h ^= h >> 29; + } + return h; +} + +// Per-entry retire-watermarked passive write-back set for console-heap V# ranges awaiting a `writes_buffer == true` +// submission. Replaces the coarse `in_flight_executes > 1` non-clearing guard: +// - Every noted [begin, end) is stamped with a monotonic sequence number `seq` and `retire_id = 0` (unpromoted). +// - Overlapping older ranges are split around [begin, end) so a fresh small note never extends an older range's seq +// or clears its retire watermark, and adjacent ranges are kept separate so stale ranges never snowball. +// - `begin_execute()` allocates a monotonic `exec_id`; `end_execute(id)` removes it and prunes any already-promoted +// entry (`retire_id != 0`) whose `retire_id` is strictly below the oldest remaining active execute (or all +// already-promoted entries when no execute remains active). +// - `promote(my_exec_id, emit)` emits entries where `retire_id == 0 || my_exec_id == 0 || my_exec_id <= retire_id`: +// * An unpromoted entry (`retire_id == 0`) gets `retire_id = max_other_active_id` (or is erased immediately when +// no other execute is in flight), guaranteeing every concurrent queue already in flight (even one that started +// before or after `note()`) still promotes it at its own later ticket while newer queues ignore it. +// * Any promoted entry with no remaining other active execute having `id <= retire_id` is erased immediately. +class PassiveWriteBackTracker { +public: + static constexpr std::size_t kDefaultMaxRanges = 8192; + static constexpr std::uint64_t kDefaultMaxBytes = std::uint64_t(64) << 20; + + explicit PassiveWriteBackTracker(std::size_t max_ranges = kDefaultMaxRanges, + std::uint64_t max_bytes = kDefaultMaxBytes) + : max_ranges_(max_ranges), max_bytes_(max_bytes) {} + + bool empty() const noexcept { return ranges_.empty(); } + std::size_t size() const noexcept { return ranges_.size(); } + std::uint64_t bytes() const noexcept { return total_bytes_; } + std::size_t active_executes() const noexcept { return active_executes_.size(); } + std::uint64_t current_seq() const noexcept { return next_seq_; } + + std::uint64_t begin_execute() { + const std::uint64_t id = ++next_exec_id_; + active_executes_.push_back(id); + return id; + } + + void end_execute(std::uint64_t id) { + if (!id) return; + for (std::size_t i = 0; i < active_executes_.size(); ++i) { + if (active_executes_[i] == id) { + active_executes_[i] = active_executes_.back(); + active_executes_.pop_back(); + break; + } + } + std::uint64_t min_active_id = UINT64_MAX; + for (const std::uint64_t active_id : active_executes_) { + if (active_id < min_active_id) min_active_id = active_id; + } + for (auto it = ranges_.begin(); it != ranges_.end();) { + if (it->second.retire_id != 0 && it->second.retire_id < min_active_id) { + const std::uint64_t span = it->second.end - it->first; + total_bytes_ = total_bytes_ >= span ? total_bytes_ - span : 0; + it = ranges_.erase(it); + } else { + ++it; + } + } + if (ranges_.empty()) order_.clear(); + } + + void note(std::uint64_t begin, std::uint64_t end) { + if (begin >= end) return; + const std::uint64_t seq = ++next_seq_; + + // Find all strictly overlapping intervals [scan->first, scan->second.end). + // Adjacent intervals (scan->second.end == begin or scan->first == end) are intentionally NOT merged so a new + // note never extends an older interval's lifetime or resets its retire_id. + auto it = ranges_.lower_bound(begin); + if (it != ranges_.begin() && std::prev(it)->second.end > begin) --it; + + // Fast-path exact match: refresh seq and reset retire_id = 0 (unpromoted) without mutating map nodes. + if (it != ranges_.end() && it->first == begin && it->second.end == end) { + it->second.seq = seq; + it->second.retire_id = 0; + order_.emplace_back(seq, begin); + trim_order(); + return; + } + + bool has_left = false; + std::uint64_t left_begin = 0, left_seq = 0, left_retire = 0; + bool has_right = false; + std::uint64_t right_end = 0, right_seq = 0, right_retire = 0; + std::uint64_t removed_bytes = 0; + + for (auto scan = it; scan != ranges_.end() && scan->first < end;) { + if (scan->first < begin) { + has_left = true; + left_begin = scan->first; + left_seq = scan->second.seq; + left_retire = scan->second.retire_id; + } + if (scan->second.end > end) { + has_right = true; + right_end = scan->second.end; + right_seq = scan->second.seq; + right_retire = scan->second.retire_id; + } + removed_bytes += scan->second.end - scan->first; + scan = ranges_.erase(scan); + } + total_bytes_ = total_bytes_ >= removed_bytes ? total_bytes_ - removed_bytes : 0; + + if (has_left) { + ranges_.emplace(left_begin, Entry{begin, left_seq, left_retire}); + total_bytes_ += begin - left_begin; + } + if (has_right) { + ranges_.emplace(end, Entry{right_end, right_seq, right_retire}); + total_bytes_ += right_end - end; + } + + const std::uint64_t new_bytes = end - begin; + evict_to_fit(new_bytes); + + ranges_.emplace(begin, Entry{end, seq, 0}); + total_bytes_ += new_bytes; + order_.emplace_back(seq, begin); + trim_order(); + } + + // Emits entries relevant to `my_exec_id` (`retire_id == 0 || my_exec_id == 0 || my_exec_id <= retire_id`), stamps + // newly promoted entries with `max_other_active_id` when concurrent executes are in flight, and immediately erases + // every entry whose `retire_id` has no remaining other active execute (`min_other_active_id > retire_id`). + // Returns true if at least one range was emitted. + template + bool promote(std::uint64_t my_exec_id, Emit&& emit) { + if (ranges_.empty()) return false; + std::uint64_t min_other_active_id = UINT64_MAX; + std::uint64_t max_other_active_id = 0; + for (const std::uint64_t active_id : active_executes_) { + if (active_id == my_exec_id) continue; + if (active_id < min_other_active_id) min_other_active_id = active_id; + if (active_id > max_other_active_id) max_other_active_id = active_id; + } + bool emitted = false; + for (auto it = ranges_.begin(); it != ranges_.end();) { + Entry& entry = it->second; + if (entry.retire_id == 0) { + emit(it->first, entry.end); + emitted = true; + if (max_other_active_id == 0) { + const std::uint64_t span = entry.end - it->first; + total_bytes_ = total_bytes_ >= span ? total_bytes_ - span : 0; + it = ranges_.erase(it); + continue; + } + entry.retire_id = max_other_active_id; + } else if (my_exec_id == 0 || my_exec_id <= entry.retire_id) { + emit(it->first, entry.end); + emitted = true; + } + if (entry.retire_id != 0 && min_other_active_id > entry.retire_id) { + const std::uint64_t span = entry.end - it->first; + total_bytes_ = total_bytes_ >= span ? total_bytes_ - span : 0; + it = ranges_.erase(it); + } else { + ++it; + } + } + if (ranges_.empty()) order_.clear(); + return emitted; + } + + void clear() { + ranges_.clear(); + order_.clear(); + total_bytes_ = 0; + } + +private: + struct Entry { + std::uint64_t end = 0; + std::uint64_t seq = 0; + std::uint64_t retire_id = 0; // 0 = unpromoted; > 0 = promoted while executes <= retire_id were in flight + }; + + void evict_to_fit(std::uint64_t incoming_bytes) { + while (!ranges_.empty() && + (ranges_.size() >= max_ranges_ || total_bytes_ + incoming_bytes > max_bytes_)) { + auto victim = ranges_.end(); + while (!order_.empty()) { + const auto [seq, key] = order_.front(); + order_.pop_front(); + const auto found = ranges_.find(key); + if (found != ranges_.end() && found->second.seq == seq) { + victim = found; + break; + } + } + if (victim == ranges_.end()) { + // Rare fallback (e.g. split right remainder whose key shifted): evict strictly oldest seq. + victim = ranges_.begin(); + for (auto it = std::next(victim); it != ranges_.end(); ++it) { + if (it->second.seq < victim->second.seq) victim = it; + } + } + const std::uint64_t victim_bytes = victim->second.end - victim->first; + total_bytes_ = total_bytes_ >= victim_bytes ? total_bytes_ - victim_bytes : 0; + ranges_.erase(victim); + } + } + + void trim_order() { + if (order_.size() <= 2 * max_ranges_) return; + while (!order_.empty()) { + const auto [seq, key] = order_.front(); + const auto found = ranges_.find(key); + if (found != ranges_.end() && found->second.seq == seq) break; + order_.pop_front(); + } + } + + std::size_t max_ranges_ = kDefaultMaxRanges; + std::uint64_t max_bytes_ = kDefaultMaxBytes; + std::map ranges_; + std::deque> order_; + std::uint64_t total_bytes_ = 0; + std::uint64_t next_seq_ = 0; + std::uint64_t next_exec_id_ = 0; + std::vector active_executes_; +}; + // Store each texture once, in the smallest aligned power-of-two page containing its CPU range. // A journal interval needs only the overlapping pages at each occupied size. Aliases keep distinct keys. class TitleTextureRangeIndex { @@ -33,7 +288,7 @@ class TitleTextureRangeIndex { void set(Address key, Address first, Address bytes) { erase(key); if (!bytes) return; - const Address last = first + std::min(bytes - 1, UINT64_MAX - first); + const Address last = first + (std::min)(bytes - 1, UINT64_MAX - first); const unsigned shift = unsigned(std::bit_width(first ^ last)); const Address number = page(first, shift); pages_[shift][{number, key}] = {first, last}; @@ -64,7 +319,7 @@ inline void merge_title_writes(TitleWriteRanges& writes) { for (const auto [begin, end] : writes) { if (begin >= end) continue; if (count && begin <= writes[count - 1].second) - writes[count - 1].second = std::max(writes[count - 1].second, end); + writes[count - 1].second = (std::max)(writes[count - 1].second, end); else writes[count++] = {begin, end}; } @@ -89,7 +344,7 @@ template std::vector> title_texture_snapshot( const Registry& textures, std::uint64_t start = 0, std::size_t limit = SIZE_MAX) { std::vector> entries; - const auto count = std::min(textures.size(), limit); + const auto count = (std::min)(textures.size(), limit); entries.reserve(count); for (auto it = textures.lower_bound(start); it != textures.end() && entries.size() < count; ++it) entries.emplace_back(it->first, it->second); @@ -115,8 +370,8 @@ void poll_title_textures(const std::vector& entries, std::uint64_t& curso } } -// Visit the marked textures of a snapshot (mapped by the title, or known stale) under a time limit -// (LEONIDA_TITLE_EVERY_BUDGET_US). Those `urgent` answers true for (a mapped texture never filled yet) are all +// Visit the marked textures of a snapshot (mapped by the title, or known stale) under a time limit. +// Those `urgent` answers true for (a mapped texture never filled yet) are all // visited first, in placement order, whatever the limit. The others are visited // from `cursor`, as poll_title_textures does for the unmarked ones, until `exhausted()` answers true after a visit; // the next pass resumes at the entry after the last one visited, so every marked texture gets its turn however many diff --git a/runtime/src/title_texture_watch.h b/runtime/src/title_texture_watch.h new file mode 100644 index 0000000000..7b21b0dbea --- /dev/null +++ b/runtime/src/title_texture_watch.h @@ -0,0 +1,1054 @@ +#pragma once +// Which title textures may have changed since they were last uploaded (the D3D12 layer's title texture refresh, +// DeviceState / Device::refresh_title_textures in d3d12_vulkan_device.cpp). +// +// A texture the title keeps in its own memory is filled from that memory, and filled again when the title writes it. +// The writes are found where they happen, not by reading the bytes back: each texture's 64 KiB tiles (at its CPU view, +// and at every other address xmem maps the same physical pages at) are cells of the geometry watch +// (title_geometry_watch.h), armed read-only. A write faults once per tile, and the fault handler, xmem's mapping +// changes and a kernel write's opening bump the tile's version and add it to this watch's write queue. collect() +// takes that queue and names the textures over the tiles in it, and nothing else: a texture nobody wrote is not +// looked at. Before a texture is read for its upload, examine() arms its changed tiles again, so a write that lands +// during or after the read faults again and is in the next collect(). +// +// Memory not committed yet is armed like the rest: a page that arrives through xmem bumps the tile's mapping, so the +// tile is in the queue then. A tile whose arming fails stays `unarmed`, and the textures over it are named at every +// collect() until it is armed, but what examine() says decides whether they are read: +// - busy: a kernel write into the tile is in progress (a ReadFile or a DirectStorage request pinned it). Reading now +// would upload a half-written texture, again at every pass until the write ends; the texture is read once the pin +// is gone and the tile could be armed. +// - unwatched: the guard cannot be set (VirtualProtect refused, no write-fault handler): read, and uploaded only when +// the bytes differ from the last upload's. The one fallback, for memory a guard cannot watch. +// +// Complexity: O(dirty tiles + unarmed tiles) per collect() and O(dirty tiles of key) per examine() using hash tables +// and per-pass generation stamps, with an O(1) lock-free may_have_work() fast-path that decouples buffer-only hot +// pages in TitleMirror from waking or scanning watched textures. +// +// Watch is the geometry watch in the runtime and a fake in the tests: +// using Cell = ...; // has std::atomic version, mapping +// Cell* acquire(std::uintptr_t tile); // a reference to the tile's cell +// void release(std::uintptr_t tile); // drops it (and the tile's guard with the last one) +// int arm(std::uintptr_t tile, Cell&); // makes the tile read-only: 1 done, 0 busy, -1 cannot be guarded +// void aliases(std::uintptr_t tile, std::vector&); // the tile's other addresses +// void take_written(std::vector& tiles, bool& overflow); // the queue since the last call +// bool enabled(); // a write-fault handler is installed: arming is allowed +// void hot_tiles(std::vector&); // tiles another owner leaves writable: written at every look +// Optional lock-free hints and batch arming (detected via requires): +// bool has_written() const; // true if take_written() has queued tiles +// std::uint64_t hot_generation() const; // monotonic counter bumped on every hot-set change (preferred) +// std::size_t hot_count() const; // fallback when hot_generation() is not provided +// void arm_batch(const std::uintptr_t* tiles, Cell* const* cells, std::int8_t* results, std::size_t count); +// +// Not thread-safe (except may_have_work()): the caller holds the title texture registry's lock. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace leonida { + +// A texture's bytes in each 64 KiB tile it covers, hashed as of its last read. When some of its tiles were written +// (TitleTextureWatch::examine's `written`), only its bytes in those tiles are hashed again: equal, and the texture is +// unchanged without being read whole. A write to a neighbour in the same tile costs that texture its share of the +// tile, not a read of all of it. The faults that report writes are per tile (the geometry watch's cells reopen a +// whole tile, which the geometry copies sharing them depend on), so this is the finest the watch can tell apart. +struct TilePieces { + static constexpr std::uintptr_t kTile = 0x10000; + std::uintptr_t cpu = 0; + std::uint64_t span = 0; + std::vector hashes; // per tile from cpu's tile on + + // The texture's bytes [cpu, cpu + span) inside `tile`, as an offset from cpu and a length. + static std::pair part(std::uintptr_t cpu, std::uint64_t span, std::uintptr_t tile) { + const std::uintptr_t from = (std::max)(cpu, tile), to = (std::min)(std::uintptr_t(cpu + span), tile + kTile); + return from < to ? std::pair{from - cpu, to - from} + : std::pair{0, 0}; + } + bool valid_for(std::uintptr_t at, std::uint64_t bytes) const { + return cpu == at && span == bytes && !hashes.empty(); + } + // The tiles [at, at + bytes) touches. + static std::size_t tiles(std::uintptr_t at, std::uint64_t bytes) { + return std::size_t((((at + bytes + kTile - 1) & ~(kTile - 1)) - (at & ~(kTile - 1))) / kTile); + } + // For a texture at `at`: one hash a tile, to be set by part (set_part, from any thread for distinct parts). + void reset(std::uintptr_t at, std::uint64_t bytes) { + cpu = at; + span = bytes; + hashes.assign(tiles(at, bytes), 0); + } + // The texture's hash: its parts' hashes (and its size) mixed in order, so a texture read in parts needs no second + // pass over its bytes. + std::uint64_t combined() const { + std::uint64_t h = 1469598103934665603ull ^ span; + for (const std::uint64_t part : hashes) { + h = (h ^ part) * 1099511628211ull; + h ^= h >> 29; + } + return h; + } + // From a whole copy of the texture's bytes: hash(pointer, length) of each tile's part. + template + void compute(std::uintptr_t at, std::uint64_t bytes, const std::uint8_t* copy, Hash&& hash) { + cpu = at; + span = bytes; + hashes.clear(); + for (std::uintptr_t tile = at & ~(kTile - 1); tile < at + bytes; tile += kTile) { + const auto [offset, length] = part(at, bytes, tile); + hashes.push_back(hash(copy + offset, length)); + } + } + // Whether the texture's parts in `written` hash as before: hash(title address, length) reads them where they are. + // False when a part differs, cannot be read (hash returns nullopt) or is not known. + template + bool unchanged(const std::vector& written, Hash&& hash) const { + for (const std::uintptr_t tile : written) { + const std::size_t i = (tile - (cpu & ~(kTile - 1))) / kTile; + if (tile < (cpu & ~(kTile - 1)) || i >= hashes.size()) return false; + const auto [offset, length] = part(cpu, span, tile); + const auto h = hash(cpu + offset, length); + if (!h || *h != hashes[i]) return false; + } + return true; + } +}; + +template +class TitleTextureWatch { +public: + static constexpr std::uintptr_t kTile = 0x10000; + using Cell = typename Watch::Cell; + + explicit TitleTextureWatch(Watch& watch) : watch_(watch) {} + ~TitleTextureWatch() { + for (auto& [address, tile] : tiles_) drop(address, tile); + } + TitleTextureWatch(const TitleTextureWatch&) = delete; + TitleTextureWatch& operator=(const TitleTextureWatch&) = delete; + + struct Stats { + std::uint64_t collects = 0, named = 0, unarmed_named = 0, arms = 0, non_hot_arms = 0, arm_failures = 0, + arm_busy = 0, written_tiles = 0, overflows = 0, hot_skips = 0; + }; + const Stats& stats() const { return stats_; } + std::size_t textures() const { return textures_.size(); } + std::size_t tiles() const { return tiles_.size(); } + std::size_t unarmed() const { return unarmed_list_.size(); } + std::size_t hot_overlap() const { return active_hot_tiles_.size(); } + + // O(1) lock-free fast-path check: false guarantees collect() would emit nothing (no pending dirty/unarmed/noted + // work, no queued write notifications, and no watched tiles overlapping hot mirror pages). + bool may_have_work() const noexcept { + if (has_pending_.load(std::memory_order_acquire)) return true; + if (hot_overlap_.load(std::memory_order_acquire) != 0) return true; + if constexpr (requires(const Watch& w) { w.has_written(); }) { + if (watch_.has_written()) return true; + } else { + return true; + } + if constexpr (has_hot_stamp()) { + if (hot_stamp() != last_hot_stamp_atomic_.load(std::memory_order_acquire)) return true; + } + return false; + } + + // Recomputes the lock-free fast-path hint after examine() finishes arming tiles for the pass. + void update_idle_hint() noexcept { + const bool pending = !unarmed_list_.empty() || !pending_dirty_keys_.empty() || + !pending_noted_tiles_.empty() || hot_sync_needed_; + hot_overlap_.store(active_hot_tiles_.size(), std::memory_order_release); + last_hot_stamp_atomic_.store(last_hot_stamp_, std::memory_order_release); + has_pending_.store(pending, std::memory_order_release); + } + + // The texture `key` reads [cpu, cpu + bytes) from now on (a new texture, or one whose range changed): it is named + // by the next collect() whatever its tiles say. Tracking it again over the same tiles changes nothing (its tiles stay + // armed and it is not named: the title's Map, a view, a layout found for the same bytes are not writes; touch() + // names it when its bytes must be read again); over other tiles it replaces its range. + void track(Key key, std::uintptr_t cpu, std::uint64_t bytes) { + const std::uintptr_t first = cpu & ~(kTile - 1); + const std::uintptr_t last = (cpu + bytes + kTile - 1) & ~(kTile - 1); + if (const auto it = textures_.find(key); it != textures_.end() && bytes && + it->second.first == first && it->second.last == last) + return; + untrack(key); + if (!bytes) return; + Texture& t = textures_[key]; + t.first = first; + t.last = last; + bool added_tile = false; + for (std::uintptr_t a = t.first; a < t.last; a += kTile) { + auto [it, fresh] = tiles_.try_emplace(a); + Tile& tile = it->second; + if (fresh) { + tile.primary = watch_.acquire(a); + add_unarmed(a, tile); // not armed for anyone yet + add_region_tile(a, tile); + added_tile = true; + } + tile.textures.emplace_back(key, &t); + } + if (added_tile) { + hot_sync_needed_ = true; + } + pending_dirty_keys_.push_back(key); + has_pending_.store(true, std::memory_order_release); + } + + // The texture is gone, or no longer filled from memory: its tiles are released when no other texture reads them. + void untrack(Key key) { + const auto it = textures_.find(key); + if (it == textures_.end()) return; + for (std::uintptr_t a = it->second.first; a < it->second.last; a += kTile) { + const auto t = tiles_.find(a); + if (t == tiles_.end()) continue; + auto& vec = t->second.textures; + for (std::size_t idx = 0; idx < vec.size(); ++idx) { + if (vec[idx].first == key) { + vec[idx] = vec.back(); + vec.pop_back(); + break; + } + } + if (vec.empty()) { + drop(a, t->second); + remove_unarmed(t->second); + if (t->second.hot_index != kNoIndex) remove_active_hot(t->second); + remove_region_tile(a, t->second); + tiles_.erase(t); + } + } + textures_.erase(it); + hot_overlap_.store(active_hot_tiles_.size(), std::memory_order_release); + } + + bool tracked(Key key) const { return textures_.count(key) != 0; } + + // Something other than a fault says [from, to) changed (a write noted by its writer, a mapping change seen by + // the caller): the textures over it are named by the next collect(). Does NOT force watch_.arm() on already-armed + // unchanged tiles unless `rearm` is true (e.g. a mapped texture whose pages may be committed without xmem). + void note_changed(std::uintptr_t from, std::uintptr_t to, bool rearm = false) { + if (from >= to || tiles_.empty()) return; + for_each_tile_in(from, to, [&](std::uintptr_t addr, Tile& tile) { note_tile_changed(addr, tile, rearm); }); + if (!pending_noted_tiles_.empty()) has_pending_.store(true, std::memory_order_release); + } + + // The texture is named by the next collect() (its last fill did not complete: no image backing yet, a failed + // upload, memory not readable yet). + void touch(Key key) { + if (textures_.count(key)) { + pending_dirty_keys_.push_back(key); + has_pending_.store(true, std::memory_order_release); + } + } + + // Each texture over [from, to), once. + template + void for_each_over(std::uintptr_t from, std::uintptr_t to, F&& f) { + if (from >= to || tiles_.empty()) return; + const std::uint64_t stamp = ++over_gen_; + for_each_tile_in(from, to, [&](std::uintptr_t, Tile& tile) { + for (const auto& [k, tex] : tile.textures) { + if (tex->over_gen != stamp) { + tex->over_gen = stamp; + f(k); + } + } + }); + } + + // Combines note_changed(from, to, rearm) and for_each_over(from, to, f) in a single pass over overlapping tiles. + template + void note_changed_and_for_each(std::uintptr_t from, std::uintptr_t to, F&& f, bool rearm = false) { + if (from >= to || tiles_.empty()) return; + const std::uint64_t stamp = ++over_gen_; + for_each_tile_in(from, to, [&](std::uintptr_t addr, Tile& tile) { + note_tile_changed(addr, tile, rearm); + for (const auto& [k, tex] : tile.textures) { + if (tex->over_gen != stamp) { + tex->over_gen = stamp; + f(k); + } + } + }); + if (!pending_noted_tiles_.empty()) has_pending_.store(true, std::memory_order_release); + } + + // The textures that may have changed since their last examine(), each once, in key order. + // Cost: strictly O(dirty tiles + unarmed tiles + overlapping hot tiles), never O(total watched textures/tiles). + template + void collect(F&& f) { + ++stats_.collects; + const std::uint64_t gen = ++pass_gen_; + named_.clear(); + + // 1. Tiles noted via note_changed() since the last collect(). Keep tile.stale as-is so arm() skips redundant + // watch_.arm() syscalls on already-armed tiles whose cell version and mapping did not move. + for (const std::uintptr_t a : pending_noted_tiles_) { + const auto it = tiles_.find(a); + if (it == tiles_.end()) continue; + it->second.pending_note = false; + mark_tile_pass(a, it->second, gen, false, false); + } + pending_noted_tiles_.clear(); + + // 2. Keys dirtied via track() or touch() since the last collect(). + for (const Key k : pending_dirty_keys_) { + if (const auto it = textures_.find(k); it != textures_.end()) mark_key_pass(k, it->second, gen, false); + } + pending_dirty_keys_.clear(); + + // 3. Tiles from the write-fault / kernel-write / remap queue. + bool overflow = false; + watch_.take_written(written_, overflow); + stats_.written_tiles += written_.size(); + if (overflow) { + ++stats_.overflows; + for (auto& [address, tile] : tiles_) changed(address, tile, gen); + } else { + for (const std::uintptr_t a : written_) { + if (const auto it = tiles_.find(a); it != tiles_.end()) changed(a, it->second, gen); + if (!by_peer_.empty()) { + if (const auto peer = by_peer_.find(a); peer != by_peer_.end()) + for (const std::uintptr_t owner : peer->second) + if (const auto it = tiles_.find(owner); it != tiles_.end()) changed(owner, it->second, gen); + } + } + } + + // 4. Tiles another owner keeps writable (TitleMirror hot pages): decouple buffer-only hot pages so + // non-overlapping hot pages neither lock geometry_writes on quiet passes nor scan all watched tiles. + // When hot_generation() is provided (monotonic counter bumped on every hot-set mutation), unchanged + // generations reuse active_hot_tiles_ directly without calling watch_.hot_tiles() or locking. + bool need_hot_poll = true; + std::uint64_t cur_hot_stamp = 0; + if constexpr (has_hot_generation()) { + cur_hot_stamp = hot_stamp(); + need_hot_poll = cur_hot_stamp != last_hot_stamp_ || hot_sync_needed_; + if (!need_hot_poll) ++stats_.hot_skips; + } else if constexpr (has_hot_stamp()) { + cur_hot_stamp = hot_stamp(); + need_hot_poll = cur_hot_stamp != last_hot_stamp_ || !written_.empty() || overflow || hot_sync_needed_ || + !active_hot_tiles_.empty(); + if (!need_hot_poll) ++stats_.hot_skips; + } + if (need_hot_poll) { + clear_active_hot(); + watch_.hot_tiles(hot_); + for (const std::uintptr_t a : hot_) { + if (const auto it = tiles_.find(a); it != tiles_.end()) { + it->second.hot_gen = gen; + add_active_hot(a, it->second); + mark_tile_pass(a, it->second, gen, false); + } + if (!by_peer_.empty()) { + if (const auto peer = by_peer_.find(a); peer != by_peer_.end()) { + for (const std::uintptr_t owner : peer->second) { + if (const auto it = tiles_.find(owner); it != tiles_.end()) { + it->second.hot_gen = gen; + add_active_hot(owner, it->second); + mark_tile_pass(owner, it->second, gen, false); + } + } + } + } + } + last_hot_stamp_ = cur_hot_stamp; + hot_sync_needed_ = false; + } else if (!active_hot_tiles_.empty()) { + for (const auto& [a, tp] : active_hot_tiles_) { + tp->hot_gen = gen; + mark_tile_pass(a, *tp, gen, false); + } + } + + // 5. Tiles not armed: whatever their version says, a write there need not have faulted. + for (const auto& [a, tp] : unarmed_list_) { + tp->stale = true; + mark_tile_pass(a, *tp, gen, true); + } + + std::sort(named_.begin(), named_.end()); + stats_.named += named_.size(); + for (const Key k : named_) f(k); + // Keep fast-path hint accurate after callback (e.g. if callback examined/armed tiles). + update_idle_hint(); + } + + // What examine() found: every tile armed (read it now; it is known unchanged afterwards until a tile is written), + // a kernel write in progress over it (do not read it yet), or a tile that cannot be guarded (read it every time). + enum class Look { armed, busy, unwatched }; + + // Before the texture's bytes are read for an upload: its tiles that changed (or were never armed) are armed + // again, so a write from now on is seen by the next collect(). Tiles not armed are tried at the next collect(). + // `written` (optional) gets those tiles: the only ones whose bytes can differ from the texture's last read. + // Cost: O(dirty tiles of key), not O(total tiles of key). + Look examine(Key key, std::vector* written = nullptr) { + if (written) written->clear(); + const auto it = textures_.find(key); + if (it == textures_.end()) return Look::unwatched; + Texture& tex = it->second; + Look look = Look::armed; + const std::uint64_t gen = pass_gen_; + if (tex.dirty_gen == gen) { + if (tex.dirty_tiles_gen == gen) { + if (tex.dirty_tiles.size() > 1) std::sort(tex.dirty_tiles.begin(), tex.dirty_tiles.end()); + for (const std::uintptr_t a : tex.dirty_tiles) { + const auto t = tiles_.find(a); + if (t == tiles_.end()) continue; + if (written && (t->second.pass_written_gen == gen || t->second.stale || t->second.unarmed_index != kNoIndex)) + written->push_back(a); + const int armed = arm(a, t->second); + if (!armed) look = Look::busy; + else if (armed < 0 && look == Look::armed) look = Look::unwatched; + } + } + return look; + } + // Direct examine() outside collect(): scan the texture's tiles. + for (std::uintptr_t a = tex.first; a < tex.last; a += kTile) { + const auto t = tiles_.find(a); + if (t == tiles_.end()) continue; + if (written && (t->second.pass_written_gen == gen || t->second.stale || t->second.unarmed_index != kNoIndex)) + written->push_back(a); + const int armed = arm(a, t->second); + if (!armed) look = Look::busy; + else if (armed < 0 && look == Look::armed) look = Look::unwatched; + } + return look; + } + + struct BatchExamine { + Look look = Look::armed; + std::uint64_t max_version = 0; + std::vector written; + }; + + // Batched examine() over all keys of a pass: deduplicates shared tiles and alias peers across keys, sorts all + // tiles needing arming by address, and issues one watch_.arm_batch() call (coalescing pin checks, geometry-watch + // lock holds, and contiguous VirtualQuery/VirtualProtect runs). Falls back to watch_.arm() when the Watch type + // does not provide arm_batch(). Preserves exact per-key Look (busy > unwatched > armed) and written-tile semantics. + void examine_batch(const std::vector& keys, std::vector& out) { + const std::size_t n = keys.size(); + out.resize(n); + if (!n) return; + const std::uint64_t gen = pass_gen_; + const std::uint64_t bgen = ++batch_arm_gen_; + const bool watch_on = watch_.enabled(); + + batch_tiles_.clear(); + batch_reqs_.clear(); + batch_tile_refs_.clear(); + bool any_peer_sync = false; + + auto queue_tile = [&](std::size_t key_idx, std::uintptr_t a, Tile& tile) { + if (tile.pass_written_gen == gen || tile.stale || tile.unarmed_index != kNoIndex) + out[key_idx].written.push_back(a); + if (!watch_on) { + add_unarmed(a, tile); + tile.stale = true; + if (out[key_idx].look == Look::armed) out[key_idx].look = Look::unwatched; + out[key_idx].max_version = UINT64_MAX; + return; + } + if (tile.batch_arm_gen == bgen) { + if (tile.batch_arm_slot != kNoIndex) + batch_tile_refs_.emplace_back(key_idx, tile.batch_arm_slot); + else + out[key_idx].max_version = (std::max)(out[key_idx].max_version, tile.batch_arm_version); + return; + } + const std::uint64_t mapping = tile.primary->mapping.load(std::memory_order_acquire); + if (!tile.stale && tile.unarmed_index == kNoIndex && tile.hot_index == kNoIndex && + tile.hot_gen != pass_gen_ && mapping == tile.mapping) { + std::uint64_t version = tile.primary->version.load(std::memory_order_acquire); + for (const auto& [peer, cell] : tile.peers) + version = (std::max)(version, cell->version.load(std::memory_order_acquire)); + if (version == tile.version) { + tile.batch_arm_gen = bgen; + tile.batch_arm_slot = kNoIndex; + tile.batch_arm_version = version; + out[key_idx].max_version = (std::max)(out[key_idx].max_version, version); + return; + } + } + const bool needs_peer_sync = (mapping != tile.mapping); + if (needs_peer_sync) any_peer_sync = true; + const std::uint32_t slot = static_cast(batch_tiles_.size()); + tile.batch_arm_gen = bgen; + tile.batch_arm_slot = slot; + tile.batch_arm_version = 0; + batch_tiles_.push_back({a, &tile, 0, mapping, false, needs_peer_sync, 1}); + batch_tile_refs_.emplace_back(key_idx, slot); + }; + + for (std::size_t i = 0; i < n; ++i) { + out[i].written.clear(); + out[i].look = Look::armed; + out[i].max_version = 0; + const auto it = textures_.find(keys[i]); + if (it == textures_.end()) { + out[i].look = Look::unwatched; + out[i].max_version = UINT64_MAX; + continue; + } + Texture& tex = it->second; + if (tex.dirty_gen == gen) { + if (tex.dirty_tiles_gen == gen) { + if (tex.dirty_tiles.size() > 1) std::sort(tex.dirty_tiles.begin(), tex.dirty_tiles.end()); + for (const std::uintptr_t a : tex.dirty_tiles) { + if (const auto t = tiles_.find(a); t != tiles_.end()) queue_tile(i, a, t->second); + } + } else if (!watch_on) { + out[i].look = Look::unwatched; + out[i].max_version = UINT64_MAX; + } else { + for (std::uintptr_t a = tex.first; a < tex.last; a += kTile) { + if (const auto t = tiles_.find(a); t != tiles_.end()) { + const Tile& tile = t->second; + std::uint64_t ver = tile.primary->version.load(std::memory_order_acquire); + for (const auto& [peer, cell] : tile.peers) + ver = (std::max)(ver, cell->version.load(std::memory_order_acquire)); + out[i].max_version = (std::max)(out[i].max_version, ver); + } + } + } + } else { + for (std::uintptr_t a = tex.first; a < tex.last; a += kTile) { + if (const auto t = tiles_.find(a); t != tiles_.end()) queue_tile(i, a, t->second); + } + } + } + + if (batch_tiles_.empty()) return; + + if (any_peer_sync) sync_batch_tile_peers(); + + for (std::size_t slot = 0; slot < batch_tiles_.size(); ++slot) { + BatchTile& bt = batch_tiles_[slot]; + Tile& tile = *bt.tile; + std::uint64_t version = tile.primary->version.load(std::memory_order_acquire); + for (const auto& [peer, cell] : tile.peers) + version = (std::max)(version, cell->version.load(std::memory_order_acquire)); + bt.version = version; + bt.pure_hot_recheck = !bt.needs_peer_sync && !tile.stale && tile.unarmed_index == kNoIndex && + tile.hot_gen == pass_gen_ && version == tile.version; + tile.batch_arm_version = version; + const auto slot_u32 = static_cast(slot); + batch_reqs_.push_back({bt.address, tile.primary, slot_u32}); + for (const auto& [peer, cell] : tile.peers) batch_reqs_.push_back({peer, cell, slot_u32}); + } + + if (batch_reqs_.size() > 1) { + std::sort(batch_reqs_.begin(), batch_reqs_.end(), + [](const BatchArmReq& lhs, const BatchArmReq& rhs) { return lhs.va < rhs.va; }); + } + + batch_arm_vas_.clear(); + batch_arm_cells_.clear(); + batch_req_unique_.resize(batch_reqs_.size()); + for (std::size_t r = 0; r < batch_reqs_.size(); ++r) { + if (r > 0 && batch_reqs_[r].va == batch_reqs_[r - 1].va) { + batch_req_unique_[r] = batch_arm_vas_.size() - 1; + } else { + batch_req_unique_[r] = batch_arm_vas_.size(); + batch_arm_vas_.push_back(batch_reqs_[r].va); + batch_arm_cells_.push_back(batch_reqs_[r].cell); + } + } + + const std::size_t unique_n = batch_arm_vas_.size(); + batch_arm_results_.assign(unique_n, -1); + if constexpr (requires(Watch& w, const std::uintptr_t* vas, Cell* const* cells, std::int8_t* res, + std::size_t count) { w.arm_batch(vas, cells, res, count); }) { + watch_.arm_batch(batch_arm_vas_.data(), batch_arm_cells_.data(), batch_arm_results_.data(), unique_n); + } else { + for (std::size_t u = 0; u < unique_n; ++u) { + const int r = watch_.arm(batch_arm_vas_[u], *batch_arm_cells_[u]); + batch_arm_results_[u] = static_cast(r > 0 ? 1 : (r == 0 ? 0 : -1)); + } + } + + for (std::size_t r = 0; r < batch_reqs_.size(); ++r) { + const int res = batch_arm_results_[batch_req_unique_[r]]; + int& tile_res = batch_tiles_[batch_reqs_[r].slot].result; + if (res == 0) tile_res = 0; + else if (res < 0 && tile_res > 0) tile_res = -1; + } + + for (BatchTile& bt : batch_tiles_) { + ++stats_.arms; + if (!bt.pure_hot_recheck || bt.result <= 0) ++stats_.non_hot_arms; + if (bt.result <= 0) { + ++(bt.result ? stats_.arm_failures : stats_.arm_busy); + add_unarmed(bt.address, *bt.tile); + bt.tile->stale = true; + } else { + bt.tile->version = bt.version; + bt.tile->stale = false; + remove_unarmed(*bt.tile); + std::uint64_t post_ver = bt.tile->primary->version.load(std::memory_order_acquire); + for (const auto& [peer, cell] : bt.tile->peers) + post_ver = (std::max)(post_ver, cell->version.load(std::memory_order_acquire)); + bt.version = (std::max)(bt.version, post_ver); + } + } + + for (const auto& [key_idx, slot] : batch_tile_refs_) { + const BatchTile& bt = batch_tiles_[slot]; + const int armed = bt.result; + Look& look = out[key_idx].look; + if (!armed) look = Look::busy; + else if (armed < 0 && look == Look::armed) look = Look::unwatched; + out[key_idx].max_version = (std::max)(out[key_idx].max_version, bt.version); + } + } + +private: + static constexpr std::uint32_t kNoIndex = ~std::uint32_t(0); + static constexpr std::uintptr_t kRegion = std::uintptr_t(16) << 20; // 16 MiB buckets (<= 256 tiles each) + + struct Texture; + struct Tile { + Cell* primary = nullptr; + std::uint64_t version = 0, mapping = 0; // as last armed; mapping 0: peers not looked up yet + std::vector> peers; + std::vector> textures; + std::uint64_t pass_written_gen = 0; + std::uint64_t hot_gen = 0; + std::uint64_t batch_arm_gen = 0; + std::uint64_t batch_arm_version = 0; + std::uint32_t batch_arm_slot = kNoIndex; + std::uint32_t unarmed_index = kNoIndex; + std::uint32_t hot_index = kNoIndex; + std::uint32_t region_index = kNoIndex; + bool stale = true; // guard was dropped or never armed since last arm + bool pending_note = false; + }; + struct Texture { + std::uintptr_t first = 0, last = 0; // its tiles, [first, last) + std::uint64_t dirty_gen = 0; + std::uint64_t dirty_tiles_gen = 0; + std::uint64_t over_gen = 0; + std::vector dirty_tiles; + }; + struct BatchTile { + std::uintptr_t address = 0; + Tile* tile = nullptr; + std::uint64_t version = 0; + std::uint64_t mapping = 0; + bool pure_hot_recheck = false; + bool needs_peer_sync = false; + int result = 1; + }; + struct BatchArmReq { + std::uintptr_t va = 0; + Cell* cell = nullptr; + std::uint32_t slot = 0; + }; + + void add_unarmed(std::uintptr_t address, Tile& tile) { + if (tile.unarmed_index != kNoIndex) return; + tile.unarmed_index = static_cast(unarmed_list_.size()); + unarmed_list_.emplace_back(address, &tile); + } + void remove_unarmed(Tile& tile) { + if (tile.unarmed_index == kNoIndex) return; + const std::uint32_t idx = tile.unarmed_index; + const auto last = unarmed_list_.back(); + unarmed_list_[idx] = last; + if (idx + 1 < unarmed_list_.size()) last.second->unarmed_index = idx; + unarmed_list_.pop_back(); + tile.unarmed_index = kNoIndex; + } + + void add_active_hot(std::uintptr_t address, Tile& tile) { + if (tile.hot_index != kNoIndex) return; + tile.hot_index = static_cast(active_hot_tiles_.size()); + active_hot_tiles_.emplace_back(address, &tile); + } + void remove_active_hot(Tile& tile) { + if (tile.hot_index == kNoIndex) return; + const std::uint32_t idx = tile.hot_index; + const auto last = active_hot_tiles_.back(); + active_hot_tiles_[idx] = last; + if (idx + 1 < active_hot_tiles_.size()) last.second->hot_index = idx; + active_hot_tiles_.pop_back(); + tile.hot_index = kNoIndex; + } + void clear_active_hot() { + for (const auto& [a, tp] : active_hot_tiles_) tp->hot_index = kNoIndex; + active_hot_tiles_.clear(); + } + + void add_region_tile(std::uintptr_t address, Tile& tile) { + if (tile.region_index != kNoIndex) return; + auto& vec = region_tiles_[address & ~(kRegion - 1)]; + tile.region_index = static_cast(vec.size()); + vec.emplace_back(address, &tile); + } + void remove_region_tile(std::uintptr_t address, Tile& tile) { + if (tile.region_index == kNoIndex) return; + const std::uintptr_t region = address & ~(kRegion - 1); + const auto rit = region_tiles_.find(region); + if (rit != region_tiles_.end()) { + auto& vec = rit->second; + const std::uint32_t idx = tile.region_index; + const auto last = vec.back(); + vec[idx] = last; + if (idx + 1 < vec.size()) last.second->region_index = idx; + vec.pop_back(); + if (vec.empty()) region_tiles_.erase(rit); + } + tile.region_index = kNoIndex; + } + + void note_tile_changed(std::uintptr_t addr, Tile& tile, bool rearm) { + if (rearm) tile.stale = true; + if (!tile.pending_note) { + tile.pending_note = true; + pending_noted_tiles_.push_back(addr); + } + } + + template + void for_each_tile_in(std::uintptr_t from, std::uintptr_t to, F&& f) { + if (from >= to || tiles_.empty()) return; + if (from == 0 && to == UINTPTR_MAX) { + for (auto& [addr, tile] : tiles_) f(addr, tile); + return; + } + const std::uintptr_t first = from & ~(kTile - 1); + const std::uintptr_t span = to > first ? to - first : 0; + if (span <= 8u * kTile) { + for (std::uintptr_t a = first; a < to;) { + if (const auto it = tiles_.find(a); it != tiles_.end()) f(a, it->second); + if (to - a <= kTile) break; + a += kTile; + } + return; + } + const std::uintptr_t first_region = first & ~(kRegion - 1); + for (auto it = region_tiles_.lower_bound(first_region); it != region_tiles_.end() && it->first < to; ++it) { + const std::uintptr_t region_start = it->first; + const bool full_region = region_start >= first && (to - region_start >= kRegion); + for (const auto& [addr, tp] : it->second) { + if (full_region || (addr >= first && addr < to)) f(addr, *tp); + } + } + } + + void drop(std::uintptr_t address, Tile& tile) { + if constexpr (requires(Watch& w, const std::pair* items, std::size_t n) { + w.release_batch(items, n); + }) { + if (!tile.peers.empty()) { + peer_rel_items_.clear(); + peer_rel_items_.reserve(tile.peers.size() + (tile.primary ? 1 : 0)); + for (const auto& [peer, cell] : tile.peers) { + unlink_peer(peer, address); + peer_rel_items_.emplace_back(peer, false); + } + tile.peers.clear(); + if (tile.primary) { + peer_rel_items_.emplace_back(address, false); + tile.primary = nullptr; + } + watch_.release_batch(peer_rel_items_.data(), peer_rel_items_.size()); + return; + } + } + for (const auto& [peer, cell] : tile.peers) { + unlink_peer(peer, address); + watch_.release(peer); + } + tile.peers.clear(); + if (tile.primary) watch_.release(address); + tile.primary = nullptr; + } + void unlink_peer(std::uintptr_t peer, std::uintptr_t owner) { + const auto it = by_peer_.find(peer); + if (it == by_peer_.end()) return; + std::erase(it->second, owner); + if (it->second.empty()) by_peer_.erase(it); + } + + void mark_key_pass(Key k, Texture& tex, std::uint64_t gen, bool from_unarmed) { + if (tex.dirty_gen != gen) { + tex.dirty_gen = gen; + named_.push_back(k); + if (from_unarmed) ++stats_.unarmed_named; + } + } + + void mark_tile_pass(std::uintptr_t address, Tile& tile, std::uint64_t gen, bool from_unarmed, + bool set_stale = true) { + if (set_stale) tile.stale = true; + if (tile.pass_written_gen == gen) return; // already marked every texture on this tile this pass + tile.pass_written_gen = gen; + for (const auto& [k, tex] : tile.textures) { + mark_key_pass(k, *tex, gen, from_unarmed); + if (tex->dirty_tiles_gen != gen) { + tex->dirty_tiles_gen = gen; + tex->dirty_tiles.clear(); + } + tex->dirty_tiles.push_back(address); + } + } + + // A tile the queue named: changed when its version (or a peer's) moved since it was armed. + void changed(std::uintptr_t address, Tile& tile, std::uint64_t gen) { + if (tile.stale) { // known already + mark_tile_pass(address, tile, gen, false); + return; + } + std::uint64_t version = tile.primary->version.load(std::memory_order_acquire); + for (const auto& [peer, cell] : tile.peers) + version = (std::max)(version, cell->version.load(std::memory_order_acquire)); + if (version != tile.version || tile.primary->mapping.load(std::memory_order_acquire) != tile.mapping) { + mark_tile_pass(address, tile, gen, false); + add_unarmed(address, tile); // until examine() arms it again + } + } + + void sync_tile_peers(std::uintptr_t address, Tile& tile, std::uint64_t mapping) { + aliases_.clear(); + watch_.aliases(address, aliases_); + std::erase(aliases_, address); + if (aliases_.size() > 1) { + std::sort(aliases_.begin(), aliases_.end()); + aliases_.erase(std::unique(aliases_.begin(), aliases_.end()), aliases_.end()); + } + bool same_peers = aliases_.size() == tile.peers.size(); + if (same_peers) { + for (std::size_t k = 0; k < aliases_.size(); ++k) { + if (tile.peers[k].first != aliases_[k]) { + same_peers = false; + break; + } + } + } + if (!same_peers) { + auto old = std::move(tile.peers); + tile.peers.clear(); + tile.peers.reserve(aliases_.size()); + if (!aliases_.empty()) { + if constexpr (requires(Watch& w, const std::uintptr_t* vas, Cell** out, std::size_t n) { + w.acquire_batch(vas, out, n); + }) { + peer_acq_cells_.resize(aliases_.size()); + watch_.acquire_batch(aliases_.data(), peer_acq_cells_.data(), aliases_.size()); + for (std::size_t k = 0; k < aliases_.size(); ++k) { + const std::uintptr_t peer = aliases_[k]; + tile.peers.emplace_back(peer, peer_acq_cells_[k]); + by_peer_[peer].push_back(address); + } + } else { + for (const std::uintptr_t peer : aliases_) { + tile.peers.emplace_back(peer, watch_.acquire(peer)); + by_peer_[peer].push_back(address); + } + } + hot_sync_needed_ = true; + } + if (!old.empty()) { + for (const auto& [peer, cell] : old) unlink_peer(peer, address); + if constexpr (requires(Watch& w, const std::pair* items, std::size_t n) { + w.release_batch(items, n); + }) { + peer_rel_items_.clear(); + peer_rel_items_.reserve(old.size()); + for (const auto& [peer, cell] : old) peer_rel_items_.emplace_back(peer, false); + watch_.release_batch(peer_rel_items_.data(), peer_rel_items_.size()); + } else { + for (const auto& [peer, cell] : old) watch_.release(peer); + } + } + } + tile.mapping = mapping; + } + + // Batches peer alias syncs across all remapped tiles in examine_batch() into at most ONE acquire_batch() + ONE + // release_batch() call (acquiring new peers before releasing old peers so surviving peers never drop refcount 0). + void sync_batch_tile_peers() { + peer_acq_vas_.clear(); + peer_acq_spans_.clear(); + peer_rel_items_.clear(); + for (std::size_t slot = 0; slot < batch_tiles_.size(); ++slot) { + BatchTile& bt = batch_tiles_[slot]; + if (!bt.needs_peer_sync) continue; + Tile& tile = *bt.tile; + const std::uintptr_t address = bt.address; + aliases_.clear(); + watch_.aliases(address, aliases_); + std::erase(aliases_, address); + if (aliases_.size() > 1) { + std::sort(aliases_.begin(), aliases_.end()); + aliases_.erase(std::unique(aliases_.begin(), aliases_.end()), aliases_.end()); + } + bool same_peers = aliases_.size() == tile.peers.size(); + if (same_peers) { + for (std::size_t k = 0; k < aliases_.size(); ++k) { + if (tile.peers[k].first != aliases_[k]) { + same_peers = false; + break; + } + } + } + if (!same_peers) { + for (const auto& [peer, cell] : tile.peers) { + unlink_peer(peer, address); + peer_rel_items_.emplace_back(peer, false); + } + tile.peers.clear(); + if (!aliases_.empty()) { + const std::size_t begin = peer_acq_vas_.size(); + peer_acq_vas_.insert(peer_acq_vas_.end(), aliases_.begin(), aliases_.end()); + peer_acq_spans_.push_back({slot, begin, aliases_.size()}); + hot_sync_needed_ = true; + } + } + tile.mapping = bt.mapping; + } + if (!peer_acq_vas_.empty()) { + peer_acq_cells_.resize(peer_acq_vas_.size()); + if constexpr (requires(Watch& w, const std::uintptr_t* vas, Cell** out, std::size_t n) { + w.acquire_batch(vas, out, n); + }) { + watch_.acquire_batch(peer_acq_vas_.data(), peer_acq_cells_.data(), peer_acq_vas_.size()); + } else { + for (std::size_t k = 0; k < peer_acq_vas_.size(); ++k) + peer_acq_cells_[k] = watch_.acquire(peer_acq_vas_[k]); + } + for (const auto& span : peer_acq_spans_) { + BatchTile& bt = batch_tiles_[span.slot]; + Tile& tile = *bt.tile; + tile.peers.reserve(span.count); + for (std::size_t k = 0; k < span.count; ++k) { + const std::uintptr_t peer = peer_acq_vas_[span.begin + k]; + tile.peers.emplace_back(peer, peer_acq_cells_[span.begin + k]); + by_peer_[peer].push_back(bt.address); + } + } + } + if (!peer_rel_items_.empty()) { + if constexpr (requires(Watch& w, const std::pair* items, std::size_t n) { + w.release_batch(items, n); + }) { + watch_.release_batch(peer_rel_items_.data(), peer_rel_items_.size()); + } else { + for (const auto& [peer, was_hot] : peer_rel_items_) watch_.release(peer); + } + } + } + + int arm(std::uintptr_t address, Tile& tile) { + if (!watch_.enabled()) { + add_unarmed(address, tile); + tile.stale = true; + return -1; + } + const std::uint64_t mapping = tile.primary->mapping.load(std::memory_order_acquire); + if (!tile.stale && tile.unarmed_index == kNoIndex && tile.hot_index == kNoIndex && + tile.hot_gen != pass_gen_ && mapping == tile.mapping) { + std::uint64_t version = tile.primary->version.load(std::memory_order_acquire); + for (const auto& [peer, cell] : tile.peers) + version = (std::max)(version, cell->version.load(std::memory_order_acquire)); + if (version == tile.version) return 1; + } + // The tile's other addresses follow its mapping: looked up again when xmem remapped it. + if (mapping != tile.mapping) { + sync_tile_peers(address, tile, mapping); + } + // The version is read before arming: a write between the two moves it, and the next collect() sees that. + // Always delegate through watch_.arm() on hot/stale/unarmed/moved tiles so kernel_writes pin checks + // (Look::busy) still run and a concurrent set_hot(false) cannot leave a writable page silently marked armed. + // Distinguish a second texture's pass-through pin-check on an already-checked hot tile (whose version/mapping + // did not move since the first texture checked it this pass) via `non_hot_arms` so shared hot tiles sync once + // per pass instead of re-copying 64 KiB per texture. + std::uint64_t version = tile.primary->version.load(std::memory_order_acquire); + for (const auto& [peer, cell] : tile.peers) + version = (std::max)(version, cell->version.load(std::memory_order_acquire)); + const bool pure_hot_recheck = !tile.stale && tile.unarmed_index == kNoIndex && tile.hot_gen == pass_gen_ && + mapping == tile.mapping && version == tile.version; + ++stats_.arms; + int result = watch_.arm(address, *tile.primary); + for (const auto& [peer, cell] : tile.peers) { + const int r = watch_.arm(peer, *cell); + if (r == 0) result = 0; + else if (r < 0 && result > 0) result = -1; + } + if (!pure_hot_recheck || result <= 0) ++stats_.non_hot_arms; + if (result <= 0) { + ++(result ? stats_.arm_failures : stats_.arm_busy); + add_unarmed(address, tile); + tile.stale = true; + return result; + } + tile.version = version; + tile.stale = false; + remove_unarmed(tile); + return 1; + } + + static constexpr bool has_hot_generation() noexcept { + return requires(const Watch& w) { w.hot_generation(); }; + } + static constexpr bool has_hot_stamp() noexcept { + return has_hot_generation() || requires(const Watch& w) { w.hot_count(); }; + } + std::uint64_t hot_stamp() const noexcept { + if constexpr (requires(const Watch& w) { w.hot_generation(); }) { + return static_cast(watch_.hot_generation()); + } else if constexpr (requires(const Watch& w) { w.hot_count(); }) { + return static_cast(watch_.hot_count()); + } else { + return 0; + } + } + + Watch& watch_; + std::unordered_map tiles_; + std::unordered_map> by_peer_; + std::unordered_map textures_; + std::vector> unarmed_list_; + std::vector> active_hot_tiles_; + std::map>> region_tiles_; + std::vector pending_noted_tiles_; + std::vector pending_dirty_keys_; + std::vector named_; + std::vector written_, aliases_, hot_; + std::vector batch_tiles_; + std::vector batch_reqs_; + std::vector> batch_tile_refs_; + struct PeerAcqSpan { + std::size_t slot = 0; + std::size_t begin = 0; + std::size_t count = 0; + }; + std::vector batch_arm_vas_; + std::vector batch_arm_cells_; + std::vector batch_req_unique_; + std::vector batch_arm_results_; + std::vector peer_acq_vas_; + std::vector peer_acq_cells_; + std::vector peer_acq_spans_; + std::vector> peer_rel_items_; + std::uint64_t pass_gen_ = 0; + std::uint64_t over_gen_ = 0; + std::uint64_t batch_arm_gen_ = 0; + std::uint64_t last_hot_stamp_ = 0; + bool hot_sync_needed_ = false; + std::atomic has_pending_{false}; + std::atomic hot_overlap_{0}; + std::atomic last_hot_stamp_atomic_{0}; + Stats stats_; +}; + +} // namespace leonida diff --git a/runtime/src/title_va_alias.h b/runtime/src/title_va_alias.h index 8ed315ecf1..8ecee2314f 100644 --- a/runtime/src/title_va_alias.h +++ b/runtime/src/title_va_alias.h @@ -45,6 +45,10 @@ class TitleVaAliases { // made: the view is then written with a zero-size range, never with the raw address). False: not the title's // memory (an arena VA, a buffer of the layer's). using Resolver = bool (*)(void* context, std::uint64_t va, std::uint64_t bytes, std::uint64_t& shader_va); + // Access-aware variant: receives whether the caller may write through the binding (false for read-only CBV/SRV + // root views so the page mirror does not queue them for GPU write-back). + using AccessResolver = bool (*)(void* context, std::uint64_t va, std::uint64_t bytes, bool writable, + 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). @@ -268,29 +272,33 @@ class TitleVaAliases { // A resolver that cannot back the address (no window or geometry copy fits) answers 0: the view is then written // with a zero-size range, never with the raw title address (heap_base + a raw VA is no allocation a shader can // read or write). Counted by kind: translated, or in the title's memory and left as it was. - std::uint64_t resolve(std::uint64_t va, std::uint64_t bytes, Kind kind) { + std::uint64_t resolve(std::uint64_t va, std::uint64_t bytes, Kind kind, bool writable = true) { if (!va) return va; std::uint64_t mapped = va, available = 0; const bool has_mapping = range_of(va, mapped, available) && mapped != va; if (has_mapping && bytes <= available) { translated_[kind].fetch_add(1, std::memory_order_relaxed); - note_reached(va, bytes); + if (writable) note_reached(va, bytes); return mapped; } + AccessResolver access_resolver; Resolver resolver; void* context; { std::lock_guard lock(hook_mutex_); + access_resolver = access_resolver_; resolver = resolver_; context = hook_context_; } std::uint64_t to = va; - if (!resolver || !resolver(context, va, bytes, to)) { + const bool resolved = access_resolver ? access_resolver(context, va, bytes, writable, to) + : (resolver && resolver(context, va, bytes, to)); + if (!resolved) { if (!has_mapping) return va; to = mapped; } (to != va ? translated_ : untranslated_)[kind].fetch_add(1, std::memory_order_relaxed); - if (to && to != va) note_reached(va, bytes); + if (writable && to) note_reached(va, bytes); return to; } @@ -347,14 +355,18 @@ class TitleVaAliases { // A commit inside a reserved range, or two that overlap, are one range. auto it = memory_.upper_bound(begin); if (it != memory_.begin() && std::prev(it)->second > begin) --it; + bool inside = false; // the range is one there already (a commit inside a reserve): nothing new while (it != memory_.end() && it->first < end) { + inside |= it->first <= begin && it->second >= end; begin = std::min(begin, it->first); end = std::max(end, it->second); it = memory_.erase(it); } memory_[begin] = end; memory_generation_.fetch_add(1, std::memory_order_release); - notify(Change::memory_added, base, bytes, 0); + // The whole merged range: a V# can only be backed through the range that holds its base, which may be an + // older one this extends. + if (!inside) notify(Change::memory_added, begin, end - begin, 0); } void remove_title_memory(std::uint64_t base) { std::unique_lock lock(memory_mutex_); @@ -449,6 +461,15 @@ class TitleVaAliases { if (hook_context_) return; hook_context_ = context; resolver_ = resolver; + access_resolver_ = nullptr; + scanner_ = scanner; + } + void set_hooks(void* context, AccessResolver resolver, TableScanner scanner) { + std::lock_guard lock(hook_mutex_); + if (hook_context_) return; + hook_context_ = context; + resolver_ = nullptr; + access_resolver_ = resolver; scanner_ = scanner; } void clear_hooks(void* context) { @@ -456,13 +477,18 @@ class TitleVaAliases { if (hook_context_ != context) return; hook_context_ = nullptr; resolver_ = nullptr; + access_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. + // Set after set_hooks, so the hook (and its context) stays the device's: access-aware resolver and write noter. + void set_access_resolver(AccessResolver resolver) { + std::lock_guard lock(hook_mutex_); + access_resolver_ = resolver; + } void set_noter(Noter noter) { std::lock_guard lock(hook_mutex_); noter_ = noter; @@ -578,6 +604,7 @@ class TitleVaAliases { void* maker_context_ = nullptr; BufferMaker maker_ = nullptr; Resolver resolver_ = nullptr; + AccessResolver access_resolver_ = nullptr; TableScanner scanner_ = nullptr; Noter noter_ = nullptr; void* source_context_ = nullptr; diff --git a/runtime/src/title_write_policy.h b/runtime/src/title_write_policy.h new file mode 100644 index 0000000000..f9918b599f --- /dev/null +++ b/runtime/src/title_write_policy.h @@ -0,0 +1,382 @@ +#pragma once +// Which pages of the title's memory a copy of them (the page mirror, src/title_mirror.h on branch page-mirror; the +// title texture refresh) must take again before a submission, and how each page is watched for that. +// +// Two ways to know a page was written, at two costs (runtime/test/guard_fault_bench.cpp measures them on the host): +// - cold: the page is guarded (read-only); the title's first write faults, the handler opens it and tells the +// policy (written()), and the page is copied before the next submission and guarded again. A page written once a +// minute costs one fault a minute. +// - hot: the page is left writable and copied before every submission, with no fault. A page the title writes in +// most submissions costs a copy a submission instead of a fault and a re-arm; under Wine a fault and a re-arm +// cost far more than copying 64 KiB. +// A page moves by its history, one bit a submission interval (frame() ends one), keeping O(dirty + hot + recent) +// active lists (never walking quiet cold pages): written in at least kPromote of the last kHistory submissions, and it +// turns hot at the end of the interval; a hot page is guarded again for one interval every kProbe intervals, and turns +// cold when such a probe interval sees no write. Measured under Wine on this machine: a 64 KiB copy is ~10 us, a fault +// 2-3 us with a handler that reopens in one call and a re-arm 4 us, so a page written in under half the submissions +// (including 1/frame pages) is cheaper cold; kPromote = 6 of 8 keeps only truly intra-frame hot pages uncovered and +// avoids copying quiet pages on empty submissions. +// +// Nothing is missed in between: a page is armed before it is reported dirty (collect() arms, then names it), so a +// write during the owner's copy faults and is in the next collect(); a page that turns hot is named at every collect() +// from then on, and one that turns cold stays armed (or returns to the dirty list to be armed and copied once more). +// +// The unit is the guard's: kPage (64 KiB, the geometry watch's tile and the mirror's page). Guard is the host side: +// bool arm(std::uintptr_t page); // read-only now; false when it cannot be (then the page is copied every time) +// void disarm(std::uintptr_t page); // writable now (a page turning hot, or leaving the policy) +// Optional batched arming: +// void arm_batch(const std::uintptr_t* pages, std::uint8_t* results, std::size_t count); // results[i]: 1 armed, 0 failed +// When present, collect() sorts pages needing arming and passes them in one call so Guard can coalesce contiguous +// 64 KiB pages into a single VirtualProtect syscall. +// The fault handler opens the page itself and calls written(page). Not thread-safe: the owner serialises calls (the +// handler's written() through a lock-free queue of its own, or under the owner's lock). +#include +#include +#include +#include +#include +#include +#include + +namespace leonida { + +template +class TitleWritePolicy { +public: + static constexpr std::uintptr_t kPage = 0x10000; + static constexpr unsigned kHistory = 8; // submission intervals of history a page keeps + static constexpr unsigned kPromote = 6; // written in this many submission intervals: submission-hot + static constexpr unsigned kProbe = 32; // submission-hot page is guarded for one interval every this many + + struct Stats { + std::uint64_t faults = 0; // written() on a guarded page + std::uint64_t hot_copies = 0; // pages named because they are hot + std::uint64_t cold_copies = 0; // pages named because they were written while guarded + std::uint64_t arms = 0, arm_failures = 0, promotions = 0, demotions = 0; + std::size_t hot = 0, cold = 0; // pages in each set now + std::uint64_t batched_arm_calls = 0; + }; + + explicit TitleWritePolicy(Guard& guard) : guard_(guard) {} + + // [begin, end) is to be copied from now on: its pages start cold and written (the owner has no copy yet). + void add(std::uintptr_t begin, std::uintptr_t end) { + if (begin >= end) return; + for (std::uintptr_t p = begin & ~(kPage - 1); p < end;) { + auto [it, fresh] = pages_.try_emplace(p); + if (fresh) { + it->second.written = true; + it->second.armed = false; + ++stats_.cold; + add_dirty(p, it->second); + } + if (end - p <= kPage) break; + p += kPage; + } + } + // No longer copied: its pages are left writable. + void remove(std::uintptr_t begin, std::uintptr_t end) { + if (begin >= end || pages_.empty()) return; + const std::uintptr_t first = begin & ~(kPage - 1); + const std::uintptr_t span = end - first; + const std::size_t count = std::size_t((span - 1) / kPage) + 1; + if (count <= pages_.size()) { + for (std::size_t i = 0; i < count; ++i) { + const std::uintptr_t addr = first + std::uintptr_t(i) * kPage; + const auto it = pages_.find(addr); + if (it != pages_.end()) erase_page(it); + } + } else { + for (auto it = pages_.begin(); it != pages_.end();) { + if (it->first >= first && it->first < end) it = erase_page(it); + else ++it; + } + } + } + + // The handler opened a guarded page the title wrote (or a kernel write is about to): copy it before the next + // submission. + void written(std::uintptr_t page) { + page &= ~(kPage - 1); + const auto it = pages_.find(page); + if (it == pages_.end()) return; + Page& p = it->second; + if (p.armed) ++stats_.faults; + p.armed = false; + p.written = true; + p.history |= 1; + if (!p.hot) { + add_dirty(page, p); + add_history(page, p); + } + } + + // Before a submission: every page the owner must copy, each once, after it was armed again where it is cold, so a + // write from here on is in the next collect(). `copy(page)` is called in address order. + // Runs in O(hot + dirty) without walking untouched cold pages. + template + void collect(Copy&& copy) { + to_copy_.clear(); + to_arm_.clear(); + for (const PageRef ref : hot_list_) { + Page& p = *ref.page; + if (!p.probe) { + ++stats_.hot_copies; + to_copy_.push_back(ref.addr); + continue; + } + if (!p.written && p.armed) continue; // guarded all along and not written: the copy is current + if (!p.armed) { + to_arm_.push_back(ref); + } else if (p.probe == 1) { + p.probe = 2; + } + p.written = false; + ++stats_.hot_copies; + to_copy_.push_back(ref.addr); + } + for (std::size_t i = 0; i < dirty_list_.size();) { + const PageRef ref = dirty_list_[i]; + Page& p = *ref.page; + if (p.hot || (!p.written && p.armed)) { + erase_dirty_at(i); + continue; + } + // Written, or not guarded since the last copy (a write then faulted nowhere): armed, then copied. + p.written = false; + ++stats_.cold_copies; + to_copy_.push_back(ref.addr); + if (!p.armed) { + to_arm_.push_back(ref); + ++i; + } else { + erase_dirty_at(i); + } + } + if (!to_arm_.empty()) { + std::sort(to_arm_.begin(), to_arm_.end(), + [](const PageRef& a, const PageRef& b) { return a.addr < b.addr; }); + to_arm_addrs_.resize(to_arm_.size()); + for (std::size_t k = 0; k < to_arm_.size(); ++k) to_arm_addrs_[k] = to_arm_[k].addr; + arm_results_.assign(to_arm_.size(), 0); + arm_pages(to_arm_addrs_.data(), arm_results_.data(), to_arm_.size()); + for (std::size_t k = 0; k < to_arm_.size(); ++k) { + Page& p = *to_arm_[k].page; + p.armed = arm_results_[k] != 0; + if (!p.armed) { + ++stats_.arm_failures; // copied every time, as a hot page + } else { + if (p.hot && p.probe == 1) p.probe = 2; + if (!p.hot) erase_dirty(p); // clean and guarded: leaves the dirty list + } + } + } + std::sort(to_copy_.begin(), to_copy_.end()); + for (const std::uintptr_t address : to_copy_) copy(address); + } + + // A submission interval ended: histories move on, and submission-hot and cold pages change sets. + // Runs in O(hot + recently-written cold) without walking quiet cold pages. + void frame() { + ++frame_; + const bool probe = frame_ % kProbe == 0; + demoted_.clear(); + to_disarm_.clear(); + for (std::size_t i = 0; i < hot_list_.size();) { + const PageRef ref = hot_list_[i]; + Page& p = *ref.page; + bool demoted = false; + if (p.probe == 2) { + p.probe = 3; // armed at the collect just before: the interval from here is observed + } else if (p.probe == 3) { + // The interval after the arming saw no write: no longer submission-hot (stays armed). + p.probe = 0; + if (!(p.history & 1) && p.armed) { + demoted = true; + p.hot = false; + } else { + // Written during probe (fault handler may already have cleared p.armed): re-establish hot + // ownership in Guard unconditionally so CellGuard::hot stays synchronized. + to_disarm_.push_back(ref.addr); + p.armed = false; + } + } else if (probe && !p.probe) { + p.probe = 1; // guarded at the next collect() + p.written = true; // and copied once more after the arming + } + p.history = std::uint16_t((p.history << 1) & kHistoryMask); + if (demoted) { + --stats_.hot; + ++stats_.cold; + ++stats_.demotions; + erase_hot_at(i); + if (p.written || !p.armed) add_dirty(ref.addr, p); + if (p.history != 0) demoted_.push_back(ref); + } else { + ++i; + } + } + for (std::size_t i = 0; i < history_active_.size();) { + const PageRef ref = history_active_[i]; + Page& p = *ref.page; + if (p.hot) { + erase_history_at(i); + continue; + } + if (unsigned(std::popcount(unsigned(p.history & kHistoryMask))) >= kPromote) { + p.hot = true; + p.probe = 0; + --stats_.cold; + ++stats_.hot; + ++stats_.promotions; + add_hot(ref.addr, p); + erase_dirty(p); + // Re-establish hot ownership in Guard unconditionally (even if written() already cleared p.armed). + to_disarm_.push_back(ref.addr); + p.armed = false; + p.history = std::uint16_t((p.history << 1) & kHistoryMask); + erase_history_at(i); + } else { + p.history = std::uint16_t((p.history << 1) & kHistoryMask); + if (p.history == 0) erase_history_at(i); + else ++i; + } + } + if (!to_disarm_.empty()) disarm_pages(to_disarm_.data(), to_disarm_.size()); + for (const PageRef ref : demoted_) add_history(ref.addr, *ref.page); + demoted_.clear(); + } + + const Stats& stats() const noexcept { return stats_; } + bool has_pending_work() const noexcept { + return !hot_list_.empty() || !dirty_list_.empty() || !history_active_.empty(); + } + std::size_t hot_count() const noexcept { return hot_list_.size(); } + std::size_t dirty_count() const noexcept { return dirty_list_.size(); } + std::size_t history_count() const noexcept { return history_active_.size(); } + bool hot(std::uintptr_t page) const { + const auto it = pages_.find(page & ~(kPage - 1)); + return it != pages_.end() && it->second.hot; + } + +private: + static constexpr std::uint16_t kHistoryMask = std::uint16_t((1u << kHistory) - 1); + static constexpr std::uint32_t kNoIndex = ~std::uint32_t(0); + + struct Page { + std::uint32_t hot_index = kNoIndex; // index in hot_list_ when hot + std::uint32_t dirty_index = kNoIndex; // index in dirty_list_ when cold and needing arm/copy + std::uint32_t history_index = kNoIndex; // index in history_active_ when cold with non-zero history + std::uint16_t history = 0; // bit 0: this submission interval + std::uint8_t probe = 0; // 1 asked, 2 armed at last collect, 3 observed + bool hot = false; + bool armed = false; + bool written = false; + }; + + struct PageRef { + std::uintptr_t addr = 0; + Page* page = nullptr; + }; + + void add_hot(std::uintptr_t address, Page& p) { + if (p.hot_index != kNoIndex) return; + p.hot_index = std::uint32_t(hot_list_.size()); + hot_list_.push_back({address, &p}); + } + void erase_hot_at(std::size_t idx) { + const PageRef removed = hot_list_[idx]; + const PageRef last = hot_list_.back(); + hot_list_[idx] = last; + if (last.page != removed.page) last.page->hot_index = std::uint32_t(idx); + hot_list_.pop_back(); + removed.page->hot_index = kNoIndex; + } + void erase_hot(Page& p) { + if (p.hot_index != kNoIndex) erase_hot_at(p.hot_index); + } + + void add_dirty(std::uintptr_t address, Page& p) { + if (p.dirty_index != kNoIndex) return; + p.dirty_index = std::uint32_t(dirty_list_.size()); + dirty_list_.push_back({address, &p}); + } + void erase_dirty_at(std::size_t idx) { + const PageRef removed = dirty_list_[idx]; + const PageRef last = dirty_list_.back(); + dirty_list_[idx] = last; + if (last.page != removed.page) last.page->dirty_index = std::uint32_t(idx); + dirty_list_.pop_back(); + removed.page->dirty_index = kNoIndex; + } + void erase_dirty(Page& p) { + if (p.dirty_index != kNoIndex) erase_dirty_at(p.dirty_index); + } + + void add_history(std::uintptr_t address, Page& p) { + if (p.history_index != kNoIndex) return; + p.history_index = std::uint32_t(history_active_.size()); + history_active_.push_back({address, &p}); + } + void erase_history_at(std::size_t idx) { + const PageRef removed = history_active_[idx]; + const PageRef last = history_active_.back(); + history_active_[idx] = last; + if (last.page != removed.page) last.page->history_index = std::uint32_t(idx); + history_active_.pop_back(); + removed.page->history_index = kNoIndex; + } + void erase_history(Page& p) { + if (p.history_index != kNoIndex) erase_history_at(p.history_index); + } + + typename std::unordered_map::iterator + erase_page(typename std::unordered_map::iterator it) { + Page& p = it->second; + if (p.armed) guard_.disarm(it->first); + const bool was_hot = p.hot; + erase_hot(p); + erase_dirty(p); + erase_history(p); + --(was_hot ? stats_.hot : stats_.cold); + return pages_.erase(it); + } + + void arm_pages(const std::uintptr_t* pages, std::uint8_t* results, std::size_t count) { + stats_.arms += count; + if constexpr (requires(Guard& g, const std::uintptr_t* p, std::uint8_t* r, std::size_t n) { + g.arm_batch(p, r, n); + }) { + ++stats_.batched_arm_calls; + guard_.arm_batch(pages, results, count); + } else { + for (std::size_t i = 0; i < count; ++i) results[i] = guard_.arm(pages[i]) ? 1 : 0; + } + } + + void disarm_pages(const std::uintptr_t* pages, std::size_t count) { + if constexpr (requires(Guard& g, const std::uintptr_t* p, std::size_t n) { + g.disarm_batch(p, n); + }) { + guard_.disarm_batch(pages, count); + } else { + for (std::size_t i = 0; i < count; ++i) guard_.disarm(pages[i]); + } + } + + Guard& guard_; + std::unordered_map pages_; + std::vector hot_list_; + std::vector dirty_list_; + std::vector history_active_; + std::vector to_copy_; + std::vector to_arm_; + std::vector to_arm_addrs_; + std::vector arm_results_; + std::vector to_disarm_; + std::vector demoted_; + std::uint64_t frame_ = 0; + Stats stats_; +}; + +} // namespace leonida diff --git a/runtime/src/vulkan13_features.h b/runtime/src/vulkan13_features.h index 0cb843cef3..a5604b3445 100644 --- a/runtime/src/vulkan13_features.h +++ b/runtime/src/vulkan13_features.h @@ -43,6 +43,10 @@ class Vulkan13Features { // VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT, asking a pipeline cache "do you have it?" without a // compile (pipeline_cache_journal.h). Core 1.3 only; a 1.2 device goes without. bool pipeline_creation_cache_control = false; + // shaderIntegerDotProduct: the OpSDot / OpUDot (SPV_KHR_integer_dot_product) the translator emits for the 4x8-bit + // dot products unless --integer-dot-fallback (docs/design.md, "Signed-byte dot products"). Required by Vulkan + // 1.3; a 1.2 device goes without, and make_game.py translates for it with the fallback. + bool integer_dot_product = false; bool usable() const { return dynamic_rendering && synchronization2; } @@ -52,7 +56,7 @@ class Vulkan13Features { core = api_version >= VK_API_VERSION_1_3; pipeline_cache_control=false;enable_pipeline_cache_control=false; dynamic_rendering = synchronization2 = subgroup_size_control = compute_full_subgroups = false; - extended_dynamic_state = pipeline_creation_cache_control = false; + extended_dynamic_state = pipeline_creation_cache_control = integer_dot_product = false; if (!features2) return; if (core) { VkPhysicalDeviceVulkan13Features f13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES}; @@ -64,6 +68,7 @@ class Vulkan13Features { subgroup_size_control = f13.subgroupSizeControl == VK_TRUE; compute_full_subgroups = f13.computeFullSubgroups == VK_TRUE; pipeline_creation_cache_control = f13.pipelineCreationCacheControl == VK_TRUE; + integer_dot_product = f13.shaderIntegerDotProduct == VK_TRUE; extended_dynamic_state = true; // core in 1.3, no feature bit return; } @@ -113,6 +118,7 @@ class Vulkan13Features { compute_full_subgroups = from.compute_full_subgroups; extended_dynamic_state = from.extended_dynamic_state; pipeline_creation_cache_control = from.pipeline_creation_cache_control; + integer_dot_product = from.integer_dot_product; } // The structs that enable both features, ahead of `chain`; returns their head for VkPhysicalDeviceVulkan12Features' @@ -126,6 +132,7 @@ class Vulkan13Features { enable13_.subgroupSizeControl = subgroup_size_control ? VK_TRUE : VK_FALSE; enable13_.computeFullSubgroups = compute_full_subgroups ? VK_TRUE : VK_FALSE; enable13_.pipelineCreationCacheControl = pipeline_creation_cache_control ? VK_TRUE : VK_FALSE; + enable13_.shaderIntegerDotProduct = integer_dot_product ? VK_TRUE : VK_FALSE; return &enable13_; } if (subgroup_size_control) { diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index 858ba46bec..b50b1b6a0f 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -46,6 +46,7 @@ #include #include #include +#include #include #include #include @@ -504,11 +505,21 @@ class DeferredDeletionQueue { pending_[tail_] = {retire_ticket, handle, kind}; tail_ = (tail_ + 1) & (pending_.size() - 1); ++count_; + head_ticket_.store(pending_[head_].ticket, std::memory_order_release); + pending_count_.store(count_, std::memory_order_release); + } + + bool has_pending() const noexcept { return pending_count_.load(std::memory_order_acquire) != 0; } + + bool has_ready(std::uint64_t current_ticket) const noexcept { + return pending_count_.load(std::memory_order_acquire) != 0 && + head_ticket_.load(std::memory_order_acquire) <= current_ticket; } // Drains all items with ticket <= current_ticket in O(k), invoking vkDestroy* outside the lock. // Uses a stack-local batch vector so concurrent drain() calls from multiple queues never race. void drain(std::uint64_t current_ticket, VkDevice device, const VulkanDeviceFunctions& vk) { + if (!has_ready(current_ticket)) return; BindlessReleaseFn release_fn = nullptr; void* release_user = nullptr; std::vector to_destroy; @@ -526,7 +537,11 @@ class DeferredDeletionQueue { if (count_ == 0) { head_ = 0; tail_ = 0; + head_ticket_.store(UINT64_MAX, std::memory_order_release); + } else { + head_ticket_.store(pending_[head_].ticket, std::memory_order_release); } + pending_count_.store(count_, std::memory_order_release); } for (const Item& item : to_destroy) { @@ -583,6 +598,8 @@ class DeferredDeletionQueue { std::size_t head_ = 0; std::size_t tail_ = 0; std::size_t count_ = 0; + std::atomic pending_count_{0}; + std::atomic head_ticket_{UINT64_MAX}; BindlessReleaseFn bindless_release_fn_ = nullptr; void* bindless_release_user_ = nullptr; }; @@ -778,6 +795,7 @@ class FenceWaitDispatcher { immediate_fn = signal_event_; } else { pending_.push_back({sem, value, event_handle, {}}); + pending_count_.store(pending_.size(), std::memory_order_release); if (!thread_.joinable() && wakeup_sem_) thread_ = std::thread([this] { run(); }); signal_wakeup_locked(); } @@ -798,6 +816,7 @@ class FenceWaitDispatcher { immediate_cb = std::move(cb); } else { pending_.push_back({sem, value, nullptr, std::move(cb)}); + pending_count_.store(pending_.size(), std::memory_order_release); if (!thread_.joinable() && wakeup_sem_) thread_ = std::thread([this] { run(); }); signal_wakeup_locked(); } @@ -809,6 +828,17 @@ class FenceWaitDispatcher { cv_.notify_one(); } + // Returns the largest pending waited value <= `value` for `sem`, or 0 when no CPU waiter awaits <= `value`. + std::uint64_t max_wait_value_le(VkSemaphore sem, std::uint64_t value) const { + if (!sem || pending_count_.load(std::memory_order_acquire) == 0) return 0; + std::lock_guard lock(mutex_); + std::uint64_t best = 0; + for (const Entry& e : pending_) { + if (e.semaphore == sem && e.value <= value && e.value > best) best = e.value; + } + return best; + } + // Wakes run() when another path marks the device lost so pending waits complete and stop()/cancel() never hang. void notify_device_lost() { { @@ -838,6 +868,7 @@ class FenceWaitDispatcher { } } pending_.resize(write); + pending_count_.store(pending_.size(), std::memory_order_release); // Entries already taken out of pending_ but not yet started belong to a live ready batch. Mark them // cancelled so dispatch skips them; this is how a re-entrant cancel() from another callback in the // same batch is completed without waiting on the callback that is already on this thread's stack. @@ -899,6 +930,7 @@ class FenceWaitDispatcher { dispatching_.push_back(slot); } lock.unlock(); + const submit_phases::WorkerScope busy(submit_phases::worker_fence_thread); // the "submit frame" line for (std::size_t i = 0; i < entries.size(); ++i) { Entry& e = entries[i]; DispatchSlot& slot = *slots[i]; @@ -951,6 +983,7 @@ class FenceWaitDispatcher { if (device_lost_.load(std::memory_order_acquire)) { std::vector drained = std::move(pending_); pending_.clear(); + pending_count_.store(0, std::memory_order_release); dispatch_outside_lock(lock, drained, signal_event_); return; } @@ -990,6 +1023,7 @@ class FenceWaitDispatcher { set_device_lost(device_lost_, "vkWaitSemaphores in the fence dispatcher returned VK_ERROR_DEVICE_LOST"); std::vector drained = std::move(pending_); pending_.clear(); + pending_count_.store(0, std::memory_order_release); dispatch_outside_lock(lock, drained, signal_event_); return; } @@ -1019,12 +1053,14 @@ class FenceWaitDispatcher { pending_.resize(write); for (Entry& e : pending_) ready.push_back(std::move(e)); pending_.clear(); + pending_count_.store(0, std::memory_order_release); set_device_lost(device_lost_, "vkGetSemaphoreCounterValue in the fence dispatcher returned VK_ERROR_DEVICE_LOST"); dispatch_outside_lock(lock, ready, signal_event_); return; } pending_.resize(write); + pending_count_.store(pending_.size(), std::memory_order_release); if (!ready.empty()) { dispatch_outside_lock(lock, ready, signal_event_); if (stop_) return; @@ -1040,10 +1076,11 @@ class FenceWaitDispatcher { VkSemaphore wakeup_sem_ = VK_NULL_HANDLE; std::uint64_t wakeup_val_ = 0; - std::mutex mutex_; + mutable std::mutex mutex_; std::condition_variable cv_; std::condition_variable epoch_cv_; std::vector pending_; + std::atomic pending_count_{0}; std::vector> dispatching_; // ready-batch callbacks outside mutex_ std::vector semaphores_; std::vector values_; @@ -1132,6 +1169,7 @@ class VulkanContext { if (loaded_ && gpu_labels_.initialize(device, get)) { replay_.gpu_label = [this](VkCommandBuffer cb, const label::Write& write) { gpu_labels_.record(cb, write); }; } + if (loaded_ && gpu_profile::enabled()) gpu_profile_.configure(device, get); // LEONIDA_GPU_PROFILE=1 replay_.pipeline_barrier = vk.vkCmdPipelineBarrier; replay_.clear_color_image = vk.vkCmdClearColorImage; replay_.clear_depth_stencil_image = vk.vkCmdClearDepthStencilImage; @@ -1208,7 +1246,10 @@ class VulkanContext { // buffer as out of bounds, which is no reason to drop the submission. replay_.buffer_at = [this](std::uint64_t va, std::uint64_t& size, VkBuffer& buffer, VkDeviceSize& offset) { BufferVaIndex::Hit hit{}; - if (!buffer_vas_.find(va, hit, size)) return false; // prefers an aliasing buffer that holds all of it + if (!buffer_vas_.find(va, hit, size)) { // prefers an aliasing buffer that holds all of it + // Title memory the page mirror holds (set_mirror_buffer): its chunk at heap_base + va. + return mirror_buffer_ && mirror_buffer_(va, size, buffer, offset); + } const ResourceBinding* b = resolve(hit.id); if (!b) return false; buffer = b->buffer; @@ -1313,6 +1354,8 @@ class VulkanContext { progress_watch_ = {}; // stop before queues, timelines or diagnostic state go away gpu_labels_.stop(device_); fence_dispatcher_.reset(); + stop_profile_resolver(); // drain/join profile resolver before destroying idle query pools + gpu_profile_.stop(); // after the fence callbacks and profile resolver that hold its recordings deletion_queue_.drain(UINT64_MAX, device_, vk); for (const auto& [key, framebuffer] : resolve_framebuffers_) vk.vkDestroyFramebuffer(device_, framebuffer, nullptr); @@ -1349,11 +1392,13 @@ class VulkanContext { std::unique_lock lock(resource_mutex_); predicate_family_ = family; predicate_reducer_ = std::make_unique(get, device_, memory, max_range); + bump_replay_version(); } // Configure before submitting work, only when storageBuffer8BitAccess is enabled on the device. void configure_predicated_copy(PFN_vkGetDeviceProcAddr get, const VkPhysicalDeviceLimits& limits) { std::unique_lock lock(resource_mutex_); predicated_copier_ = std::make_unique(get, device_, limits); + bump_replay_version(); } // Counts for DISPATCH-only ExecuteIndirect are read by a helper compute shader from GPU memory. // Requires Vulkan bufferDeviceAddress, already enabled for the D3D12 address arena. @@ -1361,6 +1406,7 @@ class VulkanContext { const VkPhysicalDeviceLimits& limits) { std::unique_lock lock(resource_mutex_); counted_dispatch_ = std::make_unique(get, device_, memory, limits); + bump_replay_version(); } // Indexed quad lists are drawn from triangle indices a compute pass writes into the copy scratch // (quad_index_expand.h). Call only with bufferDeviceAddress enabled and after an enable_copy_scratch whose chunks @@ -1368,7 +1414,7 @@ class VulkanContext { void configure_quad_indices(PFN_vkGetDeviceProcAddr get, const VkPhysicalDeviceLimits& limits) { std::unique_lock lock(resource_mutex_); quad_indices_ = std::make_unique(get, device_, limits); - + bump_replay_version(); } // Every ExecuteIndirect's arguments are clamped on the GPU into scratch before the indirect command reads them @@ -1384,12 +1430,16 @@ class VulkanContext { // reading the application's argument buffer, which may hold a record no compute pass wrote. Off, or on a // device the pass cannot run on, the replay keeps the application's buffer as before. replay_.require_indirect_clamp = indirect_clamp_enabled(); - if (!replay_.require_indirect_clamp) return; + if (!replay_.require_indirect_clamp) { + bump_replay_version(); + return; + } indirect_clamp_ = std::make_unique(get, device_, memory, limits, std::move(allocate), device_fault_.get(), std::move(families)); if (!indirect_clamp_->loaded()) { indirect_clamp_.reset(); replay_.require_indirect_clamp = false; + bump_replay_version(); return; } // The preparation callback needs this submission's counter-slot batch, so it is set per ExecuteCommandLists @@ -1397,6 +1447,7 @@ class VulkanContext { replay_.emit_indirect_clamp = [this](VkCommandBuffer command_buffer, const ClampedIndirect& job) { indirect_clamp_->emit(command_buffer, job); }; + bump_replay_version(); } VkDevice device() const { return device_; } @@ -1408,6 +1459,7 @@ class VulkanContext { replay_.insert_label = labels.cmd_insert; replay_.begin_label = labels.cmd_begin; replay_.end_label = labels.cmd_end; + bump_replay_version(); } bool debug_labels() const { return labels_.complete(); } @@ -1536,10 +1588,36 @@ class VulkanContext { // (timestampValidBits 0). Set by the device before any queue uses it. double timestamp_period() const { return timestamp_period_; } void set_timestamp_period(double period) { timestamp_period_ = period; } + // timestampValidBits by queue family, 0 for one that cannot reset or resolve queries. Set by the device before any + // queue uses it; LEONIDA_GPU_PROFILE profiles the queues of the families with bits. + void set_timestamp_bits(std::vector bits) { timestamp_bits_ = std::move(bits); } + std::uint32_t timestamp_bits(std::uint32_t family) const { + return family < timestamp_bits_.size() ? timestamp_bits_[family] : 0; + } + // LEONIDA_GPU_PROFILE=1: the GPU time per pipeline (vulkan_gpu_profile.h). Tests read its sums. + gpu_profile::Profiler& gpu_profile() { return gpu_profile_; } + + // Hands a completed GPU profile recording off the FenceWaitDispatcher thread onto a dedicated lazy resolver + // thread so vkGetQueryPoolResults / Profiler::mutex_ / periodic stderr reports never delay SetEventOnCompletion. + void enqueue_profile_resolve(std::shared_ptr recording) { + if (!recording) return; + { + std::lock_guard lock(profile_resolve_mutex_); + if (profile_resolve_stop_) return; + if (!profile_resolve_thread_.joinable()) { + profile_resolve_thread_ = std::thread([this] { profile_resolve_loop(); }); + } + profile_resolve_queue_.push_back(std::move(recording)); + } + profile_resolve_cv_.notify_one(); + } // True where a timestamp resolve must be ordered explicitly after the timestamps it copies (MoltenVK on Apple // GPUs, docs/d3d12_vulkan.md section 4.6). Set by the device before any queue uses it. bool order_timestamp_copies() const { return order_timestamp_copies_; } - void set_order_timestamp_copies(bool order) { order_timestamp_copies_ = order; } + void set_order_timestamp_copies(bool order) { + order_timestamp_copies_ = order; + bump_replay_version(); + } // The device address of the GPU address arena: console VAs are offsets from it (docs section 3.3). // execute() copies replay_ under a shared resource_mutex_, so writers hold it uniquely. @@ -1549,6 +1627,7 @@ class VulkanContext { std::unique_lock lock(resource_mutex_); replay_.heap_base = heap_base; replay_.heap_size = heap_size; + bump_replay_version(); } // Zeroed memory for unbound vertex and index buffers to read (ReplayFunctions::zero_buffer). @@ -1557,11 +1636,13 @@ class VulkanContext { replay_.zero_buffer = buffer; replay_.zero_offset = offset; replay_.zero_size = size; + bump_replay_version(); } void set_depth_range_unrestricted(bool enabled) { std::unique_lock lock(resource_mutex_); replay_.depth_range_unrestricted = enabled; + bump_replay_version(); } struct GeometryUpload { @@ -1574,12 +1655,14 @@ class VulkanContext { void set_geometry_provider(GeometryProvider provider) { std::unique_lock lock(resource_mutex_); geometry_provider_=std::move(provider); + bump_replay_version(); } // LOCAL: the copy-in fallback for vertex and index views in title memory (ReplayFunctions::title_memory). void set_title_memory(std::function copy) { std::unique_lock lock(resource_mutex_); replay_.title_memory = std::move(copy); + bump_replay_version(); } // Pre-expanded 32-bit triangle indices for non-indexed quad lists (ReplayFunctions::quad_indices). @@ -1588,12 +1671,14 @@ class VulkanContext { replay_.quad_indices = buffer; replay_.quad_indices_offset = offset; replay_.quad_index_count = count; + bump_replay_version(); } // Physical-device COLOR_ATTACHMENT format check for reinterpreted UAV clears. void set_color_attachment_format(std::function check) { std::unique_lock lock(resource_mutex_); replay_.color_attachment_format = std::move(check); + bump_replay_version(); } std::uint64_t heap_base() { std::shared_lock lock(resource_mutex_); @@ -1606,19 +1691,60 @@ class VulkanContext { void add_pipeline(std::uintptr_t id, const ComputePipeline& pipeline, const char* shader = nullptr) { std::unique_lock lock(pipeline_mutex_); pipelines_[id] = pipeline; + if (!pipeline.pipeline && pipeline.build && pipeline.built && !pipeline.async_build && !pipeline.skipped && + !pipeline.built(pipeline.build_context)) + note_unbuilt_sync_pipeline(); if (shader && device_fault_) device_fault_->pipeline_names[id] = {shader}; + if (shader && gpu_profile::enabled()) profile_names_[id] = {shader}; } void remove_pipeline(std::uintptr_t id) { std::unique_lock lock(pipeline_mutex_); pipelines_.erase(id); graphics_pipelines_.erase(id); if (device_fault_) device_fault_->pipeline_names.erase(id); + if (gpu_profile::enabled()) profile_names_.erase(id); } void add_graphics_pipeline(std::uintptr_t id, const GraphicsPipeline& pipeline, const CheckpointShaders* shaders = nullptr) { std::unique_lock lock(pipeline_mutex_); graphics_pipelines_[id] = pipeline; + if (!pipeline.async_build && pipeline.variant && pipeline.built && !pipeline.pipeline && !pipeline.built(0)) + note_unbuilt_sync_pipeline(); if (shaders && device_fault_) device_fault_->pipeline_names[id] = *shaders; + if (shaders && gpu_profile::enabled()) profile_names_[id] = *shaders; + } + // Tracks whether any registered synchronous pipeline may still need pre-pass compilation so warm runs skip + // collect_unbuilt_pipelines() in O(1) (pass-0 prepare() remains as a safe fallback for late variants or + // previously-unused PSOs). + void note_unbuilt_sync_pipeline() noexcept { + sync_pipeline_gen_.fetch_add(1, std::memory_order_acq_rel); + warm_empty_pipeline_scans_.store(0, std::memory_order_relaxed); + unbuilt_sync_pipelines_.fetch_add(1, std::memory_order_acq_rel); + } + std::uint64_t sync_pipeline_gen() const noexcept { return sync_pipeline_gen_.load(std::memory_order_acquire); } + bool has_unbuilt_sync_pipelines() const noexcept { + return unbuilt_sync_pipelines_.load(std::memory_order_acquire) != 0; + } + void note_sync_pipelines_built(std::size_t count) noexcept { + warm_empty_pipeline_scans_.store(0, std::memory_order_relaxed); + std::uint64_t cur = unbuilt_sync_pipelines_.load(std::memory_order_acquire); + while (cur > 0) { + const std::uint64_t next = cur > count ? cur - count : 0; + if (unbuilt_sync_pipelines_.compare_exchange_weak(cur, next, std::memory_order_acq_rel)) break; + } + } + void note_empty_pipeline_scan(std::uint64_t gen_before_scan) noexcept { + if (sync_pipeline_gen_.load(std::memory_order_acquire) != gen_before_scan) return; + constexpr std::uint32_t kWarmEmptyScans = 16; + if (warm_empty_pipeline_scans_.fetch_add(1, std::memory_order_relaxed) + 1 >= kWarmEmptyScans) { + if (sync_pipeline_gen_.load(std::memory_order_acquire) == gen_before_scan) { + unbuilt_sync_pipelines_.store(0, std::memory_order_release); + // Re-arm if a pipeline was registered concurrently between the gen check and store. + if (sync_pipeline_gen_.load(std::memory_order_acquire) != gen_before_scan) { + unbuilt_sync_pipelines_.fetch_add(1, std::memory_order_acq_rel); + } + } + } } // Workers for the pipelines a submission needs and that are not built yet. Null (the default): compiled serially on // the submitting thread once resource_mutex_ is released. Replacing it waits for submissions that are compiling, and @@ -1635,6 +1761,63 @@ class VulkanContext { large_compile_budget_ = std::move(budget); large_compile_demand_ = std::move(demand); } + using BatchCompileFn = std::function&)>; + void set_batch_compile_runner(BatchCompileFn runner) { + std::unique_lock lock(pipeline_mutex_); + batch_compile_runner_ = std::move(runner); + } + // Tracks pending queue Wait(semaphore, value) calls across all queues on this context so same-queue coalescing + // can merge [execute, signal(F, V), execute] when no waiter awaits (F, <= V), while splitting right after + // Signal(F, V) whenever any queue or CPU wait awaits a value <= V that is still pending in QueueHolds. + void note_wait_added(VkSemaphore semaphore, std::uint64_t value) { + if (!semaphore) return; + std::lock_guard lock(wait_tracker_mutex_); + pending_waits_.push_back({semaphore, value}); + pending_wait_count_.store(pending_waits_.size(), std::memory_order_release); + } + void note_wait_removed(VkSemaphore semaphore, std::uint64_t value) { + if (!semaphore) return; + std::lock_guard lock(wait_tracker_mutex_); + for (auto it = pending_waits_.begin(); it != pending_waits_.end(); ++it) { + if (it->first == semaphore && it->second == value) { + *it = pending_waits_.back(); + pending_waits_.pop_back(); + break; + } + } + pending_wait_count_.store(pending_waits_.size(), std::memory_order_release); + } + void note_waits_removed(std::span semaphores, std::span values) { + const std::size_t n = (std::min)(semaphores.size(), values.size()); + if (!n || pending_wait_count_.load(std::memory_order_acquire) == 0) return; + std::lock_guard lock(wait_tracker_mutex_); + for (std::size_t i = 0; i < n; ++i) { + if (!semaphores[i]) continue; + for (auto it = pending_waits_.begin(); it != pending_waits_.end(); ++it) { + if (it->first == semaphores[i] && it->second == values[i]) { + *it = pending_waits_.back(); + pending_waits_.pop_back(); + break; + } + } + } + pending_wait_count_.store(pending_waits_.size(), std::memory_order_release); + } + bool has_unsatisfied_waiter(VkSemaphore semaphore, std::uint64_t value) const { + if (!semaphore) return false; + std::uint64_t max_waited = 0; + if (pending_wait_count_.load(std::memory_order_acquire) != 0) { + std::lock_guard lock(wait_tracker_mutex_); + for (const auto& [sem, waited] : pending_waits_) { + if (sem == semaphore && waited <= value && waited > max_waited) max_waited = waited; + } + } + if (fence_dispatcher_) { + const std::uint64_t cpu_max = fence_dispatcher_->max_wait_value_le(semaphore, value); + if (cpu_max > max_waited) max_waited = cpu_max; + } + return max_waited != 0 && holds_.pending(semaphore, max_waited); + } PipelineWorkers::Stats pipeline_worker_stats() { std::shared_lock lock(pipeline_mutex_); return pipeline_workers_ ? pipeline_workers_->stats() : PipelineWorkers::Stats{}; @@ -1642,92 +1825,57 @@ class VulkanContext { // Configure before queue creation, when the selected queue family supports compute. void set_occlusion_resolve_memory(const VkPhysicalDeviceMemoryProperties& memory) { occlusion_resolve_memory_ = memory; - } - - struct HostTextureStats { std::uint64_t copies = 0, waits = 0; }; - HostTextureStats host_texture_stats() { - std::lock_guard lock(submit_mutex_); - return host_texture_stats_; - } - - // LOCAL FIX (deadlock on the first-run pages): the texture writes below used vkDeviceWaitIdle with the submit - // lock held. The device is idle only once every queue has run all it was given, and a queue whose submitted - // work waits on a value a later submission signals never gets there while this thread keeps the lock: a native - // boot sat 270 s in vkDeviceWaitIdle (title staging), then lost the device. Instead: wait for the queue - // timelines to pass what was submitted so far, at most `timeout`; on VK_TIMEOUT the caller skips this write (the - // title-texture pass tries it again) rather than freeze the title. Not covered, unlike the device wait: present - // and probe submissions, which have their own fences outside the retirement timelines (a present reading the - // image). The staged write is ordered behind them anyway (same queue, an ALL_COMMANDS barrier); the host copy - // is not, so a presented title texture can be written while a present still reads it (a torn frame, no fault). - // With submit_mutex_ held. - VkResult wait_submitted_locked(std::uint64_t timeout_ns, const char* what) { - if (is_device_lost()) return VK_ERROR_DEVICE_LOST; // a queue's timeline may be gone already - const auto pending = retire_tickets_.pending_through(submitted_ticket_.load(std::memory_order_acquire)); - if (pending.empty()) return VK_SUCCESS; - std::vector semaphores; - std::vector values; - for (const auto& [semaphore, value] : pending) { - semaphores.push_back(semaphore); - values.push_back(value); - } - VkSemaphoreWaitInfo wait{VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO}; - wait.semaphoreCount = std::uint32_t(semaphores.size()); - wait.pSemaphores = semaphores.data(); - wait.pValues = values.data(); - const VkResult r = observe_result(vk.vkWaitSemaphores(device_, &wait, timeout_ns), what); - if (r == VK_TIMEOUT) { - static std::atomic timeouts{0}; - const std::uint64_t n = timeouts.fetch_add(1, std::memory_order_relaxed) + 1; - if (!(n & (n - 1))) - std::fprintf(stderr, "[rt] vulkan: %s: submitted work not done within %llu ms (%llu time(s)); the " - "write is skipped this time\n", what, - static_cast(timeout_ns / 1000000), static_cast(n)); + bump_replay_version(); + } + + // A complete replacement of these color subresources from a staging buffer (TitleImageUpload): the title's CPU + // writes into its own texture memory, brought to the image. Serialized with replay and present while the old + // layouts are read and the transfer is submitted. It never waits for the GPU on the CPU: `copy(replay, pieces, + // waits)` records the transfer and submits it with a GPU wait on `waits`, every queue timeline value submitted so + // far, so it runs after all earlier work that may still read the image, on any queue, and before every submission + // made after it (the ones that sample the new texels). Until 2026-11 this waited on the CPU for that work for at + // most 250 ms and skipped the write when it was not done: a world frame takes longer, so changed textures (the + // planes of a video frame among them) arrived late or out of step, and the submitting thread stalled. A GPU wait + // cannot deadlock: every value in `waits` was submitted already, and a console Wait whose signal is not submitted + // yet is held in QueueHolds, outside the Vulkan queues, so the work behind these values completes without + // anything submitted later. + template + VkResult write_staged_title_image(ResourceId id, const VkImageSubresourceRange& range, Copy&& copy) { + std::unique_lock layout_lock(tracker_mutex_, std::defer_lock); + submit_phases::lock_timed(layout_lock); + std::unique_lock queue_lock(submit_mutex_, std::defer_lock); + submit_phases::lock_timed(queue_lock); + if (is_device_lost()) return VK_ERROR_DEVICE_LOST; + LayoutPieces pieces; + if (!tracker_.pieces(id, range, pieces) || pieces.empty()) return VK_ERROR_UNKNOWN; + const auto waits = retire_tickets_.pending_through(submitted_ticket_.load(std::memory_order_acquire)); + const auto r = observe_result(copy(replay_, pieces, waits), "title staging upload"); + if (r == VK_SUCCESS) { + for (const auto& p : pieces) + if (p.layout == VK_IMAGE_LAYOUT_UNDEFINED) tracker_.set(id, p.range, VK_IMAGE_LAYOUT_GENERAL); } return r; } - // Short: a timeout is certain when the awaited work needs this thread's lock, and the write is only skipped. - static constexpr std::uint64_t kTitleWriteWaitNs = 250'000'000; // 250 ms - // CPU writes to a title texture have no application fence. Prevent another queue from - // claiming a new layout or submitting work between the completion check and the host copy. - // An unsatisfied console Wait lives in QueueHolds, outside the Vulkan queues. - template - VkResult write_host_texture(ResourceId id, std::uint32_t subresource, Copy&& copy) { - std::lock_guard layout_lock(tracker_mutex_); - std::lock_guard queue_lock(submit_mutex_); - if (tracker_.layout(id, subresource) != VK_IMAGE_LAYOUT_GENERAL) return VK_NOT_READY; - if (image_work_pending_) { - ++host_texture_stats_.waits; - // A device wait is a queue operation: it passes the compile gate, so it never waits in the driver behind a - // long pipeline create (the starved wait that loses the device after 10 s). - const SubmitMutex::SubmitTurn turn(submit_mutex_, false); - const auto result = wait_submitted_locked(kTitleWriteWaitNs, "vkWaitSemaphores (title texture upload)"); - // Not done in time: VK_NOT_READY, so the caller takes its staged path (ordered on the queue) or tries - // again later, and the skip is not counted as a failed fill. - if (result == VK_TIMEOUT) return VK_NOT_READY; - if (result != VK_SUCCESS) return result; - image_work_pending_ = false; - } - if (!copy()) return VK_ERROR_UNKNOWN; - ++host_texture_stats_.copies; - return VK_SUCCESS; - } - - // A complete CPU-side replacement of these color subresources. Serialize with replay and - // present while recording the old layouts, finishing prior reads and publishing the copy. - template - VkResult write_staged_title_image(ResourceId id, const VkImageSubresourceRange& range, Copy&& copy) { - std::lock_guard layout_lock(tracker_mutex_); - std::lock_guard queue_lock(submit_mutex_); + // Split record/submit variant: holds tracker_mutex_ during command recording while leaving submit_mutex_ unlocked + // so presents, compiles, and cross-queue submits never stall on command recording. Acquires submit_mutex_ ONLY + // around snapshotting cross-queue `waits` and calling `submit(waits)`. + template + VkResult write_staged_title_image(ResourceId id, const VkImageSubresourceRange& range, Record&& record, + Submit&& submit) { + std::unique_lock layout_lock(tracker_mutex_, std::defer_lock); + submit_phases::lock_timed(layout_lock); + if (is_device_lost()) return VK_ERROR_DEVICE_LOST; LayoutPieces pieces; if (!tracker_.pieces(id, range, pieces) || pieces.empty()) return VK_ERROR_UNKNOWN; - if (image_work_pending_) { - const SubmitMutex::SubmitTurn turn(submit_mutex_, false); // a queue operation: the compile gate (as above) - const auto r = wait_submitted_locked(kTitleWriteWaitNs, "vkWaitSemaphores (title staging)"); - if (r != VK_SUCCESS) return r; - image_work_pending_ = false; + VkResult r = observe_result(record(replay_, pieces), "title staging record"); + if (r == VK_SUCCESS) { + std::unique_lock queue_lock(submit_mutex_, std::defer_lock); + submit_phases::lock_timed(queue_lock); + if (is_device_lost()) return VK_ERROR_DEVICE_LOST; + const auto waits = retire_tickets_.pending_through(submitted_ticket_.load(std::memory_order_acquire)); + r = observe_result(submit(waits), "title staging upload"); } - const auto r = observe_result(copy(replay_, pieces), "title staging upload"); if (r == VK_SUCCESS) { for (const auto& p : pieces) if (p.layout == VK_IMAGE_LAYOUT_UNDEFINED) tracker_.set(id, p.range, VK_IMAGE_LAYOUT_GENERAL); @@ -1735,8 +1883,66 @@ class VulkanContext { return r; } - // Present and probe submissions have their own fences, outside the queue retirement timelines. - void note_image_work_locked() { image_work_pending_ = true; } + // Atomic batched variant of write_staged_title_image: acquires tracker_mutex_ ONCE for all targets, records + // command buffers with submit_mutex_ UNLOCKED, then acquires submit_mutex_ ONLY for snapshotting cross-queue + // waits and submitting. Transitions UNDEFINED -> GENERAL in tracker_ ONLY if submit returns VK_SUCCESS. + struct StagedImageTarget { + ResourceId id{}; + VkImageSubresourceRange range{}; + }; + template + VkResult write_staged_title_images(std::span targets, Copy&& copy) { + if (targets.empty()) return VK_SUCCESS; + std::unique_lock layout_lock(tracker_mutex_, std::defer_lock); + submit_phases::lock_timed(layout_lock); + std::unique_lock queue_lock(submit_mutex_, std::defer_lock); + submit_phases::lock_timed(queue_lock); + if (is_device_lost()) return VK_ERROR_DEVICE_LOST; + std::vector all_pieces(targets.size()); + for (std::size_t i = 0; i < targets.size(); ++i) { + if (!tracker_.pieces(targets[i].id, targets[i].range, all_pieces[i]) || all_pieces[i].empty()) + return VK_ERROR_UNKNOWN; + } + const auto waits = retire_tickets_.pending_through(submitted_ticket_.load(std::memory_order_acquire)); + const auto r = observe_result(copy(replay_, all_pieces, waits), "title staging upload batch"); + if (r == VK_SUCCESS) { + for (std::size_t i = 0; i < targets.size(); ++i) { + for (const auto& p : all_pieces[i]) + if (p.layout == VK_IMAGE_LAYOUT_UNDEFINED) + tracker_.set(targets[i].id, p.range, VK_IMAGE_LAYOUT_GENERAL); + } + } + return r; + } + + template + VkResult write_staged_title_images(std::span targets, Record&& record, Submit&& submit) { + if (targets.empty()) return VK_SUCCESS; + std::unique_lock layout_lock(tracker_mutex_, std::defer_lock); + submit_phases::lock_timed(layout_lock); + if (is_device_lost()) return VK_ERROR_DEVICE_LOST; + std::vector all_pieces(targets.size()); + for (std::size_t i = 0; i < targets.size(); ++i) { + if (!tracker_.pieces(targets[i].id, targets[i].range, all_pieces[i]) || all_pieces[i].empty()) + return VK_ERROR_UNKNOWN; + } + VkResult r = observe_result(record(replay_, all_pieces), "title staging record batch"); + if (r == VK_SUCCESS) { + std::unique_lock queue_lock(submit_mutex_, std::defer_lock); + submit_phases::lock_timed(queue_lock); + if (is_device_lost()) return VK_ERROR_DEVICE_LOST; + const auto waits = retire_tickets_.pending_through(submitted_ticket_.load(std::memory_order_acquire)); + r = observe_result(submit(waits), "title staging upload batch"); + } + if (r == VK_SUCCESS) { + for (std::size_t i = 0; i < targets.size(); ++i) { + for (const auto& p : all_pieces[i]) + if (p.layout == VK_IMAGE_LAYOUT_UNDEFINED) + tracker_.set(targets[i].id, p.range, VK_IMAGE_LAYOUT_GENERAL); + } + } + return r; + } // For tests and traces. VkImageLayout layout(ResourceId id, std::uint32_t subresource) { @@ -1840,10 +2046,17 @@ class VulkanContext { // `prepare` is called at the start of the command buffer of every ExecuteCommandLists, before the lists are // written: the device brings the bindless set 0 of the translated shaders up to date there (vulkan_bindless.h) // and records what the set needs first. When it fails, nothing of that call is executed. - void set_transfer_only_family(std::uint32_t family) { transfer_only_family_ = family; } - void set_graphics_family(std::uint32_t family) { graphics_family_ = family; } + void set_transfer_only_family(std::uint32_t family) { + transfer_only_family_ = family; + bump_replay_version(); + } + void set_graphics_family(std::uint32_t family) { + graphics_family_ = family; + bump_replay_version(); + } void set_compute_copy_aspects(std::function check) { replay_.compute_copy_aspects = std::move(check); + bump_replay_version(); } // `before` is called at the start of every submission of command lists (a held batch: when it is released), @@ -1891,9 +2104,69 @@ class VulkanContext { return it == device_fault_->pipeline_names.end() ? nullptr : it->second[0]; } void set_before_execute(std::function before) { before_execute_ = std::move(before); } + // Monotonic visibility epoch bumped on ExecuteCommandLists and CPU Fence::Signal (tracked per-fence in + // QueueHolds) so before_execute_() can coalesce concurrent or back-to-back cross-queue refreshes while + // guaranteeing every CPU write before a batch's enqueue or a waited CPU Fence::Signal is visible. + std::uint64_t next_visibility_seq() noexcept { + return visibility_seq_.fetch_add(1, std::memory_order_acq_rel) + 1; + } + std::uint64_t current_visibility_seq() const noexcept { + return visibility_seq_.load(std::memory_order_acquire); + } + // Minimum visibility epoch required by the execute_now() invoking before_execute_() on this thread (0 outside). + static std::uint64_t current_before_execute_seq() noexcept { return t_before_execute_seq_; } + // The page mirror's lookup for buffer_at (src/title_mirror.h): the buffer and offset that hold a title address no + // buffer of ours holds. Set while no replay runs (device creation and destruction). + using MirrorBuffer = std::function; + void set_mirror_buffer(MirrorBuffer lookup) { mirror_buffer_ = std::move(lookup); } + // The page mirror bound pages in a batch that signals `value` on `semaphore`: every queue's next command-buffer + // submission waits for it (checked under submit_mutex_ before vkQueueSubmit and record_submit_locked()). Returns + // the retire ticket of the latest submission accepted before this bind was published, so freed homes stamped with + // it cannot be reused while any submission that did not wait for this bind is still in flight. + std::uint64_t note_mirror_bind(VkSemaphore semaphore, std::uint64_t value) { + std::lock_guard lock(submit_mutex_); + mirror_bind_semaphore_ = semaphore; + mirror_bind_value_ = value; + return submitted_retire_ticket(); + } + // Reads the latest published page-mirror bind timeline semaphore and value (caller must hold submit_mutex_). + void mirror_bind_locked(VkSemaphore& semaphore, std::uint64_t& value) const noexcept { + semaphore = mirror_bind_semaphore_; + value = mirror_bind_value_; + } + // Publishes the latest staged title-texture upload timeline (caller holds submit_mutex_): every queue's next + // command-buffer submission waits lazily on `(semaphore, value)` in VulkanQueue::submit_multi() instead of + // submitting an empty wait-only vkQueueSubmit per consumer queue. + void note_title_upload_locked(VkSemaphore semaphore, std::uint64_t value) noexcept { + title_upload_semaphore_ = semaphore; + title_upload_value_ = value; + } + // Clears the published title-upload timeline before destroying `semaphore` (caller holds submit_mutex_). + void clear_title_upload_locked(VkSemaphore semaphore) noexcept { + if (title_upload_semaphore_ == semaphore) { + title_upload_semaphore_ = VK_NULL_HANDLE; + title_upload_value_ = 0; + } + } + std::uint64_t replay_version() const noexcept { return replay_version_.load(std::memory_order_acquire); } // Called at the end of every ExecuteCommandLists replay that called before_execute_, however it returns: by then // the submissions it made are recorded, so submitted_retire_ticket() covers them. void set_after_execute(std::function after) { after_execute_ = std::move(after); } + // Enqueue-time / finish-time serial hooks for GeometryViews::kAfterExecutes: `on_enqueue` runs synchronously inside + // VulkanQueue::execute() BEFORE the batch enters an async worker inbox or wait-hold queue, and `on_finish` runs + // after the batch's (or coalesced submission's) vkQueueSubmit has recorded its retire ticket (or when a queued/held + // batch is dropped on device loss or teardown). + void set_on_enqueue_execute(std::function on_enqueue) { + on_enqueue_execute_ = std::move(on_enqueue); + } + void set_on_finish_execute(std::function on_finish) { + on_finish_execute_ = std::move(on_finish); + } + // Called after a submission containing at least one emitted draw or dispatch with `writes_buffer == true` (or + // legacy untyped indirect) succeeds on vkQueueSubmit, with the device's current submitted retire ticket. + void set_on_buffer_write_submitted(std::function on_buffer_write) { + on_buffer_write_submitted_ = std::move(on_buffer_write); + } // GPU work the lists of a submission depend on, recorded at the start of its command buffer by a queue that can // run compute (the console heap translation pass, src/console_heap_gpu.h): `record` returns true when it recorded // something, and `commit` follows that submit (true: it reached the queue; the ticket is a retire ticket at or @@ -1925,6 +2198,7 @@ class VulkanContext { replay_.depth24_run = [this](VkCommandBuffer command_buffer, const Depth24Job& job) { depth24_->run(command_buffer, job); }; + bump_replay_version(); } bool has_depth24() { @@ -1941,6 +2215,7 @@ class VulkanContext { scratch_ = std::make_unique(get, device_, std::move(allocate), extra_usage, std::move(families), device_fault_.get()); if (!scratch_->loaded()) scratch_.reset(); + bump_replay_version(); } // Called after that command buffer's submit: true when it was accepted, false when vkQueueSubmit failed. The @@ -2014,6 +2289,10 @@ class VulkanContext { // queue's next submission wait for this one, which binds the new set. void note_bindless_upload() { bindless_upload_pending_ = true; } + std::uint64_t cached_completed_retire_ticket() const noexcept { + return completed_retire_ticket_.load(std::memory_order_acquire); + } + std::uint64_t completed_retire_ticket() { bool lost = false; std::uint64_t ticket = 0; @@ -2032,6 +2311,7 @@ class VulkanContext { // A DEVICE_LOST seen here is the first Vulkan operation to discover it; it must not be mistaken for // "this ticket has not completed". if (lost) mark_device_lost(); + else note_completed_retire_ticket(ticket); return lost ? 0 : ticket; } @@ -2054,7 +2334,6 @@ class VulkanContext { void record_submit_locked(VkSemaphore progress, std::uint64_t value) { const auto ticket = submitted_ticket_.fetch_add(1, std::memory_order_acq_rel) + 1; retire_tickets_.record(ticket, progress, value); - note_image_work_locked(); } void retire_queue_idle_locked(VkSemaphore progress) { retire_tickets_.queue_idle(progress); @@ -2227,13 +2506,23 @@ class VulkanContext { return framebuffer; } + void note_completed_retire_ticket(std::uint64_t ticket) noexcept { + std::uint64_t prev = completed_retire_ticket_.load(std::memory_order_relaxed); + while (ticket > prev && + !completed_retire_ticket_.compare_exchange_weak(prev, ticket, std::memory_order_release, + std::memory_order_relaxed)) { + } + } + std::uint64_t poll_retirement_locked(VkResult& result) { - return retire_tickets_.completed([&](VkSemaphore semaphore, std::uint64_t value) { + const std::uint64_t ticket = retire_tickets_.completed([&](VkSemaphore semaphore, std::uint64_t value) { std::uint64_t done = 0; result = observe_result(vk.vkGetSemaphoreCounterValue(device_, semaphore, &done), "vkGetSemaphoreCounterValue (retirement)"); return result == VK_SUCCESS && done >= value; }); + if (result == VK_SUCCESS) note_completed_retire_ticket(ticket); + return ticket; } void watch_queue_progress(std::stop_token stop) { @@ -2367,10 +2656,9 @@ class VulkanContext { // gate's own mutex is a leaf; a submission waits at the gate with submit_mutex_ held, for creates already in the // driver only (SubmitMutex::CompileTurn). alignas(64) SubmitMutex submit_mutex_; - bool image_work_pending_ = false; // under submit_mutex_ - HostTextureStats host_texture_stats_; // under submit_mutex_ RetireTickets retire_tickets_; std::atomic submitted_ticket_{0}; + std::atomic completed_retire_ticket_{0}; DeferredDeletionQueue deletion_queue_; std::unique_ptr device_fault_; std::jthread progress_watch_; @@ -2381,9 +2669,16 @@ class VulkanContext { std::unordered_map> sparse_resources_; std::unordered_map pipelines_; std::unordered_map graphics_pipelines_; + std::atomic unbuilt_sync_pipelines_{0}; + std::atomic sync_pipeline_gen_{0}; + std::atomic warm_empty_pipeline_scans_{0}; std::unique_ptr pipeline_workers_; + BatchCompileFn batch_compile_runner_; std::function large_compile_budget_; std::function()> large_compile_demand_; + mutable std::mutex wait_tracker_mutex_; + std::vector> pending_waits_; + std::atomic pending_wait_count_{0}; std::unordered_map acceleration_structures_; LayoutTracker tracker_; std::mutex storage_mutex_; // a leaf lock: guards storage_pending_ and zero_pending_ only @@ -2404,8 +2699,16 @@ class VulkanContext { std::map, VkRenderPass> resolve_passes_; std::map, VkFramebuffer> resolve_framebuffers_; + std::function before_execute_; + std::atomic visibility_seq_{0}; + std::atomic replay_version_{1}; + void bump_replay_version() noexcept { replay_version_.fetch_add(1, std::memory_order_release); } + static inline thread_local std::uint64_t t_before_execute_seq_ = 0; // trivially destructible (no TLS callback) std::function after_execute_; + std::function on_enqueue_execute_; + std::function on_finish_execute_; + std::function on_buffer_write_submitted_; InputProbe input_probe_; TableScanner table_scanner_; GeometryProvider geometry_provider_; @@ -2418,6 +2721,15 @@ class VulkanContext { // a counter that says which one: every other queue's next submission waits for it (storage_mutex_). VkSemaphore bindless_upload_semaphore_ = VK_NULL_HANDLE; std::uint64_t bindless_upload_value_ = 0; + // The page mirror's last bind batch (src/title_mirror.h): every queue's next command-buffer submission waits for + // it under submit_mutex_, so none reads a page whose bind has not landed (submit_mutex_). + MirrorBuffer mirror_buffer_; + VkSemaphore mirror_bind_semaphore_ = VK_NULL_HANDLE; + std::uint64_t mirror_bind_value_ = 0; + // The latest staged title-texture upload timeline (d3d12_title_image_upload.h): every queue's next command-buffer + // submission waits for it lazily under submit_mutex_ instead of queuing empty wait submits per consumer queue. + VkSemaphore title_upload_semaphore_ = VK_NULL_HANDLE; + std::uint64_t title_upload_value_ = 0; std::uint64_t bindless_upload_version_ = 0; std::function prelude_record_; std::function prelude_commit_; @@ -2429,6 +2741,45 @@ class VulkanContext { std::function bindless_commit_; std::unordered_map query_pools_; // element pointers stay valid across inserts double timestamp_period_ = 0; + std::vector timestamp_bits_; // by queue family (set_timestamp_bits) + gpu_profile::Profiler gpu_profile_; // LEONIDA_GPU_PROFILE=1 + gpu_profile::NameMap profile_names_; // its pipeline names, guarded by pipeline_mutex_ + std::mutex profile_resolve_mutex_; + std::condition_variable profile_resolve_cv_; + std::deque> profile_resolve_queue_; + std::thread profile_resolve_thread_; + bool profile_resolve_stop_ = false; + + void profile_resolve_loop() { + for (;;) { + std::deque> batch; + { + std::unique_lock lock(profile_resolve_mutex_); + profile_resolve_cv_.wait(lock, [this] { + return profile_resolve_stop_ || !profile_resolve_queue_.empty(); + }); + if (profile_resolve_queue_.empty()) { + if (profile_resolve_stop_) return; + continue; + } + batch.swap(profile_resolve_queue_); + } + for (auto& rec : batch) { + gpu_profile_.resolve(*rec); + rec.reset(); + } + } + } + + void stop_profile_resolver() { + { + std::lock_guard lock(profile_resolve_mutex_); + profile_resolve_stop_ = true; + } + profile_resolve_cv_.notify_all(); + if (profile_resolve_thread_.joinable()) profile_resolve_thread_.join(); + profile_resolve_queue_.clear(); + } bool order_timestamp_copies_ = false; VkPhysicalDeviceMemoryProperties occlusion_resolve_memory_{}; label::Completions gpu_labels_; @@ -2512,7 +2863,26 @@ class VulkanFence { // ID3D12Fence::Signal from the CPU. Vulkan timelines only increase: a value at or below the current one is // ignored (D3D12 would set it), and the caller is told. - bool signal(std::uint64_t value) { + bool signal(std::uint64_t value) { return signal_impl(value, true); } + + // GPU-to-GPU relay signal (vis_seq = 0): signals the timeline semaphore from the CPU without bumping + // visibility_seq_, for list_values gates whose waits were met strictly by GPU writes landed via Pump::land(). + bool signal_gpu_relay(std::uint64_t value) { return signal_impl(value, false); } + + // true when the value was reached within the timeout. + bool wait(std::uint64_t value, std::uint64_t timeout_ns) const { + VkSemaphoreWaitInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO}; + info.semaphoreCount = 1; + info.pSemaphores = &semaphore_; + info.pValues = &value; + const VkResult result = context_.observe_result( + context_.vk.vkWaitSemaphores(context_.device(), &info, timeout_ns), "vkWaitSemaphores"); + if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost(); + return result == VK_SUCCESS; + } + +private: + bool signal_impl(std::uint64_t value, bool bump_vis_seq) { // The dispatcher may be testing a failed counter query. Do not call completed() here: // it marks the context lost on a query error and prevents the dispatcher from waking. if (context_.is_device_lost()) return false; @@ -2528,31 +2898,25 @@ class VulkanFence { "vkSignalSemaphore"); if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost(); if (result != VK_SUCCESS) return false; - context_.holds().signaled(semaphore_, value); // queues that held a batch for this value run it now - context_.holds().pump_ready(); + { + QueueHolds::WorkGuard active(context_.holds()); + const std::uint64_t vis_seq = bump_vis_seq ? context_.next_visibility_seq() : 0; + context_.holds().signaled(semaphore_, value, vis_seq); + context_.holds().pump_ready(); + } return true; } - // true when the value was reached within the timeout. - bool wait(std::uint64_t value, std::uint64_t timeout_ns) const { - VkSemaphoreWaitInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO}; - info.semaphoreCount = 1; - info.pSemaphores = &semaphore_; - info.pValues = &value; - const VkResult result = context_.observe_result( - context_.vk.vkWaitSemaphores(context_.device(), &info, timeout_ns), "vkWaitSemaphores"); - if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost(); - return result == VK_SUCCESS; - } - -private: VulkanContext& context_; VkSemaphore semaphore_ = VK_NULL_HANDLE; }; // One D3D12 command queue on one VkQueue. D3D12 lets one thread use a queue at a time per call and the COM wrapper -// serialises its calls; state_mutex_ additionally serialises them against the thread that releases a held batch -// (Wait-before-Signal, queue_holds.h), the only other thread that touches a queue. +// serialises its calls; state_mutex_ protects only the queue's pending/held bookkeeping (microsecond hold time), +// while the executing_ flag serialises actual Vulkan replay, before_execute_(), and submission without holding +// state_mutex_ across them. Wait, Signal, Marker, and batches blocked on an unmet Wait append under state_mutex_ +// without waiting on before_execute_() or replay; an unblocked synchronous ExecuteCommandLists waits on exec_cv_ +// until executing_ clears so before_execute_() and replay still finish synchronously before returning. // // A Wait on a fence value no Signal has been submitted for yet holds the next batch (ExecuteCommandLists or Signal) // on the CPU, with everything the queue is asked to do after it, instead of replaying it against layouts from before @@ -2560,6 +2924,28 @@ class VulkanFence { // layout tracker follows replay order. Holding on the CPU also keeps a Wait and the Signal that satisfies it from // landing on one VkQueue in the wrong order, which would never make progress on the GPU. class VulkanQueue : private QueueHolds::Holder { + // RAII guard for executing_ = true. Re-acquires state_mutex_ on abnormal exit so executing_ can never stick true. + struct ExecGuard { + VulkanQueue* q; + std::unique_lock& state; + bool active = true; + void release() { + if (!active) return; + active = false; + if (!state.owns_lock()) state.lock(); + q->executing_ = false; + q->exec_cv_.notify_all(); + } + ~ExecGuard() { + if (!active) return; + if (!state.owns_lock()) state.lock(); + q->restore_exec_waits_locked(); + q->set_active_seq_locked(0); + q->executing_ = false; + q->exec_cv_.notify_all(); + } + }; + public: enum class QueueKind : std::uint8_t { direct, compute, copy }; @@ -2569,6 +2955,7 @@ class VulkanQueue : private QueueHolds::Holder { // meanwhile ends it, and a device lost makes execute() submit nothing. static constexpr std::size_t kMaxQueuedCommandBuffers = 64; static constexpr std::uint64_t kQueuedWaitNs = 5'000'000'000; + static constexpr std::uint64_t kUnsetEpoch = UINT64_MAX; static constexpr VkPipelineStageFlags2 queue_supported_stages(QueueKind kind) noexcept { switch (kind) { @@ -2611,7 +2998,20 @@ class VulkanQueue : private QueueHolds::Holder { std::fprintf(stderr, "[rt] d3d12: queue %p (progress %p) destroyed at t=%.3f s\n", static_cast(queue_), static_cast(progress_), double(diagnostic_ms()) / 1000.0); context_.holds().detach(this); // no thread releases into this queue from here on + { + std::unique_lock state(state_mutex_); + exec_cv_.wait(state, [this] { return !executing_; }); + } report_held_at_teardown(); + { + std::lock_guard state(state_mutex_); + if (!waits_.empty()) { + context_.note_waits_removed(waits_, wait_values_); + waits_.clear(); + wait_values_.clear(); + wait_pins_.clear(); + } + } context_.holds().pump_ready(); // presents queued behind what was just dropped can run if (queue_) { std::lock_guard lock(context_.submit_mutex()); @@ -2664,6 +3064,25 @@ class VulkanQueue : private QueueHolds::Holder { bool ok() const { return ok_; } // A queue of the runtime's own whose caller waits for each call (a staging copy): never on a worker. void make_synchronous() { synchronous_ = true; } + // Skip context_.before_execute_() (and its paired after_execute_(), on_enqueue_execute_ serials, non-shader + // bindless/prelude prep, and submit_phases submission accounting) for internal runtime queues such as + // WriteToSubresource/ReadFromSubresource staging copies that never read console heaps, shadows, or GeometryViews. + void set_skip_before_execute(bool skip = true) { skip_before_execute_.store(skip, std::memory_order_release); } + bool skip_before_execute() const { return skip_before_execute_.load(std::memory_order_acquire); } + // Override LEONIDA_SUBMIT_ASYNC depth for this queue before its first queued call (used by unit tests). + void set_async_depth(unsigned depth) { + std::lock_guard lock(inbox_mutex_); + if (!worker_.joinable()) async_depth_ = depth; + } + // Async worker telemetry snapshots for unit tests. + std::uint64_t async_run_ns_for_test() { + std::lock_guard lock(inbox_mutex_); + return async_stats_.run_ns + async_pump_ns_.load(std::memory_order_relaxed); + } + std::uint64_t async_room_waits_for_test() { + std::lock_guard lock(inbox_mutex_); + return async_stats_.room_waits; + } // Entries kept between executions. Execute only uses the first lists.size(); a larger count is retained storage, // not work the next submission will replay (vk_queue_test checks both halves of that contract). @@ -2673,168 +3092,318 @@ class VulkanQueue : private QueueHolds::Holder { bool update_tiles(ResourceId id, std::span regions, std::span ranges, GetHeap&& get_heap) { flush_async(); // after the calls queued before it (LEONIDA_SUBMIT_ASYNC) - std::lock_guard state(state_mutex_); // outermost: held batches are released from other threads - std::unique_lock lock(context_.resource_mutex_); - const auto it = context_.sparse_resources_.find(id); - if (it == context_.sparse_resources_.end()) return false; - const auto& sparse = it->second; - for (const auto& region : regions) - if (!valid_tiles(*sparse, region)) return false; - const auto heap = get_heap(sparse->image != VK_NULL_HANDLE, sparse->memory_types); - - std::map changes; - std::size_t region_index = 0; - std::uint64_t consumed = 0; - for (const auto& range : ranges) { - const bool backed = range.mode == TileRangeMode::sequential || range.mode == TileRangeMode::reuse; - const std::uint64_t heap_count = heap ? heap->size / tile_size_in_bytes : 0; - const std::uint64_t required = range.mode == TileRangeMode::reuse ? 1 : range.count; - if (backed && (!heap || range.first > heap_count || required > heap_count - range.first)) return false; - for (std::uint64_t i = 0; i < range.count;) { - if (region_index == regions.size()) return false; - const auto& region = regions[region_index]; - const auto count = std::min(range.count - i, region.count - consumed); - const auto first = region.first + consumed; - if (range.mode == TileRangeMode::unmap) { - const auto end = first + count; - for (auto old = sparse->mapped.lower_bound(first); old != sparse->mapped.end() && old->first < end; ++old) - changes[old->first] = {}; - for (auto change = changes.lower_bound(first); change != changes.end() && change->first < end; ++change) - change->second = {}; - } else if (backed) { - for (std::uint64_t j = 0; j < count; ++j) { - const auto page = range.first + (range.mode == TileRangeMode::sequential ? i + j : 0); - changes[first + j] = {heap, heap->offset + page * tile_size_in_bytes}; + bool ok = false; + QueueHolds::WorkGuard work_guard; + std::vector> retired; + { + std::unique_lock state(state_mutex_); + exec_cv_.wait(state, [this] { return !executing_; }); + work_guard.arm(context_.holds()); + executing_ = true; + set_active_seq_locked(context_.holds().next_seq()); + ExecGuard exec_guard{this, state}; + take_waits_to_exec_locked(); + state.unlock(); + + ok = [&]() -> bool { + std::unique_lock lock(context_.resource_mutex_); + const auto it = context_.sparse_resources_.find(id); + if (it == context_.sparse_resources_.end()) return false; + const auto& sparse = it->second; + for (const auto& region : regions) + if (!valid_tiles(*sparse, region)) return false; + const auto heap = get_heap(sparse->image != VK_NULL_HANDLE, sparse->memory_types); + + std::map changes; + std::size_t region_index = 0; + std::uint64_t consumed = 0; + for (const auto& range : ranges) { + const bool backed = range.mode == TileRangeMode::sequential || range.mode == TileRangeMode::reuse; + const std::uint64_t heap_count = heap ? heap->size / tile_size_in_bytes : 0; + const std::uint64_t required = range.mode == TileRangeMode::reuse ? 1 : range.count; + if (backed && (!heap || range.first > heap_count || required > heap_count - range.first)) return false; + for (std::uint64_t i = 0; i < range.count;) { + if (region_index == regions.size()) return false; + const auto& region = regions[region_index]; + const auto count = std::min(range.count - i, region.count - consumed); + const auto first = region.first + consumed; + if (range.mode == TileRangeMode::unmap) { + const auto end = first + count; + for (auto old = sparse->mapped.lower_bound(first); old != sparse->mapped.end() && old->first < end; ++old) + changes[old->first] = {}; + for (auto change = changes.lower_bound(first); change != changes.end() && change->first < end; ++change) + change->second = {}; + } else if (backed) { + for (std::uint64_t j = 0; j < count; ++j) { + const auto page = range.first + (range.mode == TileRangeMode::sequential ? i + j : 0); + changes[first + j] = {heap, heap->offset + page * tile_size_in_bytes}; + } + } + i += count; + consumed += count; + if (consumed == region.count) { + ++region_index; + consumed = 0; + } } } - i += count; - consumed += count; - if (consumed == region.count) { - ++region_index; - consumed = 0; - } - } + return region_index == regions.size() && bind_tiles(id, sparse, changes); + }(); + + state.lock(); + restore_exec_waits_locked(); + flush_exec_pins_locked(retired); + set_active_seq_locked(0); + if (!async_started_.load(std::memory_order_acquire) || t_worker_of_ == this) + drain_held_while_executing(state, retired); + exec_guard.release(); + drain_pins(retired); } - return region_index == regions.size() && bind_tiles(id, sparse, changes); + retired.clear(); + context_.holds().pump_ready(); + return ok; } bool copy_tile_mappings(ResourceId dst, std::span dst_regions, ResourceId src, std::span src_regions) { flush_async(); - std::lock_guard state(state_mutex_); - std::unique_lock lock(context_.resource_mutex_); - const auto source = context_.sparse_resources_.find(src), target = context_.sparse_resources_.find(dst); - if (source == context_.sparse_resources_.end() || target == context_.sparse_resources_.end() || - bool(source->second->image) != bool(target->second->image) || src_regions.size() != dst_regions.size()) - return false; - // Read the complete source mapping before changing any destination slot, including copies within one resource. - std::map changes; - for (std::size_t row = 0; row < src_regions.size(); ++row) { - const auto from = src_regions[row], to = dst_regions[row]; - if (!valid_tiles(*source->second, from) || !valid_tiles(*target->second, to) || from.count != to.count) - return false; - for (std::uint64_t i = 0; i < from.count; ++i) { - const auto page = source->second->mapped.find(from.first + i); - changes.emplace(to.first + i, page == source->second->mapped.end() ? TileMapping{} : page->second); - } + bool ok = false; + QueueHolds::WorkGuard work_guard; + std::vector> retired; + { + std::unique_lock state(state_mutex_); + exec_cv_.wait(state, [this] { return !executing_; }); + work_guard.arm(context_.holds()); + executing_ = true; + set_active_seq_locked(context_.holds().next_seq()); + ExecGuard exec_guard{this, state}; + take_waits_to_exec_locked(); + state.unlock(); + + ok = [&]() -> bool { + std::unique_lock lock(context_.resource_mutex_); + const auto source = context_.sparse_resources_.find(src), target = context_.sparse_resources_.find(dst); + if (source == context_.sparse_resources_.end() || target == context_.sparse_resources_.end() || + bool(source->second->image) != bool(target->second->image) || src_regions.size() != dst_regions.size()) + return false; + // Read the complete source mapping before changing any destination slot, including copies within one resource. + std::map changes; + for (std::size_t row = 0; row < src_regions.size(); ++row) { + const auto from = src_regions[row], to = dst_regions[row]; + if (!valid_tiles(*source->second, from) || !valid_tiles(*target->second, to) || from.count != to.count) + return false; + for (std::uint64_t i = 0; i < from.count; ++i) { + const auto page = source->second->mapped.find(from.first + i); + changes.emplace(to.first + i, page == source->second->mapped.end() ? TileMapping{} : page->second); + } + } + return bind_tiles(dst, target->second, changes); + }(); + + state.lock(); + restore_exec_waits_locked(); + flush_exec_pins_locked(retired); + set_active_seq_locked(0); + if (!async_started_.load(std::memory_order_acquire) || t_worker_of_ == this) + drain_held_while_executing(state, retired); + exec_guard.release(); + drain_pins(retired); } - return bind_tiles(dst, target->second, changes); + retired.clear(); + context_.holds().pump_ready(); + return ok; } // ExecuteCommandLists: every list is checked before any is written, so a failure submits nothing and leaves // the layout tracker as it was. Pending Wait()s are attached to this submission. When one of them (or an - // earlier held operation) waits for a fence value no Signal has been submitted for, the lists are copied and - // held instead, and the call succeeds: the batch is replayed by the thread that submits the Signal (or the CPU - // Signal), which is also where its errors are reported (stderr, and take_held_failure()). + // earlier wait-blocked held operation) requires holding, the batch is appended to held_ under state_mutex_ + // without blocking on before_execute_() or replay, and the call succeeds: the batch is replayed in strict FIFO + // order once the wait is satisfied, which is also where its errors are reported (stderr, and take_held_failure()). + // Otherwise, if another thread is currently executing or draining ready held ops, this call waits on exec_cv_ + // (with state_mutex_ unlocked) and runs before_execute_() and execute_now() synchronously before returning. // - // `pin`, called only when the batch is held, returns what has to stay alive until the batch has run: the COM layer - // passes the pipeline states and root signatures the lists named (the application may release them and Reset - // the lists as soon as the call returns). + // `pin`, called only when the batch is held or queued asynchronously, returns what has to stay alive until the + // batch has run: the COM layer passes the pipeline states and root signatures the lists named (the application + // may release them and Reset the lists as soon as the call returns). using PinFn = std::function()>; +private: + // Move-only RAII token for an enqueue-time execute serial (GeometryViews::execute_enqueue / execute_end). + // Lives across inbox_, held_, and coalesced execute_now() submissions, calling on_finish_execute_ only after the + // submission's retire ticket has been recorded (or when a queued/held batch is dropped). + struct EnqueueSerial { + VulkanContext* context; + std::uint64_t value; + EnqueueSerial() noexcept : context(nullptr), value(0) {} + EnqueueSerial(VulkanContext* ctx, std::uint64_t v) noexcept : context(ctx), value(v) {} + EnqueueSerial(EnqueueSerial&& o) noexcept + : context(std::exchange(o.context, nullptr)), value(std::exchange(o.value, 0)) {} + EnqueueSerial& operator=(EnqueueSerial&& o) noexcept { + if (this != &o) { + finish(); + context = std::exchange(o.context, nullptr); + value = std::exchange(o.value, 0); + } + return *this; + } + EnqueueSerial(const EnqueueSerial&) = delete; + EnqueueSerial& operator=(const EnqueueSerial&) = delete; + ~EnqueueSerial() { finish(); } + void finish() noexcept { + if (value && context && context->on_finish_execute_) { + const std::uint64_t v = std::exchange(value, 0); + context->on_finish_execute_(v); + } else { + value = 0; + } + } + }; + + EnqueueSerial make_enqueue_serial() { + return (!skip_before_execute_.load(std::memory_order_acquire) && context_.on_enqueue_execute_) + ? EnqueueSerial(&context_, context_.on_enqueue_execute_()) + : EnqueueSerial{}; + } + +public: ReplayResult execute(std::span lists, const PinFn& pin = {}) { - pipeline_wait::note_submission(); // big compute warm-ups are left to their first use while the title submits + const bool skip_before = skip_before_execute_.load(std::memory_order_acquire); + if (!skip_before) pipeline_wait::note_submission(); // big compute warm-ups are left to their first use while the title submits + const std::uint64_t vis_seq = skip_before ? 0 : context_.next_visibility_seq(); auto* diagnostics = context_.device_fault(); const auto execute_call = diagnostics ? diagnostics->next_execute_call() : 0; + EnqueueSerial enqueue_serial = make_enqueue_serial(); if (async_on()) { // copied and queued: the worker replays it (a failure is reported as a held one's) Call call; call.kind = Call::Kind::execute; call.execute_call = execute_call; + call.visibility_seq = vis_seq; + call.enqueue_serial = std::move(enqueue_serial); call.lists.reserve(lists.size()); - for (const CommandList* list : lists) call.lists.push_back(*list); + for (const CommandList* list : lists) call.lists.push_back(std::make_shared(*list)); if (pin) call.pin = pin(); enqueue(std::move(call)); return ReplayResult::success; } - return execute_sync(lists, pin, execute_call); + return execute_sync(lists, pin, execute_call, std::move(enqueue_serial), vis_seq); } - ReplayResult execute_sync(std::span lists, const PinFn& pin, std::uint64_t execute_call) { - ReplayResult result = ReplayResult::success; - bool held = false; - std::vector> retired; // destroyed after state_mutex_ is released - { - std::lock_guard state(state_mutex_); - if (!must_hold()) { - result = execute_now(lists, execute_call); - } else if (context_.is_device_lost()) { - result = queue_unsupported(__LINE__); - } else { - Deferred op; - op.kind = Deferred::Kind::batch; - op.execute_call = execute_call; - op.lists.reserve(lists.size()); - for (const CommandList* list : lists) op.lists.push_back(*list); - if (pin) op.pins.push_back(pin()); - hold(std::move(op)); - held = true; - } - drain_pins(retired); + // Zero-copy ExecuteCommandLists for immutable closed CommandList snapshots (used by the COM layer so Reset() + // allocates fresh storage only while a submitted snapshot is still in flight, avoiding deep copies on submission). + ReplayResult execute(std::span> lists, const PinFn& pin = {}) { + const bool skip_before = skip_before_execute_.load(std::memory_order_acquire); + if (!skip_before) pipeline_wait::note_submission(); + const std::uint64_t vis_seq = skip_before ? 0 : context_.next_visibility_seq(); + auto* diagnostics = context_.device_fault(); + const auto execute_call = diagnostics ? diagnostics->next_execute_call() : 0; + EnqueueSerial enqueue_serial = make_enqueue_serial(); + if (async_on()) { + Call call; + call.kind = Call::Kind::execute; + call.execute_call = execute_call; + call.visibility_seq = vis_seq; + call.enqueue_serial = std::move(enqueue_serial); + call.lists.assign(lists.begin(), lists.end()); + if (pin) call.pin = pin(); + enqueue(std::move(call)); + return ReplayResult::success; } - retired.clear(); - if (held) context_.holds().pump_ready(); // a Signal may have been submitted since the check - return result; + const CommandList* small_ptrs[16]; + std::vector large_ptrs; + const CommandList* const* ptr_data = nullptr; + if (lists.size() <= 16) { + for (std::size_t i = 0; i < lists.size(); ++i) small_ptrs[i] = lists[i].get(); + ptr_data = small_ptrs; + } else { + large_ptrs.reserve(lists.size()); + for (const auto& list : lists) large_ptrs.push_back(list.get()); + ptr_data = large_ptrs.data(); + } + return execute_sync_impl( + {ptr_data, lists.size()}, pin, execute_call, + [&lists] { return std::vector>(lists.begin(), lists.end()); }, + {}, std::move(enqueue_serial), false, kUnsetEpoch, vis_seq); + } + + ReplayResult execute_sync(std::span lists, const PinFn& pin, std::uint64_t execute_call, + EnqueueSerial enqueue_serial = {}, std::uint64_t vis_seq = 0) { + return execute_sync_impl( + lists, pin, execute_call, + [&lists] { + std::vector> copies; + copies.reserve(lists.size()); + for (const CommandList* list : lists) copies.push_back(std::make_shared(*list)); + return copies; + }, + {}, std::move(enqueue_serial), false, kUnsetEpoch, vis_seq); } // ID3D12CommandQueue::Signal: the fence reaches `value` after all work submitted so far. Held behind earlier - // held operations, so the fence does not run ahead of the work it follows. `pin` (called only when the Signal is - // held) keeps the fence object alive until it has been submitted, as D3D12 does. + // held operations (or an active execution), so the fence does not run ahead of the work it follows. `pin` + // keeps the fence object alive until the submission has completed, as D3D12 does. + // GPU-only queue Signals do NOT bump visibility_seq_ (any CPU writes made prior to ExecuteCommandLists were + // already covered by that execute's visibility_seq; CPU-to-GPU edges are tracked per-fence on Fence::Signal). bool signal(VkSemaphore fence, std::uint64_t value, const PinFn& pin = {}) { if (async_on()) { Call call; call.kind = Call::Kind::signal; call.fence = fence; call.value = value; + call.visibility_seq = 0; if (pin) call.pin = pin(); enqueue(std::move(call)); return true; } - return signal_sync(fence, value, pin); + return signal_sync(fence, value, pin, {}, kUnsetEpoch, 0); } - bool signal_sync(VkSemaphore fence, std::uint64_t value, const PinFn& pin) { + bool signal_sync(VkSemaphore fence, std::uint64_t value, const PinFn& pin, std::shared_ptr async_pin = {}, + std::uint64_t async_present_epoch = kUnsetEpoch, std::uint64_t vis_seq = 0) { bool ok = true; + QueueHolds::WorkGuard work_guard; std::vector> retired; { - std::lock_guard state(state_mutex_); - if (must_hold()) { + std::unique_lock state(state_mutex_); + if (executing_ || must_hold()) { Deferred op; op.kind = Deferred::Kind::signal; + op.present_epoch = async_present_epoch; + op.visibility_seq = vis_seq; op.fence = fence; op.value = value; - if (pin) op.pins.push_back(pin()); + if (async_pin) op.pins.push_back(std::move(async_pin)); + else if (pin) op.pins.push_back(pin()); hold(std::move(op)); } else { - ok = submit(VK_NULL_HANDLE, fence, value); + work_guard.arm(context_.holds()); + executing_ = true; + set_active_seq_locked(async_seq_ ? async_seq_ : context_.holds().next_seq()); + ExecGuard exec_guard{this, state}; + take_waits_to_exec_locked(); + state.unlock(); + + ok = submit(VK_NULL_HANDLE, fence, value, nullptr, vis_seq); // As for a held Signal (release_held): the fence object, and so its semaphore, stays alive until the // GPU has run the signal. Destroying a semaphore a pending submission signals is undefined // (VUID-vkDestroySemaphore-semaphore-05149), and a title may release a fence right after Signal. - if (ok && pin) pin_queue_.push_back({submitted_, pin()}); + if (ok) { + std::shared_ptr keep = async_pin ? std::move(async_pin) : (pin ? pin() : nullptr); + if (keep) exec_ticketed_pins_.push_back({submitted_, std::move(keep)}); + } else if (async_pin) { + exec_retired_pins_.push_back(std::move(async_pin)); + } + + state.lock(); + restore_exec_waits_locked(); + flush_exec_pins_locked(retired); + set_active_seq_locked(0); + drain_held_while_executing(state, retired); + exec_guard.release(); } drain_pins(retired); } retired.clear(); - context_.holds().pump_ready(); // this Signal, or the hold above, may have made a held batch ready + context_.holds().pump_ready(); // this Signal, its active_seq_ completion, or a drain may unblock waiters return ok; } @@ -2848,19 +3417,35 @@ class VulkanQueue : private QueueHolds::Holder { call.fence = fence; call.value = value; if (pin) call.pin = pin(); + context_.note_wait_added(fence, value); enqueue(std::move(call)); return; } wait_sync(fence, value, pin); } - void wait_sync(VkSemaphore fence, std::uint64_t value, const PinFn& pin) { + void wait_sync(VkSemaphore fence, std::uint64_t value, const PinFn& pin, std::shared_ptr async_pin = {}, + bool already_tracked = false) { + std::vector::Wait> replacements; std::vector> retired; // fences whose submission has completed: released unlocked { std::lock_guard state(state_mutex_); - waits_.push_back(fence); - wait_values_.push_back(value); - if (pin) wait_pins_.push_back(pin()); + if (context_.holds().lookup_relay(fence, value, replacements)) { + if (already_tracked) context_.note_wait_removed(fence, value); + if (async_pin) retired.push_back(std::move(async_pin)); + for (auto& rep : replacements) { + context_.note_wait_added(rep.semaphore, rep.value); + waits_.push_back(rep.semaphore); + wait_values_.push_back(rep.value); + if (rep.pin) wait_pins_.push_back(std::move(rep.pin)); + } + } else { + if (!already_tracked) context_.note_wait_added(fence, value); + waits_.push_back(fence); + wait_values_.push_back(value); + if (async_pin) wait_pins_.push_back(std::move(async_pin)); + else if (pin) wait_pins_.push_back(pin()); + } drain_pins(retired); } } @@ -2875,6 +3460,7 @@ class VulkanQueue : private QueueHolds::Holder { // ID3D12CommandQueue::SetMarker/BeginEvent/EndEvent: queue labels, between the submissions around them. An end // with no begin open on this queue is dropped, as Vulkan requires a matching begin. No-ops without the extension. void marker(DebugMarker::Kind kind, const char* label) { + if (!context_.debug_labels()) return; if (async_on()) { Call call; call.kind = Call::Kind::marker; @@ -2886,23 +3472,48 @@ class VulkanQueue : private QueueHolds::Holder { marker_sync(kind, label); } - void marker_sync(DebugMarker::Kind kind, const char* label) { + void marker_sync(DebugMarker::Kind kind, const char* label, std::uint64_t async_present_epoch = kUnsetEpoch) { + if (!context_.debug_labels()) return; + bool ran = false; + QueueHolds::WorkGuard work_guard; std::vector> retired; - std::lock_guard state(state_mutex_); - drain_pins(retired); // destroyed after the lock (reverse declaration order) - if (!held_.empty()) { // behind the held work, so behind it in the queue's labels too - Deferred op; - op.kind = Deferred::Kind::marker; - op.marker_kind = kind; - op.label = label ? label : ""; - hold(std::move(op)); - return; + { + std::unique_lock state(state_mutex_); + if (executing_ || !held_.empty()) { // behind active/held work, so behind it in the queue's labels too + Deferred op; + op.kind = Deferred::Kind::marker; + op.present_epoch = async_present_epoch; + op.marker_kind = kind; + op.label = label ? label : ""; + hold(std::move(op)); + } else { + work_guard.arm(context_.holds()); + executing_ = true; + set_active_seq_locked(async_seq_ ? async_seq_ : context_.holds().next_seq()); + ExecGuard exec_guard{this, state}; + state.unlock(); + + marker_now(kind, label); + + state.lock(); + flush_exec_pins_locked(retired); + set_active_seq_locked(0); + drain_held_while_executing(state, retired); + exec_guard.release(); + ran = true; + } + drain_pins(retired); } - marker_now(kind, label); + retired.clear(); + if (ran) context_.holds().pump_ready(); } bool idle() { flush_async(); + { + std::unique_lock state(state_mutex_); + exec_cv_.wait(state, [this] { return !executing_; }); + } std::lock_guard lock(context_.submit_mutex()); const SubmitMutex::SubmitTurn turn(context_.submit_mutex(), false); // a queue operation: the compile gate return context_.observe_result(context_.vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle") == VK_SUCCESS; @@ -2912,11 +3523,7 @@ class VulkanQueue : private QueueHolds::Holder { // submit lock, so other queues keep submitting, and without waiting for anything submitted after (review D9; // idle() waits for the whole VkQueue, which D3D12 queues may share, and blocks every submission meanwhile). bool wait_submitted() { - std::uint64_t value = 0; - { - std::lock_guard state(state_mutex_); - value = submitted_; - } + const std::uint64_t value = submitted_gpu_.load(std::memory_order_acquire); if (!value) return true; VkSemaphoreWaitInfo wait{VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO}; wait.semaphoreCount = 1; @@ -2934,8 +3541,8 @@ class VulkanQueue : private QueueHolds::Holder { } private: - // Completed stages, reused by later ARRAY_OF_POINTERS builds. Only execute_now() touches the pool, and it holds - // state_mutex_ (including the deferred/held release paths), so no extra lock is needed. + // Completed stages, reused by later ARRAY_OF_POINTERS builds. Only execute_now() touches the pool, and it is + // serialized by executing_ (without holding state_mutex_), so no extra lock is needed. std::vector khr_stage_pool_; std::vector khr_as_query_pool_; std::vector xdxr_ranges_; // stage_xdxr_table's snapshot, kept for its capacity @@ -3184,35 +3791,416 @@ class VulkanQueue : private QueueHolds::Holder { return ReplayResult::success; } - ReplayResult execute_now(std::span lists, std::uint64_t execute_call) { - { - const submit_phases::Scope waited(submit_phases::wait_room); - if (context_.is_device_lost() || !wait_for_room()) return queue_unsupported(__LINE__); + struct PendingSignal { + VkSemaphore fence = VK_NULL_HANDLE; + std::uint64_t value = 0; + std::uint64_t visibility_seq = 0; + }; + + struct Depth24Guard { + Depth24Converter* d24 = nullptr; + VkSemaphore progress = VK_NULL_HANDLE; + bool active = false; + ~Depth24Guard() { + if (active && d24) d24->retire(progress, 0); } - if (context_.before_execute_) context_.before_execute_(); - struct AfterExecute { - VulkanContext& context; - ~AfterExecute() { - if (context.after_execute_) context.after_execute_(); - } - } after_execute{context_}; - // The rest of this call is the replay phase; the submission is counted when it returns, however it returns. - struct Replayed { - std::int64_t start = submit_phases::now_ns(); - ~Replayed() { - submit_phases::add(submit_phases::replay, std::uint64_t(submit_phases::now_ns() - start)); - submit_phases::submitted(); + }; + struct ScratchGuard { + ScratchBuffers* scratch = nullptr; + VkSemaphore progress = VK_NULL_HANDLE; + bool active = false; + ~ScratchGuard() { + if (active && scratch) scratch->retire(progress, 0); + } + }; + + // Maximum CPU Fence::Signal visibility epoch among this submission's explicit user waits (0 if none waited on a + // CPU-signaled fence). + std::uint64_t exec_waits_vis_seq() const { + std::uint64_t max_seq = 0; + const std::size_t n = (std::min)(exec_user_wait_count_, exec_waits_.size()); + for (std::size_t i = 0; i < n; ++i) { + const std::uint64_t s = context_.holds().signaled_vis_seq(exec_waits_[i], exec_wait_values_[i]); + if (s > max_seq) max_seq = s; + } + return max_seq; + } + + // Rebuilds cached_replay_ from context_.replay_ only when context_.replay_version() changes (typically once per + // queue lifetime), avoiding copying 27 std::functions and allocating helper lambdas on every execute_now(). + // Caller holds shared resource_mutex_. + void ensure_cached_replay_locked(bool transfer_only, bool can_resolve_occlusion) { + const std::uint64_t ver = context_.replay_version(); + if (cached_replay_version_ == ver) return; + cached_replay_ = context_.replay_; + cached_replay_on_buffer_write_ = cached_replay_.on_buffer_write; + cached_replay_on_buffer_write_ctx_ = cached_replay_.on_buffer_write_context; + if (context_.geometry_provider_) { + cached_replay_.title_memory = [this](std::uint64_t va, std::uint64_t bytes, VkBuffer& buffer, + VkDeviceSize& offset) { + if (!va || !bytes || bytes > UINT64_MAX - va) return false; + for (const auto& upload : geometry_uploads_) { + if (va < upload.source || va - upload.source > upload.size || + bytes > upload.size - (va - upload.source)) + continue; + buffer = upload.buffer; + offset = upload.offset + (va - upload.source); + return true; + } + VulkanContext::GeometryUpload upload; + if (!context_.geometry_provider_(va, bytes, upload)) return false; + buffer = upload.buffer; + offset = upload.offset; + geometry_uploads_.push_back(std::move(upload)); + return true; + }; + } + cached_replay_.graphics_family = family_ == context_.graphics_family_; + cached_replay_.queue_stages = kind_ == QueueKind::copy ? detail::queue_stages_copy + : kind_ == QueueKind::compute ? detail::queue_stages_compute + : 0; + cached_replay_.prepare_khr_instances = [this](const BuildAccelerationStructure& build, + VkDeviceAddress& address) { + return stage_khr_instances(cached_replay_, build, *exec_replay_state_.khr_stages, address); + }; + cached_replay_.prepare_xdxr_table = [this](VkDeviceAddress& address, std::uint32_t& count) { + return stage_xdxr_table(*exec_replay_state_.khr_stages, address, count); + }; + if (cached_replay_.write_acceleration_structures_properties) { + cached_replay_.prepare_khr_postbuild = [this](std::uint32_t count, VkQueryPool& pool, + std::uint32_t& first) { + return allocate_khr_as_queries(count, *exec_replay_state_.khr_as_queries, pool, first); + }; + } + if (kind_ != QueueKind::copy && context_.predicate_reducer_ && family_ == context_.predicate_family_) { + cached_replay_.prepare_predicate = [this](VkBuffer buffer, VkDeviceSize offset, PredicateCapture& out) { + return (*exec_replay_state_.pred_batch)->prepare(buffer, offset, out); + }; + cached_replay_.capture_predicate = [this](VkCommandBuffer cb, const PredicateCapture& p) { + context_.predicate_reducer_->capture(cb, p); + }; + if (context_.predicated_copier_) { + cached_replay_.prepare_predicated_copy = [this](VkBuffer source, VkBuffer destination, VkDeviceSize src, + VkDeviceSize dst, VkDeviceSize size, + std::vector& out) { + return (*exec_replay_state_.copy_batch)->prepare(source, destination, src, dst, size, out); + }; + cached_replay_.emit_predicated_copy = [this](VkCommandBuffer cb, + const std::vector& jobs) { + context_.predicated_copier_->emit(cb, jobs); + }; } - } replayed; - if (context_.input_probe_) - context_.input_probe_(lists, execute_call, kind_ == QueueKind::direct ? "direct" : - kind_ == QueueKind::compute ? "compute" : "copy"); - if (kind_ != QueueKind::direct) - for (const auto* list : lists) - for (const auto& command : list->commands()) - if (std::holds_alternative(command) || - std::holds_alternative(command)) - return queue_unsupported(__LINE__); + } + if (context_.scratch_) { + cached_replay_.copy_scratch = [this](VkDeviceSize bytes, VkBuffer& buffer, VkDeviceSize& offset) { + auto& tlock = *exec_replay_state_.tracker_lock; + if (!tlock.owns_lock()) submit_phases::lock_timed(tlock); + auto& guard = *exec_replay_state_.scratch_guard; + if (!guard.active) { + guard.scratch = context_.scratch_.get(); + context_.scratch_->collect(); + guard.active = true; + } + return context_.scratch_->get(bytes, buffer, offset); + }; + } + if (kind_ != QueueKind::copy && context_.indirect_clamp_) { + // IndirectArgumentClamp manages its own internal locks and per-Batch scratch chunks: prepare() runs + // concurrently across queues without acquiring context_.tracker_mutex_. + cached_replay_.prepare_indirect_clamp = [this](VkBuffer arguments, VkDeviceSize argument_offset, + VkBuffer count, VkDeviceSize count_offset, + std::uint32_t kind, std::uint32_t stride, + std::uint32_t max_count, ClampedIndirect& out) { + auto& cb = *exec_replay_state_.clamp_batch; + if (!cb) cb = context_.indirect_clamp_->batch(); + return cb->prepare(arguments, argument_offset, count, count_offset, kind, stride, max_count, out); + }; + } + if (kind_ != QueueKind::copy && context_.counted_dispatch_) { + cached_replay_.prepare_counted_dispatch = [this](VkBuffer args, VkDeviceSize args_offset, VkBuffer count, + VkDeviceSize count_offset, std::uint32_t stride, + std::uint32_t maximum, CountedDispatch& out) { + auto& tlock = *exec_replay_state_.tracker_lock; + if (!tlock.owns_lock()) submit_phases::lock_timed(tlock); + auto& cb = *exec_replay_state_.counted_batch; + if (!cb) cb = context_.counted_dispatch_->batch(); + return cb->prepare(args, args_offset, count, count_offset, stride, maximum, out); + }; + cached_replay_.emit_counted_dispatch = [this](VkCommandBuffer cb, const CountedDispatch& job) { + context_.counted_dispatch_->emit(cb, job); + }; + } + if (kind_ != QueueKind::copy && context_.quad_indices_ && context_.scratch_) { + cached_replay_.prepare_quad_indices = [this](VkBuffer indices, VkDeviceSize offset, VkIndexType type, + std::uint64_t readable, std::uint32_t quads, VkBuffer scratch, + VkDeviceSize scratch_offset, QuadIndexExpansion& out) { + auto& tlock = *exec_replay_state_.tracker_lock; + if (!tlock.owns_lock()) submit_phases::lock_timed(tlock); + return context_.quad_indices_->prepare(indices, offset, type, readable, quads, scratch, scratch_offset, + out); + }; + cached_replay_.emit_quad_indices = [this](VkCommandBuffer cb, const QuadIndexExpansion& job) { + context_.quad_indices_->emit(cb, job); + }; + } + if (context_.depth24_ && !transfer_only) { + cached_replay_.depth24_prepare = [this](Depth24Job& job, std::vector& parts) { + auto& tlock = *exec_replay_state_.tracker_lock; + if (!tlock.owns_lock()) submit_phases::lock_timed(tlock); + auto& guard = *exec_replay_state_.depth24_guard; + if (!guard.active) { + guard.d24 = context_.depth24_.get(); + context_.depth24_->collect(); + guard.active = true; + } + return context_.depth24_->prepare(job, parts); + }; + } + if (can_resolve_occlusion) { + cached_replay_.sum_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, + std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { + occlusion_resolve_->sum(cb, pool, first, count, dst, offset); + }; + cached_replay_.resolve_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, + std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { + occlusion_resolve_->normalize(cb, pool, first, count, dst, offset); + }; + cached_replay_.sum_statistics = [this](VkCommandBuffer cb, VkQueryPool pool, VkQueryPool mesh_pool, + VkQueryPool primitives_pool, const std::uint8_t* mesh, + std::uint32_t first, std::uint32_t count, VkBuffer dst, + VkDeviceSize offset) { + occlusion_resolve_->sum_statistics(cb, pool, mesh_pool, primitives_pool, mesh, first, count, dst, + offset); + }; + cached_replay_.sum_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, + std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { + occlusion_resolve_->sum_binary(cb, pool, first, count, dst, offset); + }; + } + const auto& events = context_.vk; + if (context_.order_timestamp_copies() && events.vkCreateEvent && events.vkDestroyEvent && events.vkResetEvent && + events.vkCmdSetEvent && events.vkCmdWaitEvents) { + cached_replay_.order_timestamp_copy = [this](VkCommandBuffer cb) { + const VkEvent event = take_event(); + if (!event) return; + exec_replay_state_.slot->events.push_back(event); + const auto& vk = context_.vk; + vk.vkCmdSetEvent(cb, event, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); + vk.vkCmdWaitEvents(cb, 1, &event, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, + VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, nullptr, 0, nullptr, 0, nullptr); + *exec_replay_state_.ordered_timestamps = true; + }; + } + cached_replay_version_ = ver; + } + + ReplayResult execute_now(std::span lists, std::uint64_t execute_call, + std::span batch_breaks = {}, + std::span trailing_signals = {}, + std::uint64_t visibility_seq = 0, bool /*from_held*/ = false) { + const bool skip_before = skip_before_execute_.load(std::memory_order_acquire); + // The "submit frame" line and the floor: this submission from before its first phase to after its last. + std::optional submission; + if (!skip_before) submission.emplace(int(kind_)); + { + std::optional waited; + if (!skip_before) waited.emplace(submit_phases::wait_room); + if (context_.is_device_lost() || !wait_for_room()) return queue_unsupported(__LINE__); + } + std::size_t total_commands = 0; + std::uint64_t captures = 0; + bool runs_shaders = false; + bool has_rt_ds_clear = false; + for (const auto* list : lists) { + if (!list) continue; + const auto& cmds = list->commands(); + total_commands += cmds.size(); + if (list->closed()) { + captures += list->predication_captures(); + runs_shaders = runs_shaders || list->runs_shaders(); + has_rt_ds_clear = has_rt_ds_clear || list->has_rt_ds_clear(); + } else { + for (const auto& command : cmds) { + if (std::holds_alternative(command) || + std::holds_alternative(command)) + has_rt_ds_clear = true; + if (const auto* p = std::get_if(&command); p && p->buffer) ++captures; + runs_shaders |= std::holds_alternative(command) || draw_command(command).state || + std::holds_alternative(command); + } + } + } + if (!skip_before && context_.before_execute_) { + std::uint64_t req_seq = visibility_seq ? visibility_seq : context_.current_visibility_seq(); + const std::uint64_t wait_vis = (std::max)(pending_wait_vis_seq_, exec_waits_vis_seq()); + if (wait_vis > req_seq) req_seq = wait_vis; + struct BeforeSeqGuard { + std::uint64_t prev; + explicit BeforeSeqGuard(std::uint64_t seq) noexcept : prev(VulkanContext::t_before_execute_seq_) { + VulkanContext::t_before_execute_seq_ = seq; + } + ~BeforeSeqGuard() { VulkanContext::t_before_execute_seq_ = prev; } + } before_seq_guard{req_seq}; + context_.before_execute_(); + pending_wait_vis_seq_ = 0; + } + struct AfterExecute { + VulkanContext& context; + bool active; + ~AfterExecute() { + if (active && context.after_execute_) context.after_execute_(); + } + } after_execute{context_, !skip_before}; + // The rest of this call is the replay phase; the submission is counted when it returns, however it returns. + struct Replayed { + bool active; + std::int64_t start; + explicit Replayed(bool a) : active(a), start(a ? submit_phases::now_ns() : 0) {} + ~Replayed() { + if (!active) return; + submit_phases::add(submit_phases::replay, std::uint64_t(submit_phases::now_ns() - start)); + submit_phases::submitted(); + } + } replayed{!skip_before}; + if (!skip_before && context_.input_probe_) + context_.input_probe_(lists, execute_call, kind_ == QueueKind::direct ? "direct" : + kind_ == QueueKind::compute ? "compute" : "copy"); + if (kind_ != QueueKind::direct && has_rt_ds_clear) return queue_unsupported(__LINE__); + const bool transfer_only = family_ == context_.transfer_only_family_; + const bool skip_shader_prep = transfer_only || (skip_before && !runs_shaders); + // Fast path for empty command-list batches (0 commands across all lists, no GPU profiler): skips copying the + // 25-member std::function ReplayFunctions table, constructing per-pass helper lambdas, pipeline_mutex_, + // prepare(), PipelineCompiles, and QueryReplay, while preserving the D3D12 boundary barrier, bindless flushes, + // zero_pending_ fills, prelude recording, cross-queue semaphore waits, and timeline retirement. + if (total_commands == 0 && !gpu_profile::enabled()) { + std::shared_lock resource_lock(context_.resource_mutex_, std::defer_lock); + if (!skip_shader_prep) submit_phases::lock_timed(resource_lock); + std::function empty_bindless_commit = + !skip_shader_prep ? context_.bindless_commit_ : std::function{}; + CommandSlot* slot = acquire(); + if (!slot) return queue_unsupported(__LINE__); + VkCommandBuffer command_buffer = slot->buffer; + const auto discard = [&] { + if (context_.vk.vkResetCommandBuffer(command_buffer, 0) == VK_SUCCESS) slot->ticket = 0; + }; + VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; + begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + context_.gpu_labels_.begin_record(command_buffer); + if (context_.observe_result(context_.vk.vkBeginCommandBuffer(command_buffer, &begin), + "vkBeginCommandBuffer") != VK_SUCCESS) { + discard(); + return queue_unsupported(__LINE__); + } + if (context_.vk.vkCmdPipelineBarrier) { + VkMemoryBarrier full{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + full.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT; + full.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; + context_.vk.vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, + VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1, &full, 0, nullptr, 0, + nullptr); + } + std::unique_lock tracker_lock(context_.tracker_mutex_, std::defer_lock); + submit_phases::lock_timed(tracker_lock); + if (!skip_shader_prep && context_.bindless_prepare_ && !context_.bindless_prepare_(command_buffer)) { + const bool ended = context_.observe_result(context_.vk.vkEndCommandBuffer(command_buffer), + "vkEndCommandBuffer") == VK_SUCCESS; + if (resource_lock.owns_lock()) resource_lock.unlock(); + const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0); + if (!submitted) discard(); + if (empty_bindless_commit) empty_bindless_commit(submitted); + tracker_lock.unlock(); + return queue_unsupported(__LINE__); + } + if (resource_lock.owns_lock()) resource_lock.unlock(); + const bool bindless_uploaded = + !skip_shader_prep && std::exchange(context_.bindless_upload_pending_, false); + auto& zero_buffers = zero_buffers_scratch_; + zero_buffers.clear(); + { + std::lock_guard lock(context_.storage_mutex_); + if (context_.storage_init_semaphore_ && context_.storage_init_semaphore_ != progress_ && + context_.storage_init_version_ != storage_init_seen_) { + exec_waits_.push_back(context_.storage_init_semaphore_); + exec_wait_values_.push_back(context_.storage_init_value_); + storage_init_seen_ = context_.storage_init_version_; + } + if (!skip_shader_prep) { + if (context_.bindless_upload_semaphore_ && context_.bindless_upload_semaphore_ != progress_ && + context_.bindless_upload_version_ != bindless_upload_seen_) { + exec_waits_.push_back(context_.bindless_upload_semaphore_); + exec_wait_values_.push_back(context_.bindless_upload_value_); + } + bindless_upload_seen_ = context_.bindless_upload_version_; + } + zero_buffers.swap(context_.zero_pending_); + } + for (const auto& zero : zero_buffers) + context_.vk.vkCmdFillBuffer(command_buffer, zero.buffer, 0, VK_WHOLE_SIZE, 0); + if (!zero_buffers.empty()) { + VkMemoryBarrier filled{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + filled.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + filled.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; + context_.vk.vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1, &filled, 0, nullptr, 0, + nullptr); + } + const bool prelude = !skip_shader_prep && context_.prelude_record_ && context_.prelude_record_(command_buffer); + static const bool cross_wait_empty = [] { + const char* v = std::getenv("LEONIDA_PRELUDE_QUEUE_WAIT"); + return !(v && v[0] == '0' && v[1] == 0); + }(); + if (!skip_shader_prep) { + std::lock_guard lock(context_.storage_mutex_); + if (cross_wait_empty && context_.prelude_semaphore_ && context_.prelude_semaphore_ != progress_ && + context_.prelude_version_ != prelude_seen_) { + exec_waits_.push_back(context_.prelude_semaphore_); + exec_wait_values_.push_back(context_.prelude_value_); + } + prelude_seen_ = context_.prelude_version_; + } + CheckpointSubmission diagnostics; + if (execute_call) { + const char* queue_kind = kind_ == QueueKind::direct ? "direct" : + kind_ == QueueKind::compute ? "compute" : "copy"; + diagnostics = context_.device_fault()->begin_submission(execute_call, queue_, queue_kind, lists.size()); + } + const bool ended = context_.observe_result(context_.vk.vkEndCommandBuffer(command_buffer), + "vkEndCommandBuffer") == VK_SUCCESS; + const bool submitted = ended && submit_multi(command_buffer, trailing_signals, + execute_call ? &diagnostics : nullptr); + if (!submitted && !zero_buffers.empty()) { + std::lock_guard lock(context_.storage_mutex_); + context_.zero_pending_.insert(context_.zero_pending_.end(), zero_buffers.begin(), zero_buffers.end()); + } + if (submitted && !zero_buffers.empty()) { + std::lock_guard lock(context_.storage_mutex_); + context_.storage_init_semaphore_ = progress_; + context_.storage_init_value_ = submitted_; + ++context_.storage_init_version_; + storage_init_seen_ = context_.storage_init_version_; + } + if (submitted && bindless_uploaded) { + std::lock_guard lock(context_.storage_mutex_); + context_.bindless_upload_semaphore_ = progress_; + context_.bindless_upload_value_ = submitted_; + ++context_.bindless_upload_version_; + bindless_upload_seen_ = context_.bindless_upload_version_; + } + if (prelude) { + if (submitted) { + std::lock_guard lock(context_.storage_mutex_); + context_.prelude_semaphore_ = progress_; + context_.prelude_value_ = submitted_; + ++context_.prelude_version_; + prelude_seen_ = context_.prelude_version_; + } + if (context_.prelude_commit_) context_.prelude_commit_(submitted, context_.submitted_retire_ticket()); + } + if (!submitted) discard(); + if (empty_bindless_commit) empty_bindless_commit(submitted); + tracker_lock.unlock(); + return submitted ? ReplayResult::success : queue_unsupported(__LINE__); + } VkCommandBuffer command_buffer = VK_NULL_HANDLE; struct KhrGuard { VulkanQueue* queue; @@ -3224,43 +4212,22 @@ class VulkanQueue : private QueueHolds::Holder { } } khr_guard{this}; std::function bindless_commit; - // Lock hierarchy: state_mutex_ -> pipeline_mutex_ -> resource_mutex_ -> tracker_mutex_ -> submit_mutex_. + // Lock hierarchy: executing_ (serializes this queue without holding state_mutex_) -> pipeline_mutex_ -> + // resource_mutex_ -> tracker_mutex_ -> submit_mutex_. // Shared pipeline_lock keeps registered pipelines, pipeline_names, and pipeline_workers_ alive across // preparation, compilation, and emit. Shared resource_lock allows concurrent prepare() across queues and is // released while unbuilt pipelines compile so add_resource()/remove_resource() never stall behind shader // compiles; tracker_mutex_ is acquired lazily during prepare() only if a list uses a shared helper, and // otherwise right before bindless_prepare_/emit() through submit() so bindless flushes, layout emits, and // submissions stay in order. - std::shared_lock pipeline_lock(context_.pipeline_mutex_); + std::shared_lock pipeline_lock(context_.pipeline_mutex_, std::defer_lock); + submit_phases::lock_timed(pipeline_lock); std::shared_lock resource_lock(context_.resource_mutex_, std::defer_lock); std::unique_lock tracker_lock(context_.tracker_mutex_, std::defer_lock); // Declared after tracker_lock so any early return after depth24_->prepare() retires uncommitted scratch/pools // with ticket 0 while tracker_lock is still held. - struct Depth24Guard { - Depth24Converter* d24 = nullptr; - VkSemaphore progress = VK_NULL_HANDLE; - bool active = false; - ~Depth24Guard() { - if (active && d24) d24->retire(progress, 0); - } - } depth24_guard{nullptr, progress_, false}; - struct ScratchGuard { // the same for the copy scratch - ScratchBuffers* scratch = nullptr; - VkSemaphore progress = VK_NULL_HANDLE; - bool active = false; - ~ScratchGuard() { - if (active && scratch) scratch->retire(progress, 0); - } - } scratch_guard{nullptr, progress_, false}; - struct ClampGuard { // and for the ExecuteIndirect clamp's record scratch - IndirectArgumentClamp* clamp = nullptr; - VkSemaphore progress = VK_NULL_HANDLE; - bool active = false; - ~ClampGuard() { - if (active && clamp) clamp->retire(progress, 0); - } - } clamp_guard{nullptr, progress_, false}; - const bool transfer_only = family_ == context_.transfer_only_family_; + Depth24Guard depth24_guard{nullptr, progress_, false}; + ScratchGuard scratch_guard{nullptr, progress_, false}; // Kept between executions: prepare refills each list's entries in the storage the last execution left, where // making them fresh for every command was about half the layer's CPU cost per command (replay_cpu_bench). auto& prepared = prepared_; @@ -3268,180 +4235,82 @@ class VulkanQueue : private QueueHolds::Holder { // a queue that sees 8 lists and then 1 in every frame would rebuild them on each execution. The loops below // use only the first lists.size() entries, so stale entries are never prepared, queried or emitted. if (prepared.size() < lists.size()) prepared.resize(lists.size()); - ReplayFunctions replay{}; unsigned mesh_draws = 0; - std::vector geometry; - std::uint64_t captures = 0; - for (const auto* list : lists) - for (const auto& command : list->commands()) - if (const auto* p = std::get_if(&command); p && p->buffer) ++captures; + auto& geometry = geometry_uploads_; + geometry.clear(); std::unique_ptr batch; std::unique_ptr copy_batch; std::unique_ptr counted_batch; std::unique_ptr clamp_batch; + bool ordered_timestamps = false; + exec_replay_state_ = {&tracker_lock, &khr_guard.stages, &khr_guard.as_queries, &batch, ©_batch, + &counted_batch, &clamp_batch, &depth24_guard, &scratch_guard, nullptr, + &ordered_timestamps}; + struct ExecReplayStateGuard { + VulkanQueue* q; + ~ExecReplayStateGuard() { + q->exec_replay_state_ = {}; + q->cached_replay_.compiles = nullptr; + q->cached_replay_.mesh_draw_count = nullptr; + q->cached_replay_.bindless_set = VK_NULL_HANDLE; + q->cached_replay_.gpu_profile = nullptr; + q->cached_replay_.on_buffer_write = q->cached_replay_on_buffer_write_; + q->cached_replay_.on_buffer_write_context = q->cached_replay_on_buffer_write_ctx_; + } + } exec_replay_guard{this}; const auto& occlusion_memory = context_.occlusion_resolve_memory_; const bool can_resolve_occlusion = occlusion_memory.memoryTypeCount != 0; const auto resolve = [this](ResourceId id) { return context_.resolve(id); }; std::uint32_t segments = 0, statistics_segments = 0; bool has_queries = false; + const bool has_parallel_compiler = bool(context_.batch_compile_runner_) || bool(context_.pipeline_workers_); const auto run_compiles = [this](std::size_t count, const std::function& job) { - context_.pipeline_workers_->run(count, job); + if (context_.batch_compile_runner_) context_.batch_compile_runner_(count, job); + else context_.pipeline_workers_->run(count, job); }; PipelineCompiles prior_compiles; bool has_prior_compiles = false; + // Fast pre-pass before acquiring resource_mutex_ or running prepare(): collect all unique unbuilt synchronous + // graphics (pipeline, unbound_mask) and compute pipelines across the batch and compile them concurrently so + // prepare() completes in one pass with zero wasted transient allocations or skipped draws. Skipped in O(1) on + // warm runs when no unbuilt synchronous pipelines remain (pass-0 prepare() below remains as a safe fallback). + if (has_parallel_compiler && runs_shaders && context_.has_unbuilt_sync_pipelines()) { + const std::uint64_t gen_before = context_.sync_pipeline_gen(); + PipelineCompiles pre_compiles; + collect_unbuilt_pipelines(lists, context_.replay_, pre_compiles); + if (!pre_compiles.empty()) { + submit_phases::note_change(submit_phases::change_pipelines); + std::shared_ptr demand; + if (context_.large_compile_demand_ && pre_compiles.any_large()) demand = context_.large_compile_demand_(); + pre_compiles.build(run_compiles, context_.large_compile_budget_); + demand.reset(); + context_.note_sync_pipelines_built(pre_compiles.size()); + prior_compiles = std::move(pre_compiles); + has_prior_compiles = true; + } else { + context_.note_empty_pipeline_scan(gen_before); + } + } for (int pass = 0;; ++pass) { - resource_lock.lock(); - bindless_commit = !transfer_only ? context_.bindless_commit_ : std::function{}; - replay = context_.replay_; + submit_phases::lock_timed(resource_lock); + bindless_commit = !skip_shader_prep ? context_.bindless_commit_ : std::function{}; + ensure_cached_replay_locked(transfer_only, can_resolve_occlusion); + ReplayFunctions& replay = cached_replay_; mesh_draws = 0; - if (pipeline_profile::enabled()) replay.mesh_draw_count = &mesh_draws; - if (context_.geometry_provider_) { - replay.title_memory = [&](std::uint64_t va, std::uint64_t bytes, VkBuffer& buffer, VkDeviceSize& offset) { - if (!va || !bytes || bytes>UINT64_MAX-va) return false; - for (const auto& upload : geometry) { - if (va < upload.source || va-upload.source > upload.size || bytes > upload.size-(va-upload.source)) continue; - buffer=upload.buffer; offset=upload.offset+(va-upload.source); - return true; - } - VulkanContext::GeometryUpload upload; - if (!context_.geometry_provider_(va,bytes,upload)) return false; - buffer=upload.buffer;offset=upload.offset; - geometry.push_back(std::move(upload)); - return true; - }; - } - replay.graphics_family = family_ == context_.graphics_family_; - replay.queue_stages = kind_ == QueueKind::copy ? detail::queue_stages_copy - : kind_ == QueueKind::compute ? detail::queue_stages_compute - : 0; - replay.prepare_khr_instances = [this, &replay, &khr_guard](const BuildAccelerationStructure& build, - VkDeviceAddress& address) { - return stage_khr_instances(replay, build, khr_guard.stages, address); - }; - replay.prepare_xdxr_table = [this, &khr_guard](VkDeviceAddress& address, std::uint32_t& count) { - return stage_xdxr_table(khr_guard.stages, address, count); - }; - if (replay.write_acceleration_structures_properties) { - replay.prepare_khr_postbuild = [this, &khr_guard](std::uint32_t count, VkQueryPool& pool, - std::uint32_t& first) { - return allocate_khr_as_queries(count, khr_guard.as_queries, pool, first); - }; - } + replay.mesh_draw_count = pipeline_profile::enabled() ? &mesh_draws : nullptr; + replay.bindless_set = VK_NULL_HANDLE; + replay.gpu_profile = nullptr; + replay.on_buffer_write = cached_replay_on_buffer_write_; + replay.on_buffer_write_context = cached_replay_on_buffer_write_ctx_; if (captures) { if (kind_ == QueueKind::copy || !context_.predicate_reducer_ || family_ != context_.predicate_family_) return queue_unsupported(__LINE__); // The helper's lazy pipeline is shared by queues. Serialize preparation with the tracker lock, // retaining pipeline -> resource -> tracker -> submit lock order through emit and submission. - if (!tracker_lock.owns_lock()) tracker_lock.lock(); + if (!tracker_lock.owns_lock()) submit_phases::lock_timed(tracker_lock); batch = context_.predicate_reducer_->batch(captures); if (!batch) return queue_unsupported(__LINE__); - replay.prepare_predicate = [&](VkBuffer buffer, VkDeviceSize offset, PredicateCapture& out) { - return batch->prepare(buffer, offset, out); - }; - replay.capture_predicate = [&](VkCommandBuffer cb, const PredicateCapture& p) { - context_.predicate_reducer_->capture(cb, p); - }; - if (context_.predicated_copier_) { - copy_batch = context_.predicated_copier_->batch(); - replay.prepare_predicated_copy = [&](VkBuffer source, VkBuffer destination, VkDeviceSize src, - VkDeviceSize dst, VkDeviceSize size, - std::vector& out) { - return copy_batch->prepare(source, destination, src, dst, size, out); - }; - replay.emit_predicated_copy = [&](VkCommandBuffer cb, const std::vector& jobs) { - context_.predicated_copier_->emit(cb, jobs); - }; - } - } - if (context_.scratch_) { - replay.copy_scratch = [this, &tracker_lock, &scratch_guard](VkDeviceSize bytes, VkBuffer& buffer, - VkDeviceSize& offset) { - if (!tracker_lock.owns_lock()) tracker_lock.lock(); - if (!scratch_guard.active) { - scratch_guard.scratch = context_.scratch_.get(); - context_.scratch_->collect(); - scratch_guard.active = true; - } - return context_.scratch_->get(bytes, buffer, offset); - }; - } - if (kind_ != QueueKind::copy && context_.indirect_clamp_) { - // The record scratch belongs to this submission: collected here, retired below with its ticket. The - // counter slots are read back once that ticket completes (the batch's destructor). - replay.prepare_indirect_clamp = [this, &tracker_lock, &clamp_batch, &clamp_guard]( - VkBuffer arguments, VkDeviceSize argument_offset, VkBuffer count, - VkDeviceSize count_offset, std::uint32_t kind, std::uint32_t stride, - std::uint32_t max_count, ClampedIndirect& out) { - // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation. - if (!tracker_lock.owns_lock()) tracker_lock.lock(); - if (!clamp_batch) clamp_batch = context_.indirect_clamp_->batch(); - if (!clamp_guard.active) { - clamp_guard.clamp = context_.indirect_clamp_.get(); - context_.indirect_clamp_->collect(); - clamp_guard.active = true; - } - return clamp_batch->prepare(arguments, argument_offset, count, count_offset, kind, stride, - max_count, out); - }; - } - if (kind_ != QueueKind::copy && context_.counted_dispatch_) { - replay.prepare_counted_dispatch = [this, &tracker_lock, &counted_batch]( - VkBuffer args, VkDeviceSize args_offset, VkBuffer count, VkDeviceSize count_offset, - std::uint32_t stride, std::uint32_t maximum, CountedDispatch& out) { - // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation. - if (!tracker_lock.owns_lock()) tracker_lock.lock(); - if (!counted_batch) counted_batch = context_.counted_dispatch_->batch(); - return counted_batch->prepare(args, args_offset, count, count_offset, stride, maximum, out); - }; - replay.emit_counted_dispatch = [this](VkCommandBuffer cb, const CountedDispatch& job) { - context_.counted_dispatch_->emit(cb, job); - }; - } - if (kind_ != QueueKind::copy && context_.quad_indices_ && context_.scratch_) { - replay.prepare_quad_indices = [this, &tracker_lock]( - VkBuffer indices, VkDeviceSize offset, VkIndexType type, std::uint64_t readable, std::uint32_t quads, - VkBuffer scratch, VkDeviceSize scratch_offset, QuadIndexExpansion& out) { - // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation. - if (!tracker_lock.owns_lock()) tracker_lock.lock(); - return context_.quad_indices_->prepare(indices, offset, type, readable, quads, scratch, - scratch_offset, out); - }; - replay.emit_quad_indices = [this](VkCommandBuffer cb, const QuadIndexExpansion& job) { - context_.quad_indices_->emit(cb, job); - }; - } - if (context_.depth24_ && !transfer_only) { - replay.depth24_prepare = [this, &tracker_lock, &depth24_guard](Depth24Job& job, - std::vector& parts) { - if (!tracker_lock.owns_lock()) tracker_lock.lock(); - if (!depth24_guard.active) { - depth24_guard.d24 = context_.depth24_.get(); - context_.depth24_->collect(); - depth24_guard.active = true; - } - return context_.depth24_->prepare(job, parts); - }; - } - if (can_resolve_occlusion) { - replay.sum_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, - std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { - occlusion_resolve_->sum(cb, pool, first, count, dst, offset); - }; - replay.resolve_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, - std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { - occlusion_resolve_->normalize(cb, pool, first, count, dst, offset); - }; - replay.sum_statistics = [this](VkCommandBuffer cb, VkQueryPool pool, VkQueryPool mesh_pool, - VkQueryPool primitives_pool, const std::uint8_t* mesh, - std::uint32_t first, std::uint32_t count, VkBuffer dst, - VkDeviceSize offset) { - occlusion_resolve_->sum_statistics(cb, pool, mesh_pool, primitives_pool, mesh, first, count, dst, - offset); - }; - replay.sum_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, - std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { - occlusion_resolve_->sum_binary(cb, pool, first, count, dst, offset); - }; + if (context_.predicated_copier_) copy_batch = context_.predicated_copier_->batch(); } segments = 0; statistics_segments = 0; @@ -3466,7 +4335,18 @@ class VulkanQueue : private QueueHolds::Holder { statistics_segments += prepared[i].statistics_segment_count; has_queries = has_queries || !prepared[i].queries.empty(); } - if (pass == 0 && !compiles.empty()) { + bool needs_unlock_compile = !compiles.empty(); + if (needs_unlock_compile && has_prior_compiles) { + needs_unlock_compile = false; + for (const PipelineCompiles::Use& u : compiles.uses()) { + if (!prior_compiles.contains_ticket(compiles, u.ticket)) { + needs_unlock_compile = true; + break; + } + } + } + if (pass == 0 && needs_unlock_compile) { + submit_phases::note_change(submit_phases::change_pipelines); // not a floor submission if (depth24_guard.active) { context_.depth24_->retire(progress_, 0); depth24_guard.active = false; @@ -3475,10 +4355,6 @@ class VulkanQueue : private QueueHolds::Holder { context_.scratch_->retire(progress_, 0); scratch_guard.active = false; } - if (clamp_guard.active) { - context_.indirect_clamp_->retire(progress_, 0); - clamp_guard.active = false; - } batch.reset(); copy_batch.reset(); counted_batch.reset(); @@ -3491,27 +4367,29 @@ class VulkanQueue : private QueueHolds::Holder { std::shared_ptr demand; if (context_.large_compile_demand_ && compiles.any_large()) demand = context_.large_compile_demand_(); - if (context_.pipeline_workers_) + if (has_parallel_compiler) compiles.build(run_compiles, context_.large_compile_budget_); else compiles.build_serial(); demand.reset(); const ReplayResult compile_result = check_compiled_pipelines(compiles, prepare_result); if (compile_result != ReplayResult::success) return compile_result; + if (!has_prior_compiles && compiles.size() >= 2) context_.note_unbuilt_sync_pipeline(); prior_compiles = std::move(compiles); has_prior_compiles = true; continue; } const PipelineCompiles* prior = has_prior_compiles ? &prior_compiles : nullptr; - prepare_result = context_.pipeline_workers_ + prepare_result = has_parallel_compiler ? build_pipelines(compiles, std::span(prepared).first(lists.size()), prepare_result, run_compiles, context_.large_compile_budget_, prior) : build_pipelines_serial(compiles, std::span(prepared).first(lists.size()), prepare_result, prior); - replay.compiles = nullptr; + cached_replay_.compiles = nullptr; if (prepare_result != ReplayResult::success) return prepare_result; break; } + ReplayFunctions& replay = cached_replay_; const auto segment_pool = [this](VkQueryType type, std::uint32_t count, std::shared_ptr& out) { const auto& vk = context_.vk; @@ -3533,9 +4411,9 @@ class VulkanQueue : private QueueHolds::Holder { if (statistics_segments && can_resolve_occlusion) { if (!segment_pool(VK_QUERY_TYPE_PIPELINE_STATISTICS, statistics_segments, statistics)) return queue_unsupported(__LINE__); - for (const auto& list : prepared) - statistics->mesh.insert(statistics->mesh.end(), list.statistics_mesh.begin(), - list.statistics_mesh.end()); + for (std::size_t i = 0; i < lists.size(); ++i) + statistics->mesh.insert(statistics->mesh.end(), prepared[i].statistics_mesh.begin(), + prepared[i].statistics_mesh.end()); if (std::find(statistics->mesh.begin(), statistics->mesh.end(), 1) == statistics->mesh.end()) { statistics->mesh.clear(); } else { @@ -3564,7 +4442,7 @@ class VulkanQueue : private QueueHolds::Holder { // QueryReplay::plan() reads QueryPool::ended / occlusion and QueryReplay::commit() writes them after // resource_lock is unlocked. Hold tracker_mutex_ across plan -> emit -> submit -> commit so concurrent queues // see submission-order query state and remove_query_pool() waits until commit finishes. - if (has_queries && !tracker_lock.owns_lock()) tracker_lock.lock(); + if (has_queries && !tracker_lock.owns_lock()) submit_phases::lock_timed(tracker_lock); QueryReplay queries; std::uint32_t base = 0, statistics_base = 0; for (std::size_t i = 0; i < lists.size(); ++i) { @@ -3592,24 +4470,7 @@ class VulkanQueue : private QueueHolds::Holder { slot->khr_as_queries = std::move(khr_guard.as_queries); khr_guard.as_queries.clear(); command_buffer = slot->buffer; - // MoltenVK writes a timestamp at the end of a Metal encoder and resolves it with a blit that nothing orders - // after that write, so a copy in the same or the next command buffer reads the old value (docs section 4.6). - // An event set and waited for in this command buffer orders it after this submission's timestamps; a wait for - // this queue's previous submission orders it after earlier ones still running. - bool ordered_timestamps = false; - const auto& events = context_.vk; - if (context_.order_timestamp_copies() && events.vkCreateEvent && events.vkDestroyEvent && events.vkResetEvent && - events.vkCmdSetEvent && events.vkCmdWaitEvents) - replay.order_timestamp_copy = [this, slot, &ordered_timestamps](VkCommandBuffer cb) { - const VkEvent event = take_event(); - if (!event) return; - slot->events.push_back(event); - const auto& vk = context_.vk; - vk.vkCmdSetEvent(cb, event, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); - vk.vkCmdWaitEvents(cb, 1, &event, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, nullptr, 0, nullptr, 0, nullptr); - ordered_timestamps = true; - }; + exec_replay_state_.slot = slot; const auto discard = [&] { if (context_.vk.vkResetCommandBuffer(command_buffer, 0) == VK_SUCCESS) slot->ticket = 0; }; @@ -3633,8 +4494,8 @@ class VulkanQueue : private QueueHolds::Holder { context_.vk.vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1, &full, 0, nullptr, 0, nullptr); } - if (!tracker_lock.owns_lock()) tracker_lock.lock(); - if (!transfer_only && context_.bindless_prepare_ && !context_.bindless_prepare_(command_buffer)) { + if (!tracker_lock.owns_lock()) submit_phases::lock_timed(tracker_lock); + if (!skip_shader_prep && context_.bindless_prepare_ && !context_.bindless_prepare_(command_buffer)) { const bool ended = context_.observe_result(context_.vk.vkEndCommandBuffer(command_buffer), "vkEndCommandBuffer") == VK_SUCCESS; resource_lock.unlock(); @@ -3649,16 +4510,24 @@ class VulkanQueue : private QueueHolds::Holder { context_.scratch_->retire(progress_, 0); scratch_guard.active = false; } - if (clamp_guard.active) { - context_.indirect_clamp_->retire(progress_, 0); - clamp_guard.active = false; - } if (bindless_commit) bindless_commit(submitted); tracker_lock.unlock(); return queue_unsupported(__LINE__); } - replay.bindless_set = context_.bindless_current_ ? context_.bindless_current_() : VK_NULL_HANDLE; - const bool bindless_uploaded = std::exchange(context_.bindless_upload_pending_, false); + replay.bindless_set = + (!skip_shader_prep && context_.bindless_current_) ? context_.bindless_current_() : VK_NULL_HANDLE; + // LEONIDA_GPU_PROFILE=1: the submission's query pool is reset and its first timestamp written here, after the + // failure path above (which submits the buffer without a recording); dropped unless the buffer is submitted. + std::unique_ptr profile; + if (gpu_profile::enabled()) { + std::size_t commands = 0; + for (const CommandList* list : lists) commands += list->commands().size(); + profile = context_.gpu_profile_.begin(command_buffer, int(kind_), context_.timestamp_period(), + context_.timestamp_bits(family_), commands, &context_.profile_names_); + replay.gpu_profile = profile.get(); + } + const bool bindless_uploaded = + !skip_shader_prep && std::exchange(context_.bindless_upload_pending_, false); // Layout changes go into the tracker itself, journalled, and are undone unless the submission reaches the // queue (tracker_mutex_ is held from here to the commit, so nothing else sees them meanwhile). auto& next_tracker = context_.tracker_; @@ -3672,29 +4541,28 @@ class VulkanQueue : private QueueHolds::Holder { } tracker_transaction{next_tracker}; // Bindless images that may already be visible to shaders are initialized on a submission that runs shaders. // initialize() zeroes committed storage images and only transitions sparse images. - bool runs_shaders = false; - for (const CommandList* list : lists) - for (const auto& command : list->commands()) - runs_shaders |= std::holds_alternative(command) || draw_command(command).state || - std::holds_alternative(command); - std::vector storage_images; - std::vector zero_buffers; + auto& storage_images = storage_images_scratch_; + storage_images.clear(); + auto& zero_buffers = zero_buffers_scratch_; + zero_buffers.clear(); { std::lock_guard lock(context_.storage_mutex_); if (context_.storage_init_semaphore_ && context_.storage_init_semaphore_ != progress_ && context_.storage_init_version_ != storage_init_seen_) { - waits_.push_back(context_.storage_init_semaphore_); - wait_values_.push_back(context_.storage_init_value_); + exec_waits_.push_back(context_.storage_init_semaphore_); + exec_wait_values_.push_back(context_.storage_init_value_); storage_init_seen_ = context_.storage_init_version_; } // The set this submission binds may be a new generation whose table another queue's submission uploads: // wait for that one, as for the storage images. The table and fallback images share the device's families. - if (context_.bindless_upload_semaphore_ && context_.bindless_upload_semaphore_ != progress_ && - context_.bindless_upload_version_ != bindless_upload_seen_) { - waits_.push_back(context_.bindless_upload_semaphore_); - wait_values_.push_back(context_.bindless_upload_value_); + if (!skip_shader_prep) { + if (context_.bindless_upload_semaphore_ && context_.bindless_upload_semaphore_ != progress_ && + context_.bindless_upload_version_ != bindless_upload_seen_) { + exec_waits_.push_back(context_.bindless_upload_semaphore_); + exec_wait_values_.push_back(context_.bindless_upload_value_); + } + bindless_upload_seen_ = context_.bindless_upload_version_; } - bindless_upload_seen_ = context_.bindless_upload_version_; if (kind_ != QueueKind::copy && runs_shaders) storage_images.assign(context_.storage_pending_.begin(), context_.storage_pending_.end()); if (!storage_images.empty()) context_.storage_pending_.clear(); @@ -3719,25 +4587,38 @@ class VulkanQueue : private QueueHolds::Holder { // The prelude (set_prelude): recorded here, after the set's upload and before the lists, and in either case // after the last submission of another queue that recorded one (its pass writes what these lists read, and // a pass here must not overtake it). - const bool prelude = !transfer_only && context_.prelude_record_ && context_.prelude_record_(command_buffer); + const bool prelude = !skip_shader_prep && context_.prelude_record_ && context_.prelude_record_(command_buffer); // LEONIDA_PRELUDE_QUEUE_WAIT=0 (an experiment): no wait for another queue's pass, so the queues do not // serialise on each other's whole submissions; a list may then read what that pass has not written yet. static const bool cross_wait = [] { const char* v = std::getenv("LEONIDA_PRELUDE_QUEUE_WAIT"); return !(v && v[0] == '0' && v[1] == 0); }(); - { + if (!skip_shader_prep) { std::lock_guard lock(context_.storage_mutex_); if (cross_wait && context_.prelude_semaphore_ && context_.prelude_semaphore_ != progress_ && context_.prelude_version_ != prelude_seen_) { - waits_.push_back(context_.prelude_semaphore_); - wait_values_.push_back(context_.prelude_value_); + exec_waits_.push_back(context_.prelude_semaphore_); + exec_wait_values_.push_back(context_.prelude_value_); } prelude_seen_ = context_.prelude_version_; } bool wrote_readback = false; VkPipelineStageFlags2 readback_stages = 0; + bool wrote_buffer = false; + struct BufferWriteChain { + bool* flag; + void (*next)(void*); + void* next_ctx; + } buffer_write_chain{&wrote_buffer, replay.on_buffer_write, replay.on_buffer_write_context}; + replay.on_buffer_write = +[](void* ctx) { + auto* c = static_cast(ctx); + *c->flag = true; + if (c->next) c->next(c->next_ctx); + }; + replay.on_buffer_write_context = &buffer_write_chain; std::uint32_t open_labels = 0; // events may span the lists of one ExecuteCommandLists + std::size_t break_cursor = 0; CheckpointSubmission diagnostics; PFN_vkCmdSetCheckpointNV checkpoint = nullptr; if (execute_call) { @@ -3747,18 +4628,36 @@ class VulkanQueue : private QueueHolds::Holder { kind_ == QueueKind::compute ? "compute" : "copy"; diagnostics = fault.begin_submission(execute_call, queue_, queue_kind, lists.size()); } + ReplayStateCache replay_state; for (std::size_t i = 0; i < lists.size(); ++i) { + // Between merged ExecuteCommandLists batches: close any open list debug labels and emit D3D12's implicit + // ExecuteCommandLists boundary barrier so writes from the previous batch are visible to the next. + while (break_cursor < batch_breaks.size() && batch_breaks[break_cursor] == i) { + ++break_cursor; + close_labels(command_buffer, replay, open_labels); + open_labels = 0; + if (context_.vk.vkCmdPipelineBarrier) { + VkMemoryBarrier between{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + between.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT; + between.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; + context_.vk.vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, + VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1, &between, 0, nullptr, 0, + nullptr); + } + } const auto& list = prepared[i]; if (execute_call && i < diagnostics.lists.size()) { const CheckpointRecorder recorder{checkpoint, diagnostics, context_.device_fault()->pipeline_names, i}; - emit_commands(list, command_buffer, replay, &next_tracker, &open_labels, &recorder); + emit_commands(list, command_buffer, replay, &next_tracker, &open_labels, &recorder, + &replay_state, &emit_scratch_); } else { - emit(list, command_buffer, replay, &next_tracker, &open_labels); + emit(list, command_buffer, replay, &next_tracker, &open_labels, &replay_state, &emit_scratch_); } wrote_readback |= list.wrote_readback; readback_stages |= list.readback_src_stages; } close_labels(command_buffer, replay, open_labels); + if (profile) profile->finish(command_buffer); // Only flush GPU writes to the host domain when this batch actually wrote to a readback buffer. if (wrote_readback) { const VkPipelineStageFlags2 allowed = queue_supported_stages(kind_); @@ -3795,11 +4694,22 @@ class VulkanQueue : private QueueHolds::Holder { pipeline_lock.unlock(); const bool wait_previous = ordered_timestamps && submitted_; if (wait_previous) { - waits_.push_back(progress_); - wait_values_.push_back(submitted_); + exec_waits_.push_back(progress_); + exec_wait_values_.push_back(submitted_); + } + const bool submitted = ended && submit_multi(command_buffer, trailing_signals, + execute_call ? &diagnostics : nullptr); + if (submitted && wrote_buffer && context_.on_buffer_write_submitted_) + context_.on_buffer_write_submitted_(context_.submitted_retire_ticket()); + if (profile && submitted) { + // Read once this submission (ticket submitted_ on progress_) is done; resolve off the FenceWaitDispatcher + // thread so timestamp readback and reporting never delay SetEventOnCompletion wakeups. + profile->mark_submitted(); + std::shared_ptr recording(std::move(profile)); + context_.enqueue_fence_callback(progress_, submitted_, [ctx = &context_, recording] { + ctx->enqueue_profile_resolve(recording); + }); } - const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0, - execute_call ? &diagnostics : nullptr); if (mesh_draws) std::fprintf(stderr, "[rt] pso-mesh unix_ms=%lld draws=%u submitted=%d\n", pipeline_profile::unix_ms(), mesh_draws, int(submitted)); @@ -3833,9 +4743,9 @@ class VulkanQueue : private QueueHolds::Holder { } if (context_.prelude_commit_) context_.prelude_commit_(submitted, context_.submitted_retire_ticket()); } - if (wait_previous && !submitted && !waits_.empty()) { // a failed submit keeps the waits for the next one - waits_.pop_back(); - wait_values_.pop_back(); + if (wait_previous && !submitted && !exec_waits_.empty()) { // a failed submit keeps the waits for the next one + exec_waits_.pop_back(); + exec_wait_values_.pop_back(); } if (submitted) { next_tracker.commit(); @@ -3846,7 +4756,10 @@ class VulkanQueue : private QueueHolds::Holder { slot->indirect_clamp = std::move(clamp_batch); queries.commit(); slot->segments = std::move(queries.retained); - slot->geometry = std::move(geometry); + if (!geometry.empty()) { + slot->geometry.clear(); + slot->geometry.swap(geometry); + } } else { next_tracker.rollback(); // here, under tracker_mutex_ (unlocked below, before the guard's scope ends) tracker_transaction.done = true; @@ -3860,10 +4773,6 @@ class VulkanQueue : private QueueHolds::Holder { context_.scratch_->retire(progress_, submitted ? submitted_ : 0); scratch_guard.active = false; } - if (clamp_guard.active) { - context_.indirect_clamp_->retire(progress_, submitted ? submitted_ : 0); - clamp_guard.active = false; - } // Under tracker_mutex_, so no other flush comes between this submit and the set's note of whether it reached // the queue (it keeps a single upload obligation). if (bindless_commit) bindless_commit(submitted); @@ -3895,11 +4804,16 @@ class VulkanQueue : private QueueHolds::Holder { struct Deferred { enum class Kind : std::uint8_t { batch, signal, marker }; Kind kind = Kind::batch; + bool barrier_after = false; // Present / after_held() was queued right after this op: do not merge past it std::uint64_t seq = 0; // QueueHolds::next_seq(): the order operations were held in, across queues + std::uint64_t present_epoch = kUnsetEpoch; // immutable submit_phases::present_calls at enqueue time std::uint64_t execute_call = 0; // original ExecuteCommandLists call for a held batch + std::uint64_t visibility_seq = 0; // context_.next_visibility_seq() at call time + EnqueueSerial enqueue_serial; std::vector waits; std::vector wait_values; - std::vector lists; // batch: copies, so the application may Reset its lists after the call + // Immutable closed CommandList snapshots (zero-copy when submitted via shared_ptr). + std::vector> lists; VkSemaphore fence = VK_NULL_HANDLE; // signal std::uint64_t value = 0; DebugMarker::Kind marker_kind = DebugMarker::Kind::set; // marker @@ -3911,38 +4825,167 @@ class VulkanQueue : private QueueHolds::Holder { std::chrono::steady_clock::time_point held_at{}; // LEONIDA_GPU_LATENCY: when it was held }; + static bool crosses_barrier(std::uint64_t cur_seq, std::uint64_t next_seq, std::uint64_t cur_epoch, + std::uint64_t next_epoch, std::uint64_t bseq) noexcept { + return cur_epoch != next_epoch || (bseq && cur_seq <= bseq && next_seq > bseq); + } + + struct DrainInfo { + bool released = false; + bool stopped_for_barrier = false; + std::uint64_t last_seq = 0; + std::uint64_t last_epoch = kUnsetEpoch; + }; + + struct HeldCountGuard { + QueueHolds& holds; + std::int64_t delta; + void release() noexcept { + if (delta) { + holds.held_changed(delta); + delta = 0; + } + } + ~HeldCountGuard() { release(); } + }; + + void set_active_seq_locked(std::uint64_t first) { + active_seq_ = first; + update_held_front_seq_locked(); + } + + // Waits for any satisfied barriers registered strictly before `op_seq` to finish executing on QueueHolds' barrier + // thread before running post-barrier GPU commands (strictly ordering Frame N Present blit before Frame N+1 writes). + // Empty-command batches execute no GPU commands or resource transitions and do not block on unrelated barriers. + // Called outside state_mutex_ by the thread owning executing_ == true. + void wait_for_preceding_barriers(std::uint64_t op_seq, std::span lists) { + if (!op_seq) return; + bool has_cmds = false; + for (const CommandList* list : lists) { + if (list && !list->commands().empty()) { + has_cmds = true; + break; + } + } + if (has_cmds) { + context_.holds().wait_barriers_drained(op_seq - 1); + } + } + bool waits_pending(const std::vector& semaphores, const std::vector& values) const { for (std::size_t i = 0; i < semaphores.size(); ++i) if (context_.holds().pending(semaphores[i], values[i])) return true; return false; } + // True when a Wait(fence, value) is already satisfied on the GPU (no pending QueueHolds signal AND the Vulkan + // timeline semaphore counter has already reached `value`), so coalescing can safely merge past it while still + // preserving its CPU Fence::Signal visibility edge via holds().signaled_vis_seq(). + bool wait_already_completed(VkSemaphore fence, std::uint64_t value) const { + if (!fence || value == 0) return true; + if (context_.is_device_lost()) return false; + if (context_.holds().pending(fence, value)) return false; + std::uint64_t done = 0; + return context_.vk.vkGetSemaphoreCounterValue(context_.device(), fence, &done) == VK_SUCCESS && done >= value; + } + + bool all_waits_already_completed(std::span semaphores, + std::span values) const { + const std::size_t n = (std::min)(semaphores.size(), values.size()); + for (std::size_t i = 0; i < n; ++i) { + if (!wait_already_completed(semaphores[i], values[i])) return false; + } + return true; + } + // The next batch or Signal has to be held: something is held ahead of it (queue order), or a Wait it carries // has no submitted Signal yet. Called with state_mutex_ held. bool must_hold() const { return !held_.empty() || waits_pending(waits_, wait_values_); } - // The waits are consumed: submitted as `ticket` (0: dropped on device loss). What the application may release - // (the fences they named) is kept until that submission has completed on the GPU, as a D3D12 queue does: - // destroying a semaphore a pending submission uses is a validation error. Retired pins are destroyed by the - // caller after state_mutex_ is released (drain_pins): the last release of a fence waits for a running release, - // which must not be waiting for this lock. - void clear_waits(std::uint64_t ticket = 0) { + // True when a synchronous caller cannot run even after the active execution finishes draining ready held ops: + // either this call carries a Wait on an unsignaled fence, or the front of held_ is blocked on one. + // Called with state_mutex_ held. + bool blocked_by_wait_locked() const { + return waits_pending(waits_, wait_values_) || (!held_.empty() && !ready(held_.front())); + } + + // Called with state_mutex_ held whenever active_seq_ or held_ changes. Keeps held_front_seq_ covering both any + // popped op currently executing and the front of held_ so Present barriers never overtake executing work. + void update_held_front_seq_locked() { + has_held_.store(!held_.empty(), std::memory_order_release); + const std::uint64_t queued = held_.empty() ? 0 : held_.front().seq; + const std::uint64_t oldest = (active_seq_ && queued) ? std::min(active_seq_, queued) + : active_seq_ ? active_seq_ + : queued; + held_front_seq_.store(oldest, std::memory_order_release); + } + + // Moves pending waits (state_mutex_-owned) into execution-local storage (owned by executing_). state_mutex_ held. + void take_waits_to_exec_locked() { + exec_user_wait_count_ += waits_.size(); + exec_waits_.insert(exec_waits_.end(), waits_.begin(), waits_.end()); + exec_wait_values_.insert(exec_wait_values_.end(), wait_values_.begin(), wait_values_.end()); + for (auto& p : wait_pins_) exec_wait_pins_.push_back(std::move(p)); waits_.clear(); wait_values_.clear(); - retire_pins(wait_pins_, ticket); + wait_pins_.clear(); + } + + // Restores unconsumed execution waits after a transient vkQueueSubmit failure onto the front of pending waits_, + // matching run()'s semantics so a held Signal behind the failed batch keeps its own waits and the retry gets these. + // Called with state_mutex_ held. + void restore_exec_waits_locked() { + if (exec_waits_.empty()) { + exec_user_wait_count_ = 0; + return; + } + waits_.insert(waits_.begin(), exec_waits_.begin(), exec_waits_.end()); + wait_values_.insert(wait_values_.begin(), exec_wait_values_.begin(), exec_wait_values_.end()); + wait_pins_.insert(wait_pins_.begin(), std::make_move_iterator(exec_wait_pins_.begin()), + std::make_move_iterator(exec_wait_pins_.end())); + exec_waits_.clear(); + exec_wait_values_.clear(); + exec_wait_pins_.clear(); + exec_user_wait_count_ = 0; } - void retire_pins(std::vector>& pins, std::uint64_t ticket) { + // The waits are consumed: submitted as `ticket` (0: dropped on device loss). Called by the thread owning + // executing_ (without state_mutex_ held). Retired pins are transferred back under state_mutex_ and destroyed + // by the caller after state_mutex_ is released (drain_pins): the last release of a fence waits for a running + // release, which must not be waiting for state_mutex_. + void clear_exec_waits(std::uint64_t ticket = 0) { + if (exec_user_wait_count_) { + const std::size_t n = (std::min)(exec_user_wait_count_, exec_waits_.size()); + context_.note_waits_removed(std::span(exec_waits_).first(n), std::span(exec_wait_values_).first(n)); + exec_user_wait_count_ = 0; + } + exec_waits_.clear(); + exec_wait_values_.clear(); + retire_exec_pins(exec_wait_pins_, ticket); + } + + void retire_exec_pins(std::vector>& pins, std::uint64_t ticket) { for (auto& pin : pins) { - if (ticket) pin_queue_.push_back({ticket, std::move(pin)}); - else retired_pins_.push_back(std::move(pin)); + if (ticket) exec_ticketed_pins_.push_back({ticket, std::move(pin)}); + else exec_retired_pins_.push_back(std::move(pin)); } pins.clear(); } + // Transfers pins accumulated while executing_ was held without state_mutex_. state_mutex_ held. + void flush_exec_pins_locked(std::vector>& retired) { + for (auto& tp : exec_ticketed_pins_) pin_queue_.push_back(std::move(tp)); + exec_ticketed_pins_.clear(); + for (auto& p : exec_retired_pins_) retired.push_back(std::move(p)); + exec_retired_pins_.clear(); + } + // Moves the pins whose submission has completed (and the ones retired outright) to `out`. state_mutex_ held. void drain_pins(std::vector>& out) { - out.swap(retired_pins_); + if (!retired_pins_.empty()) { + for (auto& p : retired_pins_) out.push_back(std::move(p)); + retired_pins_.clear(); + } if (pin_queue_.empty()) return; const std::uint64_t done = completed(); while (!pin_queue_.empty() && pin_queue_.front().ticket <= done) { @@ -3953,6 +4996,8 @@ class VulkanQueue : private QueueHolds::Holder { // Appends `op`, which takes the pending waits with it (a marker has none). Called with state_mutex_ held. void hold(Deferred&& op) { + if (op.present_epoch == kUnsetEpoch) + op.present_epoch = submit_phases::totals().present_calls.load(std::memory_order_acquire); // A call the worker runs (LEONIDA_SUBMIT_ASYNC) keeps the number it was queued with: what was registered // behind it (a Present) still waits for it. op.seq = async_seq_ ? async_seq_ : context_.holds().next_seq(); @@ -3966,93 +5011,481 @@ class VulkanQueue : private QueueHolds::Holder { } if (gpu_latency::enabled()) op.held_at = std::chrono::steady_clock::now(); held_.push_back(std::move(op)); - held_front_seq_.store(held_.front().seq, std::memory_order_release); + update_held_front_seq_locked(); context_.holds().held_changed(1); } - // Runs one held operation as the call would have, with its own waits and none of the ones queued since. - // A submission that fails leaves its waits for the next one, as when the call is not held (a transient - // vkQueueSubmit failure is retried by the application's next call), ahead of the waits asked for since. - void run(Deferred& op) { - auto later_waits = std::move(waits_); - auto later_values = std::move(wait_values_); - auto later_pins = std::move(wait_pins_); - waits_ = std::move(op.waits); - wait_values_ = std::move(op.wait_values); - wait_pins_ = std::move(op.wait_pins); // the fences stay alive until the submission has consumed their waits - switch (op.kind) { - case Deferred::Kind::batch: { - std::vector lists; - for (const CommandList& list : op.lists) lists.push_back(&list); - // The pipeline states and root signatures of the lists are in op.pins (see execute()): they live until - // the batch has been recorded and then, with the fences, until its submission has completed (below). - const ReplayResult result = execute_now(lists, op.execute_call); - if (result != ReplayResult::success) { - int none = static_cast(ReplayResult::success); - held_failure_.compare_exchange_strong(none, static_cast(result)); - std::fprintf(stderr, "[rt] d3d12: a held ExecuteCommandLists failed when it was released (result %d); " - "nothing was submitted for it, and a Signal behind it still signals\n", - static_cast(result)); + template + ReplayResult execute_sync_impl(std::span lists, const PinFn& pin, + std::uint64_t execute_call, MakeHeldLists&& make_held_lists, + std::shared_ptr async_pin = {}, EnqueueSerial enqueue_serial = {}, + bool async_barrier_after = false, + std::uint64_t async_present_epoch = kUnsetEpoch, + std::uint64_t vis_seq = 0) { + ReplayResult result = ReplayResult::success; + bool ran = false; + bool held = false; + bool pre_drained = false; + QueueHolds::WorkGuard work_guard; + std::vector> retired; // destroyed after state_mutex_ is released + EnqueueSerial dropped_serial; // finished after state_mutex_ is released if lost + auto hold_batch_locked = [&] { + Deferred op; + op.kind = Deferred::Kind::batch; + op.barrier_after = async_barrier_after; + op.present_epoch = async_present_epoch; + op.execute_call = execute_call; + op.visibility_seq = vis_seq; + op.enqueue_serial = std::move(enqueue_serial); + op.lists = make_held_lists(); + if (async_pin) op.pins.push_back(std::move(async_pin)); + else if (pin) op.pins.push_back(pin()); + hold(std::move(op)); + held = true; + }; + { + std::unique_lock state(state_mutex_, std::defer_lock); + submit_phases::lock_timed(state); + // If another thread is executing or draining ready held ops and this batch is not blocked by an unmet + // Wait, wait on exec_cv_ (with state_mutex_ unlocked so Wait/Signal/wait-blocked callers never stall on + // before_execute_()) so this batch still runs before_execute_() and execute_now() synchronously. + if (executing_ && !blocked_by_wait_locked() && !context_.is_device_lost()) { + exec_cv_.wait(state, [this] { + return !executing_ || blocked_by_wait_locked() || context_.is_device_lost(); + }); } - break; + if (context_.is_device_lost()) { + result = queue_unsupported(__LINE__); + if (async_pin) retired.push_back(std::move(async_pin)); + dropped_serial = std::move(enqueue_serial); + } else if (!executing_ && !blocked_by_wait_locked()) { + work_guard.arm(context_.holds()); + executing_ = true; + ExecGuard exec_guard{this, state}; + // Drain any ready held ops ahead of us first (strict FIFO, e.g. a gate just satisfied by + // QueueHolds::signaled() before pump_ready() reached this queue). + DrainInfo pre_info{}; + if (!held_.empty()) pre_drained = drain_held_while_executing(state, retired, false, &pre_info); + const std::uint64_t call_epoch = + async_present_epoch != kUnsetEpoch + ? async_present_epoch + : submit_phases::totals().present_calls.load(std::memory_order_acquire); + const std::uint64_t call_seq_hint = async_seq_ ? async_seq_ : context_.holds().current_seq() + 1; + const std::uint64_t bseq_now = barrier_seq_.load(std::memory_order_acquire); + const bool barrier_before_me = + pre_info.released && + (pre_info.stopped_for_barrier || + crosses_barrier(pre_info.last_seq, call_seq_hint, pre_info.last_epoch, call_epoch, bseq_now)); + if (context_.is_device_lost()) { + result = queue_unsupported(__LINE__); + if (async_pin) retired.push_back(std::move(async_pin)); + dropped_serial = std::move(enqueue_serial); + } else if (must_hold() || barrier_before_me) { + hold_batch_locked(); + if (barrier_before_me) pause_release_for_barrier_.store(true, std::memory_order_release); + } else { + const std::uint64_t my_seq = async_seq_ ? async_seq_ : context_.holds().next_seq(); + set_active_seq_locked(my_seq); + take_waits_to_exec_locked(); + state.unlock(); + + wait_for_preceding_barriers(my_seq, lists); + result = execute_now(lists, execute_call, {}, {}, vis_seq, false); + note_coalesced_submit(1); + enqueue_serial.finish(); + if (async_pin) { + if (result == ReplayResult::success && submitted_) + exec_ticketed_pins_.push_back({submitted_, std::move(async_pin)}); + else + exec_retired_pins_.push_back(std::move(async_pin)); + } + + state.lock(); + restore_exec_waits_locked(); + flush_exec_pins_locked(retired); + set_active_seq_locked(0); + drain_held_while_executing(state, retired); + ran = true; + } + exec_guard.release(); + } else { + hold_batch_locked(); + } + drain_pins(retired); } - case Deferred::Kind::signal: - if (!submit(VK_NULL_HANDLE, op.fence, op.value)) - std::fprintf(stderr, "[rt] d3d12: a held Signal failed when it was released\n"); - break; - case Deferred::Kind::marker: - marker_now(op.marker_kind, op.label.c_str()); - break; + dropped_serial.finish(); + retired.clear(); + if (ran || held || pre_drained) context_.holds().pump_ready(); + return result; + } + + // Drains all ready held operations in strict FIFO order while executing_ is owned by the caller, coalescing + // consecutive ready command-list batches that have no intervening Signal, Wait, Marker, or Present barrier into a + // single before_execute_() + single vkQueueSubmit (with inter-batch D3D12 memory barriers and per-batch fallback + // isolation on error). Releases state_mutex_ around every execute_now() / submit() / marker_now(). + // Entry & exit: state_mutex_ held, executing_ == true. + bool drain_held_while_executing(std::unique_lock& state, + std::vector>& retired, bool from_pump = false, + DrainInfo* info = nullptr) { + bool released = false; + while (!held_.empty() && (context_.is_device_lost() || ready(held_.front()))) { + if (context_.is_device_lost()) { + Deferred op = std::move(held_.front()); + held_.pop_front(); + set_active_seq_locked(op.seq); + if (!op.waits.empty()) context_.note_waits_removed(op.waits, op.wait_values); + for (auto& p : op.pins) retired.push_back(std::move(p)); + for (auto& p : op.wait_pins) retired.push_back(std::move(p)); + EnqueueSerial dropped = std::move(op.enqueue_serial); + context_.holds().held_changed(-1); + set_active_seq_locked(0); + if (dropped.value) { + state.unlock(); + dropped.finish(); + state.lock(); + } + released = true; + continue; + } + + if (held_.front().kind == Deferred::Kind::batch) { + const std::uint64_t bseq = barrier_seq_.load(std::memory_order_acquire); + std::vector group_ops; + group_ops.push_back(std::move(held_.front())); + held_.pop_front(); + std::size_t batch_count = 1; + bool stop_after_signal = false; + while (!group_ops.back().barrier_after && !held_.empty()) { + const Deferred& next = held_.front(); + if (crosses_barrier(group_ops.back().seq, next.seq, group_ops.back().present_epoch, + next.present_epoch, bseq)) + break; + if (!next.waits.empty() && !all_waits_already_completed(next.waits, next.wait_values)) break; + if (next.kind == Deferred::Kind::batch) { + if (stop_after_signal) break; + group_ops.push_back(std::move(held_.front())); + held_.pop_front(); + ++batch_count; + } else if (next.kind == Deferred::Kind::signal) { + group_ops.push_back(std::move(held_.front())); + held_.pop_front(); + if (context_.has_unsatisfied_waiter(group_ops.back().fence, group_ops.back().value)) + stop_after_signal = true; + } else { + break; + } + } + + HeldCountGuard held_guard{context_.holds(), -static_cast(group_ops.size())}; + + const std::uint64_t last_seq = group_ops.back().seq; + const std::uint64_t last_epoch = group_ops.back().present_epoch; + bool stop_for_barrier = + group_ops.back().barrier_after || + (!held_.empty() && + crosses_barrier(last_seq, held_.front().seq, last_epoch, held_.front().present_epoch, bseq)); + + Deferred& first = group_ops.front(); + set_active_seq_locked(first.seq); + + const bool log_latency = gpu_latency::enabled(); + std::uint64_t latency_fence = 0; + std::uint64_t latency_value = 0; + if (log_latency) { + for (std::size_t i = 0; i < first.waits.size(); ++i) + if (first.wait_values[i] > latency_value) { + latency_fence = std::uint64_t(reinterpret_cast(first.waits[i])); + latency_value = first.wait_values[i]; + } + } + + exec_user_wait_count_ += first.waits.size(); + exec_waits_.insert(exec_waits_.end(), first.waits.begin(), first.waits.end()); + exec_wait_values_.insert(exec_wait_values_.end(), first.wait_values.begin(), first.wait_values.end()); + for (auto& p : first.wait_pins) exec_wait_pins_.push_back(std::move(p)); + first.waits.clear(); + first.wait_values.clear(); + first.wait_pins.clear(); + + state.unlock(); + + if (log_latency) { + for (const Deferred& op : group_ops) + gpu_latency::held(int(kind_), int(op.kind), op.held_at, latency_fence, latency_value); + } + + exec_list_ptrs_.clear(); + exec_batch_breaks_.clear(); + exec_pending_signals_.clear(); + std::uint64_t group_vis_seq = 0; + for (std::size_t gi = 1; gi < group_ops.size(); ++gi) { + Deferred& op = group_ops[gi]; + if (!op.waits.empty()) { + const std::size_t wn = (std::min)(op.waits.size(), op.wait_values.size()); + for (std::size_t wi = 0; wi < wn; ++wi) { + const std::uint64_t w_vis = + context_.holds().signaled_vis_seq(op.waits[wi], op.wait_values[wi]); + op.visibility_seq = (std::max)(op.visibility_seq, w_vis); + } + context_.note_waits_removed(op.waits, op.wait_values); + retire_exec_pins(op.wait_pins, 0); + op.waits.clear(); + op.wait_values.clear(); + } + } + for (const Deferred& op : group_ops) { + group_vis_seq = (std::max)(group_vis_seq, op.visibility_seq); + if (op.kind == Deferred::Kind::batch) { + if (!exec_list_ptrs_.empty() && !op.lists.empty()) + exec_batch_breaks_.push_back(exec_list_ptrs_.size()); + for (const auto& list : op.lists) exec_list_ptrs_.push_back(list.get()); + } else if (op.kind == Deferred::Kind::signal) { + exec_pending_signals_.push_back({op.fence, op.value, op.visibility_seq}); + } + } + + wait_for_preceding_barriers(first.seq, exec_list_ptrs_); + const ReplayResult result = execute_now(exec_list_ptrs_, first.execute_call, exec_batch_breaks_, + exec_pending_signals_, group_vis_seq, /*from_held=*/true); + if (result == ReplayResult::success) { + note_coalesced_submit(batch_count); + for (Deferred& op : group_ops) { + retire_exec_pins(op.pins, submitted_); + op.enqueue_serial.finish(); + op.lists.clear(); + } + } else if (batch_count > 1 && !context_.is_device_lost()) { + // Isolate the failing batch so valid peers and trailing Signals still submit in FIFO order. + for (Deferred& op : group_ops) { + if (op.kind == Deferred::Kind::batch) { + exec_list_ptrs_.clear(); + for (const auto& list : op.lists) exec_list_ptrs_.push_back(list.get()); + const ReplayResult sub = + execute_now(exec_list_ptrs_, op.execute_call, {}, {}, op.visibility_seq, true); + note_coalesced_submit(1); + if (sub != ReplayResult::success) { + int none = static_cast(ReplayResult::success); + held_failure_.compare_exchange_strong(none, static_cast(sub)); + std::fprintf(stderr, + "[rt] d3d12: a held ExecuteCommandLists failed when it was released " + "(result %d); nothing was submitted for it, and a Signal behind it still " + "signals\n", + static_cast(sub)); + } + retire_exec_pins(op.pins, sub == ReplayResult::success ? submitted_ : 0); + op.enqueue_serial.finish(); + op.lists.clear(); + } else if (op.kind == Deferred::Kind::signal) { + // Preserve any unconsumed waits from a preceding failed batch rather than letting this + // trailing Signal (which carried no waits of its own) consume them. + auto saved_waits = std::move(exec_waits_); + auto saved_values = std::move(exec_wait_values_); + auto saved_pins = std::move(exec_wait_pins_); + const std::size_t saved_user = std::exchange(exec_user_wait_count_, 0); + exec_waits_.clear(); + exec_wait_values_.clear(); + exec_wait_pins_.clear(); + if (op.visibility_seq > pending_wait_vis_seq_) pending_wait_vis_seq_ = op.visibility_seq; + const bool ok = submit(VK_NULL_HANDLE, op.fence, op.value, nullptr, op.visibility_seq); + if (!ok) std::fprintf(stderr, "[rt] d3d12: a held Signal failed when it was released\n"); + retire_exec_pins(op.pins, ok ? submitted_ : 0); + exec_waits_ = std::move(saved_waits); + exec_wait_values_ = std::move(saved_values); + exec_wait_pins_ = std::move(saved_pins); + exec_user_wait_count_ = saved_user; + } + } + } else { + note_coalesced_submit(batch_count); + int none = static_cast(ReplayResult::success); + held_failure_.compare_exchange_strong(none, static_cast(result)); + std::fprintf(stderr, + "[rt] d3d12: a held ExecuteCommandLists failed when it was released " + "(result %d); nothing was submitted for it, and a Signal behind it still signals\n", + static_cast(result)); + // Single batch failed (do NOT re-run it); preserve its unconsumed waits for retry, and still submit + // any trailing Signals that rode along with it (unless device is lost). + auto saved_waits = std::move(exec_waits_); + auto saved_values = std::move(exec_wait_values_); + auto saved_pins = std::move(exec_wait_pins_); + const std::size_t saved_user = std::exchange(exec_user_wait_count_, 0); + exec_waits_.clear(); + exec_wait_values_.clear(); + exec_wait_pins_.clear(); + for (Deferred& op : group_ops) { + if (op.kind == Deferred::Kind::signal && !context_.is_device_lost()) { + if (op.visibility_seq > pending_wait_vis_seq_) pending_wait_vis_seq_ = op.visibility_seq; + const bool ok = submit(VK_NULL_HANDLE, op.fence, op.value, nullptr, op.visibility_seq); + if (!ok) std::fprintf(stderr, "[rt] d3d12: a held Signal failed when it was released\n"); + retire_exec_pins(op.pins, ok ? submitted_ : 0); + } else { + retire_exec_pins(op.pins, 0); + op.enqueue_serial.finish(); + op.lists.clear(); + } + } + exec_waits_ = std::move(saved_waits); + exec_wait_values_ = std::move(saved_values); + exec_wait_pins_ = std::move(saved_pins); + exec_user_wait_count_ = saved_user; + } + + state.lock(); + restore_exec_waits_locked(); + flush_exec_pins_locked(retired); + held_guard.release(); + set_active_seq_locked(0); + released = true; + const std::uint64_t bseq_after = barrier_seq_.load(std::memory_order_acquire); + if (!stop_for_barrier && !held_.empty()) { + stop_for_barrier = + crosses_barrier(last_seq, held_.front().seq, last_epoch, held_.front().present_epoch, bseq_after); + } + if (info) { + info->released = true; + info->last_seq = last_seq; + info->last_epoch = last_epoch; + info->stopped_for_barrier = stop_for_barrier; + } + if (stop_for_barrier) { + if (!from_pump && !held_.empty()) pause_release_for_barrier_.store(true, std::memory_order_release); + break; + } + continue; + } + + Deferred op = std::move(held_.front()); + held_.pop_front(); + HeldCountGuard held_guard{context_.holds(), -1}; + const std::uint64_t op_seq = op.seq; + const std::uint64_t op_epoch = op.present_epoch; + const bool op_barrier = op.barrier_after; + set_active_seq_locked(op_seq); + + // Capture latency-log metadata before moving waits out. + const bool log_latency = gpu_latency::enabled(); + const int latency_kind = int(op.kind); + const auto latency_held_at = op.held_at; + std::uint64_t latency_fence = 0; + std::uint64_t latency_value = 0; + if (log_latency) { + for (std::size_t i = 0; i < op.waits.size(); ++i) + if (op.wait_values[i] > latency_value) { + latency_fence = std::uint64_t(reinterpret_cast(op.waits[i])); + latency_value = op.wait_values[i]; + } + } + + // Move this op's waits into execution-local storage. + exec_user_wait_count_ += op.waits.size(); + exec_waits_.insert(exec_waits_.end(), op.waits.begin(), op.waits.end()); + exec_wait_values_.insert(exec_wait_values_.end(), op.wait_values.begin(), op.wait_values.end()); + for (auto& p : op.wait_pins) exec_wait_pins_.push_back(std::move(p)); + op.waits.clear(); + op.wait_values.clear(); + op.wait_pins.clear(); + + state.unlock(); + + if (log_latency) gpu_latency::held(int(kind_), latency_kind, latency_held_at, latency_fence, latency_value); + + switch (op.kind) { + case Deferred::Kind::batch: + break; + case Deferred::Kind::signal: { + const bool ok = submit(VK_NULL_HANDLE, op.fence, op.value, nullptr, op.visibility_seq); + if (!ok) std::fprintf(stderr, "[rt] d3d12: a held Signal failed when it was released\n"); + retire_exec_pins(op.pins, ok ? submitted_ : 0); + break; + } + case Deferred::Kind::marker: + marker_now(op.marker_kind, op.label.c_str()); + retire_exec_pins(op.pins, 0); + break; + } + op.enqueue_serial.finish(); + op.lists.clear(); // drop CommandList refs before re-acquiring state_mutex_ + + state.lock(); + restore_exec_waits_locked(); + flush_exec_pins_locked(retired); + held_guard.release(); + set_active_seq_locked(0); + released = true; + const std::uint64_t bseq_after = barrier_seq_.load(std::memory_order_acquire); + const bool hit_barrier = + op_barrier || + (!held_.empty() && + crosses_barrier(op_seq, held_.front().seq, op_epoch, held_.front().present_epoch, bseq_after)); + if (info) { + info->released = true; + info->last_seq = op_seq; + info->last_epoch = op_epoch; + info->stopped_for_barrier = hit_barrier; + } + if (hit_barrier) { + if (!from_pump && !held_.empty()) pause_release_for_barrier_.store(true, std::memory_order_release); + break; + } } - retire_pins(op.pins, submitted_); // the fence it signals, the pipeline states: until its submission is done - waits_.insert(waits_.end(), later_waits.begin(), later_waits.end()); - wait_values_.insert(wait_values_.end(), later_values.begin(), later_values.end()); - for (auto& pin : later_pins) wait_pins_.push_back(std::move(pin)); + return released; } bool ready(const Deferred& op) const { return !waits_pending(op.waits, op.wait_values); } // Holder: called by the thread whose Signal made a held operation ready (never with a queue lock held). - // With LEONIDA_SUBMIT_ASYNC another thread does not run this queue's held work: it asks the queue's worker, - // which releases it and then pumps the holds itself (so a Present behind it still runs after it). + // With LEONIDA_SUBMIT_ASYNC, never run release_held() inline under QueueHolds::pump_mutex_ (even when called from + // our own async_worker): schedule a worker turn so pump_ready() collects barriers and releases pump_mutex_ before + // post-barrier work waits in wait_barriers_drained(), keeping cross-queue pump_ready() unblocked during Present. bool release_ready() override { - if (async_started_.load(std::memory_order_acquire) && t_worker_of_ != this) { + if (async_started_.load(std::memory_order_acquire)) { + const bool paused_for_barrier = pause_release_for_barrier_.exchange(false, std::memory_order_acq_rel); + // Fast path: do not touch inbox_mutex_ or stamp barrier_after when this queue has no held operations. + // barrier_after is stamped ONLY by real after_held() barriers (oldest_held_seq() / present_epoch), + // never by cross-queue Signal() pump_ready() calls. + if (!has_held_.load(std::memory_order_acquire)) return false; + // On our own worker's trailing pump_ready(), avoid scheduling a redundant wakeup if the front held op is + // still blocked on an unmet wait (we only need another turn when paused at a barrier or when front became + // ready). + if (t_worker_of_ == this && !paused_for_barrier) { + std::lock_guard state(state_mutex_); + if (held_.empty() || (!context_.is_device_lost() && !ready(held_.front()))) return false; + } + bool wake = false; { std::lock_guard lock(inbox_mutex_); - release_requested_ = true; + if (async_stop_) return false; // worker is stopping/joined during teardown + // Only ask the worker to drain held_ when this queue actually has held work; avoids idle wakeups + // and cross-queue ping-pong while another queue holds an unsatisfied wait. + if (has_held_.load(std::memory_order_acquire) && !release_requested_) { + release_requested_ = true; + context_.holds().work_changed(1); + wake = true; + } } - inbox_cv_.notify_one(); + if (wake) inbox_cv_.notify_one(); return false; } - return release_held(); + // If an earlier drain stopped at a barrier boundary outside pump_ready(), yield once so pump_ready() + // runs collect_ready_barriers() (Present / after_held()) BEFORE we drain post-barrier held work on the next pass. + if (pause_release_for_barrier_.exchange(false, std::memory_order_acq_rel)) return true; + return release_held(/*from_pump=*/true); } - bool release_held() { + bool release_held(bool from_pump = false, DrainInfo* info = nullptr) { std::vector> retired; bool released = false; { - std::lock_guard state(state_mutex_); - while (!held_.empty() && (context_.is_device_lost() || ready(held_.front()))) { - Deferred op = std::move(held_.front()); - held_.pop_front(); - context_.holds().held_changed(-1); - if (gpu_latency::enabled()) { - // The wait that was pending when it was held: the fence whose Signal let it go. - std::uint64_t fence = 0, value = 0; - for (std::size_t i = 0; i < op.waits.size(); ++i) - if (op.wait_values[i] > value) { - fence = std::uint64_t(reinterpret_cast(op.waits[i])); - value = op.wait_values[i]; - } - gpu_latency::held(int(kind_), int(op.kind), op.held_at, fence, value); - } - if (!context_.is_device_lost()) run(op); - // Only now: until it has run, the operation still counts as the oldest held one. - held_front_seq_.store(held_.empty() ? 0 : held_.front().seq, std::memory_order_release); - released = true; + std::unique_lock state(state_mutex_); + if (!executing_ && !held_.empty() && (context_.is_device_lost() || ready(held_.front()))) { + executing_ = true; + ExecGuard exec_guard{this, state}; + released = drain_held_while_executing(state, retired, from_pump, info); + exec_guard.release(); } drain_pins(retired); } + retired.clear(); return released; } @@ -4069,28 +5502,164 @@ class VulkanQueue : private QueueHolds::Holder { } std::fprintf(stderr, "[rt] d3d12: a fence was released while a queue still held work that names it; " "that work is dropped\n"); + if (!it->waits.empty()) context_.note_waits_removed(it->waits, it->wait_values); dropped.push_back(std::move(*it)); it = held_.erase(it); context_.holds().held_changed(-1); } - held_front_seq_.store(held_.empty() ? 0 : held_.front().seq, std::memory_order_release); + update_held_front_seq_locked(); + } + } + + // Holder: substitutes matching waits across inbox_, waits_, and held_ for a retroactive GPU-to-GPU relay. + // Keeps context_.note_wait_added / note_wait_removed and QueueHolds held/work counts balanced. + bool apply_wait_relay(VkSemaphore gate_sem, std::uint64_t gate_val, + std::span::Wait> replacements, + bool& any_substituted) override { + if (!gate_sem || !gate_val || replacements.empty()) return false; + std::vector> retired_pins; + if (async_started_.load(std::memory_order_acquire)) { + std::lock_guard lock(inbox_mutex_); + for (std::size_t i = 0; i < inbox_.size(); ++i) { + Call& c = inbox_[i]; + if (c.kind != Call::Kind::wait || c.fence != gate_sem || c.value != gate_val) continue; + any_substituted = true; + context_.note_wait_removed(gate_sem, gate_val); + if (c.pin) retired_pins.push_back(std::move(c.pin)); + c.fence = replacements[0].semaphore; + c.value = replacements[0].value; + c.pin = replacements[0].pin; + context_.note_wait_added(c.fence, c.value); + if (replacements.size() > 1) { + const bool orig_barrier = c.barrier_after; + const std::uint64_t seq = c.seq; + const std::uint64_t epoch = c.present_epoch; + const auto queued_at = c.queued_at; + c.barrier_after = false; + std::vector extras; + extras.reserve(replacements.size() - 1); + for (std::size_t k = 1; k < replacements.size(); ++k) { + Call extra; + extra.kind = Call::Kind::wait; + extra.seq = seq; + extra.present_epoch = epoch; + extra.queued_at = queued_at; + extra.barrier_after = (k + 1 == replacements.size()) ? orig_barrier : false; + extra.fence = replacements[k].semaphore; + extra.value = replacements[k].value; + extra.pin = replacements[k].pin; + context_.note_wait_added(extra.fence, extra.value); + extras.push_back(std::move(extra)); + } + const std::int64_t added = static_cast(extras.size()); + context_.holds().held_changed(added); + context_.holds().work_changed(added); + inbox_.insert(inbox_.begin() + static_cast(i + 1), + std::make_move_iterator(extras.begin()), std::make_move_iterator(extras.end())); + i += extras.size(); + } + } + } + bool any_held_updated = false; + { + std::lock_guard state(state_mutex_); + const std::size_t orig_waits = waits_.size(); + for (std::size_t i = 0; i < orig_waits; ++i) { + if (waits_[i] != gate_sem || wait_values_[i] != gate_val) continue; + any_substituted = true; + context_.note_wait_removed(gate_sem, gate_val); + waits_[i] = replacements[0].semaphore; + wait_values_[i] = replacements[0].value; + context_.note_wait_added(replacements[0].semaphore, replacements[0].value); + if (replacements[0].pin) wait_pins_.push_back(replacements[0].pin); + for (std::size_t k = 1; k < replacements.size(); ++k) { + waits_.push_back(replacements[k].semaphore); + wait_values_.push_back(replacements[k].value); + context_.note_wait_added(replacements[k].semaphore, replacements[k].value); + if (replacements[k].pin) wait_pins_.push_back(replacements[k].pin); + } + } + for (Deferred& op : held_) { + const std::size_t orig_op_waits = op.waits.size(); + for (std::size_t i = 0; i < orig_op_waits; ++i) { + if (op.waits[i] != gate_sem || op.wait_values[i] != gate_val) continue; + any_substituted = true; + any_held_updated = true; + context_.note_wait_removed(gate_sem, gate_val); + op.waits[i] = replacements[0].semaphore; + op.wait_values[i] = replacements[0].value; + context_.note_wait_added(replacements[0].semaphore, replacements[0].value); + if (replacements[0].pin) op.wait_pins.push_back(replacements[0].pin); + for (std::size_t k = 1; k < replacements.size(); ++k) { + op.waits.push_back(replacements[k].semaphore); + op.wait_values.push_back(replacements[k].value); + context_.note_wait_added(replacements[k].semaphore, replacements[k].value); + if (replacements[k].pin) op.wait_pins.push_back(replacements[k].pin); + } + } + } + } + retired_pins.clear(); + return any_held_updated; + } + + // Holder: records a real after_held() barrier at `seq` so batches at or before `seq` never coalesce with batches + // enqueued after `seq` (including batches in transit between inbox_ and held_). Never called by run_barriers(). + void note_barrier(std::uint64_t seq) override { + if (!seq) return; + std::uint64_t prev = barrier_seq_.load(std::memory_order_relaxed); + while (seq > prev && !barrier_seq_.compare_exchange_weak(prev, seq, std::memory_order_acq_rel)) {} + { + std::lock_guard state(state_mutex_); + for (auto it = held_.rbegin(); it != held_.rend(); ++it) { + if (it->seq <= seq) { + it->barrier_after = true; + break; + } + } + } + if (async_started_.load(std::memory_order_acquire)) { + std::lock_guard lock(inbox_mutex_); + for (auto it = inbox_.rbegin(); it != inbox_.rend(); ++it) { + if (it->seq <= seq) { + it->barrier_after = true; + break; + } + } } } - // Holder: the sequence number of the oldest held operation. + // Holder: the sequence number of the oldest active, held, or queued operation (read-only query). std::uint64_t oldest_held_seq() override { - if (!async_on()) { + // Read inbox_mutex_ (running_seq_ / inbox_) before state_mutex_ (active_seq_ / held_): items only move + // inbox -> running -> held/active -> done, so reading upstream first cannot miss an item in transit. + std::uint64_t oldest = 0; + if (async_started_.load(std::memory_order_acquire)) { + std::lock_guard lock(inbox_mutex_); + oldest = running_seq_ ? running_seq_ : inbox_.empty() ? 0 : inbox_.front().seq; + } + { std::lock_guard state(state_mutex_); - return held_.empty() ? 0 : held_.front().seq; + const std::uint64_t queued = held_.empty() ? 0 : held_.front().seq; + const std::uint64_t active = (active_seq_ && queued) ? std::min(active_seq_, queued) + : active_seq_ ? active_seq_ + : queued; + if (active && (!oldest || active < oldest)) oldest = active; } - // Not under state_mutex_, which the worker holds while it replays: the front's number is kept apart. - std::uint64_t oldest = held_front_seq_.load(std::memory_order_acquire); - std::lock_guard lock(inbox_mutex_); - const std::uint64_t queued = running_seq_ ? running_seq_ : inbox_.empty() ? 0 : inbox_.front().seq; - if (queued && (!oldest || queued < oldest)) oldest = queued; return oldest; } + // Holder: true while this queue has submitted GPU work that has not retired yet. Lock-free so + // QueueHolds::has_progress() can query it safely without taking queue or submit locks. + bool has_pending_gpu_work() const override { + if (context_.is_device_lost()) return false; + const std::uint64_t sub = submitted_gpu_.load(std::memory_order_acquire); + if (!sub) return false; + std::uint64_t done = 0; + const VkResult result = context_.vk.vkGetSemaphoreCounterValue(context_.device(), progress_, &done); + return result == VK_SUCCESS && done < sub; + } + // A queue destroyed with held work. Reported, not waited for: nothing was submitted for it, so the VkQueue is // idle and the destructor goes on. The fences of held Signals will never reach their values, so what is waiting // for them on the CPU (SetEventOnCompletion, as a released fence completes them) is woken, and the batches @@ -4110,11 +5679,13 @@ class VulkanQueue : private QueueHolds::Holder { "fence value (%llu) that no Signal reached; the fence was never signaled%s\n", held_.size(), static_cast(value), signals ? "; CPU waits on the fences of its held Signals are completed" : ""); - for (const Deferred& op : held_) + for (const Deferred& op : held_) { if (op.kind == Deferred::Kind::signal) context_.cancel_fence_waits(op.fence); + if (!op.waits.empty()) context_.note_waits_removed(op.waits, op.wait_values); + } context_.holds().held_changed(-static_cast(held_.size())); dropped.swap(held_); - held_front_seq_.store(0, std::memory_order_release); + set_active_seq_locked(0); } // The pins (fences, pipeline states) are released here, outside the lock. } @@ -4218,8 +5789,8 @@ class VulkanQueue : private QueueHolds::Holder { const auto ticket = submitted_ + 1; pending.ticket = ticket; collect_bindings(completed()); - auto semaphores = waits_; - auto values = wait_values_; + auto semaphores = exec_waits_; + auto values = exec_wait_values_; // Sparse binds are not ordered against work on the same Vulkan queue by submission order alone. if (submitted_) { semaphores.push_back(progress_); @@ -4263,7 +5834,8 @@ class VulkanQueue : private QueueHolds::Holder { context_.record_submit_locked(progress_, ticket); } submitted_ = last_sparse_ = ticket; - clear_waits(ticket); + submitted_gpu_.store(ticket, std::memory_order_release); + clear_exec_waits(ticket); for (auto it = changes.begin(); it != changes.end();) { resource->mapped.erase(it->first); if (it->second.heap) ++it; @@ -4352,7 +5924,8 @@ class VulkanQueue : private QueueHolds::Holder { CommandSlot* acquire() { if (context_.is_device_lost()) return nullptr; - context_.drain_deleted_resources(context_.completed_retire_ticket()); + if (context_.deletion_queue_.has_pending()) + context_.drain_deleted_resources(context_.completed_retire_ticket()); CommandSlot* reuse = recycle_finished(); if (reuse) { if (context_.vk.vkResetCommandBuffer(reuse->buffer, 0) != VK_SUCCESS) return nullptr; @@ -4424,54 +5997,186 @@ class VulkanQueue : private QueueHolds::Holder { } bool submit(VkCommandBuffer command_buffer, VkSemaphore fence, std::uint64_t value, - CheckpointSubmission* diagnostics = nullptr) { + CheckpointSubmission* diagnostics = nullptr, std::uint64_t visibility_seq = 0) { + if (fence) { + const PendingSignal sig{fence, value, visibility_seq}; + return submit_multi(command_buffer, {&sig, 1}, diagnostics); + } + return submit_multi(command_buffer, {}, diagnostics); + } + + bool submit_multi(VkCommandBuffer command_buffer, std::span extra_signals, + CheckpointSubmission* diagnostics = nullptr) { if (context_.is_device_lost()) return false; const std::uint64_t ticket = submitted_ + 1; if (last_sparse_) { collect_bindings(completed()); if (context_.is_device_lost()) return false; } - std::span semaphores = waits_; - std::span values = wait_values_; - std::vector sparse_waits; - std::vector sparse_values; + std::span semaphores = exec_waits_; + std::span values = exec_wait_values_; + bool using_sparse = false; if (last_sparse_) { - sparse_waits = waits_; - sparse_values = wait_values_; - sparse_waits.push_back(progress_); - sparse_values.push_back(last_sparse_); - semaphores = sparse_waits; - values = sparse_values; - } - const std::vector stages(semaphores.size(), VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); VkResult res = VK_SUCCESS; + sparse_waits_ = exec_waits_; + sparse_values_ = exec_wait_values_; + sparse_waits_.push_back(progress_); + sparse_values_.push_back(last_sparse_); + semaphores = sparse_waits_; + values = sparse_values_; + using_sparse = true; + } + constexpr VkPipelineStageFlags kAllCmds = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; + VkPipelineStageFlags stack_stages[16] = { + kAllCmds, kAllCmds, kAllCmds, kAllCmds, kAllCmds, kAllCmds, kAllCmds, kAllCmds, + kAllCmds, kAllCmds, kAllCmds, kAllCmds, kAllCmds, kAllCmds, kAllCmds, kAllCmds, + }; + const VkPipelineStageFlags* stages_ptr = stack_stages; + if (semaphores.size() > 16) { + submit_stages_.assign(semaphores.size(), kAllCmds); + stages_ptr = submit_stages_.data(); + } + // Deduplicate extra_signals by VkSemaphore, keeping the highest timeline value (and max visibility_seq) per + // fence so VkSubmitInfo never names the same timeline semaphore twice (VUID-VkSubmitInfo-pSignalSemaphores-03242). + PendingSignal stack_dedup[16]; + std::size_t dedup_count = 0; + std::vector heap_dedup; + auto add_dedup = [&](VkSemaphore f, std::uint64_t v, std::uint64_t vis) { + if (!f || f == progress_) return; + PendingSignal* data = heap_dedup.empty() ? stack_dedup : heap_dedup.data(); + const std::size_t count = heap_dedup.empty() ? dedup_count : heap_dedup.size(); + for (std::size_t i = 0; i < count; ++i) { + if (data[i].fence == f) { + if (v > data[i].value) data[i].value = v; + if (vis > data[i].visibility_seq) data[i].visibility_seq = vis; + return; + } + } + if (heap_dedup.empty()) { + if (dedup_count < 16) { + stack_dedup[dedup_count++] = {f, v, vis}; + return; + } + heap_dedup.assign(stack_dedup, stack_dedup + dedup_count); + } + heap_dedup.push_back({f, v, vis}); + }; + for (const PendingSignal& sig : extra_signals) { + add_dedup(sig.fence, sig.value, sig.visibility_seq); + } + const PendingSignal* const dedup_ptr = heap_dedup.empty() ? stack_dedup : heap_dedup.data(); + const std::size_t dedup_size = heap_dedup.empty() ? dedup_count : heap_dedup.size(); + + // A signal-only submit (no command buffer) does not run before_execute_(): carry any CPU-signaled fence + // visibility epoch from its consumed user waits (and any prior signal-only wait epoch on this queue) both to + // this queue's next execute_now() and transitively onto every signaled fence in QueueHolds. + const std::uint64_t consumed_wait_vis = + command_buffer ? 0 : (std::max)(pending_wait_vis_seq_, exec_waits_vis_seq()); + std::uint64_t mirror_bind_waited = 0; + VkSemaphore title_upload_waited_sem = VK_NULL_HANDLE; + std::uint64_t title_upload_waited_val = 0; + VkResult res = VK_SUCCESS; { - std::lock_guard lock(context_.submit_mutex()); - VkSemaphore signals[2]{progress_, VK_NULL_HANDLE}; - std::uint64_t signal_values[2]{ticket, 0}; + std::unique_lock lock(context_.submit_mutex(), std::defer_lock); + submit_phases::lock_timed(lock); // a wait for another queue's submit is counted (the frame line) + auto add_lazy_wait = [&](VkSemaphore sem, std::uint64_t val) { + if (!using_sparse) { + sparse_waits_ = exec_waits_; + sparse_values_ = exec_wait_values_; + using_sparse = true; + } + bool merged = false; + for (std::size_t i = 0; i < sparse_waits_.size(); ++i) { + if (sparse_waits_[i] == sem) { + if (val > sparse_values_[i]) sparse_values_[i] = val; + merged = true; + break; + } + } + if (!merged) { + sparse_waits_.push_back(sem); + sparse_values_.push_back(val); + } + semaphores = sparse_waits_; + values = sparse_values_; + if (semaphores.size() > 16) { + submit_stages_.assign(semaphores.size(), kAllCmds); + stages_ptr = submit_stages_.data(); + } + }; + // Check the page mirror's latest bind under submit_mutex_ (serialized with note_mirror_bind() and + // record_submit_locked()), so every command-buffer submission stamped after note_mirror_bind() waits on + // the sparse bind before reading any mirrored page. + if (command_buffer && context_.mirror_bind_semaphore_ && context_.mirror_bind_value_ > mirror_bind_seen_) { + add_lazy_wait(context_.mirror_bind_semaphore_, context_.mirror_bind_value_); + mirror_bind_waited = context_.mirror_bind_value_; + } + // Check the latest staged title-texture upload timeline under submit_mutex_ (serialized with + // note_title_upload_locked()), so every queue waits lazily on its next command-buffer submit without + // empty wait-only vkQueueSubmits per consumer queue. + if (command_buffer && context_.title_upload_semaphore_ && + (context_.title_upload_semaphore_ != title_upload_sem_seen_ || + context_.title_upload_value_ > title_upload_seen_)) { + add_lazy_wait(context_.title_upload_semaphore_, context_.title_upload_value_); + title_upload_waited_sem = context_.title_upload_semaphore_; + title_upload_waited_val = context_.title_upload_value_; + } + VkSemaphore stack_signals[17]{progress_}; + std::uint64_t stack_signal_values[17]{ticket}; + std::uint64_t stack_signal_vis[17]{0}; + VkSemaphore* signals_ptr = stack_signals; + std::uint64_t* signal_values_ptr = stack_signal_values; + std::uint64_t* signal_vis_ptr = stack_signal_vis; std::uint32_t signal_count = 1; + if (dedup_size + 1 > 17) { + submit_signals_.clear(); + submit_signal_values_.clear(); + submit_signal_vis_.clear(); + submit_signals_.reserve(dedup_size + 1); + submit_signal_values_.reserve(dedup_size + 1); + submit_signal_vis_.reserve(dedup_size + 1); + submit_signals_.push_back(progress_); + submit_signal_values_.push_back(ticket); + submit_signal_vis_.push_back(0); + } // Decided under the submit lock, so the order of the checks is the order of the submissions. A Signal // that is not above what was already submitted for this fence (a held Signal(F, 2) released after an // unheld Signal(F, 3)) leaves the Vulkan signal out: the timeline cannot go down, and waits for 2 pass. // The value counts as submitted only after the submit succeeded (below). - const bool signals_fence = fence && context_.holds().would_signal(fence, value); - if (signals_fence) { - signals[signal_count] = fence; - signal_values[signal_count] = value; + for (std::size_t i = 0; i < dedup_size; ++i) { + const VkSemaphore f = dedup_ptr[i].fence; + const std::uint64_t v = dedup_ptr[i].value; + if (!context_.holds().would_signal(f, v)) continue; + const std::uint64_t sig_vis = + command_buffer ? 0 : (std::max)(consumed_wait_vis, dedup_ptr[i].visibility_seq); + if (dedup_size + 1 > 17) { + submit_signals_.push_back(f); + submit_signal_values_.push_back(v); + submit_signal_vis_.push_back(sig_vis); + } else { + stack_signals[signal_count] = f; + stack_signal_values[signal_count] = v; + stack_signal_vis[signal_count] = sig_vis; + } ++signal_count; } + if (dedup_size + 1 > 17) { + signals_ptr = submit_signals_.data(); + signal_values_ptr = submit_signal_values_.data(); + signal_vis_ptr = submit_signal_vis_.data(); + } VkTimelineSemaphoreSubmitInfo timeline{VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO}; timeline.waitSemaphoreValueCount = std::uint32_t(values.size()); timeline.pWaitSemaphoreValues = values.data(); timeline.signalSemaphoreValueCount = signal_count; - timeline.pSignalSemaphoreValues = signal_values; + timeline.pSignalSemaphoreValues = signal_values_ptr; VkSubmitInfo submit{VK_STRUCTURE_TYPE_SUBMIT_INFO, &timeline}; submit.waitSemaphoreCount = std::uint32_t(semaphores.size()); submit.pWaitSemaphores = semaphores.data(); - submit.pWaitDstStageMask = stages.data(); + submit.pWaitDstStageMask = stages_ptr; submit.commandBufferCount = command_buffer ? 1 : 0; submit.pCommandBuffers = &command_buffer; submit.signalSemaphoreCount = signal_count; - submit.pSignalSemaphores = signals; + submit.pSignalSemaphores = signals_ptr; // LEONIDA_PASS_TRACE= (with LEONIDA_DEVICE_FAULT=1): in the frame after every n-th present, each // submission logs its compute programs in order (repeats folded), for the frame's pass order. if (diagnostics) pass_trace(*diagnostics); @@ -4488,9 +6193,9 @@ class VulkanQueue : private QueueHolds::Holder { record.progress = progress_; record.ticket = ticket; record.buffers = submit.commandBufferCount; - if (signals_fence) { - record.fence = fence; - record.fence_value = value; + if (signal_count > 1) { + record.fence = signals_ptr[signal_count - 1]; + record.fence_value = signal_values_ptr[signal_count - 1]; } record.waits = std::uint32_t(semaphores.size()); for (std::size_t i = 0; i < semaphores.size() && i < SubmitRecord::max_waits; ++i) { @@ -4499,18 +6204,21 @@ class VulkanQueue : private QueueHolds::Holder { } ring_at = ring->begin_submit(record); } + const std::int64_t call_start = submit_phases::now_ns(); res = context_.observe_result(context_.queue_submit(queue_, 1, &submit, context_.gpu_labels_.submit_fence(command_buffer)), "vkQueueSubmit"); + submit_phases::add_part(submit_phases::part_submit_call, std::uint64_t(submit_phases::now_ns() - call_start)); context_.gpu_labels_.submitted(command_buffer, res == VK_SUCCESS); if (ring) ring->end_submit(ring_at, diagnostic_ms() - submit_start, res); if (res == VK_SUCCESS) { context_.record_submit_locked(progress_, ticket); - if (signals_fence) context_.holds().signaled(fence, value); + for (std::uint32_t i = 1; i < signal_count; ++i) + context_.holds().signaled(signals_ptr[i], signal_values_ptr[i], signal_vis_ptr[i]); } } if (res == VK_ERROR_DEVICE_LOST) { context_.mark_device_lost(); - clear_waits(); + clear_exec_waits(); return false; } const bool ok = (res == VK_SUCCESS); @@ -4521,14 +6229,35 @@ class VulkanQueue : private QueueHolds::Holder { context_.enqueue_fence_callback(progress_, ticket, [kind, at] { gpu_latency::done(kind, at); }); } if (ok) { + if (mirror_bind_waited > mirror_bind_seen_) mirror_bind_seen_ = mirror_bind_waited; + if (title_upload_waited_sem) { + title_upload_sem_seen_ = title_upload_waited_sem; + title_upload_seen_ = title_upload_waited_val; + } + if (consumed_wait_vis > pending_wait_vis_seq_) pending_wait_vis_seq_ = consumed_wait_vis; submitted_ = ticket; - clear_waits(ticket); + submitted_gpu_.store(ticket, std::memory_order_release); + clear_exec_waits(ticket); for (auto& slot : buffers_) if (slot.buffer == command_buffer) slot.ticket = ticket; } return ok; } + struct ExecReplayState { + std::unique_lock* tracker_lock = nullptr; + std::vector* khr_stages = nullptr; + std::vector* khr_as_queries = nullptr; + std::unique_ptr* pred_batch = nullptr; + std::unique_ptr* copy_batch = nullptr; + std::unique_ptr* counted_batch = nullptr; + std::unique_ptr* clamp_batch = nullptr; + Depth24Guard* depth24_guard = nullptr; + ScratchGuard* scratch_guard = nullptr; + CommandSlot* slot = nullptr; + bool* ordered_timestamps = nullptr; + }; + VulkanContext& context_; VkQueue queue_; QueueKind kind_ = QueueKind::direct; @@ -4536,12 +6265,22 @@ class VulkanQueue : private QueueHolds::Holder { VkCommandPool pool_ = VK_NULL_HANDLE; VkSemaphore progress_ = VK_NULL_HANDLE; // our own timeline: which command buffers are done std::uint64_t submitted_ = 0; + std::atomic submitted_gpu_{0}; // mirror of submitted_, read lock-free by has_pending_gpu_work() std::vector buffers_; std::vector free_events_; // unsignaled, for order_timestamp_copy std::unique_ptr occlusion_resolve_; std::uint64_t storage_init_seen_ = 0; // the storage_init_version_ this queue has waited for std::uint64_t bindless_upload_seen_ = 0; // the bindless_upload_version_ this queue has waited for + std::uint64_t mirror_bind_seen_ = 0; // the page mirror's bind value this queue has waited for + VkSemaphore title_upload_sem_seen_ = VK_NULL_HANDLE; + std::uint64_t title_upload_seen_ = 0; // the staged title-upload timeline value this queue has waited for + std::uint64_t pending_wait_vis_seq_ = 0; // CPU Fence::Signal visibility epoch carried from signal-only wait std::uint64_t prelude_seen_ = 0; // the prelude_version_ this queue has waited for (or recorded) + ReplayFunctions cached_replay_{}; + std::uint64_t cached_replay_version_ = 0; + void (*cached_replay_on_buffer_write_)(void*) = nullptr; + void* cached_replay_on_buffer_write_ctx_ = nullptr; + ExecReplayState exec_replay_state_{}; std::uint64_t last_sparse_ = 0; std::deque pending_bindings_; std::vector waits_; @@ -4569,13 +6308,16 @@ class VulkanQueue : private QueueHolds::Holder { return depth; } - bool async_on() const { return async_depth() && !synchronous_; } + bool async_on() const { return async_depth_ && !synchronous_; } struct Call { enum class Kind : std::uint8_t { execute, signal, wait, marker }; Kind kind = Kind::execute; - std::uint64_t seq = 0, execute_call = 0, value = 0; - std::vector lists; // copies: the application may Reset its lists after the call + bool barrier_after = false; // Present / after_held() arrived after this call: do not merge past it + std::uint64_t seq = 0, present_epoch = kUnsetEpoch, execute_call = 0, visibility_seq = 0, value = 0; + EnqueueSerial enqueue_serial; + // Immutable closed CommandList snapshots (zero-copy when submitted via shared_ptr). + std::vector> lists; std::shared_ptr pin; // the fence, or the lists' pipeline states and root signatures VkSemaphore fence = VK_NULL_HANDLE; DebugMarker::Kind marker_kind = DebugMarker::Kind::set; @@ -4589,6 +6331,35 @@ class VulkanQueue : private QueueHolds::Holder { std::chrono::steady_clock::time_point since = std::chrono::steady_clock::now(); }; + // Counts distinct frame / barrier groups pending in inbox_ (plus 1 when the worker is busy): intra-frame + // cross-queue Wait/Signal splits within the same present_epoch stay in ONE frame group so a barrier-heavy frame + // (25+ Direct batches separated by cross-queue Waits) does not stall the title thread on room_cv_ mid-frame + // (which would also delay posting cross-queue Signals needed by earlier queued Waits), while async_depth_ still + // bounds distinct frames (Present / after_held barriers) and max_batches bounds total queued batch memory. + // inbox_mutex_ held. + std::size_t pending_frame_groups_locked() const { + std::size_t groups = worker_busy_ ? 1 : 0; + bool in_group = false; + std::uint64_t prev_epoch = kUnsetEpoch; + bool prev_barrier = false; + for (const Call& c : inbox_) { + if (c.kind == Call::Kind::execute) { + if (!in_group || prev_barrier || c.present_epoch != prev_epoch) { + ++groups; + in_group = true; + } + prev_epoch = c.present_epoch; + prev_barrier = c.barrier_after; + } else if (in_group && (prev_barrier || c.present_epoch != prev_epoch)) { + in_group = false; + prev_barrier = false; + } else if (in_group && c.barrier_after) { + prev_barrier = true; + } + } + return groups; + } + void enqueue(Call&& call) { const bool batch = call.kind == Call::Kind::execute; std::unique_lock lock(inbox_mutex_); @@ -4596,15 +6367,25 @@ class VulkanQueue : private QueueHolds::Holder { worker_ = std::thread([this] { async_worker(); }); async_started_.store(true, std::memory_order_release); } - // n batches, and 4n calls of any kind (a title that signals after every small job must not queue Signals - // without bound). n = 1 makes each caller wait for the batch before it: n should be 2 or more. - const auto room = [this, batch] { - return async_stop_ || - ((!batch || inbox_batches_ < async_depth()) && inbox_.size() < 4 * std::size_t(async_depth())); + // n frame groups, with bounded batch headroom for multi-batch frames (max(16n, 64) batches, 4x calls when + // n >= 2; n = 1 keeps strict single-batch backpressure). + const std::size_t max_batches = + async_depth_ <= 1 ? std::size_t(async_depth_) + : (std::max)(std::size_t(async_depth_) * 16, std::size_t(64)); + const std::size_t max_calls = max_batches * 4; + const auto room = [this, batch, max_batches, max_calls] { + if (async_stop_) return true; + if (inbox_.size() >= max_calls) return false; + if (!batch) return true; + if (inbox_batches_ < async_depth_) return true; + if (async_depth_ <= 1 || inbox_batches_ >= max_batches) return false; + return pending_frame_groups_locked() < async_depth_; }; if (!room()) { const auto start = std::chrono::steady_clock::now(); + ++room_waiters_; room_cv_.wait(lock, room); + --room_waiters_; ++async_stats_.room_waits; async_stats_.room_wait_ns += std::uint64_t( std::chrono::duration_cast(std::chrono::steady_clock::now() - start).count()); @@ -4614,61 +6395,424 @@ class VulkanQueue : private QueueHolds::Holder { ++async_stats_.batches; } ++async_stats_.calls; + call.present_epoch = submit_phases::totals().present_calls.load(std::memory_order_acquire); call.seq = context_.holds().next_seq(); call.queued_at = std::chrono::steady_clock::now(); context_.holds().held_changed(1); + context_.holds().work_changed(1); inbox_.push_back(std::move(call)); - async_stats_.depth_max = std::max(async_stats_.depth_max, inbox_.size()); + async_stats_.depth_max = (std::max)(async_stats_.depth_max, inbox_.size()); lock.unlock(); inbox_cv_.notify_one(); } void async_worker() { t_worker_of_ = this; + std::vector group_calls; + group_calls.reserve(16); for (;;) { - Call call; - bool have = false, release = false; + Call single_call; + group_calls.clear(); + bool have_single = false; + bool release = false; + std::size_t exec_count = 0; + std::int64_t consumed_work = 0; { std::unique_lock lock(inbox_mutex_); inbox_cv_.wait(lock, [this] { return !inbox_.empty() || release_requested_ || async_stop_; }); release = std::exchange(release_requested_, false); + if (release) ++consumed_work; if (!inbox_.empty()) { - call = std::move(inbox_.front()); - inbox_.pop_front(); - running_seq_ = call.seq; - have = true; + if (inbox_.front().kind == Call::Kind::execute) { + const std::uint64_t bseq = barrier_seq_.load(std::memory_order_acquire); + group_calls.push_back(std::move(inbox_.front())); + inbox_.pop_front(); + exec_count = 1; + ++consumed_work; + bool stop_after_signal = false; + while (!group_calls.back().barrier_after && !inbox_.empty()) { + const Call& next = inbox_.front(); + if (crosses_barrier(group_calls.back().seq, next.seq, group_calls.back().present_epoch, + next.present_epoch, bseq)) + break; + if (next.kind == Call::Kind::execute) { + if (stop_after_signal) break; + group_calls.push_back(std::move(inbox_.front())); + inbox_.pop_front(); + ++exec_count; + ++consumed_work; + } else if (next.kind == Call::Kind::signal) { + group_calls.push_back(std::move(inbox_.front())); + inbox_.pop_front(); + ++consumed_work; + if (context_.has_unsatisfied_waiter(group_calls.back().fence, group_calls.back().value)) + stop_after_signal = true; + } else if (next.kind == Call::Kind::wait && !stop_after_signal && + wait_already_completed(next.fence, next.value)) { + group_calls.push_back(std::move(inbox_.front())); + inbox_.pop_front(); + ++consumed_work; + } else { + break; + } + } + running_seq_ = group_calls.front().seq; + // A coalesced group executes as ONE in-flight submission; release the (exec_count - 1) merged + // batch slots immediately so enqueue() can accumulate the next coalescing window without stalling. + if (exec_count > 1) inbox_batches_ -= (exec_count - 1); + if (room_waiters_ > 0) room_cv_.notify_all(); + } else { + single_call = std::move(inbox_.front()); + inbox_.pop_front(); + running_seq_ = single_call.seq; + have_single = true; + ++consumed_work; + if (room_waiters_ > 0) room_cv_.notify_all(); + } } else if (!release) { return; // stopping, nothing queued } worker_busy_ = true; + // Transfer consumed inbox/release work into this worker turn: keep +1 active until pump_ready() ends. + if (consumed_work != 1) context_.holds().work_changed(1 - consumed_work); } - if (release) release_held(); - std::uint64_t ran_ns = 0; + struct WorkerTurnGuard { + QueueHolds& holds; + ~WorkerTurnGuard() { holds.work_changed(-1); } + } turn_guard{context_.holds()}; + const std::size_t group_count = group_calls.size(); + const bool have = have_single || group_count != 0; + HeldCountGuard inbox_held_guard{ + context_.holds(), have ? -static_cast(group_count ? group_count : 1) : 0}; + // Wrap the entire worker turn (release_held, call execution, and pump_ready) so gate-released batches and + // deferred presents running on async_worker are attributed to worker_submit, never to title threads. + const submit_phases::WorkerScope busy(submit_phases::worker_submit); + const auto turn_start = std::chrono::steady_clock::now(); + DrainInfo rel_info{}; + const bool released = release && release_held(/*from_pump=*/false, &rel_info); + if (released && have) { + const std::uint64_t next_seq = group_count ? group_calls.front().seq : single_call.seq; + const std::uint64_t next_epoch = + group_count ? group_calls.front().present_epoch : single_call.present_epoch; + const std::uint64_t bseq = barrier_seq_.load(std::memory_order_acquire); + if (rel_info.stopped_for_barrier || + crosses_barrier(rel_info.last_seq, next_seq, rel_info.last_epoch, next_epoch, bseq)) { + // Pre-barrier held work finished; pump now and wait for satisfied pre-barrier Presents / + // after_held() callbacks to finish on the barrier thread before post-barrier inbox calls execute. + context_.holds().pump_ready(); + if (next_seq) context_.holds().wait_barriers_drained(next_seq - 1); + } + } + auto have_start = turn_start; if (have) { - const auto start = std::chrono::steady_clock::now(); - run_call(call); - const auto end = std::chrono::steady_clock::now(); - ran_ns = std::uint64_t(std::chrono::duration_cast(end - start).count()); - const auto lag = std::uint64_t( - std::chrono::duration_cast(start - call.queued_at).count()); - std::lock_guard lock(inbox_mutex_); - async_stats_.run_ns += ran_ns; - async_stats_.lag_ns += lag; - async_stats_.lag_max_ns = std::max(async_stats_.lag_max_ns, lag); + have_start = std::chrono::steady_clock::now(); + if (group_count == 1) { + run_call(group_calls[0]); + } else if (group_count > 1) { + run_coalesced_calls(group_calls, exec_count); + } else { + run_call(single_call); + } } + const auto turn_end = std::chrono::steady_clock::now(); + const std::uint64_t ran_ns = (have || released) + ? std::uint64_t(std::chrono::duration_cast(turn_end - turn_start).count()) + : 0; { std::lock_guard lock(inbox_mutex_); + async_stats_.run_ns += ran_ns + async_pump_ns_.exchange(0, std::memory_order_relaxed); + if (have) { + if (group_count != 0) { + for (const Call& c : group_calls) { + const auto lag = std::uint64_t( + std::chrono::duration_cast(have_start - c.queued_at).count()); + async_stats_.lag_ns += lag; + async_stats_.lag_max_ns = (std::max)(async_stats_.lag_max_ns, lag); + } + } else { + const auto lag = std::uint64_t( + std::chrono::duration_cast(have_start - single_call.queued_at) + .count()); + async_stats_.lag_ns += lag; + async_stats_.lag_max_ns = (std::max)(async_stats_.lag_max_ns, lag); + } + } running_seq_ = 0; worker_busy_ = false; - if (have && call.kind == Call::Kind::execute) --inbox_batches_; - if (have) room_cv_.notify_all(); + if (exec_count != 0) --inbox_batches_; + if (room_waiters_ > 0) room_cv_.notify_all(); idle_cv_.notify_all(); report_async_locked(); } - if (have) context_.holds().held_changed(-1); - call = Call{}; // the copies and pins go before the pump, outside the lock - context_.holds().pump_ready(); + inbox_held_guard.release(); + single_call = Call{}; + group_calls.clear(); // the snapshots, pins, and serials go before the pump, outside the lock + if (have || released) { + const auto pump_start = std::chrono::steady_clock::now(); + context_.holds().pump_ready(); + const auto pump_ns = std::uint64_t( + std::chrono::duration_cast(std::chrono::steady_clock::now() - pump_start) + .count()); + async_pump_ns_.fetch_add(pump_ns, std::memory_order_relaxed); + } + } + } + + // Coalesces consecutive execute and Signal items from async_worker's inbox into ONE before_execute_() + ONE + // vkQueueSubmit (with all Signals attached to that submit's timeline signaling, deduplicated to the highest value + // per fence), or moves them into held_ in exact FIFO order when blocked by an unmet Wait so they still coalesce + // when released. Falls back per-call in exact FIFO order on non-device-lost replay failure so valid peers and + // trailing Signals are never dropped. + void run_coalesced_calls(std::vector& calls, std::size_t exec_count) { + try { + run_coalesced_calls_unguarded(calls, exec_count); + } catch (const std::exception& e) { + worker_threw(calls.front(), e.what()); + } catch (...) { + worker_threw(calls.front(), "not a std::exception"); + } + async_seq_ = 0; + } + + void run_coalesced_calls_unguarded(std::vector& calls, std::size_t exec_count) { + QueueHolds::WorkGuard work_guard; + std::vector> retired; + std::vector dropped_serials; + auto hold_all_locked = [&] { + std::vector::Wait> replacements; + for (Call& call : calls) { + if (call.kind == Call::Kind::wait) { + replacements.clear(); + if (context_.holds().lookup_relay(call.fence, call.value, replacements)) { + context_.note_wait_removed(call.fence, call.value); + if (call.pin) retired.push_back(std::move(call.pin)); + for (auto& rep : replacements) { + context_.note_wait_added(rep.semaphore, rep.value); + waits_.push_back(rep.semaphore); + wait_values_.push_back(rep.value); + if (rep.pin) wait_pins_.push_back(std::move(rep.pin)); + } + } else { + waits_.push_back(call.fence); + wait_values_.push_back(call.value); + if (call.pin) wait_pins_.push_back(std::move(call.pin)); + } + continue; + } + async_seq_ = call.seq; + Deferred op; + op.barrier_after = call.barrier_after; + op.present_epoch = call.present_epoch; + op.visibility_seq = call.visibility_seq; + if (call.kind == Call::Kind::signal) { + op.kind = Deferred::Kind::signal; + op.fence = call.fence; + op.value = call.value; + } else { + op.kind = Deferred::Kind::batch; + op.execute_call = call.execute_call; + op.enqueue_serial = std::move(call.enqueue_serial); + op.lists = std::move(call.lists); + } + if (call.pin) op.pins.push_back(std::move(call.pin)); + hold(std::move(op)); + } + async_seq_ = 0; + }; + { + std::unique_lock state(state_mutex_, std::defer_lock); + submit_phases::lock_timed(state); + if (executing_ && !blocked_by_wait_locked() && !context_.is_device_lost()) { + exec_cv_.wait(state, [this] { + return !executing_ || blocked_by_wait_locked() || context_.is_device_lost(); + }); + } + if (context_.is_device_lost()) { + for (Call& call : calls) { + if (call.kind == Call::Kind::wait) context_.note_wait_removed(call.fence, call.value); + if (call.pin) retired.push_back(std::move(call.pin)); + if (call.enqueue_serial.value) dropped_serials.push_back(std::move(call.enqueue_serial)); + } + } else if (!executing_ && !blocked_by_wait_locked()) { + work_guard.arm(context_.holds()); + executing_ = true; + ExecGuard exec_guard{this, state}; + DrainInfo pre_info{}; + if (!held_.empty()) drain_held_while_executing(state, retired, false, &pre_info); + const std::uint64_t bseq_now = barrier_seq_.load(std::memory_order_acquire); + const bool barrier_before_me = + pre_info.released && + (pre_info.stopped_for_barrier || + crosses_barrier(pre_info.last_seq, calls.front().seq, pre_info.last_epoch, + calls.front().present_epoch, bseq_now)); + if (context_.is_device_lost()) { + for (Call& call : calls) { + if (call.kind == Call::Kind::wait) context_.note_wait_removed(call.fence, call.value); + if (call.pin) retired.push_back(std::move(call.pin)); + if (call.enqueue_serial.value) dropped_serials.push_back(std::move(call.enqueue_serial)); + } + } else if (must_hold() || barrier_before_me) { + hold_all_locked(); + if (barrier_before_me) pause_release_for_barrier_.store(true, std::memory_order_release); + } else { + set_active_seq_locked(calls.front().seq); + take_waits_to_exec_locked(); + state.unlock(); + + exec_list_ptrs_.clear(); + exec_batch_breaks_.clear(); + exec_pending_signals_.clear(); + std::uint64_t group_vis_seq = 0; + for (const Call& call : calls) { + if (call.kind == Call::Kind::execute) { + if (!exec_list_ptrs_.empty() && !call.lists.empty()) + exec_batch_breaks_.push_back(exec_list_ptrs_.size()); + for (const auto& list : call.lists) exec_list_ptrs_.push_back(list.get()); + group_vis_seq = (std::max)(group_vis_seq, call.visibility_seq); + } else if (call.kind == Call::Kind::signal) { + exec_pending_signals_.push_back({call.fence, call.value, call.visibility_seq}); + } else if (call.kind == Call::Kind::wait) { + // Preserve CPU Fence::Signal visibility edge across coalesced completed waits. + const std::uint64_t w_vis = context_.holds().signaled_vis_seq(call.fence, call.value); + group_vis_seq = (std::max)(group_vis_seq, w_vis); + } + } + + wait_for_preceding_barriers(calls.front().seq, exec_list_ptrs_); + const ReplayResult result = + execute_now(exec_list_ptrs_, calls.front().execute_call, exec_batch_breaks_, + exec_pending_signals_, group_vis_seq, /*from_held=*/false); + if (result == ReplayResult::success) { + note_coalesced_submit(exec_count); + for (Call& call : calls) { + if (call.kind == Call::Kind::wait) { + context_.note_wait_removed(call.fence, call.value); + if (call.pin) exec_retired_pins_.push_back(std::move(call.pin)); + continue; + } + if (call.pin) { + if (submitted_) exec_ticketed_pins_.push_back({submitted_, std::move(call.pin)}); + else exec_retired_pins_.push_back(std::move(call.pin)); + } + call.enqueue_serial.finish(); + } + } else if (exec_count > 1 && !context_.is_device_lost()) { + for (Call& call : calls) { + if (call.kind == Call::Kind::execute) { + exec_list_ptrs_.clear(); + for (const auto& list : call.lists) exec_list_ptrs_.push_back(list.get()); + const ReplayResult sub = + execute_now(exec_list_ptrs_, call.execute_call, {}, {}, call.visibility_seq, false); + note_coalesced_submit(1); + if (sub != ReplayResult::success) { + int none = static_cast(ReplayResult::success); + held_failure_.compare_exchange_strong(none, static_cast(sub)); + std::fprintf(stderr, + "[rt] d3d12: a queued ExecuteCommandLists failed on the queue's worker " + "(result %d); nothing was submitted for it\n", + static_cast(sub)); + } + if (call.pin) { + if (sub == ReplayResult::success && submitted_) + exec_ticketed_pins_.push_back({submitted_, std::move(call.pin)}); + else + exec_retired_pins_.push_back(std::move(call.pin)); + } + call.enqueue_serial.finish(); + } else if (call.kind == Call::Kind::signal) { + auto saved_waits = std::move(exec_waits_); + auto saved_values = std::move(exec_wait_values_); + auto saved_pins = std::move(exec_wait_pins_); + const std::size_t saved_user = std::exchange(exec_user_wait_count_, 0); + exec_waits_.clear(); + exec_wait_values_.clear(); + exec_wait_pins_.clear(); + const bool ok = + submit(VK_NULL_HANDLE, call.fence, call.value, nullptr, call.visibility_seq); + if (!ok) { + int none = static_cast(ReplayResult::success); + held_failure_.compare_exchange_strong(none, static_cast(ReplayResult::unsupported)); + std::fprintf(stderr, "[rt] d3d12: a queued Signal failed on the queue's worker\n"); + } + if (call.pin) { + if (ok && submitted_) + exec_ticketed_pins_.push_back({submitted_, std::move(call.pin)}); + else + exec_retired_pins_.push_back(std::move(call.pin)); + } + exec_waits_ = std::move(saved_waits); + exec_wait_values_ = std::move(saved_values); + exec_wait_pins_ = std::move(saved_pins); + exec_user_wait_count_ = saved_user; + } else if (call.kind == Call::Kind::wait) { + const std::uint64_t w_vis = context_.holds().signaled_vis_seq(call.fence, call.value); + pending_wait_vis_seq_ = (std::max)(pending_wait_vis_seq_, w_vis); + context_.note_wait_removed(call.fence, call.value); + if (call.pin) exec_retired_pins_.push_back(std::move(call.pin)); + } + } + } else { + note_coalesced_submit(exec_count); + int none = static_cast(ReplayResult::success); + held_failure_.compare_exchange_strong(none, static_cast(result)); + auto saved_waits = std::move(exec_waits_); + auto saved_values = std::move(exec_wait_values_); + auto saved_pins = std::move(exec_wait_pins_); + const std::size_t saved_user = std::exchange(exec_user_wait_count_, 0); + exec_waits_.clear(); + exec_wait_values_.clear(); + exec_wait_pins_.clear(); + for (Call& call : calls) { + if (call.kind == Call::Kind::signal && !context_.is_device_lost()) { + const bool ok = + submit(VK_NULL_HANDLE, call.fence, call.value, nullptr, call.visibility_seq); + if (!ok) { + int none_s = static_cast(ReplayResult::success); + held_failure_.compare_exchange_strong(none_s, static_cast(ReplayResult::unsupported)); + std::fprintf(stderr, "[rt] d3d12: a queued Signal failed on the queue's worker\n"); + } + if (call.pin) { + if (ok && submitted_) + exec_ticketed_pins_.push_back({submitted_, std::move(call.pin)}); + else + exec_retired_pins_.push_back(std::move(call.pin)); + } + } else { + if (call.kind == Call::Kind::wait) context_.note_wait_removed(call.fence, call.value); + if (call.pin) exec_retired_pins_.push_back(std::move(call.pin)); + call.enqueue_serial.finish(); + } + } + exec_waits_ = std::move(saved_waits); + exec_wait_values_ = std::move(saved_values); + exec_wait_pins_ = std::move(saved_pins); + exec_user_wait_count_ = saved_user; + } + + state.lock(); + restore_exec_waits_locked(); + flush_exec_pins_locked(retired); + set_active_seq_locked(0); + const std::uint64_t bseq_after = barrier_seq_.load(std::memory_order_acquire); + const bool barrier_after_group = + calls.back().barrier_after || + (!held_.empty() && + crosses_barrier(calls.back().seq, held_.front().seq, calls.back().present_epoch, + held_.front().present_epoch, bseq_after)); + if (barrier_after_group) { + if (!held_.empty()) pause_release_for_barrier_.store(true, std::memory_order_release); + } else { + drain_held_while_executing(state, retired); + } + } + exec_guard.release(); + } else { + hold_all_locked(); + } + drain_pins(retired); } + for (EnqueueSerial& s : dropped_serials) s.finish(); + retired.clear(); } // An exception on the worker would end the process (std::terminate) and leave the queue's callers waiting: it is @@ -4700,13 +6844,24 @@ class VulkanQueue : private QueueHolds::Holder { void run_call_unguarded(Call& call) { async_seq_ = call.seq; - const PinFn pin = call.pin ? PinFn([&call] { return call.pin; }) : PinFn{}; switch (call.kind) { case Call::Kind::execute: { - std::vector lists; - lists.reserve(call.lists.size()); - for (const CommandList& list : call.lists) lists.push_back(&list); - const ReplayResult result = execute_sync(lists, pin, call.execute_call); + const CommandList* small_ptrs[16]; + std::vector large_ptrs; + const CommandList* const* ptr_data = nullptr; + if (call.lists.size() <= 16) { + for (std::size_t i = 0; i < call.lists.size(); ++i) small_ptrs[i] = call.lists[i].get(); + ptr_data = small_ptrs; + } else { + large_ptrs.reserve(call.lists.size()); + for (const auto& list : call.lists) large_ptrs.push_back(list.get()); + ptr_data = large_ptrs.data(); + } + const std::size_t count = call.lists.size(); + const ReplayResult result = execute_sync_impl( + {ptr_data, count}, {}, call.execute_call, [&call] { return std::move(call.lists); }, + std::move(call.pin), std::move(call.enqueue_serial), call.barrier_after, call.present_epoch, + call.visibility_seq); if (result != ReplayResult::success) { int none = static_cast(ReplayResult::success); held_failure_.compare_exchange_strong(none, static_cast(result)); @@ -4717,23 +6872,23 @@ class VulkanQueue : private QueueHolds::Holder { break; } case Call::Kind::signal: - if (!signal_sync(call.fence, call.value, pin)) { + if (!signal_sync(call.fence, call.value, {}, std::move(call.pin), call.present_epoch, + call.visibility_seq)) { int none = static_cast(ReplayResult::success); held_failure_.compare_exchange_strong(none, static_cast(ReplayResult::unsupported)); std::fprintf(stderr, "[rt] d3d12: a queued Signal failed on the queue's worker\n"); } break; - case Call::Kind::wait: wait_sync(call.fence, call.value, pin); break; - case Call::Kind::marker: marker_sync(call.marker_kind, call.label.c_str()); break; - } - if (call.pin && call.kind == Call::Kind::execute) { - // The pipeline states stay alive until what was just submitted has completed (a held batch keeps its own). - std::lock_guard state(state_mutex_); - std::vector> pins{std::move(call.pin)}; - retire_pins(pins, submitted_); + case Call::Kind::wait: wait_sync(call.fence, call.value, {}, std::move(call.pin), /*already_tracked=*/true); break; + case Call::Kind::marker: marker_sync(call.marker_kind, call.label.c_str(), call.present_epoch); break; } } + void note_coalesced_submit(std::size_t batches) noexcept { + coalesced_batches_.fetch_add(batches, std::memory_order_relaxed); + coalesced_submits_.fetch_add(1, std::memory_order_relaxed); + } + // Every 10 s, per queue: what the worker did. Called with inbox_mutex_ held. void report_async_locked() { const auto now = std::chrono::steady_clock::now(); @@ -4741,12 +6896,16 @@ class VulkanQueue : private QueueHolds::Holder { if (s < 10.0) return; static constexpr const char* kinds[] = {"direct", "compute", "copy"}; const AsyncStats& a = async_stats_; + const std::uint64_t merged_batches = coalesced_batches_.exchange(0, std::memory_order_relaxed); + const std::uint64_t merged_submits = coalesced_submits_.exchange(0, std::memory_order_relaxed); std::fprintf(stderr, - "[rt] submit-async: %s queue %p: %.1f calls/s (%.1f batches/s), queued now %zu (max %zu), " - "worker busy %.0f%%, call waited for the worker avg %.2f ms max %.2f ms, caller waited for " - "room %llu times %.1f ms\n", + "[rt] submit-async: %s queue %p: %.1f calls/s (%.1f batches/s, merged %llu batches into %llu " + "submits), queued now %zu (max %zu), worker busy %.0f%%, call waited for the worker avg %.2f ms " + "max %.2f ms, caller waited for room %llu times %.1f ms\n", kinds[int(kind_) < 3 ? int(kind_) : 0], static_cast(this), double(a.calls) / s, - double(a.batches) / s, inbox_.size(), a.depth_max, 100.0 * double(a.run_ns) / (s * 1e9), + double(a.batches) / s, static_cast(merged_batches), + static_cast(merged_submits), inbox_.size(), a.depth_max, + 100.0 * double(a.run_ns) / (s * 1e9), a.calls ? double(a.lag_ns) / double(a.calls) / 1e6 : 0.0, double(a.lag_max_ns) / 1e6, static_cast(a.room_waits), double(a.room_wait_ns) / 1e6); async_stats_ = AsyncStats{}; @@ -4758,7 +6917,7 @@ class VulkanQueue : private QueueHolds::Holder { bool flush_async() { if (!async_started_.load(std::memory_order_acquire) || t_worker_of_ == this) return true; std::unique_lock lock(inbox_mutex_); - const auto idle = [this] { return inbox_.empty() && !worker_busy_; }; + const auto idle = [this] { return inbox_.empty() && !worker_busy_ && !release_requested_; }; for (int slice = 1; slice <= 6; ++slice) { if (idle_cv_.wait_for(lock, std::chrono::seconds(10), idle)) return true; std::fprintf(stderr, "[rt] d3d12: waited %d s for a queue's worker to finish what is queued (%zu calls, " @@ -4793,19 +6952,33 @@ class VulkanQueue : private QueueHolds::Holder { std::condition_variable inbox_cv_, room_cv_, idle_cv_; std::deque inbox_; std::size_t inbox_batches_ = 0; - std::uint64_t running_seq_ = 0; // the call the worker runs now + std::size_t room_waiters_ = 0; + std::uint64_t running_seq_ = 0; // oldest seq of the call(s) the worker runs now bool worker_busy_ = false, release_requested_ = false, async_stop_ = false; AsyncStats async_stats_; + std::atomic async_pump_ns_{0}; // pump_ready() ns folded into async_stats_.run_ns on next lock + unsigned async_depth_ = async_depth(); std::atomic async_started_{false}; bool synchronous_ = false; // make_synchronous() + std::atomic skip_before_execute_{false}; // set_skip_before_execute() + std::atomic coalesced_batches_{0}; + std::atomic coalesced_submits_{0}; std::thread worker_; static inline thread_local VulkanQueue* t_worker_of_ = nullptr; // the queue whose worker this thread is static inline thread_local std::uint64_t async_seq_ = 0; // the sequence number of the call being run - std::atomic held_front_seq_{0}; // held_.front().seq, 0 when empty; see release_held() - - // Wait-before-Signal. state_mutex_ is outermost (before pipeline_mutex_ -> resource_mutex_ -> tracker_mutex_ -> - // submit_mutex_) and guards the members above that execute, signal, wait and marker touch. + std::atomic held_front_seq_{0}; // min_nonzero(active_seq_, held_.front().seq); see release_held() + std::atomic has_held_{false}; // !held_.empty(), lock-free check for cross-queue release_ready() + std::atomic barrier_seq_{0}; // monotonic newest seq seen by oldest_held_seq() (after_held barrier) + std::atomic pause_release_for_barrier_{false}; // yield once to pump_ready() so run_barriers() fires first + + // Wait-before-Signal & queue state. state_mutex_ is held ONLY for short bookkeeping (never across + // before_execute_(), execute_now(), submit(), bind_tiles(), or pin destruction). Execution on this queue is + // serialized by executing_ (true while one thread runs/drains work): Wait/Signal/Marker and wait-blocked + // batches append under state_mutex_ without blocking, while unblocked sync execute() waits on exec_cv_. std::mutex state_mutex_; + std::condition_variable exec_cv_; + bool executing_ = false; + std::uint64_t active_seq_ = 0; std::deque held_; std::vector> wait_pins_; // keep the fences of waits_ alive std::vector> retired_pins_; // released by the caller once state_mutex_ is dropped @@ -4814,6 +6987,26 @@ class VulkanQueue : private QueueHolds::Holder { std::shared_ptr pin; }; std::deque pin_queue_; // released once progress_ reaches the ticket + // Execution-owned wait, pin & scratch staging (touched only by the single thread owning executing_ == true). + std::vector exec_waits_; + std::vector exec_wait_values_; + std::size_t exec_user_wait_count_ = 0; + std::vector> exec_wait_pins_; + std::vector> exec_retired_pins_; + std::vector exec_ticketed_pins_; + std::vector exec_list_ptrs_; + std::vector exec_batch_breaks_; + std::vector exec_pending_signals_; + std::vector geometry_uploads_; + std::vector storage_images_scratch_; + std::vector zero_buffers_scratch_; + std::vector sparse_waits_; + std::vector sparse_values_; + std::vector submit_stages_; + std::vector submit_signals_; + std::vector submit_signal_values_; + std::vector submit_signal_vis_; + EmitScratch emit_scratch_; std::atomic held_failure_{0}; // a ReplayResult: the first held batch that failed }; diff --git a/runtime/src/vulkan_bindless.h b/runtime/src/vulkan_bindless.h index fc1b2f555e..8907b0d663 100644 --- a/runtime/src/vulkan_bindless.h +++ b/runtime/src/vulkan_bindless.h @@ -76,6 +76,7 @@ #include #include +#include #include #include #include @@ -398,6 +399,7 @@ class BindlessSet { : device_(device), memory_(memory), features_(features), families_(std::move(families)), table_(64, descriptor_hash) { ok_ = vk_.load(get, device) && create_layout() && create_fallbacks() && create_table_buffers() && fill(); + sync_fast_state(); } ~BindlessSet() { @@ -438,12 +440,22 @@ class BindlessSet { std::uint32_t sampler_capacity() const { return features_.counts[bindless::sampler_binding]; } // How many more images of a dimension, or samplers, add_image and add_sampler can take before they return 0. std::uint32_t free_images(ImageDimension dimension) const { - const auto& used = image_used_[std::uint32_t(dimension)]; - return std::uint32_t(std::count(used.begin(), used.end(), std::uint8_t(0))); + const std::uint32_t d = std::uint32_t(dimension); + return free_low_count_[d] + free_high_count_[d]; + } + std::uint32_t free_storage_images(ImageDimension dimension) const { + return free_low_count_[std::uint32_t(dimension)]; } - std::uint32_t free_samplers() const { - return std::uint32_t(std::count(sampler_used_.begin(), sampler_used_.end(), std::uint8_t(0))); + std::uint32_t total_free_images() const noexcept { + return total_free_images_.load(std::memory_order_acquire); + } + bool has_free_image(ImageDimension dimension, bool stores, std::uint32_t sampled_class = 0) const { + if (!stores && bindless::sampled_binding(dimension) == bindless::no_binding) return false; + if (bindless::multisampled(dimension) && (stores || !supports_ms_class(sampled_class))) return false; + const std::uint32_t d = std::uint32_t(dimension); + return stores ? (free_low_count_[d] > 0) : (free_low_count_[d] + free_high_count_[d] > 0); } + std::uint32_t free_samplers() const { return free_sampler_count_; } // Set 0 of every pipeline layout made for translated shaders. VkDescriptorSetLayout layout() const { return layout_; } // Bound at set 0. flush() updates it in place until flush_replaces_table() is true: then the flush makes a new @@ -451,11 +463,18 @@ class BindlessSet { // that bound the previous set keeps it, intact, until release_retired() frees it. VkDescriptorSet set() const { return set_; } + // Lock-free clean-state queries for the submission hot path (published with release semantics after every mutation + // under the owner's descriptor lock, so clean submissions skip descriptor_mutex completely). + bool needs_prepare() const noexcept { return needs_prepare_.load(std::memory_order_acquire); } + VkDescriptorSet current_set() const noexcept { return current_set_.load(std::memory_order_acquire); } + bool needs_commit() const noexcept { return needs_commit_.load(std::memory_order_acquire); } + // The fallback images are created with undefined contents: record this once, in a command buffer that executes // before anything uses the set. It moves them to GENERAL, the layout their descriptors name, and zeroes them. bool fallbacks_ready() const { return fallbacks_ready_; } void record_fallback_init(VkCommandBuffer command_buffer) { fallbacks_ready_ = true; + sync_fast_state(); std::vector barriers; std::vector images; for (const auto& image : fallback_images_) images.push_back(&image); @@ -511,58 +530,57 @@ class BindlessSet { const bool stores = storage.as_float || storage.as_uint || storage.as_sint || storage.r32ui; if (!stores && bindless::sampled_binding(dimension) == bindless::no_binding) return 0; if (bindless::multisampled(dimension) && (stores || !supports_ms_class(sampled_class))) return 0; - auto& used = image_used_[std::uint32_t(dimension)]; - const std::uint32_t low_end = std::min(std::uint32_t(used.size()), storage_capacity(dimension)); - std::vector* used_2d = nullptr; // the mirror's index space, when there is one - if (mirror && dimension != ImageDimension::dim_2d && mirror->sampled) { - used_2d = &image_used_[std::uint32_t(ImageDimension::dim_2d)]; - if (mirror->sampled_layout == VK_IMAGE_LAYOUT_UNDEFINED) used_2d = nullptr; + const std::uint32_t d = std::uint32_t(dimension); + const auto& used = image_used_[d]; + const std::uint32_t low_end = low_end_[d]; + bool want_mirror = false; + if (mirror && dimension != ImageDimension::dim_2d && mirror->sampled && + mirror->sampled_layout != VK_IMAGE_LAYOUT_UNDEFINED) { + want_mirror = true; } // A store through the array T# and one through its 2D slice both have to land on a view, so an index with // storage views must be inside this dimension's storage arrays and, when the mirror has storage views too, // inside the 2D arrays' (their range can be the shorter of the two). const bool any_stores = stores || mirror_storage(mirror); - const std::uint32_t mirrored_storage_end = std::min(stores ? low_end : std::uint32_t(used.size()), - storage_capacity(ImageDimension::dim_2d)); + const std::uint32_t mirrored_storage_end = + (std::min)(stores ? low_end : std::uint32_t(used.size()), storage_capacity(ImageDimension::dim_2d)); std::uint32_t index = 0; - if (used_2d) { - index = any_stores ? allocate_pair(used, *used_2d, 1, mirrored_storage_end) - : allocate_pair(used, *used_2d, low_end, std::uint32_t(used.size())); - if (!index && !any_stores) index = allocate_pair(used, *used_2d, 1, low_end); + if (want_mirror) { + index = any_stores ? allocate_pair(dimension, 1, mirrored_storage_end) + : allocate_pair(dimension, low_end, std::uint32_t(used.size())); + if (!index && !any_stores) index = allocate_pair(dimension, 1, low_end); if (!index) { // No shared slot: the image still gets its own dimension's slot, unmirrored (a 2D read then finds // the fallback). A full array is what returns 0. - used_2d = nullptr; + want_mirror = false; } } - if (!used_2d) { - index = stores ? allocate(used, 1, low_end) : allocate(used, low_end, std::uint32_t(used.size())); - if (!index) index = allocate(used, 1, low_end); + if (!want_mirror) { + index = stores ? pop_free_image(d, true) : pop_free_image(d, false); + if (!index && !stores) index = pop_free_image(d, true); } if (!index) return 0; - assert(!used_2d || !any_stores || index < storage_capacity(ImageDimension::dim_2d)); + assert(!want_mirror || !any_stores || index < storage_capacity(ImageDimension::dim_2d)); write_image(dimension, index, sampled, sampled_layout, storage, sampled_class); - if (index < storage_used_[std::uint32_t(dimension)].size()) - storage_used_[std::uint32_t(dimension)][index] = stores ? 1 : 0; - if (used_2d) { + if (index < storage_used_[d].size()) storage_used_[d][index] = stores ? 1 : 0; + if (want_mirror) { + assert(image_used_[std::uint32_t(ImageDimension::dim_2d)][index] == in_use); write_image(ImageDimension::dim_2d, index, mirror->sampled, mirror->sampled_layout, mirror->storage, 0); - used_2d->at(index) = in_use; // The 2D slot is this image's mirror, and this image is its owner: the slot number alone does not say // so, because every dimension's index space is dense and independent. if (index < mirror_owner_.size()) { - mirror_owner_[index] = std::uint8_t(std::uint32_t(dimension) + 1); + mirror_owner_[index] = std::uint8_t(d + 1); mirror_storage_used_[index] = mirror_storage(mirror) ? 1 : 0; } auto& storage_2d = storage_used_[std::uint32_t(ImageDimension::dim_2d)]; if (index < storage_2d.size()) storage_2d[index] = mirror_storage(mirror) ? 1 : 0; } if (kind_out) { - *kind_out = kind_sampled_bit(std::uint32_t(dimension)) | - (stores ? kind_storage_bit(std::uint32_t(dimension)) : 0) | - (used_2d ? (kind_sampled_bit(std::uint32_t(ImageDimension::dim_2d)) | - (mirror_storage(mirror) ? kind_storage_bit(std::uint32_t(ImageDimension::dim_2d)) - : 0)) - : 0); + *kind_out = kind_sampled_bit(d) | (stores ? kind_storage_bit(d) : 0) | + (want_mirror ? (kind_sampled_bit(std::uint32_t(ImageDimension::dim_2d)) | + (mirror_storage(mirror) ? kind_storage_bit(std::uint32_t(ImageDimension::dim_2d)) + : 0)) + : 0); } return index; } @@ -576,12 +594,9 @@ class BindlessSet { if (!stores && bindless::sampled_binding(dimension) == bindless::no_binding) return ImageRefusal::no_array; if (bindless::multisampled(dimension) && (stores || !supports_ms_class(sampled_class))) return ImageRefusal::no_array; - const auto& used = image_used_[std::uint32_t(dimension)]; - const std::size_t low_end = std::min(used.size(), storage_capacity(dimension)); - const auto storage_end = used.begin() + std::ptrdiff_t(low_end); - const bool storage_free = low_end > 1 && std::find(used.begin() + 1, storage_end, std::uint8_t(0)) != storage_end; - return stores && !storage_free && free_images(dimension) ? ImageRefusal::storage_full - : ImageRefusal::array_full; + const std::uint32_t d = std::uint32_t(dimension); + return stores && free_low_count_[d] == 0 && free_high_count_[d] > 0 ? ImageRefusal::storage_full + : ImageRefusal::array_full; } // New views or a new layout for an index add_image returned (a texture's state changed, say). `mirror` is @@ -613,31 +628,34 @@ class BindlessSet { // held until a flush has brought the table up to date (one that did not degrade), so that no new image answers // that key; otherwise it is free at once. void remove_image(ImageDimension dimension, std::uint32_t index) { - auto& used = image_used_[std::uint32_t(dimension)]; + const std::uint32_t d = std::uint32_t(dimension); + auto& used = image_used_[d]; if (!index || index >= used.size() || used[index] != in_use) return; write_image(dimension, index, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_GENERAL, {}, 0); - used[index] = table_dirty_ ? held : 0; - if (index < storage_used_[std::uint32_t(dimension)].size()) - storage_used_[std::uint32_t(dimension)][index] = 0; - if (table_dirty_) held_images_.push_back({dimension, index}); + if (index < storage_used_[d].size()) storage_used_[d][index] = 0; + if (table_dirty_) + hold_image_slot(dimension, index); + else + free_image_slot(d, index); // Its 2D copy goes back to the fallback as well (add_image's mirror), when this image is the one that owns // that slot: another dimension's image at the same slot number has its own index space and keeps its 2D // descriptor (and, if it is a 2D-array image, its own mirror there). if (mirror_of(dimension, index)) { - auto& used_2d = image_used_[std::uint32_t(ImageDimension::dim_2d)]; write_image(ImageDimension::dim_2d, index, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_GENERAL, {}, 0); - used_2d[index] = table_dirty_ ? held : 0; mirror_owner_[index] = 0; mirror_storage_used_[index] = 0; auto& storage_2d = storage_used_[std::uint32_t(ImageDimension::dim_2d)]; if (index < storage_2d.size()) storage_2d[index] = 0; - if (table_dirty_) held_images_.push_back({ImageDimension::dim_2d, index}); + if (table_dirty_) + hold_image_slot(ImageDimension::dim_2d, index); + else + free_image_slot(std::uint32_t(ImageDimension::dim_2d), index); } } // 0 when the sampler array is full. std::uint32_t add_sampler(VkSampler sampler) { - const std::uint32_t index = allocate(sampler_used_, 1, std::uint32_t(sampler_used_.size())); + const std::uint32_t index = pop_free_sampler(); if (index) write_sampler(index, sampler); return index; } @@ -645,8 +663,12 @@ class BindlessSet { void remove_sampler(std::uint32_t index) { if (!index || index >= sampler_used_.size() || sampler_used_[index] != in_use) return; write_sampler(index, fallback_sampler_); - sampler_used_[index] = table_dirty_ ? held : 0; - if (table_dirty_) held_samplers_.push_back(index); + if (table_dirty_) { + sampler_used_[index] = held; + held_samplers_.push_back(index); + } else { + free_sampler_slot(index); + } } // What an index of `dimension` is bound in, from what add_image wrote: that dimension's sampled bit, its storage @@ -673,6 +695,7 @@ class BindlessSet { table_dirty_ |= result != DescriptorTable::InsertResult::unchanged; existing_entries_changed_ |= result == DescriptorTable::InsertResult::replaced || result == DescriptorTable::InsertResult::added_with_relocation; + if (table_dirty_) needs_prepare_.store(true, std::memory_order_release); return true; } // The T#'s own dimension, whose kind the set derives from the index it gave out (image_kind_at): a caller that @@ -685,6 +708,7 @@ class BindlessSet { bool erase_key(const DescriptorKey& key) { if (!table_.erase(key)) return false; table_dirty_ = true; + needs_prepare_.store(true, std::memory_order_release); return true; } const DescriptorTable& table() const { return table_; } @@ -713,10 +737,12 @@ class BindlessSet { upload_in_flight_ = false; if (submitted) { table_on_gpu_ = true; // the current buffers hold a table the GPU was given + sync_fast_state(); return; } table_dirty_ = true; force_full_upload_ = true; + sync_fast_state(); } // Writes the pending descriptor changes and uploads the table, in `command_buffer`, before the commands that use @@ -735,6 +761,10 @@ class BindlessSet { bool flush(VkCommandBuffer command_buffer, std::uint64_t retire_ticket = 0, const std::function& completed_ticket = {}) { if (!command_buffer) return false; + struct FastStateGuard { + BindlessSet* self; + ~FastStateGuard() { self->sync_fast_state(); } + } fast_guard{this}; bool replaced = false; bool written = true; const bool must_replace = flush_replaces_table(); @@ -783,8 +813,9 @@ class BindlessSet { pending_slots_.clear(); if (!last_flush_degraded_) { // The table this flush leaves on the GPU names no removed index any more: they can be given out again. - for (const auto& [dimension, index] : held_images_) image_used_[std::uint32_t(dimension)][index] = 0; - for (const std::uint32_t index : held_samplers_) sampler_used_[index] = 0; + for (const auto& [dimension, index] : held_images_) + free_image_slot(std::uint32_t(dimension), index); + for (const std::uint32_t index : held_samplers_) free_sampler_slot(index); held_images_.clear(); held_samplers_.clear(); } @@ -809,6 +840,7 @@ class BindlessSet { } } retired_.resize(kept); + sync_fast_state(); } bool has_retired() const { return !retired_.empty(); } // True when the last flush() started a new generation: its table upload is in that flush's command buffer, so @@ -903,25 +935,128 @@ class BindlessSet { // flush that does not degrade). static constexpr std::uint8_t in_use = 1, held = 2; - // The first free index in [begin, end), marked used; 0 when there is none. - static std::uint32_t allocate(std::vector& used, std::uint32_t begin, std::uint32_t end) { - for (std::uint32_t i = begin; i < end; ++i) { - if (used[i]) continue; - used[i] = 1; - return i; + // O(1) slot bookkeeping helpers. Every state transition of image_used_ / sampler_used_ goes through here so the + // free counts and free-lists can never drift out of sync with the occupancy arrays. + void claim_image_slot(std::uint32_t d, std::uint32_t index) { + assert(index > 0 && index < image_used_[d].size() && image_used_[d][index] == 0); + image_used_[d][index] = in_use; + if (index < low_end_[d]) + --free_low_count_[d]; + else + --free_high_count_[d]; + total_free_images_.fetch_sub(1, std::memory_order_release); + } + + void free_image_slot(std::uint32_t d, std::uint32_t index) { + if (!index || index >= image_used_[d].size() || image_used_[d][index] == 0) return; + image_used_[d][index] = 0; + if (index < low_end_[d]) { + ++free_low_count_[d]; + free_low_[d].push_back(index); + } else { + ++free_high_count_[d]; + free_high_[d].push_back(index); + } + total_free_images_.fetch_add(1, std::memory_order_release); + } + + void hold_image_slot(ImageDimension dimension, std::uint32_t index) { + const std::uint32_t d = std::uint32_t(dimension); + assert(index > 0 && index < image_used_[d].size() && image_used_[d][index] == in_use); + image_used_[d][index] = held; + held_images_.push_back({dimension, index}); + } + + std::uint32_t pop_free_image(std::uint32_t d, bool low) { + const std::uint32_t count = low ? free_low_count_[d] : free_high_count_[d]; + if (!count) return 0; + auto& list = low ? free_low_[d] : free_high_[d]; + auto& used = image_used_[d]; + while (!list.empty()) { + const std::uint32_t idx = list.back(); + list.pop_back(); + if (used[idx] == 0) { + claim_image_slot(d, idx); + return idx; + } + } + return 0; + } + + std::uint32_t pop_free_sampler() { + if (!free_sampler_count_) return 0; + while (!free_samplers_.empty()) { + const std::uint32_t idx = free_samplers_.back(); + free_samplers_.pop_back(); + if (sampler_used_[idx] == 0) { + sampler_used_[idx] = in_use; + --free_sampler_count_; + return idx; + } } return 0; } - // The first index in [begin, end) free in both arrays, marked used in the first; 0 when there is none. The - // second array's size bounds the range: a mirrored index must exist in it (its 2D slot). - static std::uint32_t allocate_pair(std::vector& used, std::vector& other, - std::uint32_t begin, std::uint32_t end) { - end = std::min(end, std::uint32_t(other.size())); - for (std::uint32_t i = begin; i < end; ++i) { - if (used[i] || other[i]) continue; - used[i] = 1; - return i; + void free_sampler_slot(std::uint32_t index) { + if (!index || index >= sampler_used_.size() || sampler_used_[index] == 0) return; + sampler_used_[index] = 0; + ++free_sampler_count_; + free_samplers_.push_back(index); + } + + // Finds a slot in [begin, limit) free in both `dim` and `dim_2d`, claiming it in BOTH spaces; 0 when none exists. + std::uint32_t allocate_pair(ImageDimension dim, std::uint32_t begin, std::uint32_t end) { + const std::uint32_t d = std::uint32_t(dim); + constexpr std::uint32_t d2 = std::uint32_t(ImageDimension::dim_2d); + const std::uint32_t limit = (std::min)(end, std::uint32_t(image_used_[d2].size())); + if (begin >= limit) return 0; + if (free_low_count_[d] + free_high_count_[d] == 0 || free_low_count_[d2] + free_high_count_[d2] == 0) return 0; + if (limit <= low_end_[d] && free_low_count_[d] == 0) return 0; + if (begin >= low_end_[d] && free_high_count_[d] == 0) return 0; + if (limit <= low_end_[d2] && free_low_count_[d2] == 0) return 0; + if (begin >= low_end_[d2] && free_high_count_[d2] == 0) return 0; + + const auto search_list = [&](std::vector& list, std::uint32_t owner_d, + std::uint32_t other_d) -> std::uint32_t { + const auto& used_a = image_used_[owner_d]; + const auto& used_b = image_used_[other_d]; + for (std::size_t k = list.size(); k > 0; --k) { + const std::uint32_t idx = list[k - 1]; + if (used_a[idx] != 0) { + list[k - 1] = list.back(); + list.pop_back(); + continue; + } + if (idx >= begin && idx < limit && used_b[idx] == 0) { + list[k - 1] = list.back(); + list.pop_back(); + claim_image_slot(d, idx); + claim_image_slot(d2, idx); + return idx; + } + } + return 0; + }; + + const bool d_uses_low = begin < low_end_[d]; + const bool d_uses_high = limit > low_end_[d]; + const bool d2_uses_low = begin < low_end_[d2]; + const bool d2_uses_high = limit > low_end_[d2]; + const std::uint32_t d_avail = (d_uses_low ? free_low_count_[d] : 0) + (d_uses_high ? free_high_count_[d] : 0); + const std::uint32_t d2_avail = + (d2_uses_low ? free_low_count_[d2] : 0) + (d2_uses_high ? free_high_count_[d2] : 0); + if (!d_avail || !d2_avail) return 0; + + if (d_avail <= d2_avail) { + if (d_uses_low) + if (const std::uint32_t idx = search_list(free_low_[d], d, d2)) return idx; + if (d_uses_high) + if (const std::uint32_t idx = search_list(free_high_[d], d, d2)) return idx; + } else { + if (d2_uses_low) + if (const std::uint32_t idx = search_list(free_low_[d2], d2, d)) return idx; + if (d2_uses_high) + if (const std::uint32_t idx = search_list(free_high_[d2], d2, d)) return idx; } return 0; } @@ -961,16 +1096,38 @@ class BindlessSet { shadow_written_[b].assign(features_.counts[b], 0); } + std::uint32_t total_free = 0; for (std::uint32_t d = 0; d < dimensions; ++d) { - image_used_[d].assign(image_capacity(ImageDimension(d)), 0); + const std::uint32_t cap = image_capacity(ImageDimension(d)); + const std::uint32_t low = (std::min)(cap, storage_capacity(ImageDimension(d))); + low_end_[d] = low; + image_used_[d].assign(cap, 0); image_used_[d][0] = 1; + const std::uint32_t low_count = low > 1 ? low - 1 : 0; + const std::uint32_t high_begin = (std::max)(low, std::uint32_t(1)); + const std::uint32_t high_count = cap > high_begin ? cap - high_begin : 0; + free_low_count_[d] = low_count; + free_high_count_[d] = high_count; + total_free += low_count + high_count; + free_low_[d].clear(); + free_low_[d].reserve(low_count); + for (std::uint32_t i = low; i > 1; --i) free_low_[d].push_back(i - 1); + free_high_[d].clear(); + free_high_[d].reserve(high_count); + for (std::uint32_t i = cap; i > high_begin; --i) free_high_[d].push_back(i - 1); } + total_free_images_.store(total_free, std::memory_order_release); for (std::uint32_t d = 0; d < dimensions; ++d) storage_used_[d].assign(image_capacity(ImageDimension(d)), 0); mirror_owner_.assign(image_capacity(ImageDimension::dim_2d), 0); mirror_storage_used_.assign(image_capacity(ImageDimension::dim_2d), 0); - sampler_used_.assign(sampler_capacity(), 0); + const std::uint32_t scap = sampler_capacity(); + sampler_used_.assign(scap, 0); sampler_used_[0] = 1; + free_sampler_count_ = scap > 1 ? scap - 1 : 0; + free_samplers_.clear(); + free_samplers_.reserve(free_sampler_count_); + for (std::uint32_t i = scap; i > 1; --i) free_samplers_.push_back(i - 1); return true; } @@ -1422,6 +1579,15 @@ class BindlessSet { pending_.push_back({binding, index, info}); else pending_[at->second].info = info; + needs_prepare_.store(true, std::memory_order_release); + } + + void sync_fast_state() noexcept { + const bool prep = !fallbacks_ready_ || table_dirty_ || !table_uploaded_ || !pending_.empty() || + !retired_.empty() || !held_images_.empty() || !held_samplers_.empty(); + current_set_.store(set_, std::memory_order_release); + needs_commit_.store(upload_in_flight_, std::memory_order_release); + needs_prepare_.store(prep, std::memory_order_release); } void write_sampler(std::uint32_t index, VkSampler sampler) { @@ -1473,6 +1639,12 @@ class BindlessSet { VkSampler fallback_sampler_ = VK_NULL_HANDLE; bool fallbacks_ready_ = false; std::array, dimensions> image_used_; + std::array low_end_{}; + std::array, dimensions> free_low_; + std::array, dimensions> free_high_; + std::array free_low_count_{}; + std::array free_high_count_{}; + std::atomic total_free_images_{0}; // Which of those slots also hold storage views (add_image's `storage`), and which 2D slots hold the mirror of an // image in another dimension (add_image's MirrorViews): removing that image frees the 2D slot too. insert_key // reads both to say which arrays an index is bound in. mirror_owner_ says whose mirror each of those 2D slots is @@ -1482,6 +1654,8 @@ class BindlessSet { std::vector mirror_owner_; std::vector mirror_storage_used_; std::vector sampler_used_; + std::vector free_samplers_; + std::uint32_t free_sampler_count_ = 0; std::vector> held_images_; // removed, not yet free (remove_image) std::vector held_samplers_; std::vector pending_; @@ -1511,6 +1685,9 @@ class BindlessSet { // Every descriptor written to the set (the table's binding aside), to fill the next generation's set. std::array, bindless::bindings.size()> shadow_; std::array, bindless::bindings.size()> shadow_written_; + std::atomic needs_prepare_{true}; + std::atomic current_set_{VK_NULL_HANDLE}; + std::atomic needs_commit_{false}; }; } // namespace leonida diff --git a/runtime/src/vulkan_device_fault.h b/runtime/src/vulkan_device_fault.h index 3c49fce8d2..c661ec90de 100644 --- a/runtime/src/vulkan_device_fault.h +++ b/runtime/src/vulkan_device_fault.h @@ -179,11 +179,15 @@ struct CheckpointSubmission { static constexpr std::size_t dispatch_limit = 64; // Numbers every recorded dispatch, across queues and submissions (the report's seq). Null: no numbers. std::atomic* dispatch_seq = nullptr; - // LEONIDA_DEVICE_MARKERS=1: this queue's marker slot, every dispatch recorded for the marker history and the seq - // whose finished marker is still to be written after its dispatch (CheckpointRecorder::dispatched). + // LEONIDA_DEVICE_MARKERS=1: this queue's marker slot, every dispatch and draw recorded for the marker history and + // the seq whose finished marker is still to be written after its work (CheckpointRecorder::dispatched, drawn). MarkerTarget markers; - std::vector marked; + std::vector marked; std::uint64_t open_marker = 0; + // The run of draws to one set of targets the last marked draw belongs to (CheckpointRecorder::draw). + std::size_t pass_list = SIZE_MAX; + std::uint64_t pass_targets = 0; + std::uint32_t pass_command = 0, pass_draws = 0; void append_dispatch(CheckpointDispatch d) { if (dispatches.size() < dispatch_limit) dispatches.push_back(d); @@ -240,6 +244,42 @@ struct CheckpointRecorder { submission.markers.finished(buffer, submission.open_marker); submission.open_marker = 0; } + + // LEONIDA_DEVICE_MARKERS=1: a draw of pipeline `id` comes next, before its helper passes and its rendering scope. + // It takes the next seq, goes into the marker history and writes its started marker; drawn() writes the finished + // one. `flags` are marked_draw bits, `counts` as MarkedWork::counts (describe_marked). Without the markers it does + // nothing, so the dispatch numbering stays as it was. + void draw(VkCommandBuffer buffer, std::size_t command, std::uintptr_t id, std::uint8_t flags, + std::array counts, const MarkedTargets& targets = {}) const { + if (!submission.markers || !submission.dispatch_seq) return; + const std::uint64_t seq = submission.dispatch_seq->fetch_add(1, std::memory_order_relaxed) + 1; + MarkedWork w{seq, submission.execute_call, submission.queue, submission.queue_kind, + static_cast(list), static_cast(command)}; + w.kind = MarkedKind::draw; + w.draw_flags = flags; + w.pipeline = id; + if (const auto names = pipeline_names.find(id); names != pipeline_names.end()) w.stages = names->second; + w.counts = counts; + if (targets.key) { + if (submission.pass_list != list || submission.pass_targets != targets.key) { + submission.pass_list = list; + submission.pass_targets = targets.key; + submission.pass_command = static_cast(command); + submission.pass_draws = 0; + } + w.pass_command = submission.pass_command; + w.pass_draw = ++submission.pass_draws; + w.area = targets.area; + w.colors = targets.colors; + w.depth = targets.depth; + } + submission.marked.push_back(w); + submission.markers.started(buffer, seq); + submission.open_marker = seq; + } + + // After the draw that draw() announced, once its rendering scope has ended: its finished marker. + void drawn(VkCommandBuffer buffer) const { dispatched(buffer); } }; // A D3D fence may stay unsignalled by design. Only queue retirement tickets represent @@ -1402,54 +1442,95 @@ class DeviceFaultDiagnostics { } // LEONIDA_DEVICE_MARKERS=1: each queue's marker slot judged against the marker history, printed; returns the - // likely hangs (the oldest started, unfinished dispatch of each queue) for dump_dispatches to mark. - std::vector report_markers(bool lost) noexcept { + // likely hangs (the oldest started, unfinished dispatch or draw of each queue) for dump_dispatches to mark. Each + // queue's verdict line is followed by the items it names, dispatches and draws alike (describe_marked): the last + // finished one, the likely hang and the rest in flight (up to 8), or for an idle queue the next not started. + // `text`, when given, also gets the lines (the tests read them). + std::vector report_markers(bool lost, std::string* text = nullptr) noexcept { std::vector hangs; if (!markers_) return hangs; try { + std::string out = std::string("[rt] device-markers: AMD buffer markers, read ") + + (lost ? "after the device loss" : "while the device is still up") + "; best-effort: " + + (lost ? "only what the GPU wrote before it stopped, and a reset may have lost the last " + "writes" + : "the GPU may still be writing them") + + "\n"; std::lock_guard lock(mutex_); - std::fprintf(stderr, "[rt] device-markers: AMD buffer markers, read %s; best-effort: %s\n", - lost ? "after the device loss" : "while the device is still up", - lost ? "only what the GPU wrote before it stopped, and a reset may have lost the last writes" - : "the GPU may still be writing them"); for (VkQueue queue : markers_->queues()) { const MarkerQueueReport r = judge_markers(queue, markers_->read(queue), *history_); - if (!r.slot.started && !r.slot.finished && !r.next_queued) continue; // never marked a dispatch + if (!r.slot.started && !r.slot.finished && !r.next_queued) continue; // never marked anything const char* kind = r.queue_kind ? r.queue_kind : "?"; + constexpr std::size_t in_flight_lines = 8; + std::vector named; // the items the detail lines describe, in print order if (r.idle()) { - std::fprintf(stderr, "[rt] device-markers: queue %p (%s) idle: finished seq=%u, nothing started " - "after it", static_cast(queue), kind, unsigned(r.slot.finished)); + out += "[rt] device-markers: queue " + hex(queue) + " (" + kind + ") idle: finished seq=" + + std::to_string(r.slot.finished) + ", nothing started after it"; if (r.next_queued) - std::fprintf(stderr, "; next submitted seq=%" PRIu64 " not started (waiting, or behind other " - "work of the queue)", r.next_queued); - std::fputc('\n', stderr); - continue; + out += "; next submitted seq=" + std::to_string(r.next_queued) + + " not started (waiting, or behind other work of the queue)"; + out += '\n'; + } else { + out += "[rt] device-markers: queue " + hex(queue) + " (" + kind + ") finished seq=" + + std::to_string(r.slot.finished) + " started seq=" + std::to_string(r.slot.started) + + "; started, not finished:"; + for (std::size_t i = 0; i < r.unfinished.size() && i < 16; ++i) + out += " " + std::to_string(r.unfinished[i]); + if (r.unfinished.size() > 16) out += " (+" + std::to_string(r.unfinished.size() - 16) + ")"; + if (r.missing) out += " (no longer in the marker history)"; + out += '\n'; + if (r.likely_hang) hangs.push_back(r.likely_hang); } - std::string line = "[rt] device-markers: queue " + hex(queue) + " (" + kind + ") finished seq=" + - std::to_string(r.slot.finished) + " started seq=" + std::to_string(r.slot.started) + - "; started, not finished:"; - for (std::size_t i = 0; i < r.unfinished.size() && i < 16; ++i) - line += " " + std::to_string(r.unfinished[i]); - if (r.unfinished.size() > 16) line += " (+" + std::to_string(r.unfinished.size() - 16) + ")"; - if (r.missing) line += " (no longer in the marker history)"; - line += '\n'; - std::fputs(line.c_str(), stderr); - if (!r.likely_hang) continue; - hangs.push_back(r.likely_hang); - history_->for_each([&](const MarkedDispatch& d) { - if (d.seq != r.likely_hang) return; - std::fprintf(stderr, "[rt] device-markers: likely hang: seq=%" PRIu64 " execute=%" PRIu64 - " queue=%p (%s) list=%u command=%u shader=%s\n", - d.seq, d.execute_call, static_cast(d.queue), kind, d.list, d.command, - d.shader ? d.shader : "-"); + if (r.last_finished) named.push_back(r.last_finished); + for (std::size_t i = 0; i < r.unfinished.size() && i < in_flight_lines; ++i) + named.push_back(r.unfinished[i]); + if (r.next_queued) named.push_back(r.next_queued); + std::vector found(named.size(), nullptr); + history_->for_each([&](const MarkedWork& d) { + if (d.queue != queue) return; + for (std::size_t i = 0; i < named.size(); ++i) + if (named[i] == d.seq) found[i] = &d; }); + for (std::size_t i = 0; i < named.size(); ++i) { + if (!found[i]) continue; + const std::uint64_t seq = named[i]; + const char* what = seq == r.likely_hang ? "likely hang: " + : seq == r.last_finished ? " finished: " + : seq == r.next_queued ? " not started: " + : " in flight: "; + out += std::string("[rt] device-markers: ") + what + describe_marked(*found[i]) + '\n'; + } + if (r.unfinished.size() > in_flight_lines) + out += "[rt] device-markers: in flight: (+" + + std::to_string(r.unfinished.size() - in_flight_lines) + " more)\n"; } + std::fputs(out.c_str(), stderr); + if (text) *text += out; } catch (...) { std::fprintf(stderr, "[rt] device-markers: marker collection failed\n"); } return hangs; } + // LEONIDA_DEVICE_MARKERS=1, for a device-fault address: the last draw each queue started (the GPU's top-of-pipe + // marker reached it), and whether its finished marker ran. Empty without markers or without such a draw. + std::string marker_fault_draws() { + std::string out; + if (!markers_) return out; + std::lock_guard lock(mutex_); + for (VkQueue queue : markers_->queues()) { + const MarkerQueueReport r = judge_markers(queue, markers_->read(queue), *history_); + if (!r.last_draw) continue; + history_->for_each([&](const MarkedWork& d) { + if (d.queue != queue || d.seq != r.last_draw) return; + out += std::string("[rt] device-fault: last started draw (device-markers): ") + describe_marked(d) + + (marker_after(d.seq, r.slot.finished) ? " (not finished)" : " (finished)") + + (d.seq == r.likely_hang ? " <- likely hang" : "") + '\n'; + }); + } + return out; + } + private: void enable_markers(PFN_vkGetDeviceProcAddr get, const VkPhysicalDeviceMemoryProperties* memory, bool synchronization2) { @@ -1461,8 +1542,8 @@ class DeviceFaultDiagnostics { int(result)); return; } - std::fprintf(stderr, "[rt] device-markers: on (VK_AMD_buffer_marker, %s): each dispatch writes its seq at top " - "and bottom of pipe\n", + std::fprintf(stderr, "[rt] device-markers: on (VK_AMD_buffer_marker, %s): each dispatch and draw writes its " + "seq at top and bottom of pipe\n", markers->synchronization2() ? "vkCmdWriteBufferMarker2AMD" : "vkCmdWriteBufferMarkerAMD"); history_ = std::make_unique(); markers_ = std::move(markers); @@ -1544,7 +1625,7 @@ class DeviceFaultDiagnostics { } } - void report_fault() const { + void report_fault() { VkDeviceFaultCountsEXT counts{VK_STRUCTURE_TYPE_DEVICE_FAULT_COUNTS_EXT}; VkResult result = vkGetDeviceFaultInfoEXT(device_, &counts, nullptr); if (result != VK_SUCCESS) { @@ -1579,6 +1660,8 @@ class DeviceFaultDiagnostics { " precision=%" PRIu64 "\n", i, int(address.addressType), address.reportedAddress, address.addressPrecision); } + // The draw that was running when the address faulted, as far as the AMD markers say. + if (counts.addressInfoCount) std::fputs(marker_fault_draws().c_str(), stderr); for (std::size_t i = 0; i < counts.vendorInfoCount; ++i) { const auto& vendor = vendors[i]; std::fprintf(stderr, "[rt] device-fault: vendor[%zu] %.*s code=0x%" PRIx64 " data=0x%" PRIx64 "\n", diff --git a/runtime/src/vulkan_device_markers.h b/runtime/src/vulkan_device_markers.h index fea7e578bc..9fbce1a502 100644 --- a/runtime/src/vulkan_device_markers.h +++ b/runtime/src/vulkan_device_markers.h @@ -1,14 +1,24 @@ #pragma once // LEONIDA_DEVICE_MARKERS=1 (diagnostic, with LEONIDA_DEVICE_FAULT=1 or 2): AMD breadcrumbs for the device-fault report -// (vulkan_device_fault.h). On a device with VK_AMD_buffer_marker every dispatch the report numbers writes its `seq` -// into its queue's slot of one small host-visible buffer twice: at top of pipe before the dispatch (started) and at -// bottom of pipe after it (finished). A bottom-of-pipe write waits for all earlier work of the queue, so the finished -// word is the last dispatch before which everything had completed; the dispatches after it up to the started word -// are the ones the GPU had begun and not finished. On a loss or a stall report the slots are read back and the oldest -// started, unfinished dispatch of a queue is reported as the likely hang. NVIDIA checkpoints do this on NVIDIA; RADV -// has none. The buffer lives in system memory, so the last values usually survive a ring reset, but they are only -// what the GPU wrote before it stopped: best-effort after a loss. +// (vulkan_device_fault.h). On a device with VK_AMD_buffer_marker every dispatch and every draw the report numbers +// writes its `seq` into its queue's slot of one small host-visible buffer twice: at top of pipe before the work +// (started) and at bottom of pipe after it (finished). A bottom-of-pipe write waits for all earlier work of the queue, +// so the finished word is the last item before which everything had completed; the items after it up to the started +// word are the ones the GPU had begun and not finished. On a loss or a stall report the slots are read back and the +// oldest started, unfinished item of a queue is reported as the likely hang. NVIDIA checkpoints do this on NVIDIA; +// RADV has none. The buffer lives in system memory, so the last values usually survive a ring reset, but they are +// only what the GPU wrote before it stopped: best-effort after a loss. +// +// Granularity: a marker pair per draw, as per dispatch. The replay opens a dynamic-rendering scope per draw, so the +// started write goes before the draw's helper passes (quad index expansion, indirect clamp) and its scope, and the +// finished one after the scope ends: both outside any render pass instance. The extension allows them inside one too +// (vk.xml: renderpass="both", conditionalrendering="false"), which only the legacy graphics ExecuteIndirect path uses, +// drawing in the caller's scope. In RADV (radv_CmdWriteMarkerToMemoryAMD) a top-of-pipe write is one COPY_DATA packet +// with write confirm (the command processor waits for that one write, not for earlier work) and any other stage one +// bottom-of-pipe EOP event (no wait); both first emit the cache flushes already pending, which the next draw would +// have emitted anyway. That is at most 12 dwords per write, 24 per draw or dispatch next to the hundreds the draw's +// own scope and state take, plus one history entry each on the CPU. #include @@ -19,6 +29,7 @@ #include #include #include +#include #include namespace leonida { @@ -31,8 +42,8 @@ inline bool device_markers_requested() { return on; } -// One queue's slot as the GPU writes it: the low 32 bits of the seq of the last dispatch whose top-of-pipe write ran -// (started) and of the last whose bottom-of-pipe write ran (finished). 0 is no dispatch yet; seqs start at 1. +// One queue's slot as the GPU writes it: the low 32 bits of the seq of the last dispatch or draw whose top-of-pipe +// write ran (started) and of the last whose bottom-of-pipe write ran (finished). 0 is nothing yet; seqs start at 1. struct MarkerSlot { std::uint32_t started = 0; std::uint32_t finished = 0; @@ -44,25 +55,143 @@ constexpr bool marker_after(std::uint64_t seq, std::uint32_t marker) { return static_cast(static_cast(seq) - marker) > 0; } -// What the marker history keeps of each recorded dispatch: enough to name one that left the report's 64-entry list. -struct MarkedDispatch { +enum class MarkedKind : std::uint8_t { dispatch, draw }; + +// What a marked draw was (MarkedWork::draw_flags). +namespace marked_draw { +inline constexpr std::uint8_t indexed = 1; +inline constexpr std::uint8_t indirect = 2; // arguments from a buffer +inline constexpr std::uint8_t counted = 4; // indirect, with a count buffer +inline constexpr std::uint8_t mesh = 8; // a mesh-shader dispatch (vkCmdDrawMeshTasks*) +inline constexpr std::uint8_t quads = 16; // a quad list, drawn as triangles +} // namespace marked_draw + +// The render targets a draw writes, for its place in the list: the draws of a list to the same targets, one after the +// other (other commands between them allowed), are one pass. `key` 0: not known (the legacy indirect path draws in +// the caller's scope). +struct MarkedTargets { + std::uint64_t key = 0; + VkExtent2D area{}; + std::uint8_t colors = 0; + bool depth = false; + + // From the attachment views (null for an unbound slot). + template + static MarkedTargets of(const Views& colors, VkImageView depth, VkExtent2D area) { + MarkedTargets t; + t.area = area; + std::uint64_t h = 0xcbf29ce484222325ull; + const auto mix = [&](VkImageView view) { + std::uint64_t v = 0; + std::memcpy(&v, &view, sizeof(view) < sizeof(v) ? sizeof(view) : sizeof(v)); + h = (h ^ v) * 0x100000001b3ull; + }; + for (VkImageView view : colors) { + mix(view); + if (view) ++t.colors; + } + mix(depth); + t.depth = depth != VK_NULL_HANDLE; + t.key = h ? h : 1; + return t; + } +}; + +// What the marker history keeps of each recorded dispatch or draw: enough to name a dispatch that left the report's +// 64-entry dispatch list, or a draw, which that list does not hold. +struct MarkedWork { std::uint64_t seq = 0; std::uint64_t execute_call = 0; VkQueue queue = VK_NULL_HANDLE; const char* queue_kind = nullptr; std::uint32_t list = 0; std::uint32_t command = 0; - const char* shader = nullptr; // ShaderLibrary name, valid until device teardown + const char* shader = nullptr; // a dispatch's ShaderLibrary name, valid until device teardown + MarkedKind kind = MarkedKind::dispatch; + // Draws only. + std::uint8_t draw_flags = 0; // marked_draw + std::uint8_t colors = 0; // bound colour targets + bool depth = false; // a depth/stencil target + std::array stages{}; // ShaderLibrary names: vertex or mesh, geometry, pixel (CheckpointShaders) + std::uintptr_t pipeline = 0; // the PSO id, named when it has no stage names + std::array counts{}; // see describe_marked + VkExtent2D area{}; + std::uint32_t pass_command = 0; // the list's command where the run of draws to these targets began + std::uint32_t pass_draw = 0; // this draw's place in that run, from 1; 0: not known + + bool is_draw() const { return kind == MarkedKind::draw; } }; -// The recent dispatches of every queue, oldest first once read. Allocated once, when the markers are on. +// A graphics pipeline as the GPU profile's lines name it (gpu_profile::label, which the marker test compares): each +// stage's tag and entry name without its folder, or "pso 0x..." when it has no names. +inline std::string marked_pipeline_label(const std::array& stages, bool mesh, std::uintptr_t id) { + static const char* const tags[3] = {"vs", "gs", "ps"}; + std::string text; + for (std::size_t i = 0; i < stages.size(); ++i) { + const char* name = stages[i]; + if (!name) continue; + if (const char* slash = std::strrchr(name, '/')) name = slash + 1; + if (!text.empty()) text += ' '; + text += i == 0 && mesh ? "ms" : tags[i]; + text += ' '; + text += name; + } + if (text.empty()) { + char buffer[48]; + std::snprintf(buffer, sizeof buffer, "pso 0x%llx", static_cast(id)); + text = buffer; + } + return text; +} + +// One marked item as the report prints it. A dispatch keeps the fields its likely-hang line always had; a draw says +// what kind it is with its counts (vertex or index count and instances; a mesh dispatch's group counts; an indirect +// draw's record count and stride), its pipeline, and its place among the draws to the same targets. +inline std::string describe_marked(const MarkedWork& w) { + char head[192]; + std::snprintf(head, sizeof head, "seq=%llu execute=%llu queue=%p (%s) list=%u command=%u", + static_cast(w.seq), static_cast(w.execute_call), + static_cast(w.queue), w.queue_kind ? w.queue_kind : "?", w.list, w.command); + std::string text = head; + if (!w.is_draw()) { + text += " shader="; + text += w.shader ? w.shader : "-"; + return text; + } + const std::uint8_t f = w.draw_flags; + const bool mesh = (f & marked_draw::mesh) != 0; + text += " draw="; + text += mesh ? "mesh" : (f & marked_draw::indexed) ? "indexed" : "vertices"; + if (f & marked_draw::quads) text += "-quads"; + if (f & marked_draw::indirect) text += (f & marked_draw::counted) ? "-indirect-count" : "-indirect"; + char counts[96]; + if (f & marked_draw::indirect) + std::snprintf(counts, sizeof counts, " max=%u stride=%u", w.counts[0], w.counts[1]); + else if (mesh) + std::snprintf(counts, sizeof counts, " groups=%u,%u,%u", w.counts[0], w.counts[1], w.counts[2]); + else + std::snprintf(counts, sizeof counts, " count=%u instances=%u", w.counts[0], w.counts[1]); + text += counts; + text += " pipeline=" + marked_pipeline_label(w.stages, mesh, w.pipeline); + if (w.pass_draw) { + char pass[128]; + std::snprintf(pass, sizeof pass, " pass=draw %u since command %u (%u colour%s%s, %ux%u)", w.pass_draw, + w.pass_command, unsigned(w.colors), w.colors == 1 ? "" : "s", w.depth ? " + depth" : "", + w.area.width, w.area.height); + text += pass; + } + return text; +} + +// The recent dispatches and draws of every queue, oldest first once read. Allocated once, when the markers are on: +// 65,536 entries of about 100 bytes (6 MiB), several frames of draws. class MarkerHistory { public: - static constexpr std::size_t capacity = 16384; + static constexpr std::size_t capacity = 65536; MarkerHistory() : entries_(capacity) {} - void push(const MarkedDispatch& d) { entries_[count_++ % capacity] = d; } + void push(const MarkedWork& d) { entries_[count_++ % capacity] = d; } std::size_t size() const { return count_ < capacity ? count_ : capacity; } @@ -72,7 +201,7 @@ class MarkerHistory { } private: - std::vector entries_; + std::vector entries_; std::size_t count_ = 0; }; @@ -82,7 +211,10 @@ struct MarkerQueueReport { const char* queue_kind = nullptr; // from the history, null when it holds no dispatch of the queue std::vector unfinished; // seqs of this queue in (finished, started], oldest first std::uint64_t likely_hang = 0; // the oldest of them; 0 when none was started and not finished - std::uint64_t next_queued = 0; // idle queue: the oldest submitted dispatch after `finished`, not started yet + std::uint64_t next_queued = 0; // idle queue: the oldest submitted item after `finished`, not started yet + std::uint64_t last_finished = 0; // the history's item whose seq is `finished`; 0 when it holds none + std::uint64_t last_started = 0; // the history's newest item of the queue at or before `started`; 0: none + std::uint64_t last_draw = 0; // the newest draw among them (the last draw the queue started); 0: none bool missing = false; // started > finished but the history no longer holds any of them bool idle() const { return slot.started == slot.finished; } @@ -95,9 +227,14 @@ MarkerQueueReport judge_markers(VkQueue queue, MarkerSlot slot, const History& h // never behind; a value that says otherwise (memory lost in a reset) is read as an idle queue. if (slot.started != slot.finished && !marker_after(slot.started, slot.finished)) slot.started = slot.finished; report.slot = slot; - history.for_each([&](const MarkedDispatch& d) { + history.for_each([&](const MarkedWork& d) { if (d.queue != queue) return; if (!report.queue_kind) report.queue_kind = d.queue_kind; + if (slot.started && !marker_after(d.seq, slot.started)) { + report.last_started = d.seq; + if (d.is_draw()) report.last_draw = d.seq; + } + if (slot.finished && std::uint32_t(d.seq) == slot.finished) report.last_finished = d.seq; if (!marker_after(d.seq, slot.finished)) return; if (!marker_after(d.seq, slot.started)) report.unfinished.push_back(d.seq); else if (!report.next_queued) report.next_queued = d.seq; diff --git a/runtime/src/vulkan_gpu_profile.h b/runtime/src/vulkan_gpu_profile.h new file mode 100644 index 0000000000..8a22884a8d --- /dev/null +++ b/runtime/src/vulkan_gpu_profile.h @@ -0,0 +1,461 @@ +#pragma once +// LEONIDA_GPU_PROFILE=1 (diagnostic, off by default): GPU time per pipeline, from timestamp queries. +// +// Each submission of a queue whose family writes timestamps gets a query pool, reset once at the start of its command +// buffer. A bottom-of-pipe timestamp goes after the submission's opening barrier and bindless upload, one before each +// run of draws or dispatches of one pipeline (consecutive commands of one pipeline share it), one after the run when +// any other command follows (a barrier, copy, clear, query or one of the layer's own passes), and one at the end. A +// bottom-of-pipe timestamp is written once everything recorded before it has finished, so on a GPU that runs a queue's +// work in order (a desktop GPU without tiling) the difference between two consecutive timestamps is the GPU time by +// which what lies between them extended the queue's work: a run's own time, or "other" when no draw or dispatch lies +// between. Work that overlaps the previous run (no barrier between) counts only for its tail; the layer's helper passes +// for a draw (index expansion, indirect clamp) count for the draw. The results are read when the submission is known +// done (the fence callback), without waiting, and summed by pipeline: by the ShaderLibrary names of its stages, as the +// pass trace and the device-fault report name them, else by the PSO's id. +// +// Every 10 s, on the thread that reads the results, `[rt] gpu profile` lines give the window's totals per frame (by +// presents) for compute, graphics and mesh pipelines and for other work, per queue kind the busy time measured as +// LEONIDA_GPU_LATENCY does (from the later of submit and the previous completion to completion, on the CPU) against +// the time between the first and the last timestamp of its submissions, and the 20 pipelines with the most GPU time. +// Queues run at the same time, so their sums can exceed the frame time. Cost when off: one relaxed load and branch +// per submission and one null test per command; when on: a query reset per submission, one timestamp per run +// boundary, a name lookup per run, and the result read on the fence thread. +#include "submit_phases.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace leonida::gpu_profile { + +inline std::atomic& switch_state() { + static std::atomic on{[] { + const char* v = std::getenv("LEONIDA_GPU_PROFILE"); + return v && std::strcmp(v, "1") == 0; + }()}; + return on; +} +inline bool enabled() { return switch_state().load(std::memory_order_relaxed); } +// Tests only: before the context is made (it loads the query functions only when the profile is on). +inline void set_enabled_for_test(bool on) { switch_state().store(on, std::memory_order_relaxed); } + +enum class Kind : std::uint8_t { compute, graphics, mesh }; +inline const char* kind_name(Kind kind) { + return kind == Kind::compute ? "compute" : kind == Kind::graphics ? "graphics" : "mesh"; +} + +// The ShaderLibrary names of a pipeline's stages, as CheckpointShaders: [0] the compute, vertex or mesh shader, [1] the +// geometry shader, [2] the pixel shader. Immutable strings, valid until the device goes. +using Names = std::array; +using NameMap = std::unordered_map; + +// What the profile sums by: the pipeline's kind and stage names, or its id when it has no names. +struct Key { + Kind kind = Kind::compute; + Names names{}; + std::uintptr_t id = 0; + bool operator==(const Key&) const = default; +}; +struct KeyHash { + std::size_t operator()(const Key& k) const noexcept { + std::size_t h = std::hash{}(k.id) ^ (std::size_t(k.kind) * 0x9e3779b97f4a7c15ull); + for (const char* n : k.names) h = (h ^ std::hash{}(n)) * 0x100000001b3ull; + return h; + } +}; + +// The name a pipeline goes by in the lines: its stages' entry names without their folder, as the pass trace prints +// them, or "pso 0x..." for one registered without names. +inline std::string label(const Key& key) { + std::string text; + static const char* const graphics_stages[3] = {"vs", "gs", "ps"}; + for (std::size_t i = 0; i < key.names.size(); ++i) { + const char* name = key.names[i]; + if (!name) continue; + if (const char* slash = std::strrchr(name, '/')) name = slash + 1; + if (!text.empty()) text += ' '; + text += key.kind == Kind::compute ? "cs" : i == 0 && key.kind == Kind::mesh ? "ms" : graphics_stages[i]; + text += ' '; + text += name; + } + if (text.empty()) { + char id[48]; + std::snprintf(id, sizeof id, "pso 0x%llx", static_cast(key.id)); + text = id; + } + return text; +} + +class Profiler; + +// One submission's timestamps, recorded by the replay (ReplayFunctions::gpu_profile) on the submitting thread. +class Recording { +public: + Recording(const Recording&) = delete; + Recording& operator=(const Recording&) = delete; + inline ~Recording(); + + // A draw or dispatch of pipeline `id` comes next. A run of the same pipeline goes on; otherwise a timestamp closes + // the interval since the last one (the open run's, or other work's) and a run of this pipeline starts. + void work(VkCommandBuffer cb, Kind kind, std::uintptr_t id) { + if (open_ && id == open_id_ && kind == open_kind_) { + ++runs_.back().calls; + return; + } + if (!stamp(cb, open_ ? std::int32_t(runs_.size() - 1) : -1)) { + open_ = false; + ++dropped_; + return; + } + open_ = true; + open_id_ = id; + open_kind_ = kind; + runs_.push_back({key(kind, id), 1, 0}); + } + // Any other command comes next: the open run ends here. + void other(VkCommandBuffer cb) { + if (!open_) return; + stamp(cb, std::int32_t(runs_.size() - 1)); + open_ = false; + } + // After the last list: the last interval. + void finish(VkCommandBuffer cb) { + stamp(cb, open_ ? std::int32_t(runs_.size() - 1) : -1); + open_ = false; + } + void mark_submitted() { submitted_ = std::chrono::steady_clock::now(); } + +private: + friend class Profiler; + struct Run { + Key key; + std::uint32_t calls; + std::uint64_t ticks; + }; + Recording() = default; + bool stamp(VkCommandBuffer cb, std::int32_t owner) { + if (used_ >= capacity_) return false; + write_(cb, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, pool_, used_); + if (used_) owners_.push_back(owner); + ++used_; + return true; + } + Key key(Kind kind, std::uintptr_t id) const { + Key k; + k.kind = kind; + if (names_) { + const auto it = names_->find(id); + if (it != names_->end()) k.names = it->second; + } + if (!k.names[0] && !k.names[1] && !k.names[2]) k.id = id; + return k; + } + + Profiler* owner_ = nullptr; + VkQueryPool pool_ = VK_NULL_HANDLE; + std::uint32_t capacity_ = 0, used_ = 0; + PFN_vkCmdWriteTimestamp write_ = nullptr; + const NameMap* names_ = nullptr; // read under the context's pipeline lock, which the replay holds + std::vector owners_; // per interval between timestamps k and k+1: a run, or -1 for other work + std::vector runs_; + bool open_ = false; + Kind open_kind_ = Kind::compute; + std::uintptr_t open_id_ = 0; + int queue_ = 0; // VulkanQueue::QueueKind: 0 direct, 1 compute, 2 copy + std::uint64_t mask_ = ~0ull; + double period_ = 0; // ns per tick + std::uint64_t dropped_ = 0; + std::chrono::steady_clock::time_point submitted_{}; +}; + +class Profiler { +public: + static constexpr unsigned kTop = 20; + static constexpr auto kWindow = std::chrono::seconds(10); + + Profiler() = default; + Profiler(const Profiler&) = delete; + Profiler& operator=(const Profiler&) = delete; + ~Profiler() { stop(); } + + // Loads the query functions. False (and the profile stays off for this device) when one is missing. + bool configure(VkDevice device, PFN_vkGetDeviceProcAddr get) { + if (!enabled() || !device || !get) return false; + std::lock_guard lock(mutex_); +#define LEONIDA_PROFILE_FN(name) reinterpret_cast(get(device, #name)) + create_ = LEONIDA_PROFILE_FN(vkCreateQueryPool); + destroy_ = LEONIDA_PROFILE_FN(vkDestroyQueryPool); + reset_ = LEONIDA_PROFILE_FN(vkCmdResetQueryPool); + write_ = LEONIDA_PROFILE_FN(vkCmdWriteTimestamp); + results_ = LEONIDA_PROFILE_FN(vkGetQueryPoolResults); +#undef LEONIDA_PROFILE_FN + if (!create_ || !destroy_ || !reset_ || !write_ || !results_) return false; + device_ = device; + stopped_ = false; + since_ = std::chrono::steady_clock::now(); + frames_at_ = submit_phases::totals().present_serial.load(std::memory_order_relaxed); + std::fprintf(stderr, "[rt] gpu profile: on (LEONIDA_GPU_PROFILE=1): the GPU time of every draw and dispatch, " + "summed by pipeline from timestamps, every 10 s\n"); + return true; + } + + // A recording for the command buffer just begun, with its query pool reset and its first timestamp written, or + // null: the profile is off, the queue's family writes no timestamps (`bits` 0) or no pool could be made. + // `commands`: the commands of its lists, which bounds the timestamps (at most one per command, and two more). + std::unique_ptr begin(VkCommandBuffer cb, int queue, double period_ns, std::uint32_t bits, + std::size_t commands, const NameMap* names) { + if (!enabled() || !cb) return nullptr; + if (!bits || period_ns <= 0) { + if (!no_timestamps_.exchange(true)) + std::fprintf(stderr, "[rt] gpu profile: a %s queue's family has no timestamps the profile can reset " + "and read; the submissions of such queues are not profiled\n", queue_name(queue)); + return nullptr; + } + const std::uint64_t wanted = std::uint64_t(commands) + 2; + if (wanted > (1u << 24)) return nullptr; + std::uint32_t capacity = 256; + while (capacity < wanted) capacity *= 2; + VkQueryPool pool = take(capacity); + if (!pool) return nullptr; + std::unique_ptr r(new Recording()); + r->owner_ = this; + r->pool_ = pool; + r->capacity_ = capacity; + r->write_ = write_; + r->names_ = names; + r->queue_ = queue < 0 || queue > 2 ? 0 : queue; + r->mask_ = bits >= 64 ? ~0ull : (1ull << bits) - 1; + r->period_ = period_ns; + r->owners_.reserve(std::size_t(wanted)); + reset_(cb, pool, 0, capacity); + r->stamp(cb, -1); + return r; + } + + // On the fence callback, once the submission is done: reads its timestamps, adds them up, and every 10 s prints. + void resolve(Recording& r) { + const auto now = std::chrono::steady_clock::now(); + std::vector ticks(r.used_); + const bool read = r.used_ >= 2 && device_ && + results_(device_, r.pool_, 0, r.used_, ticks.size() * sizeof(std::uint64_t), ticks.data(), + sizeof(std::uint64_t), VK_QUERY_RESULT_64_BIT) == VK_SUCCESS; + double other_ns = 0, span_ns = 0; + if (read) { + for (std::uint32_t k = 1; k < r.used_; ++k) { + const std::uint64_t d = (ticks[k] - ticks[k - 1]) & r.mask_; + const std::int32_t owner = r.owners_[k - 1]; + if (owner < 0) other_ns += double(d) * r.period_; + else r.runs_[std::size_t(owner)].ticks += d; + } + span_ns = double((ticks[r.used_ - 1] - ticks[0]) & r.mask_) * r.period_; + } + std::lock_guard lock(mutex_); + QueueTotals& q = queues_[r.queue_]; + // As LEONIDA_GPU_LATENCY: an in-order queue is busy from the later of the submit and the previous + // completion it saw to this one. + if (r.submitted_ != std::chrono::steady_clock::time_point{}) { + const auto from = (std::max)(r.submitted_, q.last_done); + if (now > from) q.busy_ns += double(std::chrono::duration_cast(now - from).count()); + q.last_done = now; + } + ++q.submissions; + q.dropped += r.dropped_; + if (!read) { + ++q.unread; + } else { + q.span_ns += span_ns; + q.other_ns += other_ns; + q.stamps += r.used_; + for (const auto& run : r.runs_) { + const double ns = double(run.ticks) * r.period_; + auto [it, inserted] = pipelines_.try_emplace(run.key); + if (inserted) it->second.label = label(run.key); + it->second.ns += ns; + it->second.calls += run.calls; + ++it->second.runs; + q.pipelines_ns += ns; + kind_ns_[std::size_t(run.key.kind)] += ns; + } + } + if (now - since_ >= kWindow) report_locked(now); + } + + // Tests: the sums so far, by pipeline. + struct Entry { + Key key; + std::string label; + double ms = 0; + std::uint64_t calls = 0, runs = 0; + }; + std::vector snapshot() { + std::lock_guard lock(mutex_); + std::vector out; + for (const auto& [key, t] : pipelines_) out.push_back({key, t.label, t.ns / 1e6, t.calls, t.runs}); + return out; + } + struct QueueSnapshot { + std::uint64_t submissions = 0, unread = 0, stamps = 0, dropped = 0; + double busy_ms = 0, span_ms = 0, pipelines_ms = 0, other_ms = 0; + }; + QueueSnapshot queue(int kind) { + std::lock_guard lock(mutex_); + const QueueTotals& q = queues_[kind < 0 || kind > 2 ? 0 : kind]; + return {q.submissions, q.unread, q.stamps, q.dropped, q.busy_ns / 1e6, q.span_ns / 1e6, q.pipelines_ns / 1e6, + q.other_ns / 1e6}; + } + // Tests: prints the lines now and starts a new window. + void report_now() { + std::lock_guard lock(mutex_); + report_locked(std::chrono::steady_clock::now()); + } + + // Before the device goes: destroys the idle pools; a recording that ends later destroys its own. + void stop() { + std::lock_guard lock(mutex_); + for (auto& [capacity, pools] : idle_) + for (VkQueryPool pool : pools) destroy_(device_, pool, nullptr); + idle_.clear(); + stopped_ = true; + } + +private: + friend class Recording; + struct Totals { + std::string label; + double ns = 0; + std::uint64_t calls = 0, runs = 0; + }; + struct QueueTotals { + std::uint64_t submissions = 0, unread = 0, stamps = 0, dropped = 0; + double busy_ns = 0, span_ns = 0, pipelines_ns = 0, other_ns = 0; + std::chrono::steady_clock::time_point last_done{}; + }; + + static const char* queue_name(int queue) { return queue == 0 ? "direct" : queue == 1 ? "compute" : "copy"; } + + VkQueryPool take(std::uint32_t capacity) { + { + std::lock_guard lock(mutex_); + if (!device_ || stopped_) return VK_NULL_HANDLE; + auto it = idle_.find(capacity); + if (it != idle_.end() && !it->second.empty()) { + VkQueryPool pool = it->second.back(); + it->second.pop_back(); + return pool; + } + } + VkQueryPoolCreateInfo info{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO}; + info.queryType = VK_QUERY_TYPE_TIMESTAMP; + info.queryCount = capacity; + VkQueryPool pool = VK_NULL_HANDLE; + return create_(device_, &info, nullptr, &pool) == VK_SUCCESS ? pool : VK_NULL_HANDLE; + } + void recycle(VkQueryPool pool, std::uint32_t capacity) { + if (!pool) return; + std::lock_guard lock(mutex_); + if (stopped_) destroy_(device_, pool, nullptr); + else idle_[capacity].push_back(pool); + } + + // mutex_ held. + void report_locked(std::chrono::steady_clock::time_point now) { + const double seconds = std::chrono::duration(now - since_).count(); + const std::uint64_t serial = submit_phases::totals().present_serial.load(std::memory_order_relaxed); + const std::uint64_t frames = serial - frames_at_; + // Per frame when the window presented any, else the window's totals. + const double per = frames ? double(frames) : 1.0; + const char* unit = frames ? "/frame" : ""; + double pipelines_ns = 0, other_ns = 0; + std::uint64_t calls = 0, runs = 0, stamps = 0; + for (const auto& [key, t] : pipelines_) { + pipelines_ns += t.ns; + calls += t.calls; + runs += t.runs; + } + for (const auto& q : queues_) { + other_ns += q.other_ns; + stamps += q.stamps; + } + std::fprintf(stderr, + "[rt] gpu profile: %.1f s, %llu frames%s: compute %.2f ms%s, graphics %.2f ms%s, mesh %.2f ms%s " + "(%.1f calls%s in %.1f runs%s), other %.2f ms%s (barriers, copies, clears, queries, the layer's " + "own passes); %.0f timestamps%s\n", + seconds, static_cast(frames), frames ? "" : " (none presented: totals)", + kind_ns_[0] / 1e6 / per, unit, kind_ns_[1] / 1e6 / per, unit, kind_ns_[2] / 1e6 / per, unit, + double(calls) / per, unit, double(runs) / per, unit, other_ns / 1e6 / per, unit, + double(stamps) / per, unit); + for (int k = 0; k < 3; ++k) { + const QueueTotals& q = queues_[k]; + if (!q.submissions) continue; + std::fprintf(stderr, + "[rt] gpu profile (%s): %llu submissions, busy %.2f ms%s, %.2f ms%s from first to last " + "timestamp (%.1f%% of busy), %.2f ms%s in draws and dispatches (%.1f%% of busy)", + queue_name(k), static_cast(q.submissions), q.busy_ns / 1e6 / per, unit, + q.span_ns / 1e6 / per, unit, q.busy_ns > 0 ? 100.0 * q.span_ns / q.busy_ns : 0.0, + q.pipelines_ns / 1e6 / per, unit, q.busy_ns > 0 ? 100.0 * q.pipelines_ns / q.busy_ns : 0.0); + if (q.unread || q.dropped) + std::fprintf(stderr, "; %llu submissions unread, %llu runs untimed", + static_cast(q.unread), static_cast(q.dropped)); + std::fputc('\n', stderr); + } + std::vector*> ranked; + ranked.reserve(pipelines_.size()); + for (const auto& entry : pipelines_) ranked.push_back(&entry); + const std::size_t top = (std::min)(ranked.size(), std::size_t(kTop)); + std::partial_sort(ranked.begin(), ranked.begin() + std::ptrdiff_t(top), ranked.end(), + [](const auto* a, const auto* b) { return a->second.ns > b->second.ns; }); + for (std::size_t i = 0; i < top; ++i) { + const auto& [key, t] = *ranked[i]; + std::fprintf(stderr, + "[rt] gpu profile #%zu: %.3f ms%s (%.1f%%), %s, %.1f calls%s, %.4f ms per call: %s\n", i + 1, + t.ns / 1e6 / per, unit, pipelines_ns > 0 ? 100.0 * t.ns / pipelines_ns : 0.0, + kind_name(key.kind), double(t.calls) / per, unit, t.calls ? t.ns / 1e6 / double(t.calls) : 0.0, + t.label.c_str()); + } + pipelines_.clear(); + for (auto& q : queues_) { + const auto last = q.last_done; + q = {}; + q.last_done = last; + } + kind_ns_[0] = kind_ns_[1] = kind_ns_[2] = 0; + since_ = now; + frames_at_ = serial; + } + + std::mutex mutex_; + VkDevice device_ = VK_NULL_HANDLE; + PFN_vkCreateQueryPool create_ = nullptr; + PFN_vkDestroyQueryPool destroy_ = nullptr; + PFN_vkCmdResetQueryPool reset_ = nullptr; + PFN_vkCmdWriteTimestamp write_ = nullptr; + PFN_vkGetQueryPoolResults results_ = nullptr; + bool stopped_ = false; + std::atomic no_timestamps_{false}; + std::map> idle_; // by capacity + std::unordered_map pipelines_; + QueueTotals queues_[3]; + double kind_ns_[3] = {}; + std::chrono::steady_clock::time_point since_ = std::chrono::steady_clock::now(); + std::uint64_t frames_at_ = 0; +}; + +inline Recording::~Recording() { + if (owner_) owner_->recycle(pool_, capacity_); +} + +} // namespace leonida::gpu_profile diff --git a/runtime/src/vulkan_indirect_clamp.h b/runtime/src/vulkan_indirect_clamp.h index fcf5cd76b6..1062851c65 100644 --- a/runtime/src/vulkan_indirect_clamp.h +++ b/runtime/src/vulkan_indirect_clamp.h @@ -36,6 +36,7 @@ #include #include +#include #include #include #include @@ -137,15 +138,23 @@ struct ClampedIndirect { std::uint32_t max_records = 0; }; -// One device's clamp: the pass's pipeline (made on the first call), the per-submission record pool, and the counter -// slots. Single-threaded per list, as the replay's preparation is: the caller holds the context's tracker lock for -// prepare and emit, and the batch destructor only touches the slot bookkeeping under `mutex_`. +// One device's clamp: the pass's pipeline (made on the first call), the per-batch record scratch pool, and the +// counter slots. Thread-safe across concurrent queue preparations via its own internal locks (never requires the +// context's tracker_mutex_), while each Batch owns its own disjoint scratch chunks until the submission's timeline +// ticket retires and ~Batch() returns them to the pool. class IndirectArgumentClamp { private: struct Slot { std::uint32_t area; std::uint32_t index; }; + struct ScratchChunk { + VkBuffer buffer = VK_NULL_HANDLE; + VkDeviceMemory memory = VK_NULL_HANDLE; + VkDeviceSize size = 0; + VkDeviceSize used = 0; + VkDeviceAddress address = 0; + }; static constexpr std::uint32_t no_slot = UINT32_MAX; // Slot::area of a call clamped without counters public: @@ -161,12 +170,13 @@ class IndirectArgumentClamp { // False when the pass cannot run on this device (no device addresses, no compute): the replay then keeps the // application's buffer. - bool loaded() const { return scratch_.loaded() && limits_.maxComputeWorkGroupCount[0] != 0; } + bool loaded() const { return scratch_loaded_ && limits_.maxComputeWorkGroupCount[0] != 0; } - // The record pool's life cycle, as the copy scratch's (vulkan_scratch.h). - void collect() { scratch_.collect(); } - void retire(VkSemaphore timeline, std::uint64_t ticket) { scratch_.retire(timeline, ticket); } - void forget(VkSemaphore timeline) { scratch_.forget(timeline); } + // Kept for API compatibility: scratch chunks are owned per Batch and returned to the spare pool in ~Batch() once + // the submission's timeline ticket completes (CommandSlot destruction/reuse). + void collect() {} + void retire(VkSemaphore /*timeline*/, std::uint64_t /*ticket*/) {} + void forget(VkSemaphore /*timeline*/) {} // What the pass found since the process started. `records_clamped` counts the records whose values the pass // changed (the ones it emptied included). @@ -192,12 +202,16 @@ class IndirectArgumentClamp { std::uint64_t dispatch_cut = 0; }; - // One submission's clamp state: the counter slots its calls claimed, read and released together once that - // submission has completed. Retained by the command-buffer slot until its timeline ticket does. + // One submission's clamp state: the counter slots and disjoint scratch chunks its calls claimed, read and + // released together once that submission has completed. Retained by the command-buffer slot until its timeline + // ticket completes. class Batch { public: explicit Batch(IndirectArgumentClamp& owner) : owner_(owner) {} - ~Batch() { owner_.release(slots_, true); } + ~Batch() { + owner_.release(slots_, true); + owner_.return_chunks(chunks_); + } Batch(const Batch&) = delete; Batch& operator=(const Batch&) = delete; @@ -215,7 +229,8 @@ class IndirectArgumentClamp { owner_.note_uncounted(); slot = Slot{no_slot, 0}; } - if (!owner_.prepare(arguments, argument_offset, count, count_offset, kind, stride, max_count, slot, out)) { + if (!owner_.prepare(chunks_, arguments, argument_offset, count, count_offset, kind, stride, max_count, slot, + out)) { if (counted) owner_.release_one(slot); return false; } @@ -235,6 +250,7 @@ class IndirectArgumentClamp { private: IndirectArgumentClamp& owner_; std::vector slots_; + std::vector chunks_; }; std::unique_ptr batch() { return std::make_unique(*this); } @@ -257,19 +273,51 @@ class IndirectArgumentClamp { std::uint32_t slots = 0; static constexpr std::uint32_t slot_bytes = 64; // 16 words of counters (words 4-7 unused) }; + struct VkFns { + PFN_vkCreateBuffer create_buffer = nullptr; + PFN_vkDestroyBuffer destroy_buffer = nullptr; + PFN_vkGetBufferMemoryRequirements get_buffer_memory_requirements = nullptr; + PFN_vkAllocateMemory allocate_memory = nullptr; + PFN_vkFreeMemory free_memory = nullptr; + PFN_vkBindBufferMemory bind_buffer_memory = nullptr; + PFN_vkMapMemory map_memory = nullptr; + PFN_vkUnmapMemory unmap_memory = nullptr; + PFN_vkGetBufferDeviceAddress get_buffer_device_address = nullptr; + PFN_vkDeviceWaitIdle device_wait_idle = nullptr; + PFN_vkCreateShaderModule create_shader_module = nullptr; + PFN_vkDestroyShaderModule destroy_shader_module = nullptr; + PFN_vkCreatePipelineLayout create_pipeline_layout = nullptr; + PFN_vkDestroyPipelineLayout destroy_pipeline_layout = nullptr; + PFN_vkCreateComputePipelines create_compute_pipelines = nullptr; + PFN_vkDestroyPipeline destroy_pipeline = nullptr; + PFN_vkCmdPipelineBarrier cmd_pipeline_barrier = nullptr; + PFN_vkCmdBindPipeline cmd_bind_pipeline = nullptr; + PFN_vkCmdPushConstants cmd_push_constants = nullptr; + PFN_vkCmdDispatch cmd_dispatch = nullptr; + PFN_vkCmdFillBuffer cmd_fill_buffer = nullptr; + PFN_vkCmdCopyBuffer cmd_copy_buffer = nullptr; + bool pipeline_fns_loaded = false; + }; static constexpr std::uint32_t slots_per_area = 64; // 4,096 slots (128 KiB of host memory): enough for a submission's ExecuteIndirect calls after the load, and the // calls past them are still clamped (no_slot). static constexpr std::uint32_t max_areas = 64; + static constexpr std::size_t max_spare_chunks = 16; - template T fn(const char* name) const { return reinterpret_cast(get_(device_, name)); } + void load_fns(); bool make_pipeline(); bool make_area(); + bool make_scratch_chunk(VkDeviceSize size, ScratchChunk& out); + void destroy_scratch_chunk(ScratchChunk& chunk); + bool claim_scratch(std::vector& batch_chunks, VkDeviceSize bytes, VkBuffer& buffer, + VkDeviceSize& offset, VkDeviceAddress& address); + void return_chunks(std::vector& chunks); bool claim_slot(Slot& out); void release_one(Slot slot); void release(std::vector& slots, bool read); - bool prepare(VkBuffer arguments, VkDeviceSize argument_offset, VkBuffer count, VkDeviceSize count_offset, - std::uint32_t kind, std::uint32_t stride, std::uint32_t max_count, Slot slot, ClampedIndirect& out); + bool prepare(std::vector& batch_chunks, VkBuffer arguments, VkDeviceSize argument_offset, + VkBuffer count, VkDeviceSize count_offset, std::uint32_t kind, std::uint32_t stride, + std::uint32_t max_count, Slot slot, ClampedIndirect& out); void fallback(const char* reason); void note_uncounted(); @@ -277,11 +325,19 @@ class IndirectArgumentClamp { VkDevice device_; VkPhysicalDeviceMemoryProperties memory_{}; VkPhysicalDeviceLimits limits_{}; + Allocate allocate_; + DeviceFaultDiagnostics* diagnostics_ = nullptr; std::vector families_; - ScratchBuffers scratch_; + VkFns vk_{}; + bool scratch_loaded_ = false; + std::mutex pipeline_mutex_; // guards lazy one-time make_pipeline() + std::atomic pipeline_ready_{false}; VkPipelineLayout layout_ = VK_NULL_HANDLE; VkPipeline pipeline_ = VK_NULL_HANDLE; + std::mutex scratch_mutex_; // guards spare_chunks_ + std::vector spare_chunks_; + mutable std::mutex mutex_; // the slot bookkeeping and the counters std::vector areas_; std::vector free_slots_; @@ -321,48 +377,166 @@ inline constexpr VkBufferUsageFlags indirect_clamp_scratch_usage = } // namespace detail +inline void IndirectArgumentClamp::load_fns() { + if (!get_ || !device_) return; + auto load = [&](T& dst, const char* name) { + dst = reinterpret_cast(get_(device_, name)); + return dst != nullptr; + }; + bool scratch_ok = true; + scratch_ok = load(vk_.create_buffer, "vkCreateBuffer") && scratch_ok; + scratch_ok = load(vk_.destroy_buffer, "vkDestroyBuffer") && scratch_ok; + scratch_ok = load(vk_.get_buffer_memory_requirements, "vkGetBufferMemoryRequirements") && scratch_ok; + scratch_ok = load(vk_.bind_buffer_memory, "vkBindBufferMemory") && scratch_ok; + scratch_ok = load(vk_.free_memory, "vkFreeMemory") && scratch_ok; + scratch_ok = load(vk_.get_buffer_device_address, "vkGetBufferDeviceAddress") && scratch_ok; + scratch_ok = load(vk_.device_wait_idle, "vkDeviceWaitIdle") && scratch_ok; + scratch_loaded_ = scratch_ok; + + bool pipe_ok = scratch_ok; + pipe_ok = load(vk_.allocate_memory, "vkAllocateMemory") && pipe_ok; + pipe_ok = load(vk_.map_memory, "vkMapMemory") && pipe_ok; + pipe_ok = load(vk_.unmap_memory, "vkUnmapMemory") && pipe_ok; + pipe_ok = load(vk_.create_shader_module, "vkCreateShaderModule") && pipe_ok; + pipe_ok = load(vk_.destroy_shader_module, "vkDestroyShaderModule") && pipe_ok; + pipe_ok = load(vk_.create_pipeline_layout, "vkCreatePipelineLayout") && pipe_ok; + pipe_ok = load(vk_.destroy_pipeline_layout, "vkDestroyPipelineLayout") && pipe_ok; + pipe_ok = load(vk_.create_compute_pipelines, "vkCreateComputePipelines") && pipe_ok; + pipe_ok = load(vk_.destroy_pipeline, "vkDestroyPipeline") && pipe_ok; + pipe_ok = load(vk_.cmd_pipeline_barrier, "vkCmdPipelineBarrier") && pipe_ok; + pipe_ok = load(vk_.cmd_bind_pipeline, "vkCmdBindPipeline") && pipe_ok; + pipe_ok = load(vk_.cmd_push_constants, "vkCmdPushConstants") && pipe_ok; + pipe_ok = load(vk_.cmd_dispatch, "vkCmdDispatch") && pipe_ok; + pipe_ok = load(vk_.cmd_fill_buffer, "vkCmdFillBuffer") && pipe_ok; + pipe_ok = load(vk_.cmd_copy_buffer, "vkCmdCopyBuffer") && pipe_ok; + vk_.pipeline_fns_loaded = pipe_ok; +} + inline IndirectArgumentClamp::IndirectArgumentClamp(PFN_vkGetDeviceProcAddr get, VkDevice device, const VkPhysicalDeviceMemoryProperties& memory, const VkPhysicalDeviceLimits& limits, Allocate allocate, DeviceFaultDiagnostics* diagnostics, std::vector families) - : get_(get), device_(device), memory_(memory), limits_(limits), families_(std::move(families)), - scratch_(get, device, std::move(allocate), diagnostics, detail::indirect_clamp_scratch_usage, families_) {} + : get_(get), device_(device), memory_(memory), limits_(limits), allocate_(std::move(allocate)), + diagnostics_(diagnostics), families_(std::move(families)) { + load_fns(); +} inline IndirectArgumentClamp::~IndirectArgumentClamp() { - const auto destroy_pipeline = fn("vkDestroyPipeline"); - const auto destroy_layout = fn("vkDestroyPipelineLayout"); - if (pipeline_ && destroy_pipeline) destroy_pipeline(device_, pipeline_, nullptr); - if (layout_ && destroy_layout) destroy_layout(device_, layout_, nullptr); - const auto destroy_buffer = fn("vkDestroyBuffer"); - const auto free_memory = fn("vkFreeMemory"); + if (scratch_loaded_ && vk_.device_wait_idle) { + DeviceFaultDiagnostics::observe(diagnostics_, vk_.device_wait_idle(device_), "vkDeviceWaitIdle"); + } + for (auto& chunk : spare_chunks_) destroy_scratch_chunk(chunk); + spare_chunks_.clear(); + if (pipeline_ && vk_.destroy_pipeline) vk_.destroy_pipeline(device_, pipeline_, nullptr); + if (layout_ && vk_.destroy_pipeline_layout) vk_.destroy_pipeline_layout(device_, layout_, nullptr); for (auto& area : areas_) { - if (area.buffer && destroy_buffer) destroy_buffer(device_, area.buffer, nullptr); - if (area.memory && free_memory) free_memory(device_, area.memory, nullptr); + if (area.buffer && vk_.destroy_buffer) vk_.destroy_buffer(device_, area.buffer, nullptr); + if (area.memory && vk_.free_memory) vk_.free_memory(device_, area.memory, nullptr); + } +} + +inline bool IndirectArgumentClamp::make_scratch_chunk(VkDeviceSize size, ScratchChunk& out) { + if (!scratch_loaded_) return false; + VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; + info.size = size; + info.usage = detail::indirect_clamp_scratch_usage; + share_across_queue_families(info, families_); + if (vk_.create_buffer(device_, &info, nullptr, &out.buffer) != VK_SUCCESS) return false; + VkMemoryRequirements requirements{}; + vk_.get_buffer_memory_requirements(device_, out.buffer, &requirements); + out.memory = allocate_ ? allocate_(requirements) : VK_NULL_HANDLE; + if (!out.memory || vk_.bind_buffer_memory(device_, out.buffer, out.memory, 0) != VK_SUCCESS) { + destroy_scratch_chunk(out); + return false; + } + VkBufferDeviceAddressInfo addr_info{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; + addr_info.buffer = out.buffer; + out.address = vk_.get_buffer_device_address(device_, &addr_info); + if (!out.address) { + destroy_scratch_chunk(out); + return false; + } + out.size = size; + out.used = 0; + return true; +} + +inline void IndirectArgumentClamp::destroy_scratch_chunk(ScratchChunk& chunk) { + if (chunk.buffer && vk_.destroy_buffer) vk_.destroy_buffer(device_, chunk.buffer, nullptr); + if (chunk.memory && vk_.free_memory) vk_.free_memory(device_, chunk.memory, nullptr); + chunk = {}; +} + +inline bool IndirectArgumentClamp::claim_scratch(std::vector& batch_chunks, VkDeviceSize bytes, + VkBuffer& buffer, VkDeviceSize& offset, VkDeviceAddress& address) { + constexpr VkDeviceSize alignment = 256, minimum = 4u << 20; + if (!scratch_loaded_ || !bytes) return false; + for (auto& chunk : batch_chunks) { + const VkDeviceSize rem = chunk.used % alignment; + const VkDeviceSize pad = rem ? alignment - rem : 0; + if (pad > chunk.size - chunk.used) continue; + const VkDeviceSize start = chunk.used + pad; + if (bytes <= chunk.size - start) { + chunk.used = start + bytes; + buffer = chunk.buffer; + offset = start; + address = chunk.address + start; + return true; + } + } + ScratchChunk chunk{}; + { + std::lock_guard lock(scratch_mutex_); + for (std::size_t i = 0; i < spare_chunks_.size(); ++i) { + if (spare_chunks_[i].size >= bytes) { + chunk = spare_chunks_[i]; + spare_chunks_.erase(spare_chunks_.begin() + std::ptrdiff_t(i)); + break; + } + } } + if (!chunk.buffer && !make_scratch_chunk((std::max)(bytes, minimum), chunk)) return false; + chunk.used = bytes; + buffer = chunk.buffer; + offset = 0; + address = chunk.address; + batch_chunks.push_back(chunk); + return true; +} + +inline void IndirectArgumentClamp::return_chunks(std::vector& chunks) { + if (chunks.empty()) return; + std::vector to_destroy; + { + std::lock_guard lock(scratch_mutex_); + for (auto& chunk : chunks) { + chunk.used = 0; + if (spare_chunks_.size() < max_spare_chunks) spare_chunks_.push_back(chunk); + else to_destroy.push_back(chunk); + } + } + chunks.clear(); + for (auto& chunk : to_destroy) destroy_scratch_chunk(chunk); } inline bool IndirectArgumentClamp::make_pipeline() { + if (pipeline_ready_.load(std::memory_order_acquire)) return true; + std::lock_guard lock(pipeline_mutex_); if (pipeline_) return true; - for (const char* name : {"vkCreateBuffer", "vkDestroyBuffer", "vkGetBufferMemoryRequirements", - "vkAllocateMemory", "vkFreeMemory", "vkBindBufferMemory", "vkMapMemory", "vkUnmapMemory", - "vkGetBufferDeviceAddress", "vkCreateShaderModule", "vkDestroyShaderModule", "vkCreatePipelineLayout", - "vkDestroyPipelineLayout", "vkCreateComputePipelines", "vkDestroyPipeline", "vkCmdPipelineBarrier", - "vkCmdBindPipeline", "vkCmdPushConstants", "vkCmdDispatch", "vkCmdFillBuffer", "vkCmdCopyBuffer"}) - if (!get_(device_, name)) return false; + if (!vk_.pipeline_fns_loaded) return false; VkShaderModule module = VK_NULL_HANDLE; VkShaderModuleCreateInfo shader{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; shader.codeSize = sizeof(indirect_clamp_spirv); shader.pCode = indirect_clamp_spirv; const aftermath::ShaderName aftermath_name("(runtime) indirect_clamp"); - bool ok = fn("vkCreateShaderModule")(device_, &shader, nullptr, &module) == VK_SUCCESS; + bool ok = vk_.create_shader_module(device_, &shader, nullptr, &module) == VK_SUCCESS; VkPipelineLayout layout = VK_NULL_HANDLE; const VkPushConstantRange range{VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(detail::IndirectClampPush)}; VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; layout_info.pushConstantRangeCount = 1; layout_info.pPushConstantRanges = ⦥ - ok = ok && fn("vkCreatePipelineLayout")(device_, &layout_info, nullptr, &layout) == - VK_SUCCESS; + ok = ok && vk_.create_pipeline_layout(device_, &layout_info, nullptr, &layout) == VK_SUCCESS; VkPipeline pipeline = VK_NULL_HANDLE; VkComputePipelineCreateInfo info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; @@ -370,28 +544,24 @@ inline bool IndirectArgumentClamp::make_pipeline() { info.stage.module = module; info.stage.pName = "main"; info.layout = layout; - ok = ok && fn("vkCreateComputePipelines")(device_, VK_NULL_HANDLE, 1, &info, nullptr, - &pipeline) == VK_SUCCESS; - if (module) fn("vkDestroyShaderModule")(device_, module, nullptr); + ok = ok && vk_.create_compute_pipelines(device_, VK_NULL_HANDLE, 1, &info, nullptr, &pipeline) == VK_SUCCESS; + if (module) vk_.destroy_shader_module(device_, module, nullptr); if (!ok) { - if (pipeline) fn("vkDestroyPipeline")(device_, pipeline, nullptr); - if (layout) fn("vkDestroyPipelineLayout")(device_, layout, nullptr); + if (pipeline) vk_.destroy_pipeline(device_, pipeline, nullptr); + if (layout) vk_.destroy_pipeline_layout(device_, layout, nullptr); return false; } layout_ = layout; pipeline_ = pipeline; + pipeline_ready_.store(true, std::memory_order_release); return true; } // One host-visible buffer of counter slots: a coherent mapping the pass's counters are copied into. inline bool IndirectArgumentClamp::make_area() { if (areas_.size() >= max_areas) return false; - const auto create_buffer = fn("vkCreateBuffer"); - const auto requirements_fn = fn("vkGetBufferMemoryRequirements"); - const auto bind_fn = fn("vkBindBufferMemory"); - const auto allocate_fn = fn("vkAllocateMemory"); - const auto map_fn = fn("vkMapMemory"); - if (!create_buffer || !requirements_fn || !bind_fn || !allocate_fn || !map_fn || !memory_.memoryTypeCount) + if (!vk_.create_buffer || !vk_.get_buffer_memory_requirements || !vk_.bind_buffer_memory || + !vk_.allocate_memory || !vk_.map_memory || !memory_.memoryTypeCount) return false; HostArea area{}; area.slots = slots_per_area; @@ -400,17 +570,15 @@ inline bool IndirectArgumentClamp::make_area() { info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT; // Direct and async-compute queues copy counter slots into the same HostArea buffer concurrently. share_across_queue_families(info, families_); - if (create_buffer(device_, &info, nullptr, &area.buffer) != VK_SUCCESS) return false; - const auto destroy_buffer = fn("vkDestroyBuffer"); - const auto free_memory = fn("vkFreeMemory"); + if (vk_.create_buffer(device_, &info, nullptr, &area.buffer) != VK_SUCCESS) return false; const auto cleanup = [&] { - if (area.buffer && destroy_buffer) destroy_buffer(device_, area.buffer, nullptr); - if (area.memory && free_memory) free_memory(device_, area.memory, nullptr); + if (area.buffer && vk_.destroy_buffer) vk_.destroy_buffer(device_, area.buffer, nullptr); + if (area.memory && vk_.free_memory) vk_.free_memory(device_, area.memory, nullptr); area.buffer = VK_NULL_HANDLE; area.memory = VK_NULL_HANDLE; }; VkMemoryRequirements requirements{}; - requirements_fn(device_, area.buffer, &requirements); + vk_.get_buffer_memory_requirements(device_, area.buffer, &requirements); VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; allocation.allocationSize = requirements.size; bool bound = false; @@ -419,16 +587,17 @@ inline bool IndirectArgumentClamp::make_area() { VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, 0, requirements.size)) { allocation.memoryTypeIndex = type; - if (allocate_fn(device_, &allocation, nullptr, &area.memory) != VK_SUCCESS) { + if (vk_.allocate_memory(device_, &allocation, nullptr, &area.memory) != VK_SUCCESS) { area.memory = VK_NULL_HANDLE; continue; } - bound = bind_fn(device_, area.buffer, area.memory, 0) == VK_SUCCESS; + bound = vk_.bind_buffer_memory(device_, area.buffer, area.memory, 0) == VK_SUCCESS; if (bound) break; - if (free_memory) free_memory(device_, area.memory, nullptr); + if (vk_.free_memory) vk_.free_memory(device_, area.memory, nullptr); area.memory = VK_NULL_HANDLE; } - if (!bound || map_fn(device_, area.memory, 0, info.size, 0, reinterpret_cast(&area.host)) != VK_SUCCESS) { + if (!bound || vk_.map_memory(device_, area.memory, 0, info.size, 0, reinterpret_cast(&area.host)) != + VK_SUCCESS) { cleanup(); return false; } @@ -558,9 +727,10 @@ inline void IndirectArgumentClamp::fallback(const char* reason) { "indirect command\n", static_cast(total), reason); } -inline bool IndirectArgumentClamp::prepare(VkBuffer arguments, VkDeviceSize argument_offset, VkBuffer count, - VkDeviceSize count_offset, std::uint32_t kind, std::uint32_t stride, - std::uint32_t max_count, Slot slot, ClampedIndirect& out) { +inline bool IndirectArgumentClamp::prepare(std::vector& batch_chunks, VkBuffer arguments, + VkDeviceSize argument_offset, VkBuffer count, VkDeviceSize count_offset, + std::uint32_t kind, std::uint32_t stride, std::uint32_t max_count, Slot slot, + ClampedIndirect& out) { out = {}; const std::uint32_t record_size = indirect_clamp_record_size(kind); if (kind > indirect_clamp_mesh || !arguments || !max_count || stride < record_size || stride % 4 || @@ -580,19 +750,19 @@ inline bool IndirectArgumentClamp::prepare(VkBuffer arguments, VkDeviceSize argu VkBuffer buffer = VK_NULL_HANDLE; VkDeviceSize offset = 0; VkDeviceAddress address = 0; - if (!scratch_.get(stats_scratch + 64, buffer, offset, address)) { + if (!claim_scratch(batch_chunks, stats_scratch + 64, buffer, offset, address)) { fallback("no scratch"); return false; } - const auto arguments_address = [&](VkBuffer b) { - VkBufferDeviceAddressInfo info{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; - info.buffer = b; - return fn("vkGetBufferDeviceAddress")(device_, &info); - }; if (!make_pipeline()) { fallback("no compute pipeline"); return false; } + const auto arguments_address = [&](VkBuffer b) { + VkBufferDeviceAddressInfo info{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; + info.buffer = b; + return vk_.get_buffer_device_address(device_, &info); + }; const VkDeviceAddress arguments_va = arguments_address(arguments); const VkDeviceAddress count_va = count ? arguments_address(count) : 0; if (!arguments_va || (count && !count_va) || argument_offset > UINT64_MAX - arguments_va || @@ -628,29 +798,27 @@ inline bool IndirectArgumentClamp::prepare(VkBuffer arguments, VkDeviceSize argu } inline void IndirectArgumentClamp::emit(VkCommandBuffer cb, const ClampedIndirect& job) { - const auto barrier = fn("vkCmdPipelineBarrier"); - const auto bind = fn("vkCmdBindPipeline"); - const auto push = fn("vkCmdPushConstants"); - const auto dispatch = fn("vkCmdDispatch"); // The counters start at zero: the budget's compare-and-swap and the record counts accumulate into them. A // transfer write, ordered to the compute stage by the barrier below, like the arguments' own writes. - fn("vkCmdFillBuffer")(cb, job.buffer, job.stats_scratch_offset, job.list_budget == job.stats + 16 ? 20 : 16, 0); + vk_.cmd_fill_buffer(cb, job.buffer, job.stats_scratch_offset, job.list_budget == job.stats + 16 ? 20 : 16, 0); // Words 8-15: the mesh and dispatch counters. - fn("vkCmdFillBuffer")(cb, job.buffer, job.stats_scratch_offset + 32, 32, 0); + vk_.cmd_fill_buffer(cb, job.buffer, job.stats_scratch_offset + 32, 32, 0); VkMemoryBarrier before{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; before.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT; // every earlier write: the compute that wrote these arguments before.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; - barrier(cb, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 1, &before, 0, nullptr, 0, - nullptr); - bind(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_); + vk_.cmd_pipeline_barrier(cb, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 1, + &before, 0, nullptr, 0, nullptr); + vk_.cmd_bind_pipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_); const VkDeviceSize dispatch_limit = VkDeviceSize(limits_.maxComputeWorkGroupCount[0]) * 64; // Bound per-dispatch indexing to 32 bits, even when the D3D12 stride is very large. - const std::uint32_t index_limit = (UINT32_MAX - 4u) / std::max(1u, job.stride_words); - const VkDeviceSize chunk_limit = std::max(1, std::min(dispatch_limit, VkDeviceSize(index_limit))); + const std::uint32_t index_limit = (UINT32_MAX - 4u) / (std::max)(std::uint32_t(1u), job.stride_words); + const VkDeviceSize chunk_limit = + (std::max)(VkDeviceSize(1), (std::min)(dispatch_limit, VkDeviceSize(index_limit))); const std::uint32_t tags = job.kind <= indirect_clamp_draw_indexed ? (job.kind == indirect_clamp_draw ? 4u : 5u) : 3u; for (VkDeviceSize first = 0; first < job.max_records;) { - const std::uint32_t records = std::uint32_t(std::min(chunk_limit, job.max_records - first)); + const std::uint32_t records = + std::uint32_t((std::min)(chunk_limit, VkDeviceSize(job.max_records) - first)); // Use local word offsets within each chunk. Only the count comparison needs the global record index. const detail::IndirectClampPush constants{job.arguments + first * job.stride_words * 4, job.count, @@ -669,24 +837,24 @@ inline void IndirectArgumentClamp::emit(VkCommandBuffer cb, const ClampedIndirec indirect_clamp_dispatch_limit(limits_, 1), indirect_clamp_dispatch_limit(limits_, 2), 0u}; - push(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(constants), &constants); - dispatch(cb, (records - 1u) / 64u + 1u, 1, 1); + vk_.cmd_push_constants(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(constants), &constants); + vk_.cmd_dispatch(cb, (records - 1u) / 64u + 1u, 1, 1); first += records; } if (job.stats_buffer) { // none for a call clamped without a counter slot VkMemoryBarrier after_copy{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; after_copy.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; after_copy.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; - barrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1, &after_copy, 0, nullptr, - 0, nullptr); + vk_.cmd_pipeline_barrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1, + &after_copy, 0, nullptr, 0, nullptr); VkBufferCopy copy{job.stats_scratch_offset, job.stats_offset, 16 * sizeof(std::uint32_t)}; - fn("vkCmdCopyBuffer")(cb, job.buffer, job.stats_buffer, 1, ©); + vk_.cmd_copy_buffer(cb, job.buffer, job.stats_buffer, 1, ©); } // The indirect command reads the records, and nothing else may read them while it does. VkMemoryBarrier done{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; done.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT; done.dstAccessMask = VK_ACCESS_INDIRECT_COMMAND_READ_BIT | VK_ACCESS_MEMORY_READ_BIT; - barrier(cb, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1, &done, 0, nullptr, 0, - nullptr); + vk_.cmd_pipeline_barrier(cb, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1, &done, + 0, nullptr, 0, nullptr); } } // namespace leonida diff --git a/runtime/src/vulkan_present.h b/runtime/src/vulkan_present.h index da9376e545..72f421eb2e 100644 --- a/runtime/src/vulkan_present.h +++ b/runtime/src/vulkan_present.h @@ -391,6 +391,7 @@ class VulkanPresenter { VkResult submit(const ResourceBinding* binding, ResourceId source, bool vsync, const PresentRect* source_rect, bool srgb, bool tear = false, const PresentPlanes* planes = nullptr) { + const submit_phases::TitleCall call(submit_phases::part_present); // the "submit frame" line wait_for_room(); std::lock_guard lock(present_mutex_); // `binding` null and `planes` null: clear instead of blit; `planes`: compose them (`binding`, `source`, @@ -516,11 +517,29 @@ class VulkanPresenter { return VK_ERROR_FORMAT_NOT_SUPPORTED; if (planes && !prepare_compose()) return VK_ERROR_FORMAT_NOT_SUPPORTED; const VkDevice device = context_.device(); - Frame& frame = frames_[frame_index_ % frames_.size()]; + const std::size_t slot_idx = frame_index_ % frames_.size(); + Frame& frame = frames_[slot_idx]; if (const VkResult waited = context_.observe_result( vkWaitForFences_(device, 1, &frame.done, VK_TRUE, UINT64_MAX), "vkWaitForFences (present)"); waited != VK_SUCCESS) return stop(waited); + // PresentComposer owns PresentComposer::frame_slots (2) descriptor sets indexed by slot % frame_slots. + // When frames_ is deeper than frame_slots and this present uses the composer, also wait for any peer slot + // sharing the same composer descriptor set before vkUpdateDescriptorSets rewrites it. + if (planes && frames_.size() > PresentComposer::frame_slots) { + const std::size_t comp_slot = slot_idx % PresentComposer::frame_slots; + for (std::size_t i = 0; i < frames_.size(); ++i) { + if (i == slot_idx || (i % PresentComposer::frame_slots) != comp_slot || !frames_[i].used_composer) + continue; + if (const VkResult waited = context_.observe_result( + vkWaitForFences_(device, 1, &frames_[i].done, VK_TRUE, UINT64_MAX), + "vkWaitForFences (present compose slot)"); + waited != VK_SUCCESS) + return stop(waited); + frames_[i].used_composer = false; + } + } + frame.used_composer = false; // Drain the preceding disk sample before reusing its fence or advancing its metadata. if (const VkResult r = finish_pending_capture(); r != VK_SUCCESS) return stop(r); @@ -655,7 +674,6 @@ class VulkanPresenter { const SubmitMutex::SubmitTurn turn(context_.submit_mutex(), false); // a queue operation: the compile gate submitted = context_.observe_result(context_.queue_submit(queue_, 1, &submit_info, frame.done), "vkQueueSubmit (present)"); - if (submitted == VK_SUCCESS) context_.note_image_work_locked(); if (submitted != VK_SUCCESS) rollback(); if (submitted == VK_SUCCESS && inspect) { result = finish_startup_frame(frame, image, show_title); @@ -674,6 +692,7 @@ class VulkanPresenter { } } if (submitted != VK_SUCCESS) return give_back(frame, submitted); + frame.used_composer = (planes != nullptr); ++frame_index_; // Only a present the engine took counts (SUBOPTIMAL is shown too). OUT_OF_DATE was not shown: the swapchain // is recreated next time, and the caller sees VK_SUCCESS, since its work was submitted. @@ -681,6 +700,7 @@ class VulkanPresenter { const auto shown = ++presented_; submit_phases::totals().presents.fetch_add(1, std::memory_order_relaxed); // frames a second, phase line submit_phases::totals().present_serial.fetch_add(1, std::memory_order_relaxed); + submit_phases::frame_presented(); // a frame of the "submit frame" line ends if (dump_.due(shown - 1)) { // Presentation is already queued and the queue/tracker locks are released. A sampled frame // may stall here for its transfer fence and a private CPU copy. PNG and disk I/O run on a worker. @@ -933,7 +953,6 @@ class VulkanPresenter { std::lock_guard lock(context_.submit_mutex()); submitted = context_.observe_result(context_.queue_submit(queue_, 1, &submit_info, probe_fence_), "vkQueueSubmit (present probe)"); - if (submitted == VK_SUCCESS) context_.note_image_work_locked(); } if (submitted != VK_SUCCESS || context_.observe_result(vkWaitForFences_(device, 1, &probe_fence_, VK_TRUE, 5'000'000'000ull), @@ -1025,6 +1044,7 @@ class VulkanPresenter { VkFence done = VK_NULL_HANDLE; VkSemaphore acquired = VK_NULL_HANDLE; std::array views{}; // the plane views of the last composed present, until the frame is reused + bool used_composer = false; // true when this slot's in-flight submission used PresentComposer }; bool recreate_for_present(bool vsync, bool srgb, bool hdr); @@ -1813,7 +1833,7 @@ class VulkanPresenter { VkExtent2D extent_{}; std::vector images_; std::vector ready_; // per swapchain image: blit done, present may start - std::array frames_{}; + std::array frames_{}; VkCommandPool pool_ = VK_NULL_HANDLE; std::uint64_t frame_index_ = 0; std::atomic presented_{0}; diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 4f3c476541..72b5cc3088 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -37,6 +37,7 @@ #include "indirect_draw_stats.h" #include "deferred_image_binding.h" #include "vulkan_device_fault.h" +#include "vulkan_gpu_profile.h" #include "depth24.h" #include "quad_index_expand.h" #include "rect_list_geometry.h" @@ -56,6 +57,7 @@ #include #include #include +#include #include #include #include @@ -764,11 +766,18 @@ class LayoutTracker { return true; } + std::size_t journal_size() const { return journal_.size(); } + void set(ResourceId id, const VkImageSubresourceRange& range, VkImageLayout layout) { const auto it = entries_.find(id); if (it == entries_.end()) return; - if (journaling_ && !journal_.contains(id)) journal_.emplace(id, it->second); Entry& e = it->second; + bool changed = false; + visit(e, range, [&](std::size_t index, VkImageAspectFlags, std::uint32_t, std::uint32_t) { + if (e.layouts[index] != layout) changed = true; + }); + if (!changed) return; + if (journaling_ && !journal_.contains(id)) journal_.emplace(id, e); visit(e, range, [&](std::size_t index, VkImageAspectFlags, std::uint32_t, std::uint32_t) { e.layouts[index] = layout; }); @@ -884,6 +893,8 @@ struct ComputePipeline { // one). Null: nobody is told. Called while a submission is prepared: it must never block or allocate (the only lock it may take is a non-blocking try_lock, on the first request of a pipeline and of a variant). void (*requested)(void*, std::uint32_t variant) = nullptr; void* request_context = nullptr; + bool reads_glc_buffer = false; // coherent (glc/dlc) buffer/global loads: pre-dispatch COMPUTE->COMPUTE barrier + bool writes_buffer = true; // false only when shader metadata proves no buffer/global/flat store or atomic }; // A graphics pipeline as replay needs it: the formats its attachments must have and which vertex-input slots it @@ -922,6 +933,8 @@ struct GraphicsPipeline { bool async_build = false; bool nonunit_vertex_divisor = false; // an actual instance divisor > 1, not a zero-stride emulation std::uint64_t estimate = 0; // as ComputePipeline::estimate + bool reads_glc_buffer = false; // true when any stage emits coherent glc/dlc buffer loads needing a pre-draw barrier + bool writes_buffer = true; // false only when every stage's shader metadata proves no buffer/global/flat write }; // The 144-byte push-constant block every translated shader declares: s0..s31, heap base, code base. @@ -1160,6 +1173,9 @@ struct ReplayFunctions { // Set: prepare() leaves pipelines that are not built to it instead of building each on the spot. PipelineCompiles* compiles = nullptr; std::function gpu_label; + // LEONIDA_GPU_PROFILE=1 (vulkan_gpu_profile.h): this submission's timestamps around each run of draws or + // dispatches of one pipeline. Null: no profile, and the replay records nothing for it. + gpu_profile::Recording* gpu_profile = nullptr; // Set 0 for the pipelines that declare one (their own `bindless_set` is only the marker): the device's current // generation of it, which a flush may have replaced since the pipeline was made. Null: the pipeline's. VkDescriptorSet bindless_set = VK_NULL_HANDLE; @@ -1233,6 +1249,10 @@ struct ReplayFunctions { PFN_vkCmdDrawMeshTasksIndirectCountEXT draw_mesh_tasks_indirect_count = nullptr; PFN_vkCmdDrawIndexed draw_indexed = nullptr; std::function graphics_pipeline; + // Called during emit when a draw or dispatch whose pipeline has `writes_buffer == true` (or a legacy indirect + // command without pipeline metadata) is emitted. Null: nobody is told. + void (*on_buffer_write)(void*) = nullptr; + void* on_buffer_write_context = nullptr; // The buffer and offset a console VA range starts in (from ResourceBinding::va), false when none does. `size` is // cut to what the buffer holds from there: vertex and index views use what fits, WriteBufferImmediate needs all // of it. @@ -1461,6 +1481,73 @@ struct Prepared { XdxrBlasTable xdxr_blases; // an XDXR TLAS build: how its instances' BLAS addresses are translated VkAccelerationStructureKHR accel_src = VK_NULL_HANDLE; std::uint32_t khr_postbuild = ~0u; // index into PreparedList::khr_postbuilds; ~0u: skipped or XDXR + bool draw_only = false; // true when only draw / indirect_clamp / statistics_{begin,end} were populated + + // Back to a fresh Prepared state while keeping the vectors' heap capacities for reused PreparedLists. + void reset() { + if (draw_only) { + statistics_end = PreparedQuery::no_segment; + statistics_begin = PreparedQuery::no_segment; + indirect_clamp = {}; + draw = 0; + draw_only = false; + return; + } + statistics_end = PreparedQuery::no_segment; + statistics_begin = PreparedQuery::no_segment; + predicate = {}; + if (!predicated_copy.empty()) predicated_copy.clear(); + counted_dispatch = {}; + indirect_clamp = {}; + binding = {}; + range = {}; + view = VK_NULL_HANDLE; + clear_format = VK_FORMAT_UNDEFINED; + if (!rects.empty()) rects.clear(); + skip = false; + source = {}; + source_range = {}; + if (!buffer_copies.empty()) buffer_copies.clear(); + if (!buffer_image_copies.empty()) buffer_image_copies.clear(); + tile_scratch = VK_NULL_HANDLE; + if (!tile_rows.empty()) tile_rows.clear(); + if (!image_copies.empty()) image_copies.clear(); + same_copy_subresource = false; + resolve = {}; + resolve_mode = VK_RESOLVE_MODE_NONE; + resolve_view = VK_NULL_HANDLE; + resolve_pass = VK_NULL_HANDLE; + resolve_framebuffer = VK_NULL_HANDLE; + has_depth24 = false; + rgb96_row_words = 0; + rgb96_slice_words = 0; + depth24 = {}; + if (!depth24_parts.empty()) depth24_parts.clear(); + staged = VK_NULL_HANDLE; + if (!staged_reads.empty()) staged_reads.clear(); + if (!staged_writes.empty()) staged_writes.clear(); + clear_pattern_bytes = 0; + if (!discards.empty()) discards.clear(); + write_buffer = VK_NULL_HANDLE; + write_offset = 0; + element = {}; + clear_color = {}; + if (!fills.empty()) fills.clear(); + fill_scratch = VK_NULL_HANDLE; + fill_scratch_offset = 0; + queries = nullptr; + pipeline = {}; + compile = 0; + draw = 0; + depth_uav_copy = UINT32_MAX; + order_depth_uav = false; + accel_dst = VK_NULL_HANDLE; + khr_instances = 0; + xdxr_bytes = 0; + xdxr_blases = {}; + accel_src = VK_NULL_HANDLE; + khr_postbuild = ~0u; + } }; struct DepthUavCopy { @@ -2710,11 +2797,49 @@ inline void copy_depth_uav(const ReplayFunctions& vk, VkCommandBuffer cb, const namespace detail { +// Small stack-resident direct-mapped (image, range, format) -> VkImageView cache for a single prepare() call. +// Avoids repeated views_mutex_ + std::map lookups across consecutive draws targeting the same RT/DSV. +struct PrepareViewCache { + static constexpr std::size_t kSize = 32; + struct Entry { + VkImage image = VK_NULL_HANDLE; + VkImageSubresourceRange range{}; + VkFormat format = VK_FORMAT_UNDEFINED; + VkImageView view = VK_NULL_HANDLE; + }; + std::array entries{}; + + static std::size_t slot_of(VkImage image, const VkImageSubresourceRange& range, VkFormat format) { + std::uint64_t h = 0; + std::memcpy(&h, &image, sizeof(image) < sizeof(h) ? sizeof(image) : sizeof(h)); + h ^= std::uint64_t(format) * 0x9e3779b97f4a7c15ull; + h ^= (std::uint64_t(range.baseMipLevel) << 16) | (std::uint64_t(range.baseArrayLayer) << 32) | + std::uint64_t(range.aspectMask); + h ^= h >> 33; + h *= 0xff51afd7ed558ccdull; + return std::size_t((h >> 33) & (kSize - 1)); + } + + VkImageView get(const ReplayFunctions& vk, const ResourceBinding& viewed, const VkImageSubresourceRange& range) { + const std::size_t idx = slot_of(viewed.image, range, viewed.format); + Entry& e = entries[idx]; + if (e.view && e.image == viewed.image && e.format == viewed.format && + e.range.aspectMask == range.aspectMask && e.range.baseMipLevel == range.baseMipLevel && + e.range.levelCount == range.levelCount && e.range.baseArrayLayer == range.baseArrayLayer && + e.range.layerCount == range.layerCount) { + return e.view; + } + const VkImageView view = vk.image_view(viewed, range); + if (view) e = {viewed.image, range, viewed.format, view}; + return view; + } +}; + // Resolves a draw's pipeline, attachments and buffers. Attachment views take the pipeline's formats, so a // typeless texture is viewed as the format the pipeline renders. template ReplayResult prepare_draw(const Draw& draw, const IndirectDrawArgs* arguments, Resolve&& resolve, - const ReplayFunctions& vk, PreparedDraw& p) { + const ReplayFunctions& vk, PreparedDraw& p, PrepareViewCache* view_cache = nullptr) { if (arguments) { const IndirectDrawArgs& arg = *arguments; const VkDeviceSize record_size = draw.mesh ? sizeof(VkDrawMeshTasksIndirectCommandEXT) @@ -2818,7 +2943,7 @@ ReplayResult prepare_draw(const Draw& draw, const IndirectDrawArgs* arguments, R if (!view_range(a.binding, target, VK_IMAGE_ASPECT_COLOR_BIT, a.range)) return ReplayResult::invalid_subresource; ResourceBinding viewed = a.binding; if (pipeline->color_formats[slot] != VK_FORMAT_UNDEFINED) viewed.format = pipeline->color_formats[slot]; - a.view = vk.image_view(viewed, a.range); + a.view = view_cache ? view_cache->get(vk, viewed, a.range) : vk.image_view(viewed, a.range); if (!a.view) return unsupported_at(__LINE__); shrink(a.binding, target, a.range); } @@ -2833,7 +2958,7 @@ ReplayResult prepare_draw(const Draw& draw, const IndirectDrawArgs* arguments, R if (!view_range(a.binding, draw.depth, a.binding.aspects, a.range)) return ReplayResult::invalid_subresource; ResourceBinding viewed = a.binding; viewed.format = pipeline->depth_format; - a.view = vk.image_view(viewed, a.range); + a.view = view_cache ? view_cache->get(vk, viewed, a.range) : vk.image_view(viewed, a.range); if (!a.view) return unsupported_at(__LINE__); shrink(a.binding, draw.depth, a.range); } @@ -3024,16 +3149,20 @@ inline VkPrimitiveTopology vulkan_topology(std::uint32_t topology) { } // Moves an attachment's tracked pieces to `layout` before rendering (first use zero-fills, as everywhere). +// Pieces already in `layout` accumulate into pending_{access,stages} so a multi-attachment scope open emits at most +// one combined memory barrier across all attachments instead of one per attachment. inline void to_attachment(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const PreparedDraw::Attachment& a, VkImageLayout layout, VkAccessFlags access, VkPipelineStageFlags stages, - LayoutTracker* tracker, bool separate) { + LayoutTracker* tracker, bool separate, VkAccessFlags& pending_access, + VkPipelineStageFlags& pending_stages) { const VkImageSubresourceRange range = planes_for_layout(a.binding, a.range, separate); auto pieces = current(tracker, a.id, range, layout); initialize(vk, command_buffer, a.binding, a.id, pieces, layout, tracker); for (const auto& piece : pieces) { if (piece.layout == layout) { // Attachment writes of an earlier rendering scope are not ordered with this one without a barrier. - memory_barrier(vk, command_buffer, access, stages, access, stages); + pending_access |= access; + pending_stages |= stages; continue; } image_barrier(vk, command_buffer, a.binding, piece.range, piece.layout, layout, @@ -3042,6 +3171,63 @@ inline void to_attachment(const ReplayFunctions& vk, VkCommandBuffer command_buf if (tracker) tracker->set(a.id, range, layout); } +inline void to_attachment(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const PreparedDraw::Attachment& a, + VkImageLayout layout, VkAccessFlags access, VkPipelineStageFlags stages, + LayoutTracker* tracker, bool separate) { + VkAccessFlags pending_access = 0; + VkPipelineStageFlags pending_stages = 0; + to_attachment(vk, command_buffer, a, layout, access, stages, tracker, separate, pending_access, pending_stages); + if (pending_stages) memory_barrier(vk, command_buffer, pending_access, pending_stages, pending_access, pending_stages); +} + +// Tracks the currently open vkCmdBeginRendering..vkCmdEndRendering scope in emit_commands() so consecutive draws +// sharing identical attachments, layouts, depth/stencil aspects, renderArea, and layerCount merge into one scope. +struct RenderingScope { + struct AttachmentKey { + ResourceId id = 0; + VkImageView view = VK_NULL_HANDLE; + VkImageSubresourceRange range{}; + VkImageLayout layout = VK_IMAGE_LAYOUT_UNDEFINED; + + bool operator==(const AttachmentKey& o) const { + return id == o.id && view == o.view && layout == o.layout && + range.aspectMask == o.range.aspectMask && + range.baseMipLevel == o.range.baseMipLevel && + range.levelCount == o.range.levelCount && + range.baseArrayLayer == o.range.baseArrayLayer && + range.layerCount == o.range.layerCount; + } + }; + + bool active = false; + std::uint32_t color_count = 0; + std::array colors{}; + AttachmentKey depth{}; + VkImageAspectFlags depth_aspects = 0; + VkExtent2D area{}; + std::uint32_t layers = 0; + + bool matches(const PreparedDraw& d, const GraphicsPipeline& graphics, + const std::array& color_layouts, + VkImageLayout depth_layout) const { + if (!active) return false; + if (color_count != d.colors.size() || area.width != d.area.width || area.height != d.area.height || + layers != d.layers) + return false; + const VkImageAspectFlags d_aspects = + d.depth.id ? (graphics.depth_aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) : 0; + if (depth_aspects != d_aspects || depth.id != d.depth.id) return false; + if (d.depth.id && !(depth == AttachmentKey{d.depth.id, d.depth.view, d.depth.range, depth_layout})) + return false; + for (std::size_t slot = 0; slot < color_count; ++slot) { + const auto& a = d.colors[slot]; + if (colors[slot].id != a.id) return false; + if (a.id && !(colors[slot] == AttachmentKey{a.id, a.view, a.range, color_layouts[slot]})) return false; + } + return true; + } +}; + } // namespace detail // Destination and source of a copy or resolve command. @@ -3102,6 +3288,8 @@ class PreparedList { // Set when any command writes to a host_readable (READBACK) buffer so VulkanQueue only flushes to HOST_BIT when needed. bool wrote_readback = false; VkPipelineStageFlags2 readback_src_stages = 0; + // Set when any prepared draw or dispatch uses a pipeline with `writes_buffer == true` (or legacy untyped indirect). + bool wrote_buffer = false; std::vector khr_postbuilds; }; @@ -3152,6 +3340,69 @@ inline ReplayResult build_pipelines_serial(PipelineCompiles& compiles, std::span return finish_compiled_pipelines(compiles, lists, result, prior); } +// Computes the GraphicsPipeline::variant() flags for a Draw command without resolving resources or image views: +// bit i is set when the PSO declares a color format for slot i and the draw leaves slot i unbound, unbound_depth +// when the PSO declares a depth format and the draw leaves depth unbound, and rectangle_stage when the draw uses +// the PSO's rectangle-list topology. +inline std::uint32_t draw_unbound_mask(const GraphicsPipeline& pipeline, const Draw& draw) noexcept { + std::uint32_t unbound = 0; + if (pipeline.rectangle_variant_topology && draw.topology == pipeline.rectangle_variant_topology) + unbound |= GraphicsPipeline::rectangle_stage; + const std::uint32_t render_target_count = draw.views ? draw.views->render_target_count : 0; + const std::size_t color_count = pipeline.color_formats.size(); + for (std::size_t slot = 0; slot < color_count; ++slot) { + if (pipeline.color_formats[slot] == VK_FORMAT_UNDEFINED) continue; + const bool bound = slot < render_target_count && draw.views->render_targets[slot].resource != 0; + if (!bound) unbound |= 1u << slot; + } + if (pipeline.depth_format != VK_FORMAT_UNDEFINED && !draw.depth.resource) + unbound |= GraphicsPipeline::unbound_depth; + return unbound; +} + +// Fast pre-pass over a batch of command lists that collects every unique unbuilt synchronous graphics (pipeline, +// unbound_mask) and compute pipeline into `compiles` BEFORE prepare() acquires resource/tracker locks or allocates +// transient replay state. Pipelines configured for async_build, skipped compute pipelines, or indirect draws that +// prepare_draw() skips (nonunit vertex divisor / indirect rectangle-list variant) are omitted. +inline void collect_unbuilt_pipelines(std::span lists, const ReplayFunctions& vk, + PipelineCompiles& compiles) { + for (const CommandList* list : lists) { + if (!list) continue; + for (const Command& command : list->commands()) { + if (const auto draw = draw_command(command); draw.state) { + if (!vk.graphics_pipeline) continue; + const GraphicsPipeline* pipeline = vk.graphics_pipeline(draw.state->pipeline); + if (!pipeline || pipeline->async_build || !pipeline->variant || !pipeline->built) continue; + if (pipeline->mesh != draw.state->mesh) continue; + if (pipeline->color_formats.size() > detail::max_render_targets) continue; + if (draw.arguments && pipeline->nonunit_vertex_divisor) continue; + const std::uint32_t unbound = draw_unbound_mask(*pipeline, *draw.state); + if (!unbound && pipeline->pipeline) continue; + if (draw.arguments && (unbound & GraphicsPipeline::rectangle_stage)) continue; + if (!pipeline->built(unbound)) compiles.add(*pipeline, unbound); + } else if (const auto* dispatch = std::get_if(&command)) { + if (!vk.compute_pipeline) continue; + const ComputePipeline* pipeline = vk.compute_pipeline(dispatch->pipeline); + if (!pipeline || pipeline->pipeline || !pipeline->build || !pipeline->built || + pipeline->async_build || pipeline->skipped) + continue; + if (pipeline->bindless_set && !vk.bind_descriptor_sets) continue; + if (!pipeline->built(pipeline->build_context)) + compiles.add(*pipeline, PipelineCompiles::User::dispatch); + } else if (const auto* indirect = std::get_if(&command)) { + if (indirect->kind != IndirectKind::dispatch || !indirect->max_count || !vk.compute_pipeline) continue; + const ComputePipeline* pipeline = vk.compute_pipeline(indirect->pipeline); + if (!pipeline || pipeline->pipeline || !pipeline->build || !pipeline->built || + pipeline->async_build || pipeline->skipped) + continue; + if (pipeline->bindless_set && !vk.bind_descriptor_sets) continue; + if (!pipeline->built(pipeline->build_context)) + compiles.add(*pipeline, PipelineCompiles::User::indirect_dispatch); + } + } + } +} + inline ReplayResult plan_occlusion_segments(PreparedList& out) { // Active logical queries cover a contiguous range of physical slots. A Begin or End closes the old // slot and opens a new one if any query remains active. Each shared interval is recorded only once. @@ -3442,7 +3693,8 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (list.queries_open()) return ReplayResult::invalid_query; // a Vulkan query must end in its command buffer const auto commands = list.commands(); out.list = &list; - out.commands.assign(commands.size(), {}); + const std::size_t prev_commands = out.commands.size(); + out.commands.resize(commands.size()); out.draw_count = 0; out.depth_uav_copies.clear(); out.queries.clear(); @@ -3481,6 +3733,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun std::uint32_t so_active = 0; out.wrote_readback = false; out.readback_src_stages = 0; + out.wrote_buffer = false; // Successive plane transfers use the same transient range and order their buffer accesses in emit(). VkBuffer plane_scratch = VK_NULL_HANDLE; @@ -3555,9 +3808,11 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun return ReplayResult::success; }; + detail::PrepareViewCache view_cache; for (std::size_t i = 0; i < commands.size(); ++i) { const auto& command = commands[i]; auto& p = out.commands[i]; + if (i < prev_commands) p.reset(); const auto bind = [&](ResourceId id) { const ResourceBinding* binding = resolve(id); if (binding) p.binding = *binding; @@ -3580,7 +3835,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun } ResourceBinding view_binding = p.binding; if (p.clear_format != VK_FORMAT_UNDEFINED) view_binding.format = p.clear_format; - p.view = vk.image_view(view_binding, range); + p.view = view_cache.get(vk, view_binding, range); return p.view ? ReplayResult::success : ReplayResult::unsupported; }; @@ -4160,6 +4415,11 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun // Legacy graphics IR carries no graphics state of its own: the recorded, stateful graphics indirects are // Draw commands (IndirectRasterDraw) and open their own rendering scope. A legacy one is emitted as it is // - the clamp pass above is what keeps its arguments safe - and its dispatch-side work ends here. + if (ind->kind != IndirectKind::dispatch) { + if (ind->max_count) out.wrote_buffer = true; + } else if (!ind->pipeline) { + if (ind->max_count) out.wrote_buffer = true; + } if (ind->kind == IndirectKind::dispatch && ind->pipeline) { // the pipeline and root arguments it was recorded if (!vk.bind_pipeline || !vk.push_constants || !vk.compute_pipeline) return unsupported_at(__LINE__); const ComputePipeline* pipeline = vk.compute_pipeline(ind->pipeline); @@ -4170,6 +4430,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (!found && p.pipeline.async_build && !strict_replay()) continue; if (!found) return unresolved_at(__LINE__); if (pipeline->bindless_set && !vk.bind_descriptor_sets) return unsupported_at(__LINE__); + if (ind->max_count && p.pipeline.writes_buffer) out.wrote_buffer = true; } } else if (const auto* build = std::get_if(&command)) { p.khr_instances = 0; @@ -4295,21 +4556,26 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun continue; } if (pipeline->bindless_set && !vk.bind_descriptor_sets) return unsupported_at(__LINE__); + if (p.pipeline.writes_buffer) out.wrote_buffer = true; } else if (const auto draw = draw_command(command); draw.state) { if (out.draw_count == out.draws.size()) out.draws.emplace_back(); auto& prepared_draw = out.draws[out.draw_count]; prepared_draw.reset(); p.draw = std::uint32_t(out.draw_count++); - if (const auto r = detail::prepare_draw(*draw.state, draw.arguments, resolve, vk, prepared_draw); + if (const auto r = detail::prepare_draw(*draw.state, draw.arguments, resolve, vk, prepared_draw, &view_cache); r != ReplayResult::success) { const bool strict = strict_replay(); if (r != ReplayResult::unresolved_resource || strict) return r; prepared_draw.skipped = true; // dropped at emit (see the dispatch branch above) - } else if (draw.state->indexed && !draw.state->mesh && draw.state->topology == topology_quad_list) { - // The index expansion is a helper dispatch: inside a statistics query it needs the segment pool. - if (statistics_active && !statistics_helpers && draw.state->count >= 4) return ReplayResult::unsupported; - if (const auto r = detail::prepare_quad_indices(*draw.state, vk, prepared_draw); r != ReplayResult::success) - return r; + } else { + if (!prepared_draw.skipped && prepared_draw.graphics && prepared_draw.graphics->writes_buffer) + out.wrote_buffer = true; + if (draw.state->indexed && !draw.state->mesh && draw.state->topology == topology_quad_list) { + // The index expansion is a helper dispatch: inside a statistics query it needs the segment pool. + if (statistics_active && !statistics_helpers && draw.state->count >= 4) return ReplayResult::unsupported; + if (const auto r = detail::prepare_quad_indices(*draw.state, vk, prepared_draw); r != ReplayResult::success) + return r; + } } // A stateful indirect draw takes the same clamp pass (vulkan_indirect_clamp.h) as a legacy ExecuteIndirect: // the arguments it reads are copied and bounded on the GPU before its rendering scope opens, and the draw @@ -4355,6 +4621,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun return unsupported_at(__LINE__); } } + p.draw_only = true; } } if (ordinary_active || binary_active) return ReplayResult::invalid_query; @@ -4546,8 +4813,305 @@ inline void begin_statistics_segment(const PreparedList& list, std::uint32_t seg } // namespace detail +// Per-VkCommandBuffer Vulkan state shadow cache used across emit_commands() (and across multiple PreparedLists +// recorded into one VkCommandBuffer by VulkanQueue::execute_now). Zero heap allocations; every helper pass that +// touches Vulkan pipeline/descriptor/push-constant state calls invalidate_compute() so cached state never goes stale. +struct ReplayStateCache { + static constexpr std::size_t kPushWords = sizeof(ShaderUserData) / sizeof(std::uint32_t); + static constexpr std::size_t kMaxVertexSlots = 32; + static_assert(sizeof(ShaderUserData) == kPushWords * sizeof(std::uint32_t)); + + enum class ViewportMode : std::uint8_t { none, fixed, with_count }; + + // Pipelines (independent per Vulkan bind point). + bool graphics_pipeline_valid = false; + VkPipeline graphics_pipeline = VK_NULL_HANDLE; + bool graphics_viewport_with_count = false; + + bool compute_pipeline_valid = false; + VkPipeline compute_pipeline = VK_NULL_HANDLE; + + // Bindless set 0 (independent per Vulkan bind point, keyed on exact layout + set handle). + bool graphics_desc_valid = false; + VkPipelineLayout graphics_desc_layout = VK_NULL_HANDLE; + VkDescriptorSet graphics_desc_set = VK_NULL_HANDLE; + + bool compute_desc_valid = false; + VkPipelineLayout compute_desc_layout = VK_NULL_HANDLE; + VkDescriptorSet compute_desc_set = VK_NULL_HANDLE; + + // Shared command-buffer push-constant bank: Vulkan push constants are shared across bind points and only stay + // defined across identical (layout, stageFlags) push ranges, so switching graphics <-> compute or layout forces + // a full 144-byte push while repeated pushes with the same (layout, stages) push only the dirty [lo, hi] words. + bool push_valid = false; + VkPipelineLayout push_layout = VK_NULL_HANDLE; + VkShaderStageFlags push_stages = 0; + std::array push_words{}; + + // Dynamic graphics state. + ViewportMode viewport_mode = ViewportMode::none; + std::uint32_t viewport_count = 0; + std::array viewports{}; + + ViewportMode scissor_mode = ViewportMode::none; + std::uint32_t scissor_count = 0; + std::array scissors{}; + + bool topology_valid = false; + VkPrimitiveTopology topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; + + bool primitive_restart_valid = false; + VkBool32 primitive_restart = VK_FALSE; + + bool stencil_front_valid = false; + std::uint32_t stencil_front = 0; + + bool stencil_back_valid = false; + std::uint32_t stencil_back = 0; + + bool blend_valid = false; + std::array blend_constants{}; + + bool depth_bounds_valid = false; + float depth_bounds_lo = 0.0f; + float depth_bounds_hi = 1.0f; + + // Vertex buffer bindings (up to 32 D3D12 IA slots). + std::uint32_t vertex_valid_mask = 0; + struct VertexSlot { + VkBuffer buffer = VK_NULL_HANDLE; + VkDeviceSize offset = 0; + VkDeviceSize size = 0; + VkDeviceSize stride = 0; + }; + std::array vertex_slots{}; + + // Index buffer binding (covers both vkCmdBindIndexBuffer and vkCmdBindIndexBuffer2KHR). + bool index_valid = false; + bool index_robust = false; + VkBuffer index_buffer = VK_NULL_HANDLE; + VkDeviceSize index_offset = 0; + VkDeviceSize index_size = 0; + VkIndexType index_type = VK_INDEX_TYPE_UINT16; + + // Called after any internal compute helper pass (occlusion/statistics resolve, depth24, quad index expansion, + // predicate capture, predicated copy, indirect clamp, counted dispatch, XDXR build/copy/postbuild). + // Compute helpers only touch compute pipeline/descriptors and the shared push-constant bank; graphics pipeline, + // graphics descriptors, vertex/index buffers, and dynamic graphics state persist across compute dispatches. + void invalidate_compute() noexcept { + compute_pipeline_valid = false; + compute_desc_valid = false; + push_valid = false; + } + + void reset() noexcept { *this = ReplayStateCache{}; } + + void bind_graphics_pipeline(VkCommandBuffer cb, const ReplayFunctions& vk, VkPipeline pipeline, + const GraphicsPipeline& graphics, bool is_mesh) { + if (graphics_pipeline_valid && graphics_pipeline == pipeline) return; + vk.bind_pipeline(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); + // Per Vulkan spec, binding a pipeline disturbs any dynamic state it does not declare dynamically. + if (graphics_pipeline_valid && graphics.viewport_with_count != graphics_viewport_with_count) { + viewport_mode = ViewportMode::none; + scissor_mode = ViewportMode::none; + } + if (is_mesh) { + topology_valid = false; + primitive_restart_valid = false; + vertex_valid_mask = 0; + } else if (!graphics.vertex_slots) { + vertex_valid_mask = 0; + } + if (!graphics.depth_bounds) depth_bounds_valid = false; + graphics_pipeline_valid = true; + graphics_pipeline = pipeline; + graphics_viewport_with_count = graphics.viewport_with_count; + } + + void bind_compute_pipeline(VkCommandBuffer cb, const ReplayFunctions& vk, VkPipeline pipeline) { + if (compute_pipeline_valid && compute_pipeline == pipeline) return; + vk.bind_pipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline); + compute_pipeline_valid = true; + compute_pipeline = pipeline; + } + + void bind_graphics_set0(VkCommandBuffer cb, const ReplayFunctions& vk, VkPipelineLayout layout, + VkDescriptorSet set0) { + if (graphics_desc_valid && graphics_desc_layout == layout && graphics_desc_set == set0) return; + vk.bind_descriptor_sets(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, layout, 0, 1, &set0, 0, nullptr); + graphics_desc_valid = true; + graphics_desc_layout = layout; + graphics_desc_set = set0; + } + + void bind_compute_set0(VkCommandBuffer cb, const ReplayFunctions& vk, VkPipelineLayout layout, + VkDescriptorSet set0) { + if (compute_desc_valid && compute_desc_layout == layout && compute_desc_set == set0) return; + vk.bind_descriptor_sets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, layout, 0, 1, &set0, 0, nullptr); + compute_desc_valid = true; + compute_desc_layout = layout; + compute_desc_set = set0; + } + + void push_user_data(VkCommandBuffer cb, const ReplayFunctions& vk, VkPipelineLayout layout, + VkShaderStageFlags stages, const std::array& user_data, + std::uint64_t heap_base, std::uint64_t code_base) { + alignas(std::uint64_t) std::uint32_t next[kPushWords]; + std::memcpy(next, user_data.data(), 32 * sizeof(std::uint32_t)); + std::memcpy(next + 32, &heap_base, sizeof(std::uint64_t)); + std::memcpy(next + 34, &code_base, sizeof(std::uint64_t)); + if (!push_valid || push_layout != layout || push_stages != stages) { + vk.push_constants(cb, layout, stages, 0, sizeof(ShaderUserData), next); + std::memcpy(push_words.data(), next, sizeof(ShaderUserData)); + push_layout = layout; + push_stages = stages; + push_valid = true; + return; + } + std::size_t lo = 0; + while (lo < kPushWords && next[lo] == push_words[lo]) ++lo; + if (lo == kPushWords) return; // completely unchanged + std::size_t hi = kPushWords - 1; + while (hi > lo && next[hi] == push_words[hi]) --hi; + const std::uint32_t count = static_cast(hi - lo + 1); + vk.push_constants(cb, layout, stages, static_cast(lo * sizeof(std::uint32_t)), + count * static_cast(sizeof(std::uint32_t)), next + lo); + std::memcpy(push_words.data() + lo, next + lo, count * sizeof(std::uint32_t)); + } + + void set_viewport_fixed(VkCommandBuffer cb, const ReplayFunctions& vk, const VkViewport& vp) { + if (viewport_mode == ViewportMode::fixed && viewport_count == 1 && + std::memcmp(&viewports[0], &vp, sizeof(VkViewport)) == 0) + return; + vk.set_viewport(cb, 0, 1, &vp); + viewport_mode = ViewportMode::fixed; + viewport_count = 1; + viewports[0] = vp; + } + + void set_scissor_fixed(VkCommandBuffer cb, const ReplayFunctions& vk, const VkRect2D& sc) { + if (scissor_mode == ViewportMode::fixed && scissor_count == 1 && + std::memcmp(&scissors[0], &sc, sizeof(VkRect2D)) == 0) + return; + vk.set_scissor(cb, 0, 1, &sc); + scissor_mode = ViewportMode::fixed; + scissor_count = 1; + scissors[0] = sc; + } + + void set_viewports_with_count(VkCommandBuffer cb, const ReplayFunctions& vk, std::uint32_t count, + const VkViewport* vps) { + if (viewport_mode == ViewportMode::with_count && viewport_count == count && + std::memcmp(viewports.data(), vps, count * sizeof(VkViewport)) == 0) + return; + vk.set_viewport_with_count(cb, count, vps); + viewport_mode = ViewportMode::with_count; + viewport_count = count; + std::memcpy(viewports.data(), vps, count * sizeof(VkViewport)); + } + + void set_scissors_with_count(VkCommandBuffer cb, const ReplayFunctions& vk, std::uint32_t count, + const VkRect2D* scs) { + if (scissor_mode == ViewportMode::with_count && scissor_count == count && + std::memcmp(scissors.data(), scs, count * sizeof(VkRect2D)) == 0) + return; + vk.set_scissor_with_count(cb, count, scs); + scissor_mode = ViewportMode::with_count; + scissor_count = count; + std::memcpy(scissors.data(), scs, count * sizeof(VkRect2D)); + } + + void set_primitive_topology(VkCommandBuffer cb, const ReplayFunctions& vk, VkPrimitiveTopology value) { + if (topology_valid && topology == value) return; + vk.set_primitive_topology(cb, value); + topology_valid = true; + topology = value; + } + + void set_primitive_restart(VkCommandBuffer cb, const ReplayFunctions& vk, VkBool32 value) { + if (primitive_restart_valid && primitive_restart == value) return; + vk.set_primitive_restart_enable(cb, value); + primitive_restart_valid = true; + primitive_restart = value; + } + + void set_stencil_reference(VkCommandBuffer cb, const ReplayFunctions& vk, std::uint32_t front, std::uint32_t back) { + if (!stencil_front_valid || stencil_front != front) { + vk.set_stencil_reference(cb, VK_STENCIL_FACE_FRONT_BIT, front); + stencil_front_valid = true; + stencil_front = front; + } + if (!stencil_back_valid || stencil_back != back) { + vk.set_stencil_reference(cb, VK_STENCIL_FACE_BACK_BIT, back); + stencil_back_valid = true; + stencil_back = back; + } + } + + void set_blend_constants(VkCommandBuffer cb, const ReplayFunctions& vk, const std::array& blend) { + if (blend_valid && std::memcmp(blend_constants.data(), blend.data(), sizeof(blend_constants)) == 0) return; + vk.set_blend_constants(cb, blend.data()); + blend_valid = true; + blend_constants = blend; + } + + void set_depth_bounds(VkCommandBuffer cb, const ReplayFunctions& vk, float lo, float hi) { + if (depth_bounds_valid && std::memcmp(&depth_bounds_lo, &lo, sizeof(float)) == 0 && + std::memcmp(&depth_bounds_hi, &hi, sizeof(float)) == 0) + return; + vk.set_depth_bounds(cb, lo, hi); + depth_bounds_valid = true; + depth_bounds_lo = lo; + depth_bounds_hi = hi; + } + + void bind_vertex_buffer(VkCommandBuffer cb, const ReplayFunctions& vk, std::uint32_t slot, VkBuffer buffer, + VkDeviceSize offset, VkDeviceSize size, VkDeviceSize stride) { + if (slot < kMaxVertexSlots) { + const std::uint32_t bit = 1u << slot; + const VertexSlot& cur = vertex_slots[slot]; + if ((vertex_valid_mask & bit) && cur.buffer == buffer && cur.offset == offset && cur.size == size && + cur.stride == stride) + return; + vk.bind_vertex_buffers2(cb, slot, 1, &buffer, &offset, &size, &stride); + vertex_valid_mask |= bit; + vertex_slots[slot] = {buffer, offset, size, stride}; + return; + } + vk.bind_vertex_buffers2(cb, slot, 1, &buffer, &offset, &size, &stride); + } + + void bind_index_buffer(VkCommandBuffer cb, const ReplayFunctions& vk, VkBuffer buffer, VkDeviceSize offset, + VkIndexType type) { + if (index_valid && !index_robust && index_buffer == buffer && index_offset == offset && index_type == type) + return; + vk.bind_index_buffer(cb, buffer, offset, type); + index_valid = true; + index_robust = false; + index_buffer = buffer; + index_offset = offset; + index_size = 0; + index_type = type; + } + + void bind_robust_index_buffer(VkCommandBuffer cb, const ReplayFunctions& vk, VkBuffer buffer, VkDeviceSize offset, + VkDeviceSize size, VkIndexType type) { + if (index_valid && index_robust && index_buffer == buffer && index_offset == offset && index_size == size && + index_type == type) + return; + vk.bind_robust_index_view(cb, buffer, offset, size, type); + index_valid = true; + index_robust = true; + index_buffer = buffer; + index_offset = offset; + index_size = size; + index_type = type; + } +}; + inline void emit_query(const PreparedList& list, const detail::PreparedQuery& query, VkCommandBuffer cb, - const ReplayFunctions& vk, const VkConditionalRenderingBeginInfoEXT& predicate) { + const ReplayFunctions& vk, const VkConditionalRenderingBeginInfoEXT& predicate, + ReplayStateCache* state_cache = nullptr) { constexpr auto none = detail::PreparedQuery::no_segment; if (query.end_segment != none || query.begin_segment != none) { if (query.end_segment != none) vk.end_query(cb, list.segment_pool, list.segment_base + query.end_segment); @@ -4621,11 +5185,14 @@ inline void emit_query(const PreparedList& list, const detail::PreparedQuery& qu } else if (run.sum && resolve.type == d3d12_query::pipeline_statistics) { vk.sum_statistics(cb, run.pool, run.mesh_pool, run.primitives_pool, run.mesh, run.first, run.count, dst, run.offset); + if (state_cache) state_cache->invalidate_compute(); } else if (run.sum && binary) { vk.sum_binary_occlusion(cb, run.pool, run.first, run.count, dst, run.offset); + if (state_cache) state_cache->invalidate_compute(); } else if (run.sum || binary) { const auto& resolve_occlusion = run.sum ? vk.sum_occlusion : vk.resolve_binary_occlusion; resolve_occlusion(cb, run.pool, run.first, run.count, dst, run.offset); + if (state_cache) state_cache->invalidate_compute(); } else { vk.copy_query_pool_results(cb, run.pool, run.first, run.count, dst, run.offset, size, VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); @@ -4642,13 +5209,25 @@ inline void close_labels(VkCommandBuffer command_buffer, const ReplayFunctions& open_labels = 0; } +// Reusable scratch vectors for emit_commands(), hoisted onto VulkanQueue so steady-state submissions avoid per-list +// heap allocations for multi-piece image barriers, depth24 copy regions, and acceleration-structure build arrays. +struct EmitScratch { + std::vector many_barriers; + std::vector converted_copies; + std::vector as_geoms; + std::vector as_ranges; +}; + // Writes a prepared list. With a tracker, barriers start from the tracked layouts and update them. // `open_labels` counts the debug labels begun and not yet ended in this command buffer: an EndEvent with none open // is dropped (Vulkan requires a matching begin), and the caller ends what is still open before it ends the buffer // (close_labels). Without it, the list's own events are balanced at its end. template inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_buffer, const ReplayFunctions& vk, - LayoutTracker* tracker, std::uint32_t* open_labels, const CheckpointRecorder* checkpoints) { + LayoutTracker* tracker, std::uint32_t* open_labels, const CheckpointRecorder* checkpoints, + ReplayStateCache* state_cache = nullptr, EmitScratch* emit_scratch = nullptr) { + ReplayStateCache own_state; + ReplayStateCache& cache = state_cache ? *state_cache : own_state; std::uint32_t own_labels = 0; std::uint32_t& labels = open_labels ? *open_labels : own_labels; const auto commands = prepared.list->commands(); @@ -4658,11 +5237,19 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ const bool predicates = vk.begin_conditional_rendering != nullptr; VkConditionalRenderingBeginInfoEXT predicate{VK_STRUCTURE_TYPE_CONDITIONAL_RENDERING_BEGIN_INFO_EXT}; std::size_t next_query = 0; + // Reusable scratch vectors hoisted out of the command loop (and onto VulkanQueue when `emit_scratch` is given). + EmitScratch own_scratch; + EmitScratch& scratch = emit_scratch ? *emit_scratch : own_scratch; + auto& many_barriers = scratch.many_barriers; + auto& converted_copies = scratch.converted_copies; + auto& as_geoms = scratch.as_geoms; + auto& as_ranges = scratch.as_ranges; // A dispatch honours conditional rendering and a copy does not (the layer runs copies unpredicated), so the // conversion around a copy must run whatever the predicate says: end it for the dispatch and begin it again. const auto run_depth24 = [&](const Depth24Job& job) { if (predicate.buffer) vk.end_conditional_rendering(command_buffer); vk.depth24_run(command_buffer, job); + cache.invalidate_compute(); if (predicate.buffer) vk.begin_conditional_rendering(command_buffer, &predicate); }; const auto finish_depth_uav_barrier = [&](const detail::Prepared& p, VkImageLayout layout, @@ -4677,15 +5264,109 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ } }; + detail::RenderingScope scope{}; + gpu_profile::Kind scope_profile_kind = gpu_profile::Kind::graphics; + std::uintptr_t scope_profile_id = 0; + const auto end_scope = [&] { + if (!scope.active) return; + vk.end_rendering(command_buffer); + scope.active = false; + }; + for (std::size_t i = 0; i < commands.size(); ++i) { const auto& command = commands[i]; const auto& p = prepared.commands[i]; const auto raster = draw_command(command); + bool reuse_scope = false; + std::array color_layouts{}; + VkImageLayout depth_layout = VK_IMAGE_LAYOUT_UNDEFINED; + if (raster.state) { + const detail::PreparedDraw& d = prepared.draws[p.draw]; + const bool has_stats_split = p.statistics_end != detail::PreparedQuery::no_segment || + p.statistics_begin != detail::PreparedQuery::no_segment; + const bool has_quad_expand = !p.indirect_clamp.buffer && !p.counted_dispatch.indirect && + d.quad_indices.buffer != VK_NULL_HANDLE; + if (!d.skipped) { + for (std::size_t slot = 0; slot < d.colors.size(); ++slot) + if (d.colors[slot].id) + color_layouts[slot] = + image_layout(d.colors[slot].binding, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); + if (d.depth.id) + depth_layout = image_layout(d.depth.binding, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); + const bool has_indirect_clamp = p.indirect_clamp.buffer != VK_NULL_HANDLE; + const bool has_glc_barrier = d.pipeline && d.graphics->reads_glc_buffer && vk.pipeline_barrier; + const bool profile_split = + vk.gpu_profile && + ((raster.state->mesh ? gpu_profile::Kind::mesh : gpu_profile::Kind::graphics) != + scope_profile_kind || + raster.state->pipeline != scope_profile_id); + if (scope.active && !has_stats_split && !has_quad_expand && !has_indirect_clamp && + !has_glc_barrier && !profile_split && + scope.matches(d, *d.graphics, color_layouts, depth_layout)) { + reuse_scope = true; + } else { + end_scope(); + } + } else if (has_stats_split || has_quad_expand) { + end_scope(); + } + } else { + const bool noop_debug_marker = + !vk.gpu_profile && std::holds_alternative(command) && + (!vk.insert_label || !vk.begin_label || !vk.end_label); + if (!noop_debug_marker) end_scope(); + } + // LEONIDA_GPU_PROFILE=1: before anything of the command is recorded, so that the helper passes of a draw or + // dispatch (index expansion, indirect clamp, counted dispatch) count for it. A command that records no draw + // or dispatch here (dropped, skipped, still compiling) neither starts nor ends a run. + if (vk.gpu_profile) { + auto& profile = *vk.gpu_profile; + if (const auto* dispatch = std::get_if(&command)) { + if (p.pipeline.pipeline) profile.work(command_buffer, gpu_profile::Kind::compute, dispatch->pipeline); + } else if (const auto* indirect = std::get_if(&command)) { + if (indirect->kind == IndirectKind::dispatch) { + if (!indirect->pipeline || p.pipeline.pipeline || !(p.pipeline.async_build || p.pipeline.skipped)) + profile.work(command_buffer, gpu_profile::Kind::compute, indirect->pipeline); + } else if (vk.external_graphics_scope) { + profile.work(command_buffer, gpu_profile::Kind::graphics, 0); // the caller's pipeline + } + } else if (raster.state) { + if (!prepared.draws[p.draw].skipped) + profile.work(command_buffer, + raster.state->mesh ? gpu_profile::Kind::mesh : gpu_profile::Kind::graphics, + raster.state->pipeline); + } else { + profile.other(command_buffer); + } + } + // LEONIDA_DEVICE_MARKERS=1 (vulkan_device_markers.h): a draw's started marker, before its helper passes (index + // expansion, indirect clamp) and its rendering scope, so a hang in them is the draw's too; its finished marker + // follows the scope (drawn below). Nothing without the markers. + if constexpr (Checkpoints) { + if (raster.state && !prepared.draws[p.draw].skipped && checkpoints->submission.markers) { + const Draw& s = *raster.state; + const detail::PreparedDraw& pd = prepared.draws[p.draw]; + unsigned flags = (s.indexed ? marked_draw::indexed : 0u) | (s.mesh ? marked_draw::mesh : 0u) | + (!s.mesh && s.topology == topology_quad_list ? marked_draw::quads : 0u); + std::array counts{s.count, s.instances, s.first}; + if (raster.arguments) { + flags |= marked_draw::indirect | (raster.arguments->count_buffer ? marked_draw::counted : 0u); + counts = {raster.arguments->max_count, raster.arguments->stride, 0}; + } + std::array views{}; + const std::size_t slots = std::min(pd.colors.size(), views.size()); + for (std::size_t slot = 0; slot < slots; ++slot) + views[slot] = pd.colors[slot].id ? pd.colors[slot].view : VK_NULL_HANDLE; + checkpoints->draw(command_buffer, i, s.pipeline, static_cast(flags), counts, + MarkedTargets::of(std::span(views.data(), slots), + pd.depth.id ? pd.depth.view : VK_NULL_HANDLE, pd.area)); + } + } if (next_query < prepared.queries.size() && prepared.queries[next_query].command == i) { if constexpr (Checkpoints) if (std::holds_alternative(command)) checkpoints->record(command_buffer, i, CheckpointKind::resolve); - emit_query(prepared, prepared.queries[next_query++], command_buffer, vk, predicate); + emit_query(prepared, prepared.queries[next_query++], command_buffer, vk, predicate, &cache); continue; } // Helpers run outside the per-command rendering scopes; both segment endpoints stay outside too. @@ -4702,10 +5383,284 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ if (!p.indirect_clamp.buffer && !p.counted_dispatch.indirect && (raster.state || std::holds_alternative(command))) { end_statistics(); - if (raster.state && prepared.draws[p.draw].quad_indices.buffer) + if (raster.state && prepared.draws[p.draw].quad_indices.buffer) { vk.emit_quad_indices(command_buffer, prepared.draws[p.draw].quad_indices); + cache.invalidate_compute(); + } begin_statistics(); } + if (raster.state) { + const Draw* draw = raster.state; + const detail::PreparedDraw& d = prepared.draws[p.draw]; + if (d.skipped) continue; // could not be resolved in prepare: dropped + // The clamp pass for a stateful indirect draw (vulkan_indirect_clamp.h) runs before vkCmdBeginRendering, + // because its copy and transfer barrier are not allowed inside a dynamic-rendering scope. It is a helper + // dispatch, so a pipeline-statistics query must not count it, and it runs even under a false predicate. + if (p.indirect_clamp.buffer != VK_NULL_HANDLE) { + end_statistics(); + if (predicate.buffer) vk.end_conditional_rendering(command_buffer); + vk.emit_indirect_clamp(command_buffer, p.indirect_clamp); + cache.invalidate_compute(); + if (predicate.buffer) vk.begin_conditional_rendering(command_buffer, &predicate); + begin_statistics(); + } + if constexpr (Checkpoints) + checkpoints->record(command_buffer, i, CheckpointKind::draw, + d.pipeline, draw->pipeline); + const GraphicsPipeline& graphics = *d.graphics; + if (!reuse_scope) { + constexpr VkAccessFlags color_access = + VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + constexpr VkAccessFlags depth_access = + VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; + constexpr VkPipelineStageFlags depth_stages = + VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; + VkAccessFlags pending_access = 0; + VkPipelineStageFlags pending_stages = 0; + std::array colors; + for (std::size_t slot = 0; slot < d.colors.size(); ++slot) { + colors[slot] = {VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO}; + const auto& a = d.colors[slot]; + if (!a.id) continue; // an unbound slot: no image view, writes are dropped + const VkImageLayout layout = color_layouts[slot]; + detail::to_attachment(vk, command_buffer, a, layout, color_access, + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, tracker, separate, + pending_access, pending_stages); + colors[slot].imageView = a.view; + colors[slot].imageLayout = layout; + colors[slot].loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; + colors[slot].storeOp = VK_ATTACHMENT_STORE_OP_STORE; + } + VkRenderingAttachmentInfo depth{VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO}; + if (d.depth.id) { + const VkImageLayout layout = depth_layout; + detail::to_attachment(vk, command_buffer, d.depth, layout, depth_access, depth_stages, tracker, + separate, pending_access, pending_stages); + depth.imageView = d.depth.view; + depth.imageLayout = layout; + depth.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; + depth.storeOp = VK_ATTACHMENT_STORE_OP_STORE; + } + if (pending_stages) { + detail::memory_barrier(vk, command_buffer, pending_access, pending_stages, pending_access, + pending_stages); + } + VkRenderingInfo rendering{VK_STRUCTURE_TYPE_RENDERING_INFO}; + rendering.renderArea = {{0, 0}, d.area}; + rendering.layerCount = d.layers; // array views: SV_RenderTargetArrayIndex picks the layer + rendering.colorAttachmentCount = std::uint32_t(d.colors.size()); + rendering.pColorAttachments = colors.data(); + if (d.pipeline && graphics.reads_glc_buffer && vk.pipeline_barrier) { + detail::memory_barrier(vk, command_buffer, VK_ACCESS_SHADER_WRITE_BIT, shader_stages, + VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT, + VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT); + } + const VkImageAspectFlags d_aspects = + d.depth.id ? (graphics.depth_aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) + : 0; + if (d_aspects & VK_IMAGE_ASPECT_DEPTH_BIT) rendering.pDepthAttachment = &depth; + if (d_aspects & VK_IMAGE_ASPECT_STENCIL_BIT) rendering.pStencilAttachment = &depth; + vk.begin_rendering(command_buffer, &rendering); + + scope.active = true; + scope.color_count = std::uint32_t(d.colors.size()); + for (std::size_t slot = 0; slot < d.colors.size(); ++slot) { + const auto& a = d.colors[slot]; + scope.colors[slot] = + a.id ? detail::RenderingScope::AttachmentKey{a.id, a.view, a.range, color_layouts[slot]} + : detail::RenderingScope::AttachmentKey{}; + } + scope.depth = + d.depth.id ? detail::RenderingScope::AttachmentKey{d.depth.id, d.depth.view, d.depth.range, + depth_layout} + : detail::RenderingScope::AttachmentKey{}; + scope.depth_aspects = d_aspects; + scope.area = d.area; + scope.layers = d.layers; + if (vk.gpu_profile) { + scope_profile_kind = draw->mesh ? gpu_profile::Kind::mesh : gpu_profile::Kind::graphics; + scope_profile_id = draw->pipeline; + } + } + if (d.pipeline && graphics.writes_buffer && vk.on_buffer_write) + vk.on_buffer_write(vk.on_buffer_write_context); + + cache.bind_graphics_pipeline(command_buffer, vk, d.pipeline, graphics, draw->mesh); + if (graphics.bindless_set) { + const VkDescriptorSet set0 = vk.bindless_set ? vk.bindless_set : graphics.bindless_set; + cache.bind_graphics_set0(command_buffer, vk, graphics.layout, set0); + } + cache.push_user_data(command_buffer, vk, graphics.layout, graphics.push_stages, draw->user_data, + vk.heap_base, graphics.code_base); + // Translated vertex shaders write D3D clip coordinates (y up); a negative-height viewport keeps the + // image upright, and winding as D3D12 sees it. + if (graphics.viewport_with_count) { + std::array vps; + std::array scs; + const std::uint32_t vp_n = draw->viewports ? draw->viewports->viewport_count : 1u; + const std::uint32_t sc_n = draw->viewports ? draw->viewports->scissor_count : 1u; + const std::uint32_t count = + std::clamp((std::max)(vp_n, sc_n), 1u, DrawViewports::max_count); + for (std::uint32_t k = 0; k < count; ++k) { + const Viewport v = (draw->viewports && k < vp_n) ? draw->viewports->viewports[k] + : (k == 0 ? draw->viewport : Viewport{}); + const bool valid_vp = (k < vp_n) && (v.width > 0.0f) && (v.height > 0.0f); + if (valid_vp) { + vps[k] = {v.x, v.y + v.height, v.width, -v.height, v.min_depth, v.max_depth}; + } else { + // Vulkan forbids width/height == 0; pair a 1x1 dummy viewport with an empty scissor so nothing + // rasterizes into an unbound/empty D3D12 viewport slot. + vps[k] = {0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f}; + } + if (valid_vp && k < sc_n) { + const Rect s = draw->viewports ? draw->viewports->scissors[k] : draw->scissor; + const std::int32_t left = (std::max)(0, s.left); + const std::int32_t top = (std::max)(0, s.top); + scs[k] = {{left, top}, + {std::uint32_t((std::max)(0, s.right - left)), + std::uint32_t((std::max)(0, s.bottom - top))}}; + } else { + scs[k] = {{0, 0}, {0, 0}}; + } + } + cache.set_viewports_with_count(command_buffer, vk, count, vps.data()); + cache.set_scissors_with_count(command_buffer, vk, count, scs.data()); + } else { + const Viewport& v = draw->viewport; + const VkViewport viewport{v.x, v.y + v.height, v.width, -v.height, v.min_depth, v.max_depth}; + cache.set_viewport_fixed(command_buffer, vk, viewport); + const Rect& s = draw->scissor; + const std::int32_t left = (std::max)(0, s.left); + const std::int32_t top = (std::max)(0, s.top); + const VkRect2D scissor{{left, top}, + {std::uint32_t((std::max)(0, s.right - left)), + std::uint32_t((std::max)(0, s.bottom - top))}}; + cache.set_scissor_fixed(command_buffer, vk, scissor); + } + // A mesh pipeline has no input assembly: its topology comes from the shader, and neither the topology + // nor primitive restart is dynamic state there (VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-07065). + if (!draw->mesh) { + const VkPrimitiveTopology topology = draw->topology == topology_quad_list && !draw->indexed + ? VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST : detail::vulkan_topology(draw->topology); + cache.set_primitive_topology(command_buffer, vk, topology); + const bool restart = draw->indexed && detail::strip_topology(topology) && + ((graphics.strip_cut == 1 && d.index_type == VK_INDEX_TYPE_UINT16) || + (graphics.strip_cut == 2 && d.index_type == VK_INDEX_TYPE_UINT32)); + cache.set_primitive_restart(command_buffer, vk, restart ? VK_TRUE : VK_FALSE); + } + cache.set_stencil_reference(command_buffer, vk, draw->stencil_front, draw->stencil_back); + cache.set_blend_constants(command_buffer, vk, draw->blend_factor); + if (graphics.depth_bounds) { + // Vulkan takes bounds in [0, 1] only (without VK_EXT_depth_range_unrestricted), as D3D12 does. + const float lo = std::clamp(draw->depth_bounds[0], 0.0f, 1.0f); + const float hi = std::clamp(draw->depth_bounds[1], 0.0f, 1.0f); + cache.set_depth_bounds(command_buffer, vk, lo, hi); + } + for (std::uint32_t slot = 0; slot < d.vertex_buffers.size(); ++slot) { + if (!d.vertex_buffers[slot]) continue; + cache.bind_vertex_buffer(command_buffer, vk, slot, d.vertex_buffers[slot], d.vertex_offsets[slot], + d.vertex_sizes[slot], d.vertex_strides[slot]); + } + if (raster.arguments) { + indirect_stats::note(indirect_stats::Event::emitted); + const auto& arg = *raster.arguments; + if (draw->indexed) { + // Bind only complete indices in the captured D3D12 view, never any trailing storage. + const VkDeviceSize width = d.index_type == VK_INDEX_TYPE_UINT16 ? 2 : 4; + const VkDeviceSize bytes = draw->index.size - draw->index.size % width; + cache.bind_robust_index_buffer(command_buffer, vk, d.index_buffer, d.index_offset, bytes, + d.index_type); + } + // What the draw reads: the clamp pass's scratch (and its clamped count) when it ran, else the + // application's own buffer. Its records and stride are the clamp's then, not the signature's. + const bool clamped = p.indirect_clamp.buffer != VK_NULL_HANDLE; + const VkBuffer arguments_buffer = clamped ? p.indirect_clamp.buffer : d.indirect_buffer; + const VkDeviceSize arguments_offset = clamped ? p.indirect_clamp.offset : d.indirect_offset; + const VkBuffer count_buffer = clamped ? p.indirect_clamp.count_buffer : d.indirect_count_buffer; + const VkDeviceSize count_offset = clamped ? p.indirect_clamp.count_offset : d.indirect_count_offset; + const std::uint32_t records = clamped ? p.indirect_clamp.records : arg.max_count; + const std::uint32_t stride = clamped ? p.indirect_clamp.stride : arg.stride; + if (draw->mesh) { + if (arg.count_buffer) + vk.draw_mesh_tasks_indirect_count(command_buffer, arguments_buffer, arguments_offset, count_buffer, + count_offset, records, stride); + else + vk.draw_mesh_tasks_indirect(command_buffer, arguments_buffer, arguments_offset, records, stride); + if (vk.mesh_draw_count) ++*vk.mesh_draw_count; + } else if (arg.count_buffer) { + const auto emit_counted = draw->indexed ? vk.draw_indexed_indirect_count : vk.draw_indirect_count; + emit_counted(command_buffer, arguments_buffer, arguments_offset, count_buffer, count_offset, + records, stride); + } else { + const auto emit_fixed = draw->indexed ? vk.draw_indexed_indirect : vk.draw_indirect; + emit_fixed(command_buffer, arguments_buffer, arguments_offset, records, stride); + } + } else if (draw->mesh) { + vk.draw_mesh_tasks(command_buffer, draw->count, draw->instances, draw->first); + if (vk.mesh_draw_count) ++*vk.mesh_draw_count; + } else if (draw->topology == topology_quad_list) { + if (draw->indexed) { + // The triangle indices the compute pass wrote before this rendering scope, (i0 i1 i2) (i0 i2 i3) + // for each quad of the application's indices from draw->first on: one draw, so instances run + // in D3D12's order, flat inputs come from each quad's first vertex, and VertexIndex - BaseVertex + // is still the application's index. A draw of fewer than four indices has no quad. + const QuadIndexExpansion& quads = d.quad_indices; + if (quads.buffer) { + cache.bind_index_buffer(command_buffer, vk, quads.buffer, quads.offset, VK_INDEX_TYPE_UINT32); + vk.draw_indexed(command_buffer, quads.quads * QuadIndexExpander::indices_per_quad, + draw->instances, 0, draw->base_vertex, draw->first_instance); + } + } else { + // Both triangles start at the quad's first vertex for flat inputs. One draw also preserves + // the original instance order, and VertexIndex - BaseVertex still gives 4q + k. + constexpr auto indices_per_quad = std::uint32_t(quad_triangle_indices.size()); + const std::uint32_t wanted = draw->count / 4; + const std::uint32_t quads = (std::min)(wanted, vk.quad_index_count / indices_per_quad); + if (quads < wanted) + std::fprintf(stderr, "[rt] d3d12: a non-indexed quad list of %u quads draws only the first %u\n", + wanted, quads); + if (quads) { + cache.bind_index_buffer(command_buffer, vk, vk.quad_indices, vk.quad_indices_offset, + VK_INDEX_TYPE_UINT32); + vk.draw_indexed(command_buffer, quads * indices_per_quad, draw->instances, 0, + std::int32_t(draw->first), draw->first_instance); + } + } + } else if (draw->indexed) { + cache.bind_index_buffer(command_buffer, vk, d.index_buffer, d.index_offset, d.index_type); + vk.draw_indexed(command_buffer, draw->count, draw->instances, draw->first, draw->base_vertex, + draw->first_instance); + } else { + vk.draw(command_buffer, draw->count, draw->instances, draw->first, draw->first_instance); + } + if constexpr (Checkpoints) { + if (checkpoints->submission.markers) end_scope(); + checkpoints->drawn(command_buffer); + } + continue; + } + if (const auto* dispatch = std::get_if(&command)) { + if (!p.pipeline.pipeline) continue; // could not be resolved in prepare: dropped + if constexpr (Checkpoints) + checkpoints->dispatch(command_buffer, i, p.pipeline.pipeline, dispatch->pipeline, dispatch->user_data, + {dispatch->x, dispatch->y, dispatch->z}); + cache.bind_compute_pipeline(command_buffer, vk, p.pipeline.pipeline); + if (p.pipeline.bindless_set) { + const VkDescriptorSet set0 = vk.bindless_set ? vk.bindless_set : p.pipeline.bindless_set; + cache.bind_compute_set0(command_buffer, vk, p.pipeline.layout, set0); + } + cache.push_user_data(command_buffer, vk, p.pipeline.layout, VK_SHADER_STAGE_COMPUTE_BIT, + dispatch->user_data, vk.heap_base, p.pipeline.code_base); + if (p.pipeline.reads_glc_buffer && vk.pipeline_barrier) { + detail::memory_barrier(vk, command_buffer, VK_ACCESS_SHADER_WRITE_BIT, shader_stages, + VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT, + VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); + } + if (p.pipeline.writes_buffer && vk.on_buffer_write) vk.on_buffer_write(vk.on_buffer_write_context); + vk.dispatch(command_buffer, dispatch->x, dispatch->y, dispatch->z); + if constexpr (Checkpoints) checkpoints->dispatched(command_buffer); + continue; + } if (const auto* predication = std::get_if(&command)) { // Conditional rendering cannot nest, so a new predicate ends the previous one first. if (predicate.buffer) vk.end_conditional_rendering(command_buffer); @@ -4713,6 +5668,7 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ if (predicate.buffer) { end_statistics(); vk.capture_predicate(command_buffer, p.predicate); + cache.invalidate_compute(); begin_statistics(); predicate.offset = p.predicate.offset + 8; // Vulkan discards the commands when the word is 0, which is EQUAL_ZERO; INVERTED gives NOT_EQUAL_ZERO. @@ -4723,21 +5679,9 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ } continue; } - const ResourceId id = std::visit( - [](const auto& c) -> ResourceId { - using T = std::decay_t; - if constexpr (std::is_same_v || std::is_same_v) - return c.target.resource; - else if constexpr (std::is_same_v) - return c.view.resource; - else if constexpr (requires { c.resource; }) - return c.resource; - else - return 0; - }, - command); if (const auto* transition = std::get_if(&command)) { + const ResourceId id = transition->resource; const VulkanAccess from = vulkan_access(transition->before, p.binding.presentable, predicates); const VulkanAccess to = vulkan_access(transition->after, p.binding.presentable, predicates); if (!p.binding.image) { @@ -4795,6 +5739,7 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ dependency.pMemoryBarriers = &barrier; vk.pipeline_barrier2(command_buffer, &dependency); } else if (const auto* texture = std::get_if(&command)) { + const ResourceId id = texture->resource; const auto range = detail::planes_for_layout(p.binding, p.range, separate); const bool discard = (texture->flags & texture_barrier_discard) || texture->layout_before == d3d12_layout::undefined; @@ -4823,9 +5768,11 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ const BarrierScope dst = vulkan_barrier_scope(texture->sync_after, texture->access_after, predicates); // One barrier for each piece: nearly always one or two (LayoutPieces), which stay on the stack. std::array few; - std::vector many; - if (pieces.size() > few.size()) many.resize(pieces.size()); - VkImageMemoryBarrier2* const barriers = many.empty() ? few.data() : many.data(); + VkImageMemoryBarrier2* barriers = few.data(); + if (pieces.size() > few.size()) { + many_barriers.resize(pieces.size()); + barriers = many_barriers.data(); + } std::uint32_t barrier_count = 0; for (const auto& piece : pieces) { // Released before it was ever used (the tracker still has it in UNDEFINED): nothing to order. @@ -4855,6 +5802,7 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ if (!release) finish_depth_uav_barrier(p, new_layout, end_statistics, begin_statistics); } else if (const auto* color_clear = std::get_if(&command)) { if (p.skip) continue; + const ResourceId id = color_clear->target.resource; if constexpr (Checkpoints) checkpoints->record(command_buffer, i, CheckpointKind::clear); const VulkanAccess state = vulkan_access(d3d12_state::render_target, false); auto pieces = detail::current(tracker, id, p.range, image_layout(p.binding, state.layout)); @@ -4892,6 +5840,7 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ }); } else if (const auto* depth_clear = std::get_if(&command)) { if (p.skip) continue; + const ResourceId id = depth_clear->target.resource; if constexpr (Checkpoints) checkpoints->record(command_buffer, i, CheckpointKind::clear); // With separate layouts only the cleared planes move; otherwise both do. const auto range = detail::planes_for_layout(p.binding, p.range, separate); @@ -4936,6 +5885,7 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ }); } else if (const auto* uav = std::get_if(&command)) { if (p.skip) continue; + const ResourceId id = uav->view.resource; if constexpr (Checkpoints) checkpoints->record(command_buffer, i, CheckpointKind::clear); // The UAV state, widened to transfers: a later barrier from SYNC_CLEAR_UNORDERED_ACCESS_VIEW names the // clear stage, which is a transfer stage in the legacy masks. @@ -5029,6 +5979,7 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ if (!p.predicated_copy.empty()) { end_statistics(); vk.emit_predicated_copy(command_buffer, p.predicated_copy); + cache.invalidate_compute(); begin_statistics(); } else if (!p.buffer_copies.empty()) { // Transfer dependency from natterman12, ubiquitarianism/leonida PR #354 (GPL-3.0). @@ -5092,7 +6043,6 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ } } else if (p.binding.image) { VkBuffer source = p.source.buffer; - std::vector converted; const std::vector* regions = &p.buffer_image_copies; if (p.tile_scratch) { vk.copy_buffer(command_buffer, source, p.tile_scratch, std::uint32_t(p.tile_rows.size()), @@ -5110,11 +6060,11 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ begin_statistics(); detail::memory_barrier(vk, command_buffer, VK_ACCESS_SHADER_WRITE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); - converted = p.buffer_image_copies; - converted[0].bufferOffset = p.depth24.scratch_offset; - converted[0].bufferRowLength = 0; - converted[0].bufferImageHeight = 0; - regions = &converted; + converted_copies.assign(p.buffer_image_copies.begin(), p.buffer_image_copies.end()); + converted_copies[0].bufferOffset = p.depth24.scratch_offset; + converted_copies[0].bufferRowLength = 0; + converted_copies[0].bufferImageHeight = 0; + regions = &converted_copies; source = p.depth24.scratch; } const VkImageLayout dst_layout = detail::copy_layout( @@ -5260,7 +6210,8 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ vk.end_label(command_buffer); --labels; } - } else if (std::holds_alternative(command)) { + } else if (const auto* discard_res = std::get_if(&command)) { + const ResourceId id = discard_res->resource; // oldLayout = UNDEFINED tells the driver the contents may go; the image stays in the layout the tracker // has for it, so later commands see no change. Without a tracker the layout is unknown, and a part // never used yet is still to be zero-filled: both are left alone. Without separate depth/stencil @@ -5319,6 +6270,7 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ end_statistics(); if (predicate.buffer) vk.end_conditional_rendering(command_buffer); vk.emit_indirect_clamp(command_buffer, p.indirect_clamp); + cache.invalidate_compute(); if (predicate.buffer) vk.begin_conditional_rendering(command_buffer, &predicate); begin_statistics(); } @@ -5341,7 +6293,17 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ // A legacy graphics indirect draw opens no rendering scope of its own: the caller has one open around the // replay (the tests do), and the recorded, stateful graphics indirects are Draw commands instead. if (ind->kind != IndirectKind::dispatch) { - if constexpr (Checkpoints) checkpoints->record(command_buffer, i, CheckpointKind::draw); + if constexpr (Checkpoints) { + checkpoints->record(command_buffer, i, CheckpointKind::draw); + // Inside the caller's rendering scope, which VK_AMD_buffer_marker allows. + checkpoints->draw(command_buffer, i, 0, + static_cast( + marked_draw::indirect | + (ind->kind == IndirectKind::draw_indexed ? marked_draw::indexed : 0u) | + (ind->count_buffer ? marked_draw::counted : 0u)), + {records, stride, 0}); + } + if (records && vk.on_buffer_write) vk.on_buffer_write(vk.on_buffer_write_context); if (ind->count_buffer) { if (ind->kind == IndirectKind::draw) vk.draw_indirect_count(command_buffer, indirect_buffer, arguments, count_buffer, count_offset, @@ -5354,6 +6316,7 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ } else { vk.draw_indexed_indirect(command_buffer, indirect_buffer, arguments, records, stride); } + if constexpr (Checkpoints) checkpoints->drawn(command_buffer); continue; } if (ind->pipeline && !p.pipeline.pipeline && (p.pipeline.async_build || p.pipeline.skipped)) continue; @@ -5367,33 +6330,38 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ // No D3D12 query must count this internal compute pass as an application dispatch. end_statistics(); vk.emit_counted_dispatch(command_buffer, p.counted_dispatch); + cache.invalidate_compute(); begin_statistics(); } if (ind->pipeline) { - ShaderUserData data{}; - std::copy(ind->user_data.begin(), ind->user_data.end(), data.s); - data.heap_base = vk.heap_base; - data.code_base = p.pipeline.code_base; - vk.bind_pipeline(command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, p.pipeline.pipeline); + cache.bind_compute_pipeline(command_buffer, vk, p.pipeline.pipeline); if (p.pipeline.bindless_set) { const VkDescriptorSet set0 = vk.bindless_set ? vk.bindless_set : p.pipeline.bindless_set; - vk.bind_descriptor_sets(command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, p.pipeline.layout, 0, - 1, &set0, 0, nullptr); + cache.bind_compute_set0(command_buffer, vk, p.pipeline.layout, set0); } - vk.push_constants(command_buffer, p.pipeline.layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(data), - &data); + cache.push_user_data(command_buffer, vk, p.pipeline.layout, VK_SHADER_STAGE_COMPUTE_BIT, + ind->user_data, vk.heap_base, p.pipeline.code_base); } + if (records && (!ind->pipeline || p.pipeline.writes_buffer) && vk.on_buffer_write) + vk.on_buffer_write(vk.on_buffer_write_context); for (std::uint32_t k = 0; k < records; ++k) { + if (ind->pipeline && p.pipeline.reads_glc_buffer && vk.pipeline_barrier) { + detail::memory_barrier(vk, command_buffer, VK_ACCESS_SHADER_WRITE_BIT, shader_stages, + VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT, + VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); + } vk.dispatch_indirect(command_buffer, indirect_buffer, arguments + VkDeviceSize(k) * stride); } if constexpr (Checkpoints) checkpoints->dispatched(command_buffer); } else if (const auto* xdxr_build = std::get_if(&command); xdxr_build && vk.xdxr_record) { vk.xdxr_record(command_buffer, *xdxr_build, p.xdxr_blases); + cache.invalidate_compute(); } else if (const auto* copy = std::get_if(&command)) { if constexpr (Checkpoints) checkpoints->record(command_buffer, i, CheckpointKind::copy); if (vk.xdxr_copy) { vk.xdxr_copy(command_buffer, copy->src_va, copy->dst_va, p.xdxr_bytes); + cache.invalidate_compute(); } else { VkCopyAccelerationStructureInfoKHR copy_info{VK_STRUCTURE_TYPE_COPY_ACCELERATION_STRUCTURE_INFO_KHR}; copy_info.src = p.accel_src; @@ -5407,6 +6375,7 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ if (vk.xdxr_postbuild) { for (std::size_t s = 0; s < postbuild->sources.size(); ++s) vk.xdxr_postbuild(command_buffer, postbuild->sources[s], postbuild->dest_va + 8 * s); + if (!postbuild->sources.empty()) cache.invalidate_compute(); } else if (p.khr_postbuild < prepared.khr_postbuilds.size()) { const auto& pb = prepared.khr_postbuilds[p.khr_postbuild]; const auto count = static_cast(pb.sources.size()); @@ -5437,8 +6406,8 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ // A null VA (no index buffer, no transform) stays null: heap_base + 0 would name the arena's zero page. const VkDeviceSize heap_base = vk.heap_base; const auto addr = [&](std::uint64_t va) -> VkDeviceAddress { return va ? heap_base + va : 0; }; - std::vector geoms; - std::vector ranges; + as_geoms.clear(); + as_ranges.clear(); if (build->is_tlas) { VkAccelerationStructureGeometryKHR g{VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_KHR}; g.geometryType = VK_GEOMETRY_TYPE_INSTANCES_KHR; @@ -5446,11 +6415,11 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ g.geometry.instances.arrayOfPointers = p.khr_instances ? VK_TRUE : VK_FALSE; g.geometry.instances.data.deviceAddress = p.khr_instances ? p.khr_instances : addr(build->instances_va); - geoms.push_back(g); - ranges.push_back({build->instance_count, 0, 0, 0}); + as_geoms.push_back(g); + as_ranges.push_back({build->instance_count, 0, 0, 0}); } else { - geoms.reserve(build->triangles.size()); - ranges.reserve(build->triangles.size()); + as_geoms.reserve(build->triangles.size()); + as_ranges.reserve(build->triangles.size()); for (const auto& t : build->triangles) { VkAccelerationStructureGeometryKHR g{VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_KHR}; g.geometryType = VK_GEOMETRY_TYPE_TRIANGLES_KHR; @@ -5466,10 +6435,10 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ : ((t.index_type == 2) ? VK_INDEX_TYPE_UINT32 : VK_INDEX_TYPE_NONE_KHR); tr.indexData.deviceAddress = addr(t.index_va); tr.transformData.deviceAddress = addr(t.transform_va); - geoms.push_back(g); + as_geoms.push_back(g); const std::uint32_t prim_count = (t.index_type != 0 && t.index_count >= 3) ? (t.index_count / 3u) : (t.vertex_count / 3u); - ranges.push_back({prim_count, 0, 0, 0}); + as_ranges.push_back({prim_count, 0, 0, 0}); } } VkAccelerationStructureBuildGeometryInfoKHR info{ @@ -5481,244 +6450,23 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ : VK_BUILD_ACCELERATION_STRUCTURE_MODE_BUILD_KHR; info.srcAccelerationStructure = build->update ? p.accel_src : VK_NULL_HANDLE; info.dstAccelerationStructure = p.accel_dst; - info.geometryCount = static_cast(geoms.size()); - info.pGeometries = geoms.data(); + info.geometryCount = static_cast(as_geoms.size()); + info.pGeometries = as_geoms.data(); info.scratchData.deviceAddress = addr(build->scratch_va); - const VkAccelerationStructureBuildRangeInfoKHR* range_ptr = ranges.data(); + const VkAccelerationStructureBuildRangeInfoKHR* range_ptr = as_ranges.data(); vk.build_acceleration_structures(command_buffer, 1, &info, &range_ptr); - } else if (const auto* dispatch = std::get_if(&command)) { - if (!p.pipeline.pipeline) continue; // could not be resolved in prepare: dropped - if constexpr (Checkpoints) - checkpoints->dispatch(command_buffer, i, p.pipeline.pipeline, dispatch->pipeline, dispatch->user_data, - {dispatch->x, dispatch->y, dispatch->z}); - ShaderUserData data{}; - std::copy(dispatch->user_data.begin(), dispatch->user_data.end(), data.s); - data.heap_base = vk.heap_base; - data.code_base = p.pipeline.code_base; - vk.bind_pipeline(command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, p.pipeline.pipeline); - if (p.pipeline.bindless_set) { - const VkDescriptorSet set0 = vk.bindless_set ? vk.bindless_set : p.pipeline.bindless_set; - vk.bind_descriptor_sets(command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, p.pipeline.layout, 0, 1, - &set0, 0, nullptr); - } - vk.push_constants(command_buffer, p.pipeline.layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(data), &data); - vk.dispatch(command_buffer, dispatch->x, dispatch->y, dispatch->z); - if constexpr (Checkpoints) checkpoints->dispatched(command_buffer); - } else if (raster.state) { - const Draw* draw = raster.state; - const detail::PreparedDraw& d = prepared.draws[p.draw]; - if (d.skipped) continue; // could not be resolved in prepare: dropped - // The clamp pass for a stateful indirect draw (vulkan_indirect_clamp.h) runs before vkCmdBeginRendering, - // because its copy and transfer barrier are not allowed inside a dynamic-rendering scope. It is a helper - // dispatch, so a pipeline-statistics query must not count it, and it runs even under a false predicate. - if (p.indirect_clamp.buffer != VK_NULL_HANDLE) { - end_statistics(); - if (predicate.buffer) vk.end_conditional_rendering(command_buffer); - vk.emit_indirect_clamp(command_buffer, p.indirect_clamp); - if (predicate.buffer) vk.begin_conditional_rendering(command_buffer, &predicate); - begin_statistics(); - } - if constexpr (Checkpoints) - checkpoints->record(command_buffer, i, CheckpointKind::draw, - d.pipeline, draw->pipeline); - constexpr VkAccessFlags color_access = - VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; - constexpr VkAccessFlags depth_access = - VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; - constexpr VkPipelineStageFlags depth_stages = - VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; - std::array colors; - colors.fill({VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO}); - for (std::size_t slot = 0; slot < d.colors.size(); ++slot) { - const auto& a = d.colors[slot]; - if (!a.id) continue; // an unbound slot: no image view, writes are dropped - const VkImageLayout layout = image_layout(a.binding, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); - detail::to_attachment(vk, command_buffer, a, layout, color_access, - VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, tracker, separate); - colors[slot].imageView = a.view; - colors[slot].imageLayout = layout; - colors[slot].loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; - colors[slot].storeOp = VK_ATTACHMENT_STORE_OP_STORE; - } - VkRenderingAttachmentInfo depth{VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO}; - if (d.depth.id) { - const VkImageLayout layout = image_layout(d.depth.binding, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); - detail::to_attachment(vk, command_buffer, d.depth, layout, depth_access, depth_stages, tracker, - separate); - depth.imageView = d.depth.view; - depth.imageLayout = layout; - depth.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; - depth.storeOp = VK_ATTACHMENT_STORE_OP_STORE; - } - VkRenderingInfo rendering{VK_STRUCTURE_TYPE_RENDERING_INFO}; - rendering.renderArea = {{0, 0}, d.area}; - rendering.layerCount = d.layers; // array views: SV_RenderTargetArrayIndex picks the layer - rendering.colorAttachmentCount = std::uint32_t(d.colors.size()); - rendering.pColorAttachments = colors.data(); - const GraphicsPipeline& graphics = *d.graphics; - if (d.depth.id && (graphics.depth_aspects & VK_IMAGE_ASPECT_DEPTH_BIT)) rendering.pDepthAttachment = &depth; - if (d.depth.id && (graphics.depth_aspects & VK_IMAGE_ASPECT_STENCIL_BIT)) rendering.pStencilAttachment = &depth; - vk.begin_rendering(command_buffer, &rendering); - - ShaderUserData data{}; - std::copy(draw->user_data.begin(), draw->user_data.end(), data.s); - data.heap_base = vk.heap_base; - data.code_base = graphics.code_base; - vk.bind_pipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, d.pipeline); - if (graphics.bindless_set) { - const VkDescriptorSet set0 = vk.bindless_set ? vk.bindless_set : graphics.bindless_set; - vk.bind_descriptor_sets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, graphics.layout, 0, 1, - &set0, 0, nullptr); - } - vk.push_constants(command_buffer, graphics.layout, graphics.push_stages, 0, sizeof(data), &data); - // Translated vertex shaders write D3D clip coordinates (y up); a negative-height viewport keeps the - // image upright, and winding as D3D12 sees it. - if (graphics.viewport_with_count) { - std::array vps{}; - std::array scs{}; - const std::uint32_t vp_n = draw->viewports ? draw->viewports->viewport_count : 1u; - const std::uint32_t sc_n = draw->viewports ? draw->viewports->scissor_count : 1u; - const std::uint32_t count = std::clamp(std::max(vp_n, sc_n), 1u, DrawViewports::max_count); - for (std::uint32_t k = 0; k < count; ++k) { - const Viewport v = (draw->viewports && k < vp_n) ? draw->viewports->viewports[k] - : (k == 0 ? draw->viewport : Viewport{}); - const bool valid_vp = (k < vp_n) && (v.width > 0.0f) && (v.height > 0.0f); - if (valid_vp) { - vps[k] = {v.x, v.y + v.height, v.width, -v.height, v.min_depth, v.max_depth}; - } else { - // Vulkan forbids width/height == 0; pair a 1x1 dummy viewport with an empty scissor so nothing - // rasterizes into an unbound/empty D3D12 viewport slot. - vps[k] = {0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f}; - } - if (valid_vp && k < sc_n) { - const Rect s = draw->viewports ? draw->viewports->scissors[k] : draw->scissor; - const std::int32_t left = std::max(0, s.left); - const std::int32_t top = std::max(0, s.top); - scs[k] = {{left, top}, - {std::uint32_t(std::max(0, s.right - left)), - std::uint32_t(std::max(0, s.bottom - top))}}; - } else { - scs[k] = {{0, 0}, {0, 0}}; - } - } - vk.set_viewport_with_count(command_buffer, count, vps.data()); - vk.set_scissor_with_count(command_buffer, count, scs.data()); - } else { - const Viewport& v = draw->viewport; - const VkViewport viewport{v.x, v.y + v.height, v.width, -v.height, v.min_depth, v.max_depth}; - vk.set_viewport(command_buffer, 0, 1, &viewport); - const Rect& s = draw->scissor; - const VkRect2D scissor{{std::max(0, s.left), std::max(0, s.top)}, - {std::uint32_t(std::max(0, s.right - std::max(0, s.left))), - std::uint32_t(std::max(0, s.bottom - std::max(0, s.top)))}}; - vk.set_scissor(command_buffer, 0, 1, &scissor); - } - // A mesh pipeline has no input assembly: its topology comes from the shader, and neither the topology - // nor primitive restart is dynamic state there (VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-07065). - if (!draw->mesh) { - const VkPrimitiveTopology topology = draw->topology == topology_quad_list && !draw->indexed - ? VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST : detail::vulkan_topology(draw->topology); - vk.set_primitive_topology(command_buffer, topology); - const bool restart = draw->indexed && detail::strip_topology(topology) && - ((graphics.strip_cut == 1 && d.index_type == VK_INDEX_TYPE_UINT16) || - (graphics.strip_cut == 2 && d.index_type == VK_INDEX_TYPE_UINT32)); - vk.set_primitive_restart_enable(command_buffer, restart ? VK_TRUE : VK_FALSE); - } - vk.set_stencil_reference(command_buffer, VK_STENCIL_FACE_FRONT_BIT, draw->stencil_front); - vk.set_stencil_reference(command_buffer, VK_STENCIL_FACE_BACK_BIT, draw->stencil_back); - vk.set_blend_constants(command_buffer, draw->blend_factor.data()); - if (graphics.depth_bounds) { - // Vulkan takes bounds in [0, 1] only (without VK_EXT_depth_range_unrestricted), as D3D12 does. - const float lo = std::clamp(draw->depth_bounds[0], 0.0f, 1.0f); - const float hi = std::clamp(draw->depth_bounds[1], 0.0f, 1.0f); - vk.set_depth_bounds(command_buffer, lo, hi); - } - for (std::uint32_t slot = 0; slot < d.vertex_buffers.size(); ++slot) { - if (!d.vertex_buffers[slot]) continue; - vk.bind_vertex_buffers2(command_buffer, slot, 1, &d.vertex_buffers[slot], &d.vertex_offsets[slot], - &d.vertex_sizes[slot], &d.vertex_strides[slot]); - } - if (raster.arguments) { - indirect_stats::note(indirect_stats::Event::emitted); - const auto& arg = *raster.arguments; - if (draw->indexed) { - // Bind only complete indices in the captured D3D12 view, never any trailing storage. - const VkDeviceSize width = d.index_type == VK_INDEX_TYPE_UINT16 ? 2 : 4; - const VkDeviceSize bytes = draw->index.size - draw->index.size % width; - vk.bind_robust_index_view(command_buffer, d.index_buffer, d.index_offset, bytes, d.index_type); - } - // What the draw reads: the clamp pass's scratch (and its clamped count) when it ran, else the - // application's own buffer. Its records and stride are the clamp's then, not the signature's. - const bool clamped = p.indirect_clamp.buffer != VK_NULL_HANDLE; - const VkBuffer arguments_buffer = clamped ? p.indirect_clamp.buffer : d.indirect_buffer; - const VkDeviceSize arguments_offset = clamped ? p.indirect_clamp.offset : d.indirect_offset; - const VkBuffer count_buffer = clamped ? p.indirect_clamp.count_buffer : d.indirect_count_buffer; - const VkDeviceSize count_offset = clamped ? p.indirect_clamp.count_offset : d.indirect_count_offset; - const std::uint32_t records = clamped ? p.indirect_clamp.records : arg.max_count; - const std::uint32_t stride = clamped ? p.indirect_clamp.stride : arg.stride; - if (draw->mesh) { - if (arg.count_buffer) - vk.draw_mesh_tasks_indirect_count(command_buffer, arguments_buffer, arguments_offset, count_buffer, - count_offset, records, stride); - else - vk.draw_mesh_tasks_indirect(command_buffer, arguments_buffer, arguments_offset, records, stride); - if (vk.mesh_draw_count) ++*vk.mesh_draw_count; - } else if (arg.count_buffer) { - const auto emit_counted = draw->indexed ? vk.draw_indexed_indirect_count : vk.draw_indirect_count; - emit_counted(command_buffer, arguments_buffer, arguments_offset, count_buffer, count_offset, - records, stride); - } else { - const auto emit_fixed = draw->indexed ? vk.draw_indexed_indirect : vk.draw_indirect; - emit_fixed(command_buffer, arguments_buffer, arguments_offset, records, stride); - } - } else if (draw->mesh) { - vk.draw_mesh_tasks(command_buffer, draw->count, draw->instances, draw->first); - if (vk.mesh_draw_count) ++*vk.mesh_draw_count; - } else if (draw->topology == topology_quad_list) { - if (draw->indexed) { - // The triangle indices the compute pass wrote before this rendering scope, (i0 i1 i2) (i0 i2 i3) - // for each quad of the application's indices from draw->first on: one draw, so instances run - // in D3D12's order, flat inputs come from each quad's first vertex, and VertexIndex - BaseVertex - // is still the application's index. A draw of fewer than four indices has no quad. - const QuadIndexExpansion& quads = d.quad_indices; - if (quads.buffer) { - vk.bind_index_buffer(command_buffer, quads.buffer, quads.offset, VK_INDEX_TYPE_UINT32); - vk.draw_indexed(command_buffer, quads.quads * QuadIndexExpander::indices_per_quad, - draw->instances, 0, draw->base_vertex, draw->first_instance); - } - } else { - // Both triangles start at the quad's first vertex for flat inputs. One draw also preserves - // the original instance order, and VertexIndex - BaseVertex still gives 4q + k. - constexpr auto indices_per_quad = std::uint32_t(quad_triangle_indices.size()); - const std::uint32_t wanted = draw->count / 4; - const std::uint32_t quads = std::min(wanted, vk.quad_index_count / indices_per_quad); - if (quads < wanted) - std::fprintf(stderr, "[rt] d3d12: a non-indexed quad list of %u quads draws only the first %u\n", - wanted, quads); - if (quads) { - vk.bind_index_buffer(command_buffer, vk.quad_indices, vk.quad_indices_offset, VK_INDEX_TYPE_UINT32); - vk.draw_indexed(command_buffer, quads * indices_per_quad, draw->instances, 0, - std::int32_t(draw->first), draw->first_instance); - } - } - } else if (draw->indexed) { - vk.bind_index_buffer(command_buffer, d.index_buffer, d.index_offset, d.index_type); - vk.draw_indexed(command_buffer, draw->count, draw->instances, draw->first, draw->base_vertex, - draw->first_instance); - } else { - vk.draw(command_buffer, draw->count, draw->instances, draw->first, draw->first_instance); - } - vk.end_rendering(command_buffer); } } + end_scope(); // Predication does not carry over to the next command list. if (predicate.buffer) vk.end_conditional_rendering(command_buffer); if (!open_labels) close_labels(command_buffer, vk, own_labels); } inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, const ReplayFunctions& vk, - LayoutTracker* tracker = nullptr, std::uint32_t* open_labels = nullptr) { - emit_commands(prepared, command_buffer, vk, tracker, open_labels, nullptr); + LayoutTracker* tracker = nullptr, std::uint32_t* open_labels = nullptr, + ReplayStateCache* state_cache = nullptr, EmitScratch* emit_scratch = nullptr) { + emit_commands(prepared, command_buffer, vk, tracker, open_labels, nullptr, state_cache, emit_scratch); } // prepare + emit for one list. A failed replay leaves the command buffer and the tracker untouched. diff --git a/runtime/src/vulkan_title_detile.h b/runtime/src/vulkan_title_detile.h new file mode 100644 index 0000000000..522e5c1f29 --- /dev/null +++ b/runtime/src/vulkan_title_detile.h @@ -0,0 +1,1070 @@ +#pragma once +// GPU detiling and direct linear copy of mirrored title textures. +// +// Textures whose 64 KiB pages are already backed and flushed in TitleMirror (src/title_mirror.h) can be brought +// directly into their Vulkan VkImage on the GPU without reading title memory on the CPU or staging through host RAM: +// - kLinear: direct vkCmdCopyBufferToImage from the TitleMirror sparse chunk buffer (zero compute, zero scratch). +// - k4kbS / k64kbS / k64kbD (2D / 2D-array, 1/2/4/8/16 bytes per element, full mip chains including mip tails): +// compute shader reading directly from the TitleMirror chunk buffer (std430 uint32 storage buffer, no optional +// 8-bit/16-bit/64-bit/BDA shader extensions required) into a device-local transient scratch buffer, followed by +// vkCmdCopyBufferToImage. +// +// Controlled by LEONIDA_GPU_DETILE (default ON; =0 forces CPU fallback for A/B visual parity testing). +// Pure Vulkan + C++20 stdlib (no Windows SDK headers), so vk_title_detile_test runs on both Linux and Windows. + +#ifndef VK_NO_PROTOTYPES +#define VK_NO_PROTOTYPES +#endif +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace leonida { + +inline bool title_gpu_detile_enabled() { + static const bool on = [] { + const char* v = std::getenv("LEONIDA_GPU_DETILE"); + return !v || std::strcmp(v, "0") != 0; + }(); + return on; +} + +enum class TitleDetileMode : std::uint32_t { + linear = 0, + sw_4kb_s = 5, + sw_64kb_s = 9, + sw_64kb_d = 10, +}; + +struct TitleDetileMip { + std::uint64_t offset = 0; // byte offset in slice (for !in_tail; 0 or tail byte offset for in_tail) + std::uint32_t width_elements = 0; + std::uint32_t height_elements = 0; + std::uint32_t width_texels = 0; + std::uint32_t height_texels = 0; + std::uint32_t depth = 1; // 3D depth of this mip (1 for 1D/2D/2D-array) + std::uint32_t padded_width = 0; // in elements + std::uint32_t padded_height = 0; // in elements + std::uint32_t pitch_bytes = 0; + std::uint32_t pitch_texels = 0; + std::uint32_t tail_x = 0; // element x origin inside tail block (when in_tail) + std::uint32_t tail_y = 0; // element y origin inside tail block (when in_tail) + bool in_tail = false; +}; + +struct TitleDetileDesc { + TitleDetileMode mode = TitleDetileMode::linear; + std::uint32_t dimension = 3; // 2 = 1D, 3 = 2D, 4 = 3D (matches D3D12_RESOURCE_DIMENSION / xg_xs) + std::uint32_t element_bytes = 0; // 1, 2, 4, 8, or 16 + std::uint32_t block_side = 1; // 1 for uncompressed, 4 for BC + std::uint32_t tile_width = 1; // elements per tile in X (power of 2 for swizzled) + std::uint32_t tile_height = 1; // elements per tile in Y (power of 2 for swizzled) + std::uint32_t array_layers = 1; // 1 for 3D + std::uint64_t total_size = 0; // total bytes in console tiled/linear memory + std::uint64_t slice_bytes = 0; // byte stride between array slices (or linear 3D depth slices) + std::vector mips; +}; + +struct TitleDetilePush { + std::uint32_t src_base = 0; + std::uint32_t dst_word_base = 0; + std::uint32_t width = 0; + std::uint32_t height = 0; + std::uint32_t tiles_x = 0; + std::uint32_t tail_x = 0; + std::uint32_t tail_y = 0; + std::uint32_t flags = 0; +}; +static_assert(sizeof(TitleDetilePush) == 32); + +struct TitleDetileDispatch { + VkDescriptorSet set = VK_NULL_HANDLE; + TitleDetilePush push{}; + std::uint32_t groups_x = 0; + std::uint32_t groups_y = 0; +}; + +namespace detail { + +// Compiled from GLSL 450 compute shader (local_size_x=8, local_size_y=8) with: +// glslangValidator -V --target-env vulkan1.2 --spirv-val title_detile.comp -o title_detile.spv +// spirv-opt -Os --strip-debug title_detile.spv -o title_detile_opt.spv +// spirv-val --target-env vulkan1.2 title_detile_opt.spv +// Implements exact GFX10/RDNA2 RB+ 4KB_S, 64KB_S, and 64KB_D bit equations for 1/2/4/8/16-byte elements +// (including mip tails and arbitrary odd extents via race-free uint32 word packing for 1B/2B elements). +inline constexpr std::uint32_t kTitleDetileSpirv[] = { + 0x07230203u, 0x00010500u, 0x0008000bu, 0x00000525u, 0x00000000u, 0x00020011u, 0x00000001u, 0x0006000bu, + 0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu, 0x00000000u, 0x00000001u, + 0x000c000fu, 0x00000005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00000105u, 0x0000016bu, 0x000001b5u, + 0x000001bcu, 0x000001c8u, 0x000001cbu, 0x000001d4u, 0x00060010u, 0x00000004u, 0x00000011u, 0x00000008u, + 0x00000008u, 0x00000001u, 0x00030047u, 0x00000103u, 0x00000002u, 0x00050048u, 0x00000103u, 0x00000000u, + 0x00000023u, 0x00000000u, 0x00050048u, 0x00000103u, 0x00000001u, 0x00000023u, 0x00000004u, 0x00050048u, + 0x00000103u, 0x00000002u, 0x00000023u, 0x00000008u, 0x00050048u, 0x00000103u, 0x00000003u, 0x00000023u, + 0x0000000cu, 0x00050048u, 0x00000103u, 0x00000004u, 0x00000023u, 0x00000010u, 0x00050048u, 0x00000103u, + 0x00000005u, 0x00000023u, 0x00000014u, 0x00050048u, 0x00000103u, 0x00000006u, 0x00000023u, 0x00000018u, + 0x00050048u, 0x00000103u, 0x00000007u, 0x00000023u, 0x0000001cu, 0x00040047u, 0x0000016bu, 0x0000000bu, + 0x0000001cu, 0x00040047u, 0x000001b2u, 0x00000006u, 0x00000004u, 0x00030047u, 0x000001b3u, 0x00000002u, + 0x00040048u, 0x000001b3u, 0x00000000u, 0x00000019u, 0x00050048u, 0x000001b3u, 0x00000000u, 0x00000023u, + 0x00000000u, 0x00030047u, 0x000001b5u, 0x00000019u, 0x00040047u, 0x000001b5u, 0x00000021u, 0x00000001u, + 0x00040047u, 0x000001b5u, 0x00000022u, 0x00000000u, 0x00040047u, 0x000001b9u, 0x00000006u, 0x00000004u, + 0x00030047u, 0x000001bau, 0x00000002u, 0x00040048u, 0x000001bau, 0x00000000u, 0x00000018u, 0x00050048u, + 0x000001bau, 0x00000000u, 0x00000023u, 0x00000000u, 0x00030047u, 0x000001bcu, 0x00000018u, 0x00040047u, + 0x000001bcu, 0x00000021u, 0x00000000u, 0x00040047u, 0x000001bcu, 0x00000022u, 0x00000000u, 0x00040047u, + 0x000001c8u, 0x0000000bu, 0x0000001au, 0x00040047u, 0x000001cbu, 0x0000000bu, 0x00000018u, 0x00040047u, + 0x000001d4u, 0x0000000bu, 0x0000001du, 0x00040047u, 0x0000023du, 0x0000000bu, 0x00000019u, 0x00020013u, + 0x00000002u, 0x00030021u, 0x00000003u, 0x00000002u, 0x00040015u, 0x00000006u, 0x00000020u, 0x00000000u, + 0x0004002bu, 0x00000006u, 0x0000001eu, 0x0000000fu, 0x0004002bu, 0x00000006u, 0x00000023u, 0x00000002u, + 0x0004002bu, 0x00000006u, 0x00000026u, 0x00000033u, 0x0004002bu, 0x00000006u, 0x0000002au, 0x00000001u, + 0x0004002bu, 0x00000006u, 0x0000002du, 0x00000055u, 0x0004002bu, 0x00000006u, 0x00000033u, 0x00000000u, + 0x00020014u, 0x00000035u, 0x0004002bu, 0x00000006u, 0x00000041u, 0x00000004u, 0x0004002bu, 0x00000006u, + 0x00000046u, 0x00000007u, 0x0004002bu, 0x00000006u, 0x0000004bu, 0x00000003u, 0x0004002bu, 0x00000006u, + 0x00000055u, 0x00000005u, 0x0004002bu, 0x00000006u, 0x0000005bu, 0x00000006u, 0x0004002bu, 0x00000006u, + 0x000000f6u, 0x00000008u, 0x000a001eu, 0x00000103u, 0x00000006u, 0x00000006u, 0x00000006u, 0x00000006u, + 0x00000006u, 0x00000006u, 0x00000006u, 0x00000006u, 0x00040020u, 0x00000104u, 0x00000009u, 0x00000103u, + 0x0004003bu, 0x00000104u, 0x00000105u, 0x00000009u, 0x00040015u, 0x00000106u, 0x00000020u, 0x00000001u, + 0x0004002bu, 0x00000106u, 0x00000107u, 0x00000005u, 0x00040020u, 0x00000108u, 0x00000009u, 0x00000006u, + 0x0004002bu, 0x00000106u, 0x0000010eu, 0x00000006u, 0x0004002bu, 0x00000106u, 0x00000113u, 0x00000000u, + 0x0004002bu, 0x00000106u, 0x0000011bu, 0x00000004u, 0x0004002bu, 0x00000106u, 0x00000141u, 0x00000007u, + 0x0004002bu, 0x00000006u, 0x00000150u, 0x00000010u, 0x0004002bu, 0x00000006u, 0x00000151u, 0x0000000cu, + 0x0004002bu, 0x00000006u, 0x0000015cu, 0x000000ffu, 0x0004002bu, 0x00000006u, 0x00000161u, 0x0000000eu, + 0x00040017u, 0x00000169u, 0x00000006u, 0x00000003u, 0x00040020u, 0x0000016au, 0x00000001u, 0x00000169u, + 0x0004003bu, 0x0000016au, 0x0000016bu, 0x00000001u, 0x00040020u, 0x0000016cu, 0x00000001u, 0x00000006u, + 0x0004002bu, 0x00000106u, 0x00000173u, 0x00000002u, 0x0004002bu, 0x00000106u, 0x0000017bu, 0x00000003u, + 0x0004002bu, 0x00000106u, 0x0000019du, 0x00000001u, 0x0003001du, 0x000001b2u, 0x00000006u, 0x0003001eu, + 0x000001b3u, 0x000001b2u, 0x00040020u, 0x000001b4u, 0x0000000cu, 0x000001b3u, 0x0004003bu, 0x000001b4u, + 0x000001b5u, 0x0000000cu, 0x0003001du, 0x000001b9u, 0x00000006u, 0x0003001eu, 0x000001bau, 0x000001b9u, + 0x00040020u, 0x000001bbu, 0x0000000cu, 0x000001bau, 0x0004003bu, 0x000001bbu, 0x000001bcu, 0x0000000cu, + 0x00040020u, 0x000001c0u, 0x0000000cu, 0x00000006u, 0x0004003bu, 0x0000016au, 0x000001c8u, 0x00000001u, + 0x0004003bu, 0x0000016au, 0x000001cbu, 0x00000001u, 0x0004002bu, 0x00000006u, 0x000001d2u, 0x00000040u, + 0x0004003bu, 0x0000016cu, 0x000001d4u, 0x00000001u, 0x0006002cu, 0x00000169u, 0x0000023du, 0x000000f6u, + 0x000000f6u, 0x0000002au, 0x00050036u, 0x00000002u, 0x00000004u, 0x00000000u, 0x00000003u, 0x000200f8u, + 0x00000005u, 0x000300f7u, 0x0000023eu, 0x00000000u, 0x000300fbu, 0x00000033u, 0x0000023fu, 0x000200f8u, + 0x0000023fu, 0x00050041u, 0x00000108u, 0x00000142u, 0x00000105u, 0x00000141u, 0x0004003du, 0x00000006u, + 0x00000143u, 0x00000142u, 0x000500c7u, 0x00000006u, 0x00000144u, 0x00000143u, 0x00000046u, 0x000500c2u, + 0x00000006u, 0x00000148u, 0x00000143u, 0x0000004bu, 0x000500c7u, 0x00000006u, 0x00000149u, 0x00000148u, + 0x0000002au, 0x000500c2u, 0x00000006u, 0x0000014du, 0x00000143u, 0x00000041u, 0x000500c7u, 0x00000006u, + 0x0000014eu, 0x0000014du, 0x0000002au, 0x000500abu, 0x00000035u, 0x0000014fu, 0x0000014eu, 0x00000033u, + 0x000600a9u, 0x00000006u, 0x00000152u, 0x0000014fu, 0x00000150u, 0x00000151u, 0x000500c2u, 0x00000006u, + 0x00000156u, 0x00000143u, 0x00000055u, 0x000500c7u, 0x00000006u, 0x00000157u, 0x00000156u, 0x0000002au, + 0x000500c2u, 0x00000006u, 0x0000015bu, 0x00000143u, 0x0000005bu, 0x000500c7u, 0x00000006u, 0x0000015du, + 0x0000015bu, 0x0000015cu, 0x000500c2u, 0x00000006u, 0x00000162u, 0x00000143u, 0x00000161u, 0x000500c7u, + 0x00000006u, 0x00000163u, 0x00000162u, 0x0000015cu, 0x000500aeu, 0x00000035u, 0x00000165u, 0x00000144u, + 0x00000023u, 0x000300f7u, 0x00000167u, 0x00000000u, 0x000400fau, 0x00000165u, 0x00000166u, 0x000001c6u, + 0x000200f8u, 0x00000166u, 0x00050041u, 0x0000016cu, 0x0000016du, 0x0000016bu, 0x00000033u, 0x0004003du, + 0x00000006u, 0x0000016eu, 0x0000016du, 0x00050041u, 0x0000016cu, 0x00000170u, 0x0000016bu, 0x0000002au, + 0x0004003du, 0x00000006u, 0x00000171u, 0x00000170u, 0x00050041u, 0x00000108u, 0x00000174u, 0x00000105u, + 0x00000173u, 0x0004003du, 0x00000006u, 0x00000175u, 0x00000174u, 0x000500aeu, 0x00000035u, 0x00000176u, + 0x0000016eu, 0x00000175u, 0x000400a8u, 0x00000035u, 0x00000177u, 0x00000176u, 0x000300f7u, 0x00000179u, + 0x00000000u, 0x000400fau, 0x00000177u, 0x00000178u, 0x00000179u, 0x000200f8u, 0x00000178u, 0x00050041u, + 0x00000108u, 0x0000017cu, 0x00000105u, 0x0000017bu, 0x0004003du, 0x00000006u, 0x0000017du, 0x0000017cu, + 0x000500aeu, 0x00000035u, 0x0000017eu, 0x00000171u, 0x0000017du, 0x000200f9u, 0x00000179u, 0x000200f8u, + 0x00000179u, 0x000700f5u, 0x00000035u, 0x0000017fu, 0x00000176u, 0x00000166u, 0x0000017eu, 0x00000178u, + 0x000300f7u, 0x00000181u, 0x00000000u, 0x000400fau, 0x0000017fu, 0x00000180u, 0x00000181u, 0x000200f8u, + 0x00000180u, 0x000200f9u, 0x0000023eu, 0x000200f8u, 0x00000181u, 0x000500abu, 0x00000035u, 0x0000024fu, + 0x00000157u, 0x00000033u, 0x000300f7u, 0x00000276u, 0x00000000u, 0x000400fau, 0x0000024fu, 0x00000250u, + 0x0000025bu, 0x000200f8u, 0x00000250u, 0x00050041u, 0x00000108u, 0x00000252u, 0x00000105u, 0x00000107u, + 0x0004003du, 0x00000006u, 0x00000253u, 0x00000252u, 0x00050080u, 0x00000006u, 0x00000254u, 0x0000016eu, + 0x00000253u, 0x00050041u, 0x00000108u, 0x00000256u, 0x00000105u, 0x0000010eu, 0x0004003du, 0x00000006u, + 0x00000257u, 0x00000256u, 0x00050080u, 0x00000006u, 0x00000258u, 0x00000171u, 0x00000257u, 0x00050041u, + 0x00000108u, 0x00000259u, 0x00000105u, 0x00000113u, 0x0004003du, 0x00000006u, 0x0000025au, 0x00000259u, + 0x000200f9u, 0x00000276u, 0x000200f8u, 0x0000025bu, 0x000500c2u, 0x00000006u, 0x0000025eu, 0x00000171u, + 0x00000163u, 0x00050041u, 0x00000108u, 0x0000025fu, 0x00000105u, 0x0000011bu, 0x0004003du, 0x00000006u, + 0x00000260u, 0x0000025fu, 0x00050084u, 0x00000006u, 0x00000261u, 0x0000025eu, 0x00000260u, 0x000500c2u, + 0x00000006u, 0x00000264u, 0x0000016eu, 0x0000015du, 0x00050080u, 0x00000006u, 0x00000265u, 0x00000261u, + 0x00000264u, 0x000500c4u, 0x00000006u, 0x00000268u, 0x0000002au, 0x0000015du, 0x00050082u, 0x00000006u, + 0x00000269u, 0x00000268u, 0x0000002au, 0x000500c7u, 0x00000006u, 0x0000026au, 0x0000016eu, 0x00000269u, + 0x000500c4u, 0x00000006u, 0x0000026du, 0x0000002au, 0x00000163u, 0x00050082u, 0x00000006u, 0x0000026eu, + 0x0000026du, 0x0000002au, 0x000500c7u, 0x00000006u, 0x0000026fu, 0x00000171u, 0x0000026eu, 0x00050041u, + 0x00000108u, 0x00000270u, 0x00000105u, 0x00000113u, 0x0004003du, 0x00000006u, 0x00000271u, 0x00000270u, + 0x000500c4u, 0x00000006u, 0x00000274u, 0x00000265u, 0x00000152u, 0x00050080u, 0x00000006u, 0x00000275u, + 0x00000271u, 0x00000274u, 0x000200f9u, 0x00000276u, 0x000200f8u, 0x00000276u, 0x000700f5u, 0x00000006u, + 0x000004e8u, 0x00000258u, 0x00000250u, 0x0000026fu, 0x0000025bu, 0x000700f5u, 0x00000006u, 0x000004e7u, + 0x00000254u, 0x00000250u, 0x0000026au, 0x0000025bu, 0x000700f5u, 0x00000006u, 0x000004e4u, 0x0000025au, + 0x00000250u, 0x00000275u, 0x0000025bu, 0x000500aau, 0x00000035u, 0x00000287u, 0x00000144u, 0x00000033u, + 0x000300f7u, 0x0000032bu, 0x00000000u, 0x000400fau, 0x00000287u, 0x00000288u, 0x000002aeu, 0x000200f8u, + 0x00000288u, 0x000500aau, 0x00000035u, 0x0000028au, 0x00000149u, 0x00000033u, 0x000300f7u, 0x000002adu, + 0x00000000u, 0x000400fau, 0x0000028au, 0x0000028bu, 0x00000292u, 0x000200f8u, 0x0000028bu, 0x000500c7u, + 0x00000006u, 0x0000028du, 0x000004e7u, 0x0000001eu, 0x000500c7u, 0x00000006u, 0x0000028fu, 0x000004e8u, + 0x0000001eu, 0x000500c4u, 0x00000006u, 0x00000290u, 0x0000028fu, 0x00000041u, 0x000500c5u, 0x00000006u, + 0x00000291u, 0x0000028du, 0x00000290u, 0x000200f9u, 0x000002adu, 0x000200f8u, 0x00000292u, 0x000500c7u, + 0x00000006u, 0x00000294u, 0x000004e7u, 0x00000046u, 0x000500c2u, 0x00000006u, 0x00000296u, 0x000004e8u, + 0x0000002au, 0x000500c7u, 0x00000006u, 0x00000297u, 0x00000296u, 0x0000002au, 0x000500c4u, 0x00000006u, + 0x00000298u, 0x00000297u, 0x0000004bu, 0x000500c5u, 0x00000006u, 0x00000299u, 0x00000294u, 0x00000298u, + 0x000500c7u, 0x00000006u, 0x0000029bu, 0x000004e8u, 0x0000002au, 0x000500c4u, 0x00000006u, 0x0000029cu, + 0x0000029bu, 0x00000041u, 0x000500c5u, 0x00000006u, 0x0000029du, 0x00000299u, 0x0000029cu, 0x000500c2u, + 0x00000006u, 0x0000029fu, 0x000004e8u, 0x00000023u, 0x000500c7u, 0x00000006u, 0x000002a0u, 0x0000029fu, + 0x0000002au, 0x000500c4u, 0x00000006u, 0x000002a1u, 0x000002a0u, 0x00000055u, 0x000500c5u, 0x00000006u, + 0x000002a2u, 0x0000029du, 0x000002a1u, 0x000500c2u, 0x00000006u, 0x000002a4u, 0x000004e7u, 0x0000004bu, + 0x000500c7u, 0x00000006u, 0x000002a5u, 0x000002a4u, 0x0000002au, 0x000500c4u, 0x00000006u, 0x000002a6u, + 0x000002a5u, 0x0000005bu, 0x000500c5u, 0x00000006u, 0x000002a7u, 0x000002a2u, 0x000002a6u, 0x000500c2u, + 0x00000006u, 0x000002a9u, 0x000004e8u, 0x0000004bu, 0x000500c7u, 0x00000006u, 0x000002aau, 0x000002a9u, + 0x0000002au, 0x000500c4u, 0x00000006u, 0x000002abu, 0x000002aau, 0x00000046u, 0x000500c5u, 0x00000006u, + 0x000002acu, 0x000002a7u, 0x000002abu, 0x000200f9u, 0x000002adu, 0x000200f8u, 0x000002adu, 0x000700f5u, + 0x00000006u, 0x00000502u, 0x00000291u, 0x0000028bu, 0x000002acu, 0x00000292u, 0x000200f9u, 0x0000032bu, + 0x000200f8u, 0x000002aeu, 0x000500aau, 0x00000035u, 0x000002b0u, 0x00000144u, 0x0000002au, 0x000300f7u, + 0x0000032au, 0x00000000u, 0x000400fau, 0x000002b0u, 0x000002b1u, 0x000002beu, 0x000200f8u, 0x000002b1u, + 0x000500c7u, 0x00000006u, 0x000002b3u, 0x000004e7u, 0x00000046u, 0x000500c4u, 0x00000006u, 0x000002b4u, + 0x000002b3u, 0x0000002au, 0x000500c7u, 0x00000006u, 0x000002b6u, 0x000004e8u, 0x00000046u, 0x000500c4u, + 0x00000006u, 0x000002b7u, 0x000002b6u, 0x00000041u, 0x000500c5u, 0x00000006u, 0x000002b8u, 0x000002b4u, + 0x000002b7u, 0x000500c2u, 0x00000006u, 0x000002bau, 0x000004e7u, 0x0000004bu, 0x000500c7u, 0x00000006u, + 0x000002bbu, 0x000002bau, 0x0000002au, 0x000500c4u, 0x00000006u, 0x000002bcu, 0x000002bbu, 0x00000046u, + 0x000500c5u, 0x00000006u, 0x000002bdu, 0x000002b8u, 0x000002bcu, 0x000200f9u, 0x0000032au, 0x000200f8u, + 0x000002beu, 0x000500aau, 0x00000035u, 0x000002c0u, 0x00000144u, 0x00000023u, 0x000300f7u, 0x00000329u, + 0x00000000u, 0x000400fau, 0x000002c0u, 0x000002c1u, 0x000002e4u, 0x000200f8u, 0x000002c1u, 0x000500aau, + 0x00000035u, 0x000002c3u, 0x00000149u, 0x00000033u, 0x000300f7u, 0x000002e3u, 0x00000000u, 0x000400fau, + 0x000002c3u, 0x000002c4u, 0x000002d1u, 0x000200f8u, 0x000002c4u, 0x000500c7u, 0x00000006u, 0x000002c6u, + 0x000004e7u, 0x0000004bu, 0x000500c4u, 0x00000006u, 0x000002c7u, 0x000002c6u, 0x00000023u, 0x000500c7u, + 0x00000006u, 0x000002c9u, 0x000004e8u, 0x00000046u, 0x000500c4u, 0x00000006u, 0x000002cau, 0x000002c9u, + 0x00000041u, 0x000500c5u, 0x00000006u, 0x000002cbu, 0x000002c7u, 0x000002cau, 0x000500c2u, 0x00000006u, + 0x000002cdu, 0x000004e7u, 0x00000023u, 0x000500c7u, 0x00000006u, 0x000002ceu, 0x000002cdu, 0x0000002au, + 0x000500c4u, 0x00000006u, 0x000002cfu, 0x000002ceu, 0x00000046u, 0x000500c5u, 0x00000006u, 0x000002d0u, + 0x000002cbu, 0x000002cfu, 0x000200f9u, 0x000002e3u, 0x000200f8u, 0x000002d1u, 0x000500c7u, 0x00000006u, + 0x000002d3u, 0x000004e7u, 0x0000004bu, 0x000500c4u, 0x00000006u, 0x000002d4u, 0x000002d3u, 0x00000023u, + 0x000500c7u, 0x00000006u, 0x000002d6u, 0x000004e8u, 0x0000004bu, 0x000500c4u, 0x00000006u, 0x000002d7u, + 0x000002d6u, 0x00000041u, 0x000500c5u, 0x00000006u, 0x000002d8u, 0x000002d4u, 0x000002d7u, 0x000500c2u, + 0x00000006u, 0x000002dau, 0x000004e7u, 0x00000023u, 0x000500c7u, 0x00000006u, 0x000002dbu, 0x000002dau, + 0x0000002au, 0x000500c4u, 0x00000006u, 0x000002dcu, 0x000002dbu, 0x0000005bu, 0x000500c5u, 0x00000006u, + 0x000002ddu, 0x000002d8u, 0x000002dcu, 0x000500c2u, 0x00000006u, 0x000002dfu, 0x000004e8u, 0x00000023u, + 0x000500c7u, 0x00000006u, 0x000002e0u, 0x000002dfu, 0x0000002au, 0x000500c4u, 0x00000006u, 0x000002e1u, + 0x000002e0u, 0x00000046u, 0x000500c5u, 0x00000006u, 0x000002e2u, 0x000002ddu, 0x000002e1u, 0x000200f9u, + 0x000002e3u, 0x000200f8u, 0x000002e3u, 0x000700f5u, 0x00000006u, 0x00000505u, 0x000002d0u, 0x000002c4u, + 0x000002e2u, 0x000002d1u, 0x000200f9u, 0x00000329u, 0x000200f8u, 0x000002e4u, 0x000500aau, 0x00000035u, + 0x000002e6u, 0x00000144u, 0x0000004bu, 0x000300f7u, 0x00000328u, 0x00000000u, 0x000400fau, 0x000002e6u, + 0x000002e7u, 0x0000030au, 0x000200f8u, 0x000002e7u, 0x000500aau, 0x00000035u, 0x000002e9u, 0x00000149u, + 0x00000033u, 0x000300f7u, 0x00000309u, 0x00000000u, 0x000400fau, 0x000002e9u, 0x000002eau, 0x000002f7u, + 0x000200f8u, 0x000002eau, 0x000500c7u, 0x00000006u, 0x000002ecu, 0x000004e7u, 0x0000002au, 0x000500c4u, + 0x00000006u, 0x000002edu, 0x000002ecu, 0x0000004bu, 0x000500c7u, 0x00000006u, 0x000002efu, 0x000004e8u, + 0x0000004bu, 0x000500c4u, 0x00000006u, 0x000002f0u, 0x000002efu, 0x00000041u, 0x000500c5u, 0x00000006u, + 0x000002f1u, 0x000002edu, 0x000002f0u, 0x000500c2u, 0x00000006u, 0x000002f3u, 0x000004e7u, 0x0000002au, + 0x000500c7u, 0x00000006u, 0x000002f4u, 0x000002f3u, 0x0000004bu, 0x000500c4u, 0x00000006u, 0x000002f5u, + 0x000002f4u, 0x0000005bu, 0x000500c5u, 0x00000006u, 0x000002f6u, 0x000002f1u, 0x000002f5u, 0x000200f9u, + 0x00000309u, 0x000200f8u, 0x000002f7u, 0x000500c7u, 0x00000006u, 0x000002f9u, 0x000004e7u, 0x0000002au, + 0x000500c4u, 0x00000006u, 0x000002fau, 0x000002f9u, 0x0000004bu, 0x000500c7u, 0x00000006u, 0x000002fcu, + 0x000004e8u, 0x0000002au, 0x000500c4u, 0x00000006u, 0x000002fdu, 0x000002fcu, 0x00000041u, 0x000500c5u, + 0x00000006u, 0x000002feu, 0x000002fau, 0x000002fdu, 0x000500c2u, 0x00000006u, 0x00000300u, 0x000004e7u, + 0x0000002au, 0x000500c7u, 0x00000006u, 0x00000301u, 0x00000300u, 0x0000004bu, 0x000500c4u, 0x00000006u, + 0x00000302u, 0x00000301u, 0x00000055u, 0x000500c5u, 0x00000006u, 0x00000303u, 0x000002feu, 0x00000302u, + 0x000500c2u, 0x00000006u, 0x00000305u, 0x000004e8u, 0x0000002au, 0x000500c7u, 0x00000006u, 0x00000306u, + 0x00000305u, 0x0000002au, 0x000500c4u, 0x00000006u, 0x00000307u, 0x00000306u, 0x00000046u, 0x000500c5u, + 0x00000006u, 0x00000308u, 0x00000303u, 0x00000307u, 0x000200f9u, 0x00000309u, 0x000200f8u, 0x00000309u, + 0x000700f5u, 0x00000006u, 0x00000507u, 0x000002f6u, 0x000002eau, 0x00000308u, 0x000002f7u, 0x000200f9u, + 0x00000328u, 0x000200f8u, 0x0000030au, 0x000500aau, 0x00000035u, 0x0000030cu, 0x00000149u, 0x00000033u, + 0x000300f7u, 0x00000327u, 0x00000000u, 0x000400fau, 0x0000030cu, 0x0000030du, 0x00000315u, 0x000200f8u, + 0x0000030du, 0x000500c7u, 0x00000006u, 0x0000030fu, 0x000004e8u, 0x0000004bu, 0x000500c4u, 0x00000006u, + 0x00000310u, 0x0000030fu, 0x00000041u, 0x000500c7u, 0x00000006u, 0x00000312u, 0x000004e7u, 0x0000004bu, + 0x000500c4u, 0x00000006u, 0x00000313u, 0x00000312u, 0x0000005bu, 0x000500c5u, 0x00000006u, 0x00000314u, + 0x00000310u, 0x00000313u, 0x000200f9u, 0x00000327u, 0x000200f8u, 0x00000315u, 0x000500c7u, 0x00000006u, + 0x00000317u, 0x000004e7u, 0x0000002au, 0x000500c4u, 0x00000006u, 0x00000318u, 0x00000317u, 0x00000041u, + 0x000500c7u, 0x00000006u, 0x0000031au, 0x000004e8u, 0x0000002au, 0x000500c4u, 0x00000006u, 0x0000031bu, + 0x0000031au, 0x00000055u, 0x000500c5u, 0x00000006u, 0x0000031cu, 0x00000318u, 0x0000031bu, 0x000500c2u, + 0x00000006u, 0x0000031eu, 0x000004e7u, 0x0000002au, 0x000500c7u, 0x00000006u, 0x0000031fu, 0x0000031eu, + 0x0000002au, 0x000500c4u, 0x00000006u, 0x00000320u, 0x0000031fu, 0x0000005bu, 0x000500c5u, 0x00000006u, + 0x00000321u, 0x0000031cu, 0x00000320u, 0x000500c2u, 0x00000006u, 0x00000323u, 0x000004e8u, 0x0000002au, + 0x000500c7u, 0x00000006u, 0x00000324u, 0x00000323u, 0x0000002au, 0x000500c4u, 0x00000006u, 0x00000325u, + 0x00000324u, 0x00000046u, 0x000500c5u, 0x00000006u, 0x00000326u, 0x00000321u, 0x00000325u, 0x000200f9u, + 0x00000327u, 0x000200f8u, 0x00000327u, 0x000700f5u, 0x00000006u, 0x00000508u, 0x00000314u, 0x0000030du, + 0x00000326u, 0x00000315u, 0x000200f9u, 0x00000328u, 0x000200f8u, 0x00000328u, 0x000700f5u, 0x00000006u, + 0x00000506u, 0x00000507u, 0x00000309u, 0x00000508u, 0x00000327u, 0x000200f9u, 0x00000329u, 0x000200f8u, + 0x00000329u, 0x000700f5u, 0x00000006u, 0x00000504u, 0x00000505u, 0x000002e3u, 0x00000506u, 0x00000328u, + 0x000200f9u, 0x0000032au, 0x000200f8u, 0x0000032au, 0x000700f5u, 0x00000006u, 0x00000503u, 0x000002bdu, + 0x000002b1u, 0x00000504u, 0x00000329u, 0x000200f9u, 0x0000032bu, 0x000200f8u, 0x0000032bu, 0x000700f5u, + 0x00000006u, 0x00000501u, 0x00000502u, 0x000002adu, 0x00000503u, 0x0000032au, 0x00050080u, 0x00000006u, + 0x0000032du, 0x00000144u, 0x0000002au, 0x000500c2u, 0x00000006u, 0x0000032eu, 0x0000032du, 0x0000002au, + 0x00050082u, 0x00000006u, 0x0000032fu, 0x00000041u, 0x0000032eu, 0x000500c2u, 0x00000006u, 0x00000331u, + 0x00000144u, 0x0000002au, 0x00050082u, 0x00000006u, 0x00000332u, 0x00000041u, 0x00000331u, 0x000500c2u, + 0x00000006u, 0x00000335u, 0x000004e8u, 0x0000032fu, 0x000500c7u, 0x00000006u, 0x00000344u, 0x00000335u, + 0x0000001eu, 0x000500c4u, 0x00000006u, 0x00000347u, 0x00000344u, 0x00000023u, 0x000500c5u, 0x00000006u, + 0x00000348u, 0x00000344u, 0x00000347u, 0x000500c7u, 0x00000006u, 0x00000349u, 0x00000348u, 0x00000026u, + 0x000500c4u, 0x00000006u, 0x0000034cu, 0x00000349u, 0x0000002au, 0x000500c5u, 0x00000006u, 0x0000034du, + 0x00000349u, 0x0000034cu, 0x000500c7u, 0x00000006u, 0x0000034eu, 0x0000034du, 0x0000002du, 0x000500c2u, + 0x00000006u, 0x00000339u, 0x000004e7u, 0x00000332u, 0x000500c7u, 0x00000006u, 0x00000353u, 0x00000339u, + 0x0000001eu, 0x000500c4u, 0x00000006u, 0x00000356u, 0x00000353u, 0x00000023u, 0x000500c5u, 0x00000006u, + 0x00000357u, 0x00000353u, 0x00000356u, 0x000500c7u, 0x00000006u, 0x00000358u, 0x00000357u, 0x00000026u, + 0x000500c4u, 0x00000006u, 0x0000035bu, 0x00000358u, 0x0000002au, 0x000500c5u, 0x00000006u, 0x0000035cu, + 0x00000358u, 0x0000035bu, 0x000500c7u, 0x00000006u, 0x0000035du, 0x0000035cu, 0x0000002du, 0x000500c4u, + 0x00000006u, 0x0000033bu, 0x0000035du, 0x0000002au, 0x000500c5u, 0x00000006u, 0x0000033cu, 0x0000034eu, + 0x0000033bu, 0x000500c4u, 0x00000006u, 0x0000033du, 0x0000033cu, 0x000000f6u, 0x000500c5u, 0x00000006u, + 0x00000340u, 0x00000501u, 0x0000033du, 0x00050080u, 0x00000006u, 0x0000027du, 0x000004e4u, 0x00000340u, + 0x000500c2u, 0x00000006u, 0x00000197u, 0x0000027du, 0x00000023u, 0x00050082u, 0x00000006u, 0x0000019au, + 0x00000144u, 0x00000023u, 0x000500c4u, 0x00000006u, 0x0000019bu, 0x0000002au, 0x0000019au, 0x00050041u, + 0x00000108u, 0x0000019eu, 0x00000105u, 0x0000019du, 0x0004003du, 0x00000006u, 0x0000019fu, 0x0000019eu, + 0x00050084u, 0x00000006u, 0x000001a3u, 0x00000171u, 0x00000175u, 0x00050080u, 0x00000006u, 0x000001a5u, + 0x000001a3u, 0x0000016eu, 0x00050084u, 0x00000006u, 0x000001a7u, 0x000001a5u, 0x0000019bu, 0x00050080u, + 0x00000006u, 0x000001a8u, 0x0000019fu, 0x000001a7u, 0x000200f9u, 0x000001aau, 0x000200f8u, 0x000001aau, + 0x000700f5u, 0x00000006u, 0x00000524u, 0x00000033u, 0x0000032bu, 0x000001c5u, 0x000001abu, 0x000500b0u, + 0x00000035u, 0x000001b1u, 0x00000524u, 0x0000019bu, 0x000400f6u, 0x000001acu, 0x000001abu, 0x00000000u, + 0x000400fau, 0x000001b1u, 0x000001abu, 0x000001acu, 0x000200f8u, 0x000001abu, 0x00050080u, 0x00000006u, + 0x000001b8u, 0x000001a8u, 0x00000524u, 0x00050080u, 0x00000006u, 0x000001bfu, 0x00000197u, 0x00000524u, + 0x00060041u, 0x000001c0u, 0x000001c1u, 0x000001bcu, 0x00000113u, 0x000001bfu, 0x0004003du, 0x00000006u, + 0x000001c2u, 0x000001c1u, 0x00060041u, 0x000001c0u, 0x000001c3u, 0x000001b5u, 0x00000113u, 0x000001b8u, + 0x0003003eu, 0x000001c3u, 0x000001c2u, 0x00050080u, 0x00000006u, 0x000001c5u, 0x00000524u, 0x0000019du, + 0x000200f9u, 0x000001aau, 0x000200f8u, 0x000001acu, 0x000200f9u, 0x00000167u, 0x000200f8u, 0x000001c6u, + 0x00050041u, 0x0000016cu, 0x000001c9u, 0x000001c8u, 0x0000002au, 0x0004003du, 0x00000006u, 0x000001cau, + 0x000001c9u, 0x00050041u, 0x0000016cu, 0x000001ccu, 0x000001cbu, 0x00000033u, 0x0004003du, 0x00000006u, + 0x000001cdu, 0x000001ccu, 0x00050084u, 0x00000006u, 0x000001ceu, 0x000001cau, 0x000001cdu, 0x00050041u, + 0x0000016cu, 0x000001cfu, 0x000001c8u, 0x00000033u, 0x0004003du, 0x00000006u, 0x000001d0u, 0x000001cfu, + 0x00050080u, 0x00000006u, 0x000001d1u, 0x000001ceu, 0x000001d0u, 0x00050084u, 0x00000006u, 0x000001d3u, + 0x000001d1u, 0x000001d2u, 0x0004003du, 0x00000006u, 0x000001d5u, 0x000001d4u, 0x00050080u, 0x00000006u, + 0x000001d6u, 0x000001d3u, 0x000001d5u, 0x000500c2u, 0x00000006u, 0x000001d9u, 0x00000041u, 0x00000144u, + 0x000500c4u, 0x00000006u, 0x000001dcu, 0x000000f6u, 0x00000144u, 0x000500c4u, 0x00000006u, 0x000001dfu, + 0x0000002au, 0x000001dcu, 0x00050082u, 0x00000006u, 0x000001e0u, 0x000001dfu, 0x0000002au, 0x00050041u, + 0x00000108u, 0x000001e2u, 0x00000105u, 0x00000173u, 0x0004003du, 0x00000006u, 0x000001e3u, 0x000001e2u, + 0x00050041u, 0x00000108u, 0x000001e4u, 0x00000105u, 0x0000017bu, 0x0004003du, 0x00000006u, 0x000001e5u, + 0x000001e4u, 0x00050084u, 0x00000006u, 0x000001e6u, 0x000001e3u, 0x000001e5u, 0x00050084u, 0x00000006u, + 0x000001eau, 0x000001d6u, 0x000001d9u, 0x000500aeu, 0x00000035u, 0x000001edu, 0x000001eau, 0x000001e6u, + 0x000300f7u, 0x000001efu, 0x00000000u, 0x000400fau, 0x000001edu, 0x000001eeu, 0x000001efu, 0x000200f8u, + 0x000001eeu, 0x000200f9u, 0x0000023eu, 0x000200f8u, 0x000001efu, 0x000200f9u, 0x000001f3u, 0x000200f8u, + 0x000001f3u, 0x000700f5u, 0x00000006u, 0x000004c9u, 0x00000033u, 0x000001efu, 0x00000234u, 0x000001f6u, + 0x000700f5u, 0x00000006u, 0x0000047au, 0x00000033u, 0x000001efu, 0x00000236u, 0x000001f6u, 0x000500b0u, + 0x00000035u, 0x000001fau, 0x0000047au, 0x000001d9u, 0x000400f6u, 0x000001f5u, 0x000001f6u, 0x00000000u, + 0x000400fau, 0x000001fau, 0x000001f4u, 0x000001f5u, 0x000200f8u, 0x000001f4u, 0x00050080u, 0x00000006u, + 0x000001feu, 0x000001eau, 0x0000047au, 0x000500aeu, 0x00000035u, 0x00000201u, 0x000001feu, 0x000001e6u, + 0x000300f7u, 0x00000203u, 0x00000000u, 0x000400fau, 0x00000201u, 0x00000202u, 0x00000203u, 0x000200f8u, + 0x00000202u, 0x000200f9u, 0x000001f5u, 0x000200f8u, 0x00000203u, 0x00050086u, 0x00000006u, 0x00000209u, + 0x000001feu, 0x000001e3u, 0x00050084u, 0x00000006u, 0x0000020fu, 0x00000209u, 0x000001e3u, 0x00050082u, + 0x00000006u, 0x00000210u, 0x000001feu, 0x0000020fu, 0x000500abu, 0x00000035u, 0x0000036au, 0x00000157u, + 0x00000033u, 0x000300f7u, 0x00000391u, 0x00000000u, 0x000400fau, 0x0000036au, 0x0000036bu, 0x00000376u, + 0x000200f8u, 0x0000036bu, 0x00050041u, 0x00000108u, 0x0000036du, 0x00000105u, 0x00000107u, 0x0004003du, + 0x00000006u, 0x0000036eu, 0x0000036du, 0x00050080u, 0x00000006u, 0x0000036fu, 0x00000210u, 0x0000036eu, + 0x00050041u, 0x00000108u, 0x00000371u, 0x00000105u, 0x0000010eu, 0x0004003du, 0x00000006u, 0x00000372u, + 0x00000371u, 0x00050080u, 0x00000006u, 0x00000373u, 0x00000209u, 0x00000372u, 0x00050041u, 0x00000108u, + 0x00000374u, 0x00000105u, 0x00000113u, 0x0004003du, 0x00000006u, 0x00000375u, 0x00000374u, 0x000200f9u, + 0x00000391u, 0x000200f8u, 0x00000376u, 0x000500c2u, 0x00000006u, 0x00000379u, 0x00000209u, 0x00000163u, + 0x00050041u, 0x00000108u, 0x0000037au, 0x00000105u, 0x0000011bu, 0x0004003du, 0x00000006u, 0x0000037bu, + 0x0000037au, 0x00050084u, 0x00000006u, 0x0000037cu, 0x00000379u, 0x0000037bu, 0x000500c2u, 0x00000006u, + 0x0000037fu, 0x00000210u, 0x0000015du, 0x00050080u, 0x00000006u, 0x00000380u, 0x0000037cu, 0x0000037fu, + 0x000500c4u, 0x00000006u, 0x00000383u, 0x0000002au, 0x0000015du, 0x00050082u, 0x00000006u, 0x00000384u, + 0x00000383u, 0x0000002au, 0x000500c7u, 0x00000006u, 0x00000385u, 0x00000210u, 0x00000384u, 0x000500c4u, + 0x00000006u, 0x00000388u, 0x0000002au, 0x00000163u, 0x00050082u, 0x00000006u, 0x00000389u, 0x00000388u, + 0x0000002au, 0x000500c7u, 0x00000006u, 0x0000038au, 0x00000209u, 0x00000389u, 0x00050041u, 0x00000108u, + 0x0000038bu, 0x00000105u, 0x00000113u, 0x0004003du, 0x00000006u, 0x0000038cu, 0x0000038bu, 0x000500c4u, + 0x00000006u, 0x0000038fu, 0x00000380u, 0x00000152u, 0x00050080u, 0x00000006u, 0x00000390u, 0x0000038cu, + 0x0000038fu, 0x000200f9u, 0x00000391u, 0x000200f8u, 0x00000391u, 0x000700f5u, 0x00000006u, 0x00000488u, + 0x00000373u, 0x0000036bu, 0x0000038au, 0x00000376u, 0x000700f5u, 0x00000006u, 0x00000487u, 0x0000036fu, + 0x0000036bu, 0x00000385u, 0x00000376u, 0x000700f5u, 0x00000006u, 0x00000484u, 0x00000375u, 0x0000036bu, + 0x00000390u, 0x00000376u, 0x000500aau, 0x00000035u, 0x000003a2u, 0x00000144u, 0x00000033u, 0x000300f7u, + 0x00000446u, 0x00000000u, 0x000400fau, 0x000003a2u, 0x000003a3u, 0x000003c9u, 0x000200f8u, 0x000003a3u, + 0x000500aau, 0x00000035u, 0x000003a5u, 0x00000149u, 0x00000033u, 0x000300f7u, 0x000003c8u, 0x00000000u, + 0x000400fau, 0x000003a5u, 0x000003a6u, 0x000003adu, 0x000200f8u, 0x000003a6u, 0x000500c7u, 0x00000006u, + 0x000003a8u, 0x00000487u, 0x0000001eu, 0x000500c7u, 0x00000006u, 0x000003aau, 0x00000488u, 0x0000001eu, + 0x000500c4u, 0x00000006u, 0x000003abu, 0x000003aau, 0x00000041u, 0x000500c5u, 0x00000006u, 0x000003acu, + 0x000003a8u, 0x000003abu, 0x000200f9u, 0x000003c8u, 0x000200f8u, 0x000003adu, 0x000500c7u, 0x00000006u, + 0x000003afu, 0x00000487u, 0x00000046u, 0x000500c2u, 0x00000006u, 0x000003b1u, 0x00000488u, 0x0000002au, + 0x000500c7u, 0x00000006u, 0x000003b2u, 0x000003b1u, 0x0000002au, 0x000500c4u, 0x00000006u, 0x000003b3u, + 0x000003b2u, 0x0000004bu, 0x000500c5u, 0x00000006u, 0x000003b4u, 0x000003afu, 0x000003b3u, 0x000500c7u, + 0x00000006u, 0x000003b6u, 0x00000488u, 0x0000002au, 0x000500c4u, 0x00000006u, 0x000003b7u, 0x000003b6u, + 0x00000041u, 0x000500c5u, 0x00000006u, 0x000003b8u, 0x000003b4u, 0x000003b7u, 0x000500c2u, 0x00000006u, + 0x000003bau, 0x00000488u, 0x00000023u, 0x000500c7u, 0x00000006u, 0x000003bbu, 0x000003bau, 0x0000002au, + 0x000500c4u, 0x00000006u, 0x000003bcu, 0x000003bbu, 0x00000055u, 0x000500c5u, 0x00000006u, 0x000003bdu, + 0x000003b8u, 0x000003bcu, 0x000500c2u, 0x00000006u, 0x000003bfu, 0x00000487u, 0x0000004bu, 0x000500c7u, + 0x00000006u, 0x000003c0u, 0x000003bfu, 0x0000002au, 0x000500c4u, 0x00000006u, 0x000003c1u, 0x000003c0u, + 0x0000005bu, 0x000500c5u, 0x00000006u, 0x000003c2u, 0x000003bdu, 0x000003c1u, 0x000500c2u, 0x00000006u, + 0x000003c4u, 0x00000488u, 0x0000004bu, 0x000500c7u, 0x00000006u, 0x000003c5u, 0x000003c4u, 0x0000002au, + 0x000500c4u, 0x00000006u, 0x000003c6u, 0x000003c5u, 0x00000046u, 0x000500c5u, 0x00000006u, 0x000003c7u, + 0x000003c2u, 0x000003c6u, 0x000200f9u, 0x000003c8u, 0x000200f8u, 0x000003c8u, 0x000700f5u, 0x00000006u, + 0x000004a2u, 0x000003acu, 0x000003a6u, 0x000003c7u, 0x000003adu, 0x000200f9u, 0x00000446u, 0x000200f8u, + 0x000003c9u, 0x000500aau, 0x00000035u, 0x000003cbu, 0x00000144u, 0x0000002au, 0x000300f7u, 0x00000445u, + 0x00000000u, 0x000400fau, 0x000003cbu, 0x000003ccu, 0x000003d9u, 0x000200f8u, 0x000003ccu, 0x000500c7u, + 0x00000006u, 0x000003ceu, 0x00000487u, 0x00000046u, 0x000500c4u, 0x00000006u, 0x000003cfu, 0x000003ceu, + 0x0000002au, 0x000500c7u, 0x00000006u, 0x000003d1u, 0x00000488u, 0x00000046u, 0x000500c4u, 0x00000006u, + 0x000003d2u, 0x000003d1u, 0x00000041u, 0x000500c5u, 0x00000006u, 0x000003d3u, 0x000003cfu, 0x000003d2u, + 0x000500c2u, 0x00000006u, 0x000003d5u, 0x00000487u, 0x0000004bu, 0x000500c7u, 0x00000006u, 0x000003d6u, + 0x000003d5u, 0x0000002au, 0x000500c4u, 0x00000006u, 0x000003d7u, 0x000003d6u, 0x00000046u, 0x000500c5u, + 0x00000006u, 0x000003d8u, 0x000003d3u, 0x000003d7u, 0x000200f9u, 0x00000445u, 0x000200f8u, 0x000003d9u, + 0x000500aau, 0x00000035u, 0x000003dbu, 0x00000144u, 0x00000023u, 0x000300f7u, 0x00000444u, 0x00000000u, + 0x000400fau, 0x000003dbu, 0x000003dcu, 0x000003ffu, 0x000200f8u, 0x000003dcu, 0x000500aau, 0x00000035u, + 0x000003deu, 0x00000149u, 0x00000033u, 0x000300f7u, 0x000003feu, 0x00000000u, 0x000400fau, 0x000003deu, + 0x000003dfu, 0x000003ecu, 0x000200f8u, 0x000003dfu, 0x000500c7u, 0x00000006u, 0x000003e1u, 0x00000487u, + 0x0000004bu, 0x000500c4u, 0x00000006u, 0x000003e2u, 0x000003e1u, 0x00000023u, 0x000500c7u, 0x00000006u, + 0x000003e4u, 0x00000488u, 0x00000046u, 0x000500c4u, 0x00000006u, 0x000003e5u, 0x000003e4u, 0x00000041u, + 0x000500c5u, 0x00000006u, 0x000003e6u, 0x000003e2u, 0x000003e5u, 0x000500c2u, 0x00000006u, 0x000003e8u, + 0x00000487u, 0x00000023u, 0x000500c7u, 0x00000006u, 0x000003e9u, 0x000003e8u, 0x0000002au, 0x000500c4u, + 0x00000006u, 0x000003eau, 0x000003e9u, 0x00000046u, 0x000500c5u, 0x00000006u, 0x000003ebu, 0x000003e6u, + 0x000003eau, 0x000200f9u, 0x000003feu, 0x000200f8u, 0x000003ecu, 0x000500c7u, 0x00000006u, 0x000003eeu, + 0x00000487u, 0x0000004bu, 0x000500c4u, 0x00000006u, 0x000003efu, 0x000003eeu, 0x00000023u, 0x000500c7u, + 0x00000006u, 0x000003f1u, 0x00000488u, 0x0000004bu, 0x000500c4u, 0x00000006u, 0x000003f2u, 0x000003f1u, + 0x00000041u, 0x000500c5u, 0x00000006u, 0x000003f3u, 0x000003efu, 0x000003f2u, 0x000500c2u, 0x00000006u, + 0x000003f5u, 0x00000487u, 0x00000023u, 0x000500c7u, 0x00000006u, 0x000003f6u, 0x000003f5u, 0x0000002au, + 0x000500c4u, 0x00000006u, 0x000003f7u, 0x000003f6u, 0x0000005bu, 0x000500c5u, 0x00000006u, 0x000003f8u, + 0x000003f3u, 0x000003f7u, 0x000500c2u, 0x00000006u, 0x000003fau, 0x00000488u, 0x00000023u, 0x000500c7u, + 0x00000006u, 0x000003fbu, 0x000003fau, 0x0000002au, 0x000500c4u, 0x00000006u, 0x000003fcu, 0x000003fbu, + 0x00000046u, 0x000500c5u, 0x00000006u, 0x000003fdu, 0x000003f8u, 0x000003fcu, 0x000200f9u, 0x000003feu, + 0x000200f8u, 0x000003feu, 0x000700f5u, 0x00000006u, 0x000004a5u, 0x000003ebu, 0x000003dfu, 0x000003fdu, + 0x000003ecu, 0x000200f9u, 0x00000444u, 0x000200f8u, 0x000003ffu, 0x000500aau, 0x00000035u, 0x00000401u, + 0x00000144u, 0x0000004bu, 0x000300f7u, 0x00000443u, 0x00000000u, 0x000400fau, 0x00000401u, 0x00000402u, + 0x00000425u, 0x000200f8u, 0x00000402u, 0x000500aau, 0x00000035u, 0x00000404u, 0x00000149u, 0x00000033u, + 0x000300f7u, 0x00000424u, 0x00000000u, 0x000400fau, 0x00000404u, 0x00000405u, 0x00000412u, 0x000200f8u, + 0x00000405u, 0x000500c7u, 0x00000006u, 0x00000407u, 0x00000487u, 0x0000002au, 0x000500c4u, 0x00000006u, + 0x00000408u, 0x00000407u, 0x0000004bu, 0x000500c7u, 0x00000006u, 0x0000040au, 0x00000488u, 0x0000004bu, + 0x000500c4u, 0x00000006u, 0x0000040bu, 0x0000040au, 0x00000041u, 0x000500c5u, 0x00000006u, 0x0000040cu, + 0x00000408u, 0x0000040bu, 0x000500c2u, 0x00000006u, 0x0000040eu, 0x00000487u, 0x0000002au, 0x000500c7u, + 0x00000006u, 0x0000040fu, 0x0000040eu, 0x0000004bu, 0x000500c4u, 0x00000006u, 0x00000410u, 0x0000040fu, + 0x0000005bu, 0x000500c5u, 0x00000006u, 0x00000411u, 0x0000040cu, 0x00000410u, 0x000200f9u, 0x00000424u, + 0x000200f8u, 0x00000412u, 0x000500c7u, 0x00000006u, 0x00000414u, 0x00000487u, 0x0000002au, 0x000500c4u, + 0x00000006u, 0x00000415u, 0x00000414u, 0x0000004bu, 0x000500c7u, 0x00000006u, 0x00000417u, 0x00000488u, + 0x0000002au, 0x000500c4u, 0x00000006u, 0x00000418u, 0x00000417u, 0x00000041u, 0x000500c5u, 0x00000006u, + 0x00000419u, 0x00000415u, 0x00000418u, 0x000500c2u, 0x00000006u, 0x0000041bu, 0x00000487u, 0x0000002au, + 0x000500c7u, 0x00000006u, 0x0000041cu, 0x0000041bu, 0x0000004bu, 0x000500c4u, 0x00000006u, 0x0000041du, + 0x0000041cu, 0x00000055u, 0x000500c5u, 0x00000006u, 0x0000041eu, 0x00000419u, 0x0000041du, 0x000500c2u, + 0x00000006u, 0x00000420u, 0x00000488u, 0x0000002au, 0x000500c7u, 0x00000006u, 0x00000421u, 0x00000420u, + 0x0000002au, 0x000500c4u, 0x00000006u, 0x00000422u, 0x00000421u, 0x00000046u, 0x000500c5u, 0x00000006u, + 0x00000423u, 0x0000041eu, 0x00000422u, 0x000200f9u, 0x00000424u, 0x000200f8u, 0x00000424u, 0x000700f5u, + 0x00000006u, 0x000004a7u, 0x00000411u, 0x00000405u, 0x00000423u, 0x00000412u, 0x000200f9u, 0x00000443u, + 0x000200f8u, 0x00000425u, 0x000500aau, 0x00000035u, 0x00000427u, 0x00000149u, 0x00000033u, 0x000300f7u, + 0x00000442u, 0x00000000u, 0x000400fau, 0x00000427u, 0x00000428u, 0x00000430u, 0x000200f8u, 0x00000428u, + 0x000500c7u, 0x00000006u, 0x0000042au, 0x00000488u, 0x0000004bu, 0x000500c4u, 0x00000006u, 0x0000042bu, + 0x0000042au, 0x00000041u, 0x000500c7u, 0x00000006u, 0x0000042du, 0x00000487u, 0x0000004bu, 0x000500c4u, + 0x00000006u, 0x0000042eu, 0x0000042du, 0x0000005bu, 0x000500c5u, 0x00000006u, 0x0000042fu, 0x0000042bu, + 0x0000042eu, 0x000200f9u, 0x00000442u, 0x000200f8u, 0x00000430u, 0x000500c7u, 0x00000006u, 0x00000432u, + 0x00000487u, 0x0000002au, 0x000500c4u, 0x00000006u, 0x00000433u, 0x00000432u, 0x00000041u, 0x000500c7u, + 0x00000006u, 0x00000435u, 0x00000488u, 0x0000002au, 0x000500c4u, 0x00000006u, 0x00000436u, 0x00000435u, + 0x00000055u, 0x000500c5u, 0x00000006u, 0x00000437u, 0x00000433u, 0x00000436u, 0x000500c2u, 0x00000006u, + 0x00000439u, 0x00000487u, 0x0000002au, 0x000500c7u, 0x00000006u, 0x0000043au, 0x00000439u, 0x0000002au, + 0x000500c4u, 0x00000006u, 0x0000043bu, 0x0000043au, 0x0000005bu, 0x000500c5u, 0x00000006u, 0x0000043cu, + 0x00000437u, 0x0000043bu, 0x000500c2u, 0x00000006u, 0x0000043eu, 0x00000488u, 0x0000002au, 0x000500c7u, + 0x00000006u, 0x0000043fu, 0x0000043eu, 0x0000002au, 0x000500c4u, 0x00000006u, 0x00000440u, 0x0000043fu, + 0x00000046u, 0x000500c5u, 0x00000006u, 0x00000441u, 0x0000043cu, 0x00000440u, 0x000200f9u, 0x00000442u, + 0x000200f8u, 0x00000442u, 0x000700f5u, 0x00000006u, 0x000004a8u, 0x0000042fu, 0x00000428u, 0x00000441u, + 0x00000430u, 0x000200f9u, 0x00000443u, 0x000200f8u, 0x00000443u, 0x000700f5u, 0x00000006u, 0x000004a6u, + 0x000004a7u, 0x00000424u, 0x000004a8u, 0x00000442u, 0x000200f9u, 0x00000444u, 0x000200f8u, 0x00000444u, + 0x000700f5u, 0x00000006u, 0x000004a4u, 0x000004a5u, 0x000003feu, 0x000004a6u, 0x00000443u, 0x000200f9u, + 0x00000445u, 0x000200f8u, 0x00000445u, 0x000700f5u, 0x00000006u, 0x000004a3u, 0x000003d8u, 0x000003ccu, + 0x000004a4u, 0x00000444u, 0x000200f9u, 0x00000446u, 0x000200f8u, 0x00000446u, 0x000700f5u, 0x00000006u, + 0x000004a1u, 0x000004a2u, 0x000003c8u, 0x000004a3u, 0x00000445u, 0x00050080u, 0x00000006u, 0x00000448u, + 0x00000144u, 0x0000002au, 0x000500c2u, 0x00000006u, 0x00000449u, 0x00000448u, 0x0000002au, 0x00050082u, + 0x00000006u, 0x0000044au, 0x00000041u, 0x00000449u, 0x000500c2u, 0x00000006u, 0x0000044cu, 0x00000144u, + 0x0000002au, 0x00050082u, 0x00000006u, 0x0000044du, 0x00000041u, 0x0000044cu, 0x000500c2u, 0x00000006u, + 0x00000450u, 0x00000488u, 0x0000044au, 0x000500c7u, 0x00000006u, 0x0000045fu, 0x00000450u, 0x0000001eu, + 0x000500c4u, 0x00000006u, 0x00000462u, 0x0000045fu, 0x00000023u, 0x000500c5u, 0x00000006u, 0x00000463u, + 0x0000045fu, 0x00000462u, 0x000500c7u, 0x00000006u, 0x00000464u, 0x00000463u, 0x00000026u, 0x000500c4u, + 0x00000006u, 0x00000467u, 0x00000464u, 0x0000002au, 0x000500c5u, 0x00000006u, 0x00000468u, 0x00000464u, + 0x00000467u, 0x000500c7u, 0x00000006u, 0x00000469u, 0x00000468u, 0x0000002du, 0x000500c2u, 0x00000006u, + 0x00000454u, 0x00000487u, 0x0000044du, 0x000500c7u, 0x00000006u, 0x0000046eu, 0x00000454u, 0x0000001eu, + 0x000500c4u, 0x00000006u, 0x00000471u, 0x0000046eu, 0x00000023u, 0x000500c5u, 0x00000006u, 0x00000472u, + 0x0000046eu, 0x00000471u, 0x000500c7u, 0x00000006u, 0x00000473u, 0x00000472u, 0x00000026u, 0x000500c4u, + 0x00000006u, 0x00000476u, 0x00000473u, 0x0000002au, 0x000500c5u, 0x00000006u, 0x00000477u, 0x00000473u, + 0x00000476u, 0x000500c7u, 0x00000006u, 0x00000478u, 0x00000477u, 0x0000002du, 0x000500c4u, 0x00000006u, + 0x00000456u, 0x00000478u, 0x0000002au, 0x000500c5u, 0x00000006u, 0x00000457u, 0x00000469u, 0x00000456u, + 0x000500c4u, 0x00000006u, 0x00000458u, 0x00000457u, 0x000000f6u, 0x000500c5u, 0x00000006u, 0x0000045bu, + 0x000004a1u, 0x00000458u, 0x00050080u, 0x00000006u, 0x00000398u, 0x00000484u, 0x0000045bu, 0x000500c2u, + 0x00000006u, 0x00000225u, 0x00000398u, 0x00000023u, 0x00060041u, 0x000001c0u, 0x00000226u, 0x000001bcu, + 0x00000113u, 0x00000225u, 0x0004003du, 0x00000006u, 0x00000227u, 0x00000226u, 0x000500c7u, 0x00000006u, + 0x00000229u, 0x00000398u, 0x0000004bu, 0x00050084u, 0x00000006u, 0x0000022au, 0x00000229u, 0x000000f6u, + 0x000500c2u, 0x00000006u, 0x0000022bu, 0x00000227u, 0x0000022au, 0x000500c7u, 0x00000006u, 0x0000022du, + 0x0000022bu, 0x000001e0u, 0x00050084u, 0x00000006u, 0x00000231u, 0x0000047au, 0x000001dcu, 0x000500c4u, + 0x00000006u, 0x00000232u, 0x0000022du, 0x00000231u, 0x000500c5u, 0x00000006u, 0x00000234u, 0x000004c9u, + 0x00000232u, 0x000200f9u, 0x000001f6u, 0x000200f8u, 0x000001f6u, 0x00050080u, 0x00000006u, 0x00000236u, + 0x0000047au, 0x0000019du, 0x000200f9u, 0x000001f3u, 0x000200f8u, 0x000001f5u, 0x00050041u, 0x00000108u, + 0x00000237u, 0x00000105u, 0x0000019du, 0x0004003du, 0x00000006u, 0x00000238u, 0x00000237u, 0x00050080u, + 0x00000006u, 0x0000023au, 0x00000238u, 0x000001d6u, 0x00060041u, 0x000001c0u, 0x0000023cu, 0x000001b5u, + 0x00000113u, 0x0000023au, 0x0003003eu, 0x0000023cu, 0x000004c9u, 0x000200f9u, 0x00000167u, 0x000200f8u, + 0x00000167u, 0x000200f9u, 0x0000023eu, 0x000200f8u, 0x0000023eu, 0x000100fdu, 0x00010038u, +}; + +inline VkDeviceSize align_up_size(VkDeviceSize value, VkDeviceSize alignment) { + if (alignment <= 1) return value; + const VkDeviceSize rem = value % alignment; + return rem ? value + (alignment - rem) : value; +} + +} // namespace detail + +class TitleDetilePipeline { +public: + using Allocate = std::function; + + TitleDetilePipeline(PFN_vkGetDeviceProcAddr get, VkDevice device, const VkPhysicalDeviceLimits& limits, + Allocate allocate) + : get_(get), device_(device), limits_(limits), allocate_(std::move(allocate)) { + load_fns(); + } + + ~TitleDetilePipeline() { release(); } + + TitleDetilePipeline(const TitleDetilePipeline&) = delete; + TitleDetilePipeline& operator=(const TitleDetilePipeline&) = delete; + + void release() { + if (!device_ || !get_) return; + for (auto& s : scratch_slots_) { + if (s->buffer && vk_.destroy_buffer) vk_.destroy_buffer(device_, s->buffer, nullptr); + if (s->memory && vk_.free_memory) vk_.free_memory(device_, s->memory, nullptr); + if (s->pool && vk_.destroy_descriptor_pool) vk_.destroy_descriptor_pool(device_, s->pool, nullptr); + } + scratch_slots_.clear(); + if (pipeline_) { + if (vk_.destroy_pipeline) vk_.destroy_pipeline(device_, pipeline_, nullptr); + pipeline_ = VK_NULL_HANDLE; + } + if (layout_) { + if (vk_.destroy_pipeline_layout) vk_.destroy_pipeline_layout(device_, layout_, nullptr); + layout_ = VK_NULL_HANDLE; + } + if (set_layout_) { + if (vk_.destroy_descriptor_set_layout) vk_.destroy_descriptor_set_layout(device_, set_layout_, nullptr); + set_layout_ = VK_NULL_HANDLE; + } + failed_ = false; + } + + // Whether a linear texture in a single TitleMirror chunk can be copied directly via vkCmdCopyBufferToImage. + static bool can_direct_linear(const TitleDetileDesc& desc, VkDeviceSize src_offset, VkDeviceSize chunk_size, + std::uint32_t image_width, std::uint32_t image_height, std::uint32_t image_depth, + std::uint32_t image_mips, std::uint32_t image_layers, bool volume) { + if (desc.mode != TitleDetileMode::linear) return false; + if (!desc.element_bytes || !std::has_single_bit(desc.element_bytes) || desc.element_bytes > 16) return false; + if (desc.block_side != 1 && desc.block_side != 4) return false; + if (desc.mips.empty() || desc.mips.size() > image_mips || !desc.array_layers || desc.array_layers > image_layers) + return false; + if (volume && desc.array_layers != 1) return false; + if (!desc.total_size || src_offset > chunk_size || desc.total_size > chunk_size - src_offset) return false; + const VkDeviceSize align = (std::max)(VkDeviceSize(4), VkDeviceSize(desc.element_bytes)); + if (src_offset % align != 0) return false; + if (volume && image_depth > 1 && (desc.slice_bytes % align) != 0) return false; + for (std::uint32_t layer = 0; layer < desc.array_layers; ++layer) { + for (std::uint32_t level = 0; level < desc.mips.size(); ++level) { + const auto& m = desc.mips[level]; + const std::uint32_t ew = (std::max)(1u, image_width >> level); + const std::uint32_t eh = (std::max)(1u, image_height >> level); + const std::uint32_t ed = volume ? (std::max)(1u, image_depth >> level) : 1u; + if (m.width_elements != (ew + desc.block_side - 1) / desc.block_side || + m.height_elements != (eh + desc.block_side - 1) / desc.block_side || + (volume && m.depth != ed)) + return false; + if (m.pitch_texels < ew || (m.pitch_texels % desc.block_side) != 0) return false; + if (volume && (m.padded_height * desc.block_side < eh)) return false; + const VkDeviceSize off = src_offset + VkDeviceSize(layer) * desc.slice_bytes + m.offset; + if (off % align != 0) return false; + if (volume && ed > 1) { + const VkDeviceSize row_stride = VkDeviceSize(m.pitch_texels / desc.block_side) * desc.element_bytes; + const VkDeviceSize mip_slice = row_stride * m.height_elements; + if (VkDeviceSize(ed - 1) > desc.total_size / (std::max)(VkDeviceSize(1), desc.slice_bytes)) + return false; + const VkDeviceSize last_slice_off = VkDeviceSize(ed - 1) * desc.slice_bytes + m.offset; + if (last_slice_off > desc.total_size || mip_slice > desc.total_size - last_slice_off) return false; + } + } + } + return true; + } + + // Builds VkBufferImageCopy regions reading linear rows directly from the TitleMirror chunk buffer. + static bool build_linear_regions(const TitleDetileDesc& desc, VkDeviceSize src_offset, std::uint32_t image_width, + std::uint32_t image_height, std::uint32_t image_depth, bool volume, + std::vector& out) { + out.clear(); + out.reserve(desc.array_layers * desc.mips.size()); + for (std::uint32_t layer = 0; layer < desc.array_layers; ++layer) { + for (std::uint32_t level = 0; level < desc.mips.size(); ++level) { + const auto& m = desc.mips[level]; + const std::uint32_t ew = (std::max)(1u, image_width >> level); + const std::uint32_t eh = (std::max)(1u, image_height >> level); + const std::uint32_t ed = volume ? (std::max)(1u, image_depth >> level) : 1u; + const VkDeviceSize row_stride = VkDeviceSize(m.pitch_texels / desc.block_side) * desc.element_bytes; + const bool per_depth_slice = + volume && ed > 1 && (desc.mips.size() > 1 || desc.slice_bytes != row_stride * m.padded_height); + if (per_depth_slice) { + // Console linear 3D stores each depth slice's full mip chain stride `desc.slice_bytes` apart, + // which exceeds one mip's `row_stride * padded_height` whenever mips > 1. + for (std::uint32_t z = 0; z < ed; ++z) { + VkBufferImageCopy copy{}; + copy.bufferOffset = src_offset + VkDeviceSize(z) * desc.slice_bytes + m.offset; + copy.bufferRowLength = m.pitch_texels; + copy.bufferImageHeight = 0u; + copy.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, level, 0u, 1u}; + copy.imageOffset = {0, 0, static_cast(z)}; + copy.imageExtent = {ew, eh, 1u}; + out.push_back(copy); + } + } else { + VkBufferImageCopy copy{}; + copy.bufferOffset = src_offset + VkDeviceSize(layer) * desc.slice_bytes + m.offset; + copy.bufferRowLength = m.pitch_texels; + copy.bufferImageHeight = volume ? m.padded_height * desc.block_side : 0u; + copy.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, level, layer, 1}; + copy.imageExtent = {ew, eh, ed}; + out.push_back(copy); + } + } + } + return !out.empty(); + } + + // Whether a swizzled 2D/2D-array texture in a single TitleMirror chunk can be detiled by the GPU compute shader. + bool can_gpu_detile(const TitleDetileDesc& desc, VkDeviceSize src_offset, VkDeviceSize chunk_size, + std::uint32_t image_width, std::uint32_t image_height, std::uint32_t image_mips, + std::uint32_t image_layers, bool volume) const { + if (volume || desc.dimension != 3) return false; // 2D / 2D-array only (3D thick falls back to CPU) + if (desc.mode != TitleDetileMode::sw_4kb_s && desc.mode != TitleDetileMode::sw_64kb_s && + desc.mode != TitleDetileMode::sw_64kb_d) + return false; + if (!desc.element_bytes || !std::has_single_bit(desc.element_bytes) || desc.element_bytes > 16) return false; + if (desc.block_side != 1 && desc.block_side != 4) return false; + if (!desc.tile_width || !std::has_single_bit(desc.tile_width) || desc.tile_width > 256 || + !desc.tile_height || !std::has_single_bit(desc.tile_height) || desc.tile_height > 256) + return false; + if (desc.mips.empty() || desc.mips.size() > image_mips || !desc.array_layers || desc.array_layers > image_layers) + return false; + if (!desc.total_size || src_offset > chunk_size || desc.total_size > chunk_size - src_offset) return false; + const VkDeviceSize align = std::max(4, desc.element_bytes); + if (src_offset % align != 0) return false; + const VkDeviceSize min_ssbo = std::max(4, limits_.minStorageBufferOffsetAlignment); + const VkDeviceSize src_pad = src_offset % min_ssbo; + if (desc.total_size > limits_.maxStorageBufferRange || + src_pad > limits_.maxStorageBufferRange - desc.total_size || + desc.total_size + src_pad > UINT32_MAX - 4u) + return false; + for (std::uint32_t level = 0; level < desc.mips.size(); ++level) { + const auto& m = desc.mips[level]; + const std::uint32_t ew = std::max(1u, image_width >> level); + const std::uint32_t eh = std::max(1u, image_height >> level); + if (!m.width_elements || !m.height_elements) return false; + if (m.width_elements != (ew + desc.block_side - 1) / desc.block_side || + m.height_elements != (eh + desc.block_side - 1) / desc.block_side) + return false; + if (!m.in_tail && (m.padded_width % desc.tile_width != 0 || m.offset % align != 0)) return false; + } + return true; + } + + // Computes tightly-packed linear destination regions in the GPU scratch buffer starting at `base_dst_offset` + // (must be aligned to max(minStorageBufferOffsetAlignment, 4 * element_bytes)). Returns total bytes consumed + // (rounded up to a multiple of 4 so uint32 writes never overrun). + static bool build_scratch_regions(const TitleDetileDesc& desc, VkDeviceSize base_dst_offset, + std::uint32_t image_width, std::uint32_t image_height, + std::vector& out, VkDeviceSize& out_end_offset) { + out.clear(); + out.reserve(desc.array_layers * desc.mips.size()); + VkDeviceSize cursor = base_dst_offset; + const VkDeviceSize align = VkDeviceSize(4u) * desc.element_bytes; + for (std::uint32_t layer = 0; layer < desc.array_layers; ++layer) { + for (std::uint32_t level = 0; level < desc.mips.size(); ++level) { + const auto& m = desc.mips[level]; + VkBufferImageCopy copy{}; + copy.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, level, layer, 1}; + copy.imageExtent = {std::max(1u, image_width >> level), std::max(1u, image_height >> level), 1u}; + copy.bufferOffset = detail::align_up_size(cursor, align); + const VkDeviceSize slice_bytes = + VkDeviceSize(m.width_elements) * m.height_elements * desc.element_bytes; + if (slice_bytes > UINT32_MAX || copy.bufferOffset > UINT64_MAX - slice_bytes) return false; + // Round end cursor up to 4 bytes so packed 1B/2B uint32 writes never overlap the next mip. + cursor = detail::align_up_size(copy.bufferOffset + slice_bytes, 4); + out.push_back(copy); + } + } + out_end_offset = cursor; + return !out.empty(); + } + + // A reusable device-local scratch buffer + descriptor pool for one submitted batch of GPU detile jobs. + struct ScratchSlot { + VkBuffer buffer = VK_NULL_HANDLE; + VkDeviceMemory memory = VK_NULL_HANDLE; + VkDeviceSize capacity = 0; + VkDescriptorPool pool = VK_NULL_HANDLE; + std::uint32_t pool_sets = 0; + std::uint64_t value = 0; // timeline semaphore value when its last batch completes; 0: idle + }; + + // Acquires an idle ScratchSlot (looking up `reached` without waiting; creates new up to kMaxScratchSlots, else + // returns nullptr so caller can wait on oldest_in_flight_scratch_value() or fall back), ensures its device-local + // scratch buffer holds `min_bytes` and its descriptor pool holds `sets_needed` sets (resetting the pool for fresh + // allocation). + static constexpr std::size_t kMaxScratchSlots = 64; + ScratchSlot* acquire_scratch(std::uint64_t reached, VkDeviceSize min_bytes, std::uint32_t sets_needed) { + if (!ensure_pipeline()) return nullptr; + ScratchSlot* chosen = nullptr; + for (auto& s : scratch_slots_) { + if (!s->value || s->value <= reached) { + s->value = 0; + if (!chosen || s->capacity >= min_bytes) { + chosen = s.get(); + if (s->capacity >= min_bytes) break; + } + } + } + if (!chosen) { + if (scratch_slots_.size() >= kMaxScratchSlots) return nullptr; + chosen = scratch_slots_.emplace_back(std::make_unique()).get(); + } + if (!prepare_scratch(*chosen, min_bytes, sets_needed)) return nullptr; + return chosen; + } + + // Smallest non-zero timeline value among currently in-flight scratch slots (0 if none are in flight). + // Waiting on this instead of the latest upload value frees a slot without draining the entire upload pipeline. + std::uint64_t oldest_in_flight_scratch_value() const noexcept { + std::uint64_t oldest = 0; + for (const auto& s : scratch_slots_) { + if (s->value && (!oldest || s->value < oldest)) oldest = s->value; + } + return oldest; + } + + // Deferred descriptor update entry for batching vkUpdateDescriptorSets across all detiled textures in a sub-batch. + struct PendingDescriptorUpdate { + VkDescriptorSet set = VK_NULL_HANDLE; + VkDescriptorBufferInfo src{}; + VkDescriptorBufferInfo dst{}; + }; + + // Flushes all queued descriptor updates for a sub-batch in a single vkUpdateDescriptorSets call. + void flush_descriptor_updates(const std::vector& updates) { + if (updates.empty() || !vk_.update_descriptor_sets) return; + batch_writes_.resize(updates.size() * 2); + for (std::size_t i = 0; i < updates.size(); ++i) { + VkWriteDescriptorSet& w0 = batch_writes_[i * 2]; + w0 = {}; + w0.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + w0.dstSet = updates[i].set; + w0.dstBinding = 0; + w0.descriptorCount = 1; + w0.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + w0.pBufferInfo = &updates[i].src; + + VkWriteDescriptorSet& w1 = batch_writes_[i * 2 + 1]; + w1 = {}; + w1.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + w1.dstSet = updates[i].set; + w1.dstBinding = 1; + w1.descriptorCount = 1; + w1.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + w1.pBufferInfo = &updates[i].dst; + } + vk_.update_descriptor_sets(device_, static_cast(batch_writes_.size()), batch_writes_.data(), 0, + nullptr); + } + + // Allocates `count` descriptor sets from `slot.pool` in a single vkAllocateDescriptorSets call. + bool allocate_descriptor_sets(ScratchSlot& slot, std::uint32_t count, std::vector& out) { + out.clear(); + if (!count) return true; + if (!ensure_pipeline() || !slot.pool || count > slot.pool_sets) return false; + batch_set_layouts_.assign(count, set_layout_); + out.resize(count, VK_NULL_HANDLE); + VkDescriptorSetAllocateInfo alloc{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; + alloc.descriptorPool = slot.pool; + alloc.descriptorSetCount = count; + alloc.pSetLayouts = batch_set_layouts_.data(); + if (vk_.allocate_descriptor_sets(device_, &alloc, out.data()) != VK_SUCCESS) { + out.clear(); + return false; + } + return true; + } + + // Prepares descriptor set and per-(layer, mip) compute dispatches for one swizzled texture into `slot`. + // `regions` must have been built by build_scratch_regions() with `dst_base` inside `slot.buffer`. + // When `pending_updates` is non-null, descriptor writes are appended for one batched flush_descriptor_updates() + // call across the sub-batch; otherwise vkUpdateDescriptorSets runs immediately. + // When `preallocated_set` is non-null (from allocate_descriptor_sets()), skips per-texture vkAllocateDescriptorSets. + bool prepare_texture(ScratchSlot& slot, VkBuffer src_buffer, VkDeviceSize src_offset, const TitleDetileDesc& desc, + VkDeviceSize dst_base, VkDeviceSize dst_end, const std::vector& regions, + std::vector& dispatches, + std::vector* pending_updates = nullptr, + VkDescriptorSet preallocated_set = VK_NULL_HANDLE) { + if (!ensure_pipeline() || !slot.buffer || !slot.pool || dst_end > slot.capacity || dst_end < dst_base) + return false; + const VkDeviceSize min_ssbo = (std::max)(VkDeviceSize(4), limits_.minStorageBufferOffsetAlignment); + const VkDeviceSize aligned_src = src_offset - (src_offset % min_ssbo); + const VkDeviceSize src_range = + detail::align_up_size((src_offset - aligned_src) + desc.total_size, 4); + const VkDeviceSize aligned_dst = dst_base - (dst_base % min_ssbo); + const VkDeviceSize dst_range = detail::align_up_size(dst_end - aligned_dst, 4); + if (src_range > limits_.maxStorageBufferRange || dst_range > limits_.maxStorageBufferRange || + dst_range > UINT32_MAX || aligned_dst + dst_range > slot.capacity) + return false; + + VkDescriptorSet set = preallocated_set; + if (set == VK_NULL_HANDLE) { + VkDescriptorSetAllocateInfo alloc{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; + alloc.descriptorPool = slot.pool; + alloc.descriptorSetCount = 1; + alloc.pSetLayouts = &set_layout_; + if (vk_.allocate_descriptor_sets(device_, &alloc, &set) != VK_SUCCESS) return false; + } + + const VkDescriptorBufferInfo src_info{src_buffer, aligned_src, src_range}; + const VkDescriptorBufferInfo dst_info{slot.buffer, aligned_dst, dst_range}; + + const std::uint32_t bpe_log2 = static_cast(std::countr_zero(desc.element_bytes)); + const std::uint32_t mode_d = desc.mode == TitleDetileMode::sw_64kb_d ? 1u : 0u; + const std::uint32_t bits16 = desc.mode == TitleDetileMode::sw_4kb_s ? 0u : 1u; + const std::uint32_t tw_log2 = static_cast(std::countr_zero(desc.tile_width)); + const std::uint32_t th_log2 = static_cast(std::countr_zero(desc.tile_height)); + + const std::uint32_t mips = static_cast(desc.mips.size()); + if (regions.size() != std::size_t(desc.array_layers) * mips) return false; + + const std::size_t disp_start = dispatches.size(); + std::size_t region_idx = 0; + for (std::uint32_t layer = 0; layer < desc.array_layers; ++layer) { + const VkDeviceSize slice_off = src_offset + VkDeviceSize(layer) * desc.slice_bytes; + for (std::uint32_t level = 0; level < mips; ++level, ++region_idx) { + const auto& m = desc.mips[level]; + const auto& copy = regions[region_idx]; + const VkDeviceSize mip_src = m.in_tail ? slice_off : slice_off + m.offset; + if (mip_src < aligned_src || mip_src - aligned_src > UINT32_MAX) { + dispatches.resize(disp_start); + return false; + } + if (copy.bufferOffset < aligned_dst || ((copy.bufferOffset - aligned_dst) & 3u) != 0) { + dispatches.resize(disp_start); + return false; + } + const VkDeviceSize dst_words = (copy.bufferOffset - aligned_dst) >> 2; + if (dst_words > UINT32_MAX) { + dispatches.resize(disp_start); + return false; + } + + TitleDetileDispatch d{}; + d.set = set; + d.push.src_base = static_cast(mip_src - aligned_src); + d.push.dst_word_base = static_cast(dst_words); + d.push.width = m.width_elements; + d.push.height = m.height_elements; + d.push.tiles_x = m.in_tail ? 0u : (m.padded_width / desc.tile_width); + d.push.tail_x = m.in_tail ? m.tail_x : 0u; + d.push.tail_y = m.in_tail ? m.tail_y : 0u; + d.push.flags = (bpe_log2 & 7u) | (mode_d << 3u) | (bits16 << 4u) | + ((m.in_tail ? 1u : 0u) << 5u) | ((tw_log2 & 0xFFu) << 6u) | + ((th_log2 & 0xFFu) << 14u); + + if (bpe_log2 >= 2u) { + d.groups_x = (m.width_elements + 7u) / 8u; + d.groups_y = (m.height_elements + 7u) / 8u; + } else { + const std::uint64_t total_bytes = + std::uint64_t(m.width_elements) * m.height_elements * desc.element_bytes; + const std::uint64_t total_words = (total_bytes + 3u) / 4u; + const std::uint64_t total_groups = (total_words + 63u) / 64u; + d.groups_x = static_cast((std::min)(total_groups, std::uint64_t(1024u))); + d.groups_y = static_cast((total_groups + d.groups_x - 1u) / d.groups_x); + } + if (d.groups_x == 0 || d.groups_y == 0 || + d.groups_x > limits_.maxComputeWorkGroupCount[0] || + d.groups_y > limits_.maxComputeWorkGroupCount[1]) { + dispatches.resize(disp_start); + return false; + } + dispatches.push_back(d); + } + } + if (pending_updates) { + pending_updates->push_back({set, src_info, dst_info}); + } else { + VkWriteDescriptorSet writes[2]{}; + writes[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + writes[0].dstSet = set; + writes[0].dstBinding = 0; + writes[0].descriptorCount = 1; + writes[0].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + writes[0].pBufferInfo = &src_info; + writes[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + writes[1].dstSet = set; + writes[1].dstBinding = 1; + writes[1].descriptorCount = 1; + writes[1].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + writes[1].pBufferInfo = &dst_info; + vk_.update_descriptor_sets(device_, 2, writes, 0, nullptr); + } + return true; + } + + // Records all compute detile dispatches in one pass (caller emits memory barriers before and after). + void emit_dispatches(VkCommandBuffer cb, const std::vector& dispatches) const { + if (dispatches.empty() || !pipeline_) return; + vk_.cmd_bind_pipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_); + VkDescriptorSet bound = VK_NULL_HANDLE; + for (const auto& d : dispatches) { + if (d.set != bound) { + vk_.cmd_bind_descriptor_sets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, layout_, 0, 1, &d.set, 0, nullptr); + bound = d.set; + } + vk_.cmd_push_constants(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(TitleDetilePush), &d.push); + vk_.cmd_dispatch(cb, d.groups_x, d.groups_y, 1); + } + } + + VkDeviceSize min_storage_alignment() const { + return (std::max)(VkDeviceSize(4), limits_.minStorageBufferOffsetAlignment); + } + +private: + struct VkFns { + PFN_vkCreateBuffer create_buffer = nullptr; + PFN_vkDestroyBuffer destroy_buffer = nullptr; + PFN_vkGetBufferMemoryRequirements get_buffer_memory_requirements = nullptr; + PFN_vkBindBufferMemory bind_buffer_memory = nullptr; + PFN_vkFreeMemory free_memory = nullptr; + PFN_vkCreateDescriptorPool create_descriptor_pool = nullptr; + PFN_vkDestroyDescriptorPool destroy_descriptor_pool = nullptr; + PFN_vkResetDescriptorPool reset_descriptor_pool = nullptr; + PFN_vkAllocateDescriptorSets allocate_descriptor_sets = nullptr; + PFN_vkUpdateDescriptorSets update_descriptor_sets = nullptr; + PFN_vkCreateShaderModule create_shader_module = nullptr; + PFN_vkDestroyShaderModule destroy_shader_module = nullptr; + PFN_vkCreateDescriptorSetLayout create_descriptor_set_layout = nullptr; + PFN_vkDestroyDescriptorSetLayout destroy_descriptor_set_layout = nullptr; + PFN_vkCreatePipelineLayout create_pipeline_layout = nullptr; + PFN_vkDestroyPipelineLayout destroy_pipeline_layout = nullptr; + PFN_vkCreateComputePipelines create_compute_pipelines = nullptr; + PFN_vkDestroyPipeline destroy_pipeline = nullptr; + PFN_vkCmdBindPipeline cmd_bind_pipeline = nullptr; + PFN_vkCmdBindDescriptorSets cmd_bind_descriptor_sets = nullptr; + PFN_vkCmdPushConstants cmd_push_constants = nullptr; + PFN_vkCmdDispatch cmd_dispatch = nullptr; + bool all_loaded = false; + }; + + void load_fns() { + if (!get_ || !device_) return; + auto load = [&](T& dst, const char* name) { + dst = reinterpret_cast(get_(device_, name)); + return dst != nullptr; + }; + bool ok = true; + ok = load(vk_.create_buffer, "vkCreateBuffer") && ok; + ok = load(vk_.destroy_buffer, "vkDestroyBuffer") && ok; + ok = load(vk_.get_buffer_memory_requirements, "vkGetBufferMemoryRequirements") && ok; + ok = load(vk_.bind_buffer_memory, "vkBindBufferMemory") && ok; + ok = load(vk_.free_memory, "vkFreeMemory") && ok; + ok = load(vk_.create_descriptor_pool, "vkCreateDescriptorPool") && ok; + ok = load(vk_.destroy_descriptor_pool, "vkDestroyDescriptorPool") && ok; + ok = load(vk_.reset_descriptor_pool, "vkResetDescriptorPool") && ok; + ok = load(vk_.allocate_descriptor_sets, "vkAllocateDescriptorSets") && ok; + ok = load(vk_.update_descriptor_sets, "vkUpdateDescriptorSets") && ok; + ok = load(vk_.create_shader_module, "vkCreateShaderModule") && ok; + ok = load(vk_.destroy_shader_module, "vkDestroyShaderModule") && ok; + ok = load(vk_.create_descriptor_set_layout, "vkCreateDescriptorSetLayout") && ok; + ok = load(vk_.destroy_descriptor_set_layout, "vkDestroyDescriptorSetLayout") && ok; + ok = load(vk_.create_pipeline_layout, "vkCreatePipelineLayout") && ok; + ok = load(vk_.destroy_pipeline_layout, "vkDestroyPipelineLayout") && ok; + ok = load(vk_.create_compute_pipelines, "vkCreateComputePipelines") && ok; + ok = load(vk_.destroy_pipeline, "vkDestroyPipeline") && ok; + ok = load(vk_.cmd_bind_pipeline, "vkCmdBindPipeline") && ok; + ok = load(vk_.cmd_bind_descriptor_sets, "vkCmdBindDescriptorSets") && ok; + ok = load(vk_.cmd_push_constants, "vkCmdPushConstants") && ok; + ok = load(vk_.cmd_dispatch, "vkCmdDispatch") && ok; + vk_.all_loaded = ok; + } + + bool ensure_pipeline() { + if (pipeline_) return true; + if (failed_) return false; + failed_ = true; + if (!vk_.all_loaded) return false; + VkDescriptorSetLayoutBinding bindings[2]{}; + bindings[0] = {0, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; + bindings[1] = {1, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; + VkDescriptorSetLayoutCreateInfo set_info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; + set_info.bindingCount = 2; + set_info.pBindings = bindings; + VkDescriptorSetLayout sl = VK_NULL_HANDLE; + VkPipelineLayout pl = VK_NULL_HANDLE; + VkShaderModule sm = VK_NULL_HANDLE; + VkPipeline pipe = VK_NULL_HANDLE; + bool ok = vk_.create_descriptor_set_layout(device_, &set_info, nullptr, &sl) == VK_SUCCESS; + const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(TitleDetilePush)}; + VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; + layout_info.setLayoutCount = 1; + layout_info.pSetLayouts = &sl; + layout_info.pushConstantRangeCount = 1; + layout_info.pPushConstantRanges = &push; + ok = ok && vk_.create_pipeline_layout(device_, &layout_info, nullptr, &pl) == VK_SUCCESS; + VkShaderModuleCreateInfo mod_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + mod_info.codeSize = sizeof(detail::kTitleDetileSpirv); + mod_info.pCode = detail::kTitleDetileSpirv; + ok = ok && vk_.create_shader_module(device_, &mod_info, nullptr, &sm) == VK_SUCCESS; + VkComputePipelineCreateInfo pipe_info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; + pipe_info.stage.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; + pipe_info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; + pipe_info.stage.module = sm; + pipe_info.stage.pName = "main"; + pipe_info.layout = pl; + ok = ok && vk_.create_compute_pipelines(device_, VK_NULL_HANDLE, 1, &pipe_info, nullptr, &pipe) == VK_SUCCESS; + if (sm) vk_.destroy_shader_module(device_, sm, nullptr); + if (!ok) { + if (pipe) vk_.destroy_pipeline(device_, pipe, nullptr); + if (pl) vk_.destroy_pipeline_layout(device_, pl, nullptr); + if (sl) vk_.destroy_descriptor_set_layout(device_, sl, nullptr); + return false; + } + set_layout_ = sl; + layout_ = pl; + pipeline_ = pipe; + failed_ = false; + return true; + } + + bool prepare_scratch(ScratchSlot& slot, VkDeviceSize min_bytes, std::uint32_t sets_needed) { + const VkDeviceSize need = detail::align_up_size((std::max)(min_bytes, VkDeviceSize(4u)), 4u); + if (need > slot.capacity) { + if (slot.buffer) vk_.destroy_buffer(device_, slot.buffer, nullptr); + if (slot.memory) vk_.free_memory(device_, slot.memory, nullptr); + slot.buffer = VK_NULL_HANDLE; + slot.memory = VK_NULL_HANDLE; + slot.capacity = 0; + + // Grow in power-of-two steps (min 4 MiB) to avoid frequent reallocation churn. + VkDeviceSize cap = (std::max)(VkDeviceSize(4ull << 20), need); + if (cap < (UINT64_MAX >> 1)) cap = std::bit_ceil(cap); + VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; + info.size = cap; + info.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT; + if (vk_.create_buffer(device_, &info, nullptr, &slot.buffer) != VK_SUCCESS) return false; + VkMemoryRequirements req{}; + vk_.get_buffer_memory_requirements(device_, slot.buffer, &req); + slot.memory = allocate_(req, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); + if (!slot.memory || vk_.bind_buffer_memory(device_, slot.buffer, slot.memory, 0) != VK_SUCCESS) { + if (slot.buffer) vk_.destroy_buffer(device_, slot.buffer, nullptr); + if (slot.memory) vk_.free_memory(device_, slot.memory, nullptr); + slot.buffer = VK_NULL_HANDLE; + slot.memory = VK_NULL_HANDLE; + return false; + } + slot.capacity = cap; + } + const std::uint32_t want_sets = (std::max)(sets_needed, std::uint32_t(64u)); + if (want_sets > slot.pool_sets) { + if (slot.pool) vk_.destroy_descriptor_pool(device_, slot.pool, nullptr); + slot.pool = VK_NULL_HANDLE; + slot.pool_sets = 0; + const std::uint32_t alloc_sets = std::bit_ceil(want_sets); + const VkDescriptorPoolSize size{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, alloc_sets * 2u}; + VkDescriptorPoolCreateInfo pool_info{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; + pool_info.maxSets = alloc_sets; + pool_info.poolSizeCount = 1; + pool_info.pPoolSizes = &size; + if (vk_.create_descriptor_pool(device_, &pool_info, nullptr, &slot.pool) != VK_SUCCESS) return false; + slot.pool_sets = alloc_sets; + } else if (slot.pool) { + if (vk_.reset_descriptor_pool(device_, slot.pool, 0) != VK_SUCCESS) return false; + } + return true; + } + + PFN_vkGetDeviceProcAddr get_ = nullptr; + VkDevice device_ = VK_NULL_HANDLE; + VkPhysicalDeviceLimits limits_{}; + Allocate allocate_; + VkFns vk_{}; + VkDescriptorSetLayout set_layout_ = VK_NULL_HANDLE; + VkPipelineLayout layout_ = VK_NULL_HANDLE; + VkPipeline pipeline_ = VK_NULL_HANDLE; + bool failed_ = false; + std::vector> scratch_slots_; + std::vector batch_set_layouts_; + std::vector batch_writes_; +}; + +} // namespace leonida diff --git a/runtime/src/vulkan_title_image_pool.h b/runtime/src/vulkan_title_image_pool.h index 94308f6871..e7d93c7a8e 100644 --- a/runtime/src/vulkan_title_image_pool.h +++ b/runtime/src/vulkan_title_image_pool.h @@ -69,13 +69,18 @@ class TitleImagePool { std::unique_ptr bind(VkDevice device, VkImage image, const VkMemoryRequirements& req, PFN_vkBindImageMemory bind_image, PFN_vkDestroyImage destroy_image, PFN_vkFreeMemory free_memory, Allocate allocate) { - constexpr VkDeviceSize largest_slot = VkDeviceSize{2} << 20; - const VkDeviceSize needed = std::max(req.size, req.alignment); + constexpr VkDeviceSize largest_slot = VkDeviceSize{8} << 20; + const VkDeviceSize needed = (std::max)(req.size, req.alignment); if (!needed || needed > largest_slot || !req.memoryTypeBits) return {}; // Eight size classes per power of two keep padding below one eighth (besides required alignment). - const VkDeviceSize quantum = std::max(req.alignment, std::max(VkDeviceSize{1}, std::bit_floor(needed) / 8)); + const VkDeviceSize quantum = (std::max)(req.alignment, (std::max)(VkDeviceSize{1}, std::bit_floor(needed) / 8)); const VkDeviceSize stride = (needed + quantum - 1) & ~(quantum - 1); - const VkDeviceSize page_size = std::min(VkDeviceSize{8} << 20, 256 * stride); + const VkDeviceSize max_page = stride > (VkDeviceSize{2} << 20) ? (VkDeviceSize{16} << 20) : (VkDeviceSize{8} << 20); + if (!stride || stride > max_page) return {}; + const VkDeviceSize max_bytes = (std::min)(max_page, 256 * stride); + const std::uint32_t capacity = static_cast(max_bytes / stride); + if (!capacity) return {}; + const VkDeviceSize page_size = stride * capacity; auto allocation = std::make_unique(); std::lock_guard lock(mutex_); auto& pages = classes_[stride]; diff --git a/runtime/test/arena_backing_test.cpp b/runtime/test/arena_backing_test.cpp new file mode 100644 index 0000000000..93271dc65a --- /dev/null +++ b/runtime/test/arena_backing_test.cpp @@ -0,0 +1,285 @@ +// leonida::ArenaBacking (src/arena_backing.h): the GPU address arena's backing blocks, with fake hooks. No GPU. +// - placement: an allocation no larger than a block never crosses one, a larger one takes whole blocks of its own; +// - binding: a block is bound by the first allocation in it and shared by the next ones; +// - unbinding: only once the release ticket has completed, and an allocation in a pending block revives it; +// - the accessor: an offset resolves to its unit's mapping in one table read, an unbacked or unit-crossing range is +// refused, offset_of() inverts it, with_host() refuses what has no memory; +// - the arena as one allocation (no sparse binding): every range resolves; +// - the bind queue choice: a sparse-only family first, else a sparse family with a queue to spare, else none. +// Driven together with the free-block map the device uses (src/arena_blocks.h), as DeviceState::arena_allocate does. +#include "../src/arena_backing.h" +#include "../src/arena_blocks.h" + +#include +#include +#include +#include +#include +#include + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +namespace { + +constexpr VkDeviceSize kMiB = 1 << 20; +constexpr VkDeviceSize kBlock = 2 * kMiB; + +// Memory the fake driver hands out: a VkDeviceMemory is a number, its mapping a vector. +struct FakeDriver { + std::map> memory; + std::uint64_t next = 1; + std::uint64_t binds = 0, unbinds = 0; + std::map bound; // resource offset -> memory (0: unbound) + bool fail_make = false; + + leonida::ArenaBackingHooks hooks() { + leonida::ArenaBackingHooks h; + h.make = [this](VkDeviceSize bytes, VkDeviceMemory& out, std::uint8_t*& host) { + if (fail_make) return false; + const std::uint64_t id = next++; + auto& bytes_of = memory[id]; + bytes_of.assign(std::size_t(bytes), 0); + out = reinterpret_cast(static_cast(id)); + host = bytes_of.data(); + return true; + }; + h.destroy = [this](VkDeviceMemory m) { memory.erase(reinterpret_cast(m)); }; + h.bind = [this](const VkSparseMemoryBind* b, std::uint32_t n) { + for (std::uint32_t i = 0; i < n; ++i) { + const auto id = reinterpret_cast(b[i].memory); + if (id) { + ++binds; + bound[b[i].resourceOffset] = id; + } else { + ++unbinds; + bound.erase(b[i].resourceOffset); + } + } + return true; + }; + return h; + } +}; + +// DeviceState::arena_allocate's steps: footprint, alignment, the keep-out, the block map, then acquire. +bool allocate(leonida::ArenaBlocks& blocks, leonida::ArenaBacking& backing, VkDeviceSize asked, VkDeviceSize alignment, + VkDeviceSize& out) { + const VkDeviceSize bytes = backing.footprint(asked); + if (!blocks.allocate(bytes, backing.alignment(asked, alignment), + [&](std::uint64_t lo, std::uint64_t hi) { return backing.keep_out(lo, hi); }, out)) + return false; + if (backing.acquire(out, bytes)) return true; + blocks.release(out, bytes); + return false; +} +void release(leonida::ArenaBlocks& blocks, leonida::ArenaBacking& backing, VkDeviceSize offset, VkDeviceSize asked, + std::uint64_t ticket) { + const VkDeviceSize bytes = backing.footprint(asked); + if (blocks.release(offset, bytes) == leonida::ArenaBlocks::Fault::none) backing.release(offset, bytes, ticket); +} + +int placement_and_binding() { + FakeDriver driver; + leonida::ArenaBacking backing; + EXPECT(backing.init_sparse(64 * kMiB, kBlock, driver.hooks())); + leonida::ArenaBlocks blocks; + blocks.reset(0x10000, 64 * kMiB); + EXPECT(backing.acquire(0, 0x10000, true)); // the head (zero page, quad indices) + EXPECT(backing.stats().bound == kBlock && driver.binds == 1); + + // Small allocations share the head's block, then move to the next block rather than cross into it. + VkDeviceSize a = 0, b = 0, c = 0; + EXPECT(allocate(blocks, backing, 1 * kMiB, 256, a)); + EXPECT(a == 0x10000 && driver.binds == 1); + EXPECT(allocate(blocks, backing, 1 * kMiB, 256, b)); // [0x110000, +1 MiB) would cross 2 MiB + EXPECT(b == kBlock && driver.binds == 2); + EXPECT(allocate(blocks, backing, 512 * 1024, 256, c)); + EXPECT(c == a + kMiB && driver.binds == 2); // first fit: the rest of the head's block + EXPECT(backing.stats().bound == 2 * kBlock); + + // The accessor: each allocation is one contiguous run of one mapping; a range that crosses units is refused. + std::uint8_t* pa = backing.host(a, kMiB); + std::uint8_t* pb = backing.host(b, kMiB); + std::uint8_t* pc = backing.host(c, 512 * 1024); + EXPECT(pa && pb && pc && pc == pa + kMiB); + std::memset(pb, 0xab, std::size_t(kMiB)); // writable through its whole length + EXPECT(!backing.host(kBlock - 16, 32)); // crosses from the head's unit into b's + EXPECT(!backing.host(8 * kMiB, 4)); // nothing there + EXPECT(!backing.host(64 * kMiB - 4, 8)); // past the arena + std::uint64_t back = 0; + EXPECT(backing.offset_of(pc + 100, 16, back) && back == c + 100); + EXPECT(!backing.offset_of(&back, 8, back)); + bool called = false; + EXPECT(!backing.with_host(8 * kMiB, 4, [&](std::uint8_t*) { called = true; }) && !called); + EXPECT(backing.with_host(c, 4, [&](std::uint8_t* p) { called = p == pc; }) && called); + leonida::ArenaBacking::Location where; + EXPECT(backing.locate(c, 4096, where) && where.memory_offset == c && where.host == pc); + + // Larger than a block: whole blocks of its own, block-aligned, and nothing else lands in them. + VkDeviceSize big = 0, after = 0; + EXPECT(allocate(blocks, backing, 5 * kMiB, 256, big)); + EXPECT(big % kBlock == 0 && backing.stats().bound == 2 * kBlock + 6 * kMiB && driver.binds == 3); + EXPECT(backing.host(big, 5 * kMiB) != nullptr); + EXPECT(allocate(blocks, backing, 4096, 256, after)); + EXPECT(after >= big + 6 * kMiB || after < big); + return 0; +} + +int unbinding_waits_for_the_ticket() { + FakeDriver driver; + leonida::ArenaBacking backing; + EXPECT(backing.init_sparse(64 * kMiB, kBlock, driver.hooks())); + leonida::ArenaBlocks blocks; + blocks.reset(0x10000, 64 * kMiB); + EXPECT(backing.acquire(0, 0x10000, true)); + VkDeviceSize a = 0, b = 0; + EXPECT(allocate(blocks, backing, 3 * kMiB, 256, a)); // a unit of two blocks + EXPECT(allocate(blocks, backing, 64 * 1024, 256, b)); // in the head's block + const VkDeviceSize bound = backing.stats().bound; + EXPECT(bound == kBlock + 4 * kMiB); + + // Released while submission 7 may still use it: pending, still bound, still mapped. + release(blocks, backing, a, 3 * kMiB, 7); + release(blocks, backing, b, 64 * 1024, 7); // the head is permanent: never pending + EXPECT(backing.has_pending()); + EXPECT(backing.reclaim(6) == 0); + EXPECT(backing.stats().bound == bound && driver.unbinds == 0 && backing.host(a, 4) != nullptr); + // A small allocation may not land in a pending unit of several blocks (it would keep 4 MiB bound). + VkDeviceSize small = 0; + EXPECT(allocate(blocks, backing, 4096, 4096, small)); + EXPECT(small < a || small >= a + 4 * kMiB); + // Submission 7 has completed: unbound, then freed; the accessor refuses it. + EXPECT(backing.reclaim(7) == 4 * kMiB); + EXPECT(driver.unbinds == 1 && backing.stats().bound == kBlock && !backing.host(a, 4) && !backing.has_pending()); + EXPECT(driver.memory.size() == 1); // only the head's memory is left + + // A pending single block revived by the next allocation in it: not unbound, not bound again. + VkDeviceSize c = 0, d = 0; + EXPECT(allocate(blocks, backing, 64 * 1024, 256, c)); + EXPECT(allocate(blocks, backing, kBlock - 4096, 256, d)); + const std::uint64_t binds = driver.binds; + release(blocks, backing, d, kBlock - 4096, 9); + EXPECT(backing.has_pending()); + VkDeviceSize e = 0; + EXPECT(allocate(blocks, backing, kBlock - 4096, 4096, e)); + EXPECT(e >> 21 == d >> 21 && driver.binds == binds && !backing.has_pending()); + EXPECT(backing.reclaim(100) == 0 && driver.unbinds == 1 && backing.host(e, 4) != nullptr); + return 0; +} + +// Many allocations of mixed sizes and frees: no allocation ever crosses a unit, and the bound bytes stay within the +// blocks the live allocations touch. +int random_workload() { + FakeDriver driver; + leonida::ArenaBacking backing; + constexpr VkDeviceSize size = 512 * kMiB; + EXPECT(backing.init_sparse(size, kBlock, driver.hooks())); + leonida::ArenaBlocks blocks; + blocks.reset(0x10000, size); + EXPECT(backing.acquire(0, 0x10000, true)); + std::mt19937_64 rng(12345); + struct Live { VkDeviceSize offset, bytes; }; + std::vector live; + std::uint64_t ticket = 1; + for (int step = 0; step < 20000; ++step) { + if (live.size() < 400 && (rng() % 3 || live.empty())) { + // Mostly small (as measured: most arena allocations are below 256 KiB), some larger than a block. + VkDeviceSize bytes = rng() % 10 ? 256 + rng() % (256 * 1024) : kBlock + rng() % (6 * kMiB); + VkDeviceSize at = 0; + if (!allocate(blocks, backing, bytes, 256, at)) continue; + EXPECT(backing.host(at, bytes) != nullptr); + live.push_back({at, bytes}); + } else { + const std::size_t i = std::size_t(rng() % live.size()); + release(blocks, backing, live[i].offset, live[i].bytes, ticket); + live[i] = live.back(); + live.pop_back(); + } + if (step % 50 == 0) backing.reclaim(ticket++ - 1); + } + backing.reclaim(ticket); + std::map touched; + touched[0] = true; // the head + for (const auto& l : live) { + EXPECT(backing.host(l.offset, l.bytes) != nullptr); + const VkDeviceSize footprint = backing.footprint(l.bytes); + for (VkDeviceSize at = l.offset >> 21; at <= (l.offset + footprint - 1) >> 21; ++at) touched[at] = true; + } + EXPECT(backing.stats().bound == VkDeviceSize(touched.size()) * kBlock); + EXPECT(backing.stats().bound < size); // not the whole arena: only the blocks live allocations touch + std::fprintf(stderr, "random workload: %zu live allocations, %llu MiB bound of %llu, %llu binds, %llu unbind " + "batches\n", + live.size(), (unsigned long long)(backing.stats().bound >> 20), (unsigned long long)(size >> 20), + (unsigned long long)driver.binds, (unsigned long long)backing.stats().unbinds); + return 0; +} + +// A failed bind refuses the allocation and leaves nothing behind. +int bind_failure() { + FakeDriver driver; + leonida::ArenaBacking backing; + EXPECT(backing.init_sparse(16 * kMiB, kBlock, driver.hooks())); + leonida::ArenaBlocks blocks; + blocks.reset(0x10000, 16 * kMiB); + driver.fail_make = true; + VkDeviceSize at = 0; + EXPECT(!allocate(blocks, backing, 4096, 256, at)); + EXPECT(blocks.free_bytes() == 16 * kMiB - 0x10000 && backing.stats().bound == 0); + return 0; +} + +// Without sparse binding: one unit over the whole arena, everything resolves, nothing is rounded or bound. +int one_allocation() { + std::vector memory(std::size_t(8 * kMiB)); + leonida::ArenaBacking backing; + backing.init_fixed(8 * kMiB, VK_NULL_HANDLE, memory.data()); + EXPECT(!backing.sparse() && backing.footprint(5 * kMiB) == 5 * kMiB && backing.alignment(5 * kMiB, 256) == 256); + EXPECT(backing.keep_out(kBlock - 16, kBlock + 16) == 0 && backing.placeable(kBlock - 16, 32)); + EXPECT(backing.acquire(kBlock - 16, 32)); + EXPECT(backing.host(kBlock - 16, 32) == memory.data() + kBlock - 16); + EXPECT(backing.host(0, 8 * kMiB) == memory.data() && !backing.host(0, 8 * kMiB + 1)); + std::uint64_t back = 0; + EXPECT(backing.offset_of(memory.data() + 77, 4, back) && back == 77); + EXPECT(backing.stats().bound == 8 * kMiB); + return 0; +} + +int bind_queue_choice() { + const std::uint32_t none[5] = {}; + // RADV (RX 7900 XTX, iGPU): graphics, compute, two video families and a sparse-only one. + const VkQueueFamilyProperties radv[5] = { + {VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT | VK_QUEUE_TRANSFER_BIT | VK_QUEUE_SPARSE_BINDING_BIT, 1, 64, {1, 1, 1}}, + {VK_QUEUE_COMPUTE_BIT | VK_QUEUE_TRANSFER_BIT | VK_QUEUE_SPARSE_BINDING_BIT, 4, 64, {1, 1, 1}}, + {0x20, 1, 64, {1, 1, 1}}, {0x40, 1, 64, {1, 1, 1}}, + {VK_QUEUE_SPARSE_BINDING_BIT, 1, 64, {1, 1, 1}}}; + auto q = leonida::pick_arena_bind_queue(radv, 5, none, 16); + EXPECT(q.family == 4 && q.index == 0); + // No sparse-only family: a queue to spare in a sparse family, after the ones the device takes. + const std::uint32_t used[2] = {1, 2}; + q = leonida::pick_arena_bind_queue(radv, 2, used, 16); + EXPECT(q.family == 1 && q.index == 2); + // llvmpipe: one family with one queue, already the device's: none (the arena stays one allocation). + const VkQueueFamilyProperties lvp[1] = { + {VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT | VK_QUEUE_TRANSFER_BIT | VK_QUEUE_SPARSE_BINDING_BIT, 1, 64, {1, 1, 1}}}; + const std::uint32_t one[1] = {1}; + EXPECT(leonida::pick_arena_bind_queue(lvp, 1, one, 16).family == UINT32_MAX); + // No sparse binding anywhere: none. + const VkQueueFamilyProperties plain[1] = {{VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT, 4, 64, {1, 1, 1}}}; + EXPECT(leonida::pick_arena_bind_queue(plain, 1, none, 16).family == UINT32_MAX); + return 0; +} + +} // namespace + +int main() { + if (int r = placement_and_binding()) return r; + if (int r = unbinding_waits_for_the_ticket()) return r; + if (int r = random_workload()) return r; + if (int r = bind_failure()) return r; + if (int r = one_allocation()) return r; + if (int r = bind_queue_choice()) return r; + std::fprintf(stderr, "arena_backing: ok\n"); + return 0; +} diff --git a/runtime/test/arena_sparse_gpu_test.cpp b/runtime/test/arena_sparse_gpu_test.cpp new file mode 100644 index 0000000000..bb05d05127 --- /dev/null +++ b/runtime/test/arena_sparse_gpu_test.cpp @@ -0,0 +1,389 @@ +// The GPU address arena's backing blocks on a real device (src/arena_backing.h): a sparse arena of 256 MiB with +// 40 MiB allocated has about 40 MiB bound; what the CPU writes through the blocks' mappings is what the GPU reads at +// those arena offsets; a block whose allocations are all released stays bound while a submission that read it is +// in flight, and is unbound (reading zero) only once that submission has completed. A bind made while the work queue +// is blocked completes: the arena binds on a queue of its own. No shaders, no game data. +// Exit code 77 (skipped) on a device without sparse buffers, without residencyNonResidentStrict, or without a queue +// to spare for the binds: the runtime keeps one allocation behind its arena there. LEONIDA_VK_VALIDATION=1 runs it +// under VK_LAYER_KHRONOS_validation. +#define VK_NO_PROTOTYPES +#include "../src/arena_backing.h" +#include "../src/arena_blocks.h" + +#include +#include +#include +#include +#ifdef _WIN32 +#include +#else +#include +#endif + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +namespace { + +constexpr VkDeviceSize kMiB = 1 << 20; +constexpr VkDeviceSize kArena = 256 * kMiB; +constexpr VkDeviceSize kHead = 64 * 1024; + +#define FUNCTIONS(X) \ + X(vkEnumeratePhysicalDevices) X(vkGetPhysicalDeviceProperties) X(vkGetPhysicalDeviceFeatures2) \ + X(vkGetPhysicalDeviceQueueFamilyProperties) X(vkGetPhysicalDeviceMemoryProperties) X(vkCreateDevice) \ + X(vkDestroyInstance) +#define DEVICE_FUNCTIONS(X) \ + X(vkDestroyDevice) X(vkGetDeviceQueue) X(vkCreateBuffer) X(vkDestroyBuffer) X(vkGetBufferMemoryRequirements) \ + X(vkAllocateMemory) X(vkFreeMemory) X(vkMapMemory) X(vkBindBufferMemory) X(vkQueueBindSparse) \ + X(vkQueueWaitIdle) X(vkCreateCommandPool) X(vkDestroyCommandPool) X(vkAllocateCommandBuffers) \ + X(vkBeginCommandBuffer) X(vkEndCommandBuffer) X(vkCmdCopyBuffer) X(vkQueueSubmit) X(vkCreateSemaphore) \ + X(vkDestroySemaphore) X(vkSignalSemaphore) X(vkWaitSemaphores) X(vkGetSemaphoreCounterValue) \ + X(vkDeviceWaitIdle) X(vkResetCommandBuffer) +#define DECLARE(name) PFN_##name name = nullptr; +FUNCTIONS(DECLARE) +DEVICE_FUNCTIONS(DECLARE) +#undef DECLARE + +struct Run { + VkInstance instance = VK_NULL_HANDLE; + VkDevice device = VK_NULL_HANDLE; + ~Run() { + if (device) { + vkDeviceWaitIdle(device); + vkDestroyDevice(device, nullptr); + } + if (instance) vkDestroyInstance(instance, nullptr); + } +}; + +int test() { +#ifdef _WIN32 + HMODULE library = LoadLibraryA("vulkan-1.dll"); + auto get_instance = library ? reinterpret_cast( + reinterpret_cast(GetProcAddress(library, "vkGetInstanceProcAddr"))) + : nullptr; +#else + void* library = dlopen("libvulkan.so.1", RTLD_NOW); + auto get_instance = + library ? reinterpret_cast(dlsym(library, "vkGetInstanceProcAddr")) : nullptr; +#endif + if (!get_instance) { + std::puts("SKIP: no Vulkan loader"); + return 77; + } + Run run; + auto create_instance = reinterpret_cast(get_instance(nullptr, "vkCreateInstance")); + VkApplicationInfo app{VK_STRUCTURE_TYPE_APPLICATION_INFO}; + app.apiVersion = VK_API_VERSION_1_2; + VkInstanceCreateInfo instance_info{VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; + instance_info.pApplicationInfo = &app; + const char* layer = "VK_LAYER_KHRONOS_validation"; + const char* validation = std::getenv("LEONIDA_VK_VALIDATION"); + if (validation && *validation == '1') { + instance_info.enabledLayerCount = 1; + instance_info.ppEnabledLayerNames = &layer; + } + if (!create_instance || create_instance(&instance_info, nullptr, &run.instance) != VK_SUCCESS) { + std::puts("SKIP: no Vulkan instance"); + return 77; + } +#define LOAD(name) name = reinterpret_cast(get_instance(run.instance, #name)); + FUNCTIONS(LOAD) +#undef LOAD + std::uint32_t count = 1; + VkPhysicalDevice physical = VK_NULL_HANDLE; + vkEnumeratePhysicalDevices(run.instance, &count, &physical); // the first: as the loader orders them + if (!physical) { + std::puts("SKIP: no Vulkan device"); + return 77; + } + VkPhysicalDeviceProperties properties{}; + vkGetPhysicalDeviceProperties(physical, &properties); + VkPhysicalDeviceVulkan12Features v12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; + VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &v12}; + vkGetPhysicalDeviceFeatures2(physical, &features); + std::fprintf(stderr, "device: %s (driver 0x%x)\n", properties.deviceName, properties.driverVersion); + if (!features.features.sparseBinding || !features.features.sparseResidencyBuffer || + !properties.sparseProperties.residencyNonResidentStrict || !v12.timelineSemaphore || + !v12.bufferDeviceAddress || properties.limits.sparseAddressSpaceSize < kArena) { + std::puts("SKIP: no sparse buffers with strict residency on this device (the arena stays one allocation)"); + return 77; + } + std::uint32_t family_count = 0; + vkGetPhysicalDeviceQueueFamilyProperties(physical, &family_count, nullptr); + std::vector families(family_count); + vkGetPhysicalDeviceQueueFamilyProperties(physical, &family_count, families.data()); + std::uint32_t work = UINT32_MAX; + for (std::uint32_t f = 0; f < family_count && work == UINT32_MAX; ++f) + if (families[f].queueFlags & VK_QUEUE_COMPUTE_BIT) work = f; + if (work == UINT32_MAX) { + std::puts("SKIP: no compute queue"); + return 77; + } + std::vector used(family_count, 0); + used[work] = 1; + const auto bind_queue = leonida::pick_arena_bind_queue(families.data(), family_count, used.data(), 16); + if (bind_queue.family == UINT32_MAX) { + std::puts("SKIP: no queue to spare for the arena's binds (the runtime keeps one allocation)"); + return 77; + } + std::fprintf(stderr, "work queue family %u, bind queue family %u index %u\n", work, bind_queue.family, + bind_queue.index); + const float priorities[2] = {1.0f, 1.0f}; + VkDeviceQueueCreateInfo queues[2] = {{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}, {VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}}; + queues[0].queueFamilyIndex = work; + queues[0].queueCount = bind_queue.family == work ? 2 : 1; + queues[0].pQueuePriorities = priorities; + queues[1].queueFamilyIndex = bind_queue.family; + queues[1].queueCount = 1; + queues[1].pQueuePriorities = priorities; + VkPhysicalDeviceVulkan12Features enable12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; + enable12.timelineSemaphore = VK_TRUE; + enable12.bufferDeviceAddress = VK_TRUE; + VkPhysicalDeviceFeatures2 enable{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &enable12}; + enable.features.sparseBinding = VK_TRUE; + enable.features.sparseResidencyBuffer = VK_TRUE; + VkDeviceCreateInfo device_info{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, &enable}; + device_info.queueCreateInfoCount = bind_queue.family == work ? 1 : 2; + device_info.pQueueCreateInfos = queues; + EXPECT(vkCreateDevice(physical, &device_info, nullptr, &run.device) == VK_SUCCESS); + auto get_device = reinterpret_cast(get_instance(run.instance, "vkGetDeviceProcAddr")); +#define LOAD(name) name = reinterpret_cast(get_device(run.device, #name)); + DEVICE_FUNCTIONS(LOAD) +#undef LOAD + const VkDevice device = run.device; + VkQueue work_queue = VK_NULL_HANDLE, binds = VK_NULL_HANDLE; + vkGetDeviceQueue(device, work, 0, &work_queue); + vkGetDeviceQueue(device, bind_queue.family, bind_queue.index, &binds); + + // The arena's buffer as the runtime makes it, sparse. + VkBufferCreateInfo arena_info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; + arena_info.flags = VK_BUFFER_CREATE_SPARSE_BINDING_BIT | VK_BUFFER_CREATE_SPARSE_RESIDENCY_BIT; + arena_info.size = kArena; + arena_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | + VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | + VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT | + VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; + VkBuffer arena = VK_NULL_HANDLE; + EXPECT(vkCreateBuffer(device, &arena_info, nullptr, &arena) == VK_SUCCESS); + VkMemoryRequirements requirements{}; + vkGetBufferMemoryRequirements(device, arena, &requirements); + EXPECT(leonida::kArenaBlockBytes % requirements.alignment == 0); + VkPhysicalDeviceMemoryProperties memory{}; + vkGetPhysicalDeviceMemoryProperties(physical, &memory); + const auto pick_type = [&](std::uint32_t bits) { + const VkMemoryPropertyFlags host = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; + for (const VkMemoryPropertyFlags want : {host | VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, host}) + for (std::uint32_t t = 0; t < memory.memoryTypeCount; ++t) + if ((bits >> t & 1) && (memory.memoryTypes[t].propertyFlags & want) == want) return t; + return UINT32_MAX; + }; + const std::uint32_t type = pick_type(requirements.memoryTypeBits); + EXPECT(type != UINT32_MAX); + + std::uint64_t memory_objects = 0; + leonida::ArenaBackingHooks hooks; + hooks.make = [&](VkDeviceSize bytes, VkDeviceMemory& out, std::uint8_t*& host) { + VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO}; + flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; + VkMemoryAllocateInfo allocate{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, &flags}; + allocate.allocationSize = bytes; + allocate.memoryTypeIndex = type; + void* mapped = nullptr; + if (vkAllocateMemory(device, &allocate, nullptr, &out) != VK_SUCCESS) return false; + if (vkMapMemory(device, out, 0, VK_WHOLE_SIZE, 0, &mapped) != VK_SUCCESS) { + vkFreeMemory(device, out, nullptr); + return false; + } + host = static_cast(mapped); + ++memory_objects; + return true; + }; + hooks.destroy = [&](VkDeviceMemory m) { + vkFreeMemory(device, m, nullptr); + --memory_objects; + }; + hooks.bind = [&](const VkSparseMemoryBind* b, std::uint32_t n) { + const VkSparseBufferMemoryBindInfo buffer{arena, n, b}; + VkBindSparseInfo info{VK_STRUCTURE_TYPE_BIND_SPARSE_INFO}; + info.bufferBindCount = 1; + info.pBufferBinds = &buffer; + return vkQueueBindSparse(binds, 1, &info, VK_NULL_HANDLE) == VK_SUCCESS && vkQueueWaitIdle(binds) == VK_SUCCESS; + }; + leonida::ArenaBacking backing; + EXPECT(backing.init_sparse(kArena, leonida::kArenaBlockBytes, std::move(hooks))); + leonida::ArenaBlocks blocks; + blocks.reset(kHead, kArena); + EXPECT(backing.acquire(0, kHead, true)); + const auto allocate = [&](VkDeviceSize asked, VkDeviceSize& out) { + const VkDeviceSize bytes = backing.footprint(asked); + if (!blocks.allocate(bytes, backing.alignment(asked, 256), + [&](std::uint64_t lo, std::uint64_t hi) { return backing.keep_out(lo, hi); }, out)) + return false; + if (backing.acquire(out, bytes)) return true; + blocks.release(out, bytes); + return false; + }; + + // 40 MiB allocated: 100 of 256 KiB and 3 of 5 MiB. + struct Live { VkDeviceSize offset, bytes; }; + std::vector live; + for (int i = 0; i < 100; ++i) { + VkDeviceSize at = 0; + EXPECT(allocate(256 * 1024, at)); + live.push_back({at, 256 * 1024}); + } + for (int i = 0; i < 3; ++i) { + VkDeviceSize at = 0; + EXPECT(allocate(5 * kMiB, at)); + live.push_back({at, 5 * kMiB}); + } + const VkDeviceSize allocated = 40 * kMiB; + const VkDeviceSize bound = backing.stats().bound; + std::fprintf(stderr, "arena %llu MiB, %llu MiB allocated, %llu MiB bound in %llu memory objects\n", + (unsigned long long)(kArena >> 20), (unsigned long long)(allocated >> 20), + (unsigned long long)(bound >> 20), (unsigned long long)memory_objects); + // About what is allocated: the small ones pack into whole blocks, the large ones round up to whole blocks. + EXPECT(bound >= allocated && bound <= allocated + 6 * kMiB); + + // The CPU writes through the blocks' mappings; the GPU reads the same bytes at the arena offsets. + const Live small = live[37], large = live[101]; + for (const Live& l : {small, large}) { + auto* words = reinterpret_cast(backing.host(l.offset, l.bytes)); + EXPECT(words != nullptr); + for (VkDeviceSize i = 0; i < l.bytes / 4; ++i) words[i] = std::uint32_t(l.offset / 4 + i) ^ 0x5a5a5a5au; + } + VkBufferCreateInfo readback_info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; + readback_info.size = 2 * 4096; + readback_info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT; + VkBuffer readback = VK_NULL_HANDLE; + EXPECT(vkCreateBuffer(device, &readback_info, nullptr, &readback) == VK_SUCCESS); + VkMemoryRequirements readback_requirements{}; + vkGetBufferMemoryRequirements(device, readback, &readback_requirements); + VkMemoryAllocateInfo readback_allocate{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; + readback_allocate.allocationSize = readback_requirements.size; + readback_allocate.memoryTypeIndex = pick_type(readback_requirements.memoryTypeBits); + VkDeviceMemory readback_memory = VK_NULL_HANDLE; + EXPECT(vkAllocateMemory(device, &readback_allocate, nullptr, &readback_memory) == VK_SUCCESS); + EXPECT(vkBindBufferMemory(device, readback, readback_memory, 0) == VK_SUCCESS); + void* readback_host = nullptr; + EXPECT(vkMapMemory(device, readback_memory, 0, VK_WHOLE_SIZE, 0, &readback_host) == VK_SUCCESS); + auto* got = static_cast(readback_host); + + VkCommandPoolCreateInfo pool_info{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; + pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; + pool_info.queueFamilyIndex = work; + VkCommandPool pool = VK_NULL_HANDLE; + EXPECT(vkCreateCommandPool(device, &pool_info, nullptr, &pool) == VK_SUCCESS); + VkCommandBufferAllocateInfo command_info{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; + command_info.commandPool = pool; + command_info.commandBufferCount = 1; + VkCommandBuffer commands = VK_NULL_HANDLE; + EXPECT(vkAllocateCommandBuffers(device, &command_info, &commands) == VK_SUCCESS); + VkSemaphoreTypeCreateInfo timeline{VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO}; + timeline.semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE; + VkSemaphoreCreateInfo semaphore_info{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, &timeline}; + VkSemaphore gate = VK_NULL_HANDLE, done = VK_NULL_HANDLE; // the host opens gate; done is the retire ticket + EXPECT(vkCreateSemaphore(device, &semaphore_info, nullptr, &gate) == VK_SUCCESS); + EXPECT(vkCreateSemaphore(device, &semaphore_info, nullptr, &done) == VK_SUCCESS); + const auto record_copies = [&]() { + vkResetCommandBuffer(commands, 0); + VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; + vkBeginCommandBuffer(commands, &begin); + const VkBufferCopy copies[2] = {{small.offset, 0, 4096}, {large.offset + 3 * kMiB, 4096, 4096}}; + vkCmdCopyBuffer(commands, arena, readback, 2, copies); + return vkEndCommandBuffer(commands) == VK_SUCCESS; + }; + const auto submit = [&](std::uint64_t wait, std::uint64_t signal) { + VkTimelineSemaphoreSubmitInfo values{VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO}; + values.waitSemaphoreValueCount = wait ? 1 : 0; + values.pWaitSemaphoreValues = &wait; + values.signalSemaphoreValueCount = 1; + values.pSignalSemaphoreValues = &signal; + const VkPipelineStageFlags stage = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; + VkSubmitInfo info{VK_STRUCTURE_TYPE_SUBMIT_INFO, &values}; + info.waitSemaphoreCount = wait ? 1 : 0; + info.pWaitSemaphores = &gate; + info.pWaitDstStageMask = &stage; + info.commandBufferCount = 1; + info.pCommandBuffers = &commands; + info.signalSemaphoreCount = 1; + info.pSignalSemaphores = &done; + return vkQueueSubmit(work_queue, 1, &info, VK_NULL_HANDLE) == VK_SUCCESS; + }; + const auto completed = [&] { + std::uint64_t value = 0; + vkGetSemaphoreCounterValue(device, done, &value); + return value; + }; + + // Submission 1 reads both allocations, but waits for the host first: it is in flight. + std::memset(got, 0, 2 * 4096); + EXPECT(record_copies()); + EXPECT(submit(1, 1)); + // Every allocation is released while it may still read them: their blocks are pending with ticket 1, and a + // reclaim with what has completed (0) unbinds none of them. + for (const Live& l : live) { + const VkDeviceSize bytes = backing.footprint(l.bytes); + EXPECT(blocks.release(l.offset, bytes) == leonida::ArenaBlocks::Fault::none); + backing.release(l.offset, bytes, 1); + } + EXPECT(completed() == 0); + EXPECT(backing.reclaim(completed()) == 0); + EXPECT(backing.stats().bound == bound); + // A new allocation binds a block now, on the arena's queue, while the work queue is blocked. + VkDeviceSize fresh = 0; + EXPECT(allocate(3 * kMiB, fresh)); + EXPECT(backing.stats().bound == bound + 4 * kMiB); + + // Open the gate: the submission reads what the CPU wrote, from memory that was still bound. + VkSemaphoreSignalInfo open{VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO}; + open.semaphore = gate; + open.value = 1; + EXPECT(vkSignalSemaphore(device, &open) == VK_SUCCESS); + VkSemaphoreWaitInfo wait{VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO}; + const std::uint64_t one = 1; + wait.semaphoreCount = 1; + wait.pSemaphores = &done; + wait.pValues = &one; + EXPECT(vkWaitSemaphores(device, &wait, 5'000'000'000ull) == VK_SUCCESS); + EXPECT(got[0] == (std::uint32_t(small.offset / 4) ^ 0x5a5a5a5au)); + EXPECT(got[1023] == (std::uint32_t(small.offset / 4 + 1023) ^ 0x5a5a5a5au)); + EXPECT(got[1024] == (std::uint32_t((large.offset + 3 * kMiB) / 4) ^ 0x5a5a5a5au)); + + // Ticket 1 has completed: the released blocks are unbound and freed; the head and the fresh one stay. + const VkDeviceSize unbound = backing.reclaim(completed()); + std::fprintf(stderr, "after the submission retired: %llu MiB unbound, %llu MiB bound, %llu memory objects\n", + (unsigned long long)(unbound >> 20), (unsigned long long)(backing.stats().bound >> 20), + (unsigned long long)memory_objects); + EXPECT(backing.stats().bound == leonida::kArenaBlockBytes + 4 * kMiB); + EXPECT(!backing.host(large.offset, 4) && memory_objects == 2); + // The GPU reads zero there now (residencyNonResidentStrict), and no fault. + std::memset(got, 0xff, 2 * 4096); + EXPECT(record_copies()); + EXPECT(submit(0, 2)); + const std::uint64_t two = 2; + wait.pValues = &two; + EXPECT(vkWaitSemaphores(device, &wait, 5'000'000'000ull) == VK_SUCCESS); + EXPECT(got[1024] == 0 && got[2047] == 0); + + vkDeviceWaitIdle(device); + backing.clear(); + vkDestroySemaphore(device, gate, nullptr); + vkDestroySemaphore(device, done, nullptr); + vkDestroyCommandPool(device, pool, nullptr); + vkDestroyBuffer(device, readback, nullptr); + vkFreeMemory(device, readback_memory, nullptr); + vkDestroyBuffer(device, arena, nullptr); + return 0; +} + +} // namespace + +int main() { + const int result = test(); + if (!result) std::fprintf(stderr, "arena_sparse_gpu: ok\n"); + return result; +} diff --git a/runtime/test/console_heap_slot_records_test.cpp b/runtime/test/console_heap_slot_records_test.cpp index c5fcfbe9ab..2f5b22c639 100644 --- a/runtime/test/console_heap_slot_records_test.cpp +++ b/runtime/test/console_heap_slot_records_test.cpp @@ -8,6 +8,8 @@ // compared with a full re-resolution of every slot: a slot left naming a range that went (a GPU page fault in the // runtime) or a waiting slot left null after its buffer came fails the comparison. #include "../src/console_heap_slot_records.h" +#include "../src/memory_breakdown.h" +#include "../src/title_mirror_space.h" #include #include @@ -90,6 +92,40 @@ struct Model { slots[slot] = {a, b}; fix(slot); } + // As the device fixes a slot the title rewrote: the changes noted so far are applied first (sync_slot_changes), + // then a half whose range another half has a record for takes its answer (answer()) instead of resolving. + std::uint64_t answered = 0, answered_resolved = 0, stale_answers = 0; + void write_answered(std::size_t slot, Words a, Words b = Words{}) { + apply(); + slots[slot] = {a, b}; + ++fixes; + for (unsigned half = 0; half < 2; ++half) { + const Words& w = slots[slot][half]; + ConsoleHeapSlotRecords::State state{}; + std::uint64_t target = 0; + if (w.span && records.answer(w.base, w.span, false, state, target)) { + ++answered; + const bool resolved = state == ConsoleHeapSlotRecords::resolved; + answered_resolved += resolved; + records.set(slot, half, state, w.base, w.span, target); + copy[slot][half] = resolved ? target : 0; + // The answer must be what resolving now gives, not only after the next submission's changes. + std::uint64_t refused = 0; + if (resolve(w.base, w.span, refused) != copy[slot][half]) ++stale_answers; + continue; + } + if (!w.span) { + records.set(slot, half, ConsoleHeapSlotRecords::none, 0, 0, 0); + copy[slot][half] = 0; + continue; + } + std::uint64_t refused = 0; + const std::uint64_t to = resolve(w.base, w.span, refused); + records.set(slot, half, to ? ConsoleHeapSlotRecords::resolved : ConsoleHeapSlotRecords::waiting, w.base, + w.span, to ? to : refused); + copy[slot][half] = to; + } + } void zero(std::size_t slot) { slots[slot] = {}; copy[slot] = {0, 0}; @@ -286,7 +322,8 @@ int differential() { Model::Words a{pick(2) ? pick(64) * kGranule / 2 + pick(0x800) : titles[pick(6)] + pick(0x80000), span}; Model::Words b{}; if (!pick(4)) b = {pick(64) * kGranule / 2, 4}; - m.write(slot, a, b); + if (pick(2)) m.write_answered(slot, a, b); + else m.write(slot, a, b); break; } case 3: m.zero(slot); break; @@ -327,21 +364,532 @@ int differential() { return 1; } } - EXPECT(m.records.recorded() > 0); + EXPECT(m.records.recorded() > 0 && m.answered_resolved > 0 && m.answered > m.answered_resolved && + m.stale_answers == 0); // The model's address space is a few MiB, so most changes touch most of it: this case checks results, not cost. std::printf("differential: 400 rounds, copy equal to a full re-resolution after each; %llu entries looked at, " - "%llu slots fixed again, %zu halves recorded at the end\n", + "%llu slots fixed again, %zu halves recorded at the end; %llu rewritten halves answered by a record of " + "their range (%llu resolved), each equal to a resolution at that moment\n", static_cast(looked), static_cast(touched), - m.records.recorded()); + m.records.recorded(), static_cast(m.answered), + static_cast(m.answered_resolved)); + return 0; +} + +// T# records (set_texture): a T# waits on the exact address it names; a texture registered there touches the slots +// waiting on it and only those; a texture gone touches the bound ones; a slot rewritten while waiting leaves no +// stale entry; many slots on one texture; V# and T# changes never touch each other's records. +int textures() { + using R = ConsoleHeapSlotRecords; + R records; + records.reset(70000); + constexpr std::uint64_t kTex = 0x100000100ull, kOther = 0x100000200ull, kNear = 0x100000300ull, + kRebound = 0x100000400ull; + std::vector out; + const auto touched = [&](SlotChange::Kind kind, std::uint64_t address) { + const SlotChange change{kind, address, address + 1}; + records.touched(&change, 1, out); + return out; + }; + // 60,000 T#s wait on kTex, 10 on kOther, 5 are bound to kNear (each address another texture). + for (std::uint32_t slot = 0; slot < 60000; ++slot) records.set_texture(slot, R::texture_waiting, kTex); + for (std::uint32_t slot = 60000; slot < 60010; ++slot) records.set_texture(slot, R::texture_waiting, kOther); + for (std::uint32_t slot = 60010; slot < 60015; ++slot) records.set_texture(slot, R::texture_bound, kNear); + EXPECT(records.textures() == 60015 && records.textures_waiting() == 60010 && records.recorded() == 0); + // A texture at kOther: its 10 slots, looking at 10 entries. + std::uint64_t looked = records.looked_at(); + EXPECT(touched(SlotChange::texture_added, kOther).size() == 10 && out.front() == 60000 && out.back() == 60009); + EXPECT(records.looked_at() - looked == 10); + // A texture added where no T# waits, or where only bound ones are: nothing. + EXPECT(touched(SlotChange::texture_added, kOther + 0x1000).empty()); + EXPECT(touched(SlotChange::texture_added, kNear).empty()); + // V# changes over those addresses never touch T# records. + for (const auto kind : {SlotChange::target_gone, SlotChange::source_gone, SlotChange::target_added, + SlotChange::source_added}) { + const SlotChange change{kind, kTex - 0x10000, kTex + 0x10000}; + records.touched(&change, 1, out); + EXPECT(out.empty()); + } + // The texture at kNear goes: its bound slots, which the fix makes waiting. + EXPECT(touched(SlotChange::texture_gone, kNear).size() == 5); + for (std::uint32_t slot = 60010; slot < 60015; ++slot) records.set_texture(slot, R::texture_waiting, kNear); + EXPECT(records.textures_waiting() == 60015); + // Slot 7 is rewritten while waiting: now a T# of kOther, then a V#, then zeroed. Each time kTex no longer names it. + records.set_texture(7, R::texture_waiting, kOther); + EXPECT(touched(SlotChange::texture_added, kTex).size() == 59999); + EXPECT(touched(SlotChange::texture_added, kOther).size() == 11); + records.set(7, 0, R::resolved, 0x5000, 256, kArena + 0x5000); + EXPECT(touched(SlotChange::texture_added, kOther).size() == 10); + EXPECT(records.textures() == 60014 && records.recorded() == 1); + records.clear(7); + EXPECT(touched(SlotChange::texture_gone, kOther).size() == 10 && records.recorded() == 0); + // The texture comes: the fix binds all 59,999; a later texture added there touches none (they wait no more), a + // texture gone touches them all again. + for (std::uint32_t slot = 0; slot < 60000; ++slot) + if (slot != 7) records.set_texture(slot, R::texture_bound, kTex); + EXPECT(touched(SlotChange::texture_added, kTex).empty()); + EXPECT(touched(SlotChange::texture_gone, kTex).size() == 59999); + // Rebinding the same address many times leaves one entry per slot (the bucket is cleaned as it grows). + for (int round = 0; round < 8; ++round) + for (std::uint32_t slot = 0; slot < 100; ++slot) + records.set_texture(slot, round & 1 ? R::texture_bound : R::texture_waiting, kRebound); + looked = records.looked_at(); + EXPECT(touched(SlotChange::texture_gone, kRebound).size() == 100); + EXPECT(records.looked_at() - looked <= 200); + std::printf("textures: a texture registered touches only the T#s waiting on its address (10 of 60,015, 10 looked " + "at); one gone touches the bound ones; rewritten slots leave no stale entry; V# changes touch none\n"); + return 0; +} + +// Waiting for room: a V# half refused a geometry copy for lack of room is fixed again when copies are freed +// (geometry_room) whatever its address; a T# refused for a full bindless array when entries are freed (texture_room). +// The A1 gap: such a half has no target, so no target change ever found it. +int room() { + using R = ConsoleHeapSlotRecords; + R records; + records.reset(64); + records.set(1, 0, R::waiting_room, 0x7000000000ull, 4096, 0); // geometry refused for room + records.set(2, 0, R::waiting, 0x7000100000ull, 4096, 0); // nothing at its base + records.set(3, 1, R::waiting_room, 0x7000200000ull, 64, 0); // the counter half + records.set_texture(4, R::texture_waiting_room, 0x100000400ull); + records.set_texture(5, R::texture_waiting, 0x100000500ull); + std::vector out; + const SlotChange geometry{SlotChange::geometry_room, 0, 1}, textures{SlotChange::texture_room, 0, 1}; + records.touched(&geometry, 1, out); + EXPECT(out == std::vector({1, 3})); + records.touched(&textures, 1, out); + EXPECT(out == std::vector({4})); + // Both at once, each list once; duplicates of one change count once. + const SlotChange both[] = {geometry, textures, geometry}; + records.touched(both, 3, out); + EXPECT(out == std::vector({1, 3, 4})); + // Resolved since (a copy was made): out of the list; waiting for an address alone: still found by the address. + records.set(1, 0, R::resolved, 0x7000000000ull, 4096, kArena + 0x10000); + records.set_texture(4, R::texture_waiting, 0x100000400ull); + records.touched(both, 3, out); + EXPECT(out == std::vector({3})); + const SlotChange added{SlotChange::texture_added, 0x100000400ull, 0x100000401ull}; + records.touched(&added, 1, out); + EXPECT(out == std::vector({4})); + // A room waiter is also found by its base, as any waiting half. + const SlotChange source{SlotChange::source_added, 0x7000200000ull, 0x7000200040ull}; + records.touched(&source, 1, out); + EXPECT(out == std::vector({3})); + EXPECT(records.waiting_count() == 2 && records.textures_waiting() == 2); + std::printf("room: geometry room touches only the halves refused a copy (2 of 3 waiting), texture room only the " + "T#s refused for a full array; resolved ones leave the lists\n"); return 0; } } // namespace +// Many slots in a few 64 KiB blocks, as the world's heaps have them (82,000-472,000 entries looked at for 2-15 +// changes in one run when the index grouped spans by 64 KiB block): a change looks at the halves whose range overlaps +// it, however many others share its block. 300,000 slots name 16 bytes each, in 74 blocks; a release of 48 bytes +// overlaps three of them. An addition over a range of resolved halves looks at the waiting ones only. +int dense_blocks_look_at_overlaps_only() { + constexpr std::size_t kSlots = 300000; + constexpr std::uint64_t kBase = 0x10000000; + ConsoleHeapSlotRecords records; + records.reset(kSlots); + for (std::size_t slot = 0; slot < kSlots; ++slot) { + const std::uint64_t base = kBase + slot * 16; + records.set(slot, 0, ConsoleHeapSlotRecords::resolved, base, 16, kArena + base); + } + // A slot whose 1 MiB range starts two blocks before the change, and its counter half waiting on a refused copy. + records.set(5, 1, ConsoleHeapSlotRecords::resolved, kBase + 0x80000 - 0x20000, 0x100000, kArena + 0x7000000); + std::vector touched; + const SlotChange release{SlotChange::target_gone, kArena + kBase + 0x80000 + 8, kArena + kBase + 0x80000 + 48}; + std::uint64_t before = records.looked_at(); + records.touched(&release, 1, touched); + const std::uint64_t looked = records.looked_at() - before; + // [base + 0x80008, base + 0x80030) overlaps slots 0x8000 (from byte 8), 0x8001 and 0x8002 (to byte 0x30). + EXPECT(looked == 3); + EXPECT(touched.size() == 3 && touched[0] == 0x8000 && touched[2] == 0x8002); + // The same bytes by source: the 1 MiB half of slot 5 overlaps them too. + const SlotChange removal{SlotChange::source_gone, kBase + 0x80000 + 8, kBase + 0x80000 + 48}; + before = records.looked_at(); + records.touched(&removal, 1, touched); + EXPECT(records.looked_at() - before == 4 && touched.size() == 4 && touched[0] == 5); + // A half that moves leaves nothing behind: slot 0x8001 now names other bytes, so the release looks at two. + records.set(0x8001, 0, ConsoleHeapSlotRecords::resolved, kBase - 0x1000, 16, kArena + kBase - 0x1000); + before = records.looked_at(); + records.touched(&release, 1, touched); + EXPECT(records.looked_at() - before == 2 && touched.size() == 2 && touched[1] == 0x8002); + + // Additions: 1,000 slots wait among the 300,000 resolved ones; a backing added over the whole range looks at the + // 1,000 only. + for (std::size_t slot = 100000; slot < 101000; ++slot) { + const std::uint64_t base = kBase + slot * 16; + records.set(slot, 0, ConsoleHeapSlotRecords::waiting, base, 16, 0); + } + EXPECT(records.waiting_count() == 1000); + const SlotChange added{SlotChange::source_added, kBase, kBase + kSlots * 16}; + before = records.looked_at(); + records.touched(&added, 1, touched); + EXPECT(records.looked_at() - before == 1000 && touched.size() == 1000 && touched[0] == 100000); + // Zeroed or reset, they are gone from every index. + records.clear_range(0, kSlots); + EXPECT(records.recorded() == 0 && records.ranges() == 0); + before = records.looked_at(); + records.touched(&removal, 1, touched); + EXPECT(records.looked_at() == before && touched.empty()); + std::printf("dense blocks: 300,000 slots in 74 blocks of 64 KiB; a 40-byte release looks at the 3 it overlaps, " + "an addition over all of them at the 1,000 waiting\n"); + return 0; +} + +// What one world run showed (130-210 changes a submission, 60,000-135,000 records looked at for 1,300-2,600 slots +// fixed): waiting V#s with large spans were looked at by every addition inside their span, though only a range that +// holds a V#'s base can back it, and a record named by many changes of one submission was looked at once per change. +// 5,000 waiting halves of 4 GiB each over one title range; 200 additions inside it, none holding their bases, look at +// none; one that holds 10 of the bases looks at those 10. 200 removals of one submission that all overlap the same +// 5,000 resolved halves look at each once. +int changes_look_at_each_record_once() { + constexpr std::size_t kSlots = 20000; + constexpr std::uint64_t kTitle = 0x200000000000ull, kSpan = 1ull << 32; + ConsoleHeapSlotRecords records; + records.reset(kSlots); + for (std::size_t slot = 0; slot < 5000; ++slot) + records.set(slot, 0, ConsoleHeapSlotRecords::waiting, kTitle + slot * 0x100, kSpan, 0); + std::vector added; + for (std::uint64_t i = 0; i < 200; ++i) { + const std::uint64_t lo = kTitle + 0x10000000 + i * 0x100000; // past every base, inside every span + added.push_back({SlotChange::source_added, lo, lo + 0x10000}); + } + std::vector touched; + std::uint64_t before = records.looked_at(); + records.touched(added.data(), added.size(), touched); + EXPECT(records.looked_at() - before == 0 && touched.empty()); + const SlotChange holds{SlotChange::source_added, kTitle + 0x100 * 20, kTitle + 0x100 * 30}; + before = records.looked_at(); + records.touched(&holds, 1, touched); + EXPECT(records.looked_at() - before == 10 && touched.size() == 10 && touched[0] == 20); + + for (std::size_t slot = 5000; slot < 10000; ++slot) + records.set(slot, 0, ConsoleHeapSlotRecords::resolved, kTitle, kSpan, kArena + 0x100000); + std::vector gone; + for (std::uint64_t i = 0; i < 200; ++i) + gone.push_back({SlotChange::target_gone, kArena + 0x100000 + i * 0x10000, kArena + 0x100000 + i * 0x10000 + 64}); + before = records.looked_at(); + records.touched(gone.data(), gone.size(), touched); + EXPECT(records.looked_at() - before == 5000 && touched.size() == 5000); + // A removal and an addition in one call over the same waiting half: looked at once in the source index. The 5,000 + // resolved halves the removal names by source are looked at there once more (once per index, at most twice). + gone.push_back({SlotChange::source_gone, kTitle, kTitle + 0x100}); + gone.push_back({SlotChange::source_added, kTitle, kTitle + 0x100}); + before = records.looked_at(); + records.touched(gone.data(), gone.size(), touched); + EXPECT(records.looked_at() - before == 10001 && touched.size() == 5001); + std::printf("once a call: 200 additions inside 5,000 waiting 4 GiB spans look at none, one holding 10 bases at 10; " + "200 removals over 5,000 resolved halves look at each once\n"); + return 0; +} + +// Reservations <= TitleMirror::kChunk (2 GiB) that would cross a 2 GiB chunk boundary advance to the next chunk so +// placed buffers inside them stay in one chunk; > 2 GiB reservations are not skipped past chunk boundaries. +int title_mirror_space_chunk_alignment() { + namespace tms = leonida::title_mirror_space; + constexpr std::uint64_t kChunk = tms::kChunk; + constexpr std::uint64_t kMiB = 1ull << 20; + const auto accept = [](std::uint64_t) { return true; }; + + // Small reservation starts in the first chunk; a second small one packs into the same chunk. + const std::uint64_t a = tms::take(64 * kMiB, 0x10000, true, accept); + const std::uint64_t b = tms::take(64 * kMiB, 0x10000, true, accept); + EXPECT(a >= tms::kLow && b == a + 64 * kMiB); + EXPECT(a / kChunk == (b + 64 * kMiB - 1) / kChunk); + + // A 1950 MiB reservation cannot fit in the remaining 1920 MiB of this chunk: advances to the next 2 GiB boundary. + const std::uint64_t big_size = 1950 * kMiB; + const std::uint64_t c = tms::take(big_size, 0x10000, false, accept); + EXPECT((c & (kChunk - 1)) == 0); + EXPECT(c > b); + EXPECT(c / kChunk == (c + big_size - 1) / kChunk); + + // An exact 2 GiB reservation while mid-chunk also lands chunk-aligned inside a single chunk. + const std::uint64_t exact = tms::take(kChunk, 0x10000, false, accept); + EXPECT((exact & (kChunk - 1)) == 0); + EXPECT(exact / kChunk == (exact + kChunk - 1) / kChunk); + + // A reservation > 2 GiB does not artificially align to a new chunk when already mid-chunk. + const std::uint64_t tiny = tms::take(0x10000, 0x10000, true, accept); + const std::uint64_t huge = tms::take(kChunk + 64 * kMiB, 0x10000, true, accept); + EXPECT(huge == tiny + 0x10000); + + std::printf("title_mirror_space: <= 2 GiB reservations stay inside one 2 GiB chunk\n"); + return 0; +} + +// Arena-backed title windows and shadows are split out of general arena buffers in mem-probe breakdown. +int memory_breakdown_arena_windows() { + namespace mb = leonida::memory_breakdown; + constexpr std::uint64_t kMiB = 1ull << 20; + mb::Tally t; + t.add(mb::Consumer::arena, 4095 * kMiB, false); + mb::DeviceShare share; + share.arena = true; + share.arena_reserved = share.arena_bound = 4095 * kMiB; + share.arena_in_use = 522 * kMiB; + share.arena_use = {58 * kMiB, 0, 0, 0}; + share.arena_windows = 464 * kMiB; + const std::string line = mb::format(t, share, 0); + EXPECT(line.find("buffers 58, descriptor heaps 0, shader code 0, heaps 0, windows/shadows 464]") != + std::string::npos); + EXPECT(line.find("title windows and shadows 0 (0) [in arena 464 MiB]") != std::string::npos); + + // With 0 arena windows, the compact format stays unchanged. + share.arena_windows = 0; + const std::string clean = mb::format(t, share, 0); + EXPECT(clean.find("windows/shadows") == std::string::npos); + EXPECT(clean.find("[in arena") == std::string::npos); + std::printf("memory_breakdown: arena windows/shadows split from buffers\n"); + return 0; +} + +// Clearing a deferred slot before finish_in_place resolves it prevents a placeholder waiting record from poisoning +// ConsoleHeapSlotRecords::answer(), while repeated V# halves still hit settled resolved/waiting records. +int deferred_clear_and_repeated_answers() { + using R = ConsoleHeapSlotRecords; + R records; + records.reset(16); + constexpr std::uint64_t kBase = 0x100800000000ull; + constexpr std::uint64_t kSpan = 0x1000; + // Deferred slot 0 is cleared (none), not inserted as a placeholder waiting record -> answer() returns false. + records.set(0, 0, R::none, 0, 0, 0); + R::State state = R::none; + std::uint64_t target = 0; + EXPECT(!records.answer(kBase, kSpan, false, state, target)); + EXPECT(!records.answer(kBase, kSpan, true, state, target)); + + // Once slot 0 settles as resolved, repeated slot 1 gets the exact resolved target from answer(). + records.set(0, 0, R::resolved, kBase, kSpan, kArena + 0x20000, false); + EXPECT(records.answer(kBase, kSpan, false, state, target)); + EXPECT(state == R::resolved && target == kArena + 0x20000); + + // Once slot 2 settles as waiting (asked for geometry), repeated slot 3 gets waiting whether geometry is true/false. + constexpr std::uint64_t kUnbacked = 0x100900000000ull; + records.set(2, 0, R::waiting, kUnbacked, kSpan, 0, true); + EXPECT(records.answer(kUnbacked, kSpan, true, state, target) && state == R::waiting && target == 0); + EXPECT(records.answer(kUnbacked, kSpan, false, state, target) && state == R::waiting && target == 0); + std::printf("deferred_clear_and_repeated_answers: ok\n"); + return 0; +} + +// Regression: +// 1. An unresolvable base >= arena.size V# recorded directly as waiting (geometry=true) wakes on source_added +// (late alias, backing, or extended title_memory) and answers repeated halves consistently until woken; +// 2. A tracked non-sparse direct backing (resolved with target) wakes on target_gone when freed; +// 3. Clearing a slot whose T# was overwritten with non-T# data removes its texture record so later texture changes +// never touch the slot. +int waiting_source_added_and_tsharp_clear() { + using R = ConsoleHeapSlotRecords; + R records; + records.reset(32); + std::vector out; + + // 1. Waiting record (geometry=true) for base >= arena.size wakes on source_added. + constexpr std::uint64_t kLateBase = 0x100800004000ull; + constexpr std::uint64_t kSpan = 0x1000; + records.set(4, 0, R::waiting, kLateBase, kSpan, 0, true); + R::State state = R::none; + std::uint64_t target = 0; + EXPECT(records.answer(kLateBase, kSpan, false, state, target) && state == R::waiting && target == 0); + EXPECT(records.answer(kLateBase, kSpan, true, state, target) && state == R::waiting && target == 0); + const SlotChange late_alias{SlotChange::source_added, kLateBase - 0x4000, kLateBase + 0x10000}; + records.touched(&late_alias, 1, out); + EXPECT(out == std::vector({4})); + + // 2. Non-sparse direct backing (e.g. below-arena gpu_backings or geometry copy) tracked as resolved wakes on + // target_gone when that backing is freed. + constexpr std::uint64_t kBelowOffset = (1ull << 47) | 0x200000ull; + constexpr std::uint64_t kBelowBda = kArena + (kBelowOffset | ~kMask); + records.set(7, 0, R::resolved, kBelowOffset, 0x400, kBelowBda, false); + const SlotChange freed{SlotChange::target_gone, kBelowBda, kBelowBda + 0x1000}; + records.touched(&freed, 1, out); + EXPECT(out == std::vector({7})); + + // 3. Prior texture record cleared when slot is overwritten with not_tsharp data. + constexpr std::uint64_t kTexAddr = 0x100801000000ull; + records.set_texture(9, R::texture_bound, kTexAddr); + EXPECT(records.textures() == 1); + records.clear(9); + EXPECT(records.textures() == 0 && records.state(9, 0) == R::none); + const SlotChange tex_gone{SlotChange::texture_gone, kTexAddr, kTexAddr + 1}; + records.touched(&tex_gone, 1, out); + EXPECT(out.empty()); + + std::printf("waiting_source_added_and_tsharp_clear: ok\n"); + return 0; +} + +// Fast-path regression: repeated none->none set()/clear() calls and repeated identical place() calls leave all +// counts, groups, and touched() results exact without corrupting state. +int none_to_none_and_idempotent_fast_path() { + using R = ConsoleHeapSlotRecords; + R records; + records.reset(1024); + + // Repeated none->none on untouched slots. + for (std::size_t s = 0; s < 1024; ++s) { + records.set(s, 0, R::none, 0, 0, 0); + records.set(s, 1, R::none, 0, 0, 0); + records.clear(s); + } + EXPECT(records.recorded() == 0 && records.waiting_count() == 0 && records.textures() == 0 && records.ranges() == 0); + + // Identical repeated set() and set_texture() hit place() fast path cleanly. + constexpr std::uint64_t kBase = 0x40000000ull, kTarget = kArena + 0x40000000ull, kTex = 0x50000000ull; + records.set(10, 0, R::resolved, kBase, 256, kTarget, false); + records.set(10, 0, R::resolved, kBase, 256, kTarget, false); + records.set(10, 1, R::none, 0, 0, 0); + records.set_texture(11, R::texture_bound, kTex); + records.set_texture(11, R::texture_bound, kTex); + EXPECT(records.recorded() == 1 && records.textures() == 1 && records.ranges() == 3); + + // Changing state or clearing still drops cleanly and returns to none->none. + records.set(10, 0, R::waiting, kBase, 256, 0, true); + EXPECT(records.recorded() == 1 && records.waiting_count() == 1 && records.ranges() == 2); + records.set(10, 0, R::waiting, kBase, 256, 0, true); + EXPECT(records.recorded() == 1 && records.waiting_count() == 1 && records.ranges() == 2); + + std::vector out; + const SlotChange src{SlotChange::source_added, kBase, kBase + 64}; + records.touched(&src, 1, out); + EXPECT(out == std::vector({10})); + + records.clear(10); + records.clear(10); // second clear hits none->none fast path + records.clear(11); + records.clear(11); + EXPECT(records.recorded() == 0 && records.waiting_count() == 0 && records.textures() == 0 && records.ranges() == 0); + + std::printf("none_to_none_and_idempotent_fast_path: ok\n"); + return 0; +} + +// Live texture callback: fires ONLY on kTexture kSettled 0 <-> 1 transitions per address per heap across attach, +// detach, clear/clear_range, overwrite, reset(), move, and destructor (never on waiting states or V# records). +int texture_live_callback() { + using R = ConsoleHeapSlotRecords; + struct Tracker { + std::map live_heaps; + std::vector> events; + static void on_live(void* user, std::uint64_t addr, bool bound) { + auto* self = static_cast(user); + self->events.emplace_back(addr, bound); + if (bound) { + ++self->live_heaps[addr]; + } else { + const auto it = self->live_heaps.find(addr); + if (it != self->live_heaps.end()) { + if (--it->second == 0) self->live_heaps.erase(it); + } else { + self->live_heaps[addr] = -1; // underflow sentinel + } + } + } + } tracker; + + constexpr std::uint64_t kTexA = 0x100001000ull; + constexpr std::uint64_t kTexB = 0x100002000ull; + constexpr std::uint64_t kTexC = 0x100003000ull; + constexpr std::uint64_t kTexWait = 0x100004000ull; + + { + R heap1, heap2; + heap1.set_texture_live_callback(&Tracker::on_live, &tracker); + heap2.set_texture_live_callback(&Tracker::on_live, &tracker); + heap1.reset(64); + heap2.reset(64); + + // Waiting T# and V# records at the same address never trigger callbacks. + heap1.set_texture(0, R::texture_waiting, kTexWait); + heap1.set_texture(1, R::texture_waiting_room, kTexWait); + heap1.set(2, 0, R::resolved, kTexA, 256, kArena + 0x1000); + EXPECT(tracker.events.empty() && tracker.live_heaps.empty()); + + // 0 -> 1 on kTexA fires (kTexA, true); 1 -> 2 and idempotent rewrite do not fire. + heap1.set_texture(3, R::texture_bound, kTexA); + EXPECT(tracker.events.size() == 1 && tracker.events.back() == std::make_pair(kTexA, true)); + EXPECT(tracker.live_heaps.at(kTexA) == 1); + heap1.set_texture(4, R::texture_bound, kTexA); + heap1.set_texture(3, R::texture_bound, kTexA); + EXPECT(tracker.events.size() == 1); + + // Second heap binding kTexA increments live_heaps[kTexA] to 2. + heap2.set_texture(10, R::texture_bound, kTexA); + EXPECT(tracker.events.size() == 2 && tracker.live_heaps.at(kTexA) == 2); + + // One slot in heap1 transitions bound -> waiting: slot 4 still holds kTexA, so no false event yet. + heap1.set_texture(3, R::texture_waiting, kTexA); + EXPECT(tracker.events.size() == 2 && tracker.live_heaps.at(kTexA) == 2); + + // Last slot in heap1 switches kTexA -> kTexB: fires (kTexA, false) then (kTexB, true). + heap1.set_texture(4, R::texture_bound, kTexB); + EXPECT(tracker.events.size() == 4); + EXPECT(tracker.events[2] == std::make_pair(kTexA, false)); + EXPECT(tracker.events[3] == std::make_pair(kTexB, true)); + EXPECT(tracker.live_heaps.at(kTexA) == 1 && tracker.live_heaps.at(kTexB) == 1); + + // Overwriting kTexB with a V# fires (kTexB, false). + heap1.set(4, 0, R::resolved, 0x8000, 64, kArena + 0x8000); + EXPECT(tracker.events.size() == 5 && tracker.events.back() == std::make_pair(kTexB, false)); + EXPECT(tracker.live_heaps.count(kTexB) == 0); + + // Re-bind kTexB and kTexC in heap1, then clear_range drops kTexB only. + heap1.set_texture(5, R::texture_bound, kTexB); + heap1.set_texture(8, R::texture_bound, kTexC); + EXPECT(tracker.live_heaps.at(kTexB) == 1 && tracker.live_heaps.at(kTexC) == 1); + heap1.clear_range(5, 7); + EXPECT(tracker.live_heaps.count(kTexB) == 0 && tracker.live_heaps.at(kTexC) == 1); + + // reset() notifies kTexC unbound (and NOT kTexWait), and keeps callback active afterward. + const std::size_t before_reset = tracker.events.size(); + heap1.reset(32); + EXPECT(tracker.events.size() == before_reset + 1 && tracker.events.back() == std::make_pair(kTexC, false)); + EXPECT(tracker.live_heaps.count(kTexC) == 0); + + // Post-reset binding works, and move leaves moved-from silent. + heap1.set_texture(1, R::texture_bound, kTexC); + EXPECT(tracker.live_heaps.at(kTexC) == 1); + R moved_heap(std::move(heap1)); + EXPECT(tracker.live_heaps.at(kTexC) == 1); + + // Destructors of moved_heap (kTexC) and heap2 (kTexA) unbind both cleanly. + } + EXPECT(tracker.live_heaps.empty()); + + // Detaching callback with nullptr before destruction suppresses teardown callbacks. + { + R silent; + silent.set_texture_live_callback(&Tracker::on_live, &tracker); + silent.reset(16); + silent.set_texture(0, R::texture_bound, kTexA); + EXPECT(tracker.live_heaps.at(kTexA) == 1); + const std::size_t before_detach = tracker.events.size(); + silent.set_texture_live_callback(nullptr, nullptr); + silent.reset(0); + EXPECT(tracker.events.size() == before_detach); + } + std::printf("texture_live_callback: ok\n"); + return 0; +} + int main() { if (release_looks_at_its_slots_only()) return 1; if (cases()) return 1; + if (dense_blocks_look_at_overlaps_only()) return 1; + if (changes_look_at_each_record_once()) return 1; if (differential()) return 1; + if (textures()) return 1; + if (room()) return 1; + if (title_mirror_space_chunk_alignment()) return 1; + if (memory_breakdown_arena_windows()) return 1; + if (deferred_clear_and_repeated_answers()) return 1; + if (waiting_source_added_and_tsharp_clear()) return 1; + if (none_to_none_and_idempotent_fast_path()) return 1; + if (texture_live_callback()) return 1; std::printf("console_heap_slot_records_test: ok\n"); return 0; } diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp index 1d940a7e48..dbde142949 100644 --- a/runtime/test/d3d12_existing_heap_test.cpp +++ b/runtime/test/d3d12_existing_heap_test.cpp @@ -1658,6 +1658,130 @@ int check_placed_view_map_changes(ID3D12Device* device) { return 0; } +// A shader view of `texture`, as a draw would name it: a title texture is filled from its memory only once a +// descriptor names it (the refresh's upload at first use). `heap` holds the descriptor; the caller keeps it. +int name_texture(ID3D12Device* device, ID3D12Resource* texture, Ref& heap) { + const char* who = "naming a title texture"; + D3D12_DESCRIPTOR_HEAP_DESC desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + EXPECT_HR(device->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&heap.p)), S_OK); + device->CreateShaderResourceView(texture, nullptr, heap->GetCPUDescriptorHandleForHeapStart()); + return 0; +} + +// A texture over the memory of a GPU-written texture (a render target placed at the same title pages) is not filled +// from those pages: they hold what the CPU last wrote there, not what the GPU rendered, and an upload of them (in +// 64 KiB pieces, as write-backs and neighbours' writes marked tiles written) showed blocks of older frames. +int check_texture_over_render_target(ID3D12Device* device) { + const char* who = "texture over a render target's memory"; + constexpr SIZE_T bytes = 4 * 65536; + void* pages = VirtualAlloc(nullptr, bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + EXPECT(pages); + std::memset(pages, 0x11, bytes); + GpuReader gpu; + EXPECT(!gpu.init(device, 256)); + D3D12_RESOURCE_DESC target{}; + target.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + target.Width = 256; + target.Height = 256; + target.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + target.SampleDesc.Count = target.DepthOrArraySize = target.MipLevels = 1; + target.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + Ref rendered; + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, target, 6, IID_PPV_ARGS(&rendered.p)), S_OK); + // A plain texture over the target's second 64 KiB, laid out linearly (the title's XG computer for its shape). + constexpr UINT width = 256, height = 256; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = width; + desc.Height = height; + desc.Format = DXGI_FORMAT_R8_UNORM; + desc.SampleDesc.Count = desc.DepthOrArraySize = desc.MipLevels = 1; + leonida::title_xg_layouts::note({UINT(desc.Dimension), UINT(desc.Format), height, 1, 1, width}, 1); + auto* over = static_cast(pages) + 65536; + Ref texture; + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, over, desc, 6, IID_PPV_ARGS(&texture.p)), S_OK); + void* mapped = nullptr; + EXPECT_HR(texture->Map(0, nullptr, &mapped), S_OK); + Ref named; + EXPECT(!name_texture(device, texture.p, named)); + ID3D12CommandList* lists[]{gpu.list.p}; + std::array pixels{}; + for (unsigned pass = 1; pass <= 2; ++pass) { + std::memset(over, 0x40 + pass, 65536); // a CPU write (a write-back of a GPU copy, say) of one 64 KiB piece + gpu.queue->ExecuteCommandLists(1, lists); + EXPECT_HR(gpu.queue->Signal(gpu.fence.p, pass), S_OK); + EXPECT_HR(gpu.fence->SetEventOnCompletion(pass, gpu.done), S_OK); + EXPECT(WaitForSingleObject(gpu.done, 30000) == WAIT_OBJECT_0); + EXPECT_HR(texture->ReadFromSubresource(pixels.data(), width, UINT(pixels.size()), 0, nullptr), S_OK); + EXPECT(std::none_of(pixels.begin(), pixels.end(), [&](auto value) { return value == 0x40 + pass; })); + } + texture->Unmap(0, nullptr); + texture.p->Release(); + texture.p = nullptr; + rendered.p->Release(); + rendered.p = nullptr; + VirtualFree(pages, 0, MEM_RELEASE); + return 0; +} + +// A plain texture and a render target at one address, in either order: a slot-70 view of the plain texture's +// description is a view of the render target's image (what the GPU renders there), and once the target is gone, of +// the plain texture's own image again. +int check_view_over_render_target(ID3D12Device* device) { + const char* who = "view over a render target"; + if (!rt::d3d12::bindless_set_layout(device)) return 0; + constexpr SIZE_T bytes = 4 * 65536; + D3D12_RESOURCE_DESC plain{}; + plain.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + plain.Width = 256; + plain.Height = 256; + plain.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + plain.SampleDesc.Count = plain.DepthOrArraySize = plain.MipLevels = 1; + D3D12_RESOURCE_DESC target = plain; + target.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + const auto view = [&](void* pages, const D3D12_RESOURCE_DESC& desc, std::uint64_t& image) { + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = desc.Format; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Texture2D.MipLevels = 1; + std::array resource{}; + std::array words{}; + std::memcpy(resource.data(), &desc, sizeof(desc)); + std::memcpy(words.data(), &srv, sizeof(srv)); + leonida::gfx10::ImageWords slot{}; + if (!rt::d3d12::write_placed_texture_view(device, false, resource.data(), words.data(), + reinterpret_cast(pages), {reinterpret_cast(slot.data())})) + return false; + leonida::gfx10::Image decoded{}; + if (!leonida::gfx10::decode(slot, decoded)) return false; + image = decoded.address; + return true; + }; + for (const bool target_first : {false, true}) { + void* pages = VirtualAlloc(nullptr, bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + EXPECT(pages); + Ref texture, rendered; + if (target_first) + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, target, 6, IID_PPV_ARGS(&rendered.p)), S_OK); + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, plain, 6, IID_PPV_ARGS(&texture.p)), S_OK); + if (!target_first) + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, target, 6, IID_PPV_ARGS(&rendered.p)), S_OK); + std::uint64_t of_plain = 0, of_target = 0; + EXPECT(view(pages, target, of_target)); + EXPECT(view(pages, plain, of_plain)); + EXPECT(of_plain == of_target); // the plain texture's view shows the target's image + rendered.p->Release(); + rendered.p = nullptr; + EXPECT(view(pages, plain, of_plain)); + EXPECT(of_plain != of_target); // the target is gone: the plain texture's own image again + texture.p->Release(); + texture.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"; @@ -1677,6 +1801,8 @@ int check_mapped_plane(ID3D12Device* device) { EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, desc, 6, IID_PPV_ARGS(&texture.p)), S_OK); void* mapped = nullptr; EXPECT_HR(texture->Map(0, nullptr, &mapped), S_OK); + Ref named; // filled from memory once a descriptor names it + EXPECT(!name_texture(device, texture.p, named)); EXPECT(mapped == pages); ID3D12CommandList* lists[]{gpu.list.p}; std::array pixels{}; @@ -1701,9 +1827,8 @@ int check_mapped_plane(ID3D12Device* device) { return 0; } -// LEONIDA_TEXTURE_REFRESH_ASYNC=1 (the d3d12_mapped_plane_async test): a texture the title maps and writes, and then -// reads on the GPU in its very first submission, has its bytes there, though the refresh pass runs on a worker: the -// submission fills a mapped texture that was never filled before it records anything (fill_first_mapped_textures). +// The d3d12_mapped_plane_async test (named for the refresh mode it was written for, removed since): a texture the title +// maps and writes, and then reads on the GPU in its very first submission, has its bytes there. int check_mapped_plane_first_use(ID3D12Device* device) { const char* who = "persistent slot-133 plane, first use"; constexpr UINT width = 256, height = 8, size = width * height; @@ -1724,6 +1849,8 @@ int check_mapped_plane_first_use(ID3D12Device* device) { EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, desc, 6, IID_PPV_ARGS(&texture.p)), S_OK); void* mapped = nullptr; EXPECT_HR(texture->Map(0, nullptr, &mapped), S_OK); + Ref named; // filled from memory once a descriptor names it + EXPECT(!name_texture(device, texture.p, named)); EXPECT(mapped == pages); EXPECT_HR(gpu.allocator->Reset(), S_OK); EXPECT_HR(gpu.list->Reset(gpu.allocator.p, nullptr), S_OK); @@ -2288,6 +2415,8 @@ int check_mapped_plane_byte(ID3D12Device* device, DWORD modifier) { EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, desc, 6, IID_PPV_ARGS(&texture.p)), S_OK); void* mapped = nullptr; EXPECT_HR(texture->Map(0, nullptr, &mapped), S_OK); + Ref named; // filled from memory once a descriptor names it + EXPECT(!name_texture(device, texture.p, named)); EXPECT(mapped == pages); std::memset(pages, 0x40, size); ID3D12CommandList* lists[]{gpu.list.p}; @@ -2346,6 +2475,8 @@ int check_mapped_bc_array(ID3D12Device* device) { EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, desc, 6, IID_PPV_ARGS(&texture.p)), S_OK); void* mapped = nullptr; EXPECT_HR(texture->Map(0, nullptr, &mapped), S_OK); + Ref named; // filled from memory once a descriptor names it + EXPECT(!name_texture(device, texture.p, named)); EXPECT(mapped == pages); std::vector columns; std::vector> patterns(x.mips * x.depth_or_array); @@ -2393,9 +2524,6 @@ int main(int argc, char** argv) { const bool prefix_only = argc == 2 && std::strcmp(argv[1], "--host-prefix-only") == 0; const bool async_plane = argc == 2 && std::strcmp(argv[1], "--mapped-plane-async") == 0; if (argc != 1 && !prefix_only && !async_plane) return 2; - if (async_plane) _putenv_s("LEONIDA_TEXTURE_REFRESH_ASYNC", "1"); // read once, at the device's first refresh - _putenv_s("LEONIDA_TITLE_TEXTURE_PERIOD_MS", "0"); - _putenv_s("LEONIDA_TITLE_TEXTURE_CHECK_KB", "0"); vktest::Device vk; const auto status = vk.initialize(); if (status == vktest::DeviceStatus::unavailable) return 77; @@ -2441,6 +2569,8 @@ int main(int argc, char** argv) { failures += check_placed_view_map_changes(ours.p); failures += check_shared_bc_placements(ours.p); failures += check_mapped_plane(ours.p); + failures += check_texture_over_render_target(ours.p); + failures += check_view_over_render_target(ours.p); for (const DWORD modifier : {DWORD(0), DWORD(PAGE_WRITECOMBINE)}) failures += check_mapped_plane_byte(ours.p, modifier); failures += check_mapped_bc_array(ours.p); diff --git a/runtime/test/d3d12_heap_in_place_test.cpp b/runtime/test/d3d12_heap_in_place_test.cpp new file mode 100644 index 0000000000..de79aee981 --- /dev/null +++ b/runtime/test/d3d12_heap_in_place_test.cpp @@ -0,0 +1,479 @@ +// A console descriptor heap read in place (DeviceState::add_heap_in_place): its pages are the title's, in a reservation +// xmem placed in the page mirror's range; shaders read them at heap_base + an offset below 4 GiB (the pages bound a +// second time into the arena), through the mirror's homes, which the filter fills (filter_heap_page). Checked, with the +// GPU reading where a shader would (arena_gpu_read) and the CPU reading the title's own memory: +// 1. the title's bytes are never changed: what the title wrote stays, byte for byte, while the GPU reads the filtered +// slots: a V# whose base is nobody's (past the mirror's range) has no base and no records there, a data word in a +// V#'s place reads null, a V# into the arena and one into the mirror read exactly as written, a zero slot zero; +// 2. a slot the title rewrites (through its own view: a guard fault) reaches the GPU at the next refresh, filtered; +// the title's bytes are again as written; +// 3. the null slots after the heap read zero, and the heap's address is below 4 GiB; +// 4. no copy: the device names it "read in place"; +// 5. a T# in the heap (the words CreateShaderResourceView wrote for a texture of ours) reads with the bindless index +// in its dword 6 (gfx10_descriptors.h, tsharp_index_word: the tag and the texture's index) once the filter and its +// finishing have run, while the title's bytes keep the dword 6 the title wrote; +// 6. a texture the title places in its own memory (device slot 133, in a reservation at 16 TiB and up) where a slot-70 +// view had made a texture of the layer's first, named by a T# the title writes itself (its dword 6 the title's, so +// the T# is found by its address), binds: tag and index (the slot-70 texture's retirement used to take the +// address from the placed one, and the T# found no texture); when the texture goes the slot reads the fallback +// (0: vulkan_bindless.h's 1x1 zeros), and a texture placed again at the address binds it again; +// 7. data the title keeps inline in a heap page (four words a compute program reads as sizes, which look like a V# with +// a base nothing holds) and a V# of the title pointing at them: after a slot of the same page is rewritten (the +// filter runs), the V#'s address (the title's address, through the mirror) reads the title's four words exactly, +// the table address reads the filtered entries (that "V#" null whole, the rewritten slot filtered), and the +// title's bytes are unchanged. With one filtered home bound at both addresses, the V# read [0 0 0 720]. +// Exit 77 when the device makes no page mirror (llvmpipe). No shaders, no game data. +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" +#include "../shims/shims.h" +#include "../shims/xmem.h" +#include "../src/gfx10_descriptors.h" +#include "../src/title_mirror_space.h" +#include "../src/title_va_alias.h" + +#include +#include +#include +#include +#include + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "heap in place line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +namespace { + +using XMemVirtualAllocFn = void*(WINAPI*)(void*, SIZE_T, DWORD, ULONGLONG, DWORD); +using XMemAllocatePhysicalPagesFn = BOOL(WINAPI*)(std::uint64_t, std::uint64_t*, std::uint64_t*); +using XMemFreePhysicalPagesFn = BOOL(WINAPI*)(std::uint64_t, const std::uint64_t*); +using XMemMapPhysicalPagesFn = void*(WINAPI*)(void*, std::uint64_t, const std::uint64_t*); +constexpr DWORD kXmem64kPages = 0x20400000; +constexpr SIZE_T kPage64k = 0x10000; +constexpr unsigned kPages = 4; +constexpr UINT kDescriptor = 32; + +template +struct Ref { + T* p = nullptr; + ~Ref() { reset(); } + void reset() { + if (p) p->Release(); + p = nullptr; + } +}; + +leonida::gfx10::BufferWords raw_vsharp(std::uint64_t address, std::uint32_t bytes) { + leonida::gfx10::Buffer b{}; + b.address = address; + b.num_records = bytes; + b.format = leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT); + b.oob_select = leonida::gfx10::OobSelect::raw; + return leonida::gfx10::encode(b); +} +// Device slot 133 (CreatePlacedResourceX) as the title calls it: (va, desc, layout, clear, riid, out). +using SlotFn = std::uint64_t(WINAPI*)(void*, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, + std::uint64_t, std::uint64_t); +HRESULT place(void* xbox, void* va, const D3D12_RESOURCE_DESC& desc, ID3D12Resource** out) { + void* const* vtable = *static_cast(xbox); + const GUID iid = __uuidof(ID3D12Resource); + const std::uint64_t r = reinterpret_cast(vtable[133])( + xbox, reinterpret_cast(va), reinterpret_cast(&desc), 0xFFFFFFFFull, 0, + reinterpret_cast(&iid), reinterpret_cast(out)); + return static_cast(static_cast(r)); +} + +std::uint64_t base_of(const std::uint32_t* w) { return std::uint64_t(w[0]) | (std::uint64_t(w[1] & 0xFFFFu) << 32); } + +int test() { + _putenv_s("LEONIDA_IMPORT_BELOW_ARENA", "1"); // signed V# offsets, as the sparse arena needs + 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")); + EXPECT(reserve && allocate && map && free_pages); + Ref device; + if (FAILED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&device.p))) || !device.p) { + std::puts("SKIP: no standalone Vulkan device"); + return 77; + } + if (!rt::d3d12::page_mirror_state(device.p).on) { + std::puts("SKIP: the device made no page mirror (see its line above)"); + return 77; + } + // The title's heap memory: physical pages in a reservation in the mirror's range. + auto* title = static_cast(reserve(nullptr, kPages * kPage64k, MEM_RESERVE | kXmem64kPages, 0, + PAGE_READWRITE)); + EXPECT(title && leonida::title_mirror_space::contains(std::uintptr_t(title))); + std::uint64_t pages[kPages]{}, count = kPages; + EXPECT(allocate(0x280, &count, pages) && count == kPages); + EXPECT(map(title, kPages, pages) == title); + std::memset(title, 0, kPages * kPage64k); + + // A buffer of ours in the arena. + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = 64 * 1024; + desc.Height = 1; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + Ref buffer; + EXPECT(SUCCEEDED(device.p->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&buffer.p)))); + const std::uint64_t arena_va = buffer.p->GetGPUVirtualAddress(); + const std::uint64_t nobody = 0x500000000000ull; // 80 TiB: past the mirror's range, nothing of ours + const std::uint64_t mirrored = std::uintptr_t(title) + 3 * kPage64k; + + const auto put = [&](unsigned slot, const leonida::gfx10::BufferWords& w) { + std::memcpy(title + slot * kDescriptor, w.data(), sizeof(w)); + }; + // A texture of ours and its T#, as CreateShaderResourceView writes it into a CPU heap (before the index word is on: + // dword 6 as encode() writes it). The index word is then on, as a library of modules that read it turns it on. + D3D12_RESOURCE_DESC tex_desc{}; + tex_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + tex_desc.Width = 64; + tex_desc.Height = 64; + tex_desc.DepthOrArraySize = 1; + tex_desc.MipLevels = 1; + tex_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + tex_desc.SampleDesc.Count = 1; + Ref texture; + EXPECT(SUCCEEDED(device.p->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &tex_desc, + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, nullptr, + IID_PPV_ARGS(&texture.p)))); + const D3D12_DESCRIPTOR_HEAP_DESC cpu_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, + 0}; + Ref cpu_heap; + EXPECT(SUCCEEDED(device.p->CreateDescriptorHeap(&cpu_desc, IID_PPV_ARGS(&cpu_heap.p)))); + const D3D12_CPU_DESCRIPTOR_HANDLE cpu = cpu_heap.p->GetCPUDescriptorHandleForHeapStart(); + device.p->CreateShaderResourceView(texture.p, nullptr, cpu); + std::uint32_t tsharp[8]; + std::memcpy(tsharp, reinterpret_cast(cpu.ptr), sizeof(tsharp)); + leonida::gfx10::ImageWords tsharp_words{}; + std::memcpy(tsharp_words.data(), tsharp, sizeof(tsharp_words)); + EXPECT(leonida::gfx10::is_image(tsharp_words) && !leonida::gfx10::has_tsharp_index(tsharp_words)); + tsharp[leonida::gfx10::kTsharpIndexDword] = 0x00C0FFEEu; // the title's own dword 6 (compression metadata) + rt::d3d12::set_tsharp_index_words_for_test(device.p, true); + + put(0, raw_vsharp(arena_va, 256)); + put(1, raw_vsharp(nobody, 256)); + put(2, raw_vsharp(mirrored, 256)); + const std::uint32_t data[8] = {0x12345000u, 0x00007777u, 0x00000400u, 0x40000000u, 1, 2, 3, 4}; + std::memcpy(title + 3 * kDescriptor, data, sizeof(data)); + std::memcpy(title + 6 * kDescriptor, tsharp, sizeof(tsharp)); + std::uint8_t written[5 * kDescriptor]; + std::memcpy(written, title, sizeof(written)); + + const UINT slots = UINT(kPages * kPage64k / kDescriptor); + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, slots, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + Ref heap; + EXPECT(SUCCEEDED(rt::d3d12::create_console_descriptor_heap(device.p, &heap_desc, std::uintptr_t(title), + kPages * kPage64k, 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)); + EXPECT(shader_va && shader_va + kPages * kPage64k <= (1ull << 32)); // 3: 32-bit table pointers reach it + + // 1. The GPU reads the filtered slots; the title's bytes are as written. + std::uint32_t gpu[5][8]{}; + EXPECT(rt::d3d12::arena_gpu_read(device.p, shader_va, gpu, sizeof(gpu))); + EXPECT(!std::memcmp(gpu[0], written, kDescriptor)); // arena V#: as written + EXPECT(base_of(gpu[1]) == 0 && gpu[1][2] == 0); // nobody's: no base, no records + EXPECT(!std::memcmp(gpu[2], written + 2 * kDescriptor, kDescriptor)); // mirror V#: as written + EXPECT(!(gpu[3][0] | gpu[3][1] | gpu[3][2] | gpu[3][3])); // data in a V#'s place: null + EXPECT(!(gpu[4][0] | gpu[4][1] | gpu[4][2] | gpu[4][3])); // zero + EXPECT(!std::memcmp(title, written, sizeof(written))); // the title's bytes untouched + std::uint32_t nobody_words[8]; + std::memcpy(nobody_words, title + kDescriptor, sizeof(nobody_words)); + EXPECT(base_of(nobody_words) == nobody); + + // 2. The title rewrites slot 1 through its own view, from another thread (its write faults on the mirror's + // guard): the next refresh filters it; the title keeps what it wrote. + const auto rewritten = raw_vsharp(arena_va + 512, 128); + std::thread([&] { put(1, rewritten); }).join(); + EXPECT(rt::d3d12::arena_gpu_read(device.p, shader_va + kDescriptor, gpu[1], kDescriptor)); + EXPECT(!std::memcmp(gpu[1], rewritten.data(), sizeof(rewritten))); + EXPECT(!std::memcmp(title + kDescriptor, rewritten.data(), sizeof(rewritten))); + // And back to nobody's: filtered again, the title's bytes as written. + std::thread([&] { put(1, raw_vsharp(nobody, 256)); }).join(); + EXPECT(rt::d3d12::arena_gpu_read(device.p, shader_va + kDescriptor, gpu[1], kDescriptor)); + EXPECT(base_of(gpu[1]) == 0 && gpu[1][2] == 0); + std::memcpy(nobody_words, title + kDescriptor, sizeof(nobody_words)); + EXPECT(base_of(nobody_words) == nobody); + + // A store the GPU makes into the heap's pages through the title's address (a V# of the title into its heap) goes + // back to the title's bytes as any page's does: the home there is the title's bytes. The table address, a filtered + // copy of its own, takes it as a rewrite: these words read as a T# naming no texture, left as written there + // apart from dword 6, which is the fallback (0) while nothing binds it. + const std::uint32_t stored[8] = {0xdead0001u, 0xdead0002u, 0xdead0003u, 0xdead0004u, 5, 6, 7, 8}; + EXPECT(rt::d3d12::page_mirror_gpu_write(device.p, std::uintptr_t(title) + 5 * kDescriptor, stored, sizeof(stored))); + EXPECT(rt::d3d12::page_mirror_write_back(device.p, std::uintptr_t(title), kPages * kPage64k) > 0); + EXPECT(!std::memcmp(title + 5 * kDescriptor, stored, sizeof(stored))); + std::uint32_t stored_entry[8]{}; + EXPECT(rt::d3d12::arena_gpu_read(device.p, shader_va + 5 * kDescriptor, stored_entry, sizeof(stored_entry))); + for (unsigned i = 0; i < 8; ++i) + EXPECT(stored_entry[i] == (i == leonida::gfx10::kTsharpIndexDword ? 0u : stored[i])); + std::thread([&] { std::memset(title + 5 * kDescriptor, 0, kDescriptor); }).join(); // as before, for the cases below + + // 5. The T#: dword 6 carries the tag and the texture's index, the other words as written; the title's dword 6 is + // its own. + std::uint32_t gpu_tsharp[8]{}; + EXPECT(rt::d3d12::arena_gpu_read(device.p, shader_va + 6 * kDescriptor, gpu_tsharp, sizeof(gpu_tsharp))); + const std::uint32_t word = gpu_tsharp[leonida::gfx10::kTsharpIndexDword]; + EXPECT((word >> 28) == leonida::gfx10::kTsharpIndexTag && (word & 0xFFFFu) != 0); + for (unsigned i = 0; i < 8; ++i) + if (i != leonida::gfx10::kTsharpIndexDword) EXPECT(gpu_tsharp[i] == tsharp[i]); + EXPECT(!std::memcmp(title + 6 * kDescriptor, tsharp, sizeof(tsharp))); + EXPECT(reinterpret_cast(title + 6 * kDescriptor)[leonida::gfx10::kTsharpIndexDword] == + 0x00C0FFEEu); + + // 6. A texture the title places in its own memory and names by a T# it writes. + { + auto* pixels = static_cast(reserve(nullptr, kPage64k, MEM_RESERVE | kXmem64kPages, 0, + PAGE_READWRITE)); + std::uint64_t pixel_page = 0, one = 1; + EXPECT(pixels && leonida::title_mirror_space::contains(std::uintptr_t(pixels))); + EXPECT(allocate(0x280, &one, &pixel_page) && one == 1 && map(pixels, 1, &pixel_page) == pixels); + std::memset(pixels, 0x40, kPage64k); + device.p->AddRef(); // the proxy takes one reference + Ref xbox; + EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(device.p, __uuidof(ID3D12Device), + reinterpret_cast(&xbox.p)))); + rt::d3d12::set_device_outer(device.p, xbox.p); + D3D12_RESOURCE_DESC placed_desc = tex_desc; + placed_desc.Layout = static_cast(0x100); + // First a slot-70 view of the memory, before any texture is placed there: the layer makes a texture of its + // own for it (the title's order for memory it streams into and then places a texture on). + std::array resource_words{}; + std::memcpy(resource_words.data(), &placed_desc, sizeof(placed_desc)); + D3D12_SHADER_RESOURCE_VIEW_DESC view{}; + view.Format = placed_desc.Format; + view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + view.Texture2D.MipLevels = 1; + std::array view_words{}; + std::memcpy(view_words.data(), &view, sizeof(view)); + leonida::gfx10::ImageWords streamed{}; + EXPECT(rt::d3d12::write_placed_texture_view(device.p, false, resource_words.data(), view_words.data(), + std::uintptr_t(pixels), + {reinterpret_cast(streamed.data())})); + // Then the texture placed there (slot 133): it takes the address over. + Ref placed; + EXPECT(place(xbox.p, pixels, placed_desc, &placed.p) == S_OK && placed.p); + EXPECT(placed.p->GetGPUVirtualAddress() == std::uintptr_t(pixels)); + // The T# the title writes: the words a view of the texture has, with the title's own dword 6. + device.p->CreateShaderResourceView(placed.p, nullptr, cpu); + std::uint32_t named[8]; + std::memcpy(named, reinterpret_cast(cpu.ptr), sizeof(named)); + leonida::gfx10::ImageWords named_words{}; + std::memcpy(named_words.data(), named, sizeof(named_words)); + leonida::gfx10::Image named_image{}; + EXPECT(leonida::gfx10::decode(named_words, named_image) && named_image.address == std::uintptr_t(pixels)); + named[leonida::gfx10::kTsharpIndexDword] = 0x00BEEF00u; + std::thread([&] { std::memcpy(title + 7 * kDescriptor, named, sizeof(named)); }).join(); + std::uint32_t got[8]{}; + EXPECT(rt::d3d12::arena_gpu_read(device.p, shader_va + 7 * kDescriptor, got, sizeof(got))); + const std::uint32_t placed_word = got[leonida::gfx10::kTsharpIndexDword]; + std::printf("placed texture at 0x%llx: the T# reads index word 0x%08x\n", + static_cast(std::uintptr_t(pixels)), placed_word); + EXPECT((placed_word >> 28) == leonida::gfx10::kTsharpIndexTag && (placed_word & 0xFFFFu) != 0); + EXPECT(reinterpret_cast(title + 7 * kDescriptor)[leonida::gfx10::kTsharpIndexDword] == + 0x00BEEF00u); + // The texture goes: the slot waits and reads the fallback. Another placed at the address: bound again. + placed.reset(); + EXPECT(rt::d3d12::arena_gpu_read(device.p, shader_va + 7 * kDescriptor, got, sizeof(got))); + EXPECT(got[leonida::gfx10::kTsharpIndexDword] == 0); + Ref again; + EXPECT(place(xbox.p, pixels, placed_desc, &again.p) == S_OK && again.p); + EXPECT(rt::d3d12::arena_gpu_read(device.p, shader_va + 7 * kDescriptor, got, sizeof(got))); + const std::uint32_t again_word = got[leonida::gfx10::kTsharpIndexDword]; + EXPECT((again_word >> 28) == leonida::gfx10::kTsharpIndexTag && (again_word & 0xFFFFu) != 0); + again.reset(); + rt::d3d12::set_device_outer(device.p, nullptr); + xbox.reset(); + EXPECT(map(pixels, 1, nullptr) == pixels && free_pages(1, &pixel_page)); + } + + // 7. Inline data in the heap's page, read through a V# of the title. + { + const std::uint32_t sizes[4] = {512, 256, 1280, 720}; // a "V#" of base 0x100_00000200, nothing there + const std::uint64_t data_va = std::uintptr_t(title) + 10 * kDescriptor; + const auto pointer = raw_vsharp(data_va, sizeof(sizes)); + std::thread([&] { + std::memcpy(title + 10 * kDescriptor, sizes, sizeof(sizes)); + put(11, pointer); + }).join(); + std::uint32_t table[2][8]{}; + EXPECT(rt::d3d12::arena_gpu_read(device.p, shader_va + 10 * kDescriptor, table, sizeof(table))); + // A slot of the same page rewritten: the filter runs over the page again. + const auto other = raw_vsharp(arena_va + 1024, 64); + std::thread([&] { put(1, other); }).join(); + EXPECT(rt::d3d12::arena_gpu_read(device.p, shader_va + 10 * kDescriptor, table, sizeof(table))); + std::uint32_t through_vsharp[4]{}; + EXPECT(rt::d3d12::page_mirror_gpu_read(device.p, data_va, through_vsharp, sizeof(through_vsharp))); + std::printf("inline data: through the V# [%u %u %u %u], through the table [%u %u %u %u]\n", through_vsharp[0], + through_vsharp[1], through_vsharp[2], through_vsharp[3], table[0][0], table[0][1], table[0][2], + table[0][3]); + EXPECT(!std::memcmp(through_vsharp, sizes, sizeof(sizes))); // the title's words, exactly + EXPECT(!(table[0][0] | table[0][1] | table[0][2] | table[0][3])); // null whole in the table + EXPECT(!std::memcmp(table[1], pointer.data(), sizeof(pointer))); // the V#: mirrored, as written + std::uint32_t rewritten_entry[8]{}; + EXPECT(rt::d3d12::arena_gpu_read(device.p, shader_va + kDescriptor, rewritten_entry, kDescriptor)); + EXPECT(!std::memcmp(rewritten_entry, other.data(), sizeof(other))); // filtered: an arena V# + EXPECT(!std::memcmp(title + 10 * kDescriptor, sizes, sizeof(sizes))); // the title's bytes unchanged + EXPECT(!std::memcmp(title + 11 * kDescriptor, pointer.data(), sizeof(pointer))); + } + + // 8. Oversized & out-of-range V# regression: an in-place heap V# naming > 256 MiB (past kMirrorNameMax) of a committed plain + // region inside title_mirror_space must NEVER create an orphan TitleWindow, must null the filtered copy while + // keeping the title's bytes intact, and repeated V# halves must answer identically without creating windows. + // Also verify O(1)-rejected bit-47 and out-of-arena-span V# halves null cleanly. + { + constexpr SIZE_T kBigReserve = 300ull << 20; + constexpr std::uint32_t kOverMirrorMax = 260u << 20; // > kMirrorNameMax (256 MiB) + auto* big_plain = static_cast(reserve(nullptr, kBigReserve, MEM_RESERVE, 0, PAGE_READWRITE)); + EXPECT(big_plain && leonida::title_mirror_space::contains(std::uintptr_t(big_plain))); + EXPECT(VirtualAlloc(big_plain, kPage64k, MEM_COMMIT, PAGE_READWRITE) == big_plain); + std::memset(big_plain, 0x5A, kPage64k); + const std::size_t aliases_before = leonida::title_va_aliases().size(); + + const auto wide_vsharp = raw_vsharp(std::uintptr_t(big_plain), kOverMirrorMax); + const auto bit47_vsharp = raw_vsharp((1ull << 47) | 0x200000ull, 256); + const std::uint64_t arena_sz = rt::d3d12::device_arena_size(device.p); + // base < arena_sz with span > arena_sz - base (fails reachable_as_written; O(1)-rejected in filter). + leonida::gfx10::Buffer over_arena{}; + over_arena.address = arena_sz > 0x10000 ? arena_sz - 0x10000 : 0x10000; + over_arena.stride = 16; + over_arena.num_records = 0x4000; // 256 KiB > 64 KiB remaining in arena + over_arena.format = leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT); + const auto over_arena_vsharp = leonida::gfx10::encode(over_arena); + + std::thread([&] { + put(12, wide_vsharp); + put(13, wide_vsharp); // repeated V# half in same batch + put(14, bit47_vsharp); + put(15, over_arena_vsharp); + }).join(); + std::uint32_t out[4][8]{}; + EXPECT(rt::d3d12::arena_gpu_read(device.p, shader_va + 12 * kDescriptor, out, sizeof(out))); + for (int i = 0; i < 4; ++i) EXPECT(!(out[i][0] | out[i][1] | out[i][2] | out[i][3])); + // Write another repeated wide V# on a subsequent submission (hits heap.records.answer()). + std::thread([&] { put(16, wide_vsharp); }).join(); + std::uint32_t repeat_out[8]{}; + EXPECT(rt::d3d12::arena_gpu_read(device.p, shader_va + 16 * kDescriptor, repeat_out, sizeof(repeat_out))); + EXPECT(!(repeat_out[0] | repeat_out[1] | repeat_out[2] | repeat_out[3])); + + // Zero orphan TitleWindows created in title_va_aliases. + EXPECT(leonida::title_va_aliases().size() == aliases_before); + EXPECT(leonida::title_va_aliases().shader_va(std::uintptr_t(big_plain)) == std::uintptr_t(big_plain)); + // Title's own bytes remain untouched. + EXPECT(!std::memcmp(title + 12 * kDescriptor, wide_vsharp.data(), sizeof(wide_vsharp))); + EXPECT(!std::memcmp(title + 14 * kDescriptor, bit47_vsharp.data(), sizeof(bit47_vsharp))); + EXPECT(VirtualFree(big_plain, 0, MEM_RELEASE)); + } + + // 9. Deferred-slot and pending-alias regressions: + // (a) A slot queued in heap.deferred by apply_in_place_changes (texture_gone) and overwritten in the same + // refresh's upload() with non-T# words (w[3] >> 30 != 0, !is_image) must zero w[0..3] in finish_in_place + // instead of writing raw unfiltered words into home[slot]; + // (b) A V# naming base >= arena.size not yet in title_memory or aliases is nulled and recorded as waiting, so + // adding an alias for that base later wakes and rebases the slot automatically. + { + // (a) Trigger apply_in_place_changes (texture_gone -> queues slot 17 in heap.deferred) + concurrent page write + // of raw non-T# words into slot 17 before refresh, forcing finish_in_place() to see not_tsharp. + Ref tmp_tex; + EXPECT(SUCCEEDED(device.p->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &tex_desc, + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, nullptr, + IID_PPV_ARGS(&tmp_tex.p)))); + device.p->CreateShaderResourceView(tmp_tex.p, nullptr, cpu); + std::uint32_t tmp_tsharp[8]; + std::memcpy(tmp_tsharp, reinterpret_cast(cpu.ptr), sizeof(tmp_tsharp)); + tmp_tsharp[leonida::gfx10::kTsharpIndexDword] = 0x00C0FFEEu; + std::thread([&] { std::memcpy(title + 17 * kDescriptor, tmp_tsharp, sizeof(tmp_tsharp)); }).join(); + std::uint32_t bound_tsharp[8]{}; + EXPECT(rt::d3d12::arena_gpu_read(device.p, shader_va + 17 * kDescriptor, bound_tsharp, sizeof(bound_tsharp))); + EXPECT((bound_tsharp[leonida::gfx10::kTsharpIndexDword] >> 28) == leonida::gfx10::kTsharpIndexTag); + + const std::uint32_t bad_non_tsharp[8] = {0xdead0000u, 0x0000ffffu, 0x00000400u, 0x40000000u, 1, 2, 3, 4}; + tmp_tex.reset(); // notes texture_gone -> next refresh's apply_in_place_changes defers slot 17 + std::thread([&] { std::memcpy(title + 17 * kDescriptor, bad_non_tsharp, sizeof(bad_non_tsharp)); }).join(); + std::uint32_t cleared[8]{}; + EXPECT(rt::d3d12::arena_gpu_read(device.p, shader_va + 17 * kDescriptor, cleared, sizeof(cleared))); + EXPECT(!(cleared[0] | cleared[1] | cleared[2] | cleared[3])); + EXPECT(!std::memcmp(title + 17 * kDescriptor, bad_non_tsharp, sizeof(bad_non_tsharp))); + + // (b) V# at unbacked base >= arena.size: nulled initially, then woken and rebased when an alias arrives. + constexpr std::uint64_t kLateVa = 0x510000000000ull; + const auto late_vsharp = raw_vsharp(kLateVa, 256); + std::thread([&] { put(18, late_vsharp); }).join(); + std::uint32_t late_out[8]{}; + EXPECT(rt::d3d12::arena_gpu_read(device.p, shader_va + 18 * kDescriptor, late_out, sizeof(late_out))); + EXPECT(!(late_out[0] | late_out[1] | late_out[2] | late_out[3])); + + EXPECT(leonida::title_va_aliases().add(kLateVa, 4096, arena_va)); + EXPECT(rt::d3d12::arena_gpu_read(device.p, shader_va + 18 * kDescriptor, late_out, sizeof(late_out))); + EXPECT(base_of(late_out) == arena_va && late_out[2] == 256); + + leonida::title_va_aliases().remove(kLateVa, arena_va); + EXPECT(rt::d3d12::arena_gpu_read(device.p, shader_va + 18 * kDescriptor, late_out, sizeof(late_out))); + EXPECT(!(late_out[0] | late_out[1] | late_out[2] | late_out[3])); + } + + // 10. With a live console resource heap (console_heap_count > 0), unpromoted slot-133 BC placements sharing + // zero_sampled_image deduplicate onto a single bindless slot, and promoting one gives it a private slot + // while leaving the other intact on the shared zero slot. + { + constexpr UINT width = 32, height = 32, pitch = width / 4 * 8; + void* bc_pages = VirtualAlloc(nullptr, 2 * kPage64k, MEM_RESERVE, PAGE_NOACCESS); + EXPECT(bc_pages); + D3D12_RESOURCE_DESC bc_desc{}; + bc_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + bc_desc.Width = width; + bc_desc.Height = height; + bc_desc.DepthOrArraySize = bc_desc.MipLevels = bc_desc.SampleDesc.Count = 1; + bc_desc.Format = DXGI_FORMAT_BC1_UNORM; + Ref bc_a, bc_b; + EXPECT(SUCCEEDED(rt::d3d12::create_buffer_at_host_address(device.p, bc_pages, bc_desc, 0, + IID_PPV_ARGS(&bc_a.p)))); + EXPECT(SUCCEEDED(rt::d3d12::create_buffer_at_host_address( + device.p, static_cast(bc_pages) + kPage64k, bc_desc, 0, IID_PPV_ARGS(&bc_b.p)))); + std::uint32_t av[8]{}, bv[8]{}; + device.p->CreateShaderResourceView(bc_a.p, nullptr, {reinterpret_cast(av)}); + device.p->CreateShaderResourceView(bc_b.p, nullptr, {reinterpret_cast(bv)}); + const std::uint32_t first = rt::d3d12::bindless_hash_lookup(device.p, av); + const std::uint32_t second = rt::d3d12::bindless_hash_lookup(device.p, bv); + const bool shared = !rt::d3d12::vulkan_memory_flags(bc_a.p); + EXPECT(first && second); + if (shared) EXPECT(first == second); + std::array pattern{}; + for (std::size_t i = 0; i < pattern.size(); ++i) pattern[i] = std::uint8_t(i * 11 + 37); + EXPECT(SUCCEEDED(bc_a.p->WriteToSubresource(0, nullptr, pattern.data(), pitch, UINT(pattern.size())))); + EXPECT(rt::d3d12::vulkan_memory_flags(bc_a.p)); + const std::uint32_t private_a = rt::d3d12::bindless_hash_lookup(device.p, av); + EXPECT(private_a && (!shared || private_a != first)); + EXPECT(rt::d3d12::bindless_hash_lookup(device.p, bv) == second); + bc_a.reset(); + bc_b.reset(); + EXPECT(VirtualFree(bc_pages, 0, MEM_RELEASE)); + } + + // 3. The null slots after the heap. + std::uint32_t tail[64]{}; + std::memset(tail, 0xff, sizeof(tail)); + EXPECT(rt::d3d12::arena_gpu_read(device.p, shader_va + kPages * kPage64k, tail, sizeof(tail))); + for (const std::uint32_t word : tail) EXPECT(word == 0); + + std::printf("heap in place: at heap_base + 0x%llx; the GPU reads a nobody's V# and a data word null and the others " + "as written, a rewrite at the next refresh, zeros after the heap, a T# with its index word (0x%08x); the title's bytes never change\n", + static_cast(shader_va), word); + heap.reset(); + EXPECT(map(title, kPages, nullptr) == title && free_pages(kPages, pages)); + return 0; +} + +} // namespace + +int main() { return test(); } diff --git a/runtime/test/d3d12_page_mirror_test.cpp b/runtime/test/d3d12_page_mirror_test.cpp new file mode 100644 index 0000000000..d4deaf1450 --- /dev/null +++ b/runtime/test/d3d12_page_mirror_test.cpp @@ -0,0 +1,308 @@ +// The page mirror in the game's device (src/title_mirror.h, DeviceState::refresh_page_mirror) over xmem's pages: the +// stream pool's shape (a CPU view with the title's physical pages, a GPU-only alias that queue slot 31 gives pages by +// table), placed by xmem in the mirror's range. What a shader reads at heap_base + a title address (a V# or pointer the +// title wrote) is read back with the GPU after the mirror's last bind (page_mirror_gpu_read): +// 1. the GPU-only page after a slot-31 copy, its CPU twin and the title's own view hold the title's bytes; +// 2. a write by the title's CPU through its own view reaches all three at the next refresh (the geometry watch's cell +// over the view faults, the page's home is filled again once); +// 3. a remap of the GPU-only page (another physical page) is a rebind: the next read sees the new page, and no host +// remap was made; +// 4. a page of the reservation nothing is mapped at reads zero, with no fault; +// 5. ordinary memory (committed XMemVirtualAlloc pages) is mirrored when a reader names it: a constant-buffer view +// keeps the title's address as its base, the GPU reads the bytes and a later title write there, and a binding of +// it is served by the mirror's chunk; +// 6. a slot-133 buffer over mirrored memory is the mirror's chunk (no shadow); the GPU's writes into it go back to +// the title's page, and a 256-byte piece written on both sides keeps the title's bytes; +// 7. one page, the GPU writes piece A and the title piece B in the same submission window (the title's write is +// uploaded before the GPU's goes back): both survive, on both sides; +// 8. XMemAlloc blocks lie in the mirror's range and are mirrored as the heap commits them: the GPU reads a small and +// a large block's bytes through a pointer into them that nothing named; +// 9. the write-back over 64 MiB (one submission's most) returns the one piece the GPU wrote, in well under a second. +// Exit 77 when the device makes no page mirror (no sparse aliased strict buffers or capture-replay addresses: llvmpipe). +// No shaders, no game data. +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" +#include "../shims/shims.h" +#include "../shims/xmem.h" +#include "../src/title_mirror_space.h" +#include "../src/title_page_watch.h" +#include "../src/title_va_alias.h" + +#include +#include +#include +#include +#include + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "page mirror line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +namespace { + +using XMemVirtualAllocFn = void*(WINAPI*)(void*, SIZE_T, DWORD, ULONGLONG, DWORD); +using XMemAllocFn = void*(__stdcall*)(size_t, std::uint64_t); +using XMemFreeFn = void(__stdcall*)(void*, std::uint64_t); +using XMemAllocatePhysicalPagesFn = BOOL(WINAPI*)(std::uint64_t, std::uint64_t*, std::uint64_t*); +using XMemFreePhysicalPagesFn = BOOL(WINAPI*)(std::uint64_t, const std::uint64_t*); +using XMemMapPhysicalPagesFn = void*(WINAPI*)(void*, std::uint64_t, const std::uint64_t*); +constexpr DWORD kXmem64kPages = 0x20400000; +constexpr SIZE_T kPage64k = 0x10000; + +template +struct Ref { + T* p = nullptr; + ~Ref() { if (p) p->Release(); } +}; + +std::uint32_t gpu_word(ID3D12Device* device, std::uint64_t va) { + std::uint32_t word = 0xdeadbeef; + if (!rt::d3d12::page_mirror_gpu_read(device, va, &word, sizeof(word))) return 0xdeadbeef; + return word; +} + +int test() { + // Signed V# offsets (the sparse arena needs them): as a pack of sign-extending modules gives. + _putenv_s("LEONIDA_IMPORT_BELOW_ARENA", "1"); + 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")); + EXPECT(reserve && allocate && map && free_pages); + Ref device; + if (FAILED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&device.p))) || !device.p) { + std::puts("SKIP: no standalone Vulkan device"); + return 77; + } + const auto state = rt::d3d12::page_mirror_state(device.p); + if (!state.on) { + std::puts("SKIP: the device made no page mirror (see its line above)"); + return 77; + } + constexpr unsigned n = 8; + auto window = [&](DWORD protect) { + return static_cast(reserve(nullptr, n * kPage64k, MEM_RESERVE | kXmem64kPages, 0, protect)); + }; + 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_mirror_space::contains(std::uintptr_t(dst)) && leonida::title_gpu_views::to_cpu(std::uintptr_t(dst)) == std::uintptr_t(cpu)); + std::uint64_t pages[2]{}, count = 2; + EXPECT(allocate(0x280, &count, pages) && count == 2); + EXPECT(map(pool_cpu, 2, pages) == pool_cpu); + auto* words = reinterpret_cast(pool_cpu); + for (unsigned i = 0; i < 2 * kPage64k / 4; i += 1024) words[i] = 0x51000000u + i; + words[kPage64k / 4] = 0x52000000u; // page 1's first word + + // 1. A slot-31 copy onto the GPU-only range (pages found through the pool's CPU view). + rt::xmem::Slot31Counts before{}; + rt::xmem::slot31_mapping_counts(before); + EXPECT(rt::xmem::copy_page_mappings_fn && rt::xmem::copy_page_mappings_fn(dst, pool, 2, false)); + EXPECT(gpu_word(device.p, std::uintptr_t(dst) + 4096) == 0x51000400u); + EXPECT(gpu_word(device.p, std::uintptr_t(cpu) + 4096) == 0x51000400u); + EXPECT(gpu_word(device.p, std::uintptr_t(pool_cpu) + 4096) == 0x51000400u); + EXPECT(gpu_word(device.p, std::uintptr_t(dst) + kPage64k) == 0x52000000u); + + // 2. The title's CPU writes through its own view: one fault, one upload, seen at every address of the page. + const auto uploads = rt::d3d12::page_mirror_state(device.p).uploads; + std::thread([&] { words[1024] = 0x5eed0001u; }).join(); + EXPECT(gpu_word(device.p, std::uintptr_t(dst) + 4096) == 0x5eed0001u); + EXPECT(gpu_word(device.p, std::uintptr_t(cpu) + 4096) == 0x5eed0001u); + EXPECT(rt::d3d12::page_mirror_state(device.p).uploads == uploads + 1); + + // 3. A remap of the GPU-only page to the pool's second page: a rebind, no host remap. + EXPECT(rt::xmem::copy_page_mappings_fn(dst, pool + kPage64k, 1, false)); + EXPECT(gpu_word(device.p, std::uintptr_t(dst)) == 0x52000000u); + EXPECT(gpu_word(device.p, std::uintptr_t(cpu)) == 0x52000000u); + rt::xmem::Slot31Counts after{}; + rt::xmem::slot31_mapping_counts(after); + EXPECT(after.host() == before.host()); + + // 4. A page of the reservation with nothing mapped. + EXPECT(gpu_word(device.p, std::uintptr_t(dst) + 5 * kPage64k) == 0); + + // 5. Ordinary memory (an XMemVirtualAlloc region of committed pages) is mirrored when a reader names it: a + // constant-buffer view over it keeps the title's address as its V# base (heap_base + it is the mirror, no copy), + // the GPU reads the bytes there, and a title write reaches it at the next refresh. A draw's binding of it is + // served by the mirror's chunk. + auto* plain = static_cast(reserve(nullptr, 2 * kPage64k, MEM_RESERVE | MEM_COMMIT, 0, PAGE_READWRITE)); + EXPECT(plain && leonida::title_mirror_space::contains(std::uintptr_t(plain))); + auto* plain_words = reinterpret_cast(plain); + plain_words[0x40] = 0x61000040u; + std::uint64_t unnamed = 64; + EXPECT(!rt::d3d12::page_mirror_buffer_at(device.p, std::uintptr_t(plain), unnamed)); // not named yet + D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + Ref heap; + EXPECT(SUCCEEDED(device.p->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap.p)))); + const D3D12_CPU_DESCRIPTOR_HANDLE handle = heap.p->GetCPUDescriptorHandleForHeapStart(); + const D3D12_CONSTANT_BUFFER_VIEW_DESC view{std::uintptr_t(plain), 0x200}; + device.p->CreateConstantBufferView(&view, handle); + std::uint32_t vsharp[4]{}; + std::memcpy(vsharp, reinterpret_cast(handle.ptr), sizeof(vsharp)); + const std::uint64_t base = std::uint64_t(vsharp[0]) | (std::uint64_t(vsharp[1] & 0xffffu) << 32); + EXPECT(base == (std::uintptr_t(plain) & 0xFFFFFFFFFFFFull)); + EXPECT(gpu_word(device.p, std::uintptr_t(plain) + 0x100) == 0x61000040u); + std::thread([&] { plain_words[0x40] = 0x61000041u; }).join(); + EXPECT(gpu_word(device.p, std::uintptr_t(plain) + 0x100) == 0x61000041u); + std::uint64_t binding = 0x200; + EXPECT(rt::d3d12::page_mirror_buffer_at(device.p, std::uintptr_t(plain), binding) && binding == 0x200); + // The second page, named on its own (a vertex view's range), and a GPU-only page (physical: mirrored as mapped). + plain_words[kPage64k / 4] = 0x62000000u; + EXPECT(rt::d3d12::page_mirror_name(device.p, std::uintptr_t(plain) + kPage64k, 64)); + EXPECT(gpu_word(device.p, std::uintptr_t(plain) + kPage64k) == 0x62000000u); + std::uint64_t pool_binding = 256; + EXPECT(rt::d3d12::page_mirror_buffer_at(device.p, std::uintptr_t(dst), pool_binding)); + + // 6. A slot-133 buffer over mirrored memory is the mirror's chunk there: its GPU VA is the title's address, no + // shadow. What the GPU writes into its home goes back to the title's page (the pieces that differ), and a page + // the title wrote too keeps the title's bytes. + auto* placed = static_cast(reserve(nullptr, kPage64k, MEM_RESERVE | MEM_COMMIT, 0, PAGE_READWRITE)); + EXPECT(placed); + auto* placed_words = reinterpret_cast(placed); + for (unsigned i = 0; i < kPage64k / 4; i += 64) placed_words[i] = 0x71000000u + i; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = kPage64k; + desc.Height = desc.DepthOrArraySize = desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + Ref buffer; + EXPECT(SUCCEEDED(rt::d3d12::create_buffer_at_host_address(device.p, placed, desc, 0xFFFFFFFFu, IID_PPV_ARGS(&buffer.p)))); + EXPECT(buffer.p->GetGPUVirtualAddress() == std::uintptr_t(placed) && !rt::d3d12::title_shadow_buffer(buffer.p)); + EXPECT(gpu_word(device.p, std::uintptr_t(placed) + 0x100) == 0x71000040u); // and the page is guarded now + const std::uint32_t result[4] = {0xC0DE0001u, 0xC0DE0002u, 0xC0DE0003u, 0xC0DE0004u}; + EXPECT(rt::d3d12::page_mirror_gpu_write(device.p, std::uintptr_t(placed) + 0x200, result, sizeof(result))); + EXPECT(placed_words[0x80] == 0x71000080u); // not yet: after the submission retires + EXPECT(rt::d3d12::page_mirror_write_back(device.p, std::uintptr_t(placed), kPage64k) == 256); + EXPECT(placed_words[0x80] == 0xC0DE0001u && placed_words[0x83] == 0xC0DE0004u && placed_words[0x40] == 0x71000040u); + EXPECT(gpu_word(device.p, std::uintptr_t(placed) + 0x200) == 0xC0DE0001u); // the home agrees after the refill + // Written on both sides: the title's write wins. + const std::uint32_t other[4] = {0xBAD00001u, 0xBAD00002u, 0xBAD00003u, 0xBAD00004u}; + EXPECT(rt::d3d12::page_mirror_gpu_write(device.p, std::uintptr_t(placed) + 0x400, other, sizeof(other))); + std::thread([&] { placed_words[0x100] = 0x7171u; }).join(); + EXPECT(rt::d3d12::page_mirror_write_back(device.p, std::uintptr_t(placed), kPage64k) == 0); + EXPECT(placed_words[0x100] == 0x7171u); + EXPECT(gpu_word(device.p, std::uintptr_t(placed) + 0x400) == 0x7171u); + + // 7. Pieces A (0x800) and B (0xc00) of one page: the GPU writes A, the title B; a GPU read refreshes the mirror + // first (B is uploaded, A's home bytes stay), then A goes back to the title's page. + const std::uint32_t gpu_a[4] = {0xA0A00001u, 0xA0A00002u, 0xA0A00003u, 0xA0A00004u}; + EXPECT(rt::d3d12::page_mirror_gpu_write(device.p, std::uintptr_t(placed) + 0x800, gpu_a, sizeof(gpu_a))); + std::thread([&] { placed_words[0x300] = 0xB0B00001u; }).join(); + EXPECT(gpu_word(device.p, std::uintptr_t(placed) + 0xc00) == 0xB0B00001u); + EXPECT(gpu_word(device.p, std::uintptr_t(placed) + 0x800) == 0xA0A00001u); + EXPECT(rt::d3d12::page_mirror_write_back(device.p, std::uintptr_t(placed), kPage64k) == 256); + EXPECT(placed_words[0x200] == 0xA0A00001u && placed_words[0x203] == 0xA0A00004u); + EXPECT(placed_words[0x300] == 0xB0B00001u); + EXPECT(gpu_word(device.p, std::uintptr_t(placed) + 0x800) == 0xA0A00001u); + EXPECT(gpu_word(device.p, std::uintptr_t(placed) + 0xc00) == 0xB0B00001u); + + // 8. XMemAlloc blocks. + auto xmem_alloc = reinterpret_cast(rt::shims::find("xmem.dll", "XMemAlloc")); + auto xmem_free = reinterpret_cast(rt::shims::find("xmem.dll", "XMemFree")); + EXPECT(xmem_alloc && xmem_free); + auto* heap_small = static_cast(xmem_alloc(3000, 0x5e50000)); + auto* heap_large = static_cast(xmem_alloc(200000, 0)); + EXPECT(heap_small && heap_large && std::uintptr_t(heap_small) % 64 == 0); + EXPECT(leonida::title_mirror_space::contains(std::uintptr_t(heap_small)) && + leonida::title_mirror_space::contains(std::uintptr_t(heap_large))); + heap_small[700] = 0x81000700u; + heap_large[40000] = 0x82040000u; + EXPECT(gpu_word(device.p, std::uintptr_t(heap_small) + 2800) == 0x81000700u); + EXPECT(gpu_word(device.p, std::uintptr_t(heap_large) + 160000) == 0x82040000u); + std::thread([&] { heap_small[700] = 0x81000701u; }).join(); + EXPECT(gpu_word(device.p, std::uintptr_t(heap_small) + 2800) == 0x81000701u); + xmem_free(const_cast(heap_small), 0); + xmem_free(const_cast(heap_large), 0); + EXPECT(gpu_word(device.p, std::uintptr_t(heap_large) + 160000) == 0); // decommitted: unmapped, reads zero + + // 9. The write-back over 64 MiB of mirrored memory (the most one submission's write-back covers), the GPU having + // written one piece of it: that piece goes back, and the call takes well under a second. The homes are copied + // out by the GPU; read by the CPU from device-local memory it took 1.6 s for 16 MiB here, 14.5 s in run 64w. + { + constexpr SIZE_T kBig = 64u << 20; + auto* big = static_cast(reserve(nullptr, kBig, MEM_RESERVE | MEM_COMMIT, 0, PAGE_READWRITE)); + EXPECT(big && rt::d3d12::page_mirror_name(device.p, std::uintptr_t(big), kBig)); + const std::uint32_t mark[4] = {0x9A9A0001u, 0x9A9A0002u, 0x9A9A0003u, 0x9A9A0004u}; + EXPECT(rt::d3d12::page_mirror_gpu_write(device.p, std::uintptr_t(big) + kBig - 0x1000, mark, sizeof(mark))); + const auto t0 = std::chrono::steady_clock::now(); + const auto back = rt::d3d12::page_mirror_write_back(device.p, std::uintptr_t(big), kBig); + const double ms = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + std::printf("page mirror: write-back over 64 MiB in %.1f ms\n", ms); + EXPECT(back == 256 && reinterpret_cast(big + kBig - 0x1000)[3] == 0x9A9A0004u); + EXPECT(ms < 1000.0); + } + + // 10. Remapping a stream-pool page between submissions with a pending GPU write-back over that VA must deliver + // the old page's GPU write to the old physical frame and never clobber the newly mapped CPU page. + { + EXPECT(rt::xmem::copy_page_mappings_fn(dst, pool, 1, false)); + std::thread([&] { + words[0] = 0xAA000001u; + words[kPage64k / 4] = 0xBB000001u; + }).join(); + EXPECT(gpu_word(device.p, std::uintptr_t(dst)) == 0xAA000001u); + const std::uint32_t gpu_old[4] = {0xCC000001u, 0xCC000002u, 0xCC000003u, 0xCC000004u}; + EXPECT(rt::d3d12::page_mirror_gpu_write(device.p, std::uintptr_t(dst), gpu_old, sizeof(gpu_old))); + // Remap `dst` to the second physical page before the mirror drains its feed or runs write-back. + EXPECT(rt::xmem::copy_page_mappings_fn(dst, pool + kPage64k, 1, false)); + EXPECT(rt::d3d12::page_mirror_write_back(device.p, std::uintptr_t(dst), kPage64k) == 256); + EXPECT(words[0] == 0xCC000001u); // old physical frame received its GPU write + EXPECT(words[kPage64k / 4] == 0xBB000001u); // new physical frame was never overwritten + EXPECT(gpu_word(device.p, std::uintptr_t(dst)) == 0xBB000001u); + EXPECT(rt::d3d12::page_mirror_write_back(device.p, std::uintptr_t(dst), kPage64k) == 0); + EXPECT(words[kPage64k / 4] == 0xBB000001u); + } + + // 11. Reservations <= 2 GiB (TitleMirror::kChunk) are aligned so they never straddle a 2 GiB chunk boundary, + // allowing any placed buffer inside them to bind directly to a single mirror chunk without falling back to a + // slot-133 shadow. + { + constexpr SIZE_T kBig = 1200ull << 20; // 1.2 GiB: two of these cannot share one 2 GiB chunk + constexpr std::uint64_t kChunk = leonida::title_mirror_space::kChunk; + auto* r1 = static_cast(reserve(nullptr, kBig, MEM_RESERVE, 0, PAGE_READWRITE)); + auto* r2 = static_cast(reserve(nullptr, kBig, MEM_RESERVE, 0, PAGE_READWRITE)); + EXPECT(r1 && r2); + const std::uint64_t a1 = std::uintptr_t(r1), a2 = std::uintptr_t(r2); + EXPECT(leonida::title_mirror_space::contains(a1) && leonida::title_mirror_space::contains(a2)); + EXPECT(a1 / kChunk == (a1 + kBig - 1) / kChunk); + EXPECT(a2 / kChunk == (a2 + kBig - 1) / kChunk); + EXPECT(VirtualFree(r1, 0, MEM_RELEASE) && VirtualFree(r2, 0, MEM_RELEASE)); + } + + // 12. resolve_title_memory must never create a TitleWindow over memory already covered by the page mirror, even + // when a request exceeds kMirrorNameMax (256 MiB) and page_mirror_resolve refuses it. + { + constexpr SIZE_T kBigReserve = 300ull << 20; + constexpr std::uint64_t kOverMirrorMax = 260ull << 20; + auto* big_plain = static_cast(reserve(nullptr, kBigReserve, MEM_RESERVE, 0, PAGE_READWRITE)); + EXPECT(big_plain && leonida::title_mirror_space::contains(std::uintptr_t(big_plain))); + EXPECT(VirtualAlloc(big_plain, kPage64k, MEM_COMMIT, PAGE_READWRITE) == big_plain); + std::memset(big_plain, 0x3C, kPage64k); + const std::size_t aliases_before = leonida::title_va_aliases().size(); + const std::uint64_t resolved = leonida::title_va_aliases().resolve( + std::uintptr_t(big_plain), kOverMirrorMax, leonida::TitleVaAliases::table_view, true); + EXPECT(resolved == 0); + EXPECT(leonida::title_va_aliases().size() == aliases_before); + EXPECT(leonida::title_va_aliases().shader_va(std::uintptr_t(big_plain)) == std::uintptr_t(big_plain)); + EXPECT(VirtualFree(big_plain, 0, MEM_RELEASE)); + } + + const auto end = rt::d3d12::page_mirror_state(device.p); + std::printf("page mirror: heap_base 0x%llx, %llu pages in %llu homes over %llu chunk(s); slot-31 copies, a title " + "write through its own view and a remap reach heap_base + the GPU-only address; an unmapped page reads " + "zero\n", + static_cast(end.heap_base), static_cast(end.pages), + static_cast(end.homes), static_cast(end.chunks)); + EXPECT(rt::xmem::copy_page_mappings_fn(dst, nullptr, 2, false)); + EXPECT(map(pool_cpu, 2, nullptr) == pool_cpu && free_pages(2, pages)); + return 0; +} + +} // namespace + +int main() { return test(); } diff --git a/runtime/test/d3d12_queue_wait_test.cpp b/runtime/test/d3d12_queue_wait_test.cpp index 3dfb1bad3e..d93465157a 100644 --- a/runtime/test/d3d12_queue_wait_test.cpp +++ b/runtime/test/d3d12_queue_wait_test.cpp @@ -74,5 +74,63 @@ int main(int argc, char** argv) { std::_Exit(1); } std::puts("copy/compute and direct/direct Wait-before-Signal completed"); + + // Round 10 WS3: COM-level fence_signal_gpu_relay & retroactive fence_relay_wait (single-wait and multi-wait, + // never signaling gate_multi on the CPU or GPU). + { + Ref gate_multi, writer_a, writer_b, done_relay, done_multi, gpu_relayed; + if (FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&gate_multi.p))) || + FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&writer_a.p))) || + FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&writer_b.p))) || + FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&done_relay.p))) || + FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&done_multi.p))) || + FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&gpu_relayed.p)))) + return 1; + + // 1. fence_signal_gpu_relay wakes held waiters cleanly. + if (FAILED(direct_a->Wait(gpu_relayed.p, 1)) || FAILED(direct_a->Signal(done_relay.p, 1)) || + FAILED(rt::d3d12::fence_signal_gpu_relay(gpu_relayed.p, 1)) || !wait_for(done_relay.p, 1)) + return 1; + + // 2. Retroactive single-wait & multi-wait fence_relay_wait (direct_a waits on gate_multi -> relayed onto + // compute's writer_a and copy's writer_b without ever signaling gate_multi). + if (FAILED(direct_a->Wait(gate_multi.p, 1)) || FAILED(direct_a->Signal(done_multi.p, 1)) || + FAILED(compute->Signal(writer_a.p, 1)) || FAILED(copy->Signal(writer_b.p, 1))) + return 1; + const rt::d3d12::FenceRelayTarget targets[] = {{writer_a.p, 1}, {writer_b.p, 1}}; + if (!rt::d3d12::fence_relay_wait(gate_multi.p, 1, targets) || !wait_for(done_multi.p, 1)) { + std::fputs("retroactive fence_relay_wait did not complete\n", stderr); + std::fflush(stderr); + std::_Exit(1); + } + if (gate_multi->GetCompletedValue() != 0) { + std::fputs("retroactive fence_relay_wait unexpectedly signaled gate_multi\n", stderr); + return 1; + } + + // 3. Round 10b A4: fence_relay_wait returns false when no wait was substituted yet, while retaining the + // redirect entry so an in-transit Wait arriving afterwards still resolves onto writer_a without signaling + // gate_race. + Ref gate_race, done_race; + if (FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&gate_race.p))) || + FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&done_race.p)))) + return 1; + const rt::d3d12::FenceRelayTarget race_target[] = {{writer_a.p, 1}}; + if (rt::d3d12::fence_relay_wait(gate_race.p, 1, race_target)) { + std::fputs("fence_relay_wait unexpectedly returned true with no waiting queue\n", stderr); + return 1; + } + if (FAILED(direct_a->Wait(gate_race.p, 1)) || FAILED(direct_a->Signal(done_race.p, 1)) || + !wait_for(done_race.p, 1)) { + std::fputs("in-transit fence_relay_wait did not complete\n", stderr); + std::fflush(stderr); + std::_Exit(1); + } + if (gate_race->GetCompletedValue() != 0) { + std::fputs("in-transit fence_relay_wait unexpectedly signaled gate_race\n", stderr); + return 1; + } + std::puts("COM fence_signal_gpu_relay and retroactive fence_relay_wait completed"); + } return 0; } diff --git a/runtime/test/d3d12_title_va_test.cpp b/runtime/test/d3d12_title_va_test.cpp index b968b4edeb..9db3c10ba2 100644 --- a/runtime/test/d3d12_title_va_test.cpp +++ b/runtime/test/d3d12_title_va_test.cpp @@ -1745,6 +1745,10 @@ int main(int argc, char** argv) { window_write_back_tile || (argc == 2 && std::strcmp(argv[1], "--window-writeback-fault") == 0); const bool placed_write_back = argc == 2 && std::strcmp(argv[1], "--placed-writeback") == 0; const bool keep_refill = argc == 2 && std::strcmp(argv[1], "--shadow-keep-refill") == 0; + // The device the game makes (create_vulkan_device_standalone: the arena's bind queue, so a sparse arena where the + // GPU can), not one built on the test's own Vulkan device: a sparse arena puts every other buffer below heap_base + // on RADV, which the test's own device never showed. + const bool game_device = argc == 2 && std::strcmp(argv[1], "--game-device") == 0; if (window_cap) { const char* cap = std::getenv("LEONIDA_TITLE_WINDOWS_MB"); if (!cap || std::strcmp(cap, "0")) { @@ -1773,7 +1777,7 @@ int main(int argc, char** argv) { std::ofstream index(library / "index.json", std::ios::binary); index << "{\"cs_user_data\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << leonida::sha256_hex(fssm) << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"local_size\": [64, 1, 1], " - "\"uses_code_base\": true, \"wave64\": false}}"; + "\"uses_code_base\": true, \"wave64\": false, \"vsharp_base_sign_extended\": true}}"; } int checks = 0; @@ -1793,7 +1797,34 @@ int main(int argc, char** argv) { Ref first; if (second_device) EXPECT(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&first.p)) == S_OK); ID3D12Device* inner = nullptr; // owned by the proxy, as in d3d12_compute_test - EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); + if (game_device) { + // The standalone device reads its shaders from LEONIDA_SHADERS, as the game's does. + const std::string dir = library.string(); + SetEnvironmentVariableA("LEONIDA_SHADERS", dir.c_str()); + _putenv_s("LEONIDA_SHADERS", dir.c_str()); + if (FAILED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&inner)))) { + std::fprintf(stderr, "SKIP: no standalone Vulkan device\n"); + return 77; + } + } else { + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); + } + if (game_device) { + // The module above sign-extends a V# base, so buffers outside the arena may lie below heap_base, and the + // arena binds its memory as it is used wherever the device can (sparse binding and residency, strict + // non-resident reads, a queue for the binds): not its whole range at once. + const auto arena = rt::d3d12::device_arena_memory(inner); + std::fprintf(stderr, "game device: arena %llu MiB at 0x%llx, %llu KiB bound, %s (capable: %s), %s V# " + "offsets\n", + static_cast(arena.size >> 20), + static_cast(arena.address), + static_cast(arena.bound >> 10), arena.sparse ? "sparse" : "one allocation", + arena.sparse_capable ? "yes" : "no", arena.signed_offsets ? "signed" : "unsigned"); + EXPECT(arena.size != 0); + EXPECT(arena.signed_offsets); + EXPECT(arena.sparse == arena.sparse_capable); + if (arena.sparse) EXPECT(arena.bound < arena.size); + } Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), reinterpret_cast(&device.p)))); diff --git a/runtime/test/d3d12_tsharp_refill_test.cpp b/runtime/test/d3d12_tsharp_refill_test.cpp new file mode 100644 index 0000000000..4646524075 --- /dev/null +++ b/runtime/test/d3d12_tsharp_refill_test.cpp @@ -0,0 +1,357 @@ +// A T# the title writes into a console descriptor heap (Xbox slot 14) before its texture exists is bound when the +// texture appears, at the next submission, through the heap's slot records (docs/d3d12_vulkan.md section 3.4): no +// pass looks at waiting T#s again on its own. Through D3D12 alone, on the Xbox-ABI proxy over the Vulkan device: +// - a probe texture gives the T# words of an 8x8 RGBA8 texture and the address the layer gives textures (the next +// one is 256 bytes on, Resource::image_address); +// - a console heap of 60,001 slots, written before the heap is made: 60,000 T#s naming addresses no texture will +// ever have, then, last, the T# of the texture to come. All wait after the heap's first refresh; +// - the texture is made at the address the T# names, filled by a copy, and sampled through that slot by the +// test/glsl/cs_set0_sample.comp shader (d3d12_set0_compute_test) in the same submission. Its texels must come +// back exactly. With a pass that tries waiting T#s round robin under a time budget, the last of 60,001 is not +// reached in that submission and the shader reads the fallback image; +// - the texture goes: its T# leaves the descriptor hash table at once, and the slot waits again. +// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation (0 errors required). No game data: the program +// is two marker words and the module is GLSL written to the translator's contract. +#include "shader_fixture_path.h" +#include "test_temp_dir.h" +#include "vk_test_device.h" +#include "d3d12_test_shaders.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" +#include "../src/shader_library.h" + +#include +#include +#include +#include +#include +#include + +#ifndef LEONIDA_TEST_CS_SET0_SAMPLE_SPV +#error "LEONIDA_TEST_CS_SET0_SAMPLE_SPV must name the compiled test shader" +#endif + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +using namespace d3d12test; +using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slots 9/10: handle in RAX + +namespace { + +using Texel = std::array; +constexpr UINT texture_size = 8, texels = texture_size * texture_size, run_bytes = texels * 4; +constexpr UINT waiting = 60000; // T#s that never find a texture, ahead of the one that will +constexpr UINT kDescriptor = 32; + +Texel pattern(UINT x, UINT y) { + return {std::uint8_t(200 - x * 20), std::uint8_t(30 + y * 25), std::uint8_t((x * 8 + y) * 3), 255}; +} + +// The T# words `words` with their base address replaced (dword 0: address bits 8..39, dword 1 bits 0..7: 40..47). +std::array at_address(std::array words, std::uint64_t address) { + words[0] = std::uint32_t(address >> 8); + words[1] = (words[1] & ~0xffu) | (std::uint32_t(address >> 40) & 0xffu); + return words; +} + +} // namespace + +int main() { + vktest::Device d; + const auto device_status = d.initialize(); + if (device_status == vktest::DeviceStatus::unavailable) return 77; + if (device_status != vktest::DeviceStatus::ready) return 1; + if (!d.bindless) { + std::printf("SKIP: the device lacks the descriptor indexing features of the bindless set 0\n"); + return 77; + } + + const auto program = fssm_program({0x43530003, 0xbf810000}); + const auto container = shader_container(program); + const testfiles::ScratchDir scratch("leonida_tsharp_refill_test"); + const auto& library = scratch.path(); + EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SET0_SAMPLE_SPV), + library / "cs_set0_sample.spv")); + { + std::ofstream index(library / "index.json", std::ios::binary); + index << "{\"cs_set0_sample\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << leonida::sha256_hex(program) + << "\", \"bindings\": [0, 1, 2], \"push_constant_bytes\": 144, \"local_size\": [64, 1, 1], " + "\"uses_code_base\": false, \"wave64\": false}}"; + } + + std::vector results(run_bytes); + std::array refill_words{}; + { + 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.bindless = d.bindless; + info.bindless_partially_bound = d.partially_bound; + info.image_view_min_lod = d.image_view_min_lod; + info.shader_dir = library.string(); + ID3D12Device* inner = nullptr; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); + Ref device; + EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), + reinterpret_cast(&device.p), /*console_lists=*/false))); + rt::d3d12::set_device_outer(inner, device.p); + if (rt::d3d12::device_push_constants_need_fallback(inner)) { + std::printf("d3d12_tsharp_refill_test: skipped, the PSO needs 144 push-constant bytes and this GPU has %u\n", + rt::d3d12::device_max_push_constants_size(inner)); + return 77; + } + + // Root signature and PSO as in d3d12_set0_compute_test: s4 the view's offset in dwords, s5 the first output + // element, s6:s7 the output, s8 the view table, s9 the sampler table. + D3D12_DESCRIPTOR_RANGE view_range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; + D3D12_DESCRIPTOR_RANGE sampler_range{D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, 1, 0, 0, 0}; + D3D12_ROOT_PARAMETER params[4] = {}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[0].Constants = {0, 0, 2}; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + params[1].Descriptor = {0, 0}; + params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[2].DescriptorTable = {1, &view_range}; + params[3].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[3].DescriptorTable = {1, &sampler_range}; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; + root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + root_desc.Desc_1_0 = {4, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + const auto root_blob = serialize_root_signature(root_desc); + EXPECT(!root_blob.empty()); + Ref root; + EXPECT(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p)))); + D3D12_COMPUTE_PIPELINE_STATE_DESC pso_desc{}; + pso_desc.pRootSignature = root.p; + pso_desc.CS = {container.data(), container.size()}; + Ref pso; + EXPECT(SUCCEEDED(device->CreateComputePipelineState(&pso_desc, IID_PPV_ARGS(&pso.p)))); + + // Every buffer first: from here on the only textures made are the probe and the one to come. + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}; + const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; + Ref upload, output, readback; + const auto upload_desc = buffer_desc(4096); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &upload_desc, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + IID_PPV_ARGS(&upload.p)))); + const auto output_desc = buffer_desc(results.size(), D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &output_desc, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, + IID_PPV_ARGS(&output.p)))); + const auto readback_desc = buffer_desc(results.size()); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback.p)))); + const D3D12_DESCRIPTOR_HEAP_DESC view_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + const D3D12_DESCRIPTOR_HEAP_DESC sampler_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 1, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + Ref view_heap, sampler_heap; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&view_heap_desc, IID_PPV_ARGS(&view_heap.p)))); + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&sampler_heap_desc, IID_PPV_ARGS(&sampler_heap.p)))); + const std::uint64_t view_cpu = reinterpret_cast(slot(view_heap.p, 9))(view_heap.p); + const std::uint64_t sampler_cpu = reinterpret_cast(slot(sampler_heap.p, 9))(sampler_heap.p); + const std::uint64_t sampler_gpu = reinterpret_cast(slot(sampler_heap.p, 10))(sampler_heap.p); + EXPECT(view_cpu && sampler_cpu && sampler_gpu < (1ull << 32)); + D3D12_SAMPLER_DESC sampler_desc{}; + sampler_desc.Filter = D3D12_FILTER_MIN_MAG_MIP_POINT; + sampler_desc.AddressU = sampler_desc.AddressV = sampler_desc.AddressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP; + sampler_desc.MaxAnisotropy = 1; + sampler_desc.ComparisonFunc = D3D12_COMPARISON_FUNC_NEVER; + sampler_desc.MaxLOD = D3D12_FLOAT32_MAX; + device->CreateSampler(&sampler_desc, D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(sampler_cpu)}); + + // The probe: the T# words of an 8x8 RGBA8 texture, and where the layer put it. + D3D12_RESOURCE_DESC texture_desc{}; + texture_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + texture_desc.Width = texture_desc.Height = texture_size; + texture_desc.DepthOrArraySize = 1; + texture_desc.MipLevels = 1; + texture_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + texture_desc.SampleDesc.Count = 1; + Ref probe; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &texture_desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&probe.p)))); + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Texture2D = {0, 1, 0, 0.0f}; + device->CreateShaderResourceView(probe.p, &srv, D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(view_cpu)}); + std::array probe_words{}; + std::memcpy(probe_words.data(), reinterpret_cast(view_cpu), sizeof(probe_words)); + const std::uint64_t probe_address = rt::d3d12::resource_image_address(probe.p); + EXPECT(probe_address && (probe_words[0] == std::uint32_t(probe_address >> 8))); + const std::uint64_t refill_address = probe_address + 256; + refill_words = at_address(probe_words, refill_address); + + // The console heap, written before it is made: 60,000 T#s at addresses no texture will have (a range of the + // address space the layer never gives textures, 256 apart), then the one to come, last. + // After it, the same texture's T# as the title rebuilds it from 32 bits (run 58: 0x7f0000021400 for the + // layer's 0x100021400, and the low 32 bits alone): both must wait for the texture and bind when it comes. + constexpr UINT slots = waiting + 3; + constexpr std::uint64_t bytes = std::uint64_t(slots) * kDescriptor; + auto* title = static_cast(VirtualAlloc(nullptr, bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + EXPECT(title); + for (UINT i = 0; i < waiting; ++i) { + const auto words = at_address(probe_words, 0x7e0000000000ull + std::uint64_t(i) * 256); + std::memcpy(title + std::size_t(i) * kDescriptor, words.data(), sizeof(words)); + } + std::memcpy(title + std::size_t(waiting) * kDescriptor, refill_words.data(), sizeof(refill_words)); + const auto title_form = at_address(probe_words, 0x7f0000000000ull | (refill_address & 0xffffffffull)); + const auto low_form = at_address(probe_words, refill_address & 0xffffffffull); + std::memcpy(title + std::size_t(waiting + 1) * kDescriptor, title_form.data(), sizeof(title_form)); + std::memcpy(title + std::size_t(waiting + 2) * kDescriptor, low_form.data(), sizeof(low_form)); + std::uint32_t title_key[8], low_key[8]; + std::memcpy(title_key, title_form.data(), sizeof(title_key)); + std::memcpy(low_key, low_form.data(), sizeof(low_key)); + const D3D12_DESCRIPTOR_HEAP_DESC console_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, slots, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + Ref console_heap; + EXPECT(SUCCEEDED(rt::d3d12::create_console_descriptor_heap(device.p, &console_desc, + reinterpret_cast(title), bytes, + IID_PPV_ARGS(&console_heap.p)))); + D3D12_DESCRIPTOR_HEAP_DESC got{}; + D3D12_GPU_VIRTUAL_ADDRESS shader_va = 0; + EXPECT(rt::d3d12::descriptor_heap_info(console_heap.p, got, shader_va)); + const std::uint64_t refill_slot_va = shader_va + std::uint64_t(waiting) * kDescriptor; + EXPECT(refill_slot_va < (1ull << 32)); + std::uint32_t key[8]; + std::memcpy(key, refill_words.data(), sizeof(key)); + EXPECT(rt::d3d12::bindless_hash_lookup(device.p, key) == 0); // no texture yet: the slot waits + EXPECT(rt::d3d12::bindless_hash_lookup(device.p, title_key) == 0); + EXPECT(rt::d3d12::bindless_hash_lookup(device.p, low_key) == 0); + + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + Ref queue; + Ref allocator; + Ref list; + Ref fence; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, + IID_PPV_ARGS(&list.p)))); + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + // One empty submission: the waiting T#s have had a refresh with nothing new (as a running title's would). + EXPECT(list->Close() == S_OK); + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + EXPECT(SUCCEEDED(queue->Signal(fence.p, 1))); + EXPECT(SUCCEEDED(fence->SetEventOnCompletion(1, nullptr))); + EXPECT(rt::d3d12::bindless_hash_lookup(device.p, key) == 0); + + // The texture comes, at the address the T# names. + Ref texture; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &texture_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&texture.p)))); + EXPECT(rt::d3d12::resource_image_address(texture.p) == refill_address); + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + device->GetCopyableFootprints(&texture_desc, 0, 1, 0, &footprint, nullptr, nullptr, nullptr); + EXPECT(footprint.Footprint.RowPitch * texture_size <= 4096); + std::uint8_t* up = nullptr; + EXPECT(SUCCEEDED(upload->Map(0, nullptr, reinterpret_cast(&up)))); + for (UINT y = 0; y < texture_size; ++y) + for (UINT x = 0; x < texture_size; ++x) + std::memcpy(up + y * footprint.Footprint.RowPitch + x * 4, pattern(x, y).data(), 4); + + // One submission: fill the texture and sample it through the waiting slot. + EXPECT(SUCCEEDED(allocator->Reset())); + EXPECT(SUCCEEDED(list->Reset(allocator.p, nullptr))); + D3D12_TEXTURE_COPY_LOCATION dst{}; + dst.pResource = texture.p; + dst.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + D3D12_TEXTURE_COPY_LOCATION src{}; + src.pResource = upload.p; + src.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + src.PlacedFootprint = footprint; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + D3D12_RESOURCE_BARRIER sampled = + transition(texture.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + list->ResourceBarrier(1, &sampled); + ID3D12DescriptorHeap* heaps[] = {view_heap.p, sampler_heap.p}; + list->SetDescriptorHeaps(2, heaps); + list->SetComputeRootSignature(root.p); + list->SetPipelineState(pso.p); + const D3D12_GPU_VIRTUAL_ADDRESS output_va = output->GetGPUVirtualAddress(); + EXPECT(output_va < (1ull << 32)); + list->SetComputeRootUnorderedAccessView(1, output_va); + list->SetComputeRootDescriptorTable(2, D3D12_GPU_DESCRIPTOR_HANDLE{refill_slot_va}); + list->SetComputeRootDescriptorTable(3, D3D12_GPU_DESCRIPTOR_HANDLE{sampler_gpu}); + const std::uint32_t offset_and_first[2] = {0, 0}; + list->SetComputeRoot32BitConstants(0, 2, offset_and_first, 0); + list->Dispatch(1, 1, 1); + D3D12_RESOURCE_BARRIER to_copy = transition(output.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &to_copy); + list->CopyBufferRegion(readback.p, 0, output.p, 0, results.size()); + EXPECT(list->Close() == S_OK); + queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); + EXPECT(SUCCEEDED(queue->Signal(fence.p, 2))); + EXPECT(SUCCEEDED(fence->SetEventOnCompletion(2, nullptr))); + void* mapped = nullptr; + EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); + std::memcpy(results.data(), mapped, results.size()); + EXPECT(rt::d3d12::bindless_hash_lookup(device.p, key) != 0); + // The title's 32-bit forms of the same address were fixed at that submission too. + EXPECT(rt::d3d12::bindless_hash_lookup(device.p, title_key) != 0); + EXPECT(rt::d3d12::bindless_hash_lookup(device.p, low_key) != 0); + + // The texture goes: its T# leaves the hash table at once (a shader reading the slot gets the fallback), and + // the next submission takes the slot's record back to waiting. + texture.reset(); + EXPECT(rt::d3d12::bindless_hash_lookup(device.p, key) == 0); + EXPECT(rt::d3d12::bindless_hash_lookup(device.p, title_key) == 0); + EXPECT(rt::d3d12::bindless_hash_lookup(device.p, low_key) == 0); + EXPECT(SUCCEEDED(allocator->Reset())); + EXPECT(SUCCEEDED(list->Reset(allocator.p, nullptr))); + EXPECT(list->Close() == S_OK); + queue->ExecuteCommandLists(1, lists); + EXPECT(SUCCEEDED(queue->Signal(fence.p, 3))); + EXPECT(SUCCEEDED(fence->SetEventOnCompletion(3, nullptr))); + EXPECT(rt::d3d12::bindless_hash_lookup(device.p, key) == 0); + + for (auto* r : {&probe, &upload, &output, &readback}) r->reset(); + pso.reset(); + root.reset(); + view_heap.reset(); + sampler_heap.reset(); + console_heap.reset(); + list.reset(); + allocator.reset(); + queue.reset(); + fence.reset(); + VirtualFree(title, 0, MEM_RELEASE); + EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); + } + + unsigned mismatches = 0; + for (UINT i = 0; i < texels; ++i) { + const UINT x = i % texture_size, y = i / texture_size; + const Texel want = pattern(x, y); + const std::uint8_t* got = results.data() + i * 4; + if (!std::memcmp(got, want.data(), 4)) continue; + if (mismatches++ < 8) + std::fprintf(stderr, "texel %u: got %u,%u,%u,%u want %u,%u,%u,%u\n", i, got[0], got[1], got[2], got[3], + want[0], want[1], want[2], want[3]); + } + EXPECT(!mismatches); + if (d.validation_errors()) { + std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); + return 1; + } + std::printf("T# refill: the last of %u waiting T#s sampled its texture, all %u texels, at the first submission " + "after the texture appeared; its T# left the hash table when the texture went\n", waiting + 1, texels); + return 0; +} diff --git a/runtime/test/d3d12_unbound_tsharp_rules_test.cpp b/runtime/test/d3d12_unbound_tsharp_rules_test.cpp index bc9aa1ca96..f935d57ec9 100644 --- a/runtime/test/d3d12_unbound_tsharp_rules_test.cpp +++ b/runtime/test/d3d12_unbound_tsharp_rules_test.cpp @@ -374,8 +374,60 @@ int main() { const char* why = nullptr; const auto result = rt::d3d12::test_bind_title_image(device.p, words, &why); check(result == rt::d3d12::TitleImage::unknown, "unknown address returns TitleImage::unknown"); - check(why && std::string(why) == "no texture at T# address", - "unknown address explains no texture at T# address"); + check(why && std::string(why) == "no texture at the T# address: no title memory and no texture of ours", + "unknown address explains no texture at the T# address, and what the address is"); + } + + // The classes of an address with no texture: one of ours that is gone, and one whose low 32 bits name one of + // ours (of the T#'s shape, of another, or gone) with other high bits. + { + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = 16; + desc.Height = 4; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + desc.SampleDesc.Count = 1; + Ref texture; + check(SUCCEEDED(device->CreateCommittedResource(&heap_props, D3D12_HEAP_FLAG_NONE, &desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(texture.put()))), + "created a 16x4 texture"); + const std::uint64_t addr = rt::d3d12::resource_image_address(texture.p); + check(addr >> 32 == 1, "the layer's texture addresses start at 1 << 32"); + g::Image img{}; + img.address = 0x7f0000000000ull | (addr & 0xffffffffull); + img.type = g::ImageType::image_2d; + img.format = g::format_from_vulkan(VK_FORMAT_R8G8B8A8_UNORM); + img.width = 16; + img.height = 4; + img.layer_count = 1; + img.mip_count = 1; + const auto reason = [&](const g::Image& image) { + const char* why = nullptr; + const auto result = rt::d3d12::test_bind_title_image(device.p, g::encode(image), &why); + return result == rt::d3d12::TitleImage::unknown && why ? std::string(why) : std::string("?"); + }; + // The title's 32-bit form of the texture's address (bits 32-39 clear, 0x7f above) with the texture's shape + // binds it (tsharp_texture_key); another shape does not. + { + const char* why = nullptr; + check(rt::d3d12::test_bind_title_image(device.p, g::encode(img), &why) == rt::d3d12::TitleImage::bound, + "other high bits, same shape: bound to the texture with those low 32 bits"); + } + g::Image other = img; + other.width = 32; + check(reason(other) == + "no texture at the T# address: its low 32 bits name a texture of ours of another shape", + "other high bits, another shape"); + texture.put(); // released: its address leaves the device's table + check(reason(img) == "no texture at the T# address: its low 32 bits name a texture of ours that is gone", + "other high bits, texture gone"); + g::Image gone = img; + gone.address = addr; + check(reason(gone) == "no texture at the T# address: a texture of ours that is gone", + "the address of a texture of ours that is gone"); } // Not a valid T# (decode failure) diff --git a/runtime/test/d3d12_xmem_placed_test.cpp b/runtime/test/d3d12_xmem_placed_test.cpp index 33b5d462ad..3432ab31a3 100644 --- a/runtime/test/d3d12_xmem_placed_test.cpp +++ b/runtime/test/d3d12_xmem_placed_test.cpp @@ -14,6 +14,7 @@ #include "../shims/shims.h" #include "../shims/xmem.h" +#include "../src/title_geometry_watch.h" #include "../src/title_page_watch.h" #include #include @@ -174,6 +175,11 @@ int queue_remap(ID3D12Device* real, ID3D12Device* proxy) { return 0; } +int read_back(ID3D12Device* real, ID3D12Resource* buffer, UINT64 size, std::vector& out); +template +bool on_thread(F f); +DWORD protection_of(const void* address); + // 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 @@ -227,26 +233,92 @@ int queue_remap_default_route(ID3D12Device* real, ID3D12Device* proxy) { 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 GPU-only pages took the pool's pages (found through its CPU alias) in xmem's table alone: no host view there, + // as on the console. A copy from them shows what the table holds. + EXPECT(state_is(dst, MEM_RESERVE) && state_is(dst + kPage64k, MEM_RESERVE)); + auto* probe = window(PAGE_READWRITE); + EXPECT(probe && rt::xmem::copy_page_mappings_fn && + rt::xmem::copy_page_mappings_fn(probe, dst, n, false) && probe[0] == 40 && probe[kPage64k] == 41); + EXPECT(rt::xmem::copy_page_mappings_fn(probe, nullptr, n, false)); + // A CPU twin with no mapping of the title's follows the copy, in the table too: no host view, its bytes through + // its frame (src/title_frames.h). The title's own page is kept. + leonida::title_frames::Frame frame; + EXPECT(state_is(cpu, MEM_RESERVE) && leonida::title_frames::find(uintptr_t(cpu), frame) && frame.bytes[0] == 40); + EXPECT(cpu[kPage64k] == 77 && !leonida::title_frames::backed(uintptr_t(cpu + kPage64k))); + + // The layer's readers go through the table. A slot-133 buffer over the GPU-only pages (a shadow: they have no host + // view to import) and one over the CPU twin read the pages the copy gave them; a write through the title's own + // mapping of a page (the pool's CPU alias) reaches both, guarded there by the geometry watch's cells (xmem names + // that mapping as the table pages' other address); a remap reaches them with no host map or unmap at all. + leonida::geometry_writes::aliases.store(&rt::xmem::geometry_aliases, std::memory_order_release); + { + rt::xmem::Slot31Counts before{}; + rt::xmem::slot31_mapping_counts(before); + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = n * kPage64k; + desc.Height = desc.DepthOrArraySize = desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + Ref over_gpu, over_twin; + EXPECT(SUCCEEDED(rt::d3d12::create_buffer_at_host_address(real, dst, desc, 0xFFFFFFFFu, IID_PPV_ARGS(&over_gpu.p)))); + desc.Width = kPage64k; + EXPECT(SUCCEEDED(rt::d3d12::create_buffer_at_host_address(real, cpu, desc, 0xFFFFFFFFu, IID_PPV_ARGS(&over_twin.p)))); + std::vector got; + EXPECT(read_back(real, over_gpu.p, n * kPage64k, got) == 0 && got[0] == 40 && got[kPage64k] == 41); + EXPECT(read_back(real, over_twin.p, kPage64k, got) == 0 && got[0] == 40); + EXPECT((protection_of(pool_cpu) & 0xff) == PAGE_READONLY); // guarded at the other address + on_thread([&] { pool_cpu[16] = 55; }); // the title's CPU, through its own mapping of the page + EXPECT(read_back(real, over_gpu.p, n * kPage64k, got) == 0 && got[16] == 55 && got[kPage64k] == 41); + EXPECT(read_back(real, over_twin.p, kPage64k, got) == 0 && got[16] == 55); + on_thread([&] { pool_cpu[17] = 56; }); // and again, after the pages were read (and guarded) once more + EXPECT(read_back(real, over_gpu.p, n * kPage64k, got) == 0 && got[17] == 56); + // The remap: the first GPU-only page (and its twin) takes the pool's second page. + const PageRange swap[] = {{0, 1, 1}}; + const PageBatch swap_batch{uintptr_t(dst), 1, swap}; + EXPECT(SUCCEEDED(call(queue.p, 1, &swap_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(read_back(real, over_gpu.p, n * kPage64k, got) == 0 && got[0] == 41 && got[16] == 0 && + got[kPage64k] == 41); + EXPECT(read_back(real, over_twin.p, kPage64k, got) == 0 && got[0] == 41); + rt::xmem::Slot31Counts after{}; + rt::xmem::slot31_mapping_counts(after); + EXPECT(after.host() == before.host() && after.table() == before.table() + 2); + // Back as it was, for the unmap below. + const PageRange back[] = {{0, 0, 1}}; + const PageBatch back_batch{uintptr_t(dst), 1, back}; + EXPECT(SUCCEEDED(call(queue.p, 1, &back_batch, uintptr_t(pool), n, 0))); + EXPECT(SUCCEEDED(real_queue->Signal(gate.p, 4))); + remapped = CreateEventW(nullptr, FALSE, FALSE, nullptr); + EXPECT(remapped && SUCCEEDED(gate->SetEventOnCompletion(4, remapped))); + EXPECT(WaitForSingleObject(remapped, 10000) == WAIT_OBJECT_0); + CloseHandle(remapped); + EXPECT(read_back(real, over_gpu.p, n * kPage64k, got) == 0 && got[0] == 40 && got[16] == 55); + } + leonida::geometry_writes::aliases.store(nullptr, std::memory_order_release); // 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))); + EXPECT(SUCCEEDED(real_queue->Signal(gate.p, 5))); remapped = CreateEventW(nullptr, FALSE, FALSE, nullptr); - EXPECT(remapped && SUCCEEDED(gate->SetEventOnCompletion(3, remapped))); + EXPECT(remapped && SUCCEEDED(gate->SetEventOnCompletion(5, 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(!leonida::title_frames::backed(uintptr_t(dst)) && !leonida::title_frames::backed(uintptr_t(cpu))); 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"); + "title's own CPU twin page; slot-133 buffers over the GPU-only pages and their twin read them through " + "the frame table, with the title's CPU writes and a remap, and no host remap"); return 0; } @@ -410,6 +482,33 @@ int paired_views(ID3D12Device* real) { return failures; } +// The title's own VirtualProtect (xmem's TitleVirtualProtect) never sees one of our read-only guards as the protection +// it had: a title that saves `old` and sets it back later would leave the page read-only with no guard to answer for it, +// and its next write faults (run 62's "stray read-only title page"). A cell of the geometry watch, armed as the title +// texture watch arms them, stands for the guards. +int title_protect_round_trip() { + const char* who = "title VirtualProtect over a guard"; + using VirtualProtectFn = BOOL(WINAPI*)(LPVOID, SIZE_T, DWORD, PDWORD); + const auto protect = reinterpret_cast(rt::shims::find("kernel32.dll", "VirtualProtect")); + EXPECT(protect); + auto* pages = static_cast(VirtualAlloc(nullptr, kPage64k, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + EXPECT(pages); + const auto va = reinterpret_cast(pages); + auto* cell = leonida::geometry_writes::acquire(va); + EXPECT(leonida::geometry_writes::arm(va, *cell)); + EXPECT((protection_of(pages + 0x1000) & 0xff) == PAGE_READONLY); // guarded + DWORD old = 0, again = 0; + EXPECT(protect(pages + 0x1000, 0x1000, PAGE_READWRITE, &old)); + EXPECT((old & 0xff) == PAGE_READWRITE); // what the title set, not our guard + EXPECT(protect(pages + 0x1000, 0x1000, old, &again)); // set back as the title saw it + EXPECT((protection_of(pages + 0x1000) & 0xff) == PAGE_READWRITE); + pages[0x1964] = 1; // and written: no fault left to the title + leonida::geometry_writes::release(va); + EXPECT(VirtualFree(pages, 0, MEM_RELEASE)); + std::printf("%s: the title saw and restored its own protection\n", who); + return 0; +} + int exposure_map_ranges(void* device) { auto* pages = static_cast(VirtualAlloc(nullptr, 2 * kPage64k, MEM_RESERVE, PAGE_READWRITE)); EXPECT(pages && VirtualAlloc(pages, kPage64k, MEM_COMMIT, PAGE_READWRITE)); @@ -625,6 +724,7 @@ int main(int argc, char** argv) { failures += queue_remap(real.p, device.p); failures += queue_remap_default_route(real.p, device.p); failures += paired_views(real.p); + failures += title_protect_round_trip(); } } if (vk.validation_errors()) { diff --git a/runtime/test/geometry_views_test.cpp b/runtime/test/geometry_views_test.cpp index 37a1bd391d..a2f2fc906f 100644 --- a/runtime/test/geometry_views_test.cpp +++ b/runtime/test/geometry_views_test.cpp @@ -19,7 +19,9 @@ // (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, not when they are not; -// 16. a full release queue joins touching ranges before it collapses to one covering range. +// 16. a full release queue joins touching ranges before it collapses to one covering range; +// 17. a retired view stays live while a pre-retirement command_list_epochs::Stamp is alive, and gets stamped and +// reaped once that stamp drops (a post-retirement stamp does not hold it). #include #include @@ -141,6 +143,27 @@ void title_write(std::uintptr_t at, std::uint8_t value) { } // namespace int main() { + // Which blocks outside the arena a V# base reaches (TitleBufferWindows::shader_reachable), with the addresses RADV + // gives (Mesa 26.3.1): a sparse arena at 0xffffc00100200000, ordinary buffers at 0xffff8001..., 64 TiB below it. + { + using Windows = rt::d3d12::TitleBufferWindows; + constexpr std::uint64_t sparse_arena = 0xffffc00100200000ull, ordinary = 0xffff800100010000ull; + constexpr std::uint64_t k4m = 4ull << 20, k47 = 1ull << 47; + // Below heap_base: only with sign-extending shaders. + if (!Windows::shader_reachable(ordinary, k4m, sparse_arena, true)) return 1; + if (Windows::shader_reachable(ordinary, k4m, sparse_arena, false)) return 1; + // Above it (an ordinary arena with blocks made after it): both readings. + if (!Windows::shader_reachable(ordinary + (1ull << 30), k4m, ordinary, false)) return 1; + if (!Windows::shader_reachable(ordinary + (1ull << 30), k4m, ordinary, true)) return 1; + // The edges of the signed range: [-2^47, 2^47). + if (!Windows::shader_reachable(sparse_arena - k47, k4m, sparse_arena, true)) return 1; + if (Windows::shader_reachable(sparse_arena - k47 - 65536, k4m, sparse_arena, true)) return 1; + if (!Windows::shader_reachable(sparse_arena + k47 - k4m, k4m, sparse_arena, true)) return 1; + if (Windows::shader_reachable(sparse_arena + k47 - k4m + 65536, k4m, sparse_arena, true)) return 1; + // A block that ends exactly at heap_base, and no block at all. + if (!Windows::shader_reachable(sparse_arena - k4m, k4m, sparse_arena, true)) return 1; + if (Windows::shader_reachable(0, k4m, sparse_arena, true)) return 1; + } _putenv_s("LEONIDA_GEOMETRY_MB", "64"); constexpr std::size_t kTile = 65536, kView = 16 * kTile; auto* title = static_cast(VirtualAlloc(nullptr, 2 * kView, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); @@ -443,7 +466,7 @@ int main() { check(g_live_buffers == 0 && g_live_allocs == 0, "multi-instance teardown frees all blocks"); VirtualFree(shared_title, 0, MEM_RELEASE); - // 13. DeviceState's order for one submission: execute_begin, drain_geometry_releases (kAfterExecutes) and the + // 13. DeviceState's order for one submission: execute_enqueue, drain_geometry_releases (kAfterExecutes) and the // console heaps in before_execute_, the replay records its submission, execute_end. Another queue's replay began // before the release (its heap slots may already name the view); one more begins after the retirement. auto* fly_title = static_cast(VirtualAlloc(nullptr, kView, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); @@ -464,8 +487,8 @@ int main() { const int gone = g_gone_blocks; std::uint64_t submitted = 7; // completed == submitted below: the GPU is idle - const std::uint64_t other = fly.execute_begin(); - const std::uint64_t own = fly.execute_begin(); + const std::uint64_t other = fly.execute_enqueue(); + const std::uint64_t own = fly.execute_enqueue(); leonida::TitleVaAliases aliases; aliases.record_removals(true); // What the console heaps' slot records are told (TitleVaAliases::add_listener). @@ -501,7 +524,7 @@ int main() { check(fly.reap(device, 8) == 0 && fly.retired_count() == 1 && fly.bytes() == kView, "not freed while a replay begun before the retirement is still in progress"); - const std::uint64_t later = fly.execute_begin(); + const std::uint64_t later = fly.execute_enqueue(); submitted = 9; // the other queue's submission fly.execute_end(other, [&] { return submitted; }); check(fly.reap(device, 8) == 0 && fly.retired_count() == 1, @@ -617,6 +640,43 @@ int main() { 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); + + // 17. Command-list-epoch guard: a view retired with kAfterExecutes stays unstamped (not reaped even when + // every replay has ended and completed == submitted) while a command list recorded before the retirement is + // still alive, and gets stamped and reaped once that list's Stamp drops (a list recorded after does not hold it). + { + rt::d3d12::GeometryViews guarded(2 * kView); + const std::uint64_t va_g = guarded.resolve(device, hbase, kView, copy); + check(va_g != 0 && guarded.live_views() == 1 && g_live_buffers == 1, + "epoch guard: view created in its own block"); + std::uint64_t submitted = 20; + auto pre_list = std::make_unique(); + const std::uint64_t replay = guarded.execute_enqueue(); + check(guarded.retire_range(hbase, hbase + kView, rt::d3d12::GeometryViews::kAfterExecutes) == 1 && + guarded.retired_count() == 1, + "epoch guard: view retired with kAfterExecutes while pre-retirement list is alive"); + auto post_list = std::make_unique(); + + submitted = 21; + guarded.execute_end(replay, [&] { return submitted; }); + guarded.stamp_retired([&] { return submitted; }); + check(guarded.reap(device, 100) == 0 && guarded.retired_count() == 1 && g_live_buffers == 1, + "epoch guard: retired view stays live while pre-retirement command list stamp is alive"); + + // Drop the pre-retirement list (simulating Reset or Release after its final submission at ticket 25); + // the post-retirement list stays alive and must NOT block stamping. + submitted = 25; + pre_list.reset(); + guarded.stamp_retired([&] { return submitted; }); + check(guarded.reap(device, 24) == 0 && guarded.retired_count() == 1 && g_live_buffers == 1, + "epoch guard: stamped view waits for ticket 25 after pre-retirement list drops"); + check(guarded.reap(device, 25) == 1 && guarded.retired_count() == 0 && guarded.bytes() == 0 && + g_live_buffers == 0, + "epoch guard: stamped view is reaped at ticket 25 while post-retirement list is still alive"); + post_list.reset(); + guarded.release(device); + } + VirtualFree(host_title, 0, MEM_RELEASE); } diff --git a/runtime/test/gfx10_descriptors_test.cpp b/runtime/test/gfx10_descriptors_test.cpp index f30d7f026d..b5278de8cf 100644 --- a/runtime/test/gfx10_descriptors_test.cpp +++ b/runtime/test/gfx10_descriptors_test.cpp @@ -25,6 +25,26 @@ int main() { // and TYPE (SQ_RSRC_IMG_2D = 9 at bits 31:28). const ImageWords plain = encode(Image{}); CHECK((plain == ImageWords{0, 0, 0, 0x90000FAC, 0, 0, 0, 0})); + + // The bindless index in dword 6 (tsharp_index_word): TAG 0xA [31:28], the storage kind bits 8..12 at [27:23], the + // sampled kind bits 0..6 at [22:16], the index at [15:0]; decoded back as the translator does, and stripped from the + // key. Index 0 and an index past 16 bits get no word, which every shader reads as the fallback. + { + const std::uint32_t kind = 0x1Fu << 8 | 0x7Fu; // every array + CHECK(tsharp_index_word(0x1234, kind) == 0xAFFF1234u); + CHECK(tsharp_index_word(7, 1u | 1u << 8) == 0xA0810007u); + CHECK(tsharp_index_word(0, kind) == 0 && tsharp_index_word(0x10000, kind) == 0); + ImageWords words = plain; + words[kTsharpIndexDword] = tsharp_index_word(9, 1u << 2 | 1u << 10); + CHECK(has_tsharp_index(words) && tsharp_index_of(words) == 9 && tsharp_kind_of(words) == (1u << 2 | 1u << 10)); + CHECK(tsharp_key(words) == plain); + ImageWords no_image = words; + no_image[3] = 0x30000FAC; // TYPE 3: not an image, whatever dword 6 holds + CHECK(tsharp_index_of(no_image) == 0 && tsharp_kind_of(no_image) == 0); + ImageWords title = plain; + title[kTsharpIndexDword] = 0x1234; // a title's own dword 6 (no tag) stays in its key + CHECK(!has_tsharp_index(title) && tsharp_key(title) == title && tsharp_index_of(title) == 0); + } // One field at a time: the bits that change, word by word. const auto changed = [&](const Image& image) { ImageWords words = encode(image); diff --git a/runtime/test/glsl/cs_title_mirror_read.comp b/runtime/test/glsl/cs_title_mirror_read.comp new file mode 100644 index 0000000000..b05451d699 --- /dev/null +++ b/runtime/test/glsl/cs_title_mirror_read.comp @@ -0,0 +1,28 @@ +#version 460 +// The page mirror's acceptance shape (vk_title_mirror_test): a V# the title wrote into its own memory, read from a +// buffer and then dereferenced as the translated shaders do it (heap_base + sext48(base), docs/design.md +// "Heap-relative buffer device addresses"), as MS_VS_Depth-style code reads a V# out of a constant buffer with +// s_buffer_load and loads through it. Each invocation reads V# i's base and the dword at base + 0x40. +#extension GL_EXT_buffer_reference : require +#extension GL_EXT_shader_explicit_arithmetic_types_int64 : require +layout(local_size_x = 8) in; + +layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer Words { uint w[]; }; +layout(buffer_reference, std430, buffer_reference_align = 4) writeonly buffer Out { uint v[]; }; + +layout(push_constant) uniform Push { + uint64_t heap_base; + uint64_t vsharps; // 16-byte V#s, one per invocation + uint64_t out_words; + uint count; +} p; + +void main() { + const uint i = gl_GlobalInvocationID.x; + if (i >= p.count) return; + Words v = Words(p.vsharps + uint64_t(i) * 16ul); + const uint64_t base48 = uint64_t(v.w[0]) | (uint64_t(v.w[1] & 0xffffu) << 32); + const int64_t signed_base = (int64_t(base48) << 16) >> 16; // sext48 + Words target = Words(p.heap_base + uint64_t(signed_base) + 0x40ul); + Out(p.out_words).v[i] = target.w[0]; +} diff --git a/runtime/test/glsl/cs_user_data.comp b/runtime/test/glsl/cs_user_data.comp index 113d1454c0..cad441d1f2 100644 --- a/runtime/test/glsl/cs_user_data.comp +++ b/runtime/test/glsl/cs_user_data.comp @@ -85,7 +85,8 @@ void main() { const uint bytes_per_record = mode < 2u ? max(stride, 1u) : 1u; const uint byte_off = (indexed ? 0u : pc.s[4]) + i * 4u; if (byte_off <= 0xfffffffcu && (byte_off + 3u) / bytes_per_record < num_records) { - Words cbv = at(uvec2(table.w[word], table.w[word + 1u] & 0xFFFFu)); + // V# bases are signed 48-bit offsets from heap_base, as the translator reads them. + Words cbv = at(uvec2(table.w[word], uint(int(table.w[word + 1u] << 16u) >> 16))); result.w[i] = cbv.w[byte_off >> 2u]; } else { result.w[i] = 0u; @@ -97,7 +98,7 @@ void main() { const uint stride = (table.w[1] >> 16u) & 0x3FFFu; const uint num_records = table.w[2]; const uint oob_select = (table.w[3] >> 28u) & 3u; - const uvec2 base = uvec2(table.w[0], table.w[1] & 0xFFFFu); + const uvec2 base = uvec2(table.w[0], uint(int(table.w[1] << 16u) >> 16)); // signed 48-bit offset if (oob_select == 3u) { const uint byte_off = pc.s[4] + i * 4u; result.w[i] = (byte_off + 4u <= num_records) ? at(base).w[byte_off >> 2u] : 0u; diff --git a/runtime/test/glsl/gpu_profile_spin.comp b/runtime/test/glsl/gpu_profile_spin.comp new file mode 100644 index 0000000000..d9c70ccdf8 --- /dev/null +++ b/runtime/test/glsl/gpu_profile_spin.comp @@ -0,0 +1,21 @@ +#version 450 +// vk_gpu_profile_test: a dispatch whose GPU time grows with s0, the loop count (the translator's 144-byte user-data +// block: s0..s31, heap base, code base). Each invocation writes its result, so the loop is kept. +layout(local_size_x = 64) in; + +layout(set = 0, binding = 0, std430) buffer Results { + uint value[]; +} results; + +layout(push_constant) uniform UserData { + uint s[32]; + uvec2 heap_base; + uvec2 code_base; +} pc; + +void main() { + const uint x = gl_GlobalInvocationID.x; + uint v = x; + for (uint i = 0; i < pc.s[0]; ++i) v = (v * 1664525u + 1013904223u) ^ (v >> 13); + results.value[x] = v; +} diff --git a/runtime/test/glsl/gpu_profile_spin.vert b/runtime/test/glsl/gpu_profile_spin.vert new file mode 100644 index 0000000000..3dfde77b97 --- /dev/null +++ b/runtime/test/glsl/gpu_profile_spin.vert @@ -0,0 +1,14 @@ +#version 450 +// vk_gpu_profile_test: a draw whose GPU time is its vertex shader's loop of s0 turns. Every vertex lands outside the +// viewport, so nothing is rasterised; the position depends on the loop, so the loop is kept. +layout(push_constant) uniform UserData { + uint s[32]; + uvec2 heap_base; + uvec2 code_base; +} pc; + +void main() { + uint v = uint(gl_VertexIndex); + for (uint i = 0; i < pc.s[0]; ++i) v = (v * 1664525u + 1013904223u) ^ (v >> 13); + gl_Position = vec4(3.0 + float(v & 1u), 3.0, 0.0, 1.0); +} diff --git a/runtime/test/guard_fault_bench.cpp b/runtime/test/guard_fault_bench.cpp new file mode 100644 index 0000000000..91df7d933a --- /dev/null +++ b/runtime/test/guard_fault_bench.cpp @@ -0,0 +1,290 @@ +// What tracking a page by its guard costs on this host (under Wine, the numbers the tracking policy is set from, +// src/title_write_policy.h): VirtualProtect per call and per page for ranges of 4 KiB to 4 MiB, one call over a range +// against one call per page; one write fault from the fault to the resumed write, through a minimal vectored handler and +// through the geometry watch's cells (title_geometry_watch.h: notify(fault) reopens a whole 64 KiB tile, page by page), +// on one thread and on eight at once; re-arming a tile; whether GetWriteWatch works for memory VirtualAlloc made and for +// a file-mapped section; and whether Linux's soft-dirty bits (/proc/self/pagemap) can be read from here. +// +// A benchmark: it prints its table and fails only when a measurement could not be made at all. +#include + +#include "../src/title_geometry_watch.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using clock_type = std::chrono::steady_clock; +double us_since(clock_type::time_point start) { + return std::chrono::duration(clock_type::now() - start).count(); +} + +constexpr std::size_t kPage = 4096, kTile = 65536; + +// The region the handlers below answer for, and how: 0 the faulting page, 1 its 64 KiB tile, 2 the geometry cells. +std::atomic g_lo{0}, g_hi{0}; +std::atomic g_mode{0}; +std::atomic g_faults{0}; + +LONG CALLBACK on_fault(EXCEPTION_POINTERS* info) { + const EXCEPTION_RECORD* r = info ? info->ExceptionRecord : nullptr; + if (!r || r->ExceptionCode != EXCEPTION_ACCESS_VIOLATION || r->NumberParameters < 2 || r->ExceptionInformation[0] != 1) + return EXCEPTION_CONTINUE_SEARCH; + const auto address = static_cast(r->ExceptionInformation[1]); + if (address < g_lo.load(std::memory_order_relaxed) || address >= g_hi.load(std::memory_order_relaxed)) + return EXCEPTION_CONTINUE_SEARCH; + g_faults.fetch_add(1, std::memory_order_relaxed); + DWORD old = 0; + switch (g_mode.load(std::memory_order_relaxed)) { + case 0: + return VirtualProtect(reinterpret_cast(address & ~(kPage - 1)), kPage, PAGE_READWRITE, &old) + ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_CONTINUE_SEARCH; + case 1: + return VirtualProtect(reinterpret_cast(address & ~(kTile - 1)), kTile, PAGE_READWRITE, &old) + ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_CONTINUE_SEARCH; + default: { + bool restored = false; + leonida::geometry_writes::notify(address, address + 1, leonida::geometry_writes::Event::fault, &restored); + return restored ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_CONTINUE_SEARCH; + } + } +} + +int failures = 0; +#define CHECK(c) \ + do { \ + if (!(c)) { \ + std::printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #c); \ + ++failures; \ + } \ + } while (0) + +void protect_costs(std::uint8_t* base) { + std::printf("VirtualProtect, read-only and back, a call / a page:\n"); + for (const std::size_t bytes : {kPage, kTile, std::size_t(256) << 10, std::size_t(1) << 20, std::size_t(4) << 20}) { + constexpr int kRounds = 64; + DWORD old = 0; + auto start = clock_type::now(); + for (int i = 0; i < kRounds; ++i) { + CHECK(VirtualProtect(base, bytes, PAGE_READONLY, &old)); + CHECK(VirtualProtect(base, bytes, PAGE_READWRITE, &old)); + } + const double call = us_since(start) / (2.0 * kRounds); + // The same range one page at a time. + const std::size_t pages = bytes / kPage; + const int rounds = std::max(1, int(256 / pages)); + start = clock_type::now(); + for (int i = 0; i < rounds; ++i) + for (std::size_t p = 0; p < pages; ++p) { + CHECK(VirtualProtect(base + p * kPage, kPage, PAGE_READONLY, &old)); + CHECK(VirtualProtect(base + p * kPage, kPage, PAGE_READWRITE, &old)); + } + const double per_page_calls = us_since(start) / (2.0 * rounds * double(pages)); + std::printf(" %7zu KiB: one call %9.2f us (%7.3f us a page); one call a page %7.2f us a page\n", bytes >> 10, + call, call / double(pages), per_page_calls); + } +} + +// Faults: `pages` pages armed in one call, each written once; mode as g_mode. +double fault_cost(std::uint8_t* base, std::size_t pages, int mode, std::size_t stride) { + DWORD old = 0; + g_mode.store(mode); + if (mode == 2) { + for (std::size_t p = 0; p < pages; ++p) { + const auto tile = reinterpret_cast(base + p * stride) & ~(kTile - 1); + auto* cell = leonida::geometry_writes::acquire(tile); + CHECK(leonida::geometry_writes::arm(tile, *cell)); + } + } else { + CHECK(VirtualProtect(base, pages * stride, PAGE_READONLY, &old)); + } + const std::uint64_t before = g_faults.load(); + const auto start = clock_type::now(); + for (std::size_t p = 0; p < pages; ++p) base[p * stride + 8] = std::uint8_t(p); + const double us = us_since(start); + const std::uint64_t taken = g_faults.load() - before; + if (mode == 2) + for (std::size_t p = 0; p < pages; ++p) + leonida::geometry_writes::release(reinterpret_cast(base + p * stride) & ~(kTile - 1)); + VirtualProtect(base, pages * stride, PAGE_READWRITE, &old); + return taken ? us / double(taken) : -1; +} + +void fault_costs(std::uint8_t* base, std::size_t span) { + std::printf("A write fault, from the fault to the resumed write (one thread):\n"); + const std::size_t pages = 256; + std::printf(" handler reopens the page: %7.2f us\n", fault_cost(base, pages, 0, kPage)); + std::printf(" handler reopens the 64 KiB tile: %7.2f us\n", fault_cost(base, pages, 1, kTile)); + std::printf(" geometry cells (VirtualQuery + VirtualProtect a page, 16 a tile): %7.2f us\n", + fault_cost(base, pages, 2, kTile)); + // Eight threads at once, each over its own tiles. + constexpr unsigned kThreads = 8; + const std::size_t each = std::min(64, span / kTile / kThreads); + for (const int mode : {0, 2}) { + g_mode.store(mode); + DWORD old = 0; + if (mode == 2) { + for (std::size_t p = 0; p < kThreads * each; ++p) { + const auto tile = reinterpret_cast(base) + p * kTile; + CHECK(leonida::geometry_writes::arm(tile, *leonida::geometry_writes::acquire(tile))); + } + } else { + CHECK(VirtualProtect(base, kThreads * each * kTile, PAGE_READONLY, &old)); + } + std::atomic ready{0}; + std::atomic go{false}; + std::vector per(kThreads); + std::vector threads; + const std::uint64_t before = g_faults.load(); + for (unsigned t = 0; t < kThreads; ++t) + threads.emplace_back([&, t] { + ++ready; + while (!go.load()) std::this_thread::yield(); + const auto start = clock_type::now(); + for (std::size_t p = 0; p < each; ++p) base[(t * each + p) * kTile + 16] = std::uint8_t(p); + per[t] = us_since(start) / double(each); + }); + while (ready.load() < kThreads) std::this_thread::yield(); + const auto start = clock_type::now(); + go.store(true); + for (auto& thread : threads) thread.join(); + const double wall = us_since(start); + const std::uint64_t taken = g_faults.load() - before; + std::printf(" 8 threads at once, %s: %7.2f us a fault on each thread, %7.2f us of wall time a fault " + "(%llu faults)\n", + mode ? "geometry cells" : "reopening the page", *std::max_element(per.begin(), per.end()), + wall / double(std::max(1, taken)), static_cast(taken)); + if (mode == 2) + for (std::size_t p = 0; p < kThreads * each; ++p) + leonida::geometry_writes::release(reinterpret_cast(base) + p * kTile); + VirtualProtect(base, kThreads * each * kTile, PAGE_READWRITE, &old); + } + // Re-arming a tile through its cell (VirtualQuery a region, VirtualProtect it). + const auto tile = reinterpret_cast(base); + auto* cell = leonida::geometry_writes::acquire(tile); + constexpr int kArms = 256; + double arm_us = 0; + for (int i = 0; i < kArms; ++i) { + const auto start = clock_type::now(); + CHECK(leonida::geometry_writes::arm(tile, *cell)); + arm_us += us_since(start); + base[8] = 1; // fault, reopen + } + leonida::geometry_writes::release(tile); + std::printf("Re-arming a 64 KiB tile through its cell: %7.2f us\n", arm_us / kArms); +} + +void write_watch() { + std::printf("GetWriteWatch:\n"); + constexpr std::size_t bytes = std::size_t(16) << 20; + auto* watched = static_cast( + VirtualAlloc(nullptr, bytes, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE)); + std::printf(" VirtualAlloc with MEM_WRITE_WATCH: %s (error %lu)\n", watched ? "made" : "refused", + watched ? 0ul : GetLastError()); + if (watched) { + std::vector found(bytes / kPage); + ULONG_PTR count = found.size(); + ULONG granularity = 0; + GetWriteWatch(WRITE_WATCH_FLAG_RESET, watched, bytes, found.data(), &count, &granularity); // clear + for (std::size_t p = 0; p < 37; ++p) watched[p * 3 * kPage] = 1; + count = found.size(); + const auto start = clock_type::now(); + const UINT r = GetWriteWatch(WRITE_WATCH_FLAG_RESET, watched, bytes, found.data(), &count, &granularity); + const double us = us_since(start); + std::printf(" private memory: GetWriteWatch %s, %llu of 37 written pages reported, %.1f us for 16 MiB " + "(%.3f us a page)\n", + r == 0 ? "works" : "fails", static_cast(r == 0 ? count : 0), us, + us / double(bytes / kPage)); + VirtualFree(watched, 0, MEM_RELEASE); + } + // A section view, as xmem maps the title's physical pages: write watching is not a flag of a view. + HANDLE section = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, DWORD(bytes), nullptr); + auto* view = section ? static_cast(MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, bytes)) : nullptr; + if (view) { + std::vector found(bytes / kPage); + ULONG_PTR count = found.size(); + ULONG granularity = 0; + view[0] = 1; + const UINT r = GetWriteWatch(0, view, bytes, found.data(), &count, &granularity); + std::printf(" section view: GetWriteWatch %s (error %lu): a view cannot be write-watched (on Windows " + "neither: only VirtualAlloc'd reservations made with MEM_WRITE_WATCH)\n", + r == 0 ? "answers" : "fails", r == 0 ? 0ul : GetLastError()); + UnmapViewOfFile(view); + } + if (section) CloseHandle(section); +} + +// Linux's soft-dirty bit (bit 55 of /proc/self/pagemap, cleared by writing 4 to /proc/self/clear_refs), through Wine's +// file layer (the Z: drive is the host's root): no Wine patch, no syscall of our own. +void soft_dirty(std::uint8_t* base) { + std::printf("Linux soft-dirty bits through Z:\\proc\\self:\n"); + HANDLE clear = CreateFileA("Z:\\proc\\self\\clear_refs", GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, + OPEN_EXISTING, 0, nullptr); + HANDLE map = CreateFileA("Z:\\proc\\self\\pagemap", GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, + OPEN_EXISTING, 0, nullptr); + if (clear == INVALID_HANDLE_VALUE || map == INVALID_HANDLE_VALUE) { + std::printf(" not reachable (clear_refs %s, pagemap %s; error %lu)\n", + clear == INVALID_HANDLE_VALUE ? "no" : "yes", map == INVALID_HANDLE_VALUE ? "no" : "yes", + GetLastError()); + if (clear != INVALID_HANDLE_VALUE) CloseHandle(clear); + if (map != INVALID_HANDLE_VALUE) CloseHandle(map); + return; + } + const auto read_bits = [&](std::uintptr_t va, std::size_t pages, std::vector& out) { + out.assign(pages, 0); + LARGE_INTEGER at{}; + at.QuadPart = LONGLONG(va / kPage * 8); + DWORD got = 0; + return SetFilePointerEx(map, at, nullptr, FILE_BEGIN) && + ReadFile(map, out.data(), DWORD(pages * 8), &got, nullptr) && got == pages * 8; + }; + constexpr std::size_t pages = 256; + for (std::size_t p = 0; p < pages; ++p) base[p * kPage] = 1; // present + DWORD wrote = 0; + auto start = clock_type::now(); + const bool cleared = WriteFile(clear, "4", 1, &wrote, nullptr) && wrote == 1; + const double clear_us = us_since(start); + for (std::size_t p = 0; p < pages; p += 4) base[p * kPage] = 2; + std::vector bits; + start = clock_type::now(); + const bool read = read_bits(reinterpret_cast(base), pages, bits); + const double read_us = us_since(start); + std::size_t dirty = 0, wrong = 0; + for (std::size_t p = 0; p < pages && read; ++p) { + const bool d = (bits[p] >> 55) & 1; + dirty += d; + wrong += d != (p % 4 == 0); + } + std::printf(" clear_refs %s (%.1f us, for the whole process), pagemap %s (%.1f us for %zu pages): %zu of %zu " + "written pages soft-dirty, %zu wrong\n", + cleared ? "written" : "refused", clear_us, read ? "read" : "refused", read_us, pages, dirty, pages / 4, + wrong); + CloseHandle(clear); + CloseHandle(map); +} + +} // namespace + +int main() { + constexpr std::size_t span = std::size_t(64) << 20; + auto* base = static_cast(VirtualAlloc(nullptr, span, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + CHECK(base != nullptr); + if (!base) return 1; + std::memset(base, 0, span); + g_lo.store(reinterpret_cast(base)); + g_hi.store(reinterpret_cast(base) + span); + CHECK(AddVectoredExceptionHandler(1, &on_fault) != nullptr); + protect_costs(base); + fault_costs(base, span); + write_watch(); + soft_dirty(base); + VirtualFree(base, 0, MEM_RELEASE); + return failures ? 1 : 0; +} diff --git a/runtime/test/list_value_progress_test.cpp b/runtime/test/list_value_progress_test.cpp new file mode 100644 index 0000000000..6f24ba3139 --- /dev/null +++ b/runtime/test/list_value_progress_test.cpp @@ -0,0 +1,556 @@ +// Portable CPU-only tests for runtime/src/list_value_progress.h: when a held console memory wait may go without its +// value. Nothing can make progress first; then a cycle goes at once, a root (a wait no held write meets) goes at a +// present queued after it or when the title has stopped calling, and a gate whose writer is held behind another +// queue's root waits for that root. No time alone ever releases a gate. No Windows, D3D12 or Vulkan headers. +#include "../src/list_value_progress.h" +#include "../src/queue_holds.h" + +#include +#include +#include +#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 { + +using namespace leonida::list_value_progress; + +constexpr bool 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; + } +} + +int qa_, qb_, qc_; +const void* const qa = &qa_; +const void* const qb = &qb_; +const void* const qc = &qc_; + +PendingGate gate(const void* queue, std::uint64_t value, std::span waits, + std::uint64_t presents_at_hold = 0, std::uint64_t held_ms = 0) { + PendingGate g; + g.queue = queue; + g.value = value; + g.unmet_waits = waits; + g.presents_at_hold = presents_at_hold; + g.held_ms = held_ms; + return g; +} + +PendingWriteGroup group(const void* queue, std::uint64_t after_gate, std::span writes, + bool running = false) { + PendingWriteGroup w; + w.queue = queue; + w.after_gate = after_gate; + w.running = running; + w.writes = writes; + return w; +} + +Decision run(std::span writes, std::span gates, const Activity& activity) { + return decide(writes, gates, activity, met); +} + +} // namespace + +int main() { + const WaitPredicate wait_x[] = {{0x1000, 5, 7, true}}; // x >= 5 + const WaitPredicate wait_y[] = {{0x2000, 9, 7, true}}; // y >= 9 + const WaitPredicate wait_z[] = {{0x3000, 1, 3, false}}; // z == 1 (32-bit) + const PendingWrite write_x[] = {{0x1000, 5, 8, false}}; + const PendingWrite write_y[] = {{0x2000, 9, 8, false}}; + const PendingWrite write_x_low[] = {{0x1000, 4, 8, false}}; + + // 1. One gate, nothing in flight, no present, the title calling: held, however long it has stood. + { + const PendingGate gates[] = {gate(qa, 1, wait_x, 0, 0)}; + Activity a; + a.now_ms = 3'600'000; // an hour after it was held + a.title_call_ms = a.now_ms; // the title called just now + CHECK(run({}, gates, a).reason == Reason::hold); + } + + // 2. Something can still make progress: no release, whatever else holds (a present queued, the title quiet). + { + const PendingGate gates[] = {gate(qa, 1, wait_x, 0, 0)}; + Activity quiet; + quiet.presents = 5; + quiet.now_ms = 100'000; + Activity a = quiet; + a.releasing = true; + CHECK(run({}, gates, a).reason == Reason::hold); + a = quiet; + a.title_submitting = true; + CHECK(run({}, gates, a).reason == Reason::hold); + // A running write group, even one that does not meet the wait: it may unblock what does. + const PendingWriteGroup running[] = {group(qb, 0, write_y, true)}; + CHECK(run(running, gates, quiet).reason == Reason::hold); + // A running action on another queue. + PendingGate action = gate(qc, 1, {}); + action.is_action = true; + action.action_running = true; + const PendingGate with_action[] = {gates[0], action}; + CHECK(run({}, with_action, quiet).reason == Reason::hold); + CHECK(can_progress(running, gates, quiet) && !can_progress({}, gates, quiet)); + // The same with nothing running: the present releases it. + CHECK(run({}, gates, quiet).reason == Reason::present && run({}, gates, quiet).gate == 0); + } + + // 3. Present rule: only a present made after the gate was held counts. + { + const PendingGate gates[] = {gate(qa, 1, wait_x, 3, 0)}; + Activity a; + a.now_ms = 10; + a.title_call_ms = 10; + a.presents = 3; // the present before the hold + CHECK(run({}, gates, a).reason == Reason::hold); + a.presents = 4; + const Decision d = run({}, gates, a); + CHECK(d.reason == Reason::present && d.gate == 0); + } + + // 4. Stalled rule: the title made no queue call for kStalledMs while nothing ran, and the gate stood that long. + { + const PendingGate gates[] = {gate(qa, 1, wait_x, 0, 1000)}; + Activity a; + a.title_call_ms = 1000; + a.now_ms = 1000 + kStalledMs - 1; + CHECK(run({}, gates, a).reason == Reason::hold); + a.now_ms = 1000 + kStalledMs; + CHECK(run({}, gates, a).reason == Reason::stalled); + a.title_call_ms = a.now_ms - 1; // a call just now: held again + CHECK(run({}, gates, a).reason == Reason::hold); + // A gate held after the title's last call needs to have stood kStalledMs too. + const PendingGate young[] = {gate(qa, 1, wait_x, 0, 1000 + kStalledMs)}; + a.title_call_ms = 1000; + CHECK(run({}, young, a).reason == Reason::hold); + } + + // 5. A cycle goes at once, without a present: A waits for x, written by B's group held behind B's gate, which + // waits for y, written by A's group held behind A's gate. + { + const PendingGate gates[] = {gate(qa, 1, wait_x), gate(qb, 1, wait_y)}; + const PendingWriteGroup writes[] = {group(qb, 1, write_x), group(qa, 1, write_y)}; + Activity a; + a.now_ms = 5; + a.title_call_ms = 5; + const Decision d = run(writes, gates, a); + CHECK(d.reason == Reason::cycle && d.gate == 0); + // A queue's own later write behind its gate: a cycle of one queue. + const PendingGate self[] = {gate(qa, 1, wait_x)}; + const PendingWriteGroup own[] = {group(qa, 1, write_x)}; + CHECK(run(own, self, a).reason == Reason::cycle); + // But while either writer runs, nothing goes. + const PendingWriteGroup running[] = {group(qb, 1, write_x), group(qa, 0, write_y, true)}; + CHECK(run(running, gates, a).reason == Reason::hold); + } + + // 6. A chain unwinds from its root: A waits for x, which B's group writes behind B's gate; B's gate waits for z, + // which nothing writes. At a present, B's gate goes first (A then waits for B's write), though A is older. + { + const PendingGate gates[] = {gate(qa, 1, wait_x), gate(qb, 1, wait_z)}; + const PendingWriteGroup writes[] = {group(qb, 1, write_x)}; + Activity a; + a.now_ms = 5; + a.title_call_ms = 5; + CHECK(run(writes, gates, a).reason == Reason::hold); // no present, the title calling: held + a.presents = 1; + const Decision d = run(writes, gates, a); + CHECK(d.reason == Reason::present && d.gate == 1); + } + + // 7. A write that does not meet the wait (too low), or one overwritten later in its group, is no writer: the gate + // is a root. A timestamp write to the address counts as a writer. + { + const PendingGate gates[] = {gate(qa, 1, wait_x)}; + const PendingWriteGroup low[] = {group(qb, 1, write_x_low)}; + const PendingGate b_gate[] = {gates[0], gate(qb, 1, wait_z)}; + Activity a; + a.presents = 1; + a.now_ms = 5; + a.title_call_ms = 5; + Decision d = run(low, b_gate, a); + CHECK(d.reason == Reason::present && d.gate == 0); // both roots: the older goes + const PendingWrite overwritten[] = {{0x1000, 5, 8, false}, {0x1000, 4, 8, false}}; + const PendingWriteGroup over[] = {group(qb, 1, overwritten)}; + d = run(over, b_gate, a); + CHECK(d.reason == Reason::present && d.gate == 0); + const PendingWrite stamp[] = {{0x1000, 0, 8, true}}; + const PendingWriteGroup stamped[] = {group(qb, 1, stamp)}; + d = run(stamped, b_gate, a); + CHECK(d.reason == Reason::present && d.gate == 1); // A waits for B's timestamp: B's root goes first + } + + // 8. Only a queue's first gate is a candidate; a queue's later gate never goes before its first. + { + const PendingGate gates[] = {gate(qa, 1, wait_x, 1), gate(qa, 2, wait_y, 0)}; + Activity a; + a.presents = 1; // after the second gate's hold, not after the first's + a.now_ms = 5; + a.title_call_ms = 5; + CHECK(run({}, gates, a).reason == Reason::hold); + a.presents = 2; + const Decision d = run({}, gates, a); + CHECK(d.reason == Reason::present && d.gate == 0); + } + + // 9. A writer held by something not modelled here (a relayed wait or a title fence; no gate of ours before it): + // the gate counts as a root, so the present releases it rather than waiting for ever. + { + const PendingGate gates[] = {gate(qa, 1, wait_x)}; + const PendingWriteGroup writes[] = {group(qb, 0, write_x, false)}; + Activity a; + a.presents = 1; + a.now_ms = 5; + a.title_call_ms = 5; + const Decision d = run(writes, gates, a); + CHECK(d.reason == Reason::present && d.gate == 0); + } + + // 10. Action gates are never released by these rules (they open when their point of the queue is reached). + { + PendingGate action = gate(qa, 1, {}); + action.is_action = true; + const PendingGate gates[] = {action}; + Activity a; + a.presents = 9; + a.now_ms = 100'000; + CHECK(run({}, gates, a).reason == Reason::hold); + } + + // 11. QueueHolds progress integration (LEONIDA_SUBMIT_ASYNC + busy worker + unretired GPU work): + // a held gate with a queued Present must NOT be released unmet while any queue has active CPU/async work, + // an unpumped signal for held work, or unretired GPU work; once all queues and the GPU are truly idle, + // genuine Present and cycle deadlocks still break cleanly. + { + struct MockHolder final : leonida::QueueHolds::Holder { + std::atomic gpu_busy{false}; + bool release_ready() override { return false; } + void discard_waiting_on(std::uint64_t) override {} + std::uint64_t oldest_held_seq() override { return 0; } + bool has_pending_gpu_work() const override { return gpu_busy.load(std::memory_order_acquire); } + }; + + leonida::QueueHolds holds; + MockHolder holder; + holds.attach(&holder); + holds.add_fence(1, 0); + CHECK(!leonida::queue_holds::any_progress()); + + const PendingGate gates[] = {gate(qa, 1, wait_x, 0, 0)}; + // Producer's write group has running == false because its Signal is still sitting in an async queue inbox. + const PendingWriteGroup queued_write[] = {group(qb, 0, write_x, false)}; + Activity at_present; + at_present.presents = 1; + at_present.now_ms = 250; + at_present.title_call_ms = 10; + + // 11a. Active async inbox / busy worker keeps any_progress() true -> gate stays held at Present. + { + leonida::QueueHolds::WorkGuard busy(holds); + CHECK(leonida::queue_holds::any_progress()); + Activity a = at_present; + a.title_submitting = leonida::queue_holds::any_progress(); + CHECK(run(queued_write, gates, a).reason == Reason::hold); + } + CHECK(!leonida::queue_holds::any_progress()); + + // 11b. Unpumped Signal while held work exists keeps any_progress() true until pump_ready() runs. + holds.held_changed(1); + holds.signaled(1, 1); + CHECK(leonida::queue_holds::any_progress()); + { + Activity a = at_present; + a.title_submitting = leonida::queue_holds::any_progress(); + CHECK(run(queued_write, gates, a).reason == Reason::hold); + } + holds.pump_ready(); + holds.held_changed(-1); + CHECK(!leonida::queue_holds::any_progress()); + + // 11c. Unretired GPU submission on any queue keeps any_progress() true -> gate stays held at Present. + holder.gpu_busy.store(true, std::memory_order_release); + CHECK(leonida::queue_holds::any_progress()); + { + Activity a = at_present; + a.title_submitting = leonida::queue_holds::any_progress(); + CHECK(run({}, gates, a).reason == Reason::hold); + } + // Once the GPU retires and all queues are idle, a genuine Present deadlock breaks cleanly. + holder.gpu_busy.store(false, std::memory_order_release); + CHECK(!leonida::queue_holds::any_progress()); + { + Activity a = at_present; + a.title_submitting = leonida::queue_holds::any_progress(); + const Decision d = run({}, gates, a); + CHECK(d.reason == Reason::present && d.gate == 0); + } + + // 11d. Genuine cycle deadlock also breaks cleanly once queues and GPU are idle. + { + const PendingGate cycle_gates[] = {gate(qa, 1, wait_x), gate(qb, 1, wait_y)}; + const PendingWriteGroup cycle_writes[] = {group(qb, 1, write_x), group(qa, 1, write_y)}; + Activity a; + a.now_ms = 5; + a.title_call_ms = 5; + a.title_submitting = leonida::queue_holds::any_progress(); + const Decision d = run(cycle_writes, cycle_gates, a); + CHECK(d.reason == Reason::cycle && d.gate == 0); + } + + holds.detach(&holder); + } + + // 12. Round 8 P0 TOCTOU + Present quiet-window debounce invariants: + // (a) A write group or action whose GPU fence already completed (done >= target, awaiting take_landed()) MUST + // count as active progress (running == true -> Reason::hold even at Present), never stuck! + // (b) A 10 ms quiet debounce on Reason::present (matching Pump::choose_release()) defers unmet Present release + // while progress occurred within the last 10 ms, while leaving Reason::cycle immediate and decide() pure. + { + const PendingGate gates[] = {gate(qa, 1, wait_x, 0, 0)}; + Activity at_present; + at_present.presents = 1; + at_present.now_ms = 100; + at_present.title_call_ms = 95; + + // Simulate write group whose GPU fence already retired (done == target, done != UINT64_MAX): + // must be classified as active progress (never passed to decide() as running == false). + const auto write_progress = [](std::uint64_t done, std::uint64_t target, bool submitted) { + return done != UINT64_MAX && (done >= target || submitted); + }; + CHECK(write_progress(/*done=*/5, /*target=*/5, /*submitted=*/false)); // retired between take_landed & check + CHECK(write_progress(/*done=*/6, /*target=*/5, /*submitted=*/false)); // retired past target + CHECK(write_progress(/*done=*/4, /*target=*/5, /*submitted=*/true)); // in flight on GPU + CHECK(!write_progress(/*done=*/4, /*target=*/5, /*submitted=*/false)); // held in layer, not submitted + CHECK(!write_progress(UINT64_MAX, /*target=*/5, /*submitted=*/true)); // device lost + + // Present quiet window helper matching Pump::choose_release(): gates ONLY Reason::present. + constexpr std::uint64_t kPresentQuietMs = 10; + const auto apply_present_quiet = [&](Decision d, std::uint64_t now_ms, std::uint64_t last_progress_ms) { + if (d.reason == Reason::present && now_ms >= last_progress_ms && + now_ms - last_progress_ms < kPresentQuietMs) + return Decision{}; + return d; + }; + const Decision raw_present = run({}, gates, at_present); + CHECK(raw_present.reason == Reason::present && raw_present.gate == 0); // decide() itself remains pure + CHECK(apply_present_quiet(raw_present, /*now_ms=*/100, /*last_progress_ms=*/95).reason == Reason::hold); + CHECK(apply_present_quiet(raw_present, /*now_ms=*/104, /*last_progress_ms=*/95).reason == Reason::hold); + CHECK(apply_present_quiet(raw_present, /*now_ms=*/105, /*last_progress_ms=*/95).reason == Reason::present); + + // Cycle release is NOT delayed by the Present quiet window. + const PendingGate cycle_gates[] = {gate(qa, 1, wait_x), gate(qb, 1, wait_y)}; + const PendingWriteGroup cycle_writes[] = {group(qb, 1, write_x), group(qa, 1, write_y)}; + const Decision raw_cycle = run(cycle_writes, cycle_gates, at_present); + CHECK(raw_cycle.reason == Reason::cycle && raw_cycle.gate == 0); + CHECK(apply_present_quiet(raw_cycle, /*now_ms=*/100, /*last_progress_ms=*/100).reason == Reason::cycle); + } + + // 13. Round 8 P2 QueueHolds dedicated barrier-drain thread guardrails (a), (b), (c): + // (a) active_work_ / has_progress() stays true while barriers are queued or running on the barrier thread; + // (b) wait_barriers_drained(seq) waits for ready/running barriers <= seq without blocking on barriers > seq; + // (c) cancel_after(owner) cancels queued barriers (balancing active_work_) and waits for any running barrier; + // ~QueueHolds() cleanly shuts down and joins the barrier thread. + { + struct SeqHolder final : leonida::QueueHolds::Holder { + std::atomic oldest{0}; + bool release_ready() override { return false; } + void discard_waiting_on(std::uint64_t) override {} + std::uint64_t oldest_held_seq() override { return oldest.load(std::memory_order_acquire); } + }; + + { + leonida::QueueHolds holds; + SeqHolder holder; + holds.attach(&holder); + + // Hold seq 1 so barriers wait until released. + const std::uint64_t s1 = holds.next_seq(); + holder.oldest.store(s1, std::memory_order_release); + holds.held_changed(1); + + std::atomic in_b1{false}, go_b1{false}, b2_ran{false}, b3_ran{false}; + std::mutex order_m; + std::vector order; + int owner_a = 0, owner_cancel = 0; + + holds.after_held(&owner_a, [&] { + in_b1.store(true, std::memory_order_release); + while (!go_b1.load(std::memory_order_acquire)) std::this_thread::yield(); + std::lock_guard lk(order_m); + order.push_back(1); + }); + holds.after_held(&owner_a, [&] { + b2_ran.store(true, std::memory_order_release); + std::lock_guard lk(order_m); + order.push_back(2); + }); + holds.after_held(&owner_cancel, [&] { b3_ran.store(true, std::memory_order_release); }); + + // Release held op: pump_ready() hands barriers to the dedicated barrier thread and returns IMMEDIATELY! + holder.oldest.store(0, std::memory_order_release); + holds.held_changed(-1); + holds.pump_ready(); + + while (!in_b1.load(std::memory_order_acquire)) std::this_thread::yield(); + + // Guardrail (a): active_work_ / has_progress() MUST be true while b1 is running & b2/b3 are queued. + CHECK(holds.has_progress()); + CHECK(leonida::queue_holds::any_progress()); + + // Guardrail (b): wait_barriers_drained(s1) MUST block until b1 & b2 finish; wait_barriers_drained(s1 - 1) + // returns immediately when s1 > 0. + if (s1 > 0) holds.wait_barriers_drained(s1 - 1); + std::atomic drained_s1{false}; + std::thread waiter([&] { + holds.wait_barriers_drained(s1); + drained_s1.store(true, std::memory_order_release); + }); + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + CHECK(!drained_s1.load(std::memory_order_acquire)); + + // Guardrail (c): cancel_after(&owner_cancel) drops queued b3 and waits for running b1 before returning. + std::atomic cancel_done{false}; + std::thread canceller([&] { + holds.cancel_after(&owner_cancel); + cancel_done.store(true, std::memory_order_release); + }); + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + CHECK(!cancel_done.load(std::memory_order_acquire)); + + go_b1.store(true, std::memory_order_release); + waiter.join(); + canceller.join(); + + CHECK(drained_s1.load(std::memory_order_acquire)); + CHECK(cancel_done.load(std::memory_order_acquire)); + CHECK(b2_ran.load(std::memory_order_acquire)); + CHECK(!b3_ran.load(std::memory_order_acquire)); + CHECK((order == std::vector{1, 2})); + + // Once all barriers finished (and cancelled b3 decremented active_work_), has_progress() settles to false! + const auto settle = std::chrono::steady_clock::now() + std::chrono::milliseconds(500); + while (holds.has_progress() && std::chrono::steady_clock::now() < settle) + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + CHECK(!holds.has_progress()); + CHECK(!leonida::queue_holds::any_progress()); + + holds.detach(&holder); + } // ~QueueHolds() cleanly stops and joins barrier_thread_ + } + + // 14. Round 10 WS3 QueueHolds::relay_wait redirect table, pruning, multi-wait substitution, and in-transit lookup: + { + struct RelayHolder final : leonida::QueueHolds::Holder { + using Wait = leonida::QueueHolds::Wait; + struct Op { + std::vector sems; + std::vector vals; + }; + std::vector held; + std::atomic release_calls{0}; + bool release_ready() override { + release_calls.fetch_add(1, std::memory_order_relaxed); + return false; + } + void discard_waiting_on(std::uint64_t) override {} + std::uint64_t oldest_held_seq() override { return 0; } + bool apply_wait_relay(std::uint64_t gate_sem, std::uint64_t gate_val, std::span replacements, + bool& any_substituted) override { + bool updated = false; + for (Op& op : held) { + const std::size_t n = op.sems.size(); + for (std::size_t i = 0; i < n; ++i) { + if (op.sems[i] != gate_sem || op.vals[i] != gate_val) continue; + any_substituted = true; + updated = true; + op.sems[i] = replacements[0].semaphore; + op.vals[i] = replacements[0].value; + for (std::size_t k = 1; k < replacements.size(); ++k) { + op.sems.push_back(replacements[k].semaphore); + op.vals.push_back(replacements[k].value); + } + } + } + return updated; + } + }; + + leonida::QueueHolds holds; + RelayHolder holder; + holds.attach(&holder); + holds.add_fence(10, 0); // gate fence (never signaled!) + holds.add_fence(20, 0); // writer A + holds.add_fence(30, 0); // writer B + holds.add_fence(40, 0); // already-signaled gate + holds.signaled(40, 5, 0); + + using Wait = leonida::QueueHolds::Wait; + // Reject invalid relays (self-relay, empty, already-passed gate). + const Wait self_rep[] = {{10, 1, {}}}; + CHECK(!holds.relay_wait(10, 1, self_rep)); + CHECK(!holds.relay_wait(10, 1, {})); + const Wait ok_rep[] = {{20, 2, {}}}; + CHECK(!holds.relay_wait(40, 5, ok_rep)); // gate 40 already at 5 + CHECK(holds.active_relay_count() == 0); + + // Multi-wait substitution in held op + consume_on_substitute immediate pruning + pump_ready() trigger. + holder.held.push_back({{10}, {1}}); + holds.held_changed(1); + const Wait multi_rep[] = {{20, 2, {}}, {30, 3, {}}}; + CHECK(holds.relay_wait(10, 1, multi_rep, /*consume_on_substitute=*/true)); + CHECK(holds.active_relay_count() == 0); // pruned immediately on substitute! + CHECK(holder.release_calls.load() >= 1); + CHECK((holder.held[0].sems == std::vector{20, 30})); + CHECK((holder.held[0].vals == std::vector{2, 3})); + CHECK(holds.pending(10, 1)); // gate 10 was NEVER signaled! + holds.held_changed(-1); + + // In-transit lookup_relay() when apply_wait_relay finds nothing yet (race ordering): relay_wait() returns false + // (nothing substituted yet) while keeping the redirect registered for lookup_relay() and consume pruning. + const Wait single_rep[] = {{20, 4, {}}}; + CHECK(!holds.relay_wait(10, 2, single_rep, /*consume_on_substitute=*/true)); + CHECK(holds.active_relay_count() == 1); // retained for in-transit waiter + CHECK(!holds.relay_wait(10, 2, single_rep, /*consume_on_substitute=*/true)); // duplicate rejected cleanly + CHECK(holds.active_relay_count() == 1); + std::vector found; + CHECK(holds.lookup_relay(10, 2, found)); + CHECK(found.size() == 1 && found[0].semaphore == 20 && found[0].value == 4); + CHECK(holds.active_relay_count() == 0); // consumed and pruned! + CHECK(!holds.lookup_relay(10, 2, found)); + + // Non-consuming relays (with no matching waiter yet -> returns false, still registered) prune cleanly when + // gate is later signaled past gate_val or replacement fence is removed. + CHECK(!holds.relay_wait(10, 3, single_rep, /*consume_on_substitute=*/false)); + CHECK(!holds.relay_wait(10, 7, single_rep, /*consume_on_substitute=*/false)); + CHECK(holds.active_relay_count() == 2); + holds.signaled(10, 5, 0); + CHECK(holds.active_relay_count() == 1); // val 3 pruned, val 7 kept + holds.remove_fence(20); + CHECK(holds.active_relay_count() == 0); // replacement fence removed -> pruned + + holds.detach(&holder); + } + + std::printf("list_value_progress_test: all checks passed\n"); + return 0; +} diff --git a/runtime/test/list_value_wait_budget_test.cpp b/runtime/test/list_value_wait_budget_test.cpp deleted file mode 100644 index 6bf9bfbf53..0000000000 --- a/runtime/test/list_value_wait_budget_test.cpp +++ /dev/null @@ -1,348 +0,0 @@ -// 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/memory_breakdown_test.cpp b/runtime/test/memory_breakdown_test.cpp index d27a1166d7..fd99fda42f 100644 --- a/runtime/test/memory_breakdown_test.cpp +++ b/runtime/test/memory_breakdown_test.cpp @@ -87,6 +87,10 @@ int text() { share.arena_in_use = 757 * kMiB; share.arena_use = {500 * kMiB, 171 * kMiB, 80 * kMiB, 6 * kMiB}; share.bindless_table_bytes = 2 * kMiB; + share.mirror = true; + share.mirror_homes = 32; + share.mirror_pages = 40; + share.mirror_chunks = 1; const std::string line = mb::format(t, share, 12 * kMiB); std::fprintf(stderr, "%s\n", line.c_str()); EXPECT(line.rfind("allocated 9961 MiB = arena 4095 (1) [reserved 4095, bound 4095, in use 757: buffers 500, " @@ -95,7 +99,10 @@ int text() { EXPECT(contains(line, " + geometry copies 3867 (1)")); EXPECT(contains(line, " + title windows and shadows 0 (0)")); EXPECT(contains(line, " + upload heaps 0 (0) + staging 0 (0) + texture blocks 0 (0) + sampled textures 0 (0)")); - EXPECT(contains(line, " + render targets and depth 1180 (1) + other 819 (1);")); + EXPECT(contains(line, " + render targets and depth 1180 (1) + page mirror 0 (0)")); + EXPECT(contains(line, " 0 host] + other 819 (1);")); + EXPECT(contains(line, "page mirror 0 (0) [homes bound 2 MiB (32), pages mirrored 40, chunks 1, units 0 " + "device-local 0 host]")); EXPECT(contains(line, "imported 206 MiB (1)")); EXPECT(contains(line, "bindless tables 2 MiB")); EXPECT(contains(line, "shader modules 12 MiB SPIR-V")); diff --git a/runtime/test/r3b_runtime_hooks_test.cpp b/runtime/test/r3b_runtime_hooks_test.cpp new file mode 100644 index 0000000000..9de99a2570 --- /dev/null +++ b/runtime/test/r3b_runtime_hooks_test.cpp @@ -0,0 +1,962 @@ +// Round 3B runtime hooks test: +// 1. LiteralSamplerSpec builds valid VkSpecializationInfo entries with SpecId base + i, 0xFFFFFFFF fallback, +// and uint32 overflow protection (CPU-only). +// 2. vulkan_replay emits a pre-dispatch COMPUTE->COMPUTE SHADER_WRITE -> SHADER_READ|SHADER_WRITE memory barrier +// iff ComputePipeline::reads_glc_buffer == true (direct and indirect dispatch), and fires +// ReplayFunctions::on_buffer_write + PreparedList::wrote_buffer iff writes_buffer == true (CPU-only). +// 3. Live Vulkan test (when a GPU is present): enables vulkanMemoryModel + vulkanMemoryModelDeviceScope, +// compiles a hand-written SPIR-V 1.5 compute shader declaring OpCapability VulkanMemoryModel/DeviceScope +// and two OpSpecConstant uint32s, specializes them via LiteralSamplerSpec (one live BindlessSet sampler index +// and one 0xFFFFFFFF fallback), dispatches through VulkanQueue with reads_glc_buffer=true, verifies +// on_buffer_write_submitted fires iff writes_buffer==true, and reads back the specialized values from the GPU. +// No game data. + +#ifndef VK_NO_PROTOTYPES +#define VK_NO_PROTOTYPES +#endif + +#include "../src/literal_sampler_spec.h" +#include "../src/title_mirror.h" +#include "../src/title_texture_refresh.h" +#include "../src/vulkan_backend.h" +#include "../src/vulkan_bindless.h" +#include "../src/vulkan_replay.h" +#include "vk_test_device.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +int failures = 0; + +void check(bool ok, const char* what, int line) { + if (ok) return; + std::fprintf(stderr, "FAIL (line %d): %s\n", line, what); + ++failures; +} + +#define CHECK(expr) check((expr), #expr, __LINE__) + +template +T fake_handle(std::uintptr_t n) { + return reinterpret_cast(n); +} + +// --------------------------------------------------------------------------------------------------------------- +// Part 1: LiteralSamplerSpec unit checks (CPU-only) + +void test_literal_sampler_spec() { + leonida::LiteralSamplerSpec spec; + CHECK(!spec.active() && spec.ptr() == nullptr); + + // Empty slice leaves spec inactive. + const std::vector empty; + spec.build(100u, empty); + CHECK(!spec.active() && spec.ptr() == nullptr); + + // Normal specialization with a bound index, a fallback sentinel, and another bound index. + const std::uint32_t indices[3] = {5u, leonida::LiteralSamplerSpec::kFallbackIndex, 42u}; + spec.build(100u, indices); + CHECK(spec.active() && spec.ptr() != nullptr); + const VkSpecializationInfo* info = spec.ptr(); + CHECK(info->mapEntryCount == 3); + CHECK(info->dataSize == 3 * sizeof(std::uint32_t)); + CHECK(info->pMapEntries != nullptr && info->pData != nullptr); + for (std::uint32_t i = 0; i < 3; ++i) { + CHECK(info->pMapEntries[i].constantID == 100u + i); + CHECK(info->pMapEntries[i].offset == i * sizeof(std::uint32_t)); + CHECK(info->pMapEntries[i].size == sizeof(std::uint32_t)); + } + const auto* vals = static_cast(info->pData); + CHECK(vals[0] == 5u && vals[1] == 0xFFFFFFFFu && vals[2] == 42u); + + // Boundary: SpecId UINT32_MAX with 1 entry is valid; with 2 entries overflows and safely clears. + const std::uint32_t one[1] = {7u}; + spec.build(std::numeric_limits::max(), one); + CHECK(spec.active() && spec.ptr()->pMapEntries[0].constantID == std::numeric_limits::max()); + + const std::uint32_t two[2] = {7u, 8u}; + spec.build(std::numeric_limits::max(), two); + CHECK(!spec.active() && spec.ptr() == nullptr); +} + +// --------------------------------------------------------------------------------------------------------------- +// Part 2: Replay reads_glc_buffer barrier + writes_buffer hook checks (CPU-only) + +struct RecordedBarrier { + VkPipelineStageFlags src_stage = 0; + VkPipelineStageFlags dst_stage = 0; + VkAccessFlags src_access = 0; + VkAccessFlags dst_access = 0; + std::size_t order = 0; +}; + +struct ReplayLog { + std::size_t seq = 0; + std::vector barriers; + std::vector dispatches; + std::vector indirect_dispatches; + std::vector begin_renderings; + std::vector draws; + std::size_t buffer_writes = 0; + + void reset() { + seq = 0; + barriers.clear(); + dispatches.clear(); + indirect_dispatches.clear(); + begin_renderings.clear(); + draws.clear(); + buffer_writes = 0; + } +}; + +ReplayLog g_log; + +void VKAPI_PTR mock_barrier(VkCommandBuffer, VkPipelineStageFlags src, VkPipelineStageFlags dst, VkDependencyFlags, + std::uint32_t mem_count, const VkMemoryBarrier* mem, std::uint32_t, + const VkBufferMemoryBarrier*, std::uint32_t, const VkImageMemoryBarrier*) { + RecordedBarrier b{}; + b.src_stage = src; + b.dst_stage = dst; + if (mem_count && mem) { + b.src_access = mem[0].srcAccessMask; + b.dst_access = mem[0].dstAccessMask; + } + b.order = ++g_log.seq; + g_log.barriers.push_back(b); +} + +void VKAPI_PTR mock_dispatch(VkCommandBuffer, std::uint32_t, std::uint32_t, std::uint32_t) { + g_log.dispatches.push_back(++g_log.seq); +} + +void VKAPI_PTR mock_dispatch_indirect(VkCommandBuffer, VkBuffer, VkDeviceSize) { + g_log.indirect_dispatches.push_back(++g_log.seq); +} + +void VKAPI_PTR mock_begin_rendering(VkCommandBuffer, const VkRenderingInfo*) { + g_log.begin_renderings.push_back(++g_log.seq); +} + +void VKAPI_PTR mock_draw(VkCommandBuffer, std::uint32_t, std::uint32_t, std::uint32_t, std::uint32_t) { + g_log.draws.push_back(++g_log.seq); +} + +void test_replay_hooks() { + using namespace leonida; + + std::map compute; + std::map graphics; + + ComputePipeline cs_ro{}; + cs_ro.layout = fake_handle(1); + cs_ro.pipeline = fake_handle(0x100); + cs_ro.reads_glc_buffer = false; + cs_ro.writes_buffer = false; + compute[1] = cs_ro; + + ComputePipeline cs_glc_rw{}; + cs_glc_rw.layout = fake_handle(1); + cs_glc_rw.pipeline = fake_handle(0x101); + cs_glc_rw.reads_glc_buffer = true; + cs_glc_rw.writes_buffer = true; + compute[2] = cs_glc_rw; + + ComputePipeline cs_glc_ro{}; + cs_glc_ro.layout = fake_handle(1); + cs_glc_ro.pipeline = fake_handle(0x102); + cs_glc_ro.reads_glc_buffer = true; + cs_glc_ro.writes_buffer = false; + compute[3] = cs_glc_ro; + + ComputePipeline cs_rw_noglc{}; + cs_rw_noglc.layout = fake_handle(1); + cs_rw_noglc.pipeline = fake_handle(0x103); + cs_rw_noglc.reads_glc_buffer = false; + cs_rw_noglc.writes_buffer = true; + compute[4] = cs_rw_noglc; + + ComputePipeline cs_skipped{}; + cs_skipped.layout = fake_handle(1); + cs_skipped.skipped = true; + cs_skipped.writes_buffer = true; + cs_skipped.build = +[](void*) -> VkPipeline { return VK_NULL_HANDLE; }; + compute[5] = cs_skipped; + + GraphicsPipeline gfx_ro{}; + gfx_ro.layout = fake_handle(2); + gfx_ro.pipeline = fake_handle(0x200); + gfx_ro.color_formats = {VK_FORMAT_R8G8B8A8_UNORM}; + gfx_ro.vertex_slots = 1; + gfx_ro.writes_buffer = false; + graphics[10] = gfx_ro; + + GraphicsPipeline gfx_rw = gfx_ro; + gfx_rw.pipeline = fake_handle(0x201); + gfx_rw.writes_buffer = true; + graphics[11] = gfx_rw; + + GraphicsPipeline gfx_glc = gfx_ro; + gfx_glc.pipeline = fake_handle(0x202); + gfx_glc.reads_glc_buffer = true; + gfx_glc.writes_buffer = false; + graphics[12] = gfx_glc; + + ReplayFunctions vk{}; + vk.pipeline_barrier = &mock_barrier; + vk.bind_pipeline = +[](VkCommandBuffer, VkPipelineBindPoint, VkPipeline) {}; + vk.push_constants = +[](VkCommandBuffer, VkPipelineLayout, VkShaderStageFlags, std::uint32_t, std::uint32_t, + const void*) {}; + vk.dispatch = &mock_dispatch; + vk.dispatch_indirect = &mock_dispatch_indirect; + vk.begin_rendering = &mock_begin_rendering; + vk.end_rendering = +[](VkCommandBuffer) {}; + vk.set_viewport = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, const VkViewport*) {}; + vk.set_scissor = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, const VkRect2D*) {}; + vk.set_primitive_topology = +[](VkCommandBuffer, VkPrimitiveTopology) {}; + vk.set_primitive_restart_enable = +[](VkCommandBuffer, VkBool32) {}; + vk.set_stencil_reference = +[](VkCommandBuffer, VkStencilFaceFlags, std::uint32_t) {}; + vk.set_blend_constants = +[](VkCommandBuffer, const float*) {}; + vk.bind_index_buffer = +[](VkCommandBuffer, VkBuffer, VkDeviceSize, VkIndexType) {}; + vk.bind_vertex_buffers2 = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, const VkBuffer*, const VkDeviceSize*, + const VkDeviceSize*, const VkDeviceSize*) {}; + vk.draw = &mock_draw; + vk.draw_indexed = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, std::uint32_t, std::int32_t, std::uint32_t) {}; + vk.image_view = [](const ResourceBinding&, const VkImageSubresourceRange&) { return fake_handle(8); }; + vk.buffer_at = [](std::uint64_t, std::uint64_t&, VkBuffer& buffer, VkDeviceSize& offset) { + buffer = fake_handle(9); + offset = 0; + return true; + }; + vk.compute_pipeline = [&compute](std::uintptr_t id) -> const ComputePipeline* { + const auto it = compute.find(id); + return it == compute.end() ? nullptr : &it->second; + }; + vk.graphics_pipeline = [&graphics](std::uintptr_t id) -> const GraphicsPipeline* { + const auto it = graphics.find(id); + return it == graphics.end() ? nullptr : &it->second; + }; + vk.on_buffer_write = +[](void* ctx) { ++static_cast(ctx)->buffer_writes; }; + vk.on_buffer_write_context = &g_log; + + constexpr ResourceId kColorId = 1; + constexpr ResourceId kArgBufId = 2; + const auto resolve = [](ResourceId id) -> const ResourceBinding* { + static const ResourceBinding color = [] { + ResourceBinding b{}; + b.aspects = VK_IMAGE_ASPECT_COLOR_BIT; + b.format = VK_FORMAT_R8G8B8A8_UNORM; + b.width = b.height = 16; + b.image = fake_handle(10); + return b; + }(); + static const ResourceBinding arg_buf = [] { + ResourceBinding b{}; + b.buffer = fake_handle(11); + b.size = 256; + b.indirect_arguments = true; + return b; + }(); + if (id == kColorId) return &color; + if (id == kArgBufId) return &arg_buf; + return nullptr; + }; + + const auto make_draw = [&](std::uintptr_t pso) { + Draw d{}; + d.pipeline = pso; + d.topology = 4; + d.count = 3; + d.instances = 1; + auto views = std::make_shared(); + views->render_targets[0] = {kColorId, 0, 0, 1}; + views->render_target_count = 1; + views->vertex_buffers[0].va = 0x1000; + views->vertex_buffers[0].size = 64; + d.views = views; + return d; + }; + + const auto run_list = [&](const CommandList& list, PreparedList& out) { + g_log.reset(); + CHECK(prepare(list, resolve, vk, out) == ReplayResult::success); + emit(out, fake_handle(99), vk); + }; + + // 2a: Direct dispatch with reads_glc_buffer=false, writes_buffer=false. + { + CommandList list; + Dispatch d{}; + d.pipeline = 1; + d.x = d.y = d.z = 1; + CHECK(list.dispatch(d) && list.close()); + PreparedList prep; + run_list(list, prep); + CHECK(!prep.wrote_buffer); + CHECK(g_log.barriers.empty()); + CHECK(g_log.dispatches.size() == 1); + CHECK(g_log.buffer_writes == 0); + } + + // 2b: Direct dispatch with reads_glc_buffer=true, writes_buffer=true (direct queue: src_stage = shader_stages). + { + CommandList list; + Dispatch d{}; + d.pipeline = 2; + d.x = d.y = d.z = 1; + CHECK(list.dispatch(d) && list.close()); + PreparedList prep; + run_list(list, prep); + CHECK(prep.wrote_buffer); + CHECK(g_log.barriers.size() == 1); + CHECK(g_log.dispatches.size() == 1); + CHECK(g_log.barriers[0].order < g_log.dispatches[0]); + CHECK(g_log.barriers[0].src_stage == shader_stages); + CHECK(g_log.barriers[0].dst_stage == VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); + CHECK(g_log.barriers[0].src_access == VK_ACCESS_SHADER_WRITE_BIT); + CHECK(g_log.barriers[0].dst_access == (VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT)); + CHECK(g_log.buffer_writes == 1); + } + + // 2b-compute: Dedicated compute queue restricts src_stage to COMPUTE_SHADER_BIT (no ALL_GRAPHICS_BIT). + { + vk.queue_stages = detail::queue_stages_compute; + CommandList list; + Dispatch d{}; + d.pipeline = 2; + d.x = d.y = d.z = 1; + CHECK(list.dispatch(d) && list.close()); + PreparedList prep; + run_list(list, prep); + vk.queue_stages = 0; + CHECK(g_log.barriers.size() == 1); + CHECK(g_log.barriers[0].src_stage == VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); + CHECK(g_log.barriers[0].dst_stage == VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); + } + + // 2c: Indirect dispatch (2 records) with reads_glc_buffer=true, writes_buffer=false. + { + CommandList list; + ExecuteIndirect ind{}; + ind.kind = IndirectKind::dispatch; + ind.max_count = 2; + ind.argument_buffer = kArgBufId; + ind.argument_offset = 0; + ind.stride = sizeof(VkDispatchIndirectCommand); + ind.pipeline = 3; + CHECK(list.execute_indirect(ind) && list.close()); + PreparedList prep; + run_list(list, prep); + CHECK(!prep.wrote_buffer); + CHECK(g_log.indirect_dispatches.size() == 2); + CHECK(g_log.barriers.size() == 2); + CHECK(g_log.barriers[0].order < g_log.indirect_dispatches[0]); + CHECK(g_log.barriers[1].order > g_log.indirect_dispatches[0] && + g_log.barriers[1].order < g_log.indirect_dispatches[1]); + CHECK(g_log.barriers[0].src_stage == shader_stages); + CHECK(g_log.barriers[0].dst_stage == VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); + CHECK(g_log.barriers[0].src_access == VK_ACCESS_SHADER_WRITE_BIT); + CHECK(g_log.barriers[0].dst_access == (VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT)); + CHECK(g_log.buffer_writes == 0); + } + + // 2d: Indirect dispatch with reads_glc_buffer=false, writes_buffer=true. + { + CommandList list; + ExecuteIndirect ind{}; + ind.kind = IndirectKind::dispatch; + ind.max_count = 1; + ind.argument_buffer = kArgBufId; + ind.argument_offset = 0; + ind.stride = sizeof(VkDispatchIndirectCommand); + ind.pipeline = 4; + CHECK(list.execute_indirect(ind) && list.close()); + PreparedList prep; + run_list(list, prep); + CHECK(prep.wrote_buffer); + CHECK(g_log.barriers.empty()); + CHECK(g_log.indirect_dispatches.size() == 1); + CHECK(g_log.buffer_writes == 1); + } + + // 2e: Skipped compute dispatch does NOT fire on_buffer_write. + { + CommandList list; + Dispatch d{}; + d.pipeline = 5; + d.x = d.y = d.z = 1; + CHECK(list.dispatch(d) && list.close()); + PreparedList prep; + run_list(list, prep); + CHECK(!prep.wrote_buffer); + CHECK(g_log.dispatches.empty()); + CHECK(g_log.buffer_writes == 0); + } + + // 2f: Graphics draw with writes_buffer=false, writes_buffer=true, and reads_glc_buffer=true. + { + CommandList list; + CHECK(list.draw(make_draw(10)) && list.close()); + PreparedList prep; + run_list(list, prep); + CHECK(!prep.wrote_buffer); + CHECK(g_log.draws.size() == 1); + CHECK(g_log.buffer_writes == 0); + // No GLC memory barrier (only image layout transition barriers have src_access != VK_ACCESS_SHADER_WRITE_BIT). + bool saw_glc = false; + for (const auto& b : g_log.barriers) + if (b.src_access == VK_ACCESS_SHADER_WRITE_BIT && b.dst_stage == VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) + saw_glc = true; + CHECK(!saw_glc); + } + { + CommandList list; + CHECK(list.draw(make_draw(11)) && list.close()); + PreparedList prep; + run_list(list, prep); + CHECK(prep.wrote_buffer); + CHECK(g_log.draws.size() == 1); + CHECK(g_log.buffer_writes == 1); + } + { + CommandList list; + CHECK(list.draw(make_draw(12)) && list.close()); + PreparedList prep; + run_list(list, prep); + CHECK(!prep.wrote_buffer); + CHECK(g_log.begin_renderings.size() == 1); + CHECK(g_log.draws.size() == 1); + CHECK(g_log.buffer_writes == 0); + bool saw_glc_before_rp = false; + for (const auto& b : g_log.barriers) { + if (b.src_stage == shader_stages && b.dst_stage == VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT && + b.src_access == VK_ACCESS_SHADER_WRITE_BIT && + b.dst_access == (VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT) && + b.order < g_log.begin_renderings[0]) { + saw_glc_before_rp = true; + } + } + CHECK(saw_glc_before_rp); + } +} + +// --------------------------------------------------------------------------------------------------------------- +// Part 3: Live GPU test (VulkanMemoryModel + LiteralSamplerSpec + reads_glc_buffer + on_buffer_write_submitted) + +// Hand-assembled SPIR-V 1.5 compute shader: +// - Optional OpCapability VulkanMemoryModel + VulkanMemoryModelDeviceScope (with OpMemoryModel Logical Vulkan) +// - layout(constant_id = 100) const uint kSpec0 = 0xFFFFFFFFu; +// - layout(constant_id = 101) const uint kSpec1 = 0xFFFFFFFFu; +// - layout(set = 0, binding = 0) buffer Out { uint vals[2]; } out_buf; +// - void main() { out_buf.vals[0] = kSpec0; out_buf.vals[1] = kSpec1; } +std::vector build_spec_test_spirv(bool use_vulkan_memory_model) { + std::vector w; + const auto emit = [&](std::uint16_t op, std::initializer_list args) { + w.push_back((std::uint32_t(args.size() + 1) << 16) | op); + for (std::uint32_t a : args) w.push_back(a); + }; + + // IDs + constexpr std::uint32_t kVoid = 1; + constexpr std::uint32_t kFnType = 2; + constexpr std::uint32_t kU32 = 3; + constexpr std::uint32_t kConst2 = 4; + constexpr std::uint32_t kArrU32 = 5; + constexpr std::uint32_t kStruct = 6; + constexpr std::uint32_t kPtrStruct = 7; + constexpr std::uint32_t kVarBuf = 8; + constexpr std::uint32_t kPtrU32 = 9; + constexpr std::uint32_t kConst0 = 10; + constexpr std::uint32_t kConst1 = 11; + constexpr std::uint32_t kSpec0 = 12; + constexpr std::uint32_t kSpec1 = 13; + constexpr std::uint32_t kMain = 14; + constexpr std::uint32_t kEntryLabel = 15; + constexpr std::uint32_t kPtr0 = 16; + constexpr std::uint32_t kPtr1 = 17; + constexpr std::uint32_t kBound = 18; + + // Header: magic, SPIR-V 1.5, generator 0, bound, schema 0 + w.push_back(0x07230203u); + w.push_back(0x00010500u); + w.push_back(0u); + w.push_back(kBound); + w.push_back(0u); + + // Capabilities + emit(17, {1u}); // OpCapability Shader + if (use_vulkan_memory_model) { + emit(17, {5345u}); // OpCapability VulkanMemoryModel + emit(17, {5346u}); // OpCapability VulkanMemoryModelDeviceScope + } + + // Memory model: Logical (0), Vulkan (3) or GLSL450 (1) + emit(14, {0u, use_vulkan_memory_model ? 3u : 1u}); + + // OpEntryPoint GLCompute(5) %main "main" %var_buf + // "main\0" packed little-endian: 0x6e69616du, 0x00000000u + emit(15, {5u, kMain, 0x6e69616du, 0u, kVarBuf}); + // OpExecutionMode %main LocalSize(17) 1 1 1 + emit(16, {kMain, 17u, 1u, 1u, 1u}); + + // Decorations + emit(71, {kArrU32, 6u, 4u}); // ArrayStride 4 + emit(72, {kStruct, 0u, 35u, 0u}); // MemberDecorate Offset 0 + emit(71, {kStruct, 2u}); // Block + emit(71, {kVarBuf, 34u, 0u}); // DescriptorSet 0 + emit(71, {kVarBuf, 33u, 0u}); // Binding 0 + emit(71, {kSpec0, 1u, 100u}); // SpecId 100 + emit(71, {kSpec1, 1u, 101u}); // SpecId 101 + + // Types & constants + emit(19, {kVoid}); // OpTypeVoid + emit(33, {kFnType, kVoid}); // OpTypeFunction + emit(21, {kU32, 32u, 0u}); // OpTypeInt 32 0 + emit(43, {kU32, kConst2, 2u}); // OpConstant 2 + emit(28, {kArrU32, kU32, kConst2}); // OpTypeArray u32[2] + emit(30, {kStruct, kArrU32}); // OpTypeStruct { u32[2] } + emit(32, {kPtrStruct, 12u, kStruct}); // OpTypePointer StorageBuffer(12) + emit(59, {kPtrStruct, kVarBuf, 12u}); // OpVariable StorageBuffer + emit(32, {kPtrU32, 12u, kU32}); // OpTypePointer StorageBuffer u32 + emit(43, {kU32, kConst0, 0u}); // OpConstant 0 + emit(43, {kU32, kConst1, 1u}); // OpConstant 1 + emit(50, {kU32, kSpec0, 0xFFFFFFFFu}); // OpSpecConstant 0xFFFFFFFF + emit(50, {kU32, kSpec1, 0xFFFFFFFFu}); // OpSpecConstant 0xFFFFFFFF + + // Function main() + emit(54, {kVoid, kMain, 0u, kFnType}); + emit(248, {kEntryLabel}); + emit(65, {kPtrU32, kPtr0, kVarBuf, kConst0, kConst0}); // &out_buf.vals[0] + emit(62, {kPtr0, kSpec0}); + emit(65, {kPtrU32, kPtr1, kVarBuf, kConst0, kConst1}); // &out_buf.vals[1] + emit(62, {kPtr1, kSpec1}); + emit(253, {}); // OpReturn + emit(56, {}); // OpFunctionEnd + return w; +} + +void test_gpu_live() { + vktest::Device dev; + dev.request_buffer_device_address = true; + const auto status = dev.initialize(); + if (status == vktest::DeviceStatus::unavailable) { + std::puts("SKIP: no Vulkan device for live Round 3B GPU test"); + return; + } + CHECK(status == vktest::DeviceStatus::ready); + if (status != vktest::DeviceStatus::ready) return; + + std::printf("r3b GPU: vulkanMemoryModel=%d vulkanMemoryModelDeviceScope=%d bindless=%d\n", + int(dev.vulkan_memory_model), int(dev.vulkan_memory_model_device_scope), int(dev.bindless)); + + const auto vkCreateShaderModule = dev.fn("vkCreateShaderModule"); + const auto vkDestroyShaderModule = dev.fn("vkDestroyShaderModule"); + const auto vkCreateDescriptorSetLayout = dev.fn("vkCreateDescriptorSetLayout"); + const auto vkDestroyDescriptorSetLayout = dev.fn("vkDestroyDescriptorSetLayout"); + const auto vkCreateDescriptorPool = dev.fn("vkCreateDescriptorPool"); + const auto vkDestroyDescriptorPool = dev.fn("vkDestroyDescriptorPool"); + const auto vkAllocateDescriptorSets = dev.fn("vkAllocateDescriptorSets"); + const auto vkUpdateDescriptorSets = dev.fn("vkUpdateDescriptorSets"); + const auto vkCreatePipelineLayout = dev.fn("vkCreatePipelineLayout"); + const auto vkDestroyPipelineLayout = dev.fn("vkDestroyPipelineLayout"); + const auto vkCreateComputePipelines = dev.fn("vkCreateComputePipelines"); + const auto vkDestroyPipeline = dev.fn("vkDestroyPipeline"); + const auto vkCreateSampler = dev.fn("vkCreateSampler"); + const auto vkDestroySampler = dev.fn("vkDestroySampler"); + + // 1. Bind a real sampler into BindlessSet (when bindless is supported) to get a live non-zero sampler index. + std::uint32_t expected_sampler_index = 7u; + VkSampler test_sampler = VK_NULL_HANDLE; + std::unique_ptr bindless; + if (dev.bindless) { + VkPhysicalDeviceMemoryProperties mem_props{}; + dev.instance_fn("vkGetPhysicalDeviceMemoryProperties")(dev.physical, + &mem_props); + leonida::BindlessFeatures bf{}; + bf.update_after_bind = true; + bf.partially_bound = dev.partially_bound; + bindless = std::make_unique(dev.device_proc, dev.device, mem_props, bf); + CHECK(bindless->ok()); + VkSamplerCreateInfo sci{VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO}; + sci.magFilter = sci.minFilter = VK_FILTER_LINEAR; + sci.addressModeU = sci.addressModeV = sci.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; + CHECK(vkCreateSampler(dev.device, &sci, nullptr, &test_sampler) == VK_SUCCESS); + expected_sampler_index = bindless->add_sampler(test_sampler); + CHECK(expected_sampler_index != 0 && expected_sampler_index != leonida::LiteralSamplerSpec::kFallbackIndex); + } + + // 2. Output SSBO + descriptor set. + void* mapped = nullptr; + const VkBuffer out_buf = dev.buffer(256, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &mapped); + CHECK(out_buf != VK_NULL_HANDLE && mapped != nullptr); + if (!out_buf || !mapped) return; + std::memset(mapped, 0xCC, 256); + + const VkDescriptorSetLayoutBinding b0{0, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; + VkDescriptorSetLayoutCreateInfo dsl_ci{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; + dsl_ci.bindingCount = 1; + dsl_ci.pBindings = &b0; + VkDescriptorSetLayout dsl = VK_NULL_HANDLE; + CHECK(vkCreateDescriptorSetLayout(dev.device, &dsl_ci, nullptr, &dsl) == VK_SUCCESS); + + const VkDescriptorPoolSize pool_sz{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}; + VkDescriptorPoolCreateInfo dp_ci{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; + dp_ci.maxSets = 1; + dp_ci.poolSizeCount = 1; + dp_ci.pPoolSizes = &pool_sz; + VkDescriptorPool dp = VK_NULL_HANDLE; + CHECK(vkCreateDescriptorPool(dev.device, &dp_ci, nullptr, &dp) == VK_SUCCESS); + + VkDescriptorSetAllocateInfo ds_ai{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; + ds_ai.descriptorPool = dp; + ds_ai.descriptorSetCount = 1; + ds_ai.pSetLayouts = &dsl; + VkDescriptorSet ds = VK_NULL_HANDLE; + CHECK(vkAllocateDescriptorSets(dev.device, &ds_ai, &ds) == VK_SUCCESS); + + const VkDescriptorBufferInfo dbi{out_buf, 0, 256}; + VkWriteDescriptorSet wds{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET}; + wds.dstSet = ds; + wds.dstBinding = 0; + wds.descriptorCount = 1; + wds.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + wds.pBufferInfo = &dbi; + vkUpdateDescriptorSets(dev.device, 1, &wds, 0, nullptr); + + const VkPushConstantRange pcr{VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(leonida::ShaderUserData)}; + VkPipelineLayoutCreateInfo pl_ci{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; + pl_ci.setLayoutCount = 1; + pl_ci.pSetLayouts = &dsl; + pl_ci.pushConstantRangeCount = 1; + pl_ci.pPushConstantRanges = &pcr; + VkPipelineLayout layout = VK_NULL_HANDLE; + CHECK(vkCreatePipelineLayout(dev.device, &pl_ci, nullptr, &layout) == VK_SUCCESS); + + // 3. Build SPIR-V module (with VulkanMemoryModel + VulkanMemoryModelDeviceScope when supported) and + // specialize SpecId 100 -> expected_sampler_index, SpecId 101 -> 0xFFFFFFFF fallback via LiteralSamplerSpec. + const bool use_vmm = dev.vulkan_memory_model && dev.vulkan_memory_model_device_scope; + const auto spv = build_spec_test_spirv(use_vmm); + VkShaderModuleCreateInfo sm_ci{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + sm_ci.codeSize = spv.size() * sizeof(std::uint32_t); + sm_ci.pCode = spv.data(); + VkShaderModule mod = VK_NULL_HANDLE; + CHECK(vkCreateShaderModule(dev.device, &sm_ci, nullptr, &mod) == VK_SUCCESS); + + VkPipeline pipe = VK_NULL_HANDLE; + { + leonida::LiteralSamplerSpec spec; + const std::uint32_t spec_vals[2] = {expected_sampler_index, leonida::LiteralSamplerSpec::kFallbackIndex}; + spec.build(100u, spec_vals); + CHECK(spec.active()); + VkComputePipelineCreateInfo cp_ci{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; + cp_ci.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, nullptr, 0, VK_SHADER_STAGE_COMPUTE_BIT, + mod, "main", spec.ptr()}; + cp_ci.layout = layout; + CHECK(vkCreateComputePipelines(dev.device, VK_NULL_HANDLE, 1, &cp_ci, nullptr, &pipe) == VK_SUCCESS); + } // spec destroyed here: pipeline creation must have copied all specialization data + vkDestroyShaderModule(dev.device, mod, nullptr); + + // 4. Execute through VulkanContext + VulkanQueue and verify on_buffer_write_submitted + GPU output. + leonida::VulkanContext ctx(dev.device_proc, dev.device, true, dev.conditional_rendering, + dev.buffer_device_address); + CHECK(ctx.loaded()); + std::vector write_tickets; + ctx.set_on_buffer_write_submitted([&](std::uint64_t ticket) { write_tickets.push_back(ticket); }); + + leonida::ComputePipeline p_ro{}; + p_ro.pipeline = pipe; + p_ro.layout = layout; + p_ro.bindless_set = ds; + p_ro.reads_glc_buffer = true; + p_ro.writes_buffer = false; + ctx.add_pipeline(1001, p_ro); + + leonida::ComputePipeline p_rw = p_ro; + p_rw.writes_buffer = true; + ctx.add_pipeline(1002, p_rw); + + leonida::VulkanQueue queue(ctx, dev.queue, dev.family, leonida::VulkanQueue::QueueKind::direct); + CHECK(queue.ok()); + + // Submission 1: writes_buffer=false -> on_buffer_write_submitted must NOT fire. + { + leonida::CommandList list; + leonida::Dispatch d{}; + d.pipeline = 1001; + d.x = d.y = d.z = 1; + CHECK(list.dispatch(d) && list.close()); + const leonida::CommandList* lists[1] = {&list}; + CHECK(queue.execute(lists) == leonida::ReplayResult::success); + CHECK(write_tickets.empty()); + } + + // Submission 2: writes_buffer=true, reads_glc_buffer=true -> on_buffer_write_submitted MUST fire with ticket > 0. + { + leonida::CommandList list; + leonida::Dispatch d{}; + d.pipeline = 1002; + d.x = d.y = d.z = 1; + CHECK(list.dispatch(d) && list.close()); + const leonida::CommandList* lists[1] = {&list}; + CHECK(queue.execute(lists) == leonida::ReplayResult::success); + CHECK(write_tickets.size() == 1 && write_tickets[0] > 0); + } + + CHECK(queue.idle()); + + const auto* out_words = static_cast(mapped); + CHECK(out_words[0] == expected_sampler_index); + CHECK(out_words[1] == leonida::LiteralSamplerSpec::kFallbackIndex); + + vkDestroyPipeline(dev.device, pipe, nullptr); + vkDestroyPipelineLayout(dev.device, layout, nullptr); + vkDestroyDescriptorPool(dev.device, dp, nullptr); + vkDestroyDescriptorSetLayout(dev.device, dsl, nullptr); + bindless.reset(); + if (test_sampler) vkDestroySampler(dev.device, test_sampler, nullptr); + CHECK(dev.validation_errors() == 0); +} + +// --------------------------------------------------------------------------------------------------------------- +// Part 4: PassiveWriteBackTracker (overlapping dual-queue seq pruning + split/non-snowballing) & TitleMirror::range_sum +// bit-for-bit parity with mirror_range_sum_bytes() (CPU-only) + +void test_passive_write_back_tracker() { + using leonida::PassiveWriteBackTracker; + using Range = std::pair; + + const auto collect_promote = [](PassiveWriteBackTracker& tr, std::uint64_t id) { + std::vector out; + tr.promote(id, [&](std::uint64_t b, std::uint64_t e) { out.emplace_back(b, e); }); + return out; + }; + + // 4a. Single queue: promote clears everything immediately. + { + PassiveWriteBackTracker tr; + const std::uint64_t id1 = tr.begin_execute(); + tr.note(0x1000, 0x3000); + const auto p1 = collect_promote(tr, id1); + CHECK(p1.size() == 1 && p1[0] == Range(0x1000, 0x3000)); + CHECK(tr.empty() && tr.bytes() == 0); + tr.end_execute(id1); + } + + // 4b. Read-only submission followed by writes_buffer submission: ranges survive end_execute until promoted. + { + PassiveWriteBackTracker tr; + const std::uint64_t ro = tr.begin_execute(); + tr.note(0x1000, 0x2000); + tr.end_execute(ro); // did not write buffers -> NOT promoted + CHECK(!tr.empty() && tr.bytes() == 0x1000); + + const std::uint64_t rw = tr.begin_execute(); + tr.note(0x4000, 0x6000); + const auto p = collect_promote(tr, rw); + CHECK(p.size() == 2 && p[0] == Range(0x1000, 0x2000) && p[1] == Range(0x4000, 0x6000)); + CHECK(tr.empty() && tr.bytes() == 0); + tr.end_execute(rw); + } + + // 4c. Continuous overlapping dual-queue (direct + compute) over 100 submissions: + // Stale ranges from submission k MUST be evicted on k's promote (never re-promoted on k+2..99!), + // while concurrent newly noted ranges from submission k+1 MUST NOT be lost! + { + PassiveWriteBackTracker tr; + constexpr std::uint64_t kRangeSize = 0x10000; // 64 KiB each + constexpr std::uint64_t kBase = 0x10000000; + std::uint64_t prev_id = tr.begin_execute(); + tr.note(kBase, kBase + kRangeSize); // sub 0 + + std::uint64_t total_promoted_bytes = 0; + for (std::size_t step = 1; step < 100; ++step) { + const std::uint64_t next_id = tr.begin_execute(); + const std::uint64_t next_addr = kBase + step * 2 * kRangeSize; + tr.note(next_addr, next_addr + kRangeSize); // concurrent submission notes its own range + + // Previous submission promotes while `next_id` is STILL in flight: + const auto promoted = collect_promote(tr, prev_id); + tr.end_execute(prev_id); + + // Must have promoted only ranges relevant to prev_id (never accumulating ranges from steps <= step - 2!). + CHECK(promoted.size() <= (step == 2 ? 3u : 2u)); + for (const auto& [b, e] : promoted) total_promoted_bytes += (e - b); + // At step == 1 both R0 and R1 are held for next_id (2); for step >= 2 only next_id's freshly noted range remains! + const std::size_t expected_left = (step == 1) ? 2u : 1u; + CHECK(tr.size() == expected_left && tr.bytes() == expected_left * kRangeSize); + prev_id = next_id; + } + // Final submission promotes its own range and clears completely. + const auto last = collect_promote(tr, prev_id); + tr.end_execute(prev_id); + CHECK(last.size() == 1 && last[0] == Range(kBase + 99 * 2 * kRangeSize, kBase + 99 * 2 * kRangeSize + kRangeSize)); + CHECK(tr.empty() && tr.bytes() == 0); + // Without retire_id pruning, 100 overlapping submits re-promote ~5050 * 64 KiB; with retire_id each range is + // promoted at most twice (exactly 200 * 64 KiB across 100 overlapping dual-queue steps). + CHECK(total_promoted_bytes == 199 * kRangeSize); + } + + // 4d. Pre-existing note(R) + concurrent begin(B) -> begin(A) -> promote(A) -> promote(B): + // BOTH A and B MUST emit R so B's later GPU write is never dropped, a newer queue C started after A's promote + // MUST NOT re-promote R, and R MUST be erased immediately after B promotes! + { + PassiveWriteBackTracker tr; + tr.note(0x10000, 0x20000); // pre-existing R + const std::uint64_t id_b = tr.begin_execute(); // B starts (id 1) + const std::uint64_t id_a = tr.begin_execute(); // A starts (id 2) + // A promotes first while B is still in flight: A emits R and stamps R.retire_id = id_b (1). + const auto pa = collect_promote(tr, id_a); + tr.end_execute(id_a); + CHECK(pa.size() == 1 && pa[0] == Range(0x10000, 0x20000)); + CHECK(tr.size() == 1 && tr.bytes() == 0x10000); // still held for B + + // A third queue C starts AFTER A's promote (id 3 > retire_id 1): C must NOT re-promote R! + const std::uint64_t id_c = tr.begin_execute(); + const auto pc = collect_promote(tr, id_c); + CHECK(pc.empty()); + CHECK(tr.size() == 1); // still held for B + + // Now B promotes: B MUST emit R (id_b <= retire_id), and R is immediately erased because min_other (3) > 1! + const auto pb = collect_promote(tr, id_b); + tr.end_execute(id_b); + CHECK(pb.size() == 1 && pb[0] == Range(0x10000, 0x20000)); + CHECK(tr.empty() && tr.bytes() == 0); + tr.end_execute(id_c); + } + + // 4e. Read-only overlapping queue ending without promote still prunes already-promoted entries on end_execute(), + // while preserving freshly noted unpromoted entries. + { + PassiveWriteBackTracker tr; + tr.note(0x10000, 0x20000); // R_old + const std::uint64_t ro = tr.begin_execute(); // read-only queue (id 1) + const std::uint64_t rw = tr.begin_execute(); // writes_buffer queue (id 2) + const auto p_rw = collect_promote(tr, rw); + tr.end_execute(rw); + CHECK(p_rw.size() == 1 && p_rw[0] == Range(0x10000, 0x20000)); + CHECK(tr.size() == 1); // retained until ro ends + + // ro notes a new range R_new (retire_id = 0) and finishes without promoting: R_old MUST be pruned on + // end_execute(ro), while unpromoted R_new MUST survive for a future writes_buffer submission! + tr.note(0x30000, 0x34000); + tr.end_execute(ro); + CHECK(tr.size() == 1 && tr.bytes() == 0x4000); + const auto p_later = collect_promote(tr, 0); + CHECK(p_later.size() == 1 && p_later[0] == Range(0x30000, 0x34000)); + CHECK(tr.empty()); + } + + // 4f. Partial overlap split + adjacent non-snowballing across retire watermarks: + { + PassiveWriteBackTracker tr; + tr.note(0x10000, 0x20000); // old 64 KiB range (retire_id = 0) + const std::uint64_t id_a = tr.begin_execute(); // id 1 + const std::uint64_t id_b = tr.begin_execute(); // id 2 + // Queue A promotes first: stamps [0x10000, 0x20000) with retire_id = id_b (2). + const auto pa = collect_promote(tr, id_a); + tr.end_execute(id_a); + CHECK(pa.size() == 1 && pa[0] == Range(0x10000, 0x20000)); + + // Queue C starts (id 3 > 2), notes a 4 KiB sub-range inside [0x10000, 0x20000) AND an adjacent 4 KiB range: + // left [0x10000, 0x14000) and right [0x15000, 0x20000) keep retire_id = 2, while new ranges get retire_id = 0! + const std::uint64_t id_c = tr.begin_execute(); + tr.note(0x14000, 0x15000); + tr.note(0x20000, 0x21000); + // Queue C promotes: MUST emit ONLY the 8 KiB new ranges (NOT the old 60 KiB with retire_id = 2 < 3)! + const auto pc = collect_promote(tr, id_c); + tr.end_execute(id_c); + CHECK(pc.size() == 2 && pc[0] == Range(0x14000, 0x15000) && pc[1] == Range(0x20000, 0x21000)); + + // Queue B promotes last (id 2): emits everything still relevant to B and clears ALL! + const auto pb = collect_promote(tr, id_b); + tr.end_execute(id_b); + CHECK(pb.size() == 4); + CHECK(tr.empty() && tr.bytes() == 0); + } + + // 4g. FIFO cap eviction evicts strictly oldest seq first. + { + PassiveWriteBackTracker tr(4, 0x4000); // max 4 ranges, 16 KiB + tr.note(0x1000, 0x2000); // seq 1 (4 KiB) + tr.note(0x3000, 0x4000); // seq 2 (4 KiB) + tr.note(0x5000, 0x6000); // seq 3 (4 KiB) + tr.note(0x7000, 0x8000); // seq 4 (4 KiB) + tr.note(0x9000, 0xB000); // seq 5 (8 KiB) -> evicts seq 1 and seq 2 + CHECK(tr.size() == 3 && tr.bytes() == 0x4000); + const auto p = collect_promote(tr, 0); + CHECK(p.size() == 3 && p[0] == Range(0x5000, 0x6000) && p[1] == Range(0x7000, 0x8000) && + p[2] == Range(0x9000, 0xB000)); + } +} + +void test_mirror_range_sum_parity() { + constexpr std::uint64_t kPage = leonida::TitleMirror::kPage; + std::vector unit_mem(leonida::TitleMirror::kUnitBytes, 0); + std::vector page0(kPage), page1(kPage); + for (std::size_t i = 0; i < kPage; ++i) { + page0[i] = static_cast((i * 29u + 3u) & 0xffu); + page1[i] = static_cast((i * 53u + 17u) & 0xffu); + } + leonida::TitleMirrorHooks hooks{}; + hooks.make_chunk = [](std::uint64_t, std::uint64_t, VkBuffer& out) { + out = fake_handle(0x500); + return true; + }; + hooks.make_unit = [&](VkDeviceMemory& out, std::uint8_t*& host) { + out = fake_handle(0x600); + host = unit_mem.data(); + return true; + }; + hooks.bind = [](const std::vector&, std::uint64_t) { return true; }; + + leonida::TitleMirror mirror(std::move(hooks)); + constexpr std::uint64_t kBase = 0x10000000; + CHECK(mirror.cover(kBase, kBase + 2 * kPage)); + mirror.map(kBase, page0.data(), nullptr); + mirror.map(kBase + kPage, page1.data(), nullptr); + + std::vector contiguous(2 * kPage); + std::memcpy(contiguous.data(), page0.data(), kPage); + std::memcpy(contiguous.data() + kPage, page1.data(), kPage); + + // Verify exact bit-for-bit equality between TitleMirror::range_sum() and mirror_range_sum_bytes() across + // sub-page, full-page, and cross-page 256B-aligned ranges! + const std::pair cases[] = { + {0, 256}, + {256, 4096}, + {0x4000, 0x8000}, + {0, kPage}, + {kPage - 0x2000, 0x12000}, // crosses tile 0 -> tile 1 + {0, 2 * kPage}, + }; + for (const auto& [off, len] : cases) { + std::uint64_t mirror_h = 0; + CHECK(mirror.range_sum(kBase + off, len, mirror_h)); + const std::uint64_t cpu_h = leonida::mirror_range_sum_bytes(contiguous.data() + off, len); + CHECK(mirror_h != 0 && mirror_h == cpu_h); + } +} + +} // namespace + +int main() { + test_literal_sampler_spec(); + test_replay_hooks(); + test_gpu_live(); + test_passive_write_back_tracker(); + test_mirror_range_sum_parity(); + if (failures) { + std::fprintf(stderr, "r3b_runtime_hooks_test: %d failure(s)\n", failures); + return 1; + } + std::puts("r3b_runtime_hooks_test: OK"); + return 0; +} diff --git a/runtime/test/replay_quad_list_test.cpp b/runtime/test/replay_quad_list_test.cpp index 0557a3e577..d571d96a50 100644 --- a/runtime/test/replay_quad_list_test.cpp +++ b/runtime/test/replay_quad_list_test.cpp @@ -5,14 +5,18 @@ // then one draw over that scratch. The dispatch runs before the draw's rendering scope and outside a // pipeline-statistics query, reads no index past the view, and a draw with more quads than one dispatch may // cover is split into several. +// - With LEONIDA_DEVICE_MARKERS' breadcrumbs, the draw's marker pair encloses the expansion and the draw. // No GPU: the Vulkan calls are recorded. #include "../src/vulkan_replay.h" +#include +#include #include #include #include #include #include +#include #include namespace { @@ -402,5 +406,45 @@ int main() { "begin_rendering", "bind_graphics", "draw_indexed", "end_rendering", "end_query 5"}; ok &= check(events == want, "the dispatch runs between the query's two segments, the draw in the second"); } + + // LEONIDA_DEVICE_MARKERS=1 (vulkan_device_markers.h): the draw's started marker comes before its index expansion + // and rendering scope, its finished marker after the scope, and the history entry says what the draw was. + { + reset(); + CommandList list; + ok &= check(list.draw(draw) && list.close(), "record a quad draw for the markers"); + PreparedList prepared; + ok &= check(prepare(list, resolve, vk, prepared) == ReplayResult::success, "prepare the marked draw"); + std::atomic seq{41}; + CheckpointSubmission submission; + submission.execute_call = 3; + submission.queue_kind = "direct"; + submission.lists.resize(1); + submission.dispatch_seq = &seq; + submission.markers = {nullptr, + +[](VkCommandBuffer, VkPipelineStageFlags2 stage, VkBuffer, VkDeviceSize, std::uint32_t m) { + events.push_back( + (stage == VK_PIPELINE_STAGE_2_TOP_OF_PIPE_BIT ? "started " : "finished ") + + std::to_string(m)); + }, + handle(30), 0}; + const std::unordered_map names{ + {1, {"library/vs_quad", nullptr, "library/ps_quad"}}}; + const CheckpointRecorder recorder{nullptr, submission, names, 0}; + emit_commands(prepared, VK_NULL_HANDLE, vk, nullptr, nullptr, &recorder); + std::vector want{"started 42"}; + want.insert(want.end(), one_dispatch_one_draw.begin(), one_dispatch_one_draw.end()); + want.push_back("finished 42"); + ok &= check(events == want, "a draw's markers enclose its index expansion and its rendering scope"); + ok &= check(submission.marked.size() == 1 && submission.marked[0].is_draw() && + submission.marked[0].draw_flags == (marked_draw::indexed | marked_draw::quads) && + submission.marked[0].counts == std::array{8, 2, 0} && + submission.marked[0].pass_draw == 1 && submission.marked[0].seq == 42, + "the marked draw is an indexed quad list of 8 indices and 2 instances"); + ok &= check(describe_marked(submission.marked[0]).find( + "draw=indexed-quads count=8 instances=2 pipeline=vs vs_quad ps ps_quad pass=draw 1 since " + "command 0 (0 colours, 0x0)") != std::string::npos, + "the report line names the draw and its pipeline"); + } return ok ? 0 : 1; } diff --git a/runtime/test/replay_state_cache_test.cpp b/runtime/test/replay_state_cache_test.cpp new file mode 100644 index 0000000000..ceeaf61243 --- /dev/null +++ b/runtime/test/replay_state_cache_test.cpp @@ -0,0 +1,2428 @@ +// Stage 5b Replay State Cache test (runtime/src/vulkan_replay.h, runtime/src/vulkan_backend.h): +// 1. CPU mock correctness: verifies redundant bind/push/dynamic-state elision across repeated draws & dispatches, +// minimal dirty [lo, hi] 4-byte push-constant sub-range updates, full re-push on layout/stage switch and +// graphics<->compute interleaving, dynamic state disturbance on mesh / !depth_bounds / !vertex_slots / +// viewport_with_count pipeline transitions, cross-list caching on a shared ReplayStateCache, and compute+push +// cache invalidation across every internal helper pass (capture_predicate, emit_indirect_clamp, +// emit_quad_indices, emit_counted_dispatch, emit_predicated_copy, depth24_run, resolve_binary_occlusion, +// sum_occlusion, sum_statistics, xdxr_record). +// 2. Throughput benchmark: replays 5,000 draws in a tight loop and verifies < 1.0 us/draw. +// 3. Live Vulkan validation test (when a GPU is present; run with LEONIDA_VK_VALIDATION=1): runs real graphics +// draws (with dynamic viewport/scissor/topology/restart/stencil/blend/vertex/index), partial push-constant +// updates, interleaved compute dispatches, and a clear pass through VulkanContext + VulkanQueue, reading back +// both the color target and SSBO to verify bit-exact GPU execution with zero validation errors. +// No game data. + +#ifndef VK_NO_PROTOTYPES +#define VK_NO_PROTOTYPES +#endif + +#include "../src/vulkan_backend.h" +#include "../src/vulkan_bindless.h" +#include "../src/vulkan_replay.h" +#include "vk_test_device.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using namespace leonida; + +int g_failures = 0; + +void check_impl(bool ok, const char* expr, int line) { + if (ok) return; + std::fprintf(stderr, "FAIL (line %d): %s\n", line, expr); + ++g_failures; +} + +#define CHECK(expr) check_impl((expr), #expr, __LINE__) + +template +H fake_handle(std::uintptr_t v) { + return reinterpret_cast(v); +} + +std::uint32_t float_bits(float f) { + std::uint32_t u = 0; + std::memcpy(&u, &f, sizeof(u)); + return u; +} + +// --------------------------------------------------------------------------------------------------------------- +// Part 1: CPU mock correctness & invalidation coverage + +struct PushCall { + VkPipelineLayout layout = VK_NULL_HANDLE; + VkShaderStageFlags stages = 0; + std::uint32_t offset = 0; + std::uint32_t size = 0; + std::array words{}; +}; + +struct MockCounts { + std::size_t bind_gfx = 0; + std::size_t bind_comp = 0; + std::size_t desc_gfx = 0; + std::size_t desc_comp = 0; + std::size_t push = 0; + std::size_t viewport = 0; + std::size_t scissor = 0; + std::size_t viewport_count = 0; + std::size_t scissor_count = 0; + std::size_t topology = 0; + std::size_t restart = 0; + std::size_t stencil_front = 0; + std::size_t stencil_back = 0; + std::size_t blend = 0; + std::size_t depth_bounds = 0; + std::size_t vertex = 0; + std::size_t index = 0; + std::size_t index_robust = 0; + std::size_t draws = 0; + std::size_t dispatches = 0; + std::size_t begin_rendering = 0; + std::size_t end_rendering = 0; + std::size_t barriers = 0; + std::vector pushes; + + void reset() { *this = MockCounts{}; } +}; + +MockCounts g_mc; + +void VKAPI_PTR mc_bind_pipeline(VkCommandBuffer, VkPipelineBindPoint bp, VkPipeline) { + if (bp == VK_PIPELINE_BIND_POINT_GRAPHICS) ++g_mc.bind_gfx; + else ++g_mc.bind_comp; +} +void VKAPI_PTR mc_bind_desc(VkCommandBuffer, VkPipelineBindPoint bp, VkPipelineLayout, std::uint32_t, std::uint32_t, + const VkDescriptorSet*, std::uint32_t, const std::uint32_t*) { + if (bp == VK_PIPELINE_BIND_POINT_GRAPHICS) ++g_mc.desc_gfx; + else ++g_mc.desc_comp; +} +void VKAPI_PTR mc_push(VkCommandBuffer, VkPipelineLayout layout, VkShaderStageFlags stages, std::uint32_t offset, + std::uint32_t size, const void* values) { + ++g_mc.push; + PushCall call{}; + call.layout = layout; + call.stages = stages; + call.offset = offset; + call.size = size; + if (values && offset + size <= sizeof(ShaderUserData) && (offset % 4 == 0) && (size % 4 == 0)) + std::memcpy(call.words.data() + offset / 4, values, size); + g_mc.pushes.push_back(call); +} +void VKAPI_PTR mc_viewport(VkCommandBuffer, std::uint32_t, std::uint32_t, const VkViewport*) { ++g_mc.viewport; } +void VKAPI_PTR mc_scissor(VkCommandBuffer, std::uint32_t, std::uint32_t, const VkRect2D*) { ++g_mc.scissor; } +void VKAPI_PTR mc_viewport_cnt(VkCommandBuffer, std::uint32_t, const VkViewport*) { ++g_mc.viewport_count; } +void VKAPI_PTR mc_scissor_cnt(VkCommandBuffer, std::uint32_t, const VkRect2D*) { ++g_mc.scissor_count; } +void VKAPI_PTR mc_topology(VkCommandBuffer, VkPrimitiveTopology) { ++g_mc.topology; } +void VKAPI_PTR mc_restart(VkCommandBuffer, VkBool32) { ++g_mc.restart; } +void VKAPI_PTR mc_stencil(VkCommandBuffer, VkStencilFaceFlags face, std::uint32_t) { + if (face & VK_STENCIL_FACE_FRONT_BIT) ++g_mc.stencil_front; + if (face & VK_STENCIL_FACE_BACK_BIT) ++g_mc.stencil_back; +} +void VKAPI_PTR mc_blend(VkCommandBuffer, const float*) { ++g_mc.blend; } +void VKAPI_PTR mc_depth_bounds(VkCommandBuffer, float, float) { ++g_mc.depth_bounds; } +void VKAPI_PTR mc_vertex(VkCommandBuffer, std::uint32_t, std::uint32_t, const VkBuffer*, const VkDeviceSize*, + const VkDeviceSize*, const VkDeviceSize*) { + ++g_mc.vertex; +} +void VKAPI_PTR mc_index(VkCommandBuffer, VkBuffer, VkDeviceSize, VkIndexType) { ++g_mc.index; } +void VKAPI_PTR mc_index_robust(VkCommandBuffer, VkBuffer, VkDeviceSize, VkDeviceSize, VkIndexType) { + ++g_mc.index_robust; +} +void VKAPI_PTR mc_draw(VkCommandBuffer, std::uint32_t, std::uint32_t, std::uint32_t, std::uint32_t) { ++g_mc.draws; } +void VKAPI_PTR mc_draw_indexed(VkCommandBuffer, std::uint32_t, std::uint32_t, std::uint32_t, std::int32_t, + std::uint32_t) { + ++g_mc.draws; +} +void VKAPI_PTR mc_draw_mesh(VkCommandBuffer, std::uint32_t, std::uint32_t, std::uint32_t) { ++g_mc.draws; } +void VKAPI_PTR mc_draw_indirect(VkCommandBuffer, VkBuffer, VkDeviceSize, std::uint32_t, std::uint32_t) { ++g_mc.draws; } +void VKAPI_PTR mc_dispatch(VkCommandBuffer, std::uint32_t, std::uint32_t, std::uint32_t) { ++g_mc.dispatches; } +void VKAPI_PTR mc_dispatch_indirect(VkCommandBuffer, VkBuffer, VkDeviceSize) { ++g_mc.dispatches; } + +struct MockEnv { + static constexpr ResourceId kColor = 1; + static constexpr ResourceId kBuf = 2; + static constexpr ResourceId kPred = 3; + static constexpr ResourceId kTexD24 = 4; + static constexpr ResourceId kResults = 5; + static constexpr QueryHeapId kOccHeap = 10; + static constexpr std::uint64_t kGeomVa = 0x100000000ull; + + std::map res; + std::map gfx; + std::map comp; + QueryPool occ_pool{}; + ReplayFunctions vk{}; + + MockEnv() { + ResourceBinding color{}; + color.image = fake_handle(0x100); + color.format = VK_FORMAT_R8G8B8A8_UNORM; + color.aspects = VK_IMAGE_ASPECT_COLOR_BIT; + color.width = color.height = 64; + color.color_attachment = true; + res[kColor] = color; + + ResourceBinding buf{}; + buf.buffer = fake_handle(0x200); + buf.size = 1 << 20; + buf.indirect_arguments = true; + res[kBuf] = buf; + + ResourceBinding pred{}; + pred.buffer = fake_handle(0x201); + pred.size = 4096; + res[kPred] = pred; + + ResourceBinding d24{}; + d24.image = fake_handle(0x101); + d24.format = VK_FORMAT_D32_SFLOAT_S8_UINT; + d24.aspects = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; + d24.width = d24.height = 16; + d24.depth24_as_float = true; + d24.depth24 = true; + res[kTexD24] = d24; + + ResourceBinding results{}; + results.buffer = fake_handle(0x202); + results.size = 4096; + res[kResults] = results; + + occ_pool = {fake_handle(0x300), d3d12_query_heap::occlusion, 16, true, + std::vector(16, false)}; + + const auto gfx_layout = fake_handle(0x500); + const auto comp_layout = fake_handle(0x501); + const auto bindless = fake_handle(0x600); + + GraphicsPipeline g1{}; + g1.pipeline = fake_handle(0x700); + g1.layout = gfx_layout; + g1.push_stages = VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT; + g1.bindless_set = bindless; + g1.color_formats = {VK_FORMAT_R8G8B8A8_UNORM}; + g1.vertex_slots = 0b1; + g1.depth_bounds = true; + gfx[1] = g1; + + GraphicsPipeline g2 = g1; + g2.pipeline = fake_handle(0x701); + g2.depth_bounds = false; // disturbs depth_bounds when bound + gfx[2] = g2; + + GraphicsPipeline g_vp_cnt = g1; + g_vp_cnt.pipeline = fake_handle(0x702); + g_vp_cnt.viewport_with_count = true; // disturbs fixed viewport/scissor + gfx[3] = g_vp_cnt; + + GraphicsPipeline g_mesh = g1; + g_mesh.pipeline = fake_handle(0x703); + g_mesh.mesh = true; + g_mesh.vertex_slots = 0; + g_mesh.push_stages = VK_SHADER_STAGE_MESH_BIT_EXT | VK_SHADER_STAGE_FRAGMENT_BIT; + gfx[4] = g_mesh; + + ComputePipeline c1{}; + c1.pipeline = fake_handle(0x800); + c1.layout = comp_layout; + c1.bindless_set = bindless; + comp[1] = c1; + + ComputePipeline c2 = c1; + c2.pipeline = fake_handle(0x801); + comp[2] = c2; + + vk.heap_base = 0x10000000ull; + vk.pipeline_barrier = +[](VkCommandBuffer, VkPipelineStageFlags, VkPipelineStageFlags, VkDependencyFlags, + std::uint32_t, const VkMemoryBarrier*, std::uint32_t, const VkBufferMemoryBarrier*, + std::uint32_t, const VkImageMemoryBarrier*) { ++g_mc.barriers; }; + vk.clear_color_image = +[](VkCommandBuffer, VkImage, VkImageLayout, const VkClearColorValue*, std::uint32_t, + const VkImageSubresourceRange*) {}; + vk.begin_rendering = +[](VkCommandBuffer, const VkRenderingInfo*) { ++g_mc.begin_rendering; }; + vk.end_rendering = +[](VkCommandBuffer) { ++g_mc.end_rendering; }; + vk.copy_buffer = +[](VkCommandBuffer, VkBuffer, VkBuffer, std::uint32_t, const VkBufferCopy*) {}; + vk.copy_buffer_to_image = +[](VkCommandBuffer, VkBuffer, VkImage, VkImageLayout, std::uint32_t, + const VkBufferImageCopy*) {}; + vk.copy_image_to_buffer = +[](VkCommandBuffer, VkImage, VkImageLayout, VkBuffer, std::uint32_t, + const VkBufferImageCopy*) {}; + vk.copy_image = +[](VkCommandBuffer, VkImage, VkImageLayout, VkImage, VkImageLayout, std::uint32_t, + const VkImageCopy*) {}; + vk.draw_indirect_first_instance = true; + vk.fill_buffer = +[](VkCommandBuffer, VkBuffer, VkDeviceSize, VkDeviceSize, std::uint32_t) {}; + vk.begin_conditional_rendering = +[](VkCommandBuffer, const VkConditionalRenderingBeginInfoEXT*) {}; + vk.end_conditional_rendering = +[](VkCommandBuffer) {}; + vk.reset_query_pool = +[](VkCommandBuffer, VkQueryPool, std::uint32_t, std::uint32_t) {}; + vk.begin_query = +[](VkCommandBuffer, VkQueryPool, std::uint32_t, VkQueryControlFlags) {}; + vk.end_query = +[](VkCommandBuffer, VkQueryPool, std::uint32_t) {}; + vk.write_timestamp = +[](VkCommandBuffer, VkPipelineStageFlagBits, VkQueryPool, std::uint32_t) {}; + vk.copy_query_pool_results = +[](VkCommandBuffer, VkQueryPool, std::uint32_t, std::uint32_t, VkBuffer, + VkDeviceSize, VkDeviceSize, VkQueryResultFlags) {}; + vk.bind_pipeline = &mc_bind_pipeline; + vk.bind_descriptor_sets = &mc_bind_desc; + vk.push_constants = &mc_push; + vk.set_viewport = &mc_viewport; + vk.set_scissor = &mc_scissor; + vk.set_viewport_with_count = &mc_viewport_cnt; + vk.set_scissor_with_count = &mc_scissor_cnt; + vk.set_primitive_topology = &mc_topology; + vk.set_primitive_restart_enable = &mc_restart; + vk.set_stencil_reference = &mc_stencil; + vk.set_blend_constants = &mc_blend; + vk.set_depth_bounds = &mc_depth_bounds; + vk.bind_vertex_buffers2 = &mc_vertex; + vk.bind_index_buffer = &mc_index; + vk.bind_robust_index_view = &mc_index_robust; + vk.draw = &mc_draw; + vk.draw_indexed = &mc_draw_indexed; + vk.draw_mesh_tasks = &mc_draw_mesh; + vk.draw_indirect = &mc_draw_indirect; + vk.dispatch = &mc_dispatch; + vk.dispatch_indirect = &mc_dispatch_indirect; + vk.zero_buffer = fake_handle(0x210); + vk.zero_size = 65536; + vk.quad_indices = fake_handle(0x211); + vk.quad_index_count = 64; + vk.image_view = [](const ResourceBinding&, const VkImageSubresourceRange&) { + return fake_handle(0x400); + }; + vk.buffer_at = [](std::uint64_t va, std::uint64_t& size, VkBuffer& buffer, VkDeviceSize& offset) { + if (va < kGeomVa || va >= kGeomVa + (16ull << 20)) return false; + buffer = fake_handle(0x220); + offset = va - kGeomVa; + size = (std::min)(size, std::uint64_t(kGeomVa + (16ull << 20) - va)); + return true; + }; + vk.graphics_pipeline = [this](std::uintptr_t id) -> const GraphicsPipeline* { + const auto it = gfx.find(id); + return it == gfx.end() ? nullptr : &it->second; + }; + vk.compute_pipeline = [this](std::uintptr_t id) -> const ComputePipeline* { + const auto it = comp.find(id); + return it == comp.end() ? nullptr : &it->second; + }; + vk.query_pool = [this](QueryHeapId id) -> QueryPool* { return id == kOccHeap ? &occ_pool : nullptr; }; + vk.prepare_predicate = [](VkBuffer src, VkDeviceSize off, PredicateCapture& out) { + out = {src, off, fake_handle(0x230), 0, VK_NULL_HANDLE}; + return true; + }; + vk.capture_predicate = [](VkCommandBuffer, const PredicateCapture&) {}; + vk.resolve_binary_occlusion = [](VkCommandBuffer, VkQueryPool, std::uint32_t, std::uint32_t, VkBuffer, + VkDeviceSize) {}; + vk.copy_scratch = [](VkDeviceSize, VkBuffer& b, VkDeviceSize& off) { + b = fake_handle(0x240); + off = 0; + return true; + }; + vk.prepare_indirect_clamp = [](VkBuffer, VkDeviceSize, VkBuffer, VkDeviceSize, std::uint32_t, + std::uint32_t stride, std::uint32_t max_count, ClampedIndirect& out) { + out.buffer = fake_handle(0x241); + out.offset = 0; + out.records = max_count; + out.stride = stride; + return true; + }; + vk.emit_indirect_clamp = [](VkCommandBuffer, const ClampedIndirect&) {}; + vk.prepare_quad_indices = [](VkBuffer, VkDeviceSize, VkIndexType, std::uint64_t, std::uint32_t quads, + VkBuffer scratch, VkDeviceSize scratch_off, QuadIndexExpansion& out) { + out.buffer = scratch; + out.offset = scratch_off; + out.quads = quads; + return true; + }; + vk.emit_quad_indices = [](VkCommandBuffer, const QuadIndexExpansion&) {}; + vk.depth24_prepare = [](Depth24Job& job, std::vector& parts) { + job.scratch = fake_handle(0x242); + job.scratch_offset = 0; + parts.push_back(job); + return true; + }; + vk.depth24_run = [](VkCommandBuffer, const Depth24Job&) {}; + } + + const ResourceBinding* resolve(ResourceId id) const { + const auto it = res.find(id); + return it == res.end() ? nullptr : &it->second; + } + + Draw base_draw(std::uintptr_t pso = 1, bool indexed = true) const { + Draw d{}; + d.pipeline = pso; + auto views = std::make_shared(); + views->render_targets[0] = {kColor, 0, 0, 1}; + views->render_target_count = 1; + views->vertex_buffers[0] = {kGeomVa, 4096, 16}; + d.views = std::move(views); + if (indexed) d.index = {kGeomVa + 4096, 1024, 57}; // R16_UINT + d.topology = 4; // TRIANGLELIST + d.viewport = {0, 0, 64, 64, 0, 1}; + d.scissor = {0, 0, 64, 64}; + d.blend_factor = {1, 0.5f, 0.25f, 1}; + d.stencil_front = 3; + d.stencil_back = 7; + d.depth_bounds = {0.1f, 0.9f}; + d.indexed = indexed; + d.count = 6; + d.instances = 1; + d.user_data[0] = 0x1111u; + d.user_data[5] = 0x5555u; + return d; + } +}; + +void test_cpu_elision_and_invalidation() { + MockEnv env; + const auto resolve = [&env](ResourceId id) { return env.resolve(id); }; + const VkCommandBuffer cb = fake_handle(0x1); + + // 1a: 5 identical indexed draws -> state emitted ONCE, 4 subsequent draws elide every redundant bind/push/dynamic. + { + CommandList list; + const Draw d = env.base_draw(1, true); + for (int k = 0; k < 5; ++k) CHECK(list.draw(d)); + CHECK(list.close()); + PreparedList prep; + CHECK(prepare(list, resolve, env.vk, prep) == ReplayResult::success); + g_mc.reset(); + emit(prep, cb, env.vk); + CHECK(g_mc.draws == 5); + CHECK(g_mc.begin_rendering == 1 && g_mc.end_rendering == 1); + CHECK(g_mc.barriers == 1); + CHECK(g_mc.bind_gfx == 1); + CHECK(g_mc.desc_gfx == 1); + CHECK(g_mc.push == 1 && g_mc.pushes[0].offset == 0 && g_mc.pushes[0].size == sizeof(ShaderUserData)); + CHECK(g_mc.viewport == 1 && g_mc.scissor == 1); + CHECK(g_mc.topology == 1 && g_mc.restart == 1); + CHECK(g_mc.stencil_front == 1 && g_mc.stencil_back == 1); + CHECK(g_mc.blend == 1 && g_mc.depth_bounds == 1); + CHECK(g_mc.vertex == 1 && g_mc.index == 1); + } + + // 1b: Partial push-constant dirty range [lo, hi] + individual dynamic state mutations always re-emit. + { + CommandList list; + Draw d = env.base_draw(1, true); + CHECK(list.draw(d)); + // Mutate ONLY s[5] -> push [20, 4] + d.user_data[5] = 0x6666u; + CHECK(list.draw(d)); + // Mutate s[2] and s[4] -> minimal contiguous range [8, 12] + d.user_data[2] = 0x2222u; + d.user_data[4] = 0x4444u; + CHECK(list.draw(d)); + // Mutate viewport, scissor, stencil_back only, blend, depth_bounds, index offset, vertex offset + d.viewport.width = 32; + d.scissor.right = 32; + d.stencil_back = 9; + d.blend_factor[2] = 0.75f; + d.depth_bounds[1] = 0.8f; + d.index.va += 256; + auto views2 = std::make_shared(*d.views); + views2->vertex_buffers[0].va += 128; + d.views = views2; + CHECK(list.draw(d)); + CHECK(list.close()); + + PreparedList prep; + CHECK(prepare(list, resolve, env.vk, prep) == ReplayResult::success); + g_mc.reset(); + emit(prep, cb, env.vk); + CHECK(g_mc.draws == 4); + CHECK(g_mc.bind_gfx == 1 && g_mc.desc_gfx == 1); + CHECK(g_mc.push == 3); + CHECK(g_mc.pushes[0].offset == 0 && g_mc.pushes[0].size == 144); + CHECK(g_mc.pushes[1].offset == 20 && g_mc.pushes[1].size == 4 && g_mc.pushes[1].words[5] == 0x6666u); + CHECK(g_mc.pushes[2].offset == 8 && g_mc.pushes[2].size == 12 && g_mc.pushes[2].words[2] == 0x2222u && + g_mc.pushes[2].words[4] == 0x4444u); + CHECK(g_mc.viewport == 2 && g_mc.scissor == 2); + CHECK(g_mc.stencil_front == 1 && g_mc.stencil_back == 2); + CHECK(g_mc.blend == 2 && g_mc.depth_bounds == 2); + CHECK(g_mc.vertex == 2 && g_mc.index == 2); + } + + // 1c: Interleaved graphics <-> compute: push-constant bank is shared so full 144B re-pushes on switch, + // while graphics & compute pipeline/descriptor bindings remain independently cached. + { + CommandList list; + const Draw d = env.base_draw(1, false); + Dispatch c{}; + c.pipeline = 1; + c.x = c.y = c.z = 1; + c.user_data[0] = 0xAAu; + CHECK(list.draw(d)); + CHECK(list.dispatch(c)); + CHECK(list.draw(d)); // identical draw after compute: MUST re-push full 144B, skips gfx bind/desc/dyn + CHECK(list.dispatch(c)); // identical dispatch after gfx: MUST re-push full 144B, skips compute bind/desc + c.user_data[3] = 0xBBu; + CHECK(list.dispatch(c)); // consecutive compute: partial push [12, 4] + CHECK(list.close()); + + PreparedList prep; + CHECK(prepare(list, resolve, env.vk, prep) == ReplayResult::success); + g_mc.reset(); + emit(prep, cb, env.vk); + CHECK(g_mc.draws == 2 && g_mc.dispatches == 3); + CHECK(g_mc.bind_gfx == 1 && g_mc.desc_gfx == 1); + CHECK(g_mc.bind_comp == 1 && g_mc.desc_comp == 1); + CHECK(g_mc.push == 5); + CHECK(g_mc.pushes[0].size == 144 && g_mc.pushes[1].size == 144 && g_mc.pushes[2].size == 144 && + g_mc.pushes[3].size == 144); + CHECK(g_mc.pushes[4].offset == 12 && g_mc.pushes[4].size == 4 && g_mc.pushes[4].words[3] == 0xBBu); + } + + // 1d: Pipeline dynamic-state disturbance: !depth_bounds, viewport_with_count, and mesh pipelines disturb the + // dynamic states they don't declare so the subsequent regular draw re-emits them. + { + CommandList list; + const Draw d1 = env.base_draw(1, false); // depth_bounds=true, fixed vp, vertex slot 0 + const Draw d2 = env.base_draw(2, false); // depth_bounds=false -> disturbs depth_bounds + const Draw d3 = env.base_draw(3, false); // viewport_with_count=true -> disturbs fixed vp/sc + Draw d4 = env.base_draw(4, false); // mesh=true -> disturbs topology, restart, vertex slots + d4.mesh = true; + d4.first = 1; // mesh dispatch group count Z = 1 (non-zero) + CHECK(list.draw(d1)); + CHECK(list.draw(d2)); + CHECK(list.draw(d1)); // must re-emit depth_bounds + CHECK(list.draw(d3)); // switches to with_count + CHECK(list.draw(d1)); // must re-emit fixed viewport/scissor + CHECK(list.draw(d4)); // mesh: disturbs topology, restart, vertex_buffers + CHECK(list.draw(d1)); // must re-emit topology, restart, vertex_buffers + CHECK(list.close()); + + PreparedList prep; + CHECK(prepare(list, resolve, env.vk, prep) == ReplayResult::success); + g_mc.reset(); + emit(prep, cb, env.vk); + CHECK(g_mc.draws == 7); + CHECK(g_mc.depth_bounds == 2); // d1 (#1), d1 (#3 after d2 disturbed depth_bounds) + CHECK(g_mc.viewport == 2 && g_mc.viewport_count == 1); // d1 (#1), d3 (#4 with_count), d1 (#5 after d3) + CHECK(g_mc.topology == 2 && g_mc.restart == 2 && g_mc.vertex == 2); // initial + after mesh disturbed them + } + + // 1e: Helper pass invalidation: capture_predicate, emit_indirect_clamp, emit_quad_indices, depth24_run, and + // resolve_binary_occlusion MUST invalidate compute pipeline, compute desc, and shared push constants! + { + const auto check_helper_invalidates = [&](const char* name, auto&& inject_helper) { + CommandList list; + Dispatch c{}; + c.pipeline = 1; + c.x = c.y = c.z = 1; + c.user_data[0] = 0x77u; + CHECK(list.dispatch(c)); + inject_helper(list); + CHECK(list.dispatch(c)); // identical dispatch after helper MUST re-bind compute, desc, and full push! + CHECK(list.close()); + PreparedList prep; + const ReplayResult pr = prepare(list, resolve, env.vk, prep); + CHECK(pr == ReplayResult::success); + if (pr != ReplayResult::success) return; + QueryReplay qr; + CHECK(qr.plan(prep) == ReplayResult::success); + g_mc.reset(); + emit(prep, cb, env.vk); + const bool ok = g_mc.bind_comp == 2 && g_mc.desc_comp == 2 && g_mc.push >= 2 && + g_mc.pushes.back().offset == 0 && g_mc.pushes.back().size == 144; + if (!ok) { + std::fprintf(stderr, "FAIL helper invalidation (%s): bind_comp=%zu desc_comp=%zu push=%zu last_sz=%u\n", + name, g_mc.bind_comp, g_mc.desc_comp, g_mc.push, + g_mc.pushes.empty() ? 0u : g_mc.pushes.back().size); + ++g_failures; + } + }; + + check_helper_invalidates("capture_predicate", [](CommandList& l) { + CHECK(l.set_predication({MockEnv::kPred, 0, d3d12_predication::equal_zero})); + CHECK(l.set_predication({0, 0, 0})); + }); + check_helper_invalidates("emit_indirect_clamp", [&env](CommandList& l) { + Draw d = env.base_draw(1, false); + IndirectDrawArgs ind{}; + ind.argument_buffer = MockEnv::kBuf; + ind.stride = 16; + ind.max_count = 1; + CHECK(l.draw_indirect(std::move(d), ind)); + }); + check_helper_invalidates("emit_quad_indices", [&env](CommandList& l) { + Draw d = env.base_draw(1, true); + d.topology = topology_quad_list; + d.count = 8; + CHECK(l.draw(d)); + }); + check_helper_invalidates("depth24_run", [](CommandList& l) { + CopyTexture cp{}; + cp.dst = {MockEnv::kTexD24, false, 0, 0, 0, 0, 0, 0}; + cp.src = {MockEnv::kBuf, true, 0, 0, 16, 16, 1, 256}; + CHECK(l.copy_texture(cp)); + }); + check_helper_invalidates("resolve_binary_occlusion", [](CommandList& l) { + CHECK(l.begin_query({MockEnv::kOccHeap, d3d12_query::binary_occlusion, 0})); + CHECK(l.end_query({MockEnv::kOccHeap, d3d12_query::binary_occlusion, 0})); + CHECK(l.resolve_queries({MockEnv::kOccHeap, d3d12_query::binary_occlusion, 0, 1, MockEnv::kResults, 0})); + }); + } + + // 1f: Cross-list ReplayStateCache sharing (as VulkanQueue::execute_now does across PreparedLists in one CB). + { + CommandList l1, l2; + const Draw d = env.base_draw(1, true); + CHECK(l1.draw(d) && l1.close()); + CHECK(l2.draw(d) && l2.close()); + PreparedList p1, p2; + CHECK(prepare(l1, resolve, env.vk, p1) == ReplayResult::success); + CHECK(prepare(l2, resolve, env.vk, p2) == ReplayResult::success); + ReplayStateCache shared; + g_mc.reset(); + emit(p1, cb, env.vk, nullptr, nullptr, &shared); + emit(p2, cb, env.vk, nullptr, nullptr, &shared); + CHECK(g_mc.draws == 2 && g_mc.bind_gfx == 1 && g_mc.desc_gfx == 1 && g_mc.push == 1 && g_mc.index == 1); + } + + std::puts("replay_state_cache CPU mock elision & invalidation: ok"); +} + +// --------------------------------------------------------------------------------------------------------------- +// Part 2: 5,000-draw throughput check (< 1.0 us/draw) + +void test_throughput_5000_draws() { + MockEnv env; + // Swap to zero-overhead no-op callbacks (without vector push_back on pushes) for clean timing. + env.vk.pipeline_barrier = +[](VkCommandBuffer, VkPipelineStageFlags, VkPipelineStageFlags, VkDependencyFlags, + std::uint32_t, const VkMemoryBarrier*, std::uint32_t, const VkBufferMemoryBarrier*, + std::uint32_t, const VkImageMemoryBarrier*) {}; + env.vk.begin_rendering = +[](VkCommandBuffer, const VkRenderingInfo*) {}; + env.vk.end_rendering = +[](VkCommandBuffer) {}; + env.vk.bind_pipeline = +[](VkCommandBuffer, VkPipelineBindPoint, VkPipeline) {}; + env.vk.bind_descriptor_sets = +[](VkCommandBuffer, VkPipelineBindPoint, VkPipelineLayout, std::uint32_t, + std::uint32_t, const VkDescriptorSet*, std::uint32_t, const std::uint32_t*) {}; + env.vk.push_constants = +[](VkCommandBuffer, VkPipelineLayout, VkShaderStageFlags, std::uint32_t, std::uint32_t, + const void*) {}; + env.vk.set_viewport = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, const VkViewport*) {}; + env.vk.set_scissor = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, const VkRect2D*) {}; + env.vk.set_primitive_topology = +[](VkCommandBuffer, VkPrimitiveTopology) {}; + env.vk.set_primitive_restart_enable = +[](VkCommandBuffer, VkBool32) {}; + env.vk.set_stencil_reference = +[](VkCommandBuffer, VkStencilFaceFlags, std::uint32_t) {}; + env.vk.set_blend_constants = +[](VkCommandBuffer, const float*) {}; + env.vk.set_depth_bounds = +[](VkCommandBuffer, float, float) {}; + env.vk.bind_vertex_buffers2 = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, const VkBuffer*, + const VkDeviceSize*, const VkDeviceSize*, const VkDeviceSize*) {}; + env.vk.bind_index_buffer = +[](VkCommandBuffer, VkBuffer, VkDeviceSize, VkIndexType) {}; + env.vk.draw_indexed = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, std::uint32_t, std::int32_t, + std::uint32_t) {}; + + constexpr std::uint32_t kDraws = 5000; + CommandList list; + Draw d = env.base_draw(1, true); + for (std::uint32_t i = 0; i < kDraws; ++i) { + // Realistic mix: same pipeline/viewport/scissor, 1 push-constant word changes every draw. + d.user_data[0] = i; + CHECK(list.draw(d)); + } + CHECK(list.close()); + + PreparedList prep; + const auto resolve = [&env](ResourceId id) { return env.resolve(id); }; + CHECK(prepare(list, resolve, env.vk, prep) == ReplayResult::success); + + const VkCommandBuffer cb = fake_handle(0x1); + for (int w = 0; w < 5; ++w) emit(prep, cb, env.vk); + + constexpr int kReps = 21; + std::vector us_per_draw; + us_per_draw.reserve(kReps); + for (int r = 0; r < kReps; ++r) { + const auto t0 = std::chrono::steady_clock::now(); + emit(prep, cb, env.vk); + const auto t1 = std::chrono::steady_clock::now(); + const double us = std::chrono::duration(t1 - t0).count(); + us_per_draw.push_back(us / double(kDraws)); + } + std::sort(us_per_draw.begin(), us_per_draw.end()); + const double median_us = us_per_draw[us_per_draw.size() / 2]; + std::printf("replay_state_cache throughput (%u draws): %.4f us/draw (%.2f ms total)\n", kDraws, median_us, + median_us * double(kDraws) / 1000.0); + CHECK(median_us < 1.0); +} + +// --------------------------------------------------------------------------------------------------------------- +// Part 3: Live Vulkan GPU validation test (real graphics + compute + partial push + clear + interleave) + +// Hand-assembled SPIR-V 1.3 vertex shader: +// layout(location = 0) in vec2 in_pos; +// void main() { gl_Position = vec4(in_pos, 0.0, 1.0); } +std::vector build_vs_spirv() { + std::vector w; + const auto op = [&](std::uint16_t code, std::initializer_list args) { + w.push_back((std::uint32_t(args.size() + 1) << 16) | code); + for (std::uint32_t a : args) w.push_back(a); + }; + constexpr std::uint32_t kVoid = 1, kFn = 2, kF32 = 3, kVec2 = 4, kVec4 = 5; + constexpr std::uint32_t kPtrInVec2 = 6, kInPos = 7; + constexpr std::uint32_t kPerVertex = 8, kPtrOutPV = 9, kOutPV = 10, kPtrOutVec4 = 11; + constexpr std::uint32_t kI32 = 12, kI0 = 13, kF0 = 14, kF1 = 15; + constexpr std::uint32_t kMain = 16, kLabel = 17, kLoadPos = 18, kX = 19, kY = 20, kPos4 = 21, kPtrPos = 22; + constexpr std::uint32_t kBound = 23; + + w.insert(w.end(), {0x07230203u, 0x00010300u, 0u, kBound, 0u}); + op(17, {1u}); // OpCapability Shader + op(14, {0u, 1u}); // OpMemoryModel Logical GLSL450 + op(15, {0u, kMain, 0x6e69616du, 0u, kOutPV, kInPos}); // OpEntryPoint Vertex %main "main" + op(72, {kPerVertex, 0u, 11u, 0u}); // MemberDecorate PerVertex 0 BuiltIn Position(0) + op(71, {kPerVertex, 2u}); // Decorate PerVertex Block + op(71, {kInPos, 30u, 0u}); // Decorate in_pos Location 0 + + op(19, {kVoid}); + op(33, {kFn, kVoid}); + op(22, {kF32, 32u}); + op(23, {kVec2, kF32, 2u}); + op(23, {kVec4, kF32, 4u}); + op(32, {kPtrInVec2, 1u, kVec2}); // Input(1) + op(59, {kPtrInVec2, kInPos, 1u}); + op(30, {kPerVertex, kVec4}); + op(32, {kPtrOutPV, 3u, kPerVertex}); // Output(3) + op(59, {kPtrOutPV, kOutPV, 3u}); + op(32, {kPtrOutVec4, 3u, kVec4}); + op(21, {kI32, 32u, 1u}); + op(43, {kI32, kI0, 0u}); + op(43, {kF32, kF0, float_bits(0.0f)}); + op(43, {kF32, kF1, float_bits(1.0f)}); + + op(54, {kVoid, kMain, 0u, kFn}); + op(248, {kLabel}); + op(61, {kVec2, kLoadPos, kInPos}); + op(81, {kF32, kX, kLoadPos, 0u}); + op(81, {kF32, kY, kLoadPos, 1u}); + op(80, {kVec4, kPos4, kX, kY, kF0, kF1}); + op(65, {kPtrOutVec4, kPtrPos, kOutPV, kI0}); + op(62, {kPtrPos, kPos4}); + op(253, {}); + op(56, {}); + return w; +} + +// Hand-assembled SPIR-V 1.3 fragment shader: +// layout(push_constant) uniform PC { float r, g, b, a; uint pad[4]; float scale; } pc; +// layout(location = 0) out vec4 out_color; +// void main() { +// vec4 col = vec4(pc.r * pc.scale, pc.g * pc.scale, pc.b * pc.scale, pc.a); +// out_color = (gl_FragCoord.x >= 0.0) ? col : vec4(0.0); +// } +// Reads BOTH word 0..3 (offset 0..15) AND word 8 (offset 32) so partial push updates to either region are verified. +// The gl_FragCoord guard is always true for framebuffer pixels and avoids a Mesa llvmpipe linear-fastpath bug +// where inputless flat-color fragment shaders misread non-contiguous push-constant struct offsets. +std::vector build_fs_spirv() { + std::vector w; + const auto op = [&](std::uint16_t code, std::initializer_list args) { + w.push_back((std::uint32_t(args.size() + 1) << 16) | code); + for (std::uint32_t a : args) w.push_back(a); + }; + constexpr std::uint32_t kVoid = 1, kFn = 2, kF32 = 3, kVec4 = 4, kI32 = 5; + constexpr std::uint32_t kPtrOutVec4 = 6, kOutColor = 7; + constexpr std::uint32_t kPcStruct = 8, kPtrPcStruct = 9, kPcVar = 10, kPtrPcF32 = 11; + constexpr std::uint32_t kI0 = 12, kI1 = 13, kI2 = 14, kI3 = 15, kI4 = 16; + constexpr std::uint32_t kMain = 17, kLabel = 18; + constexpr std::uint32_t kPr = 19, kPg = 20, kPb = 21, kPa = 22, kPs = 23; + constexpr std::uint32_t kR = 24, kG = 25, kB = 26, kA = 27, kS = 28; + constexpr std::uint32_t kRs = 29, kGs = 30, kBs = 31, kCol = 32; + constexpr std::uint32_t kBool = 33, kPtrInVec4 = 34, kFragCoord = 35, kF0 = 36; + constexpr std::uint32_t kFc = 37, kFcx = 38, kCond = 39, kSg = 40; + constexpr std::uint32_t kBound = 41; + + w.insert(w.end(), {0x07230203u, 0x00010300u, 0u, kBound, 0u}); + op(17, {1u}); // OpCapability Shader + op(14, {0u, 1u}); // OpMemoryModel Logical GLSL450 + op(15, {4u, kMain, 0x6e69616du, 0u, kOutColor, kFragCoord}); // OpEntryPoint Fragment %main "main" + op(16, {kMain, 7u}); // OriginUpperLeft(7) + op(71, {kOutColor, 30u, 0u}); // Location 0 + op(71, {kFragCoord, 11u, 15u}); // BuiltIn FragCoord(15) + op(71, {kPcStruct, 2u}); // Block + op(72, {kPcStruct, 0u, 35u, 0u}); // Offset 0 (user_data[0]: r) + op(72, {kPcStruct, 1u, 35u, 4u}); // Offset 4 (user_data[1]: g) + op(72, {kPcStruct, 2u, 35u, 8u}); // Offset 8 (user_data[2]: b) + op(72, {kPcStruct, 3u, 35u, 12u}); // Offset 12 (user_data[3]: a) + op(72, {kPcStruct, 4u, 35u, 32u}); // Offset 32 (user_data[8]: scale) + + op(19, {kVoid}); + op(33, {kFn, kVoid}); + op(20, {kBool}); + op(22, {kF32, 32u}); + op(23, {kVec4, kF32, 4u}); + op(21, {kI32, 32u, 1u}); + op(32, {kPtrOutVec4, 3u, kVec4}); // Output(3) + op(59, {kPtrOutVec4, kOutColor, 3u}); + op(32, {kPtrInVec4, 1u, kVec4}); // Input(1) + op(59, {kPtrInVec4, kFragCoord, 1u}); + op(30, {kPcStruct, kF32, kF32, kF32, kF32, kF32}); + op(32, {kPtrPcStruct, 9u, kPcStruct}); // PushConstant(9) + op(59, {kPtrPcStruct, kPcVar, 9u}); + op(32, {kPtrPcF32, 9u, kF32}); + op(43, {kI32, kI0, 0u}); + op(43, {kI32, kI1, 1u}); + op(43, {kI32, kI2, 2u}); + op(43, {kI32, kI3, 3u}); + op(43, {kI32, kI4, 4u}); + op(43, {kF32, kF0, 0u}); + + op(54, {kVoid, kMain, 0u, kFn}); + op(248, {kLabel}); + op(65, {kPtrPcF32, kPr, kPcVar, kI0}); + op(65, {kPtrPcF32, kPg, kPcVar, kI1}); + op(65, {kPtrPcF32, kPb, kPcVar, kI2}); + op(65, {kPtrPcF32, kPa, kPcVar, kI3}); + op(65, {kPtrPcF32, kPs, kPcVar, kI4}); + op(61, {kF32, kR, kPr}); + op(61, {kF32, kG, kPg}); + op(61, {kF32, kB, kPb}); + op(61, {kF32, kA, kPa}); + op(61, {kF32, kS, kPs}); + op(61, {kVec4, kFc, kFragCoord}); + op(81, {kF32, kFcx, kFc, 0u}); + op(190, {kBool, kCond, kFcx, kF0}); // OpFOrdGreaterThanEqual + op(169, {kF32, kSg, kCond, kS, kF0}); // scalar OpSelect (valid in SPIR-V 1.3) + op(133, {kF32, kRs, kR, kSg}); // OpFMul + op(133, {kF32, kGs, kG, kSg}); + op(133, {kF32, kBs, kB, kSg}); + op(80, {kVec4, kCol, kRs, kGs, kBs, kA}); + op(62, {kOutColor, kCol}); + op(253, {}); + op(56, {}); + return w; +} + +// Hand-assembled SPIR-V 1.3 compute shader: +// layout(set = 0, binding = 0) buffer Out { uint vals[4]; } out_buf; +// layout(push_constant) uniform PC { uint slot; uint val; uint pad[3]; uint xor_k; } pc; +// void main() { out_buf.vals[pc.slot] = pc.val ^ pc.xor_k; } +std::vector build_cs_spirv() { + std::vector w; + const auto op = [&](std::uint16_t code, std::initializer_list args) { + w.push_back((std::uint32_t(args.size() + 1) << 16) | code); + for (std::uint32_t a : args) w.push_back(a); + }; + constexpr std::uint32_t kVoid = 1, kFn = 2, kU32 = 3, kI32 = 4, kC4 = 5, kArr = 6, kBufS = 7; + constexpr std::uint32_t kPtrBufS = 8, kBufVar = 9, kPtrBufU32 = 10; + constexpr std::uint32_t kPcS = 11, kPtrPcS = 12, kPcVar = 13, kPtrPcU32 = 14; + constexpr std::uint32_t kI0 = 15, kI1 = 16, kI2 = 17; + constexpr std::uint32_t kMain = 18, kLabel = 19; + constexpr std::uint32_t kPslot = 20, kPval = 21, kPxor = 22, kSlot = 23, kVal = 24, kXor = 25, kRes = 26, kDst = 27; + constexpr std::uint32_t kBound = 28; + + w.insert(w.end(), {0x07230203u, 0x00010300u, 0u, kBound, 0u}); + op(17, {1u}); // OpCapability Shader + op(14, {0u, 1u}); // OpMemoryModel Logical GLSL450 + op(15, {5u, kMain, 0x6e69616du, 0u}); // OpEntryPoint GLCompute %main "main" + op(16, {kMain, 17u, 1u, 1u, 1u}); // LocalSize 1 1 1 + + op(71, {kArr, 6u, 4u}); // ArrayStride 4 + op(72, {kBufS, 0u, 35u, 0u}); + op(71, {kBufS, 2u}); // Block + op(71, {kBufVar, 34u, 0u}); // DescriptorSet 0 + op(71, {kBufVar, 33u, 0u}); // Binding 0 + op(71, {kPcS, 2u}); // Block + op(72, {kPcS, 0u, 35u, 0u}); // Offset 0 (user_data[0]: slot) + op(72, {kPcS, 1u, 35u, 4u}); // Offset 4 (user_data[1]: val) + op(72, {kPcS, 2u, 35u, 20u}); // Offset 20 (user_data[5]: xor_k) + + op(19, {kVoid}); + op(33, {kFn, kVoid}); + op(21, {kU32, 32u, 0u}); + op(21, {kI32, 32u, 1u}); + op(43, {kU32, kC4, 4u}); + op(28, {kArr, kU32, kC4}); + op(30, {kBufS, kArr}); + op(32, {kPtrBufS, 12u, kBufS}); // StorageBuffer(12) + op(59, {kPtrBufS, kBufVar, 12u}); + op(32, {kPtrBufU32, 12u, kU32}); + op(30, {kPcS, kU32, kU32, kU32}); + op(32, {kPtrPcS, 9u, kPcS}); // PushConstant(9) + op(59, {kPtrPcS, kPcVar, 9u}); + op(32, {kPtrPcU32, 9u, kU32}); + op(43, {kI32, kI0, 0u}); + op(43, {kI32, kI1, 1u}); + op(43, {kI32, kI2, 2u}); + + op(54, {kVoid, kMain, 0u, kFn}); + op(248, {kLabel}); + op(65, {kPtrPcU32, kPslot, kPcVar, kI0}); + op(65, {kPtrPcU32, kPval, kPcVar, kI1}); + op(65, {kPtrPcU32, kPxor, kPcVar, kI2}); + op(61, {kU32, kSlot, kPslot}); + op(61, {kU32, kVal, kPval}); + op(61, {kU32, kXor, kPxor}); + op(198, {kU32, kRes, kVal, kXor}); // OpBitwiseXor + op(65, {kPtrBufU32, kDst, kBufVar, kI0, kSlot}); + op(62, {kDst, kRes}); + op(253, {}); + op(56, {}); + return w; +} + +void test_gpu_live_validation() { + vktest::Device dev; + const auto status = dev.initialize(); + if (status == vktest::DeviceStatus::unavailable) { + std::puts("SKIP: no Vulkan device for live replay_state_cache GPU test"); + return; + } + CHECK(status == vktest::DeviceStatus::ready); + if (status != vktest::DeviceStatus::ready) return; + + const auto vkCreateShaderModule = dev.fn("vkCreateShaderModule"); + const auto vkDestroyShaderModule = dev.fn("vkDestroyShaderModule"); + const auto vkCreateDescriptorSetLayout = dev.fn("vkCreateDescriptorSetLayout"); + const auto vkDestroyDescriptorSetLayout = dev.fn("vkDestroyDescriptorSetLayout"); + const auto vkCreateDescriptorPool = dev.fn("vkCreateDescriptorPool"); + const auto vkDestroyDescriptorPool = dev.fn("vkDestroyDescriptorPool"); + const auto vkAllocateDescriptorSets = dev.fn("vkAllocateDescriptorSets"); + const auto vkUpdateDescriptorSets = dev.fn("vkUpdateDescriptorSets"); + const auto vkCreatePipelineLayout = dev.fn("vkCreatePipelineLayout"); + const auto vkDestroyPipelineLayout = dev.fn("vkDestroyPipelineLayout"); + const auto vkCreateGraphicsPipelines = dev.fn("vkCreateGraphicsPipelines"); + const auto vkCreateComputePipelines = dev.fn("vkCreateComputePipelines"); + const auto vkDestroyPipeline = dev.fn("vkDestroyPipeline"); + + constexpr std::uint32_t kW = 8, kH = 8, kPitch = 256; + const VkImage color_img = + dev.image(VK_FORMAT_R8G8B8A8_UNORM, kW, kH, 1, + VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | + VK_IMAGE_USAGE_TRANSFER_DST_BIT); + void* rb_pixels = nullptr; + const VkBuffer rb_buf = dev.buffer(kH * kPitch, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &rb_pixels); + void* ssbo_mapped = nullptr; + const VkBuffer ssbo = dev.buffer(64, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &ssbo_mapped); + void* vb_mapped = nullptr; + const VkBuffer vb = dev.buffer(256, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, &vb_mapped); + void* ib_mapped = nullptr; + const VkBuffer ib = dev.buffer(256, VK_BUFFER_USAGE_INDEX_BUFFER_BIT, &ib_mapped); + CHECK(color_img && rb_buf && rb_pixels && ssbo && ssbo_mapped && vb && vb_mapped && ib && ib_mapped); + if (!color_img || !rb_buf || !ssbo || !vb || !ib) return; + + std::memset(rb_pixels, 0, kH * kPitch); + std::memset(ssbo_mapped, 0, 64); + + // Full-screen quad vertices (4 vertices, vec2) + two index slices (same triangles at offset 0 and offset 16). + const float verts[8] = {-1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f}; + std::memcpy(vb_mapped, verts, sizeof(verts)); + const std::uint16_t indices[12] = {0, 1, 2, 0, 2, 3, 0, 0, 0, 1, 2, 3}; + std::memcpy(ib_mapped, indices, sizeof(indices)); + + // Descriptor set 0 for compute SSBO (and empty set layout for graphics). + const VkDescriptorSetLayoutBinding b0{0, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; + VkDescriptorSetLayoutCreateInfo dsl_ci{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; + dsl_ci.bindingCount = 1; + dsl_ci.pBindings = &b0; + VkDescriptorSetLayout comp_dsl = VK_NULL_HANDLE; + CHECK(vkCreateDescriptorSetLayout(dev.device, &dsl_ci, nullptr, &comp_dsl) == VK_SUCCESS); + + const VkDescriptorPoolSize pool_sz{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}; + VkDescriptorPoolCreateInfo dp_ci{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; + dp_ci.maxSets = 1; + dp_ci.poolSizeCount = 1; + dp_ci.pPoolSizes = &pool_sz; + VkDescriptorPool dp = VK_NULL_HANDLE; + CHECK(vkCreateDescriptorPool(dev.device, &dp_ci, nullptr, &dp) == VK_SUCCESS); + + VkDescriptorSetAllocateInfo ds_ai{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; + ds_ai.descriptorPool = dp; + ds_ai.descriptorSetCount = 1; + ds_ai.pSetLayouts = &comp_dsl; + VkDescriptorSet comp_ds = VK_NULL_HANDLE; + CHECK(vkAllocateDescriptorSets(dev.device, &ds_ai, &comp_ds) == VK_SUCCESS); + + const VkDescriptorBufferInfo dbi{ssbo, 0, 64}; + VkWriteDescriptorSet wds{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET}; + wds.dstSet = comp_ds; + wds.dstBinding = 0; + wds.descriptorCount = 1; + wds.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + wds.pBufferInfo = &dbi; + vkUpdateDescriptorSets(dev.device, 1, &wds, 0, nullptr); + + // Pipeline layouts. + const VkPushConstantRange gfx_pcr{VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, + sizeof(ShaderUserData)}; + VkPipelineLayoutCreateInfo gpl_ci{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; + gpl_ci.pushConstantRangeCount = 1; + gpl_ci.pPushConstantRanges = &gfx_pcr; + VkPipelineLayout gfx_layout = VK_NULL_HANDLE; + CHECK(vkCreatePipelineLayout(dev.device, &gpl_ci, nullptr, &gfx_layout) == VK_SUCCESS); + + const VkPushConstantRange comp_pcr{VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(ShaderUserData)}; + VkPipelineLayoutCreateInfo cpl_ci{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; + cpl_ci.setLayoutCount = 1; + cpl_ci.pSetLayouts = &comp_dsl; + cpl_ci.pushConstantRangeCount = 1; + cpl_ci.pPushConstantRanges = &comp_pcr; + VkPipelineLayout comp_layout = VK_NULL_HANDLE; + CHECK(vkCreatePipelineLayout(dev.device, &cpl_ci, nullptr, &comp_layout) == VK_SUCCESS); + + // Shader modules. + const auto vs_spv = build_vs_spirv(); + const auto fs_spv = build_fs_spirv(); + const auto cs_spv = build_cs_spirv(); + const auto make_mod = [&](const std::vector& spv) { + VkShaderModuleCreateInfo ci{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + ci.codeSize = spv.size() * sizeof(std::uint32_t); + ci.pCode = spv.data(); + VkShaderModule m = VK_NULL_HANDLE; + CHECK(vkCreateShaderModule(dev.device, &ci, nullptr, &m) == VK_SUCCESS); + return m; + }; + const VkShaderModule vs_mod = make_mod(vs_spv); + const VkShaderModule fs_mod = make_mod(fs_spv); + const VkShaderModule cs_mod = make_mod(cs_spv); + + // Graphics pipeline (dynamic rendering, dynamic viewport/scissor/topology/restart/stencil/blend/vertex_stride). + VkPipelineShaderStageCreateInfo stages[2]{ + {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}, + {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}, + }; + stages[0].stage = VK_SHADER_STAGE_VERTEX_BIT; + stages[0].module = vs_mod; + stages[0].pName = "main"; + stages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; + stages[1].module = fs_mod; + stages[1].pName = "main"; + + VkVertexInputBindingDescription vbind{0, 8, VK_VERTEX_INPUT_RATE_VERTEX}; + VkVertexInputAttributeDescription vattr{0, 0, VK_FORMAT_R32G32_SFLOAT, 0}; + VkPipelineVertexInputStateCreateInfo vi{VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO}; + vi.vertexBindingDescriptionCount = 1; + vi.pVertexBindingDescriptions = &vbind; + vi.vertexAttributeDescriptionCount = 1; + vi.pVertexAttributeDescriptions = &vattr; + + VkPipelineInputAssemblyStateCreateInfo ia{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO}; + ia.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; + + VkPipelineViewportStateCreateInfo vp{VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO}; + vp.viewportCount = 1; + vp.scissorCount = 1; + + VkPipelineRasterizationStateCreateInfo rs{VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO}; + rs.polygonMode = VK_POLYGON_MODE_FILL; + rs.cullMode = VK_CULL_MODE_NONE; + rs.frontFace = VK_FRONT_FACE_CLOCKWISE; + rs.lineWidth = 1.0f; + + VkPipelineMultisampleStateCreateInfo ms{VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO}; + ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; + + VkPipelineColorBlendAttachmentState cba{}; + cba.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | + VK_COLOR_COMPONENT_A_BIT; + VkPipelineColorBlendStateCreateInfo cb_state{VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO}; + cb_state.attachmentCount = 1; + cb_state.pAttachments = &cba; + + const VkDynamicState dyn_states[] = { + VK_DYNAMIC_STATE_VIEWPORT, + VK_DYNAMIC_STATE_SCISSOR, + VK_DYNAMIC_STATE_PRIMITIVE_TOPOLOGY, + VK_DYNAMIC_STATE_PRIMITIVE_RESTART_ENABLE, + VK_DYNAMIC_STATE_STENCIL_REFERENCE, + VK_DYNAMIC_STATE_BLEND_CONSTANTS, + VK_DYNAMIC_STATE_VERTEX_INPUT_BINDING_STRIDE, + }; + VkPipelineDynamicStateCreateInfo dyn{VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO}; + dyn.dynamicStateCount = static_cast(std::size(dyn_states)); + dyn.pDynamicStates = dyn_states; + + const VkFormat color_fmt = VK_FORMAT_R8G8B8A8_UNORM; + VkPipelineRenderingCreateInfo rend{VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO}; + rend.colorAttachmentCount = 1; + rend.pColorAttachmentFormats = &color_fmt; + + VkGraphicsPipelineCreateInfo gp_ci{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, &rend}; + gp_ci.stageCount = 2; + gp_ci.pStages = stages; + gp_ci.pVertexInputState = &vi; + gp_ci.pInputAssemblyState = &ia; + gp_ci.pViewportState = &vp; + gp_ci.pRasterizationState = &rs; + gp_ci.pMultisampleState = &ms; + gp_ci.pColorBlendState = &cb_state; + gp_ci.pDynamicState = &dyn; + gp_ci.layout = gfx_layout; + VkPipeline gfx_pipe = VK_NULL_HANDLE; + CHECK(vkCreateGraphicsPipelines(dev.device, VK_NULL_HANDLE, 1, &gp_ci, nullptr, &gfx_pipe) == VK_SUCCESS); + + // Compute pipeline. + VkComputePipelineCreateInfo cp_ci{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; + cp_ci.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; + cp_ci.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; + cp_ci.stage.module = cs_mod; + cp_ci.stage.pName = "main"; + cp_ci.layout = comp_layout; + VkPipeline comp_pipe = VK_NULL_HANDLE; + CHECK(vkCreateComputePipelines(dev.device, VK_NULL_HANDLE, 1, &cp_ci, nullptr, &comp_pipe) == VK_SUCCESS); + + // Second graphics pipeline with depth-only, and third with depth+stencil (tests depth_aspects scope split on GPU). + const VkImage depth_img = + dev.image(VK_FORMAT_D32_SFLOAT_S8_UINT, kW, kH, 1, + VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT); + VkPipeline gfx_depth_pipe = VK_NULL_HANDLE; + VkPipeline gfx_depth_stencil_pipe = VK_NULL_HANDLE; + { + VkPipelineDepthStencilStateCreateInfo ds{VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO}; + VkPipelineRenderingCreateInfo rend_d = rend; + rend_d.depthAttachmentFormat = VK_FORMAT_D32_SFLOAT_S8_UINT; + VkGraphicsPipelineCreateInfo gp_d = gp_ci; + gp_d.pNext = &rend_d; + gp_d.pDepthStencilState = &ds; + CHECK(vkCreateGraphicsPipelines(dev.device, VK_NULL_HANDLE, 1, &gp_d, nullptr, &gfx_depth_pipe) == VK_SUCCESS); + + VkPipelineRenderingCreateInfo rend_ds = rend_d; + rend_ds.stencilAttachmentFormat = VK_FORMAT_D32_SFLOAT_S8_UINT; + VkGraphicsPipelineCreateInfo gp_ds = gp_d; + gp_ds.pNext = &rend_ds; + CHECK(vkCreateGraphicsPipelines(dev.device, VK_NULL_HANDLE, 1, &gp_ds, nullptr, &gfx_depth_stencil_pipe) == + VK_SUCCESS); + } + + if (gfx_pipe && comp_pipe && depth_img && gfx_depth_pipe && gfx_depth_stencil_pipe) { + VulkanContext ctx(dev.device_proc, dev.device, true, dev.conditional_rendering, dev.buffer_device_address); + CHECK(ctx.loaded()); + + constexpr ResourceId kRtId = 1, kVbId = 2, kIbId = 3, kRbId = 4, kDsId = 5; + constexpr std::uint64_t kVbVa = 0x10000ull, kIbVa = 0x20000ull; + ResourceBinding rt_b{}; + rt_b.image = color_img; + rt_b.format = VK_FORMAT_R8G8B8A8_UNORM; + rt_b.aspects = VK_IMAGE_ASPECT_COLOR_BIT; + rt_b.width = kW; + rt_b.height = kH; + rt_b.color_attachment = true; + ctx.add_resource(kRtId, rt_b, VK_IMAGE_LAYOUT_UNDEFINED); + + ResourceBinding ds_b{}; + ds_b.image = depth_img; + ds_b.format = VK_FORMAT_D32_SFLOAT_S8_UINT; + ds_b.aspects = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; + ds_b.width = kW; + ds_b.height = kH; + ctx.add_resource(kDsId, ds_b, VK_IMAGE_LAYOUT_UNDEFINED); + + ResourceBinding vb_b{}; + vb_b.buffer = vb; + vb_b.size = 256; + vb_b.va = kVbVa; + ctx.add_resource(kVbId, vb_b); + + ResourceBinding ib_b{}; + ib_b.buffer = ib; + ib_b.size = 256; + ib_b.va = kIbVa; + ctx.add_resource(kIbId, ib_b); + + ResourceBinding rb_b{}; + rb_b.buffer = rb_buf; + rb_b.size = kH * kPitch; + rb_b.host_readable = true; + ctx.add_resource(kRbId, rb_b); + + GraphicsPipeline gp{}; + gp.pipeline = gfx_pipe; + gp.layout = gfx_layout; + gp.push_stages = VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT; + gp.color_formats = {VK_FORMAT_R8G8B8A8_UNORM}; + gp.vertex_slots = 0b1; + ctx.add_graphics_pipeline(100, gp); + + GraphicsPipeline gp_glc = gp; + gp_glc.reads_glc_buffer = true; + ctx.add_graphics_pipeline(101, gp_glc); + + GraphicsPipeline gp_d = gp; + gp_d.pipeline = gfx_depth_pipe; + gp_d.depth_format = VK_FORMAT_D32_SFLOAT_S8_UINT; + gp_d.depth_aspects = VK_IMAGE_ASPECT_DEPTH_BIT; + ctx.add_graphics_pipeline(102, gp_d); + + GraphicsPipeline gp_ds = gp_d; + gp_ds.pipeline = gfx_depth_stencil_pipe; + gp_ds.depth_aspects = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; + ctx.add_graphics_pipeline(103, gp_ds); + + ComputePipeline cp{}; + cp.pipeline = comp_pipe; + cp.layout = comp_layout; + cp.bindless_set = comp_ds; + ctx.add_pipeline(200, cp); + + VulkanQueue queue(ctx, dev.queue, dev.family, VulkanQueue::QueueKind::direct); + CHECK(queue.ok()); + + // List 1: Clear -> Draw 1 (red, left half) -> Draw 2 (identical, elided) -> Draw 3 (partial push: change ONLY + // g=1.0 -> yellow on top-right) -> Compute 1 & Compute 2 (partial push) -> Draw 4 (identical color to + // Draw 3 but on bottom-right, proving compute invalidated push constants and Draw 4 re-pushed!). + CommandList list1; + CHECK(list1.transition({kRtId, all_subresources, d3d12_state::common, d3d12_state::render_target})); + CHECK(list1.clear_render_target({kRtId, 0, 0, 1}, {0.0f, 0.0f, 1.0f, 1.0f})); + + auto make_quad = [&](float r, float g, float b, float scale, std::int32_t x0, std::int32_t y0, std::int32_t x1, + std::int32_t y1) { + Draw d{}; + d.pipeline = 100; + auto views = std::make_shared(); + views->render_targets[0] = {kRtId, 0, 0, 1}; + views->render_target_count = 1; + views->vertex_buffers[0] = {kVbVa, 256, 8}; + d.views = std::move(views); + d.index = {kIbVa, 12, 57}; // R16_UINT + d.indexed = true; + d.topology = 4; + d.viewport = {0.0f, 0.0f, float(kW), float(kH), 0.0f, 1.0f}; + d.scissor = {x0, y0, x1, y1}; + d.blend_factor = {1, 1, 1, 1}; + d.count = 6; + d.instances = 1; + d.user_data[0] = float_bits(r); + d.user_data[1] = float_bits(g); + d.user_data[2] = float_bits(b); + d.user_data[3] = float_bits(1.0f); + d.user_data[8] = float_bits(scale); + return d; + }; + + // Top-left [0..4, 0..4): red (1, 0, 0, 1) * 1.0 = (255, 0, 0, 255) + const Draw d_red = make_quad(1.0f, 0.0f, 0.0f, 1.0f, 0, 0, 4, 4); + CHECK(list1.draw(d_red)); + CHECK(list1.draw(d_red)); // identical draw (state elided) + + // Top-right [4..8, 0..4): change ONLY user_data[1] (g = 1.0) & scissor -> yellow (255, 255, 0, 255) + const Draw d_yellow = make_quad(1.0f, 1.0f, 0.0f, 1.0f, 4, 0, 8, 4); + CHECK(list1.draw(d_yellow)); + + // Interleaved compute dispatches: + // slot 0: 0x12340000 ^ 0x000000A5 = 0x123400A5 + // slot 1 (partial push: slot + val change, xor_k unchanged): 0x56780000 ^ 0x000000A5 = 0x567800A5 + // slot 2 (partial push: slot + xor_k change, val unchanged): 0x56780000 ^ 0x0000005A = 0x5678005A + Dispatch c{}; + c.pipeline = 200; + c.x = c.y = c.z = 1; + c.user_data[0] = 0; + c.user_data[1] = 0x12340000u; + c.user_data[5] = 0x000000A5u; + CHECK(list1.dispatch(c)); + c.user_data[0] = 1; + c.user_data[1] = 0x56780000u; + CHECK(list1.dispatch(c)); + c.user_data[0] = 2; + c.user_data[5] = 0x0000005Au; + CHECK(list1.dispatch(c)); + + // Bottom-right [4..8, 4..8): SAME user_data as d_yellow after compute -> MUST re-push full push constants! + const Draw d_yellow_br = make_quad(1.0f, 1.0f, 0.0f, 1.0f, 4, 4, 8, 8); + CHECK(list1.draw(d_yellow_br)); + + // Bottom-left [0..4, 4..8): change ONLY user_data[8] (scale = 0.0 -> black (0, 0, 0, 255))! + const Draw d_black_bl = make_quad(1.0f, 1.0f, 0.0f, 0.0f, 0, 4, 4, 8); + CHECK(list1.draw(d_black_bl)); + + // Consecutive reads_glc_buffer draw on the same RT (must close open scope for ALL_GRAPHICS_BIT barrier), + // followed by depth-only -> depth+stencil draws on the same D32S8 target (must split on depth_aspects!). + Draw d_glc_br = make_quad(1.0f, 1.0f, 0.0f, 1.0f, 4, 4, 8, 8); + d_glc_br.pipeline = 101; // reads_glc_buffer = true + CHECK(list1.draw(d_glc_br)); + + CHECK(list1.transition({kDsId, all_subresources, d3d12_state::common, d3d12_state::depth_write})); + Draw d_depth_only = make_quad(1.0f, 0.0f, 0.0f, 1.0f, 0, 0, 4, 4); + d_depth_only.pipeline = 102; // depth_aspects = DEPTH_BIT + d_depth_only.depth = {kDsId, 0, 0, 1}; + CHECK(list1.draw(d_depth_only)); + Draw d_depth_stencil = make_quad(1.0f, 0.0f, 0.0f, 1.0f, 0, 0, 4, 4); + d_depth_stencil.pipeline = 103; // depth_aspects = DEPTH_BIT | STENCIL_BIT + d_depth_stencil.depth = {kDsId, 0, 0, 1}; + CHECK(list1.draw(d_depth_stencil)); + CHECK(list1.draw(d_depth_stencil)); // merged into same depth+stencil scope + + // Read back color target into rb_buf. + CHECK(list1.transition({kRtId, all_subresources, d3d12_state::render_target, d3d12_state::copy_source})); + CopyTexture readback{}; + readback.dst = {kRbId, true, 0, 0, kW, kH, 1, kPitch}; + readback.src = {kRtId, false, 0, 0, 0, 0, 0, 0}; + CHECK(list1.copy_texture(readback)); + CHECK(list1.close()); + + const CommandList* batch[1] = {&list1}; + CHECK(queue.execute(batch) == ReplayResult::success); + CHECK(queue.idle()); + + // Verify SSBO compute outputs. + const auto* out_u32 = static_cast(ssbo_mapped); + CHECK(out_u32[0] == 0x123400A5u); + CHECK(out_u32[1] == 0x567800A5u); + CHECK(out_u32[2] == 0x5678005Au); + + // Verify color quadrants: + // TL (1,1): red (255,0,0,255) + // TR (6,1): yellow (255,255,0,255) + // BR (6,6): yellow (255,255,0,255) <-- proves graphics push constants re-pushed after compute! + // BL (1,6): black (0,0,0,255) <-- proves partial push update to user_data[8] (scale=0.0)! + const auto* px = static_cast(rb_pixels); + const auto check_px = [&](std::uint32_t x, std::uint32_t y, std::uint8_t r, std::uint8_t g, std::uint8_t b, + std::uint8_t a) { + const std::size_t off = std::size_t(y) * kPitch + std::size_t(x) * 4; + const bool ok = px[off] == r && px[off + 1] == g && px[off + 2] == b && px[off + 3] == a; + if (!ok) + std::fprintf(stderr, "FAIL pixel (%u,%u): got (%u,%u,%u,%u) want (%u,%u,%u,%u)\n", x, y, + unsigned(px[off]), unsigned(px[off + 1]), unsigned(px[off + 2]), unsigned(px[off + 3]), + unsigned(r), unsigned(g), unsigned(b), unsigned(a)); + CHECK(ok); + }; + check_px(1, 1, 255, 0, 0, 255); + check_px(6, 1, 255, 255, 0, 255); + check_px(6, 6, 255, 255, 0, 255); + check_px(1, 6, 0, 0, 0, 255); + std::puts("replay_state_cache live GPU validation (graphics + partial push + compute interleave): ok"); + } + + if (gfx_depth_stencil_pipe) vkDestroyPipeline(dev.device, gfx_depth_stencil_pipe, nullptr); + if (gfx_depth_pipe) vkDestroyPipeline(dev.device, gfx_depth_pipe, nullptr); + if (gfx_pipe) vkDestroyPipeline(dev.device, gfx_pipe, nullptr); + if (comp_pipe) vkDestroyPipeline(dev.device, comp_pipe, nullptr); + if (vs_mod) vkDestroyShaderModule(dev.device, vs_mod, nullptr); + if (fs_mod) vkDestroyShaderModule(dev.device, fs_mod, nullptr); + if (cs_mod) vkDestroyShaderModule(dev.device, cs_mod, nullptr); + if (gfx_layout) vkDestroyPipelineLayout(dev.device, gfx_layout, nullptr); + if (comp_layout) vkDestroyPipelineLayout(dev.device, comp_layout, nullptr); + if (dp) vkDestroyDescriptorPool(dev.device, dp, nullptr); + if (comp_dsl) vkDestroyDescriptorSetLayout(dev.device, comp_dsl, nullptr); + CHECK(dev.validation_errors() == 0); +} + +// --------------------------------------------------------------------------------------------------------------- +// Part 4: Batch-parallel synchronous pipeline compile (collect_unbuilt_pipelines + set_batch_compile_runner + +// closed/cancel teardown race safety) + +struct MiniCompilePool { + struct Entry { + const void* owner = nullptr; + std::function fn; + }; + std::mutex mutex; + std::condition_variable cv; + std::condition_variable done_cv; + std::deque queue; + std::vector running_owners; + std::vector threads; + bool closed = false; + + explicit MiniCompilePool(std::size_t n) { + threads.reserve(n); + for (std::size_t i = 0; i < n; ++i) { + threads.emplace_back([this] { + for (;;) { + Entry entry; + { + std::unique_lock lock(mutex); + cv.wait(lock, [&] { return closed || !queue.empty(); }); + if (queue.empty()) return; + entry = std::move(queue.front()); + queue.pop_front(); + running_owners.push_back(entry.owner); + } + entry.fn(); + { + std::lock_guard lock(mutex); + const auto it = std::find(running_owners.begin(), running_owners.end(), entry.owner); + if (it != running_owners.end()) running_owners.erase(it); + } + done_cv.notify_all(); + } + }); + } + } + ~MiniCompilePool() { + close_and_drop(); + for (auto& t : threads) + if (t.joinable()) t.join(); + } + bool submit(const void* owner, std::function fn) { + std::lock_guard lock(mutex); + if (closed) return false; + queue.push_back({owner, std::move(fn)}); + cv.notify_one(); + return true; + } + // Mirrors PipelineCompiler::cancel(owner): drops unstarted queued jobs for `owner` outside the lock and waits + // only if `owner` is currently running (never waits on unrelated busy workers). + std::size_t cancel(const void* owner) { + std::vector dropped; + { + std::unique_lock lock(mutex); + for (;;) { + std::deque kept; + for (auto& e : queue) { + if (e.owner == owner) dropped.push_back(std::move(e)); + else kept.push_back(std::move(e)); + } + queue.swap(kept); + if (std::find(running_owners.begin(), running_owners.end(), owner) == running_owners.end()) break; + done_cv.wait(lock); + } + } + return dropped.size(); // destroys dropped captures outside the lock + } + void close_and_drop() { + std::deque dropped; + { + std::lock_guard lock(mutex); + closed = true; + dropped.swap(queue); + } + cv.notify_all(); + dropped.clear(); // mirrors PipelineCompiler::drop_locked(): destroys queued lambdas without running them + } + void drop_queued() { + std::deque dropped; + { + std::lock_guard lock(mutex); + dropped.swap(queue); + } + dropped.clear(); + } +}; + +// Mirrors the exact work-stealing BatchState + RAII HelperDone + WaitHelpers (with cancel) runner used by Device. +VulkanContext::BatchCompileFn make_pool_batch_runner(MiniCompilePool& pool, std::size_t max_helpers) { + return [&pool, max_helpers](std::size_t count, const std::function& job) { + if (!count) return; + if (count == 1) { + job(0); + return; + } + struct BatchState { + std::atomic next{0}; + std::size_t count = 0; + const std::function* job = nullptr; + std::vector owner_tags; + std::mutex mutex; + std::condition_variable cv; + std::size_t pending_helpers = 0; + }; + auto run_work = [](BatchState& s) { + for (;;) { + const std::size_t i = s.next.fetch_add(1, std::memory_order_relaxed); + if (i >= s.count) break; + (*s.job)(i); + } + }; + struct HelperDone { + std::shared_ptr state; + explicit HelperDone(std::shared_ptr s) : state(std::move(s)) { + std::lock_guard lock(state->mutex); + ++state->pending_helpers; + } + ~HelperDone() { + if (!state) return; + std::lock_guard lock(state->mutex); + if (--state->pending_helpers == 0) state->cv.notify_all(); + } + }; + auto state = std::make_shared(); + state->count = count; + state->job = &job; + const std::size_t helpers = (std::min)(count - 1, max_helpers); + state->owner_tags.resize(helpers, 0); + { + struct WaitHelpers { + MiniCompilePool& pool; + std::shared_ptr state; + std::size_t submitted_helpers = 0; + ~WaitHelpers() { + for (std::size_t k = 0; k < submitted_helpers; ++k) + pool.cancel(&state->owner_tags[k]); + std::unique_lock lock(state->mutex); + state->cv.wait(lock, [&] { return state->pending_helpers == 0; }); + } + } wait_guard{pool, state, 0}; + for (std::size_t k = 0; k < helpers; ++k) { + auto done = std::make_shared(state); + if (!pool.submit(&state->owner_tags[k], [done = std::move(done), run_work] { run_work(*done->state); })) + break; + ++wait_guard.submitted_helpers; + } + run_work(*state); + } + }; +} + +void test_batch_parallel_sync_pipeline_compile() { + // 4a: collect_unbuilt_pipelines() deduplicates graphics (pso, unbound_mask, rectangle_stage) and compute across lists. + { + MockEnv env; + GraphicsPipeline unbuilt_a = env.gfx[1]; + unbuilt_a.pipeline = VK_NULL_HANDLE; + unbuilt_a.color_formats = {VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM}; + unbuilt_a.depth_format = VK_FORMAT_D32_SFLOAT; + unbuilt_a.variant = [](std::uint32_t) { return fake_handle(0x910); }; + unbuilt_a.built = [](std::uint32_t) -> VkPipeline { return VK_NULL_HANDLE; }; + env.gfx[10] = unbuilt_a; + + GraphicsPipeline unbuilt_b = env.gfx[1]; + unbuilt_b.pipeline = VK_NULL_HANDLE; + unbuilt_b.rectangle_variant_topology = 35u; + unbuilt_b.variant = [](std::uint32_t) { return fake_handle(0x911); }; + unbuilt_b.built = [](std::uint32_t) -> VkPipeline { return VK_NULL_HANDLE; }; + env.gfx[11] = unbuilt_b; + + ComputePipeline unbuilt_c = env.comp[1]; + unbuilt_c.pipeline = VK_NULL_HANDLE; + unbuilt_c.build = +[](void*) { return fake_handle(0x912); }; + unbuilt_c.built = +[](void*) -> VkPipeline { return VK_NULL_HANDLE; }; + env.comp[10] = unbuilt_c; + + CommandList l1, l2; + // Already-built pipeline (id=1): must NOT be collected. + CHECK(l1.draw(env.base_draw(1, false))); + // Unbuilt PSO 10 with slot 0 bound, slot 1 unbound, depth unbound -> flags = (1<<1) | unbound_depth = 0x102. + Draw da1 = env.base_draw(10, false); + CHECK(l1.draw(da1)); + CHECK(l1.draw(da1)); // duplicate in same list -> deduplicated + // Unbuilt PSO 10 with both color slots bound, depth unbound -> flags = unbound_depth = 0x100. + Draw da2 = env.base_draw(10, false); + auto views2 = std::make_shared(*da2.views); + views2->render_targets[1] = {MockEnv::kColor, 0, 0, 1}; + views2->render_target_count = 2; + da2.views = std::move(views2); + CHECK(l1.draw(da2)); + // Unbuilt PSO 11 with rectangle-list variant topology -> flags = rectangle_stage. + Draw db = env.base_draw(11, false); + db.topology = 35u; + CHECK(l2.draw(db)); + CHECK(l2.draw(da1)); // duplicate across second list -> deduplicated + // Unbuilt compute pipeline 10 (twice -> deduplicated). + Dispatch c{}; + c.pipeline = 10; + c.x = c.y = c.z = 1; + CHECK(l2.dispatch(c)); + CHECK(l2.dispatch(c)); + CHECK(l1.close() && l2.close()); + + const CommandList* batch[2] = {&l1, &l2}; + PipelineCompiles compiles; + collect_unbuilt_pipelines(batch, env.vk, compiles); + CHECK(compiles.size() == 4); // 3 graphics variants + 1 compute + VkPipeline out = VK_NULL_HANDLE; + CHECK(!compiles.lookup(&env.gfx[1], nullptr, 0u, out)); + CHECK(compiles.lookup(&env.gfx[10], nullptr, (1u << 1) | GraphicsPipeline::unbound_depth, out)); + CHECK(compiles.lookup(&env.gfx[10], nullptr, GraphicsPipeline::unbound_depth, out)); + CHECK(compiles.lookup(&env.gfx[11], nullptr, GraphicsPipeline::rectangle_stage, out)); + CHECK(compiles.lookup(nullptr, &env.comp[10], 0u, out)); + } + + // 4b: Closed pool and mid-batch cancel/drop_queued race safety (zero deadlocks, 100% job completion). + { + // Closed pool: every submit returns false -> calling thread finishes all jobs cleanly. + MiniCompilePool closed_pool(4); + closed_pool.close_and_drop(); + auto closed_runner = make_pool_batch_runner(closed_pool, 4); + constexpr std::size_t kClosedJobs = 32; + std::array, kClosedJobs> closed_hits{}; + for (auto& h : closed_hits) h.store(0, std::memory_order_relaxed); + closed_runner(kClosedJobs, [&](std::size_t i) { closed_hits[i].fetch_add(1, std::memory_order_relaxed); }); + for (std::size_t i = 0; i < kClosedJobs; ++i) CHECK(closed_hits[i].load() == 1); + + // Concurrent mid-batch drop_queued / close_and_drop while helpers are active: zero deadlocks, exact-once runs. + for (int iter = 0; iter < 50; ++iter) { + MiniCompilePool pool(4); + auto runner = make_pool_batch_runner(pool, 4); + constexpr std::size_t kJobs = 48; + std::array, kJobs> hits{}; + for (auto& h : hits) h.store(0, std::memory_order_relaxed); + std::atomic started{false}; + std::thread dropper([&] { + while (!started.load(std::memory_order_acquire)) std::this_thread::yield(); + if (iter % 2 == 0) pool.drop_queued(); + else pool.close_and_drop(); + }); + runner(kJobs, [&](std::size_t i) { + started.store(true, std::memory_order_release); + hits[i].fetch_add(1, std::memory_order_relaxed); + if (i < 4) std::this_thread::sleep_for(std::chrono::microseconds(50)); + }); + dropper.join(); + for (std::size_t i = 0; i < kJobs; ++i) CHECK(hits[i].load() == 1); + } + + // 4b-busy: All pool workers blocked on unrelated long jobs — calling thread must finish all batch jobs and + // cancel unstarted queued helpers immediately without stalling behind the busy workers! + { + MiniCompilePool busy_pool(2); + std::mutex gate_mu; + std::condition_variable gate_cv; + bool release_unrelated = false; + std::atomic blocked_workers{0}; + int unrelated_owner_a = 0, unrelated_owner_b = 0; + const auto blocker = [&] { + blocked_workers.fetch_add(1, std::memory_order_acq_rel); + std::unique_lock lock(gate_mu); + gate_cv.wait(lock, [&] { return release_unrelated; }); + }; + CHECK(busy_pool.submit(&unrelated_owner_a, blocker)); + CHECK(busy_pool.submit(&unrelated_owner_b, blocker)); + while (blocked_workers.load(std::memory_order_acquire) < 2) std::this_thread::yield(); + + auto runner = make_pool_batch_runner(busy_pool, 4); + constexpr std::size_t kFastJobs = 8; + std::array, kFastJobs> fast_hits{}; + for (auto& h : fast_hits) h.store(0, std::memory_order_relaxed); + const auto t0 = std::chrono::steady_clock::now(); + runner(kFastJobs, [&](std::size_t i) { fast_hits[i].fetch_add(1, std::memory_order_relaxed); }); + const auto elapsed_ms = + std::chrono::duration_cast(std::chrono::steady_clock::now() - t0).count(); + for (std::size_t i = 0; i < kFastJobs; ++i) CHECK(fast_hits[i].load() == 1); + CHECK(elapsed_ms < 250); + + { + std::lock_guard lock(gate_mu); + release_unrelated = true; + } + gate_cv.notify_all(); + } + } + + // 4c: Live VulkanQueue::execute() batch-parallel pre-compile of 4 unbuilt graphics PSOs (with duplicates): + // compiles concurrently (max_in_flight >= 2), builds each PSO once, executes all draws with zero skips. + { + vktest::Device dev; + const auto status = dev.initialize(); + if (status == vktest::DeviceStatus::unavailable) { + std::puts("SKIP: no Vulkan device for live batch-parallel pipeline compile test"); + return; + } + CHECK(status == vktest::DeviceStatus::ready); + if (status != vktest::DeviceStatus::ready) return; + + const auto vkCreateShaderModule = dev.fn("vkCreateShaderModule"); + const auto vkDestroyShaderModule = dev.fn("vkDestroyShaderModule"); + const auto vkCreatePipelineLayout = dev.fn("vkCreatePipelineLayout"); + const auto vkDestroyPipelineLayout = dev.fn("vkDestroyPipelineLayout"); + const auto vkCreateGraphicsPipelines = dev.fn("vkCreateGraphicsPipelines"); + const auto vkDestroyPipeline = dev.fn("vkDestroyPipeline"); + + constexpr std::uint32_t kW = 8, kH = 8, kPitch = 256; + const VkImage color_img = + dev.image(VK_FORMAT_R8G8B8A8_UNORM, kW, kH, 1, + VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | + VK_IMAGE_USAGE_TRANSFER_DST_BIT); + void* rb_pixels = nullptr; + const VkBuffer rb_buf = dev.buffer(kH * kPitch, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &rb_pixels); + void* vb_mapped = nullptr; + const VkBuffer vb = dev.buffer(256, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, &vb_mapped); + CHECK(color_img && rb_buf && rb_pixels && vb && vb_mapped); + if (!color_img || !rb_buf || !vb) return; + std::memset(rb_pixels, 0, kH * kPitch); + const float verts[12] = {-1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f}; + std::memcpy(vb_mapped, verts, sizeof(verts)); + + const VkPushConstantRange gfx_pcr{VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, + sizeof(ShaderUserData)}; + VkPipelineLayoutCreateInfo gpl_ci{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; + gpl_ci.pushConstantRangeCount = 1; + gpl_ci.pPushConstantRanges = &gfx_pcr; + VkPipelineLayout gfx_layout = VK_NULL_HANDLE; + CHECK(vkCreatePipelineLayout(dev.device, &gpl_ci, nullptr, &gfx_layout) == VK_SUCCESS); + + const auto vs_spv = build_vs_spirv(); + const auto fs_spv = build_fs_spirv(); + const auto make_mod = [&](const std::vector& spv) { + VkShaderModuleCreateInfo ci{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + ci.codeSize = spv.size() * sizeof(std::uint32_t); + ci.pCode = spv.data(); + VkShaderModule m = VK_NULL_HANDLE; + CHECK(vkCreateShaderModule(dev.device, &ci, nullptr, &m) == VK_SUCCESS); + return m; + }; + const VkShaderModule vs_mod = make_mod(vs_spv); + const VkShaderModule fs_mod = make_mod(fs_spv); + + const auto build_real_gfx_pipe = [&]() -> VkPipeline { + VkPipelineShaderStageCreateInfo stages[2]{ + {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}, + {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}, + }; + stages[0].stage = VK_SHADER_STAGE_VERTEX_BIT; + stages[0].module = vs_mod; + stages[0].pName = "main"; + stages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; + stages[1].module = fs_mod; + stages[1].pName = "main"; + + VkVertexInputBindingDescription vbind{0, 8, VK_VERTEX_INPUT_RATE_VERTEX}; + VkVertexInputAttributeDescription vattr{0, 0, VK_FORMAT_R32G32_SFLOAT, 0}; + VkPipelineVertexInputStateCreateInfo vi{VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO}; + vi.vertexBindingDescriptionCount = 1; + vi.pVertexBindingDescriptions = &vbind; + vi.vertexAttributeDescriptionCount = 1; + vi.pVertexAttributeDescriptions = &vattr; + + VkPipelineInputAssemblyStateCreateInfo ia{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO}; + ia.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; + VkPipelineViewportStateCreateInfo vp{VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO}; + vp.viewportCount = 1; + vp.scissorCount = 1; + VkPipelineRasterizationStateCreateInfo rs{VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO}; + rs.polygonMode = VK_POLYGON_MODE_FILL; + rs.cullMode = VK_CULL_MODE_NONE; + rs.frontFace = VK_FRONT_FACE_CLOCKWISE; + rs.lineWidth = 1.0f; + VkPipelineMultisampleStateCreateInfo ms{VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO}; + ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; + VkPipelineColorBlendAttachmentState cba{}; + cba.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | + VK_COLOR_COMPONENT_A_BIT; + VkPipelineColorBlendStateCreateInfo cb_state{VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO}; + cb_state.attachmentCount = 1; + cb_state.pAttachments = &cba; + const VkDynamicState dyn_states[] = { + VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR, + VK_DYNAMIC_STATE_PRIMITIVE_TOPOLOGY, VK_DYNAMIC_STATE_PRIMITIVE_RESTART_ENABLE, + VK_DYNAMIC_STATE_STENCIL_REFERENCE, VK_DYNAMIC_STATE_BLEND_CONSTANTS, + VK_DYNAMIC_STATE_VERTEX_INPUT_BINDING_STRIDE, + }; + VkPipelineDynamicStateCreateInfo dyn{VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO}; + dyn.dynamicStateCount = static_cast(std::size(dyn_states)); + dyn.pDynamicStates = dyn_states; + const VkFormat color_fmt = VK_FORMAT_R8G8B8A8_UNORM; + VkPipelineRenderingCreateInfo rend{VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO}; + rend.colorAttachmentCount = 1; + rend.pColorAttachmentFormats = &color_fmt; + VkGraphicsPipelineCreateInfo gp_ci{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, &rend}; + gp_ci.stageCount = 2; + gp_ci.pStages = stages; + gp_ci.pVertexInputState = &vi; + gp_ci.pInputAssemblyState = &ia; + gp_ci.pViewportState = &vp; + gp_ci.pRasterizationState = &rs; + gp_ci.pMultisampleState = &ms; + gp_ci.pColorBlendState = &cb_state; + gp_ci.pDynamicState = &dyn; + gp_ci.layout = gfx_layout; + VkPipeline pipe = VK_NULL_HANDLE; + CHECK(vkCreateGraphicsPipelines(dev.device, VK_NULL_HANDLE, 1, &gp_ci, nullptr, &pipe) == VK_SUCCESS); + return pipe; + }; + + std::array created_pipes{}; + { + VulkanContext ctx(dev.device_proc, dev.device, true, dev.conditional_rendering, dev.buffer_device_address); + CHECK(ctx.loaded()); + MiniCompilePool pool(4); + ctx.set_batch_compile_runner(make_pool_batch_runner(pool, 4)); + + constexpr ResourceId kRtId = 1, kVbId = 2, kRbId = 3; + constexpr std::uint64_t kVbVa = 0x10000ull; + ResourceBinding rt_b{}; + rt_b.image = color_img; + rt_b.format = VK_FORMAT_R8G8B8A8_UNORM; + rt_b.aspects = VK_IMAGE_ASPECT_COLOR_BIT; + rt_b.width = kW; + rt_b.height = kH; + rt_b.color_attachment = true; + ctx.add_resource(kRtId, rt_b, VK_IMAGE_LAYOUT_UNDEFINED); + + ResourceBinding vb_b{}; + vb_b.buffer = vb; + vb_b.size = 256; + vb_b.va = kVbVa; + ctx.add_resource(kVbId, vb_b); + + ResourceBinding rb_b{}; + rb_b.buffer = rb_buf; + rb_b.size = kH * kPitch; + rb_b.host_readable = true; + ctx.add_resource(kRbId, rb_b); + + std::atomic in_flight{0}; + std::atomic max_in_flight{0}; + std::array, 4> compile_calls{}; + for (auto& c : compile_calls) c.store(0, std::memory_order_relaxed); + std::mutex pipe_mu; + + for (std::size_t idx = 0; idx < 4; ++idx) { + GraphicsPipeline gp{}; + gp.pipeline = VK_NULL_HANDLE; + gp.layout = gfx_layout; + gp.push_stages = VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT; + gp.color_formats = {VK_FORMAT_R8G8B8A8_UNORM}; + gp.vertex_slots = 0b1; + gp.built = [&, idx](std::uint32_t) -> VkPipeline { + std::lock_guard lock(pipe_mu); + return created_pipes[idx]; + }; + gp.variant = [&, idx](std::uint32_t) -> VkPipeline { + compile_calls[idx].fetch_add(1, std::memory_order_relaxed); + const unsigned cur = in_flight.fetch_add(1, std::memory_order_acq_rel) + 1; + unsigned prev = max_in_flight.load(std::memory_order_relaxed); + while (cur > prev && !max_in_flight.compare_exchange_weak(prev, cur, std::memory_order_acq_rel)) {} + // Brief wait so at least 2 threads overlap concurrently inside variant(). + const auto until = std::chrono::steady_clock::now() + std::chrono::milliseconds(50); + while (max_in_flight.load(std::memory_order_acquire) < 2 && + std::chrono::steady_clock::now() < until) + std::this_thread::yield(); + VkPipeline p = build_real_gfx_pipe(); + { + std::lock_guard lock(pipe_mu); + created_pipes[idx] = p; + } + in_flight.fetch_sub(1, std::memory_order_acq_rel); + return p; + }; + ctx.add_graphics_pipeline(300 + idx, gp); + } + + VulkanQueue queue(ctx, dev.queue, dev.family, VulkanQueue::QueueKind::direct); + CHECK(queue.ok()); + + auto make_quad = [&](std::uintptr_t pso, float r, float g, float b, std::int32_t x0, std::int32_t y0, + std::int32_t x1, std::int32_t y1) { + Draw d{}; + d.pipeline = pso; + auto views = std::make_shared(); + views->render_targets[0] = {kRtId, 0, 0, 1}; + views->render_target_count = 1; + views->vertex_buffers[0] = {kVbVa, 256, 8}; + d.views = std::move(views); + d.indexed = false; + d.topology = 4; + d.viewport = {0.0f, 0.0f, float(kW), float(kH), 0.0f, 1.0f}; + d.scissor = {x0, y0, x1, y1}; + d.blend_factor = {1, 1, 1, 1}; + d.count = 6; + d.instances = 1; + d.user_data[0] = float_bits(r); + d.user_data[1] = float_bits(g); + d.user_data[2] = float_bits(b); + d.user_data[3] = float_bits(1.0f); + d.user_data[8] = float_bits(1.0f); + return d; + }; + + // Two lists across one execute() batch using all 4 unbuilt PSOs (with duplicate draws). + CommandList list1, list2; + CHECK(list1.transition({kRtId, all_subresources, d3d12_state::common, d3d12_state::render_target})); + CHECK(list1.draw(make_quad(300, 1.0f, 0.0f, 0.0f, 0, 0, 4, 4))); + CHECK(list1.draw(make_quad(300, 1.0f, 0.0f, 0.0f, 0, 0, 4, 4))); // duplicate PSO 300 + CHECK(list1.draw(make_quad(301, 0.0f, 1.0f, 0.0f, 4, 0, 8, 4))); + CHECK(list1.close()); + + CHECK(list2.draw(make_quad(302, 0.0f, 0.0f, 1.0f, 0, 4, 4, 8))); + CHECK(list2.draw(make_quad(303, 1.0f, 1.0f, 0.0f, 4, 4, 8, 8))); + CHECK(list2.draw(make_quad(301, 0.0f, 1.0f, 0.0f, 4, 0, 8, 4))); // duplicate across list boundary + CHECK(list2.transition({kRtId, all_subresources, d3d12_state::render_target, d3d12_state::copy_source})); + CopyTexture readback{}; + readback.dst = {kRbId, true, 0, 0, kW, kH, 1, kPitch}; + readback.src = {kRtId, false, 0, 0, 0, 0, 0, 0}; + CHECK(list2.copy_texture(readback)); + CHECK(list2.close()); + + const CommandList* batch[2] = {&list1, &list2}; + CHECK(queue.execute(batch) == ReplayResult::success); + CHECK(queue.idle()); + + CHECK(max_in_flight.load(std::memory_order_acquire) >= 2); + for (std::size_t idx = 0; idx < 4; ++idx) CHECK(compile_calls[idx].load() == 1); + + const auto* px = static_cast(rb_pixels); + const auto check_px = [&](std::uint32_t x, std::uint32_t y, std::uint8_t r, std::uint8_t g, std::uint8_t b, + std::uint8_t a) { + const std::size_t off = std::size_t(y) * kPitch + std::size_t(x) * 4; + CHECK(px[off] == r && px[off + 1] == g && px[off + 2] == b && px[off + 3] == a); + }; + check_px(1, 1, 255, 0, 0, 255); + check_px(6, 1, 0, 255, 0, 255); + check_px(1, 6, 0, 0, 255, 255); + check_px(6, 6, 255, 255, 0, 255); + ctx.set_batch_compile_runner({}); + } + + for (VkPipeline p : created_pipes) + if (p) vkDestroyPipeline(dev.device, p, nullptr); + if (vs_mod) vkDestroyShaderModule(dev.device, vs_mod, nullptr); + if (fs_mod) vkDestroyShaderModule(dev.device, fs_mod, nullptr); + if (gfx_layout) vkDestroyPipelineLayout(dev.device, gfx_layout, nullptr); + CHECK(dev.validation_errors() == 0); + std::puts("batch-parallel sync pipeline compile (collect_unbuilt, concurrency, closed/drop race, GPU): ok"); + } +} + +// --------------------------------------------------------------------------------------------------------------- +// Part 5: Dynamic rendering scope batching, LayoutTracker no-op elision, PrepareViewCache & PreparedList reuse + +void test_rendering_scope_batching_and_fast_paths() { + MockEnv env; + constexpr ResourceId kColor2 = 100; + constexpr ResourceId kColorArray = 101; + constexpr ResourceId kColorGeneral = 102; + constexpr ResourceId kDepth = 103; + constexpr ResourceId kDepth2 = 104; + + ResourceBinding color2 = env.res[MockEnv::kColor]; + color2.image = fake_handle(0x110); + color2.mip_levels = 2; + env.res[kColor2] = color2; + + ResourceBinding color_arr = env.res[MockEnv::kColor]; + color_arr.image = fake_handle(0x111); + color_arr.array_layers = 4; + env.res[kColorArray] = color_arr; + + ResourceBinding color_gen = env.res[MockEnv::kColor]; + color_gen.image = fake_handle(0x112); + color_gen.simultaneous_access = true; + env.res[kColorGeneral] = color_gen; + + ResourceBinding depth{}; + depth.image = fake_handle(0x113); + depth.format = VK_FORMAT_D24_UNORM_S8_UINT; + depth.aspects = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; + depth.width = depth.height = 64; + env.res[kDepth] = depth; + + ResourceBinding depth2 = depth; + depth2.image = fake_handle(0x114); + env.res[kDepth2] = depth2; + + // Distinct image views per (image, mip, layer, layerCount, format) so view changes are observable. + std::size_t view_calls = 0; + env.vk.image_view = [&view_calls](const ResourceBinding& r, const VkImageSubresourceRange& range) { + ++view_calls; + std::uintptr_t h = reinterpret_cast(r.image) * 1315423911ull; + h ^= std::uintptr_t(range.baseMipLevel) << 8; + h ^= std::uintptr_t(range.baseArrayLayer) << 12; + h ^= std::uintptr_t(range.layerCount) << 16; + h ^= std::uintptr_t(r.format) << 20; + return fake_handle(h ? h : 1); + }; + + // Additional pipelines for depth_aspects, reads_glc_buffer, multi-RT, and attachment-less draws. + GraphicsPipeline g_depth_only = env.gfx[1]; + g_depth_only.pipeline = fake_handle(0x710); + g_depth_only.depth_format = VK_FORMAT_D24_UNORM_S8_UINT; + g_depth_only.depth_aspects = VK_IMAGE_ASPECT_DEPTH_BIT; + env.gfx[10] = g_depth_only; + + GraphicsPipeline g_depth_stencil = g_depth_only; + g_depth_stencil.pipeline = fake_handle(0x711); + g_depth_stencil.depth_aspects = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; + env.gfx[11] = g_depth_stencil; + + GraphicsPipeline g_glc = env.gfx[1]; + g_glc.pipeline = fake_handle(0x712); + g_glc.reads_glc_buffer = true; + env.gfx[12] = g_glc; + + GraphicsPipeline g_mrt2 = env.gfx[1]; + g_mrt2.pipeline = fake_handle(0x713); + g_mrt2.color_formats = {VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM}; + g_mrt2.depth_format = VK_FORMAT_D24_UNORM_S8_UINT; + g_mrt2.depth_aspects = VK_IMAGE_ASPECT_DEPTH_BIT; + env.gfx[13] = g_mrt2; + + GraphicsPipeline g_no_att = env.gfx[1]; + g_no_att.pipeline = fake_handle(0x714); + g_no_att.color_formats.clear(); + env.gfx[14] = g_no_att; + + const auto resolve = [&env](ResourceId id) { return env.resolve(id); }; + const VkCommandBuffer cb = fake_handle(0x1); + + // 5a: Consecutive MRT + DSV draws sharing targets (even across different pipelines) merge into 1 scope + 1 barrier; + // PrepareViewCache calls vk.image_view only once per unique attachment view across all draws. + { + CommandList list; + Draw d = env.base_draw(13, true); + auto v = std::make_shared(*d.views); + v->render_targets[0] = {MockEnv::kColor, 0, 0, 1}; + v->render_targets[1] = {kColor2, 0, 0, 1}; + v->render_target_count = 2; + d.views = v; + d.depth = {kDepth, 0, 0, 1}; + for (int k = 0; k < 6; ++k) { + d.user_data[0] = std::uint32_t(k); + CHECK(list.draw(d)); + } + CHECK(list.close()); + + view_calls = 0; + PreparedList prep; + CHECK(prepare(list, resolve, env.vk, prep) == ReplayResult::success); + CHECK(view_calls == 3); // 2 color views + 1 depth view cached across all 6 draws (instead of 18) + + g_mc.reset(); + emit(prep, cb, env.vk); + CHECK(g_mc.draws == 6); + CHECK(g_mc.begin_rendering == 1 && g_mc.end_rendering == 1); + CHECK(g_mc.barriers == 1); // coalesced single attachment barrier for 2 RTs + 1 DSV + } + + // 5b: Changing color target, mip/view, depth_aspects, layers, or area closes and reopens rendering scope. + { + // Color target change (kColor -> kColor2) + CommandList list; + Draw d1 = env.base_draw(1, false); + Draw d2 = env.base_draw(1, false); + auto v2 = std::make_shared(*d2.views); + v2->render_targets[0] = {kColor2, 0, 0, 1}; + d2.views = v2; + // Same kColor2, different mip (mip 1 -> different view, range, and area 32x32) + Draw d3 = env.base_draw(1, false); + auto v3 = std::make_shared(*d3.views); + v3->render_targets[0] = {kColor2, 1, 0, 1}; + d3.views = v3; + // Different layerCount (1 layer -> 2 layers on kColorArray) + Draw d4 = env.base_draw(1, false); + auto v4 = std::make_shared(*d4.views); + v4->render_targets[0] = {kColorArray, 0, 0, 1}; + d4.views = v4; + Draw d5 = env.base_draw(1, false); + auto v5 = std::make_shared(*d5.views); + v5->render_targets[0] = {kColorArray, 0, 0, 2}; + d5.views = v5; + // Different depth_aspects on the SAME depth target (DEPTH -> DEPTH|STENCIL) + Draw d6 = env.base_draw(10, false); + d6.depth = {kDepth, 0, 0, 1}; + Draw d7 = env.base_draw(11, false); + d7.depth = {kDepth, 0, 0, 1}; + // Attachment-less draws with different viewport areas (64x64 -> 32x32) + Draw d8 = env.base_draw(14, false); + auto v8 = std::make_shared(*d8.views); + v8->render_target_count = 0; + d8.views = v8; + d8.viewport = {0, 0, 64, 64, 0, 1}; + Draw d9 = env.base_draw(14, false); + auto v9 = std::make_shared(*d9.views); + v9->render_target_count = 0; + d9.views = v9; + d9.viewport = {0, 0, 32, 32, 0, 1}; + // Different layout (OPTIMAL vs simultaneous_access GENERAL) + Draw d10 = env.base_draw(1, false); + auto v10 = std::make_shared(*d10.views); + v10->render_targets[0] = {kColorGeneral, 0, 0, 1}; + d10.views = v10; + + CHECK(list.draw(d1) && list.draw(d2) && list.draw(d3) && list.draw(d4) && list.draw(d5)); + CHECK(list.draw(d6) && list.draw(d7) && list.draw(d8) && list.draw(d9) && list.draw(d10)); + CHECK(list.close()); + + PreparedList prep; + CHECK(prepare(list, resolve, env.vk, prep) == ReplayResult::success); + g_mc.reset(); + emit(prep, cb, env.vk); + CHECK(g_mc.draws == 10); + CHECK(g_mc.begin_rendering == 10 && g_mc.end_rendering == 10); + } + + // 5c: Exact event ordering at mandatory scope-closing boundaries: + // reads_glc_buffer, indirect_clamp, quad_indices, non-draw (dispatch/barrier/clear), query, and predication. + { + static std::vector ev; + ev.clear(); + ReplayFunctions trace_vk = env.vk; + trace_vk.begin_rendering = +[](VkCommandBuffer, const VkRenderingInfo*) { ev.push_back("begin_rp"); }; + trace_vk.end_rendering = +[](VkCommandBuffer) { ev.push_back("end_rp"); }; + trace_vk.draw = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, std::uint32_t, std::uint32_t) { + ev.push_back("draw"); + }; + trace_vk.draw_indexed = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, std::uint32_t, std::int32_t, + std::uint32_t) { ev.push_back("draw_idx"); }; + trace_vk.draw_indirect = +[](VkCommandBuffer, VkBuffer, VkDeviceSize, std::uint32_t, std::uint32_t) { + ev.push_back("draw_ind"); + }; + trace_vk.pipeline_barrier = +[](VkCommandBuffer, VkPipelineStageFlags, VkPipelineStageFlags dst, + VkDependencyFlags, std::uint32_t, const VkMemoryBarrier*, std::uint32_t, + const VkBufferMemoryBarrier*, std::uint32_t, const VkImageMemoryBarrier*) { + if (dst == VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) ev.push_back("glc_barrier"); + }; + trace_vk.emit_indirect_clamp = [](VkCommandBuffer, const ClampedIndirect&) { ev.push_back("clamp"); }; + trace_vk.emit_quad_indices = [](VkCommandBuffer, const QuadIndexExpansion&) { ev.push_back("quad_expand"); }; + trace_vk.dispatch = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, std::uint32_t) { + ev.push_back("dispatch"); + }; + trace_vk.begin_query = +[](VkCommandBuffer, VkQueryPool, std::uint32_t, VkQueryControlFlags) { + ev.push_back("begin_q"); + }; + trace_vk.end_query = +[](VkCommandBuffer, VkQueryPool, std::uint32_t) { ev.push_back("end_q"); }; + trace_vk.begin_conditional_rendering = +[](VkCommandBuffer, const VkConditionalRenderingBeginInfoEXT*) { + ev.push_back("begin_pred"); + }; + trace_vk.end_conditional_rendering = +[](VkCommandBuffer) { ev.push_back("end_pred"); }; + + CommandList list; + const Draw d = env.base_draw(1, false); + const Draw d_glc = env.base_draw(12, false); + Draw d_quad = env.base_draw(1, true); + d_quad.topology = topology_quad_list; + d_quad.count = 8; + IndirectDrawArgs ind{}; + ind.argument_buffer = MockEnv::kBuf; + ind.stride = 16; + ind.max_count = 1; + Dispatch c{}; + c.pipeline = 1; + c.x = c.y = c.z = 1; + + // 2 merged draws -> reads_glc_buffer -> quad_expand -> indirect_clamp -> dispatch -> query -> predication + CHECK(list.draw(d)); + CHECK(list.draw(d)); + CHECK(list.draw(d_glc)); + CHECK(list.draw(d_quad)); + CHECK(list.draw_indirect(Draw{d}, ind)); + CHECK(list.dispatch(c)); + CHECK(list.begin_query({MockEnv::kOccHeap, d3d12_query::occlusion, 0})); + CHECK(list.draw(d)); + CHECK(list.draw(d)); + CHECK(list.end_query({MockEnv::kOccHeap, d3d12_query::occlusion, 0})); + CHECK(list.set_predication({MockEnv::kPred, 0, d3d12_predication::equal_zero})); + CHECK(list.draw(d)); + CHECK(list.draw(d)); + CHECK(list.close()); + + PreparedList prep; + CHECK(prepare(list, resolve, trace_vk, prep) == ReplayResult::success); + QueryReplay qr; + CHECK(qr.plan(prep) == ReplayResult::success); + emit(prep, cb, trace_vk); + + const std::vector expected = { + "begin_rp", "draw", "draw", "end_rp", + "glc_barrier", "begin_rp", "draw", "end_rp", + "quad_expand", "begin_rp", "draw_idx", "end_rp", + "clamp", "begin_rp", "draw_ind", "end_rp", + "dispatch", + "begin_q", "begin_rp", "draw", "draw", "end_rp", "end_q", + "begin_pred", "begin_rp", "draw", "draw", "end_rp", "end_pred", + }; + if (ev != expected) { + std::fprintf(stderr, "FAIL scope boundary event order (got %zu vs expected %zu):\n got: ", ev.size(), + expected.size()); + for (const auto& s : ev) std::fprintf(stderr, "%s ", s.c_str()); + std::fprintf(stderr, "\n want: "); + for (const auto& s : expected) std::fprintf(stderr, "%s ", s.c_str()); + std::fprintf(stderr, "\n"); + ++g_failures; + } + } + + // 5d: No-op LayoutTracker::set() elision (0 journal entries when unchanged; exact rollback when changed). + { + LayoutTracker tracker(true); + ResourceBinding img{}; + img.image = fake_handle(0x120); + img.format = VK_FORMAT_R8G8B8A8_UNORM; + img.aspects = VK_IMAGE_ASPECT_COLOR_BIT; + img.mip_levels = 3; + img.array_layers = 2; + tracker.track(42, img, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); + + tracker.begin(); + CHECK(tracker.journal_size() == 0); + // No-op set on whole image and on single subresource must NOT journal anything. + tracker.set(42, {VK_IMAGE_ASPECT_COLOR_BIT, 0, VK_REMAINING_MIP_LEVELS, 0, VK_REMAINING_ARRAY_LAYERS}, + VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); + tracker.set(42, {VK_IMAGE_ASPECT_COLOR_BIT, 1, 1, 1, 1}, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); + CHECK(tracker.journal_size() == 0); + + // Actual change on mip 1 layer 0 journals once. + tracker.set(42, {VK_IMAGE_ASPECT_COLOR_BIT, 1, 1, 0, 1}, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); + CHECK(tracker.journal_size() == 1); + CHECK(tracker.layout(42, 1) == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); + CHECK(tracker.layout(42, 0) == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); + + // Rollback restores mip 1 layer 0 to COLOR_ATTACHMENT_OPTIMAL. + tracker.rollback(); + CHECK(tracker.journal_size() == 0); + CHECK(tracker.layout(42, 1) == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); + + // Commit persists the change. + tracker.begin(); + tracker.set(42, {VK_IMAGE_ASPECT_COLOR_BIT, 2, 1, 1, 1}, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); + CHECK(tracker.journal_size() == 1); + tracker.commit(); + CHECK(tracker.journal_size() == 0); + CHECK(tracker.layout(42, 5) == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); + } + + // 5e: PreparedList reuse across mixed lists (draws -> copies/clears -> draws -> shorter list) has no stale state. + { + PreparedList reused; + CommandList l1, l2, l3; + const Draw d = env.base_draw(1, true); + CHECK(l1.draw(d) && l1.draw(d) && l1.draw(d) && l1.close()); + CHECK(l2.transition({MockEnv::kColor, all_subresources, d3d12_state::common, d3d12_state::render_target})); + CHECK(l2.clear_render_target({MockEnv::kColor, 0, 0, 1}, {0, 0, 0, 1})); + CHECK(l2.copy_buffer({MockEnv::kBuf, 0, MockEnv::kResults, 0, 64})); + CHECK(l2.draw(d)); + CHECK(l2.close()); + CHECK(l3.draw(d) && l3.close()); + + CHECK(prepare(l1, resolve, env.vk, reused) == ReplayResult::success); + CHECK(reused.commands.size() == 3 && reused.draw_count == 3); + CHECK(prepare(l2, resolve, env.vk, reused) == ReplayResult::success); + CHECK(reused.commands.size() == 4 && reused.draw_count == 1); + CHECK(!reused.commands[2].buffer_copies.empty()); + CHECK(reused.commands[3].buffer_copies.empty()); + CHECK(prepare(l3, resolve, env.vk, reused) == ReplayResult::success); + CHECK(reused.commands.size() == 1 && reused.draw_count == 1); + CHECK(reused.commands[0].buffer_copies.empty()); + g_mc.reset(); + emit(reused, cb, env.vk); + CHECK(g_mc.draws == 1 && g_mc.begin_rendering == 1 && g_mc.end_rendering == 1); + } + + std::puts("rendering scope batching, LayoutTracker no-op elision & prepare fast path: ok"); +} + +// --------------------------------------------------------------------------------------------------------------- +// Part 6: Round 8 WS3 replay floor cuts: CommandList::close() cached summary, EmitScratch reuse, +// VulkanContext::unbuilt_sync_pipelines_ atomic fast-path + pass-0 fallback, and BindlessSet clean atomics. +void test_r8_replay_floor_cuts() { + // 6a: CommandList::close() caches predication_captures, runs_shaders, has_rt_ds_clear, and reset() clears them. + { + CommandList l; + CHECK(l.close()); + CHECK(l.commands().empty() && l.predication_captures() == 0 && !l.runs_shaders() && !l.has_rt_ds_clear()); + + CHECK(l.reset()); + CHECK(l.uav_barrier({})); + CHECK(l.copy_buffer({1, 0, 2, 0, 64})); + CHECK(l.set_predication({3, 0, d3d12_predication::equal_zero})); + CHECK(l.set_predication({0, 0, 0})); // turning predication off does NOT increment captures + CHECK(l.set_predication({3, 8, d3d12_predication::not_equal_zero})); + CHECK(l.close()); + CHECK(l.predication_captures() == 2 && !l.runs_shaders() && !l.has_rt_ds_clear()); + + CHECK(l.reset()); + CHECK(l.predication_captures() == 0 && !l.runs_shaders() && !l.has_rt_ds_clear()); + TargetView tv{}; + tv.resource = 1; + tv.layer_count = 1; + CHECK(l.clear_render_target(tv, ClearColor{})); + Dispatch d{}; + d.pipeline = 1; + d.x = d.y = d.z = 1; + CHECK(l.dispatch(d)); + CHECK(l.close()); + CHECK(l.predication_captures() == 0 && l.runs_shaders() && l.has_rt_ds_clear()); + + CHECK(l.reset()); + CHECK(l.clear_depth_stencil(tv, clear_depth, 1.0f, 0)); + CHECK(l.close()); + CHECK(!l.runs_shaders() && l.has_rt_ds_clear()); + + CHECK(l.reset()); + ExecuteIndirect ei{}; + ei.kind = IndirectKind::dispatch; + ei.argument_buffer = 2; + ei.stride = 16; + ei.max_count = 1; + CHECK(l.execute_indirect(ei)); + CHECK(l.close()); + CHECK(l.runs_shaders() && !l.has_rt_ds_clear()); + } + + // 6b: EmitScratch reuse across repeated emit() calls preserves vector capacity without reallocating. + { + MockEnv env; + const auto resolve = [&env](ResourceId id) { return env.resolve(id); }; + const VkCommandBuffer cb = fake_handle(0x2); + + CommandList list; + const Draw d = env.base_draw(1, false); + CHECK(list.draw(d) && list.close()); + PreparedList prep; + CHECK(prepare(list, resolve, env.vk, prep) == ReplayResult::success); + + EmitScratch scratch; + scratch.many_barriers.reserve(8); + const void* orig_ptr = scratch.many_barriers.data(); + const std::size_t orig_cap = scratch.many_barriers.capacity(); + g_mc.reset(); + ReplayStateCache cache; + emit(prep, cb, env.vk, nullptr, nullptr, &cache, &scratch); + emit(prep, cb, env.vk, nullptr, nullptr, &cache, &scratch); + CHECK(g_mc.draws == 2); + CHECK(scratch.many_barriers.data() == orig_ptr && scratch.many_barriers.capacity() == orig_cap); + } + + // 6c & 6d: Live Vulkan checks for unbuilt_sync_pipelines_ atomic fast-path (+ pass-0 fallback) and BindlessSet + // lock-free clean atomics (needs_prepare / current_set / needs_commit). + vktest::Device dev; + if (!dev.create()) { + std::puts("r8 replay floor cuts (CPU): ok (GPU part skipped: no Vulkan device)"); + return; + } + + // 6c: VulkanContext unbuilt_sync_pipelines_ atomic fast-path. + { + VulkanContext ctx(dev.device_proc, dev.device, true, dev.conditional_rendering, dev.buffer_device_address); + CHECK(ctx.loaded()); + CHECK(!ctx.has_unbuilt_sync_pipelines()); + + // Pre-built pipeline does NOT arm unbuilt_sync_pipelines_. + ComputePipeline prebuilt{}; + prebuilt.pipeline = fake_handle(0x900); + ctx.add_pipeline(1, prebuilt); + CHECK(!ctx.has_unbuilt_sync_pipelines()); + + // Unbuilt synchronous compute pipeline arms unbuilt_sync_pipelines_; building clears it back to 0. + bool is_built = false; + ComputePipeline lazy{}; + lazy.build_context = &is_built; + lazy.built = +[](void* ctx) -> VkPipeline { + return *static_cast(ctx) ? fake_handle(0x901) : VK_NULL_HANDLE; + }; + lazy.build = +[](void* ctx) -> VkPipeline { + *static_cast(ctx) = true; + return fake_handle(0x901); + }; + ctx.add_pipeline(2, lazy); + CHECK(ctx.has_unbuilt_sync_pipelines()); + ctx.note_sync_pipelines_built(1); + CHECK(!ctx.has_unbuilt_sync_pipelines()); + + // Unused unbuilt pipeline clears after kWarmEmptyScans consecutive empty scans with no new registrations. + ctx.add_pipeline(3, lazy); + CHECK(ctx.has_unbuilt_sync_pipelines()); + const std::uint64_t gen = ctx.sync_pipeline_gen(); + for (int i = 0; i < 16; ++i) ctx.note_empty_pipeline_scan(gen); + CHECK(!ctx.has_unbuilt_sync_pipelines()); + } + + // 6d: BindlessSet lock-free clean atomics (needs_prepare / current_set / needs_commit). + { + VkPhysicalDeviceMemoryProperties mem_props{}; + const auto get_mem = reinterpret_cast( + dev.instance_proc(dev.instance, "vkGetPhysicalDeviceMemoryProperties")); + CHECK(get_mem != nullptr); + get_mem(dev.physical, &mem_props); + + BindlessFeatures features{}; + features.update_after_bind = false; + features.partially_bound = false; + BindlessSet set(dev.device_proc, dev.device, mem_props, features); + CHECK(set.ok()); + CHECK(set.needs_prepare()); + CHECK(set.current_set() == set.set() && set.current_set() != VK_NULL_HANDLE); + CHECK(!set.needs_commit()); + + const auto create_pool = dev.fn("vkCreateCommandPool"); + const auto destroy_pool = dev.fn("vkDestroyCommandPool"); + const auto alloc_cb = dev.fn("vkAllocateCommandBuffers"); + const auto begin_cb = dev.fn("vkBeginCommandBuffer"); + const auto end_cb = dev.fn("vkEndCommandBuffer"); + const auto queue_submit = dev.fn("vkQueueSubmit"); + const auto queue_wait = dev.fn("vkQueueWaitIdle"); + + VkCommandPool pool = VK_NULL_HANDLE; + VkCommandPoolCreateInfo pci{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; + pci.queueFamilyIndex = dev.family; + pci.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; + CHECK(create_pool(dev.device, &pci, nullptr, &pool) == VK_SUCCESS); + VkCommandBuffer cb = VK_NULL_HANDLE; + VkCommandBufferAllocateInfo cai{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; + cai.commandPool = pool; + cai.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; + cai.commandBufferCount = 1; + CHECK(alloc_cb(dev.device, &cai, &cb) == VK_SUCCESS); + + auto record_and_submit = [&](auto&& fn) { + VkCommandBufferBeginInfo bi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; + bi.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + CHECK(begin_cb(cb, &bi) == VK_SUCCESS); + fn(cb); + CHECK(end_cb(cb) == VK_SUCCESS); + VkSubmitInfo si{VK_STRUCTURE_TYPE_SUBMIT_INFO}; + si.commandBufferCount = 1; + si.pCommandBuffers = &cb; + CHECK(queue_submit(dev.queue, 1, &si, VK_NULL_HANDLE) == VK_SUCCESS); + CHECK(queue_wait(dev.queue) == VK_SUCCESS); + }; + + // First flush: initializes fallbacks & uploads initial table -> needs_commit becomes true until result reported. + record_and_submit([&](VkCommandBuffer c) { + set.record_fallback_init(c); + CHECK(set.flush(c, 1)); + CHECK(set.needs_commit()); + }); + set.table_upload_result(true); + CHECK(!set.needs_commit()); + CHECK(!set.needs_prepare()); + CHECK(set.current_set() == set.set()); + + // Inserting a key dirties needs_prepare(); flushing + committing clears it back to false. + DescriptorKey key{}; + key[0] = 0x12345678u; + CHECK(set.insert_key(key, 0, 0)); + CHECK(set.needs_prepare()); + record_and_submit([&](VkCommandBuffer c) { + CHECK(set.flush(c, 2)); + CHECK(set.needs_commit()); + }); + set.table_upload_result(true); + CHECK(!set.needs_commit()); + CHECK(!set.needs_prepare()); + + // Replacing an existing key replaces the generation (updates current_set() and keeps needs_prepare() true + // while a retired generation waits for release_retired()). + const VkDescriptorSet old_set = set.current_set(); + CHECK(set.insert_key(key, 1, 0)); + CHECK(set.needs_prepare()); + record_and_submit([&](VkCommandBuffer c) { + CHECK(set.flush(c, 3)); + }); + set.table_upload_result(true); + CHECK(set.current_set() == set.set() && set.current_set() != old_set); + CHECK(set.has_retired() && set.needs_prepare()); // retired generation still pending release + set.release_retired(3); + CHECK(!set.has_retired() && !set.needs_prepare()); + + // Erasing a key dirties needs_prepare() again. + CHECK(set.erase_key(key)); + CHECK(set.needs_prepare()); + record_and_submit([&](VkCommandBuffer c) { + CHECK(set.flush(c, 4)); + }); + set.table_upload_result(true); + CHECK(!set.needs_prepare()); + + destroy_pool(dev.device, pool, nullptr); + CHECK(dev.validation_errors() == 0); + } + + std::puts("r8 replay floor cuts (CommandList summary, EmitScratch, unbuilt_sync_pipelines_, BindlessSet atomics): ok"); +} + +} // namespace + +int main() { + test_cpu_elision_and_invalidation(); + test_throughput_5000_draws(); + test_gpu_live_validation(); + test_batch_parallel_sync_pipeline_compile(); + test_rendering_scope_batching_and_fast_paths(); + test_r8_replay_floor_cuts(); + if (g_failures) { + std::fprintf(stderr, "replay_state_cache_test: %d failure(s)\n", g_failures); + return 1; + } + std::puts("replay_state_cache_test: ALL PASS"); + return 0; +} diff --git a/runtime/test/shader_library_test.cpp b/runtime/test/shader_library_test.cpp index ee49c48ebb..f3affd9d68 100644 --- a/runtime/test/shader_library_test.cpp +++ b/runtime/test/shader_library_test.cpp @@ -745,6 +745,50 @@ int main() { CHECK(!library.load(dir.string(), &error) && !error.empty()); // refused, not thrown std::filesystem::remove_all(dir); + // The V# base marker (`vsharp_base_sign_extended` in each module's meta, VsharpBaseCensus): the device names a + // buffer below heap_base only when every loaded module, sub-indexes included, sign-extends the 48-bit base. One + // module without the marker (an older translation) makes the offsets unsigned again. + { + const auto root = dir / "vsharp_bases"; + const auto write_index = [](const std::filesystem::path& folder, const std::string& modules) { + std::filesystem::create_directories(folder); + std::ofstream index(folder / "index.json", std::ios::binary); + index << "{" << modules << "}"; + }; + const auto module = [](const char* name, const char* marker) { + std::string out = "{\"stage\": \"cs\", \"fssm_sha256\": \"" + std::string(name) + "\""; + if (marker) out += ", \"vsharp_base_sign_extended\": " + std::string(marker); + return out + "}"; + }; + write_index(root, "\"a\": " + module("aa", "true") + ", \"b\": " + module("bb", "true")); + ShaderLibrary all_signed; + CHECK(all_signed.load(root.string(), &error)); + CHECK(all_signed.vsharp_base_census().sign_extended == 2 && all_signed.vsharp_base_census().zero_extended == 0); + CHECK(all_signed.vsharp_base_census().signed_offsets()); + + // An absent marker and an explicit false are both the old zero extension. + write_index(root, "\"a\": " + module("aa", "true") + ", \"b\": " + module("bb", nullptr) + ", \"c\": " + + module("cc", "false")); + ShaderLibrary mixed; + CHECK(mixed.load(root.string(), &error)); + CHECK(mixed.vsharp_base_census().sign_extended == 1 && mixed.vsharp_base_census().zero_extended == 2); + CHECK(!mixed.vsharp_base_census().signed_offsets()); + + // An old module in a sub-index counts as well; loading again replaces the census. + write_index(root, "\"a\": " + module("aa", "true")); + write_index(root / "library", "\"l\": " + module("ll", nullptr)); + ShaderLibrary old_sub_index; + CHECK(old_sub_index.load(root.string(), &error)); + CHECK(old_sub_index.vsharp_base_census().total() == 2 && !old_sub_index.vsharp_base_census().signed_offsets()); + std::filesystem::remove_all(root / "library"); + CHECK(old_sub_index.load(root.string(), &error)); + CHECK(old_sub_index.vsharp_base_census().total() == 1 && old_sub_index.vsharp_base_census().signed_offsets()); + + // Nothing loaded reads a base the old way. + CHECK(VsharpBaseCensus{}.signed_offsets()); + std::filesystem::remove_all(root); + } + // The descriptor-hash marker (`descriptor_hash` in each module's meta, descriptor_table.h): absent is bare fnv1a; // the census covers the root index and every sub-index, and the majority decides. LEONIDA_DESCRIPTOR_HASH overrides // in the device, through descriptor_hash_kind_from_env. @@ -820,6 +864,32 @@ int main() { std::filesystem::remove_all(dir); } + // The T# index-word marker (`"tsharp_index": "dword6"`, TsharpIndexCensus): the modules that take a heap T#'s + // bindless index from its dword 6, which the device then writes into every heap, and the older ones (no key, or + // a value this runtime does not know), which look such T#s up in the hash table. + { + const auto root = dir / "tsharp_index"; + const auto write_index = [](const std::filesystem::path& folder, const std::string& modules) { + std::filesystem::create_directories(folder); + std::ofstream index(folder / "index.json", std::ios::binary); + index << "{" << modules << "}"; + }; + const auto module = [](const char* name, const char* marker) { + std::string out = "{\"stage\": \"ps\", \"fssm_sha256\": \"" + std::string(name) + "\""; + if (marker) out += ", \"tsharp_index\": \"" + std::string(marker) + "\""; + return out + "}"; + }; + write_index(root, "\"a\": " + module("aa", "dword6") + ", \"b\": " + module("bb", nullptr) + ", \"c\": " + + module("cc", "dword7") + ", \"d\": " + module("dd", "dword6")); + ShaderLibrary mixed; + CHECK(mixed.load(root.string(), &error)); + CHECK(mixed.tsharp_index_census().dword6 == 2 && mixed.tsharp_index_census().none == 2); + write_index(root, "\"a\": " + module("aa", nullptr)); + CHECK(mixed.load(root.string(), &error)); // a reload replaces the census + CHECK(mixed.tsharp_index_census().dword6 == 0 && mixed.tsharp_index_census().none == 1); + std::filesystem::remove_all(root); + } + // The descriptor-table layout marker (`descriptor_table` in each module's meta, descriptor_table.h): absent is // the old plain layout. The kind word is additive - a tagged module reads it, a plain one ignores it and reads // the index at the same place - so one tagged module needs the tagged layout however many plain ones a merged or @@ -1289,6 +1359,105 @@ int main() { CHECK(huffman_lut_checks() == 0); + // Round 3B metadata: reads_glc_buffer, writes_buffer (default true when absent + all_have_writes_buffer_meta()), + // buffer_write_slots (array of ints or "dynamic"), and literal_sampler_spec_base (absent vs present including 0). + { + const std::string h1 = sha256_hex(bytes("r3b_cs_glc_ro")); + const std::string h2 = sha256_hex(bytes("r3b_ps_rw_slots")); + const std::string h3 = sha256_hex(bytes("r3b_cs_dynamic_slots")); + const std::string h4 = sha256_hex(bytes("r3b_legacy_no_meta")); + std::filesystem::create_directories(dir); + const auto write_index = [&](const std::string& body) { + std::ofstream f(dir / "index.json", std::ios::binary | std::ios::trunc); + f << body; + }; + + // 1. All modules declare writes_buffer -> all_have_writes_buffer_meta() is true. + write_index( + "{" + "\"cs_glc\": {\"stage\": \"cs\", \"fssm_sha256\": \"" + h1 + + "\", \"reads_glc_buffer\": true, \"writes_buffer\": false, \"buffer_write_slots\": [], " + "\"literal_samplers\": [[1, 2, 3, 4], [5, 6, 7, 8]], \"literal_sampler_spec_base\": 0}," + "\"ps_rw\": {\"stage\": \"ps\", \"fssm_sha256\": \"" + h2 + + "\", \"reads_glc_buffer\": false, \"writes_buffer\": true, \"buffer_write_slots\": [2, 5, 11], " + "\"literal_samplers\": [[9, 10, 11, 12]], \"literal_sampler_spec_base\": 100}," + "\"cs_dyn\": {\"stage\": \"cs\", \"fssm_sha256\": \"" + h3 + + "\", \"writes_buffer\": true, \"buffer_write_slots\": \"dynamic\"}" + "}"); + ShaderLibrary lib; + CHECK(!lib.all_have_writes_buffer_meta()); // empty library: false + CHECK(lib.load(dir.string(), &error) && lib.size() == 3); + CHECK(lib.all_have_writes_buffer_meta()); + CHECK(lib.writes_buffer_census().present == 3 && lib.writes_buffer_census().missing == 0); + + const ShaderEntry* e1 = lib.find("cs", h1); + CHECK(e1 != nullptr); + CHECK(e1->reads_glc_buffer == true); + CHECK(e1->has_writes_buffer == true && e1->writes_buffer == false); + CHECK(!e1->buffer_write_slots_dynamic && e1->buffer_write_slots.empty()); + CHECK(e1->literal_sampler_spec_base.has_value() && *e1->literal_sampler_spec_base == 0u); + CHECK(e1->literal_samplers.size() == 2); + + const ShaderEntry* e2 = lib.find("ps", h2); + CHECK(e2 != nullptr); + CHECK(e2->reads_glc_buffer == false); + CHECK(e2->has_writes_buffer == true && e2->writes_buffer == true); + CHECK(!e2->buffer_write_slots_dynamic && + e2->buffer_write_slots == std::vector({2u, 5u, 11u})); + CHECK(e2->literal_sampler_spec_base.has_value() && *e2->literal_sampler_spec_base == 100u); + + const ShaderEntry* e3 = lib.find("cs", h3); + CHECK(e3 != nullptr); + CHECK(e3->reads_glc_buffer == false); + CHECK(e3->has_writes_buffer == true && e3->writes_buffer == true); + CHECK(e3->buffer_write_slots_dynamic && e3->buffer_write_slots.empty()); + CHECK(!e3->literal_sampler_spec_base.has_value()); + + // 2. Mixed pack (one legacy module omitting writes_buffer) -> legacy defaults to writes_buffer == true, + // reads_glc_buffer == false, literal_sampler_spec_base absent, and all_have_writes_buffer_meta() is false. + write_index( + "{" + "\"cs_glc\": {\"stage\": \"cs\", \"fssm_sha256\": \"" + h1 + "\", \"writes_buffer\": false}," + "\"cs_legacy\": {\"stage\": \"cs\", \"fssm_sha256\": \"" + h4 + "\"}" + "}"); + CHECK(lib.load(dir.string(), &error) && lib.size() == 2); + CHECK(!lib.all_have_writes_buffer_meta()); + CHECK(lib.writes_buffer_census().present == 1 && lib.writes_buffer_census().missing == 1); + const ShaderEntry* e4 = lib.find("cs", h4); + CHECK(e4 != nullptr); + CHECK(e4->reads_glc_buffer == false); + CHECK(e4->has_writes_buffer == false && e4->writes_buffer == true); + CHECK(!e4->buffer_write_slots_dynamic && e4->buffer_write_slots.empty()); + CHECK(!e4->literal_sampler_spec_base.has_value()); + + // 3. FSPX bare program ambiguity when reads_glc_buffer, writes_buffer, or literal_sampler_spec_base differ. + const auto code = fspx_code(0x6000); + std::vector st_a(28, 0), st_b(28, 0); + st_a[12] = 32; + st_b[12] = 64; + const std::uint32_t spv_words[5] = {0x07230203, 0x00010500, 7, 1, 0}; + std::filesystem::create_directories(dir / "fspx"); + for (const char* nm : {"a.spv", "b.spv"}) { + std::ofstream s(dir / "fspx" / nm, std::ios::binary | std::ios::trunc); + s.write(reinterpret_cast(spv_words), sizeof(spv_words)); + } + write_index("{}"); + { + std::ofstream sub(dir / "fspx" / "index.json", std::ios::binary | std::ios::trunc); + sub << "{\"a\": {\"stage\": \"cs\", \"fspx_code_sha256\": \"" << sha256_hex(code) + << "\", \"fspx_state_sha256\": \"" << sha256_hex(st_a) + << "\", \"reads_glc_buffer\": true, \"writes_buffer\": false, \"literal_sampler_spec_base\": 10}," + << "\"b\": {\"stage\": \"cs\", \"fspx_code_sha256\": \"" << sha256_hex(code) + << "\", \"fspx_state_sha256\": \"" << sha256_hex(st_b) + << "\", \"reads_glc_buffer\": false, \"writes_buffer\": false, \"literal_sampler_spec_base\": 10}}"; + } + CHECK(lib.load(dir.string(), &error) && lib.size() == 2 && lib.all_have_writes_buffer_meta()); + bool ambig = false; + CHECK(lib.program_candidates("cs", compute_program(code), &ambig).empty() && ambig); + + std::filesystem::remove_all(dir); + } + std::printf("SHA-256, inflate (stored/fixed/dynamic), JSON, FSSM extraction, FSPX programs and index lookup OK\n"); return 0; } diff --git a/runtime/test/shaders/ps_table_fetch.asm b/runtime/test/shaders/ps_table_fetch.asm index fad9cb9eeb..c118c6fd92 100644 --- a/runtime/test/shaders/ps_table_fetch.asm +++ b/runtime/test/shaders/ps_table_fetch.asm @@ -1,6 +1,9 @@ ; vk_texture_test fetch-sint / fetch-uint / fetch-miss. Texel (0,0) holds bytes ; 82 22 f8 4d: expect (-126,34,-8,77) or (130,34,248,77). A key mismatch ; fetches magenta UNORM at index zero. Convert raw integer words for RGBA32F output. +; s0 is a descriptor-table pointer (s1 = 0): the index comes from the T#'s dword 6 (docs/design.md, "Bindless index in +; the T#"), and fetch-miss writes a dword 6 without the index tag, which must read index zero. +s_mov_b32 s1, 0 s_load_dwordx8 s[8:15], s[0:1], 0 s_waitcnt lgkmcnt(0) v_mov_b32_e32 v0, 0 diff --git a/runtime/test/shaders/ps_texture_sample.asm b/runtime/test/shaders/ps_texture_sample.asm index 35e3c6ddba..e3851fde3c 100644 --- a/runtime/test/shaders/ps_texture_sample.asm +++ b/runtime/test/shaders/ps_texture_sample.asm @@ -2,10 +2,13 @@ ; using normalized UV coordinates from attr0, outputs sampled color to mrt0. ; Run: vk_texture_test (autonomously, or with vs.spv fs.spv out.raw ptr_sgpr s0 s1 s2 s3) ; -> verifies center pixel = gradient color (0.5, 0.5, 0.5, 1.0) sampled via descriptor table -; s[0:1] = 64-bit pointer to T# in GPU heap +; s0 = descriptor-table pointer to the T# in the GPU heap, made a 32-bit pointer (s1 = 0) as the title's shaders do: +; the shader takes the T#'s bindless index from its dword 6, with no hash-table lookup (docs/design.md, "Bindless +; index in the T#"); vk_texture_test writes the index word there. ; s[8:15] = 8-dword T# (image descriptor) ; s[16:19] = 4-dword S# (sampler descriptor) ; v[0:1] = barycentric UV coordinates +s_mov_b32 s1, 0 v_interp_p1_f32_e32 v2, v0, attr0.x v_interp_p2_f32_e32 v2, v1, attr0.x v_interp_p1_f32_e32 v3, v0, attr0.y diff --git a/runtime/test/shadow_keep_test.cpp b/runtime/test/shadow_keep_test.cpp index 87960c0a29..5d8c0cdba1 100644 --- a/runtime/test/shadow_keep_test.cpp +++ b/runtime/test/shadow_keep_test.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include @@ -124,6 +125,85 @@ void sums_tell_bytes_apart() { EXPECT(leonida::shadow_keep::sum_of(a, 16) != leonida::shadow_keep::sum_of(a, 17)); // the length counts } +void sum_of_batch_256_matches_sum_of() { + constexpr std::size_t kMaxPieces = 256; + constexpr std::size_t kPad = 64; + std::vector buf(kMaxPieces * kPiece + kPad); + std::vector batch_out(kMaxPieces, 0); + + const std::size_t counts[] = {0, 1, 2, 15, 16, 17, 64, 256}; + const std::size_t offsets[] = {0, 1, 3, 7, 15, 31}; + std::mt19937_64 rng(0x5eed123456789abcull); + + for (int pattern = 0; pattern < 4; ++pattern) { + if (pattern == 0) { + std::fill(buf.begin(), buf.end(), std::uint8_t(0)); + } else if (pattern == 1) { + std::fill(buf.begin(), buf.end(), std::uint8_t(0xff)); + } else if (pattern == 2) { + for (std::size_t i = 0; i < buf.size(); ++i) buf[i] = std::uint8_t((i * 131 + 17) & 0xff); + } else { + for (std::size_t i = 0; i < buf.size(); ++i) buf[i] = std::uint8_t(rng() & 0xff); + } + for (const std::size_t off : offsets) { + const std::uint8_t* const ptr = buf.data() + off; + for (const std::size_t n : counts) { + std::fill(batch_out.begin(), batch_out.end(), std::uint64_t(0xdeadbeefull)); + leonida::shadow_keep::sum_of_batch_256(ptr, n, batch_out.data()); + for (std::size_t i = 0; i < n; ++i) { + const std::uint64_t expected = leonida::shadow_keep::sum_of(ptr + i * kPiece, kPiece); + EXPECT(batch_out[i] == expected); + EXPECT(batch_out[i] != 0); + } + if (n < kMaxPieces) EXPECT(batch_out[n] == 0xdeadbeefull); + } + } + } +} + +void copy_and_sum_256_matches_sum_of() { + constexpr std::size_t kMaxPieces = 256; + constexpr std::size_t kPad = 64; + std::vector src(kMaxPieces * kPiece + kPad); + std::vector dst(kMaxPieces * kPiece + kPad); + std::vector fused_out(kMaxPieces, 0); + + const std::size_t counts[] = {0, 1, 2, 15, 16, 17, 64, 256}; + const std::size_t offsets[] = {0, 1, 3, 7, 15, 31}; + std::mt19937_64 rng(0xf05ed123456789abull); + + for (int pattern = 0; pattern < 4; ++pattern) { + if (pattern == 0) { + std::fill(src.begin(), src.end(), std::uint8_t(0)); + } else if (pattern == 1) { + std::fill(src.begin(), src.end(), std::uint8_t(0xff)); + } else if (pattern == 2) { + for (std::size_t i = 0; i < src.size(); ++i) src[i] = std::uint8_t((i * 131 + 17) & 0xff); + } else { + for (std::size_t i = 0; i < src.size(); ++i) src[i] = std::uint8_t(rng() & 0xff); + } + for (const std::size_t src_off : offsets) { + const std::size_t dst_off = (src_off * 3) % 32; + const std::uint8_t* const sptr = src.data() + src_off; + std::uint8_t* const dptr = dst.data() + dst_off; + for (const std::size_t n : counts) { + std::fill(dst.begin(), dst.end(), std::uint8_t(0xCC)); + std::fill(fused_out.begin(), fused_out.end(), std::uint64_t(0xdeadbeefull)); + leonida::shadow_keep::copy_and_sum_256(dptr, sptr, n, fused_out.data()); + if (dst_off > 0) EXPECT(dst[dst_off - 1] == 0xCC); + if (n > 0) EXPECT(std::memcmp(dptr, sptr, n * kPiece) == 0); + EXPECT(dst[dst_off + n * kPiece] == 0xCC); + for (std::size_t i = 0; i < n; ++i) { + const std::uint64_t expected = leonida::shadow_keep::sum_of(sptr + i * kPiece, kPiece); + EXPECT(fused_out[i] == expected); + EXPECT(fused_out[i] != 0); + } + if (n < kMaxPieces) EXPECT(fused_out[n] == 0xdeadbeefull); + } + } + } +} + } // namespace int main() { @@ -132,6 +212,8 @@ int main() { partial_first_and_last_pieces(); forgotten_sums_copy_once(); sums_tell_bytes_apart(); + sum_of_batch_256_matches_sum_of(); + copy_and_sum_256_matches_sum_of(); if (failures) { std::fprintf(stderr, "shadow_keep: %d check(s) failed\n", failures); return 1; diff --git a/runtime/test/submit_frame_test.cpp b/runtime/test/submit_frame_test.cpp new file mode 100644 index 0000000000..4b54931b23 --- /dev/null +++ b/runtime/test/submit_frame_test.cpp @@ -0,0 +1,2806 @@ +// The "submit frame" and "submit floor" lines (runtime/src/submit_phases.h): their sums against the per-submission +// phases the "submit phases" line adds up. +// 1. A scripted run on the CPU, with known phase times: two frames, a submission on each of two queue kinds, a phase +// on one of our threads (a WorkerScope), a title call (TitleCall) and a contended lock. The frame sums, the +// split between title and own threads, the worst frame and the floor must come out as scripted. +// 2. Real submissions through VulkanQueue (empty lists; 77-free: without a Vulkan device this part is skipped and +// the test still passes): the floor's phase sums must equal what the phase totals grew by, submission for +// submission, and every one of them is a floor submission. +#include "vk_test_device.h" +#include "../src/list_value_progress.h" +#include "../src/vulkan_backend.h" + +#include +#include +#include +#include +#include +#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 namespace leonida; +namespace sp = leonida::submit_phases; +constexpr std::uint64_t ms = 1000000; // ns + +std::uint64_t load(const std::atomic& a) { return a.load(std::memory_order_relaxed); } + +std::uint64_t phase_total() { + std::uint64_t n = 0; + for (const auto& p : sp::totals().ns) n += load(p); + return n; +} + +int scripted() { + sp::FrameTotals& f = sp::frame_totals(); + // Frame 1: a direct submission with heaps 1 ms and replay 2 ms, nothing changed (a floor submission). + { + const sp::Submission s(0); + sp::add(sp::heaps, 1 * ms); + sp::add(sp::replay, 2 * ms); + } + // One of our threads: its 5 ms of textures are the phase line's, not the title threads'. + std::thread([] { + const sp::WorkerScope busy(sp::worker_texture_reads); + sp::add(sp::textures, 5 * ms); + }).join(); + // A title call that spends about 3 ms, 1 ms of it in a phase: about 2 ms of fences. + const auto call_start = std::chrono::steady_clock::now(); + { + const sp::TitleCall call(sp::part_fences); + sp::add(sp::replay, 1 * ms); + std::this_thread::sleep_for(std::chrono::milliseconds(3)); + } + const double call_ns = double(std::chrono::duration_cast( + std::chrono::steady_clock::now() - call_start).count()); + const std::uint64_t fences = load(f.part_ns[sp::part_fences]); + EXPECT(fences > 1 * ms && double(fences) <= call_ns - 1e6); + // A lock another thread holds for 4 ms: counted as a lock wait, inside the other parts (not in the frame's sum). + std::mutex m; + std::atomic taken{false}; + std::thread holder([&] { // takes the lock and lets it go on its own thread, as a mutex must be + const std::lock_guard held(m); + taken.store(true); + std::this_thread::sleep_for(std::chrono::milliseconds(4)); + }); + while (!taken.load()) std::this_thread::yield(); + { + std::unique_lock lock(m, std::defer_lock); + sp::lock_timed(lock); + } + holder.join(); + EXPECT(load(f.part_ns[sp::part_lock_wait]) >= 2 * ms); + const std::uint64_t frame1 = 3 * ms + 1 * ms + fences; // heaps, replay, replay in the call, fences + EXPECT(load(f.current_ns) == frame1); + sp::frame_presented(); + // Frame 2: a compute submission with geometry 4 ms that uploaded geometry: not a floor submission. + { + const sp::Submission s(1); + sp::add(sp::geometry, 4 * ms); + sp::note_change(sp::change_geometry); + } + sp::frame_presented(); + + EXPECT(load(f.frames) == 2); + EXPECT(load(f.submissions[0]) == 1 && load(f.submissions[1]) == 1 && load(f.submissions[2]) == 0); + EXPECT(load(f.phase_ns[sp::heaps]) == 1 * ms && load(f.phase_ns[sp::replay]) == 3 * ms); + EXPECT(load(f.phase_ns[sp::geometry]) == 4 * ms && load(f.phase_ns[sp::textures]) == 0); + EXPECT(load(f.worker_ns[sp::worker_texture_reads]) > 0); + // The phase line counts every thread: the title threads' phases and the worker's add up to its total. + std::uint64_t title = 0; + for (const auto& p : f.phase_ns) title += load(p); + EXPECT(phase_total() == title + 5 * ms); + EXPECT(load(f.worst_ns) == (frame1 > 4 * ms ? frame1 : 4 * ms)); + EXPECT(load(f.all_count) == 2 && load(f.all_ns) == 7 * ms); + EXPECT(load(f.floor_count) == 1 && load(f.floor_min_ns) == 3 * ms); + EXPECT(load(f.floor_ns[sp::heaps]) == 1 * ms && load(f.floor_ns[sp::replay]) == 2 * ms && + load(f.floor_ns[sp::geometry]) == 0); + sp::frame_lines(1.0); // the two lines' format, on stderr; a new window + EXPECT(load(f.frames) == 0 && load(f.all_count) == 0 && load(f.floor_count) == 0 && load(f.worst_ns) == 0); + for (const auto& p : f.phase_ns) EXPECT(load(p) == 0); + // Mirror refresh/write-back inside a list submission: time inside Scope(shadows) is billed to shadows, not lists, + // and contended lock_timed inside it is billed to lock waits. + { + const sp::TitleCall call(sp::part_lists); + const sp::Scope shadows_scope(sp::shadows); + std::mutex mirror_m; + std::atomic held_flag{false}; + std::thread holder([&] { + const std::lock_guard held(mirror_m); + held_flag.store(true); + std::this_thread::sleep_for(std::chrono::milliseconds(4)); + }); + while (!held_flag.load()) std::this_thread::yield(); + { + std::unique_lock lock(mirror_m, std::defer_lock); + sp::lock_timed(lock); + } + holder.join(); + } + EXPECT(load(f.phase_ns[sp::shadows]) >= 2 * ms); + EXPECT(load(f.part_ns[sp::part_lock_wait]) >= 2 * ms); + EXPECT(load(f.part_ns[sp::part_lists]) < load(f.phase_ns[sp::shadows])); + // Contended lock_timed inside a WorkerScope bills worker_lock_wait_ns without polluting title-thread lock waits. + { + const std::uint64_t title_waits_before = load(f.part_ns[sp::part_lock_wait]); + std::mutex worker_m; + std::atomic held_flag{false}; + std::thread holder([&] { + const std::lock_guard held(worker_m); + held_flag.store(true, std::memory_order_release); + std::this_thread::sleep_for(std::chrono::milliseconds(4)); + }); + while (!held_flag.load(std::memory_order_acquire)) std::this_thread::yield(); + std::thread worker([&] { + const sp::WorkerScope busy(sp::worker_submit); + std::unique_lock lock(worker_m, std::defer_lock); + sp::lock_timed(lock); + }); + worker.join(); + holder.join(); + EXPECT(load(f.worker_lock_wait_ns) >= 2 * ms); + EXPECT(load(f.part_ns[sp::part_lock_wait]) == title_waits_before); + } + sp::frame_lines(1.0); + EXPECT(load(f.worker_lock_wait_ns) == 0); + std::printf("scripted: frame sums, title and own threads, worker lock waits, worst frame and floor as scripted\n"); + return 0; +} + +int submissions() { + vktest::Device d; + if (!d.create()) { + std::printf("no usable Vulkan device: the submissions part is skipped\n"); + return 0; + } + VulkanContext context(d.device_proc, d.device, true); + EXPECT(context.loaded()); + VulkanQueue direct(context, d.queue, d.family, VulkanQueue::QueueKind::direct); + EXPECT(direct.ok()); + CommandList list; + EXPECT(list.close()); + const CommandList* lists[] = {&list}; + sp::FrameTotals& f = sp::frame_totals(); + const std::uint64_t phases_before = phase_total(), submitted_before = load(sp::totals().submissions); + const std::uint64_t all_before = load(f.all_count), all_ns_before = load(f.all_ns); + const std::uint64_t floor_before = load(f.floor_count), direct_before = load(f.submissions[0]); + std::uint64_t floor_ns_before = 0; + for (const auto& p : f.floor_ns) floor_ns_before += load(p); + constexpr std::uint64_t kSubmissions = 20; + for (std::uint64_t i = 0; i < kSubmissions; ++i) EXPECT(direct.execute(lists) == ReplayResult::success); + EXPECT(direct.idle()); + std::uint64_t floor_ns = 0; + for (const auto& p : f.floor_ns) floor_ns += load(p); + const std::uint64_t phases = phase_total() - phases_before; + std::printf("submissions: %llu, phases %.3f ms in all, floor %llu of them, %.3f ms\n", + static_cast(load(f.all_count) - all_before), double(phases) * 1e-6, + static_cast(load(f.floor_count) - floor_before), + double(floor_ns - floor_ns_before) * 1e-6); + EXPECT(load(sp::totals().submissions) - submitted_before == kSubmissions); + EXPECT(load(f.submissions[0]) - direct_before == kSubmissions); + EXPECT(load(f.all_count) - all_before == kSubmissions); + EXPECT(load(f.floor_count) - floor_before == kSubmissions); // empty lists: nothing to bring up to date + // Every phase of these submissions ran on this thread inside them: the sums agree to the nanosecond. + EXPECT(load(f.all_ns) - all_ns_before == phases); + EXPECT(floor_ns - floor_ns_before == phases); + EXPECT(phases > 0); + return 0; +} + +// Queue sync contract, unlocked state_mutex_, per-batch FIFO drain, active_seq_ / after_held(), +// zero-copy CommandList snapshot, async worker, and QueueHolds progress tracking tests. +int queue_sync_and_async() { + vktest::Device d; + if (!d.create()) { + std::printf("no usable Vulkan device: the queue_sync_and_async part is skipped\n"); + return 0; + } + + constexpr VkDeviceSize kBufBytes = 256; + const VkBufferUsageFlags usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; + + auto make_copy_list = [](ResourceId dst, std::uint64_t dst_off, ResourceId src, std::uint64_t src_off, + std::uint64_t bytes) -> std::shared_ptr { + auto list = std::make_shared(); + if (!list->copy_buffer({dst, dst_off, src, src_off, bytes}) || !list->close()) return {}; + return list; + }; + + // 1. Synchronous execute() arriving while executing_ == true: + // (a) With !must_hold(), waits on exec_cv_ and runs before_execute_() synchronously before returning. + // (b) With must_hold() (unmet Wait) or Signal, enqueues immediately under state_mutex_ without blocking on + // before_execute_(), preserves zero-copy CommandList snapshots across Reset(), and runs before_execute_() + // once per batch on drain. + // (c) Arriving while a releaser thread is draining multiple ready held batches waits until the ready held + // batches finish and then runs before_execute_() synchronously before returning (strict FIFO). + { + VulkanContext context(d.device_proc, d.device, true); + EXPECT(context.loaded()); + VulkanQueue queue(context, d.queue, d.family, VulkanQueue::QueueKind::direct); + EXPECT(queue.ok()); + queue.set_async_depth(0); + + void* src_map = nullptr; + void* dst_map = nullptr; + VkBuffer src = d.buffer(kBufBytes, usage, &src_map); + VkBuffer dst = d.buffer(kBufBytes, usage, &dst_map); + EXPECT(src && dst); + auto* sb = static_cast(src_map); + auto* db = static_cast(dst_map); + std::memset(sb, 0, kBufBytes); + std::memset(db, 0, kBufBytes); + sb[0] = 0x11; + sb[16] = 0x22; + sb[32] = 0x33; + + ResourceBinding r_src{}, r_dst{}; + r_src.buffer = src; + r_src.size = kBufBytes; + r_dst.buffer = dst; + r_dst.size = kBufBytes; + r_dst.host_readable = true; + context.add_resource(1, r_src); + context.add_resource(2, r_dst); + + std::atomic before_calls{0}; + std::atomic in_first_before{false}; + std::atomic release_first_before{false}; + context.set_before_execute([&] { + const unsigned n = before_calls.fetch_add(1, std::memory_order_acq_rel) + 1; + if (n == 1) { + in_first_before.store(true, std::memory_order_release); + while (!release_first_before.load(std::memory_order_acquire)) std::this_thread::yield(); + } + }); + + // Each batch writes its marker to its own slot AND overwrites slot 0 (final value proves strict FIFO order). + auto b1 = std::make_shared(); + EXPECT(b1->copy_buffer({2, 16, 1, 0, 1}) && b1->copy_buffer({2, 0, 1, 0, 1}) && b1->close()); + auto b2 = std::make_shared(); + EXPECT(b2->copy_buffer({2, 32, 1, 16, 1}) && b2->copy_buffer({2, 0, 1, 16, 1}) && b2->close()); + auto b3 = std::make_shared(); + EXPECT(b3->copy_buffer({2, 48, 1, 32, 1}) && b3->copy_buffer({2, 0, 1, 32, 1}) && b3->close()); + + // (a) Unheld sync execute() while executing_ == true must wait on exec_cv_ and run before_execute_(). + ReplayResult t1_res = ReplayResult::unsupported, t2_res = ReplayResult::unsupported; + std::atomic t2_done{false}; + std::atomic t2_before_at_return{0}; + std::thread worker1([&] { + std::shared_ptr s1 = b1; + t1_res = queue.execute({&s1, 1}); + }); + while (!in_first_before.load(std::memory_order_acquire)) std::this_thread::yield(); + + std::thread worker2([&] { + std::shared_ptr s2 = b2; + t2_res = queue.execute({&s2, 1}); + t2_before_at_return.store(before_calls.load(std::memory_order_acquire), std::memory_order_release); + t2_done.store(true, std::memory_order_release); + }); + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + EXPECT(!t2_done.load(std::memory_order_acquire)); + EXPECT(before_calls.load(std::memory_order_acquire) == 1); + + release_first_before.store(true, std::memory_order_release); + worker1.join(); + worker2.join(); + EXPECT(t1_res == ReplayResult::success && t2_res == ReplayResult::success); + EXPECT(t2_before_at_return.load(std::memory_order_acquire) == 2); + EXPECT(queue.idle()); + EXPECT(db[16] == 0x11 && db[32] == 0x22 && db[0] == 0x22); + + // (b) must_hold() ops (behind an unmet Wait) and Signal enqueue immediately without blocking on executing_. + std::memset(db, 0, kBufBytes); + before_calls.store(0, std::memory_order_release); + in_first_before.store(false, std::memory_order_release); + release_first_before.store(false, std::memory_order_release); + VulkanFence gate(context, 0), done(context, 0); + EXPECT(gate.semaphore() != VK_NULL_HANDLE && done.semaphore() != VK_NULL_HANDLE); + + t1_res = ReplayResult::unsupported; + std::thread worker_b([&] { + std::shared_ptr s1 = b1; + t1_res = queue.execute({&s1, 1}); + }); + while (!in_first_before.load(std::memory_order_acquire)) std::this_thread::yield(); + + // While worker_b is blocked inside before_execute_(), this thread queues wait(gate), b2, b3, and Signal(done). + // If state_mutex_ were held across before_execute_() or wait-blocked ops waited on exec_cv_, this would + // deadlock before release_first_before is set! + queue.wait(gate.semaphore(), 1); + std::shared_ptr s2 = b2; + std::shared_ptr s3 = b3; + EXPECT(queue.execute({&s2, 1}) == ReplayResult::success); + EXPECT(queue.execute({&s3, 1}) == ReplayResult::success); + EXPECT(queue.signal(done.semaphore(), 1)); + + // Zero-copy proof: queue holds references to b2 and b3 without copying; simulating Reset() when use_count > 1 + // allocates fresh storage and never mutates the in-flight snapshot. + EXPECT(b2.use_count() > 1 && b3.use_count() > 1); + b2 = std::make_shared(); + EXPECT(b2->copy_buffer({2, 0, 1, 0, 1}) && b2->close()); // distinct content (0x11), must not affect in-flight + + release_first_before.store(true, std::memory_order_release); + worker_b.join(); + EXPECT(t1_res == ReplayResult::success); + EXPECT(before_calls.load(std::memory_order_acquire) == 1); // b2 & b3 stay held behind gate + + EXPECT(gate.signal(1)); + EXPECT(done.wait(1, 5'000'000'000ull)); + EXPECT(queue.idle()); + // b1 ran first (1), then held {b2, b3} coalesced into one before_execute_() + one submit (2). + EXPECT(before_calls.load(std::memory_order_acquire) == 2); + EXPECT(db[16] == 0x11 && db[32] == 0x22 && db[48] == 0x33 && db[0] == 0x33); + s2.reset(); + s3.reset(); + EXPECT(b1.use_count() == 1 && b3.use_count() == 1); + EXPECT(b3->reset()); // steady-state reuse with zero allocation + + // (c) Sync execute() arriving while a releaser drains [b1, b2 (coalesced in held_)] must wait for the held + // drain to finish and run before_execute_() for b3 synchronously before returning. + auto b2_fresh = std::make_shared(); + EXPECT(b2_fresh->copy_buffer({2, 32, 1, 16, 1}) && b2_fresh->copy_buffer({2, 0, 1, 16, 1}) && + b2_fresh->close()); + EXPECT(b3->copy_buffer({2, 48, 1, 32, 1}) && b3->copy_buffer({2, 0, 1, 32, 1}) && b3->close()); + std::memset(db, 0, kBufBytes); + before_calls.store(0, std::memory_order_release); + in_first_before.store(false, std::memory_order_release); + release_first_before.store(false, std::memory_order_release); + VulkanFence gate_c(context, 0); + EXPECT(gate_c.semaphore() != VK_NULL_HANDLE); + + queue.wait(gate_c.semaphore(), 1); + std::shared_ptr c1 = b1, c2 = b2_fresh, c3 = b3; + EXPECT(queue.execute({&c1, 1}) == ReplayResult::success); + EXPECT(queue.execute({&c2, 1}) == ReplayResult::success); + EXPECT(before_calls.load(std::memory_order_acquire) == 0); + + std::thread releaser([&] { (void)gate_c.signal(1); }); + while (!in_first_before.load(std::memory_order_acquire)) std::this_thread::yield(); + + ReplayResult title_res = ReplayResult::unsupported; + std::atomic title_done{false}; + std::atomic title_before_at_return{0}; + std::thread title([&] { + title_res = queue.execute({&c3, 1}); + title_before_at_return.store(before_calls.load(std::memory_order_acquire), std::memory_order_release); + title_done.store(true, std::memory_order_release); + }); + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + EXPECT(!title_done.load(std::memory_order_acquire)); + EXPECT(before_calls.load(std::memory_order_acquire) == 1); + + release_first_before.store(true, std::memory_order_release); + releaser.join(); + title.join(); + EXPECT(title_res == ReplayResult::success); + EXPECT(title_before_at_return.load(std::memory_order_acquire) == 2); + EXPECT(queue.idle()); + EXPECT(db[16] == 0x11 && db[32] == 0x22 && db[48] == 0x33 && db[0] == 0x33); + + // (d) Gate front held on `queue`, signaled while another thread holds pump_mutex_ (so pump_ready() has not + // reached `queue` yet and executing_ == false with !held_.empty() && ready(held_.front())): + // sync execute() must drain the ready front and run before_execute_() for itself before returning! + VulkanQueue other_q(context, d.queue, d.family, VulkanQueue::QueueKind::compute); + EXPECT(other_q.ok()); + other_q.set_async_depth(0); + VulkanFence gate_other(context, 0), gate_d(context, 0); + EXPECT(gate_other.semaphore() && gate_d.semaphore()); + auto empty_other = std::make_shared(); + EXPECT(empty_other->uav_barrier({}) && empty_other->close()); + std::shared_ptr s_other = empty_other; + + std::memset(db, 0, kBufBytes); + std::atomic in_pumper_before{false}; + std::atomic release_pumper{false}; + std::atomic main_before_calls{0}; + const std::thread::id main_tid = std::this_thread::get_id(); + context.set_before_execute([&] { + if (std::this_thread::get_id() == main_tid) { + main_before_calls.fetch_add(1, std::memory_order_acq_rel); + } else { + in_pumper_before.store(true, std::memory_order_release); + while (!release_pumper.load(std::memory_order_acquire)) std::this_thread::yield(); + } + }); + + other_q.wait(gate_other.semaphore(), 1); + EXPECT(other_q.execute({&s_other, 1}) == ReplayResult::success); + queue.wait(gate_d.semaphore(), 1); + EXPECT(queue.execute({&c1, 1}) == ReplayResult::success); + + // Pumper thread holds QueueHolds::pump_mutex_ while blocked inside other_q's before_execute_(). + std::thread pumper([&] { (void)gate_other.signal(1); }); + while (!in_pumper_before.load(std::memory_order_acquire)) std::this_thread::yield(); + + // Signal gate_d: QueueHolds::signaled() marks c1 ready, while pump_ready() returns immediately because + // pumper holds pump_mutex_. Thus queue has executing_ == false, !held_.empty(), and ready(held_.front()). + EXPECT(gate_d.signal(1)); + EXPECT(main_before_calls.load(std::memory_order_acquire) == 0); + + // Sync execute(c2) must drain c1 and execute c2 synchronously before returning (while pumper still holds pump). + EXPECT(queue.execute({&c2, 1}) == ReplayResult::success); + EXPECT(main_before_calls.load(std::memory_order_acquire) == 2); + EXPECT(queue.idle()); + EXPECT(db[16] == 0x11 && db[32] == 0x22 && db[0] == 0x22); + + release_pumper.store(true, std::memory_order_release); + pumper.join(); + EXPECT(other_q.idle()); + std::printf("queue sync: exec_cv_ sync wait, unlocked must_hold, releaser-drain sync, ready-front drain, zero-copy Reset ok\n"); + } + + // 2. after_held() must wait behind an active unheld synchronous execute() and an active unheld synchronous + // signal() (active_seq_ tracking via oldest_held_seq()). + { + VulkanContext context(d.device_proc, d.device, true); + EXPECT(context.loaded()); + VulkanQueue queue(context, d.queue, d.family, VulkanQueue::QueueKind::direct); + EXPECT(queue.ok()); + queue.set_async_depth(0); + + auto empty = std::make_shared(); + EXPECT(empty->uav_barrier({}) && empty->close()); + std::shared_ptr snap = empty; + + // (a) Active unheld sync execute(). + std::atomic in_before{false}, release_before{false}; + std::atomic after_calls{0}; + context.set_before_execute([&] { + in_before.store(true, std::memory_order_release); + while (!release_before.load(std::memory_order_acquire)) std::this_thread::yield(); + }); + context.set_after_execute([&] { after_calls.fetch_add(1, std::memory_order_acq_rel); }); + + ReplayResult res = ReplayResult::unsupported; + std::thread exec_t([&] { res = queue.execute({&snap, 1}); }); + while (!in_before.load(std::memory_order_acquire)) std::this_thread::yield(); + + std::atomic barrier_ran{false}; + std::atomic barrier_saw_after{0}; + int owner_a = 0; + context.holds().after_held(&owner_a, [&] { + barrier_saw_after.store(after_calls.load(std::memory_order_acquire), std::memory_order_release); + barrier_ran.store(true, std::memory_order_release); + }); + EXPECT(!barrier_ran.load(std::memory_order_acquire)); + + release_before.store(true, std::memory_order_release); + exec_t.join(); + context.holds().wait_barriers_drained(UINT64_MAX); + EXPECT(res == ReplayResult::success); + EXPECT(barrier_ran.load(std::memory_order_acquire)); + EXPECT(barrier_saw_after.load(std::memory_order_acquire) == 1); + + // (b) Active unheld sync signal(). + context.set_before_execute({}); + context.set_after_execute({}); + VulkanFence sig_fence(context, 0); + EXPECT(sig_fence.semaphore() != VK_NULL_HANDLE); + + std::atomic sig_ok{false}; + std::atomic sig_barrier_ran{false}; + std::atomic sig_barrier_saw_signaled{false}; + int owner_b = 0; + const std::uint64_t seq_before = context.holds().current_seq(); + std::thread sig_t; + { + std::lock_guard hold_submit(context.submit_mutex()); + sig_t = std::thread([&] { sig_ok.store(queue.signal(sig_fence.semaphore(), 1), std::memory_order_release); }); + // Wait until signal_sync() has acquired active_seq_ under state_mutex_ and is blocked in submit(). + while (context.holds().current_seq() == seq_before) std::this_thread::yield(); + + context.holds().after_held(&owner_b, [&] { + sig_barrier_saw_signaled.store(!context.holds().pending(sig_fence.semaphore(), 1), + std::memory_order_release); + sig_barrier_ran.store(true, std::memory_order_release); + }); + EXPECT(!sig_barrier_ran.load(std::memory_order_acquire)); + } + sig_t.join(); + context.holds().wait_barriers_drained(UINT64_MAX); + EXPECT(sig_ok.load(std::memory_order_acquire)); + EXPECT(sig_barrier_ran.load(std::memory_order_acquire)); + EXPECT(sig_barrier_saw_signaled.load(std::memory_order_acquire)); + EXPECT(sig_fence.wait(1, 5'000'000'000ull)); + EXPECT(queue.idle()); + std::printf("queue active_seq_: after_held waits behind active unheld execute() and signal() ok\n"); + } + + // 3. Held batches drain in strict FIFO order with before_execute_() called once per batch (no cross-batch + // coalescing), and an invalid held batch reports its failure without dropping valid peers. + { + VulkanContext context(d.device_proc, d.device, true); + EXPECT(context.loaded()); + VulkanQueue queue(context, d.queue, d.family, VulkanQueue::QueueKind::direct); + VulkanQueue copy_q(context, d.queue, d.family, VulkanQueue::QueueKind::copy); + EXPECT(queue.ok() && copy_q.ok()); + queue.set_async_depth(0); + copy_q.set_async_depth(0); + + void* src_map = nullptr; + void* dst_map = nullptr; + VkBuffer src = d.buffer(kBufBytes, usage, &src_map); + VkBuffer dst = d.buffer(kBufBytes, usage, &dst_map); + EXPECT(src && dst); + auto* sb = static_cast(src_map); + auto* db = static_cast(dst_map); + std::memset(db, 0, kBufBytes); + for (int i = 0; i < 6; ++i) sb[i * 16] = std::uint8_t(0xA1 + i); + + ResourceBinding r_src{}, r_dst{}; + r_src.buffer = src; + r_src.size = kBufBytes; + r_dst.buffer = dst; + r_dst.size = kBufBytes; + r_dst.host_readable = true; + context.add_resource(1, r_src); + context.add_resource(2, r_dst); + + std::atomic before_calls{0}; + context.set_before_execute([&] { before_calls.fetch_add(1, std::memory_order_relaxed); }); + + VulkanFence gate(context, 0), mid(context, 0), done(context, 0); + EXPECT(gate.semaphore() && mid.semaphore() && done.semaphore()); + + auto make_step = [&](int idx) { + auto l = std::make_shared(); + if (!l->copy_buffer({2, std::uint64_t((idx + 1) * 16), 1, std::uint64_t(idx * 16), 1}) || + !l->copy_buffer({2, 0, 1, std::uint64_t(idx * 16), 1}) || !l->close()) + return std::shared_ptr{}; + return std::shared_ptr(std::move(l)); + }; + std::shared_ptr steps[6]; + for (int i = 0; i < 6; ++i) { + steps[i] = make_step(i); + EXPECT(steps[i] != nullptr); + } + + queue.wait(gate.semaphore(), 1); + EXPECT(queue.execute({&steps[0], 1}) == ReplayResult::success); + EXPECT(queue.execute({&steps[1], 1}) == ReplayResult::success); + EXPECT(queue.execute({&steps[2], 1}) == ReplayResult::success); + EXPECT(queue.signal(mid.semaphore(), 1)); + EXPECT(queue.execute({&steps[3], 1}) == ReplayResult::success); + queue.wait(mid.semaphore(), 1); + EXPECT(queue.execute({&steps[4], 1}) == ReplayResult::success); + EXPECT(queue.execute({&steps[5], 1}) == ReplayResult::success); + EXPECT(queue.signal(done.semaphore(), 1)); + + EXPECT(before_calls.load() == 0); + EXPECT(gate.signal(1)); + EXPECT(done.wait(1, 5'000'000'000ull)); + EXPECT(queue.idle()); + + // Held consecutive batches coalesce across {steps[0..2]} (1), split at Signal(mid), run {steps[3]} (2), + // and either split at Wait(mid) (3) or coalesce {steps[3..5]} if mid already completed on the GPU (2). + EXPECT(before_calls.load() == 2 || before_calls.load() == 3); + for (int i = 0; i < 6; ++i) EXPECT(db[(i + 1) * 16] == std::uint8_t(0xA1 + i)); + EXPECT(db[0] == std::uint8_t(0xA6)); // strict FIFO through all 6 batches + + // Invalid held batch [valid, invalid ClearRenderTarget on copy queue, valid] must not drop valid peers. + VulkanFence gate2(context, 0), done2(context, 0); + EXPECT(gate2.semaphore() && done2.semaphore()); + std::memset(db, 0, kBufBytes); + auto bad_clear = std::make_shared(); + TargetView tv{}; + tv.resource = 2; + tv.layer_count = 1; + EXPECT(bad_clear->clear_render_target(tv, ClearColor{}) && bad_clear->close()); + std::shared_ptr bad_snap = bad_clear; + copy_q.wait(gate2.semaphore(), 1); + EXPECT(copy_q.execute({&steps[0], 1}) == ReplayResult::success); + EXPECT(copy_q.execute({&bad_snap, 1}) == ReplayResult::success); + EXPECT(copy_q.execute({&steps[1], 1}) == ReplayResult::success); + EXPECT(copy_q.signal(done2.semaphore(), 1)); + EXPECT(gate2.signal(1)); + EXPECT(done2.wait(1, 5'000'000'000ull)); + EXPECT(copy_q.idle()); + EXPECT(copy_q.take_held_failure() == ReplayResult::unsupported); + EXPECT(db[16] == 0xA1 && db[32] == 0xA2 && db[0] == 0xA2); + std::printf("queue held FIFO drain: 6 batches -> 3 merged before_execute_ calls, invalid peer isolation ok\n"); + } + + // 4. LEONIDA_SUBMIT_ASYNC (per-queue async worker depth=4): same-queue inbox coalescing, Present barrier split & + // ordering, held-batch release coalescing through worker, and zero-copy CommandList Reset() while queued. + { + VulkanContext context(d.device_proc, d.device, true); + EXPECT(context.loaded()); + VulkanQueue queue(context, d.queue, d.family, VulkanQueue::QueueKind::direct); + EXPECT(queue.ok()); + queue.set_async_depth(4); + + void* src_map = nullptr; + void* dst_map = nullptr; + VkBuffer src = d.buffer(kBufBytes, usage, &src_map); + VkBuffer dst = d.buffer(kBufBytes, usage, &dst_map); + EXPECT(src && dst); + auto* sb = static_cast(src_map); + auto* db = static_cast(dst_map); + std::memset(db, 0, kBufBytes); + for (int i = 0; i < 4; ++i) sb[i * 16] = std::uint8_t(0xC1 + i); + + ResourceBinding r_src{}, r_dst{}; + r_src.buffer = src; + r_src.size = kBufBytes; + r_dst.buffer = dst; + r_dst.size = kBufBytes; + r_dst.host_readable = true; + context.add_resource(1, r_src); + context.add_resource(2, r_dst); + + std::atomic before_calls{0}; + std::atomic in_first{false}; + std::atomic go_first{false}; + context.set_before_execute([&] { + const unsigned n = before_calls.fetch_add(1, std::memory_order_acq_rel) + 1; + if (n == 1) { + in_first.store(true, std::memory_order_release); + while (!go_first.load(std::memory_order_acquire)) std::this_thread::yield(); + } + }); + + auto c0 = make_copy_list(2, 16, 1, 0, 1); + auto c1 = make_copy_list(2, 32, 1, 16, 1); + auto c2 = make_copy_list(2, 48, 1, 32, 1); + auto c3 = make_copy_list(2, 64, 1, 48, 1); + EXPECT(c0 && c1 && c2 && c3); + + std::shared_ptr s0 = c0, s1 = c1, s2 = c2, s3 = c3; + EXPECT(queue.execute({&s0, 1}) == ReplayResult::success); + while (!in_first.load(std::memory_order_acquire)) std::this_thread::yield(); + + // Enqueue c1, c2, then a Present after_held barrier, then c3. + EXPECT(queue.execute({&s1, 1}) == ReplayResult::success); + EXPECT(queue.execute({&s2, 1}) == ReplayResult::success); + EXPECT(c1.use_count() > 1 && c2.use_count() > 1); // queued zero-copy + + std::atomic barrier_seen_before_calls{0}; + std::atomic barrier_ran{false}; + int barrier_owner = 0; + context.holds().after_held(&barrier_owner, [&] { + barrier_seen_before_calls.store(before_calls.load(std::memory_order_acquire), std::memory_order_release); + barrier_ran.store(true, std::memory_order_release); + }); + + EXPECT(queue.execute({&s3, 1}) == ReplayResult::success); + VulkanFence done(context, 0); + EXPECT(done.semaphore() != VK_NULL_HANDLE); + EXPECT(queue.signal(done.semaphore(), 1)); + + // Simulate Reset() of c1 while still in inbox: allocating new storage leaves in-flight snapshot intact. + c1 = make_copy_list(2, 32, 1, 0, 1); + EXPECT(c1 != nullptr); + + go_first.store(true, std::memory_order_release); + EXPECT(done.wait(1, 5'000'000'000ull)); + EXPECT(queue.idle()); + EXPECT(barrier_ran.load(std::memory_order_acquire)); + + // 3 before_execute_() calls total: {c0}, coalesced {c1, c2}, {c3}; barrier ran after {c1, c2} (count == 2)! + EXPECT(before_calls.load() == 3); + EXPECT(barrier_seen_before_calls.load() == 2); + EXPECT(db[16] == 0xC1 && db[32] == 0xC2 && db[48] == 0xC3 && db[64] == 0xC4); + + // Held batches behind a gate in async mode: release_ready() wakes worker and coalesces {s0, s2} into 1 submit. + before_calls.store(0); + std::memset(db, 0, kBufBytes); + VulkanFence gate(context, 0), done2(context, 0); + EXPECT(gate.semaphore() && done2.semaphore()); + const std::uint64_t title_replay_before = load(sp::frame_totals().phase_ns[sp::replay]); + queue.wait(gate.semaphore(), 1); + EXPECT(queue.execute({&s0, 1}) == ReplayResult::success); + EXPECT(queue.execute({&s2, 1}) == ReplayResult::success); + EXPECT(queue.signal(done2.semaphore(), 1)); + EXPECT(queue.idle()); // flushes inbox into held_ while gate is still closed + EXPECT(before_calls.load() == 0); + EXPECT(gate.signal(1)); + EXPECT(done2.wait(1, 5'000'000'000ull)); + EXPECT(queue.idle()); + EXPECT(before_calls.load() == 1); + EXPECT(db[16] == 0xC1 && db[48] == 0xC3); + // WorkerScope(worker_submit) covers release_held() on async_worker, so title-thread replay_ns stays unchanged! + EXPECT(load(sp::frame_totals().phase_ns[sp::replay]) == title_replay_before); + std::printf("queue async (depth=4): inbox coalescing, Present barrier split, gate release & WorkerScope ok\n"); + } + + // 5. Async queue progress tracking (LEONIDA_SUBMIT_ASYNC=4 + queued Present + busy producer worker + genuine + // deadlock): + // (a) While the direct producer async worker is busy inside before_execute_() with a WriteGroup Signal + // still queued in its inbox_, a consumer compute gate with a Present queued behind it must NOT be + // released unmet (queue_holds::any_progress() == true -> list_value_progress::Reason::hold). + // (b) Once all async workers finish draining into held_ and the GPU is idle, two async queues holding + // unsatisfied waits must NOT ping-pong release_ready(), queue_holds::any_progress() settles to false, + // and a genuine Present deadlock breaks cleanly. + // (c) In synchronous mode, executing_ == true (unlocked before_execute_()) also keeps any_progress() true. + { + namespace lvp = leonida::list_value_progress; + const auto met_ge = [](std::uint32_t, std::uint64_t v, std::uint64_t ref, bool) { return v >= ref; }; + + VulkanContext context(d.device_proc, d.device, true); + EXPECT(context.loaded()); + VulkanQueue direct(context, d.queue, d.family, VulkanQueue::QueueKind::direct); + VulkanQueue compute(context, d.queue, d.family, VulkanQueue::QueueKind::compute); + EXPECT(direct.ok() && compute.ok()); + direct.set_async_depth(4); + compute.set_async_depth(4); + + auto empty_list = std::make_shared(); + EXPECT(empty_list->uav_barrier({}) && empty_list->close()); + std::shared_ptr snap = empty_list; + + std::atomic hold_before{true}; + std::atomic in_before{false}; + context.set_before_execute([&] { + if (hold_before.load(std::memory_order_acquire)) { + in_before.store(true, std::memory_order_release); + while (hold_before.load(std::memory_order_acquire)) std::this_thread::yield(); + } + }); + + VulkanFence producer_written(context, 0), consumer_gate(context, 0), consumer_done(context, 0); + EXPECT(producer_written.semaphore() && consumer_gate.semaphore() && consumer_done.semaphore()); + + // (a) Direct worker starts batch 0 and blocks inside before_execute_(). + EXPECT(direct.execute({&snap, 1}) == ReplayResult::success); + while (!in_before.load(std::memory_order_acquire)) std::this_thread::yield(); + + // Compute queue holds a batch behind consumer_gate (simulating wait64 on title memory). + compute.wait(consumer_gate.semaphore(), 1); + EXPECT(compute.execute({&snap, 1}) == ReplayResult::success); + EXPECT(compute.signal(consumer_done.semaphore(), 1)); + + // Direct queue queues the producer batch + Signal(producer_written, 1) behind the blocked batch in inbox_. + EXPECT(direct.execute({&snap, 1}) == ReplayResult::success); + EXPECT(direct.signal(producer_written.semaphore(), 1)); + + // Title queues Present (after_held) and returns to idle (title_calls == 0). + std::atomic present_ran{false}; + int present_owner = 0; + context.holds().after_held(&present_owner, [&] { present_ran.store(true, std::memory_order_release); }); + + // Wait briefly for compute's worker to move its batch into held_, while direct's worker stays busy. + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + + // Producer's Signal has NOT reached Vulkan yet (still in direct.inbox_!), so pending() is true — the exact + // condition where Pump::choose_release() sees wg.running == false and would falsely break at Present + // without QueueHolds progress tracking. + EXPECT(context.holds().pending(producer_written.semaphore(), 1)); + EXPECT(queue_holds::any_progress()); + + const lvp::WaitPredicate wait_val[] = {{0x1000, 1, 7, true}}; + const lvp::PendingWrite write_val[] = {{0x1000, 1, 8, false}}; + const lvp::PendingGate gates[] = { + {&compute, 1, false, false, wait_val, /*presents_at_hold=*/0, /*held_ms=*/0}}; + const lvp::PendingWriteGroup writes[] = {{&direct, 0, /*running=*/false, write_val}}; + lvp::Activity at_present; + at_present.presents = 1; + at_present.now_ms = 250; + at_present.title_call_ms = 10; + at_present.title_submitting = queue_holds::any_progress(); + EXPECT(lvp::decide(writes, gates, at_present, met_ge).reason == lvp::Reason::hold); + EXPECT(!present_ran.load(std::memory_order_acquire)); + + // Unblock direct's worker: producer executes and submits Signal(producer_written, 1) cleanly. + hold_before.store(false, std::memory_order_release); + EXPECT(producer_written.wait(1, 5'000'000'000ull)); + EXPECT(direct.idle()); + EXPECT(!context.holds().pending(producer_written.semaphore(), 1)); + + // Now consumer_gate is met: signaling it wakes compute's worker, which drains consumer_batch and Present. + EXPECT(consumer_gate.signal(1)); + EXPECT(consumer_done.wait(1, 5'000'000'000ull)); + EXPECT(compute.idle()); + context.holds().wait_barriers_drained(UINT64_MAX); + EXPECT(present_ran.load(std::memory_order_acquire)); + + // (b) Genuine deadlock across BOTH async queues (no producer can ever signal): any_progress() must settle + // to false (zero cross-queue release_ready() ping-pong) so Present breaks the deadlock cleanly. + VulkanFence dead_gate_a(context, 0), dead_gate_b(context, 0), dead_done_a(context, 0), dead_done_b(context, 0); + EXPECT(dead_gate_a.semaphore() && dead_gate_b.semaphore() && dead_done_a.semaphore() && + dead_done_b.semaphore()); + direct.wait(dead_gate_a.semaphore(), 1); + EXPECT(direct.execute({&snap, 1}) == ReplayResult::success); + EXPECT(direct.signal(dead_done_a.semaphore(), 1)); + compute.wait(dead_gate_b.semaphore(), 1); + EXPECT(compute.execute({&snap, 1}) == ReplayResult::success); + EXPECT(compute.signal(dead_done_b.semaphore(), 1)); + + EXPECT(direct.idle()); + EXPECT(compute.idle()); + // Wait up to 500 ms for any trailing pump_ready() to finish; must settle to false and stay false. + const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(500); + while (queue_holds::any_progress() && std::chrono::steady_clock::now() < deadline) + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + EXPECT(!queue_holds::any_progress()); + at_present.title_submitting = queue_holds::any_progress(); + const lvp::Decision broken = lvp::decide({}, gates, at_present, met_ge); + EXPECT(broken.reason == lvp::Reason::present && broken.gate == 0); + + // Clean teardown of held deadlock ops. + EXPECT(dead_gate_a.signal(1)); + EXPECT(dead_gate_b.signal(1)); + EXPECT(dead_done_a.wait(1, 5'000'000'000ull)); + EXPECT(dead_done_b.wait(1, 5'000'000'000ull)); + EXPECT(direct.idle() && compute.idle()); + + // (c) Synchronous executing_ == true (unlocked before_execute_()) also keeps any_progress() true. + VulkanQueue sync_q(context, d.queue, d.family, VulkanQueue::QueueKind::direct); + EXPECT(sync_q.ok()); + sync_q.set_async_depth(0); + hold_before.store(true, std::memory_order_release); + in_before.store(false, std::memory_order_release); + ReplayResult sync_res = ReplayResult::unsupported; + std::thread sync_t([&] { sync_res = sync_q.execute({&snap, 1}); }); + while (!in_before.load(std::memory_order_acquire)) std::this_thread::yield(); + EXPECT(queue_holds::any_progress()); + hold_before.store(false, std::memory_order_release); + sync_t.join(); + EXPECT(sync_res == ReplayResult::success); + EXPECT(sync_q.idle()); + EXPECT(!queue_holds::any_progress()); + std::printf("queue async progress: held gate protected during busy worker/executing_, genuine deadlock breaks ok\n"); + } + + // 6. Explicit async inbox submit merging + vkQueueSubmit count + Signal / Wait / Present splits: + // Consecutive Call::Kind::execute items in async_worker() coalesce into ONE before_execute_() + ONE + // command-buffer vkQueueSubmit, while intervening Signal, Wait, and Present (after_held) each split cleanly. + { + static PFN_vkQueueSubmit s_real_submit = nullptr; + static std::atomic s_cb_submits{0}; + struct HookSubmit { + static VKAPI_ATTR VkResult VKAPI_CALL call(VkQueue q, std::uint32_t count, const VkSubmitInfo* infos, + VkFence fence) { + for (std::uint32_t i = 0; i < count; ++i) + if (infos[i].commandBufferCount > 0) s_cb_submits.fetch_add(1, std::memory_order_relaxed); + return s_real_submit(q, count, infos, fence); + } + }; + + VulkanContext context(d.device_proc, d.device, true); + EXPECT(context.loaded()); + s_real_submit = context.vk.vkQueueSubmit; + s_cb_submits.store(0, std::memory_order_relaxed); + context.vk.vkQueueSubmit = &HookSubmit::call; + + VulkanQueue queue(context, d.queue, d.family, VulkanQueue::QueueKind::direct); + EXPECT(queue.ok()); + queue.set_async_depth(12); + + void* src_map = nullptr; + void* dst_map = nullptr; + VkBuffer src = d.buffer(kBufBytes, usage, &src_map); + VkBuffer dst = d.buffer(kBufBytes, usage, &dst_map); + EXPECT(src && dst); + auto* sb = static_cast(src_map); + auto* db = static_cast(dst_map); + std::memset(db, 0, kBufBytes); + for (int i = 0; i < 9; ++i) sb[i * 16] = std::uint8_t(0xD0 + i); + + ResourceBinding r_src{}, r_dst{}; + r_src.buffer = src; + r_src.size = kBufBytes; + r_dst.buffer = dst; + r_dst.size = kBufBytes; + r_dst.host_readable = true; + context.add_resource(1, r_src); + context.add_resource(2, r_dst); + + std::atomic before_calls{0}; + std::atomic in_first{false}; + std::atomic go_first{false}; + context.set_before_execute([&] { + const unsigned n = before_calls.fetch_add(1, std::memory_order_acq_rel) + 1; + if (n == 1) { + in_first.store(true, std::memory_order_release); + while (!go_first.load(std::memory_order_acquire)) std::this_thread::yield(); + } + }); + + std::shared_ptr steps[9]; + for (int i = 0; i < 9; ++i) { + auto l = std::make_shared(); + EXPECT(l->copy_buffer({2, std::uint64_t((i + 1) * 16), 1, std::uint64_t(i * 16), 1}) && + l->copy_buffer({2, 0, 1, std::uint64_t(i * 16), 1}) && l->close()); + steps[i] = std::move(l); + } + + VulkanFence mid(context, 0), done(context, 0); + EXPECT(mid.semaphore() && done.semaphore()); + + // Batch 0 starts on worker and holds in before_execute_() while the remaining 8 batches queue in inbox_. + EXPECT(queue.execute({&steps[0], 1}) == ReplayResult::success); + while (!in_first.load(std::memory_order_acquire)) std::this_thread::yield(); + + // Group A: 3 consecutive execute batches -> coalesces into 1 submit (#2). + EXPECT(queue.execute({&steps[1], 1}) == ReplayResult::success); + EXPECT(queue.execute({&steps[2], 1}) == ReplayResult::success); + EXPECT(queue.execute({&steps[3], 1}) == ReplayResult::success); + // Split 1: Signal(mid, 1). + EXPECT(queue.signal(mid.semaphore(), 1)); + // Group B: 2 consecutive execute batches -> coalesces into 1 submit (#3). + EXPECT(queue.execute({&steps[4], 1}) == ReplayResult::success); + EXPECT(queue.execute({&steps[5], 1}) == ReplayResult::success); + // Split 2: Wait(mid, 1). + queue.wait(mid.semaphore(), 1); + // Group C: 2 consecutive execute batches -> coalesces into 1 submit (#4). + EXPECT(queue.execute({&steps[6], 1}) == ReplayResult::success); + EXPECT(queue.execute({&steps[7], 1}) == ReplayResult::success); + // Split 3: Present barrier (after_held). + std::atomic present_saw_submits{0}; + int present_owner = 0; + context.holds().after_held(&present_owner, [&] { + present_saw_submits.store(s_cb_submits.load(std::memory_order_acquire), std::memory_order_release); + }); + // Group D: 1 execute batch after Present -> 1 submit (#5). + EXPECT(queue.execute({&steps[8], 1}) == ReplayResult::success); + EXPECT(queue.signal(done.semaphore(), 1)); + + go_first.store(true, std::memory_order_release); + EXPECT(done.wait(1, 5'000'000'000ull)); + EXPECT(queue.idle()); + + // 9 execute calls coalesced into 4 (when mid already GPU-completed before Wait(mid)) or 5 submits! + const unsigned bc = before_calls.load(std::memory_order_acquire); + const unsigned sc = s_cb_submits.load(std::memory_order_acquire); + const unsigned ps = present_saw_submits.load(std::memory_order_acquire); + EXPECT((bc == 4 || bc == 5) && sc == bc && ps == bc - 1); + for (int i = 0; i < 9; ++i) EXPECT(db[(i + 1) * 16] == std::uint8_t(0xD0 + i)); + EXPECT(db[0] == std::uint8_t(0xD8)); // exact FIFO overwrite order preserved across inter-batch barriers + std::printf("queue async submit merging: 9 batches -> 5 submits, split cleanly on Signal/Wait/Present ok\n"); + } + + // 7. ASYNC enqueue-serial retirement epoch contract (set_on_enqueue_execute / set_on_finish_execute): + // A view retired with kAfterExecutes during batch 1's before_execute_() must NOT be stamped or reaped while + // an already-enqueued batch 2 is still waiting in async inbox_, even after batch 1's GPU work completes! + { + // Mirrors GeometryViews' exact execute_enqueue / retire(kAfterExecutes) / execute_end / reap state machine. + struct EpochTracker { + enum : std::uint64_t { kAfterExecutes = UINT64_MAX }; + struct Retired { + std::uint64_t id = 0; + std::uint64_t ticket = kAfterExecutes; + std::uint64_t epoch = 0; + }; + std::mutex mutex, execute_mutex; + std::vector executing; + std::vector retired; + std::uint64_t execute_serial = 0; + std::atomic unstamped{false}; + std::uint64_t reaped = 0; + + std::uint64_t execute_enqueue() { + std::lock_guard lock(execute_mutex); + executing.push_back(++execute_serial); + return execute_serial; + } + void retire(std::uint64_t id) { + std::lock_guard lock(mutex); + std::uint64_t epoch = 0; + { + std::lock_guard exec(execute_mutex); + epoch = execute_serial; + } + unstamped.store(true, std::memory_order_release); + retired.push_back({id, kAfterExecutes, epoch}); + } + void execute_end(std::uint64_t serial, const std::function& submitted) { + if (!serial) return; + { + std::lock_guard exec(execute_mutex); + std::erase(executing, serial); + } + if (!unstamped.load(std::memory_order_acquire)) return; + std::lock_guard lock(mutex); + std::uint64_t oldest = kAfterExecutes; + { + std::lock_guard exec(execute_mutex); + for (const auto s : executing) oldest = std::min(oldest, s); + } + const std::uint64_t ticket = submitted(); + bool left = false; + for (auto& r : retired) { + if (r.ticket != kAfterExecutes) continue; + if (r.epoch < oldest) r.ticket = ticket; + else left = true; + } + unstamped.store(left, std::memory_order_release); + } + std::size_t reap(std::uint64_t completed) { + std::lock_guard lock(mutex); + std::size_t freed = 0, keep = 0; + for (std::size_t i = 0; i < retired.size(); ++i) { + if (retired[i].ticket != kAfterExecutes && retired[i].ticket <= completed) { + ++reaped; + ++freed; + } else { + if (keep != i) retired[keep] = retired[i]; + ++keep; + } + } + retired.resize(keep); + return freed; + } + } tracker; + + VulkanContext context(d.device_proc, d.device, true); + EXPECT(context.loaded()); + context.set_on_enqueue_execute([&] { return tracker.execute_enqueue(); }); + context.set_on_finish_execute( + [&](std::uint64_t serial) { tracker.execute_end(serial, [&] { return context.submitted_retire_ticket(); }); }); + + VulkanQueue queue(context, d.queue, d.family, VulkanQueue::QueueKind::direct); + EXPECT(queue.ok()); + queue.set_async_depth(4); + + auto empty_list = std::make_shared(); + EXPECT(empty_list->uav_barrier({}) && empty_list->close()); + std::shared_ptr snap = empty_list; + + std::atomic before_n{0}; + std::atomic b1_entered{false}, b1_go{false}, b2_entered{false}, b2_go{false}; + context.set_before_execute([&] { + const unsigned n = before_n.fetch_add(1, std::memory_order_acq_rel) + 1; + if (n == 1) { + b1_entered.store(true, std::memory_order_release); + while (!b1_go.load(std::memory_order_acquire)) std::this_thread::yield(); + // Batch 1 retires view #1 AFTER batch 2 has already been enqueued in inbox_! + tracker.retire(1); + } else if (n == 2) { + b2_entered.store(true, std::memory_order_release); + while (!b2_go.load(std::memory_order_acquire)) std::this_thread::yield(); + } + }); + + // 1. Enqueue batch 1 (serial 1); wait until worker enters batch 1's before_execute_(). + EXPECT(queue.execute({&snap, 1}) == ReplayResult::success); + while (!b1_entered.load(std::memory_order_acquire)) std::this_thread::yield(); + + // 2. Title thread enqueues batch 2 (serial 2) + batch 3 (serial 3) into inbox_ while batch 1 is in flight! + VulkanFence done(context, 0); + EXPECT(done.semaphore() != VK_NULL_HANDLE); + EXPECT(queue.execute({&snap, 1}) == ReplayResult::success); + EXPECT(queue.execute({&snap, 1}) == ReplayResult::success); + EXPECT(queue.signal(done.semaphore(), 1)); + + // 3. Let batch 1 retire view #1, submit to Vulkan, and finish; worker then coalesces {batch 2, batch 3} and + // pauses at n == 2 inside before_execute_(). + b1_go.store(true, std::memory_order_release); + while (!b2_entered.load(std::memory_order_acquire)) std::this_thread::yield(); + + // Wait until batch 1's GPU submission has completely retired on the GPU! + const std::uint64_t b1_ticket = context.submitted_retire_ticket(); + EXPECT(b1_ticket >= 1); + EXPECT(context.wait_retire_ticket(b1_ticket) >= b1_ticket); + + // CRITICAL INVARIANT: Even though batch 1's GPU work is 100% done, view #1 MUST NOT be reaped because + // {batch 2, batch 3} (enqueued BEFORE view #1 retired!) have not submitted yet! + EXPECT(tracker.reap(context.completed_retire_ticket()) == 0); + EXPECT(tracker.reaped == 0); + + // 4. Release {batch 2, batch 3}: both serials 2 and 3 finish after the coalesced vkQueueSubmit, stamping + // view #1 with the coalesced submit ticket; once GPU completes, view #1 reaps cleanly! + b2_go.store(true, std::memory_order_release); + EXPECT(done.wait(1, 5'000'000'000ull)); + EXPECT(queue.idle()); + EXPECT(tracker.reap(context.completed_retire_ticket()) == 1); + EXPECT(tracker.reaped == 1); + std::printf("queue async retirement epoch: view deferred across queued & coalesced inbox batches ok\n"); + } + + // 8. set_skip_before_execute(true) (internal staging_queue path): skips before_execute_(), after_execute_(), + // on_enqueue_execute_ / on_finish_execute_, non-shader bindless/prelude prep, and submit_phases accounting, + // while normal queues (and toggling back to false) still invoke all of them. + { + VulkanContext context(d.device_proc, d.device, true); + EXPECT(context.loaded()); + + void* src_map = nullptr; + void* dst_map = nullptr; + VkBuffer src = d.buffer(kBufBytes, usage, &src_map); + VkBuffer dst = d.buffer(kBufBytes, usage, &dst_map); + EXPECT(src && dst); + auto* sb = static_cast(src_map); + auto* db = static_cast(dst_map); + std::memset(sb, 0, kBufBytes); + std::memset(db, 0, kBufBytes); + sb[0] = 0x5A; + sb[16] = 0x6B; + sb[32] = 0x7C; + + ResourceBinding r_src{}, r_dst{}; + r_src.buffer = src; + r_src.size = kBufBytes; + r_dst.buffer = dst; + r_dst.size = kBufBytes; + r_dst.host_readable = true; + context.add_resource(1, r_src); + context.add_resource(2, r_dst); + + std::atomic before_calls{0}, after_calls{0}, enqueue_calls{0}, finish_calls{0}; + std::atomic bindless_calls{0}, prelude_calls{0}; + std::atomic next_serial{0}; + context.set_before_execute([&] { before_calls.fetch_add(1, std::memory_order_acq_rel); }); + context.set_after_execute([&] { after_calls.fetch_add(1, std::memory_order_acq_rel); }); + context.set_on_enqueue_execute([&] { + enqueue_calls.fetch_add(1, std::memory_order_acq_rel); + return next_serial.fetch_add(1, std::memory_order_acq_rel) + 1; + }); + context.set_on_finish_execute([&](std::uint64_t) { finish_calls.fetch_add(1, std::memory_order_acq_rel); }); + context.set_bindless_prepare([&](VkCommandBuffer) { + bindless_calls.fetch_add(1, std::memory_order_acq_rel); + return true; + }); + context.set_prelude( + [&](VkCommandBuffer) { + prelude_calls.fetch_add(1, std::memory_order_acq_rel); + return false; + }, + {}); + + VulkanQueue staging_q(context, d.queue, d.family, VulkanQueue::QueueKind::direct); + VulkanQueue normal_q(context, d.queue, d.family, VulkanQueue::QueueKind::direct); + EXPECT(staging_q.ok() && normal_q.ok()); + staging_q.make_synchronous(); + staging_q.set_skip_before_execute(true); + EXPECT(staging_q.skip_before_execute()); + EXPECT(!normal_q.skip_before_execute()); + normal_q.set_async_depth(0); + + auto copy0 = make_copy_list(2, 0, 1, 0, 1); + auto copy1 = make_copy_list(2, 16, 1, 16, 1); + auto copy2 = make_copy_list(2, 32, 1, 32, 1); + EXPECT(copy0 && copy1 && copy2); + + const std::uint64_t subs_before = load(sp::totals().submissions); + const std::uint64_t direct_before = load(sp::frame_totals().submissions[0]); + const CommandList* raw0[] = {copy0.get()}; + EXPECT(staging_q.execute(raw0) == ReplayResult::success); + EXPECT(staging_q.idle()); + EXPECT(db[0] == 0x5A); + EXPECT(before_calls.load(std::memory_order_acquire) == 0); + EXPECT(after_calls.load(std::memory_order_acquire) == 0); + EXPECT(enqueue_calls.load(std::memory_order_acquire) == 0); + EXPECT(finish_calls.load(std::memory_order_acquire) == 0); + EXPECT(bindless_calls.load(std::memory_order_acquire) == 0); + EXPECT(prelude_calls.load(std::memory_order_acquire) == 0); + EXPECT(load(sp::totals().submissions) == subs_before); + EXPECT(load(sp::frame_totals().submissions[0]) == direct_before); + + const CommandList* raw1[] = {copy1.get()}; + EXPECT(normal_q.execute(raw1) == ReplayResult::success); + EXPECT(normal_q.idle()); + EXPECT(db[16] == 0x6B); + EXPECT(before_calls.load(std::memory_order_acquire) == 1); + EXPECT(after_calls.load(std::memory_order_acquire) == 1); + EXPECT(enqueue_calls.load(std::memory_order_acquire) == 1); + EXPECT(finish_calls.load(std::memory_order_acquire) == 1); + EXPECT(bindless_calls.load(std::memory_order_acquire) == 1); + EXPECT(prelude_calls.load(std::memory_order_acquire) == 1); + EXPECT(load(sp::totals().submissions) == subs_before + 1); + EXPECT(load(sp::frame_totals().submissions[0]) == direct_before + 1); + + // Toggling set_skip_before_execute(false) restores normal callbacks on the same queue. + staging_q.set_skip_before_execute(false); + EXPECT(!staging_q.skip_before_execute()); + const CommandList* raw2[] = {copy2.get()}; + EXPECT(staging_q.execute(raw2) == ReplayResult::success); + EXPECT(staging_q.idle()); + EXPECT(db[32] == 0x7C); + EXPECT(before_calls.load(std::memory_order_acquire) == 2); + EXPECT(after_calls.load(std::memory_order_acquire) == 2); + EXPECT(enqueue_calls.load(std::memory_order_acquire) == 2); + EXPECT(finish_calls.load(std::memory_order_acquire) == 2); + std::printf("queue set_skip_before_execute: staging skips hooks/phases while normal queue invokes all ok\n"); + } + + // 9. Cross-queue Signal() / pump_ready() -> release_ready() and no-op debug markers must NOT split coalescing + // (in either inbox_ or held_), while a real after_held() (Present) barrier DOES split coalescing and runs + // strictly between pre-barrier and post-barrier batches; coalesced batches release (K - 1) inbox_batches_ + // slots immediately so async_depth_=4 does not stall enqueue() while a coalesced batch runs. + { + static PFN_vkQueueSubmit s_real_submit = nullptr; + static std::atomic s_cb_submits{0}; + struct HookSubmit { + static VKAPI_ATTR VkResult VKAPI_CALL call(VkQueue q, std::uint32_t count, const VkSubmitInfo* infos, + VkFence fence) { + for (std::uint32_t i = 0; i < count; ++i) + if (infos[i].commandBufferCount > 0) s_cb_submits.fetch_add(1, std::memory_order_relaxed); + return s_real_submit(q, count, infos, fence); + } + }; + + VulkanContext context(d.device_proc, d.device, true); + EXPECT(context.loaded()); + s_real_submit = context.vk.vkQueueSubmit; + s_cb_submits.store(0, std::memory_order_relaxed); + context.vk.vkQueueSubmit = &HookSubmit::call; + + VulkanQueue direct(context, d.queue, d.family, VulkanQueue::QueueKind::direct); + VulkanQueue compute(context, d.queue, d.family, VulkanQueue::QueueKind::compute); + EXPECT(direct.ok() && compute.ok()); + direct.set_async_depth(4); + compute.set_async_depth(4); + + void* src_map = nullptr; + void* dst_map = nullptr; + VkBuffer src = d.buffer(kBufBytes, usage, &src_map); + VkBuffer dst = d.buffer(kBufBytes, usage, &dst_map); + EXPECT(src && dst); + auto* sb = static_cast(src_map); + auto* db = static_cast(dst_map); + std::memset(db, 0, kBufBytes); + for (int i = 0; i < 7; ++i) sb[i * 16] = std::uint8_t(0xE0 + i); + + ResourceBinding r_src{}, r_dst{}; + r_src.buffer = src; + r_src.size = kBufBytes; + r_dst.buffer = dst; + r_dst.size = kBufBytes; + r_dst.host_readable = true; + context.add_resource(1, r_src); + context.add_resource(2, r_dst); + + std::shared_ptr steps[7]; + for (int i = 0; i < 7; ++i) { + auto l = std::make_shared(); + EXPECT(l->copy_buffer({2, std::uint64_t((i + 1) * 16), 1, std::uint64_t(i * 16), 1}) && + l->copy_buffer({2, 0, 1, std::uint64_t(i * 16), 1}) && l->close()); + steps[i] = std::move(l); + } + + // (a) Cross-queue Signals (pump_ready() -> release_ready()) and no-op markers do NOT split inbox coalescing, + // while a real after_held() barrier DOES split coalescing strictly between {B1, B2} and {B3}. + std::atomic before_calls{0}; + std::atomic in_first{false}, go_first{false}; + context.set_before_execute([&] { + const unsigned n = before_calls.fetch_add(1, std::memory_order_acq_rel) + 1; + if (n == 1) { + in_first.store(true, std::memory_order_release); + while (!go_first.load(std::memory_order_acquire)) std::this_thread::yield(); + } + }); + + VulkanFence cross_fence(context, 0), done_a(context, 0); + EXPECT(cross_fence.semaphore() && done_a.semaphore()); + + EXPECT(direct.execute({&steps[0], 1}) == ReplayResult::success); + while (!in_first.load(std::memory_order_acquire)) std::this_thread::yield(); + + EXPECT(direct.execute({&steps[1], 1}) == ReplayResult::success); + // Cross-queue Signal triggers QueueHolds::pump_ready() -> direct.release_ready() while B1 sits in direct.inbox_. + EXPECT(compute.signal(cross_fence.semaphore(), 1)); + EXPECT(cross_fence.wait(1, 5'000'000'000ull)); + EXPECT(compute.idle()); + // No-op debug marker (debug_labels() == false) must also not split inbox coalescing. + direct.marker(DebugMarker::Kind::set, "noop-marker"); + EXPECT(direct.execute({&steps[2], 1}) == ReplayResult::success); + EXPECT(compute.signal(cross_fence.semaphore(), 2)); + EXPECT(cross_fence.wait(2, 5'000'000'000ull)); + EXPECT(compute.idle()); + + // Real after_held() (Present) barrier MUST split coalescing between {B1, B2} and {B3}. + std::atomic barrier_ran{false}; + std::atomic barrier_seen_before{0}, barrier_seen_submits{0}; + int barrier_owner = 0; + context.holds().after_held(&barrier_owner, [&] { + barrier_seen_before.store(before_calls.load(std::memory_order_acquire), std::memory_order_release); + barrier_seen_submits.store(s_cb_submits.load(std::memory_order_acquire), std::memory_order_release); + barrier_ran.store(true, std::memory_order_release); + }); + + EXPECT(direct.execute({&steps[3], 1}) == ReplayResult::success); + EXPECT(direct.signal(done_a.semaphore(), 1)); + + go_first.store(true, std::memory_order_release); + EXPECT(done_a.wait(1, 5'000'000'000ull)); + EXPECT(direct.idle()); + + EXPECT(barrier_ran.load(std::memory_order_acquire)); + EXPECT(before_calls.load(std::memory_order_acquire) == 3); // {B0}, coalesced {B1, B2}, {B3} + EXPECT(s_cb_submits.load(std::memory_order_acquire) == 3); + EXPECT(barrier_seen_before.load(std::memory_order_acquire) == 2); + EXPECT(barrier_seen_submits.load(std::memory_order_acquire) == 2); + for (int i = 0; i < 4; ++i) EXPECT(db[(i + 1) * 16] == std::uint8_t(0xE0 + i)); + EXPECT(db[0] == 0xE3); + + // (b) Cross-queue Signals calling direct.release_ready() while batches sit in direct.held_ must NOT split + // held-batch coalescing either. + before_calls.store(0, std::memory_order_release); + s_cb_submits.store(0, std::memory_order_release); + std::memset(db, 0, kBufBytes); + context.set_before_execute([&] { before_calls.fetch_add(1, std::memory_order_acq_rel); }); + + VulkanFence gate_b(context, 0), done_b(context, 0); + EXPECT(gate_b.semaphore() && done_b.semaphore()); + direct.wait(gate_b.semaphore(), 1); + EXPECT(direct.execute({&steps[0], 1}) == ReplayResult::success); + EXPECT(direct.idle()); // steps[0] is now in direct.held_ + EXPECT(compute.signal(cross_fence.semaphore(), 3)); + EXPECT(cross_fence.wait(3, 5'000'000'000ull)); + EXPECT(compute.idle()); + EXPECT(direct.execute({&steps[1], 1}) == ReplayResult::success); + EXPECT(direct.signal(done_b.semaphore(), 1)); + EXPECT(direct.idle()); // steps[1] + signal are now in direct.held_ behind steps[0] + EXPECT(compute.signal(cross_fence.semaphore(), 4)); + EXPECT(cross_fence.wait(4, 5'000'000'000ull)); + EXPECT(compute.idle()); + EXPECT(before_calls.load(std::memory_order_acquire) == 0); + + EXPECT(gate_b.signal(1)); + EXPECT(done_b.wait(1, 5'000'000'000ull)); + EXPECT(direct.idle()); + EXPECT(before_calls.load(std::memory_order_acquire) == 1); // {steps[0], steps[1]} coalesced into 1 submit + EXPECT(s_cb_submits.load(std::memory_order_acquire) == 1); + EXPECT(db[16] == 0xE0 && db[32] == 0xE1 && db[0] == 0xE1); + + // (c) async_depth_=4 backpressure: while coalesced {B1, B2, B3} is running as 1 in-flight submission, + // enqueuing 3 more batches {B4, B5, B6} must NOT stall on room_cv_ and must coalesce into 1 submit. + before_calls.store(0, std::memory_order_release); + s_cb_submits.store(0, std::memory_order_release); + std::memset(db, 0, kBufBytes); + std::atomic p1_in{false}, p1_go{false}, p2_in{false}, p2_go{false}; + context.set_before_execute([&] { + const unsigned n = before_calls.fetch_add(1, std::memory_order_acq_rel) + 1; + if (n == 1) { + p1_in.store(true, std::memory_order_release); + while (!p1_go.load(std::memory_order_acquire)) std::this_thread::yield(); + } else if (n == 2) { + p2_in.store(true, std::memory_order_release); + while (!p2_go.load(std::memory_order_acquire)) std::this_thread::yield(); + } + }); + + VulkanFence done_c(context, 0); + EXPECT(done_c.semaphore()); + EXPECT(direct.execute({&steps[0], 1}) == ReplayResult::success); + while (!p1_in.load(std::memory_order_acquire)) std::this_thread::yield(); + EXPECT(direct.execute({&steps[1], 1}) == ReplayResult::success); + EXPECT(direct.execute({&steps[2], 1}) == ReplayResult::success); + EXPECT(direct.execute({&steps[3], 1}) == ReplayResult::success); + + // Release B0 -> worker pops coalesced {B1, B2, B3}, releases 2 batch slots immediately, and pauses at n == 2. + p1_go.store(true, std::memory_order_release); + while (!p2_in.load(std::memory_order_acquire)) std::this_thread::yield(); + + // Enqueue 3 more batches on a separate thread while {B1, B2, B3} is paused: must finish without stalling! + std::atomic queued_next_three{false}; + std::thread producer([&] { + const bool ok4 = direct.execute({&steps[4], 1}) == ReplayResult::success; + const bool ok5 = direct.execute({&steps[5], 1}) == ReplayResult::success; + const bool ok6 = direct.execute({&steps[6], 1}) == ReplayResult::success; + const bool ok_sig = direct.signal(done_c.semaphore(), 1); + if (ok4 && ok5 && ok6 && ok_sig) queued_next_three.store(true, std::memory_order_release); + }); + const auto wait_deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(500); + while (!queued_next_three.load(std::memory_order_acquire) && std::chrono::steady_clock::now() < wait_deadline) + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + const bool non_stalling = queued_next_three.load(std::memory_order_acquire); + p2_go.store(true, std::memory_order_release); + producer.join(); + EXPECT(non_stalling); + EXPECT(done_c.wait(1, 5'000'000'000ull)); + EXPECT(direct.idle()); + EXPECT(before_calls.load(std::memory_order_acquire) == 3); // {B0}, {B1..B3}, {B4..B6} + EXPECT(s_cb_submits.load(std::memory_order_acquire) == 3); + for (int i = 0; i < 7; ++i) EXPECT(db[(i + 1) * 16] == std::uint8_t(0xE0 + i)); + EXPECT(db[0] == 0xE6); + std::printf("queue cross-queue Signal & depth=4 coalescing: inbox/held merge, Present split & non-stalling room ok\n"); + } + + // 10. Present / after_held() barrier ordering across held batches (P0 regressions): + // (a) Race A: PresentX (TitleCall(part_present) + after_held()) when another queue short-circuits + // QueueHolds::run_barriers() so direct->oldest_held_seq() is NOT called before post-Present B2 & B3 + // enter direct.held_. Immutable per-op present_epoch MUST split B1 from {B2, B3}, fire Present0 + // strictly between B1 and {B2, B3}, and still coalesce {B2, B3} into 1 submit. + // (b) Race B: Generic after_held() (no present_calls bump) racing with B1 moving inbox_ -> running_seq_ -> + // held_ before post-barrier B2 & B3 enqueue. Monotonic barrier_seq_ + pause_release_for_barrier_ MUST + // split B1 from {B2, B3} and fire barrier strictly between B1 and {B2, B3} on every iteration. + { + static PFN_vkQueueSubmit s_real_submit = nullptr; + static std::atomic s_cb_submits{0}; + struct HookSubmit { + static VKAPI_ATTR VkResult VKAPI_CALL call(VkQueue q, std::uint32_t count, const VkSubmitInfo* infos, + VkFence fence) { + for (std::uint32_t i = 0; i < count; ++i) + if (infos[i].commandBufferCount > 0) s_cb_submits.fetch_add(1, std::memory_order_relaxed); + return s_real_submit(q, count, infos, fence); + } + }; + + VulkanContext context(d.device_proc, d.device, true); + EXPECT(context.loaded()); + s_real_submit = context.vk.vkQueueSubmit; + s_cb_submits.store(0, std::memory_order_relaxed); + context.vk.vkQueueSubmit = &HookSubmit::call; + + // `blocker` is attached BEFORE `direct` so QueueHolds::run_barriers() inspects `blocker` first and + // short-circuits before calling `direct.oldest_held_seq()` while `blocker` holds an older seq. + VulkanQueue blocker(context, d.queue, d.family, VulkanQueue::QueueKind::compute); + VulkanQueue direct(context, d.queue, d.family, VulkanQueue::QueueKind::direct); + EXPECT(blocker.ok() && direct.ok()); + blocker.set_async_depth(4); + direct.set_async_depth(4); + + void* src_map = nullptr; + void* dst_map = nullptr; + VkBuffer src = d.buffer(kBufBytes, usage, &src_map); + VkBuffer dst = d.buffer(kBufBytes, usage, &dst_map); + EXPECT(src && dst); + auto* sb = static_cast(src_map); + auto* db = static_cast(dst_map); + std::memset(db, 0, kBufBytes); + sb[0] = 0xF1; + sb[16] = 0xF2; + sb[32] = 0xF3; + + ResourceBinding r_src{}, r_dst{}; + r_src.buffer = src; + r_src.size = kBufBytes; + r_dst.buffer = dst; + r_dst.size = kBufBytes; + r_dst.host_readable = true; + context.add_resource(1, r_src); + context.add_resource(2, r_dst); + + std::shared_ptr steps[3]; + for (int i = 0; i < 3; ++i) { + auto l = std::make_shared(); + EXPECT(l->copy_buffer({2, std::uint64_t((i + 1) * 16), 1, std::uint64_t(i * 16), 1}) && + l->copy_buffer({2, 0, 1, std::uint64_t(i * 16), 1}) && l->close()); + steps[i] = std::move(l); + } + + // (a) Race A: PresentX with short-circuited run_barriers() -> immutable present_epoch splits B1 from {B2, B3}. + std::atomic before_calls{0}; + context.set_before_execute([&] { before_calls.fetch_add(1, std::memory_order_acq_rel); }); + + VulkanFence blk_gate(context, 0), blk_done(context, 0), dir_gate(context, 0), dir_done(context, 0); + EXPECT(blk_gate.semaphore() && blk_done.semaphore() && dir_gate.semaphore() && dir_done.semaphore()); + + // Hold a Signal on `blocker` (holder 0, seq=1) so run_barriers() returns early without touching `direct`. + blocker.wait(blk_gate.semaphore(), 1); + EXPECT(blocker.signal(blk_done.semaphore(), 1)); + EXPECT(blocker.idle()); + + // Frame 0: hold B1 on `direct` behind dir_gate (epoch = E0). + direct.wait(dir_gate.semaphore(), 1); + EXPECT(direct.execute({&steps[0], 1}) == ReplayResult::success); + EXPECT(direct.idle()); // B1 is now in direct.held_ with epoch = E0 + + // Frame 0 PresentX: bumps present_calls to E0 + 1 and registers after_held(Present0). + // Because `blocker` holds seq=1, run_barriers() short-circuits and NEVER calls direct.oldest_held_seq()! + std::atomic present_ran{false}; + std::atomic present_seen_before{0}, present_seen_submits{0}; + int present_owner = 0; + { + const sp::TitleCall present_call(sp::part_present); + context.holds().after_held(&present_owner, [&] { + present_seen_before.store(before_calls.load(std::memory_order_acquire), std::memory_order_release); + present_seen_submits.store(s_cb_submits.load(std::memory_order_acquire), std::memory_order_release); + present_ran.store(true, std::memory_order_release); + }); + } + + // Frame 1: enqueue post-Present B2 & B3 onto `direct` (epoch = E0 + 1), both landing in direct.held_. + EXPECT(direct.execute({&steps[1], 1}) == ReplayResult::success); + EXPECT(direct.execute({&steps[2], 1}) == ReplayResult::success); + EXPECT(direct.signal(dir_done.semaphore(), 1)); + EXPECT(direct.idle()); + EXPECT(!present_ran.load(std::memory_order_acquire)); + EXPECT(before_calls.load(std::memory_order_acquire) == 0); + + // Release `blocker` first, then `direct`: B1 must run alone, Present0 must fire at count==1, then {B2, B3} + // must coalesce into submit #2! + EXPECT(blk_gate.signal(1)); + EXPECT(blk_done.wait(1, 5'000'000'000ull)); + EXPECT(blocker.idle()); + EXPECT(!present_ran.load(std::memory_order_acquire)); + + EXPECT(dir_gate.signal(1)); + EXPECT(dir_done.wait(1, 5'000'000'000ull)); + EXPECT(direct.idle()); + + EXPECT(present_ran.load(std::memory_order_acquire)); + EXPECT(present_seen_before.load(std::memory_order_acquire) == 1); + EXPECT(present_seen_submits.load(std::memory_order_acquire) == 1); + EXPECT(before_calls.load(std::memory_order_acquire) == 2); // {B1}, then coalesced {B2, B3} + EXPECT(s_cb_submits.load(std::memory_order_acquire) == 2); + EXPECT(db[16] == 0xF1 && db[32] == 0xF2 && db[48] == 0xF3 && db[0] == 0xF3); + + // (b) Race B: Generic after_held() (NO present_calls bump) racing with in-transit B1 (inbox_ -> + // running_seq_ -> held_) followed by B2 & B3, repeated 20 times to cover every transit state. + for (int iter = 0; iter < 20; ++iter) { + before_calls.store(0, std::memory_order_release); + s_cb_submits.store(0, std::memory_order_release); + std::memset(db, 0, kBufBytes); + VulkanFence g(context, 0), done(context, 0); + EXPECT(g.semaphore() && done.semaphore()); + + direct.wait(g.semaphore(), 1); + EXPECT(direct.execute({&steps[0], 1}) == ReplayResult::success); + // Do NOT flush direct before after_held(): B1 may be in inbox_, in-transit (running_seq_), or in held_. + std::atomic b_ran{false}; + std::atomic b_seen_before{0}, b_seen_submits{0}; + int b_owner = 0; + context.holds().after_held(&b_owner, [&] { + b_seen_before.store(before_calls.load(std::memory_order_acquire), std::memory_order_release); + b_seen_submits.store(s_cb_submits.load(std::memory_order_acquire), std::memory_order_release); + b_ran.store(true, std::memory_order_release); + }); + EXPECT(direct.execute({&steps[1], 1}) == ReplayResult::success); + EXPECT(direct.execute({&steps[2], 1}) == ReplayResult::success); + EXPECT(direct.signal(done.semaphore(), 1)); + EXPECT(direct.idle()); + EXPECT(!b_ran.load(std::memory_order_acquire)); + + EXPECT(g.signal(1)); + EXPECT(done.wait(1, 5'000'000'000ull)); + EXPECT(direct.idle()); + + EXPECT(b_ran.load(std::memory_order_acquire)); + EXPECT(b_seen_before.load(std::memory_order_acquire) == 1); + EXPECT(b_seen_submits.load(std::memory_order_acquire) == 1); + EXPECT(before_calls.load(std::memory_order_acquire) == 2); // {B1}, then coalesced {B2, B3} + EXPECT(s_cb_submits.load(std::memory_order_acquire) == 2); + EXPECT(db[16] == 0xF1 && db[32] == 0xF2 && db[48] == 0xF3 && db[0] == 0xF3); + } + std::printf("queue held Present/after_held barrier ordering: present_epoch & in-transit barrier_seq_ ok\n"); + } + + // 10. note_mirror_bind() returns the latest submitted retire ticket under submit_mutex_, and every subsequent + // command-buffer submission on VulkanQueue waits on the newly published mirror bind timeline semaphore value. + { + VulkanContext context(d.device_proc, d.device, true); + EXPECT(context.loaded()); + VulkanQueue queue(context, d.queue, d.family, VulkanQueue::QueueKind::direct); + EXPECT(queue.ok()); + + auto empty = std::make_shared(); + EXPECT(empty->close()); + std::shared_ptr snap = empty; + + EXPECT(queue.execute({&snap, 1}) == ReplayResult::success); + EXPECT(queue.idle()); + const std::uint64_t t_before = context.submitted_retire_ticket(); + EXPECT(t_before >= 1); + + VulkanFence mirror_tl(context, 0), done(context, 0); + EXPECT(mirror_tl.semaphore() != VK_NULL_HANDLE && done.semaphore() != VK_NULL_HANDLE); + const std::uint64_t bind_ticket = context.note_mirror_bind(mirror_tl.semaphore(), 1); + EXPECT(bind_ticket == t_before); + { + std::lock_guard lock(context.submit_mutex()); + VkSemaphore seen_sem = VK_NULL_HANDLE; + std::uint64_t seen_val = 0; + context.mirror_bind_locked(seen_sem, seen_val); + EXPECT(seen_sem == mirror_tl.semaphore() && seen_val == 1); + } + + // Next submission MUST wait on (mirror_tl, 1) before completing on the GPU. + EXPECT(queue.execute({&snap, 1}) == ReplayResult::success); + EXPECT(queue.signal(done.semaphore(), 1)); + EXPECT(!done.wait(1, 20'000'000ull)); // 20 ms: still blocked waiting for mirror_tl == 1 + EXPECT(mirror_tl.signal(1)); + EXPECT(done.wait(1, 5'000'000'000ull)); + EXPECT(queue.idle()); + EXPECT(context.submitted_retire_ticket() > bind_ticket); + std::printf("note_mirror_bind ticket & submit wait ordering: ok\n"); + } + + // 11. Round 5 same-queue execute+signal coalescing, depth=4 frame-burst room gating, cross-queue Wait split, + // Present barrier split, and coalesced error fallback isolation (LEONIDA_VK_VALIDATION=1 clean). + { + static PFN_vkQueueSubmit s_real_submit = nullptr; + static std::atomic s_cb_submits{0}; + static std::atomic s_total_submits{0}; + struct HookSubmit { + static VKAPI_ATTR VkResult VKAPI_CALL call(VkQueue q, std::uint32_t count, const VkSubmitInfo* infos, + VkFence fence) { + for (std::uint32_t i = 0; i < count; ++i) { + s_total_submits.fetch_add(1, std::memory_order_relaxed); + if (infos[i].commandBufferCount > 0) s_cb_submits.fetch_add(1, std::memory_order_relaxed); + } + return s_real_submit(q, count, infos, fence); + } + }; + + VulkanContext context(d.device_proc, d.device, true); + EXPECT(context.loaded()); + s_real_submit = context.vk.vkQueueSubmit; + s_cb_submits.store(0, std::memory_order_relaxed); + s_total_submits.store(0, std::memory_order_relaxed); + context.vk.vkQueueSubmit = &HookSubmit::call; + + VulkanQueue direct(context, d.queue, d.family, VulkanQueue::QueueKind::direct); + VulkanQueue compute(context, d.queue, d.family, VulkanQueue::QueueKind::compute); + VulkanQueue copy_q(context, d.queue, d.family, VulkanQueue::QueueKind::copy); + EXPECT(direct.ok() && compute.ok() && copy_q.ok()); + direct.set_async_depth(4); + compute.set_async_depth(4); + copy_q.set_async_depth(4); + + constexpr VkDeviceSize kBurstBufBytes = 512; + void* src_map = nullptr; + void* dst_map = nullptr; + VkBuffer src = d.buffer(kBurstBufBytes, usage, &src_map); + VkBuffer dst = d.buffer(kBurstBufBytes, usage, &dst_map); + EXPECT(src && dst); + auto* sb = static_cast(src_map); + auto* db = static_cast(dst_map); + std::memset(sb, 0, kBurstBufBytes); + std::memset(db, 0, kBurstBufBytes); + constexpr int kSteps = 18; + for (int i = 0; i < kSteps; ++i) sb[i * 16] = std::uint8_t(0x40 + i); + + ResourceBinding r_src{}, r_dst{}; + r_src.buffer = src; + r_src.size = kBurstBufBytes; + r_dst.buffer = dst; + r_dst.size = kBurstBufBytes; + r_dst.host_readable = true; + context.add_resource(1, r_src); + context.add_resource(2, r_dst); + + std::shared_ptr steps[kSteps]; + for (int i = 0; i < kSteps; ++i) { + auto l = std::make_shared(); + EXPECT(l->copy_buffer({2, std::uint64_t((i + 1) * 16), 1, std::uint64_t(i * 16), 1}) && + l->copy_buffer({2, 0, 1, std::uint64_t(i * 16), 1}) && l->close()); + steps[i] = std::move(l); + } + + // (a) Unwaited [execute, signal(F, 1), execute, signal(F, 2), execute, signal(F, 3), execute, signal(F, 4)] + // plus trailing signal(F2, 7) coalesces into ONE before_execute_() + ONE vkQueueSubmit (deduping F -> 4). + std::atomic before_calls{0}; + std::atomic in_first{false}, go_first{false}; + context.set_before_execute([&] { + const unsigned n = before_calls.fetch_add(1, std::memory_order_acq_rel) + 1; + if (n == 1) { + in_first.store(true, std::memory_order_release); + while (!go_first.load(std::memory_order_acquire)) std::this_thread::yield(); + } + }); + + VulkanFence f_a(context, 0), f_a2(context, 0); + EXPECT(f_a.semaphore() && f_a2.semaphore()); + + EXPECT(direct.execute({&steps[0], 1}) == ReplayResult::success); + while (!in_first.load(std::memory_order_acquire)) std::this_thread::yield(); + + for (int i = 1; i <= 4; ++i) { + EXPECT(direct.execute({&steps[i], 1}) == ReplayResult::success); + EXPECT(direct.signal(f_a.semaphore(), std::uint64_t(i))); + } + EXPECT(direct.signal(f_a2.semaphore(), 7)); + + go_first.store(true, std::memory_order_release); + EXPECT(f_a.wait(4, 5'000'000'000ull)); + EXPECT(f_a2.wait(7, 5'000'000'000ull)); + EXPECT(direct.idle()); + + EXPECT(before_calls.load(std::memory_order_acquire) == 2); + EXPECT(s_cb_submits.load(std::memory_order_acquire) == 2); + EXPECT(s_total_submits.load(std::memory_order_acquire) == 2); // zero separate signal-only vkQueueSubmits! + for (int i = 0; i < 5; ++i) EXPECT(db[(i + 1) * 16] == std::uint8_t(0x40 + i)); + EXPECT(db[0] == std::uint8_t(0x44)); + + // (b) 17-batch + 17-signal single-frame burst on depth=4 completes without stalling on room_cv_ and merges + // all 17 batches + 17 signals into ONE vkQueueSubmit. + before_calls.store(0, std::memory_order_release); + s_cb_submits.store(0, std::memory_order_release); + s_total_submits.store(0, std::memory_order_release); + in_first.store(false, std::memory_order_release); + go_first.store(false, std::memory_order_release); + std::memset(db, 0, kBurstBufBytes); + + VulkanFence f_burst(context, 0); + EXPECT(f_burst.semaphore()); + EXPECT(direct.execute({&steps[0], 1}) == ReplayResult::success); + while (!in_first.load(std::memory_order_acquire)) std::this_thread::yield(); + + std::atomic burst_queued{false}; + std::thread burst_producer([&] { + bool ok = true; + for (int i = 1; i <= 17 && ok; ++i) { + ok = (direct.execute({&steps[i], 1}) == ReplayResult::success) && + direct.signal(f_burst.semaphore(), std::uint64_t(i)); + } + if (ok) burst_queued.store(true, std::memory_order_release); + }); + const auto burst_deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(500); + while (!burst_queued.load(std::memory_order_acquire) && std::chrono::steady_clock::now() < burst_deadline) + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + const bool burst_no_stall = burst_queued.load(std::memory_order_acquire); + go_first.store(true, std::memory_order_release); + burst_producer.join(); + EXPECT(burst_no_stall); + EXPECT(f_burst.wait(17, 5'000'000'000ull)); + EXPECT(direct.idle()); + + EXPECT(before_calls.load(std::memory_order_acquire) == 2); + EXPECT(s_cb_submits.load(std::memory_order_acquire) == 2); + EXPECT(s_total_submits.load(std::memory_order_acquire) == 2); + for (int i = 0; i < 18; ++i) EXPECT(db[(i + 1) * 16] == std::uint8_t(0x40 + i)); + EXPECT(db[0] == std::uint8_t(0x40 + 17)); + + // (c) Cross-queue Wait(cross_f, 1) on `compute` splits `direct` right after Signal(cross_f, 1) (attaching + // Signal(cross_f, 1) to B1's submit rather than merging B2 ahead of it) and unblocks `compute` cleanly. + before_calls.store(0, std::memory_order_release); + s_cb_submits.store(0, std::memory_order_release); + s_total_submits.store(0, std::memory_order_release); + in_first.store(false, std::memory_order_release); + go_first.store(false, std::memory_order_release); + std::memset(db, 0, kBurstBufBytes); + + VulkanFence cross_f(context, 0), compute_done(context, 0), direct_done(context, 0); + EXPECT(cross_f.semaphore() && compute_done.semaphore() && direct_done.semaphore()); + + auto compute_step = make_copy_list(2, 320, 1, 16, 1); // copies 0x41 -> db[320] + EXPECT(compute_step != nullptr); + std::shared_ptr s_comp = compute_step; + + EXPECT(direct.execute({&steps[0], 1}) == ReplayResult::success); + while (!in_first.load(std::memory_order_acquire)) std::this_thread::yield(); + + // Register cross-queue Wait(cross_f, 1) on compute queue and flush into held_. + compute.wait(cross_f.semaphore(), 1); + EXPECT(compute.execute({&s_comp, 1}) == ReplayResult::success); + EXPECT(compute.signal(compute_done.semaphore(), 1)); + EXPECT(compute.idle()); + + // Queue B1 + Signal(cross_f, 1) + B2 + Signal(direct_done, 1) on direct. + EXPECT(direct.execute({&steps[1], 1}) == ReplayResult::success); + EXPECT(direct.signal(cross_f.semaphore(), 1)); + EXPECT(direct.execute({&steps[2], 1}) == ReplayResult::success); + EXPECT(direct.signal(direct_done.semaphore(), 1)); + + go_first.store(true, std::memory_order_release); + EXPECT(compute_done.wait(1, 5'000'000'000ull)); + EXPECT(direct_done.wait(1, 5'000'000'000ull)); + EXPECT(direct.idle() && compute.idle()); + + // Direct split into {B0}, {B1 + sig(cross_f)}, {B2 + sig(direct_done)} (3 submits) + compute {s_comp + sig} (1) = 4. + EXPECT(before_calls.load(std::memory_order_acquire) == 4); + EXPECT(s_cb_submits.load(std::memory_order_acquire) == 4); + EXPECT(s_total_submits.load(std::memory_order_acquire) == 4); + EXPECT(db[16] == 0x40 && db[32] == 0x41 && db[48] == 0x42 && db[0] == 0x42 && db[320] == 0x41); + + // (d) Present (after_held) barrier strictly splits [B1, signal(F, 1)] from [B2, signal(F, 2)]. + before_calls.store(0, std::memory_order_release); + s_cb_submits.store(0, std::memory_order_release); + s_total_submits.store(0, std::memory_order_release); + in_first.store(false, std::memory_order_release); + go_first.store(false, std::memory_order_release); + std::memset(db, 0, kBurstBufBytes); + + VulkanFence f_pres(context, 0); + EXPECT(f_pres.semaphore()); + EXPECT(direct.execute({&steps[0], 1}) == ReplayResult::success); + while (!in_first.load(std::memory_order_acquire)) std::this_thread::yield(); + + EXPECT(direct.execute({&steps[1], 1}) == ReplayResult::success); + EXPECT(direct.signal(f_pres.semaphore(), 1)); + + std::atomic pres_ran{false}; + std::atomic pres_seen_before{0}, pres_seen_total{0}; + int pres_owner = 0; + context.holds().after_held(&pres_owner, [&] { + pres_seen_before.store(before_calls.load(std::memory_order_acquire), std::memory_order_release); + pres_seen_total.store(s_total_submits.load(std::memory_order_acquire), std::memory_order_release); + pres_ran.store(true, std::memory_order_release); + }); + + EXPECT(direct.execute({&steps[2], 1}) == ReplayResult::success); + EXPECT(direct.signal(f_pres.semaphore(), 2)); + + go_first.store(true, std::memory_order_release); + EXPECT(f_pres.wait(2, 5'000'000'000ull)); + EXPECT(direct.idle()); + + EXPECT(pres_ran.load(std::memory_order_acquire)); + EXPECT(pres_seen_before.load(std::memory_order_acquire) == 2); + EXPECT(pres_seen_total.load(std::memory_order_acquire) == 2); + EXPECT(before_calls.load(std::memory_order_acquire) == 3); + EXPECT(s_cb_submits.load(std::memory_order_acquire) == 3); + EXPECT(s_total_submits.load(std::memory_order_acquire) == 3); + EXPECT(db[16] == 0x40 && db[32] == 0x41 && db[48] == 0x42 && db[0] == 0x42); + + // (e) Coalesced [valid1, signal(s1, 1), bad_clear, valid2, signal(s2, 1)] on async copy queue falls back + // per-item in exact FIFO order without dropping valid peers or signals. + before_calls.store(0, std::memory_order_release); + in_first.store(false, std::memory_order_release); + go_first.store(false, std::memory_order_release); + std::memset(db, 0, kBurstBufBytes); + + auto bad_clear = std::make_shared(); + TargetView bad_tv{}; + bad_tv.resource = 2; + bad_tv.layer_count = 1; + EXPECT(bad_clear->clear_render_target(bad_tv, ClearColor{}) && bad_clear->close()); + std::shared_ptr bad_snap = bad_clear; + + VulkanFence err_s1(context, 0), err_s2(context, 0); + EXPECT(err_s1.semaphore() && err_s2.semaphore()); + + EXPECT(copy_q.execute({&steps[0], 1}) == ReplayResult::success); + while (!in_first.load(std::memory_order_acquire)) std::this_thread::yield(); + + EXPECT(copy_q.execute({&steps[1], 1}) == ReplayResult::success); + EXPECT(copy_q.signal(err_s1.semaphore(), 1)); + EXPECT(copy_q.execute({&bad_snap, 1}) == ReplayResult::success); + EXPECT(copy_q.execute({&steps[2], 1}) == ReplayResult::success); + EXPECT(copy_q.signal(err_s2.semaphore(), 1)); + + go_first.store(true, std::memory_order_release); + EXPECT(err_s1.wait(1, 5'000'000'000ull)); + EXPECT(err_s2.wait(1, 5'000'000'000ull)); + EXPECT(copy_q.idle()); + EXPECT(copy_q.take_held_failure() == ReplayResult::unsupported); + EXPECT(db[16] == 0x40 && db[32] == 0x41 && db[48] == 0x42 && db[0] == 0x42); + std::printf("queue execute+signal coalescing: unwaited merge, 17-batch burst, cross-queue Wait split, Present split & error fallback ok\n"); + } + + // 12. Round 6 queue contention fixes: + // (a) 24 Wait-separated batches within one frame on depth=4 enqueue with zero room_cv_ stalls; + // (b) Distinct Present-separated frames still throttle cleanly at depth=4 (bounded backpressure); + // (c) Held-only Compute queue executions via release_held() are counted in async_run_ns (worker busy %); + // (d) Visibility epochs (current_before_execute_seq / signaled_visibility_seq) allow safe single-flight + // before_execute_() coalescing across concurrent/back-to-back queues while NEVER skipping a refresh + // when a Wait-before-Signal CPU Fence::Signal lands after the previous refresh started. + { + VulkanContext context(d.device_proc, d.device, true); + EXPECT(context.loaded()); + VulkanQueue direct(context, d.queue, d.family, VulkanQueue::QueueKind::direct); + VulkanQueue compute(context, d.queue, d.family, VulkanQueue::QueueKind::compute); + EXPECT(direct.ok() && compute.ok()); + direct.set_async_depth(4); + compute.set_async_depth(4); + + auto empty = std::make_shared(); + EXPECT(empty->uav_barrier({}) && empty->close()); + std::shared_ptr snap = empty; + + // (a) 24 Wait-separated batches within a single present_epoch on depth=4: zero room_cv_ stalls! + std::atomic block_first{true}, in_first{false}; + context.set_before_execute([&] { + if (block_first.exchange(false, std::memory_order_acq_rel)) { + in_first.store(true, std::memory_order_release); + while (in_first.load(std::memory_order_acquire)) std::this_thread::yield(); + } + }); + VulkanFence intra_f(context, 0), done_a(context, 0); + EXPECT(intra_f.semaphore() && done_a.semaphore()); + EXPECT(direct.execute({&snap, 1}) == ReplayResult::success); + while (!in_first.load(std::memory_order_acquire)) std::this_thread::yield(); + + std::atomic burst24_done{false}; + std::thread producer24([&] { + bool ok = true; + for (int i = 1; i <= 24 && ok; ++i) { + direct.wait(intra_f.semaphore(), std::uint64_t(i - 1)); + ok = (direct.execute({&snap, 1}) == ReplayResult::success) && + direct.signal(intra_f.semaphore(), std::uint64_t(i)); + } + ok = ok && direct.signal(done_a.semaphore(), 1); + if (ok) burst24_done.store(true, std::memory_order_release); + }); + const auto d24 = std::chrono::steady_clock::now() + std::chrono::milliseconds(500); + while (!burst24_done.load(std::memory_order_acquire) && std::chrono::steady_clock::now() < d24) + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + const bool non_stalling_24 = burst24_done.load(std::memory_order_acquire); + in_first.store(false, std::memory_order_release); + producer24.join(); + EXPECT(non_stalling_24); + EXPECT(done_a.wait(1, 5'000'000'000ull)); + EXPECT(direct.idle()); + EXPECT(direct.async_room_waits_for_test() == 0); + + // (b) Distinct Present frames on depth=4 still throttle when 4 frames are already queued/running. + block_first.store(true, std::memory_order_release); + in_first.store(false, std::memory_order_release); + VulkanFence done_b(context, 0); + EXPECT(done_b.semaphore()); + EXPECT(direct.execute({&snap, 1}) == ReplayResult::success); + while (!in_first.load(std::memory_order_acquire)) std::this_thread::yield(); + + std::atomic frames_queued{0}; + std::thread frame_producer([&] { + for (unsigned f = 1; f <= 5; ++f) { + { + const sp::TitleCall pres(sp::part_present); + } + (void)direct.execute({&snap, 1}); + frames_queued.store(f, std::memory_order_release); + } + (void)direct.signal(done_b.semaphore(), 1); + }); + std::this_thread::sleep_for(std::chrono::milliseconds(20)); + // Worker busy (1) + 3 distinct present_epoch frames in inbox_ = 4 == depth: 4th queued frame must wait! + EXPECT(frames_queued.load(std::memory_order_acquire) == 3); + in_first.store(false, std::memory_order_release); + frame_producer.join(); + EXPECT(done_b.wait(1, 5'000'000'000ull)); + EXPECT(direct.idle()); + EXPECT(direct.async_room_waits_for_test() >= 1); + + // (c) Held-only Compute queue execution via release_held() is measured in async_run_ns (worker busy %). + context.set_before_execute([] { std::this_thread::sleep_for(std::chrono::milliseconds(10)); }); + VulkanFence gate_c(context, 0), done_c(context, 0); + EXPECT(gate_c.semaphore() && done_c.semaphore()); + compute.wait(gate_c.semaphore(), 1); + EXPECT(compute.execute({&snap, 1}) == ReplayResult::success); + EXPECT(compute.signal(done_c.semaphore(), 1)); + EXPECT(compute.idle()); // flushed into held_ while gate_c is unmet + const std::uint64_t run_before = compute.async_run_ns_for_test(); + EXPECT(gate_c.signal(1)); + EXPECT(done_c.wait(1, 5'000'000'000ull)); + EXPECT(compute.idle()); + const std::uint64_t run_after = compute.async_run_ns_for_test(); + EXPECT(run_after - run_before >= 5 * ms); + + // (d) Visibility epoch contract for single-flight before_execute_() coalescing + Wait-before-Signal safety. + std::mutex coal_m; + std::uint64_t coal_completed = 0; + std::atomic coal_ran{0}, coal_skipped{0}; + std::atomic hold_lead{false}, in_lead{false}, coal_bad_req{false}; + std::atomic cpu_data{0}, observed_data{0}; + context.set_before_execute([&] { + const std::uint64_t req = VulkanContext::current_before_execute_seq(); + if (req == 0) { + coal_bad_req.store(true, std::memory_order_relaxed); + return; + } + std::unique_lock lock(coal_m); + if (coal_completed >= req) { + coal_skipped.fetch_add(1, std::memory_order_relaxed); + return; + } + const std::uint64_t pass = (std::max)(req, context.current_visibility_seq()); + lock.unlock(); + if (hold_lead.exchange(false, std::memory_order_acq_rel)) { + in_lead.store(true, std::memory_order_release); + while (in_lead.load(std::memory_order_acquire)) std::this_thread::yield(); + } + observed_data.store(cpu_data.load(std::memory_order_acquire), std::memory_order_release); + coal_ran.fetch_add(1, std::memory_order_relaxed); + lock.lock(); + if (pass > coal_completed) coal_completed = pass; + }); + + // Case d1: Back-to-back direct + compute enqueued before direct's pass starts -> compute coalesces cleanly! + VulkanFence cross_d(context, 0), comp_done_d(context, 0); + EXPECT(cross_d.semaphore() && comp_done_d.semaphore()); + hold_lead.store(true, std::memory_order_release); + EXPECT(direct.execute({&snap, 1}) == ReplayResult::success); // batch 0 holds lead + while (!in_lead.load(std::memory_order_acquire)) std::this_thread::yield(); + + cpu_data.store(42, std::memory_order_release); + EXPECT(direct.execute({&snap, 1}) == ReplayResult::success); + EXPECT(direct.signal(cross_d.semaphore(), 1)); + compute.wait(cross_d.semaphore(), 1); + EXPECT(compute.execute({&snap, 1}) == ReplayResult::success); + EXPECT(compute.signal(comp_done_d.semaphore(), 1)); + EXPECT(compute.idle()); // compute batch now held waiting for cross_d + + in_lead.store(false, std::memory_order_release); + EXPECT(comp_done_d.wait(1, 5'000'000'000ull)); + EXPECT(direct.idle() && compute.idle()); + EXPECT(observed_data.load(std::memory_order_acquire) == 42); + EXPECT(coal_skipped.load(std::memory_order_acquire) >= 1); + + // Case d2: Wait-before-Signal with CPU write + CPU Fence::Signal AFTER prior pass completed MUST NOT skip! + VulkanFence cpu_gate(context, 0), comp_done_d2(context, 0); + EXPECT(cpu_gate.semaphore() && comp_done_d2.semaphore()); + compute.wait(cpu_gate.semaphore(), 1); + EXPECT(compute.execute({&snap, 1}) == ReplayResult::success); + EXPECT(compute.signal(comp_done_d2.semaphore(), 1)); + EXPECT(compute.idle()); // held in compute.held_ + + // Run a direct pass now: coal_completed advances past compute's enqueue visibility_seq! + EXPECT(direct.execute({&snap, 1}) == ReplayResult::success); + EXPECT(direct.idle()); + const unsigned ran_before_cpu_sig = coal_ran.load(std::memory_order_acquire); + + // Title writes new CPU data and signals cpu_gate from CPU: compute MUST run a fresh refresh and see 99! + cpu_data.store(99, std::memory_order_release); + EXPECT(cpu_gate.signal(1)); + EXPECT(comp_done_d2.wait(1, 5'000'000'000ull)); + EXPECT(compute.idle()); + EXPECT(!coal_bad_req.load(std::memory_order_acquire)); + EXPECT(coal_ran.load(std::memory_order_acquire) == ran_before_cpu_sig + 1); + EXPECT(observed_data.load(std::memory_order_acquire) == 99); + std::printf("queue r6 contention: 24-wait frame 0 room stalls, frame-group bound, held run_ns & visibility coalescing ok\n"); + } + + // 13. Round 7 sync & texture upload optimizations: + // (a) Per-fence vis_seq in QueueHolds + GPU-only VulkanQueue::signal() does NOT bump visibility_seq_ + // (stopping cross-fence & GPU-signal false invalidations while preserving CPU Fence::Signal visibility, + // including across Wait -> Signal -> Execute); + // (b) Unlocked QueueHolds::run_barriers() under barrier_mutex_: strict FIFO Present ordering while + // concurrent cross-queue pump_ready() never stalls behind a blocked barrier, plus cancel_after() wait; + // (c) Lazy title-upload semaphore in VulkanQueue::submit_multi() + submit_mutex_ unlocked during + // write_staged_title_images() recording. + { + // (a) Per-fence vis_seq & GPU-only signal visibility isolation. + VulkanContext context(d.device_proc, d.device, true); + EXPECT(context.loaded()); + VulkanQueue direct(context, d.queue, d.family, VulkanQueue::QueueKind::direct); + VulkanQueue compute(context, d.queue, d.family, VulkanQueue::QueueKind::compute); + EXPECT(direct.ok() && compute.ok()); + direct.set_async_depth(4); + compute.set_async_depth(4); + + auto empty = std::make_shared(); + EXPECT(empty->uav_barrier({}) && empty->close()); + std::shared_ptr snap = empty; + + // GPU-only queue Signal must NOT bump visibility_seq_. + VulkanFence gpu_f(context, 0); + EXPECT(gpu_f.semaphore()); + const std::uint64_t vis_before_gpu_sig = context.current_visibility_seq(); + EXPECT(direct.signal(gpu_f.semaphore(), 1)); + EXPECT(gpu_f.wait(1, 5'000'000'000ull)); + EXPECT(direct.idle()); + EXPECT(context.current_visibility_seq() == vis_before_gpu_sig); + EXPECT(context.holds().signaled_vis_seq(gpu_f.semaphore(), 1) == 0); + + // Unrelated CPU Fence::Signal on fence_a MUST NOT invalidate a held batch waiting on GPU-signaled fence_b. + std::mutex coal_m; + std::uint64_t coal_completed = 0; + std::atomic coal_ran{0}, coal_skipped{0}; + std::atomic cpu_val{0}, seen_val{0}; + context.set_before_execute([&] { + const std::uint64_t req = VulkanContext::current_before_execute_seq(); + std::unique_lock lock(coal_m); + if (req && coal_completed >= req) { + coal_skipped.fetch_add(1, std::memory_order_relaxed); + return; + } + const std::uint64_t pass = (std::max)(req, context.current_visibility_seq()); + lock.unlock(); + seen_val.store(cpu_val.load(std::memory_order_acquire), std::memory_order_release); + coal_ran.fetch_add(1, std::memory_order_relaxed); + lock.lock(); + if (pass > coal_completed) coal_completed = pass; + }); + + VulkanFence fence_a(context, 0), fence_b(context, 0), comp_done(context, 0); + EXPECT(fence_a.semaphore() && fence_b.semaphore() && comp_done.semaphore()); + + // Hold compute batch on GPU fence_b. + compute.wait(fence_b.semaphore(), 1); + EXPECT(compute.execute({&snap, 1}) == ReplayResult::success); + EXPECT(compute.signal(comp_done.semaphore(), 1)); + EXPECT(compute.idle()); + + // Direct runs a pass advancing coal_completed past compute's enqueue visibility_seq. + EXPECT(direct.execute({&snap, 1}) == ReplayResult::success); + EXPECT(direct.idle()); + const unsigned ran_before = coal_ran.load(std::memory_order_acquire); + const unsigned skipped_before = coal_skipped.load(std::memory_order_acquire); + + // Unrelated CPU signal on fence_a bumps visibility_seq_ and fence_a's per-fence vis_seq ONLY. + EXPECT(fence_a.signal(1)); + EXPECT(context.holds().signaled_vis_seq(fence_a.semaphore(), 1) > 0); + EXPECT(context.holds().signaled_vis_seq(fence_b.semaphore(), 1) == 0); + + // GPU-only signal on fence_b releases compute: must COALESCE (not re-run) because fence_b has vis_seq == 0! + EXPECT(direct.signal(fence_b.semaphore(), 1)); + EXPECT(comp_done.wait(1, 5'000'000'000ull)); + EXPECT(direct.idle() && compute.idle()); + EXPECT(coal_ran.load(std::memory_order_acquire) == ran_before); + EXPECT(coal_skipped.load(std::memory_order_acquire) == skipped_before + 1); + + // Wait(cpu_f, 1) -> Signal(mid, 1) -> Execute(B2): CPU Fence::Signal on cpu_f MUST still lift B2's req_seq! + VulkanFence cpu_f(context, 0), mid_f(context, 0), done_f(context, 0); + EXPECT(cpu_f.semaphore() && mid_f.semaphore() && done_f.semaphore()); + compute.wait(cpu_f.semaphore(), 1); + EXPECT(compute.signal(mid_f.semaphore(), 1)); + EXPECT(compute.execute({&snap, 1}) == ReplayResult::success); + EXPECT(compute.signal(done_f.semaphore(), 1)); + EXPECT(compute.idle()); + + EXPECT(direct.execute({&snap, 1}) == ReplayResult::success); + EXPECT(direct.idle()); + const unsigned ran_before_cpu = coal_ran.load(std::memory_order_acquire); + cpu_val.store(777, std::memory_order_release); + EXPECT(cpu_f.signal(1)); + EXPECT(done_f.wait(1, 5'000'000'000ull)); + EXPECT(compute.idle()); + EXPECT(coal_ran.load(std::memory_order_acquire) == ran_before_cpu + 1); + EXPECT(seen_val.load(std::memory_order_acquire) == 777); + + // (b) Unlocked QueueHolds::run_barriers(): strict FIFO order + concurrent pump_ready() unblocked + cancel_after. + context.set_before_execute({}); + auto empty_13b = std::make_shared(); + EXPECT(empty_13b->close()); + std::shared_ptr snap_13b = empty_13b; + VulkanFence hold_b1(context, 0), hold_comp(context, 0), comp_b_done(context, 0); + EXPECT(hold_b1.semaphore() && hold_comp.semaphore() && comp_b_done.semaphore()); + + direct.wait(hold_b1.semaphore(), 1); + EXPECT(direct.execute({&snap_13b, 1}) == ReplayResult::success); + EXPECT(direct.idle()); + + std::mutex fifo_m; + std::vector fifo_order; + std::atomic in_b1{false}, release_b1{false}, b3_ran{false}; + int owner_fifo = 0, owner_cancel = 0; + context.holds().after_held(&owner_fifo, [&] { + in_b1.store(true, std::memory_order_release); + while (!release_b1.load(std::memory_order_acquire)) std::this_thread::yield(); + std::lock_guard lk(fifo_m); + fifo_order.push_back(1); + }); + context.holds().after_held(&owner_fifo, [&] { + std::lock_guard lk(fifo_m); + fifo_order.push_back(2); + }); + context.holds().after_held(&owner_cancel, [&] { b3_ran.store(true, std::memory_order_release); }); + + // Hold an independent compute batch behind hold_comp. + compute.wait(hold_comp.semaphore(), 1); + EXPECT(compute.execute({&snap_13b, 1}) == ReplayResult::success); + EXPECT(compute.signal(comp_b_done.semaphore(), 1)); + EXPECT(compute.idle()); + + // Release direct -> starts barrier 1 (blocks on release_b1). + std::thread sig_b1([&] { (void)hold_b1.signal(1); }); + while (!in_b1.load(std::memory_order_acquire)) std::this_thread::yield(); + + // While barrier 1 is blocked inside barrier_mutex_, pump_mutex_ MUST be free so hold_comp.signal(1) + // releases compute and completes comp_b_done immediately without stalling! + EXPECT(hold_comp.signal(1)); + EXPECT(comp_b_done.wait(1, 2'000'000'000ull)); + EXPECT(compute.idle()); + + // Cancel owner_cancel while barrier 1 is running: b3 must be dropped and never run! + std::atomic cancel_done{false}; + std::thread canceller([&] { + context.holds().cancel_after(&owner_cancel); + cancel_done.store(true, std::memory_order_release); + }); + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + // cancel_after waits for barrier_mutex_ (running barrier) before returning! + EXPECT(!cancel_done.load(std::memory_order_acquire)); + + release_b1.store(true, std::memory_order_release); + sig_b1.join(); + canceller.join(); + context.holds().wait_barriers_drained(UINT64_MAX); + EXPECT(direct.idle()); + EXPECT(cancel_done.load(std::memory_order_acquire)); + EXPECT(!b3_ran.load(std::memory_order_acquire)); + EXPECT((fifo_order == std::vector{1, 2})); + + // (c) Lazy title-upload semaphore in submit_multi() + submit_mutex_ unlocked during write_staged_title_images() + // recording. + static PFN_vkQueueSubmit s_r7_real_submit = nullptr; + static VkSemaphore s_r7_watch_sem = VK_NULL_HANDLE; + static std::atomic s_r7_wait_hits{0}; + static std::atomic s_r7_last_wait_val{0}; + struct R7HookSubmit { + static VKAPI_ATTR VkResult VKAPI_CALL call(VkQueue q, std::uint32_t count, const VkSubmitInfo* infos, + VkFence fence) { + for (std::uint32_t i = 0; i < count; ++i) { + const auto* tl = static_cast(infos[i].pNext); + for (std::uint32_t w = 0; w < infos[i].waitSemaphoreCount; ++w) { + if (infos[i].pWaitSemaphores[w] == s_r7_watch_sem) { + s_r7_wait_hits.fetch_add(1, std::memory_order_relaxed); + if (tl && tl->sType == VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO && + w < tl->waitSemaphoreValueCount) { + s_r7_last_wait_val.store(tl->pWaitSemaphoreValues[w], std::memory_order_relaxed); + } + } + } + } + return s_r7_real_submit(q, count, infos, fence); + } + }; + + VulkanContext ctx_up(d.device_proc, d.device, true); + EXPECT(ctx_up.loaded()); + VulkanFence upload_tl(ctx_up, 0); + EXPECT(upload_tl.semaphore()); + s_r7_real_submit = ctx_up.vk.vkQueueSubmit; + s_r7_watch_sem = upload_tl.semaphore(); + s_r7_wait_hits.store(0, std::memory_order_relaxed); + s_r7_last_wait_val.store(0, std::memory_order_relaxed); + ctx_up.vk.vkQueueSubmit = &R7HookSubmit::call; + + VulkanQueue q_dir(ctx_up, d.queue, d.family, VulkanQueue::QueueKind::direct); + VulkanQueue q_cmp(ctx_up, d.queue, d.family, VulkanQueue::QueueKind::compute); + EXPECT(q_dir.ok() && q_cmp.ok()); + q_dir.set_async_depth(0); + q_cmp.set_async_depth(0); + + // Register a dummy image so write_staged_title_images() exercises its split record/submit path. + ResourceBinding img_b{}; + img_b.image = reinterpret_cast(0x1234); + img_b.aspects = VK_IMAGE_ASPECT_COLOR_BIT; + img_b.mip_levels = 1; + img_b.array_layers = 1; + ctx_up.add_resource(99, img_b, VK_IMAGE_LAYOUT_UNDEFINED); + + bool submit_unlocked_in_record = false; + bool submit_locked_in_submit = false; + const VulkanContext::StagedImageTarget target{99, {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}}; + const VkResult staged_r = ctx_up.write_staged_title_images( + {&target, 1}, + [&](const ReplayFunctions&, const std::vector& pieces) -> VkResult { + if (pieces.size() != 1 || pieces[0].empty()) return VK_ERROR_UNKNOWN; + // submit_mutex_ MUST be unlocked during command recording! + if (ctx_up.submit_mutex().try_lock()) { + submit_unlocked_in_record = true; + ctx_up.submit_mutex().unlock(); + } + return VK_SUCCESS; + }, + [&](const auto&) -> VkResult { + // submit_mutex_ MUST be held during submit callback! + submit_locked_in_submit = !ctx_up.submit_mutex().try_lock(); + ctx_up.note_title_upload_locked(upload_tl.semaphore(), 1); + return VK_SUCCESS; + }); + EXPECT(staged_r == VK_SUCCESS); + EXPECT(submit_unlocked_in_record && submit_locked_in_submit); + EXPECT(ctx_up.layout(99, 0) == VK_IMAGE_LAYOUT_GENERAL); + + // Signal upload_tl to 1 so GPU waits complete immediately. + EXPECT(upload_tl.signal(1)); + + // A signal-only submit on q_dir must NOT consume title_upload_seen_. + VulkanFence sig_only(ctx_up, 0); + EXPECT(sig_only.semaphore()); + EXPECT(q_dir.signal(sig_only.semaphore(), 1)); + EXPECT(sig_only.wait(1, 5'000'000'000ull)); + EXPECT(s_r7_wait_hits.load(std::memory_order_acquire) == 0); + + // First command-buffer submit on q_dir MUST wait on (upload_tl, 1); second MUST NOT wait redundantly! + EXPECT(q_dir.execute({&snap, 1}) == ReplayResult::success); + EXPECT(s_r7_wait_hits.load(std::memory_order_acquire) == 1); + EXPECT(s_r7_last_wait_val.load(std::memory_order_acquire) == 1); + EXPECT(q_dir.execute({&snap, 1}) == ReplayResult::success); + EXPECT(s_r7_wait_hits.load(std::memory_order_acquire) == 1); + + // First command-buffer submit on q_cmp MUST ALSO wait on (upload_tl, 1) independently! + EXPECT(q_cmp.execute({&snap, 1}) == ReplayResult::success); + EXPECT(s_r7_wait_hits.load(std::memory_order_acquire) == 2); + EXPECT(q_cmp.execute({&snap, 1}) == ReplayResult::success); + EXPECT(s_r7_wait_hits.load(std::memory_order_acquire) == 2); + + { + std::lock_guard lk(ctx_up.submit_mutex()); + ctx_up.clear_title_upload_locked(upload_tl.semaphore()); + } + EXPECT(q_dir.idle() && q_cmp.idle()); + std::printf("queue r7 sync-tex: per-fence vis_seq, unlocked run_barriers FIFO, lazy title_upload wait & unlocked record ok\n"); + } + + // 14. Round 8 WS3: + // (a) Empty-batch before_execute_() / after_execute_() / visibility_seq_ skip + mandatory guardrail that + // pending_wait_vis_seq_ is NEVER cleared and carries exec_waits_vis_seq() forward to the next non-empty + // execute_now(); + // (b) Coalescing past already-GPU-completed Waits in BOTH async_worker inbox_ and drain_held_while_executing(), + // merging holds().signaled_vis_seq() into group_vis_seq so CPU Fence::Signal visibility edges are preserved; + // (c) Dedicated QueueHolds barrier-drain thread: gate.signal() returns immediately without blocking on Present, + // active_work_ / any_progress() stays true while barrier runs, and post-barrier Frame N+1 GPU commands wait + // via wait_barriers_drained() before running. + { + static PFN_vkQueueSubmit s_r8_real_submit = nullptr; + static std::atomic s_r8_cb_submits{0}; + struct R8HookSubmit { + static VKAPI_ATTR VkResult VKAPI_CALL call(VkQueue q, std::uint32_t count, const VkSubmitInfo* infos, + VkFence fence) { + for (std::uint32_t i = 0; i < count; ++i) + if (infos[i].commandBufferCount > 0) s_r8_cb_submits.fetch_add(1, std::memory_order_relaxed); + return s_r8_real_submit(q, count, infos, fence); + } + }; + + VulkanContext context(d.device_proc, d.device, true); + EXPECT(context.loaded()); + s_r8_real_submit = context.vk.vkQueueSubmit; + s_r8_cb_submits.store(0, std::memory_order_relaxed); + context.vk.vkQueueSubmit = &R8HookSubmit::call; + + VulkanQueue direct(context, d.queue, d.family, VulkanQueue::QueueKind::direct); + EXPECT(direct.ok()); + direct.set_async_depth(4); + + void* src_map = nullptr; + void* dst_map = nullptr; + VkBuffer src = d.buffer(kBufBytes, usage, &src_map); + VkBuffer dst = d.buffer(kBufBytes, usage, &dst_map); + EXPECT(src && dst); + auto* sb = static_cast(src_map); + auto* db = static_cast(dst_map); + std::memset(sb, 0, kBufBytes); + std::memset(db, 0, kBufBytes); + sb[0] = 0x81; + sb[16] = 0x82; + sb[32] = 0x83; + ResourceBinding r_src{}, r_dst{}; + r_src.buffer = src; + r_src.size = kBufBytes; + r_dst.buffer = dst; + r_dst.size = kBufBytes; + r_dst.host_readable = true; + context.add_resource(1, r_src); + context.add_resource(2, r_dst); + + auto empty_list = std::make_shared(); + EXPECT(empty_list->close()); + std::shared_ptr empty_snap = empty_list; + + auto make_step = [&](int idx) -> std::shared_ptr { + auto l = std::make_shared(); + if (!l->copy_buffer({2, std::uint64_t((idx + 1) * 16), 1, std::uint64_t(idx * 16), 1}) || + !l->copy_buffer({2, 0, 1, std::uint64_t(idx * 16), 1}) || !l->close()) + return {}; + return l; + }; + std::shared_ptr b0 = make_step(0), b1 = make_step(1), b2 = make_step(2); + EXPECT(b0 && b1 && b2); + + // (a) Empty-command ExecuteCommandLists MUST still run before_execute_() / after_execute_() (titles and + // d3d12_existing_heap rely on empty submissions to flush pending streamed views & title textures). + std::atomic before_calls{0}, after_calls{0}; + std::atomic last_req_seq{0}; + context.set_before_execute([&] { + before_calls.fetch_add(1, std::memory_order_acq_rel); + last_req_seq.store(VulkanContext::current_before_execute_seq(), std::memory_order_release); + }); + context.set_after_execute([&] { after_calls.fetch_add(1, std::memory_order_acq_rel); }); + + const std::uint64_t vis0 = context.current_visibility_seq(); + EXPECT(direct.execute({&empty_snap, 1}) == ReplayResult::success); + EXPECT(direct.idle()); + EXPECT(context.current_visibility_seq() > vis0); + EXPECT(before_calls.load(std::memory_order_acquire) == 1); + EXPECT(after_calls.load(std::memory_order_acquire) == 1); + + // Wait on a CPU-signaled fence (vis_seq V), consume it with an empty list + non-empty list: before_execute_() + // MUST observe req_seq >= V! + before_calls.store(0, std::memory_order_release); + after_calls.store(0, std::memory_order_release); + VulkanFence cpu_f2(context, 0), done_a(context, 0); + EXPECT(cpu_f2.semaphore() && done_a.semaphore()); + direct.wait(cpu_f2.semaphore(), 1); + EXPECT(direct.execute({&empty_snap, 1}) == ReplayResult::success); + EXPECT(direct.execute({&b0, 1}) == ReplayResult::success); + EXPECT(direct.signal(done_a.semaphore(), 1)); + EXPECT(direct.idle()); + EXPECT(before_calls.load(std::memory_order_acquire) == 0); + + EXPECT(cpu_f2.signal(1)); + const std::uint64_t cpu_vis2 = context.holds().signaled_vis_seq(cpu_f2.semaphore(), 1); + EXPECT(done_a.wait(1, 5'000'000'000ull)); + EXPECT(direct.idle()); + EXPECT(before_calls.load(std::memory_order_acquire) == 1); + EXPECT(after_calls.load(std::memory_order_acquire) == 1); + EXPECT(last_req_seq.load(std::memory_order_acquire) >= cpu_vis2); + EXPECT(db[16] == 0x81); + + // (b1) Coalescing past already-GPU-completed Wait in async_worker inbox_ + CPU Fence::Signal vis_seq merge. + before_calls.store(0, std::memory_order_release); + s_r8_cb_submits.store(0, std::memory_order_release); + last_req_seq.store(0, std::memory_order_release); + std::memset(db, 0, kBufBytes); + std::atomic in_lead{false}, go_lead{false}; + context.set_before_execute([&] { + const unsigned n = before_calls.fetch_add(1, std::memory_order_acq_rel) + 1; + last_req_seq.store(VulkanContext::current_before_execute_seq(), std::memory_order_release); + if (n == 1) { + in_lead.store(true, std::memory_order_release); + while (!go_lead.load(std::memory_order_acquire)) std::this_thread::yield(); + } + }); + + VulkanFence done_wait_f(context, 0), done_b1(context, 0); + EXPECT(done_wait_f.semaphore() && done_b1.semaphore()); + + EXPECT(direct.execute({&b0, 1}) == ReplayResult::success); // pauses in before_execute_() + while (!in_lead.load(std::memory_order_acquire)) std::this_thread::yield(); + + // Enqueue b1, then Wait(done_wait_f, 1) (already CPU-signaled with a HIGHER vis_seq!), then b2. + EXPECT(direct.execute({&b1, 1}) == ReplayResult::success); + EXPECT(done_wait_f.signal(1)); // GPU counter is already 1 AND carries a fresh CPU vis_seq! + const std::uint64_t done_wait_vis = context.holds().signaled_vis_seq(done_wait_f.semaphore(), 1); + direct.wait(done_wait_f.semaphore(), 1); + EXPECT(direct.execute({&b2, 1}) == ReplayResult::success); + EXPECT(direct.signal(done_b1.semaphore(), 1)); + + go_lead.store(true, std::memory_order_release); + EXPECT(done_b1.wait(1, 5'000'000'000ull)); + EXPECT(direct.idle()); + + // {b0} (1) + coalesced {b1, completed Wait, b2} (2) = exactly 2 submits, and req_seq >= done_wait_vis! + EXPECT(before_calls.load(std::memory_order_acquire) == 2); + EXPECT(s_r8_cb_submits.load(std::memory_order_acquire) == 2); + EXPECT(last_req_seq.load(std::memory_order_acquire) >= done_wait_vis); + EXPECT(db[16] == 0x81 && db[32] == 0x82 && db[48] == 0x83 && db[0] == 0x83); + + // (b2) Coalescing past already-GPU-completed Wait in drain_held_while_executing() + CPU vis_seq merge. + before_calls.store(0, std::memory_order_release); + s_r8_cb_submits.store(0, std::memory_order_release); + last_req_seq.store(0, std::memory_order_release); + std::memset(db, 0, kBufBytes); + context.set_before_execute([&] { + before_calls.fetch_add(1, std::memory_order_acq_rel); + last_req_seq.store(VulkanContext::current_before_execute_seq(), std::memory_order_release); + }); + + VulkanFence hold_gate(context, 0), held_cpu_f(context, 0), done_b2(context, 0); + EXPECT(hold_gate.semaphore() && held_cpu_f.semaphore() && done_b2.semaphore()); + + direct.wait(hold_gate.semaphore(), 1); + EXPECT(direct.execute({&b1, 1}) == ReplayResult::success); + direct.wait(held_cpu_f.semaphore(), 1); // unsignaled when queued -> lands in b2.waits in held_ + EXPECT(direct.execute({&b2, 1}) == ReplayResult::success); + EXPECT(direct.signal(done_b2.semaphore(), 1)); + EXPECT(direct.idle()); // both b1 and b2 are now in held_ + EXPECT(before_calls.load(std::memory_order_acquire) == 0); + + // Signal held_cpu_f from CPU first (now GPU-completed with a newer vis_seq), THEN release hold_gate! + EXPECT(held_cpu_f.signal(1)); + const std::uint64_t held_cpu_vis = context.holds().signaled_vis_seq(held_cpu_f.semaphore(), 1); + EXPECT(hold_gate.signal(1)); + EXPECT(done_b2.wait(1, 5'000'000'000ull)); + EXPECT(direct.idle()); + + // Held {b1, completed Wait(held_cpu_f), b2} coalesced into ONE submit & preserved held_cpu_vis! + EXPECT(before_calls.load(std::memory_order_acquire) == 1); + EXPECT(s_r8_cb_submits.load(std::memory_order_acquire) == 1); + EXPECT(last_req_seq.load(std::memory_order_acquire) >= held_cpu_vis); + EXPECT(db[32] == 0x82 && db[48] == 0x83 && db[0] == 0x83); + + // (c) Dedicated QueueHolds barrier-drain thread: releaser returns immediately while barrier blocks, + // any_progress() stays true, post-barrier Frame N+1 strictly waits for barrier completion OUTSIDE + // pump_mutex_, and an independent compute queue's held work still pumps and completes while direct's + // Frame N+1 is waiting on blocked Present N! + VulkanQueue compute_c(context, d.queue, d.family, VulkanQueue::QueueKind::compute); + EXPECT(compute_c.ok()); + compute_c.set_async_depth(4); + + before_calls.store(0, std::memory_order_release); + std::memset(db, 0, kBufBytes); + context.set_before_execute([&] { before_calls.fetch_add(1, std::memory_order_acq_rel); }); + + VulkanFence f_gate(context, 0), f_done_c(context, 0), comp_gate_c(context, 0), comp_done_c(context, 0); + EXPECT(f_gate.semaphore() && f_done_c.semaphore() && comp_gate_c.semaphore() && comp_done_c.semaphore()); + + direct.wait(f_gate.semaphore(), 1); + EXPECT(direct.execute({&b0, 1}) == ReplayResult::success); // Frame N + EXPECT(direct.idle()); + + std::atomic in_present{false}, release_present{false}; + std::atomic present_saw_before{0}; + int present_owner = 0; + context.holds().after_held(&present_owner, [&] { + present_saw_before.store(before_calls.load(std::memory_order_acquire), std::memory_order_release); + in_present.store(true, std::memory_order_release); + while (!release_present.load(std::memory_order_acquire)) std::this_thread::yield(); + }); + + EXPECT(direct.execute({&b1, 1}) == ReplayResult::success); // Frame N+1 (must wait for Present N!) + EXPECT(direct.signal(f_done_c.semaphore(), 1)); + EXPECT(direct.idle()); + + // Hold independent work on compute_c behind comp_gate_c (skip before_execute so before_calls tracks direct). + compute_c.set_skip_before_execute(true); + compute_c.wait(comp_gate_c.semaphore(), 1); + EXPECT(compute_c.execute({&empty_snap, 1}) == ReplayResult::success); + EXPECT(compute_c.signal(comp_done_c.semaphore(), 1)); + EXPECT(compute_c.idle()); + + // Releaser signals f_gate: MUST return immediately without stalling on blocked Present N! + EXPECT(f_gate.signal(1)); + while (!in_present.load(std::memory_order_acquire)) std::this_thread::yield(); + + // While Present N is blocked on the barrier thread AND direct's async_worker is waiting in + // wait_barriers_drained() for Frame N+1: + // - any_progress() == true; + // - Frame N+1 (b1) has NOT run yet; + // - pump_mutex_ MUST be free so comp_gate_c.signal(1) pumps compute_c and completes comp_done_c immediately! + std::this_thread::sleep_for(std::chrono::milliseconds(15)); + EXPECT(queue_holds::any_progress()); + EXPECT(before_calls.load(std::memory_order_acquire) == 1); // only Frame N (b0) ran; b1 waits for Present N! + EXPECT(present_saw_before.load(std::memory_order_acquire) == 1); + EXPECT(comp_gate_c.signal(1)); + EXPECT(comp_done_c.wait(1, 2'000'000'000ull)); + EXPECT(compute_c.idle()); + EXPECT(before_calls.load(std::memory_order_acquire) == 1); // b1 STILL waits for Present N! + + release_present.store(true, std::memory_order_release); + EXPECT(f_done_c.wait(1, 5'000'000'000ull)); + EXPECT(direct.idle()); + EXPECT(before_calls.load(std::memory_order_acquire) == 2); + EXPECT(db[16] == 0x81 && db[32] == 0x82 && db[0] == 0x82); + std::printf("queue r8 ws3: empty-batch skip+vis carry, completed-wait coalescing, dedicated barrier thread ok\n"); + } + + // 9. Round 10 WS3: VulkanFence::signal_gpu_relay() (vis_seq = 0 vs CPU Signal vis_seq > 0) and retroactive + // QueueHolds::relay_wait() (single-wait in held_, multi-wait in held_ & inbox_, in-transit race ordering, + // never signaling gate_sem, balanced note_wait_added/removed & active_work_). + { + VulkanContext context(d.device_proc, d.device, true); + EXPECT(context.loaded()); + VulkanQueue direct(context, d.queue, d.family, VulkanQueue::QueueKind::direct); + VulkanQueue compute_a(context, d.queue, d.family, VulkanQueue::QueueKind::compute); + VulkanQueue compute_b(context, d.queue, d.family, VulkanQueue::QueueKind::compute); + EXPECT(direct.ok() && compute_a.ok() && compute_b.ok()); + direct.set_async_depth(4); + compute_a.set_async_depth(4); + compute_b.set_async_depth(4); + compute_a.set_skip_before_execute(true); + compute_b.set_skip_before_execute(true); + + void* src_map = nullptr; + void* mid_map = nullptr; + void* dst_map = nullptr; + VkBuffer src = d.buffer(kBufBytes, usage, &src_map); + VkBuffer mid = d.buffer(kBufBytes, usage, &mid_map); + VkBuffer dst = d.buffer(kBufBytes, usage, &dst_map); + EXPECT(src && mid && dst); + auto* sb = static_cast(src_map); + auto* mb = static_cast(mid_map); + auto* db = static_cast(dst_map); + std::memset(sb, 0, kBufBytes); + std::memset(mb, 0, kBufBytes); + std::memset(db, 0, kBufBytes); + sb[0] = 0x5A; + sb[16] = 0x6B; + sb[32] = 0x7C; + + ResourceBinding r_src{}, r_mid{}, r_dst{}; + r_src.buffer = src; + r_src.size = kBufBytes; + r_mid.buffer = mid; + r_mid.size = kBufBytes; + r_dst.buffer = dst; + r_dst.size = kBufBytes; + r_dst.host_readable = true; + context.add_resource(1, r_src); + context.add_resource(2, r_mid); + context.add_resource(3, r_dst); + + std::atomic before_calls{0}; + std::atomic last_req_seq{0}; + context.set_before_execute([&] { + before_calls.fetch_add(1, std::memory_order_acq_rel); + last_req_seq.store(VulkanContext::current_before_execute_seq(), std::memory_order_release); + }); + + auto empty_list = std::make_shared(); + EXPECT(empty_list->close()); + std::shared_ptr empty_snap = empty_list; + + // (a) GPU-met signal_gpu_relay (vis_seq = 0) vs CPU-met signal (vis_seq > 0). + { + VulkanFence gate_gpu(context, 0), gate_cpu(context, 0), done_a(context, 0), done_b(context, 0); + EXPECT(gate_gpu.semaphore() && gate_cpu.semaphore() && done_a.semaphore() && done_b.semaphore()); + + direct.wait(gate_gpu.semaphore(), 1); + EXPECT(direct.execute({&empty_snap, 1}) == ReplayResult::success); + const std::uint64_t seq_after_enqueue = context.current_visibility_seq(); + EXPECT(direct.signal(done_a.semaphore(), 1)); + EXPECT(direct.idle()); + EXPECT(before_calls.load(std::memory_order_acquire) == 0); + + EXPECT(gate_gpu.signal_gpu_relay(1)); + EXPECT(context.current_visibility_seq() == seq_after_enqueue); // vis_seq NOT bumped! + EXPECT(context.holds().signaled_vis_seq(gate_gpu.semaphore(), 1) == 0); + EXPECT(done_a.wait(1, 5'000'000'000ull)); + EXPECT(direct.idle()); + EXPECT(before_calls.load(std::memory_order_acquire) == 1); + EXPECT(last_req_seq.load(std::memory_order_acquire) == seq_after_enqueue); + + // CPU-met signal MUST bump visibility_seq and propagate into before_execute_(). + direct.wait(gate_cpu.semaphore(), 1); + EXPECT(direct.execute({&empty_snap, 1}) == ReplayResult::success); + const std::uint64_t seq_before_cpu = context.current_visibility_seq(); + EXPECT(direct.signal(done_b.semaphore(), 1)); + EXPECT(direct.idle()); + + EXPECT(gate_cpu.signal(1)); + const std::uint64_t cpu_vis = context.holds().signaled_vis_seq(gate_cpu.semaphore(), 1); + EXPECT(cpu_vis > seq_before_cpu); + EXPECT(done_b.wait(1, 5'000'000'000ull)); + EXPECT(direct.idle()); + EXPECT(last_req_seq.load(std::memory_order_acquire) >= cpu_vis); + } + + // (b) Retroactive single-wait relay in held_: direct waits on gate_single, compute_a writes mid[0], + // relay_wait redirects (gate_single, 1) -> (written_a, 1) WITHOUT signaling gate_single! + { + std::memset(mb, 0, kBufBytes); + std::memset(db, 0, kBufBytes); + before_calls.store(0, std::memory_order_release); + last_req_seq.store(0, std::memory_order_release); + + auto write_mid0 = make_copy_list(2, 0, 1, 0, 1); // mid[0] = 0x5A + auto read_mid0 = make_copy_list(3, 0, 2, 0, 1); // dst[0] = mid[0] + EXPECT(write_mid0 && read_mid0); + std::shared_ptr sw = write_mid0, sr = read_mid0; + + VulkanFence gate_single(context, 0), written_a(context, 0), done_s(context, 0); + EXPECT(gate_single.semaphore() && written_a.semaphore() && done_s.semaphore()); + + direct.wait(gate_single.semaphore(), 1); + EXPECT(direct.execute({&sr, 1}) == ReplayResult::success); + const std::uint64_t seq_after_direct = context.current_visibility_seq(); + EXPECT(direct.signal(done_s.semaphore(), 1)); + EXPECT(direct.idle()); // sr is held behind gate_single + EXPECT(before_calls.load(std::memory_order_acquire) == 0); + + EXPECT(compute_a.execute({&sw, 1}) == ReplayResult::success); + EXPECT(compute_a.signal(written_a.semaphore(), 1)); + + const QueueHolds::Wait rep[] = {{written_a.semaphore(), 1, {}}}; + EXPECT(context.holds().relay_wait(gate_single.semaphore(), 1, rep, /*consume_on_substitute=*/true)); + EXPECT(done_s.wait(1, 5'000'000'000ull)); + EXPECT(direct.idle() && compute_a.idle()); + EXPECT(gate_single.completed() == 0); // gate_single was NEVER signaled! + EXPECT(db[0] == 0x5A); // GPU ordering preserved! + EXPECT(context.current_visibility_seq() == seq_after_direct); + EXPECT(last_req_seq.load(std::memory_order_acquire) == seq_after_direct); + EXPECT(context.holds().active_relay_count() == 0); + EXPECT(!context.has_unsatisfied_waiter(gate_single.semaphore(), 1)); + } + + // (c) Retroactive multi-wait relay in held_ (two distinct writers, one initially blocked) AND in inbox_ + // (expanding 1 Call::Kind::wait into 2 Calls while async_worker is busy inside before_execute_()). + { + std::memset(mb, 0, kBufBytes); + std::memset(db, 0, kBufBytes); + auto write_m1 = make_copy_list(2, 16, 1, 16, 1); // mid[16] = 0x6B + auto write_m2 = make_copy_list(2, 32, 1, 32, 1); // mid[32] = 0x7C + auto read_both = std::make_shared(); + EXPECT(read_both->copy_buffer({3, 16, 2, 16, 1}) && read_both->copy_buffer({3, 32, 2, 32, 1}) && + read_both->close()); + EXPECT(write_m1 && write_m2); + std::shared_ptr sm1 = write_m1, sm2 = write_m2, srb = read_both; + + VulkanFence gate_multi(context, 0), gate_b_hold(context, 0), written_a(context, 0), written_b(context, 0), + done_m(context, 0); + EXPECT(gate_multi.semaphore() && gate_b_hold.semaphore() && written_a.semaphore() && + written_b.semaphore() && done_m.semaphore()); + + // Hold direct in held_ behind gate_multi; compute_a submits immediately; compute_b is still held behind + // gate_b_hold so written_b is pending when relay_wait runs! + direct.wait(gate_multi.semaphore(), 1); + EXPECT(direct.execute({&srb, 1}) == ReplayResult::success); + EXPECT(direct.signal(done_m.semaphore(), 1)); + EXPECT(direct.idle()); + + EXPECT(compute_a.execute({&sm1, 1}) == ReplayResult::success); + EXPECT(compute_a.signal(written_a.semaphore(), 1)); + compute_b.wait(gate_b_hold.semaphore(), 1); + EXPECT(compute_b.execute({&sm2, 1}) == ReplayResult::success); + EXPECT(compute_b.signal(written_b.semaphore(), 1)); + EXPECT(compute_b.idle()); + + const QueueHolds::Wait reps[] = {{written_a.semaphore(), 1, {}}, + {written_b.semaphore(), 1, {}}}; + EXPECT(context.holds().relay_wait(gate_multi.semaphore(), 1, reps, /*consume_on_substitute=*/true)); + EXPECT(context.holds().active_relay_count() == 0); + // Release compute_b -> written_b signals -> direct unblocks and reads both mid[16] and mid[32]. + EXPECT(gate_b_hold.signal_gpu_relay(1)); + EXPECT(done_m.wait(1, 5'000'000'000ull)); + EXPECT(direct.idle() && compute_a.idle() && compute_b.idle()); + EXPECT(gate_multi.completed() == 0); + EXPECT(db[16] == 0x6B && db[32] == 0x7C); + + // Multi-wait substitution inside inbox_ while direct's worker is blocked inside before_execute_(). + std::memset(db, 0, kBufBytes); + std::atomic in_lead{false}, go_lead{false}; + before_calls.store(0, std::memory_order_release); + context.set_before_execute([&] { + if (before_calls.fetch_add(1, std::memory_order_acq_rel) == 0) { + in_lead.store(true, std::memory_order_release); + while (!go_lead.load(std::memory_order_acquire)) std::this_thread::yield(); + } + }); + VulkanFence gate_inbox(context, 0), done_in(context, 0); + EXPECT(gate_inbox.semaphore() && done_in.semaphore()); + EXPECT(direct.execute({&empty_snap, 1}) == ReplayResult::success); + while (!in_lead.load(std::memory_order_acquire)) std::this_thread::yield(); + + direct.wait(gate_inbox.semaphore(), 1); + EXPECT(direct.execute({&srb, 1}) == ReplayResult::success); + EXPECT(direct.signal(done_in.semaphore(), 1)); + EXPECT(context.holds().relay_wait(gate_inbox.semaphore(), 1, reps, /*consume_on_substitute=*/true)); + EXPECT(context.holds().active_relay_count() == 0); + + go_lead.store(true, std::memory_order_release); + EXPECT(done_in.wait(1, 5'000'000'000ull)); + EXPECT(direct.idle()); + EXPECT(gate_inbox.completed() == 0); + EXPECT(db[16] == 0x6B && db[32] == 0x7C); + EXPECT(!context.holds().has_progress()); // held/work counts stayed balanced across inbox expansion! + } + + // (d) Race ordering (in-transit lookup_relay): relay_wait registered BEFORE wait_sync sees (gate_race, 1). + // Returns false (nothing substituted yet) while keeping the redirect entry active for lookup_relay(). + { + context.set_before_execute({}); + VulkanFence gate_race(context, 0), written_r(context, 0), done_r(context, 0); + EXPECT(gate_race.semaphore() && written_r.semaphore() && done_r.semaphore()); + EXPECT(compute_a.signal(written_r.semaphore(), 1)); + const QueueHolds::Wait rep[] = {{written_r.semaphore(), 1, {}}}; + EXPECT(!context.holds().relay_wait(gate_race.semaphore(), 1, rep, /*consume_on_substitute=*/true)); + EXPECT(context.holds().active_relay_count() == 1); // retained until in-transit wait consumes it + + direct.wait(gate_race.semaphore(), 1); + EXPECT(direct.execute({&empty_snap, 1}) == ReplayResult::success); + EXPECT(direct.signal(done_r.semaphore(), 1)); + EXPECT(done_r.wait(1, 5'000'000'000ull)); + EXPECT(direct.idle() && compute_a.idle()); + EXPECT(gate_race.completed() == 0); + EXPECT(context.holds().active_relay_count() == 0); + EXPECT(!context.has_unsatisfied_waiter(gate_race.semaphore(), 1)); + EXPECT(!context.holds().has_progress()); + } + + // (e) Round 10b A5: signal-only submit propagates consumed_wait_vis transitively into QueueHolds::signaled() + // so a downstream queue waiting on that signal observes the upstream CPU visibility epoch. + { + before_calls.store(0, std::memory_order_release); + last_req_seq.store(0, std::memory_order_release); + context.set_before_execute([&] { + before_calls.fetch_add(1, std::memory_order_acq_rel); + last_req_seq.store(VulkanContext::current_before_execute_seq(), std::memory_order_release); + }); + + VulkanFence cpu_gate(context, 0), relay_a(context, 0), relay_b(context, 0), done_t(context, 0); + EXPECT(cpu_gate.semaphore() && relay_a.semaphore() && relay_b.semaphore() && done_t.semaphore()); + + // Consumer `direct` is held behind `relay_a` with an older enqueue visibility_seq. + direct.wait(relay_a.semaphore(), 1); + EXPECT(direct.execute({&empty_snap, 1}) == ReplayResult::success); + const std::uint64_t seq_old = context.current_visibility_seq(); + EXPECT(direct.signal(done_t.semaphore(), 1)); + EXPECT(direct.idle()); + EXPECT(before_calls.load(std::memory_order_acquire) == 0); + + // Intermediate `compute_a` waits on `cpu_gate` and issues TWO signal-only submits (no ExecuteCommandLists). + compute_a.wait(cpu_gate.semaphore(), 1); + EXPECT(compute_a.signal(relay_a.semaphore(), 1)); + EXPECT(compute_a.signal(relay_b.semaphore(), 1)); + EXPECT(compute_a.idle()); + + // CPU-signal `cpu_gate`: bumps visibility_seq past `seq_old`. + EXPECT(cpu_gate.signal(1)); + const std::uint64_t cpu_vis = context.holds().signaled_vis_seq(cpu_gate.semaphore(), 1); + EXPECT(cpu_vis > seq_old); + + EXPECT(done_t.wait(1, 5'000'000'000ull)); + EXPECT(direct.idle() && compute_a.idle()); + EXPECT(context.holds().signaled_vis_seq(relay_a.semaphore(), 1) >= cpu_vis); + EXPECT(context.holds().signaled_vis_seq(relay_b.semaphore(), 1) >= cpu_vis); + EXPECT(before_calls.load(std::memory_order_acquire) == 1); + EXPECT(last_req_seq.load(std::memory_order_acquire) >= cpu_vis); + } + + std::printf("queue r10 ws3 + r10b a4/a5: signal_gpu_relay, relay_wait, signal-only vis_seq transitivity ok\n"); + } + + return 0; +} + +} // namespace + +int main() { + if (scripted() || submissions() || queue_sync_and_async()) return 1; + std::printf("submit_frame_test: OK\n"); + return 0; +} diff --git a/runtime/test/title_frames_test.cpp b/runtime/test/title_frames_test.cpp new file mode 100644 index 0000000000..88a5dc9968 --- /dev/null +++ b/runtime/test/title_frames_test.cpp @@ -0,0 +1,140 @@ +// src/title_frames.h: the host's reads and writes of title pages that only xmem's frame table holds (queue slot 31's +// copies onto a stream pool's GPU-only range and its CPU twin, which get no host view). No Windows headers, no GPU, no +// game data: the "frames" are arrays here, the table a map, and the addresses made up. +#include "../src/title_frames.h" + +#include +#include +#include +#include +#include +#include + +namespace { + +int failures = 0; +#define EXPECT(condition) \ + do { \ + if (!(condition)) { \ + std::fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #condition); \ + ++failures; \ + } \ + } while (0) + +namespace frames = leonida::title_frames; +constexpr std::uintptr_t kPage = frames::kPage; + +// The fake xmem: a table of page address -> frame (one physical page each), and each frame's host views. +struct Table { + std::map>> pages; + std::map> views; + unsigned lookups = 0; +}; +Table g_table; + +bool lookup(std::uintptr_t page, frames::Frame& out) { + ++g_table.lookups; + const auto it = g_table.pages.find(page); + if (it == g_table.pages.end()) return false; + out.bytes = it->second->data(); + out.keep = it->second; + return true; +} +void peers(std::uintptr_t page, std::vector& out) { + const auto it = g_table.views.find(page); + if (it != g_table.views.end()) out.insert(out.end(), it->second.begin(), it->second.end()); +} + +// A copy of [from, from + n) as the D3D12 layer's copy_guarded makes it: a table page from its frame, the rest from +// `host`, a stand-in for the title's own memory at those addresses. +bool copy(std::uint8_t* to, std::uintptr_t from, std::size_t n, const std::uint8_t* host, std::uintptr_t host_base) { + return frames::for_each_part(from, n, [&](std::uintptr_t at, std::size_t bytes, std::uint8_t* frame) { + std::memcpy(to + (at - from), frame ? frame : host + (at - host_base), bytes); + return true; + }); +} + +std::shared_ptr> frame_of(std::uint8_t fill) { + return std::make_shared>(kPage, fill); +} + +} // namespace + +int main() { + constexpr std::uintptr_t base = 0x7f0000000000; // a GPU-only range's first page (made up) + std::vector host(8 * kPage, 0xee); // what the host shows where no table page is + + // Before xmem registers its table nothing is a table page, and no range costs a lookup. + EXPECT(!frames::may_hold(base, base + kPage) && !frames::backed(base)); + frames::set_lookup(&lookup, &peers); + EXPECT(!frames::may_hold(base, base + kPage)); // still no page in the bounds + g_table.lookups = 0; + std::vector out(3 * kPage); + EXPECT(copy(out.data(), base, out.size(), host.data(), base) && out[0] == 0xee && g_table.lookups == 0); + + // Pages 1 and 2 get frames (a slot-31 copy): the copy reads them there, the host around them. + auto a = frame_of(0xa1), b = frame_of(0xb2); + g_table.pages[base + kPage] = a; + g_table.pages[base + 2 * kPage] = b; + frames::note_page(base + kPage); + frames::note_page(base + 2 * kPage); + EXPECT(frames::may_hold(base, base + kPage + 1) && !frames::may_hold(base + 3 * kPage, base + 4 * kPage)); + EXPECT(!frames::backed(base) && frames::backed(base + kPage + 0x1234) && frames::backed(base + 3 * kPage - 1)); + frames::Frame f; + EXPECT(frames::find(base + kPage + 0x10, f) && f.bytes == a->data() + 0x10 && f.keep); + // An unaligned run over all four pages: host bytes, a's, b's, host bytes again. + std::vector run(3 * kPage); + const std::uintptr_t from = base + 0x8000; + EXPECT(copy(run.data(), from, run.size(), host.data(), base)); + EXPECT(run[0] == 0xee && run[0x7fff] == 0xee && run[0x8000] == 0xa1 && run[0x17fff] == 0xa1 && + run[0x18000] == 0xb2 && run[0x27fff] == 0xb2 && run[0x28000] == 0xee && run.back() == 0xee); + // The parts come in order, a table page's inside its own 64 KiB, neighbouring host pages as one. + std::vector> parts; + frames::for_each_part(base, 4 * kPage, [&](std::uintptr_t at, std::size_t n, std::uint8_t* frame) { + parts.emplace_back(at, frame != nullptr); + EXPECT(!frame || n == kPage); + return true; + }); + EXPECT(parts.size() == 4 && !parts[0].second && parts[1].second && parts[2].second && !parts[3].second && + parts[3].first == base + 3 * kPage); + bool backed = false; + EXPECT(frames::run_end(base, base + 4 * kPage, backed) == base + kPage && !backed); + EXPECT(frames::run_end(base + kPage + 4, base + 4 * kPage, backed) == base + 3 * kPage && backed); + EXPECT(frames::run_end(base + 3 * kPage, base + 4 * kPage, backed) == base + 4 * kPage && !backed); + + // A remap is a table update: the next read sees the new frame, with nothing else to tell. + auto c = frame_of(0xc3); + g_table.pages[base + kPage] = c; + EXPECT(copy(run.data(), from, run.size(), host.data(), base) && run[0x8000] == 0xc3 && run[0x18000] == 0xb2); + // A frame a reader holds stays alive after the table lets it go (the section's scratch view stays mapped). + EXPECT(frames::find(base + 2 * kPage, f)); + g_table.pages.erase(base + 2 * kPage); + b.reset(); + EXPECT(f.bytes[0] == 0xb2 && !frames::backed(base + 2 * kPage)); + f = {}; + // The title's CPU writes the frame through its own mapping (here: the frame itself): the reader sees it, and asks + // xmem for that mapping to guard it there. + (*c)[0x40] = 0x55; + EXPECT(copy(run.data(), from, run.size(), host.data(), base) && run[0x8040] == 0x55); + g_table.views[base + kPage] = {0x10000000}; + std::vector others; + frames::peers(base + kPage + 0x40, others); + EXPECT(others.size() == 1 && others[0] == 0x10000000); + + // A part that fails stops the walk and says so. + unsigned calls = 0; + EXPECT(!frames::for_each_part(base, 4 * kPage, [&](std::uintptr_t, std::size_t, std::uint8_t*) { return ++calls < 2; })); + EXPECT(calls == 2); + // Empty and top-of-memory ranges. + EXPECT(frames::for_each_part(base, 0, [](std::uintptr_t, std::size_t, std::uint8_t*) { return false; })); + EXPECT(frames::for_each_part(UINTPTR_MAX - 16, 64, [](std::uintptr_t at, std::size_t n, std::uint8_t* frame) { + return !frame && at == UINTPTR_MAX - 16 && n == 16; + })); + + if (failures) { + std::fprintf(stderr, "title_frames_test: %d failure(s)\n", failures); + return 1; + } + std::puts("title_frames_test: table pages read through their frames, host pages around them, remaps and frees seen"); + return 0; +} diff --git a/runtime/test/title_heap_test.cpp b/runtime/test/title_heap_test.cpp new file mode 100644 index 0000000000..20b895efa5 --- /dev/null +++ b/runtime/test/title_heap_test.cpp @@ -0,0 +1,249 @@ +// src/title_heap.h: the XMemAlloc heap the runtime keeps in the page mirror's range. No Windows headers, no GPU, no +// game data: the "reservation" is host memory here, and commit and decommit are counted. +// 1. blocks are 64-byte aligned, a size of zero is one byte, sizes fall in their class, large blocks are whole pages; +// 2. a randomised run of allocations and frees against a reference (a map of live blocks with their bytes): no two +// live blocks overlap, every block keeps what was written into it until it is freed, frees give space back; +// 3. a large block is committed when handed out and decommitted when freed; pointers the heap did not hand out are +// refused. +#include "../src/title_heap.h" + +#include +#include +#include +#include +#include +#include + +namespace { + +int failures = 0; +#define EXPECT(condition) \ + do { \ + if (!(condition)) { \ + std::fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #condition); \ + ++failures; \ + } \ + } while (0) + +using leonida::TitleHeap; + +} // namespace + +int main() { + constexpr std::size_t kBytes = std::size_t(256) << 20; + std::vector memory(kBytes + TitleHeap::kPage); + const std::uintptr_t base = + (reinterpret_cast(memory.data()) + TitleHeap::kPage - 1) & ~std::uintptr_t(TitleHeap::kPage - 1); + std::size_t committed = 0, decommitted = 0; + TitleHeap heap; + TitleHeap::Hooks hooks; + hooks.commit = [&](std::uintptr_t, std::size_t bytes) { + committed += bytes; + return true; + }; + hooks.decommit = [&](std::uintptr_t at, std::size_t bytes) { + decommitted += bytes; + std::memset(reinterpret_cast(at), 0, bytes); // as a decommit reads back + }; + EXPECT(heap.init(base, kBytes, hooks)); + + // 1. + void* zero = heap.allocate(0); + EXPECT(zero && reinterpret_cast(zero) % 64 == 0 && heap.size_of(zero) == 64); + for (std::size_t size : {1u, 63u, 64u, 65u, 1000u, 1024u, 1025u, 4096u, 30000u, 32768u}) { + void* p = heap.allocate(size); + EXPECT(p && reinterpret_cast(p) % 64 == 0 && heap.size_of(p) >= size && heap.owns(p)); + EXPECT(heap.release(p)); + } + void* large = heap.allocate(100000); + EXPECT(large && reinterpret_cast(large) % TitleHeap::kPage == 0 && + heap.size_of(large) == 2 * TitleHeap::kPage); + // 3. + const std::size_t before = decommitted; + std::memset(large, 0x5a, 100000); + EXPECT(heap.release(large) && decommitted == before + 2 * TitleHeap::kPage); + void* again = heap.allocate(100000); + EXPECT(again && static_cast(again)[0] == 0); // reads zero handed out again + EXPECT(heap.release(again)); + int outside = 0; + EXPECT(!heap.release(&outside) && !heap.owns(&outside)); + EXPECT(!heap.release(static_cast(zero) + 8)); // not a block's start + EXPECT(heap.size_of(static_cast(zero) + 8) == 0); + EXPECT(heap.release(zero)); + EXPECT(heap.size_of(zero) == 0); + EXPECT(!heap.release(zero)); // double-free of small block rejected + + // 4. Small-block double-free must not duplicate the freelist; interior / unallocated / tail pointers rejected. + { + const std::size_t live_before = heap.stats().live; + void* a = heap.allocate(128); + void* b = heap.allocate(128); + EXPECT(a && b && a != b && heap.size_of(a) == 128 && heap.size_of(b) == 128); + EXPECT(heap.size_of(static_cast(a) + 64) == 0); + EXPECT(!heap.release(static_cast(a) + 64)); + EXPECT(heap.release(a)); + EXPECT(heap.size_of(a) == 0); + EXPECT(!heap.release(a)); // second free rejected + EXPECT(heap.stats().live == live_before + 1); + void* c = heap.allocate(128); + void* d = heap.allocate(128); + EXPECT(c && d && c != d && c != b && d != b); // freelist not duplicated + EXPECT(heap.release(b) && heap.release(c) && heap.release(d)); + EXPECT(heap.stats().live == live_before); + + // Large-block interior pointer & double-free rejected, size_of is 0 after release. + void* big = heap.allocate(100000); + EXPECT(big && heap.size_of(big) == 2 * TitleHeap::kPage); + EXPECT(heap.size_of(static_cast(big) + 64) == 0); + EXPECT(!heap.release(static_cast(big) + 64)); + EXPECT(heap.release(big)); + EXPECT(heap.size_of(big) == 0 && !heap.release(big)); + + // Non-power-of-two class (192 B): unused span tail & never-allocated slot rejected. + void* p192 = heap.allocate(192); + EXPECT(p192 && heap.size_of(p192) == 192); + auto* const span_start = reinterpret_cast( + base + ((reinterpret_cast(p192) - base) / TitleHeap::kSpan) * TitleHeap::kSpan); + EXPECT(heap.size_of(span_start + 192) == 0 && !heap.release(span_start + 192)); // never allocated + const std::size_t tail_off = (TitleHeap::kSpan / 192) * 192; + EXPECT(tail_off < TitleHeap::kSpan); + EXPECT(heap.size_of(span_start + tail_off) == 0 && !heap.release(span_start + tail_off)); // unused tail + EXPECT(heap.release(p192)); + } + + // 2. + std::mt19937 random(2026); + struct Live { + std::size_t size; + std::uint8_t tag; + }; + std::map live; + const auto check_block = [&](std::uintptr_t at, const Live& b) { + const auto* bytes = reinterpret_cast(at); + for (std::size_t i = 0; i < b.size; i += 97) + if (bytes[i] != std::uint8_t(b.tag + i)) return false; + return true; + }; + for (int round = 0; round < 20000; ++round) { + const bool free_one = !live.empty() && (random() % 100 < 45 || live.size() > 3000); + if (free_one) { + auto it = live.begin(); + std::advance(it, random() % live.size()); + EXPECT(check_block(it->first, it->second)); + EXPECT(heap.release(reinterpret_cast(it->first))); + live.erase(it); + continue; + } + const unsigned kind = random() % 100; + const std::size_t size = kind < 70 ? random() % 512 : kind < 95 ? random() % 32768 : 32769 + random() % 300000; + void* p = heap.allocate(size); + EXPECT(p != nullptr); + if (!p) break; + const auto at = reinterpret_cast(p); + EXPECT(at % 64 == 0 && heap.owns(p)); + const std::size_t span = size ? size : 1; + // No live block overlaps it. + auto next = live.lower_bound(at); + if (next != live.end()) EXPECT(at + span <= next->first); + if (next != live.begin()) { + const auto previous = std::prev(next); + EXPECT(previous->first + previous->second.size <= at); + } + const Live b{span, std::uint8_t(random())}; + auto* bytes = static_cast(p); + for (std::size_t i = 0; i < span; i += 97) bytes[i] = std::uint8_t(b.tag + i); + live[at] = b; + } + for (const auto& [at, b] : live) { + EXPECT(check_block(at, b)); + EXPECT(heap.release(reinterpret_cast(at))); + } + EXPECT(heap.stats().live == 0 && committed > 0); + EXPECT(!heap.write_watched() && !heap.stats().write_watched && heap.base() == base && heap.capacity() == kBytes); + + // 5. MEM_WRITE_WATCH reservation helper: prefers write-watched reservation, falls back silently when rejected. + { + bool ww = false; + int tries = 0; + const std::uintptr_t got_ww = TitleHeap::reserve( + [&](bool want_write_watch) -> std::uintptr_t { + ++tries; + return want_write_watch ? base : 0; + }, + ww); + EXPECT(got_ww == base && ww && tries == 1); + + TitleHeap ww_heap; + EXPECT(ww_heap.init(base, kBytes, hooks, ww)); + EXPECT(ww_heap.write_watched() && ww_heap.stats().write_watched); + void* p = ww_heap.allocate(256); + EXPECT(p && ww_heap.owns(p) && ww_heap.release(p)); + + ww = true; + tries = 0; + const std::uintptr_t got_fallback = TitleHeap::reserve( + [&](bool want_write_watch) -> std::uintptr_t { + ++tries; + return want_write_watch ? 0 : base; + }, + ww); + EXPECT(got_fallback == base && !ww && tries == 2); + + TitleHeap plain_heap; + EXPECT(plain_heap.init(base, kBytes, hooks, ww)); + EXPECT(!plain_heap.write_watched() && !plain_heap.stats().write_watched); + } + + // 6. Committed-span tracking (for_each_committed): coalesces contiguous spans & large blocks and splits + // cleanly around decommitted holes so late readers / write-watch scans never span uncommitted sub-ranges. + { + TitleHeap span_heap; + EXPECT(span_heap.init(base, kBytes, hooks, true)); + auto collect_extents = [&](const TitleHeap& h) { + std::vector> extents; + h.for_each_committed([&](std::uintptr_t at, std::size_t bytes) { extents.emplace_back(at, bytes); }); + return extents; + }; + EXPECT(collect_extents(span_heap).empty()); + + void* s1 = span_heap.allocate(64); // commits 1 MiB span [base, base + 1M) + void* l1 = span_heap.allocate(2 * TitleHeap::kPage); // commits 128 KiB [base + 1M, base + 1M + 128K) + void* l2 = span_heap.allocate(2 * TitleHeap::kPage); // commits 128 KiB [base + 1M + 128K, base + 1M + 256K) + EXPECT(s1 && l1 && l2); + auto ext = collect_extents(span_heap); + EXPECT(ext.size() == 1 && ext[0].first == base && + ext[0].second == TitleHeap::kSpan + 4 * TitleHeap::kPage && + ext[0].second == span_heap.stats().committed); + + // Releasing l1 decommits [base + 1M, base + 1M + 128K), splitting into two committed extents around the hole. + EXPECT(span_heap.release(l1)); + ext = collect_extents(span_heap); + EXPECT(ext.size() == 2); + if (ext.size() == 2) { + EXPECT(ext[0].first == base && ext[0].second == TitleHeap::kSpan); + EXPECT(ext[1].first == base + TitleHeap::kSpan + 2 * TitleHeap::kPage && + ext[1].second == 2 * TitleHeap::kPage); + EXPECT(ext[0].second + ext[1].second == span_heap.stats().committed); + } + + // Re-allocating into the hole re-coalesces back into a single contiguous committed extent. + void* l1_again = span_heap.allocate(2 * TitleHeap::kPage); + EXPECT(l1_again == l1); + ext = collect_extents(span_heap); + EXPECT(ext.size() == 1 && ext[0].first == base && + ext[0].second == TitleHeap::kSpan + 4 * TitleHeap::kPage); + + EXPECT(span_heap.release(l1_again) && span_heap.release(l2) && span_heap.release(s1)); + ext = collect_extents(span_heap); + EXPECT(ext.size() == 1 && ext[0].first == base && ext[0].second == TitleHeap::kSpan); + } + + if (failures) { + std::fprintf(stderr, "title_heap_test: %d failure(s)\n", failures); + return 1; + } + std::printf("title_heap_test: alignment, classes, large blocks, 20000 random allocations and frees against a " + "reference (%zu KiB committed, %zu KiB decommitted)\n", + committed >> 10, decommitted >> 10); + return 0; +} diff --git a/runtime/test/title_mirror_hooks_test.cpp b/runtime/test/title_mirror_hooks_test.cpp new file mode 100644 index 0000000000..71e8ed0589 --- /dev/null +++ b/runtime/test/title_mirror_hooks_test.cpp @@ -0,0 +1,1907 @@ +// The page mirror's alias for console descriptor heaps read in place (src/title_mirror.h), without a GPU: fake handles +// stand for the chunks, the units and the arena buffer, and the bind hook records what each batch binds. +// alias(): the pages of a range are also bound into another buffer at an offset, in the same batches as their chunk +// binds, following remaps and unmaps, each with a home of its own there (the filtered copy), which hooks.filter +// fills (fresh when made, not fresh when the title's bytes change again, never when they did not); the page's own +// home at the title's address keeps the title's bytes exactly and is written back as any page; unalias() unbinds +// the alias and frees the copies. Without an alias the batches are as before. The title's bytes are only written +// by write-back. +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../src/title_mirror.h" + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +namespace { + +using leonida::TitleMirror; +constexpr std::uint64_t kPage = TitleMirror::kPage; +constexpr std::uint64_t kBase = std::uint64_t(16) << 40; // a title reservation in the mirror's range + +template +H fake(std::uintptr_t n) { + return reinterpret_cast(n); +} + +struct Fixture { + std::vector> units; + std::uintptr_t next_handle = 0x1000; + // Per buffer, per offset: the memory and offset of the last bind (memory null: unbound). + std::map>> bound; + std::vector batch_sizes; // binds per flush + std::uint64_t last_value = 0; + struct Filtered { + std::uint64_t va; + bool fresh; + }; + std::vector filtered; + std::map hosts; + + leonida::TitleMirrorHooks hooks() { + leonida::TitleMirrorHooks h; + h.make_chunk = [this](std::uint64_t, std::uint64_t, VkBuffer& out) { + out = fake(next_handle++); + return true; + }; + h.make_unit = [this](VkDeviceMemory& out, std::uint8_t*& host) { + units.emplace_back(new std::uint8_t[TitleMirror::kUnitBytes]()); + out = fake(next_handle++); + host = units.back().get(); + hosts[out] = host; + return true; + }; + h.free_unit = [](VkDeviceMemory) {}; + h.bind = [this](const std::vector& infos, std::uint64_t value) { + std::size_t n = 0; + for (const auto& info : infos) + for (std::uint32_t i = 0; i < info.bindCount; ++i, ++n) + bound[info.buffer][info.pBinds[i].resourceOffset] = {info.pBinds[i].memory, + info.pBinds[i].memoryOffset}; + batch_sizes.push_back(n); + last_value = value; + return true; + }; + // The filter of the test: copy, then turn every byte 0xA5 into 0x5A (a stand-in for nulling a V#). + h.filter = [this](std::uint64_t va, std::uint8_t* to, const std::uint8_t* from, std::size_t bytes, bool fresh) { + filtered.push_back({va, fresh}); + for (std::size_t i = 0; i < bytes; ++i) to[i] = from[i] == 0xA5 ? 0x5A : from[i]; + return true; + }; + return h; + } + // The bytes the GPU reads at `offset` of `buffer`: the home bound there. + const std::uint8_t* read(VkBuffer buffer, VkDeviceSize offset) { + const auto b = bound.find(buffer); + if (b == bound.end()) return nullptr; + const auto page = b->second.find(offset & ~(kPage - 1)); + if (page == b->second.end() || !page->second.first) return nullptr; + return hosts[page->second.first] + page->second.second + (offset & (kPage - 1)); + } +}; + +int aliases() { + Fixture f; + TitleMirror mirror(f.hooks()); + EXPECT(mirror.cover(kBase, kBase + 16 * kPage)); + VkBuffer chunk = VK_NULL_HANDLE; + VkDeviceSize in_chunk = 0; + EXPECT(mirror.chunk_at(kBase, chunk, in_chunk) && in_chunk == 0); + std::vector frames(4 * kPage); + for (std::size_t i = 0; i < frames.size(); ++i) frames[i] = std::uint8_t(i / kPage + 1); + // Without an alias: two pages, one batch of two binds, as before. + mirror.map(kBase, &frames[0], nullptr, 1); + mirror.map(kBase + kPage, &frames[kPage], nullptr, 1); + EXPECT(mirror.flush(1) && f.batch_sizes.back() == 2 && f.bound.size() == 1); + // The alias binds the mapped pages' copies into the arena at its offset, in the next batch with the chunk binds. + const VkBuffer arena = fake(0x77); + constexpr VkDeviceSize kAt = 0xb000000; + mirror.alias(kBase, kBase + 4 * kPage, arena, kAt); + mirror.map(kBase + 2 * kPage, &frames[2 * kPage], nullptr, 2); // a page mapped after the alias + EXPECT(mirror.flush(2) && f.batch_sizes.back() == 4); // 1 chunk bind, 3 alias binds + for (int p = 0; p < 3; ++p) { + const std::uint8_t* through_arena = f.read(arena, kAt + p * kPage + 17); + const std::uint8_t* through_chunk = f.read(chunk, p * kPage + 17); + // Memory of its own at the alias; the same bytes here, as the test's filter changes only 0xA5. + EXPECT(through_arena && through_chunk && through_arena != through_chunk && *through_arena == p + 1 && + *through_chunk == p + 1); + } + EXPECT(!f.read(arena, kAt + 3 * kPage)); // not mapped: unbound there too + // A remap: page 0 shows frame 3 now; the arena follows in the same batch. + mirror.map(kBase, &frames[3 * kPage], nullptr, 3); + EXPECT(mirror.flush(3) && f.batch_sizes.back() == 2); + EXPECT(*f.read(arena, kAt) == 4 && *f.read(chunk, 0) == 4); + // An unmap unbinds both. + mirror.map(kBase + kPage, nullptr, nullptr, 4); + EXPECT(mirror.flush(4) && !f.read(arena, kAt + kPage) && !f.read(chunk, kPage)); + // unalias: the arena pages are unbound; the chunk keeps its pages; later maps bind the chunk only. + mirror.unalias(kBase, 5); + EXPECT(mirror.flush(5) && !f.read(arena, kAt) && !f.read(arena, kAt + 2 * kPage) && f.read(chunk, 0)); + EXPECT(!mirror.copy_bytes(kBase)); + mirror.map(kBase + kPage, &frames[kPage], nullptr, 6); + EXPECT(mirror.flush(6) && f.batch_sizes.back() == 1 && !f.read(arena, kAt + kPage)); + std::printf("alias: pages bound into a second buffer with copies of their own, in the chunk batches, following a " + "map, a remap and an unmap\n"); + return 0; +} + +int filters() { + Fixture f; + TitleMirror mirror(f.hooks()); + EXPECT(mirror.cover(kBase, kBase + 16 * kPage)); + std::vector frames(3 * kPage, 0xA5); + const VkBuffer arena = fake(0x77); + constexpr VkDeviceSize kAt = 0xb000000; + mirror.alias(kBase, kBase + 2 * kPage, arena, kAt); + mirror.map(kBase, &frames[0], nullptr, 1); // aliased: a copy, filtered fresh + mirror.map(kBase + 2 * kPage, &frames[2 * kPage], nullptr, 1); // outside: no copy + EXPECT(f.filtered.size() == 1 && f.filtered[0].va == kBase && f.filtered[0].fresh); + // The title's address reads the title's bytes; the alias the filter's. + EXPECT(mirror.home_bytes(kBase)[100] == 0xA5 && mirror.copy_bytes(kBase)[100] == 0x5A); + EXPECT(mirror.home_bytes(kBase + 2 * kPage)[100] == 0xA5 && !mirror.copy_bytes(kBase + 2 * kPage)); + EXPECT(mirror.flush(1) && *f.read(arena, kAt + 100) == 0x5A); + EXPECT(mirror.counters().filtered == 1 && mirror.counters().uploads == 2); + // Write-back: the aliased page's own home is the title's bytes, written back to its physical frame as any page; + // the title's bytes changed, so its copy is filtered again (not fresh). + std::size_t written = 0; + std::uint64_t last_dst = 0; + const auto write = [&](std::uint64_t dst, const std::uint8_t* bytes, std::uint64_t n) { + last_dst = dst; + std::memcpy(reinterpret_cast(static_cast(dst)), bytes, std::size_t(n)); + written += std::size_t(n); + return true; + }; + mirror.home_bytes(kBase)[300] = 0x77; // a GPU store through a V# into the heap's page + EXPECT(mirror.write_back(kBase, kBase + kPage, write) == 256 && written == 256 && frames[300] == 0x77); + EXPECT(last_dst == reinterpret_cast(&frames[0]) + 256); + EXPECT(f.filtered.size() == 2 && !f.filtered[1].fresh && mirror.copy_bytes(kBase)[300] == 0x77); + // A write and its refill: the home takes the title's bytes, the copy is filtered, not fresh. + frames[200] = 0x11; + EXPECT(mirror.dirty(kBase) && mirror.upload() == 1); + EXPECT(mirror.home_bytes(kBase)[200] == 0x11 && mirror.copy_bytes(kBase)[200] == 0x11); + EXPECT(f.filtered.size() == 3 && !f.filtered[2].fresh); + // The same title bytes again: no filter. + EXPECT(mirror.dirty(kBase) && mirror.upload() == 1 && f.filtered.size() == 3); + // The same physical page shown at a second, unaliased address: one home, its copy kept for the aliased one. + mirror.map(kBase + 5 * kPage, &frames[0], nullptr, 2); + EXPECT(mirror.home_bytes(kBase + 5 * kPage) == mirror.home_bytes(kBase) && mirror.copy_bytes(kBase)[0] == 0x5A); + // The aliased address unmaps while the other still shows the page: the copy goes, the home stays the title's. + mirror.map(kBase, nullptr, nullptr, 3); + EXPECT(!mirror.copy_bytes(kBase + 5 * kPage) && mirror.home_bytes(kBase + 5 * kPage)[0] == 0xA5); + // An alias made over a page already mapped: a copy, filtered fresh at once. + mirror.alias(kBase + 2 * kPage, kBase + 3 * kPage, arena, kAt + 2 * kPage); + EXPECT(mirror.copy_bytes(kBase + 2 * kPage)[0] == 0x5A && f.filtered.back().fresh && + f.filtered.back().va == kBase + 2 * kPage); + EXPECT(mirror.flush(4) && *f.read(arena, kAt + 2 * kPage) == 0x5A && *f.read(arena, kAt + 2 * kPage + 1) == 0x5A); + mirror.unalias(kBase + 2 * kPage, 5); + EXPECT(!mirror.copy_bytes(kBase + 2 * kPage) && mirror.home_bytes(kBase + 2 * kPage)[0] == 0xA5); + // The title's bytes changed only where write-back wrote them. + std::vector expect(3 * kPage, 0xA5); + expect[300] = 0x77; + expect[200] = 0x11; + EXPECT(frames == expect); + std::printf("filter: an aliased page's copy filled through the filter (fresh when made, again when the title's " + "bytes change), its own home the title's bytes, written back as any page\n"); + return 0; +} + +int pending_guard_and_frame_dest() { + Fixture f; + TitleMirror mirror(f.hooks()); + EXPECT(mirror.cover(kBase, kBase + 4 * kPage)); + std::vector f_old(kPage, 0x11); + std::vector f_new(kPage, 0x22); + + // Map va -> F_old, flush: now flushed, visible to homes_in and write_back. + mirror.map(kBase, f_old.data(), nullptr, 1); + EXPECT(mirror.has_pending(kBase)); + EXPECT(mirror.flush(1)); + EXPECT(!mirror.has_pending(kBase)); + + // GPU writes to F_old's home: write_back must target F_old's physical frame address, NOT kBase (va). + mirror.home_bytes(kBase)[512] = 0x99; + std::uint64_t got_dst = 0; + const auto write_direct = [&](std::uint64_t dst, const std::uint8_t* bytes, std::size_t n) { + got_dst = dst; + std::memcpy(reinterpret_cast(static_cast(dst)), bytes, n); + return true; + }; + EXPECT(mirror.write_back(kBase, kBase + kPage, write_direct) == 256); + EXPECT(got_dst == reinterpret_cast(f_old.data()) + 512); + EXPECT(got_dst != kBase + 512 && f_old[512] == 0x99); + + // Remap va -> F_new WITHOUT flushing: chunk on GPU still holds F_old's bytes. + // Both homes_in() and write_back() MUST skip va so F_new is never overwritten with stale F_old bytes. + mirror.map(kBase, f_new.data(), nullptr, 2); + EXPECT(mirror.has_pending(kBase)); + std::vector pages; + mirror.homes_in(kBase, kBase + kPage, pages); + EXPECT(pages.empty()); + EXPECT(mirror.homes_in_ranges({{kBase, kBase + kPage}}).empty()); + + std::size_t stale_writes = 0; + const auto staged_stale = [&](std::uint64_t) -> const std::uint8_t* { return f_old.data(); }; + const auto count_writes = [&](std::uint64_t, const std::uint8_t*, std::size_t n) { + stale_writes += n; + return true; + }; + EXPECT(mirror.write_back(kBase, kBase + kPage, staged_stale, count_writes) == 0); + EXPECT(stale_writes == 0 && f_new[0] == 0x22 && f_new[512] == 0x22); + + // Once flushed, homes_in() and write_back() include va again and target F_new. + EXPECT(mirror.flush(2) && !mirror.has_pending(kBase)); + mirror.homes_in(kBase, kBase + kPage, pages); + EXPECT(pages.size() == 1 && pages[0] == kBase); + mirror.home_bytes(kBase)[256] = 0x77; + got_dst = 0; + EXPECT(mirror.write_back(kBase, kBase + kPage, write_direct) == 256); + EXPECT(got_dst == reinterpret_cast(f_new.data()) + 256 && f_new[256] == 0x77); + std::printf("pending_guard_and_frame_dest: unflushed remaps skipped, write-back targets physical frame\n"); + return 0; +} + +int refilter_scaling() { + // 10,240 distinct homes + 1 aliased home, sharing a single 32 MiB dummy unit for the untouched homes so the test + // stays light in RAM while exercising O(changed) refiltering over >10,000 entries in homes_. + constexpr std::size_t kDummyHomes = 10240; + std::vector shared_unit(TitleMirror::kUnitBytes, 0); + std::vector aliased_unit(TitleMirror::kUnitBytes, 0); + std::uintptr_t next_handle = 0x2000; + std::size_t filter_calls = 0; + std::size_t units_made = 0; + + leonida::TitleMirrorHooks h; + h.make_chunk = [&](std::uint64_t, std::uint64_t, VkBuffer& out) { + out = fake(next_handle++); + return true; + }; + h.make_unit = [&](VkDeviceMemory& out, std::uint8_t*& host) { + out = fake(next_handle++); + host = (units_made++ == 0) ? aliased_unit.data() : shared_unit.data(); + return true; + }; + h.free_unit = [](VkDeviceMemory) {}; + h.bind = [](const std::vector&, std::uint64_t) { return true; }; + h.filter = [&](std::uint64_t, std::uint8_t* to, const std::uint8_t* from, std::size_t bytes, bool) { + ++filter_calls; + std::memcpy(to, from, bytes); + return true; + }; + + TitleMirror mirror(std::move(h)); + EXPECT(mirror.cover(kBase, kBase + (kDummyHomes + 4) * kPage)); + + std::vector aliased_frame(kPage, 0x33); + const VkBuffer arena = fake(0x88); + mirror.alias(kBase, kBase + kPage, arena, 0); + mirror.map(kBase, aliased_frame.data(), nullptr, 1); + EXPECT(filter_calls == 1); + + // Distinct frame pointers shifted by 1 byte each over a single (kPage + kDummyHomes) zero buffer. + std::vector dummy_buf(kPage + kDummyHomes, 0); + for (std::size_t i = 0; i < kDummyHomes; ++i) + mirror.map(kBase + (i + 1) * kPage, dummy_buf.data() + i, nullptr, 1); + EXPECT(mirror.flush(1)); + EXPECT(mirror.counters().homes == kDummyHomes + 1); + + const auto noop_write = [](std::uint64_t dst, const std::uint8_t* bytes, std::size_t n) { + std::memcpy(reinterpret_cast(static_cast(dst)), bytes, n); + return true; + }; + // 500 unchanged write-backs on 1 page must be O(1), not O(homes_.size()). + const auto t0 = std::chrono::steady_clock::now(); + for (int i = 0; i < 500; ++i) EXPECT(mirror.write_back(kBase, kBase + kPage, noop_write) == 0); + const auto elapsed_ms = std::chrono::duration_cast(std::chrono::steady_clock::now() - t0).count(); + EXPECT(filter_calls == 1); + + // One real GPU write to the aliased page triggers exactly one refilter. + mirror.home_bytes(kBase)[64] = 0x55; + EXPECT(mirror.write_back(kBase, kBase + kPage, noop_write) == 256); + EXPECT(aliased_frame[64] == 0x55 && filter_calls == 2 && mirror.copy_bytes(kBase)[64] == 0x55); + std::printf("refilter_scaling: 500 write_back calls over %zu homes in %lld ms, O(changed) refilter\n", + std::size_t(mirror.counters().homes), static_cast(elapsed_ms)); + return 0; +} + +int fill_copy_and_fallback() { + Fixture f; + auto h = f.hooks(); + constexpr std::size_t kStrip = TitleMirror::kStripBytes; + constexpr std::size_t kStripsPerPage = kPage / kStrip; + std::size_t strip_calls = 0, piece_calls = 0; + std::size_t fail_strip_offset = ~std::size_t(0); + std::size_t fail_piece_offset = ~std::size_t(0); + const std::uint8_t* tracked_frame = nullptr; + h.copy = [&](std::uint8_t* to, const std::uint8_t* from, std::size_t bytes) { + if (bytes == kStrip) { + ++strip_calls; + if (tracked_frame && std::size_t(from - tracked_frame) == fail_strip_offset) return false; + std::memcpy(to, from, bytes); + return true; + } + ++piece_calls; + if (tracked_frame && std::size_t(from - tracked_frame) == fail_piece_offset) return false; + std::memcpy(to, from, bytes); + return true; + }; + + TitleMirror mirror(std::move(h)); + EXPECT(mirror.cover(kBase, kBase + 4 * kPage)); + std::vector frame(kPage, 0x42); + tracked_frame = frame.data(); + + // Fast path: 4 x 16 KiB L1-hot strip hooks_.copy calls, 0 per-piece calls. + EXPECT(kStrip == 16384 && TitleMirror::kStripPieces == 64 && kStripsPerPage == 4); + mirror.map(kBase, frame.data(), nullptr, 1); + EXPECT(strip_calls == kStripsPerPage && piece_calls == 0 && mirror.counters().upload_failures == 0); + EXPECT(mirror.home_bytes(kBase)[0] == 0x42 && mirror.home_bytes(kBase)[kPage - 1] == 0x42); + + // Dirty refill also uses 4 x 16 KiB strip hooks_.copy calls. + frame[1024] = 0x99; + EXPECT(mirror.dirty(kBase) && mirror.upload() == 1); + EXPECT(strip_calls == 2 * kStripsPerPage && piece_calls == 0 && mirror.home_bytes(kBase)[1024] == 0x99); + + // Fallback path: strip 0 fails -> falls back to ONLY 64 per-piece copies in strip 0; unreadable piece 5 is zeroed. + fail_strip_offset = 0; + fail_piece_offset = 5 * 256; + frame[0] = 0x77; + frame[5 * 256 + 10] = 0xAA; + frame[6 * 256 + 10] = 0xBB; + EXPECT(mirror.dirty(kBase) && mirror.upload() == 1); + EXPECT(strip_calls == 3 * kStripsPerPage && piece_calls == kStrip / 256 && mirror.counters().upload_failures == 1); + EXPECT(mirror.home_bytes(kBase)[0] == 0x77); + EXPECT(mirror.home_bytes(kBase)[5 * 256 + 10] == 0); + EXPECT(mirror.home_bytes(kBase)[6 * 256 + 10] == 0xBB); + std::printf("fill_copy_and_fallback: 16 KiB L1-hot strips on fast path, per-strip 64-piece fallback on failure\n"); + return 0; +} + +int batched_write_back() { + Fixture f; + TitleMirror mirror(f.hooks()); + EXPECT(mirror.cover(kBase, kBase + 6 * kPage)); + std::vector f0(kPage, 0x10), f1(kPage, 0x20), f2(kPage, 0x30), f3(kPage, 0x40), f4(kPage, 0x50); + mirror.map(kBase + 0 * kPage, f0.data(), nullptr, 1); + mirror.map(kBase + 1 * kPage, f1.data(), nullptr, 1); + mirror.map(kBase + 2 * kPage, f2.data(), nullptr, 1); + mirror.map(kBase + 3 * kPage, f3.data(), nullptr, 1); + EXPECT(mirror.flush(1)); + + // Make page 2 pending (unflushed remap): homes_in_ranges must skip it. + mirror.map(kBase + 2 * kPage, f4.data(), nullptr, 2); + EXPECT(mirror.has_pending(kBase + 2 * kPage)); + + // Unsorted, overlapping, and same-piece sub-ranges across pages 0, 1, 2, 3. + const std::vector> ranges = { + {kBase + 3 * kPage + 256, kBase + 3 * kPage + 512}, + {kBase + 0 * kPage + 128, kBase + 0 * kPage + 192}, // same piece 0 as below + {kBase + 0 * kPage + 0, kBase + 0 * kPage + 64}, + {kBase + 0 * kPage + kPage - 64, kBase + 2 * kPage + 512}, // crosses page 0 -> 1 -> pending page 2 + }; + const auto refs = mirror.homes_in_ranges(ranges); + EXPECT(refs.size() == 3); + EXPECT(refs[0].page == kBase + 0 * kPage && refs[0].frame == f0.data() && refs[0].chunk != VK_NULL_HANDLE); + EXPECT(refs[1].page == kBase + 1 * kPage && refs[1].frame == f1.data()); + EXPECT(refs[2].page == kBase + 3 * kPage && refs[2].frame == f3.data()); + + // Build contiguous staged buffer for the 3 snapshotted pages. + std::vector staged(refs.size() * kPage); + std::memcpy(&staged[0 * kPage], f0.data(), kPage); + std::memcpy(&staged[1 * kPage], f1.data(), kPage); + std::memcpy(&staged[2 * kPage], f3.data(), kPage); + + // GPU modified: page 0 piece 0 (covered by two sub-ranges -> must write ONCE), page 1 piece 2 (GPU-only), + // page 1 piece 3 (BOTH GPU and CPU modified -> conflict, CPU wins), page 3 piece 1 (GPU modified, but page 3 is + // remapped while mutex was released -> must be skipped!). + staged[0 * kPage + 10] = 0xA1; + staged[1 * kPage + 2 * 256 + 5] = 0xB2; + staged[1 * kPage + 3 * 256 + 5] = 0xB3; + f1[3 * 256 + 5] = 0xC3; // CPU also modified piece 3 -> conflict + staged[2 * kPage + 1 * 256 + 5] = 0xD4; + + // Simulate page 3 remapping & flushing while page_mirror.mutex was released during GPU readback wait. + std::vector f3_new(kPage, 0x60); + mirror.map(kBase + 3 * kPage, f3_new.data(), nullptr, 3); + EXPECT(mirror.flush(3)); + + std::size_t write_calls = 0; + const auto write = [&](std::uint64_t dst, const std::uint8_t* bytes, std::size_t n) { + ++write_calls; + std::memcpy(reinterpret_cast(static_cast(dst)), bytes, n); + return true; + }; + const std::uint64_t written = mirror.write_back_batch(refs, ranges, staged.data(), write); + EXPECT(written == 512 && write_calls == 2); + EXPECT(f0[10] == 0xA1); + EXPECT(f1[2 * 256 + 5] == 0xB2); + EXPECT(f1[3 * 256 + 5] == 0xC3); // conflict kept CPU bytes + EXPECT(mirror.counters().conflicts == 1); + EXPECT(f3[1 * 256 + 5] == 0x40 && f3_new[1 * 256 + 5] == 0x60); // remapped page 3 skipped + std::printf("batched_write_back: coalescing, dedup, conflict counting, and concurrent-remap skip ok\n"); + return 0; +} + +int filter_pieces_mask_and_scratch() { + Fixture f; + auto h = f.hooks(); + std::size_t copy_bytes_total = 0; + h.copy = [&](std::uint8_t* to, const std::uint8_t* from, std::size_t bytes) { + copy_bytes_total += bytes; + std::memcpy(to, from, bytes); + return true; + }; + struct PieceCall { + std::uint64_t va; + bool fresh; + std::array mask; + std::uint8_t sample_byte; + }; + std::vector piece_calls; + h.filter_pieces = [&](std::uint64_t va, std::uint8_t* to, const std::uint8_t* scratch, std::size_t bytes, + bool fresh, const std::array& mask) { + piece_calls.push_back({va, fresh, mask, scratch[0]}); + for (std::size_t k = 0; k < bytes / 256; ++k) { + if (!fresh && !(mask[k >> 6] & (std::uint64_t(1) << (k & 63)))) continue; + for (std::size_t j = 0; j < 256; ++j) { + const std::uint8_t b = scratch[k * 256 + j]; + to[k * 256 + j] = b == 0xA5 ? 0x5A : b; + } + } + return true; + }; + + TitleMirror mirror(std::move(h)); + EXPECT(mirror.cover(kBase, kBase + 4 * kPage)); + std::vector frame(kPage, 0xA5); + const VkBuffer arena = fake(0x99); + mirror.alias(kBase, kBase + kPage, arena, 0); + + // Initial map on an aliased page: fill() copies once (kPage bytes in 4 KiB strips) into fill_scratch_ and calls + // filter_pieces fresh with all-1s mask from that exact same snapshot (zero duplicate copy, zero TOCTOU). + mirror.map(kBase, frame.data(), nullptr, 1); + EXPECT(copy_bytes_total == kPage && f.filtered.empty() && piece_calls.size() == 1 && piece_calls[0].va == kBase && + piece_calls[0].fresh && piece_calls[0].mask[0] == ~0ull && piece_calls[0].mask[1] == ~0ull && + piece_calls[0].mask[2] == ~0ull && piece_calls[0].mask[3] == ~0ull); + EXPECT(mirror.copy_bytes(kBase)[0] == 0x5A); + + // Dirty refill modifying 3 pieces across 64-bit mask word boundaries: pieces 1, 64, and 255. + // Must copy kPage bytes ONCE (fill's scratch), ZERO extra copies, and call filter_pieces with exact mask! + frame[1 * 256 + 7] = 0x11; + frame[64 * 256 + 3] = 0x22; + frame[255 * 256 + 200] = 0x33; + EXPECT(mirror.dirty(kBase) && mirror.upload() == 1); + EXPECT(copy_bytes_total == 2 * kPage); // exactly 1 page copied in fill(), 0 duplicate copies in filter_pieces! + EXPECT(f.filtered.empty() && piece_calls.size() == 2); + EXPECT(piece_calls[1].va == kBase && !piece_calls[1].fresh); + EXPECT(piece_calls[1].mask[0] == (std::uint64_t(1) << 1)); + EXPECT(piece_calls[1].mask[1] == (std::uint64_t(1) << 0)); + EXPECT(piece_calls[1].mask[2] == 0); + EXPECT(piece_calls[1].mask[3] == (std::uint64_t(1) << 63)); + EXPECT(mirror.copy_bytes(kBase)[1 * 256 + 7] == 0x11); + EXPECT(mirror.copy_bytes(kBase)[64 * 256 + 3] == 0x22); + EXPECT(mirror.copy_bytes(kBase)[255 * 256 + 200] == 0x33); + EXPECT(mirror.copy_bytes(kBase)[0] == 0x5A); // untouched piece preserved + + // Unchanged dirty upload: neither filter_pieces nor filter called. + EXPECT(mirror.dirty(kBase) && mirror.upload() == 1); + EXPECT(copy_bytes_total == 3 * kPage && piece_calls.size() == 2 && f.filtered.empty()); + + // Only filter_pieces installed (no hooks_.filter): make_copy calls filter_pieces with all-1s mask. + Fixture f2; + auto h2 = f2.hooks(); + h2.filter = nullptr; + std::array init_mask{}; + bool init_fresh = false; + h2.filter_pieces = [&](std::uint64_t, std::uint8_t* to, const std::uint8_t* scratch, std::size_t bytes, + bool fresh, const std::array& mask) { + init_mask = mask; + init_fresh = fresh; + std::memcpy(to, scratch, bytes); + return true; + }; + TitleMirror mirror2(std::move(h2)); + EXPECT(mirror2.cover(kBase, kBase + 2 * kPage)); + mirror2.alias(kBase, kBase + kPage, arena, 0); + mirror2.map(kBase, frame.data(), nullptr, 1); + EXPECT(init_fresh && init_mask[0] == ~0ull && init_mask[1] == ~0ull && init_mask[2] == ~0ull && + init_mask[3] == ~0ull); + EXPECT(mirror2.copy_bytes(kBase)[64 * 256 + 3] == 0x22); + + std::printf("filter_pieces_mask_and_scratch: zero duplicate copy, exact 256-bit changed-piece mask ok\n"); + return 0; +} + +int coalesced_fill_and_write_back_soundness() { + Fixture f; + TitleMirror mirror(f.hooks()); + EXPECT(mirror.cover(kBase, kBase + 2 * kPage)); + std::vector frame(kPage, 0x10); + mirror.map(kBase, frame.data(), nullptr, 1); + EXPECT(mirror.flush(1)); + + // Modify contiguous runs spanning 64-bit word boundaries: [0..2], [62..65], [127..129], [254..255]. + const std::vector cpu_pieces = {0, 1, 2, 62, 63, 64, 65, 127, 128, 129, 254, 255}; + for (const std::size_t p : cpu_pieces) std::memset(frame.data() + p * 256, int(0x40 + (p & 0x3f)), 256); + EXPECT(mirror.dirty(kBase) && mirror.upload() == 1); + EXPECT(!std::memcmp(mirror.home_bytes(kBase), frame.data(), kPage)); + + // Now test write-back soundness (home.sums must be exact after coalesced fill!): + // - Piece 63 (in CPU-updated run): GPU modifies it, CPU does not -> GPU write goes back! + // - Piece 64 (in CPU-updated run): BOTH GPU and CPU modify it -> conflict, CPU wins! + // - Piece 10 (untouched since initial whole fill): GPU modifies it -> GPU write goes back! + mirror.home_bytes(kBase)[63 * 256 + 11] = 0xE1; + mirror.home_bytes(kBase)[64 * 256 + 12] = 0xE2; + frame[64 * 256 + 13] = 0xF2; + mirror.home_bytes(kBase)[10 * 256 + 14] = 0xE3; + + const auto write = [](std::uint64_t dst, const std::uint8_t* bytes, std::size_t n) { + std::memcpy(reinterpret_cast(static_cast(dst)), bytes, n); + return true; + }; + const std::uint64_t written = mirror.write_back(kBase, kBase + kPage, write); + EXPECT(written == 512); // pieces 10 and 63 only + EXPECT(frame[63 * 256 + 11] == 0xE1); + EXPECT(frame[10 * 256 + 14] == 0xE3); + EXPECT(frame[64 * 256 + 12] == std::uint8_t(0x40 + (64 & 0x3f))); // conflict: GPU byte rejected + EXPECT(frame[64 * 256 + 13] == 0xF2); // conflict: CPU byte preserved + EXPECT(mirror.counters().conflicts == 1); + + std::printf("coalesced_fill_and_write_back_soundness: word-spanning runs and home.sums conflict detection ok\n"); + return 0; +} + +// Regression: A -> B -> A writes across home_of() -> make_copy() (alias over mapped page), alias handoff in map(), and +// finish_write_back(). Every filtered copy fill syncs home and home.sums[] from the exact same snapshot so reverting +// B -> A is always detected by fill() and propagated to the filtered copy without clobbering GPU-only pieces. +int make_copy_aba_staleness() { + Fixture f; + auto h = f.hooks(); + std::vector> masks; + h.filter_pieces = [&](std::uint64_t, std::uint8_t* to, const std::uint8_t* scratch, std::size_t bytes, bool fresh, + const std::array& mask) { + masks.push_back(mask); + for (std::size_t k = 0; k < bytes / 256; ++k) { + if (!fresh && !(mask[k >> 6] & (std::uint64_t(1) << (k & 63)))) continue; + for (std::size_t j = 0; j < 256; ++j) { + const std::uint8_t b = scratch[k * 256 + j]; + to[k * 256 + j] = b == 0xA5 ? 0x5A : b; + } + } + return true; + }; + + TitleMirror mirror(std::move(h)); + EXPECT(mirror.cover(kBase, kBase + 8 * kPage)); + const VkBuffer arena = fake(0xAA); + + // 1. alias() over an already-mapped page (make_copy path): A -> B before alias(), then B -> A on upload(). + std::vector frame0(kPage, 0x11); // A + mirror.map(kBase, frame0.data(), nullptr, 1); + EXPECT(mirror.flush(1)); + // GPU writes piece 5 (must be preserved by make_copy's piece-wise sync!). + mirror.home_bytes(kBase)[5 * 256 + 9] = 0xEE; + // Title writes B (0xA5) into piece 2 before alias() calls make_copy(), without upload(). + frame0[2 * 256 + 4] = 0xA5; + mirror.alias(kBase, kBase + kPage, arena, 0); + EXPECT(mirror.copy_bytes(kBase)[2 * 256 + 4] == 0x5A); // filtered B + EXPECT(mirror.home_bytes(kBase)[2 * 256 + 4] == 0xA5); // home synced to B + EXPECT(mirror.home_bytes(kBase)[5 * 256 + 9] == 0xEE); // GPU-only piece preserved! + // Title writes A (0x11) back into piece 2: upload() MUST see piece 2 changed vs home.sums[2] and update copy! + frame0[2 * 256 + 4] = 0x11; + const std::size_t calls_before = masks.size(); + EXPECT(mirror.dirty(kBase) && mirror.upload() == 1); + EXPECT(masks.size() == calls_before + 1); + EXPECT(masks.back()[0] == (std::uint64_t(1) << 2)); + EXPECT(mirror.copy_bytes(kBase)[2 * 256 + 4] == 0x11); + EXPECT(mirror.home_bytes(kBase)[2 * 256 + 4] == 0x11); + EXPECT(mirror.home_bytes(kBase)[5 * 256 + 9] == 0xEE); + + // 2. Alias handoff in map(): two aliased VAs share one frame; A -> B before va1 unmaps, then B -> A on va2. + std::vector frame1(kPage, 0x22); // A + const std::uint64_t va1 = kBase + 2 * kPage; + const std::uint64_t va2 = kBase + 3 * kPage; + mirror.alias(va1, va2 + kPage, arena, 2 * kPage); + mirror.map(va1, frame1.data(), nullptr, 2); + mirror.map(va2, frame1.data(), nullptr, 2); + EXPECT(mirror.flush(2)); + frame1[3 * 256 + 8] = 0xA5; // B without upload() + mirror.map(va1, nullptr, nullptr, 3); // hands off copy to va2 + EXPECT(mirror.copy_bytes(va2)[3 * 256 + 8] == 0x5A); + EXPECT(mirror.home_bytes(va2)[3 * 256 + 8] == 0xA5); + frame1[3 * 256 + 8] = 0x22; // revert B -> A + EXPECT(mirror.dirty(va2) && mirror.upload() == 1); + EXPECT(mirror.copy_bytes(va2)[3 * 256 + 8] == 0x22); + EXPECT(mirror.home_bytes(va2)[3 * 256 + 8] == 0x22); + + // 3. Concurrent title A -> B write during write_back() before finish_write_back() runs, then B -> A on upload(). + std::vector frame2(kPage, 0x33); // A + const std::uint64_t va3 = kBase + 5 * kPage; + mirror.alias(va3, va3 + kPage, arena, 5 * kPage); + mirror.map(va3, frame2.data(), nullptr, 4); + EXPECT(mirror.flush(4)); + mirror.home_bytes(va3)[1 * 256 + 10] = 0x77; // GPU writes piece 1 + const auto write_with_race = [&](std::uint64_t dst, const std::uint8_t* bytes, std::size_t n) { + std::memcpy(reinterpret_cast(static_cast(dst)), bytes, n); + // Simulate concurrent CPU write A -> B in piece 0 before finish_write_back() refilters. + frame2[0 * 256 + 12] = 0xA5; + return true; + }; + EXPECT(mirror.write_back(va3, va3 + kPage, write_with_race) == 256); + EXPECT(mirror.copy_bytes(va3)[1 * 256 + 10] == 0x77); + EXPECT(mirror.copy_bytes(va3)[0 * 256 + 12] == 0x5A); // filtered B + EXPECT(mirror.home_bytes(va3)[0 * 256 + 12] == 0xA5); // home synced to B + frame2[0 * 256 + 12] = 0x33; // revert B -> A + EXPECT(mirror.dirty(va3) && mirror.upload() == 1); + EXPECT(mirror.copy_bytes(va3)[0 * 256 + 12] == 0x33); + EXPECT(mirror.home_bytes(va3)[0 * 256 + 12] == 0x33); + + std::printf("make_copy_aba_staleness: make_copy, alias handoff, and finish_write_back sync home.sums[] on A->B->A ok\n"); + return 0; +} + +// Regression: re-entrant map() calls inside filter_pieces during alias() (make_copy) and map() (alias handoff) can +// rehash both pages_ and homes_. Neither path may dereference invalidated unordered_map iterators. +int reentrant_rehash_in_alias_and_handoff() { + Fixture f; + auto h = f.hooks(); + TitleMirror* mirror_ptr = nullptr; + std::vector reentrant_frames(128 * kPage, 0x44); + std::size_t next_reentrant = 0; + bool trigger_rehash = false; + h.filter_pieces = [&](std::uint64_t, std::uint8_t* to, const std::uint8_t* scratch, std::size_t bytes, bool, + const std::array&) { + std::memcpy(to, scratch, bytes); + if (trigger_rehash && mirror_ptr) { + trigger_rehash = false; + // Insert 64 distinct pages & homes to force pages_ and homes_ rehashes mid-callback. + for (std::size_t i = 0; i < 64 && next_reentrant < 128; ++i, ++next_reentrant) { + mirror_ptr->map(kBase + (100 + next_reentrant) * kPage, + &reentrant_frames[next_reentrant * kPage], nullptr, 10); + } + } + return true; + }; + + TitleMirror mirror(std::move(h)); + mirror_ptr = &mirror; + EXPECT(mirror.cover(kBase, kBase + 300 * kPage)); + const VkBuffer arena = fake(0xBB); + + // 1. alias() over mapped pages with re-entrant homes_/pages_ rehash inside make_copy(). + std::vector f0(kPage, 0x12), f1(kPage, 0x34); + mirror.map(kBase, f0.data(), nullptr, 1); + mirror.map(kBase + kPage, f1.data(), nullptr, 1); + trigger_rehash = true; + mirror.alias(kBase, kBase + 2 * kPage, arena, 0); + EXPECT(mirror.flush(1)); + EXPECT(mirror.copy_bytes(kBase) && mirror.copy_bytes(kBase)[0] == 0x12); + EXPECT(mirror.copy_bytes(kBase + kPage) && mirror.copy_bytes(kBase + kPage)[0] == 0x34); + EXPECT(*f.read(arena, 0) == 0x12 && *f.read(arena, kPage) == 0x34); + + // 2. map() alias handoff with re-entrant pages_/homes_ rehash inside sync_and_fill_copy(). + std::vector shared(kPage, 0x56); + const std::uint64_t va1 = kBase + 10 * kPage; + const std::uint64_t va2 = kBase + 11 * kPage; + mirror.alias(va1, va2 + kPage, arena, 10 * kPage); + mirror.map(va1, shared.data(), nullptr, 2); + mirror.map(va2, shared.data(), nullptr, 2); + EXPECT(mirror.flush(2)); + trigger_rehash = true; + mirror.map(va1, nullptr, nullptr, 3); // hands off copy to va2, rehashes pages_/homes_, then erases va1 + EXPECT(mirror.flush(3)); + EXPECT(!mirror.mirrored(va1) && mirror.mirrored(va2)); + EXPECT(mirror.copy_bytes(va2) && mirror.copy_bytes(va2)[0] == 0x56); + EXPECT(!f.read(arena, 10 * kPage) && *f.read(arena, 11 * kPage) == 0x56); + + std::printf("reentrant_rehash_in_alias_and_handoff: alias() and map() handoff safe across pages_/homes_ rehash ok\n"); + return 0; +} + +int lock_free_pending_fast_paths() { + Fixture f; + TitleMirror mirror(f.hooks()); + EXPECT(mirror.cover(kBase, kBase + 4 * kPage)); + EXPECT(!mirror.has_pending_work() && !mirror.has_pending_binds() && !mirror.has_dirty() && + !mirror.has_retired_homes()); + + std::vector frame(kPage, 0x21); + mirror.map(kBase, frame.data(), nullptr, 1); + EXPECT(mirror.has_pending_binds() && mirror.has_pending_work() && !mirror.has_dirty()); + EXPECT(mirror.flush(1)); + EXPECT(!mirror.has_pending_binds() && !mirror.has_pending_work()); + + // Dirty with unchanged bytes: has_dirty() transitions true -> false, and last_upload_bytes() reports 0! + EXPECT(mirror.dirty(kBase)); + EXPECT(mirror.has_dirty() && mirror.has_pending_work()); + EXPECT(mirror.upload() == 1); + EXPECT(!mirror.has_dirty() && !mirror.has_pending_work()); + EXPECT(mirror.last_upload_bytes() == 0); + + // Dirty with 1 modified 256-byte piece: last_upload_bytes() reports 256. + frame[10] = 0x99; + EXPECT(mirror.dirty(kBase)); + EXPECT(mirror.upload() == 1); + EXPECT(mirror.last_upload_bytes() == 256); + + // Unmap retires home at ticket 10: has_retired_homes(completed) checks oldest ticket in O(1) without locking. + mirror.map(kBase, nullptr, nullptr, 10); + EXPECT(mirror.flush(2)); + EXPECT(mirror.has_retired_homes()); + EXPECT(!mirror.has_retired_homes(9)); + EXPECT(mirror.has_retired_homes(10)); + mirror.retire(9); + EXPECT(mirror.has_retired_homes()); + mirror.retire(10); + EXPECT(!mirror.has_retired_homes() && !mirror.has_pending_work()); + + std::printf("lock_free_pending_fast_paths: O(1) bind/dirty/retire/upload_bytes queries ok\n"); + return 0; +} + +int range_sum_piece_hashing() { + Fixture f; + TitleMirror mirror(f.hooks()); + EXPECT(mirror.cover(kBase, kBase + 8 * kPage)); + + std::vector f0(kPage, 0x11); + std::vector f1(kPage, 0x22); + std::vector f2(kPage, 0x33); + mirror.map(kBase + 0 * kPage, f0.data(), nullptr, 1); + mirror.map(kBase + 1 * kPage, f1.data(), nullptr, 1); + EXPECT(mirror.flush(1)); + + // Error / boundary cases: zero bytes, overflow, unmirrored page. + std::uint64_t h = 0; + EXPECT(!mirror.range_sum(kBase, 0, h)); + EXPECT(!mirror.range_sum(UINT64_MAX - 10, 100, h)); + EXPECT(!mirror.range_sum(kBase + 2 * kPage, 256, h)); // page 2 not mapped + EXPECT(!mirror.range_sum(kBase + kPage, 2 * kPage, h)); // crosses into unmapped page 2 + + // 1. Sub-page range [512, 512 + 1024) inside page 0 (pieces [2, 6)). + const std::uint64_t tex_a = kBase + 512; + const std::uint64_t tex_a_bytes = 1024; + std::uint64_t ha0 = 0; + EXPECT(mirror.range_sum(tex_a, tex_a_bytes, ha0)); + + // Modify neighbor byte in a DIFFERENT 256-byte piece of the SAME 64 KiB page (piece 0 & piece 6): + // range_sum for tex_a MUST stay identical! + f0[10] = 0xAA; // piece 0 (before tex_a) + f0[6 * 256 + 7] = 0xBB; // piece 6 (right after tex_a) + EXPECT(mirror.dirty(kBase) && mirror.upload() == 1); + std::uint64_t ha1 = 0; + EXPECT(mirror.range_sum(tex_a, tex_a_bytes, ha1)); + EXPECT(ha1 == ha0); + + // Modify a byte INSIDE tex_a (piece 4): range_sum MUST change! + f0[4 * 256 + 13] = 0xCC; + EXPECT(mirror.dirty(kBase) && mirror.upload() == 1); + std::uint64_t ha2 = 0; + EXPECT(mirror.range_sum(tex_a, tex_a_bytes, ha2)); + EXPECT(ha2 != ha0); + + // Revert byte back to original value: range_sum MUST return to ha0! + f0[4 * 256 + 13] = 0x11; + EXPECT(mirror.dirty(kBase) && mirror.upload() == 1); + std::uint64_t ha3 = 0; + EXPECT(mirror.range_sum(tex_a, tex_a_bytes, ha3)); + EXPECT(ha3 == ha0); + + // 2. Unaligned multi-page range crossing page 0 -> page 1: [kBase + kPage - 100, kBase + kPage + 300). + // Overlaps piece 255 of page 0 and pieces [0, 2) of page 1. + const std::uint64_t cross_va = kBase + kPage - 100; + const std::uint64_t cross_bytes = 400; + std::uint64_t hc0 = 0; + EXPECT(mirror.range_sum(cross_va, cross_bytes, hc0)); + + // Neighbor write in piece 254 of page 0 and piece 2 of page 1 -> MUST NOT change cross_va's range_sum! + f0[254 * 256 + 255] = 0x44; + f1[2 * 256 + 0] = 0x55; + EXPECT(mirror.dirty(kBase) && mirror.dirty(kBase + kPage) && mirror.upload() == 2); + std::uint64_t hc1 = 0; + EXPECT(mirror.range_sum(cross_va, cross_bytes, hc1)); + EXPECT(hc1 == hc0); + + // Write inside piece 255 of page 0 -> MUST change cross_va's range_sum! + f0[kPage - 1] = 0x66; + EXPECT(mirror.dirty(kBase) && mirror.upload() == 1); + std::uint64_t hc2 = 0; + EXPECT(mirror.range_sum(cross_va, cross_bytes, hc2)); + EXPECT(hc2 != hc0); + + // Write inside piece 1 of page 1 -> MUST change cross_va's range_sum again! + f1[256 + 43] = 0x77; + EXPECT(mirror.dirty(kBase + kPage) && mirror.upload() == 1); + std::uint64_t hc3 = 0; + EXPECT(mirror.range_sum(cross_va, cross_bytes, hc3)); + EXPECT(hc3 != hc2); + + // 3. write_back() updates home.sums[], so range_sum() MUST reflect GPU write-backs! + const auto write = [](std::uint64_t dst, const std::uint8_t* bytes, std::size_t n) { + std::memcpy(reinterpret_cast(static_cast(dst)), bytes, n); + return true; + }; + mirror.home_bytes(kBase + kPage)[0 * 256 + 12] = 0xEE; // GPU writes piece 0 of page 1 (inside cross_va) + EXPECT(mirror.write_back(kBase + kPage, kBase + 2 * kPage, write) == 256); + EXPECT(f1[12] == 0xEE); + std::uint64_t hc4 = 0; + EXPECT(mirror.range_sum(cross_va, cross_bytes, hc4)); + EXPECT(hc4 != hc3); + + // 4. Remap page 1 to f2 (different bytes): range_sum() MUST change! + mirror.map(kBase + kPage, f2.data(), nullptr, 2); + EXPECT(mirror.flush(2)); + std::uint64_t hc5 = 0; + EXPECT(mirror.range_sum(cross_va, cross_bytes, hc5)); + EXPECT(hc5 != hc4); + + std::printf("range_sum_piece_hashing: same-page neighbor invariance, multi-page unaligned, write_back, remap ok\n"); + return 0; +} + +int unstamped_freed_homes_wait_for_flush() { + Fixture f; + TitleMirror mirror(f.hooks()); + EXPECT(mirror.cover(kBase, kBase + 4 * kPage)); + const VkBuffer arena = fake(0x99); + constexpr VkDeviceSize kAt = 0xc000000; + mirror.alias(kBase, kBase + 2 * kPage, arena, kAt); + + std::vector f0(kPage, 0x31); + std::vector f1(kPage, 0x42); + mirror.map(kBase, f0.data(), nullptr); + mirror.map(kBase + kPage, f1.data(), nullptr); + EXPECT(mirror.flush(1)); + EXPECT(mirror.unstamped_freed_count() == 0 && !mirror.has_retired_homes() && mirror.counters().homes_freed == 0); + + // Unmap page 0 (frees both its home and its aliased filtered copy as unstamped) and unalias page 1 (frees its + // filtered copy as unstamped): NONE of the 3 freed slots may be retired until flush() + stamp_freed() run. + mirror.map(kBase, nullptr, nullptr); + mirror.unalias(kBase); + EXPECT(mirror.unstamped_freed_count() == 3); + EXPECT(!mirror.has_retired_homes()); + mirror.retire(UINT64_MAX); + EXPECT(mirror.counters().homes_freed == 0 && mirror.unstamped_freed_count() == 3); + + // Flush publishes the sparse unbinds; stamp_freed(42) stamps the 3 slots with the post-note_mirror_bind ticket. + EXPECT(mirror.flush(2)); + mirror.stamp_freed(42); + EXPECT(mirror.unstamped_freed_count() == 0); + EXPECT(mirror.has_retired_homes() && !mirror.has_retired_homes(41) && mirror.has_retired_homes(42)); + mirror.retire(41); + EXPECT(mirror.counters().homes_freed == 0 && mirror.has_retired_homes()); + mirror.retire(42); + EXPECT(mirror.counters().homes_freed == 3 && !mirror.has_retired_homes()); + + std::printf("unstamped_freed_homes_wait_for_flush: unstamped home and alias copies stay held until flush + stamp ok\n"); + return 0; +} + +int parallel_upload_matches_serial() { + constexpr std::size_t kPages = 96; + constexpr std::size_t kFilteredPages = 16; + constexpr std::size_t kFailPage = 90; + constexpr std::size_t kFailPiece = 17; + const VkBuffer arena = fake(0xC1); + + struct FilterLog { + std::uint64_t va; + bool fresh; + std::array mask; + bool operator==(const FilterLog& o) const = default; + }; + + struct RunResult { + std::size_t uploaded_count = 0; + std::uint64_t last_upload_bytes = 0; + TitleMirror::Counters counters{}; + std::vector all_homes; + std::vector all_copies; + std::vector page_hashes; + std::vector filter_logs; + std::uint64_t reentrant_hash = 0; + }; + + const auto run_once = [&](bool parallel, RunResult& out) -> int { + Fixture f; + auto h = f.hooks(); + std::vector frames(kPages * kPage); + for (std::size_t i = 0; i < frames.size(); ++i) + frames[i] = std::uint8_t((i * 37 + (i / kPage) * 13 + 5) & 0xff); + const std::uint8_t* const fail_frame = frames.data() + kFailPage * kPage; + bool enable_copy_fail = false; + h.copy = [fail_frame, &enable_copy_fail](std::uint8_t* to, const std::uint8_t* from, std::size_t bytes) { + constexpr std::size_t kFailStripOff = (kFailPiece * 256) & ~(TitleMirror::kStripBytes - 1); + if (enable_copy_fail && from == fail_frame + kFailStripOff && bytes == TitleMirror::kStripBytes) + return false; + if (enable_copy_fail && bytes == 256 && from == fail_frame + kFailPiece * 256) return false; + std::memcpy(to, from, bytes); + return true; + }; + + TitleMirror* mirror_ptr = nullptr; + std::vector reentrant_frames(64 * kPage, 0x6D); + bool trigger_rehash = false; + h.filter_pieces = [&](std::uint64_t va, std::uint8_t* to, const std::uint8_t* scratch, std::size_t bytes, + bool fresh, const std::array& mask) { + out.filter_logs.push_back({va, fresh, mask}); + for (std::size_t k = 0; k < bytes / 256; ++k) { + if (!fresh && !(mask[k >> 6] & (std::uint64_t(1) << (k & 63)))) continue; + for (std::size_t j = 0; j < 256; ++j) { + const std::uint8_t b = scratch[k * 256 + j]; + to[k * 256 + j] = (b == 0xA5) ? 0x5A : b; + } + } + if (trigger_rehash && va == kBase + 4 * kPage && mirror_ptr) { + trigger_rehash = false; + for (std::size_t r = 0; r < 64; ++r) { + mirror_ptr->map(kBase + (200 + r) * kPage, reentrant_frames.data() + r * kPage, nullptr, 9); + } + } + return true; + }; + + TitleMirror mirror(std::move(h)); + mirror_ptr = &mirror; + mirror.set_parallel(parallel); + EXPECT(mirror.cover(kBase, kBase + 300 * kPage)); + mirror.alias(kBase, kBase + kFilteredPages * kPage, arena, 0); + + for (std::size_t p = 0; p < kPages; ++p) { + // Pages 20..23 alias physical frames 16..19 (physical-page aliasing). + const std::size_t frame_idx = (p >= 20 && p < 24) ? (p - 4) : p; + mirror.map(kBase + p * kPage, frames.data() + frame_idx * kPage, nullptr, 1); + } + EXPECT(mirror.flush(1)); + + // Inject GPU-only writes into untouched piece 10 of several homes to verify parallel upload preserves them. + for (std::size_t p = 24; p < 40; ++p) mirror.home_bytes(kBase + p * kPage)[10 * 256 + 3] = 0xEE; + + // Mutate a diverse mix: filtered pages (with 0xA5), aliased frames, word-boundary pieces, full pages, + // untouched pages (40..55), and the failing-copy page 90. + for (std::size_t p = 0; p < kPages; ++p) { + if (p >= 20 && p < 24) continue; // shared with 16..19 + if (p >= 40 && p < 56) continue; // intentionally unchanged dirty pages + std::uint8_t* const fptr = frames.data() + p * kPage; + if (p < kFilteredPages) { + fptr[0 * 256 + 1] = 0xA5; + fptr[63 * 256 + 2] = std::uint8_t(0x20 + p); + fptr[64 * 256 + 3] = 0xA5; + fptr[255 * 256 + 4] = std::uint8_t(0x80 + p); + } else if (p < 40) { + const std::size_t pcs[] = {0, 1, 62, 63, 64, 65, 127, 128, 254, 255}; + for (std::size_t pc : pcs) fptr[pc * 256 + (p & 31)] ^= 0x5A; + } else if (p < 72) { + for (std::size_t pc = 0; pc < 256; ++pc) fptr[pc * 256] ^= std::uint8_t(0xA0 + (pc & 15)); + } else { + fptr[5 * 256 + 9] ^= 0x33; + fptr[kFailPiece * 256 + 7] = 0xCC; + fptr[200 * 256 + 11] ^= 0x77; + } + } + enable_copy_fail = true; + trigger_rehash = true; + for (std::size_t p = 0; p < kPages; ++p) EXPECT(mirror.dirty(kBase + p * kPage)); + + out.uploaded_count = mirror.upload(); + out.last_upload_bytes = mirror.last_upload_bytes(); + out.counters = mirror.counters(); + out.all_homes.resize(kPages * kPage); + for (std::size_t p = 0; p < kPages; ++p) { + std::memcpy(out.all_homes.data() + p * kPage, mirror.home_bytes(kBase + p * kPage), kPage); + } + out.all_copies.resize(kFilteredPages * kPage); + for (std::size_t p = 0; p < kFilteredPages; ++p) { + std::memcpy(out.all_copies.data() + p * kPage, mirror.copy_bytes(kBase + p * kPage), kPage); + } + out.page_hashes.resize(kPages); + for (std::size_t p = 0; p < kPages; ++p) { + EXPECT(mirror.range_sum(kBase + p * kPage, kPage, out.page_hashes[p])); + } + EXPECT(mirror.range_sum(kBase + 200 * kPage, 64 * kPage, out.reentrant_hash)); + // Verify GPU-only writes survived and failing piece 17 was zeroed. + for (std::size_t p = 24; p < 40; ++p) EXPECT(mirror.home_bytes(kBase + p * kPage)[10 * 256 + 3] == 0xEE); + EXPECT(mirror.home_bytes(kBase + kFailPage * kPage)[kFailPiece * 256 + 7] == 0); + EXPECT(mirror.counters().upload_failures == 1); + return 0; + }; + + RunResult serial{}, par{}; + if (run_once(false, serial)) return 1; + if (run_once(true, par)) return 1; + + EXPECT(par.uploaded_count == serial.uploaded_count); + EXPECT(par.uploaded_count == kPages - 4); // 4 aliased VAs deduplicated + EXPECT(par.last_upload_bytes == serial.last_upload_bytes); + EXPECT(par.counters.uploads == serial.counters.uploads); + EXPECT(par.counters.uploaded_bytes == serial.counters.uploaded_bytes); + EXPECT(par.counters.upload_failures == serial.counters.upload_failures); + EXPECT(par.counters.filtered == serial.counters.filtered); + EXPECT(par.counters.homes == serial.counters.homes); + EXPECT(par.counters.pages == serial.counters.pages); + EXPECT(par.all_homes == serial.all_homes); + EXPECT(par.all_copies == serial.all_copies); + EXPECT(par.page_hashes == serial.page_hashes); + EXPECT(par.filter_logs == serial.filter_logs); + EXPECT(par.reentrant_hash == serial.reentrant_hash); + + std::printf("parallel_upload_matches_serial: 96 dirty pages (filtered, aliased, partial, fallback, rehash) 100%% " + "identical\n"); + return 0; +} + +int parallel_write_back_batch_matches_serial() { + constexpr std::size_t kPages = 80; + constexpr std::size_t kFilteredPages = 8; + const VkBuffer arena = fake(0xC2); + + struct WriteEvent { + std::size_t frame_offset; + std::array bytes; + bool operator==(const WriteEvent& o) const = default; + }; + + struct RunResult { + std::uint64_t written = 0; + TitleMirror::Counters counters{}; + std::vector frames; + std::vector copies; + std::vector page_hashes; + std::vector writes; + }; + + const auto run_once = [&](bool parallel, RunResult& out) -> int { + Fixture f; + TitleMirror mirror(f.hooks()); + mirror.set_parallel(parallel); + EXPECT(mirror.cover(kBase, kBase + (kPages + 8) * kPage)); + mirror.alias(kBase, kBase + kFilteredPages * kPage, arena, 0); + + out.frames.resize(kPages * kPage); + for (std::size_t i = 0; i < out.frames.size(); ++i) + out.frames[i] = std::uint8_t((i * 53 + (i / kPage) * 19 + 11) & 0xff); + + for (std::size_t p = 0; p < kPages; ++p) { + // Pages 12 and 13 share physical frames 10 and 11 (physical-page aliasing). + const std::size_t frame_idx = (p == 12 || p == 13) ? (p - 2) : p; + mirror.map(kBase + p * kPage, out.frames.data() + frame_idx * kPage, nullptr, 1); + } + EXPECT(mirror.flush(1)); + + // Mix of full-page ranges, partial sub-ranges, overlapping ranges, and out-of-order ranges. + const std::vector> ranges = { + {kBase + 40 * kPage, kBase + kPages * kPage}, + {kBase + 0 * kPage, kBase + 24 * kPage}, + {kBase + 24 * kPage + 256, kBase + 24 * kPage + 1024}, // partial pieces [1..4) + {kBase + 25 * kPage + 63 * 256, kBase + 25 * kPage + 66 * 256}, // word boundary [63..66) + {kBase + 26 * kPage, kBase + 41 * kPage}, // overlaps 40..41 + }; + const auto refs = mirror.homes_in_ranges(ranges); + EXPECT(refs.size() == kPages); + + std::vector staged(refs.size() * kPage); + for (std::size_t i = 0; i < refs.size(); ++i) { + std::memcpy(staged.data() + i * kPage, refs[i].frame, kPage); + } + + // Apply GPU-only writes, CPU-only writes, and both-sides conflicts across the 80 pages. + // 1. Filtered aliased pages 2 and 5: GPU-only writes -> must write back AND refilter! + staged[2 * kPage + 3 * 256 + 7] = 0xA5; // filtered to 0x5A in copy_bytes + staged[5 * kPage + 128 * 256 + 15] = 0x91; + // 2. Shared physical frames 10/12 and 11/13: GPU writes on alias 10, conflict on alias 11. + staged[10 * kPage + 4 * 256 + 1] = 0xE1; + staged[12 * kPage + 4 * 256 + 1] = 0xE1; + staged[11 * kPage + 8 * 256 + 2] = 0xE2; + out.frames[11 * kPage + 8 * 256 + 2] = 0xC2; // CPU also modified -> conflict + // 3. Partial-range page 24: GPU modifies piece 0 (outside [1..4) -> ignored!) and piece 2 (inside -> written!). + staged[24 * kPage + 0 * 256 + 5] = 0xDD; + staged[24 * kPage + 2 * 256 + 5] = 0x72; + // 4. Word-boundary partial page 25: GPU modifies pieces 63, 64, 65 (64 also CPU-modified -> conflict). + staged[25 * kPage + 63 * 256 + 1] = 0x73; + staged[25 * kPage + 64 * 256 + 1] = 0x74; + out.frames[25 * kPage + 64 * 256 + 2] = 0x84; + staged[25 * kPage + 65 * 256 + 1] = 0x75; + // 5. High pages 30..75: mix of GPU-only, CPU-only, and conflicts. + for (std::size_t p = 30; p < 76; ++p) { + if (p % 3 == 0) { + // GPU-only across 3 pieces + staged[p * kPage + 1 * 256 + 3] ^= 0x41; + staged[p * kPage + 64 * 256 + 4] ^= 0x42; + staged[p * kPage + 255 * 256 + 5] ^= 0x43; + } else if (p % 3 == 1) { + // CPU-only write (GPU unchanged -> no write-back, CPU bytes preserved) + out.frames[p * kPage + 12 * 256 + 6] ^= 0x55; + } else { + // Both sides modify piece 20 -> conflict, CPU wins; GPU-only modifies piece 21 -> written! + staged[p * kPage + 20 * 256 + 7] ^= 0x61; + out.frames[p * kPage + 20 * 256 + 8] ^= 0x62; + staged[p * kPage + 21 * 256 + 9] ^= 0x63; + } + } + // 6. Remap page 77 (flushed) and make page 78 pending (unflushed) after snapshot -> both must be skipped! + std::vector remap_frame(kPage, 0xFA); + staged[77 * kPage + 2 * 256 + 1] = 0x19; + staged[78 * kPage + 2 * 256 + 1] = 0x29; + mirror.map(kBase + 77 * kPage, remap_frame.data(), nullptr, 2); + EXPECT(mirror.flush(2)); + mirror.map(kBase + 78 * kPage, remap_frame.data(), nullptr, 3); // pending, not flushed + + const auto base_ptr = reinterpret_cast(out.frames.data()); + const auto write_fn = [&](std::uint64_t dst, const std::uint8_t* bytes, std::size_t n) { + if (n != 256) return false; + WriteEvent ev{}; + ev.frame_offset = std::size_t(static_cast(dst) - base_ptr); + std::memcpy(ev.bytes.data(), bytes, 256); + out.writes.push_back(ev); + std::memcpy(reinterpret_cast(static_cast(dst)), bytes, n); + return true; + }; + + out.written = mirror.write_back_batch(refs, ranges, staged.data(), write_fn); + out.counters = mirror.counters(); + out.copies.resize(kFilteredPages * kPage); + for (std::size_t p = 0; p < kFilteredPages; ++p) + std::memcpy(out.copies.data() + p * kPage, mirror.copy_bytes(kBase + p * kPage), kPage); + out.page_hashes.resize(kPages); + for (std::size_t p = 0; p < kPages; ++p) + EXPECT(mirror.range_sum(kBase + p * kPage, kPage, out.page_hashes[p])); + + // Spot-check key semantics: filtered refilter ran, partial out-of-range piece 0 skipped, remap/pending skipped. + EXPECT(out.frames[2 * kPage + 3 * 256 + 7] == 0xA5); + EXPECT(mirror.copy_bytes(kBase + 2 * kPage)[3 * 256 + 7] == 0x5A); + EXPECT(out.frames[24 * kPage + 0 * 256 + 5] != 0xDD && out.frames[24 * kPage + 2 * 256 + 5] == 0x72); + EXPECT(out.frames[77 * kPage + 2 * 256 + 1] != 0x19 && out.frames[78 * kPage + 2 * 256 + 1] != 0x29); + EXPECT(out.counters.conflicts == 17); // page 11 + page 25 + 15 pages in [30..75] with p%3==2 + return 0; + }; + + RunResult serial{}, par{}; + if (run_once(false, serial)) return 1; + if (run_once(true, par)) return 1; + + EXPECT(par.written == serial.written && par.written > 0); + EXPECT(par.counters.written_back_bytes == serial.counters.written_back_bytes); + EXPECT(par.counters.conflicts == serial.counters.conflicts); + EXPECT(par.counters.filtered == serial.counters.filtered); + EXPECT(par.writes == serial.writes); + EXPECT(par.frames == serial.frames); + EXPECT(par.copies == serial.copies); + EXPECT(par.page_hashes == serial.page_hashes); + + std::printf("parallel_write_back_batch_matches_serial: 80 pages (GPU-only, CPU-only, conflicts, filtered, aliased) " + "100%% identical (%llu bytes, %llu conflicts)\n", + static_cast(par.written), + static_cast(par.counters.conflicts)); + return 0; +} + +int parallel_fill_and_write_back_benchmark() { + constexpr std::size_t kFillPages = 400; + constexpr std::size_t kWbPages = 256; + constexpr int kIters = 8; + + Fixture f; + TitleMirror mirror(f.hooks()); + EXPECT(mirror.cover(kBase, kBase + kFillPages * kPage)); + + std::vector frames(kFillPages * kPage); + for (std::size_t i = 0; i < frames.size(); ++i) frames[i] = std::uint8_t((i * 131 + 7) & 0xff); + for (std::size_t p = 0; p < kFillPages; ++p) mirror.map(kBase + p * kPage, frames.data() + p * kPage, nullptr, 1); + EXPECT(mirror.flush(1)); + + const auto bench_upload = [&](bool parallel) -> double { + mirror.set_parallel(parallel); + double total_ms = 0.0; + for (int it = 0; it < kIters; ++it) { + for (std::size_t p = 0; p < kFillPages; ++p) { + for (std::size_t k = 0; k < 256; k += 4) frames[p * kPage + k * 256] ^= std::uint8_t(it + 1); + mirror.dirty(kBase + p * kPage); + } + const auto t0 = std::chrono::steady_clock::now(); + const std::size_t n = mirror.upload(); + total_ms += std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + if (n != kFillPages) return -1.0; + } + return total_ms / kIters; + }; + + const std::vector> wb_ranges = {{kBase, kBase + kWbPages * kPage}}; + const auto refs = mirror.homes_in_ranges(wb_ranges); + EXPECT(refs.size() == kWbPages); + std::vector staged(kWbPages * kPage); + std::memcpy(staged.data(), frames.data(), staged.size()); + const auto write_fn = [](std::uint64_t dst, const std::uint8_t* bytes, std::size_t n) { + std::memcpy(reinterpret_cast(static_cast(dst)), bytes, n); + return true; + }; + + const auto bench_wb = [&](bool parallel) -> double { + mirror.set_parallel(parallel); + double total_ms = 0.0; + for (int it = 0; it < kIters; ++it) { + for (std::size_t q = 0; q < 4; ++q) + staged[(q * 60 + 7) * kPage + 5 * 256 + 11] ^= std::uint8_t(it + 5); + const auto t0 = std::chrono::steady_clock::now(); + const std::uint64_t wb = mirror.write_back_batch(refs, wb_ranges, staged.data(), write_fn); + total_ms += std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + if (wb != 4 * 256) return -1.0; + } + return total_ms / kIters; + }; + + const double fill_serial_ms = bench_upload(false); + const double fill_par_ms = bench_upload(true); + std::memcpy(staged.data(), frames.data(), staged.size()); // sync staged after fill bench + const double wb_serial_ms = bench_wb(false); + const double wb_par_ms = bench_wb(true); + EXPECT(fill_serial_ms > 0.0 && fill_par_ms > 0.0 && wb_serial_ms > 0.0 && wb_par_ms > 0.0); + std::printf("bench (400-page upload, 25%% dirty): serial %.3f ms -> parallel %.3f ms (%.2fx)\n", + fill_serial_ms, fill_par_ms, fill_serial_ms / fill_par_ms); + std::printf("bench (256-page write_back_batch): serial %.3f ms -> parallel %.3f ms (%.2fx)\n", + wb_serial_ms, wb_par_ms, wb_serial_ms / wb_par_ms); + + // Measure lock-free Phase 1 prehash + locked Phase 2 write_back_prehashed vs old 1-page-at-a-time fallback. + auto readback_pool = TitleMirror::make_worker_pool(); + TitleMirror::PrehashedReadback prehashed; + double prehash_ms = 0.0, phase2_ms = 0.0; + for (int it = 0; it < kIters; ++it) { + for (std::size_t q = 0; q < 4; ++q) + staged[(q * 60 + 7) * kPage + 5 * 256 + 11] ^= std::uint8_t(it + 9); + const auto t0 = std::chrono::steady_clock::now(); + TitleMirror::prehash_readback_slice(refs.data(), refs.size(), wb_ranges, staged.data(), prehashed, + readback_pool.get()); + const auto t1 = std::chrono::steady_clock::now(); + const std::uint64_t wb = + mirror.write_back_prehashed(refs.data(), refs.size(), prehashed, staged.data(), nullptr, nullptr, write_fn); + const auto t2 = std::chrono::steady_clock::now(); + if (wb != 4 * 256) return 1; + prehash_ms += std::chrono::duration(t1 - t0).count(); + phase2_ms += std::chrono::duration(t2 - t1).count(); + } + std::printf("bench (256-page prehashed wb): phase1 (unlocked) %.3f ms, phase2 (locked) %.3f ms\n", + prehash_ms / kIters, phase2_ms / kIters); + return 0; +} + +int coalesced_write_back_runs_and_fallback() { + Fixture f; + TitleMirror mirror(f.hooks()); + EXPECT(mirror.cover(kBase, kBase + 4 * kPage)); + std::vector f0(kPage, 0x10), f1(kPage, 0x20); + mirror.map(kBase, f0.data(), nullptr, 1); + mirror.map(kBase + kPage, f1.data(), nullptr, 1); + EXPECT(mirror.flush(1)); + + // GPU modifies contiguous pieces [0..31] (32 pieces = 8 KiB) and [62..67] (spanning 64-bit word boundary), + // with CPU also modifying piece 64 -> splits [62..67] into [62..63] and [65..67] with 1 conflict! + std::uint8_t* h0 = mirror.home_bytes(kBase); + for (std::size_t k = 0; k < 32; ++k) h0[k * 256 + 3] = std::uint8_t(0xA0 + k); + for (std::size_t k = 62; k <= 67; ++k) h0[k * 256 + 5] = std::uint8_t(0xB0 + (k - 62)); + f0[64 * 256 + 7] = 0xCC; // CPU conflict on piece 64 + + struct Call { + std::size_t off; + std::size_t n; + }; + std::vector calls; + const auto base_ptr = reinterpret_cast(f0.data()); + const auto write_coalesced = [&](std::uint64_t dst, const std::uint8_t* bytes, std::size_t n) { + calls.push_back({std::size_t(static_cast(dst) - base_ptr), n}); + std::memcpy(reinterpret_cast(static_cast(dst)), bytes, n); + return true; + }; + const std::uint64_t written = mirror.write_back(kBase, kBase + kPage, write_coalesced); + EXPECT(written == (32 + 2 + 3) * 256); + EXPECT(calls.size() == 3); + EXPECT(calls[0].off == 0 && calls[0].n == 32 * 256); + EXPECT(calls[1].off == 62 * 256 && calls[1].n == 2 * 256); + EXPECT(calls[2].off == 65 * 256 && calls[2].n == 3 * 256); + EXPECT(f0[0 * 256 + 3] == 0xA0 && f0[31 * 256 + 3] == 0xBF); + EXPECT(f0[63 * 256 + 5] == 0xB1 && f0[64 * 256 + 7] == 0xCC && f0[65 * 256 + 5] == 0xB3); + EXPECT(mirror.counters().conflicts == 1); + + // Multi-piece write() failure falls back piece-by-piece so healthy pieces still commit (piece 10 fails). + std::uint8_t* h1 = mirror.home_bytes(kBase + kPage); + for (std::size_t k = 8; k <= 12; ++k) h1[k * 256 + 1] = std::uint8_t(0x70 + k); + const auto base1 = reinterpret_cast(f1.data()); + std::size_t multi_calls = 0, single_calls = 0; + const auto write_fallback = [&](std::uint64_t dst, const std::uint8_t* bytes, std::size_t n) { + const std::size_t off = std::size_t(static_cast(dst) - base1); + if (n > 256) { + ++multi_calls; + return false; // force piece-by-piece fallback + } + ++single_calls; + if (off == 10 * 256) return false; // single bad piece fails + std::memcpy(reinterpret_cast(static_cast(dst)), bytes, n); + return true; + }; + const std::uint64_t written1 = mirror.write_back(kBase + kPage, kBase + 2 * kPage, write_fallback); + EXPECT(written1 == 4 * 256 && multi_calls == 1 && single_calls == 5); + EXPECT(f1[8 * 256 + 1] == 0x78 && f1[9 * 256 + 1] == 0x79); + EXPECT(f1[10 * 256 + 1] == 0x20); // failed piece untouched + EXPECT(f1[11 * 256 + 1] == 0x7B && f1[12 * 256 + 1] == 0x7C); + std::printf("coalesced_write_back_runs_and_fallback: coalesced runs, conflict split, and fallback ok\n"); + return 0; +} + +int prehashed_readback_and_skip_masks() { + constexpr std::size_t kPages = 48; + Fixture f; + TitleMirror mirror(f.hooks()); + EXPECT(mirror.cover(kBase, kBase + (kPages + 4) * kPage)); + + std::vector frames(kPages * kPage); + for (std::size_t i = 0; i < frames.size(); ++i) + frames[i] = std::uint8_t((i * 29 + (i / kPage) * 7 + 3) & 0xff); + for (std::size_t p = 0; p < kPages; ++p) { + // Page 11 aliases physical frame 10. + const std::size_t fidx = (p == 11) ? 10 : p; + mirror.map(kBase + p * kPage, frames.data() + fidx * kPage, nullptr, 1); + } + EXPECT(mirror.flush(1)); + + const std::vector> ranges = { + {kBase + 0 * kPage, kBase + 20 * kPage}, + {kBase + 20 * kPage + 2 * 256, kBase + 20 * kPage + 6 * 256}, // partial pieces [2..6) + {kBase + 22 * kPage, kBase + kPages * kPage}, + }; + const auto refs = mirror.homes_in_ranges(ranges); + EXPECT(refs.size() == kPages - 1); // page 21 excluded + + // Snapshot GPU staged buffer before concurrent upload() modifies some pieces! + std::vector staged(refs.size() * kPage); + for (std::size_t i = 0; i < refs.size(); ++i) std::memcpy(staged.data() + i * kPage, refs[i].frame, kPage); + + // GPU wrote: + // - Page 0: piece 1 (GPU-only) and piece 2 (will be concurrently uploaded by CPU -> skipped via skip_mask!) + // - Page 5: piece 10 (will be skipped whole via skip_page!) + // - Page 10 & alias 11: piece 4 (GPU-only, shared frame -> written ONCE even though both aliases see it) + // - Page 20 (partial [2..6)): piece 1 (out of range -> ignored), piece 3 (in range -> written) + // - Pages 25..40: pieces 0..3 (contiguous GPU writes) + staged[0 * kPage + 1 * 256 + 4] = 0xE1; + staged[0 * kPage + 2 * 256 + 4] = 0xE2; + staged[5 * kPage + 10 * 256 + 4] = 0xE5; + staged[10 * kPage + 4 * 256 + 4] = 0xEA; + staged[11 * kPage + 4 * 256 + 4] = 0xEA; + staged[20 * kPage + 1 * 256 + 4] = 0xEE; // outside [2..6) + staged[20 * kPage + 3 * 256 + 4] = 0xEC; // inside [2..6) + for (std::size_t idx = 24; idx < 39; ++idx) { + for (std::size_t k = 0; k < 4; ++k) staged[idx * kPage + k * 256 + 9] ^= 0x55; + } + + // Simulate concurrent refresh_page_mirror() -> upload() modifying piece 2 of page 0 while readback was in flight: + // on_changed captures exact changed_pieces into skip_masks[0] WITHOUT invalidating piece 1! + frames[0 * kPage + 2 * 256 + 4] = 0x99; + std::vector> skip_masks(refs.size()); + std::vector skip_page(refs.size(), 0); + skip_page[5] = 1; // simulate external whole-frame invalidation of page 5 + EXPECT(mirror.dirty(kBase)); + std::size_t changed_callbacks = 0; + EXPECT(mirror.upload([&](std::uint8_t* frame, const std::array& mask) { + ++changed_callbacks; + for (std::size_t i = 0; i < refs.size(); ++i) { + if (refs[i].frame == frame) { + for (std::size_t w = 0; w < 4; ++w) skip_masks[i][w] |= mask[w]; + } + } + }) == 1); + EXPECT(changed_callbacks == 1); + EXPECT(skip_masks[0][0] == (std::uint64_t(1) << 2)); + + // Unchanged dirty upload must NOT invoke on_changed! + EXPECT(mirror.dirty(kBase + 2 * kPage)); + EXPECT(mirror.upload([&](std::uint8_t*, const std::array&) { ++changed_callbacks; }) == 1); + EXPECT(changed_callbacks == 1); + + // Phase 1 (lock-free parallel prehash) + Phase 2 (locked write_back_prehashed). + auto pool = TitleMirror::make_worker_pool(); + TitleMirror::PrehashedReadback prehashed; + TitleMirror::prehash_readback_slice(refs.data(), refs.size(), ranges, staged.data(), prehashed, pool.get()); + const auto write_fn = [](std::uint64_t dst, const std::uint8_t* bytes, std::size_t n) { + std::memcpy(reinterpret_cast(static_cast(dst)), bytes, n); + return true; + }; + const std::uint64_t written = mirror.write_back_prehashed(refs.data(), refs.size(), prehashed, staged.data(), + skip_masks.data(), skip_page.data(), write_fn); + // Page 0 piece 1 (1) + Page 10 piece 4 (1, alias 11 sees updated home.sums) + Page 20 piece 3 (1) + 15*4 (60) = 63 + EXPECT(written == 63 * 256); + EXPECT(frames[0 * kPage + 1 * 256 + 4] == 0xE1); // GPU piece 1 written back! + EXPECT(frames[0 * kPage + 2 * 256 + 4] == 0x99); // CPU-uploaded piece 2 NOT overwritten by stale staged 0xE2! + EXPECT(frames[5 * kPage + 10 * 256 + 4] != 0xE5); // skip_page[5] skipped whole page 5 + EXPECT(frames[10 * kPage + 4 * 256 + 4] == 0xEA); // shared frame written back once + EXPECT(frames[20 * kPage + 1 * 256 + 4] != 0xEE); // out of partial range + EXPECT(frames[20 * kPage + 3 * 256 + 4] == 0xEC); // inside partial range + + std::printf("prehashed_readback_and_skip_masks: lock-free Phase 1, piece skip_mask, skip_page, and aliases ok\n"); + return 0; +} + +int deferred_map_fill_and_on_changed() { + constexpr std::size_t kPages = 40; + Fixture f; + TitleMirror mirror(f.hooks()); + EXPECT(mirror.cover(kBase, kBase + (kPages + 8) * kPage)); + + std::vector frames(kPages * kPage); + for (std::size_t i = 0; i < frames.size(); ++i) frames[i] = std::uint8_t((i * 41 + 17) & 0xff); + + // Map kPages with defer_fill=true: zero immediate uploads, range_sum returns false until upload(). + for (std::size_t p = 0; p < kPages; ++p) + mirror.map(kBase + p * kPage, frames.data() + p * kPage, nullptr, TitleMirror::kUnstamped, true); + EXPECT(mirror.counters().uploads == 0); + std::uint64_t h = 0; + EXPECT(!mirror.range_sum(kBase, kPage, h)); + + // Unmap page 3 before upload(): its deferred home is erased and never wastes a fill! + mirror.map(kBase + 3 * kPage, nullptr, nullptr, TitleMirror::kUnstamped, true); + + // Alias page 4 before upload(): make_copy() fills home + filtered copy immediately and clears whole_fill/dirty. + const VkBuffer arena = fake(0xD4); + mirror.alias(kBase + 4 * kPage, kBase + 5 * kPage, arena, 0); + EXPECT(mirror.counters().uploads == 1); + EXPECT(mirror.range_sum(kBase + 4 * kPage, kPage, h)); + + // upload() fills the remaining kPages - 2 deferred homes in parallel and fires on_changed for each. + std::size_t notified = 0; + const std::size_t filled = mirror.upload([&](std::uint8_t*, const std::array& mask) { + if (mask[0] == ~0ull && mask[1] == ~0ull && mask[2] == ~0ull && mask[3] == ~0ull) ++notified; + }); + EXPECT(filled == kPages - 2 && notified == kPages - 2); + EXPECT(mirror.counters().uploads == kPages - 1); + for (std::size_t p = 0; p < kPages; ++p) { + if (p == 3) continue; + EXPECT(!std::memcmp(mirror.home_bytes(kBase + p * kPage), frames.data() + p * kPage, kPage)); + EXPECT(mirror.range_sum(kBase + p * kPage, kPage, h)); + } + + std::printf("deferred_map_fill_and_on_changed: parallel deferred fills, unmap elision, and alias handoff ok\n"); + return 0; +} + +// Verifies: +// 1. upload(on_changed, filter_batch) delivers exact AliasedPageJob snapshots with WorkerPool, handles per-page +// filter failure (zeroing + setting fresh for the next upload), and produces identical output to serial upload(). +// 2. Page-aware write-back writer: +// - scratch frames (frame != ref.page): bypasses pinning (begin_page reports scratch=true); +// - ordinary pages (frame == ref.page): calls begin_page ONCE per page with exact [first_off, first_off+span) +// covering multiple scattered coalesced runs, and calls ~PageGuard ONCE after all runs; +// - conflict-only pages: never calls begin_page; +// - whole_title_ok threshold lowered from 16 -> 2: 1 differing piece uses 1x256B hooks_.copy, >=2 uses 1x64KiB. +int batched_filter_and_page_aware_write_back() { + constexpr std::size_t kPages = 24; + const VkBuffer arena = fake(0xE1); + + // 1. Batched upload(on_changed, filter_batch) parity + failure recovery. + { + Fixture f; + TitleMirror mirror(f.hooks()); + EXPECT(mirror.cover(kBase, kBase + (kPages + 4) * kPage)); + mirror.alias(kBase, kBase + kPages * kPage, arena, 0); + + std::vector frames(kPages * kPage, 0x11); + for (std::size_t p = 0; p < kPages; ++p) + mirror.map(kBase + p * kPage, frames.data() + p * kPage, nullptr, 1); + EXPECT(mirror.flush(1)); + + // Mutate 3 pieces on each page (including 0xA5 sentinel bytes) and leave unchanged slots with 0xCC in copy. + for (std::size_t p = 0; p < kPages; ++p) { + std::uint8_t* copy = mirror.copy_bytes(kBase + p * kPage); + copy[10 * 256 + 3] = 0xCC; // untouched slot sentinel: must NOT be clobbered! + frames[p * kPage + 0 * 256 + 1] = 0xA5; + frames[p * kPage + 64 * 256 + 2] = std::uint8_t(0x30 + p); + frames[p * kPage + 255 * 256 + 4] = 0xA5; + EXPECT(mirror.dirty(kBase + p * kPage)); + } + + std::size_t batch_calls = 0; + std::size_t batch_jobs = 0; + bool saw_pool = false; + const auto run_batch = [&](TitleMirror::AliasedPageJob* jobs, std::size_t count, + TitleMirror::WorkerPool* pool, std::uint8_t* ok_out) { + ++batch_calls; + batch_jobs += count; + if (pool) saw_pool = true; + const auto work = [&](std::size_t b, std::size_t e, std::size_t) { + for (std::size_t i = b; i < e; ++i) { + if (jobs[i].va == kBase + 5 * kPage && batch_calls == 1) { + ok_out[i] = 0; // simulate filter failure on page 5 + continue; + } + // Write only changed 256B pieces from scratch into host buffer then copy into jobs[i].to. + std::vector buf(kPage); + for (std::size_t k = 0; k < kPage / 256; ++k) { + if (!jobs[i].fresh && !(jobs[i].mask[k >> 6] & (std::uint64_t(1) << (k & 63)))) continue; + for (std::size_t j = 0; j < 256; ++j) { + const std::uint8_t v = jobs[i].scratch[k * 256 + j]; + buf[k * 256 + j] = (v == 0xA5) ? 0x5A : v; + } + std::memcpy(jobs[i].to + k * 256, buf.data() + k * 256, 256); + } + ok_out[i] = 1; + } + }; + if (pool) pool->run(count, 2, work); + else work(0, count, 0); + }; + + std::size_t on_changed_calls = 0; + const std::size_t uploaded = + mirror.upload([&](std::uint8_t*, const std::array&) { ++on_changed_calls; }, run_batch); + EXPECT(uploaded == kPages && on_changed_calls == kPages && batch_calls == 1 && batch_jobs == kPages); + EXPECT(mirror.counters().upload_failures == 1); + // Page 5 failed -> zeroed and marked fresh for next upload. + EXPECT(mirror.copy_bytes(kBase + 5 * kPage)[0] == 0); + // Other pages filtered changed pieces accurately AND preserved untouched piece 10! + for (std::size_t p = 0; p < kPages; ++p) { + if (p == 5) continue; + const std::uint8_t* copy = mirror.copy_bytes(kBase + p * kPage); + EXPECT(copy[0 * 256 + 1] == 0x5A); + EXPECT(copy[64 * 256 + 2] == std::uint8_t(0x30 + p)); + EXPECT(copy[255 * 256 + 4] == 0x5A); + EXPECT(copy[10 * 256 + 3] == 0xCC); + } + // Re-uploading page 5 (even with unchanged bytes) MUST re-run filter with fresh=true! + bool page5_fresh = false; + EXPECT(mirror.dirty(kBase + 5 * kPage)); + EXPECT(mirror.upload([](std::uint8_t*, const std::array&) {}, + [&](TitleMirror::AliasedPageJob* jobs, std::size_t count, TitleMirror::WorkerPool*, + std::uint8_t* ok_out) { + if (count == 1 && jobs[0].va == kBase + 5 * kPage) page5_fresh = jobs[0].fresh; + for (std::size_t i = 0; i < count; ++i) { + std::memcpy(jobs[i].to, jobs[i].scratch, kPage); + ok_out[i] = 1; + } + }) == 1); + EXPECT(page5_fresh); + (void)saw_pool; + } + + // 2. Page-aware write-back writer: scratch bypass, ordinary-page single pin batch, conflict skip, whole_title_ok>=2. + { + Fixture f; + auto h = f.hooks(); + std::size_t copy_64k = 0, copy_256 = 0; + h.copy = [&](std::uint8_t* to, const std::uint8_t* from, std::size_t bytes) { + if (bytes == kPage) ++copy_64k; + else if (bytes == 256) ++copy_256; + std::memcpy(to, from, bytes); + return true; + }; + + TitleMirror mirror(std::move(h)); + // Allocate 4 aligned 64 KiB pages; map page 0 as "ordinary" (va == frame address!), pages 1..3 as "scratch" + // (va != frame address). + std::vector backing(5 * kPage, 0x20); + const std::uintptr_t raw = reinterpret_cast(backing.data()); + const std::uintptr_t aligned = (raw + kPage - 1) & ~(kPage - 1); + auto* const ord_frame = reinterpret_cast(aligned); + auto* const scr1_frame = ord_frame + kPage; + auto* const scr2_frame = ord_frame + 2 * kPage; + auto* const scr3_frame = ord_frame + 3 * kPage; + + const std::uint64_t ord_va = static_cast(aligned); + // Ensure ord_va and kBase are both covered (ord_va is a real host pointer; kBase is a high title VA). + EXPECT(mirror.cover(ord_va, ord_va + kPage)); + EXPECT(mirror.cover(kBase, kBase + 4 * kPage)); + + mirror.map(ord_va, ord_frame, nullptr, 1); // frame == page_va (ordinary page) + mirror.map(kBase + 0 * kPage, scr1_frame, nullptr, 1); // frame != page_va (xmem scratch, 1 piece diff) + mirror.map(kBase + 1 * kPage, scr2_frame, nullptr, 1); // frame != page_va (xmem scratch, 2 pieces diff) + mirror.map(kBase + 2 * kPage, scr3_frame, nullptr, 1); // frame != page_va (conflict-only page) + EXPECT(mirror.flush(1)); + + const std::vector> ranges = { + {ord_va, ord_va + kPage}, + {kBase, kBase + 3 * kPage}, + }; + const auto refs = mirror.homes_in_ranges(ranges); + EXPECT(refs.size() == 4); + + std::vector staged(refs.size() * kPage); + for (std::size_t i = 0; i < refs.size(); ++i) std::memcpy(staged.data() + i * kPage, refs[i].frame, kPage); + + // Locate each ref index (sorted by page address). + auto idx_of = [&](std::uint64_t va) -> std::size_t { + for (std::size_t i = 0; i < refs.size(); ++i) + if (refs[i].page == va) return i; + return ~std::size_t(0); + }; + const std::size_t i_ord = idx_of(ord_va); + const std::size_t i_scr1 = idx_of(kBase + 0 * kPage); + const std::size_t i_scr2 = idx_of(kBase + 1 * kPage); + const std::size_t i_scr3 = idx_of(kBase + 2 * kPage); + EXPECT(i_ord < 4 && i_scr1 < 4 && i_scr2 < 4 && i_scr3 < 4); + + // Ordinary page: 3 scattered runs (pieces 2, 10..11, 200) -> 1 begin_page([2*256, 201*256)), 3 writes, 1 end! + staged[i_ord * kPage + 2 * 256 + 1] = 0xA1; + staged[i_ord * kPage + 10 * 256 + 1] = 0xA2; + staged[i_ord * kPage + 11 * 256 + 1] = 0xA3; + staged[i_ord * kPage + 200 * 256 + 1] = 0xA4; + // Scratch page 1: 1 differing piece (piece 5) -> 1x256B hooks_.copy (NOT 64 KiB!). + staged[i_scr1 * kPage + 5 * 256 + 1] = 0xB1; + // Scratch page 2: 2 differing pieces (pieces 3, 70) -> whole_title_ok threshold=2 -> 1x64 KiB hooks_.copy! + staged[i_scr2 * kPage + 3 * 256 + 1] = 0xC1; + staged[i_scr2 * kPage + 70 * 256 + 1] = 0xC2; + // Scratch page 3: 1 differing piece, ALSO modified by CPU -> conflict, write_count==0 -> 0 begin_page calls! + staged[i_scr3 * kPage + 4 * 256 + 1] = 0xD1; + scr3_frame[4 * 256 + 2] = 0xD2; + + TitleMirror::PrehashedReadback prehashed; + TitleMirror::prehash_readback_slice(refs.data(), refs.size(), ranges, staged.data(), prehashed, nullptr); + + copy_64k = copy_256 = 0; + struct PageEvent { + std::uint64_t page_va = 0; + bool scratch = false; + std::size_t first_off = 0; + std::size_t span_bytes = 0; + std::size_t writes = 0; + bool ended = false; + }; + std::vector events; + struct TestPageWriter { + std::vector* events = nullptr; + struct Guard { + std::vector* events = nullptr; + std::size_t idx = ~std::size_t(0); + Guard(std::vector* ev, std::size_t i) : events(ev), idx(i) {} + Guard(const Guard&) = delete; + Guard& operator=(const Guard&) = delete; + Guard(Guard&& o) noexcept : events(o.events), idx(std::exchange(o.idx, ~std::size_t(0))) {} + ~Guard() { + if (events && idx < events->size()) (*events)[idx].ended = true; + } + }; + Guard begin_page(std::uint64_t page_va, std::uint8_t* frame, std::size_t first_off, + std::size_t span_bytes) const { + const bool scratch = reinterpret_cast(frame) != static_cast(page_va); + const std::size_t idx = events->size(); + events->push_back({page_va, scratch, first_off, span_bytes, 0, false}); + return Guard(events, idx); + } + bool write(const Guard& g, std::uint64_t dst, const std::uint8_t* bytes, std::size_t n) const { + ++(*events)[g.idx].writes; + std::memcpy(reinterpret_cast(static_cast(dst)), bytes, n); + return true; + } + } writer{&events}; + + const std::uint64_t wb = mirror.write_back_prehashed(refs.data(), refs.size(), prehashed, staged.data(), + nullptr, nullptr, writer); + EXPECT(wb == (4 + 1 + 2) * 256); + EXPECT(mirror.counters().conflicts == 1); + // 3 pages written (conflict-only scr3 skipped begin_page!). + EXPECT(events.size() == 3); + bool saw_ord = false, saw_scr1 = false, saw_scr2 = false; + for (const PageEvent& ev : events) { + EXPECT(ev.ended); + if (ev.page_va == ord_va) { + saw_ord = true; + EXPECT(!ev.scratch); + EXPECT(ev.first_off == 2 * 256 && ev.span_bytes == (201 - 2) * 256); + EXPECT(ev.writes == 3); // 3 coalesced runs under 1 begin_page/end_page! + } else if (ev.page_va == kBase + 0 * kPage) { + saw_scr1 = true; + EXPECT(ev.scratch && ev.writes == 1); + } else if (ev.page_va == kBase + 1 * kPage) { + saw_scr2 = true; + EXPECT(ev.scratch && ev.writes == 2); + } + } + EXPECT(saw_ord && saw_scr1 && saw_scr2); + // whole_title_ok threshold = 2: ord(4 pieces) + scr2(2 pieces) = 2x64KiB copies; scr1(1) + scr3(1) = 2x256B! + EXPECT(copy_64k == 2 && copy_256 == 2); + EXPECT(ord_frame[2 * 256 + 1] == 0xA1 && ord_frame[11 * 256 + 1] == 0xA3 && ord_frame[200 * 256 + 1] == 0xA4); + EXPECT(scr1_frame[5 * 256 + 1] == 0xB1 && scr2_frame[70 * 256 + 1] == 0xC2 && scr3_frame[4 * 256 + 2] == 0xD2); + } + + std::printf("batched_filter_and_page_aware_write_back: upload filter_batch, scratch bypass, ordinary batched pin, " + "whole_title_ok>=2 ok\n"); + return 0; +} + +int multi_chunk_direct_table_boundaries() { + Fixture f; + TitleMirror mirror(f.hooks()); + constexpr std::uint64_t kChunk = TitleMirror::kChunk; + // Cover chunk 0 at kBase, skip chunk 1 (uncovered gap), cover chunk 2 at kBase + 2 * kChunk. + EXPECT(mirror.cover(kBase, kBase + kChunk)); + EXPECT(mirror.cover(kBase + 2 * kChunk, kBase + 3 * kChunk)); + + std::vector f0(kPage, 0x11), f1(kPage, 0x22), f2(kPage, 0x33), f3(kPage, 0x44); + const std::uint64_t va_c0_first = kBase; + const std::uint64_t va_c0_last = kBase + kChunk - kPage; // page slot 32767 + const std::uint64_t va_c2_first = kBase + 2 * kChunk; + const std::uint64_t va_c2_last = kBase + 3 * kChunk - kPage; + + mirror.map(va_c0_first, f0.data(), nullptr, 1); + mirror.map(va_c0_last, f1.data(), nullptr, 1); + mirror.map(va_c2_first, f2.data(), nullptr, 1); + mirror.map(va_c2_last, f3.data(), nullptr, 1); + EXPECT(mirror.counters().pages == 4); + EXPECT(mirror.has_pending(va_c0_last) && !mirror.has_pending(va_c0_first + kPage)); + EXPECT(mirror.flush(1)); + EXPECT(!mirror.has_pending_binds() && !mirror.has_pending(va_c0_last)); + + EXPECT(mirror.frame_at(va_c0_first) == f0.data() && mirror.frame_at(va_c0_last) == f1.data()); + EXPECT(mirror.frame_at(va_c2_first) == f2.data() && mirror.frame_at(va_c2_last) == f3.data()); + EXPECT(!mirror.mirrored(kBase + kChunk) && mirror.frame_at(kBase + kChunk) == nullptr); + + // homes_in_ranges across the uncovered chunk gap must return all 4 boundary pages in sorted order. + const auto refs = mirror.homes_in_ranges({{va_c0_first, va_c2_last + kPage}}); + EXPECT(refs.size() == 4); + EXPECT(refs[0].page == va_c0_first && refs[1].page == va_c0_last && refs[2].page == va_c2_first && + refs[3].page == va_c2_last); + + // range_sum across chunk boundary (va_c0_last -> va_c0_last + kPage, then uncovered fails). + std::uint64_t h = 0; + EXPECT(mirror.range_sum(va_c0_last, kPage, h)); + EXPECT(!mirror.range_sum(va_c0_last, 2 * kPage, h)); + + // Unmap and verify pages_count_ returns to 0. + mirror.map(va_c0_first, nullptr, nullptr, 2); + mirror.map(va_c0_last, nullptr, nullptr, 2); + mirror.map(va_c2_first, nullptr, nullptr, 2); + mirror.map(va_c2_last, nullptr, nullptr, 2); + EXPECT(mirror.counters().pages == 0 && !mirror.mirrored(va_c0_last) && !mirror.mirrored(va_c2_last)); + std::printf("multi_chunk_direct_table_boundaries: 32768-slot per-chunk direct page table ok\n"); + return 0; +} + +int upload_breakdown_and_unit_sums_slab() { + Fixture f; + TitleMirror mirror(f.hooks()); + EXPECT(mirror.cover(kBase, kBase + 8 * kPage)); + const VkBuffer arena = fake(0xE5); + mirror.alias(kBase, kBase + 2 * kPage, arena, 0); + + std::vector f0(kPage, 0x11), f1(kPage, 0x22), f2(kPage, 0x33), f3(kPage, 0x44); + mirror.map(kBase + 0 * kPage, f0.data(), nullptr, 1); // aliased (filled immediately) + mirror.map(kBase + 2 * kPage, f1.data(), nullptr, 1, /*defer_fill=*/true); // deferred whole fill + mirror.map(kBase + 3 * kPage, f2.data(), nullptr, 1, /*defer_fill=*/true); // deferred whole fill + f0[63 * 256 + 5] = 0xA5; // cross-strip boundary piece 63 (last piece of strip 0) + f0[64 * 256 + 5] = 0x77; // first piece of strip 1 + EXPECT(mirror.dirty(kBase + 0 * kPage)); + EXPECT(mirror.upload() == 3); + EXPECT(mirror.last_whole_pages() == 2 && mirror.last_inc_pages() == 1 && mirror.last_aliased_pages() == 1); + EXPECT(mirror.copy_bytes(kBase)[63 * 256 + 5] == 0x5A && mirror.copy_bytes(kBase)[64 * 256 + 5] == 0x77); + EXPECT(mirror.flush(1)); + + // Empty upload resets breakdown counts to 0. + EXPECT(mirror.upload() == 0); + EXPECT(mirror.last_whole_pages() == 0 && mirror.last_inc_pages() == 0 && mirror.last_aliased_pages() == 0); + + // Slot recycling over contiguous Unit::sums slab: unmap + retire frees slot, next map reuses it cleanly. + std::uint64_t h_old = 0; + EXPECT(mirror.range_sum(kBase + 2 * kPage, kPage, h_old)); + mirror.map(kBase + 2 * kPage, nullptr, nullptr, 5); + EXPECT(mirror.flush(2)); + mirror.retire(5); + EXPECT(mirror.counters().homes_freed == 1); + mirror.map(kBase + 2 * kPage, f3.data(), nullptr, 6); + EXPECT(mirror.flush(3)); + std::uint64_t h_new = 0; + EXPECT(mirror.range_sum(kBase + 2 * kPage, kPage, h_new) && h_new != h_old); + EXPECT(!std::memcmp(mirror.home_bytes(kBase + 2 * kPage), f3.data(), kPage)); + // Verify incremental diff on reused slot detects single-byte changes across all 4 x 16 KiB strips. + for (std::size_t s = 0; s < 4; ++s) f3[s * 16384 + 256] = std::uint8_t(0xC0 + s); + EXPECT(mirror.dirty(kBase + 2 * kPage) && mirror.upload() == 1); + EXPECT(mirror.last_upload_bytes() == 4 * 256); + EXPECT(!std::memcmp(mirror.home_bytes(kBase + 2 * kPage), f3.data(), kPage)); + std::printf("upload_breakdown_and_unit_sums_slab: breakdown counts, 16 KiB strips, and Unit::sums slab reuse ok\n"); + return 0; +} + +int fused_copy_and_sum_hook_and_fallback() { + EXPECT(TitleMirror::kMaxWorkers == 8); + Fixture f_fused, f_ref; + auto h_fused = f_fused.hooks(); + auto h_ref = f_ref.hooks(); + + constexpr std::size_t kStrip = TitleMirror::kStripBytes; + constexpr std::size_t kStripsPerPage = kPage / kStrip; + std::size_t fused_calls = 0, fallback_piece_calls = 0; + std::size_t fail_strip_offset = ~std::size_t(0); + std::size_t fail_piece_offset = ~std::size_t(0); + const std::uint8_t* tracked_frame = nullptr; + + h_fused.copy_and_sum = [&](std::uint8_t* to, const std::uint8_t* from, std::size_t pieces, std::uint64_t* sums) { + ++fused_calls; + if (tracked_frame && std::size_t(from - tracked_frame) == fail_strip_offset) return false; + leonida::shadow_keep::copy_and_sum_256(to, from, pieces, sums); + return true; + }; + h_fused.copy = [&](std::uint8_t* to, const std::uint8_t* from, std::size_t bytes) { + ++fallback_piece_calls; + if (tracked_frame && std::size_t(from - tracked_frame) == fail_piece_offset) return false; + std::memcpy(to, from, bytes); + return true; + }; + h_ref.copy = [](std::uint8_t* to, const std::uint8_t* from, std::size_t bytes) { + std::memcpy(to, from, bytes); + return true; + }; + + TitleMirror m_fused(std::move(h_fused)); + TitleMirror m_ref(std::move(h_ref)); + EXPECT(m_fused.cover(kBase, kBase + 4 * kPage)); + EXPECT(m_ref.cover(kBase, kBase + 4 * kPage)); + + std::vector frame(kPage); + for (std::size_t i = 0; i < frame.size(); ++i) frame[i] = std::uint8_t((i * 73 + 19) & 0xff); + tracked_frame = frame.data(); + + // Whole fill via fused copy_and_sum: 4 strip calls, 0 fallback copy calls, exact range_sum parity with ref. + m_fused.map(kBase, frame.data(), nullptr, 1); + m_ref.map(kBase, frame.data(), nullptr, 1); + EXPECT(fused_calls == kStripsPerPage && fallback_piece_calls == 0); + EXPECT(std::memcmp(m_fused.home_bytes(kBase), m_ref.home_bytes(kBase), kPage) == 0); + std::uint64_t hf = 0, hr = 0; + EXPECT(m_fused.range_sum(kBase, kPage, hf) && m_ref.range_sum(kBase, kPage, hr) && hf == hr); + + // Incremental dirty upload across strip boundaries: exact changed_pieces parity. + frame[3 * 256 + 9] ^= 0x5A; + frame[64 * 256 + 17] ^= 0xA5; + frame[255 * 256 + 200] ^= 0x3C; + std::array mask_f{}, mask_r{}; + EXPECT(m_fused.dirty(kBase) && + m_fused.upload([&](std::uint8_t*, const std::array& m) { mask_f = m; }) == 1); + EXPECT(m_ref.dirty(kBase) && + m_ref.upload([&](std::uint8_t*, const std::array& m) { mask_r = m; }) == 1); + EXPECT(fused_calls == 2 * kStripsPerPage && fallback_piece_calls == 0); + EXPECT(mask_f == mask_r); + EXPECT(m_fused.last_upload_bytes() == 3 * 256 && m_ref.last_upload_bytes() == 3 * 256); + EXPECT(std::memcmp(m_fused.home_bytes(kBase), m_ref.home_bytes(kBase), kPage) == 0); + + // Fallback path: strip 1 fails in copy_and_sum -> falls back to 64 per-piece hooks_.copy calls, zeroes only piece 70. + fail_strip_offset = kStrip; + fail_piece_offset = 70 * 256; + frame[65 * 256 + 4] = 0xEE; + frame[70 * 256 + 4] = 0xDD; + EXPECT(m_fused.dirty(kBase) && m_fused.upload() == 1); + EXPECT(fused_calls == 3 * kStripsPerPage && fallback_piece_calls == TitleMirror::kStripPieces); + EXPECT(m_fused.counters().upload_failures == 1); + EXPECT(m_fused.home_bytes(kBase)[65 * 256 + 4] == 0xEE); + EXPECT(m_fused.home_bytes(kBase)[70 * 256 + 4] == 0); + + std::printf("fused_copy_and_sum_hook_and_fallback: AVX2 fused strip hook, fallback, and kMaxWorkers==8 ok\n"); + return 0; +} + +} // namespace + +int main() { + if (aliases()) return 1; + if (filters()) return 1; + if (pending_guard_and_frame_dest()) return 1; + if (refilter_scaling()) return 1; + if (fill_copy_and_fallback()) return 1; + if (batched_write_back()) return 1; + if (filter_pieces_mask_and_scratch()) return 1; + if (coalesced_fill_and_write_back_soundness()) return 1; + if (make_copy_aba_staleness()) return 1; + if (reentrant_rehash_in_alias_and_handoff()) return 1; + if (lock_free_pending_fast_paths()) return 1; + if (range_sum_piece_hashing()) return 1; + if (unstamped_freed_homes_wait_for_flush()) return 1; + if (parallel_upload_matches_serial()) return 1; + if (parallel_write_back_batch_matches_serial()) return 1; + if (parallel_fill_and_write_back_benchmark()) return 1; + if (coalesced_write_back_runs_and_fallback()) return 1; + if (prehashed_readback_and_skip_masks()) return 1; + if (deferred_map_fill_and_on_changed()) return 1; + if (batched_filter_and_page_aware_write_back()) return 1; + if (multi_chunk_direct_table_boundaries()) return 1; + if (upload_breakdown_and_unit_sums_slab()) return 1; + if (fused_copy_and_sum_hook_and_fallback()) return 1; + std::printf("title_mirror_hooks_test: ok\n"); + return 0; +} diff --git a/runtime/test/title_mirror_hot_cold_test.cpp b/runtime/test/title_mirror_hot_cold_test.cpp new file mode 100644 index 0000000000..1560c2d1bd --- /dev/null +++ b/runtime/test/title_mirror_hot_cold_test.cpp @@ -0,0 +1,693 @@ +// HotColdTracking (src/title_mirror_hot_cold.h) on real guards: the geometry watch's cells over VirtualAlloc'd pages, +// and a vectored handler that does what the D3D12 layer's does first (geometry_writes::notify on the fault). A page +// written at every interval stops faulting, a rarely written one faults once an interval, and the copy the collects +// name equals the memory after every collect. +#include + +#include "../src/title_mirror_hot_cold.h" +#include "../src/title_texture_watch.h" + +#include +#include +#include +#include +#include + +namespace { + +constexpr std::size_t kPage = 0x10000, kPages = 16; +std::atomic g_lo{0}, g_hi{0}; +std::atomic g_faults[kPages]; + +LONG CALLBACK on_fault(EXCEPTION_POINTERS* info) { + const EXCEPTION_RECORD* r = info ? info->ExceptionRecord : nullptr; + if (!r || r->ExceptionCode != EXCEPTION_ACCESS_VIOLATION || r->NumberParameters < 2 || r->ExceptionInformation[0] != 1) + return EXCEPTION_CONTINUE_SEARCH; + const auto address = static_cast(r->ExceptionInformation[1]); + if (address < g_lo.load() || address >= g_hi.load()) return EXCEPTION_CONTINUE_SEARCH; + g_faults[(address - g_lo.load()) / kPage].fetch_add(1); + bool restored = false; + leonida::geometry_writes::notify(address, address + 1, leonida::geometry_writes::Event::fault, &restored); + return restored ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_CONTINUE_SEARCH; +} + +int failures = 0; +#define EXPECT(c) \ + do { \ + if (!(c)) { \ + std::printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #c); \ + ++failures; \ + } \ + } while (0) + +// The title texture refresh's view of the same cells (as the D3D12 layer's TitleTextureCells): a second copy of a page +// the mirror tracks, which must hear of every write the mirror's tracking lets through unguarded. +struct TextureCells { + using Cell = leonida::geometry_writes::Cell; + leonida::geometry_writes::WriteQueue queue; + TextureCells() { leonida::geometry_writes::subscribe_writes(queue); } + ~TextureCells() { leonida::geometry_writes::unsubscribe_writes(queue); } + Cell* acquire(std::uintptr_t tile) { return leonida::geometry_writes::acquire(tile); } + void release(std::uintptr_t tile) { leonida::geometry_writes::release(tile); } + int arm(std::uintptr_t tile, Cell& cell) { return leonida::geometry_writes::arm(tile, cell) ? 1 : -1; } + void aliases(std::uintptr_t, std::vector&) {} + void take_written(std::vector& out, bool& overflow) { + leonida::geometry_writes::take_written(queue, out, overflow); + } + void hot_tiles(std::vector& out) { leonida::geometry_writes::hot_tiles(out); } + bool enabled() const { return true; } +}; + +} // namespace + +int main() { + auto* memory = static_cast(VirtualAlloc(nullptr, kPages * kPage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + EXPECT(memory); + if (!memory) return 1; + std::vector copy(kPages * kPage); + const auto base = reinterpret_cast(memory); + g_lo.store(base); + g_hi.store(base + kPages * kPage); + EXPECT(AddVectoredExceptionHandler(1, &on_fault) != nullptr); + std::mt19937 random(7); + { + leonida::HotColdTracking tracking; + for (std::size_t p = 0; p < kPages; ++p) tracking.watch(base + p * kPage); + // A texture over page 0 (a video plane the title writes every interval) and one over page 2, watched by the + // texture refresh's watch over the same cells. + TextureCells cells; + leonida::TitleTextureWatch textures(cells); + textures.track(1, base, kPage); + textures.track(2, base + 2 * kPage, kPage); + unsigned plane_missed = 0; + std::vector out; + std::uint64_t hot_faults_late = 0; + for (unsigned interval = 0; interval < 200; ++interval) { + const std::uint64_t before = g_faults[0].load(); + memory[interval % kPage] = std::uint8_t(interval); // page 0: every interval + if (interval > 20 && (interval % 32) != 1) hot_faults_late += g_faults[0].load() - before; + if (interval % 10 == 0) memory[kPage + interval] = std::uint8_t(interval); // page 1: every 10th + if (random() % 4 == 0) memory[(2 + random() % (kPages - 2)) * kPage + random() % kPage] = std::uint8_t(random()); + tracking.collect(out); + for (const std::uint64_t page : out) + std::memcpy(copy.data() + (page - base), reinterpret_cast(page), kPage); + EXPECT(!std::memcmp(copy.data(), memory, copy.size())); + // The texture refresh's pass after the mirror's: the plane, written this interval, must be named. + bool plane = false; + textures.collect([&](std::uint64_t key) { + plane |= key == 1; + textures.examine(key); + }); + if (interval > 0 && !plane) { + ++plane_missed; + if (plane_missed <= 8) + std::printf("plane not named at interval %u (hot %d)\n", interval, int(tracking.stats().hot)); + } + } + EXPECT(tracking.stats().hot >= 1); // the plane's page turned hot in the mirror's tracking + EXPECT(plane_missed == 0); // and the texture watch still heard of every write to it + EXPECT(hot_faults_late == 0); + EXPECT(g_faults[1].load() <= 21); + const auto& s = tracking.stats(); + std::printf("hot/cold on cells: %zu hot, %zu cold; %llu faults on the hot page, %llu on the 10th-interval " + "page; %llu hot and %llu cold copies, %llu promotions, %llu demotions\n", + s.hot, s.cold, static_cast(g_faults[0].load()), + static_cast(g_faults[1].load()), static_cast(s.hot_copies), + static_cast(s.cold_copies), static_cast(s.promotions), + static_cast(s.demotions)); + for (std::size_t p = 0; p < kPages; ++p) tracking.unwatch(base + p * kPage); + } + memory[5] = 1; // every guard is gone: no fault left + + // Verify HotColdTracking::unwatch() single-lock behavior: + // 1. Cold armed page with sole owner (refs==1): unwatch() reopens once without toggling set_hot(true/false) + // (hot_generation unchanged) and without pushing a bogus tile entry to WriteQueue subscribers. + // 2. Hot page with sole owner (refs==1): unwatch() clears hot state without pushing a bogus WriteQueue entry. + // 3. Hot page with a second owner (refs==2): unwatch() drops our hot count and notifies WriteQueue so the + // remaining owner observes writes made while hot. + { + leonida::geometry_writes::WriteQueue observer; + leonida::geometry_writes::subscribe_writes(observer); + std::vector written_tiles; + bool overflow = false; + std::vector out; + + leonida::HotColdTracking tracking; + const std::uintptr_t p_cold = base + 0 * kPage; + const std::uintptr_t p_hot_sole = base + 1 * kPage; + const std::uintptr_t p_hot_shared = base + 2 * kPage; + tracking.watch(p_cold); + tracking.watch(p_hot_sole); + tracking.watch(p_hot_shared); + + // Acquire a second owner on p_hot_shared. + TextureCells extra_owner; + extra_owner.acquire(p_hot_shared); + + // Arm p_cold (never written after initial collect) and promote p_hot_sole + p_hot_shared to hot. + for (unsigned i = 0; i < 12; ++i) { + memory[1 * kPage + i] = std::uint8_t(i + 1); + memory[2 * kPage + i] = std::uint8_t(i + 2); + tracking.collect(out); + } + EXPECT(!tracking.hot(p_cold) && tracking.unwritten(p_cold)); + EXPECT(tracking.hot(p_hot_sole) && tracking.hot(p_hot_shared)); + + // Drain observer queue before testing unwatch(). + leonida::geometry_writes::take_written(observer, written_tiles, overflow); + const std::uint64_t hot_gen_before = + leonida::geometry_writes::state().hot_generation.load(std::memory_order_acquire); + + // 1. Cold armed unwatch (sole owner): zero hot_generation bump, zero bogus WriteQueue push, page writable! + tracking.unwatch(p_cold); + const std::uint64_t hot_gen_after_cold = + leonida::geometry_writes::state().hot_generation.load(std::memory_order_acquire); + leonida::geometry_writes::take_written(observer, written_tiles, overflow); + EXPECT(hot_gen_after_cold == hot_gen_before); + EXPECT(!overflow && written_tiles.empty()); + const std::uint64_t faults_before_write = g_faults[0].load(); + memory[0 * kPage + 7] = 0x5A; // must NOT fault: guard was reopened on release + EXPECT(g_faults[0].load() == faults_before_write); + + // 2. Hot unwatch (sole owner): hot_generation bumps once (erased from s.hot), zero bogus WriteQueue push! + tracking.unwatch(p_hot_sole); + leonida::geometry_writes::take_written(observer, written_tiles, overflow); + EXPECT(!overflow && written_tiles.empty()); + EXPECT(!tracking.hot(p_hot_sole)); + + // 3. Hot unwatch (shared owner): remaining owner still holds ref, so WriteQueue DOES receive notification! + tracking.unwatch(p_hot_shared); + leonida::geometry_writes::take_written(observer, written_tiles, overflow); + EXPECT(!overflow && written_tiles.size() == 1 && written_tiles[0] == p_hot_shared); + extra_owner.release(p_hot_shared); + + // 4. Verify notify(Event::fault) returns opened=true both when reopen() restores begin's page (fast path, + // skipping 2nd VirtualQuery) and when the page is already writable (concurrent fault fallback VirtualQuery). + tracking.watch(p_cold); + tracking.collect(out); // arms p_cold + EXPECT(tracking.unwritten(p_cold)); + bool restored = false; + EXPECT(leonida::geometry_writes::notify(p_cold + 123, p_cold + 124, + leonida::geometry_writes::Event::fault, &restored)); + EXPECT(restored); + restored = false; + EXPECT(leonida::geometry_writes::notify(p_cold + 123, p_cold + 124, + leonida::geometry_writes::Event::fault, &restored)); + EXPECT(!restored); + tracking.unwatch(p_cold); + + leonida::geometry_writes::unsubscribe_writes(observer); + std::printf("unwatch single-lock & fault reopen fast path: ok\n"); + } + + // Verify watch_batch / unwatch_batch, gap-bridging with pinned-tile guardrail, mid-batch unrelated map change, + // and reopen() fast path + unexpected-protection fallback. + { + std::vector out; + leonida::HotColdTracking tracking; + std::vector pages(kPages); + for (std::size_t p = 0; p < kPages; ++p) pages[p] = base + p * kPage; + tracking.watch_batch(pages.data(), pages.size()); + tracking.collect(out); // arms all 16 tiles and populates known_protect + armed_map_gen + EXPECT(out.size() == kPages); + for (std::size_t p = 0; p < kPages; ++p) EXPECT(tracking.unwritten(pages[p])); + + // Fault tiles 0, 2, 5 (gaps at 1 and 3..4 are already-armed cold tiles -> eligible for gap-bridging!). + memory[0 * kPage + 1] = 0x11; + memory[2 * kPage + 1] = 0x22; + memory[5 * kPage + 1] = 0x55; + // Bump title_memory_map on an UNRELATED VA range to exercise range-scoped changes_since(). + leonida::title_memory_map::changed(base + 0x10000000, base + 0x10010000); + tracking.collect(out); + EXPECT(out.size() == 3 && out[0] == pages[0] && out[1] == pages[2] && out[2] == pages[5]); + for (std::size_t p = 0; p < 6; ++p) EXPECT(tracking.unwritten(pages[p])); + + // Pinned-tile guardrail: pin tile 1 via kernel_writes::hold() (opener opens tile 1 writable), fault tiles 0 + // and 2, then collect() MUST NOT bridge over pinned tile 1 and must leave tile 1 writable! + leonida::kernel_writes::set_opener([](std::uintptr_t b, std::uintptr_t e) { + leonida::geometry_writes::notify(b, e, leonida::geometry_writes::Event::open); + }); + const std::uint64_t pin = leonida::kernel_writes::hold(memory + 1 * kPage, kPage); + EXPECT(pin != 0); + memory[0 * kPage + 2] = 0x33; + memory[2 * kPage + 2] = 0x44; + tracking.collect(out); + // Tile 0 and tile 2 re-armed; pinned tile 1 stayed writable (writing it must NOT fault!). + EXPECT(tracking.unwritten(pages[0]) && tracking.unwritten(pages[2])); + const std::uint64_t f1_before = g_faults[1].load(); + memory[1 * kPage + 2] = 0x77; + EXPECT(g_faults[1].load() == f1_before); + leonida::kernel_writes::release(pin); + leonida::kernel_writes::set_opener(nullptr); + + // Unwatch all pages in one batch and verify zero faults on subsequent writes. + tracking.unwatch_batch(pages.data(), pages.size()); + const std::uint64_t f0_before = g_faults[0].load(); + memory[0 * kPage + 3] = 0x99; + EXPECT(g_faults[0].load() == f0_before); + std::printf("watch_batch/unwatch_batch, gap-bridging pin guardrail, reopen fast path: ok\n"); + } + + // Verify WS1 Round 9 fast paths: + // 1. Zero-syscall all_armed skip when another owner already armed all 16 sub-pages. + // 2. VirtualQuery region cache for MEM_RESERVE and PAGE_READONLY (explicit cached_state). + // 3. Range-scoped reopen() fast path across unrelated map changes + unexpected-protection rollback. + // 4. kMaxBridgeGap = 32 bridging (>8 tile gap bridged in 1 VirtualProtect) + set_hot_batch/disarm_batch. + // 5. WC tile detection (wc_tiles + is_wc_page) when host preserves PAGE_WRITECOMBINE. + { + std::vector out; + + // 1. Zero-syscall all_armed skip. + { + TextureCells other; + leonida::geometry_writes::Cell* cell = other.acquire(base); + EXPECT(other.arm(base, *cell) == 1); // arms all 16 sub-pages + leonida::HotColdTracking tracking; + tracking.watch(base); + tracking.collect(out); + const auto arm_s = tracking.last_arm_stats(); + EXPECT(arm_s.already_armed_skips == 1 && arm_s.vp_calls == 0 && arm_s.vq_calls == 0); + EXPECT(tracking.unwritten(base)); + tracking.unwatch(base); + other.release(base); + } + + // 2. MEM_RESERVE and PAGE_NOACCESS VQ region caching (explicit cached_state), while PAGE_READONLY is NEVER + // cached across sub-runs in the intra-lock VQ cache (ShadowPages::reopen() bypasses map_gen). + { + auto* reserved = static_cast(VirtualAlloc(nullptr, 4 * kPage, MEM_RESERVE, PAGE_NOACCESS)); + auto* noacc_mem = static_cast( + VirtualAlloc(nullptr, 4 * kPage, MEM_RESERVE | MEM_COMMIT, PAGE_NOACCESS)); + auto* ro_mem = static_cast( + VirtualAlloc(nullptr, 4 * kPage, MEM_RESERVE | MEM_COMMIT, PAGE_READONLY)); + EXPECT(reserved && noacc_mem && ro_mem); + if (reserved && noacc_mem && ro_mem) { + const auto res_base = reinterpret_cast(reserved); + const auto noacc_base = reinterpret_cast(noacc_mem); + const auto ro_base = reinterpret_cast(ro_mem); + { + leonida::HotColdTracking tracking; + std::vector mix = {res_base, res_base + 2 * kPage, res_base + 3 * kPage, + noacc_base, noacc_base + 2 * kPage, noacc_base + 3 * kPage}; + tracking.watch_batch(mix.data(), mix.size()); + tracking.collect(out); + const auto arm_s = tracking.last_arm_stats(); + EXPECT(arm_s.vp_calls == 0); + EXPECT(arm_s.vq_calls <= 2); // cached across non-contiguous sub-runs in each region! + EXPECT(tracking.take_refused() == 0); + tracking.unwatch_batch(mix.data(), mix.size()); + } + { + leonida::HotColdTracking tracking; + std::vector ro_mix = {ro_base, ro_base + 2 * kPage, ro_base + 3 * kPage}; + tracking.watch_batch(ro_mix.data(), ro_mix.size()); + tracking.collect(out); + const auto arm_s = tracking.last_arm_stats(); + EXPECT(arm_s.vp_calls == 0); + EXPECT(arm_s.vq_calls == 2); // PAGE_READONLY NOT cached across sub-runs! + EXPECT(tracking.take_refused() == 0); + tracking.unwatch_batch(ro_mix.data(), ro_mix.size()); + } + } + if (reserved) VirtualFree(reserved, 0, MEM_RELEASE); + if (noacc_mem) VirtualFree(noacc_mem, 0, MEM_RELEASE); + if (ro_mem) VirtualFree(ro_mem, 0, MEM_RELEASE); + } + + // 3. Range-scoped reopen() fast path + unexpected-protection rollback. + { + leonida::HotColdTracking tracking; + tracking.watch(base); + tracking.collect(out); + EXPECT(tracking.unwritten(base)); + // Unrelated map change must NOT disable range-scoped reopen() fast path. + leonida::title_memory_map::changed(base + 0x20000000, base + 0x20010000); + bool restored = false; + EXPECT(leonida::geometry_writes::notify(base + 64, base + 65, leonida::geometry_writes::Event::fault, + &restored)); + EXPECT(restored); + // Re-arm, then bypass title_memory_map::changed and change protection to PAGE_NOACCESS: reopen() MUST + // detect old != ro && old != r0, restore PAGE_NOACCESS, and NOT make it PAGE_READWRITE! + tracking.collect(out); + EXPECT(tracking.unwritten(base)); + DWORD prev_prot = 0; + EXPECT(VirtualProtect(memory, kPage, PAGE_NOACCESS, &prev_prot) != 0); + restored = false; + leonida::geometry_writes::notify(base, base + 1, leonida::geometry_writes::Event::open, &restored); + EXPECT(!restored); + MEMORY_BASIC_INFORMATION mbi{}; + EXPECT(VirtualQuery(memory, &mbi, sizeof mbi) && mbi.Protect == PAGE_NOACCESS); + EXPECT(VirtualProtect(memory, kPage, PAGE_READWRITE, &prev_prot) != 0); + leonida::title_memory_map::changed(base, base + kPage); + tracking.unwatch(base); + } + + // 4. kMaxBridgeGap = 32 bridging (gap of 16 cold armed tiles bridged in 1 VirtualProtect) + disarm_batch. + { + constexpr std::size_t kBridgePages = 24; + auto* bmem = static_cast( + VirtualAlloc(nullptr, kBridgePages * kPage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + EXPECT(bmem != nullptr); + if (bmem) { + const auto bbase = reinterpret_cast(bmem); + leonida::HotColdTracking tracking; + std::vector bpages(kBridgePages); + for (std::size_t p = 0; p < kBridgePages; ++p) bpages[p] = bbase + p * kPage; + tracking.watch_batch(bpages.data(), bpages.size()); + tracking.collect(out); // initial arm populates known_protect + // Open tiles 0 and 18 via notify(open) -> gap of 17 already-armed tiles (>8, <=32). + leonida::geometry_writes::notify(bbase, bbase + 1, leonida::geometry_writes::Event::open); + leonida::geometry_writes::notify(bbase + 18 * kPage, bbase + 18 * kPage + 1, + leonida::geometry_writes::Event::open); + tracking.collect(out); + const auto arm_s = tracking.last_arm_stats(); + EXPECT(arm_s.bridged_runs == 1 && arm_s.vp_calls == 1 && arm_s.vq_calls == 0); + // Promote 4 tiles simultaneously and run through a kProbe=32 cycle to exercise disarm_batch/set_hot_batch. + for (unsigned step = 0; step < 40; ++step) { + for (std::size_t p = 0; p < 4; ++p) + leonida::geometry_writes::notify(bbase + p * kPage, bbase + p * kPage + 1, + leonida::geometry_writes::Event::open); + tracking.collect(out); + } + for (std::size_t p = 0; p < 4; ++p) EXPECT(tracking.hot(bpages[p])); + tracking.unwatch_batch(bpages.data(), bpages.size()); + VirtualFree(bmem, 0, MEM_RELEASE); + } + } + + // 5. PAGE_WRITECOMBINE detection (when OS/Wine preserves PAGE_WRITECOMBINE on VirtualAlloc). + { + auto* wc_mem = static_cast( + VirtualAlloc(nullptr, 2 * kPage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE | PAGE_WRITECOMBINE)); + if (wc_mem) { + MEMORY_BASIC_INFORMATION mbi{}; + const bool host_has_wc = + VirtualQuery(wc_mem, &mbi, sizeof mbi) && (mbi.Protect & PAGE_WRITECOMBINE) != 0; + const auto wc_base = reinterpret_cast(wc_mem); + leonida::HotColdTracking tracking; + std::vector wpages = {wc_base, wc_base + kPage}; + tracking.watch_batch(wpages.data(), wpages.size()); + tracking.collect(out); + if (host_has_wc) { + EXPECT(tracking.last_arm_stats().wc_tiles == 2); + EXPECT(tracking.is_wc_page(wc_base) && tracking.is_wc_page(wc_base + kPage + 123)); + } + tracking.unwatch_batch(wpages.data(), wpages.size()); + EXPECT(!tracking.is_wc_page(wc_base)); + VirtualFree(wc_mem, 0, MEM_RELEASE); + } + } + std::printf("WS1 fast paths (all_armed, reserve/ro cache, range-scoped reopen, 32-gap bridge, disarm_batch, WC): ok\n"); + } + + // Verify Round 10 WS2 improvements & guardrails: + // 1. Shared Cell::known_* populated on all_armed skip -> subsequent re-arm takes 0 VQ, 1 VP fast path. + // 2. Cross-pass PAGE_NOACCESS and MEM_RESERVE caching in CellGuard (0 VQ, 0 VP on repeat arm; invalidated by + // title_memory_map::changed()), while PAGE_READONLY is NEVER cached cross-pass (reopened RO->RW without + // map change MUST be re-queried and re-guarded!). + // 3. BB1-BB4: bridging across already_armed batch tiles (no double-counting), bridging across a tile watched + // only by another owner (s.cells.find fallback), and 48-tile gap (<= kMaxBridgeGap = 64) in 1 VirtualProtect. + // 4. C1: title_write_watch::ask() single-reader fast path reports+erases mark() entries inside [from, to), + // preserves mark() entries outside [from, to), and does not insert GetWriteWatch pages into s.written. + { + std::vector out; + + // 1. Shared Cell::known_* seeded from all_armed skip. + { + TextureCells other; + leonida::geometry_writes::Cell* cell = other.acquire(base); + EXPECT(other.arm(base, *cell) == 1); + leonida::HotColdTracking tracking; + tracking.watch(base); + tracking.collect(out); // all_armed skip seeds Cell::known_* + EXPECT(tracking.last_arm_stats().already_armed_skips == 1 && tracking.last_arm_stats().vq_calls == 0); + leonida::geometry_writes::notify(base, base + 1, leonida::geometry_writes::Event::open); + tracking.collect(out); // repeat arm hits shared Cell::known_* -> 0 VQ, 1 VP! + const auto arm_s = tracking.last_arm_stats(); + EXPECT(arm_s.vq_calls == 0 && arm_s.vp_calls == 1 && arm_s.fast_tiles == 1); + tracking.unwatch(base); + other.release(base); + } + + // 2. Cross-pass PAGE_NOACCESS / MEM_RESERVE caching + PAGE_READONLY NEVER cached cross-pass. + { + auto* res = static_cast(VirtualAlloc(nullptr, kPage, MEM_RESERVE, PAGE_NOACCESS)); + auto* noacc = + static_cast(VirtualAlloc(nullptr, kPage, MEM_RESERVE | MEM_COMMIT, PAGE_NOACCESS)); + auto* ro = + static_cast(VirtualAlloc(nullptr, kPage, MEM_RESERVE | MEM_COMMIT, PAGE_READONLY)); + EXPECT(res && noacc && ro); + if (res && noacc && ro) { + const auto res_va = reinterpret_cast(res); + const auto noacc_va = reinterpret_cast(noacc); + const auto ro_va = reinterpret_cast(ro); + leonida::HotColdTracking tracking; + std::vector mix = {res_va, noacc_va, ro_va}; + tracking.watch_batch(mix.data(), mix.size()); + tracking.collect(out); // initial arm queries all 3 + // Re-arm MEM_RESERVE and PAGE_NOACCESS -> 0 VQ, 0 VP! + leonida::geometry_writes::notify(res_va, res_va + 1, leonida::geometry_writes::Event::write); + leonida::geometry_writes::notify(noacc_va, noacc_va + 1, leonida::geometry_writes::Event::write); + tracking.collect(out); + const auto s_noguard = tracking.last_arm_stats(); + EXPECT(s_noguard.vq_calls == 0 && s_noguard.vp_calls == 0); + + // Reopen PAGE_READONLY -> PAGE_READWRITE WITHOUT title_memory_map::changed() (ShadowPages::reopen): + // re-arm MUST re-query and protect it! + DWORD old_prot = 0; + EXPECT(VirtualProtect(ro, kPage, PAGE_READWRITE, &old_prot) != 0); + leonida::geometry_writes::notify(ro_va, ro_va + 1, leonida::geometry_writes::Event::write); + tracking.collect(out); + const auto s_ro = tracking.last_arm_stats(); + EXPECT(s_ro.vq_calls >= 1 && s_ro.vp_calls == 1); + MEMORY_BASIC_INFORMATION mbi{}; + EXPECT(VirtualQuery(ro, &mbi, sizeof mbi) && mbi.Protect == PAGE_READONLY); + + tracking.unwatch_batch(mix.data(), mix.size()); + } + if (res) VirtualFree(res, 0, MEM_RELEASE); + if (noacc) VirtualFree(noacc, 0, MEM_RELEASE); + if (ro) VirtualFree(ro, 0, MEM_RELEASE); + } + + // 3. BB1-BB4: bridge across already_armed batch tile, other-owner-only gap tile, and 48-tile gap (<=64). + { + constexpr std::size_t kBigBridge = 56; + auto* bmem = static_cast( + VirtualAlloc(nullptr, kBigBridge * kPage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + EXPECT(bmem != nullptr); + if (bmem) { + const auto bbase = reinterpret_cast(bmem); + leonida::HotColdTracking tracking; + TextureCells other; + std::vector bpages; + for (std::size_t p = 0; p < kBigBridge; ++p) { + if (p == 2) continue; // watched ONLY by `other` (s.cells.find fallback!) + bpages.push_back(bbase + p * kPage); + } + leonida::geometry_writes::Cell* c2 = other.acquire(bbase + 2 * kPage); + EXPECT(other.arm(bbase + 2 * kPage, *c2) == 1); + // Populate shared known_* on tile 2 via a brief watch+collect or direct arm (already armed via other). + { + leonida::HotColdTracking seed; + seed.watch(bbase + 2 * kPage); + seed.collect(out); // all_armed skip populates Cell::known_* on tile 2 + seed.unwatch(bbase + 2 * kPage); + } + tracking.watch_batch(bpages.data(), bpages.size()); + tracking.collect(out); // arms all remaining tiles and populates Cell::known_* + + // Open tiles 0 and 50 (gap of 49 tiles: includes tile 2 owned only by `other`, plus tile 1 armed in + // batch via write-notify on already-armed tile 1? Wait: make tile 1 already-armed in this batch by + // opening tile 1 via `other` re-arming it before collect!). + leonida::geometry_writes::notify(bbase + 0 * kPage, bbase + 0 * kPage + 1, + leonida::geometry_writes::Event::open); + leonida::geometry_writes::notify(bbase + 1 * kPage, bbase + 1 * kPage + 1, + leonida::geometry_writes::Event::open); + leonida::geometry_writes::notify(bbase + 50 * kPage, bbase + 50 * kPage + 1, + leonida::geometry_writes::Event::open); + // Re-arm tile 1 via `other` so tile 1 is in this batch's dirty list AND already_armed! + leonida::geometry_writes::Cell* c1 = other.acquire(bbase + 1 * kPage); + EXPECT(other.arm(bbase + 1 * kPage, *c1) == 1); + tracking.collect(out); + const auto arm_s = tracking.last_arm_stats(); + EXPECT(arm_s.bridged_runs == 1 && arm_s.vp_calls == 1 && arm_s.vq_calls == 0); + EXPECT(arm_s.already_armed_skips == 1 && arm_s.fast_tiles == 2); // tile 1 NOT double-counted! + + tracking.unwatch_batch(bpages.data(), bpages.size()); + other.release(bbase + 1 * kPage); + other.release(bbase + 2 * kPage); + VirtualFree(bmem, 0, MEM_RELEASE); + } + } + + // 4. C1: title_write_watch::ask() single-reader fast path with mark() inside and outside [from, to). + { + auto* ww = static_cast( + VirtualAlloc(nullptr, 4 * kPage, MEM_RESERVE | MEM_WRITE_WATCH, PAGE_READWRITE)); + if (ww) { + EXPECT(VirtualAlloc(ww, 4 * kPage, MEM_COMMIT, PAGE_READWRITE) != nullptr); + const auto ww_base = reinterpret_cast(ww); + leonida::title_write_watch::add(ww_base, 4 * kPage); + const std::uint64_t r = leonida::title_write_watch::open_reader(); + const std::vector> run0 = {{ww_base, ww_base + 2 * kPage}}; + const std::vector> run1 = { + {ww_base + 2 * kPage, ww_base + 4 * kPage}}; + // Prime reader past reservation's `born`. + leonida::title_write_watch::ask(r, run0, [](std::uintptr_t, std::uintptr_t) {}, + [](std::uintptr_t, std::uintptr_t) {}); + // Write page 0 via CPU and mark page 1 (inside run0) + page 3 (outside run0). + ww[10] = 0x42; + leonida::title_write_watch::mark(ww_base + kPage, ww_base + kPage + 4096); + leonida::title_write_watch::mark(ww_base + 3 * kPage, ww_base + 3 * kPage + 4096); + std::vector> got; + leonida::title_write_watch::ask( + r, run0, [&](std::uintptr_t a, std::uintptr_t b) { got.emplace_back(a, b); }, + [](std::uintptr_t, std::uintptr_t) {}); + bool saw_p0 = false, saw_p1 = false; + for (const auto& [a, b] : got) { + if (a <= ww_base && b >= ww_base + 4096) saw_p0 = true; + if (a <= ww_base + kPage && b >= ww_base + kPage + 4096) saw_p1 = true; + } + EXPECT(saw_p0 && saw_p1); + // Entry outside run0 (page 3) was preserved in s.written; entries inside run0 were erased and + // GetWriteWatch page 0 was never inserted into s.written. + { + auto& st = leonida::title_write_watch::state(); + std::lock_guard lock(st.journal); + EXPECT(st.written.find(ww_base) == st.written.end()); + EXPECT(st.written.find(ww_base + kPage) == st.written.end()); + EXPECT(st.written.find(ww_base + 3 * kPage) != st.written.end()); + } + // Drain run1 so s.written stays clean. + leonida::title_write_watch::ask(r, run1, [](std::uintptr_t, std::uintptr_t) {}, + [](std::uintptr_t, std::uintptr_t) {}); + leonida::title_write_watch::close_reader(r); + leonida::title_write_watch::remove(ww_base); + VirtualFree(ww, 0, MEM_RELEASE); + } + } + std::printf("WS2 fast paths (shared Cell::known_*, no-guard cache + RO guardrail, 64-gap bridge, C1): ok\n"); + } + + // Verify Round 10b WS-C fixes: + // 1. C2 bridged multi-tile rollback: when tile 0 has an unexpected prior protection (e.g., PAGE_NOACCESS changed + // without title_memory_map::changed()), rollback restores ONLY eligible tiles individually (tile 0 -> old, + // other eligible tiles -> verified kp), preserves already-armed gap tiles (both batch run_already_armed_ and + // other-owner s.cells tiles) at kg (PAGE_READONLY), and clears Cell::known_* across the bridged span. + // 2. C2 non-bridged multi-tile fast-path rollback: tile 0 restored to old, remaining tiles restored to fkp and + // re-armed cleanly via slow path (never clobbered to old). + { + std::vector out; + + // 1. Bridged rollback preserves already-armed gap tiles and clears Cell::known_*. + { + constexpr std::size_t kSpan = 6; + auto* smem = static_cast( + VirtualAlloc(nullptr, kSpan * kPage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + EXPECT(smem != nullptr); + if (smem) { + const auto sbase = reinterpret_cast(smem); + leonida::HotColdTracking tracking; + TextureCells other; + // Tile 2 is watched ONLY by `other` (s.cells gap tile); tiles 0,1,3,4,5 watched by `tracking`. + leonida::geometry_writes::Cell* c2 = other.acquire(sbase + 2 * kPage); + EXPECT(other.arm(sbase + 2 * kPage, *c2) == 1); + { + leonida::HotColdTracking seed; + seed.watch(sbase + 2 * kPage); + seed.collect(out); // seed Cell::known_* on tile 2 + seed.unwatch(sbase + 2 * kPage); + } + std::vector spages = {sbase + 0 * kPage, sbase + 1 * kPage, sbase + 3 * kPage, + sbase + 4 * kPage, sbase + 5 * kPage}; + tracking.watch_batch(spages.data(), spages.size()); + tracking.collect(out); // arms all tiles and populates Cell::known_* + + // Open tiles 0, 1, 4; re-arm tile 1 via `other` so tile 1 is run_already_armed_ in this batch, + // tile 2 is an other-owner gap tile, tile 3 is a tracking-owned armed gap tile, and tiles 0 & 4 + // are eligible -> bridged span covers [tile 0 .. tile 4]. + leonida::geometry_writes::notify(sbase + 0 * kPage, sbase + 0 * kPage + 1, + leonida::geometry_writes::Event::open); + leonida::geometry_writes::notify(sbase + 1 * kPage, sbase + 1 * kPage + 1, + leonida::geometry_writes::Event::open); + leonida::geometry_writes::notify(sbase + 4 * kPage, sbase + 4 * kPage + 1, + leonida::geometry_writes::Event::open); + leonida::geometry_writes::Cell* c1 = other.acquire(sbase + 1 * kPage); + EXPECT(other.arm(sbase + 1 * kPage, *c1) == 1); + + // Bypass title_memory_map::changed() on tile 0 -> PAGE_NOACCESS triggers unexpected `old` in + // bridged VirtualProtect! + DWORD prev_prot = 0; + EXPECT(VirtualProtect(smem + 0 * kPage, kPage, PAGE_NOACCESS, &prev_prot) != 0); + + tracking.collect(out); + + MEMORY_BASIC_INFORMATION mbi{}; + // Tile 0 restored to PAGE_NOACCESS; gap tiles 1, 2, 3 preserved at PAGE_READONLY; tile 4 re-armed! + EXPECT(VirtualQuery(smem + 0 * kPage, &mbi, sizeof mbi) && mbi.Protect == PAGE_NOACCESS); + EXPECT(VirtualQuery(smem + 1 * kPage, &mbi, sizeof mbi) && mbi.Protect == PAGE_READONLY); + EXPECT(VirtualQuery(smem + 2 * kPage, &mbi, sizeof mbi) && mbi.Protect == PAGE_READONLY); + EXPECT(VirtualQuery(smem + 3 * kPage, &mbi, sizeof mbi) && mbi.Protect == PAGE_READONLY); + EXPECT(VirtualQuery(smem + 4 * kPage, &mbi, sizeof mbi) && mbi.Protect == PAGE_READONLY); + EXPECT(tracking.unwritten(sbase + 4 * kPage)); + + // Cell::known_* cleared across the bridged span's gap tiles (tile 4 was re-populated by slow path). + { + auto& st = leonida::geometry_writes::state(); + std::lock_guard lock(st.mutex); + for (std::size_t g : {std::size_t(1), std::size_t(2), std::size_t(3)}) { + const auto it = st.cells.find(sbase + g * kPage); + EXPECT(it != st.cells.end() && it->second.known_state == 0); + } + } + + // Restore tile 0 before cleanup. + EXPECT(VirtualProtect(smem + 0 * kPage, kPage, PAGE_READWRITE, &prev_prot) != 0); + leonida::title_memory_map::changed(sbase, sbase + kPage); + tracking.unwatch_batch(spages.data(), spages.size()); + other.release(sbase + 1 * kPage); + other.release(sbase + 2 * kPage); + VirtualFree(smem, 0, MEM_RELEASE); + } + } + + // 2. Non-bridged multi-tile fast-path rollback: tile 0 -> old (PAGE_NOACCESS), tiles 1 & 2 -> fkp then armed! + { + constexpr std::size_t kRun = 3; + auto* rmem = static_cast( + VirtualAlloc(nullptr, kRun * kPage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + EXPECT(rmem != nullptr); + if (rmem) { + const auto rbase = reinterpret_cast(rmem); + leonida::HotColdTracking tracking; + std::vector rpages = {rbase + 0 * kPage, rbase + 1 * kPage, rbase + 2 * kPage}; + tracking.watch_batch(rpages.data(), rpages.size()); + tracking.collect(out); // arms all 3 and populates Cell::known_* + for (std::size_t p = 0; p < kRun; ++p) + leonida::geometry_writes::notify(rbase + p * kPage, rbase + p * kPage + 1, + leonida::geometry_writes::Event::open); + // Bypass title_memory_map::changed() on tile 0 -> PAGE_NOACCESS. + DWORD prev_prot = 0; + EXPECT(VirtualProtect(rmem + 0 * kPage, kPage, PAGE_NOACCESS, &prev_prot) != 0); + + tracking.collect(out); + + MEMORY_BASIC_INFORMATION mbi{}; + EXPECT(VirtualQuery(rmem + 0 * kPage, &mbi, sizeof mbi) && mbi.Protect == PAGE_NOACCESS); + EXPECT(VirtualQuery(rmem + 1 * kPage, &mbi, sizeof mbi) && mbi.Protect == PAGE_READONLY); + EXPECT(VirtualQuery(rmem + 2 * kPage, &mbi, sizeof mbi) && mbi.Protect == PAGE_READONLY); + EXPECT(tracking.unwritten(rbase + 1 * kPage) && tracking.unwritten(rbase + 2 * kPage)); + + EXPECT(VirtualProtect(rmem + 0 * kPage, kPage, PAGE_READWRITE, &prev_prot) != 0); + leonida::title_memory_map::changed(rbase, rbase + kPage); + tracking.unwatch_batch(rpages.data(), rpages.size()); + VirtualFree(rmem, 0, MEM_RELEASE); + } + } + std::printf("Round 10b WS-C (bridged/non-bridged rollback preserving gap tiles, RO VQ exclusion): ok\n"); + } + + VirtualFree(memory, 0, MEM_RELEASE); + return failures ? 1 : 0; +} diff --git a/runtime/test/title_texture_refresh_test.cpp b/runtime/test/title_texture_refresh_test.cpp index 9333b3b3cd..33ee4055ff 100644 --- a/runtime/test/title_texture_refresh_test.cpp +++ b/runtime/test/title_texture_refresh_test.cpp @@ -61,6 +61,12 @@ int main() { CHECK(unsorted.size() == 2); CHECK(unsorted[0] == std::make_pair(std::uintptr_t{0x1000}, std::uintptr_t{0x5000})); CHECK(unsorted[1] == std::make_pair(std::uintptr_t{0x8000}, std::uintptr_t{0x9000})); + + // Repeated full-space map changes ({0, UINTPTR_MAX}) plus sub-ranges collapse to a single {0, UINTPTR_MAX}. + TitleWriteRanges full_space{{0x2000, 0x4000}, {0, UINTPTR_MAX}, {0x8000, 0x9000}, {0, UINTPTR_MAX}}; + merge_title_writes(full_space); + CHECK(full_space.size() == 1); + CHECK(full_space[0] == std::make_pair(std::uintptr_t{0}, UINTPTR_MAX)); } // 2. title_write_overlaps: empty, degenerate query, single-range fast path, envelope reject, multi-range boundaries. diff --git a/runtime/test/title_texture_watch_test.cpp b/runtime/test/title_texture_watch_test.cpp new file mode 100644 index 0000000000..56745c88be --- /dev/null +++ b/runtime/test/title_texture_watch_test.cpp @@ -0,0 +1,1209 @@ +// TitleTextureWatch (src/title_texture_watch.h): a title texture is looked at only when something says it may have +// changed. A fake geometry watch stands in for the cells: a "write" bumps a tile's version and queues the tile, as +// the write-fault handler does through geometry_writes::notify. +#include "../src/title_frames.h" +#include "../src/title_texture_refresh.h" +#include "../src/title_texture_watch.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +struct FakeWatch { + struct Cell { + std::atomic version{1}, mapping{1}; + int refs = 0; + bool armed = false; + }; + std::map cells; + std::vector queue; + std::map> alias; // tile -> its other addresses + std::set unarmable, pinned; + bool on = true, overflow = false; + std::uint64_t serial = 1; + + Cell* acquire(std::uintptr_t tile) { + Cell& c = cells[tile]; + ++c.refs; + return &c; + } + void release(std::uintptr_t tile) { + auto it = cells.find(tile); + if (it != cells.end() && !--it->second.refs) cells.erase(it); + } + int arm(std::uintptr_t tile, Cell& c) { + if (pinned.count(tile)) return 0; + if (unarmable.count(tile)) return -1; + c.armed = true; + return 1; + } + void aliases(std::uintptr_t tile, std::vector& out) { + if (const auto it = alias.find(tile); it != alias.end()) out = it->second; + } + std::vector hot; + void hot_tiles(std::vector& out) { out = hot; } + void take_written(std::vector& out, bool& lost) { + out = std::move(queue); + queue.clear(); + lost = std::exchange(overflow, false); + } + bool enabled() const { return on; } + + // A write (fault, kernel write, mapping change) at `address`: only an armed tile's write faults. + void write(std::uintptr_t address, bool mapping = false) { + const std::uintptr_t tile = address & ~std::uintptr_t(0xffff); + const auto it = cells.find(tile); + if (it == cells.end()) return; + if (!it->second.armed && !mapping) return; // writable: no fault, nobody told (the watch's unarmed case) + it->second.armed = false; + it->second.version.store(++serial); + if (mapping) it->second.mapping.store(serial); + queue.push_back(tile); + } +}; + +using Watch = leonida::TitleTextureWatch; + +std::vector collect(Watch& w) { + std::vector out; + w.collect([&](std::uint64_t k) { + out.push_back(k); + w.examine(k); + }); + return out; +} + +int failures = 0; +#define EXPECT(c) \ + do { \ + if (!(c)) { \ + std::printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #c); \ + ++failures; \ + } \ + } while (0) + +using V = std::vector; + +} // namespace + +int main() { + constexpr std::uintptr_t kTile = 0x10000, base = 0x7f0000000000; + { // a new texture is examined once; untouched afterwards it is never examined again + FakeWatch f; + Watch w(f); + w.track(1, base, 3 * kTile); + w.track(2, base + 8 * kTile, kTile / 2); + EXPECT((collect(w) == V{1, 2})); + for (int pass = 0; pass < 5; ++pass) EXPECT(collect(w).empty()); + EXPECT(f.cells.at(base).armed && f.cells.at(base + 2 * kTile).armed); + w.track(1, base, 3 * kTile); // tracked again over the same tiles (a Map, a view): not named, still armed + EXPECT(collect(w).empty()); + EXPECT(f.cells.at(base).armed); + w.track(1, base, 4 * kTile); // over more tiles: named + EXPECT((collect(w) == V{1})); + } + { // a write to one page names exactly the textures over that page's tile + FakeWatch f; + Watch w(f); + w.track(1, base, 2 * kTile); // tiles 0, 1 + w.track(2, base + kTile + 0x8000, 0x1000); // tile 1 (shares it with 1) + w.track(3, base + 4 * kTile, kTile); // tile 4 + collect(w); + f.write(base + 0x100); // tile 0: texture 1 only + EXPECT((collect(w) == V{1})); + f.write(base + kTile + 0x9000); // tile 1: textures 1 and 2 + EXPECT((collect(w) == V{1, 2})); + EXPECT(collect(w).empty()); + f.write(base + 6 * kTile); // no texture there + EXPECT(collect(w).empty()); + } + { // a texture mapped at two addresses: a write through the other address names it too + FakeWatch f; + const std::uintptr_t other = 0x5000000000; + f.alias[base] = {other}; + Watch w(f); + w.track(7, base, kTile); + EXPECT((collect(w) == V{7})); + EXPECT(f.cells.count(other) && f.cells.at(other).armed); + f.write(other + 0x40); + EXPECT((collect(w) == V{7})); + EXPECT(collect(w).empty()); + } + { // a remap: the tile's mapping changes, the texture is named, and its new aliases are looked up + FakeWatch f; + Watch w(f); + w.track(9, base, kTile); + collect(w); + const std::uintptr_t other = 0x6000000000; + f.alias[base] = {other}; + f.write(base, true); + EXPECT((collect(w) == V{9})); + EXPECT(f.cells.count(other) && f.cells.at(other).armed); + f.alias[base] = {}; + f.write(base, true); + EXPECT((collect(w) == V{9})); + EXPECT(!f.cells.count(other)); // the old alias is released + } + { // a texture written every frame is named every frame, and only then + FakeWatch f; + Watch w(f); + w.track(4, base, 2 * kTile); + w.track(5, base + 4 * kTile, kTile); + collect(w); + for (int frame = 0; frame < 10; ++frame) { + f.write(base + kTile + 16 * frame); + EXPECT((collect(w) == V{4})); + EXPECT(collect(w).empty()); // the frame's other submissions + } + } + { // memory that cannot be armed: the texture is named at every collect until it can be (the one fallback) + FakeWatch f; + f.unarmable.insert(base); + Watch w(f); + w.track(3, base, kTile); + w.track(8, base + 2 * kTile, kTile); + EXPECT((collect(w) == V{3, 8})); + EXPECT((collect(w) == V{3})); + EXPECT((collect(w) == V{3})); + f.unarmable.clear(); + EXPECT((collect(w) == V{3})); // armed now + EXPECT(collect(w).empty()); + f.on = false; // no fault handler: nothing is ever armed, so a texture is always named + w.track(6, base + 5 * kTile, kTile); + EXPECT((collect(w) == V{6})); + EXPECT((collect(w) == V{6})); + } + { // a kernel write in progress: named, but busy (not to be read) until the pin ends; then read once + FakeWatch f; + Watch w(f); + w.track(2, base, 2 * kTile); + collect(w); + f.write(base + kTile); + f.pinned.insert(base + kTile); + std::vector looks; + const auto pass = [&] { + looks.clear(); + w.collect([&](std::uint64_t k) { looks.push_back(w.examine(k)); }); + }; + pass(); + EXPECT(looks.size() == 1 && looks[0] == Watch::Look::busy); + pass(); + EXPECT(looks.size() == 1 && looks[0] == Watch::Look::busy); + f.pinned.clear(); + pass(); + EXPECT(looks.size() == 1 && looks[0] == Watch::Look::armed); + pass(); + EXPECT(looks.empty()); + f.unarmable.insert(base); // a guard that cannot be set: read every time + f.write(base); + pass(); + EXPECT(looks.size() == 1 && looks[0] == Watch::Look::unwatched); + } + { // two textures in one tile, one written: both are named (the fault is per tile), exactly one is read whole + FakeWatch f; + Watch w(f); + static std::uint8_t memory[3 * kTile]; + const auto at = [&](std::uintptr_t a) { return memory + (a - base); }; + const std::uintptr_t a = base + 0x1000, b = base + 0x9000; // 16 KiB each, in tile 0 + const std::uintptr_t c = base + kTile - 0x2000; // 72 KiB, tiles 0 and 1 + const std::uint64_t sa = 0x4000, sb = 0x4000, sc = 0x12000; + for (std::size_t i = 0; i < sizeof memory; ++i) memory[i] = std::uint8_t(i * 7 + 1); + const auto hash = [](const std::uint8_t* p, std::uint64_t n) { + std::uint64_t h = 1469598103934665603ull; + for (std::uint64_t i = 0; i < n; ++i) h = (h ^ p[i]) * 1099511628211ull; + return h; + }; + std::map pieces; + const std::map> range{ + {1, {a, sa}}, {2, {b, sb}}, {3, {c, sc}}}; + for (const auto& [k, r] : range) w.track(k, r.first, r.second); + unsigned whole = 0; + std::uint64_t compared = 0; + std::vector written; + const auto pass = [&] { + std::vector read; + w.collect([&](std::uint64_t k) { + w.examine(k, &written); + const auto [cpu, span] = range.at(k); + auto& p = pieces[k]; + if (p.valid_for(cpu, span) && + p.unchanged(written, [&](std::uintptr_t from, std::uint64_t n) -> std::optional { + compared += n; + return hash(at(from), n); + })) + return; + ++whole; + read.push_back(k); + p.compute(cpu, span, at(cpu), hash); + }); + return read; + }; + EXPECT((pass() == V{1, 2, 3})); // new: read whole + whole = 0; + compared = 0; + memory[b - base + 5] ^= 0xff; // texture 2 written; the fault names tile 0 (textures 1, 2 and 3) + f.write(b + 5); + EXPECT((pass() == V{2})); + EXPECT(whole == 1); + EXPECT(compared == sa + sb + 0x2000); // 1 and 3 hashed only their parts of tile 0 + whole = 0; + memory[c - base + 0x3000] ^= 0xff; // texture 3 written in tile 1: only 3 is named, and read + f.write(c + 0x3000); + EXPECT((pass() == V{3})); + EXPECT(whole == 1); + } + { // a lost queue names every texture once; untrack releases the tiles + FakeWatch f; + Watch w(f); + w.track(1, base, kTile); + w.track(2, base + kTile, kTile); + collect(w); + f.overflow = true; + f.write(base); + EXPECT((collect(w) == V{1})); // the tile written; the other's version did not move + w.untrack(1); + w.untrack(2); + EXPECT(f.cells.empty()); + EXPECT(w.tiles() == 0 && w.textures() == 0); + } + { // O(1) lock-free clean fast-path (may_have_work) and buffer-hot decoupling (hot_count / hot_tiles) + struct FastFakeWatch : FakeWatch { + std::uint64_t hot_tile_calls = 0; + bool has_written() const { return !queue.empty() || overflow; } + std::size_t hot_count() const { return hot.size(); } + void hot_tiles(std::vector& out) { + ++hot_tile_calls; + out = hot; + } + }; + using FastWatch = leonida::TitleTextureWatch; + FastFakeWatch f; + FastWatch w(f); + for (std::uint64_t i = 0; i < 1000; ++i) w.track(i + 1, base + i * kTile, kTile); + EXPECT(w.may_have_work()); + std::vector seen; + w.collect([&](std::uint64_t k) { + seen.push_back(k); + w.examine(k); + }); + EXPECT(seen.size() == 1000); + // Clean steady state: O(1) lock-free fast-path reports no work. + EXPECT(!w.may_have_work()); + + // 500 buffer-only hot pages in TitleMirror (disjoint from watched textures): + const std::uintptr_t buf_base = base + 0x10000000; + for (std::size_t i = 0; i < 500; ++i) f.hot.push_back(buf_base + i * kTile); + // hot_count changed -> one sync pass detects zero texture overlap and decouples them. + EXPECT(w.may_have_work()); + seen.clear(); + w.collect([&](std::uint64_t k) { + seen.push_back(k); + w.examine(k); + }); + EXPECT(seen.empty()); + EXPECT(w.hot_overlap() == 0); + EXPECT(!w.may_have_work()); // buffer-only hot pages no longer wake refresh! + const std::uint64_t calls_before = f.hot_tile_calls; + for (int pass = 0; pass < 5; ++pass) { + w.collect([&](std::uint64_t k) { seen.push_back(k); }); + } + EXPECT(seen.empty()); + EXPECT(f.hot_tile_calls == calls_before); // hot_tiles() was completely skipped on quiet passes! + EXPECT(w.stats().hot_skips >= 5); + + // One hot page that DOES overlap texture #42: only texture #42 is named, and examine() still delegates to + // watch_.arm() so kernel-write pin checks (Look::busy) and concurrent set_hot(false) transitions stay safe. + f.hot.push_back(base + 41 * kTile); + EXPECT(w.may_have_work()); + const std::uint64_t arms_before = w.stats().arms; + seen.clear(); + w.collect([&](std::uint64_t k) { + seen.push_back(k); + w.examine(k); + }); + EXPECT((seen == V{42})); + EXPECT(w.hot_overlap() == 1); + EXPECT(w.may_have_work()); // overlapping hot tile stays active + EXPECT(w.stats().arms == arms_before + 1); // delegates to watch_.arm() for pin & set_hot(false) safety + + // Tile cools down (TitleMirror::set_hot(false) removes from hot and queues write): + f.hot.pop_back(); + f.write(base + 41 * kTile, true); // simulate set_hot(false) bumping version + queuing tile + seen.clear(); + w.collect([&](std::uint64_t k) { + seen.push_back(k); + w.examine(k); + }); + EXPECT((seen == V{42})); + EXPECT(w.hot_overlap() == 0); + EXPECT(!w.may_have_work()); + + // Equal-swap edge case with hot_generation(): one buffer page cools while one texture page heats in the + // same pass (hot.size() stays numerically equal, but hot_generation() increments). + struct GenFakeWatch : FastFakeWatch { + std::uint64_t hot_gen = 0; + std::uint64_t hot_generation() const { return hot_gen; } + }; + using GenWatch = leonida::TitleTextureWatch; + GenFakeWatch gf; + GenWatch gw(gf); + gw.track(1, base, kTile); + gw.track(2, base + kTile, kTile); + gw.collect([&](std::uint64_t k) { gw.examine(k); }); + gf.hot = {buf_base}; + ++gf.hot_gen; + gw.collect([&](std::uint64_t k) { gw.examine(k); }); + EXPECT(gw.hot_overlap() == 0 && !gw.may_have_work()); + // Swap buffer page out and texture-2 page in: hot.size() == 1 before and after, hot_gen bumped! + gf.hot = {base + kTile}; + ++gf.hot_gen; + EXPECT(gw.may_have_work()); + seen.clear(); + gw.collect([&](std::uint64_t k) { + seen.push_back(k); + gw.examine(k); + }); + EXPECT((seen == V{2})); + EXPECT(gw.hot_overlap() == 1); + + // Single-tile write on a multi-tile texture names ONLY that texture and examine() returns ONLY that 1 tile. + const std::uintptr_t big_base = base + 0x20000000; + w.track(9999, big_base, 16 * kTile); + w.collect([&](std::uint64_t k) { w.examine(k); }); + EXPECT(!w.may_have_work()); + f.write(big_base + 7 * kTile + 123); + EXPECT(w.may_have_work()); + std::vector written_tiles; + seen.clear(); + w.collect([&](std::uint64_t k) { + seen.push_back(k); + w.examine(k, &written_tiles); + }); + EXPECT((seen == V{9999})); + EXPECT(written_tiles.size() == 1 && written_tiles[0] == big_base + 7 * kTile); + EXPECT(!w.may_have_work()); + } + { // 1-tile hash-before-reserve skips staging reserve & whole read when bytes are unchanged + FakeWatch f; + Watch w(f); + static std::uint8_t mem[kTile]; + for (std::size_t i = 0; i < sizeof mem; ++i) mem[i] = std::uint8_t(i * 13 + 5); + const auto at = [&](std::uintptr_t a) { return mem + (a - base); }; + const auto hash = [](const std::uint8_t* p, std::uint64_t n) { + std::uint64_t h = 1469598103934665603ull; + for (std::uint64_t i = 0; i < n; ++i) h = (h ^ p[i]) * 1099511628211ull; + return h; + }; + // Two 1-tile textures sharing tile 0. + const std::map> range{ + {1, {base + 0x0000, 0x4000}}, {2, {base + 0x8000, 0x4000}}}; + std::map pieces; + for (const auto& [k, r] : range) w.track(k, r.first, r.second); + unsigned reserves = 0; + std::vector written; + const auto pass = [&] { + std::vector uploaded; + w.collect([&](std::uint64_t k) { + w.examine(k, &written); + const auto [cpu, span] = range.at(k); + const std::size_t tiles = leonida::TilePieces::tiles(cpu, span); + auto& p = pieces[k]; + // Hash-before-reserve: `written.size() <= tiles` (including tiles == 1) hashes before reserving. + if (p.valid_for(cpu, span) && !written.empty() && written.size() <= tiles && + p.unchanged(written, [&](std::uintptr_t from, std::uint64_t n) -> std::optional { + return hash(at(from), n); + })) + return; + ++reserves; + uploaded.push_back(k); + p.compute(cpu, span, at(cpu), hash); + }); + return uploaded; + }; + EXPECT((pass() == V{1, 2})); + EXPECT(reserves == 2); + reserves = 0; + // Mutate only texture 2 in shared tile 0: texture 1 (1-tile!) must NOT reserve or upload. + mem[0x8010] ^= 0xff; + f.write(base + 0x8010); + EXPECT((pass() == V{2})); + EXPECT(reserves == 1); + } + { // note_changed() / note_changed_and_for_each() on already-armed unchanged tiles skips redundant + // watch_.arm(), while remapped, faulted, hot, pinned, and rearm=true tiles still call watch_.arm(). + FakeWatch f; + Watch w(f); + w.track(1, base, 2 * kTile); + w.track(2, base + 4 * kTile, kTile); + EXPECT((collect(w) == V{1, 2})); + const std::uint64_t arms_initial = w.stats().arms; + EXPECT(arms_initial == 3); + + // 1. note_changed_and_for_each on already-armed unchanged tiles: names textures & populates `written`, + // ZERO redundant watch_.arm() calls! + std::vector over; + w.note_changed_and_for_each(base, base + 5 * kTile, [&](std::uint64_t k) { over.push_back(k); }); + std::sort(over.begin(), over.end()); + EXPECT((over == V{1, 2})); + std::vector seen; + std::vector written_1, written_2; + w.collect([&](std::uint64_t k) { + seen.push_back(k); + auto look = w.examine(k, k == 1 ? &written_1 : &written_2); + EXPECT(look == Watch::Look::armed); + }); + EXPECT((seen == V{1, 2})); + EXPECT(written_1.size() == 2 && written_2.size() == 1); + EXPECT(w.stats().arms == arms_initial); // ZERO redundant watch_.arm() calls! + + // 2. Remap (mapping moved) + note_changed: MUST call watch_.arm() and pick up new aliases. + const std::uintptr_t alias_addr = 0x5500000000; + f.alias[base] = {alias_addr}; + f.write(base, true); + w.note_changed(base, base + kTile); + EXPECT((collect(w) == V{1})); + EXPECT(w.stats().arms == arms_initial + 1); + EXPECT(f.cells.count(alias_addr) && f.cells.at(alias_addr).armed); + + // 3. Faulted (version moved) + pinned: MUST call watch_.arm() and return Look::busy. + const std::uint64_t arms_before_pin = w.stats().arms; + f.write(base + kTile); + f.pinned.insert(base + kTile); + w.note_changed(base + kTile, base + 2 * kTile); + Watch::Look pin_look = Watch::Look::armed; + w.collect([&](std::uint64_t k) { pin_look = w.examine(k); }); + EXPECT(pin_look == Watch::Look::busy); + EXPECT(w.stats().arms == arms_before_pin + 1); + f.pinned.clear(); + EXPECT((collect(w) == V{1})); // armed once unpinned + EXPECT(w.stats().arms == arms_before_pin + 2); + + // 4. Hot tile: MUST still call watch_.arm() on hot pass. + const std::uint64_t arms_before_hot = w.stats().arms; + f.hot = {base + 4 * kTile}; + EXPECT((collect(w) == V{2})); + EXPECT(w.stats().arms == arms_before_hot + 1); + f.hot.clear(); + f.write(base + 4 * kTile, true); + EXPECT((collect(w) == V{2})); + EXPECT(w.stats().arms == arms_before_hot + 2); + + // 5. Explicit rearm=true (mapped texture whose pages may be committed without xmem): MUST call watch_.arm(). + const std::uint64_t arms_before_rearm = w.stats().arms; + w.note_changed(base + 4 * kTile, base + 5 * kTile, true); + EXPECT((collect(w) == V{2})); + EXPECT(w.stats().arms == arms_before_rearm + 1); + + // 6. Shared-tile re-examine safety (for synced_frames reuse gate `look == armed && arms == arms_before`): + // - Two textures sharing a non-hot tile: first examine() arms (+1), second examine() with NO concurrent + // write keeps arms unchanged (+0), whereas a concurrent write between them bumps version and arms (+1)! + // - Two textures sharing a hot tile: BOTH examine() calls MUST delegate to watch_.arm() (+1 each) so a + // hot tile never appears unchanged/armed to the second texture in the same pass! + w.track(10, base + 8 * kTile, 0x4000); + w.track(11, base + 8 * kTile + 0x8000, 0x4000); + EXPECT((collect(w) == V{10, 11})); + // 6a. Single pre-pass fault on shared tile, no concurrent write between examine(10) and examine(11): + f.write(base + 8 * kTile); + std::vector shared_keys; + w.collect([&](std::uint64_t k) { shared_keys.push_back(k); }); + EXPECT((shared_keys == V{10, 11})); + const std::uint64_t a0 = w.stats().arms; + EXPECT(w.examine(10) == Watch::Look::armed && w.stats().arms == a0 + 1); + const std::uint64_t a1 = w.stats().arms; + EXPECT(w.examine(11) == Watch::Look::armed && w.stats().arms == a1); // unchanged since examine(10) + + // 6b. Concurrent write T2 lands on shared tile BETWEEN examine(10) and examine(11): + f.write(base + 8 * kTile); + shared_keys.clear(); + w.collect([&](std::uint64_t k) { shared_keys.push_back(k); }); + EXPECT((shared_keys == V{10, 11})); + const std::uint64_t b0 = w.stats().arms; + EXPECT(w.examine(10) == Watch::Look::armed && w.stats().arms == b0 + 1); + f.write(base + 8 * kTile + 0x8010); // concurrent title write to texture 11 before examine(11)! + const std::uint64_t b1 = w.stats().arms; + EXPECT(w.examine(11) == Watch::Look::armed && w.stats().arms == b1 + 1); // MUST arm (+1) to signal resync! + + // 6c. Shared HOT tile: BOTH examine(10) and examine(11) MUST call watch_.arm() (+1 each)! + f.hot = {base + 8 * kTile}; + shared_keys.clear(); + w.collect([&](std::uint64_t k) { shared_keys.push_back(k); }); + EXPECT((shared_keys == V{10, 11})); + const std::uint64_t c0 = w.stats().arms; + EXPECT(w.examine(10) == Watch::Look::armed && w.stats().arms == c0 + 1); + const std::uint64_t c1 = w.stats().arms; + EXPECT(w.examine(11) == Watch::Look::armed && w.stats().arms == c1 + 1); // hot tile never skips arm()! + f.hot.clear(); + f.write(base + 8 * kTile, true); + EXPECT((collect(w) == V{10, 11})); + } + { // 86k-tile scale test verifying O(overlapping) chunked region index (no O(86k) std::sort). + struct FastScaleWatch { + struct Cell { + std::atomic version{1}, mapping{1}; + }; + Cell shared_cell; + Cell* acquire(std::uintptr_t) { return &shared_cell; } + void release(std::uintptr_t) {} + int arm(std::uintptr_t, Cell&) { return 1; } + void aliases(std::uintptr_t, std::vector&) {} + void hot_tiles(std::vector& out) { out.clear(); } + void take_written(std::vector& out, bool& lost) { + out.clear(); + lost = false; + } + bool enabled() const { return true; } + bool has_written() const { return false; } + std::uint64_t hot_generation() const { return 0; } + }; + FastScaleWatch sf; + leonida::TitleTextureWatch sw(sf); + constexpr std::size_t kTextures = 43000; // 2 tiles each = 86,000 tiles across ~336 x 16 MiB regions + for (std::size_t i = 0; i < kTextures; ++i) { + sw.track(i + 1, base + i * 2 * kTile, 2 * kTile); + } + EXPECT(sw.tiles() == kTextures * 2); + sw.collect([&](std::uint64_t k) { sw.examine(k); }); + + // Interleave track/untrack mutations with > 4 MiB range queries (20 iterations). + // Previously each track/untrack dirtied sorted_tiles_ and forced O(86k) std::sort (~5-12 ms each!). + constexpr std::size_t kIters = 20; + const std::uintptr_t probe_from = base + 50000 * kTile; // spans region boundary + const std::uintptr_t probe_to = probe_from + 128 * kTile; // 8 MiB (> 4 MiB threshold) + std::size_t total_over = 0; + const auto t0 = std::chrono::steady_clock::now(); + for (std::size_t iter = 0; iter < kIters; ++iter) { + const std::uint64_t temp_key = 1000000 + iter; + sw.track(temp_key, base + (kTextures * 2 + iter * 2) * kTile, 2 * kTile); + std::size_t over_count = 0; + sw.note_changed_and_for_each(probe_from, probe_to, [&](std::uint64_t) { ++over_count; }); + EXPECT(over_count == 64); // 128 tiles / 2 tiles per texture = 64 textures + total_over += over_count; + sw.untrack(temp_key); + } + const auto elapsed_us = + std::chrono::duration_cast(std::chrono::steady_clock::now() - t0).count(); + const double per_iter_ms = double(elapsed_us) / 1000.0 / double(kIters); + EXPECT(total_over == kIters * 64); + EXPECT(per_iter_ms < 0.5); + // Untrack one texture inside [probe_from, probe_to) and verify region index swap-and-pop stays exact. + sw.untrack(25001); // covers tiles 50000..50001 + std::size_t after_untrack = 0; + sw.for_each_over(probe_from, probe_to, [&](std::uint64_t) { ++after_untrack; }); + EXPECT(after_untrack == 63); + std::printf("86k-tile region index: %.4f ms/iter across %zu tiles (%zu iters, total %lld us)\n", + per_iter_ms, sw.tiles(), kIters, static_cast(elapsed_us)); + } + { // hot_generation() skips watch_.hot_tiles() even while overlapping hot tiles stay active, and non_hot_arms + // distinguishes steady-state shared hot-tile pin-checks from real re-arms / concurrent set_hot(false). + struct GenHotWatch : FakeWatch { + std::uint64_t hot_gen = 0; + std::uint64_t hot_tile_calls = 0; + bool has_written() const { return !queue.empty() || overflow; } + std::uint64_t hot_generation() const { return hot_gen; } + void hot_tiles(std::vector& out) { + ++hot_tile_calls; + out = hot; + } + }; + using GenWatch = leonida::TitleTextureWatch; + GenHotWatch f; + GenWatch w(f); + w.track(1, base, 0x4000); + w.track(2, base + 0x8000, 0x4000); // shares tile 0 with texture 1 + w.track(3, base + 2 * kTile, kTile); // tile 2 (separate) + w.collect([&](std::uint64_t k) { w.examine(k); }); + + // Mark tile 0 + 150 unrelated buffer tiles hot (1 hot_generation bump). + f.hot.push_back(base); + for (std::size_t i = 0; i < 150; ++i) f.hot.push_back(base + (1000 + i) * kTile); + ++f.hot_gen; + + std::vector seen; + w.collect([&](std::uint64_t k) { seen.push_back(k); }); + EXPECT((seen == V{1, 2})); + EXPECT(w.hot_overlap() == 1); + const std::uint64_t calls_after_sync = f.hot_tile_calls; + + // First examine on shared hot tile increments both arms and non_hot_arms; second examine on the same hot tile + // in the same pass still delegates to watch_.arm() (+1 arms) without bumping non_hot_arms (+0 non_hot_arms)! + const std::uint64_t arms0 = w.stats().arms, nha0 = w.stats().non_hot_arms; + EXPECT(w.examine(1) == GenWatch::Look::armed); + EXPECT(w.stats().arms == arms0 + 1 && w.stats().non_hot_arms == nha0 + 1); + EXPECT(w.examine(2) == GenWatch::Look::armed); + EXPECT(w.stats().arms == arms0 + 2 && w.stats().non_hot_arms == nha0 + 1); + + // Subsequent passes with unchanged hot_generation() MUST NOT call watch_.hot_tiles() even though + // active_hot_tiles_ is non-empty AND even when an unrelated tile faults! + const std::uint64_t skips_before = w.stats().hot_skips; + for (int pass = 0; pass < 5; ++pass) { + f.write(base + 2 * kTile); + seen.clear(); + w.collect([&](std::uint64_t k) { + seen.push_back(k); + w.examine(k); + }); + EXPECT((seen == V{1, 2, 3})); + } + EXPECT(f.hot_tile_calls == calls_after_sync); + EXPECT(w.stats().hot_skips == skips_before + 5); + + // Concurrent set_hot(false) (version bump) between examine(1) and examine(2) MUST bump non_hot_arms! + seen.clear(); + w.collect([&](std::uint64_t k) { seen.push_back(k); }); + EXPECT((seen == V{1, 2})); + const std::uint64_t nha1 = w.stats().non_hot_arms; + EXPECT(w.examine(1) == GenWatch::Look::armed && w.stats().non_hot_arms == nha1 + 1); + f.cells.at(base).version.fetch_add(1, std::memory_order_release); // simulate concurrent set_hot(false) + EXPECT(w.examine(2) == GenWatch::Look::armed && w.stats().non_hot_arms == nha1 + 2); + + // Cooling tile 0 bumps hot_generation() -> triggers re-poll and drops hot_overlap to 0. + f.hot.erase(f.hot.begin()); + ++f.hot_gen; + f.write(base, true); + seen.clear(); + w.collect([&](std::uint64_t k) { + seen.push_back(k); + w.examine(k); + }); + EXPECT((seen == V{1, 2})); + EXPECT(f.hot_tile_calls == calls_after_sync + 1); + EXPECT(w.hot_overlap() == 0); + EXPECT(!w.may_have_work()); + } + { // mirror_range_sum_bytes() and mirror_range_sum_from_pieces() parity + single-byte mutation sensitivity. + std::vector buf(2 * kTile); + for (std::size_t i = 0; i < buf.size(); ++i) buf[i] = static_cast((i * 37u + 11u) & 0xffu); + EXPECT(leonida::mirror_range_sum_bytes(buf.data(), 0) == 0); + for (const std::uint64_t sz : {std::uint64_t(256), std::uint64_t(4096), std::uint64_t(kTile), + std::uint64_t(2 * kTile)}) { + const std::uint64_t direct = leonida::mirror_range_sum_bytes(buf.data(), sz); + std::vector sums; + for (std::uint64_t off = 0; off < sz; off += leonida::shadow_keep::kPiece) + sums.push_back(leonida::shadow_keep::sum_of(buf.data() + off, leonida::shadow_keep::kPiece)); + const std::uint64_t combined = leonida::mirror_range_sum_from_pieces(sums.data(), sums.size(), sz); + EXPECT(direct != 0 && direct == combined); + // Flipping one byte changes the digest. + buf[sz - 1] ^= 0x80u; + EXPECT(leonida::mirror_range_sum_bytes(buf.data(), sz) != direct); + buf[sz - 1] ^= 0x80u; + EXPECT(leonida::mirror_range_sum_bytes(buf.data(), sz) == direct); + } + } + { // examine_batch(): batched arming with arm_batch()-capable watch, deduplication of shared tiles & mutual alias + // peers, contiguous address ordering, busy > unwatched > armed precedence, hot tiles, and fallback without + // arm_batch(). + struct BatchFakeWatch : FakeWatch { + std::uint64_t batch_calls = 0; + std::uint64_t batch_tiles_total = 0; + std::vector last_batch_vas; + void arm_batch(const std::uintptr_t* tiles, Cell* const* cell_ptrs, std::int8_t* results, + std::size_t count) { + ++batch_calls; + batch_tiles_total += count; + last_batch_vas.assign(tiles, tiles + count); + for (std::size_t i = 0; i < count; ++i) { + const int r = arm(tiles[i], *cell_ptrs[i]); + results[i] = static_cast(r > 0 ? 1 : (r == 0 ? 0 : -1)); + } + } + }; + using BatchWatch = leonida::TitleTextureWatch; + BatchFakeWatch bf; + BatchWatch bw(bf); + + // Textures 1 & 2 share tile 0; texture 3 covers contiguous tiles 1..4; texture 4 & 5 are mutual aliases (tiles + // 10 and 20); texture 6 covers tiles 30 (unarmable) & 31 (pinned) to verify busy > unwatched precedence. + bw.track(1, base + 0 * kTile, 0x4000); + bw.track(2, base + 0 * kTile + 0x8000, 0x4000); + bw.track(3, base + 1 * kTile, 4 * kTile); + bf.alias[base + 10 * kTile] = {base + 20 * kTile}; + bf.alias[base + 20 * kTile] = {base + 10 * kTile}; + bw.track(4, base + 10 * kTile, kTile); + bw.track(5, base + 20 * kTile, kTile); + bf.unarmable.insert(base + 30 * kTile); + bf.pinned.insert(base + 31 * kTile); + bw.track(6, base + 30 * kTile, 2 * kTile); + + std::vector keys; + bw.collect([&](std::uint64_t k) { keys.push_back(k); }); + EXPECT((keys == V{1, 2, 3, 4, 5, 6})); + + std::vector results; + bw.examine_batch(keys, results); + bw.update_idle_hint(); + EXPECT(results.size() == 6); + EXPECT(bf.batch_calls == 1); // ALL 6 textures armed in ONE single arm_batch() call! + // Unique tiles armed: 0, 1, 2, 3, 4, 10, 20, 30, 31 = 9 unique tiles (shared tile 0 and mutual aliases 10/20 + // deduplicated!), sorted in ascending address order for contiguous VirtualProtect coalescing. + EXPECT(bf.last_batch_vas.size() == 9); + EXPECT(std::is_sorted(bf.last_batch_vas.begin(), bf.last_batch_vas.end())); + EXPECT(results[0].look == BatchWatch::Look::armed && results[0].written.size() == 1); + EXPECT(results[1].look == BatchWatch::Look::armed && results[1].written.size() == 1); + EXPECT(results[2].look == BatchWatch::Look::armed && results[2].written.size() == 4); + EXPECT(results[3].look == BatchWatch::Look::armed && results[3].written.size() == 1); + EXPECT(results[4].look == BatchWatch::Look::armed && results[4].written.size() == 1); + // Texture 6 has tile 30 unarmable (-1) AND tile 31 pinned (0): busy MUST override unwatched! + EXPECT(results[5].look == BatchWatch::Look::busy && results[5].written.size() == 2); + + // Release pin on tile 31 while tile 30 stays unarmable: texture 6 now reports Look::unwatched. + bf.pinned.clear(); + keys.clear(); + bw.collect([&](std::uint64_t k) { keys.push_back(k); }); + EXPECT((keys == V{6})); + bw.examine_batch(keys, results); + EXPECT(results.size() == 1 && results[0].look == BatchWatch::Look::unwatched); + + // Clear unarmable too: texture 6 arms cleanly and steady state goes quiet. + bf.unarmable.clear(); + keys.clear(); + bw.collect([&](std::uint64_t k) { keys.push_back(k); }); + EXPECT((keys == V{6})); + bw.examine_batch(keys, results); + EXPECT(results.size() == 1 && results[0].look == BatchWatch::Look::armed); + keys.clear(); + bw.collect([&](std::uint64_t k) { keys.push_back(k); }); + EXPECT(keys.empty()); + + // Duplicate tiles in write queue: tile 0 pushed 10 times still names textures 1 & 2 once each with 1 tile in + // written and 1 unique arm in arm_batch(). + bf.write(base + 0 * kTile); + for (int dup = 0; dup < 9; ++dup) bf.queue.push_back(base + 0 * kTile); + const std::uint64_t calls_before = bf.batch_calls; + keys.clear(); + bw.collect([&](std::uint64_t k) { keys.push_back(k); }); + EXPECT((keys == V{1, 2})); + bw.examine_batch(keys, results); + EXPECT(bf.batch_calls == calls_before + 1); + EXPECT(bf.last_batch_vas.size() == 1 && bf.last_batch_vas[0] == base + 0 * kTile); + EXPECT(results[0].look == BatchWatch::Look::armed && results[0].written.size() == 1); + EXPECT(results[1].look == BatchWatch::Look::armed && results[1].written.size() == 1); + + // Peer busy > primary unwatched precedence: primary tile 10 unarmable (-1), peer tile 20 pinned (0) -> busy! + bf.write(base + 10 * kTile); + bf.unarmable.insert(base + 10 * kTile); + bf.pinned.insert(base + 20 * kTile); + keys.clear(); + bw.collect([&](std::uint64_t k) { keys.push_back(k); }); + EXPECT((keys == V{4, 5})); + bw.examine_batch(keys, results); + EXPECT(results[0].look == BatchWatch::Look::busy); + EXPECT(results[1].look == BatchWatch::Look::busy); + bf.unarmable.clear(); + bf.pinned.clear(); + keys.clear(); + bw.collect([&](std::uint64_t k) { keys.push_back(k); }); + bw.examine_batch(keys, results); + + // Fallback examine_batch() on Watch WITHOUT arm_batch() (FakeWatch): identical semantics. + FakeWatch ff; + Watch fw(ff); + fw.track(1, base, 2 * kTile); + fw.track(2, base + kTile, kTile); + keys.clear(); + fw.collect([&](std::uint64_t k) { keys.push_back(k); }); + std::vector fres; + fw.examine_batch(keys, fres); + EXPECT(fres.size() == 2 && fres[0].look == Watch::Look::armed && fres[1].look == Watch::Look::armed); + EXPECT(fres[0].written.size() == 2 && fres[1].written.size() == 1); + } + { // 41k-texture / 81k-tile / 350-written-tile microbenchmark: verifies collect() + examine_batch() throughput + // and arm_batch() syscall coalescing vs per-tile examine() at realistic open-world scale. + struct ScaleBatchWatch { + struct Cell { + std::atomic version{1}, mapping{1}; + }; + std::deque pool; + std::unordered_map index; + std::vector queue; + std::uint64_t arm_calls = 0; + std::uint64_t batch_calls = 0; + std::uint64_t contiguous_runs = 0; + + Cell* acquire(std::uintptr_t tile) { + auto [it, fresh] = index.try_emplace(tile, pool.size()); + if (fresh) pool.emplace_back(); + return &pool[it->second]; + } + void release(std::uintptr_t) {} + int arm(std::uintptr_t, Cell&) { + ++arm_calls; + return 1; + } + void arm_batch(const std::uintptr_t* tiles, Cell* const*, std::int8_t* results, std::size_t count) { + ++batch_calls; + for (std::size_t i = 0; i < count; ++i) { + if (i == 0 || tiles[i] != tiles[i - 1] + kTile) ++contiguous_runs; + results[i] = 1; + } + } + void aliases(std::uintptr_t, std::vector&) {} + void hot_tiles(std::vector& out) { out.clear(); } + void take_written(std::vector& out, bool& lost) { + out.swap(queue); + queue.clear(); + lost = false; + } + bool enabled() const { return true; } + bool has_written() const { return !queue.empty(); } + std::uint64_t hot_generation() const { return 0; } + }; + ScaleBatchWatch sw_watch; + leonida::TitleTextureWatch sw(sw_watch); + constexpr std::size_t kTextures = 41000; // 41k textures over ~81k tiles + std::uintptr_t cursor = base; + std::vector texture_tiles; + texture_tiles.reserve(kTextures); + for (std::size_t i = 0; i < kTextures; ++i) { + const std::size_t ntiles = (i % 10 == 0) ? 1 : ((i % 10 == 1) ? 3 : 2); + sw.track(i + 1, cursor, ntiles * kTile); + texture_tiles.push_back(cursor); + cursor += ntiles * kTile; + } + EXPECT(sw.textures() == kTextures && sw.tiles() >= 81000); + // Initial arm pass via examine_batch. + std::vector named; + sw.collect([&](std::uint64_t k) { named.push_back(k); }); + std::vector::BatchExamine> batch_out; + sw.examine_batch(named, batch_out); + EXPECT(named.size() == kTextures); + EXPECT(sw_watch.batch_calls == 1); + + // Simulate 200 passes: 350 written tiles/pass (300 unrelated buffer tiles + 50 watched texture tiles in + // contiguous runs across ~35 textures). + constexpr std::size_t kPasses = 200; + const std::uintptr_t buf_base = base + 0x400000000ull; + sw_watch.batch_calls = 0; + sw_watch.contiguous_runs = 0; + std::uint64_t serial = 2; + std::size_t total_named = 0; + const auto t0 = std::chrono::steady_clock::now(); + for (std::size_t p = 0; p < kPasses; ++p) { + sw_watch.queue.clear(); + for (std::size_t b = 0; b < 300; ++b) sw_watch.queue.push_back(buf_base + ((p * 37 + b) % 4096) * kTile); + const std::size_t start_tex = (p * 173) % (kTextures - 64); + for (std::size_t k = 0; k < 25; ++k) { + const std::uintptr_t a0 = texture_tiles[start_tex + k]; + const std::uintptr_t a1 = a0 + kTile; + sw_watch.pool[sw_watch.index.at(a0)].version.store(++serial, std::memory_order_relaxed); + sw_watch.queue.push_back(a0); + if (const auto it = sw_watch.index.find(a1); it != sw_watch.index.end()) { + sw_watch.pool[it->second].version.store(++serial, std::memory_order_relaxed); + sw_watch.queue.push_back(a1); + } + } + named.clear(); + sw.collect([&](std::uint64_t k) { named.push_back(k); }); + sw.examine_batch(named, batch_out); + sw.update_idle_hint(); + total_named += named.size(); + } + const auto elapsed_us = + std::chrono::duration_cast(std::chrono::steady_clock::now() - t0).count(); + const double per_pass_ms = double(elapsed_us) / 1000.0 / double(kPasses); + EXPECT(sw_watch.batch_calls == kPasses); + EXPECT(sw_watch.contiguous_runs < kPasses * 10); // ~50 tiles coalesced into <= 3 contiguous runs/pass! + EXPECT(total_named >= kPasses * 25); + EXPECT(per_pass_ms < 0.25); + std::printf("41k-tex/81k-tile/350-written bench: %.4f ms/pass (%zu passes, %.1f contiguous runs/pass, %zu " + "named/pass)\n", + per_pass_ms, kPasses, double(sw_watch.contiguous_runs) / double(kPasses), total_named / kPasses); + } + { // Slot-70 deferral contract: touch() on a clean tracked texture wakes may_have_work() and collect() so + // refresh_title_textures() never fast-skips it, and examine_batch() with 1 tile still routes through arm_batch(). + struct SingleBatchWatch : FakeWatch { + std::uint64_t batch_calls = 0; + std::uint64_t single_calls = 0; + int arm(std::uintptr_t tile, Cell& c) { + ++single_calls; + return FakeWatch::arm(tile, c); + } + void arm_batch(const std::uintptr_t* tiles, Cell* const* cell_ptrs, std::int8_t* results, + std::size_t count) { + ++batch_calls; + for (std::size_t i = 0; i < count; ++i) { + const int r = FakeWatch::arm(tiles[i], *cell_ptrs[i]); + results[i] = static_cast(r > 0 ? 1 : (r == 0 ? 0 : -1)); + } + } + bool has_written() const { return !queue.empty() || overflow; } + std::uint64_t hot_generation() const { return 0; } + }; + SingleBatchWatch sfw; + leonida::TitleTextureWatch sw(sfw); + sw.track(101, base, kTile); + EXPECT(sw.may_have_work()); + std::vector keys; + sw.collect([&](std::uint64_t k) { keys.push_back(k); }); + EXPECT((keys == V{101})); + std::vector::BatchExamine> res; + sw.examine_batch(keys, res); + sw.update_idle_hint(); + EXPECT(sfw.batch_calls == 1 && sfw.single_calls == 0); // even count==1 uses arm_batch()! + EXPECT(!sw.may_have_work()); + + // Existing texture deferred from slot-70 refresh_title_texture(): touch() MUST wake may_have_work() & collect(). + sw.touch(101); + EXPECT(sw.may_have_work()); + keys.clear(); + sw.collect([&](std::uint64_t k) { keys.push_back(k); }); + EXPECT((keys == V{101})); + sw.examine_batch(keys, res); + sw.update_idle_hint(); + EXPECT(!sw.may_have_work()); + } + { // BatchExamine::max_version propagation (shared tiles, alias peers, raced writes during arm_batch, pure touch) + // and sync_tile_peers() zero-acquire/release skip when alias set is unchanged across remaps. + struct PeerAndVersionWatch : FakeWatch { + std::uint64_t acquire_calls = 0; + std::uint64_t release_calls = 0; + std::uintptr_t race_tile = 0; + Cell* acquire(std::uintptr_t tile) { + ++acquire_calls; + return FakeWatch::acquire(tile); + } + void release(std::uintptr_t tile) { + ++release_calls; + FakeWatch::release(tile); + } + void arm_batch(const std::uintptr_t* tiles, Cell* const* cell_ptrs, std::int8_t* results, + std::size_t count) { + for (std::size_t i = 0; i < count; ++i) { + const int r = FakeWatch::arm(tiles[i], *cell_ptrs[i]); + if (r > 0 && race_tile && tiles[i] == race_tile) { + // Simulate a write that raced between queue_tile() version read and arm_batch(). + cell_ptrs[i]->version.store(++serial, std::memory_order_release); + } + results[i] = static_cast(r > 0 ? 1 : (r == 0 ? 0 : -1)); + } + } + }; + PeerAndVersionWatch pw; + leonida::TitleTextureWatch watch(pw); + + const std::uintptr_t peer_a = 0x5100000000; + const std::uintptr_t peer_b = 0x5200000000; + const std::uintptr_t peer_c = 0x5300000000; + pw.alias[base] = {peer_b, peer_a}; // intentionally unsorted to test sorting + equality skip + watch.track(1, base, 2 * kTile); + watch.track(2, base + kTile, kTile); // shares tile 1 with texture 1 + + std::vector keys; + std::vector::BatchExamine> res; + watch.collect([&](std::uint64_t k) { keys.push_back(k); }); + EXPECT((keys == V{1, 2})); + watch.examine_batch(keys, res); + EXPECT(res.size() == 2 && res[0].look == leonida::TitleTextureWatch::Look::armed); + EXPECT(res[0].max_version == 1 && res[1].max_version == 1); + + // Bump mapping on base with IDENTICAL peer set (different order + duplicate + self): + // sync_tile_peers() MUST skip acquire() and release() completely! + const std::uint64_t acq0 = pw.acquire_calls, rel0 = pw.release_calls; + pw.alias[base] = {peer_a, base, peer_b, peer_a}; + pw.write(base, /*mapping=*/true); + const std::uint64_t ver_after_remap = pw.serial; + keys.clear(); + watch.collect([&](std::uint64_t k) { keys.push_back(k); }); + EXPECT((keys == V{1})); + watch.examine_batch(keys, res); + EXPECT(pw.acquire_calls == acq0 && pw.release_calls == rel0); + EXPECT(res[0].max_version == ver_after_remap); + + // Bump mapping on base with CHANGED peer set ({peer_a, peer_c}): acquires new peers, releases old. + pw.alias[base] = {peer_a, peer_c}; + pw.write(base, /*mapping=*/true); + keys.clear(); + watch.collect([&](std::uint64_t k) { keys.push_back(k); }); + watch.examine_batch(keys, res); + EXPECT(pw.cells.count(peer_a) && pw.cells.count(peer_c) && !pw.cells.count(peer_b)); + EXPECT(pw.acquire_calls > acq0 && pw.release_calls > rel0); + + // Write through alias peer_c: max_version of texture 1 reflects peer_c's version! + pw.write(peer_c + 0x100); + const std::uint64_t peer_ver = pw.serial; + keys.clear(); + watch.collect([&](std::uint64_t k) { keys.push_back(k); }); + EXPECT((keys == V{1})); + watch.examine_batch(keys, res); + EXPECT(res[0].max_version == peer_ver); + + // Shared tile 1 written + raced during arm_batch(): post-arm max_version reflects raced version for BOTH keys! + pw.write(base + kTile); + pw.race_tile = base + kTile; + keys.clear(); + watch.collect([&](std::uint64_t k) { keys.push_back(k); }); + EXPECT((keys == V{1, 2})); + watch.examine_batch(keys, res); + const std::uint64_t raced_ver = pw.serial; + EXPECT(res[0].max_version == raced_ver && res[1].max_version == raced_ver); + pw.race_tile = 0; + + // Pure touch() with no dirty tiles: max_version still reads current cell versions accurately. + watch.touch(2); + keys.clear(); + watch.collect([&](std::uint64_t k) { keys.push_back(k); }); + EXPECT((keys == V{2})); + watch.examine_batch(keys, res); + EXPECT(res[0].max_version == raced_ver); + } + { // Batched peer sync (acquire_batch / release_batch) in sync_tile_peers(), examine_batch(), and drop(): + // across 4 remapping tiles with overlapping surviving peers, examine_batch() issues ONE acquire_batch() before + // ONE release_batch() so surviving peers never drop refcount to 0. + struct BatchPeerWatch : FakeWatch { + std::uint64_t single_acq = 0, single_rel = 0; + std::uint64_t batch_acq_calls = 0, batch_rel_calls = 0; + std::uint64_t batch_acq_items = 0, batch_rel_items = 0; + bool peer_dropped_to_zero = false; + std::uintptr_t watch_nonzero_peer = 0; + Cell* acquire(std::uintptr_t tile) { + ++single_acq; + return FakeWatch::acquire(tile); + } + void release(std::uintptr_t tile) { + ++single_rel; + FakeWatch::release(tile); + } + void acquire_batch(const std::uintptr_t* vas, Cell** out, std::size_t n) { + ++batch_acq_calls; + batch_acq_items += n; + for (std::size_t i = 0; i < n; ++i) out[i] = FakeWatch::acquire(vas[i]); + } + void release_batch(const std::pair* items, std::size_t n) { + ++batch_rel_calls; + batch_rel_items += n; + for (std::size_t i = 0; i < n; ++i) { + FakeWatch::release(items[i].first); + if (watch_nonzero_peer && items[i].first == watch_nonzero_peer && !cells.count(watch_nonzero_peer)) + peer_dropped_to_zero = true; + } + } + void arm_batch(const std::uintptr_t* tiles, Cell* const* cell_ptrs, std::int8_t* results, + std::size_t count) { + for (std::size_t i = 0; i < count; ++i) { + const int r = FakeWatch::arm(tiles[i], *cell_ptrs[i]); + results[i] = static_cast(r > 0 ? 1 : (r == 0 ? 0 : -1)); + } + } + }; + BatchPeerWatch bpw; + leonida::TitleTextureWatch bwatch(bpw); + const std::uintptr_t p0 = 0x6100000000, p1 = 0x6200000000, p2 = 0x6300000000, p3 = 0x6400000000; + for (std::uint64_t k = 0; k < 4; ++k) { + bpw.alias[base + k * kTile] = {p0, p1}; + bwatch.track(k + 1, base + k * kTile, kTile); + } + std::vector keys; + std::vector::BatchExamine> res; + bwatch.collect([&](std::uint64_t k) { keys.push_back(k); }); + EXPECT((keys == V{1, 2, 3, 4})); + const std::uint64_t sa0 = bpw.single_acq; + bwatch.examine_batch(keys, res); + // All 4 tiles' initial peer syncs ran in ONE acquire_batch (8 items, 0 single_acq for peers). + EXPECT(bpw.single_acq == sa0); + EXPECT(bpw.batch_acq_calls == 1 && bpw.batch_acq_items == 8); + EXPECT(bpw.batch_rel_calls == 0); + EXPECT(bpw.cells.at(p0).refs == 4 && bpw.cells.at(p1).refs == 4); + + // Remap all 4 tiles from {p0, p1} -> {p0, p2} (p0 survives and MUST never hit refcount 0!). + bpw.watch_nonzero_peer = p0; + for (std::uint64_t k = 0; k < 4; ++k) { + bpw.alias[base + k * kTile] = {p0, p2}; + bpw.write(base + k * kTile, /*mapping=*/true); + } + keys.clear(); + bwatch.collect([&](std::uint64_t k) { keys.push_back(k); }); + EXPECT((keys == V{1, 2, 3, 4})); + bwatch.examine_batch(keys, res); + EXPECT(!bpw.peer_dropped_to_zero); + EXPECT(bpw.batch_acq_calls == 2 && bpw.batch_acq_items == 16); + EXPECT(bpw.batch_rel_calls == 1 && bpw.batch_rel_items == 8); + EXPECT(bpw.cells.at(p0).refs == 4 && bpw.cells.at(p2).refs == 4 && !bpw.cells.count(p1)); + + // Single-key examine() with remap also routes through acquire_batch / release_batch. + bpw.alias[base] = {p0, p3}; + bpw.write(base, /*mapping=*/true); + keys.clear(); + bwatch.collect([&](std::uint64_t k) { keys.push_back(k); }); + EXPECT((keys == V{1})); + EXPECT(bwatch.examine(1) == leonida::TitleTextureWatch::Look::armed); + EXPECT(!bpw.peer_dropped_to_zero); + EXPECT(bpw.batch_acq_calls == 3 && bpw.batch_rel_calls == 2); + EXPECT(bpw.cells.at(p3).refs == 1 && bpw.cells.at(p2).refs == 3); + + // untrack() releases primary + peers via release_batch. + bpw.watch_nonzero_peer = 0; + const std::uint64_t sr0 = bpw.single_rel; + for (std::uint64_t k = 0; k < 4; ++k) bwatch.untrack(k + 1); + EXPECT(bpw.single_rel == sr0); + EXPECT(bpw.cells.empty()); + } + { // title_frames::run_end() and title_frames::backed_batch(): fast single-hook path & fallback path. + static std::set s_pages; + static std::uint8_t s_dummy_buf[65536]; + static std::uint64_t s_lookup_calls = 0; + static std::uint64_t s_run_end_calls = 0; + static std::uint64_t s_backed_batch_calls = 0; + const auto lookup_fn = [](std::uintptr_t page, leonida::title_frames::Frame& out) -> bool { + ++s_lookup_calls; + if (!s_pages.count(page)) return false; + out.bytes = s_dummy_buf; + return true; + }; + const auto run_end_fn = [](std::uintptr_t from, std::uintptr_t to, bool& is_backed) -> std::uintptr_t { + ++s_run_end_calls; + constexpr std::uintptr_t kP = leonida::title_frames::kPage; + const std::uintptr_t p0 = from & ~(kP - 1); + is_backed = s_pages.count(p0) != 0; + std::uintptr_t at = p0 + kP; + while (at < to && at > from && (s_pages.count(at) != 0) == is_backed) at += kP; + return at < to && at > from ? at : to; + }; + const auto backed_batch_fn = [](const std::uintptr_t* pages, std::uint8_t* out, std::size_t n) { + ++s_backed_batch_calls; + constexpr std::uintptr_t kP = leonida::title_frames::kPage; + for (std::size_t i = 0; i < n; ++i) out[i] = s_pages.count(pages[i] & ~(kP - 1)) ? 1u : 0u; + }; + + const std::uintptr_t tf_base = 0x700000000000ull; + s_pages = {tf_base + 1 * kTile, tf_base + 2 * kTile, tf_base + 5 * kTile}; + for (const std::uintptr_t p : s_pages) leonida::title_frames::note_page(p); + + // 1. Registered fast hooks: run_end() and backed_batch() invoke fast hooks with ZERO per-page lookup_fn calls! + leonida::title_frames::set_lookup(lookup_fn, nullptr, run_end_fn, backed_batch_fn); + bool is_b = false; + EXPECT(leonida::title_frames::run_end(tf_base, tf_base + 6 * kTile, is_b) == tf_base + 1 * kTile && !is_b); + EXPECT(leonida::title_frames::run_end(tf_base + 1 * kTile, tf_base + 6 * kTile, is_b) == tf_base + 3 * kTile && + is_b); + EXPECT(leonida::title_frames::run_end(tf_base + 3 * kTile, tf_base + 6 * kTile, is_b) == tf_base + 5 * kTile && + !is_b); + EXPECT(leonida::title_frames::run_end(tf_base + 5 * kTile, tf_base + 6 * kTile, is_b) == tf_base + 6 * kTile && + is_b); + const std::uintptr_t query[6] = {tf_base, tf_base + 1 * kTile + 123, tf_base + 2 * kTile, + tf_base + 3 * kTile, tf_base + 4 * kTile, tf_base + 5 * kTile}; + std::uint8_t out[6] = {}; + leonida::title_frames::backed_batch(query, out, 6); + EXPECT(out[0] == 0 && out[1] == 1 && out[2] == 1 && out[3] == 0 && out[4] == 0 && out[5] == 1); + EXPECT(s_run_end_calls == 4 && s_backed_batch_calls == 1 && s_lookup_calls == 0); + + // 2. Fallback without fast hooks (2-arg set_lookup): identical results via lookup_fn. + leonida::title_frames::set_lookup(lookup_fn, nullptr); + std::uint8_t out2[6] = {}; + leonida::title_frames::backed_batch(query, out2, 6); + for (int i = 0; i < 6; ++i) EXPECT(out2[i] == out[i]); + EXPECT(leonida::title_frames::run_end(tf_base + 1 * kTile, tf_base + 6 * kTile, is_b) == tf_base + 3 * kTile && + is_b); + EXPECT(s_lookup_calls > 0); + leonida::title_frames::set_lookup(nullptr, nullptr); + } + if (failures) return 1; + std::puts("title texture watch: new, untouched, one page, two addresses, remap, every frame, unarmable, kernel " + "write in progress, lost queue, O(1) fast-path, buffer-hot decoupling, 1-tile hash-before-reserve, " + "note_changed arm-skip, 86k-tile region index, hot_generation skip, non_hot_arms, mirror piece hash, " + "examine_batch, max_version, peer-skip, batched peer sync, title_frames batch, 41k-tex scale bench"); + return 0; +} diff --git a/runtime/test/title_va_alias_test.cpp b/runtime/test/title_va_alias_test.cpp index 7cc51cf920..cc884fae2f 100644 --- a/runtime/test/title_va_alias_test.cpp +++ b/runtime/test/title_va_alias_test.cpp @@ -138,6 +138,84 @@ int main() { EXPECT(!a.shader_side(arena) && a.shader_side(0xA0000ff) && !a.shader_side(0xA000100)); a.remove(title + 0x100, 0xA000000); EXPECT(a.size() == 0 && !a.shader_side(0xA000000)); + // Read-only vs writable resolution: writable=false translates without invoking Noter, while writable=true invokes + // Noter and forwards the writable flag to AccessResolver. + struct HookState { + std::uint64_t noted = 0, last_noted_va = 0, last_noted_bytes = 0; + std::uint64_t resolved = 0, last_writable_calls = 0, last_readonly_calls = 0; + std::uint64_t mirror_va = 0, remap_from = 0, remap_to = 0; + } hs; + hs.mirror_va = title + 0x800000; + hs.remap_from = title + 0x900000; + hs.remap_to = 0xB000000; + a.set_hooks( + &hs, + [](void* ctx, std::uint64_t va, std::uint64_t bytes, bool writable, std::uint64_t& out) -> bool { + (void)bytes; + auto* s = static_cast(ctx); + ++s->resolved; + if (writable) ++s->last_writable_calls; + else ++s->last_readonly_calls; + if (va == s->mirror_va) { + out = va; + return true; + } + if (va == s->remap_from) { + out = s->remap_to; + return true; + } + return false; + }, + nullptr); + a.set_noter([](void* ctx, std::uint64_t va, std::uint64_t bytes) { + auto* s = static_cast(ctx); + ++s->noted; + s->last_noted_va = va; + s->last_noted_bytes = bytes; + }); + // Existing alias hit: writable=false translates without noting; writable=true (and default) notes. + EXPECT(a.add(title, size, arena)); + EXPECT(a.resolve(title + 0x20, 64, leonida::TitleVaAliases::root_view, false) == arena + 0x20); + EXPECT(hs.noted == 0); + EXPECT(a.resolve(title + 0x20, 64, leonida::TitleVaAliases::root_view, true) == arena + 0x20); + EXPECT(hs.noted == 1 && hs.last_noted_va == title + 0x20 && hs.last_noted_bytes == 64); + EXPECT(a.resolve(title + 0x40, 32, leonida::TitleVaAliases::root_view) == arena + 0x40); + EXPECT(hs.noted == 2 && hs.last_noted_va == title + 0x40 && hs.last_noted_bytes == 32); + a.remove(title, arena); + // AccessResolver path: writable flag is passed through; Noter fires iff writable && to != 0 (including mirror to == va). + EXPECT(a.resolve(hs.mirror_va, 128, leonida::TitleVaAliases::root_view, false) == hs.mirror_va); + EXPECT(hs.last_readonly_calls == 1 && hs.last_writable_calls == 0 && hs.noted == 2); + EXPECT(a.resolve(hs.mirror_va, 128, leonida::TitleVaAliases::root_view, true) == hs.mirror_va); + EXPECT(hs.last_readonly_calls == 1 && hs.last_writable_calls == 1 && hs.noted == 3 && + hs.last_noted_va == hs.mirror_va && hs.last_noted_bytes == 128); + EXPECT(a.resolve(hs.remap_from, 256, leonida::TitleVaAliases::root_view, false) == hs.remap_to); + EXPECT(hs.last_readonly_calls == 2 && hs.noted == 3); + EXPECT(a.resolve(hs.remap_from, 256, leonida::TitleVaAliases::root_view, true) == hs.remap_to); + EXPECT(hs.last_writable_calls == 2 && hs.noted == 4 && hs.last_noted_va == hs.remap_from && + hs.last_noted_bytes == 256); + a.clear_hooks(&hs); + // 4-arg Resolver path (unchanged hook signature): mirrored (to == va) notes iff writable=true. + hs.noted = 0; + a.set_hooks( + &hs, + [](void* ctx, std::uint64_t va, std::uint64_t, std::uint64_t& out) -> bool { + auto* s = static_cast(ctx); + if (va != s->mirror_va) return false; + out = va; + return true; + }, + nullptr); + a.set_noter([](void* ctx, std::uint64_t va, std::uint64_t bytes) { + auto* s = static_cast(ctx); + ++s->noted; + s->last_noted_va = va; + s->last_noted_bytes = bytes; + }); + EXPECT(a.resolve(hs.mirror_va, 64, leonida::TitleVaAliases::root_view, false) == hs.mirror_va); + EXPECT(hs.noted == 0); + EXPECT(a.resolve(hs.mirror_va, 64, leonida::TitleVaAliases::root_view, true) == hs.mirror_va); + EXPECT(hs.noted == 1 && hs.last_noted_va == hs.mirror_va && hs.last_noted_bytes == 64); + a.clear_hooks(&hs); constexpr std::uint64_t twin = title + 0x10000000; EXPECT(a.add(twin + size, size, arena)); @@ -176,7 +254,6 @@ int main() { EXPECT(!a.shader_side(0x8000010)); EXPECT(a.shader_va(twin + 4 * size + 16) == twin + 4 * size + 16); EXPECT(a.shader_va(twin + 5 * size - 16) == 0x9000000); - std::printf("title_va_alias: translation inside a title-placed range, identity outside it and after release\n"); return 0; } diff --git a/runtime/test/title_write_policy_test.cpp b/runtime/test/title_write_policy_test.cpp new file mode 100644 index 0000000000..af98cb0ffd --- /dev/null +++ b/runtime/test/title_write_policy_test.cpp @@ -0,0 +1,352 @@ +// TitleWritePolicy (src/title_write_policy.h) with a scripted and a randomised write pattern over fake memory: a fake +// guard (a page is read-only while armed; the first write to it "faults" into written()), the title's writes, and the +// owner's copy taken in collect(). Pages written in most submissions (kPromote = 6 of 8) stop faulting, 1/frame and +// rare pages stay cold without over-copying on empty submissions, and no write is missed: the copy equals the memory +// byte for byte after every collect, except pages written during that collect's own copy, which the next one brings +// over. +#include "../src/title_write_policy.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +constexpr std::uintptr_t kPage = 0x10000, kBase = 0x100000000; +constexpr std::size_t kPages = 64; + +struct Fake { + std::vector memory = std::vector(kPages * kPage), copy = memory; + std::set armed; + bool refuse = false; + std::uint64_t faults = 0; + leonida::TitleWritePolicy* policy = nullptr; + std::map faults_by_page; + + bool arm(std::uintptr_t page) { + if (refuse) return false; + armed.insert(page); + return true; + } + void disarm(std::uintptr_t page) { armed.erase(page); } + void write(std::uintptr_t va, std::uint8_t value) { + const std::uintptr_t page = va & ~(kPage - 1); + if (armed.erase(page)) { // the fault: the handler opens the page and tells the policy + ++faults; + ++faults_by_page[page]; + policy->written(page); + } + memory[va - kBase] = value; + } + void take(std::uintptr_t page) { + std::memcpy(copy.data() + (page - kBase), memory.data() + (page - kBase), kPage); + } + bool same(std::uintptr_t page) const { + return !std::memcmp(copy.data() + (page - kBase), memory.data() + (page - kBase), kPage); + } +}; + +int failures = 0; +#define EXPECT(c) \ + do { \ + if (!(c)) { \ + std::printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #c); \ + ++failures; \ + } \ + } while (0) + +using Policy = leonida::TitleWritePolicy; + +} // namespace + +int main() { + { // scripted: page 0 written every frame, page 1 every 10th frame, page 2 never after the start + Fake f; + Policy policy(f); + f.policy = &policy; + policy.add(kBase, kBase + 3 * kPage); + policy.collect([&](std::uintptr_t p) { f.take(p); }); + std::uint64_t hot_faults_late = 0, rare_faults = 0; + for (unsigned frame = 1; frame <= 200; ++frame) { + for (unsigned submission = 0; submission < 4; ++submission) { + const std::uint64_t before = f.faults_by_page[kBase]; + f.write(kBase + 100 + submission, std::uint8_t(frame + submission)); + // (a probe: armed at the collect after the probe's frame() and observed for the next interval) + const unsigned phase = frame % Policy::kProbe; + if (frame > 20 && phase != 1 && phase != 2) hot_faults_late += f.faults_by_page[kBase] - before; + if (frame % 10 == 0 && submission == 0) { + const std::uint64_t b = f.faults_by_page[kBase + kPage]; + f.write(kBase + kPage + frame, std::uint8_t(frame)); + f.write(kBase + kPage + frame + 1, std::uint8_t(frame)); // same page, same interval: no fault + rare_faults += f.faults_by_page[kBase + kPage] - b; + } + policy.collect([&](std::uintptr_t p) { f.take(p); }); + for (std::uintptr_t p = kBase; p < kBase + 3 * kPage; p += kPage) EXPECT(f.same(p)); + } + policy.frame(); + } + EXPECT(policy.hot(kBase)); // written every frame: hot + EXPECT(!policy.hot(kBase + kPage)); // every 10th: cold + EXPECT(hot_faults_late == 0); // a hot page stops faulting (but in its probe frames) + EXPECT(rare_faults == 20); // a cold page: one fault per written interval + EXPECT(f.faults_by_page[kBase + 2 * kPage] == 0); + // The hot page stops being written: a probe frame finds it quiet and it turns cold. + for (unsigned frame = 0; frame < 2 * Policy::kProbe; ++frame) { + policy.collect([&](std::uintptr_t p) { f.take(p); }); + policy.frame(); + } + EXPECT(!policy.hot(kBase)); + EXPECT(policy.stats().demotions == 1); + } + { // randomised: writes anywhere, also during the owner's copy; compared with the memory after every collect + std::mt19937_64 random(12345); + Fake f; + Policy policy(f); + f.policy = &policy; + policy.add(kBase, kBase + kPages * kPage); + std::vector rate(kPages); + for (auto& r : rate) r = std::uniform_real_distribution(0, 1)(random) < 0.2 ? 0.95 : 0.03; + std::uint64_t mismatches = 0; + for (unsigned frame = 0; frame < 400; ++frame) { + if (frame == 200) f.refuse = true; // a guard that cannot be set: copied every time + if (frame == 260) f.refuse = false; + for (unsigned submission = 0; submission < 3; ++submission) { + for (std::size_t p = 0; p < kPages; ++p) + if (std::uniform_real_distribution(0, 1)(random) < rate[p] / 3) + f.write(kBase + p * kPage + random() % kPage, std::uint8_t(random())); + std::set during; + policy.collect([&](std::uintptr_t page) { + f.take(page); + if (random() % 16 == 0) { // the title writes while the owner copies: armed first, so it faults + const std::uintptr_t other = kBase + (random() % kPages) * kPage; + f.write(other + random() % kPage, std::uint8_t(random())); + during.insert(other); + } + }); + for (std::size_t p = 0; p < kPages; ++p) { + const std::uintptr_t page = kBase + p * kPage; + if (!during.count(page) && !f.same(page)) ++mismatches; + } + } + policy.frame(); + } + policy.collect([&](std::uintptr_t p) { f.take(p); }); + EXPECT(mismatches == 0); + EXPECT(f.copy == f.memory); // byte-exact once the last writes are collected + const auto& s = policy.stats(); + EXPECT(s.hot > 0 && s.cold > 0); + std::printf("randomised: %zu hot and %zu cold pages; %llu faults, %llu hot and %llu cold copies, %llu " + "promotions, %llu demotions, %llu refused arms\n", + s.hot, s.cold, static_cast(s.faults), + static_cast(s.hot_copies), static_cast(s.cold_copies), + static_cast(s.promotions), static_cast(s.demotions), + static_cast(s.arm_failures)); + } + { // scale + correctness: 200,000 cold pages + 100 hot pages stays O(dirty + hot), sub-millisecond per collect+frame + struct LightGuard { + std::uint64_t arms = 0, disarms = 0; + bool arm(std::uintptr_t) { + ++arms; + return true; + } + void disarm(std::uintptr_t) { ++disarms; } + } lg; + constexpr std::size_t kCold = 200000, kHot = 100, kTotal = kCold + kHot; + leonida::TitleWritePolicy policy(lg); + policy.add(kBase, kBase + kTotal * kPage); + // Initial collect arms all 200,100 pages once. + std::size_t initial = 0; + policy.collect([&](std::uintptr_t) { ++initial; }); + EXPECT(initial == kTotal); + EXPECT(policy.stats().cold == kTotal && policy.stats().hot == 0); + // Promote the first kHot pages by writing them every submission for kPromote intervals. + for (unsigned f = 0; f < Policy::kPromote; ++f) { + for (std::size_t h = 0; h < kHot; ++h) policy.written(kBase + h * kPage); + std::size_t copied = 0; + std::uintptr_t prev = 0; + policy.collect([&](std::uintptr_t p) { + EXPECT(p > prev); // delivered in address order + prev = p; + ++copied; + }); + EXPECT(copied == kHot); + policy.frame(); + } + EXPECT(policy.stats().hot == kHot && policy.stats().cold == kCold); + for (std::size_t h = 0; h < kHot; ++h) EXPECT(policy.hot(kBase + h * kPage)); + EXPECT(!policy.hot(kBase + kHot * kPage)); + // Steady-state benchmark: 50 submissions (collect + frame) with 100 hot + 10 cold writes each. + constexpr unsigned kIters = 50; + const auto t0 = std::chrono::steady_clock::now(); + for (unsigned it = 0; it < kIters; ++it) { + for (unsigned c = 0; c < 10; ++c) + policy.written(kBase + (kHot + ((it * 13 + c * 97) % kCold)) * kPage); + std::size_t copied = 0; + std::uintptr_t prev = 0; + policy.collect([&](std::uintptr_t p) { + EXPECT(p > prev); + prev = p; + ++copied; + }); + EXPECT(copied >= 10); // at least the 10 cold pages (hot pages may skip during probe wait) + policy.frame(); + } + const double ms = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + const double per_iter_ms = ms / double(kIters); + std::printf("scale (%zu cold + %zu hot): %.3f ms per collect+frame (%.2f ms for %u iters)\n", + kCold, kHot, per_iter_ms, ms, kIters); + EXPECT(per_iter_ms < 1.0); + // Stop writing the hot pages: they demote after a probe cycle, and removing pages updates stats cleanly. + for (unsigned f = 0; f < 2 * Policy::kProbe; ++f) { + policy.collect([&](std::uintptr_t) {}); + policy.frame(); + } + EXPECT(policy.stats().hot == 0 && policy.stats().cold == kTotal); + EXPECT(policy.stats().demotions >= kHot); + policy.remove(kBase, kBase + 50 * kPage); + EXPECT(policy.stats().cold == kTotal - 50); + } + { // submission-hot threshold: kPromote == 6 of 8 promotes, 5 of 8 stays cold + Fake f; + Policy policy(f); + f.policy = &policy; + policy.add(kBase, kBase + 2 * kPage); + policy.collect([&](std::uintptr_t p) { f.take(p); }); + // Page 0 written on 6 of 8 submissions; page 1 written on 5 of 8 submissions. + for (unsigned sub = 0; sub < 8; ++sub) { + if (sub != 2 && sub != 5) f.write(kBase + sub, std::uint8_t(sub + 1)); + if (sub != 1 && sub != 4 && sub != 7) f.write(kBase + kPage + sub, std::uint8_t(sub + 1)); + policy.collect([&](std::uintptr_t p) { f.take(p); }); + EXPECT(f.same(kBase) && f.same(kBase + kPage)); + policy.frame(); + } + EXPECT(Policy::kPromote == 6 && Policy::kHistory == 8); + EXPECT(policy.hot(kBase)); + EXPECT(!policy.hot(kBase + kPage)); + } + { // 1-write/frame pages stay cold across low-sub and high-sub frames: zero per-submission over-copying, + // zero copies on empty submissions, while truly intra-frame hot pages (6+/8 subs) promote cleanly. + Fake f; + Policy policy(f); + f.policy = &policy; + policy.add(kBase, kBase + 2 * kPage); + policy.collect([&](std::uintptr_t p) { f.take(p); }); + // 20 frames of 4 submissions/frame: page 0 written once per frame (sub 0), page 1 written every sub. + std::uint64_t p0_copies = 0, p0_empty_sub_copies = 0; + for (unsigned frame = 1; frame <= 20; ++frame) { + for (unsigned sub = 0; sub < 4; ++sub) { + const bool wrote_p0 = (sub == 0); + if (wrote_p0) f.write(kBase + frame, std::uint8_t(frame)); + f.write(kBase + kPage + sub, std::uint8_t(frame + sub)); + policy.collect([&](std::uintptr_t p) { + if (p == kBase) { + ++p0_copies; + if (!wrote_p0) ++p0_empty_sub_copies; + } + f.take(p); + }); + EXPECT(f.same(kBase) && f.same(kBase + kPage)); + policy.frame(); + } + } + EXPECT(!policy.hot(kBase)); // 1/frame (2 of 8 subs) never promotes to hot + EXPECT(policy.hot(kBase + kPage)); // written every sub: hot + EXPECT(p0_copies == 20); // copied strictly once per written submission + EXPECT(p0_empty_sub_copies == 0); // zero over-copying on empty submissions + } + { // batched arming: Guard with arm_batch() receives sorted pages in one call per collect(), handles partial refusal + struct BatchGuard { + std::set armed; + std::uintptr_t refuse_page = 0; + std::uint64_t single_arms = 0, batch_calls = 0, batch_pages = 0; + bool sorted_ok = true; + + bool arm(std::uintptr_t page) { + ++single_arms; + if (page == refuse_page) return false; + armed.insert(page); + return true; + } + void arm_batch(const std::uintptr_t* pages, std::uint8_t* results, std::size_t count) { + ++batch_calls; + batch_pages += count; + for (std::size_t i = 0; i < count; ++i) { + if (i > 0 && pages[i] <= pages[i - 1]) sorted_ok = false; + if (pages[i] == refuse_page) { + results[i] = 0; + } else { + armed.insert(pages[i]); + results[i] = 1; + } + } + } + void disarm(std::uintptr_t page) { armed.erase(page); } + } bg; + + leonida::TitleWritePolicy policy(bg); + policy.add(kBase, kBase + 16 * kPage); + bg.refuse_page = kBase + 5 * kPage; + std::vector copied; + policy.collect([&](std::uintptr_t p) { copied.push_back(p); }); + EXPECT(copied.size() == 16); + EXPECT(bg.single_arms == 0 && bg.batch_calls == 1 && bg.batch_pages == 16 && bg.sorted_ok); + EXPECT(policy.stats().batched_arm_calls == 1 && policy.stats().arm_failures == 1); + EXPECT(bg.armed.size() == 15 && !bg.armed.count(kBase + 5 * kPage)); + + // Next collect retries only the refused page (5) plus newly written pages (10, 2) in sorted order. + bg.refuse_page = 0; + policy.written(kBase + 10 * kPage); + policy.written(kBase + 2 * kPage); + copied.clear(); + policy.collect([&](std::uintptr_t p) { copied.push_back(p); }); + EXPECT(copied.size() == 3 && copied[0] == kBase + 2 * kPage && copied[1] == kBase + 5 * kPage && + copied[2] == kBase + 10 * kPage); + EXPECT(bg.batch_calls == 2 && bg.batch_pages == 19 && bg.sorted_ok); + EXPECT(bg.armed.size() == 16); + } + { // O(1) clean fast-path (has_pending_work) + unconditional disarm on hot promotion even when !p.armed + Fake f; + Policy policy(f); + f.policy = &policy; + policy.add(kBase, kBase + kPages * kPage); + EXPECT(policy.has_pending_work()); + policy.collect([&](std::uintptr_t p) { f.take(p); }); + EXPECT(!policy.has_pending_work()); // all 64 pages armed & clean: O(1) fast-path is false + + // A single write decays out of history_active_ over kHistory quiet submissions, then returns to clean. + f.write(kBase, 42); + EXPECT(policy.has_pending_work()); + policy.collect([&](std::uintptr_t p) { f.take(p); }); + EXPECT(f.same(kBase)); + for (unsigned sub = 0; sub < Policy::kHistory; ++sub) { + policy.frame(); + policy.collect([&](std::uintptr_t) {}); + } + EXPECT(!policy.hot(kBase)); + EXPECT(!policy.has_pending_work()); + + // Promote page 0 when a write lands AFTER collect() (so !p.armed at frame()): guard_.disarm() must still run. + for (unsigned sub = 0; sub < Policy::kPromote; ++sub) { + f.write(kBase + sub, std::uint8_t(sub + 1)); + policy.collect([&](std::uintptr_t p) { f.take(p); }); + if (sub + 1 == Policy::kPromote) f.write(kBase + 99, 77); // opens OS page -> p.armed == false + policy.frame(); + } + EXPECT(policy.hot(kBase)); + EXPECT(policy.has_pending_work()); + for (unsigned sub = 0; sub < 2 * Policy::kProbe; ++sub) { + policy.collect([&](std::uintptr_t p) { f.take(p); }); + policy.frame(); + } + EXPECT(!policy.hot(kBase)); + EXPECT(!policy.has_pending_work()); + std::puts("clean fast-path & unconditional disarm on hot promotion: ok"); + } + if (failures) return 1; + std::puts("title write policy: hot pages stop faulting, cold pages fault once an interval, nothing missed"); + return 0; +} diff --git a/runtime/test/vk_bindless_test.cpp b/runtime/test/vk_bindless_test.cpp index e81181849f..79b370095c 100644 --- a/runtime/test/vk_bindless_test.cpp +++ b/runtime/test/vk_bindless_test.cpp @@ -255,6 +255,9 @@ int main(int argc, char** argv) { enable12.descriptorBindingStorageImageUpdateAfterBind = device_flags.update_after_bind; enable12.descriptorBindingStorageBufferUpdateAfterBind = device_flags.update_after_bind; enable12.descriptorBindingPartiallyBound = device_flags.partially_bound; + enable12.vulkanMemoryModel = have12.vulkanMemoryModel; + enable12.vulkanMemoryModelDeviceScope = + have12.vulkanMemoryModel && have12.vulkanMemoryModelDeviceScope ? VK_TRUE : VK_FALSE; VkPhysicalDeviceFeatures2 enable{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &enable12}; enable.features.shaderInt64 = int64 ? VK_TRUE : VK_FALSE; enable.features.shaderSampledImageArrayDynamicIndexing = VK_TRUE; @@ -1378,6 +1381,135 @@ int main(int argc, char** argv) { std::printf("%s: no room past 5000 2D images and 2100 samplers on this device; step 9 skipped\n", name); } + // 13. O(1) free-list: storage vs high ranges, has_free_image, free_storage_images, total_free_images, + // image_refusal, held_images_ fast state, and shared-slot refcount + storage-upgrade semantics. + { + const std::uint32_t cap_1d = set.image_capacity(ImageDimension::dim_1d); + const std::uint32_t stor_1d = set.storage_capacity(ImageDimension::dim_1d); + const std::uint32_t total_before = set.total_free_images(); + EXPECT(set.free_images(ImageDimension::dim_1d) == cap_1d - 1); + EXPECT(set.free_storage_images(ImageDimension::dim_1d) == stor_1d - 1); + EXPECT(set.has_free_image(ImageDimension::dim_1d, true)); + EXPECT(set.has_free_image(ImageDimension::dim_1d, false)); + EXPECT(!set.has_free_image(ImageDimension::dim_1d_array, false)); + EXPECT(set.has_free_image(ImageDimension::dim_1d_array, true)); + + // Fill the entire 1D storage range [1, stor_1d) with storage views. + StorageViews dummy_storage{}; + dummy_storage.as_float = stored_view; + std::vector stor_indices; + stor_indices.reserve(stor_1d - 1); + for (std::uint32_t i = 1; i < stor_1d; ++i) { + const std::uint32_t idx = + set.add_image(ImageDimension::dim_1d, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_GENERAL, dummy_storage); + EXPECT(idx >= 1 && idx < stor_1d); + stor_indices.push_back(idx); + } + EXPECT(set.free_storage_images(ImageDimension::dim_1d) == 0); + EXPECT(!set.has_free_image(ImageDimension::dim_1d, true)); + EXPECT(set.add_image(ImageDimension::dim_1d, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_GENERAL, dummy_storage) == 0); + if (cap_1d > stor_1d) { + EXPECT(set.image_refusal(ImageDimension::dim_1d, true) == BindlessSet::ImageRefusal::storage_full); + EXPECT(set.has_free_image(ImageDimension::dim_1d, false)); + const std::uint32_t high_idx = + set.add_image(ImageDimension::dim_1d, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_GENERAL); + EXPECT(high_idx >= stor_1d && high_idx < cap_1d); + set.remove_image(ImageDimension::dim_1d, high_idx); + } else { + EXPECT(set.image_refusal(ImageDimension::dim_1d, true) == BindlessSet::ImageRefusal::array_full); + } + // Freeing one storage slot restores storage room and hands back that exact storage index. + const std::uint32_t freed_stor = stor_indices[stor_indices.size() / 2]; + set.remove_image(ImageDimension::dim_1d, freed_stor); + EXPECT(set.free_storage_images(ImageDimension::dim_1d) == 1); + EXPECT(set.has_free_image(ImageDimension::dim_1d, true)); + const std::uint32_t reused_stor = + set.add_image(ImageDimension::dim_1d, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_GENERAL, dummy_storage); + EXPECT(reused_stor == freed_stor); + EXPECT(set.free_storage_images(ImageDimension::dim_1d) == 0); + for (const std::uint32_t idx : stor_indices) set.remove_image(ImageDimension::dim_1d, idx); + EXPECT(set.free_storage_images(ImageDimension::dim_1d) == stor_1d - 1); + EXPECT(set.free_images(ImageDimension::dim_1d) == cap_1d - 1); + EXPECT(set.total_free_images() == total_before); + + // held_images_ fast state: removing while table_dirty_ holds the slot until flush() and keeps + // needs_prepare() true. + const std::uint32_t free_3d_before = set.free_images(ImageDimension::dim_3d); + const std::uint32_t held_idx = + set.add_image(ImageDimension::dim_3d, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_GENERAL); + EXPECT(held_idx != 0 && set.free_images(ImageDimension::dim_3d) == free_3d_before - 1); + DescriptorKey held_key = tsharp; + held_key[7] ^= 0x55AA1234u; + EXPECT(set.insert_key(held_key, held_idx, ImageDimension::dim_3d)); + set.remove_image(ImageDimension::dim_3d, held_idx); + EXPECT(set.free_images(ImageDimension::dim_3d) == free_3d_before - 1); // held while table_dirty_ + EXPECT(set.needs_prepare()); + EXPECT(set.erase_key(held_key)); + EXPECT(flush()); + set.table_upload_result(true); + set.release_retired(); + EXPECT(set.free_images(ImageDimension::dim_3d) == free_3d_before); + EXPECT(set.total_free_images() == total_before); + EXPECT(!set.needs_prepare()); + + // Shared ViewKey refcount + storage upgrade: two distinct T# keys share ONE sampled-only bindless index; + // upgrading key 1 to a storage slot keeps the old sampled-only slot alive for key 2 until key 2 leaves. + const std::uint32_t free_2d_before = set.free_images(ImageDimension::dim_2d); + const std::uint32_t shared_idx = + set.add_image(ImageDimension::dim_2d, gradient_view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); + EXPECT(shared_idx >= set.storage_capacity(ImageDimension::dim_2d)); + DescriptorKey shared_k1 = tsharp, shared_k2 = tsharp; + shared_k1[7] ^= 0x1010101u; + shared_k2[7] ^= 0x2020202u; + std::uint32_t shared_refcount = 0; + EXPECT(set.insert_key(shared_k1, shared_idx, ImageDimension::dim_2d)); + ++shared_refcount; + EXPECT(set.insert_key(shared_k2, shared_idx, ImageDimension::dim_2d)); + ++shared_refcount; + EXPECT(set.free_images(ImageDimension::dim_2d) == free_2d_before - 1); + EXPECT(flush()); + const auto draw_key = [&](const DescriptorKey& key) { + std::memcpy(static_cast(heap_map) + table_va, key.data(), 32); + return draw(); + }; + CHECK(draw_key(shared_k1)); + compare("13a shared ViewKey k1", nullptr); + CHECK(draw_key(shared_k2)); + compare("13b shared ViewKey k2", nullptr); + + // Upgrade shared_k1 to a storage-capable index: shared_idx stays alive for shared_k2 (refcount 2 -> 1). + StorageViews upgrade_storage{}; + upgrade_storage.as_float = stored_view; + const std::uint32_t upgrade_idx = + set.add_image(ImageDimension::dim_2d, stored_view, VK_IMAGE_LAYOUT_GENERAL, upgrade_storage); + EXPECT(upgrade_idx >= 1 && upgrade_idx < set.storage_capacity(ImageDimension::dim_2d)); + EXPECT(set.insert_key(shared_k1, upgrade_idx, ImageDimension::dim_2d)); + --shared_refcount; + EXPECT(shared_refcount == 1); + EXPECT(flush()); + const float blue_pixel[4] = {0, 0, 128.0f / 255.0f, 1}; + CHECK(draw_key(shared_k1)); + compare("13c upgraded k1 reads storage slot", blue_pixel); + CHECK(draw_key(shared_k2)); + compare("13d peer k2 keeps shared sampled slot", nullptr); + + // Release shared_k2: refcount hits 0, releasing shared_idx while upgraded shared_k1 stays live. + EXPECT(set.erase_key(shared_k2)); + if (--shared_refcount == 0) set.remove_image(ImageDimension::dim_2d, shared_idx); + EXPECT(flush()); + EXPECT(set.free_images(ImageDimension::dim_2d) == free_2d_before - 1); // only upgrade_idx remains + CHECK(draw_key(shared_k2)); + compare("13e removed k2 reads fallback", zeros); + CHECK(draw_key(shared_k1)); + compare("13f upgraded k1 still live", blue_pixel); + + EXPECT(set.erase_key(shared_k1)); + set.remove_image(ImageDimension::dim_2d, upgrade_idx); + EXPECT(flush()); + EXPECT(set.free_images(ImageDimension::dim_2d) == free_2d_before); + std::memcpy(static_cast(heap_map) + table_va, tsharp.data(), 32); + } + std::printf("%s: descriptor table in %s memory\n", name, set.table_in_device_local_memory() ? "device-local" : "host-visible"); std::printf("%s: gradient at the %uth slot probed, miss, table grown %u -> %u slots, rebound, restored, " diff --git a/runtime/test/vk_compute_test.cpp b/runtime/test/vk_compute_test.cpp index 8cc6a2a2f4..cfaa23caf3 100644 --- a/runtime/test/vk_compute_test.cpp +++ b/runtime/test/vk_compute_test.cpp @@ -338,6 +338,8 @@ static int run(int argc, char** argv) { f12.bufferDeviceAddress = VK_TRUE; f12.shaderBufferInt64Atomics = int64_atomics ? VK_TRUE : VK_FALSE; f12.shaderSharedInt64Atomics = int64_atomics && f12q.shaderSharedInt64Atomics ? VK_TRUE : VK_FALSE; + f12.vulkanMemoryModel = f12q.vulkanMemoryModel; + f12.vulkanMemoryModelDeviceScope = f12q.vulkanMemoryModel && f12q.vulkanMemoryModelDeviceScope ? VK_TRUE : VK_FALSE; if (f13q.subgroupSizeControl || require_wave64) { f13.subgroupSizeControl = f13q.subgroupSizeControl; f13.computeFullSubgroups = require_wave64 || observed_full ? VK_TRUE : VK_FALSE; diff --git a/runtime/test/vk_device_markers_test.cpp b/runtime/test/vk_device_markers_test.cpp index f6e76fd739..54c28a9311 100644 --- a/runtime/test/vk_device_markers_test.cpp +++ b/runtime/test/vk_device_markers_test.cpp @@ -1,8 +1,9 @@ // The AMD breadcrumbs of the device-fault report (src/vulkan_device_markers.h, LEONIDA_DEVICE_MARKERS=1) on a real // device: dispatches recorded through CheckpointRecorder with the markers on, submitted and waited for, leave their // queue's started and finished markers at the last dispatch's seq, and the report calls none of them hung. Two -// submissions, so the second continues the first one's numbering. The shader is an empty hand-written compute -// program; nothing is meant to fault or hang. SKIP (77) without a Vulkan device or without VK_AMD_buffer_marker. +// submissions, so the second continues the first one's numbering; a third adds draw markers outside and inside a +// dynamic-rendering scope and the report names the last draw. The shader is an empty hand-written compute program; +// nothing is meant to fault or hang. SKIP (77) without a Vulkan device or without VK_AMD_buffer_marker. // LEONIDA_VK_VALIDATION=1 runs it under VK_LAYER_KHRONOS_validation (any validation error fails the test). #include "vk_test_device.h" #include "../src/vulkan_device_fault.h" @@ -10,6 +11,7 @@ #include #include #include +#include #include #define EXPECT(condition) do { \ @@ -116,6 +118,48 @@ int run(vktest::Device& d) { EXPECT(slot.started == last_seq && slot.finished == last_seq); EXPECT(diagnostics.report_markers(false).empty()); } + + // Draw markers, as the replay writes them: one pair outside a rendering scope (the replay's own draws) and one + // inside an open dynamic-rendering scope (the legacy indirect path draws in the caller's), which + // VK_AMD_buffer_marker allows. No draw call is needed for the markers; the scope has no attachments. + const auto begin_rendering = d.fn("vkCmdBeginRendering"); + const auto end_rendering = d.fn("vkCmdEndRendering"); + EXPECT(begin_rendering && end_rendering); + auto submission = diagnostics.begin_submission(diagnostics.next_execute_call(), d.queue, "direct", 1); + const CheckpointRecorder recorder{nullptr, submission, diagnostics.pipeline_names, 0}; + const std::uintptr_t graphics_id = pipeline_id + 1; + diagnostics.pipeline_names[graphics_id] = {"vs_marker_test", nullptr, "ps_marker_test"}; + const bool ran = d.run([&](VkCommandBuffer cb) { + recorder.dispatch(cb, 0, pipeline.pipeline, pipeline_id, roots, {1, 1, 1}); // seq 9 + bind(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline.pipeline); + dispatch(cb, 1, 1, 1); + recorder.dispatched(cb); + recorder.draw(cb, 1, graphics_id, marked_draw::indexed, {6, 1, 0}); // seq 10, outside a scope + recorder.drawn(cb); + VkRenderingInfo rendering{VK_STRUCTURE_TYPE_RENDERING_INFO}; + rendering.renderArea = {{0, 0}, {16, 16}}; + rendering.layerCount = 1; + begin_rendering(cb, &rendering); + recorder.draw(cb, 2, graphics_id, marked_draw::indirect, {4, 16, 0}); // seq 11, inside the scope + recorder.drawn(cb); + end_rendering(cb); + return true; + }); + EXPECT(ran); + EXPECT(submission.marked.size() == 3 && submission.marked.back().seq == last_seq + 3); + diagnostics.publish(std::move(submission)); + const MarkerSlot slot = diagnostics.marker_slot(d.queue); + std::printf("draws: started=%u finished=%u, last seq %llu\n", slot.started, slot.finished, + static_cast(last_seq + 3)); + EXPECT(slot.started == last_seq + 3 && slot.finished == last_seq + 3); + std::string text; + EXPECT(diagnostics.report_markers(false, &text).empty()); + EXPECT(text.find(" finished: seq=" + std::to_string(last_seq + 3) + " ") != std::string::npos); + EXPECT(text.find("command=2 draw=vertices-indirect max=4 stride=16 pipeline=vs vs_marker_test ps ps_marker_test") != + std::string::npos); + const std::string fault = diagnostics.marker_fault_draws(); + EXPECT(fault.find("last started draw (device-markers): seq=" + std::to_string(last_seq + 3)) != std::string::npos && + fault.find("(finished)") != std::string::npos); return 0; } diff --git a/runtime/test/vk_gpu_profile_test.cpp b/runtime/test/vk_gpu_profile_test.cpp new file mode 100644 index 0000000000..f2c0d2800c --- /dev/null +++ b/runtime/test/vk_gpu_profile_test.cpp @@ -0,0 +1,362 @@ +// LEONIDA_GPU_PROFILE (runtime/src/vulkan_gpu_profile.h): known dispatches and draws go through VulkanQueue with the +// profile on, and each pipeline must come back under its name with its call count, its runs and a GPU time that is +// above zero and grows with its work; the submission's span covers what the pipelines were given. Then the same +// short dispatches run with the profile off and on, and the difference per timestamp is printed (not checked). No +// game data. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation; any validation error fails it. +#include "vk_test_device.h" +#include "../src/vulkan_backend.h" + +#include +#include +#include +#include +#include +#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 namespace leonida; +using Kind = VulkanQueue::QueueKind; + +constexpr std::uint32_t kGroups = 64; // 64 x 64 invocations a dispatch +constexpr std::uint32_t kHeavyTurns = 20000, kLightTurns = 300, kVertexTurns = 4000; +constexpr std::uint32_t kVertices = 3 * 2048; +constexpr std::uintptr_t kHeavy = 0x1001, kLight = 0x1002, kDraw = 0x2001; + +std::vector read_words(const char* path) { + std::ifstream file(path, std::ios::binary | std::ios::ate); + const std::streamoff bytes = file.tellg(); + if (bytes <= 0 || bytes % 4 != 0) return {}; + std::vector words(static_cast(bytes) / 4); + file.seekg(0); + if (!file.read(reinterpret_cast(words.data()), bytes)) return {}; + return words; +} + +struct Fixture { + vktest::Device& d; + VkShaderModule cs = VK_NULL_HANDLE, vs = VK_NULL_HANDLE; + VkDescriptorSetLayout set_layout = VK_NULL_HANDLE; + VkDescriptorPool pool = VK_NULL_HANDLE; + VkDescriptorSet set = VK_NULL_HANDLE; + VkPipelineLayout compute_layout = VK_NULL_HANDLE, graphics_layout = VK_NULL_HANDLE; + VkPipeline compute = VK_NULL_HANDLE, graphics = VK_NULL_HANDLE; + + ~Fixture() { + if (graphics) d.fn("vkDestroyPipeline")(d.device, graphics, nullptr); + if (compute) d.fn("vkDestroyPipeline")(d.device, compute, nullptr); + const auto destroy_layout = d.fn("vkDestroyPipelineLayout"); + if (graphics_layout) destroy_layout(d.device, graphics_layout, nullptr); + if (compute_layout) destroy_layout(d.device, compute_layout, nullptr); + if (pool) d.fn("vkDestroyDescriptorPool")(d.device, pool, nullptr); + if (set_layout) + d.fn("vkDestroyDescriptorSetLayout")(d.device, set_layout, nullptr); + const auto destroy_shader = d.fn("vkDestroyShaderModule"); + if (vs) destroy_shader(d.device, vs, nullptr); + if (cs) destroy_shader(d.device, cs, nullptr); + } + + VkShaderModule module(const char* path) { + const auto words = read_words(path); + if (words.empty()) return VK_NULL_HANDLE; + VkShaderModuleCreateInfo info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + info.codeSize = words.size() * 4; + info.pCode = words.data(); + VkShaderModule m = VK_NULL_HANDLE; + return d.fn("vkCreateShaderModule")(d.device, &info, nullptr, &m) == VK_SUCCESS + ? m : VK_NULL_HANDLE; + } + + bool create(const char* compute_path, const char* vertex_path, VkBuffer results) { + cs = module(compute_path); + vs = module(vertex_path); + if (!cs || !vs) return false; + const VkDescriptorSetLayoutBinding binding{0, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, + nullptr}; + VkDescriptorSetLayoutCreateInfo set_info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; + set_info.bindingCount = 1; + set_info.pBindings = &binding; + if (d.fn("vkCreateDescriptorSetLayout")(d.device, &set_info, nullptr, + &set_layout) != VK_SUCCESS) + return false; + const VkDescriptorPoolSize size{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}; + VkDescriptorPoolCreateInfo pool_info{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; + pool_info.maxSets = 1; + pool_info.poolSizeCount = 1; + pool_info.pPoolSizes = &size; + if (d.fn("vkCreateDescriptorPool")(d.device, &pool_info, nullptr, &pool) != + VK_SUCCESS) + return false; + VkDescriptorSetAllocateInfo alloc{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; + alloc.descriptorPool = pool; + alloc.descriptorSetCount = 1; + alloc.pSetLayouts = &set_layout; + if (d.fn("vkAllocateDescriptorSets")(d.device, &alloc, &set) != VK_SUCCESS) + return false; + const VkDescriptorBufferInfo buffer{results, 0, VK_WHOLE_SIZE}; + VkWriteDescriptorSet write{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET}; + write.dstSet = set; + write.descriptorCount = 1; + write.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + write.pBufferInfo = &buffer; + d.fn("vkUpdateDescriptorSets")(d.device, 1, &write, 0, nullptr); + + const VkPushConstantRange compute_range{VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(ShaderUserData)}; + VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; + layout_info.setLayoutCount = 1; + layout_info.pSetLayouts = &set_layout; + layout_info.pushConstantRangeCount = 1; + layout_info.pPushConstantRanges = &compute_range; + const auto create_layout = d.fn("vkCreatePipelineLayout"); + if (create_layout(d.device, &layout_info, nullptr, &compute_layout) != VK_SUCCESS) return false; + const VkPushConstantRange vertex_range{VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(ShaderUserData)}; + layout_info.setLayoutCount = 0; + layout_info.pSetLayouts = nullptr; + layout_info.pPushConstantRanges = &vertex_range; + if (create_layout(d.device, &layout_info, nullptr, &graphics_layout) != VK_SUCCESS) return false; + + VkComputePipelineCreateInfo compute_info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; + compute_info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, nullptr, 0, + VK_SHADER_STAGE_COMPUTE_BIT, cs, "main"}; + compute_info.layout = compute_layout; + if (d.fn("vkCreateComputePipelines")(d.device, VK_NULL_HANDLE, 1, &compute_info, + nullptr, &compute) != VK_SUCCESS) + return false; + + // A vertex stage only, no attachments: the replay sizes the rendering by the viewport. + const VkPipelineShaderStageCreateInfo stage{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, nullptr, 0, + VK_SHADER_STAGE_VERTEX_BIT, vs, "main"}; + const VkPipelineVertexInputStateCreateInfo vi{VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO}; + VkPipelineInputAssemblyStateCreateInfo ia{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO}; + ia.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; + VkPipelineViewportStateCreateInfo viewport{VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO}; + viewport.viewportCount = viewport.scissorCount = 1; + VkPipelineRasterizationStateCreateInfo raster{VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO}; + raster.lineWidth = 1; + VkPipelineMultisampleStateCreateInfo ms{VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO}; + ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; + const VkPipelineColorBlendStateCreateInfo blend{VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO}; + const VkPipelineDepthStencilStateCreateInfo depth{VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO}; + const VkPipelineRenderingCreateInfo rendering{VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO}; + // What the replay sets at every draw (emit_commands). + const VkDynamicState states[] = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR, + VK_DYNAMIC_STATE_PRIMITIVE_TOPOLOGY, VK_DYNAMIC_STATE_PRIMITIVE_RESTART_ENABLE, + VK_DYNAMIC_STATE_STENCIL_REFERENCE, VK_DYNAMIC_STATE_BLEND_CONSTANTS}; + VkPipelineDynamicStateCreateInfo dynamic{VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO}; + dynamic.dynamicStateCount = std::uint32_t(std::size(states)); + dynamic.pDynamicStates = states; + VkGraphicsPipelineCreateInfo info{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, &rendering}; + info.stageCount = 1; + info.pStages = &stage; + info.pVertexInputState = &vi; + info.pInputAssemblyState = &ia; + info.pViewportState = &viewport; + info.pRasterizationState = &raster; + info.pMultisampleState = &ms; + info.pDepthStencilState = &depth; + info.pColorBlendState = &blend; + info.pDynamicState = &dynamic; + info.layout = graphics_layout; + return d.fn("vkCreateGraphicsPipelines")(d.device, VK_NULL_HANDLE, 1, &info, + nullptr, &graphics) == VK_SUCCESS; + } +}; + +Dispatch dispatch(std::uintptr_t pipeline, std::uint32_t turns, std::uint32_t groups = kGroups) { + Dispatch d{}; + d.pipeline = pipeline; + d.user_data[0] = turns; + d.x = groups; + d.y = d.z = 1; + return d; +} + +Draw draw() { + Draw d{}; + d.pipeline = kDraw; + d.user_data[0] = kVertexTurns; + d.topology = 4; // D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST + d.viewport = {0, 0, 64, 64, 0, 1}; + d.scissor = {0, 0, 64, 64}; + d.count = kVertices; + d.instances = 1; + return d; +} + +const gpu_profile::Profiler::Entry* find(const std::vector& entries, const char* label) { + for (const auto& e : entries) + if (e.label == label) return &e; + return nullptr; +} + +// Waits until the fence thread has read `count` submissions of the direct queue. +bool resolved(VulkanContext& context, std::uint64_t count) { + const auto until = std::chrono::steady_clock::now() + std::chrono::seconds(10); + while (context.gpu_profile().queue(0).submissions < count) { + if (std::chrono::steady_clock::now() > until) return false; + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + return true; +} + +int check_labels() { + gpu_profile::Key key; + key.kind = gpu_profile::Kind::mesh; + key.names = {"a/b/mesh_main", nullptr, "c/pixel_main"}; + EXPECT(gpu_profile::label(key) == "ms mesh_main ps pixel_main"); + key.kind = gpu_profile::Kind::graphics; + key.names = {"vertex_main", "geometry_main", nullptr}; + EXPECT(gpu_profile::label(key) == "vs vertex_main gs geometry_main"); + key.kind = gpu_profile::Kind::compute; + key.names = {"x/compute_main", nullptr, nullptr}; + EXPECT(gpu_profile::label(key) == "cs compute_main"); + key.names = {}; + key.id = 0xabc; + EXPECT(gpu_profile::label(key) == "pso 0xabc"); + std::printf("labels: by stage names, else by id\n"); + return 0; +} + +} // namespace + +int main(int argc, char** argv) { + if (argc < 3) { + std::fprintf(stderr, "usage: vk_gpu_profile_test \n"); + return 2; + } + if (check_labels()) return 1; + gpu_profile::set_enabled_for_test(true); // before the context, which loads the query functions only then + + vktest::Device d; + if (!d.create()) { + std::printf("SKIP: no usable Vulkan device\n"); + return 77; + } + const std::uint32_t bits = d.families[d.family].timestampValidBits; + VkPhysicalDeviceProperties properties{}; + d.instance_fn("vkGetPhysicalDeviceProperties")(d.physical, &properties); + if (!bits || properties.limits.timestampPeriod <= 0) { + std::printf("SKIP: the graphics family writes no timestamps\n"); + return 77; + } + std::printf("device: %s, timestamps %u bits, %.3f ns a tick\n", properties.deviceName, bits, + properties.limits.timestampPeriod); + + void* mapped = nullptr; + const VkBuffer results = d.buffer(VkDeviceSize(kGroups) * 64 * 4, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &mapped); + EXPECT(results); + Fixture fixture{d}; + EXPECT(fixture.create(argv[1], argv[2], results)); + + VulkanContext context(d.device_proc, d.device, true); + EXPECT(context.loaded()); + context.set_timestamp_period(properties.limits.timestampPeriod); + std::vector family_bits; + for (const auto& family : d.families) family_bits.push_back(family.timestampValidBits); + context.set_timestamp_bits(family_bits); + // One VkPipeline under two PSO ids and names: what each does is its user data's loop count. + ComputePipeline compute{fixture.compute, fixture.compute_layout, 0, fixture.set}; + context.add_pipeline(kHeavy, compute, "profile_test/heavy"); + context.add_pipeline(kLight, compute, "profile_test/light"); + GraphicsPipeline graphics; + graphics.pipeline = fixture.graphics; + graphics.layout = fixture.graphics_layout; + graphics.push_stages = VK_SHADER_STAGE_VERTEX_BIT; + const CheckpointShaders draw_names{"profile_test/spin_vertices", nullptr, nullptr}; + context.add_graphics_pipeline(kDraw, graphics, &draw_names); + VulkanQueue direct(context, d.queue, d.family, Kind::direct); + EXPECT(direct.ok()); + + // heavy x3, a UAV barrier, light x2, draw x4, heavy x1: heavy in two runs, the others in one each. + CommandList list; + for (int i = 0; i < 3; ++i) EXPECT(list.dispatch(dispatch(kHeavy, kHeavyTurns))); + EXPECT(list.uav_barrier({0})); + for (int i = 0; i < 2; ++i) EXPECT(list.dispatch(dispatch(kLight, kLightTurns))); + for (int i = 0; i < 4; ++i) EXPECT(list.draw(draw())); + EXPECT(list.dispatch(dispatch(kHeavy, kHeavyTurns))); + EXPECT(list.close()); + const CommandList* lists[] = {&list}; + EXPECT(direct.execute(lists) == ReplayResult::success); + EXPECT(direct.idle()); + EXPECT(resolved(context, 1)); + + const auto entries = context.gpu_profile().snapshot(); + const auto queue = context.gpu_profile().queue(0); + for (const auto& e : entries) + std::printf(" %-28s %-8s %3llu calls in %llu runs, %.4f ms, %.4f ms per call\n", e.label.c_str(), + gpu_profile::kind_name(e.key.kind), static_cast(e.calls), + static_cast(e.runs), e.ms, e.ms / double(e.calls)); + std::printf(" queue: %llu submissions, %llu timestamps, busy %.4f ms, span %.4f ms, pipelines %.4f ms, " + "other %.4f ms\n", + static_cast(queue.submissions), static_cast(queue.stamps), + queue.busy_ms, queue.span_ms, queue.pipelines_ms, queue.other_ms); + EXPECT(entries.size() == 3); + const auto* heavy = find(entries, "cs heavy"); + const auto* light = find(entries, "cs light"); + const auto* vertices = find(entries, "vs spin_vertices"); + EXPECT(heavy && light && vertices); + EXPECT(heavy->key.kind == gpu_profile::Kind::compute && light->key.kind == gpu_profile::Kind::compute); + EXPECT(vertices->key.kind == gpu_profile::Kind::graphics); + EXPECT(heavy->calls == 4 && heavy->runs == 2); + EXPECT(light->calls == 2 && light->runs == 1); + EXPECT(vertices->calls == 4 && vertices->runs == 1); + // Apple Paravirtual GPUs (macOS VM runners under MoltenVK) advertise 64-bit timestamps and resolve all queries, + // but return constant timestamps within a command buffer (span == 0.0 ms). Verify all structural/query counts + // everywhere, and enforce positive-duration and relative-scaling checks whenever timestamps tick (or on any + // non-paravirtual device). + const bool paravirtual_constant_ts = + queue.span_ms == 0.0 && std::strstr(properties.deviceName, "Paravirtual") != nullptr; + if (paravirtual_constant_ts) { + std::printf("note: %s returned constant timestamps (span 0.0 ms); skipping positive-duration checks\n", + properties.deviceName); + } else { + for (const auto* e : {heavy, light, vertices}) EXPECT(e->ms > 0 && e->ms < 2000); + // 66 times the loop: well over twice the time per call, whatever the fixed cost of a dispatch is here. + EXPECT(heavy->ms / 4 > 2 * (light->ms / 2)); + } + // Start, before heavy, after its first run (the barrier), before light, the draws and heavy, end: 7, all read. + EXPECT(queue.submissions == 1 && queue.unread == 0 && queue.dropped == 0 && queue.stamps == 7); + // Consecutive intervals: the pipelines and the other work add up to the span. + EXPECT(queue.pipelines_ms <= queue.span_ms + 1e-6); + EXPECT(queue.pipelines_ms + queue.other_ms <= queue.span_ms * 1.0001 + 1e-6); + EXPECT(queue.pipelines_ms + queue.other_ms >= queue.span_ms * 0.9999 - 1e-6); + context.gpu_profile().report_now(); // the lines' format, on stderr + + // The cost: 2048 one-group dispatches alternating between two pipelines (a run boundary, so a timestamp, at each), + // submitted and waited for with the profile off and on; the best of five each. + CommandList churn; + for (int i = 0; i < 2048; ++i) EXPECT(churn.dispatch(dispatch(i % 2 ? kLight : kHeavy, 1, 1))); + EXPECT(churn.close()); + const CommandList* churn_lists[] = {&churn}; + const auto best = [&](bool on) { + gpu_profile::set_enabled_for_test(on); + double least = 1e30; + for (int round = 0; round < 5; ++round) { + const auto start = std::chrono::steady_clock::now(); + if (direct.execute(churn_lists) != ReplayResult::success || !direct.idle()) return -1.0; + least = std::min(least, std::chrono::duration(std::chrono::steady_clock::now() - + start).count()); + } + return least; + }; + const double off_ms = best(false), on_ms = best(true); + EXPECT(off_ms >= 0 && on_ms >= 0); + gpu_profile::set_enabled_for_test(true); + EXPECT(resolved(context, 5)); // report_now() started a new window + std::printf("cost: 2048 dispatches %.3f ms off, %.3f ms on (%.2f us per timestamp, submit to idle)\n", off_ms, + on_ms, (on_ms - off_ms) * 1000.0 / 2049.0); + + if (d.validation) { + std::printf("validation errors: %u\n", d.validation_errors()); + EXPECT(d.validation_errors() == 0); + } + std::printf("vk_gpu_profile_test: OK\n"); + return 0; +} diff --git a/runtime/test/vk_harness.cpp b/runtime/test/vk_harness.cpp index 872e30b936..2ef50099f8 100644 --- a/runtime/test/vk_harness.cpp +++ b/runtime/test/vk_harness.cpp @@ -436,6 +436,12 @@ int main(int argc, char** argv) { chain = &f13; } VkPhysicalDeviceVulkan12Features f12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; + bool enable_f12 = false; + if (f12q.vulkanMemoryModel) { + f12.vulkanMemoryModel = VK_TRUE; + f12.vulkanMemoryModelDeviceScope = f12q.vulkanMemoryModelDeviceScope; + enable_f12 = true; + } if (need_heap || mesh_compute) { // 77 is the "this device cannot run the test" code that check.py and run_gpu_tests.py report as SKIP. if (!f12q.bufferDeviceAddress) { @@ -452,6 +458,9 @@ int main(int argc, char** argv) { f12.runtimeDescriptorArray = VK_TRUE; f12.descriptorIndexing = VK_TRUE; } + enable_f12 = true; + } + if (enable_f12) { f12.pNext = chain; chain = &f12; } diff --git a/runtime/test/vk_heap_alias_test.cpp b/runtime/test/vk_heap_alias_test.cpp new file mode 100644 index 0000000000..296c98c249 --- /dev/null +++ b/runtime/test/vk_heap_alias_test.cpp @@ -0,0 +1,318 @@ +// A console descriptor heap read in place through the GPU address arena (docs/d3d12_vulkan.md section 3.4): the +// title's heap pages have one GPU home in the page mirror (src/title_mirror.h: sparse buffers at heap_base + the +// title's address), but 25,865 of the corpus's 26,503 shaders keep only the low 32 bits of a descriptor-table pointer, +// so the heap must also be readable at heap_base + an offset below 4 GiB, inside the sparse arena. This checks the +// mechanism on a real device, with no shader and no game data: one VkDeviceMemory bound into two sparse aliased +// buffers (a "mirror chunk" at the title's offset and the "arena" at the heap's offset) shows the same bytes through +// both - what the CPU writes into the home, and what the GPU writes through either buffer - and the arena's pages after +// the heap, which nothing is bound to, read zero (the null-slot guard without memory). Unbinding the mirror's view +// leaves the arena's view intact. +// Exit code 77 (skipped) on a device without sparse aliased buffers with strict residency. LEONIDA_VK_VALIDATION=1 runs +// it under VK_LAYER_KHRONOS_validation. +#define VK_NO_PROTOTYPES +#include "../src/arena_backing.h" + +#include +#include +#include +#include +#ifdef _WIN32 +#include +#else +#include +#endif + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +namespace { + +constexpr VkDeviceSize kMiB = 1 << 20; +constexpr VkDeviceSize kBuffer = 64 * kMiB; +constexpr VkDeviceSize kTitle = 40 * kMiB; // where the heap's pages lie in the mirror chunk +constexpr VkDeviceSize kHeap = 8 * kMiB; // where shaders read the heap in the arena +constexpr std::uint32_t kPages = 4; + +#define FUNCTIONS(X) \ + X(vkEnumeratePhysicalDevices) X(vkGetPhysicalDeviceProperties) X(vkGetPhysicalDeviceFeatures2) \ + X(vkGetPhysicalDeviceQueueFamilyProperties) X(vkGetPhysicalDeviceMemoryProperties) X(vkCreateDevice) \ + X(vkDestroyInstance) +#define DEVICE_FUNCTIONS(X) \ + X(vkDestroyDevice) X(vkGetDeviceQueue) X(vkCreateBuffer) X(vkDestroyBuffer) X(vkGetBufferMemoryRequirements) \ + X(vkAllocateMemory) X(vkFreeMemory) X(vkMapMemory) X(vkBindBufferMemory) X(vkQueueBindSparse) \ + X(vkQueueWaitIdle) X(vkCreateCommandPool) X(vkDestroyCommandPool) X(vkAllocateCommandBuffers) \ + X(vkBeginCommandBuffer) X(vkEndCommandBuffer) X(vkCmdCopyBuffer) X(vkCmdFillBuffer) X(vkCmdPipelineBarrier) \ + X(vkQueueSubmit) X(vkDeviceWaitIdle) X(vkResetCommandBuffer) +#define DECLARE(name) PFN_##name name = nullptr; +FUNCTIONS(DECLARE) +DEVICE_FUNCTIONS(DECLARE) +#undef DECLARE + +struct Run { + VkInstance instance = VK_NULL_HANDLE; + VkDevice device = VK_NULL_HANDLE; + ~Run() { + if (device) { + vkDeviceWaitIdle(device); + vkDestroyDevice(device, nullptr); + } + if (instance) vkDestroyInstance(instance, nullptr); + } +}; + +int test() { +#ifdef _WIN32 + HMODULE library = LoadLibraryA("vulkan-1.dll"); + auto get_instance = library ? reinterpret_cast( + reinterpret_cast(GetProcAddress(library, "vkGetInstanceProcAddr"))) + : nullptr; +#else + void* library = dlopen("libvulkan.so.1", RTLD_NOW); + auto get_instance = + library ? reinterpret_cast(dlsym(library, "vkGetInstanceProcAddr")) : nullptr; +#endif + if (!get_instance) { + std::puts("SKIP: no Vulkan loader"); + return 77; + } + Run run; + auto create_instance = reinterpret_cast(get_instance(nullptr, "vkCreateInstance")); + VkApplicationInfo app{VK_STRUCTURE_TYPE_APPLICATION_INFO}; + app.apiVersion = VK_API_VERSION_1_2; + VkInstanceCreateInfo instance_info{VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; + instance_info.pApplicationInfo = &app; + const char* layer = "VK_LAYER_KHRONOS_validation"; + const char* validation = std::getenv("LEONIDA_VK_VALIDATION"); + if (validation && *validation == '1') { + instance_info.enabledLayerCount = 1; + instance_info.ppEnabledLayerNames = &layer; + } + if (!create_instance || create_instance(&instance_info, nullptr, &run.instance) != VK_SUCCESS) { + std::puts("SKIP: no Vulkan instance"); + return 77; + } +#define LOAD(name) name = reinterpret_cast(get_instance(run.instance, #name)); + FUNCTIONS(LOAD) +#undef LOAD + std::uint32_t count = 1; + VkPhysicalDevice physical = VK_NULL_HANDLE; + vkEnumeratePhysicalDevices(run.instance, &count, &physical); // the first: as the loader orders them + if (!physical) { + std::puts("SKIP: no Vulkan device"); + return 77; + } + VkPhysicalDeviceProperties properties{}; + vkGetPhysicalDeviceProperties(physical, &properties); + VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; + vkGetPhysicalDeviceFeatures2(physical, &features); + std::fprintf(stderr, "device: %s (driver 0x%x)\n", properties.deviceName, properties.driverVersion); + if (!features.features.sparseBinding || !features.features.sparseResidencyBuffer || + !features.features.sparseResidencyAliased || !properties.sparseProperties.residencyNonResidentStrict || + properties.limits.sparseAddressSpaceSize < 2 * kBuffer) { + std::puts("SKIP: no sparse aliased buffers with strict residency on this device"); + return 77; + } + std::uint32_t family_count = 0; + vkGetPhysicalDeviceQueueFamilyProperties(physical, &family_count, nullptr); + std::vector families(family_count); + vkGetPhysicalDeviceQueueFamilyProperties(physical, &family_count, families.data()); + std::uint32_t work = UINT32_MAX; + for (std::uint32_t f = 0; f < family_count && work == UINT32_MAX; ++f) + if (families[f].queueFlags & VK_QUEUE_COMPUTE_BIT) work = f; + if (work == UINT32_MAX) { + std::puts("SKIP: no compute queue"); + return 77; + } + std::vector used(family_count, 0); + used[work] = 1; + const auto bind_queue = leonida::pick_arena_bind_queue(families.data(), family_count, used.data(), 16); + if (bind_queue.family == UINT32_MAX) { + std::puts("SKIP: no queue to spare for the binds"); + return 77; + } + const float priorities[2] = {1.0f, 1.0f}; + VkDeviceQueueCreateInfo queues[2] = {{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}, {VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}}; + queues[0].queueFamilyIndex = work; + queues[0].queueCount = bind_queue.family == work ? 2 : 1; + queues[0].pQueuePriorities = priorities; + queues[1].queueFamilyIndex = bind_queue.family; + queues[1].queueCount = 1; + queues[1].pQueuePriorities = priorities; + VkPhysicalDeviceFeatures2 enable{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; + enable.features.sparseBinding = VK_TRUE; + enable.features.sparseResidencyBuffer = VK_TRUE; + enable.features.sparseResidencyAliased = VK_TRUE; + VkDeviceCreateInfo device_info{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, &enable}; + device_info.queueCreateInfoCount = bind_queue.family == work ? 1 : 2; + device_info.pQueueCreateInfos = queues; + EXPECT(vkCreateDevice(physical, &device_info, nullptr, &run.device) == VK_SUCCESS); + auto get_device = reinterpret_cast(get_instance(run.instance, "vkGetDeviceProcAddr")); +#define LOAD(name) name = reinterpret_cast(get_device(run.device, #name)); + DEVICE_FUNCTIONS(LOAD) +#undef LOAD + const VkDevice device = run.device; + VkQueue work_queue = VK_NULL_HANDLE, binds = VK_NULL_HANDLE; + vkGetDeviceQueue(device, work, 0, &work_queue); + vkGetDeviceQueue(device, bind_queue.family, bind_queue.index, &binds); + + // The arena and a mirror chunk, both sparse and aliased, as the device makes them. + VkBufferCreateInfo sparse_info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; + sparse_info.flags = VK_BUFFER_CREATE_SPARSE_BINDING_BIT | VK_BUFFER_CREATE_SPARSE_RESIDENCY_BIT | + VK_BUFFER_CREATE_SPARSE_ALIASED_BIT; + sparse_info.size = kBuffer; + sparse_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | + VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; + VkBuffer arena = VK_NULL_HANDLE, mirror = VK_NULL_HANDLE; + EXPECT(vkCreateBuffer(device, &sparse_info, nullptr, &arena) == VK_SUCCESS); + EXPECT(vkCreateBuffer(device, &sparse_info, nullptr, &mirror) == VK_SUCCESS); + VkMemoryRequirements requirements{}; + vkGetBufferMemoryRequirements(device, arena, &requirements); + const VkDeviceSize page = requirements.alignment; + EXPECT(page && kTitle % page == 0 && kHeap % page == 0); + VkPhysicalDeviceMemoryProperties memory{}; + vkGetPhysicalDeviceMemoryProperties(physical, &memory); + const auto pick_type = [&](std::uint32_t bits) { + const VkMemoryPropertyFlags host = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; + for (const VkMemoryPropertyFlags want : {host | VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, host}) + for (std::uint32_t t = 0; t < memory.memoryTypeCount; ++t) + if ((bits >> t & 1) && (memory.memoryTypes[t].propertyFlags & want) == want) return t; + return UINT32_MAX; + }; + // The heap pages' one home. + VkMemoryAllocateInfo home_info{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; + home_info.allocationSize = page * kPages; + home_info.memoryTypeIndex = pick_type(requirements.memoryTypeBits); + EXPECT(home_info.memoryTypeIndex != UINT32_MAX); + VkDeviceMemory home = VK_NULL_HANDLE; + EXPECT(vkAllocateMemory(device, &home_info, nullptr, &home) == VK_SUCCESS); + void* home_host = nullptr; + EXPECT(vkMapMemory(device, home, 0, VK_WHOLE_SIZE, 0, &home_host) == VK_SUCCESS); + auto* words = static_cast(home_host); + + const auto bind = [&](VkBuffer buffer, VkDeviceSize at, VkDeviceMemory memory_or_null) { + VkSparseMemoryBind b{}; + b.resourceOffset = at; + b.size = page * kPages; + b.memory = memory_or_null; + const VkSparseBufferMemoryBindInfo buffer_bind{buffer, 1, &b}; + VkBindSparseInfo info{VK_STRUCTURE_TYPE_BIND_SPARSE_INFO}; + info.bufferBindCount = 1; + info.pBufferBinds = &buffer_bind; + return vkQueueBindSparse(binds, 1, &info, VK_NULL_HANDLE) == VK_SUCCESS && vkQueueWaitIdle(binds) == VK_SUCCESS; + }; + EXPECT(bind(mirror, kTitle, home)); + EXPECT(bind(arena, kHeap, home)); + + // Readback. + VkBufferCreateInfo readback_info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; + readback_info.size = 3 * page; + readback_info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT; + VkBuffer readback = VK_NULL_HANDLE; + EXPECT(vkCreateBuffer(device, &readback_info, nullptr, &readback) == VK_SUCCESS); + VkMemoryRequirements readback_requirements{}; + vkGetBufferMemoryRequirements(device, readback, &readback_requirements); + VkMemoryAllocateInfo readback_allocate{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; + readback_allocate.allocationSize = readback_requirements.size; + readback_allocate.memoryTypeIndex = pick_type(readback_requirements.memoryTypeBits); + VkDeviceMemory readback_memory = VK_NULL_HANDLE; + EXPECT(vkAllocateMemory(device, &readback_allocate, nullptr, &readback_memory) == VK_SUCCESS); + EXPECT(vkBindBufferMemory(device, readback, readback_memory, 0) == VK_SUCCESS); + void* readback_host = nullptr; + EXPECT(vkMapMemory(device, readback_memory, 0, VK_WHOLE_SIZE, 0, &readback_host) == VK_SUCCESS); + auto* got = static_cast(readback_host); + + VkCommandPoolCreateInfo pool_info{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; + pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; + pool_info.queueFamilyIndex = work; + VkCommandPool pool = VK_NULL_HANDLE; + EXPECT(vkCreateCommandPool(device, &pool_info, nullptr, &pool) == VK_SUCCESS); + VkCommandBufferAllocateInfo command_info{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; + command_info.commandPool = pool; + command_info.commandBufferCount = 1; + VkCommandBuffer commands = VK_NULL_HANDLE; + EXPECT(vkAllocateCommandBuffers(device, &command_info, &commands) == VK_SUCCESS); + // Records `body`, submits and waits. + const auto run_commands = [&](auto&& body) { + vkResetCommandBuffer(commands, 0); + VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; + vkBeginCommandBuffer(commands, &begin); + body(); + if (vkEndCommandBuffer(commands) != VK_SUCCESS) return false; + VkSubmitInfo info{VK_STRUCTURE_TYPE_SUBMIT_INFO}; + info.commandBufferCount = 1; + info.pCommandBuffers = &commands; + return vkQueueSubmit(work_queue, 1, &info, VK_NULL_HANDLE) == VK_SUCCESS && + vkQueueWaitIdle(work_queue) == VK_SUCCESS; + }; + const auto transfer_barrier = [&] { + VkMemoryBarrier barrier{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT; + vkCmdPipelineBarrier(commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1, &barrier, 0, + nullptr, 0, nullptr); + }; + + // The CPU writes descriptor-like words into the home: the arena's view and the mirror's show them; the arena page + // after the heap reads zero. + const std::size_t per_page = std::size_t(page / 4); + for (std::size_t i = 0; i < per_page * kPages; ++i) words[i] = std::uint32_t(i * 2654435761u) | 1u; + std::memset(got, 0xff, std::size_t(3 * page)); + EXPECT(run_commands([&] { + const VkBufferCopy from_arena[2] = {{kHeap + page, 0, page}, {kHeap + kPages * page, page, page}}; + vkCmdCopyBuffer(commands, arena, readback, 2, from_arena); + const VkBufferCopy from_mirror{kTitle + page, 2 * page, page}; + vkCmdCopyBuffer(commands, mirror, readback, 1, &from_mirror); + })); + for (std::size_t i = 0; i < per_page; ++i) { + EXPECT(got[i] == words[per_page + i]); + EXPECT(got[per_page + i] == 0); // the guard: nothing bound + EXPECT(got[2 * per_page + i] == words[per_page + i]); + } + + // The GPU writes through the mirror's view: the arena's view and the CPU's mapping show it; and the other way. + EXPECT(run_commands([&] { + vkCmdFillBuffer(commands, mirror, kTitle + 2 * page + 256, 256, 0xabcdef01u); + vkCmdFillBuffer(commands, arena, kHeap + 3 * page, 256, 0x01fedcbau); + transfer_barrier(); + const VkBufferCopy copies[2] = {{kHeap + 2 * page + 256, 0, 256}, {kHeap + 3 * page, 256, 256}}; + vkCmdCopyBuffer(commands, arena, readback, 1, &copies[0]); + const VkBufferCopy from_mirror{kTitle + 3 * page, 256, 256}; + vkCmdCopyBuffer(commands, mirror, readback, 1, &from_mirror); + })); + for (std::size_t i = 0; i < 64; ++i) { + EXPECT(got[i] == 0xabcdef01u && words[2 * per_page + 64 + i] == 0xabcdef01u); + EXPECT(got[64 + i] == 0x01fedcbau && words[3 * per_page + i] == 0x01fedcbau); + } + + // The page leaves the mirror (the title unmapped that view): the arena's view still shows the home, the mirror's + // reads zero. + EXPECT(bind(mirror, kTitle, VK_NULL_HANDLE)); + std::memset(got, 0xff, std::size_t(3 * page)); + EXPECT(run_commands([&] { + const VkBufferCopy from_arena{kHeap, 0, page}; + vkCmdCopyBuffer(commands, arena, readback, 1, &from_arena); + const VkBufferCopy from_mirror{kTitle, page, page}; + vkCmdCopyBuffer(commands, mirror, readback, 1, &from_mirror); + })); + for (std::size_t i = 0; i < per_page; ++i) { + EXPECT(got[i] == words[i]); + EXPECT(got[per_page + i] == 0); + } + + EXPECT(bind(arena, kHeap, VK_NULL_HANDLE)); + vkDeviceWaitIdle(device); + vkDestroyCommandPool(device, pool, nullptr); + vkDestroyBuffer(device, readback, nullptr); + vkFreeMemory(device, readback_memory, nullptr); + vkDestroyBuffer(device, arena, nullptr); + vkDestroyBuffer(device, mirror, nullptr); + vkFreeMemory(device, home, nullptr); + std::printf("vk_heap_alias_test: ok (one home in a mirror chunk and in the arena, %llu KiB pages)\n", + static_cast(page >> 10)); + return 0; +} + +} // namespace + +int main() { return test(); } diff --git a/runtime/test/vk_host_texture_order_test.cpp b/runtime/test/vk_host_texture_order_test.cpp index f7aae702f9..8b6e84a0e7 100644 --- a/runtime/test/vk_host_texture_order_test.cpp +++ b/runtime/test/vk_host_texture_order_test.cpp @@ -1,20 +1,21 @@ -// Title texture uploads must keep a queue submission from racing the host copy. +// A title texture upload (VulkanContext::write_staged_title_image) never waits for the GPU on the CPU: it hands the +// transfer every queue timeline value submitted so far, to wait for on the GPU, and keeps other submissions out while +// it reads the layouts and submits. Until 2026-11 it waited on the CPU for that work for at most 250 ms and skipped the +// write when the work was not done. #include "../src/vulkan_backend.h" #include #include +#include +#include namespace { unsigned waits = 0; -VkResult wait_result = VK_SUCCESS; -std::uint64_t last_timeout = 0; -// The writes wait for the queue timelines (vkWaitSemaphores, bounded), not for the device. -VkResult VKAPI_CALL wait_semaphores(VkDevice, const VkSemaphoreWaitInfo* info, std::uint64_t timeout) { +VkResult VKAPI_CALL wait_semaphores(VkDevice, const VkSemaphoreWaitInfo*, std::uint64_t) { ++waits; - last_timeout = timeout; - return info && info->semaphoreCount ? wait_result : VK_ERROR_UNKNOWN; + return VK_TIMEOUT; } -VkResult VKAPI_CALL device_idle(VkDevice) { return VK_ERROR_UNKNOWN; } // must not be called any more +VkResult VKAPI_CALL device_idle(VkDevice) { return VK_ERROR_UNKNOWN; } // must not be called PFN_vkVoidFunction VKAPI_CALL no_proc(VkDevice, const char*) { return nullptr; } } @@ -25,11 +26,14 @@ int main() { leonida::ResourceBinding binding{}; binding.image = reinterpret_cast(1); binding.mip_levels = 1; + binding.array_layers = 1; ctx.add_resource(1, binding, VK_IMAGE_LAYOUT_GENERAL); - ctx.add_resource(2, binding, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); + const VkImageSubresourceRange range{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; unsigned copies = 0; - const auto copy = [&] { + std::vector> seen; + const auto copy = [&](const leonida::ReplayFunctions&, const leonida::LayoutPieces& pieces, const auto& handed) { ++copies; + seen.assign(handed.begin(), handed.end()); bool raced = false; std::thread contender([&] { if (ctx.submit_mutex().try_lock()) { @@ -38,24 +42,26 @@ int main() { } }); contender.join(); - return !raced; + if (raced || pieces.empty() || pieces[0].layout != VK_IMAGE_LAYOUT_GENERAL) return VK_ERROR_UNKNOWN; + return VK_SUCCESS; }; - const auto progress = reinterpret_cast(std::uintptr_t{0x10}); - const auto submit = [&] { // a queue submission in flight: a retirement ticket, and image work pending + // Nothing submitted: nothing to wait for. + if (ctx.write_staged_title_image(1, range, copy) != VK_SUCCESS || copies != 1 || !seen.empty()) return 1; + const auto graphics = reinterpret_cast(std::uintptr_t{0x10}); + const auto compute = reinterpret_cast(std::uintptr_t{0x20}); + { // work in flight on two queues, which a CPU wait would time out on (wait_semaphores says VK_TIMEOUT) std::lock_guard lock(ctx.submit_mutex()); - ctx.record_submit_locked(progress, 1); - }; - submit(); - if (ctx.write_host_texture(2, 0, copy) != VK_NOT_READY || copies || waits) return 1; // wrong layout: no wait - if (ctx.write_host_texture(1, 0, copy) != VK_SUCCESS || copies != 1 || waits != 1) return 2; - if (last_timeout == 0 || last_timeout == UINT64_MAX) return 3; // bounded - if (ctx.write_host_texture(1, 0, copy) != VK_SUCCESS || copies != 2 || waits != 1) return 4; // wait reused - submit(); - wait_result = VK_TIMEOUT; // the submitted work is not done in time: skipped as not ready, not a failure - if (ctx.write_host_texture(1, 0, copy) != VK_NOT_READY || copies != 2 || waits != 2) return 5; - wait_result = VK_ERROR_DEVICE_LOST; - if (ctx.write_host_texture(1, 0, copy) != VK_ERROR_DEVICE_LOST || copies != 2 || waits != 3) return 6; - const auto stats = ctx.host_texture_stats(); - if (stats.copies != 2 || stats.waits != 3) return 7; - std::puts("ordered texture upload: layout, submit exclusion, bounded timeline wait, reuse, timeout, loss passed"); + ctx.record_submit_locked(graphics, 7); + ctx.record_submit_locked(compute, 3); + } + if (ctx.write_staged_title_image(1, range, copy) != VK_SUCCESS || copies != 2) return 2; // not skipped + if (waits) return 3; // no CPU wait + bool g = false, c = false; + for (const auto& [semaphore, value] : seen) { + g |= semaphore == graphics && value == 7; + c |= semaphore == compute && value == 3; + } + if (!g || !c) return 4; // the transfer waits for both queues' work on the GPU + if (ctx.write_staged_title_image(2, range, copy) != VK_ERROR_UNKNOWN || copies != 2) return 5; // unknown image + std::puts("title texture upload: no CPU wait, no skip, GPU waits for every queue's submitted work, submit exclusion"); } diff --git a/runtime/test/vk_pipeline_check.cpp b/runtime/test/vk_pipeline_check.cpp index 2cff5e4112..9e1a6aae99 100644 --- a/runtime/test/vk_pipeline_check.cpp +++ b/runtime/test/vk_pipeline_check.cpp @@ -1324,7 +1324,7 @@ int main(int argc, char** argv) { #endif } // Execution modes the translator declares (SignedZeroInfNanPreserve 32, and 64 with Float64; - // DenormPreserve 16) need a device property, not a feature. + // DenormPreserve 16; DenormFlushToZero 32) need a device property, not a feature. for (const auto& fc : meta.float_controls) { if (fc == "shaderSignedZeroInfNanPreserveFloat32") { if (!indexed.shaderSignedZeroInfNanPreserveFloat32) return "no " + fc; @@ -1332,6 +1332,8 @@ int main(int argc, char** argv) { if (!indexed.shaderSignedZeroInfNanPreserveFloat64) return "no " + fc; } else if (fc == "shaderDenormPreserveFloat16") { if (!indexed.shaderDenormPreserveFloat16) return "no " + fc; + } else if (fc == "shaderDenormFlushToZeroFloat32") { + if (!indexed.shaderDenormFlushToZeroFloat32) return "no " + fc; } else { return "unknown float control " + fc; } @@ -1349,8 +1351,15 @@ int main(int argc, char** argv) { if (feat == "shaderDrawParameters" && !f11.shaderDrawParameters) return "no shaderDrawParameters"; if (feat == "bufferDeviceAddress" && !f12.bufferDeviceAddress) return "no bufferDeviceAddress"; if (feat == "runtimeDescriptorArray" && !f12.runtimeDescriptorArray) return "no runtimeDescriptorArray"; + if (feat == "vulkanMemoryModel" && !f12.vulkanMemoryModel) return "no vulkanMemoryModel"; + if (feat == "vulkanMemoryModelDeviceScope" && + !(f12.vulkanMemoryModel && f12.vulkanMemoryModelDeviceScope)) + return "no vulkanMemoryModelDeviceScope"; if (feat == "shaderImageGatherExtended" && !f2.features.shaderImageGatherExtended) return "no shaderImageGatherExtended"; if (feat == "shaderResourceMinLod" && !f2.features.shaderResourceMinLod) return "no shaderResourceMinLod"; + if (feat == "shaderIntegerDotProduct" && + !(props.apiVersion >= VK_API_VERSION_1_3 && f13.shaderIntegerDotProduct)) + return "no shaderIntegerDotProduct"; if (props.apiVersion < VK_API_VERSION_1_3) { if (feat == "shaderStorageImageWriteWithoutFormat" && !f2.features.shaderStorageImageWriteWithoutFormat) return "no shaderStorageImageWriteWithoutFormat"; diff --git a/runtime/test/vk_sparse_bind_bench.cpp b/runtime/test/vk_sparse_bind_bench.cpp new file mode 100644 index 0000000000..7ef0ffdcfd --- /dev/null +++ b/runtime/test/vk_sparse_bind_bench.cpp @@ -0,0 +1,261 @@ +// What a page-sized sparse bind costs on this device: vkQueueBindSparse of N 64 KiB pages (contiguous in the buffer, +// scattered over one memory pool, as a remap of title pages would bind them), the time the call takes on the CPU and +// the time until its timeline semaphore is signalled, for N = 1 .. 4096; the same for unbinds; and the same page of +// memory bound at two buffer offsets (an aliased physical page). A measurement for the page mirror's layout, not a +// pass/fail test: it prints a table and exits 0 (77 when the device has no sparse buffers). Pick the device with +// MESA_VK_DEVICE_SELECT. No shaders, no game data. +#define VK_NO_PROTOTYPES +#include "../src/arena_backing.h" + +#include +#include +#include +#include +#include +#include +#include +#ifdef _WIN32 +#include +#else +#include +#endif + +namespace { + +constexpr VkDeviceSize kPage = 64 * 1024; +constexpr VkDeviceSize kBuffer = VkDeviceSize(3) << 30; // a mirror chunk: 3 GiB +constexpr VkDeviceSize kPool = 256ull << 20; // the frames: 4,096 pages + +#define FUNCTIONS(X) \ + X(vkEnumeratePhysicalDevices) X(vkGetPhysicalDeviceProperties) X(vkGetPhysicalDeviceFeatures2) \ + X(vkGetPhysicalDeviceQueueFamilyProperties) X(vkGetPhysicalDeviceMemoryProperties) X(vkCreateDevice) \ + X(vkDestroyInstance) +#define DEVICE_FUNCTIONS(X) \ + X(vkDestroyDevice) X(vkGetDeviceQueue) X(vkCreateBuffer) X(vkDestroyBuffer) X(vkGetBufferMemoryRequirements) \ + X(vkAllocateMemory) X(vkFreeMemory) X(vkQueueBindSparse) X(vkCreateSemaphore) X(vkDestroySemaphore) \ + X(vkWaitSemaphores) X(vkDeviceWaitIdle) X(vkGetBufferDeviceAddress) +#define DECLARE(name) PFN_##name name = nullptr; +FUNCTIONS(DECLARE) +DEVICE_FUNCTIONS(DECLARE) +#undef DECLARE + +using Clock = std::chrono::steady_clock; +double us(Clock::duration d) { return std::chrono::duration(d).count(); } + +} // namespace + +int main() { +#ifdef _WIN32 + HMODULE library = LoadLibraryA("vulkan-1.dll"); + auto get_instance = library ? reinterpret_cast( + reinterpret_cast(GetProcAddress(library, "vkGetInstanceProcAddr"))) + : nullptr; +#else + void* library = dlopen("libvulkan.so.1", RTLD_NOW); + auto get_instance = + library ? reinterpret_cast(dlsym(library, "vkGetInstanceProcAddr")) : nullptr; +#endif + if (!get_instance) return std::puts("SKIP: no Vulkan loader"), 77; + VkInstance instance = VK_NULL_HANDLE; + auto create_instance = reinterpret_cast(get_instance(nullptr, "vkCreateInstance")); + VkApplicationInfo app{VK_STRUCTURE_TYPE_APPLICATION_INFO}; + app.apiVersion = VK_API_VERSION_1_2; + VkInstanceCreateInfo instance_info{VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; + instance_info.pApplicationInfo = &app; + if (!create_instance || create_instance(&instance_info, nullptr, &instance) != VK_SUCCESS) + return std::puts("SKIP: no Vulkan instance"), 77; +#define LOAD(name) name = reinterpret_cast(get_instance(instance, #name)); + FUNCTIONS(LOAD) +#undef LOAD + std::uint32_t count = 1; + VkPhysicalDevice physical = VK_NULL_HANDLE; + vkEnumeratePhysicalDevices(instance, &count, &physical); + if (!physical) return std::puts("SKIP: no Vulkan device"), 77; + VkPhysicalDeviceProperties properties{}; + vkGetPhysicalDeviceProperties(physical, &properties); + VkPhysicalDeviceVulkan12Features v12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; + VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &v12}; + vkGetPhysicalDeviceFeatures2(physical, &features); + std::printf("device: %s (driver 0x%x); sparseAddressSpaceSize %llu GiB, maxBufferSize via 3 GiB chunk, " + "aliased %d, strict %d\n", + properties.deviceName, properties.driverVersion, + static_cast(properties.limits.sparseAddressSpaceSize >> 30), + int(features.features.sparseResidencyAliased), int(properties.sparseProperties.residencyNonResidentStrict)); + if (!features.features.sparseBinding || !features.features.sparseResidencyBuffer || !v12.timelineSemaphore) + return std::puts("SKIP: no sparse buffers"), 77; + std::uint32_t family_count = 0; + vkGetPhysicalDeviceQueueFamilyProperties(physical, &family_count, nullptr); + std::vector families(family_count); + vkGetPhysicalDeviceQueueFamilyProperties(physical, &family_count, families.data()); + std::vector used(family_count, 0); + const auto bind_queue = leonida::pick_arena_bind_queue(families.data(), family_count, used.data(), 16); + if (bind_queue.family == UINT32_MAX) return std::puts("SKIP: no sparse queue"), 77; + const float priority = 1.0f; + VkDeviceQueueCreateInfo queue{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}; + queue.queueFamilyIndex = bind_queue.family; + queue.queueCount = bind_queue.index + 1; + std::vector priorities(queue.queueCount, priority); + queue.pQueuePriorities = priorities.data(); + VkPhysicalDeviceVulkan12Features enable12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; + enable12.timelineSemaphore = VK_TRUE; + enable12.bufferDeviceAddress = v12.bufferDeviceAddress; + enable12.bufferDeviceAddressCaptureReplay = v12.bufferDeviceAddressCaptureReplay; + VkPhysicalDeviceFeatures2 enable{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &enable12}; + enable.features.sparseBinding = VK_TRUE; + enable.features.sparseResidencyBuffer = VK_TRUE; + enable.features.sparseResidencyAliased = features.features.sparseResidencyAliased; + VkDeviceCreateInfo device_info{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, &enable}; + device_info.queueCreateInfoCount = 1; + device_info.pQueueCreateInfos = &queue; + VkDevice device = VK_NULL_HANDLE; + if (vkCreateDevice(physical, &device_info, nullptr, &device) != VK_SUCCESS) return std::puts("no device"), 1; + auto get_device = reinterpret_cast(get_instance(instance, "vkGetDeviceProcAddr")); +#define LOAD(name) name = reinterpret_cast(get_device(device, #name)); + DEVICE_FUNCTIONS(LOAD) +#undef LOAD + VkQueue binds = VK_NULL_HANDLE; + vkGetDeviceQueue(device, bind_queue.family, bind_queue.index, &binds); + + VkBufferCreateInfo buffer_info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; + buffer_info.flags = VK_BUFFER_CREATE_SPARSE_BINDING_BIT | VK_BUFFER_CREATE_SPARSE_RESIDENCY_BIT | + (features.features.sparseResidencyAliased ? VK_BUFFER_CREATE_SPARSE_ALIASED_BIT : 0); + buffer_info.size = kBuffer; + buffer_info.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; + VkBuffer buffer = VK_NULL_HANDLE; + if (vkCreateBuffer(device, &buffer_info, nullptr, &buffer) != VK_SUCCESS) return std::puts("no 3 GiB sparse buffer"), 1; + VkMemoryRequirements requirements{}; + vkGetBufferMemoryRequirements(device, buffer, &requirements); + VkPhysicalDeviceMemoryProperties memory{}; + vkGetPhysicalDeviceMemoryProperties(physical, &memory); + std::uint32_t type = UINT32_MAX; + for (std::uint32_t t = 0; t < memory.memoryTypeCount && type == UINT32_MAX; ++t) + if ((requirements.memoryTypeBits >> t & 1) && + (memory.memoryTypes[t].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)) + type = t; + VkMemoryAllocateInfo allocate{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; + allocate.allocationSize = kPool; + allocate.memoryTypeIndex = type; + VkDeviceMemory pool = VK_NULL_HANDLE; + if (type == UINT32_MAX || vkAllocateMemory(device, &allocate, nullptr, &pool) != VK_SUCCESS) + return std::puts("no pool memory"), 1; + std::printf("page alignment %llu; bind queue family %u index %u\n", + static_cast(requirements.alignment), bind_queue.family, bind_queue.index); + + VkSemaphoreTypeCreateInfo timeline_type{VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO}; + timeline_type.semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE; + VkSemaphoreCreateInfo semaphore_info{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, &timeline_type}; + VkSemaphore timeline = VK_NULL_HANDLE; + vkCreateSemaphore(device, &semaphore_info, nullptr, &timeline); + std::uint64_t value = 0; + + std::mt19937 random(7); + const std::uint64_t pool_pages = kPool / kPage, buffer_pages = kBuffer / kPage; + // One call of `n` binds; returns {cpu us, until-signalled us}. + std::vector list; + // memory: 0 scattered pool pages, 1 one page for all, 2 the pool's pages in order (a run of one allocation) + const auto bind = [&](std::size_t n, bool unbind, std::uint64_t first, bool scattered_buffer, int same_memory) { + list.resize(n); + for (std::size_t i = 0; i < n; ++i) { + const std::uint64_t at = scattered_buffer ? random() % buffer_pages : (first + i) % buffer_pages; + list[i] = {at * kPage, kPage, unbind ? VK_NULL_HANDLE : pool, + unbind ? 0 + : same_memory == 1 ? 0 + : same_memory == 2 ? ((first + i) % pool_pages) * kPage + : (random() % pool_pages) * kPage, + 0}; + } + const VkSparseBufferMemoryBindInfo buffer_bind{buffer, std::uint32_t(n), list.data()}; + VkTimelineSemaphoreSubmitInfo signal_value{VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO}; + const std::uint64_t next = ++value; + signal_value.signalSemaphoreValueCount = 1; + signal_value.pSignalSemaphoreValues = &next; + VkBindSparseInfo info{VK_STRUCTURE_TYPE_BIND_SPARSE_INFO, &signal_value}; + info.bufferBindCount = 1; + info.pBufferBinds = &buffer_bind; + info.signalSemaphoreCount = 1; + info.pSignalSemaphores = &timeline; + const auto t0 = Clock::now(); + const VkResult r = vkQueueBindSparse(binds, 1, &info, VK_NULL_HANDLE); + const auto t1 = Clock::now(); + VkSemaphoreWaitInfo wait{VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO}; + wait.semaphoreCount = 1; + wait.pSemaphores = &timeline; + wait.pValues = &next; + vkWaitSemaphores(device, &wait, UINT64_MAX); + const auto t2 = Clock::now(); + if (r != VK_SUCCESS) std::printf(" bind failed: %d\n", int(r)); + return std::pair{us(t1 - t0), us(t2 - t0)}; + }; + const auto row = [&](const char* what, std::size_t n, bool unbind, bool scattered, int same, int rounds) { + std::vector cpu, done; + for (int k = 0; k < rounds; ++k) { + const auto [c, d] = bind(n, unbind, std::uint64_t(k) * n, scattered, same); + cpu.push_back(c); + done.push_back(d); + } + std::sort(cpu.begin(), cpu.end()); + std::sort(done.begin(), done.end()); + const double c = cpu[cpu.size() / 2], d = done[done.size() / 2]; + std::printf("%-34s %5zu pages: call %9.1f us (%7.2f us/page), signalled after %9.1f us (%7.2f us/page)\n", + what, n, c, c / double(n), d, d / double(n)); + }; + row("warm-up", 64, false, false, 0, 4); + for (const std::size_t n : {std::size_t(1), std::size_t(16), std::size_t(64), std::size_t(256), std::size_t(1024), + std::size_t(4096)}) { + row("bind, contiguous VAs", n, false, false, 0, n >= 1024 ? 5 : 21); + row("bind, scattered VAs", n, false, true, 0, n >= 1024 ? 5 : 21); + row("bind, VAs and memory both in order", n, false, false, 2, n >= 1024 ? 5 : 21); + row("unbind, contiguous VAs", n, true, false, 0, n >= 1024 ? 5 : 21); + } + if (features.features.sparseResidencyAliased) row("aliased: one page at many VAs", 256, false, false, 1, 21); + // Placement: can a sparse buffer be made at a device address of our choosing (bufferDeviceAddressCaptureReplay, + // VkBufferOpaqueCaptureAddressCreateInfo)? If so, a mirror chunk could sit at heap_base + the title's address, + // and a V# or pointer the title wrote into its own memory would reach it unchanged. + std::printf("bufferDeviceAddressCaptureReplay %d\n", int(v12.bufferDeviceAddressCaptureReplay)); + if (v12.bufferDeviceAddress && v12.bufferDeviceAddressCaptureReplay && vkGetBufferDeviceAddress) { + const auto place = [&](std::uint64_t want, VkDeviceSize bytes) { + VkBufferOpaqueCaptureAddressCreateInfo at{VK_STRUCTURE_TYPE_BUFFER_OPAQUE_CAPTURE_ADDRESS_CREATE_INFO}; + at.opaqueCaptureAddress = want; + VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, &at}; + info.flags = VK_BUFFER_CREATE_SPARSE_BINDING_BIT | VK_BUFFER_CREATE_SPARSE_RESIDENCY_BIT | + VK_BUFFER_CREATE_DEVICE_ADDRESS_CAPTURE_REPLAY_BIT; + info.size = bytes; + info.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; + VkBuffer made = VK_NULL_HANDLE; + const VkResult r = vkCreateBuffer(device, &info, nullptr, &made); + std::uint64_t got = 0; + if (r == VK_SUCCESS) { + VkBufferDeviceAddressInfo address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; + address.buffer = made; + got = vkGetBufferDeviceAddress(device, &address); + } + std::printf(" sparse %llu MiB at 0x%016llx: %s, address 0x%016llx\n", + static_cast(bytes >> 20), static_cast(want), + r == VK_SUCCESS ? (got == want ? "placed" : "made elsewhere") : "refused", + static_cast(got)); + return made; + }; + // A heap base low in the upper half, and chunks at heap_base + title addresses seen under Wine. + const std::uint64_t heap = 0xffff800100000000ull; + std::vector placed; + for (const std::uint64_t title : {0ull, 0x0000000600000000ull, 0x00000075e0000000ull, 0x000000d340000000ull, + 0x00007fb3a0000000ull, 0x00007fb7a0000000ull, 0x00007ffe00000000ull}) + placed.push_back(place(heap + title, VkDeviceSize(3) << 30)); + for (VkBuffer b : placed) + if (b) vkDestroyBuffer(device, b, nullptr); + } + // A remap's rate: 2,000 pages a second in batches of 32 (the logs' queue slot 31: tens of pages a call). + { + const auto t0 = Clock::now(); + for (int k = 0; k < 63; ++k) bind(32, false, std::uint64_t(k) * 32, true, 0); + std::printf("remap load: 63 calls of 32 scattered pages in %.1f ms\n", us(Clock::now() - t0) / 1000.0); + } + bind(std::size_t(buffer_pages > 65536 ? 65536 : buffer_pages), true, 0, false, 0); + vkDeviceWaitIdle(device); + vkDestroySemaphore(device, timeline, nullptr); + vkDestroyBuffer(device, buffer, nullptr); + vkFreeMemory(device, pool, nullptr); + vkDestroyDevice(device, nullptr); + vkDestroyInstance(instance, nullptr); + return 0; +} diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h index 8369d594c7..4ff8d70210 100644 --- a/runtime/test/vk_test_device.h +++ b/runtime/test/vk_test_device.h @@ -144,6 +144,8 @@ class Device { bool custom_border_color = false; // VK_EXT_custom_border_color and customBorderColors enabled bool custom_border_color_without_format = false; bool shader_output_viewport_index = false; // Vulkan 1.2 shaderOutputViewportIndex enabled + bool vulkan_memory_model = false; // Vulkan 1.2 vulkanMemoryModel enabled + bool vulkan_memory_model_device_scope = false; // Vulkan 1.2 vulkanMemoryModelDeviceScope enabled bool request_buffer_marker = false; // set before initialize(): enable VK_AMD_buffer_marker where available bool buffer_marker = false; // VK_AMD_buffer_marker is enabled bool request_null_descriptor = false; // set before initialize(): enable VK_EXT_robustness2 nullDescriptor @@ -456,6 +458,10 @@ class Device { enable12.samplerFilterMinmax = sampler_filter_minmax; shader_output_viewport_index = features12.shaderOutputViewportIndex == VK_TRUE; enable12.shaderOutputViewportIndex = shader_output_viewport_index; + vulkan_memory_model = features12.vulkanMemoryModel == VK_TRUE; + vulkan_memory_model_device_scope = vulkan_memory_model && features12.vulkanMemoryModelDeviceScope == VK_TRUE; + enable12.vulkanMemoryModel = vulkan_memory_model ? VK_TRUE : VK_FALSE; + enable12.vulkanMemoryModelDeviceScope = vulkan_memory_model_device_scope ? VK_TRUE : VK_FALSE; enable12.bufferDeviceAddress = VK_TRUE; const std::uint32_t graphics_count = std::max(1u, std::min(queue_count_wanted, family_queue_count)); diff --git a/runtime/test/vk_texture_test.cpp b/runtime/test/vk_texture_test.cpp index 97e93cb046..df0177bb3d 100644 --- a/runtime/test/vk_texture_test.cpp +++ b/runtime/test/vk_texture_test.cpp @@ -151,8 +151,14 @@ int main(int argc, char** argv) { const VkFormat sampled_format = dref ? VK_FORMAT_D32_SFLOAT : (uint_mips || fetch_uint) ? VK_FORMAT_R8G8B8A8_UINT : (signed_mips || fetch) ? VK_FORMAT_R8G8B8A8_SINT : VK_FORMAT_R8G8B8A8_UNORM; - uint32_t tsharp[8] = {0x11111111, leonida::gfx10::format_from_vulkan(sampled_format) << 20, 0x33333333, 0x44440444, - 0x55555555, 0x66666666, 0x77777777, 0x88888888}; + // The shaders load the T# through a descriptor-table pointer (s[ptr_sgpr], high dword 0), so they take its index + // from dword 6 as the layer writes it (gfx10_descriptors.h, tsharp_index_word; docs/design.md, "Bindless index in + // the T#"): index 1, bound in both sampled arrays they read (see the table insert below). Word 3's TYPE is 9 (2D): + // a word without the tag, or a dword 3 that names no image, reads the fallback. + const uint32_t index_word = leonida::gfx10::tsharp_index_word(1, leonida::kind_sampled_bit(0) | + leonida::kind_sampled_bit(1)); + uint32_t tsharp[8] = {0x11111111, leonida::gfx10::format_from_vulkan(sampled_format) << 20, 0x33333333, 0x94440444, + 0x55555555, 0x66666666, index_word, 0x88888888}; const uint32_t tsharp_va = 256; gipa = load_vulkan(); @@ -318,7 +324,13 @@ int main(int argc, char** argv) { const VkDeviceSize heap_bytes = heap_mb && std::atoi(heap_mb) > 0 ? VkDeviceSize(std::atoi(heap_mb)) << 20 : 65536; CHECK(make_buffer(heap_bytes, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, &heap, &heapm, &heapp)); std::memset(heapp, 0, size_t(heap_bytes)); - std::memcpy(static_cast(heapp) + tsharp_va, tsharp, 32); + { + // The miss control: a T# whose dword 6 carries no index (the title's own word) reads the fallback. + uint32_t in_heap[8]; + std::memcpy(in_heap, tsharp, sizeof(in_heap)); + if (fetch_miss) in_heap[leonida::gfx10::kTsharpIndexDword] = 0x77777777; + std::memcpy(static_cast(heapp) + tsharp_va, in_heap, 32); + } if (two_mip) // The gather test loads its S# from the four words just after the T#. std::memcpy(static_cast(heapp) + tsharp_va + 32, ssharp, 16); VkBufferDeviceAddressInfo bdai{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; bdai.buffer = heap; diff --git a/runtime/test/vk_title_detile_test.cpp b/runtime/test/vk_title_detile_test.cpp new file mode 100644 index 0000000000..37adbd5263 --- /dev/null +++ b/runtime/test/vk_title_detile_test.cpp @@ -0,0 +1,832 @@ +// GPU detile & linear mirror direct-copy bit-for-bit parity test (src/vulkan_title_detile.h). +// +// Verifies bit-for-bit parity between leonida::TitleDetilePipeline (GPU compute detile & direct linear copy into a +// real optimal-tiling VkImage, read back via vkCmdCopyImageToBuffer) and the CPU console texture detiler +// (leonida::console_texture::Layout, matching rt::xg_xs::copy_elements bit-for-bit) across: +// - BC1, BC3, BC4, BC5, BC7, R8, RG8, RGBA8, R16F, RG16F, RGBA16F, R32F, RGBA32F +// - Swizzle modes: 4KB_S, 64KB_S, 64KB_D, and Linear direct copy +// - Full mip chains (exercising both macro-tiled mips and mip-tail mips), array slices, odd/NPOT extents, and +// non-zero TitleMirror chunk offsets. +// Skips with exit code 77 when no Vulkan 1.2/1.3 device with textureCompressionBC is available. No game data. + +#include "vk_test_device.h" +#include "../src/console_texture_layout.h" +#include "../src/vulkan_title_detile.h" +#include "../src/vulkan_title_image_pool.h" + +#include +#include +#include +#include +#include +#include + +#define EXPECT(cond) \ + do { \ + if (!(cond)) { \ + std::fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \ + return 1; \ + } \ + } while (0) + +namespace { + +struct Buffer { + VkDevice device = VK_NULL_HANDLE; + PFN_vkDestroyBuffer destroy = nullptr; + PFN_vkFreeMemory free_mem = nullptr; + VkBuffer handle = VK_NULL_HANDLE; + VkDeviceMemory memory = VK_NULL_HANDLE; + std::uint8_t* mapped = nullptr; + VkDeviceSize size = 0; + + ~Buffer() { + if (handle && destroy) destroy(device, handle, nullptr); + if (memory && free_mem) free_mem(device, memory, nullptr); + } + Buffer() = default; + Buffer(const Buffer&) = delete; + Buffer& operator=(const Buffer&) = delete; +}; + +struct Image { + VkDevice device = VK_NULL_HANDLE; + PFN_vkDestroyImage destroy = nullptr; + PFN_vkFreeMemory free_mem = nullptr; + VkImage handle = VK_NULL_HANDLE; + VkDeviceMemory memory = VK_NULL_HANDLE; + + ~Image() { + if (handle && destroy) destroy(device, handle, nullptr); + if (memory && free_mem) free_mem(device, memory, nullptr); + } + Image() = default; + Image(const Image&) = delete; + Image& operator=(const Image&) = delete; +}; + +VkDeviceMemory alloc_memory(const vktest::Device& d, const VkMemoryRequirements& req, + VkMemoryPropertyFlags required, VkMemoryPropertyFlags preferred) { + VkPhysicalDeviceMemoryProperties mp{}; + d.instance_fn("vkGetPhysicalDeviceMemoryProperties")(d.physical, &mp); + std::uint32_t chosen = UINT32_MAX; + for (std::uint32_t i = 0; i < mp.memoryTypeCount; ++i) { + if (!(req.memoryTypeBits & (1u << i))) continue; + const auto flags = mp.memoryTypes[i].propertyFlags; + if ((flags & required) != required) continue; + if (chosen == UINT32_MAX) chosen = i; + if ((flags & preferred) == preferred) { + chosen = i; + break; + } + } + if (chosen == UINT32_MAX) return VK_NULL_HANDLE; + VkMemoryAllocateInfo info{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; + info.allocationSize = req.size; + info.memoryTypeIndex = chosen; + VkDeviceMemory mem = VK_NULL_HANDLE; + if (d.fn("vkAllocateMemory")(d.device, &info, nullptr, &mem) != VK_SUCCESS) + return VK_NULL_HANDLE; + return mem; +} + +bool make_host_buffer(const vktest::Device& d, VkDeviceSize size, VkBufferUsageFlags usage, Buffer& out) { + out.device = d.device; + out.destroy = d.fn("vkDestroyBuffer"); + out.free_mem = d.fn("vkFreeMemory"); + out.size = size; + VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; + info.size = size; + info.usage = usage; + if (d.fn("vkCreateBuffer")(d.device, &info, nullptr, &out.handle) != VK_SUCCESS) return false; + VkMemoryRequirements req{}; + d.fn("vkGetBufferMemoryRequirements")(d.device, out.handle, &req); + out.memory = alloc_memory(d, req, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, + VK_MEMORY_PROPERTY_HOST_CACHED_BIT); + if (!out.memory) return false; + if (d.fn("vkBindBufferMemory")(d.device, out.handle, out.memory, 0) != VK_SUCCESS) + return false; + void* ptr = nullptr; + if (d.fn("vkMapMemory")(d.device, out.memory, 0, VK_WHOLE_SIZE, 0, &ptr) != VK_SUCCESS) + return false; + out.mapped = static_cast(ptr); + return true; +} + +bool make_image(const vktest::Device& d, VkFormat format, std::uint32_t width, std::uint32_t height, + std::uint32_t mips, std::uint32_t layers, Image& out) { + out.device = d.device; + out.destroy = d.fn("vkDestroyImage"); + out.free_mem = d.fn("vkFreeMemory"); + VkImageCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; + info.imageType = VK_IMAGE_TYPE_2D; + info.format = format; + info.extent = {width, height, 1}; + info.mipLevels = mips; + info.arrayLayers = layers; + info.samples = VK_SAMPLE_COUNT_1_BIT; + info.tiling = VK_IMAGE_TILING_OPTIMAL; + info.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; + if (d.fn("vkCreateImage")(d.device, &info, nullptr, &out.handle) != VK_SUCCESS) return false; + VkMemoryRequirements req{}; + d.fn("vkGetImageMemoryRequirements")(d.device, out.handle, &req); + out.memory = alloc_memory(d, req, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); + if (!out.memory) return false; + return d.fn("vkBindImageMemory")(d.device, out.handle, out.memory, 0) == VK_SUCCESS; +} + +leonida::TitleDetileDesc to_detile_desc(const leonida::console_texture::Layout& layout) { + leonida::TitleDetileDesc out{}; + switch (layout.desc.swizzle) { + case leonida::console_texture::kLinear: out.mode = leonida::TitleDetileMode::linear; break; + case leonida::console_texture::kSw4kbS: out.mode = leonida::TitleDetileMode::sw_4kb_s; break; + case leonida::console_texture::kSw64kbS: out.mode = leonida::TitleDetileMode::sw_64kb_s; break; + case leonida::console_texture::kSw64kbD: out.mode = leonida::TitleDetileMode::sw_64kb_d; break; + default: break; + } + out.dimension = 3; // 2D + out.element_bytes = layout.desc.element_bytes; + out.block_side = layout.desc.block; + out.tile_width = layout.block[0]; + out.tile_height = layout.block[1]; + out.array_layers = layout.slices; + out.total_size = layout.size; + out.slice_bytes = layout.slice_size; + out.mips.resize(layout.mips.size()); + for (std::size_t i = 0; i < layout.mips.size(); ++i) { + const auto& m = layout.mips[i]; + auto& dst = out.mips[i]; + dst.offset = m.offset; + dst.width_elements = m.width; + dst.height_elements = m.height; + dst.width_texels = std::max(1u, layout.desc.width >> i); + dst.height_texels = std::max(1u, layout.desc.height >> i); + dst.depth = m.depth; + dst.padded_width = m.pitch; + dst.padded_height = m.rows; + dst.pitch_bytes = m.pitch * layout.desc.element_bytes; + dst.pitch_texels = m.pitch * layout.desc.block; + dst.in_tail = m.tail.has_value(); + if (m.tail) { + dst.tail_x = m.tail->x; + dst.tail_y = m.tail->y; + } + } + return out; +} + +struct FormatCase { + const char* name; + VkFormat vk_format; + std::uint32_t element_bytes; + std::uint32_t block_side; +}; + +struct ExtentCase { + std::uint32_t width; + std::uint32_t height; + std::uint32_t mips; + std::uint32_t layers; + std::uint32_t swizzle; + VkDeviceSize src_offset; +}; + +int run_case(vktest::Device& d, leonida::TitleDetilePipeline& pipe, const FormatCase& fmt, const ExtentCase& ec, + std::uint64_t& serial) { + namespace ct = leonida::console_texture; + ct::Desc cd{}; + cd.dimension = ct::Dimension::tex2d; + cd.width = ec.width; + cd.height = ec.height; + cd.depth = ec.layers; + cd.mips = ec.mips; + cd.element_bytes = fmt.element_bytes; + cd.block = fmt.block_side; + cd.samples = 1; + cd.swizzle = ec.swizzle; + const auto layout_opt = ct::Layout::make(cd); + EXPECT(layout_opt.has_value()); + const ct::Layout& layout = *layout_opt; + const auto desc = to_detile_desc(layout); + + // 1. Fill simulated TitleMirror chunk buffer with deterministic non-repeating bytes at ec.src_offset. + const VkDeviceSize chunk_size = ec.src_offset + layout.size + 4096; + Buffer mirror_chunk; + EXPECT(make_host_buffer(d, chunk_size, + VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT, mirror_chunk)); + std::memset(mirror_chunk.mapped, 0xCC, std::size_t(chunk_size)); + std::uint8_t* const tiled_ptr = mirror_chunk.mapped + ec.src_offset; + std::uint64_t seed = 0x9e3779b97f4a7c15ull ^ (serial * 0xbf58476d1ce4e5b9ull) ^ (std::uint64_t(ec.width) << 16) ^ + ec.height ^ (std::uint64_t(ec.swizzle) << 32) ^ (std::uint64_t(fmt.element_bytes) << 40); + for (std::size_t i = 0; i < layout.size; ++i) { + seed = seed * 6364136223846793005ull + 1442695040888963407ull; + tiled_ptr[i] = static_cast(seed >> 56); + } + + // 2. Compute CPU ground truth for every (layer, mip) via console_texture::Layout::detile(). + std::vector> cpu_truth; + cpu_truth.reserve(std::size_t(ec.layers) * ec.mips); + std::vector readback_regions; + VkDeviceSize readback_bytes = 0; + const VkDeviceSize rb_align = std::max(4u, fmt.element_bytes) * 4u; + for (std::uint32_t layer = 0; layer < ec.layers; ++layer) { + for (std::uint32_t mip = 0; mip < ec.mips; ++mip) { + const auto& m = layout.mips[mip]; + const std::size_t row_bytes = std::size_t(m.width) * fmt.element_bytes; + const std::size_t slice_bytes = row_bytes * m.height; + std::vector linear(slice_bytes, 0xA5); + EXPECT(layout.detile(tiled_ptr, std::size_t(layout.size), mip, layer, linear.data(), linear.size(), + row_bytes, slice_bytes) == ct::Error::ok); + cpu_truth.push_back(std::move(linear)); + + VkBufferImageCopy rb{}; + rb.bufferOffset = leonida::detail::align_up_size(readback_bytes, rb_align); + rb.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, mip, layer, 1}; + rb.imageExtent = {std::max(1u, ec.width >> mip), std::max(1u, ec.height >> mip), 1u}; + readback_regions.push_back(rb); + readback_bytes = rb.bufferOffset + slice_bytes; + } + } + + // 3. Create target optimal-tiling VkImage and host-visible readback buffer. + Image image; + EXPECT(make_image(d, fmt.vk_format, ec.width, ec.height, ec.mips, ec.layers, image)); + Buffer readback; + EXPECT(make_host_buffer(d, std::max(readback_bytes, 64), VK_BUFFER_USAGE_TRANSFER_DST_BIT, readback)); + std::memset(readback.mapped, 0x5A, std::size_t(readback.size)); + + // 4. Execute GPU mirror path (direct linear copy OR compute detile -> scratch -> image) + readback. + const bool is_linear = ec.swizzle == ct::kLinear; + std::vector copy_regions; + std::vector dispatches; + leonida::TitleDetilePipeline::ScratchSlot* scratch = nullptr; + VkBuffer copy_src = VK_NULL_HANDLE; + + if (is_linear) { + EXPECT(leonida::TitleDetilePipeline::can_direct_linear(desc, ec.src_offset, chunk_size, ec.width, ec.height, 1, + ec.mips, ec.layers, false)); + EXPECT(leonida::TitleDetilePipeline::build_linear_regions(desc, ec.src_offset, ec.width, ec.height, 1, false, + copy_regions)); + copy_src = mirror_chunk.handle; + } else { + EXPECT(pipe.can_gpu_detile(desc, ec.src_offset, chunk_size, ec.width, ec.height, ec.mips, ec.layers, false)); + VkDeviceSize scratch_end = 0; + EXPECT(leonida::TitleDetilePipeline::build_scratch_regions(desc, 0, ec.width, ec.height, copy_regions, + scratch_end)); + // Pass serial as `reached` because vktest::Device::run() waits for queue idle after each test case. + scratch = pipe.acquire_scratch(serial, scratch_end, 1); + EXPECT(scratch != nullptr); + EXPECT(pipe.prepare_texture(*scratch, mirror_chunk.handle, ec.src_offset, desc, 0, scratch_end, copy_regions, + dispatches)); + copy_src = scratch->buffer; + } + + const bool ran = d.run([&](VkCommandBuffer cb) { + const auto barrier = d.fn("vkCmdPipelineBarrier"); + const auto copy_b2i = d.fn("vkCmdCopyBufferToImage"); + const auto copy_i2b = d.fn("vkCmdCopyImageToBuffer"); + + // Mirror visibility barrier (HOST_WRITE | TRANSFER_WRITE -> SHADER_READ | TRANSFER_READ). + VkMemoryBarrier mem{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + mem.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT; + mem.dstAccessMask = + VkAccessFlags(is_linear ? 0u : VK_ACCESS_SHADER_READ_BIT) | VK_ACCESS_TRANSFER_READ_BIT; + const VkPipelineStageFlags dst_stage = + VkPipelineStageFlags(is_linear ? 0u : VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT) | + VK_PIPELINE_STAGE_TRANSFER_BIT; + barrier(cb, VK_PIPELINE_STAGE_HOST_BIT | VK_PIPELINE_STAGE_TRANSFER_BIT, dst_stage, 0, 1, &mem, 0, nullptr, 0, + nullptr); + + VkImageMemoryBarrier to_dst{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; + to_dst.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + to_dst.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; + to_dst.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + to_dst.srcQueueFamilyIndex = to_dst.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + to_dst.image = image.handle; + to_dst.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, ec.mips, 0, ec.layers}; + barrier(cb, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, + &to_dst); + + if (!is_linear) { + pipe.emit_dispatches(cb, dispatches); + VkMemoryBarrier cs_to_xfer{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + cs_to_xfer.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; + cs_to_xfer.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; + barrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1, &cs_to_xfer, 0, + nullptr, 0, nullptr); + } + + copy_b2i(cb, copy_src, image.handle, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + static_cast(copy_regions.size()), copy_regions.data()); + + VkImageMemoryBarrier to_src{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; + to_src.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + to_src.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; + to_src.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + to_src.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; + to_src.srcQueueFamilyIndex = to_src.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + to_src.image = image.handle; + to_src.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, ec.mips, 0, ec.layers}; + barrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, + &to_src); + + copy_i2b(cb, image.handle, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, readback.handle, + static_cast(readback_regions.size()), readback_regions.data()); + + VkMemoryBarrier host_vis{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + host_vis.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + host_vis.dstAccessMask = VK_ACCESS_HOST_READ_BIT; + barrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, 1, &host_vis, 0, nullptr, 0, + nullptr); + return true; + }); + EXPECT(ran); + if (scratch) scratch->value = serial; + ++serial; + + // 5. Bit-for-bit comparison of every single byte across every layer and mip! + for (std::size_t idx = 0; idx < cpu_truth.size(); ++idx) { + const auto& expected = cpu_truth[idx]; + const std::uint8_t* actual = readback.mapped + readback_regions[idx].bufferOffset; + if (std::memcmp(actual, expected.data(), expected.size()) != 0) { + for (std::size_t b = 0; b < expected.size(); ++b) { + if (actual[b] != expected[b]) { + std::fprintf(stderr, + "MISMATCH fmt=%s swizzle=%u %ux%u mips=%u layers=%u region=%zu byte=%zu: " + "gpu=0x%02x cpu=0x%02x (in_tail=%d)\n", + fmt.name, ec.swizzle, ec.width, ec.height, ec.mips, ec.layers, idx, b, + unsigned(actual[b]), unsigned(expected[b]), + int(layout.mips[readback_regions[idx].imageSubresource.mipLevel].tail.has_value())); + return 1; + } + } + } + } + return 0; +} + +} // namespace + +int main() { + vktest::Device d; + const auto status = d.initialize(); + if (status == vktest::DeviceStatus::unavailable) { + std::puts("vk_title_detile_test: no Vulkan 1.2/1.3 device available (skipping)"); + return 77; + } + EXPECT(status == vktest::DeviceStatus::ready); + if (!d.bc) { + std::puts("vk_title_detile_test: textureCompressionBC unavailable (skipping)"); + return 77; + } + + VkPhysicalDeviceProperties props{}; + d.instance_fn("vkGetPhysicalDeviceProperties")(d.physical, &props); + + leonida::TitleDetilePipeline pipe( + d.device_proc, d.device, props.limits, + [&d](const VkMemoryRequirements& req, VkMemoryPropertyFlags required, VkMemoryPropertyFlags preferred) { + return alloc_memory(d, req, required, preferred); + }); + + const FormatCase formats[] = { + {"BC1", VK_FORMAT_BC1_RGBA_UNORM_BLOCK, 8, 4}, + {"BC3", VK_FORMAT_BC3_UNORM_BLOCK, 16, 4}, + {"BC4", VK_FORMAT_BC4_UNORM_BLOCK, 8, 4}, + {"BC5", VK_FORMAT_BC5_UNORM_BLOCK, 16, 4}, + {"BC7", VK_FORMAT_BC7_UNORM_BLOCK, 16, 4}, + {"R8", VK_FORMAT_R8_UNORM, 1, 1}, + {"RG8", VK_FORMAT_R8G8_UNORM, 2, 1}, + {"RGBA8", VK_FORMAT_R8G8B8A8_UNORM, 4, 1}, + {"R16F", VK_FORMAT_R16_SFLOAT, 2, 1}, + {"RG16F", VK_FORMAT_R16G16_SFLOAT, 4, 1}, + {"RGBA16F", VK_FORMAT_R16G16B16A16_SFLOAT, 8, 1}, + {"R32F", VK_FORMAT_R32_SFLOAT, 4, 1}, + {"RGBA32F", VK_FORMAT_R32G32B32A32_SFLOAT, 16, 1}, + }; + + namespace ct = leonida::console_texture; + const ExtentCase extents[] = { + // Multi-mip chains with both macro-tiled mips and mip tails across all 3 swizzle modes: + {256, 256, 9, 1, ct::kSw64kbS, 65536}, + {256, 256, 9, 1, ct::kSw64kbD, 65536}, + {256, 128, 9, 1, ct::kSw4kbS, 4096}, + // Odd / non-power-of-two extents with multi-mip chains & mip tails: + {127, 95, 7, 1, ct::kSw64kbS, 65536}, + {73, 51, 6, 1, ct::kSw64kbD, 65536}, + {37, 29, 5, 1, ct::kSw4kbS, 4096}, + // Tiny odd extents (tests 1B/2B word packing boundary & partial tail bytes): + {13, 7, 1, 1, ct::kSw4kbS, 4096}, + {3, 5, 1, 1, ct::kSw64kbD, 65536}, + {1, 1, 1, 1, ct::kSw64kbS, 65536}, + // Array textures (multiple slices + mips + mip tails): + {64, 64, 6, 3, ct::kSw64kbD, 65536}, + {33, 27, 4, 2, ct::kSw4kbS, 4096}, + // Linear direct copy (multi-mip, array slices, odd extents, non-zero offset): + {128, 64, 5, 2, ct::kLinear, 4096}, + {37, 29, 4, 1, ct::kLinear, 256}, + {13, 7, 1, 1, ct::kLinear, 256}, + }; + + std::uint64_t serial = 1; + std::uint32_t passed = 0; + for (const auto& fmt : formats) { + for (const auto& ec : extents) { + // Skip odd extents smaller than a 4x4 block for BC formats when mip count would be valid, + // Note: console_texture::Layout handles odd BC extents (rounds up to blocks); test all of them! + if (run_case(d, pipe, fmt, ec, serial) != 0) return 1; + ++passed; + } + } + + EXPECT(d.validation_errors() == 0); + + // Verify cached PFN_vk* (zero vkGetDeviceProcAddr calls during prepare/flush/emit), batched + // vkAllocateDescriptorSets (1 driver call for 4 textures), batched vkUpdateDescriptorSets (1 driver call for 4 + // textures), oldest_in_flight_scratch_value(), and kMaxScratchSlots==64. + { + static_assert(leonida::TitleDetilePipeline::kMaxScratchSlots == 64); + static PFN_vkGetDeviceProcAddr s_real_gdpa = nullptr; + static PFN_vkAllocateDescriptorSets s_real_alloc = nullptr; + static PFN_vkUpdateDescriptorSets s_real_update = nullptr; + static std::atomic s_gdpa_calls{0}; + static std::atomic s_alloc_calls{0}; + static std::atomic s_alloc_sets{0}; + static std::atomic s_update_calls{0}; + static std::atomic s_update_writes{0}; + struct CountingProc { + static VKAPI_ATTR VkResult VKAPI_CALL alloc_ds(VkDevice dev, const VkDescriptorSetAllocateInfo* info, + VkDescriptorSet* out) { + s_alloc_calls.fetch_add(1, std::memory_order_relaxed); + if (info) s_alloc_sets.fetch_add(info->descriptorSetCount, std::memory_order_relaxed); + return s_real_alloc(dev, info, out); + } + static VKAPI_ATTR void VKAPI_CALL update_ds(VkDevice dev, std::uint32_t write_count, + const VkWriteDescriptorSet* writes, std::uint32_t copy_count, + const VkCopyDescriptorSet* copies) { + s_update_calls.fetch_add(1, std::memory_order_relaxed); + s_update_writes.fetch_add(write_count, std::memory_order_relaxed); + s_real_update(dev, write_count, writes, copy_count, copies); + } + static VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get(VkDevice dev, const char* name) { + s_gdpa_calls.fetch_add(1, std::memory_order_relaxed); + if (name && std::strcmp(name, "vkAllocateDescriptorSets") == 0) { + s_real_alloc = reinterpret_cast(s_real_gdpa(dev, name)); + return reinterpret_cast(&alloc_ds); + } + if (name && std::strcmp(name, "vkUpdateDescriptorSets") == 0) { + s_real_update = reinterpret_cast(s_real_gdpa(dev, name)); + return reinterpret_cast(&update_ds); + } + return s_real_gdpa(dev, name); + } + }; + s_real_gdpa = d.device_proc; + s_gdpa_calls.store(0, std::memory_order_relaxed); + s_alloc_calls.store(0, std::memory_order_relaxed); + s_alloc_sets.store(0, std::memory_order_relaxed); + s_update_calls.store(0, std::memory_order_relaxed); + s_update_writes.store(0, std::memory_order_relaxed); + + leonida::TitleDetilePipeline batch_pipe( + &CountingProc::get, d.device, props.limits, + [&d](const VkMemoryRequirements& req, VkMemoryPropertyFlags required, VkMemoryPropertyFlags preferred) { + return alloc_memory(d, req, required, preferred); + }); + const std::uint64_t gdpa_after_ctor = s_gdpa_calls.load(std::memory_order_acquire); + EXPECT(gdpa_after_ctor > 0); + + namespace ct = leonida::console_texture; + constexpr std::size_t kBatchTex = 4; + std::vector srcs(kBatchTex); + std::vector imgs(kBatchTex); + std::vector rbs(kBatchTex); + std::vector descs(kBatchTex); + std::vector> expected(kBatchTex); + std::vector> regions(kBatchTex); + VkDeviceSize bases[kBatchTex]{}, ends[kBatchTex]{}; + VkDeviceSize total_scratch = 0; + + for (std::size_t i = 0; i < kBatchTex; ++i) { + ct::Desc cd{}; + cd.dimension = ct::Dimension::tex2d; + cd.width = 64; + cd.height = 64; + cd.depth = 1; + cd.mips = 1; + cd.element_bytes = 4; + cd.block = 1; + cd.samples = 1; + cd.swizzle = (i % 2 == 0) ? ct::kSw64kbD : ct::kSw4kbS; + const auto lay = ct::Layout::make(cd); + EXPECT(lay.has_value()); + descs[i] = to_detile_desc(*lay); + EXPECT(make_host_buffer(d, lay->size, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT, + srcs[i])); + for (std::size_t b = 0; b < lay->size; ++b) + srcs[i].mapped[b] = static_cast((b * (17 + i * 7) + i * 31) & 0xffu); + expected[i].resize(64u * 64u * 4u); + EXPECT(lay->detile(srcs[i].mapped, std::size_t(lay->size), 0, 0, expected[i].data(), expected[i].size(), + 64u * 4u, expected[i].size()) == ct::Error::ok); + EXPECT(make_image(d, VK_FORMAT_R8G8B8A8_UNORM, 64, 64, 1, 1, imgs[i])); + EXPECT(make_host_buffer(d, expected[i].size(), VK_BUFFER_USAGE_TRANSFER_DST_BIT, rbs[i])); + const VkDeviceSize align = (std::max)(batch_pipe.min_storage_alignment(), VkDeviceSize(16)); + bases[i] = leonida::detail::align_up_size(total_scratch, align); + EXPECT(leonida::TitleDetilePipeline::build_scratch_regions(descs[i], bases[i], 64, 64, regions[i], ends[i])); + total_scratch = ends[i]; + } + + auto* slot = batch_pipe.acquire_scratch(0, total_scratch, kBatchTex); + EXPECT(slot != nullptr); + std::vector pre_sets; + EXPECT(batch_pipe.allocate_descriptor_sets(*slot, kBatchTex, pre_sets)); + EXPECT(pre_sets.size() == kBatchTex); + EXPECT(s_alloc_calls.load(std::memory_order_acquire) == 1); // ONE batched vkAllocateDescriptorSets call! + EXPECT(s_alloc_sets.load(std::memory_order_acquire) == kBatchTex); + std::vector dispatches; + std::vector pending; + for (std::size_t i = 0; i < kBatchTex; ++i) { + EXPECT(batch_pipe.prepare_texture(*slot, srcs[i].handle, 0, descs[i], bases[i], ends[i], regions[i], + dispatches, &pending, pre_sets[i])); + } + EXPECT(s_alloc_calls.load(std::memory_order_acquire) == 1); // ZERO per-texture vkAllocateDescriptorSets! + EXPECT(s_update_calls.load(std::memory_order_acquire) == 0); // deferred until flush! + batch_pipe.flush_descriptor_updates(pending); + EXPECT(s_update_calls.load(std::memory_order_acquire) == 1); // ONE batched vkUpdateDescriptorSets call! + EXPECT(s_update_writes.load(std::memory_order_acquire) == kBatchTex * 2u); + + const bool ok = d.run([&](VkCommandBuffer cb) { + const auto barrier = d.fn("vkCmdPipelineBarrier"); + const auto copy_b2i = d.fn("vkCmdCopyBufferToImage"); + const auto copy_i2b = d.fn("vkCmdCopyImageToBuffer"); + VkMemoryBarrier mem{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + mem.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT; + mem.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; + barrier(cb, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 1, &mem, 0, nullptr, 0, + nullptr); + batch_pipe.emit_dispatches(cb, dispatches); + VkMemoryBarrier cs_to_x{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + cs_to_x.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; + cs_to_x.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; + barrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1, &cs_to_x, 0, + nullptr, 0, nullptr); + for (std::size_t i = 0; i < kBatchTex; ++i) { + VkImageMemoryBarrier to_dst{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; + to_dst.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + to_dst.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; + to_dst.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + to_dst.srcQueueFamilyIndex = to_dst.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + to_dst.image = imgs[i].handle; + to_dst.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + barrier(cb, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, + nullptr, 1, &to_dst); + copy_b2i(cb, slot->buffer, imgs[i].handle, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + static_cast(regions[i].size()), regions[i].data()); + VkImageMemoryBarrier to_src = to_dst; + to_src.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + to_src.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; + to_src.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + to_src.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; + barrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, + 1, &to_src); + VkBufferImageCopy rb{}; + rb.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; + rb.imageExtent = {64, 64, 1}; + copy_i2b(cb, imgs[i].handle, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, rbs[i].handle, 1, &rb); + } + VkMemoryBarrier host_vis{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + host_vis.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + host_vis.dstAccessMask = VK_ACCESS_HOST_READ_BIT; + barrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, 1, &host_vis, 0, nullptr, 0, + nullptr); + return true; + }); + EXPECT(ok); + // Zero vkGetDeviceProcAddr calls after constructor (all PFN_vk* cached once!). + EXPECT(s_gdpa_calls.load(std::memory_order_acquire) == gdpa_after_ctor); + for (std::size_t i = 0; i < kBatchTex; ++i) { + EXPECT(std::memcmp(rbs[i].mapped, expected[i].data(), expected[i].size()) == 0); + } + + // Verify kMaxScratchSlots == 64 allows > 32 concurrent in-flight slots and oldest_in_flight_scratch_value() + // picks the smallest non-zero in-flight slot value. + slot->value = 42; + auto* slot2 = batch_pipe.acquire_scratch(0, 64, 1); + EXPECT(slot2 != nullptr && slot2 != slot); + slot2->value = 17; + EXPECT(batch_pipe.oldest_in_flight_scratch_value() == 17); + std::vector extra_slots; + for (std::size_t k = 0; k < 34; ++k) { + auto* s = batch_pipe.acquire_scratch(0, 64, 1); + EXPECT(s != nullptr); + s->value = 100 + k; + extra_slots.push_back(s); + } + EXPECT(batch_pipe.oldest_in_flight_scratch_value() == 17); + slot2->value = 0; + EXPECT(batch_pipe.oldest_in_flight_scratch_value() == 42); + slot->value = 0; + EXPECT(batch_pipe.oldest_in_flight_scratch_value() == 100); + for (auto* s : extra_slots) s->value = 0; + EXPECT(batch_pipe.oldest_in_flight_scratch_value() == 0); + EXPECT(d.validation_errors() == 0); + } + + // Verify linear 3D direct copy with mips > 1 (array_layers == 1) bit-for-bit against console_texture::Layout, + // plus rejection of invalid array_layers != 1 for volume textures. + { + namespace ct = leonida::console_texture; + struct VolumeCase { + const char* name; + VkFormat vk_format; + std::uint32_t element_bytes; + std::uint32_t block_side; + std::uint32_t width; + std::uint32_t height; + std::uint32_t depth; + std::uint32_t mips; + VkDeviceSize src_offset; + }; + const VolumeCase vcases[] = { + {"RGBA8 32x24x8 mips=4", VK_FORMAT_R8G8B8A8_UNORM, 4, 1, 32, 24, 8, 4, 4096}, + {"R8 17x13x5 mips=3", VK_FORMAT_R8_UNORM, 1, 1, 17, 13, 5, 3, 256}, + {"RGBA16F 16x12x6 mips=4", VK_FORMAT_R16G16B16A16_SFLOAT, 8, 1, 16, 12, 6, 4, 512}, + {"BC1 32x32x4 mips=3", VK_FORMAT_BC1_RGBA_UNORM_BLOCK, 8, 4, 32, 32, 4, 3, 4096}, + {"RGBA8 16x16x4 mips=1", VK_FORMAT_R8G8B8A8_UNORM, 4, 1, 16, 16, 4, 1, 256}, + }; + for (const auto& vc : vcases) { + ct::Desc cd{}; + cd.dimension = ct::Dimension::tex3d; + cd.width = vc.width; + cd.height = vc.height; + cd.depth = vc.depth; + cd.mips = vc.mips; + cd.element_bytes = vc.element_bytes; + cd.block = vc.block_side; + cd.samples = 1; + cd.swizzle = ct::kLinear; + const auto layout_opt = ct::Layout::make(cd); + EXPECT(layout_opt.has_value()); + const ct::Layout& layout = *layout_opt; + leonida::TitleDetileDesc desc = to_detile_desc(layout); + desc.dimension = 4; + desc.array_layers = 1; + + const VkDeviceSize chunk_size = vc.src_offset + layout.size + 4096; + Buffer mirror_chunk; + EXPECT(make_host_buffer(d, chunk_size, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, mirror_chunk)); + std::memset(mirror_chunk.mapped, 0xCC, std::size_t(chunk_size)); + std::uint8_t* const tiled_ptr = mirror_chunk.mapped + vc.src_offset; + std::uint64_t seed = 0x517cc1b727220a95ull ^ (serial * 0x94d049bb133111ebull); + for (std::size_t i = 0; i < layout.size; ++i) { + seed = seed * 6364136223846793005ull + 1442695040888963407ull; + tiled_ptr[i] = static_cast(seed >> 56); + } + + // Invalid array_layers > 1 on a 3D volume must be rejected. + auto bad_desc = desc; + bad_desc.array_layers = 2; + EXPECT(!leonida::TitleDetilePipeline::can_direct_linear(bad_desc, vc.src_offset, chunk_size, vc.width, + vc.height, vc.depth, vc.mips, 2, true)); + + EXPECT(leonida::TitleDetilePipeline::can_direct_linear(desc, vc.src_offset, chunk_size, vc.width, + vc.height, vc.depth, vc.mips, 1, true)); + std::vector copy_regions; + EXPECT(leonida::TitleDetilePipeline::build_linear_regions(desc, vc.src_offset, vc.width, vc.height, + vc.depth, true, copy_regions)); + + std::vector> cpu_truth; + std::vector rb_regions; + VkDeviceSize rb_bytes = 0; + const VkDeviceSize rb_align = (std::max)(VkDeviceSize(4u), VkDeviceSize(vc.element_bytes)) * 4u; + for (std::uint32_t mip = 0; mip < vc.mips; ++mip) { + const auto& m = layout.mips[mip]; + const std::size_t row_bytes = std::size_t(m.width) * vc.element_bytes; + const std::size_t slice_bytes = row_bytes * m.height; + const std::size_t vol_bytes = slice_bytes * m.depth; + std::vector linear(vol_bytes, 0xA5); + EXPECT(layout.detile(tiled_ptr, std::size_t(layout.size), mip, 0, linear.data(), linear.size(), + row_bytes, slice_bytes) == ct::Error::ok); + cpu_truth.push_back(std::move(linear)); + + VkBufferImageCopy rb{}; + rb.bufferOffset = leonida::detail::align_up_size(rb_bytes, rb_align); + rb.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, mip, 0, 1}; + rb.imageExtent = {(std::max)(1u, vc.width >> mip), (std::max)(1u, vc.height >> mip), + (std::max)(1u, vc.depth >> mip)}; + rb_regions.push_back(rb); + rb_bytes = rb.bufferOffset + vol_bytes; + } + + Image img; + img.device = d.device; + img.destroy = d.fn("vkDestroyImage"); + img.free_mem = d.fn("vkFreeMemory"); + VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; + ii.imageType = VK_IMAGE_TYPE_3D; + ii.format = vc.vk_format; + ii.extent = {vc.width, vc.height, vc.depth}; + ii.mipLevels = vc.mips; + ii.arrayLayers = 1; + ii.samples = VK_SAMPLE_COUNT_1_BIT; + ii.tiling = VK_IMAGE_TILING_OPTIMAL; + ii.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; + EXPECT(d.fn("vkCreateImage")(d.device, &ii, nullptr, &img.handle) == VK_SUCCESS); + VkMemoryRequirements req{}; + d.fn("vkGetImageMemoryRequirements")(d.device, img.handle, &req); + img.memory = alloc_memory(d, req, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); + EXPECT(img.memory != VK_NULL_HANDLE); + EXPECT(d.fn("vkBindImageMemory")(d.device, img.handle, img.memory, 0) == VK_SUCCESS); + + Buffer readback; + EXPECT(make_host_buffer(d, (std::max)(rb_bytes, VkDeviceSize(64)), VK_BUFFER_USAGE_TRANSFER_DST_BIT, + readback)); + std::memset(readback.mapped, 0x5A, std::size_t(readback.size)); + + const bool ran = d.run([&](VkCommandBuffer cb) { + const auto barrier = d.fn("vkCmdPipelineBarrier"); + const auto copy_b2i = d.fn("vkCmdCopyBufferToImage"); + const auto copy_i2b = d.fn("vkCmdCopyImageToBuffer"); + VkImageMemoryBarrier to_dst{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; + to_dst.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + to_dst.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; + to_dst.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + to_dst.srcQueueFamilyIndex = to_dst.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + to_dst.image = img.handle; + to_dst.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, vc.mips, 0, 1}; + barrier(cb, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, + nullptr, 1, &to_dst); + copy_b2i(cb, mirror_chunk.handle, img.handle, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + static_cast(copy_regions.size()), copy_regions.data()); + VkImageMemoryBarrier to_src = to_dst; + to_src.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + to_src.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; + to_src.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + to_src.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; + barrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, + 1, &to_src); + copy_i2b(cb, img.handle, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, readback.handle, + static_cast(rb_regions.size()), rb_regions.data()); + VkMemoryBarrier host_vis{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + host_vis.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + host_vis.dstAccessMask = VK_ACCESS_HOST_READ_BIT; + barrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, 1, &host_vis, 0, nullptr, 0, + nullptr); + return true; + }); + EXPECT(ran); + for (std::uint32_t mip = 0; mip < vc.mips; ++mip) { + const auto& expected = cpu_truth[mip]; + const std::uint8_t* actual = readback.mapped + rb_regions[mip].bufferOffset; + if (std::memcmp(actual, expected.data(), expected.size()) != 0) { + std::fprintf(stderr, "3D LINEAR MISMATCH case=%s mip=%u\n", vc.name, mip); + return 1; + } + } + ++serial; + ++passed; + } + EXPECT(d.validation_errors() == 0); + } + + // Verify TitleImagePool raises largest_slot to 8 MiB and caps >2 MiB page allocations at <= 16 MiB. + { + leonida::TitleImagePool pool; + std::vector alloc_sizes; + std::uint64_t next_mem = 1; + auto fake_bind = [](VkDevice, VkImage, VkDeviceMemory, VkDeviceSize) -> VkResult { return VK_SUCCESS; }; + auto fake_destroy_img = [](VkDevice, VkImage, const VkAllocationCallbacks*) {}; + auto fake_free_mem = [](VkDevice, VkDeviceMemory, const VkAllocationCallbacks*) {}; + auto fake_alloc = [&](VkDeviceSize size, std::uint32_t& type) -> VkDeviceMemory { + alloc_sizes.push_back(size); + type = 0; + return reinterpret_cast(next_mem++); + }; + const VkDevice fake_dev = reinterpret_cast(std::uintptr_t(1)); + const VkImage fake_img = reinterpret_cast(std::uintptr_t(1)); + + // 5.5 MiB texture -> pooled in 11 MiB page (capacity 2, <= 16 MiB cap), second reuses same page! + VkMemoryRequirements req_55{5632ull << 10, 65536, 1u}; + auto a1 = pool.bind(fake_dev, fake_img, req_55, fake_bind, fake_destroy_img, fake_free_mem, fake_alloc); + auto a2 = pool.bind(fake_dev, fake_img, req_55, fake_bind, fake_destroy_img, fake_free_mem, fake_alloc); + EXPECT(a1 && a2 && a1->page == a2->page); + EXPECT(alloc_sizes.size() == 1 && alloc_sizes[0] <= (16ull << 20)); + + // 8 MiB texture -> pooled in 16 MiB page (capacity 2). + VkMemoryRequirements req_8m{8ull << 20, 65536, 1u}; + auto b1 = pool.bind(fake_dev, fake_img, req_8m, fake_bind, fake_destroy_img, fake_free_mem, fake_alloc); + auto b2 = pool.bind(fake_dev, fake_img, req_8m, fake_bind, fake_destroy_img, fake_free_mem, fake_alloc); + EXPECT(b1 && b2 && b1->page == b2->page); + EXPECT(alloc_sizes.size() == 2 && alloc_sizes[1] == (16ull << 20)); + + // > 8 MiB texture -> refused by pool (returns nullptr). + VkMemoryRequirements req_9m{9ull << 20, 65536, 1u}; + auto c1 = pool.bind(fake_dev, fake_img, req_9m, fake_bind, fake_destroy_img, fake_free_mem, fake_alloc); + EXPECT(!c1 && alloc_sizes.size() == 2); + } + + std::printf("vk_title_detile_test: %u cases + batched descriptor/cached PFN + linear 3D multi-mip + pool 8MiB " + "checks passed bit-for-bit (0 validation errors)\n", + passed); + return 0; +} diff --git a/runtime/test/vk_title_mirror_test.cpp b/runtime/test/vk_title_mirror_test.cpp new file mode 100644 index 0000000000..c555b46b4c --- /dev/null +++ b/runtime/test/vk_title_mirror_test.cpp @@ -0,0 +1,464 @@ +// The page mirror on a real device (src/title_mirror.h): chunks made at heap_base + a title address (a sparse "heap" +// buffer stands in for the GPU address arena, whose address is heap_base), pages bound to one home per physical page, +// and a compute shader that reads a V# out of a buffer and loads through it as the translated shaders do +// (glsl/cs_title_mirror_read.comp). Checked: +// 1. a V# whose base is a mirrored title address reads that page's bytes; one at another title address of the same +// physical page (an alias) reads the same; one at a page with nothing bound reads zero, with no fault; +// 2. a remap (a page given another physical page, as CopyPageMappingsBatchX does) is a rebind: the next dispatch, +// which waits for the batch's value (the ordering rule), reads the new page; a write to a physical page, once +// dirty() names a page that shows it, reaches every alias with one upload; an unmap reads zero again; +// 3. a home no page binds is freed only once the ticket passed to map() has completed. +// Exit 77 without sparse aliased strict residency, bufferDeviceAddressCaptureReplay or glslangValidator (llvmpipe: the +// runtime keeps the old paths there, the page mirror is off). No game data. +#define VK_NO_PROTOTYPES +#include "../src/arena_backing.h" +#include "../src/title_mirror.h" +#include "../src/title_mirror_space.h" + +#include +#include +#include +#include +#include +#include +#ifdef _WIN32 +#include +#else +#include +#endif + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +namespace { + +#define FUNCTIONS(X) \ + X(vkEnumeratePhysicalDevices) X(vkGetPhysicalDeviceProperties) X(vkGetPhysicalDeviceFeatures2) \ + X(vkGetPhysicalDeviceQueueFamilyProperties) X(vkGetPhysicalDeviceMemoryProperties) X(vkCreateDevice) \ + X(vkDestroyInstance) +#define DEVICE_FUNCTIONS(X) \ + X(vkDestroyDevice) X(vkGetDeviceQueue) X(vkCreateBuffer) X(vkDestroyBuffer) X(vkGetBufferMemoryRequirements) \ + X(vkAllocateMemory) X(vkFreeMemory) X(vkMapMemory) X(vkBindBufferMemory) X(vkQueueBindSparse) \ + X(vkQueueSubmit) X(vkCreateSemaphore) X(vkDestroySemaphore) X(vkWaitSemaphores) X(vkDeviceWaitIdle) \ + X(vkGetBufferDeviceAddress) X(vkCreateCommandPool) X(vkDestroyCommandPool) X(vkAllocateCommandBuffers) \ + X(vkBeginCommandBuffer) X(vkEndCommandBuffer) X(vkCmdBindPipeline) X(vkCmdPushConstants) X(vkCmdDispatch) \ + X(vkCreateShaderModule) X(vkDestroyShaderModule) X(vkCreatePipelineLayout) X(vkDestroyPipelineLayout) \ + X(vkCreateComputePipelines) X(vkDestroyPipeline) X(vkResetCommandBuffer) +#define DECLARE(name) PFN_##name name = nullptr; +FUNCTIONS(DECLARE) +DEVICE_FUNCTIONS(DECLARE) +#undef DECLARE + +constexpr std::uint64_t kPage = leonida::TitleMirror::kPage; + +std::vector load_spirv(const char* path) { + std::ifstream file(path, std::ios::binary | std::ios::ate); + if (!file) return {}; + const auto bytes = static_cast(file.tellg()); + std::vector words(bytes / 4); + file.seekg(0); + file.read(reinterpret_cast(words.data()), std::streamsize(words.size() * 4)); + return words; +} + +struct Push { + std::uint64_t heap_base, vsharps, out_words; + std::uint32_t count, pad; +}; + +int test() { +#ifndef LEONIDA_TEST_TITLE_MIRROR_SPV + std::puts("SKIP: no glslangValidator at build time"); + return 77; +#else +#ifdef _WIN32 + HMODULE library = LoadLibraryA("vulkan-1.dll"); + auto get_instance = library ? reinterpret_cast( + reinterpret_cast(GetProcAddress(library, "vkGetInstanceProcAddr"))) + : nullptr; +#else + void* library = dlopen("libvulkan.so.1", RTLD_NOW); + auto get_instance = + library ? reinterpret_cast(dlsym(library, "vkGetInstanceProcAddr")) : nullptr; +#endif + if (!get_instance) return std::puts("SKIP: no Vulkan loader"), 77; + VkInstance instance = VK_NULL_HANDLE; + auto create_instance = reinterpret_cast(get_instance(nullptr, "vkCreateInstance")); + VkApplicationInfo app{VK_STRUCTURE_TYPE_APPLICATION_INFO}; + app.apiVersion = VK_API_VERSION_1_2; + VkInstanceCreateInfo instance_info{VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; + instance_info.pApplicationInfo = &app; + if (!create_instance || create_instance(&instance_info, nullptr, &instance) != VK_SUCCESS) + return std::puts("SKIP: no Vulkan instance"), 77; +#define LOAD(name) name = reinterpret_cast(get_instance(instance, #name)); + FUNCTIONS(LOAD) +#undef LOAD + // Declared before the cleanup, which uses them. + std::vector chunks; + std::vector units; + std::unique_ptr mirror; + struct Cleanup { + VkInstance instance; + VkDevice device = VK_NULL_HANDLE; + std::vector> undo; + ~Cleanup() { + if (device) vkDeviceWaitIdle(device); + for (auto it = undo.rbegin(); it != undo.rend(); ++it) (*it)(); + if (device) vkDestroyDevice(device, nullptr); + vkDestroyInstance(instance, nullptr); + } + } run{instance}; + std::uint32_t count = 1; + VkPhysicalDevice physical = VK_NULL_HANDLE; + vkEnumeratePhysicalDevices(instance, &count, &physical); + if (!physical) return std::puts("SKIP: no Vulkan device"), 77; + VkPhysicalDeviceProperties properties{}; + vkGetPhysicalDeviceProperties(physical, &properties); + VkPhysicalDeviceVulkan12Features v12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; + VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &v12}; + vkGetPhysicalDeviceFeatures2(physical, &features); + std::fprintf(stderr, "device: %s\n", properties.deviceName); + if (!features.features.sparseBinding || !features.features.sparseResidencyBuffer || + !features.features.sparseResidencyAliased || !properties.sparseProperties.residencyNonResidentStrict || + !v12.timelineSemaphore || !v12.bufferDeviceAddress || !v12.bufferDeviceAddressCaptureReplay || + !features.features.shaderInt64) + return std::puts("SKIP: no aliased strict sparse buffers with capture-replay addresses (page mirror off)"), 77; + std::uint32_t family_count = 0; + vkGetPhysicalDeviceQueueFamilyProperties(physical, &family_count, nullptr); + std::vector families(family_count); + vkGetPhysicalDeviceQueueFamilyProperties(physical, &family_count, families.data()); + std::uint32_t work = UINT32_MAX; + for (std::uint32_t f = 0; f < family_count && work == UINT32_MAX; ++f) + if (families[f].queueFlags & VK_QUEUE_COMPUTE_BIT) work = f; + std::vector used(family_count, 0); + if (work != UINT32_MAX) used[work] = 1; + const auto bind_queue = leonida::pick_arena_bind_queue(families.data(), family_count, used.data(), 16); + if (work == UINT32_MAX || bind_queue.family == UINT32_MAX) return std::puts("SKIP: no queue for the binds"), 77; + const float priorities[2] = {1.0f, 1.0f}; + VkDeviceQueueCreateInfo queues[2] = {{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}, {VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}}; + queues[0].queueFamilyIndex = work; + queues[0].queueCount = bind_queue.family == work ? 2 : 1; + queues[0].pQueuePriorities = priorities; + queues[1].queueFamilyIndex = bind_queue.family; + queues[1].queueCount = 1; + queues[1].pQueuePriorities = priorities; + VkPhysicalDeviceVulkan12Features enable12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; + enable12.timelineSemaphore = VK_TRUE; + enable12.bufferDeviceAddress = VK_TRUE; + enable12.bufferDeviceAddressCaptureReplay = VK_TRUE; + VkPhysicalDeviceFeatures2 enable{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &enable12}; + enable.features.sparseBinding = VK_TRUE; + enable.features.sparseResidencyBuffer = VK_TRUE; + enable.features.sparseResidencyAliased = VK_TRUE; + enable.features.shaderInt64 = VK_TRUE; + VkDeviceCreateInfo device_info{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, &enable}; + device_info.queueCreateInfoCount = bind_queue.family == work ? 1 : 2; + device_info.pQueueCreateInfos = queues; + EXPECT(vkCreateDevice(physical, &device_info, nullptr, &run.device) == VK_SUCCESS); + auto get_device = reinterpret_cast(get_instance(instance, "vkGetDeviceProcAddr")); +#define LOAD(name) name = reinterpret_cast(get_device(run.device, #name)); + DEVICE_FUNCTIONS(LOAD) +#undef LOAD + const VkDevice device = run.device; + VkQueue work_queue = VK_NULL_HANDLE, binds = VK_NULL_HANDLE; + vkGetDeviceQueue(device, work, 0, &work_queue); + vkGetDeviceQueue(device, bind_queue.family, bind_queue.index, &binds); + VkPhysicalDeviceMemoryProperties memory{}; + vkGetPhysicalDeviceMemoryProperties(physical, &memory); + const VkBufferUsageFlags usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; + const auto address_of = [&](VkBuffer b) { + VkBufferDeviceAddressInfo info{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; + info.buffer = b; + return vkGetBufferDeviceAddress(device, &info); + }; + const auto sparse_info = [&](VkDeviceSize bytes) { + VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; + info.flags = VK_BUFFER_CREATE_SPARSE_BINDING_BIT | VK_BUFFER_CREATE_SPARSE_RESIDENCY_BIT | + VK_BUFFER_CREATE_SPARSE_ALIASED_BIT; + info.size = bytes; + info.usage = usage; + return info; + }; + // The "arena": a sparse buffer whose address is heap_base, as the runtime's sparse arena is. + const VkBufferCreateInfo heap_info = sparse_info(64ull << 20); + VkBuffer heap = VK_NULL_HANDLE; + EXPECT(vkCreateBuffer(device, &heap_info, nullptr, &heap) == VK_SUCCESS); + run.undo.push_back([device, heap] { vkDestroyBuffer(device, heap, nullptr); }); + const std::uint64_t heap_base = address_of(heap); + VkMemoryRequirements sparse_requirements{}; + vkGetBufferMemoryRequirements(device, heap, &sparse_requirements); + std::fprintf(stderr, "heap_base 0x%llx\n", static_cast(heap_base)); + + VkSemaphoreTypeCreateInfo timeline_type{VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO}; + timeline_type.semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE; + VkSemaphoreCreateInfo semaphore_info{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, &timeline_type}; + VkSemaphore timeline = VK_NULL_HANDLE, done = VK_NULL_HANDLE; + EXPECT(vkCreateSemaphore(device, &semaphore_info, nullptr, &timeline) == VK_SUCCESS); + EXPECT(vkCreateSemaphore(device, &semaphore_info, nullptr, &done) == VK_SUCCESS); + run.undo.push_back([device, timeline, done] { + vkDestroySemaphore(device, timeline, nullptr); + vkDestroySemaphore(device, done, nullptr); + }); + + leonida::TitleMirrorHooks hooks; + hooks.make_chunk = [&](std::uint64_t title_base, std::uint64_t bytes, VkBuffer& out) { + VkBufferOpaqueCaptureAddressCreateInfo at{VK_STRUCTURE_TYPE_BUFFER_OPAQUE_CAPTURE_ADDRESS_CREATE_INFO}; + at.opaqueCaptureAddress = heap_base + title_base; + VkBufferCreateInfo info = sparse_info(bytes); + info.flags |= VK_BUFFER_CREATE_DEVICE_ADDRESS_CAPTURE_REPLAY_BIT; + info.pNext = &at; + if (vkCreateBuffer(device, &info, nullptr, &out) != VK_SUCCESS) return false; + if (address_of(out) != heap_base + title_base) { + vkDestroyBuffer(device, out, nullptr); + return false; + } + chunks.push_back(out); + return true; + }; + hooks.make_unit = [&](VkDeviceMemory& out, std::uint8_t*& host) { + const VkMemoryPropertyFlags want = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; + std::uint32_t type = UINT32_MAX; + for (std::uint32_t t = 0; t < memory.memoryTypeCount && type == UINT32_MAX; ++t) + if ((sparse_requirements.memoryTypeBits >> t & 1) && (memory.memoryTypes[t].propertyFlags & want) == want) + type = t; + if (type == UINT32_MAX) return false; + VkMemoryAllocateInfo allocate{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; + allocate.allocationSize = leonida::TitleMirror::kUnitBytes; + allocate.memoryTypeIndex = type; + void* mapped = nullptr; + if (vkAllocateMemory(device, &allocate, nullptr, &out) != VK_SUCCESS) return false; + if (vkMapMemory(device, out, 0, VK_WHOLE_SIZE, 0, &mapped) != VK_SUCCESS) return false; + host = static_cast(mapped); + units.push_back(out); + return true; + }; + hooks.free_unit = [&](VkDeviceMemory m) { vkFreeMemory(device, m, nullptr); }; + hooks.bind = [&](const std::vector& list, std::uint64_t value) { + VkTimelineSemaphoreSubmitInfo signal{VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO}; + signal.signalSemaphoreValueCount = 1; + signal.pSignalSemaphoreValues = &value; + VkBindSparseInfo info{VK_STRUCTURE_TYPE_BIND_SPARSE_INFO, &signal}; + info.bufferBindCount = std::uint32_t(list.size()); + info.pBufferBinds = list.data(); + info.signalSemaphoreCount = 1; + info.pSignalSemaphores = &timeline; + return vkQueueBindSparse(binds, 1, &info, VK_NULL_HANDLE) == VK_SUCCESS; + }; + mirror = std::make_unique(std::move(hooks)); + run.undo.push_back([&mirror, &chunks, device] { + vkDeviceWaitIdle(device); + mirror.reset(); + for (VkBuffer c : chunks) vkDestroyBuffer(device, c, nullptr); + }); + + // A reservation of the title's in the mirror's range, and two physical pages (host memory, as xmem's sections are). + const std::uint64_t t0 = leonida::title_mirror_space::kLow; + EXPECT(mirror->cover(t0, t0 + 64 * kPage) && mirror->covers(t0) && !mirror->covers(t0 + leonida::TitleMirror::kChunk)); + std::vector a(kPage / 4), b(kPage / 4); + for (std::size_t i = 0; i < a.size(); ++i) { + a[i] = 0xA0000000u + std::uint32_t(i); + b[i] = 0xB0000000u + std::uint32_t(i); + } + auto* page_a = reinterpret_cast(a.data()); + auto* page_b = reinterpret_cast(b.data()); + std::uint64_t ticket = 1; + mirror->map(t0, page_a, nullptr, ticket); // page 0: A + mirror->map(t0 + 3 * kPage, page_a, nullptr, ticket); // page 3: A again (an alias) + mirror->map(t0 + kPage, page_b, nullptr, ticket); // page 1: B; page 2: nothing + EXPECT(mirror->counters().homes == 2 && mirror->counters().uploads == 2); + EXPECT(mirror->flush(1) && mirror->last_batch() == 3); + + // The V#s, in a buffer of their own (the title's memory a shader reads them from), and the output. + const auto host_buffer = [&](VkDeviceSize bytes, VkBuffer& out, void*& mapped) { + VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; + info.size = bytes; + info.usage = usage; + if (vkCreateBuffer(device, &info, nullptr, &out) != VK_SUCCESS) return false; + VkMemoryRequirements r{}; + vkGetBufferMemoryRequirements(device, out, &r); + const VkMemoryPropertyFlags want = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; + std::uint32_t type = UINT32_MAX; + for (std::uint32_t t = 0; t < memory.memoryTypeCount && type == UINT32_MAX; ++t) + if ((r.memoryTypeBits >> t & 1) && (memory.memoryTypes[t].propertyFlags & want) == want) type = t; + VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO}; + flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; + VkMemoryAllocateInfo allocate{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, &flags}; + allocate.allocationSize = r.size; + allocate.memoryTypeIndex = type; + VkDeviceMemory m = VK_NULL_HANDLE; + if (type == UINT32_MAX || vkAllocateMemory(device, &allocate, nullptr, &m) != VK_SUCCESS) return false; + run.undo.push_back([device, out, m] { + vkDestroyBuffer(device, out, nullptr); + vkFreeMemory(device, m, nullptr); + }); + return vkBindBufferMemory(device, out, m, 0) == VK_SUCCESS && + vkMapMemory(device, m, 0, VK_WHOLE_SIZE, 0, &mapped) == VK_SUCCESS; + }; + constexpr std::uint32_t kViews = 4; + VkBuffer vsharps = VK_NULL_HANDLE, out = VK_NULL_HANDLE; + void* vsharp_words = nullptr; + void* out_words = nullptr; + EXPECT(host_buffer(kViews * 16, vsharps, vsharp_words) && host_buffer(kViews * 4, out, out_words)); + // Title-written V#s: base = the title address (48 bits), stride 0, records 0x1000, as the title builds them. + const std::uint64_t bases[kViews] = {t0, t0 + 3 * kPage, t0 + kPage, t0 + 2 * kPage}; + auto* w = static_cast(vsharp_words); + for (std::uint32_t i = 0; i < kViews; ++i) { + w[i * 4 + 0] = std::uint32_t(bases[i]); + w[i * 4 + 1] = std::uint32_t(bases[i] >> 32) & 0xffffu; + w[i * 4 + 2] = 0x1000; + w[i * 4 + 3] = 0; + } + + const std::vector code = load_spirv(LEONIDA_TEST_TITLE_MIRROR_SPV); + EXPECT(!code.empty()); + VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + module_info.codeSize = code.size() * 4; + module_info.pCode = code.data(); + VkShaderModule module = VK_NULL_HANDLE; + EXPECT(vkCreateShaderModule(device, &module_info, nullptr, &module) == VK_SUCCESS); + const VkPushConstantRange range{VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(Push)}; + VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; + layout_info.pushConstantRangeCount = 1; + layout_info.pPushConstantRanges = ⦥ + VkPipelineLayout layout = VK_NULL_HANDLE; + EXPECT(vkCreatePipelineLayout(device, &layout_info, nullptr, &layout) == VK_SUCCESS); + VkComputePipelineCreateInfo pipeline_info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; + pipeline_info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, nullptr, 0, VK_SHADER_STAGE_COMPUTE_BIT, + module, "main", nullptr}; + pipeline_info.layout = layout; + VkPipeline pipeline = VK_NULL_HANDLE; + EXPECT(vkCreateComputePipelines(device, VK_NULL_HANDLE, 1, &pipeline_info, nullptr, &pipeline) == VK_SUCCESS); + VkCommandPoolCreateInfo pool_info{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; + pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; + pool_info.queueFamilyIndex = work; + VkCommandPool pool = VK_NULL_HANDLE; + EXPECT(vkCreateCommandPool(device, &pool_info, nullptr, &pool) == VK_SUCCESS); + run.undo.push_back([device, module, layout, pipeline, pool] { + vkDestroyCommandPool(device, pool, nullptr); + vkDestroyPipeline(device, pipeline, nullptr); + vkDestroyPipelineLayout(device, layout, nullptr); + vkDestroyShaderModule(device, module, nullptr); + }); + VkCommandBufferAllocateInfo command_info{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; + command_info.commandPool = pool; + command_info.commandBufferCount = 1; + VkCommandBuffer commands = VK_NULL_HANDLE; + EXPECT(vkAllocateCommandBuffers(device, &command_info, &commands) == VK_SUCCESS); + + std::uint64_t done_value = 0; + // One dispatch that waits for the mirror's bind value `wait` (the ordering rule), then the four reads. + const auto dispatch = [&](std::uint64_t wait, std::uint32_t* result) { + vkResetCommandBuffer(commands, 0); + VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; + vkBeginCommandBuffer(commands, &begin); + vkCmdBindPipeline(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline); + const Push push{heap_base, address_of(vsharps), address_of(out), kViews, 0}; + vkCmdPushConstants(commands, layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), &push); + vkCmdDispatch(commands, 1, 1, 1); + vkEndCommandBuffer(commands); + const std::uint64_t signal = ++done_value; + VkTimelineSemaphoreSubmitInfo values{VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO}; + values.waitSemaphoreValueCount = 1; + values.pWaitSemaphoreValues = &wait; + values.signalSemaphoreValueCount = 1; + values.pSignalSemaphoreValues = &signal; + const VkPipelineStageFlags stage = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; + VkSubmitInfo submit{VK_STRUCTURE_TYPE_SUBMIT_INFO, &values}; + submit.waitSemaphoreCount = 1; + submit.pWaitSemaphores = &timeline; + submit.pWaitDstStageMask = &stage; + submit.commandBufferCount = 1; + submit.pCommandBuffers = &commands; + submit.signalSemaphoreCount = 1; + submit.pSignalSemaphores = &done; + if (vkQueueSubmit(work_queue, 1, &submit, VK_NULL_HANDLE) != VK_SUCCESS) return false; + VkSemaphoreWaitInfo wait_info{VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO}; + wait_info.semaphoreCount = 1; + wait_info.pSemaphores = &done; + wait_info.pValues = &signal; + if (vkWaitSemaphores(device, &wait_info, 5'000'000'000ull) != VK_SUCCESS) return false; + std::memcpy(result, out_words, kViews * 4); + return true; + }; + + // 1. The page, its alias, another page, and a page with nothing bound. + std::uint32_t r[kViews]{}; + EXPECT(dispatch(1, r)); + std::fprintf(stderr, "read 0x%08x 0x%08x 0x%08x 0x%08x\n", r[0], r[1], r[2], r[3]); + EXPECT(r[0] == a[0x10] && r[1] == a[0x10] && r[2] == b[0x10] && r[3] == 0); + + // 2. A remap of page 0 to B, a write to A seen through its alias with one upload, and an unmap of page 1. + mirror->map(t0, page_b, nullptr, ++ticket); + a[0x10] = 0xA11A5E00u; + const std::uint64_t uploads = mirror->counters().uploads; + EXPECT(mirror->dirty(t0 + 3 * kPage) && mirror->upload() == 1 && mirror->counters().uploads == uploads + 1); + EXPECT(mirror->flush(2)); + EXPECT(dispatch(2, r)); + EXPECT(r[0] == b[0x10] && r[1] == 0xA11A5E00u && r[2] == b[0x10] && r[3] == 0); + mirror->map(t0 + kPage, nullptr, nullptr, ++ticket); + EXPECT(mirror->flush(3)); + EXPECT(dispatch(3, r)); + EXPECT(r[0] == b[0x10] && r[1] == 0xA11A5E00u && r[2] == 0 && r[3] == 0); + + // 3. A unbound at page 3 too: its home stays unstamped (never freed even by retire(UINT64_MAX)) until flush() + // publishes the sparse unbind and stamp_freed() assigns the ticket; then it waits for that ticket to retire. + const std::uint64_t freed = mirror->counters().homes_freed; + mirror->map(t0 + 3 * kPage, nullptr, nullptr); + EXPECT(mirror->counters().homes == 1 && mirror->unstamped_freed_count() == 1); + mirror->retire(UINT64_MAX); + EXPECT(mirror->counters().homes_freed == freed && mirror->unstamped_freed_count() == 1); + EXPECT(mirror->flush(4)); + const std::uint64_t stamp = ++ticket; + mirror->stamp_freed(stamp); + EXPECT(mirror->unstamped_freed_count() == 0); + mirror->retire(stamp - 1); + EXPECT(mirror->counters().homes_freed == freed); + mirror->retire(stamp); + EXPECT(mirror->counters().homes_freed == freed + 1); + EXPECT(dispatch(4, r) && r[0] == b[0x10] && r[1] == 0); + + // 4. Parallel batch upload (>= kParallelThreshold): 64 distinct pages mapped, mutated, uploaded via internal + // worker pool into mapped Vulkan unit memory, and verified on the GPU through title-written V#s. + constexpr std::size_t kBatchPages = 64; + std::vector batch_frames(kBatchPages * (kPage / 4)); + for (std::size_t p = 0; p < kBatchPages; ++p) { + std::uint32_t* page_words = batch_frames.data() + p * (kPage / 4); + for (std::size_t i = 0; i < kPage / 4; ++i) + page_words[i] = 0xC0000000u | (std::uint32_t(p) << 16) | std::uint32_t(i); + mirror->map(t0 + (4 + p) * kPage, reinterpret_cast(page_words), nullptr, ++ticket); + } + EXPECT(mirror->flush(5)); + // Mutate word 0x10 of every page in the 64-page batch and upload in parallel. + for (std::size_t p = 0; p < kBatchPages; ++p) { + batch_frames[p * (kPage / 4) + 0x10] = 0xD0000000u | (std::uint32_t(p) << 16) | 0x10u; + EXPECT(mirror->dirty(t0 + (4 + p) * kPage)); + } + const std::uint64_t batch_uploads_before = mirror->counters().uploads; + EXPECT(mirror->upload() == kBatchPages); + EXPECT(mirror->counters().uploads == batch_uploads_before + kBatchPages); + EXPECT(mirror->last_upload_bytes() == kBatchPages * 256); + // Point the 4 V#s at 4 pages spanning the parallel batch (0, 17, 41, 63) and verify GPU reads. + const std::size_t sample_pages[kViews] = {0, 17, 41, 63}; + for (std::uint32_t i = 0; i < kViews; ++i) { + const std::uint64_t va = t0 + (4 + sample_pages[i]) * kPage; + w[i * 4 + 0] = std::uint32_t(va); + w[i * 4 + 1] = std::uint32_t(va >> 32) & 0xffffu; + } + EXPECT(dispatch(5, r)); + for (std::uint32_t i = 0; i < kViews; ++i) { + const std::uint32_t expected = 0xD0000000u | (std::uint32_t(sample_pages[i]) << 16) | 0x10u; + EXPECT(r[i] == expected); + } + + std::printf("title mirror: a title-written V# read through a buffer reaches its page at heap_base + its address, " + "its alias the same home, an unbound page zero; a remap, a write and an unmap reach the next dispatch " + "that waits for the bind; 64-page parallel upload verified on GPU (%zu chunk, %zu unit)\n", + chunks.size(), units.size()); + return 0; +#endif +} + +} // namespace + +int main() { return test(); } diff --git a/runtime/test/vulkan13_features_test.cpp b/runtime/test/vulkan13_features_test.cpp index c9795ade5b..489b2eb81d 100644 --- a/runtime/test/vulkan13_features_test.cpp +++ b/runtime/test/vulkan13_features_test.cpp @@ -26,6 +26,7 @@ struct FakeDevice { VkBool32 synchronization2 = VK_FALSE; VkBool32 subgroup_size_control = VK_FALSE; VkBool32 compute_full_subgroups = VK_FALSE; + VkBool32 integer_dot_product = VK_FALSE; VkBool32 eds = VK_FALSE; VkBool32 eds2 = VK_FALSE; int features2_calls = 0; @@ -65,6 +66,7 @@ VKAPI_ATTR void VKAPI_CALL fake_get_features2(VkPhysicalDevice, VkPhysicalDevice f->synchronization2 = g_device->synchronization2; f->subgroupSizeControl = g_device->subgroup_size_control; f->computeFullSubgroups = g_device->compute_full_subgroups; + f->shaderIntegerDotProduct = g_device->integer_dot_product; break; } case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES_KHR: @@ -127,6 +129,28 @@ VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL fake_get_device_proc(VkDevice, const ch } // namespace int main() { + // shaderIntegerDotProduct (the translator's OpSDot / OpUDot) is enabled where a 1.3 device has it. + { + FakeDevice dev; + dev.dynamic_rendering = VK_TRUE; + dev.synchronization2 = VK_TRUE; + dev.integer_dot_product = VK_TRUE; + g_device = &dev; + Vulkan13Features v13; + v13.query(VK_NULL_HANDLE, VK_API_VERSION_1_3, fake_get_features2, nullptr); + EXPECT(v13.integer_dot_product); + Vulkan13Features chosen; + chosen.choose(v13); + EXPECT(chosen.integer_dot_product); + VkBaseOutStructure tail{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, nullptr}; + const auto* enable13 = static_cast(chosen.enable(&tail)); + EXPECT(enable13->shaderIntegerDotProduct == VK_TRUE); + // A 1.2 device goes without (make_game.py translates for it with --integer-dot-fallback). + Vulkan13Features v12; + v12.query(VK_NULL_HANDLE, VK_API_VERSION_1_2, fake_get_features2, nullptr); + EXPECT(!v12.integer_dot_product); + } + // Vulkan 1.3 core device: queries VkPhysicalDeviceVulkan13Features without enumerating extensions. { FakeDevice dev; @@ -152,6 +176,7 @@ int main() { EXPECT(enable13->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES); EXPECT(enable13->dynamicRendering == VK_TRUE && enable13->synchronization2 == VK_TRUE); EXPECT(enable13->subgroupSizeControl == VK_TRUE && enable13->computeFullSubgroups == VK_FALSE); + EXPECT(!v13.integer_dot_product && enable13->shaderIntegerDotProduct == VK_FALSE); EXPECT(enable13->pNext == &tail); // Inserting a later feature struct through next() places it between enable13 and tail. diff --git a/runtime/test/vulkan_device_markers_test.cpp b/runtime/test/vulkan_device_markers_test.cpp index 64693a83d5..3c79dbf1c7 100644 --- a/runtime/test/vulkan_device_markers_test.cpp +++ b/runtime/test/vulkan_device_markers_test.cpp @@ -1,13 +1,16 @@ // The AMD breadcrumbs of the device-fault report (src/vulkan_device_markers.h, LEONIDA_DEVICE_MARKERS=1), on the -// CPU: seq numbering, the marker writes a recorded dispatch makes, the history ring, and which dispatch the report -// calls the likely hang for given marker values. The driver is faked: its marker writes are logged, and a "GPU" -// applies a prefix of them to the mapped words, as a queue that stopped at that point would have. No GPU, no game -// data. +// CPU: seq numbering, the marker writes a recorded dispatch or draw makes, the history ring, and which dispatch or draw +// the report calls the likely hang for given marker values, with the lines that name it. The driver is faked: its +// marker writes are logged, and a "GPU" applies a prefix of them to the mapped words, as a queue that stopped at that +// point would have. No GPU, no game data. #include "../src/vulkan_device_fault.h" +#include "../src/vulkan_gpu_profile.h" +#include #include #include #include +#include #include #include @@ -104,7 +107,7 @@ void execute(std::size_t count) { } struct History { // a plain list in MarkerHistory::for_each order, for judge_markers - std::vector entries; + std::vector entries; template void for_each(Visit&& visit) const { for (const auto& d : entries) visit(d); @@ -124,7 +127,7 @@ int pure_logic() { EXPECT(ring.size() == MarkerHistory::capacity); std::uint64_t expect = 6, visited = 0; bool ordered = true; - ring.for_each([&](const MarkedDispatch& d) { ordered &= d.seq == expect++; ++visited; }); + ring.for_each([&](const MarkedWork& d) { ordered &= d.seq == expect++; ++visited; }); EXPECT(ordered && visited == MarkerHistory::capacity); // Two queues interleaved: compute has 1 3 5 6 8, direct has 2 4 7. @@ -256,6 +259,143 @@ int recorded(bool synchronization2) { return 0; } +bool contains(const std::string& text, const char* part) { + if (text.find(part) != std::string::npos) return true; + std::fprintf(stderr, "missing \"%s\" in:\n%s", part, text.c_str()); + return false; +} + +// Draws get marker pairs too, numbered with the dispatches, and the report names the draw the "GPU" stopped in: its +// kind and counts, its pipeline as the GPU profile names it, its list and command, and its place among the draws to the +// same targets. Also the device-fault address note, the draws in flight and an idle queue's next draw. +int draws() { + writes.clear(); + const auto memory = memory_types(); + DeviceFaultExtensions enabled; + enabled.markers = true; + const VkQueue direct = fake_handle(0x20); + const VkCommandBuffer cb = fake_handle(0x30); + DeviceFaultDiagnostics diagnostics(get_proc, VK_NULL_HANDLE, enabled, &memory, true); + diagnostics.add_queue(direct); + diagnostics.pipeline_names[4] = {"library/cs_example_a"}; + diagnostics.pipeline_names[7] = {"library/vs_example", nullptr, "library/ps_example"}; + diagnostics.pipeline_names[8] = {"library/ms_example", nullptr, "library/ps_mesh_example"}; + const std::array roots{}; + const VkImageView rt0 = fake_handle(0x41), rt1 = fake_handle(0x42); + const VkImageView depth = fake_handle(0x43), other = fake_handle(0x44); + const std::array gbuffer{rt0, VK_NULL_HANDLE, rt1}; // slot 1 unbound + const std::array single{other}; + const MarkedTargets pass_a = MarkedTargets::of(gbuffer, depth, {640, 480}); + const MarkedTargets pass_b = MarkedTargets::of(single, VK_NULL_HANDLE, {320, 240}); + EXPECT(pass_a.key && pass_a.colors == 2 && pass_a.depth && pass_a.key != pass_b.key && !pass_b.depth); + + auto s = diagnostics.begin_submission(diagnostics.next_execute_call(), direct, "direct", 2); + { + const CheckpointRecorder list0{nullptr, s, diagnostics.pipeline_names, 0}; + list0.dispatch(cb, 0, VK_NULL_HANDLE, 4, roots, {8, 1, 1}); // seq 1 + list0.dispatched(cb); + list0.draw(cb, 3, 7, marked_draw::indexed, {36, 2, 0}, pass_a); // seq 2 + list0.drawn(cb); + list0.draw(cb, 5, 7, marked_draw::indexed, {12, 1, 6}, pass_a); // seq 3 + list0.drawn(cb); + list0.draw(cb, 6, 8, marked_draw::mesh, {4, 2, 1}, pass_a); // seq 4 + list0.drawn(cb); + list0.draw(cb, 9, 7, 0, {3, 1, 0}, pass_b); // seq 5 + list0.drawn(cb); + } + { + const CheckpointRecorder list1{nullptr, s, diagnostics.pipeline_names, 1}; + list1.draw(cb, 0, 7, marked_draw::indexed | marked_draw::indirect | marked_draw::counted, {64, 20, 0}, + pass_b); // seq 6 + list1.drawn(cb); + list1.dispatch(cb, 1, VK_NULL_HANDLE, 4, roots, {1, 1, 1}); // seq 7 + list1.dispatched(cb); + } + EXPECT(writes.size() == 14); + for (std::size_t i = 0; i < writes.size(); ++i) // started, finished, ... with seqs 1..7, all in slot 0 + EXPECT(writes[i].marker == i / 2 + 1 && writes[i].offset == (i % 2 ? 4u : 0u) && + writes[i].stage == + std::uint64_t(i % 2 ? VK_PIPELINE_STAGE_2_BOTTOM_OF_PIPE_BIT : VK_PIPELINE_STAGE_2_TOP_OF_PIPE_BIT)); + // The dispatch list keeps dispatches only, with their seqs; draws are in the marker history. + EXPECT(s.dispatches.size() == 2 && s.dispatches[0].seq == 1 && s.dispatches[1].seq == 7); + EXPECT(s.marked.size() == 7 && s.marked[1].is_draw() && !s.marked[0].is_draw()); + EXPECT(s.marked[2].pass_command == 3 && s.marked[2].pass_draw == 2); // the second draw to pass_a + EXPECT(s.marked[3].pass_command == 3 && s.marked[3].pass_draw == 3); + EXPECT(s.marked[4].pass_command == 9 && s.marked[4].pass_draw == 1); // other targets: a new pass + EXPECT(s.marked[5].list == 1 && s.marked[5].pass_command == 0 && s.marked[5].pass_draw == 1); // a new list + diagnostics.publish(std::move(s)); + + // The pipeline as the GPU profile's lines call it. + const gpu_profile::Key graphics{gpu_profile::Kind::graphics, {"library/vs_example", nullptr, "library/ps_example"}}; + EXPECT(marked_pipeline_label(graphics.names, false, 7) == gpu_profile::label(graphics)); + const gpu_profile::Key mesh{gpu_profile::Kind::mesh, {"library/ms_example", nullptr, "library/ps_mesh_example"}}; + EXPECT(marked_pipeline_label(mesh.names, true, 8) == gpu_profile::label(mesh)); + gpu_profile::Key unnamed{gpu_profile::Kind::graphics}; + unnamed.id = 0x99; + EXPECT(marked_pipeline_label({}, false, 0x99) == gpu_profile::label(unnamed)); + + // The "GPU" ran seq 1 and 2, started 3 and stopped in it: 3 is the likely hang, 2 the last finished. + execute(5); + std::string text; + EXPECT(diagnostics.report_markers(true, &text) == std::vector({3})); + EXPECT(contains(text, " (direct) finished seq=2 started seq=3; started, not finished: 3\n")); + EXPECT(contains(text, "[rt] device-markers: finished: seq=2 execute=1 queue=")); + EXPECT(contains(text, " (direct) list=0 command=3 draw=indexed count=36 instances=2 pipeline=vs vs_example ps " + "ps_example pass=draw 1 since command 3 (2 colours + depth, 640x480)\n")); + EXPECT(contains(text, "[rt] device-markers: likely hang: seq=3 execute=1 queue=")); + EXPECT(contains(text, " (direct) list=0 command=5 draw=indexed count=12 instances=1 pipeline=vs vs_example ps " + "ps_example pass=draw 2 since command 3 (2 colours + depth, 640x480)\n")); + // With a fault address: the last draw the queue started. + std::string fault = diagnostics.marker_fault_draws(); + EXPECT(contains(fault, "[rt] device-fault: last started draw (device-markers): seq=3 execute=1")); + EXPECT(contains(fault, "list=0 command=5 draw=indexed count=12 instances=1 pipeline=vs vs_example ps ps_example")); + EXPECT(contains(fault, " (not finished) <- likely hang\n")); + + // Stopped inside the mesh dispatch, with the vertex draw after it started too: both in flight. + execute(7); // through seq 4 started, 3 finished + words[0] = 5; // seq 5 started + text.clear(); + EXPECT(diagnostics.report_markers(true, &text) == std::vector({4})); + EXPECT(contains(text, "likely hang: seq=4 execute=1 queue=")); + EXPECT(contains(text, " list=0 command=6 draw=mesh groups=4,2,1 pipeline=ms ms_example ps ps_mesh_example " + "pass=draw 3 since command 3 (2 colours + depth, 640x480)\n")); + EXPECT(contains(text, "[rt] device-markers: in flight: seq=5 execute=1 queue=")); + EXPECT(contains(text, " list=0 command=9 draw=vertices count=3 instances=1 pipeline=vs vs_example ps ps_example " + "pass=draw 1 since command 9 (1 colour, 320x240)\n")); + fault = diagnostics.marker_fault_draws(); + EXPECT(contains(fault, "seq=5 execute=1") && contains(fault, "(not finished)\n")); + + // Idle after seq 5: the next one, an indirect draw, was not started. + execute(10); + text.clear(); + EXPECT(diagnostics.report_markers(false, &text).empty()); + EXPECT(contains(text, "idle: finished seq=5, nothing started after it; next submitted seq=6 not started")); + EXPECT(contains(text, "[rt] device-markers: not started: seq=6 execute=1 queue=")); + EXPECT(contains(text, " list=1 command=0 draw=indexed-indirect-count max=64 stride=20 pipeline=vs vs_example ps " + "ps_example pass=draw 1 since command 0 (1 colour, 320x240)\n")); + fault = diagnostics.marker_fault_draws(); + EXPECT(contains(fault, "seq=5 execute=1") && contains(fault, "(finished)\n")); + // Everything ran: the last item is the dispatch, the last started draw seq 6, finished. + execute(writes.size()); + text.clear(); + EXPECT(diagnostics.report_markers(false, &text).empty()); + EXPECT(contains(text, "idle: finished seq=7, nothing started after it\n")); + EXPECT(contains(text, " list=1 command=1 shader=library/cs_example_a\n")); + EXPECT(contains(diagnostics.marker_fault_draws(), "seq=6 execute=1")); + + // Without the markers a draw writes nothing and takes no seq. + DeviceFaultDiagnostics plain(get_proc, VK_NULL_HANDLE, DeviceFaultExtensions{}); + auto off = plain.begin_submission(plain.next_execute_call(), direct, "direct", 1); + writes.clear(); + const CheckpointRecorder recorder{nullptr, off, plain.pipeline_names, 0}; + recorder.draw(cb, 0, 7, 0, {3, 1, 0}, pass_b); + recorder.drawn(cb); + recorder.dispatch(cb, 1, VK_NULL_HANDLE, 4, roots, {1, 1, 1}); + EXPECT(writes.empty() && off.marked.empty() && off.dispatches[0].seq == 1); + EXPECT(plain.marker_fault_draws().empty()); + return 0; +} + // Without LEONIDA_DEVICE_MARKERS the extension is not asked for, and with it only where the device has it. int extension_request() { const VkExtensionProperties with[] = {{VK_AMD_BUFFER_MARKER_EXTENSION_NAME, 1}}; @@ -294,6 +434,7 @@ int main() { if (int failed = pure_logic()) return failed; if (int failed = recorded(true)) return failed; if (int failed = recorded(false)) return failed; + if (int failed = draws()) return failed; if (int failed = extension_request()) return failed; std::puts("vulkan_device_markers: ok"); return 0; diff --git a/runtime/test/vulkan_title_image_pool_test.cpp b/runtime/test/vulkan_title_image_pool_test.cpp index 9666e70c02..5e6c07f9c8 100644 --- a/runtime/test/vulkan_title_image_pool_test.cpp +++ b/runtime/test/vulkan_title_image_pool_test.cpp @@ -7,7 +7,7 @@ namespace { unsigned allocated, freed, destroyed, next_type; bool fail_alloc, fail_bind; -VkDeviceSize last_offset; +VkDeviceSize last_offset, last_alloc_size; VKAPI_ATTR VkResult VKAPI_CALL bind_image(VkDevice, VkImage, VkDeviceMemory, VkDeviceSize offset) { last_offset = offset; return fail_bind ? VK_ERROR_OUT_OF_DEVICE_MEMORY : VK_SUCCESS; @@ -24,7 +24,8 @@ int main() { const auto make = [&] { const auto image = (VkImage)(std::uintptr_t(++next_image)); return pool.bind(VK_NULL_HANDLE, image, req, bind_image, destroy_image, free_memory, - [](VkDeviceSize, std::uint32_t& type) { + [](VkDeviceSize size, std::uint32_t& type) { + last_alloc_size = size; type = next_type; return fail_alloc ? VkDeviceMemory{} : (VkDeviceMemory)(std::uintptr_t(++allocated)); }); @@ -61,11 +62,28 @@ int main() { fail_alloc = true; CHECK(!make() && allocated == 4 && freed == 4); fail_alloc = false; - req.size++; - CHECK(!make() && allocated == 4); + + // > 2 MiB .. 8 MiB classes cap page_size at 16 MiB (no VRAM bloat) and pack stride * capacity tightly. + req = {5632u << 10, 65536, 2}; + for (int i = 0; i < 3; ++i) live.push_back(make()); + CHECK(live[0] && live[1] && live[2] && live[0]->page == live[1]->page && live[2]->page != live[1]->page); + CHECK(last_alloc_size <= (16u << 20) && allocated == 6); + live.clear(); + CHECK(freed == 6); + + req = {8u << 20, 65536, 2}; + for (int i = 0; i < 3; ++i) live.push_back(make()); + CHECK(live[0] && live[1] && live[2] && live[0]->page == live[1]->page && live[2]->page != live[1]->page); + CHECK(last_alloc_size == (16u << 20) && allocated == 8); + live.clear(); + CHECK(freed == 8); + + // > 8 MiB exceeds largest_slot and falls back to dedicated allocation. + req.size = (8u << 20) + 1; + CHECK(!make() && allocated == 8); req = {701440, 512, 2}; a = make(); b = make(); CHECK(a && b && a->page == b->page && last_offset % req.alignment == 0); CHECK(last_offset >= req.size && last_offset <= req.size + req.size / 8); - std::puts("title image pool alignment, type separation, retirement, reuse and fallback OK"); + std::puts("title image pool alignment, type separation, retirement, reuse, 8MiB/16MiB cap and fallback OK"); } diff --git a/runtime/test/xbox_list_value_fallback_test.cpp b/runtime/test/xbox_list_value_fallback_test.cpp index fe5718c522..98e88e54b1 100644 --- a/runtime/test/xbox_list_value_fallback_test.cpp +++ b/runtime/test/xbox_list_value_fallback_test.cpp @@ -12,9 +12,11 @@ #include "d3d12_test_shaders.h" #include "../shims/d3d12_com.h" #include "../shims/d3d12_xs_device.h" +#include "../shims/d3d12_xs_list_values.h" #include "../shims/shims.h" #include "../shims/xmem.h" #include "../src/title_page_watch.h" +#include "../src/title_texture_memory.h" #include #include @@ -217,6 +219,322 @@ int main() { CHECK(free_pages(1, &page)); std::puts("a write to a PAGE_NOACCESS page of xmem's lands through xmem's own mapping"); + // 4. Round 10 WS3: retroactive GPU-to-GPU wait relay (Wait-before-Signal across two queues -> relayed onto + // writer's written fence with zero unmet gate releases, and cycle preservation when after_gate != 0). + { + // Console list slot 74: wait64(address, comparison, reference, flags). + using WaitOp = void(WINAPI *)(void *, std::uintptr_t, std::uint32_t, std::uint64_t, std::uint32_t); + D3D12_COMMAND_QUEUE_DESC compute_desc{}; + compute_desc.Type = D3D12_COMMAND_LIST_TYPE_COMPUTE; + Ref compute_q; + Ref compute_alloc; + CHECK(SUCCEEDED(device->CreateCommandQueue(&compute_desc, IID_PPV_ARGS(&compute_q.p)))); + CHECK(SUCCEEDED(inner->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE, IID_PPV_ARGS(&compute_alloc.p)))); + + auto *slot_mem = + static_cast(VirtualAlloc(nullptr, 4096, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + CHECK(slot_mem); + slot_mem[0] = 0; + slot_mem[1] = 0; + leonida::title_va_aliases().add_title_memory(reinterpret_cast(slot_mem), 4096); + + // 4a. Direct submits Wait(slot_mem[0] >= 1) BEFORE Compute submits Write(slot_mem[0] = 1). + xs::reset_list_value_stats(); + std::uint64_t desc[4]{}; + std::uint64_t compute_list_desc[4]{static_cast(D3D12_COMMAND_LIST_TYPE_COMPUTE)}; + Ref wait_list, write_list; + CHECK(SUCCEEDED(reinterpret_cast(slot(device.p, 73))(device.p, desc, allocator.p, nullptr, + &__uuidof(ID3D12GraphicsCommandList), + reinterpret_cast(&wait_list.p)))); + reinterpret_cast(slot(wait_list.p, 74))( + wait_list.p, reinterpret_cast(slot_mem), 7 /*>=*/, 1, 0); + CHECK(SUCCEEDED(wait_list->Close())); + ID3D12CommandList *wl[1] = {wait_list.p}; + queue->ExecuteCommandLists(1, wl); + + Ref direct_done; + CHECK(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&direct_done.p)))); + CHECK(SUCCEEDED(queue->Signal(direct_done.p, 1))); + + // Now Compute submits the matching write: Pump::add_writes() retroactively relays Direct's gate! + CHECK(SUCCEEDED(reinterpret_cast(slot(device.p, 73))(device.p, compute_list_desc, compute_alloc.p, + nullptr, &__uuidof(ID3D12GraphicsCommandList), + reinterpret_cast(&write_list.p)))); + reinterpret_cast(slot(write_list.p, 72))( + write_list.p, reinterpret_cast(slot_mem), 1, 0, 0); + CHECK(SUCCEEDED(write_list->Close())); + ID3D12CommandList *wrl[1] = {write_list.p}; + compute_q->ExecuteCommandLists(1, wrl); + + CHECK(SUCCEEDED(direct_done->SetEventOnCompletion(1, nullptr))); + CHECK(xs::list_values_idle(4000)); + stats = xs::list_value_stats(); + CHECK(stats.waits_relayed >= 1); + CHECK(stats.gates_released == 0); + CHECK(InterlockedCompareExchange64(slot_mem, 0, 0) == 1); + + // 4b. Cycle preservation (after_gate != 0): Direct waits on slot_mem[0] >= 10 then writes slot_mem[1] = 10; + // Compute waits on slot_mem[1] >= 10 then writes slot_mem[0] = 10. Neither write group has after_gate == 0, + // so neither is retroactively relayed into a GPU cycle and list_value_progress breaks the cycle cleanly. + xs::reset_list_value_stats(); + Ref cyc_a, cyc_b; + CHECK(SUCCEEDED(reinterpret_cast(slot(device.p, 73))(device.p, desc, allocator.p, nullptr, + &__uuidof(ID3D12GraphicsCommandList), + reinterpret_cast(&cyc_a.p)))); + reinterpret_cast(slot(cyc_a.p, 74))( + cyc_a.p, reinterpret_cast(slot_mem), 7 /*>=*/, 10, 0); + reinterpret_cast(slot(cyc_a.p, 72))( + cyc_a.p, reinterpret_cast(slot_mem + 1), 10, 0, 0); + CHECK(SUCCEEDED(cyc_a->Close())); + CHECK(SUCCEEDED(reinterpret_cast(slot(device.p, 73))(device.p, compute_list_desc, compute_alloc.p, + nullptr, &__uuidof(ID3D12GraphicsCommandList), + reinterpret_cast(&cyc_b.p)))); + reinterpret_cast(slot(cyc_b.p, 74))( + cyc_b.p, reinterpret_cast(slot_mem + 1), 7 /*>=*/, 10, 0); + reinterpret_cast(slot(cyc_b.p, 72))( + cyc_b.p, reinterpret_cast(slot_mem), 10, 0, 0); + CHECK(SUCCEEDED(cyc_b->Close())); + + ID3D12CommandList *cal[1] = {cyc_a.p}; + ID3D12CommandList *cbl[1] = {cyc_b.p}; + queue->ExecuteCommandLists(1, cal); + compute_q->ExecuteCommandLists(1, cbl); + Ref cyc_done_a, cyc_done_b; + CHECK(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&cyc_done_a.p)))); + CHECK(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&cyc_done_b.p)))); + CHECK(SUCCEEDED(queue->Signal(cyc_done_a.p, 1))); + CHECK(SUCCEEDED(compute_q->Signal(cyc_done_b.p, 1))); + CHECK(SUCCEEDED(cyc_done_a->SetEventOnCompletion(1, nullptr))); + CHECK(SUCCEEDED(cyc_done_b->SetEventOnCompletion(1, nullptr))); + CHECK(xs::list_values_idle(4000)); + stats = xs::list_value_stats(); + CHECK(stats.waits_relayed == 0); + CHECK(stats.released_cycle >= 1); + + VirtualFree(const_cast(slot_mem), 0, MEM_RELEASE); + std::puts("retroactive Wait-before-Signal relay and after_gate!=0 cycle preservation ok"); + } + + // 4c. Round 10b WS-A (A1/A2/A3/A4): bare write groups force CPU visibility signal (no retro-relay, no + // signal_gpu_relay); exact-value/width/timestamp checks downgrade non-matching landed writes to cpu_met; + // stale wait_met re-check prevents premature retro-relay; relay_wait returning false preserves the gate. + { + namespace lv = rt::d3d12_xs::list_values; + using WaitOp = void(WINAPI *)(void *, std::uintptr_t, std::uint32_t, std::uint64_t, std::uint32_t); + + // Unit checks for Pump::match_landed() (A1 bare + A2 exact address/width/value/timestamp). + { + const lv::Wait w64{0x1000, 10, 7 /*>=*/, true}; + const lv::Wait w32{0x1000, 10, 7 /*>=*/, false}; + const lv::Pump::LandedRange exact_ok[] = {{0x1000, 10, 8, true, false}}; + const lv::Pump::LandedRange bare_ok[] = {{0x1000, 10, 8, true, true}}; + const lv::Pump::LandedRange low_val[] = {{0x1000, 5, 8, true, false}}; + const lv::Pump::LandedRange wrong_width[] = {{0x1000, 10, 4, true, false}}; + const lv::Pump::LandedRange wrong_addr[] = {{0x1004, 10, 4, true, false}}; + const lv::Pump::LandedRange timestamp_wr[] = {{0x1000, 10, 8, false, false}}; + const lv::Pump::LandedRange overwritten_low[] = {{0x1000, 10, 8, true, false}, {0x1000, 5, 8, true, false}}; + const lv::Pump::LandedRange bare_then_exec[] = {{0x1000, 10, 8, true, true}, {0x1000, 11, 8, true, false}}; + const lv::Pump::LandedRange unrelated[] = {{0x2000, 10, 8, true, false}}; + + CHECK(lv::Pump::match_landed(w64, exact_ok) == lv::Pump::LandedMatch::gpu_met); + CHECK(lv::Pump::match_landed(w64, bare_ok) == lv::Pump::LandedMatch::bare); + CHECK(lv::Pump::match_landed(w64, low_val) == lv::Pump::LandedMatch::val_mismatch); + CHECK(lv::Pump::match_landed(w64, wrong_width) == lv::Pump::LandedMatch::val_mismatch); + CHECK(lv::Pump::match_landed(w32, exact_ok) == lv::Pump::LandedMatch::val_mismatch); + CHECK(lv::Pump::match_landed(w64, wrong_addr) == lv::Pump::LandedMatch::val_mismatch); + CHECK(lv::Pump::match_landed(w64, timestamp_wr) == lv::Pump::LandedMatch::val_mismatch); + CHECK(lv::Pump::match_landed(w64, overwritten_low) == lv::Pump::LandedMatch::val_mismatch); + CHECK(lv::Pump::match_landed(w64, bare_then_exec) == lv::Pump::LandedMatch::bare); + CHECK(lv::Pump::match_landed(w64, unrelated) == lv::Pump::LandedMatch::none); + } + + D3D12_COMMAND_QUEUE_DESC compute_desc{}; + compute_desc.Type = D3D12_COMMAND_LIST_TYPE_COMPUTE; + Ref compute_q; + Ref compute_alloc; + CHECK(SUCCEEDED(device->CreateCommandQueue(&compute_desc, IID_PPV_ARGS(&compute_q.p)))); + CHECK(SUCCEEDED(inner->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE, IID_PPV_ARGS(&compute_alloc.p)))); + + auto *mem = + static_cast(VirtualAlloc(nullptr, 4096, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + CHECK(mem); + leonida::title_va_aliases().add_title_memory(reinterpret_cast(mem), 4096); + + static std::atomic gpu_relay_calls{0}; + struct HookGuard { + ~HookGuard() { + lv::signal_gpu_relay_hook() = nullptr; + lv::relay_wait_hook() = nullptr; + } + } hook_guard; + lv::signal_gpu_relay_hook() = [](ID3D12Fence *f, std::uint64_t v) -> HRESULT { + gpu_relay_calls.fetch_add(1, std::memory_order_relaxed); + return rt::d3d12::fence_signal_gpu_relay(f, v); + }; + + std::uint64_t direct_desc[4]{}; + std::uint64_t compute_list_desc[4]{static_cast(D3D12_COMMAND_LIST_TYPE_COMPUTE)}; + + // A1 live test: bare pre-write group (`[write64(mem[0]=1); wait64(mem[1]>=1)]` as first list of execute) + // releases held compute consumer -> NOT retro-relayed, NOT signaled via signal_gpu_relay, increments bare + // downgrade counter. + mem[0] = 0; + mem[1] = 0; + gpu_relay_calls.store(0, std::memory_order_relaxed); + xs::reset_list_value_stats(); + { + Ref wait_list, bare_list; + CHECK(SUCCEEDED(reinterpret_cast(slot(device.p, 73))( + device.p, compute_list_desc, compute_alloc.p, nullptr, &__uuidof(ID3D12GraphicsCommandList), + reinterpret_cast(&wait_list.p)))); + reinterpret_cast(slot(wait_list.p, 74))(wait_list.p, reinterpret_cast(mem), + 7 /*>=*/, 1, 0); + CHECK(SUCCEEDED(wait_list->Close())); + ID3D12CommandList *wl[1] = {wait_list.p}; + compute_q->ExecuteCommandLists(1, wl); + Ref compute_done; + CHECK(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&compute_done.p)))); + CHECK(SUCCEEDED(compute_q->Signal(compute_done.p, 1))); + + CHECK(SUCCEEDED(reinterpret_cast(slot(device.p, 73))( + device.p, direct_desc, allocator.p, nullptr, &__uuidof(ID3D12GraphicsCommandList), + reinterpret_cast(&bare_list.p)))); + // Pre-write before an unmet wait on the first list -> ValueSubmission::flush() runs with group_.empty()! + reinterpret_cast(slot(bare_list.p, 72))(bare_list.p, reinterpret_cast(mem), 1, 0, 0); + reinterpret_cast(slot(bare_list.p, 74))(bare_list.p, reinterpret_cast(mem + 1), + 7 /*>=*/, 1, 0); + CHECK(SUCCEEDED(bare_list->Close())); + ID3D12CommandList *bl[1] = {bare_list.p}; + queue->ExecuteCommandLists(1, bl); + Ref direct_done; + CHECK(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&direct_done.p)))); + CHECK(SUCCEEDED(queue->Signal(direct_done.p, 1))); + + CHECK(SUCCEEDED(compute_done->SetEventOnCompletion(1, nullptr))); + CHECK(gpu_relay_calls.load(std::memory_order_relaxed) == 0); + CHECK(lv::counters().gpu_relay_downgraded_bare.load(std::memory_order_relaxed) >= 1); + CHECK(xs::list_value_stats().waits_relayed == 0); + + InterlockedExchange64(mem + 1, 1); + CHECK(SUCCEEDED(direct_done->SetEventOnCompletion(1, nullptr))); + CHECK(xs::list_values_idle(4000)); + } + + // A2 live test: non-bare 32-bit write meeting a 64-bit wait AND non-bare GPU timestamp write meeting a 64-bit + // wait both downgrade to cpu_met (no signal_gpu_relay, increments gpu_relay_downgraded_val). + for (int kind = 0; kind < 2; ++kind) { + mem[0] = 0; + gpu_relay_calls.store(0, std::memory_order_relaxed); + xs::reset_list_value_stats(); + Ref wait_list, wr_list; + CHECK(SUCCEEDED(reinterpret_cast(slot(device.p, 73))( + device.p, direct_desc, allocator.p, nullptr, &__uuidof(ID3D12GraphicsCommandList), + reinterpret_cast(&wait_list.p)))); + reinterpret_cast(slot(wait_list.p, 74))(wait_list.p, reinterpret_cast(mem), + 7 /*>=*/, 1, 0); + CHECK(SUCCEEDED(wait_list->Close())); + ID3D12CommandList *wl[1] = {wait_list.p}; + queue->ExecuteCommandLists(1, wl); + Ref done; + CHECK(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&done.p)))); + CHECK(SUCCEEDED(queue->Signal(done.p, 1))); + + CHECK(SUCCEEDED(reinterpret_cast(slot(device.p, 73))( + device.p, compute_list_desc, compute_alloc.p, nullptr, &__uuidof(ID3D12GraphicsCommandList), + reinterpret_cast(&wr_list.p)))); + if (kind == 0) { + // 32-bit write (slot 71) overlapping 64-bit wait -> width mismatch downgrade. + reinterpret_cast(slot(wr_list.p, 71))(wr_list.p, reinterpret_cast(mem), 1, 0, 0); + } else { + // GPU timestamp write (slot 72, flags=1) -> exact_value == false downgrade. + reinterpret_cast(slot(wr_list.p, 72))(wr_list.p, reinterpret_cast(mem), 0, 0, 1); + } + CHECK(SUCCEEDED(wr_list->Close())); + ID3D12CommandList *wrl[1] = {wr_list.p}; + compute_q->ExecuteCommandLists(1, wrl); + + CHECK(SUCCEEDED(done->SetEventOnCompletion(1, nullptr))); + CHECK(xs::list_values_idle(4000)); + CHECK(gpu_relay_calls.load(std::memory_order_relaxed) == 0); + CHECK(lv::counters().gpu_relay_downgraded_val.load(std::memory_order_relaxed) >= 1); + } + + // A4 live test: when relay_wait returns false (nothing substituted), apply_retroactive_relays preserves the + // gate so Pump still opens it when the write lands. + mem[0] = 0; + gpu_relay_calls.store(0, std::memory_order_relaxed); + xs::reset_list_value_stats(); + lv::relay_wait_hook() = [](ID3D12Fence *, std::uint64_t, std::span) -> bool { + return false; + }; + { + Ref wait_list, wr_list; + CHECK(SUCCEEDED(reinterpret_cast(slot(device.p, 73))( + device.p, direct_desc, allocator.p, nullptr, &__uuidof(ID3D12GraphicsCommandList), + reinterpret_cast(&wait_list.p)))); + reinterpret_cast(slot(wait_list.p, 74))(wait_list.p, reinterpret_cast(mem), + 7 /*>=*/, 1, 0); + CHECK(SUCCEEDED(wait_list->Close())); + ID3D12CommandList *wl[1] = {wait_list.p}; + queue->ExecuteCommandLists(1, wl); + Ref done; + CHECK(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&done.p)))); + CHECK(SUCCEEDED(queue->Signal(done.p, 1))); + + CHECK(SUCCEEDED(reinterpret_cast(slot(device.p, 73))( + device.p, compute_list_desc, compute_alloc.p, nullptr, &__uuidof(ID3D12GraphicsCommandList), + reinterpret_cast(&wr_list.p)))); + reinterpret_cast(slot(wr_list.p, 72))(wr_list.p, reinterpret_cast(mem), 1, 0, 0); + CHECK(SUCCEEDED(wr_list->Close())); + ID3D12CommandList *wrl[1] = {wr_list.p}; + compute_q->ExecuteCommandLists(1, wrl); + + CHECK(SUCCEEDED(done->SetEventOnCompletion(1, nullptr))); + CHECK(xs::list_values_idle(4000)); + stats = xs::list_value_stats(); + CHECK(stats.waits_relayed == 0); + CHECK(stats.gates_met >= 1); + CHECK(stats.gates_released == 0); + CHECK(gpu_relay_calls.load(std::memory_order_relaxed) >= 1); // non-bare exact match still uses vis-0! + } + + VirtualFree(const_cast(mem), 0, MEM_RELEASE); + std::puts("WS-A bare downgrade, exact-value/width/timestamp downgrade, and relay_wait false preservation ok"); + } + + // 5. Round 10 WS3: TextureVqCache negative caching & hoisted host_stop over fragmented VMAs. + { + constexpr SIZE_T kSpan = 4 * kPage64k; + auto *region = static_cast(VirtualAlloc(nullptr, kSpan, MEM_RESERVE, PAGE_READWRITE)); + CHECK(region); + const auto base = reinterpret_cast(region); + leonida::TextureVqCache cache; + + // Reserved (uncommitted) pool caches negative readability across probes in the same region. + CHECK(leonida::texture_memory_readable_bytes(base, kPage64k, nullptr, &cache) == 0); + CHECK(!cache.readable && cache.lo <= base && cache.hi >= base + kSpan); + CHECK(leonida::texture_memory_readable_bytes(base + kPage64k, kPage64k, nullptr, &cache) == 0); + CHECK(!cache.readable); + + // Commit all 4 tiles, notify title_memory_map, and fragment alternating RO/RW 64 KiB VMAs. + CHECK(VirtualAlloc(region, kSpan, MEM_COMMIT, PAGE_READWRITE) == region); + leonida::title_memory_map::changed(base, base + kSpan); + DWORD old_prot = 0; + CHECK(VirtualProtect(region, kPage64k, PAGE_READONLY, &old_prot)); + CHECK(VirtualProtect(region + 2 * kPage64k, kPage64k, PAGE_READONLY, &old_prot)); + CHECK(leonida::texture_memory_readable_bytes(base, kSpan, nullptr, &cache) == kSpan); + CHECK(cache.readable); + + // PAGE_NOACCESS in the middle stops readability and populates negative cache entry. + CHECK(VirtualProtect(region + 2 * kPage64k, kPage64k, PAGE_NOACCESS, &old_prot)); + leonida::title_memory_map::changed(base + 2 * kPage64k, base + 3 * kPage64k); + CHECK(leonida::texture_memory_readable_bytes(base, kSpan, nullptr, &cache) == 2 * kPage64k); + CHECK(!cache.readable && cache.lo == base + 2 * kPage64k && cache.hi == base + 3 * kPage64k); + + VirtualFree(region, 0, MEM_RELEASE); + std::puts("TextureVqCache negative caching and fragmented VMA readability ok"); + } + CHECK(gpu.validation_errors() == 0); return 0; } diff --git a/runtime/test/xg_xs_test.cpp b/runtime/test/xg_xs_test.cpp index 228c198ec6..541bb3f087 100644 --- a/runtime/test/xg_xs_test.cpp +++ b/runtime/test/xg_xs_test.cpp @@ -473,7 +473,7 @@ int main() { for (unsigned pass = 0; pass < 3; ++pass) poll([] { return true; }); check(polled == std::vector{4}, "an expired wall budget advances past priority entries to the next texture"); - // LEONIDA_TITLE_EVERY_BUDGET_US: the marked textures (mapped or stale) are visited from a cursor of their own + // visit_marked_title_textures: the marked textures (mapped or stale) are visited from a cursor of their own // until the budget runs out; the unmarked ones are the round robin's and are skipped here. { Entry m1{true, false, 11}, u1{false, false, 12}, s1{false, true, 13}, m2{true, false, 14}; diff --git a/runtime/test/xmem_test.cpp b/runtime/test/xmem_test.cpp index 79f6554128..4397639794 100644 --- a/runtime/test/xmem_test.cpp +++ b/runtime/test/xmem_test.cpp @@ -31,6 +31,8 @@ #include "startup_trace.h" #include "xmem.h" #include "../src/title_page_watch.h" +#include "../src/title_mirror_space.h" +#include // 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 @@ -693,10 +695,32 @@ bool access_faults(volatile uint32_t* address, bool write); // The same hook on a GPU-only destination: the title reserves a CPU-mappable range and a GPU-only one of the same size // right after it (title_gpu_views), and the D3D12 layer reads the GPU-only range's memory at the CPU range's address. -// A batch copy onto the GPU-only range maps the same pages at the CPU range too, so that memory becomes readable there. +// A batch copy onto the GPU-only range gives both its pages and the paired CPU pages their physical pages in xmem's +// table alone: no host view at either, as on the console, where the call edits GPU page tables only. The host reads +// and writes them through their frames (src/title_frames.h), and guards them at their physical pages' host views. No +// host map at all for a paired range (rt::xmem::slot31_mapping_counts). void test_copy_page_mappings_cpu_view(const PhysicalApi& api) { const auto copy = rt::xmem::copy_page_mappings_fn; if (!copy) return; // test_copy_page_mappings reports it + rt::xmem::Slot31Counts base{}; + rt::xmem::slot31_mapping_counts(base); + const auto counted = [&](uint64_t gpu_pages, uint64_t twin_pages, uint64_t kept, uint64_t unpaired, + uint64_t replaced) { + rt::xmem::Slot31Counts c{}; + rt::xmem::slot31_mapping_counts(c); + const bool ok = c.gpu_pages - base.gpu_pages == gpu_pages && c.twin_pages - base.twin_pages == twin_pages && + c.twins_kept - base.twins_kept == kept && c.unpaired_pages - base.unpaired_pages == unpaired && + c.views_replaced - base.views_replaced == replaced; + if (!ok) + std::fprintf(stderr, " slot-31 pages so far: %llu GPU-only and %llu twins by table, %llu twins kept, %llu " + "unpaired and %llu views replaced by host\n", + static_cast(c.gpu_pages - base.gpu_pages), + static_cast(c.twin_pages - base.twin_pages), + static_cast(c.twins_kept - base.twins_kept), + static_cast(c.unpaired_pages - base.unpaired_pages), + static_cast(c.views_replaced - base.views_replaced)); + return ok; + }; constexpr uint64_t kPool = 2, kPair = 3; auto* const pool = static_cast(api.virtual_alloc( nullptr, kPool * kPage64k, MEM_RESERVE | kXmem64kPages, 0x23, PAGE_READWRITE | PAGE_GRAPHICS_READWRITE)); @@ -717,45 +741,100 @@ void test_copy_page_mappings_cpu_view(const PhysicalApi& api) { check(api.map(pool, kPool, pages) == pool, "the pool maps its pages"); for (uint64_t i = 0; i < kPool; ++i) fill_page(pool + i * kPage64k, 0x7300u + static_cast(i)); - // A run onto the GPU-only range: its CPU range shows the same bytes. Each page is read under a guard first, so a - // page left reserved fails its check instead of faulting the test (Wine's VirtualQuery does not report a view - // mapped into a placeholder as committed, so the state is not asked for). + // Each page is read under a guard first, so a page left reserved fails its check instead of faulting the test + // (Wine's VirtualQuery does not report a view mapped into a placeholder as committed, so the state is not asked + // for). A table page is read through its frame. const auto readable = [](const uint8_t* page) { return !access_faults(reinterpret_cast(const_cast(page)), false); }; + const auto frame_holds = [](const uint8_t* page, uint32_t tag) { + leonida::title_frames::Frame frame; + return leonida::title_frames::find(reinterpret_cast(page), frame) && page_holds(frame.bytes, tag); + }; + const auto backed = [](const uint8_t* page) { return leonida::title_frames::backed(reinterpret_cast(page)); }; + const auto frame_word = [](const uint8_t* at) { + leonida::title_frames::Frame frame; + return leonida::title_frames::find(reinterpret_cast(at), frame) ? read_u32(frame.bytes, 0) : 0u; + }; + + // A run onto the GPU-only range: no host call at all. Both ranges are table pages, holding the pool's pages. check(copy(gpu, pool, kPool, false), "a run of pool pages maps onto the GPU-only range"); - check(readable(gpu) && page_holds(gpu, 0x7300u), "the GPU-only range shows the pool pages"); - check(readable(cpu) && readable(cpu + kPage64k), "the paired CPU range is readable after the copy"); - check(readable(cpu) && readable(cpu + kPage64k) && page_holds(cpu, 0x7300u) && page_holds(cpu + kPage64k, 0x7301u), - "the paired CPU range shows the same bytes as the pool"); - check(!readable(cpu + 2 * kPage64k), "a CPU page past the copied run stays unmapped"); - if (readable(cpu + kPage64k)) { - static_cast(static_cast(cpu + kPage64k))[1] = 0xc0ffee32; - check(read_u32(pool + kPage64k, 4) == 0xc0ffee32 && read_u32(gpu + kPage64k, 4) == 0xc0ffee32, - "a write at the CPU range is seen in the pool and the GPU-only range: one memory"); - } - - // A GPU-only source whose page is mapped only at its CPU range is found there. + check(!readable(gpu) && !readable(gpu + kPage64k), "the GPU-only range has no host view: a table entry only"); + check(!readable(cpu) && !readable(cpu + kPage64k), "the paired CPU range has no host view either"); + check(counted(kPool, kPool, 0, 0, 0), "no host remap: the GPU-only pages and their CPU twins by table"); + check(frame_holds(cpu, 0x7300u) && frame_holds(cpu + kPage64k, 0x7301u) && frame_holds(gpu, 0x7300u), + "the paired CPU range reads the pool's bytes through the frame table"); + check(!backed(cpu + 2 * kPage64k) && !readable(cpu + 2 * kPage64k), "a CPU page past the copied run stays unmapped"); + // The title's CPU still writes the page through its own mapping (the pool): the table page shows it, and names + // that mapping as its other address, where the D3D12 layer's shadows and watches guard it. + static_cast(static_cast(pool + kPage64k))[1] = 0xc0ffee32; + check(frame_word(cpu + kPage64k + 4) == 0xc0ffee32, "a write through the title's own mapping is seen at the twin"); + std::vector peers; + rt::xmem::geometry_aliases(reinterpret_cast(cpu + kPage64k), peers); + check(peers.size() == 1 && peers[0] == reinterpret_cast(pool + kPage64k), + "the twin's other address is the title's own mapping of its page"); + bool aliased = false; + leonida::title_page_aliases::for_each_in(reinterpret_cast(cpu), reinterpret_cast(cpu) + 1, + [&](uintptr_t) { aliased = true; }); + check(aliased, "a table page is aliased: written only through other addresses"); + // A host writer (DirectStorage's copy into a request's destination) writes the frame, seen at the pool. + const uint32_t value = 0x5eed0031; + check(leonida::kernel_writes::write(cpu + 8, &value, sizeof(value)) && read_u32(pool, 8) == value, + "a host write into a table page lands in its physical page"); + check(leonida::kernel_writes::store(cpu + kPage64k + 16, 0x5eed0032, 4) && read_u32(pool + kPage64k, 16) == 0x5eed0032, + "a value store into a table page lands in its physical page"); + + // A remap of a table page is a table update too: the next read through it sees the new page, and no host call. + check(copy(gpu, pool + kPage64k, 1, false), "a remap of a GPU-only page"); + check(counted(kPool + 1, kPool + 1, 0, 0, 0), "the remap took no host call"); + check(frame_word(cpu + 4) == 0xc0ffee32 && frame_word(gpu + 4) == 0xc0ffee32, + "a read after the remap sees the new page at the GPU-only page and its twin"); + check(copy(gpu, pool, 1, false) && frame_word(cpu + 8) == value, "and the page before it after a remap back"); + + // A GPU-only source page is found in the table; one mapped only at its CPU range is found there. check(api.map(cpu + 2 * kPage64k, 1, &pages[0]) == cpu + 2 * kPage64k, "a page maps at the CPU range alone"); check(copy(other, gpu + 2 * kPage64k, 1, false), "a copy from the GPU-only range maps"); - check(readable(other) && page_holds(other, 0x7300u), + check(counted(kPool + 2, kPool + 2, 0, 1, 0), "a destination with no CPU pair is mapped on the host"); + check(readable(other) && read_u32(other, 8) == value, "a GPU-only source page unmapped there is looked up at its CPU range"); // 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), + check(counted(kPool + 3, kPool + 2, 1, 1, 0), "the GPU-only page took the pool page by table, the twin was kept"); + // The table is what later copies read: a copy from that GPU-only page brings the pool page it was given. + check(copy(other, gpu + 2 * kPage64k, 1, false) && readable(other) && read_u32(other, 4) == 0xc0ffee32, + "a copy from the GPU-only page finds the page its table entry holds"); + check(readable(cpu + 2 * kPage64k) && !backed(cpu + 2 * kPage64k) && read_u32(cpu + 2 * kPage64k, 8) == value, "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), + check(!readable(gpu + 2 * kPage64k) && !backed(gpu + 2 * kPage64k), "the GPU-only page is unmapped"); + check(readable(cpu + 2 * kPage64k) && read_u32(cpu + 2 * kPage64k, 8) == value, "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. + // A null source empties both ranges' table entries 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"); + check(!backed(gpu) && !backed(cpu) && !backed(cpu + kPage64k) && !readable(cpu), + "the paired CPU range leaves the table with it"); + check(copy(other, gpu, 1, false) && !readable(other), "the GPU-only page's table entry is gone: a copy of it is a hole"); + + // A page the title mapped itself into the GPU-only range (XMemMapPhysicalPages) is a host view: a copy onto it + // unmaps that view once and keeps the page in the table; the title's own unmap of the range clears the table too. + check(api.map(gpu, 1, &pages[1]) == gpu && readable(gpu) && read_u32(gpu, 4) == 0xc0ffee32, + "the title maps a page into the GPU-only range itself"); + rt::xmem::Slot31Counts before{}; + rt::xmem::slot31_mapping_counts(before); + check(copy(gpu, pool, 1, false) && !readable(gpu) && backed(gpu), "a copy onto it replaces the host view by a table entry"); + rt::xmem::Slot31Counts after{}; + rt::xmem::slot31_mapping_counts(after); + check(after.views_replaced - before.views_replaced == 1, "the title's view there was unmapped once"); + check(copy(other, gpu, 1, false) && readable(other) && read_u32(other, 8) == value, "the table entry holds the copied page"); + // The title maps a page of its own at the twin the copy gave a table entry: the host view replaces the entry. + check(backed(cpu) && api.map(cpu, 1, &pages[1]) == cpu && !backed(cpu) && readable(cpu) && + read_u32(cpu, 4) == 0xc0ffee32, + "the title's own mapping at a table twin replaces the table entry"); + check(api.map(gpu, 1, nullptr) == gpu && api.map(cpu, 1, nullptr) == cpu, "the title unmaps both pages"); + check(!backed(gpu) && copy(other, gpu, 1, false) && !readable(other), "after the title's unmap the table entry is gone"); api.map(other, 1, nullptr); api.map(cpu, kPair, nullptr); @@ -763,6 +842,129 @@ void test_copy_page_mappings_cpu_view(const PhysicalApi& api) { check(api.free_pages(kPool, pages) == TRUE, "the pool's pages are freed"); } +// A physical page number the title frees comes back with its next allocation (the free slots are reused last in, first +// out), now naming another page of memory. A slot-31 copy of that number onto a table page that still holds the freed +// page's number must give it the new page: the table's frame is the memory behind the number now, not the one it was +// given before (the readers of a stream pool's pages read through it: a stale frame showed them the freed page's +// bytes). +void test_copy_page_mappings_reused_number(const PhysicalApi& api) { + const auto copy = rt::xmem::copy_page_mappings_fn; + if (!copy) return; // test_copy_page_mappings reports it + auto* const pool = static_cast(api.virtual_alloc( + nullptr, kPage64k, MEM_RESERVE | kXmem64kPages, 0x23, PAGE_READWRITE | PAGE_GRAPHICS_READWRITE)); + auto* const cpu = static_cast(api.virtual_alloc( + nullptr, kPage64k, MEM_RESERVE | kXmem64kPages, 0x23, PAGE_READWRITE | PAGE_GRAPHICS_READWRITE)); + auto* const gpu = static_cast( + api.virtual_alloc(nullptr, kPage64k, MEM_RESERVE | kXmem64kPages, 0x3, 0x801)); + check(pool && cpu && gpu, "XMemVirtualAlloc reserves a pool and a CPU + GPU-only pair"); + if (!pool || !cpu || !gpu) return; + const auto frame_word = [](const uint8_t* at) { + leonida::title_frames::Frame frame; + return leonida::title_frames::find(reinterpret_cast(at), frame) ? read_u32(frame.bytes, 0) : 0u; + }; + uint64_t first = 0, count = 1; + check(api.allocate(0x280, &count, &first) == TRUE && count == 1 && api.map(pool, 1, &first) == pool, + "a page for the pool"); + fill_page(pool, 0x7500u); + check(copy(gpu, pool, 1, false) && frame_word(gpu) == 0x7500u && frame_word(cpu) == 0x7500u, + "the GPU-only page and its twin take the pool's page"); + // The title lets the page go and allocates again: the same number, another page of memory. + check(api.map(pool, 1, nullptr) == pool && api.free_pages(1, &first) == TRUE, "the title frees the page"); + uint64_t second = 0; + count = 1; + check(api.allocate(0x280, &count, &second) == TRUE && count == 1 && second == first, + "the next allocation reuses the freed page's number"); + check(api.map(pool, 1, &second) == pool, "the pool maps the new page"); + fill_page(pool, 0x7600u); + check(copy(gpu, pool, 1, false), "a copy of the reused number onto the table pages"); + check(frame_word(gpu) == 0x7600u && frame_word(cpu) == 0x7600u, + "the table pages read the new page behind the number, not the freed one"); + check(copy(gpu, nullptr, 1, false) && api.map(pool, 1, nullptr) == pool && api.free_pages(1, &second) == TRUE, + "the pages are unmapped and freed"); +} + +// The page mirror's side of xmem (src/title_mirror_space.h, src/title_frames.h Feed): a reservation the title lets +// xmem place lands in the mirror's range, below the address RADV's sparse range allows at heap_base + it; and every change +// of what a page there shows (a host view mapped or unmapped, a slot-31 copy onto a GPU-only page and its twin) reaches +// the feed in order, with the physical page's bytes, and the pages mapped before the feed was attached come first. +struct MirrorFeedLog { + struct Entry { + uintptr_t page; + uint8_t* frame; + }; + std::vector entries; + static void feed(void* context, uintptr_t page, uint8_t* frame, const std::shared_ptr&) { + static_cast(context)->entries.push_back({page, frame}); + } + // The last entry for `page`: its frame (null: unmapped), or false when there is none. + bool last(uintptr_t page, uint8_t*& frame) const { + for (auto it = entries.rbegin(); it != entries.rend(); ++it) + if (it->page == page) { + frame = it->frame; + return true; + } + return false; + } +}; + +void test_mirror_space_and_feed(const PhysicalApi& api) { + const auto copy = rt::xmem::copy_page_mappings_fn; + const auto attach = leonida::title_frames::attach_fn.load(); + check(attach != nullptr, "xmem sets the page mirror's attach hook"); + if (!copy || !attach) return; + namespace space = leonida::title_mirror_space; + auto* const pool = static_cast(api.virtual_alloc( + nullptr, 2 * kPage64k, MEM_RESERVE | kXmem64kPages, 0x23, PAGE_READWRITE | PAGE_GRAPHICS_READWRITE)); + auto* const cpu = static_cast(api.virtual_alloc( + nullptr, 2 * kPage64k, MEM_RESERVE | kXmem64kPages, 0x23, PAGE_READWRITE | PAGE_GRAPHICS_READWRITE)); + auto* const gpu = static_cast( + api.virtual_alloc(nullptr, 2 * kPage64k, MEM_RESERVE | kXmem64kPages, 0x3, 0x801)); + auto* const plain = static_cast(api.virtual_alloc(nullptr, kPage64k, MEM_RESERVE | MEM_COMMIT, 0x23, + PAGE_READWRITE)); + check(pool && cpu && gpu && plain, "XMemVirtualAlloc reserves windows, a pair and committed memory"); + if (!pool || !cpu || !gpu || !plain) return; + if (!space::enabled()) { + std::puts("SKIP mirror space: LEONIDA_PAGE_MIRROR=0"); + return; + } + check(space::contains(uintptr_t(pool)) && space::contains(uintptr_t(cpu)) && space::contains(uintptr_t(gpu)) && + space::contains(uintptr_t(plain)), + "reservations xmem places lie in the page mirror's range"); + check(uintptr_t(cpu) < uintptr_t(gpu) && leonida::title_gpu_views::other_view(uintptr_t(gpu)) == uintptr_t(cpu), + "the pair is still made: the GPU-only reservation pairs with the CPU one before it"); + plain[0] = 7; + check(plain[0] == 7, "committed memory placed there is usable"); + uint64_t pages[2]{}, count = 2; + check(api.allocate(0x280, &count, pages) == TRUE && count == 2, "pages for the mirror test"); + check(api.map(pool, 1, &pages[0]) == pool, "a page mapped before the feed is attached"); + fill_page(pool, 0x7700u); + + MirrorFeedLog log; + attach(&log, &MirrorFeedLog::feed); + uint8_t* frame = nullptr; + check(log.last(uintptr_t(pool), frame) && frame && page_holds(frame, 0x7700u), + "attaching feeds the pages mapped now, with their bytes"); + const std::size_t at_attach = log.entries.size(); + check(api.map(pool + kPage64k, 1, &pages[1]) == pool + kPage64k && log.last(uintptr_t(pool + kPage64k), frame) && frame, + "a host view mapped later is fed"); + check(copy(gpu, pool, 2, false), "a slot-31 copy onto the GPU-only pair"); + uint8_t* gpu_frame = nullptr; + uint8_t* twin_frame = nullptr; + check(log.last(uintptr_t(gpu), gpu_frame) && log.last(uintptr_t(cpu), twin_frame) && gpu_frame && + gpu_frame == twin_frame && page_holds(gpu_frame, 0x7700u), + "the GPU-only page and its twin are fed the copied page (table updates)"); + check(log.entries.size() > at_attach + 2, "each change is its own entry"); + check(copy(gpu, nullptr, 2, false) && log.last(uintptr_t(gpu), gpu_frame) && !gpu_frame && + log.last(uintptr_t(cpu), twin_frame) && !twin_frame, + "an unmap is fed as nothing shown"); + check(api.map(pool, 2, nullptr) == pool && log.last(uintptr_t(pool), frame) && !frame, "a host unmap is fed"); + attach(nullptr, nullptr); + const std::size_t detached = log.entries.size(); + check(api.map(pool, 1, &pages[0]) == pool && log.entries.size() == detached, "nothing is fed once detached"); + api.map(pool, 1, nullptr); + check(api.free_pages(2, pages) == TRUE, "the mirror test's pages are freed"); +} + bool access_faults(volatile uint32_t* address, bool write) { __try { if (write) { @@ -2706,6 +2908,8 @@ int main(int argc, char** argv) { } test_copy_page_mappings(physical); test_copy_page_mappings_cpu_view(physical); + test_copy_page_mappings_reused_number(physical); + test_mirror_space_and_feed(physical); test_stream_cpu_twin(physical); test_unowned_guards(physical); test_physical_pages_commit_on_touch(physical); diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index 7735c4112c..c5ecd2320f 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -4057,7 +4057,6 @@ int check_list_values() { EXPECT(device); mock->zero_fences = true; // the gate and write fences start at 0: nothing is reached before the test says so xs::reset_list_value_stats(); - xs::set_list_value_wait_timeout_ms(5000); void* qa = make_queue(device); void* qb = make_queue(device); EXPECT(qa && qb); @@ -4121,7 +4120,7 @@ int check_list_values() { fence_signal(a_written, 2); EXPECT(xs::list_values_idle(2000) && cell(3) == 5 && fence_completed(b_gate) == 1); stats = xs::list_value_stats(); - EXPECT(stats.waits_recorded == 1 && stats.gates_held == 1 && stats.gates_met == 1 && stats.gates_timed_out == 0); + EXPECT(stats.waits_recorded == 1 && stats.gates_held == 1 && stats.gates_met == 1 && stats.gates_released == 0); // 3. A wait a write in flight will meet is relayed: the waiter's queue waits on the writer's fence value. EXPECT(hr_of(raw(lw, 139, word(allocator), 0)) == S_OK); @@ -4143,22 +4142,26 @@ int check_list_values() { EXPECT(xs::list_values_idle(2000) && cell(4) == 9); // 4. A met wait costs nothing (a 32-bit one ignores the high half of memory); an unmet one that nothing meets - // is bounded: the gate opens after the timeout. + // is held, past the old 200 ms timeout, until the title presents: a present queued behind it with nothing else + // able to run releases it, counted and logged with the reason. g_cells[5] = 0xffffffff00000077ull; - xs::set_list_value_wait_timeout_ms(30); EXPECT(hr_of(raw(lv, 139, word(allocator), 0)) == S_OK); raw(lv, 73, word(&g_cells[5]), 3, 0x77, 1); // wait32(address, ==, 0x77): met now raw(lv, 73, word(&g_cells[6]), 3, 0x77, 1); // never written raw(lv, 14, 1, 1, 1); EXPECT(hr_of(raw(lv, 9)) == S_OK); g_queue_call_count = 0; - const ULONGLONG started = GetTickCount64(); EXPECT(submit(qb, lv) == 0); EXPECT(g_queue_call_count == 2 && queue_call_is(0, qb_mock, 15, word(b_gate), 2)); - EXPECT(xs::list_values_idle(3000) && fence_completed(b_gate) == 2 && GetTickCount64() - started >= 20); + EXPECT(!xs::list_values_idle(400) && fence_completed(b_gate) == 1); // held: no timeout stats = xs::list_value_stats(); - EXPECT(stats.gates_timed_out == 1 && stats.waits_met_at_submit >= 1); - xs::set_list_value_wait_timeout_ms(5000); + EXPECT(stats.gates_released == 0 && stats.waits_met_at_submit >= 1); + const ULONGLONG presented = GetTickCount64(); + xs::note_list_value_present(); + EXPECT(xs::list_values_idle(3000) && fence_completed(b_gate) == 2 && GetTickCount64() - presented < 1000); + stats = xs::list_value_stats(); + EXPECT(stats.gates_released == 1 && stats.released_present == 1 && stats.released_cycle == 0 && + stats.released_stalled == 0 && stats.met_after_release == 0); // 5. Memory the title's CPU writes opens a gate too (the pump looks at it while a gate is held). EXPECT(hr_of(raw(lv, 139, word(allocator), 0)) == S_OK); @@ -4229,7 +4232,7 @@ int check_list_values() { // 8. Writes before a part's first wait (no work yet) land before the queue stands at it, without a cut: the // title's direct lists write job tags as their first calls and then wait for compute results whose lists wait - // for those tags; a gate ahead of the writes would hold both queues until the timeout. + // for those tags; a gate ahead of the writes would hold both queues until nothing else could run. EXPECT(hr_of(raw(lw, 139, word(allocator), 0)) == S_OK); raw(lw, 72, word(&g_cells[3]), 0x55, 0, 0); // write64 first raw(lw, 74, word(&g_cells[7]), 7, 2, 1); // then a wait (memory holds 1) @@ -4272,13 +4275,14 @@ int check_list_values() { EXPECT(a_gate->refs == 0 && a_written->refs == 0 && b_gate->refs == 0 && b_written->refs == 0); EXPECT(release(device) == 0 && mock->refs == 0); std::printf("%s: list memory writes land after their part, waits hold their part behind a gate (relayed onto a " - "write in flight, bounded by a timeout), and a wait after work cuts the list with its state replayed\n", + "write in flight, released unmet only when nothing else can run), and a wait after work cuts the list " + "with its state replayed\n", g_label); return 0; } // ---- 15. List values, the rest: LEONIDA_LIST_VALUES=0, bundles, ClearState, root constants, landing order across -// queues, the short timeout for every wait, CopyPageMappingsBatchX behind held work, value stores, the exit ---- +// queues, holding and releasing waits, CopyPageMappingsBatchX behind held work, value stores, the exit ---- alignas(64) std::uint64_t g_cells2[32]; @@ -4306,6 +4310,12 @@ std::uint64_t logged_signal(const Mock* queue, const Mock* fence) { return 0; } +// The write fence whose Signals the test says the layer holds (section 5c, 11c): not running work. +Mock* g_held_fence = nullptr; +bool held_fence_hook(ID3D12Fence* fence, std::uint64_t) { + return reinterpret_cast(fence) != g_held_fence; +} + DWORD WINAPI tear_reader(LPVOID) { while (!g_tear.stop.load(std::memory_order_relaxed)) { const std::uint64_t v = *reinterpret_cast(&g_tear.cell); @@ -4350,7 +4360,6 @@ int check_list_values_more() { EXPECT(device); mock->zero_fences = true; xs::reset_list_value_stats(); - xs::set_list_value_wait_timeout_ms(5000); void* qa = make_queue(device); void* qb = make_queue(device); void* qc = make_queue(device); @@ -4472,11 +4481,9 @@ int check_list_values_more() { EXPECT(xs::list_values_idle(2000) && fence_completed(a_written) == 1); EXPECT(cell2(2) == 2 && cell2(3) == 0xA); - // 5. Four gates in a row that time out give the short timeout to every wait whose address was never met (a new - // address each time here, so none times out three times on its own). A wait cut short and met in the rest of the - // full timeout keeps the full timeout for its address only; a gate cut short and met within its short timeout - // gives every wait the full timeout again. - xs::set_list_value_wait_timeout_ms(100); + // 5. A wait is held until its value is in memory, with no timeout (before: let go after 200 ms), while work that + // does not depend on it goes on; it goes without its value only when nothing else can make progress: in a cycle + // at once, and, with nothing writing it, when the title stops calling (here: no present). xs::reset_list_value_stats(); const auto hold_on = [&](void* queue, int index, std::uint64_t reference) -> bool { if (FAILED(hr_of(raw(lb, 139, word(allocator), 0)))) return false; @@ -4492,45 +4499,72 @@ int check_list_values_more() { const auto set_cell = [](int index, std::uint64_t value) { InterlockedExchange64(reinterpret_cast(&g_cells2[index]), static_cast(value)); }; - for (int i = 0; i < 4; ++i) EXPECT(hold(4 + i) && xs::list_values_idle(3000)); - stats = xs::list_value_stats(); - EXPECT(stats.gates_held == 4 && stats.gates_timed_out == 4 && stats.demotions == 1 && stats.gates_short == 0); + // One list on queue A writing `value` to a cell; the value of A's write fence it lands at. + 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; + }; + // 5a. The writer comes 300 ms after the wait, later than the old timeout: the gate opens only once the write has + // landed (the waiting list runs after the write), and is counted met. + // 5b. Meanwhile queue A's work that the wait does not concern lands at once. Clock::time_point started = Clock::now(); - EXPECT(hold(8) && xs::list_values_idle(3000) && ms_since(started) < 60); // a new address: cut short + const std::uint64_t b_gate_before = fence_completed(b_gate); + EXPECT(hold_on(qb, 4, 1)); + Sleep(300); + EXPECT(fence_completed(b_gate) == b_gate_before && cell2(4) == 0); + std::uint64_t unrelated = 0; + EXPECT(write_on_a(5, 7, unrelated)); + fence_signal(a_written, unrelated); + for (int i = 0; i < 2000 && cell2(5) != 7; ++i) Sleep(1); + EXPECT(cell2(5) == 7 && fence_completed(b_gate) == b_gate_before); // A's write landed, B still held + std::uint64_t producer = 0; + EXPECT(write_on_a(4, 1, producer)); + Sleep(50); + EXPECT(fence_completed(b_gate) == b_gate_before && cell2(4) == 0); // written on the GPU only once A ran + fence_signal(a_written, producer); + EXPECT(xs::list_values_idle(3000) && cell2(4) == 1 && fence_completed(b_gate) == b_gate_before + 1); stats = xs::list_value_stats(); - EXPECT(stats.gates_short == 1 && stats.gates_timed_out == 5 && stats.late_met == 0); - set_cell(8, 1); // late, within the full timeout - for (int i = 0; i < 2000 && xs::list_value_stats().late_met == 0; ++i) Sleep(1); - EXPECT(xs::list_value_stats().late_met == 1); - started = Clock::now(); - EXPECT(hold(9) && xs::list_values_idle(3000) && ms_since(started) < 60); // still demoted for a new address - stats = xs::list_value_stats(); - EXPECT(stats.gates_short == 2 && stats.gates_timed_out == 6 && stats.demotions == 1); - // Cell 8 was met before: it keeps the full timeout (met here after 30 ms, within it), and the demotion stays. - EXPECT(hold_on(qb, 8, 2) && !xs::list_values_idle(30)); - set_cell(8, 2); - EXPECT(xs::list_values_idle(3000)); - stats = xs::list_value_stats(); - EXPECT(stats.gates_short == 2 && stats.gates_met == 1 && stats.gates_timed_out == 6); + EXPECT(stats.gates_held == 1 && stats.gates_met == 1 && stats.gates_released == 0 && ms_since(started) >= 300); + // 5c. A queue stands at a wait that its own later list writes, a list the layer holds behind that wait (the hook + // says its Signal never reached the GPU): a cycle, released at once, without a present. + g_held_fence = b_written; + xs::set_list_value_signal_submitted_hook(&held_fence_hook); + EXPECT(hold_on(qb, 6, 1)); + EXPECT(hr_of(raw(lb, 139, word(allocator), 0)) == S_OK); + raw(lb, 14, 1, 1, 1); + raw(lb, 72, word(&g_cells2[6]), 1, 0, 0); + EXPECT(hr_of(raw(lb, 9)) == S_OK); + g_queue_call_count = 0; started = Clock::now(); - EXPECT(hold(10) && xs::list_values_idle(3000) && ms_since(started) < 60); - EXPECT(xs::list_value_stats().gates_short == 3); - // A gate cut short and met within its short timeout lifts the demotion (the write follows the submission at - // once; a slow machine may need another try). - bool lifted = false; - for (int i = 0; i < 3 && !lifted; ++i) { - const std::uint64_t met_before = xs::list_value_stats().gates_met; - EXPECT(hold(11 + i)); - set_cell(11 + i, 1); - EXPECT(xs::list_values_idle(3000)); - lifted = xs::list_value_stats().gates_met == met_before + 1; - } - EXPECT(lifted); - const std::uint64_t short_before = xs::list_value_stats().gates_short; + EXPECT(submit(qb, lb) == 0); + const std::uint64_t own_write = logged_signal(qb_mock, b_written); + EXPECT(own_write != 0); + for (int i = 0; i < 2000 && xs::list_value_stats().released_cycle == 0; ++i) Sleep(1); + EXPECT(xs::list_value_stats().released_cycle == 1 && ms_since(started) < 1000); + EXPECT(fence_completed(b_gate) == b_gate_before + 2 && cell2(6) == 0); + xs::set_list_value_signal_submitted_hook(nullptr); + g_held_fence = nullptr; + fence_signal(b_written, own_write); // the held list ran: its write lands, and the release is seen met later + EXPECT(xs::list_values_idle(3000) && cell2(6) == 1); + for (int i = 0; i < 2000 && xs::list_value_stats().met_after_release == 0; ++i) Sleep(1); + EXPECT(xs::list_value_stats().met_after_release == 1); + // 5d. Nothing writes the value, nothing else runs, and the title presents nothing: held while the title calls; it + // goes once the title has made no queue call for the stall period (its threads wait for the held work). started = Clock::now(); - EXPECT(hold(14) && !xs::list_values_idle(40)); // a new address, the full timeout again - EXPECT(xs::list_values_idle(3000) && ms_since(started) >= 90); - EXPECT(xs::list_value_stats().gates_short == short_before && xs::list_value_stats().demotions == 1); + EXPECT(hold(7)); + Sleep(300); + EXPECT(fence_completed(b_gate) == b_gate_before + 2 && xs::list_value_stats().released_stalled == 0); + for (int i = 0; i < 5000 && xs::list_value_stats().released_stalled == 0; ++i) Sleep(1); + stats = xs::list_value_stats(); + EXPECT(stats.released_stalled == 1 && stats.released_present == 0 && stats.gates_released == 2 && + ms_since(started) >= 1900); + EXPECT(xs::list_values_idle(3000) && fence_completed(b_gate) == b_gate_before + 3); // 6. CopyPageMappingsBatchX behind work the queue has not done: the call returns, and the remap (of a copy of // the batches) runs once the queue gets there, before the gate its later work waits on opens. With the earlier @@ -4550,16 +4584,16 @@ int check_list_values_more() { EXPECT(g_queue_call_count == 2 && queue_call_is(0, qc_mock, 14, word(c_written), 1) && queue_call_is(1, qc_mock, 15, word(c_gate), 1)); EXPECT(!xs::list_values_idle(30) && fence_completed(c_gate) == 0 && g_page_mapping.count == 0); - // A memory wait behind the remap on the same queue: its time starts when the remap's gate opens, not at its - // submission (held 150 ms behind the remap, it does not open at once then). - const std::uint64_t timed_out_before = xs::list_value_stats().gates_timed_out; + // A memory wait behind the remap on the same queue: held behind it, and after it until memory meets it. + const std::uint64_t released_before = xs::list_value_stats().gates_released; EXPECT(hold_on(qc, 15, 1)); Sleep(150); - EXPECT(fence_completed(c_gate) == 0 && xs::list_value_stats().gates_timed_out == timed_out_before); + EXPECT(fence_completed(c_gate) == 0 && xs::list_value_stats().gates_released == released_before); fence_signal(c_written, 1); EXPECT(!xs::list_values_idle(40) && fence_completed(c_gate) == 1); + set_cell(15, 1); EXPECT(xs::list_values_idle(3000) && fence_completed(c_gate) == 2); - EXPECT(xs::list_value_stats().gates_timed_out == timed_out_before + 1); + EXPECT(xs::list_value_stats().gates_released == released_before); EXPECT(g_page_mapping.count == 1 && g_page_mapping.batches != remap && g_page_mapping.pool == 0x7000000000 && g_page_mapping.pages == 16 && g_page_mapping.first_destination == 0x9000000000 && g_page_mapping.first_count == 2 && g_page_mapping.first_ranges[0].start == 4 && @@ -4575,7 +4609,6 @@ int check_list_values_more() { EXPECT(stats.remaps_deferred == 1 && stats.remaps_now == 1); qc_mock->signals_complete = false; xs::set_copy_page_mappings_hook(nullptr); - xs::set_list_value_wait_timeout_ms(5000); // 7. Value stores: an aligned 4- or 8-byte value in one locked access (a reader polling it never sees half of // each), an unaligned one byte by byte, memory that cannot be written reported, not raised. @@ -4603,7 +4636,6 @@ int check_list_values_more() { // begin/end pair is the GPU work's, not one landing time), flag 2 as the QPC value the queue's clock calibration // gives. A pre-write that lands before its part ran (the gate is held) takes the CPU's clock instead. xs::reset_list_value_stats(); - xs::set_list_value_wait_timeout_ms(5000); EXPECT(hr_of(raw(direct, 139, word(allocator), 0)) == S_OK); const unsigned end_queries = direct_real->calls[53], resolves = direct_real->calls[54]; raw(direct, 72, word(&g_cells2[20]), 0, 0, 1); // begin @@ -4654,7 +4686,7 @@ int check_list_values_more() { EXPECT(xs::list_values_idle(3000)); // 10. A GPU wait for a label a CPU job of the title's writes later never blocks the submitting thread: the - // submission returns at once with the gate held (with a 5 s timeout), a submission behind it on the same queue + // submission returns at once with the gate held, a submission behind it on the same queue // returns at once too, and the CPU job's write (on another thread, 100 ms later) opens the gate. const std::uint64_t met_before = xs::list_value_stats().gates_met; started = Clock::now(); @@ -4668,37 +4700,26 @@ 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); + // 11. What counts as progress (src/list_value_progress.h): + // a) a matching write in flight on the GPU keeps a held gate shut, even past a present, until it lands; + // b) a releaser running held work (an action gate's remap) keeps a concurrent memory gate shut; + // c) a writer the layer holds (its Signal never reached the GPU, behind a relayed wait or a title fence) is not + // progress: at a present the gate goes, and the write still lands later. xs::reset_list_value_stats(); - // 11a. Wait on qb before qa submits its matching write (so relay() misses it and Pump holds a gate). + // 11a. Wait on qb before qa submits its matching write (so relay() misses it and the 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 + xs::note_list_value_present(); + EXPECT(!xs::list_values_idle(300)); // the producer runs: neither the present nor the time releases the gate stats = xs::list_value_stats(); - EXPECT(stats.gates_timed_out == 0 && stats.gates_met == 0 && cell2(27) == 0); + EXPECT(stats.gates_released == 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); + EXPECT(stats.gates_met == 1 && stats.gates_released == 0); - // 11b. Releaser inside a 150 ms action gate pauses a concurrent memory gate past the 40 ms idle timeout. + // 11b. Releaser inside a 150 ms action gate: a concurrent memory gate stays shut, met once the action wrote. 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); @@ -4710,47 +4731,41 @@ int check_list_values_more() { 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)); + xs::note_list_value_present(); 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)); + EXPECT(stats.gates_met == met_before_rel + 1 && stats.gates_released == 0); - // 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(); + // 11c. The writer is held in the layer: a present releases the gate (a root: nothing that runs can meet it). EXPECT(hold_on(qb, 29, 1)); std::uint64_t stuck_sig = 0; + g_held_fence = a_written; + xs::set_list_value_signal_submitted_hook(&held_fence_hook); 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); + EXPECT(!xs::list_values_idle(100) && xs::list_value_stats().gates_released == 0); // no present yet + started = Clock::now(); + xs::note_list_value_present(); + for (int i = 0; i < 2000 && xs::list_value_stats().released_present == 0; ++i) Sleep(1); + EXPECT(xs::list_value_stats().released_present == 1 && ms_since(started) < 1000); + xs::set_list_value_signal_submitted_hook(nullptr); + g_held_fence = nullptr; fence_signal(a_written, stuck_sig); - EXPECT(xs::list_values_idle(3000)); - xs::set_list_value_wait_timeout_ms(5000); + EXPECT(xs::list_values_idle(3000) && cell2(29) == 1); // 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. + // CopyPageMappingsBatchX remaps at the call rather than wait for a queue whose gates stay shut. A gate held at the + // time (nothing writes it) does not keep stop() waiting, and stays shut. + const std::uint64_t held_at_stop = fence_completed(b_gate); + EXPECT(hold(17) && !xs::list_values_idle(50)); + started = Clock::now(); xs::stop_list_values(2000); + EXPECT(ms_since(started) < 1000); + Sleep(20); + EXPECT(fence_completed(b_gate) == held_at_stop); const std::uint64_t gates_before = fence_completed(b_gate); EXPECT(hold(16)); Sleep(20); @@ -4773,11 +4788,12 @@ int check_list_values_more() { c_gate->refs == 0); EXPECT(release(device) == 0 && mock->refs == 0); std::printf("%s: with LEONIDA_LIST_VALUES=0 and on bundles writes and waits are no-ops, a bundle's and " - "ClearState's state carry over a cut, writes land in submission order across queues, timeouts in a " - "row shorten the waits for addresses never met until one cut short is met, a gate's time starts at " - "its queue's head, a page remap behind held work is deferred, value stores do not tear, and nothing " - "is opened after stop(); timestamp writes land the GPU's timestamps, and a wait for a label a CPU job " - "writes later never blocks the submitting thread\n", + "ClearState's state carry over a cut, writes land in submission order across queues, a wait is held " + "until its write lands however late while other queues' writes land, a cycle and a wait nothing " + "writes are released only when nothing else can run (at once, at a present, when the title stops " + "calling), a page remap behind held work is deferred, value stores do not tear, and nothing " + "is opened after stop(), which a held gate does not delay; timestamp writes land the GPU's " + "timestamps, and a wait for a label a CPU job writes later never blocks the submitting thread\n", g_label); return 0; } diff --git a/tests/semantic/check_absent_lane_ub.py b/tests/semantic/check_absent_lane_ub.py new file mode 100644 index 0000000000..5f928c78af --- /dev/null +++ b/tests/semantic/check_absent_lane_ub.py @@ -0,0 +1,444 @@ +"""Static SPIR-V invariant checker for absent-lane / inactive-lane subgroup UB. + +Verifies that every `OpGroupNonUniformShuffle` and `OpGroupNonUniformBroadcast` in a +SPIR-V module (assembly text or binary `.spv`) only ever passes a lane index provably +guaranteed to be a running invocation in the current subgroup: + * own physical lane (`BuiltIn SubgroupLocalInvocationId`), + * a lane proven present by `OpGroupNonUniformBallotBitExtract` on a subgroup ballot, + * the lowest set bit of a non-empty subgroup ballot (or its 32-lane half word), + * an `OpSelect` combining provably running lanes (never falling back to `%uint_0` or + any constant / unguarded lane). + +Also flags `OpGroupNonUniformQuadSwap` / `OpGroupNonUniformQuadBroadcast` in non-Fragment +stages (where partial quads are possible in Vulkan). + +Standalone CLI usage: + python3 -I tests/semantic/check_absent_lane_ub.py path/to/shader.spv [shader2.spvasm ...] + +Standard library only; no GPU, no LLVM, no external SPIRV-Tools needed. +""" +import os +import re +import struct +import sys + +_TOOLS_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "tools") +if _TOOLS_DIR not in sys.path: + sys.path.insert(0, _TOOLS_DIR) + +import spirv_asm_tables as _spv_tables # noqa: E402 + +_LINE_RE = re.compile(r"^(?:(%\S+)\s*=\s*)?(Op\w+)\s*(.*)$") + +# Derive all binary SPIR-V opcodes and enum values directly from tools/spirv_asm_tables.py. +_SPV_MAGIC = 0x07230203 +_TRACKED_OPS = frozenset({ + "OpEntryPoint", + "OpTypeInt", + "OpTypeFloat", + "OpTypeVector", + "OpConstantTrue", + "OpConstantFalse", + "OpConstant", + "OpConstantNull", + "OpVariable", + "OpLoad", + "OpStore", + "OpDecorate", + "OpCompositeExtract", + "OpCopyObject", + "OpExtInst", + "OpIAdd", + "OpLogicalOr", + "OpLogicalAnd", + "OpSelect", + "OpIEqual", + "OpINotEqual", + "OpBitwiseOr", + "OpBitwiseXor", + "OpBitwiseAnd", + "OpGroupNonUniformAll", + "OpGroupNonUniformAny", + "OpGroupNonUniformBroadcast", + "OpGroupNonUniformBroadcastFirst", + "OpGroupNonUniformBallot", + "OpGroupNonUniformInverseBallot", + "OpGroupNonUniformBallotBitExtract", + "OpGroupNonUniformBallotBitCount", + "OpGroupNonUniformBallotFindLSB", + "OpGroupNonUniformBallotFindMSB", + "OpGroupNonUniformShuffle", + "OpGroupNonUniformShuffleXor", + "OpGroupNonUniformShuffleUp", + "OpGroupNonUniformShuffleDown", + "OpGroupNonUniformQuadBroadcast", + "OpGroupNonUniformQuadSwap", +}) +_OP_NAMES = {_spv_tables.INSTRUCTIONS[name][0]: name for name in _TRACKED_OPS} +_EXEC_MODELS = {} +for _em_name, (_em_code, _) in _spv_tables.VALUE_ENUMS["ExecutionModel"].items(): + _EXEC_MODELS.setdefault(_em_code, _em_name) +_DECORATION_BUILTIN = _spv_tables.VALUE_ENUMS["Decoration"]["BuiltIn"][0] +_BUILTIN_SUBGROUP_LOCAL_INVOCATION_ID = _spv_tables.VALUE_ENUMS["BuiltIn"]["SubgroupLocalInvocationId"][0] +_GLSL_FIND_ILSB = _spv_tables.GLSL_STD_450["FindILsb"] + + +def _parse_spv_binary(data: bytes): + """Parse the subset of a SPIR-V binary needed for static subgroup lane safety checks.""" + if len(data) < 20 or len(data) % 4 != 0: + raise ValueError("invalid SPIR-V binary length") + magic = struct.unpack_from("" if magic == 0x03022307 else None + if endian is None: + raise ValueError(f"bad SPIR-V magic: {magic:#x}") + words = struct.unpack(f"{endian}{len(data) // 4}I", data) + insns = [] + consts = {} + builtins = {} + exec_models = set() + id_str = lambda i: f"%{i}" # noqa: E731 + idx = 5 + while idx < len(words): + wc = words[idx] >> 16 + op = words[idx] & 0xFFFF + if wc == 0 or idx + wc > len(words): + break + args = words[idx + 1:idx + wc] + idx += wc + name = _OP_NAMES.get(op) + if name is None: + continue + if name == "OpEntryPoint" and args: + exec_models.add(_EXEC_MODELS.get(args[0], str(args[0]))) + elif name == "OpDecorate" and len(args) >= 3: + if args[1] == _DECORATION_BUILTIN and args[2] == _BUILTIN_SUBGROUP_LOCAL_INVOCATION_ID: + builtins[id_str(args[0])] = "SubgroupLocalInvocationId" + elif name == "OpConstant" and len(args) >= 3: + consts[id_str(args[1])] = args[2] + elif name == "OpConstantNull" and len(args) >= 2: + consts[id_str(args[1])] = 0 + elif name == "OpConstantTrue" and len(args) >= 2: + consts[id_str(args[1])] = True + elif name == "OpConstantFalse" and len(args) >= 2: + consts[id_str(args[1])] = False + elif name == "OpStore" and len(args) >= 2: + insns.append((None, name, [id_str(args[0]), id_str(args[1])])) + elif name == "OpExtInst" and len(args) >= 5: + ext_op = "FindILsb" if args[3] == _GLSL_FIND_ILSB else str(args[3]) + insns.append((id_str(args[1]), name, [id_str(args[0]), id_str(args[2]), ext_op] + [id_str(x) for x in args[4:]])) + elif name == "OpCompositeExtract" and len(args) >= 4: + insns.append((id_str(args[1]), name, [id_str(args[0]), id_str(args[2]), str(args[3])])) + elif len(args) >= 2: + # Result-bearing instructions have [result_type, result_id, ...operands] + insns.append((id_str(args[1]), name, [id_str(args[0])] + [id_str(x) for x in args[2:]])) + return insns, consts, builtins, exec_models + + +def _parse_spv_text(text: str): + insns = [] + consts = {} + builtins = {} + exec_models = set() + for raw in text.splitlines(): + line = raw.split(";", 1)[0].strip() + if not line: + continue + m = _LINE_RE.match(line) + if not m: + continue + res, op, rest = m.groups() + a = rest.split() + if op == "OpEntryPoint" and a: + exec_models.add(a[0]) + elif op == "OpDecorate" and len(a) >= 3 and a[1] == "BuiltIn": + builtins[a[0]] = a[2] + elif op == "OpConstant" and res and len(a) >= 2: + try: + consts[res] = int(a[1], 0) + except ValueError: + pass + elif op == "OpConstantNull" and res: + consts[res] = 0 + elif op == "OpConstantTrue" and res: + consts[res] = True + elif op == "OpConstantFalse" and res: + consts[res] = False + else: + insns.append((res, op, a)) + return insns, consts, builtins, exec_models + + +def check_absent_lane_ub(module) -> list: + """Return a list of violation strings for any unsafe subgroup shuffle/broadcast/quad op. + + `module` may be SPIR-V assembly text (`str`) or SPIR-V binary (`bytes` / `bytearray`). + An empty list means every shuffle/broadcast lane operand is statically proven to name a + running invocation (never `%uint_0` or an unguarded lane), and no quad op appears in a + non-Fragment stage. + """ + if isinstance(module, (bytes, bytearray)): + insns, consts, builtins, exec_models = _parse_spv_binary(bytes(module)) + else: + insns, consts, builtins, exec_models = _parse_spv_text(module) + + defs = {} + var_single_store = {} + var_store_count = {} + for res, op, a in insns: + if res: + defs[res] = (op, a) + elif op == "OpStore" and len(a) >= 2: + ptr, val = a[0], a[1] + var_store_count[ptr] = var_store_count.get(ptr, 0) + 1 + var_single_store[ptr] = val + + sg_lane_vars = {vid for vid, b in builtins.items() if b == "SubgroupLocalInvocationId"} + + def unwrap(x, depth=0): + """Follow OpCopyObject and single-store Function variable (Gen.eager) loads.""" + if depth > 16 or x not in defs: + return x + op, a = defs[x] + if op == "OpCopyObject" and len(a) >= 2: + return unwrap(a[1], depth + 1) + if op == "OpLoad" and len(a) >= 2 and var_store_count.get(a[1]) == 1: + return unwrap(var_single_store[a[1]], depth + 1) + return x + + def is_const(x, val): + x = unwrap(x) + return x in consts and consts[x] == val + + def is_sg_lane(x): + x = unwrap(x) + if x in defs: + op, a = defs[x] + if op == "OpLoad" and len(a) >= 2 and a[1] in sg_lane_vars: + return True + return False + + def is_half_base(x): + """Matches `sg_lane & 32`.""" + x = unwrap(x) + if x not in defs: + return False + op, a = defs[x] + if op == "OpBitwiseAnd" and len(a) >= 3: + return (is_sg_lane(a[1]) and is_const(a[2], 32)) or (is_sg_lane(a[2]) and is_const(a[1], 32)) + return False + + def is_half_local_self(x): + """Matches `sg_lane & 31`.""" + x = unwrap(x) + if x not in defs: + return False + op, a = defs[x] + if op == "OpBitwiseAnd" and len(a) >= 3: + return (is_sg_lane(a[1]) and is_const(a[2], 31)) or (is_sg_lane(a[2]) and is_const(a[1], 31)) + return False + + def unpack_wave_source_lane(x): + """If `x` is `(sg_lane & 32) | (inner & 31)` (or `(sg_lane & 32) | inner`), return `inner`, else None.""" + x = unwrap(x) + if x not in defs: + return None + op, a = defs[x] + if op == "OpBitwiseOr" and len(a) >= 3: + if is_half_base(a[1]): + rhs = unwrap(a[2]) + elif is_half_base(a[2]): + rhs = unwrap(a[1]) + else: + return None + if rhs in defs and defs[rhs][0] == "OpBitwiseAnd" and len(defs[rhs][1]) >= 3: + ra = defs[rhs][1] + if is_const(ra[2], 31): + return ra[1] + if is_const(ra[1], 31): + return ra[2] + return rhs + return None + + def ballot_of_word(w): + """If `w` is an extracted 32-bit word of a ballot (directly or via wave32_ballot_word), return (ballot_id, half).""" + w = unwrap(w) + if w not in defs: + return None + op, a = defs[w] + if op == "OpCompositeExtract" and len(a) >= 3: + src = unwrap(a[1]) + if src in defs and defs[src][0] == "OpGroupNonUniformBallot": + return (src, int(a[2])) + if op == "OpSelect" and len(a) >= 4: + # wave32_ballot_word: OpSelect %uint upper hi lo where hi=bal[1], lo=bal[0] + b1 = ballot_of_word(a[2]) + b0 = ballot_of_word(a[3]) + if b1 and b0 and b1[0] == b0[0] and {b1[1], b0[1]} == {0, 1}: + return (b1[0], "half") + return None + + def ballot_words_nonzero(cond): + """Return the ballot id if `cond` tests that a ballot (or its half word) is non-zero, else None.""" + cond = unwrap(cond) + if cond not in defs: + return None + op, a = defs[cond] + if op == "OpGroupNonUniformAny" and len(a) >= 3: + return ("any_pred", unwrap(a[2])) + if op == "OpINotEqual" and len(a) >= 3: + bw = ballot_of_word(a[1]) if is_const(a[2], 0) else ballot_of_word(a[2]) if is_const(a[1], 0) else None + if bw is not None: + return ("ballot", bw[0], bw[1]) + if op == "OpLogicalOr" and len(a) >= 3: + b1 = ballot_words_nonzero(a[1]) + b2 = ballot_words_nonzero(a[2]) + if b1 and b2 and b1[0] == "ballot" and b2[0] == "ballot" and b1[1] == b2[1]: + return ("ballot", b1[1], "multi") + return None + + def ballot_of_lsb(x): + """If `x` is the LSB of a ballot (BallotFindLSB, FindILsb of half word, or ballot_lsb_by_words), return info.""" + x = unwrap(x) + if x not in defs: + return None + op, a = defs[x] + if op == "OpGroupNonUniformBallotFindLSB" and len(a) >= 3: + bal = unwrap(a[2]) + if bal in defs and defs[bal][0] == "OpGroupNonUniformBallot": + return ("phys", bal, unwrap(defs[bal][1][2])) + if op == "OpExtInst" and len(a) >= 4 and a[2] == "FindILsb": + bw = ballot_of_word(a[3]) + if bw is not None: + bal = bw[0] + return ("half" if bw[1] == "half" else "word", bal, unwrap(defs[bal][1][2])) + if op == "OpIAdd" and len(a) >= 3: + inner = ballot_of_lsb(a[1]) or ballot_of_lsb(a[2]) + if inner is not None and inner[0] == "word": + return inner + if op == "OpSelect" and len(a) >= 4: + # ballot_lsb_by_words folds words 3..0 with OpSelect(w != 0, lsb_k, prev) + nz = ballot_words_nonzero(a[1]) + lt = ballot_of_lsb(a[2]) + lf = ballot_of_lsb(a[3]) + if nz and nz[0] == "ballot" and lt and lf and lt[1] == nz[1] and lf[1] == nz[1]: + return ("phys", nz[1], lt[2]) + return None + + def ballot_extract_lane(cond): + """If `cond` implies lane `L` is set in a subgroup ballot, return the set of proven-running lane ids.""" + cond = unwrap(cond) + if cond not in defs: + return set() + op, a = defs[cond] + if op == "OpGroupNonUniformBallotBitExtract" and len(a) >= 4: + bal = unwrap(a[2]) + if bal in defs and defs[bal][0] == "OpGroupNonUniformBallot": + return {unwrap(a[3])} + if op == "OpLogicalAnd" and len(a) >= 3: + return ballot_extract_lane(a[1]) | ballot_extract_lane(a[2]) + return set() + + def is_safe_half_local(x, depth=0): + """True if `x` is a logical 0..31 lane guaranteed to map via wave_source_lane to a running lane.""" + if depth > 24: + return False + x = unwrap(x) + if is_half_local_self(x): + return True + if x not in defs: + return False + op, a = defs[x] + if op == "OpSelect" and len(a) >= 4: + cond, t_arm, f_arm = a[1], a[2], a[3] + if not is_safe_half_local(f_arm, depth + 1): + return False + if is_safe_half_local(t_arm, depth + 1): + return True + nz = ballot_words_nonzero(cond) + lsb = ballot_of_lsb(t_arm) + if nz and lsb and nz[0] == "ballot" and nz[1] == lsb[1] and lsb[0] == "half": + return True + return False + + def is_safe_physical(x, depth=0): + """True if `x` is statically proven to be a running physical SubgroupLocalInvocationId.""" + if depth > 24: + return False + x = unwrap(x) + if is_sg_lane(x): + return True + inner = unpack_wave_source_lane(x) + if inner is not None and is_safe_half_local(inner, depth + 1): + return True + if x not in defs: + return False + op, a = defs[x] + if op == "OpSelect" and len(a) >= 4: + cond, t_arm, f_arm = a[1], a[2], a[3] + if not is_safe_physical(f_arm, depth + 1): + return False + if is_safe_physical(t_arm, depth + 1): + return True + # Guarded by BallotBitExtract(bal, t_arm) + proven = ballot_extract_lane(cond) + if unwrap(t_arm) in proven: + return True + # Guarded by ballot non-zero -> LSB of that same ballot + nz = ballot_words_nonzero(cond) + lsb = ballot_of_lsb(t_arm) + if nz and lsb and lsb[0] == "phys": + if nz[0] == "ballot" and nz[1] == lsb[1]: + return True + if nz[0] == "any_pred" and nz[1] == lsb[2]: + return True + return False + + def describe_reason(x): + ux = unwrap(x) + if ux in consts: + return f"constant lane {consts[ux]} ({ux})" + if ux in defs and defs[ux][0] == "OpSelect": + a = defs[ux][1] + f_arm = unwrap(a[3]) + if f_arm in consts: + return f"OpSelect {ux} falls back to constant lane {consts[f_arm]} ({f_arm})" + return f"OpSelect {ux} has unverified arm(s) (true={a[2]}, false={a[3]})" + return f"unguarded lane operand {ux}" + + violations = [] + for res, op, a in insns: + if op in ("OpGroupNonUniformShuffle", "OpGroupNonUniformBroadcast") and len(a) >= 4: + lane_id = a[3] + if not is_safe_physical(lane_id): + violations.append(f"{res} = {op} ... {lane_id}: {describe_reason(lane_id)}") + elif op in ("OpGroupNonUniformShuffleXor", "OpGroupNonUniformShuffleUp", "OpGroupNonUniformShuffleDown"): + violations.append(f"{res} = {op}: relative/xor shuffle can read absent lanes in a partial subgroup") + elif op in ("OpGroupNonUniformQuadSwap", "OpGroupNonUniformQuadBroadcast"): + if exec_models and not exec_models.issubset({"Fragment"}): + violations.append(f"{res} = {op} in non-Fragment stage {sorted(exec_models)} (partial-quad UB)") + return violations + + +def main(argv=None): + paths = sys.argv[1:] if argv is None else argv + if not paths: + print("usage: check_absent_lane_ub.py [...]", file=sys.stderr) + return 2 + rc = 0 + for path in paths: + with open(path, "rb") as f: + raw = f.read() + mod = raw if len(raw) >= 4 and struct.unpack_from("= 3 and a[1] == "DenormFlushToZero" and a[2] == "32": + ftz32 = True + continue + if op == "OpDecorate" and len(a) >= 3 and a[1] == "SpecId": + spec_ids[a[0]] = int(a[2]) + continue if op in _IGNORED: continue if op == "OpTypeInt": @@ -641,15 +651,18 @@ def walk(type_id, indices): ptr_types[res] = (a[0], a[1]) elif op in ("OpTypeImage", "OpTypeSampler", "OpTypeSampledImage"): types.t[res] = ("image",) # opaque: only OpImageFetch on a bound resource reads it - elif op == "OpConstant": + elif op in ("OpConstant", "OpSpecConstant"): k = types.t[a[0]] if k[0] == "float": constants[res] = values[res] = f32_literal(a[1]) if k[1] == 32 else float(a[1]) + id_type[res] = a[0] elif k[0] == "int": - constants[res] = values[res] = int(a[1]) & ((1 << k[1]) - 1) + sid = spec_ids.get(res) if op == "OpSpecConstant" else None + raw_v = spec_constants[sid] if (sid is not None and sid in spec_constants) else int(a[1]) + constants[res] = values[res] = raw_v & ((1 << k[1]) - 1) id_type[res] = a[0] else: - raise UnsupportedConstruct(f"OpConstant of type {k[0]}") + raise UnsupportedConstruct(f"{op} of type {k[0]}") elif op == "OpConstantTrue": constants[res] = values[res] = True elif op == "OpConstantFalse": @@ -709,6 +722,18 @@ def psb_word(addr): def wmask(type_id): return (1 << types.bits(type_id)) - 1 + def ftz(v): + """Flush binary32 subnormals to signed zero when DenormFlushToZero 32 is active.""" + if ftz32 and isinstance(v, float) and v != 0.0 and abs(v) < 2.0 ** -126: + return math.copysign(0.0, v) + return v + + def is_f32_type(type_id): + t = types.t.get(type_id) + if t == ("float", 32): + return True + return bool(t and t[0] == "vec" and types.t.get(t[1]) == ("float", 32)) + def signed(v, bits): v &= (1 << bits) - 1 return v - (1 << bits) if v >> (bits - 1) else v @@ -869,9 +894,15 @@ def sval(x): w = p[1] // 4 values[res] = push_constants[w] if 0 <= w < len(push_constants) else 0 elif p[0] == "psb": - if types.t[a[0]][:2] != ("int", 32): - raise UnsupportedConstruct("PhysicalStorageBuffer load of a type that is not a 32-bit integer") - values[res] = memory.get(psb_word(p[1]), 0) + kind = types.t[a[0]] + if kind[0] == "vec" and types.t[kind[1]][:2] == ("int", 32): + # A uvecN: N consecutive words (the wide scalar loads of rdna2spirv.scalar_load). + values[res] = [memory.get(psb_word(p[1] + 4 * i), 0) for i in range(kind[2])] + elif kind[:2] != ("int", 32): + raise UnsupportedConstruct("PhysicalStorageBuffer load of a type that is not a 32-bit integer " + "or a vector of them") + else: + values[res] = memory.get(psb_word(p[1]), 0) else: values[res] = types.copy_value(a[0], deref(p)) elif op == "OpImageFetch": @@ -1148,16 +1179,18 @@ def sval(x): continue def _fdiv(p, q): - # SPIR-V leaves OpFDiv by zero undefined: refuse it, as the interpreter does for every undefined case + # SPIR-V leaves OpFDiv by zero undefined: refuse an actual zero divisor (a subnormal divisor + # under DenormFlushToZero 32 gives +-inf for non-zero p, matching RDNA2 v_rcp_f32). if q == 0.0: raise UnsupportedConstruct("OpFDiv by zero (undefined in SPIR-V)") - if math.isinf(p) and math.isinf(q): + p_f = ftz(p) + if math.isinf(p_f) and math.isinf(q): return math.nan - return f32(p / q) # x/inf is a signed zero, as in Python + return ftz(f32(p_f / q)) # x/inf is a signed zero, as in Python - fn = {"OpFAdd": (lambda p, q: f32(ieee_nan(p + q, p, q))), - "OpFSub": (lambda p, q: f32(ieee_nan(p - q, p, q))), - "OpFMul": (lambda p, q: f32(ieee_nan(p * q, p, q))), "OpFDiv": _fdiv}[op] + fn = {"OpFAdd": (lambda p, q: ftz(f32(ieee_nan(ftz(p) + ftz(q), ftz(p), ftz(q))))), + "OpFSub": (lambda p, q: ftz(f32(ieee_nan(ftz(p) - ftz(q), ftz(p), ftz(q))))), + "OpFMul": (lambda p, q: ftz(f32(ieee_nan(ftz(p) * ftz(q), ftz(p), ftz(q))))), "OpFDiv": _fdiv}[op] if isinstance(x, tuple) and isinstance(y, tuple) and len(x) == len(y) and all( isinstance(p, float) and isinstance(q, float) for p, q in zip(x, y)): values[res] = tuple(fn(p, q) for p, q in zip(x, y)) @@ -1169,9 +1202,9 @@ def _fdiv(p, q): # SPV_KHR_fma: x * y + z correctly rounded, the same exact single rounding as GLSL Fma above (fma_f32) x, y, z = (val(t) for t in a[1:4]) if isinstance(x, tuple): - values[res] = tuple(fma_f32(p, q, s) for p, q, s in zip(x, y, z)) + values[res] = tuple(ftz(fma_f32(ftz(p), ftz(q), ftz(s))) for p, q, s in zip(x, y, z)) else: - values[res] = fma_f32(x, y, z) + values[res] = ftz(fma_f32(ftz(x), ftz(y), ftz(z))) elif op == "OpFNegate": # IEEE 754 negate only flips the sign bit: it keeps a NaN's payload and does not quiet a signalling NaN. # A binary32 operand is negated on its bits, because the float round trip in f32() sets the quiet bit @@ -1209,6 +1242,8 @@ def _fdiv(p, q): x, y = val(a[1]), val(a[2]) if not (isinstance(x, float) and isinstance(y, float)): raise UnsupportedConstruct(f"{op} on non-float") + if is_f32_type(id_type.get(a[1])) or is_f32_type(id_type.get(a[2])): + x, y = ftz(x), ftz(y) # Ordered: false if either operand is NaN. Unordered: true if either is NaN. Python's own comparisons # are already ordered (NaN compares false), and -0.0 == 0.0 as in SPIR-V. unordered = math.isnan(x) or math.isnan(y) @@ -1234,6 +1269,27 @@ def _fdiv(p, q): raise UnsupportedConstruct("bit-field insert beyond 32 bits (undefined in SPIR-V)") mk = ((1 << cnt) - 1) << off values[res] = ((base & ~mk) | ((ins << off) & mk)) & MASK + elif op in ("OpSDotKHR", "OpUDotKHR", "OpSDotAccSatKHR", "OpUDotAccSatKHR", + "OpSDot", "OpUDot", "OpSDotAccSat", "OpUDotAccSat"): + # SPV_KHR_integer_dot_product, PackedVectorFormat4x8Bit only: the exact sum of the four products of the + # sign- (OpS*) or zero- (OpU*) extended bytes; plain forms keep its low bits, AccSat forms add the + # accumulator exactly and saturate to the result type's range (signed for OpS*, unsigned for OpU*). + acc_sat = "AccSat" in op + if a[-1] not in ("PackedVectorFormat4x8BitKHR", "PackedVectorFormat4x8Bit") or types.bits(a[0]) != 32: + raise UnsupportedConstruct(f"{op} other than 32-bit PackedVectorFormat4x8Bit") + is_signed = op.startswith("OpS") + x, y = val(a[1]), val(a[2]) + + def byte(w, i): + b = (w >> (8 * i)) & 0xFF + return b - 256 if is_signed and b & 0x80 else b + total = sum(byte(x, i) * byte(y, i) for i in range(4)) + if acc_sat: + acc = val(a[3]) & MASK + total += (acc - (1 << 32) if acc >> 31 else acc) if is_signed else acc + lo, hi = (-(1 << 31), (1 << 31) - 1) if is_signed else (0, MASK) + total = min(max(total, lo), hi) + values[res] = total & MASK elif op == "OpConvertUToPtr": values[res] = ("psb", val(a[1])) pointers[res] = values[res] @@ -1257,9 +1313,9 @@ def _fdiv(p, q): # Exact product and sum, one rounding to binary32 (fma_f32). x, y, z = args if isinstance(x, tuple): - values[res] = tuple(fma_f32(p, q, s) for p, q, s in zip(x, y, z)) + values[res] = tuple(ftz(fma_f32(ftz(p), ftz(q), ftz(s))) for p, q, s in zip(x, y, z)) else: - values[res] = fma_f32(x, y, z) + values[res] = ftz(fma_f32(ftz(x), ftz(y), ftz(z))) elif name in ("Sin", "Cos"): values[res] = f32(math.sin(args[0]) if name == "Sin" else math.cos(args[0])) elif name == "FAbs": @@ -1276,13 +1332,15 @@ def _fdiv(p, q): values[res] = abs(signed(args[0], bits)) & wmask(a[0]) elif name in ("FMax", "FClamp"): def fmax_clamp(*xs): + if is_f32_type(a[0]): + xs = tuple(ftz(v) for v in xs) if any(math.isnan(v) for v in xs) or (name == "FClamp" and xs[1] > xs[2]): raise UnsupportedConstruct(f"GLSL.std.450 {name} with these operands (undefined)") # Equal zeros: -0 is ordered below +0, as in NMin/NMax above (the order RDNA2 hardware uses, # so a med3 built from these ops is the hardware's median for signed zeros too). v = _nmin_nmax("NMax", xs[0], xs[1]) result = v if name == "FMax" else _nmin_nmax("NMin", v, xs[2]) - return result if types.t[a[0]] == ("float", 64) else f32(result) + return result if types.t[a[0]] == ("float", 64) else ftz(f32(result)) # Vector operands (v_pk_* clamp) are component-wise. values[res] = (tuple(fmax_clamp(*c) for c in zip(*args)) if isinstance(args[0], tuple) else fmax_clamp(*args)) diff --git a/tests/semantic/spirv_wave_interp.py b/tests/semantic/spirv_wave_interp.py index 113f25bb4d..181dfa2e7a 100644 --- a/tests/semantic/spirv_wave_interp.py +++ b/tests/semantic/spirv_wave_interp.py @@ -334,7 +334,8 @@ def _copy(v): class _Wave: - def __init__(self, mod, wave, push_constants, max_steps, builtins=None, inputs=None, memory=None): + def __init__(self, mod, wave, push_constants, max_steps, builtins=None, inputs=None, memory=None, + active_lanes=None, strict_subgroup_ub=False, fault_on_unmapped=False): self.m = mod self.wave = wave self.pcw = list(push_constants or []) @@ -344,6 +345,11 @@ def __init__(self, mod, wave, push_constants, max_steps, builtins=None, inputs=N self.killed = set() self.returned = set() self.memory = memory if memory is not None else {} + self.active_lanes = set(range(wave)) if active_lanes is None else set(active_lanes) + if not self.active_lanes or any(not 0 <= i < wave for i in self.active_lanes): + raise ValueError(f"active_lanes must be a non-empty subset of 0..{wave - 1}") + self.strict_subgroup_ub = strict_subgroup_ub + self.fault_on_unmapped = fault_on_unmapped for lane in self.lanes: for vid, cls, pointee, init in mod.globals: if cls == "PushConstant": @@ -404,13 +410,13 @@ def bool_of(self, lane, x): # -- structured execution ------------------------------------------------------------------------------------ def run(self): - group = set(range(self.wave)) + group = set(self.active_lanes) rest = self.region(group, self.m.entry, frozenset()) if rest: raise UnsupportedConstruct(f"invocations left the function through {sorted(rest)}") out = [] for lane in self.lanes: - if lane.index in self.killed: + if lane.index not in self.active_lanes or lane.index in self.killed: out.append(None) continue words = {} @@ -576,7 +582,7 @@ def exec_block(self, blk, group): v = self.eval(self.lanes[i], res, op, a) except _UsedPoison as p: # OpSelect reads its arms without inspecting them, so only its condition gets here. - if op in ("OpAccessChain", "OpSelect"): + if op in ("OpAccessChain", "OpSelect", "OpConvertUToPtr"): raise UnsupportedConstruct(f"{op} {res} depends on an undefined value " f"({p.poison.why})") from None v = p.poison @@ -659,9 +665,19 @@ def ballot_bits(v): src_vals = {i: self.raw(L[i], a[2]) for i in members} for i in members: idx = self.int_of(L[i], a[3]) - L[i].values[res] = src_vals[idx] if idx in src_vals else \ - _Poison(f"{op[17:]} from invocation {idx}, which is not running") + if idx in src_vals: + L[i].values[res] = src_vals[idx] + else: + msg = f"{op[17:]} from invocation {idx}, which is not running" + if self.strict_subgroup_ub: + raise UnsupportedConstruct(msg) + L[i].values[res] = _Poison(msg) elif op == "OpGroupNonUniformBroadcastFirst": + if not members: + msg = "BroadcastFirst with no running invocation" + if self.strict_subgroup_ub: + raise UnsupportedConstruct(msg) + return first = self.raw(L[members[0]], a[2]) for i in members: L[i].values[res] = first @@ -675,7 +691,13 @@ def ballot_bits(v): if d not in (0, 1, 2): raise UnsupportedConstruct(f"OpGroupNonUniformQuadSwap direction {d}") partner = i ^ (d + 1) - L[i].values[res] = src_vals[partner] if partner in src_vals else _Poison(f"QuadSwap from invocation {partner}, which is not running") + if partner in src_vals: + L[i].values[res] = src_vals[partner] + else: + msg = f"QuadSwap from invocation {partner}, which is not running" + if self.strict_subgroup_ub: + raise UnsupportedConstruct(msg) + L[i].values[res] = _Poison(msg) elif op == "OpGroupNonUniformQuadBroadcast": src_vals = {i: self.raw(L[i], a[2]) for i in members} for i in members: @@ -683,7 +705,13 @@ def ballot_bits(v): if not 0 <= idx < 4: raise UnsupportedConstruct(f"OpGroupNonUniformQuadBroadcast index {idx}") partner = (i & ~3) | idx - L[i].values[res] = src_vals[partner] if partner in src_vals else _Poison(f"QuadBroadcast from invocation {partner}, which is not running") + if partner in src_vals: + L[i].values[res] = src_vals[partner] + else: + msg = f"QuadBroadcast from invocation {partner}, which is not running" + if self.strict_subgroup_ub: + raise UnsupportedConstruct(msg) + L[i].values[res] = _Poison(msg) else: raise UnsupportedConstruct(op) @@ -751,10 +779,25 @@ def eval(self, lane, res, op, a): if p is None: raise UnsupportedConstruct(f"OpLoad from {a[1]}, which is not a pointer") if p[0] == "psb": + k = m.types[p[2]] + if k[0] == "vec": + elem_k = m.types[k[1]] + if m.size(k[1]) != 4: + raise UnsupportedConstruct("psb vector load with non-32-bit element") + out_v = [] + for wi in range(k[2]): + ea = p[1] + 4 * wi + if self.fault_on_unmapped and ea not in self.memory: + raise UnsupportedConstruct(f"psb load from unmapped address {ea:#x}") + w = self.memory.get(ea, 0) & MASK + out_v.append(F(w) if elem_k[0] == "float" else w) + return tuple(out_v) if m.size(p[2]) != 4: raise UnsupportedConstruct("psb load wider than one word") - v = self.memory.get(p[1], 0) - return F(v) if m.types[p[2]][0] == "float" else v & MASK + if self.fault_on_unmapped and p[1] not in self.memory: + raise UnsupportedConstruct(f"psb load from unmapped address {p[1]:#x}") + v = self.memory.get(p[1], 0) & MASK + return F(v) if k[0] == "float" else v if p[0] == "pc": if m.size(p[2]) != 4: raise UnsupportedConstruct("push-constant load wider than one word") @@ -953,6 +996,25 @@ def eval(self, lane, res, op, a): return _Poison("bit-field insert beyond the width") mk = ((1 << cnt) - 1) << off return ((base & ~mk) | ((ins << off) & mk)) & w + if op in ("OpSDotKHR", "OpUDotKHR", "OpSDotAccSatKHR", "OpUDotAccSatKHR", + "OpSDot", "OpUDot", "OpSDotAccSat", "OpUDotAccSat"): + # SPV_KHR_integer_dot_product on PackedVectorFormat4x8Bit (as spirv_mini_interp): the exact sum of the four + # byte products, its low bits, or with AccSat the accumulator added exactly and saturated. + if a[-1] not in ("PackedVectorFormat4x8BitKHR", "PackedVectorFormat4x8Bit") or bits != 32: + raise UnsupportedConstruct(f"{op} other than 32-bit PackedVectorFormat4x8Bit") + is_signed = op.startswith("OpS") + x, y = self.int_of(lane, a[1]) & MASK, self.int_of(lane, a[2]) & MASK + + def byte(word, i): + b = (word >> (8 * i)) & 0xFF + return b - 256 if is_signed and b & 0x80 else b + total = sum(byte(x, i) * byte(y, i) for i in range(4)) + if "AccSat" in op: + acc = self.int_of(lane, a[3]) & MASK + total += _signed(acc, 32) if is_signed else acc + lo, hi = (-(1 << 31), (1 << 31) - 1) if is_signed else (0, MASK) + total = min(max(total, lo), hi) + return total & MASK if op in ("OpIAddCarry", "OpISubBorrow"): x, y = self.int_of(lane, a[1]) & MASK, self.int_of(lane, a[2]) & MASK if op == "OpIAddCarry": @@ -1024,9 +1086,12 @@ def __init__(self, name): self.name = name -def run_wave(text, wave=32, push_constants=None, max_steps=2_000_000, builtins=None, inputs=None, memory=None): +def run_wave(text, wave=32, push_constants=None, max_steps=2_000_000, builtins=None, inputs=None, memory=None, + active_lanes=None, strict_subgroup_ub=False, fault_on_unmapped=False): if wave not in (32, 64): raise ValueError("wave must be 32 or 64") - w = _Wave(_Module(text), wave, push_constants, max_steps, builtins, inputs=inputs, memory=memory) + w = _Wave(_Module(text), wave, push_constants, max_steps, builtins, inputs=inputs, memory=memory, + active_lanes=active_lanes, strict_subgroup_ub=strict_subgroup_ub, + fault_on_unmapped=fault_on_unmapped) outputs = w.run() return {"outputs": outputs, "steps": w.steps, "memory": w.memory} diff --git a/tests/semantic/test_absent_lane_ub.py b/tests/semantic/test_absent_lane_ub.py new file mode 100644 index 0000000000..6ba9080510 --- /dev/null +++ b/tests/semantic/test_absent_lane_ub.py @@ -0,0 +1,513 @@ +"""Regression suite for absent-lane / inactive-lane subgroup UB across all stages and ops. + +Covers both static SPIR-V invariants (tests/semantic/check_absent_lane_ub.py) and strict +partial-wave execution in spirv_wave_interp.py (strict_subgroup_ub=True, active_lanes without +lane 0, single-lane waves, EXEC == 0, BDA fault_on_unmapped=True) and spirv_mini_interp.py: + * wave32 PS (in 32-wide and 64-wide subgroups, lanes 0..3 absent, single lane, helper-only) + * wave64 PS (lanes 0..3 absent, only upper lanes 35..38 running, EXEC == 0) + * wave32 MS & CS (partial wave with lane 0 absent, EXEC == 0) + * wave32 VS (partial wave with lane 0 absent, EXEC == 0, no BallotFindLSB) + * v_readfirstlane_b32 followed by s_load_dword / s_buffer_load_dword (no unmapped BDA fault) + * v_readlane_b32 (pure spill, mixed-VGPR definite spill, non-spill varying & dynamic) + * v_permlane16_b32 / v_permlanex16_b32 (FI=0 and FI=1 on partial waves) + * DPP (row_shr / row_shl out-of-bounds clamp + dpp8 fi:1 on partial waves) + * quad_any (s_wqm_b32 / s_wqm_b64 in CS/VS/MS partial quads and PS full quads) + * ds_append / ds_consume with EXEC == 0 and partial waves + * Negative controls proving both spirv_wave_interp and check_absent_lane_ub catch `%uint_0` + fallbacks and unguarded shuffles! + +Hand-written synthetic listings only; no game data. +""" +import os +import re +import shutil +import struct +import subprocess +import sys +import tempfile +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +if HERE not in sys.path: + sys.path.insert(0, HERE) + +import check_absent_lane_ub as checker # noqa: E402 +import spirv_asm # noqa: E402 +import spirv_mini_interp as si # noqa: E402 +import spirv_wave_interp as wi # noqa: E402 +import support # noqa: E402 + +SPIRV_AS = shutil.which("spirv-as") +SPIRV_VAL = shutil.which("spirv-val") + + +def fbits(value): + return struct.unpack(" static check (text + binary) -> spirv-val -> strict partial-wave run.""" + + def assert_clean_module(self, spv): + self.assertEqual(checker.check_absent_lane_ub(spv), []) + raw = spirv_validate(spv) + if raw is not None: + self.assertEqual(checker.check_absent_lane_ub(raw), []) + + def test_wave32_ps_readfirstlane_and_sload_with_absent_lane0_and_zero_exec(self): + # Every running lane holds a valid 64-bit pointer in v[4:5]; EXEC goes to 0 before + # v_readfirstlane_b32 + s_load_dword. Lane 0 is NOT launched (only lane 5 or lanes 4..7). + # With the old %uint_0 fallback this read absent lane 0 and dereferenced garbage (run93). + base = 0x2000 + spv = support.translate_lines("ps_w32_rfl_sload_zero_exec", [ + f"v_mov_b32_e32 v4, {base:#x}", + "v_mov_b32_e32 v5, 0", + "s_mov_b32 exec_lo, 0", + "v_readfirstlane_b32 s10, v4", + "v_readfirstlane_b32 s11, v5", + "s_load_dword s12, s[10:11], 0x0", + "s_waitcnt lgkmcnt(0)", + "s_mov_b32 exec_lo, -1", + "v_mov_b32_e32 v6, s12", + "exp mrt0 v6, v6, v6, v6 done vm", + "s_endpgm", + ]) + self.assert_clean_module(spv) + mem = {base: 0xCAFEBABE} + for wave, active in ((32, [5]), (32, [31]), (32, [4, 5, 6, 7]), (64, [35, 36, 37, 38])): + with self.subTest(wave=wave, active=active): + res = wi.run_wave(spv, wave=wave, memory=mem, active_lanes=active, + strict_subgroup_ub=True, fault_on_unmapped=True) + for lane in active: + self.assertEqual(res["outputs"][lane]["%out_mrt0"], (0xCAFEBABE,) * 4) + + def test_wave64_ps_readfirstlane_and_sload_with_absent_lane0_and_zero_exec(self): + # Wave64 PS hits the non-wave32_fragment path of v_readfirstlane_b32, which previously + # fell back directly to %uint_0 when EXEC == 0. + base = 0x3000 + spv = support.translate_lines("ps_w64_rfl_sload_zero_exec", [ + "s_mov_b64 exec, -1", + f"v_mov_b32_e32 v4, {base:#x}", + "v_mov_b32_e32 v5, 0", + "s_mov_b64 exec, 0", + "v_readfirstlane_b32 s10, v4", + "v_readfirstlane_b32 s11, v5", + "s_load_dword s12, s[10:11], 0x0", + "s_waitcnt lgkmcnt(0)", + "s_mov_b64 exec, -1", + "v_mov_b32_e32 v6, s12", + "exp mrt0 v6, v6, v6, v6 done vm", + "s_endpgm", + ]) + self.assert_clean_module(spv) + mem = {base: 0x12345678} + for active in ([5], [31], [35, 36, 37, 38], [63]): + with self.subTest(active=active): + res = wi.run_wave(spv, wave=64, memory=mem, active_lanes=active, + strict_subgroup_ub=True, fault_on_unmapped=True) + for lane in active: + self.assertEqual(res["outputs"][lane]["%out_mrt0"], (0x12345678,) * 4) + + def test_wave32_vs_and_cs_readfirstlane_with_absent_lane0_and_zero_exec(self): + # VS (ballot_lsb_by_words path) and CS (BallotFindLSB path) must both avoid %uint_0. + vs_spv = support.translate_lines("vs_w32_rfl_absent0", [ + "v_mov_b32_e32 v4, 0x4242", + "s_mov_b32 exec_lo, 0", + "v_readfirstlane_b32 s10, v4", + "s_mov_b32 exec_lo, -1", + "v_mov_b32_e32 v5, 0", + "v_mov_b32_e32 v6, s10", + "exp pos0 v5, v5, v5, v5 done", + "exp param0 v6, v5, v5, v5", + "s_endpgm", + ]) + self.assert_clean_module(vs_spv) + self.assertNotIn("OpGroupNonUniformBallotFindLSB", vs_spv) + res = wi.run_wave(vs_spv, wave=32, active_lanes=[7, 8], strict_subgroup_ub=True, + builtins={"VertexIndex": lambda lane: lane, "InstanceIndex": lambda lane: 0}) + for lane in (7, 8): + self.assertEqual(res["outputs"][lane]["%out_param0"][0], 0x4242) + + cs_spv = support.translate_lines("cs_w32_rfl_absent0", [ + "v_mov_b32_e32 v4, 0x55aa", + "s_mov_b32 exec_lo, 0", + "v_readfirstlane_b32 s10, v4", + "s_mov_b32 exec_lo, -1", + "v_mov_b32_e32 v6, s10", + "v_mov_b32_e32 v7, 0", + "buffer_store_dword v6, v7, s[0:3], 0 offen", + "s_endpgm", + ], fssm=compute_fssm(32, wave64=False)) + self.assert_clean_module(cs_spv) + vsharp = [0x4000, 0, 0x100, 0x31016FAC] + mem = {} + si.run_workgroup( + cs_spv, 1, 32, lanes=[5], + inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (5, 0, 0), "%sg_lane": 5}, + push_constants=vsharp + [0] * 28, memory=mem, + ) + self.assertEqual(mem.get(0x4000), 0x55AA) + + def test_mixed_vgpr_scalar_spill_and_nonspill_readlane_absent_lanes(self): + # v48 is used as a vector register FIRST, then reused as a constant-lane scalar spill + # (lanes 0 and 19); definite_spill_reads parks those reloads so absent lanes 0/19 stay exact! + # v12 is a non-spill varying VGPR read from absent lane 0; guarded shuffle redirects to first + # running lane (wave-uniform, zero UB). + spv = support.translate_lines("ps_w32_mixed_spill_and_readlane", [ + "v_mov_b32_e32 v48, 0x9999", # vector write disqualifies pure scalar_spills() + "s_mov_b32 s20, 0x11223344", + "s_mov_b32 s21, 0x55667788", + "v_writelane_b32 v48, s20, 0", + "v_writelane_b32 v48, s21, 19", + "s_mov_b32 s20, 0", + "s_mov_b32 s21, 0", + "v_readlane_b32 s4, v48, 0", # definite mixed-VGPR spill reload -> parked + "v_readlane_b32 s5, v48, 19", # definite mixed-VGPR spill reload -> parked + "v_mov_b32_e32 v12, 0x7777", # non-spill VGPR read from absent lane 0 -> guarded + "v_readlane_b32 s6, v12, 0", + "v_mov_b32_e32 v6, s4", + "v_mov_b32_e32 v7, s5", + "v_mov_b32_e32 v8, s6", + "exp mrt0 v6, v7, v8, v8 done vm", + "s_endpgm", + ]) + self.assert_clean_module(spv) + # Only one shuffle (for v12), zero shuffles for mixed spill v48! + self.assertEqual(spv.count("OpGroupNonUniformShuffle"), 1) + for wave, active in ((32, [5]), (32, [4, 5, 6, 7]), (64, [37, 38])): + with self.subTest(wave=wave, active=active): + res = wi.run_wave(spv, wave=wave, active_lanes=active, strict_subgroup_ub=True) + for lane in active: + self.assertEqual(res["outputs"][lane]["%out_mrt0"], + (0x11223344, 0x55667788, 0x7777, 0x7777)) + + def test_permlane16_and_permlanex16_fi1_absent_lanes(self): + # FI=1 reads EXEC-off launched lanes, and must redirect unlaunched/absent lanes to own + # subgroup lane (yielding 0) without triggering UB. + spv = support.translate_lines("ps_w32_permlane_fi1_absent", [ + "v_mbcnt_lo_u32_b32 v1, -1, 0", + "v_add_nc_u32_e32 v2, 100, v1", + # lane 5 reads lane 0 (absent) via permlane16 FI=1, and lane 21 (absent) via permlanex16 FI=1 + "v_permlane16_b32 v6, v2, 0, 0 op_sel:[1,0]", + "v_permlanex16_b32 v7, v2, 0x55555555, 0x55555555 op_sel:[1,0]", + # lane 5 reads lane 5 (present!) via permlane16 FI=1 + "v_permlane16_b32 v8, v2, 0x55555555, 0x55555555 op_sel:[1,0]", + "exp mrt0 v6, v7, v8, v2 done vm", + "s_endpgm", + ]) + self.assert_clean_module(spv) + res = wi.run_wave(spv, wave=32, active_lanes=[5], strict_subgroup_ub=True) + # v_mbcnt_lo_u32_b32 with -1 gives lane id 5 -> v2 = 105. + self.assertEqual(res["outputs"][5]["%out_mrt0"], (0, 0, 105, 105)) + + def test_dpp_in_bounds_and_fi1_absent_lanes(self): + # row_shr:1 in lane 16 is out-of-bounds (previously clamped safe_sg to %uint_0!); + # dpp8 fi:1 reads absent neighbours in partial wave (previously unguarded!). + spv = support.translate_lines("ps_w32_dpp_absent", [ + "v_mov_b32_e32 v2, 50", + "v_mov_b32_e32 v6, 99", + "v_add_nc_u32_dpp v6, v2, 1 row_shr:1 row_mask:0xf bank_mask:0xf bound_ctrl:1", + "v_add_nc_u32_dpp v7, v2, 2 dpp8:[0,0,0,0,0,0,0,0] fi:1", + "exp mrt0 v6, v7, v2, v2 done vm", + "s_endpgm", + ]) + self.assert_clean_module(spv) + # Only lane 16 running: row_shr:1 is OOB -> 0+1 = 1; dpp8 lane 0 of group (lane 16) IS present -> 50+2 = 52! + res16 = wi.run_wave(spv, wave=32, active_lanes=[16], strict_subgroup_ub=True) + self.assertEqual(res16["outputs"][16]["%out_mrt0"], (1, 52, 50, 50)) + # Only lane 17 running: row_shr:1 reads absent lane 16 -> 0+1 = 1; dpp8 reads absent lane 16 -> 0+2 = 2! + res17 = wi.run_wave(spv, wave=32, active_lanes=[17], strict_subgroup_ub=True) + self.assertEqual(res17["outputs"][17]["%out_mrt0"], (1, 2, 50, 50)) + + def test_quad_any_partial_quad_in_vs_and_cs(self): + # Partial quad (only lane 5 running in quad 4..7): VS and CS use OpGroupNonUniformBallot + # (never QuadSwap or unguarded 4x Shuffle). + vs_spv = support.translate_lines("vs_w32_wqm_partial", [ + "v_cmp_eq_u32_e32 vcc_lo, 5, v0", + "s_wqm_b32 s4, vcc_lo", + "v_cndmask_b32_e64 v6, 0, 1, s4", + "v_mov_b32_e32 v5, 0", + "exp pos0 v5, v5, v5, v5 done", + "exp param0 v6, v5, v5, v5", + "s_endpgm", + ]) + self.assert_clean_module(vs_spv) + self.assertNotIn("OpGroupNonUniformShuffle", vs_spv) + self.assertNotIn("OpGroupNonUniformQuadSwap", vs_spv) + res = wi.run_wave(vs_spv, wave=32, active_lanes=[5, 6], strict_subgroup_ub=True, + builtins={"VertexIndex": lambda lane: lane, "InstanceIndex": lambda lane: 0}) + self.assertEqual(res["outputs"][5]["%out_param0"][0], 1) + self.assertEqual(res["outputs"][6]["%out_param0"][0], 1) + + cs_spv = support.translate_lines("cs_w32_wqm_partial", [ + "v_cmp_eq_u32_e32 vcc_lo, 5, v0", + "s_wqm_b32 s4, vcc_lo", + "v_cndmask_b32_e64 v6, 0, 1, s4", + "v_lshlrev_b32_e32 v7, 2, v0", + "buffer_store_dword v6, v7, s[0:3], 0 offen", + "s_endpgm", + ], fssm=compute_fssm(5, wave64=False)) + self.assert_clean_module(cs_spv) + self.assertNotIn("OpGroupNonUniformQuadSwap", cs_spv) + mem = {} + si.run_workgroup( + cs_spv, 2, 32, lanes=[5, 6], + inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": ([5, 6][i], 0, 0), "%sg_lane": [5, 6][i]}, + push_constants=[0x1000, 0, 0x100, 0x31016FAC] + [0] * 28, memory=mem, + ) + self.assertEqual(mem.get(0x1000 + 20), 1) + self.assertEqual(mem.get(0x1000 + 24), 1) + + def test_ds_append_zero_exec_and_absent_lane0(self): + # ds_append with EXEC == 0 in a partial wave where lane 0 is absent previously masked + # first=64 & 31 -> 0 and shuffled from absent lane 0! + cs_spv = support.translate_lines("cs_w32_ds_append_zero_exec", [ + "v_mov_b32_e32 v8, 0xdead", + "s_mov_b32 exec_lo, 0", + "ds_append v8", + "s_mov_b32 exec_lo, -1", + "v_mov_b32_e32 v7, 0", + "buffer_store_dword v8, v7, s[0:3], 0 offen", + "s_endpgm", + ], fssm=compute_fssm(32, wave64=False)) + self.assert_clean_module(cs_spv) + mem = {} + si.run_workgroup( + cs_spv, 1, 32, lanes=[5], + inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (5, 0, 0), "%sg_lane": 5}, + push_constants=[0x2000, 0, 0x100, 0x31016FAC] + [0] * 28, memory=mem, + ) + self.assertEqual(mem.get(0x2000), 0xDEAD) + + def test_wave32_mesh_shader_readfirstlane_sload_and_wqm(self): + # Synthetic wave32 mesh shader (like the run93 MS shape) exercising v_readfirstlane_b32 + # feeding s_load_dword, s_wqm_b32, and v_readlane_b32: zero unsafe shuffles, passes spirv-val. + r = bytearray(48) + struct.pack_into(" +0, signed subnormal underflow, normal products) in both FTZ32 and --no-ftz32 modes. + * Emitted SPIR-V passes spirv-as + spirv-val --target-env vulkan1.2, and CLI --no-ftz32 works end to end. +""" +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(os.path.dirname(HERE)) +TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") +sys.dont_write_bytecode = True +if TOOLS_DIR not in sys.path: + sys.path.insert(0, TOOLS_DIR) +if HERE not in sys.path: + sys.path.insert(0, HERE) + +import rdna2spirv # noqa: E402 +from shader_ir import parse_line # noqa: E402 +import support # noqa: E402 + + +def _translate(lines, *, ftz32=True, float_controls=True, name="ps_ftz32_test"): + old_fc, old_ftz = rdna2spirv.FLOAT_CONTROLS, rdna2spirv.FTZ32 + rdna2spirv.FLOAT_CONTROLS = float_controls + rdna2spirv.FTZ32 = ftz32 + try: + spv = support.translate_lines(name, lines) + meta = rdna2spirv.shader_meta(rdna2spirv.translate.last_gen, spv) + return spv, meta + finally: + rdna2spirv.FLOAT_CONTROLS = old_fc + rdna2spirv.FTZ32 = old_ftz + + +def _validate(spv): + if not (shutil.which("spirv-as") and shutil.which("spirv-val")): + return + with tempfile.TemporaryDirectory() as tmp: + asm, out = os.path.join(tmp, "m.spvasm"), os.path.join(tmp, "m.spv") + with open(asm, "w", encoding="utf-8", newline="\n") as f: + f.write(spv) + r1 = subprocess.run(["spirv-as", "--target-env", "vulkan1.2", asm, "-o", out], + capture_output=True, text=True) + assert r1.returncode == 0, r1.stderr + r2 = subprocess.run(["spirv-val", "--target-env", "vulkan1.2", out], + capture_output=True, text=True) + assert r2.returncode == 0, r2.stderr + + +class Ftz32AndFmulzTests(unittest.TestCase): + def test_hand_written_fixture_values_and_header(self): + path = Path(HERE) / "fixtures" / "ftz32_fmulz.asm" + lines = [ln.strip() for ln in path.read_text(encoding="utf-8").splitlines() + if ln.strip() and not ln.lstrip().startswith(";")] + spv_hw, meta_hw = _translate(lines, ftz32=True) + spv_sw, meta_sw = _translate(lines, ftz32=False) + + self.assertIn("OpCapability DenormFlushToZero", spv_hw) + self.assertIn("OpExecutionMode %main DenormFlushToZero 32", spv_hw) + self.assertIn("OpExecutionMode %main DenormPreserve 16", spv_hw) + self.assertIn("OpExecutionMode %main SignedZeroInfNanPreserve 32", spv_hw) + self.assertNotIn("SPV_KHR_float_controls", spv_hw) + self.assertEqual(meta_hw["float_controls"], [ + "shaderSignedZeroInfNanPreserveFloat32", + "shaderDenormPreserveFloat16", + "shaderDenormFlushToZeroFloat32", + ]) + # Software flush_f32() comparisons against 2^-126 are elided under FTZ32. + self.assertEqual(spv_hw.count("OpFOrdLessThan %bool"), 0) + self.assertGreaterEqual(spv_sw.count("OpFOrdLessThan %bool"), 10) + self.assertNotIn("DenormFlushToZero", spv_sw) + self.assertEqual(meta_sw["float_controls"], [ + "shaderSignedZeroInfNanPreserveFloat32", + "shaderDenormPreserveFloat16", + ]) + + # Expected mrt0 words: + # v2 = legacy_mul(subnorm, qNaN) = +0.0 (0x00000000) + # v5 = legacy_mul(-FLT_MIN, 0.5) = -0.0 (0x80000000) + # v8 = mad_f32(2.0, 3.0, subnorm) = 6.0 (0x40C00000) + # v9 = mad_legacy_f32(subnorm, qNaN, 2.0) = 2.0 (0x40000000) + want = [0x00000000, 0x80000000, 0x40C00000, 0x40000000] + self.assertEqual(support.mrt0_words(spv_hw), want) + self.assertEqual(support.mrt0_words(spv_sw), want) + _validate(spv_hw) + _validate(spv_sw) + + def test_gated_off_on_div_fmas_div_scale_and_setreg_mode(self): + # 1. s_setreg_imm32_b32 on HW_REG_MODE bits [3:2] (FP_ROUND.fp64_fp16) does NOT touch FP_DENORM.fp32 [5:4], + # so hardware DenormFlushToZero 32 stays enabled for both value 3 and value 0. + for imm in (3, 0): + with self.subTest(mode_round_imm=imm): + setreg_lines = [ + f"s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), {imm}", + "v_mov_b32 v0, 0x00000001", + "v_mov_b32 v1, 0x7fc00000", + "v_mul_legacy_f32 v2, v0, v1", + "exp mrt0 v2, v2, v2, v2 done vm", + "s_endpgm", + ] + spv_sr, meta_sr = _translate(setreg_lines, ftz32=True) + self.assertIn("OpCapability DenormFlushToZero", spv_sr) + self.assertIn("OpExecutionMode %main DenormFlushToZero 32", spv_sr) + self.assertIn("OpExecutionMode %main DenormPreserve 16", spv_sr) + self.assertIn("shaderDenormFlushToZeroFloat32", meta_sr["float_controls"]) + self.assertEqual(spv_sr.count("OpFOrdLessThan %bool"), 0) + self.assertEqual(support.mrt0_words(spv_sr), [0] * 4) + _validate(spv_sr) + + # 2. v_div_fmas_f32 disables FTZ32 (keeps subnormal inputs/intermediates on RDNA2 even under denorm32=0). + div_fmas_lines = [ + "v_mov_b32 v1, 0x00080000", + "v_mov_b32 v2, 0x67800000", + "v_mov_b32 v3, 0", + "v_cmp_eq_u32_e32 vcc_lo, 0, 1", + "v_div_fmas_f32 v0, v1, v2, v3", + "exp mrt0 v0, v0, v0, v0 done vm", + "s_endpgm", + ] + spv_df, meta_df = _translate(div_fmas_lines, ftz32=True) + self.assertNotIn("DenormFlushToZero", spv_df) + self.assertNotIn("shaderDenormFlushToZeroFloat32", meta_df["float_controls"]) + self.assertEqual(support.mrt0_words(spv_df)[0], 0x26800000) + _validate(spv_df) + + # 3. Direct predicate check for HW_REG_MODE bit-range overlap against [5:4] (FP_DENORM.fp32), + # plus v_div_scale_f32, s_denorm_mode, and non-MODE registers. + keep_ftz = [ + "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 3", + "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 0", + "s_setreg_imm32_b32 hwreg(0x1, 2, 2), 3", + "s_setreg_imm32_b32 0x0881, 3", # simm16: id=1 (HW_REG_MODE), offset=2, size=2 + "s_setreg_imm32_b32 0x0901, 0", # simm16: id=1 (HW_REG_MODE), offset=4, size=2, val=0 + "s_setreg_imm32_b32 0x0902, 3", # simm16: id=2 (non-MODE), offset=4, size=2 + "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 0, 4), 0xf", + "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 6, 4), 0xf", + "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 4, 2), 0", + "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 4, 4), 0", + "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 0, 32), 0x0c", + "s_setreg_imm32_b32 hwreg(HW_REG_MODE), 0", + "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 3, 2), 1", + "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 5, 2), 2", + "s_setreg_b32 hwreg(HW_REG_MODE, 2, 2), s0", + "s_setreg_imm32_b32 hwreg(HW_REG_FLAT_SCR_LO), 0", + "v_mul_legacy_f32 v0, v1, v2", + ] + disable_ftz = [ + "v_div_scale_f32 v0, vcc_lo, v1, v2, v1", + "s_denorm_mode 0", + "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 4, 2), 3", + "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 4, 2), 1", + "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 4, 2), 2", + "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 0, 32), 0x30", + "s_setreg_imm32_b32 hwreg(HW_REG_MODE), 0x10", + "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 3, 2), 2", + "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 5, 2), 1", + "s_setreg_imm32_b32 hwreg(1, 4, 2), 3", + "s_setreg_imm32_b32 hwreg(0x1, 4, 2), 3", + "s_setreg_b32 hwreg(0x1, 4, 2), s0", + "s_setreg_imm32_b32 0x0901, 3", # simm16: id=1 (HW_REG_MODE), offset=4, size=2, val=3 + "s_setreg_b32 0x0901, s0", # simm16: id=1 (HW_REG_MODE), offset=4, size=2, reg + "s_setreg_b32 hwreg(HW_REG_MODE, 4, 2), s0", + "s_setreg_b32 hwreg(HW_REG_MODE), s0", + "s_setreg_imm32_b32 hwreg(HW_REG_MODE, bad, 2), 0", + "s_setreg_imm32_b32 hwreg(1, bad, 2), 3", + "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 0, 33), 0", + ] + for line in keep_ftz: + with self.subTest(keep_ftz=line): + self.assertFalse(rdna2spirv._disables_ftz32([parse_line(line)])) + for line in disable_ftz: + with self.subTest(disable_ftz=line): + self.assertTrue(rdna2spirv._disables_ftz32([parse_line(line)])) + + def test_v_mul_legacy_f32_edge_cases_both_modes(self): + cases = [ + # 0 * NaN = +0.0, 0 * Inf = +0.0, (-0) * (+1) = +0.0, subnormal * NaN/Inf/normal = +0.0 + (0x00000000, 0x7FC00000, 0x00000000), + (0x80000000, 0x7FC00001, 0x00000000), + (0xFFC00000, 0x00000000, 0x00000000), + (0x00000000, 0x7F800000, 0x00000000), + (0x80000000, 0xFF800000, 0x00000000), + (0x7F800000, 0x80000000, 0x00000000), + (0x80000000, 0x3F800000, 0x00000000), + (0x3F800000, 0x80000000, 0x00000000), + (0x00000001, 0x7FC00000, 0x00000000), + (0x807FFFFF, 0x7F800000, 0x00000000), + # Underflow preserves product sign + (0x00800000, 0x3F000000, 0x00000000), + (0x80800000, 0x3F000000, 0x80000000), + # Normal products and Inf + (0x40000000, 0x40400000, 0x40C00000), + (0xBF800000, 0x7F800000, 0xFF800000), + ] + for ftz32 in (True, False): + for x, y, want in cases: + with self.subTest(ftz32=ftz32, x=hex(x), y=hex(y)): + spv, _ = _translate([ + f"v_mov_b32 v0, {x:#x}", + f"v_mov_b32 v1, {y:#x}", + "v_mul_legacy_f32 v2, v0, v1", + "exp mrt0 v2, v2, v2, v2 done vm", + "s_endpgm", + ], ftz32=ftz32) + self.assertEqual(support.mrt0_words(spv)[0], want) + # Non-zero * NaN stays NaN + for ftz32 in (True, False): + spv, _ = _translate([ + "v_mov_b32 v0, 0x3f800000", + "v_mov_b32 v1, 0x7fc00000", + "v_mul_legacy_f32 v2, v0, v1", + "exp mrt0 v2, v2, v2, v2 done vm", + "s_endpgm", + ], ftz32=ftz32) + got = support.mrt0_words(spv)[0] + self.assertEqual(got & 0x7F800000, 0x7F800000) + self.assertNotEqual(got & 0x007FFFFF, 0) + + def test_cli_no_ftz32_flag(self): + with tempfile.TemporaryDirectory() as tmp: + dis = os.path.join(tmp, "disasm") + out = os.path.join(tmp, "out") + os.mkdir(dis) + with open(os.path.join(dis, "ps_cli.s"), "w", encoding="utf-8") as f: + f.write("; ps_cli\n\tv_mul_legacy_f32 v0, v1, v2\n\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n") + with open(os.path.join(tmp, "ps_cli.dxbc"), "wb") as f: + f.write(support.STUB_DXBC) + cmd = [sys.executable, "-I", os.path.join(TOOLS_DIR, "rdna2spirv.py"), + dis, "--out", out, "--assembler", "python", "--no-validate", "--no-ftz32"] + p = subprocess.run(cmd, capture_output=True, text=True) + self.assertEqual(p.returncode, 0, p.stderr) + spvasm = Path(out, "ps_cli.spvasm").read_text(encoding="utf-8") + self.assertNotIn("DenormFlushToZero", spvasm) + self.assertGreaterEqual(spvasm.count("OpFOrdLessThan %bool"), 3) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_image_float_elide_and_store_table.py b/tests/semantic/test_image_float_elide_and_store_table.py new file mode 100644 index 0000000000..3780e1ebc6 --- /dev/null +++ b/tests/semantic/test_image_float_elide_and_store_table.py @@ -0,0 +1,331 @@ +"""Item 3B.6 tests: float-only image_read_typed elision + compact table-driven buffer_store_format. + +Part A: + * Elides dead uint/sint branches, format-mask lookups, and %itx1/%itx2 descriptor array aliases + when an image_load* / image_sample* is provably float-only (dest VGPRs consumed solely by + float ops, or filtered literal S# on image_sample*). + * Never drops uint/sint branches for integer-sampled/gathered/loaded ops (image_gather4, + point-filtered image_sample with int consumers, or image_load consumed by int/untyped ops). + +Part B: + * Verifies %fmt_encode_fn / %fmt_enc_chan is branch-free and compact (no 77-way OpSwitch). + * Verifies bit-for-bit parity between dynamic table-driven `buffer_store_format_*` and fixed + `tbuffer_store_format_*` across ALL 77 GFX10 format codes in `Gen.FORMATS` (plus unknown codes, + BGRA 0xf2e swizzle on codes 50/56, 2-component DST_SEL swizzles, and d16 sign extension). +""" +import os +import re +import shutil +import struct +import subprocess +import tempfile +import unittest + +import support +import rdna2spirv +import spirv_asm +from spirv_mini_interp import run_fragment + +BASE = 0x2000 +BRANCHES = ("OpBranchConditional", "OpSelectionMerge", "OpSwitch", "OpBranch", "OpLoopMerge") +GFX10_FORMAT_NAMES = {code: name.removeprefix("GFX10_FORMAT_") for code, name in rdna2spirv.GFX10_FORMATS.items()} + + +def validate_v12(testcase, asm, label): + if not (shutil.which("spirv-as") and shutil.which("spirv-val")): + return + with tempfile.TemporaryDirectory() as tmp: + sa = os.path.join(tmp, f"{label}.spvasm") + sv = os.path.join(tmp, f"{label}.spv") + with open(sa, "w", encoding="utf-8") as f: + f.write(asm) + res = rdna2spirv.assemble_spirv(sa, sv) + testcase.assertEqual(res.returncode, 0, f"{label} spirv-as/val failed:\n{res.stderr}\n{res.stdout}") + sv_py = os.path.join(tmp, f"{label}_py.spv") + with open(sv_py, "wb") as f: + f.write(spirv_asm.assemble(asm, target_env="vulkan1.2")) + r2 = subprocess.run(["spirv-val", "--target-env", "vulkan1.2", sv_py], capture_output=True, text=True) + testcase.assertEqual(r2.returncode, 0, f"{label} spirv_asm+val failed:\n{r2.stderr}\n{r2.stdout}") + + +def function_body(spv, name): + body, inside = [], False + for line in spv.splitlines(): + text = line.strip() + if text.startswith(f"{name} = OpFunction"): + inside = True + continue + if inside: + if text == "OpFunctionEnd": + break + body.append(text) + return body + + +class ImageReadTypedFloatElisionTests(unittest.TestCase): + def test_float_only_image_load_elides_uint_sint_branches(self): + lines = [ + "v_mov_b32 v4, 1", + "v_mov_b32 v5, 2", + "image_load v[0:1], v[4:5], s[0:7] dmask:0x3 dim:SQ_RSRC_IMG_2D unorm", + "s_waitcnt vmcnt(0)", + "v_mul_f32_e32 v0, 0x40000000, v0", + "v_add_f32_e32 v1, 0x3f800000, v1", + "exp mrt0 v0, v1, v0, v1 done vm", + "s_endpgm", + ] + asm = support.translate_lines("ps_load_float_only", lines) + self.assertNotIn("%itx1_0", asm) + self.assertNotIn("%itx2_0", asm) + self.assertNotIn("%fmt_uint_mask", asm) + self.assertNotIn("%fmt_sint_mask", asm) + self.assertEqual(asm.count("OpImageFetch "), 1) + self.assertIn("OpImageFetch %v4float", asm) + validate_v12(self, asm, "load_float_only") + + def test_float_only_image_load_d16_elides_int_views_keeps_d16_masks(self): + lines = [ + "v_mov_b32 v4, 1", + "v_mov_b32 v5, 2", + "image_load v0, v[4:5], s[0:7] dmask:0x3 dim:SQ_RSRC_IMG_2D unorm d16", + "s_waitcnt vmcnt(0)", + "v_pk_mul_f16 v0, v0, v0", + "exp mrt0 v0, v0, v0, v0 done vm", + "s_endpgm", + ] + asm = support.translate_lines("ps_load_d16_float_only", lines) + self.assertNotIn("%itx1_0", asm) + self.assertNotIn("%itx2_0", asm) + self.assertNotIn("%fmt_uint_mask", asm) + self.assertIn("%fmt_norm_mask", asm) + self.assertIn("%fmt_f32_mask", asm) + self.assertEqual(asm.count("OpImageFetch "), 1) + validate_v12(self, asm, "load_d16_float_only") + + def test_filtered_literal_sampler_sample_elides_uint_sint_branches(self): + # S# word 2 = 0x00500000 -> XY_MAG_FILTER=1 (bilinear), XY_MIN_FILTER=1 (bilinear). + for op, addr in (("image_sample", "v[4:5]"), ("image_sample_lz", "v[4:5]"), ("image_sample_l", "v[4:6]")): + with self.subTest(op=op): + lines = [ + "s_mov_b32 s8, 0x92", + "s_mov_b32 s9, 0x00c00000", + "s_mov_b32 s10, 0x00500000", + "s_mov_b32 s11, 0", + "v_mov_b32 v4, 0x3f000000", + "v_mov_b32 v5, 0x3f000000", + "v_mov_b32 v6, 0", + f"{op} v[0:3], {addr}, s[0:7], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D", + "s_waitcnt vmcnt(0)", + "exp mrt0 v0, v1, v2, v3 done vm", + "s_endpgm", + ] + asm = support.translate_lines("ps_filt_smp", lines) + self.assertNotIn("%itx1_0", asm) + self.assertNotIn("%itx2_0", asm) + self.assertNotIn("%fmt_uint_mask", asm) + validate_v12(self, asm, "filt_" + op) + + def test_int_consumers_and_gather4_never_elide_uint_sint_branches(self): + # 1. image_load consumed by integer op must keep all 3 typed fetches. + int_load = [ + "v_mov_b32 v4, 1", + "v_mov_b32 v5, 2", + "image_load v0, v[4:5], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm", + "s_waitcnt vmcnt(0)", + "v_add_nc_u32_e32 v0, 1, v0", + "exp mrt0 v0, v0, v0, v0 done vm", + "s_endpgm", + ] + asm_load = support.translate_lines("ps_int_load", int_load) + self.assertIn("%itx1_0", asm_load) + self.assertIn("%itx2_0", asm_load) + self.assertEqual(asm_load.count("OpImageFetch "), 3) + + # 2. point-filtered literal sampler + integer consumer (like SINT sample) must keep all 3 branches. + int_sample = [ + "s_mov_b32 s8, 0x92", + "s_mov_b32 s9, 0x00c00000", + "s_mov_b32 s10, 0x00000000", + "s_mov_b32 s11, 0", + "v_mov_b32 v4, 0x3f000000", + "v_mov_b32 v5, 0x3f000000", + "image_sample v0, v[4:5], s[0:7], s[8:11] dmask:0x1 dim:SQ_RSRC_IMG_2D d16", + "s_waitcnt vmcnt(0)", + "v_bfe_i32 v0, v0, 0, 16", + "exp mrt0 v0, v0, v0, v0 done vm", + "s_endpgm", + ] + asm_smp = support.translate_lines("ps_int_sample", int_sample) + self.assertIn("%itx1_0", asm_smp) + self.assertIn("%itx2_0", asm_smp) + + # 3. image_gather4_lz (even with float consumers) stays typed because gather4 works on int formats. + gather = [ + "v_mov_b32 v4, 0x3f000000", + "v_mov_b32 v5, 0x3f000000", + "image_gather4_lz v[0:3], v[4:5], s[0:7], s[8:11] dmask:0x1 dim:SQ_RSRC_IMG_2D", + "s_waitcnt vmcnt(0)", + "v_add_f32_e32 v0, v0, v1", + "v_add_f32_e32 v2, v2, v3", + "exp mrt0 v0, v2, v0, v2 done vm", + "s_endpgm", + ] + asm_g = support.translate_lines("ps_gather_typed", gather) + self.assertIn("%itx1_0", asm_g) + self.assertIn("%itx2_0", asm_g) + self.assertEqual(asm_g.count("OpImageGather "), 3) + + def test_atomics_ds_indirect_and_partial_f16_writes_never_elide_uint_sint(self): + # P0-1: a[0] read by buffer_atomic_add / ds_add_u32 / image_atomic_add must prevent float-only elision. + for label, stage, tail in ( + ("buffer_atomic", "ps", [ + "image_load v[0:1], v[4:5], s[0:7] dmask:0x3 dim:SQ_RSRC_IMG_2D unorm", + "s_waitcnt vmcnt(0)", + "v_mul_f32_e32 v2, 0x40000000, v1", + "buffer_atomic_add v0, v4, s[8:11], 0 offen", + "exp mrt0 v2, v2, v2, v2 done vm", + "s_endpgm", + ]), + ("ds_atomic", "cs", [ + "image_load v[0:1], v[4:5], s[0:7] dmask:0x3 dim:SQ_RSRC_IMG_2D unorm", + "s_waitcnt vmcnt(0)", + "v_mul_f32_e32 v2, 0x40000000, v1", + "ds_add_u32 v0, v4", + "s_endpgm", + ]), + ("image_atomic", "ps", [ + "image_load v[0:1], v[4:5], s[0:7] dmask:0x3 dim:SQ_RSRC_IMG_2D unorm", + "s_waitcnt vmcnt(0)", + "v_mul_f32_e32 v2, 0x40000000, v1", + "image_atomic_add v0, v[4:5], s[8:15] dmask:0x1 dim:SQ_RSRC_IMG_2D", + "exp mrt0 v2, v2, v2, v2 done vm", + "s_endpgm", + ]), + ("v_movrels", "ps", [ + "image_load v0, v[4:5], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm", + "s_waitcnt vmcnt(0)", + "v_mul_f32_e32 v2, 0x40000000, v0", + "v_movrels_b32_e32 v3, v0", + "exp mrt0 v2, v3, v2, v3 done vm", + "s_endpgm", + ]), + # P0-2: scalar 16-bit write v_add_f16 preserves v0[31:16], so downstream integer read sees upper half! + ("partial_f16_write", "ps", [ + "image_load v0, v[4:5], s[0:7] dmask:0x3 dim:SQ_RSRC_IMG_2D unorm d16", + "s_waitcnt vmcnt(0)", + "v_add_f16_e32 v0, 0x3c00, v0", + "v_lshrrev_b32_e32 v1, 16, v0", + "exp mrt0 v0, v1, v0, v1 done vm", + "s_endpgm", + ]), + ): + with self.subTest(case=label): + fssm = None + if stage == "cs": + hdr = bytearray(0x148) + struct.pack_into("<4I", hdr, 0x138, 0x8088, 64, 1, 1) + fssm = bytes(hdr) + asm = support.translate_lines(f"{stage}_neg_" + label, [ + "v_mov_b32 v4, 1", + "v_mov_b32 v5, 2", + ] + tail, fssm=fssm) + self.assertIn("%itx1_0", asm, f"{label} must NOT elide %itx1_0") + self.assertIn("%itx2_0", asm, f"{label} must NOT elide %itx2_0") + self.assertEqual(asm.count("OpImageFetch "), 3, f"{label} must keep all 3 typed fetches") + + +def _store_dynamic(code, vals, dst_sel=0xFAC, d16=False): + op = "buffer_store_format_d16_xyzw" if d16 else "buffer_store_format_xyzw" + regs = "v[2:3]" if d16 else "v[2:5]" + movs = [f"v_mov_b32 v{2 + i}, {w:#x}" for i, w in enumerate(vals)] + d3 = 0x30000000 | (code << 12) | dst_sel + lines = [ + f"s_mov_b32 s0, {BASE:#x}", + "s_mov_b32 s1, 0", + "s_mov_b32 s2, 0x100", + f"s_mov_b32 s3, {d3:#x}", + "v_mov_b32 v1, 0", + *movs, + f"{op} {regs}, v1, s[0:3], 0 offen", + "exp mrt0 v1, v1, v1, v1 done vm", + "s_endpgm", + ] + spv = support.translate_lines("ps_dyn_store", lines) + mem = {BASE + 4 * i: 0xDEAD0000 + i for i in range(4)} + run_fragment(spv, memory=mem) + return tuple(mem[BASE + 4 * i] for i in range(4)), spv + + +def _store_fixed(code, vals, dst_sel=0xFAC, d16=False): + op = "tbuffer_store_format_d16_xyzw" if d16 else "tbuffer_store_format_xyzw" + regs = "v[2:3]" if d16 else "v[2:5]" + movs = [f"v_mov_b32 v{2 + i}, {w:#x}" for i, w in enumerate(vals)] + fmt_name = GFX10_FORMAT_NAMES[code] + d3 = 0x30000000 | (code << 12) | dst_sel + lines = [ + f"s_mov_b32 s0, {BASE:#x}", + "s_mov_b32 s1, 0", + "s_mov_b32 s2, 0x100", + f"s_mov_b32 s3, {d3:#x}", + "v_mov_b32 v1, 0", + *movs, + f"{op} {regs}, v1, s[0:3], 0 format:[BUF_FMT_{fmt_name}] offen", + "exp mrt0 v1, v1, v1, v1 done vm", + "s_endpgm", + ] + spv = support.translate_lines("ps_fix_store", lines) + mem = {BASE + 4 * i: 0xDEAD0000 + i for i in range(4)} + run_fragment(spv, memory=mem) + return tuple(mem[BASE + 4 * i] for i in range(4)) + + +class TableDrivenBufferStoreFormatTests(unittest.TestCase): + def test_encoder_is_compact_and_branch_free(self): + _, spv = _store_dynamic(56, (0x3F000000, 0x3E99999A, 0xBF000000, 0x3F800000)) + self.assertIn("%fmt_enc_desc_tab = OpVariable", spv) + self.assertIn("%fmt_enc_chan = OpFunction %uint None %fn_fmt_enc_chan", spv) + self.assertIn("%fmt_encode_fn = OpFunction %v4uint_fmt None %fn_fmt_encode", spv) + chan_body = function_body(spv, "%fmt_enc_chan") + enc_body = function_body(spv, "%fmt_encode_fn") + self.assertTrue(chan_body and enc_body) + for line in chan_body + enc_body: + for br in BRANCHES: + self.assertNotIn(br, line, f"format encoder must be branch-free, found: {line}") + total = len(chan_body) + len(enc_body) + # Old 77-way OpSwitch was ~3,668 ops; table-driven encoder is < 350 ops. + self.assertLess(total, 350, f"format encoder too large: {total} ops") + validate_v12(self, spv, "table_store_enc") + + def test_bit_for_bit_parity_across_all_77_gfx10_formats(self): + # Test vectors exercising ties (0.3 UNORM16 -> 19661), negatives, overflow, NaN, inf, ufloat, int clamping. + f_vec1 = (0x3E99999A, 0xBF000000, 0x42C80000, 0x7FC00000) # 0.3, -0.5, 100.0, qNaN + f_vec2 = (0x80000000, 0x3F800000, 0x7F800000, 0xFF800000) # -0.0, 1.0, +inf, -inf + i_vec = (0x0000007F, 0xFFFFFF80, 0x00012345, 0x80000001) # +127, -128, large +, large - + for code, (_, kind, widths) in sorted(rdna2spirv.Gen.FORMATS.items()): + # Use XY01 (0x00000000 | 4 | 5<<3 = 0x24 -> XY00) for 2-component formats so MUBUF and MTBUF match. + sel = 0x024 if len(widths) == 2 else 0xFAC + vecs = (i_vec,) if kind in ("u32", "i32", "uint", "sint") else (f_vec1, f_vec2) + for vec in vecs: + with self.subTest(code=code, kind=kind, vec=tuple(hex(x) for x in vec)): + got, _ = _store_dynamic(code, vec, dst_sel=sel) + want = _store_fixed(code, vec, dst_sel=sel) + self.assertEqual(got, want, f"format {code} ({kind} {widths}) mismatch") + + def test_unknown_formats_bgra_swap_and_d16_signed_parity(self): + # Unknown codes (0, 78, 127) write nothing (memory keeps sentinel 0xDEAD0000..3). + sentinel = tuple(0xDEAD0000 + i for i in range(4)) + for code in (0, 78, 127): + got, _ = _store_dynamic(code, (0x3F800000,) * 4) + self.assertEqual(got, sentinel, f"unknown format {code} should not touch memory") + # BGRA swap (dst_sel=0xF2E) on codes 50 (2_10_10_10_UNORM) and 56 (8_8_8_8_UNORM). + vec = (0x3E800000, 0x3F000000, 0x3F400000, 0x3F800000) # 0.25, 0.5, 0.75, 1.0 + for code in (50, 56): + self.assertEqual(_store_dynamic(code, vec, dst_sel=0xF2E)[0], _store_fixed(code, vec, dst_sel=0xF2E)) + # D16 signed SINT (e.g. code 61 = 8_8_8_8_SINT, code 76 = 32_32_32_32_SINT) parity. + d16_vals = (0xFF80007F, 0x80000001) # (+127, -128, +1, -32768) + for code in (60, 61, 69, 70, 75, 76): + self.assertEqual(_store_dynamic(code, d16_vals, d16=True)[0], _store_fixed(code, d16_vals, d16=True)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_int32_to_f64.py b/tests/semantic/test_int32_to_f64.py index f8079dddf9..3d3f1ee623 100644 --- a/tests/semantic/test_int32_to_f64.py +++ b/tests/semantic/test_int32_to_f64.py @@ -22,7 +22,9 @@ def test_constant_folded_mrt_words(self): foldable = translate_fixture("ps_int32_to_f64") float_controls = { "OpCapability SignedZeroInfNanPreserve", "OpCapability DenormPreserve", + "OpCapability DenormFlushToZero", "OpExecutionMode %main SignedZeroInfNanPreserve 32", "OpExecutionMode %main DenormPreserve 16", + "OpExecutionMode %main DenormFlushToZero 32", # SHADER-597 (#3290): a module that declares Float64 also preserves f64 signed zeros, infs and NaNs "OpExecutionMode %main SignedZeroInfNanPreserve 64", } diff --git a/tests/semantic/test_literal_sampler_spec.py b/tests/semantic/test_literal_sampler_spec.py new file mode 100644 index 0000000000..fc90219b4d --- /dev/null +++ b/tests/semantic/test_literal_sampler_spec.py @@ -0,0 +1,160 @@ +"""Compile-time literal S# samplers via OpSpecConstant (Item 3B.5). + +For each compile-time literal S# in `meta["literal_samplers"]` (exact sorted list order): + * Declares `OpSpecConstant %uint 4294967295` (`0xFFFFFFFF`) with `OpDecorate %lit_smp_ SpecId `. + * Emits `meta["literal_sampler_spec_base"] = 0`. + * At each sample/gather/get_lod site using that literal S#, branches on `%lit_smp_ != 0xFFFFFFFF`: + - When specialized (`!= 0xFFFFFFFF`), uses `%lit_smp_` directly (bypassing `%desc_lookup_fn`). + - When unspecialized (`0xFFFFFFFF`), falls back to the bindless hash-table probe. +""" +import os +import re +import shutil +import subprocess +import tempfile +import unittest + +import support +import rdna2spirv +import spirv_asm + +S0 = (0x00000092, 0x00C00000, 0x00000000, 0x00000000) # point filter literal S# +S1 = (0x00000092, 0x00C00000, 0x00500000, 0x00000000) # bilinear filter literal S# + + +def translate_with_meta(name, lines): + asm = support.translate_lines(name, lines) + meta = rdna2spirv.shader_meta(rdna2spirv.translate.last_gen, asm) + return asm, meta + + +def validate_v12(testcase, asm, label): + if not (shutil.which("spirv-as") and shutil.which("spirv-val")): + return + with tempfile.TemporaryDirectory() as tmp: + sa = os.path.join(tmp, f"{label}.spvasm") + sv = os.path.join(tmp, f"{label}.spv") + with open(sa, "w", encoding="utf-8") as f: + f.write(asm) + res = rdna2spirv.assemble_spirv(sa, sv) + testcase.assertEqual(res.returncode, 0, f"{label} spirv-as/val failed:\n{res.stderr}\n{res.stdout}") + sv_py = os.path.join(tmp, f"{label}_py.spv") + with open(sv_py, "wb") as f: + f.write(spirv_asm.assemble(asm, target_env="vulkan1.2")) + r2 = subprocess.run(["spirv-val", "--target-env", "vulkan1.2", sv_py], capture_output=True, text=True) + testcase.assertEqual(r2.returncode, 0, f"{label} spirv_asm+val failed:\n{r2.stderr}\n{r2.stdout}") + + +def eval_sampler_select(asm, spec_val, hash_result): + """Evaluate the spec-constant selection branch for %lit_smp_0 and return (selected_index, probed_hash).""" + defs = {} + order = [] + for line in asm.splitlines(): + m = re.match(r"\s*(%\w+) = (Op\w+)\s*(.*)$", line) + if m: + defs[m.group(1)] = (m.group(2), m.group(3).split()) + order.append((m.group(1), m.group(2), m.group(3).split())) + else: + m2 = re.match(r"\s*(OpBranchConditional)\s+(.*)$", line) + if m2: + order.append((None, m2.group(1), m2.group(2).split())) + # Locate the OpINotEqual comparing %lit_smp_0 against 0xFFFFFFFF and its merge OpPhi. + cmp_id = next(r for r, op, a in order if op == "OpINotEqual" and "%lit_smp_0" in a) + br = next(a for _, op, a in order if op == "OpBranchConditional" and a[0] == cmp_id) + fast_lbl, probe_lbl = br[1], br[2] + phi_id, _, phi_args = next((r, op, a) for r, op, a in order if op == "OpPhi" and "%lit_smp_0" in a) + # %lit_smp_0 != 0xFFFFFFFF branches straight to fast_lbl (skipping probe_lbl). + is_specialized = (spec_val & 0xFFFFFFFF) != 0xFFFFFFFF + if is_specialized: + assert phi_args[1] == "%lit_smp_0" + return spec_val, False + # Unspecialized path enters probe_lbl, runs %desc_lookup_fn, and arrives from probe_lbl. + assert probe_lbl in phi_args + # Verify the probe block actually calls %desc_lookup_fn. + probe_idx = next(i for i, (r, op, _) in enumerate(order) if r == probe_lbl and op == "OpLabel") + fast_idx = next(i for i, (r, op, _) in enumerate(order) if r == fast_lbl and op == "OpLabel") + probe_calls = [a for _, op, a in order[probe_idx:fast_idx] if op == "OpFunctionCall" and a[1] == "%desc_lookup_fn"] + assert len(probe_calls) == 1, f"expected 1 hash lookup call in probe block, got {probe_calls}" + return hash_result, True + + +class LiteralSamplerSpecConstantTests(unittest.TestCase): + def test_single_literal_sampler_spec_constant_and_both_paths(self): + lines = [ + f"s_mov_b32 s12, {S0[0]:#x}", + f"s_mov_b32 s13, {S0[1]:#x}", + f"s_mov_b32 s14, {S0[2]:#x}", + f"s_mov_b32 s15, {S0[3]:#x}", + "v_mov_b32 v4, 0x3f000000", + "v_mov_b32 v5, 0x3f000000", + "image_sample v[0:3], v[4:5], s[0:7], s[12:15] dmask:0xf dim:SQ_RSRC_IMG_2D", + "s_waitcnt vmcnt(0)", + "exp mrt0 v0, v1, v2, v3 done vm", + "s_endpgm", + ] + asm, meta = translate_with_meta("ps_lit_smp1", lines) + self.assertEqual(meta["literal_samplers"], [list(S0)]) + self.assertEqual(meta["literal_sampler_spec_base"], 0) + self.assertIn("OpDecorate %lit_smp_0 SpecId 0", asm) + self.assertIn("%lit_smp_0 = OpSpecConstant %uint 4294967295", asm) + validate_v12(self, asm, "lit_smp1") + + # Specialized path: uses spec constant directly without calling %desc_lookup_fn. + idx_spec, probed_spec = eval_sampler_select(asm, spec_val=7, hash_result=99) + self.assertEqual((idx_spec, probed_spec), (7, False)) + + # Unspecialized path (0xFFFFFFFF): falls back to %desc_lookup_fn hash probe. + idx_fb, probed_fb = eval_sampler_select(asm, spec_val=0xFFFFFFFF, hash_result=13) + self.assertEqual((idx_fb, probed_fb), (13, True)) + + def test_two_literal_samplers_preserve_exact_sorted_order(self): + # Emit S1 before S0 in instruction order; literal_samplers is sorted so S0 -> SpecId 0, S1 -> SpecId 1. + lines = [ + f"s_mov_b32 s12, {S1[0]:#x}", + f"s_mov_b32 s13, {S1[1]:#x}", + f"s_mov_b32 s14, {S1[2]:#x}", + f"s_mov_b32 s15, {S1[3]:#x}", + f"s_mov_b32 s16, {S0[0]:#x}", + f"s_mov_b32 s17, {S0[1]:#x}", + f"s_mov_b32 s18, {S0[2]:#x}", + f"s_mov_b32 s19, {S0[3]:#x}", + "v_mov_b32 v4, 0x3f000000", + "v_mov_b32 v5, 0x3f000000", + "image_sample v[0:3], v[4:5], s[0:7], s[12:15] dmask:0xf dim:SQ_RSRC_IMG_2D", + "image_sample_lz v[6:9], v[4:5], s[0:7], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D", + "s_waitcnt vmcnt(0)", + "exp mrt0 v0, v6, v1, v7 done vm", + "s_endpgm", + ] + asm, meta = translate_with_meta("ps_lit_smp2", lines) + self.assertEqual(meta["literal_samplers"], [list(S0), list(S1)]) + self.assertEqual(meta["literal_sampler_spec_base"], 0) + self.assertIn("OpDecorate %lit_smp_0 SpecId 0", asm) + self.assertIn("OpDecorate %lit_smp_1 SpecId 1", asm) + self.assertIn("%lit_smp_0 = OpSpecConstant %uint 4294967295", asm) + self.assertIn("%lit_smp_1 = OpSpecConstant %uint 4294967295", asm) + # First sample used S1 (SpecId 1), second sample used S0 (SpecId 0). + pos1 = asm.index("OpINotEqual %bool %lit_smp_1") + pos0 = asm.index("OpINotEqual %bool %lit_smp_0") + self.assertLess(pos1, pos0) + validate_v12(self, asm, "lit_smp2") + + def test_dynamic_sampler_omits_spec_constants_and_meta_key(self): + lines = [ + "v_mov_b32 v4, 0x3f000000", + "v_mov_b32 v5, 0x3f000000", + "image_sample v[0:3], v[4:5], s[0:7], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D", + "s_waitcnt vmcnt(0)", + "exp mrt0 v0, v1, v2, v3 done vm", + "s_endpgm", + ] + asm, meta = translate_with_meta("ps_dyn_smp", lines) + self.assertNotIn("literal_samplers", meta) + self.assertNotIn("literal_sampler_spec_base", meta) + self.assertNotIn("OpSpecConstant", asm) + self.assertNotIn("SpecId", asm) + validate_v12(self, asm, "dyn_smp") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_mutations.py b/tests/semantic/test_mutations.py index e99ef82ea5..f82ae30554 100644 --- a/tests/semantic/test_mutations.py +++ b/tests/semantic/test_mutations.py @@ -68,11 +68,11 @@ 'self.emit(f"{arg} = OpFMul %float {t} {self.fconst(1.0)}")', "test_ps_ops4"), ("v_mul_legacy_f32 drops zero-times-anything guard", TRANSLATOR, - # since SHADER-340 v_mul_legacy_f32 flushes its inputs and product; the guard is the OpSelect on either zero - ' self.emit(f"{either} = OpLogicalOr %bool {zx} {zy}")\n' - ' self.emit(f"{r} = OpSelect %float {either} %f0 {self.flush_f32(m)}")', - ' self.emit(f"{either} = OpLogicalOr %bool {zx} {zy}")\n' - ' self.emit(f"{r} = OpCopyObject %float {self.flush_f32(m)}")', + # Under default FTZ32 v_mul_legacy_f32 uses the canonical fmulz select; dropping it fails test_ps_legacy_mul. + ' self.emit(f"{either} = OpLogicalOr %bool {zx} {zy}")\n' + ' self.emit(f"{r} = OpSelect %float {either} %f0 {m}")', + ' self.emit(f"{either} = OpLogicalOr %bool {zx} {zy}")\n' + ' self.emit(f"{r} = OpCopyObject %float {m}")', "test_ps_legacy_mul"), ] diff --git a/tests/semantic/test_packed_dot4.py b/tests/semantic/test_packed_dot4.py new file mode 100644 index 0000000000..7c3c0deddd --- /dev/null +++ b/tests/semantic/test_packed_dot4.py @@ -0,0 +1,92 @@ +"""The 4x8-bit dot products as SPV_KHR_integer_dot_product instructions, and their --integer-dot-fallback form. + +v_dot4_i32_i8 / v_dot4c_i32_i8 become OpSDot on the two dwords read as packed signed bytes, v_dot4_u32_u8 / +v_dot4c_u32_u8 OpUDot on packed unsigned ones (PackedVectorFormat4x8Bit), and the addend is added with OpIAdd, which +wraps at 32 bits as the instructions do. Under clamp the hardware saturates the addend plus the exact sum, which is +what OpSDotAccSat / OpUDotAccSat compute. op_sel picks 16-bit halves of the sources (measured on gfx1036, +test_alu_dot4_i8.py); the halves are put together into one dword first (Gen.dot4_halves), so the instruction still +sees four bytes. The expanded form (four extracts, multiplies and adds) stays for --integer-dot-fallback and must give +the same words. docs/design.md, "Signed-byte dot products". + + python -m unittest discover -s tests/semantic -p test_packed_dot4.py +""" +import inspect +from pathlib import Path +import unittest + +from support import HERE, mrt0_words, rdna2spirv, translate_listing + +FIXTURES = Path(HERE) / "fixtures" +I8_WORDS = [0x8000FC03, 0x7FFFFFFF, 0x80000000, 0x0000003E] +U8_WORDS = [0x00004288, 0x0003F803, 0xFFFFFFFF, 0x00008506] + + +def translate_text(name, data, fallback=False): + saved = rdna2spirv.INTEGER_DOT_FALLBACK + rdna2spirv.INTEGER_DOT_FALLBACK = fallback + try: + return translate_listing(name, data) + finally: + rdna2spirv.INTEGER_DOT_FALLBACK = saved + + +def translate(name, fallback=False): + return translate_text("ps_" + name, (FIXTURES / (name + ".asm")).read_bytes(), fallback) + + +def body(text): + """The module from its first function on: what the instructions became, without the header.""" + return text[text.index(" = OpFunction "):] + + +class PackedDot4(unittest.TestCase): + def test_signed_bytes(self): + text = translate("packed_dot4_i8") + self.assertEqual(mrt0_words(text), I8_WORDS) + self.assertEqual(text.count("OpSDotKHR %int"), 2) # the plain form and op_sel + self.assertEqual(text.count("OpSDotAccSatKHR %int"), 2) # both clamps + self.assertNotIn("OpBitFieldSExtract", body(text)) + self.assertIn("OpCapability DotProductKHR", text) + self.assertIn("OpCapability DotProductInput4x8BitPackedKHR", text) + self.assertIn('OpExtension "SPV_KHR_integer_dot_product"', text) + + def test_unsigned_bytes(self): + text = translate("packed_dot4_u8") + self.assertEqual(mrt0_words(text), U8_WORDS) + self.assertEqual(text.count("OpUDotKHR %uint"), 4) # v_dot4_u32_u8 twice, v_dot4c_u32_u8 twice + self.assertEqual(text.count("OpUDotAccSatKHR %uint"), 1) + self.assertNotIn("OpBitFieldUExtract", body(text)) + + def test_fallback_gives_the_same_words(self): + for name, words in (("packed_dot4_i8", I8_WORDS), ("packed_dot4_u8", U8_WORDS)): + with self.subTest(name=name): + text = translate(name, fallback=True) + self.assertEqual(mrt0_words(text), words) + self.assertNotIn("DotProduct", text) + self.assertNotIn("SPV_KHR_integer_dot_product", text) + self.assertNotIn("Dot", body(text)) + + def test_the_index_names_the_feature(self): + # shader_meta maps each capability to the device feature the runtime must enable. + self.assertIn('"DotProductKHR": "shaderIntegerDotProduct"', inspect.getsource(rdna2spirv.shader_meta)) + + def test_the_halves_op_sel_picks(self): + # Every op_sel / op_sel_hi pair the rule takes for S1, against the reference of test_alu_dot4_i8: bytes 0..1 + # from half `lo`, bytes 2..3 from half `hi`. Both forms must agree with it. + def s8(byte): + return byte - 256 if byte & 0x80 else byte + a, b = 0x7F01FE80, 0x02FD7F81 + for lo, hi in ((0, 0), (0, 1), (1, 0), (1, 1)): + halves = ((b >> (16 * lo)) & 0xFFFF) | (((b >> (16 * hi)) & 0xFFFF) << 16) + want = sum(s8((a >> (8 * i)) & 0xFF) * s8((halves >> (8 * i)) & 0xFF) for i in range(4)) & 0xFFFFFFFF + lines = (f"\tv_mov_b32 v1, 0x{a:08x}\n\tv_mov_b32 v2, 0x{b:08x}\n\tv_mov_b32 v3, 0\n" + f"\tv_dot4_i32_i8 v8, v1, v2, v3 op_sel:[0,{lo},0] op_sel_hi:[1,{hi},1]\n" + "\texp mrt0 v8, v8, v8, v8 done vm\n\ts_endpgm\n") + for fallback in (False, True): + with self.subTest(lo=lo, hi=hi, fallback=fallback): + text = translate_text("ps_dot4_halves", lines.encode(), fallback) + self.assertEqual(mrt0_words(text), [want] * 4) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_r4_smem_img_opt.py b/tests/semantic/test_r4_smem_img_opt.py new file mode 100644 index 0000000000..4382976d55 --- /dev/null +++ b/tests/semantic/test_r4_smem_img_opt.py @@ -0,0 +1,663 @@ +"""Round 4 Translator items 4T.3A + 4T.3B tests: + * 4T.3A: Sound improvements to `analyse_scalar_load_ro`: + - Forward CFG store-reachability (`not store_reached`), including loop back-edge soundness. + - Explicit same-origin WAR protection (load before store to the same known origin stays mutable). + - Generalized descriptor-only `s_load_dword*` provenance: 64-bit user SGPR table pointers `(in(k), in(k+1))`, + 2-level descriptor table loads (`s_load` -> `s_load` -> T#/S#/V#), and descriptors/V#s carried across + scalar-spill VGPR lanes (`v_writelane_b32` / `v_readlane_b32`). + - Branch-merge widening of static table slots to `("load_dyn", base)` without poisoning disjoint CBVs. + - Negative controls: loop back-edge stores, 64-bit RW buffer data `s_load`, 2-level data `s_load`, + spilled VGPR read as non-spill data or dynamic lane, and descriptor chain from a written root. + * 4T.3B: Sound improvements to `float_only_image_ops`: + - Complete f32 / f16 pure-float consumer coverage (`v_fmaak_f32`, `v_fmamk_f32`, `v_min3_f32`, `v_max3_f32`, + `v_fma_legacy_f32`, `v_cubema_f32`, `v_div_fixup_f32`, `v_ldexp_f32`/`f16` src0, `v_fma_mix*` op_sel_hi, + `v_mov_b32`/`v_cndmask_b32` VOP3 float `neg`/`abs`, `v_pk_fma_f16`, `v_cvt_pknorm_u16_f16`, etc.). + - Transitive pure register-copy / select / pack propagation (`v_mov_b32`, `v_cndmask_b32`, `v_pack_b32_f16`) + requiring all transitive consumers to be float-only. + - Per-path EXEC-superset kill tracking (allows safe register-reuse kills in shaders that modify EXEC, + while preserving soundness when EXEC narrows after `image_load` or switches via `s_xor`). + - Full 32-bit packed overwrite kills (`v_cvt_pkrtz_f16_f32`). + - Comprehensive negative controls for every soundness boundary. +""" +import os +import shutil +import struct +import subprocess +import sys +import tempfile +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(os.path.dirname(HERE)) +TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") +sys.dont_write_bytecode = True +if TOOLS_DIR not in sys.path: + sys.path.insert(0, TOOLS_DIR) +if HERE not in sys.path: + sys.path.insert(0, HERE) + +import rdna2spirv # noqa: E402 +from shader_ir import parse_line # noqa: E402 +import support # noqa: E402 +import test_value_semantics as tv # noqa: E402 + +FSSM_12 = tv._fssm(12 << 1, (64, 1, 1)) + + +def _validate(spv): + if not (shutil.which("spirv-as") and shutil.which("spirv-val")): + return + with tempfile.TemporaryDirectory() as tmp: + asm, out = os.path.join(tmp, "m.spvasm"), os.path.join(tmp, "m.spv") + with open(asm, "w", encoding="utf-8", newline="\n") as f: + f.write(spv) + r1 = subprocess.run(["spirv-as", "--target-env", "vulkan1.2", asm, "-o", out], + capture_output=True, text=True) + assert r1.returncode == 0, r1.stderr + r2 = subprocess.run(["spirv-val", "--target-env", "vulkan1.2", out], + capture_output=True, text=True) + assert r2.returncode == 0, r2.stderr + + +def _cs_fssm(): + hdr = bytearray(0x148) + struct.pack_into("<4I", hdr, 0x138, 0x8088, 64, 1, 1) + return bytes(hdr) + + +class ScalarLoadRoR4Tests(unittest.TestCase): + def test_pre_store_disjoint_load_nonwritable_and_war_unknown_store_or_origin_stays_mutable(self): + # Positive (CFG path-sensitive): Block 0 branches to Block 1 (disjoint CBV s[4:7] load -> buffer_store s[0:3]) + # and Block 2 (unknown global_store ... off -> endpgm). Block 1's load has `not store_reached` and its only + # reachable following write is disjoint known s[0:3] -> gets NonWritable even though global_store exists in Block 2! + b0 = [parse_line("s_cmp_eq_u32 s10, 0")] + b1 = [ + parse_line("s_buffer_load_dwordx4 s[16:19], s[4:7], 0x0"), + parse_line("buffer_store_dword v0, v1, s[0:3], 0 offen"), + parse_line("s_endpgm"), + ] + b2 = [ + parse_line("global_store_dword v[0:1], v2, off"), + parse_line("s_endpgm"), + ] + ro_cfg = rdna2spirv.analyse_scalar_load_ro([b0, b1, b2], [[1, 2], [], []], user_limit=12) + self.assertIn(id(b1[0]), ro_cfg) + + # Negative control A1 (WAR hazard with later unknown store): s_load from s[0:1] before global_store ... off + # could alias v[0:1]; NonWritable would allow ACO to sink the load past the store -> MUST stay mutable! + lines_a1 = [ + "s_load_dwordx4 s[16:19], s[0:1], 0x0", + "s_waitcnt lgkmcnt(0)", + "global_store_dword v[0:1], v2, off", + "s_waitcnt vmcnt(0)", + "v_add_nc_u32_e32 v3, 1, s16", + "s_endpgm", + ] + spv_a1 = support.translate_lines("cs_r4_war_unknown_store", lines_a1, fssm=FSSM_12) + _validate(spv_a1) + self.assertIn("%sl_rw_blk4 = OpTypeStruct %v4uint_sl", spv_a1) + self.assertNotIn("%sl_blk4", spv_a1) + + # Negative control A2 (WAR hazard with unknown-origin load before known store): v_readfirstlane pointer has + # origin None and could alias s[0:3] -> MUST stay mutable! + lines_a2 = [ + "v_readfirstlane_b32 s10, v0", + "v_readfirstlane_b32 s11, v1", + "s_load_dwordx4 s[16:19], s[10:11], 0x0", + "s_waitcnt lgkmcnt(0)", + "buffer_store_dword v2, v3, s[0:3], 0 offen", + "s_waitcnt vmcnt(0)", + "v_add_nc_u32_e32 v4, 1, s16", + "s_endpgm", + ] + spv_a2 = support.translate_lines("cs_r4_war_unknown_load", lines_a2, fssm=FSSM_12) + _validate(spv_a2) + self.assertIn("%sl_rw_blk4 = OpTypeStruct %v4uint_sl", spv_a2) + self.assertNotIn("%sl_blk4", spv_a2) + + def test_pre_store_same_origin_war_stays_mutable(self): + # Negative control (WAR safety): reading from s[0:3] before writing to the same known s[0:3] keeps + # mutable loads so the driver cannot sink a NonWritable load past the store. + lines = [ + "s_buffer_load_dwordx4 s[16:19], s[0:3], 0x0", + "s_waitcnt lgkmcnt(0)", + "buffer_store_dword v0, v1, s[0:3], 0 offen", + "s_waitcnt vmcnt(0)", + "v_mov_b32 v2, s16", + "s_endpgm", + ] + spv = support.translate_lines("cs_r4_war_same_origin", lines, fssm=FSSM_12) + _validate(spv) + self.assertIn("%sl_rw_blk4 = OpTypeStruct %v4uint_sl", spv) + self.assertNotIn("%sl_blk4", spv) + + def test_loop_backedge_store_reaches_earlier_load_in_loop(self): + # Negative control (CFG loop back-edge): a load in a loop header before a store in the loop body IS + # reached by the store via the back-edge (`store_reached = True`), while a load on a disjoint write-free + # exit path is RO. + b0 = [parse_line("s_cmp_eq_u32 s10, 0")] + b1 = [parse_line("s_buffer_load_dwordx4 s[16:19], s[8:11], 0x0")] + b2 = [parse_line("global_store_dword v[0:1], v2, off")] + b3 = [parse_line("s_endpgm")] + b4 = [ + parse_line("s_buffer_load_dwordx4 s[12:15], s[4:7], 0x0"), + parse_line("s_endpgm"), + ] + ro = rdna2spirv.analyse_scalar_load_ro([b0, b1, b2, b3, b4], [[1, 4], [2, 3], [1], [], []], user_limit=12) + self.assertIn(id(b4[0]), ro) + self.assertNotIn(id(b1[0]), ro) + + # Single-block self-loop: load before store in same block with self back-edge must also stay mutable. + loop_blk = [ + parse_line("s_buffer_load_dwordx4 s[16:19], s[8:11], 0x0"), + parse_line("global_store_dword v[0:1], v2, off"), + ] + ro_self = rdna2spirv.analyse_scalar_load_ro([loop_blk, b3], [[0, 1], []], user_limit=12) + self.assertNotIn(id(loop_blk[0]), ro_self) + + def test_pointer_arith_offset_table_load_does_not_forge_static_slot(self): + # Negative control (P0): adding +0x20 to table base s2 before loading V# s[16:19] at imm 0x0 hits the + # SAME slot as s[12:15] loaded from s[2:3]+0x20 -> must widen to load_dyn so s_buffer_load stays mutable! + lines = [ + "s_load_dwordx4 s[12:15], s[2:3], 0x20", + "s_add_u32 s4, s2, 0x20", + "s_addc_u32 s5, s3, 0", + "s_load_dwordx4 s[16:19], s[4:5], 0x0", + "s_waitcnt lgkmcnt(0)", + "buffer_store_dword v0, v1, s[16:19], 0 offen", + "s_waitcnt vmcnt(0)", + "s_buffer_load_dwordx4 s[20:23], s[12:15], 0x0", + "s_waitcnt lgkmcnt(0)", + "v_mov_b32 v2, s20", + "s_endpgm", + ] + insns = [parse_line(ln) for ln in lines] + ro = rdna2spirv.analyse_scalar_load_ro([insns], [[]], user_limit=12) + self.assertNotIn(id(insns[7]), ro) + + def test_special_reg_copy_vlist_spill_overwrite_and_2arg_vcmp_vcc_clobber(self): + # Negative control B1: s_mov_b32 m0 / s_cselect_b32 exec_lo consumes s12 as data -> must drop NonWritable! + for extra in ("s_mov_b32 m0, s12", "s_cselect_b32 exec_lo, s12, s13"): + with self.subTest(case="special_copy", op=extra): + insns = [ + parse_line("global_store_dword v[0:1], v2, off"), + parse_line("s_load_dwordx4 s[12:15], s[2:3], 0x0"), + parse_line("buffer_load_dword v3, v0, s[12:15], 0 offen"), + parse_line(extra), + parse_line("s_endpgm"), + ] + self.assertNotIn(id(insns[1]), rdna2spirv.analyse_scalar_load_ro([insns], [[]], user_limit=12)) + + # Negative control B2: vlist overwrite of spill VGPR v40 clears its spill provenance -> write origin becomes None! + insns_b2 = [ + parse_line("s_load_dwordx4 s[12:15], s[2:3], 0x0"), + parse_line("v_writelane_b32 v40, s12, 0"), + parse_line("global_load_dwordx2 [v40,v41], v[0:1], off"), + parse_line("v_readlane_b32 s20, v40, 0"), + parse_line("buffer_store_dword v2, v3, s[20:23], 0 offen"), + parse_line("s_buffer_load_dwordx4 s[24:27], s[4:7], 0x0"), + parse_line("s_endpgm"), + ] + self.assertNotIn(id(insns_b2[5]), rdna2spirv.analyse_scalar_load_ro([insns_b2], [[]], user_limit=12)) + + # Negative control VCC: 2-arg v_cmp_lt_u32_e32 v0, v1 clobbers implicit vcc -> s_load via vcc stays mutable! + insns_vcc = [ + parse_line("s_load_dwordx2 vcc, s[2:3], 0x0"), + parse_line("v_cmp_lt_u32_e32 v0, v1"), + parse_line("buffer_store_dword v2, v3, s[0:3], 0 offen"), + parse_line("s_load_dwordx4 s[16:19], vcc, 0x0"), + parse_line("v_mov_b32 v4, s16"), + parse_line("s_endpgm"), + ] + self.assertNotIn(id(insns_vcc[3]), rdna2spirv.analyse_scalar_load_ro([insns_vcc], [[]], user_limit=12)) + + def test_64bit_and_2level_descriptor_table_loads_stay_nonwritable(self): + # 64-bit user SGPR table pointer s[2:3] -> L1 loads sub-table pointer s[10:11] -> L2 loads V# s[16:19] + # consumed solely by buffer_load_dword, even AFTER an unknown global_store! + lines = [ + "global_store_dword v[0:1], v2, off", + "s_waitcnt vmcnt(0)", + "s_load_dwordx2 s[10:11], s[2:3], 0x10", + "s_waitcnt lgkmcnt(0)", + "s_load_dwordx4 s[16:19], s[10:11], 0x20", + "s_waitcnt lgkmcnt(0)", + "buffer_load_dword v3, v0, s[16:19], 0 offen", + "s_endpgm", + ] + spv = support.translate_lines("cs_r4_2level_desc", lines, fssm=FSSM_12) + _validate(spv) + self.assertIn("OpMemberDecorate %sl_blk2 0 NonWritable", spv) + self.assertIn("OpMemberDecorate %sl_blk4 0 NonWritable", spv) + self.assertNotIn("%sl_rw_blk", spv) + + def test_spilled_descriptors_and_write_vsharp_provenance_survive_writelane_readlane(self): + # Realistic heavy compute shader pattern: + # - 64-bit descriptor table s[2:3] loads CBV V# (+0x0) and UAV V# (+0x20). + # - UAV V# s[48:51] is spilled to v40 lanes 0..3 via v_writelane_b32 and reloaded via v_readlane_b32. + # - buffer_store_format_xyzw writes through s[48:51]; provenance stays ("load", ("in", 2), 0x20), NOT None! + # - Subsequent s_buffer_load through CBV s[12:15] (+0x0) stays NonWritable! + lines = [ + "s_load_dwordx4 s[12:15], s[2:3], 0x0", + "s_load_dwordx4 s[48:51], s[2:3], 0x20", + "s_waitcnt lgkmcnt(0)", + "v_writelane_b32 v40, s48, 0", + "v_writelane_b32 v40, s49, 1", + "v_writelane_b32 v40, s50, 2", + "v_writelane_b32 v40, s51, 3", + "v_readlane_b32 s48, v40, 0", + "v_readlane_b32 s49, v40, 1", + "v_readlane_b32 s50, v40, 2", + "v_readlane_b32 s51, v40, 3", + "buffer_store_format_xyzw v[0:3], v4, s[48:51], 0 idxen", + "s_waitcnt vmcnt(0)", + "s_buffer_load_dwordx4 s[20:23], s[12:15], 0x0", + "s_waitcnt lgkmcnt(0)", + "v_mov_b32 v5, s20", + "s_endpgm", + ] + spv = support.translate_lines("cs_r4_spill_vsharp", lines, fssm=FSSM_12) + _validate(spv) + self.assertIn("OpMemberDecorate %sl_blk4 0 NonWritable", spv) + self.assertNotIn("%sl_rw_blk", spv) + + def test_64bit_rw_data_sload_and_2level_data_and_nonspill_vgpr_stay_mutable(self): + # 1. 64-bit RW buffer data s_load after store MUST stay mutable. + for store_line in ( + "global_store_dword v0, v1, s[0:1]", + "global_store_dword v[0:1], v2, off", + ): + with self.subTest(case="rw64_data", store=store_line): + lines = [ + store_line, + "s_waitcnt vmcnt(0)", + "s_load_dwordx4 s[4:7], s[0:1], 0x0", + "s_waitcnt lgkmcnt(0)", + "v_mov_b32 v3, s4", + "s_endpgm", + ] + spv = support.translate_lines("cs_r4_rw64_data", lines, fssm=FSSM_12) + _validate(spv) + self.assertIn("%sl_rw_blk4 = OpTypeStruct %v4uint_sl", spv) + self.assertNotIn("%sl_blk4", spv) + + # 2. 2-level load where L2 is consumed as data -> NEITHER L1 nor L2 may be NonWritable. + lines_2lvl_data = [ + "global_store_dword v[0:1], v2, off", + "s_waitcnt vmcnt(0)", + "s_load_dwordx2 s[10:11], s[2:3], 0x10", + "s_waitcnt lgkmcnt(0)", + "s_load_dwordx4 s[16:19], s[10:11], 0x20", + "s_waitcnt lgkmcnt(0)", + "v_mov_b32 v3, s16", + "s_endpgm", + ] + spv2 = support.translate_lines("cs_r4_2lvl_data", lines_2lvl_data, fssm=FSSM_12) + _validate(spv2) + self.assertIn("%sl_rw_blk2 = OpTypeStruct %v2uint_sl", spv2) + self.assertIn("%sl_rw_blk4 = OpTypeStruct %v4uint_sl", spv2) + self.assertNotIn("%sl_blk2", spv2) + self.assertNotIn("%sl_blk4", spv2) + + # 3. Spilled descriptor VGPR read directly by VALU (not pure spill) -> MUST stay mutable. + lines_bad_spill = [ + "global_store_dword v[0:1], v2, off", + "s_waitcnt vmcnt(0)", + "s_load_dwordx4 s[12:15], s[2:3], 0x0", + "s_waitcnt lgkmcnt(0)", + "v_writelane_b32 v40, s12, 0", + "v_add_nc_u32_e32 v1, 1, v40", + "v_readlane_b32 s12, v40, 0", + "buffer_load_dword v3, v0, s[12:15], 0 offen", + "s_endpgm", + ] + insns_bs = [parse_line(ln) for ln in lines_bad_spill] + self.assertEqual(rdna2spirv.analyse_scalar_load_ro([insns_bs], [[]], user_limit=12), frozenset()) + + # 4. 2-level descriptor load whose root table s[0:1] is explicitly written -> NEITHER may be NonWritable. + lines_written_root = [ + "global_store_dword v0, v1, s[0:1]", + "s_waitcnt vmcnt(0)", + "s_load_dwordx2 s[10:11], s[0:1], 0x10", + "s_waitcnt lgkmcnt(0)", + "s_load_dwordx4 s[16:19], s[10:11], 0x20", + "s_waitcnt lgkmcnt(0)", + "buffer_load_dword v3, v0, s[16:19], 0 offen", + "s_endpgm", + ] + insns_wr = [parse_line(ln) for ln in lines_written_root] + self.assertEqual(rdna2spirv.analyse_scalar_load_ro([insns_wr], [[]], user_limit=12), frozenset()) + + def test_branch_merge_table_slots_widens_without_poisoning_disjoint_cbv(self): + # Merging V#s from +0x20 and +0x40 of table s[2:3] widens the write origin to ("load_dyn", ("in", 2)): + # - A disjoint CBV s[4:7] AFTER the store still gets NonWritable. + # - A static slot (+0x0) from the SAME table s[2:3] AFTER the store MUST stay mutable (may alias load_dyn). + b0 = [ + parse_line("s_load_dwordx4 s[12:15], s[2:3], 0x0"), + ] + b1 = [parse_line("s_load_dwordx4 s[48:51], s[2:3], 0x20")] + b2 = [parse_line("s_load_dwordx4 s[48:51], s[2:3], 0x40")] + b3 = [ + parse_line("buffer_store_dword v0, v1, s[48:51], 0 offen"), + parse_line("s_buffer_load_dwordx4 s[20:23], s[4:7], 0x0"), + parse_line("s_buffer_load_dwordx4 s[24:27], s[12:15], 0x0"), + parse_line("s_endpgm"), + ] + ro = rdna2spirv.analyse_scalar_load_ro([b0, b1, b2, b3], [[1, 2], [3], [3], []], user_limit=12) + self.assertIn(id(b0[0]), ro) # descriptor load + self.assertIn(id(b1[0]), ro) # descriptor load + self.assertIn(id(b2[0]), ro) # descriptor load + self.assertIn(id(b3[1]), ro) # disjoint CBV s[4:7] + self.assertNotIn(id(b3[2]), ro) # same table s[2:3] (+0x0) may alias load_dyn(s[2:3])! + + +class FloatOnlyImageOpsR4Tests(unittest.TestCase): + def _assert_elided(self, name, lines, *, fssm=None): + asm = support.translate_lines(name, lines, fssm=fssm) + self.assertNotIn("%itx1_0", asm, f"{name} should elide %itx1_0") + self.assertNotIn("%itx2_0", asm, f"{name} should elide %itx2_0") + self.assertEqual(asm.count("OpImageFetch "), 1, f"{name} should emit 1 OpImageFetch") + _validate(asm) + + def _assert_not_elided(self, name, lines, *, fssm=None): + asm = support.translate_lines(name, lines, fssm=fssm) + self.assertIn("%itx1_0", asm, f"{name} MUST keep %itx1_0") + self.assertIn("%itx2_0", asm, f"{name} MUST keep %itx2_0") + self.assertEqual(asm.count("OpImageFetch "), 3, f"{name} MUST keep all 3 OpImageFetch branches") + + def test_new_f32_and_f16_pure_float_consumers_elide(self): + f32_cases = [ + ("fmaak_f32", ["v_fmaak_f32 v0, v0, 0x3f000000, 0x3f800000"]), + ("fmamk_f32", ["v_fmamk_f32 v0, v0, 0x3f000000, v2"]), + ("min3_f32", ["v_min3_f32 v0, v0, v2, 1.0"]), + ("max3_f32", ["v_max3_f32 v0, v0, v2, 0.0"]), + ("mac_legacy_f32", ["v_mac_legacy_f32_e32 v0, 0x3f800000, v2"]), + ("cubema_f32", ["v_cubema_f32 v0, v0, v2, v3"]), + ("div_fixup_f32", ["v_div_fixup_f32 v0, v0, v2, 1.0"]), + ("ldexp_f32_src0", ["v_ldexp_f32 v0, v0, 2"]), + ("fma_mix_f32_s0_f32", ["v_fma_mix_f32 v0, v0, 1.0, 0.0 op_sel_hi:[0,0,0]"]), + ("mov_neg_f32", ["v_mov_b32_e64 v0, -v0"]), + ("mov_abs_f32", ["v_mov_b32_e64 v0, |v0|"]), + ("cndmask_neg_f32", ["v_cndmask_b32_e64 v0, -v0, v2, vcc"]), + ] + for label, consumer in f32_cases: + with self.subTest(case=label): + lines = [ + "v_mov_b32 v4, 1", + "v_mov_b32 v5, 2", + "v_mov_b32 v2, 0x3f800000", + "v_mov_b32 v3, 0x40000000", + "image_load v0, v[4:5], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm", + "s_waitcnt vmcnt(0)", + *consumer, + "exp mrt0 v0, v0, v0, v0 done vm", + "s_endpgm", + ] + self._assert_elided(f"ps_r4_{label}", lines) + + f16_cases = [ + ("pk_fma_f16", ["v_pk_fma_f16 v0, v0, v2, v3"]), + ("min3_f16", ["v_min3_f16 v1, v0, v2, v3"]), + ("max3_f16", ["v_max3_f16 v1, v0, v2, v3"]), + ("cvt_pknorm_u16_f16", ["v_cvt_pknorm_u16_f16 v0, v0, v2"]), + ("fma_mix_f16_src", ["v_fma_mix_f32 v0, v0, 1.0, 0.0 op_sel_hi:[1,0,0]"]), + ("pack_b32_f16_neg", ["v_pack_b32_f16 v0, -v0, v2"]), + ] + for label, consumer in f16_cases: + with self.subTest(case=label): + lines = [ + "v_mov_b32 v4, 1", + "v_mov_b32 v5, 2", + "v_mov_b32 v2, 0x3c003c00", + "v_mov_b32 v3, 0x3c003c00", + "image_load v0, v[4:5], s[0:7] dmask:0x3 dim:SQ_RSRC_IMG_2D unorm d16", + "s_waitcnt vmcnt(0)", + *consumer, + "exp mrt0 v1, v1, v1, v1 done vm", + "s_endpgm", + ] + self._assert_elided(f"ps_r4_d16_{label}", lines) + + def test_transitive_copy_select_pack_and_cvt_pk_elide_when_float_only(self): + # 1. v_mov_b32 chain -> v_fmac_f32 elides. + self._assert_elided("ps_r4_copy_fmac", [ + "v_mov_b32 v4, 1", + "v_mov_b32 v5, 2", + "v_mov_b32 v3, 0x3f800000", + "image_load v0, v[4:5], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm", + "s_waitcnt vmcnt(0)", + "v_mov_b32 v1, v0", + "v_mov_b32 v2, v1", + "v_fmac_f32_e32 v3, 0x40000000, v2", + "exp mrt0 v3, v3, v3, v3 done vm", + "s_endpgm", + ]) + + # 2. v_cndmask_b32 -> v_mul_f32 elides. + self._assert_elided("ps_r4_cndmask_mul", [ + "v_mov_b32 v4, 1", + "v_mov_b32 v5, 2", + "v_mov_b32 v6, 0x3f800000", + "image_load v0, v[4:5], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm", + "s_waitcnt vmcnt(0)", + "v_cndmask_b32_e32 v1, v0, v6, vcc", + "v_mul_f32_e32 v2, 0x40000000, v1", + "exp mrt0 v2, v2, v2, v2 done vm", + "s_endpgm", + ]) + + # 3. d16 image_load -> plain v_pack_b32_f16 -> v_pk_fma_f16 elides. + self._assert_elided("ps_r4_d16_pack_pkfma", [ + "v_mov_b32 v4, 1", + "v_mov_b32 v5, 2", + "v_mov_b32 v6, 0x3c003c00", + "image_load v0, v[4:5], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm d16", + "s_waitcnt vmcnt(0)", + "v_pack_b32_f16 v1, v0, v6", + "v_pk_fma_f16 v2, v1, v6, v6", + "exp mrt0 v2, v2, v2, v2 done vm", + "s_endpgm", + ]) + + # 4. v_cvt_pkrtz_f16_f32 overwrites all 32 bits of v0 after consuming v0/v1 as f32 -> buffer_store v0 ok! + self._assert_elided("cs_r4_cvt_pkrtz_store", [ + "v_mov_b32 v4, 1", + "v_mov_b32 v5, 2", + "image_load v[0:1], v[4:5], s[0:7] dmask:0x3 dim:SQ_RSRC_IMG_2D unorm", + "s_waitcnt vmcnt(0)", + "v_cvt_pkrtz_f16_f32 v0, v0, v1", + "buffer_store_dword v0, v4, s[8:11], 0 offen", + "s_endpgm", + ], fssm=_cs_fssm()) + + def test_transitive_copy_select_and_partial_consumer_negative_controls(self): + # 1. v_mov_b32 -> v_add_nc_u32 MUST NOT elide. + self._assert_not_elided("ps_r4_neg_mov_int", [ + "v_mov_b32 v4, 1", + "v_mov_b32 v5, 2", + "image_load v0, v[4:5], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm", + "s_waitcnt vmcnt(0)", + "v_mov_b32 v1, v0", + "v_add_nc_u32_e32 v2, 1, v1", + "exp mrt0 v2, v2, v2, v2 done vm", + "s_endpgm", + ]) + + # 2. v_cndmask_b32 -> buffer_store_dword MUST NOT elide. + self._assert_not_elided("cs_r4_neg_cndmask_store", [ + "v_mov_b32 v4, 1", + "v_mov_b32 v5, 2", + "v_mov_b32 v6, 0", + "image_load v0, v[4:5], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm", + "s_waitcnt vmcnt(0)", + "v_cndmask_b32_e32 v1, v0, v6, vcc", + "buffer_store_dword v1, v4, s[8:11], 0 offen", + "s_endpgm", + ], fssm=_cs_fssm()) + + # 3. v_mov_b32 -> exp (or exit without any float consumer) MUST NOT elide. + self._assert_not_elided("ps_r4_neg_mov_exp", [ + "v_mov_b32 v4, 1", + "v_mov_b32 v5, 2", + "image_load v0, v[4:5], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm", + "s_waitcnt vmcnt(0)", + "v_mov_b32 v1, v0", + "exp mrt0 v1, v1, v1, v1 done vm", + "s_endpgm", + ]) + self._assert_not_elided("cs_r4_neg_mov_exit", [ + "v_mov_b32 v4, 1", + "v_mov_b32 v5, 2", + "image_load v0, v[4:5], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm", + "s_waitcnt vmcnt(0)", + "v_mov_b32 v1, v0", + "s_endpgm", + ], fssm=_cs_fssm()) + + # 4. d16 image_load -> plain v_pack_b32_f16 -> buffer_store_dword MUST NOT elide. + self._assert_not_elided("cs_r4_neg_d16_pack_store", [ + "v_mov_b32 v4, 1", + "v_mov_b32 v5, 2", + "v_mov_b32 v6, 0", + "image_load v0, v[4:5], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm d16", + "s_waitcnt vmcnt(0)", + "v_pack_b32_f16 v1, v0, v6", + "buffer_store_dword v1, v4, s[8:11], 0 offen", + "s_endpgm", + ], fssm=_cs_fssm()) + + # 5. d16 image_load -> v_add_f16 + v_lshrrev_b32 MUST NOT elide (upper 16 bits preserved!). + self._assert_not_elided("ps_r4_neg_d16_partial_shr", [ + "v_mov_b32 v4, 1", + "v_mov_b32 v5, 2", + "image_load v0, v[4:5], s[0:7] dmask:0x3 dim:SQ_RSRC_IMG_2D unorm d16", + "s_waitcnt vmcnt(0)", + "v_add_f16_e32 v0, 0x3c00, v0", + "v_lshrrev_b32_e32 v1, 16, v0", + "exp mrt0 v0, v1, v0, v1 done vm", + "s_endpgm", + ]) + + # 6. v_ldexp_f32 integer exponent operand (src1) MUST NOT count as float consumer. + self._assert_not_elided("ps_r4_neg_ldexp_exp", [ + "v_mov_b32 v4, 1", + "v_mov_b32 v5, 2", + "v_mov_b32 v2, 0x3f800000", + "image_load v0, v[4:5], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm", + "s_waitcnt vmcnt(0)", + "v_ldexp_f32 v1, v2, v0", + "exp mrt0 v1, v1, v1, v1 done vm", + "s_endpgm", + ]) + + # 7. v_cvt_pk_u8_f32 integer byte-index operand (src1) MUST NOT count as float consumer. + self._assert_not_elided("ps_r4_neg_cvt_pk_u8_idx", [ + "v_mov_b32 v4, 1", + "v_mov_b32 v5, 2", + "v_mov_b32 v2, 0x3f800000", + "v_mov_b32 v3, 0", + "image_load v0, v[4:5], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm", + "s_waitcnt vmcnt(0)", + "v_cvt_pk_u8_f32 v1, v2, v0, v3", + "exp mrt0 v1, v1, v1, v1 done vm", + "s_endpgm", + ]) + + # 8. v_fma_mix_f32 reading an f32-loaded VGPR as f16 (op_sel_hi:[1,0,0]) MUST NOT elide. + self._assert_not_elided("ps_r4_neg_fma_mix_mismatch", [ + "v_mov_b32 v4, 1", + "v_mov_b32 v5, 2", + "image_load v0, v[4:5], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm", + "s_waitcnt vmcnt(0)", + "v_fma_mix_f32 v1, v0, 1.0, 0.0 op_sel_hi:[1,0,0]", + "exp mrt0 v1, v1, v1, v1 done vm", + "s_endpgm", + ]) + + def test_exec_superset_register_reuse_positive_and_negative_controls(self): + # Positive: shader modifies EXEC before image_load and widens EXEC afterward with s_or_b32; + # v0 is consumed by v_fma_f32 and overwritten under EXEC >= E0, then reused as an integer counter. + self._assert_elided("cs_r4_exec_superset_reuse", [ + "v_cmp_lt_u32_e32 vcc_lo, v0, 64", + "s_and_saveexec_b32 s10, vcc_lo", + "v_mov_b32 v4, 1", + "v_mov_b32 v5, 2", + "image_load v0, v[4:5], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm", + "s_waitcnt vmcnt(0)", + "v_fma_f32 v0, v0, 0x40000000, 0x3f800000", + "buffer_store_dword v0, v4, s[8:11], 0 offen", + "s_or_b32 exec_lo, exec_lo, s10", + "v_mov_b32 v0, 7", + "v_add_nc_u32_e32 v0, 1, v0", + "buffer_store_dword v0, v4, s[8:11], 0 offen", + "s_endpgm", + ], fssm=_cs_fssm()) + + # Negative 1: EXEC narrows AFTER image_load -> v_mul_f32 only overwrites active lanes, leaving + # image_load's v0 live in inactive lanes -> later v_add_nc_u32 reads image_load's v0 -> MUST NOT elide! + self._assert_not_elided("cs_r4_neg_exec_narrow_after_load", [ + "v_mov_b32 v4, 1", + "v_mov_b32 v5, 2", + "image_load v0, v[4:5], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm", + "s_waitcnt vmcnt(0)", + "v_cmp_lt_u32_e32 vcc_lo, v4, 32", + "s_and_saveexec_b32 s10, vcc_lo", + "v_mul_f32_e32 v0, 0x40000000, v0", + "s_or_b32 exec_lo, exec_lo, s10", + "v_add_nc_u32_e32 v1, 1, v0", + "buffer_store_dword v1, v4, s[8:11], 0 offen", + "s_endpgm", + ], fssm=_cs_fssm()) + + # Negative 2: image_load inside `if`, s_xor_b32 switches to `else` and overwrites v0 there; + # `if` lanes STILL hold image_load's v0 after s_or_b32 merge -> v_add_nc_u32 reads it -> MUST NOT elide! + self._assert_not_elided("cs_r4_neg_exec_xor_else_overwrite", [ + "v_mov_b32 v4, 1", + "v_mov_b32 v5, 2", + "v_cmp_lt_u32_e32 vcc_lo, v4, 32", + "s_and_saveexec_b32 s10, vcc_lo", + "image_load v0, v[4:5], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm", + "s_waitcnt vmcnt(0)", + "v_mul_f32_e32 v2, 0x40000000, v0", + "s_xor_b32 exec_lo, exec_lo, s10", + "v_mov_b32 v0, 0", + "s_or_b32 exec_lo, exec_lo, s10", + "v_add_nc_u32_e32 v1, 1, v0", + "buffer_store_dword v1, v4, s[8:11], 0 offen", + "s_endpgm", + ], fssm=_cs_fssm()) + + def test_permlane16_without_fi_or_bc_preserves_dst_and_never_elides(self): + # Negative control F1: v_permlane16_b32 / v_permlanex16_b32 with FI=0 and BOUND_CTRL=0 preserves vdst in + # inactive-source lanes, so v0 still reaches v_add_nc_u32 -> MUST NOT elide! + for op in ("v_permlane16_b32", "v_permlanex16_b32"): + with self.subTest(op=op, mode="preserve"): + self._assert_not_elided(f"cs_r4_neg_{op}", [ + "v_mov_b32 v4, 1", + "v_mov_b32 v5, 2", + "v_mov_b32 v3, 0", + "image_load v0, v[4:5], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm", + "s_waitcnt vmcnt(0)", + "v_add_f32_e32 v2, 1.0, v0", + f"{op} v0, v3, s0, s1", + "v_add_nc_u32_e32 v4, 1, v0", + "buffer_store_dword v4, v5, s[8:11], 0 offen", + "s_endpgm", + ], fssm=_cs_fssm()) + + # Positive control: with op_sel:[1,0] (FI=1), v_permlane16_b32 unconditionally overwrites v0 -> elides! + self._assert_elided("cs_r4_pos_permlane16_fi1", [ + "v_mov_b32 v4, 1", + "v_mov_b32 v5, 2", + "v_mov_b32 v3, 0", + "image_load v0, v[4:5], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm", + "s_waitcnt vmcnt(0)", + "v_add_f32_e32 v2, 1.0, v0", + "v_permlane16_b32 v0, v3, s0, s1 op_sel:[1,0]", + "v_add_nc_u32_e32 v4, 1, v0", + "buffer_store_dword v4, v5, s[8:11], 0 offen", + "s_endpgm", + ], fssm=_cs_fssm()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_sampled_dynamic_index.py b/tests/semantic/test_sampled_dynamic_index.py index afc7963906..927228e332 100644 --- a/tests/semantic/test_sampled_dynamic_index.py +++ b/tests/semantic/test_sampled_dynamic_index.py @@ -62,6 +62,11 @@ def check_accesses(self, asm, sampled_bindings, storage_bindings=()): more |= {res for res, true_value, false_value in re.findall( r"(%\w+) = OpSelect %uint %\w+ (%\w+) (%\w+)", asm) if true_value in lookup_indices and false_value == "%c0"} + # These T#s come from user SGPRs, not a heap slot, so they are looked up, and the index word of their + # dword 6 wins where it carries the tag (docs/design.md, "Bindless index in the T#"): an OpPhi of the + # word and the lookup's index, which runs only without the word. + more |= {res for res, probed in re.findall( + r"(%\w+) = OpPhi %uint %\w+ %\w+ (%\w+) %\w+", asm) if probed in lookup_indices} if more <= lookup_indices: break lookup_indices |= more @@ -91,12 +96,20 @@ def check_accesses(self, asm, sampled_bindings, storage_bindings=()): def test_sample_with_literal_sampler_still_indexes_both_arrays_dynamically(self): fixture = Path(__file__).with_name("fixtures") / "sampled_dynamic_index.asm" - asm = support.translate_lines("ps_dynamic_index", fixture.read_text(encoding="utf-8").splitlines()) + lines = fixture.read_text(encoding="utf-8").splitlines() + asm = support.translate_lines("ps_dynamic_index", lines) self.check_accesses(asm, (0, 1)) self.assertIn("OpSampledImage", asm) self.assertIn("OpImageSampleExplicitLod", asm) + # Bilinear literal S# (word2 = 0x14500000) is float-only (Item 3B.6), so dead uint/sint aliases are elided. + for signedness in (1, 2): + self.assertNotIn(f"%itx{signedness}_0", asm) + # Point-filtered literal S# (word2 = 0) retains UINT/SINT aliases of binding 0, still dynamically indexed. + point_lines = [ln.replace("0x14500000", "0x0") for ln in lines] + asm_point = support.translate_lines("ps_dynamic_index_pt", point_lines) + self.check_accesses(asm_point, (0, 1)) for signedness in (1, 2): # UINT/SINT alias the same sampled binding as the float view. - self.assertRegex(asm, rf"OpAccessChain %_ptr_UC_itx{signedness}_0 %itx{signedness}_0 ") + self.assertRegex(asm_point, rf"OpAccessChain %_ptr_UC_itx{signedness}_0 %itx{signedness}_0 ") def test_fetch_and_query_paths(self): for op, dim, coords, sampler, expected_op, bindings in ( diff --git a/tests/semantic/test_scalar_mem_smem.py b/tests/semantic/test_scalar_mem_smem.py index 48c111c37b..6ba7efc267 100644 --- a/tests/semantic/test_scalar_mem_smem.py +++ b/tests/semantic/test_scalar_mem_smem.py @@ -325,25 +325,41 @@ def test_s_buffer_load_dword_emits_cffff_mask(self): self.assertTrue(g.uses_psb) def test_multi_dword_emission_counts(self): + # (line, uvec2 loads, uvec4 loads, single-dword loads). A multi-dword load is the fewest wide loads (uvec4, + # then uvec2): an s_load always, an s_buffer_load when its last dword is in range. An s_buffer_load whose + # bound is known only at run time keeps the per-dword path for a load that is partly out of range. cases = [ - ("s_load_dword s0, s[2:3], 0", 1), - ("s_load_dwordx2 s[0:1], s[2:3], 0", 2), - ("s_load_dwordx4 s[0:3], s[4:5], 0", 4), - ("s_load_dwordx8 s[0:7], s[8:9], 0", 8), - ("s_load_dwordx16 s[0:15], s[16:17], 0", 16), - ("s_buffer_load_dword s0, s[4:7], 0", 1), - ("s_buffer_load_dwordx4 s[0:3], s[8:11], 0", 4), - ("s_buffer_load_dwordx8 s[0:7], s[8:11], 0", 8), + ("s_load_dword s0, s[2:3], 0", 0, 0, 1), + ("s_load_dwordx2 s[0:1], s[2:3], 0", 1, 0, 0), + ("s_load_dwordx4 s[0:3], s[4:5], 0", 0, 1, 0), + ("s_load_dwordx8 s[0:7], s[8:9], 0", 0, 2, 0), + ("s_load_dwordx16 s[0:15], s[16:17], 0", 0, 4, 0), + ("s_buffer_load_dword s0, s[4:7], 0", 0, 0, 1), + ("s_buffer_load_dwordx2 s[0:1], s[8:11], 0", 1, 0, 2), + ("s_buffer_load_dwordx4 s[0:3], s[8:11], 0", 0, 1, 4), + ("s_buffer_load_dwordx8 s[0:7], s[8:11], 0", 0, 2, 8), + ("s_buffer_load_dwordx16 s[0:15], s[16:19], 0", 0, 4, 16), ] - for line, expected_n in cases: + for line, v2, v4, single in cases: with self.subTest(line=line): g = rdna2spirv.Gen("ps") ins = parse_line(line) g.scalar_load(ins["op"], ins["args"], ins["mods"]) - psb_chains = [ln for ln in g.body if "OpAccessChain %_ptr_PSB_uint" in ln] - psb_loads = [ln for ln in g.body if "OpLoad %uint" in ln and "Aligned 4" in ln] - self.assertEqual(len(psb_chains), expected_n) - self.assertEqual(len(psb_loads), expected_n) + if line.startswith("s_buffer_load_dwordx"): + n = int(line.split("x", 1)[1].split()[0]) + self.assertIn(f"OpFunctionCall %arr_sbuf_x{n} %sbuf_slow_ro_x{n}", "\n".join(g.body)) + self.assertEqual(sum("OpAccessChain %_ptr_PSB_uint" in ln for ln in g.body), 0) + slow_lines = g.sbuf_slow_fns[(n, True)] + self.assertTrue(any("OpLoopMerge" in ln and "DontUnroll" in ln for ln in slow_lines)) + self.assertEqual(sum("OpAccessChain %_ptr_PSB_uint" in ln for ln in slow_lines), 1) + self.assertEqual(sum("OpLoad %uint" in ln and "Aligned 4" in ln for ln in slow_lines), 1) + else: + psb_chains = [ln for ln in g.body if "OpAccessChain %_ptr_PSB_uint" in ln] + psb_loads = [ln for ln in g.body if "OpLoad %uint" in ln and "Aligned 4" in ln] + self.assertEqual(len(psb_chains), single) + self.assertEqual(len(psb_loads), single) + self.assertEqual(sum("OpLoad %v2uint_sl" in ln for ln in g.body), v2) + self.assertEqual(sum("OpLoad %v4uint_sl" in ln for ln in g.body), v4) def test_special_destinations_emission(self): for line in ("s_buffer_load_dword vcc_lo, s[0:3], 0", @@ -390,20 +406,31 @@ class SmemBodyEvaluator: def __init__(self, gen, sgpr, memory, heap_base=0): self.consts = {name: value for value, name in gen.consts.items()} self.consts.update({name: value for value, name in gen.lconsts.items()}) + self.slow_fns = {} + for (n, ro), flines in gen.sbuf_slow_fns.items(): + self.consts[f"%null_sbuf_x{n}"] = [0] * n + tag = "ro" if ro else "rw" + self.slow_fns[f"%sbuf_slow_{tag}_x{n}"] = [ln.split() for ln in flines] self.sgpr = dict(sgpr) self.memory = memory self.heap_base = heap_base self.ids = {} self.reads = [] # byte address of every PhysicalStorageBuffer dword load, in order - lines = [line.split() for line in gen.body] + self._exec([line.split() for line in gen.body], "%entry") + + def _exec(self, lines, start_block): labels = {w[0]: i for i, w in enumerate(lines) if len(w) == 3 and w[1:] == ["=", "OpLabel"]} - self.block, self.came_from = "%entry", None + self.block, self.came_from = start_block, None pc = 0 + back_edges = 0 while pc < len(lines): words = lines[pc] - if words[0] == "OpSelectionMerge": + if words[0] in ("OpSelectionMerge", "OpLoopMerge", "OpFunctionEnd") or ( + len(words) >= 3 and words[2] in ("OpFunction", "OpFunctionParameter")): pc += 1 continue + if words[0] == "OpReturnValue": + return self._value(words[1]) target = None if words[0] == "OpBranch": target = words[1] @@ -413,18 +440,24 @@ def __init__(self, gen, sgpr, memory, heap_base=0): raise AssertionError("OpBranchConditional on a non-bool") target = words[2] if cond else words[3] if target is not None: - if labels.get(target, -1) <= pc: - raise AssertionError("branch backwards or to an unknown label: " + " ".join(words)) + if target not in labels: + raise AssertionError("branch to an unknown label: " + " ".join(words)) + if labels[target] <= pc: + back_edges += 1 + if back_edges > 1024: + raise AssertionError("loop iteration limit exceeded: " + " ".join(words)) self.came_from, pc = self.block, labels[target] continue if len(words) == 3 and words[1:] == ["=", "OpLabel"]: - if self.block != words[0] and pc > 0 and lines[pc - 1][0] not in ("OpBranch", "OpBranchConditional"): + if self.block != words[0] and pc > 0 and lines[pc - 1][0] not in ("OpBranch", "OpBranchConditional") and not ( + len(lines[pc - 1]) >= 3 and lines[pc - 1][2] in ("OpFunction", "OpFunctionParameter")): raise AssertionError("fall-through into " + words[0]) self.block = words[0] pc += 1 continue self._step(words) pc += 1 + return None def _value(self, name): if name == "%heap_base": # built once in the entry block, outside the body run here @@ -441,21 +474,40 @@ def _value(self, name): def _step(self, words): if words[0] == "OpStore": - kind, index = self._value(words[1]) - if kind != "sgpr": - raise AssertionError(f"store through {kind}") - self.sgpr[index] = self._value(words[2]) + target = self._value(words[1]) + if target[0] == "sgpr": + self.sgpr[target[1]] = self._value(words[2]) + elif target[0] == "arr_elem": + target[1][target[2]] = self._value(words[2]) + else: + raise AssertionError(f"store through {target[0]}") return if len(words) < 4 or words[1] != "=": raise AssertionError("unmodelled line: " + " ".join(words)) result, op, ty, args = words[0], words[2], words[3], words[4:] - if op == "OpAccessChain" and ty == "%_ptr_Function_uint" and args[0] == "%sgpr": + if op == "OpVariable" and ty.startswith("%_ptr_Function_arr_sbuf_x") and args[0] == "Function": + init = list(self._value(args[1])) + value = ("arr_var", init) + elif op == "OpAccessChain" and ty == "%_ptr_Function_uint" and args[0] == "%sgpr": value = ("sgpr", self._value(args[1])) + elif op == "OpAccessChain" and ty == "%_ptr_Function_uint": + kind, arr = self._value(args[0]) + if kind != "arr_var": + raise AssertionError(f"Function access chain on {kind}") + value = ("arr_elem", arr, self._value(args[1])) elif op == "OpAccessChain" and ty == "%_ptr_PSB_uint": - kind, address = self._value(args[0]) - if kind != "psb": - raise AssertionError(f"PSB access chain on {kind}") - value = ("mem", (address + 4 * self._value(args[1])) & MASK64) + base = self._value(args[0]) + if base[0] == "psb": + value = ("mem", (base[1] + 4 * self._value(args[1])) & MASK64) + elif base[0] == "blk" and base[2] == 1 and self._value(args[1]) == 0 and len(args) == 2: + value = ("mem", base[1]) + else: + raise AssertionError(f"PSB access chain on {base}") + elif op == "OpLoad" and ty.startswith("%arr_sbuf_x"): + kind, arr = self._value(args[0]) + if kind != "arr_var": + raise AssertionError("unmodelled array load: " + " ".join(words)) + value = list(arr) elif op == "OpLoad" and ty == "%uint": kind, where = self._value(args[0]) if kind == "sgpr": @@ -465,21 +517,35 @@ def _step(self, words): value = self.memory.read_dword(where) else: raise AssertionError("unmodelled load: " + " ".join(words)) - elif op == "OpPhi" and ty == "%uint": + elif op == "OpPhi" and (ty == "%uint" or ty.startswith("%arr_sbuf_x")): pairs = dict(zip(args[1::2], args[0::2])) if len(args) % 2 or self.came_from not in pairs: raise AssertionError("OpPhi without the block it came from: " + " ".join(words)) value = self._value(pairs[self.came_from]) + elif op == "OpCompositeConstruct" and ty.startswith("%arr_sbuf_x"): + value = [self._value(a) for a in args] + elif op == "OpFunctionCall" and args[0] in self.slow_fns: + fn_lines = self.slow_fns[args[0]] + params = [w[0] for w in fn_lines if len(w) >= 3 and w[2] == "OpFunctionParameter"] + saved_block, saved_came = self.block, self.came_from + for p, arg in zip(params, args[1:]): + self.ids[p] = self._value(arg) + value = self._exec(fn_lines, params[0] if params else args[0]) + self.block, self.came_from = saved_block, saved_came elif op == "OpBitwiseAnd" and ty == "%uint": value = self._value(args[0]) & self._value(args[1]) elif op == "OpBitFieldUExtract" and ty == "%uint": value = (self._value(args[0]) >> self._value(args[1])) & ((1 << self._value(args[2])) - 1) elif op == "OpIAdd" and ty == "%uint": value = (self._value(args[0]) + self._value(args[1])) & MASK32 + elif op == "OpUConvert" and ty == "%uint": + value = self._value(args[0]) & MASK32 elif op == "OpUConvert" and ty == "%ulong": value = self._value(args[0]) & MASK32 elif op == "OpShiftLeftLogical" and ty == "%ulong": value = (self._value(args[0]) << self._value(args[1])) & MASK64 + elif op == "OpShiftRightLogical" and ty == "%ulong": + value = (self._value(args[0]) & MASK64) >> self._value(args[1]) elif op == "OpShiftRightArithmetic" and ty == "%ulong": operand = self._value(args[0]) if operand >> 63: @@ -489,10 +555,14 @@ def _step(self, words): value = self._value(args[0]) | self._value(args[1]) elif op == "OpIAdd" and ty == "%ulong": value = (self._value(args[0]) + self._value(args[1])) & MASK64 + elif op == "OpISub" and ty == "%ulong": + value = (self._value(args[0]) - self._value(args[1])) & MASK64 elif op == "OpIMul" and ty == "%ulong": value = (self._value(args[0]) * self._value(args[1])) & MASK64 elif op == "OpIEqual" and ty == "%bool": value = self._value(args[0]) == self._value(args[1]) + elif op == "OpULessThan" and ty == "%bool": + value = self._value(args[0]) < self._value(args[1]) elif op == "OpUGreaterThanEqual" and ty == "%bool": value = self._value(args[0]) >= self._value(args[1]) elif op == "OpSelect" and ty in ("%ulong", "%uint"): @@ -502,6 +572,29 @@ def _step(self, words): value = self._value(args[1] if cond else args[2]) elif op == "OpConvertUToPtr" and ty == "%_ptr_PSB_arr": value = ("psb", self._value(args[0])) + elif op == "OpConvertUToPtr" and ty in ("%_ptr_PSB_sl_blk1", "%_ptr_PSB_sl_blk2", "%_ptr_PSB_sl_blk4"): + value = ("blk", self._value(args[0]) & MASK64, int(ty[-1])) + elif op == "OpAccessChain" and ty in ("%_ptr_PSB_v2uint_sl", "%_ptr_PSB_v4uint_sl"): + # Member 0 of the read-only block a wide load goes through: the block's own address. + kind, address, count = self._value(args[0]) + if kind != "blk" or count != (2 if "v2" in ty else 4) or self._value(args[1]) != 0 or len(args) != 2: + raise AssertionError("unmodelled access chain: " + " ".join(words)) + value = ("vec", address, count) + elif op == "OpLoad" and ty in ("%v2uint_sl", "%v4uint_sl"): + # A wide load reads its dwords in order, each at the vector's address + 4 * i. + kind, address, count = self._value(args[0]) + if kind != "vec" or count != (2 if "v2" in ty else 4) or args[1:] != ["Aligned", "4"]: + raise AssertionError("unmodelled load: " + " ".join(words)) + value = [] + for i in range(count): + where = (address + 4 * i) & MASK64 + self.reads.append(where) + value.append(self.memory.read_dword(where)) + elif op == "OpCompositeExtract" and ty == "%uint": + vector = self._value(args[0]) + if not isinstance(vector, list): + raise AssertionError("OpCompositeExtract of a non-vector: " + " ".join(words)) + value = vector[int(args[1])] else: raise AssertionError("unmodelled instruction: " + " ".join(words)) self.ids[result] = value diff --git a/tests/semantic/test_smem_nonwritable_outline.py b/tests/semantic/test_smem_nonwritable_outline.py new file mode 100644 index 0000000000..e733cfc7b2 --- /dev/null +++ b/tests/semantic/test_smem_nonwritable_outline.py @@ -0,0 +1,345 @@ +"""Per-load NonWritable SMEM restoration + outlined %sbuf_slow_xN partial-OOB helper (Item 3B.4). + +Verifies: + * Part A (NonWritable restoration & alias safety): + - Read-only shaders keep NonWritable on all scalar loads. + - Shaders with buffer stores/atomics still keep NonWritable (%sl_blk1/2/4) on provably non-aliasing scalar + loads: disjoint V# roots, disjoint descriptor-table slots, 32-bit descriptor-heap s_load* (user SGPR + hi=0), + s_getpc_b64 rodata loads, and loads with no PSB write reachable before or after them. + - Scalar loads that can alias a store/atomic (same V# root, derived base from the written V# as in + valu_fuzz --family mem, or unknown/constant base with a reaching/following write) use the mutable + %sl_rw_blk2 / %sl_rw_blk4 / %_ptr_PSB_arr path without NonWritable. + - Mixed shaders emit both NonWritable (%sl_blk*) and mutable (%sl_rw_blk*) loads cleanly in the same module. + - Any s_dcache_* instruction alongside a PSB write conservatively disables NonWritable across the module. + * Part B (Outlined %sbuf_slow_xN partial-OOB fallback): + - Repeated wide s_buffer_load_dwordxN sites share one module-level %sbuf_slow_xN OpFunction per used width + (emitting only widths actually used by the shader). + - Partial-OOB and all-OOB runs match exact hardware bounds (zero out-of-range reads, exact values). + - All generated SPIR-V modules pass spirv-as + spirv-val --target-env vulkan1.2. +""" +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(os.path.dirname(HERE)) +TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") +sys.dont_write_bytecode = True +if TOOLS_DIR not in sys.path: + sys.path.insert(0, TOOLS_DIR) +if HERE not in sys.path: + sys.path.insert(0, HERE) + +import check_absent_lane_ub # noqa: E402 +import rdna2spirv # noqa: E402 +from shader_ir import parse_line # noqa: E402 +import support # noqa: E402 +import test_value_semantics as tv # noqa: E402 + +OUT = 0x2000 +CB = 0x4000 +TBL = 0x6000 +OUT_V = 0x31016FAC +FSSM_12 = tv._fssm(12 << 1, (64, 1, 1)) + + +def _validate(spv): + if not (shutil.which("spirv-as") and shutil.which("spirv-val")): + return + with tempfile.TemporaryDirectory() as tmp: + asm, out = os.path.join(tmp, "m.spvasm"), os.path.join(tmp, "m.spv") + with open(asm, "w", encoding="utf-8", newline="\n") as f: + f.write(spv) + r1 = subprocess.run(["spirv-as", "--target-env", "vulkan1.2", asm, "-o", out], + capture_output=True, text=True) + assert r1.returncode == 0, r1.stderr + r2 = subprocess.run(["spirv-val", "--target-env", "vulkan1.2", out], + capture_output=True, text=True) + assert r2.returncode == 0, r2.stderr + + +class SmemNonWritableAndOutlineTests(unittest.TestCase): + def test_fixture_restores_nonwritable_outlines_helpers_and_checks_oob(self): + src = (Path(HERE) / "fixtures" / "cs_smem_nonwritable_outline.asm").read_bytes() + spv = support.translate_listing("cs_smem_nonwritable_outline", src, fssm=FSSM_12) + _validate(spv) + + # Part A: disjoint CBV s[4:7] and descriptor-table s[8:9] keep NonWritable despite buffer_store to s[0:3]. + self.assertIn("OpMemberDecorate %sl_blk4 0 NonWritable", spv) + self.assertIn("OpMemberDecorate %sl_blk1 0 NonWritable", spv) + self.assertNotIn("%sl_rw_blk", spv) + self.assertEqual(check_absent_lane_ub.check_absent_lane_ub(spv), []) + + # Part B: two x4 + two x16 RO loads share ONE %sbuf_slow_ro_x4 and ONE %sbuf_slow_ro_x16 loop helper + # (no unused x2/x8, no mutable _rw_ helpers, ONE OpLoad per helper inside OpLoopMerge ... DontUnroll). + self.assertEqual(spv.count("%sbuf_slow_ro_x4 = OpFunction "), 1) + self.assertEqual(spv.count("%sbuf_slow_ro_x16 = OpFunction "), 1) + self.assertNotIn("%sbuf_slow_ro_x2", spv) + self.assertNotIn("%sbuf_slow_ro_x8", spv) + self.assertNotIn("%sbuf_slow_rw_", spv) + self.assertEqual(spv.count("OpFunctionCall %arr_sbuf_x4 %sbuf_slow_ro_x4"), 2) + self.assertEqual(spv.count("OpFunctionCall %arr_sbuf_x16 %sbuf_slow_ro_x16"), 2) + self.assertEqual(spv.count("DontUnroll"), 2) + self.assertEqual(spv.count("OpConvertUToPtr %_ptr_PSB_sl_blk1"), 2) + # Compact loop: ONE per-dword OpLoad per width helper (1 + 1 = 2), not unrolled (4 + 16 = 20). + self.assertEqual(sum("OpLoad %uint" in ln and "Aligned 4" in ln for ln in spv.splitlines()), 2) + + # Execute with partial OOB: NUM_RECORDS = 0x18 (6 dwords: 0x00..0x14 in range, 0x18.. out of range). + cb_bytes = 0x18 + mem = tv.ReadLog({a: 0xB0000000 | a for base in (CB, TBL) for a in range(base, base + 0x80, 4)}) + support.run_fragment(spv, inputs={"%wg_id": (0, 0, 0), "%local_id": (0, 0, 0)}, + push_constants=[OUT, 0, 0x100, OUT_V, CB, 0, cb_bytes, OUT_V, TBL] + [0] * 23, + memory=mem) + got = [dict.get(mem, OUT + 4 * i) for i in range(8)] + self.assertEqual(got, [ + 0xB0000000 | TBL, # s12: table dword 0 + 0xB0000000 | CB, # s16: x4 @ 0x00 dword 0 (in bounds) + 0xB0000000 | (CB + 0x10), # s20: x4 @ 0x10 dword 0 (in bounds, dwords 2..3 OOB) + 0xB0000000 | (CB + 0x10), # s36: x16 @ 0x00 dword 4 (in bounds) + 0xB0000000 | (CB + 0x10), # s48: x16 @ 0x10 dword 0 (in bounds) + 0, # s51: x16 @ 0x10 dword 3 (+0x1c -> OOB -> 0) + 0, # s62: x16 @ 0x10 dword 14 (OOB -> 0) + 0, # s63: x16 @ 0x10 dword 15 (OOB -> 0) + ]) + cb_reads = sorted({a for a in mem.reads if CB <= a < CB + 0x80}) + self.assertEqual(cb_reads, list(range(CB, CB + cb_bytes, 4))) + + # Execute with all-OOB (NUM_RECORDS = 0): zero CB reads, all CB results 0. + mem0 = tv.ReadLog({a: 0xC0000000 | a for base in (CB, TBL) for a in range(base, base + 0x80, 4)}) + support.run_fragment(spv, inputs={"%wg_id": (0, 0, 0), "%local_id": (0, 0, 0)}, + push_constants=[OUT, 0, 0x100, OUT_V, CB, 0, 0, OUT_V, TBL] + [0] * 23, + memory=mem0) + self.assertEqual([dict.get(mem0, OUT + 4 * i) for i in range(8)], + [0xC0000000 | TBL, 0, 0, 0, 0, 0, 0, 0]) + self.assertEqual([a for a in mem0.reads if CB <= a < CB + 0x80], []) + + def test_aliasing_derived_vsharp_drops_nonwritable(self): + # valu_fuzz --family mem shape: s[16:19] is derived from s[0:3] (same root user SGPR s0), + # so s_buffer_load_dwordx4 after buffer_store to s[0:3] must NOT carry NonWritable. + lines = [ + "s_add_u32 s16, s0, 0x1000", + "s_and_b32 s17, s1, 0xffff", + "s_mov_b32 s18, 0x1000", + "s_mov_b32 s19, 0x31016fac", + "buffer_store_dword v0, v1, s[0:3], 0 offen", + "s_waitcnt vmcnt(0)", + "s_buffer_load_dwordx4 s[20:23], s[16:19], 0x0", + "s_waitcnt lgkmcnt(0)", + "s_endpgm", + ] + spv = support.translate_lines("cs_alias_smem", lines, fssm=FSSM_12) + _validate(spv) + self.assertIn("%sl_rw_blk4 = OpTypeStruct %v4uint_sl", spv) + self.assertNotIn("OpMemberDecorate %sl_rw_blk4 0 NonWritable", spv) + self.assertNotIn("%sl_blk4", spv) + self.assertIn("%sbuf_slow_rw_x4 = OpFunction ", spv) + self.assertNotIn("%sbuf_slow_ro_x4", spv) + self.assertNotIn("%sl_blk1", spv) + + def test_mixed_ro_and_rw_loads_in_same_shader(self): + # Disjoint CBV s[4:7] gets NonWritable (%sl_blk4 + %sbuf_slow_ro_x4); + # same-V# s[0:3] after store gets mutable (%sl_rw_blk4 + %sbuf_slow_rw_x4), sharing ONE %fn_sbuf_slow_x4. + lines = [ + "s_buffer_load_dwordx4 s[16:19], s[4:7], 0x0", + "buffer_store_dword v0, v1, s[0:3], 0 offen", + "s_waitcnt vmcnt(0)", + "s_buffer_load_dwordx4 s[20:23], s[0:3], 0x0", + "s_waitcnt lgkmcnt(0)", + "s_endpgm", + ] + spv = support.translate_lines("cs_mixed_ro_rw", lines, fssm=FSSM_12) + _validate(spv) + self.assertEqual(check_absent_lane_ub.check_absent_lane_ub(spv), []) + self.assertIn("OpMemberDecorate %sl_blk4 0 NonWritable", spv) + self.assertIn("OpMemberDecorate %sl_blk1 0 NonWritable", spv) + self.assertIn("%sl_rw_blk4 = OpTypeStruct %v4uint_sl", spv) + self.assertNotIn("OpMemberDecorate %sl_rw_blk4 0 NonWritable", spv) + self.assertIn("OpConvertUToPtr %_ptr_PSB_sl_blk4", spv) + self.assertIn("OpConvertUToPtr %_ptr_PSB_sl_rw_blk4", spv) + self.assertEqual(spv.count("%sbuf_slow_ro_x4 = OpFunction "), 1) + self.assertEqual(spv.count("%sbuf_slow_rw_x4 = OpFunction "), 1) + self.assertEqual(spv.count("%fn_sbuf_slow_x4 = OpTypeFunction "), 1) + self.assertEqual(spv.count("OpFunctionCall %arr_sbuf_x4 %sbuf_slow_ro_x4"), 1) + self.assertEqual(spv.count("OpFunctionCall %arr_sbuf_x4 %sbuf_slow_rw_x4"), 1) + # 1 OpLoad in %sbuf_slow_ro_x4 + 1 OpLoad in %sbuf_slow_rw_x4 = 2. + self.assertEqual(sum("OpLoad %uint" in ln and "Aligned 4" in ln for ln in spv.splitlines()), 2) + + def test_rw_slow_loop_partial_oob_and_all_oob_execution(self): + # Exercises %sbuf_slow_rw_x4 after a store to the same V# root s[0:3]: verifies exact partial-OOB + # values, store visibility, zero reads past NUM_RECORDS, and off > lim (zero reads, all zeros). + lines = [ + "v_mov_b32 v0, 0x11223344", + "v_mov_b32 v1, 0", + "buffer_store_dword v0, v1, s[0:3], 0 offen", + "s_waitcnt vmcnt(0)", + "s_buffer_load_dwordx4 s[16:19], s[0:3], 0x4", + "s_buffer_load_dwordx4 s[20:23], s[0:3], 0x20", + "s_waitcnt lgkmcnt(0)", + "v_mov_b32 v2, s16", + "v_mov_b32 v3, s17", + "v_mov_b32 v4, s18", + "v_mov_b32 v5, s19", + "v_mov_b32 v6, s20", + "buffer_store_dword v2, v1, s[4:7], 0 offen offset:0", + "buffer_store_dword v3, v1, s[4:7], 0 offen offset:4", + "buffer_store_dword v4, v1, s[4:7], 0 offen offset:8", + "buffer_store_dword v5, v1, s[4:7], 0 offen offset:12", + "buffer_store_dword v6, v1, s[4:7], 0 offen offset:16", + "s_endpgm", + ] + spv = support.translate_lines("cs_rw_slow_exec", lines, fssm=FSSM_12) + _validate(spv) + self.assertEqual(spv.count("%sbuf_slow_rw_x4 = OpFunction "), 1) + self.assertNotIn("%sbuf_slow_ro_x4", spv) + # NUM_RECORDS = 15 (0x0f): at offset 0x4, dword 0 (4..7) and dword 1 (8..11) fit; dword 2 (12..15) is OOB! + # At offset 0x20, off > lim -> 0 dwords fit, zero reads. + mem = tv.ReadLog({CB + 4 * i: 0xD0000000 | (4 * i) for i in range(16)}) + support.run_fragment(spv, inputs={"%wg_id": (0, 0, 0), "%local_id": (0, 0, 0)}, + push_constants=[CB, 0, 15, OUT_V, OUT, 0, 0x100, OUT_V] + [0] * 24, + memory=mem) + self.assertEqual([dict.get(mem, OUT + 4 * i) for i in range(5)], + [0xD0000004, 0xD0000008, 0, 0, 0]) + cb_reads = sorted({a for a in mem.reads if CB <= a < CB + 0x40}) + self.assertEqual(cb_reads, [CB + 4, CB + 8]) + + def test_descriptor_heap_load_stays_nonwritable_with_global_store(self): + # 32-bit descriptor-table pointer in user SGPR s8 with hi=0 whose loaded dwords are consumed solely + # as a V# descriptor stays NonWritable even alongside global_store with unknown VGPR address (saddr=off), + # while a constant-address data s_load stays mutable. + lines = [ + "s_mov_b32 s9, 0", + "s_load_dwordx4 s[12:15], s[8:9], 0x0", + "s_waitcnt lgkmcnt(0)", + "buffer_load_dword v3, v0, s[12:15], 0 offen", + "global_store_dword v[0:1], v2, off", + "s_mov_b32 s20, 0x1000", + "s_mov_b32 s21, 0", + "s_load_dwordx4 s[24:27], s[20:21], 0x0", + "v_mov_b32 v4, s24", + "s_endpgm", + ] + spv = support.translate_lines("cs_heap_with_gstore", lines, fssm=FSSM_12) + _validate(spv) + self.assertIn("OpMemberDecorate %sl_blk4 0 NonWritable", spv) + self.assertIn("OpConvertUToPtr %_ptr_PSB_sl_blk4", spv) + self.assertIn("OpConvertUToPtr %_ptr_PSB_sl_rw_blk4", spv) + + def test_32bit_rw_buffer_data_sload_drops_nonwritable(self): + # Negative control (P0): a 32-bit RW buffer pointer in user SGPR s0 with hi=0 that is written via + # global_store (both via s[0:1] and via unknown off) and read as data via s_load MUST stay mutable. + for store_line in ( + "global_store_dword v0, v1, s[0:1]", + "global_store_dword v[0:1], v2, off", + ): + with self.subTest(store=store_line): + lines = [ + "s_mov_b32 s1, 0", + store_line, + "s_waitcnt vmcnt(0)", + "s_load_dwordx4 s[4:7], s[0:1], 0x0", + "s_waitcnt lgkmcnt(0)", + "v_mov_b32 v3, s4", + "s_endpgm", + ] + spv = support.translate_lines("cs_rw32_sload", lines, fssm=FSSM_12) + _validate(spv) + self.assertIn("%sl_rw_blk4 = OpTypeStruct %v4uint_sl", spv) + self.assertNotIn("OpMemberDecorate %sl_rw_blk4 0 NonWritable", spv) + self.assertNotIn("%sl_blk4", spv) + + def test_unknown_plus_user_sgpr_does_not_forge_disjoint_origin(self): + # Negative control (P0): v_readfirstlane_b32 produces an unknown pointer in s10; adding user SGPR s4 + # (or s_lshl2_add_u32 with an unknown base) must NOT inherit ("in", 4) as a disjoint origin. + for arith in ( + "s_add_u32 s10, s10, s4", + "s_lshl2_add_u32 s10, s4, s10", + "s_lshl2_add_u32 s10, s10, s4", + ): + with self.subTest(arith=arith): + lines = [ + "buffer_store_dword v0, v1, s[0:3], 0 offen", + "s_waitcnt vmcnt(0)", + "v_readfirstlane_b32 s10, v0", + arith, + "s_mov_b32 s11, 0", + "s_load_dwordx4 s[16:19], s[10:11], 0x0", + "s_waitcnt lgkmcnt(0)", + "v_mov_b32 v2, s16", + "s_endpgm", + ] + spv = support.translate_lines("cs_unknown_add_sgpr", lines, fssm=FSSM_12) + _validate(spv) + self.assertIn("%sl_rw_blk4 = OpTypeStruct %v4uint_sl", spv) + self.assertNotIn("%sl_blk4", spv) + + def test_multi_sgpr_clobbers_clear_provenance(self): + # Negative control (P1): s_movreld_b32 / s_swappc_b64 / s_setpc_b64 / s_call_b64 clobber arbitrary SGPRs, + # so prior provenance of s[4:7] must not survive across them. + for clobber in ( + "s_movreld_b32 s4, s0", + "s_swappc_b64 s[20:21], s[22:23]", + "s_setpc_b64 s[22:23]", + "s_call_b64 s[20:21], 4", + ): + with self.subTest(clobber=clobber): + insns = [ + parse_line("buffer_store_dword v0, v1, s[0:3], 0 offen"), + parse_line(clobber), + parse_line("s_buffer_load_dwordx4 s[16:19], s[4:7], 0x0"), + parse_line("s_endpgm"), + ] + ro = rdna2spirv.analyse_scalar_load_ro([insns], [[]], user_limit=12) + self.assertEqual(ro, frozenset()) + + def test_disjoint_table_slots_stay_nonwritable(self): + # Two V#s loaded from distinct static offsets (0x0 and 0x20) of the same descriptor table s[8:9]: + # CBV at +0x0 stays NonWritable even after buffer_store through UAV at +0x20. + lines = [ + "s_mov_b32 s9, 0", + "s_load_dwordx4 s[12:15], s[8:9], 0x0", + "s_load_dwordx4 s[16:19], s[8:9], 0x20", + "s_waitcnt lgkmcnt(0)", + "buffer_store_dword v0, v1, s[16:19], 0 offen", + "s_waitcnt vmcnt(0)", + "s_buffer_load_dwordx4 s[20:23], s[12:15], 0x0", + "s_endpgm", + ] + spv = support.translate_lines("cs_disjoint_table_slots", lines, fssm=FSSM_12) + _validate(spv) + self.assertIn("OpMemberDecorate %sl_blk4 0 NonWritable", spv) + self.assertNotIn("%sl_rw_blk", spv) + + def test_dcache_inv_disables_nonwritable_conservatively(self): + insns = [ + parse_line("s_buffer_load_dwordx4 s[16:19], s[4:7], 0x0"), + parse_line("buffer_store_dword v0, v1, s[0:3], 0 offen"), + parse_line("s_dcache_inv"), + parse_line("s_endpgm"), + ] + ro = rdna2spirv.analyse_scalar_load_ro([insns], [[]], user_limit=12) + self.assertEqual(ro, frozenset()) + + def test_unanalysed_scalar_load_ro_none_strips_sl_blk1_nonwritable(self): + # When Gen() is assembled directly with scalar_load_ro=None alongside a PSB write, + # scalar_loads_read_only() must strip NonWritable from %sl_blk1 as well as %sl_blk2/%sl_blk4. + g = rdna2spirv.Gen("ps") + self.assertIsNone(g.scalar_load_ro) + for line in ( + "buffer_store_dword v0, v1, s[0:3], 0 offen", + "s_buffer_load_dwordx4 s[4:7], s[0:3], 0x0", + ): + ins = parse_line(line) + g.insn(ins) + spv = rdna2spirv.assemble(g) + _validate(spv) + self.assertIn("%sl_blk1 = OpTypeStruct %uint", spv) + self.assertNotIn("OpMemberDecorate %sl_blk1 0 NonWritable", spv) + self.assertNotIn("OpMemberDecorate %sl_blk4 0 NonWritable", spv) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_tsharp_index_word.py b/tests/semantic/test_tsharp_index_word.py new file mode 100644 index 0000000000..412b54ed56 --- /dev/null +++ b/tests/semantic/test_tsharp_index_word.py @@ -0,0 +1,189 @@ +"""The bindless index in the T# (docs/design.md, "Bindless index in the T#"). + +A T# whose dword 6 the dataflow (tools/descriptor_sources.py) traces to a heap slot takes its index from that word: +TAG [31:28] | storage kind [27:23] | sampled kind [22:16] | index [15:0], which the layer writes into every heap +shaders read (runtime/src/gfx10_descriptors.h, tsharp_index_word). No hash-table lookup is emitted for it. A T# from +anywhere else keeps the lookup, and its dword-6 index wins when the word carries the tag. The fixture +fixtures/disasm/ps_tsharp_index_word.s has both, and a T# loaded in either arm of a branch. +""" +import os +import re +import struct +import sys +import tempfile +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.dont_write_bytecode = True +sys.path.insert(0, HERE) + +import support # noqa: E402 +import spirv_mini_interp as si # noqa: E402 +import rdna2spirv # noqa: E402 +import descriptor_sources # noqa: E402 +import shader_ir # noqa: E402 + +HEADER = os.path.join(support.ROOT, "runtime", "src", "gfx10_descriptors.h") +LOOKUP = re.compile(r"OpFunctionCall %\w+ %desc_lookup_fn ") +SAMPLED_2D = 1 << 16 # kind bit 0 (the 2D sampled array) in the word +SAMPLED_3D = 1 << (16 + 2) # kind bit 2 (the 3D sampled array) +TEXELS = {0: (0.0, 0.0, 0.0, 0.0), 2: (0.25, 0.5, 0.75, 1.0), 5: (1.0, 0.75, 0.5, 0.25)} +EPILOGUE = ["s_waitcnt vmcnt(0)", "exp mrt0 v4, v5, v6, v7 done vm", "s_endpgm"] + + +def fbits(value): + return struct.unpack("> 8) & 0x1Fu) << 23) | ((kind & 0x7Fu) << 16) | index", + text) + + def test_heap_tsharp_reads_dword6_without_a_lookup(self): + spv = load_program(["s_mov_b32 s1, 0"]) + self.assertIsNone(LOOKUP.search(spv)) + # No %desc_map is bound: a lookup would raise. The word's index picks the image. + self.assertEqual(run(spv, tsharp(word(2))), expected(2)) + self.assertEqual(run(spv, tsharp(word(5))), expected(5)) + + def test_untagged_word_wrong_array_or_no_image_read_the_fallback(self): + spv = load_program(["s_mov_b32 s1, 0"]) + for name, words in (("no tag", tsharp(word(2, tag=0x1))), + ("3D index for a 2D load", tsharp(word(2, kind=SAMPLED_3D))), + ("dword 3 names no image", tsharp(word(2), word3=0x30000000)), + ("zero slot", [0] * 8)): + with self.subTest(name): + self.assertEqual(run(spv, words), expected(0)) + + def test_tsharp_of_unknown_source_keeps_the_lookup_and_prefers_the_word(self): + spv = load_program([]) # s[0:1] is a 64-bit pointer: not a descriptor-table pointer + self.assertIsNotNone(LOOKUP.search(spv)) + untagged = tsharp(5) + desc_map = [0, *untagged, 5, 0x80000001] # mask 0: one slot, holding the T#'s words -> index 5, 2D + self.assertEqual(run(spv, untagged, desc_map), expected(5)) + # Tagged: the word wins over the table (whose key no longer matches anyway). + self.assertEqual(run(spv, tsharp(word(2)), desc_map), expected(2)) + + def test_branches_and_the_module_meta(self): + spv = support.translate_fixture("ps_tsharp_index_word") + gen = rdna2spirv.translate.last_gen + self.assertEqual(gen.tsharp_index_reads, 2) # +0x20, and +0x40 / +0x60 joined after the branch + self.assertEqual(gen.tsharp_lookups, 1) # the T# from the 64-bit pointer s[4:5] + self.assertEqual(len(LOOKUP.findall(spv)), 2) # that T#, and the literal S# (all three samples share it) + meta = rdna2spirv.shader_meta(gen, spv) + self.assertEqual(meta["tsharp_index"], "dword6") + self.assertEqual((meta["tsharp_index_reads"], meta["tsharp_lookups"]), (2, 1)) + + +def verdicts(lines, user=32): + text = "; t hand-written\n" + "".join("\t" + ln + "\n" for ln in lines) + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, "t.s") + with open(path, "w", encoding="utf-8", newline="\n") as f: + f.write(text) + insns = shader_ir.parse_file(path)["insns"] + out = descriptor_sources.analyse([insns], [[]], user) + return [out[id(i)] for i in insns if i["op"].startswith("image_")] + + +class DescriptorSources(unittest.TestCase): + SAMPLE = "image_load v[0:3], v[4:5], s[8:15] dmask:0xf dim:SQ_RSRC_IMG_2D unorm" + + def test_table_pointer_static_and_dynamic_offsets(self): + self.assertEqual(verdicts(["s_mov_b32 s1, 0", "s_load_dwordx8 s[8:15], s[0:1], 0x40", self.SAMPLE]), [True]) + self.assertEqual(verdicts(["s_mov_b32 s1, 0", "s_lshl_b32 s20, s3, 5", + "s_load_dwordx8 s[8:15], s[0:1], s20", self.SAMPLE]), [True]) + + def test_a_slot_read_in_two_halves(self): + # Dwords 4..7 from offset 0x10: dword 6 is the load's dword 2, at byte 24 of the slot. + self.assertEqual(verdicts(["s_mov_b32 s1, 0", "s_load_dwordx4 s[8:11], s[0:1], 0x0", + "s_load_dwordx4 s[12:15], s[0:1], 0x10", self.SAMPLE]), [True]) + # The same registers from offset 0x20 and 0x30 + 8: dword 6 lands at byte 8 of a slot. + self.assertEqual(verdicts(["s_mov_b32 s1, 0", "s_load_dwordx4 s[8:11], s[0:1], 0x20", + "s_load_dwordx4 s[12:15], s[0:1], 0x38", self.SAMPLE]), [False]) + + def test_a_table_pointer_spilled_to_vgpr_lanes(self): + # A compiler parks SGPRs in VGPR lanes; the pointer read back is still the table pointer. + spill = ["s_mov_b32 s1, 0", "v_writelane_b32 v63, s0, 10", "v_writelane_b32 v63, s1, 11", + "v_writelane_b32 v63, vcc_hi, 12", "v_readlane_b32 vcc_lo, v63, 12"] + back = ["v_readlane_b32 s20, v63, 10", "v_readlane_b32 s21, v63, 11", + "s_load_dwordx8 s[8:15], s[20:21], 0x40", self.SAMPLE] + self.assertEqual(verdicts(spill + back), [True]) + # Anything else that names the VGPR, or a lane written again, forgets what the lanes held. + self.assertEqual(verdicts(spill + ["v_mov_b32_e32 v63, 0"] + back), [False]) + self.assertEqual(verdicts(spill + ["s_load_dword s40, s[2:3], 0x0", "v_writelane_b32 v63, s40, 10"] + back), + [False]) + + def test_a_tsharp_loaded_into_vcc(self): + # Short of SGPRs, a compiler loads a T#'s last two dwords into VCC; dword 6 is then vcc_lo. + load = ["s_mov_b32 s1, 0", "s_load_dwordx8 [s100,s101,s102,s103,s104,s105,vcc_lo,vcc_hi], s[0:1], 0x40", + "v_mov_b32_e32 v8, 1.0"] + use = "image_sample_lz v[0:3], v[4:5], [s100,s101,s102,s103,s104,s105,vcc_lo,vcc_hi], s[16:19] " \ + "dmask:0xf dim:SQ_RSRC_IMG_2D" + self.assertEqual(verdicts(load + [use]), [True]) + # An instruction that writes VCC (printed: VOPC and carry instructions name it) forgets what it held. + self.assertEqual(verdicts(load + ["v_cmp_lt_f32_e32 vcc_lo, v0, v1", use]), [False]) + # A pointer parked in VCC and copied back is still the table pointer. + self.assertEqual(verdicts(["s_mov_b32 s1, 0", "v_writelane_b32 v63, s0, 10", "v_writelane_b32 v63, s1, 11", + "v_readlane_b32 vcc_lo, v63, 10", "v_readlane_b32 vcc_hi, v63, 11", + "s_mov_b64 s[20:21], vcc", "s_load_dwordx8 s[8:15], s[20:21], 0x40", self.SAMPLE]), + [True]) + + def test_other_sources_keep_the_lookup(self): + for name, lines in ( + ("64-bit pointer", ["s_load_dwordx8 s[8:15], s[0:1], 0x0"]), + ("system SGPR", ["s_mov_b32 s41, 0", "s_load_dwordx8 s[8:15], s[40:41], 0x0"]), + ("loaded pointer", ["s_mov_b32 s1, 0", "s_load_dword s20, s[0:1], 0x0", "s_mov_b32 s21, 0", + "s_load_dwordx8 s[8:15], s[20:21], 0x0"]), + ("constant buffer", ["s_buffer_load_dwordx8 s[8:15], s[0:3], 0x0"]), + ("edited dword 6", ["s_mov_b32 s1, 0", "s_load_dwordx8 s[8:15], s[0:1], 0x0", + "s_or_b32 s14, s14, 1"]), + ("literal", [f"s_mov_b32 s{r}, 0" for r in range(8, 16)])): + with self.subTest(name): + self.assertEqual(verdicts(lines + [self.SAMPLE], user=40 if name == "system SGPR" else 32), [False]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_valu_f32_min3_max3_mad.py b/tests/semantic/test_valu_f32_min3_max3_mad.py index db75232df5..acdce71bad 100644 --- a/tests/semantic/test_valu_f32_min3_max3_mad.py +++ b/tests/semantic/test_valu_f32_min3_max3_mad.py @@ -753,7 +753,8 @@ def test_normal_values_nan_and_inf_pass_through(self): self.assertEqual(run_three_input("v_mad_legacy_f32", NEG_ZERO, TWO, NEG_ZERO), POS_ZERO) def test_denormal_divergence_is_still_detectable(self): - # Sabotage: turn every flush select into a pass-through; the subnormal cases above now differ. + # Sabotage: drop hardware DenormFlushToZero 32 (default) or software flush selects (--no-ftz32); + # the subnormal cases above now differ. cases = [ ("v_mad_f32", 0x17800000, 0x1C800000, SUBNORM_MIN, POS_ZERO), ("v_mac_f32", SUBNORM_MIN, ONE, SUBNORM_MIN, POS_ZERO), @@ -768,9 +769,19 @@ def test_denormal_divergence_is_still_detectable(self): lines = [f"v_mov_b32 v1, {a:#x}", f"v_mov_b32 v2, {b:#x}", f"v_mov_b32 v3, {c:#x}", f"{op} v0, v1, v2, v3"] spv = translate_ps(lines) + self.assertIn("OpExecutionMode %main DenormFlushToZero 32", spv) self.assertEqual(si.run_fragment(spv)["%out_mrt0"][0], want) + no_mode = "\n".join(ln for ln in spv.splitlines() if "DenormFlushToZero" not in ln) + self.assertNotEqual(si.run_fragment(no_mode)["%out_mrt0"][0], want) + old_ftz = rdna2spirv.FTZ32 + rdna2spirv.FTZ32 = False + try: + spv_sw = translate_ps(lines) + finally: + rdna2spirv.FTZ32 = old_ftz + self.assertEqual(si.run_fragment(spv_sw)["%out_mrt0"][0], want) unflushed, count = re.subn(r"(%\w+) = OpSelect %float (%\w+) (%\w+) (%\w+)", - r"\1 = OpCopyObject %float \4", spv) + r"\1 = OpCopyObject %float \4", spv_sw) self.assertGreaterEqual(count, 3) self.assertNotEqual(si.run_fragment(unflushed)["%out_mrt0"][0], want) diff --git a/tests/semantic/test_valu_mul_legacy_denorm.py b/tests/semantic/test_valu_mul_legacy_denorm.py index 47bcc1683a..c1a4305702 100644 --- a/tests/semantic/test_valu_mul_legacy_denorm.py +++ b/tests/semantic/test_valu_mul_legacy_denorm.py @@ -16,7 +16,7 @@ import support -def run_mul(src0, src1, mods=""): +def run_mul(src0, src1, mods="", ftz32=None): ins = "v_mul_legacy_f32_e64" if mods else "v_mul_legacy_f32" lines = [ f"v_mov_b32 v0, {src0:#x}", @@ -25,7 +25,13 @@ def run_mul(src0, src1, mods=""): "exp mrt0 v2, v2, v2, v2 done vm", "s_endpgm", ] - spv = support.translate_lines("ps_mul_legacy_denorm_semantic", lines) + old = support.rdna2spirv.FTZ32 + if ftz32 is not None: + support.rdna2spirv.FTZ32 = ftz32 + try: + spv = support.translate_lines("ps_mul_legacy_denorm_semantic", lines) + finally: + support.rdna2spirv.FTZ32 = old words = support.mrt0_words(spv) assert len(words) == 4 return words[0], spv @@ -36,52 +42,60 @@ def test_inputs_flush_before_legacy_zero_override(self): # With mode0, 2^-149 is treated as zero, so the nonzero result 2^-125 # of an IEEE multiply must not survive. Both signs of a zero input # give +0 under the legacy DX9 zero-times-anything rule. - for src0, src1 in [ - (0x00000001, 0x4B800000), - (0x7F800000, 0x807FFFFF), - (0xFF800000, 0x007FFFFF), - (0x80000001, 0x4B800000), - (0x00000001, 0x7F800000), - (0x80000001, 0xFFC00000), - (0x00000000, 0x7F800000), - (0x80000000, 0xFF800000), - ]: - with self.subTest(src0=hex(src0), src1=hex(src1)): - got, _ = run_mul(src0, src1) - self.assertEqual(got, 0) + for ftz32 in (True, False): + for src0, src1 in [ + (0x00000001, 0x4B800000), + (0x7F800000, 0x807FFFFF), + (0xFF800000, 0x007FFFFF), + (0x80000001, 0x4B800000), + (0x00000001, 0x7F800000), + (0x80000001, 0xFFC00000), + (0x00000000, 0x7F800000), + (0x80000000, 0xFF800000), + ]: + with self.subTest(ftz32=ftz32, src0=hex(src0), src1=hex(src1)): + got, _ = run_mul(src0, src1, ftz32=ftz32) + self.assertEqual(got, 0) def test_nonzero_products_flush_signed_underflow(self): - for src0, src1, expected in [ - (0x00800000, 0x3F000000, 0x00000000), - (0x80800000, 0x3F000000, 0x80000000), - (0x00800000, 0x3F800000, 0x00800000), - (0x80800000, 0x3F800000, 0x80800000), - (0x40000000, 0x40400000, 0x40C00000), - ]: - with self.subTest(src0=hex(src0), src1=hex(src1)): - got, _ = run_mul(src0, src1) - self.assertEqual(got, expected) + for ftz32 in (True, False): + for src0, src1, expected in [ + (0x00800000, 0x3F000000, 0x00000000), + (0x80800000, 0x3F000000, 0x80000000), + (0x00800000, 0x3F800000, 0x00800000), + (0x80800000, 0x3F800000, 0x80800000), + (0x40000000, 0x40400000, 0x40C00000), + ]: + with self.subTest(ftz32=ftz32, src0=hex(src0), src1=hex(src1)): + got, _ = run_mul(src0, src1, ftz32=ftz32) + self.assertEqual(got, expected) def test_product_flush_precedes_modifiers(self): - for src0, src1, mods, expected in [ - (0x00800000, 0x3F000000, "mul:2", 0x00000000), - (0x80800000, 0x3F000000, "mul:4", 0x00000000), - (0x00800000, 0x3F800000, "div:2", 0x00000000), - (0x80800000, 0x3F800000, "div:2", 0x00000000), - (0x40000000, 0x40400000, "div:2", 0x40400000), - ]: - with self.subTest(src0=hex(src0), src1=hex(src1), mods=mods): - got, _ = run_mul(src0, src1, mods) - self.assertEqual(got, expected) + for ftz32 in (True, False): + for src0, src1, mods, expected in [ + (0x00800000, 0x3F000000, "mul:2", 0x00000000), + (0x80800000, 0x3F000000, "mul:4", 0x00000000), + (0x00800000, 0x3F800000, "div:2", 0x00000000), + (0x80800000, 0x3F800000, "div:2", 0x00000000), + (0x40000000, 0x40400000, "div:2", 0x40400000), + ]: + with self.subTest(ftz32=ftz32, src0=hex(src0), src1=hex(src1), mods=mods): + got, _ = run_mul(src0, src1, mods, ftz32=ftz32) + self.assertEqual(got, expected) - def test_emits_explicit_f32_flushes_instead_of_a_driver_mode(self): - _, spv = run_mul(0x00800000, 0x3F000000, "mul:2") - # One check for each input, plus the product and final result. - self.assertGreaterEqual(spv.count("OpFOrdLessThan %bool"), 4) - self.assertIn("OpFMul %float", spv) - self.assertIn("OpSelect %float", spv) - # The software rule does not demand a vendor-specific float control. - self.assertNotIn("DenormFlushToZero 32", spv) + def test_default_uses_ftz32_fmulz_and_no_ftz32_uses_software_flushes(self): + _, spv_hw = run_mul(0x00800000, 0x3F000000, "mul:2", ftz32=True) + self.assertIn("OpExecutionMode %main DenormFlushToZero 32", spv_hw) + self.assertEqual(spv_hw.count("OpFOrdLessThan %bool"), 0) + self.assertIn("OpFOrdEqual %bool", spv_hw) + self.assertIn("OpFMul %float", spv_hw) + self.assertIn("OpSelect %float", spv_hw) + # --no-ftz32 keeps the software flush-to-zero checks without DenormFlushToZero 32. + _, spv_sw = run_mul(0x00800000, 0x3F000000, "mul:2", ftz32=False) + self.assertGreaterEqual(spv_sw.count("OpFOrdLessThan %bool"), 4) + self.assertIn("OpFMul %float", spv_sw) + self.assertIn("OpSelect %float", spv_sw) + self.assertNotIn("DenormFlushToZero 32", spv_sw) if __name__ == "__main__": diff --git a/tests/semantic/test_valu_rcp_fdiv.py b/tests/semantic/test_valu_rcp_fdiv.py index 975ee8560f..54a7705e93 100644 --- a/tests/semantic/test_valu_rcp_fdiv.py +++ b/tests/semantic/test_valu_rcp_fdiv.py @@ -715,7 +715,16 @@ def test_hand_worked_and_edge_values_across_encodings(self): for name, x_bits, want in RCP_F32_HAND_WORKED: with self.subTest(op=op + suffix, case=name): got = run_op(f"{op}{suffix} v0, v1", x_bits) - self.assertEqual(got, want) + # Under default DenormFlushToZero 32 (matching RDNA2 denorm32=0), a subnormal reciprocal + # (1 / 2^127 = 2^-127) flushes to +0.0; --no-ftz32 keeps the subnormal. + want_ftz = 0x00000000 if name == "2p127_to_subnorm" else want + self.assertEqual(got, want_ftz) + old_ftz = rdna2spirv.FTZ32 + rdna2spirv.FTZ32 = False + try: + self.assertEqual(run_op(f"{op}{suffix} v0, v1", 0x7F000000), 0x00400000) + finally: + rdna2spirv.FTZ32 = old_ftz def test_nan_inputs_preserve_nan(self): for op in self.OPS: @@ -1106,17 +1115,25 @@ def test_quotient_accuracy_within_one_ulp_wide_dynamic_range(self): ) def test_subnormal_quotients_and_inputs(self): + # (name, a, b, want_no_ftz32, want_ftz32) cases = ( - ("subnormal_div_2", 0x00000004, f32_bits(2.0), 0x00000002), - ("neg_subnormal_div_2", 0x80000004, f32_bits(2.0), 0x80000002), - ("subnormal_div_half", 0x00000002, f32_bits(0.5), 0x00000004), - ("normal_underflow_to_subnormal", 0x00400000, f32_bits(2.0), 0x00200000), - ("subnormal_divisor_to_normal", f32_bits(1.0), 0x00400000, 0x7F000000), + ("subnormal_div_2", 0x00000004, f32_bits(2.0), 0x00000002, 0x00000000), + ("neg_subnormal_div_2", 0x80000004, f32_bits(2.0), 0x80000002, 0x80000000), + ("subnormal_div_half", 0x00000002, f32_bits(0.5), 0x00000004, 0x00000000), + ("normal_underflow_to_subnormal", 0x00400000, f32_bits(2.0), 0x00200000, 0x00000000), + ("subnormal_divisor_to_normal", f32_bits(1.0), 0x00400000, 0x7F000000, 0x7F800000), ) - for name, ab, bb, want in cases: - with self.subTest(case=name): - got = run_nr_fdiv_ps(ab, bb) - self.assertEqual(got, want) + for name, ab, bb, want_ieee, want_ftz in cases: + with self.subTest(case=name, ftz32=True): + self.assertEqual(run_nr_fdiv_ps(ab, bb), want_ftz) + old_ftz = rdna2spirv.FTZ32 + rdna2spirv.FTZ32 = False + try: + for name, ab, bb, want_ieee, _ in cases: + with self.subTest(case=name, ftz32=False): + self.assertEqual(run_nr_fdiv_ps(ab, bb), want_ieee) + finally: + rdna2spirv.FTZ32 = old_ftz def test_sign_rule_preservation(self): cases = ( diff --git a/tests/semantic/test_wave32_lane_select.py b/tests/semantic/test_wave32_lane_select.py index 5008e38f25..ab3cdd1fd6 100644 --- a/tests/semantic/test_wave32_lane_select.py +++ b/tests/semantic/test_wave32_lane_select.py @@ -47,23 +47,24 @@ class Wave32LaneSelect(unittest.TestCase): def test_lane_select_uses_bits_4_0(self): self.assertEqual(run(translate()), EXPECTED) - def test_mask_63_is_undefined(self): - # Negative control: put the wave64 mask back on the lane selects; the read of lane 40 must then be - # out of range for the subgroup. + def test_mask_63_breaks_lane_40_wrap(self): + # Negative control: put the wave64 mask back on the lane selects; lane 40 no longer wraps to lane 8 + # (writelane(40) misses lane 8 and present-lane guarded readlane(40) redirects to lane 0 instead of lane 8). spv = translate() c31 = re.search(r"^(%\S+) = OpConstant %uint 31$", spv, re.M).group(1) lines = spv.splitlines() sels = [i for i, ln in enumerate(lines) if re.search(r"= OpBitwiseAnd %uint \S+ " + re.escape(c31) + "$", ln)] - # Four reads and one write select a lane, plus the wave lane (LocalInvocationIndex & 31), which a wider - # mask leaves unchanged in a 32-thread group. - self.assertGreaterEqual(len(sels), 5) + # Two non-spill reads on v2 and the write on v10 select a lane (plus wave_lane & 31). + self.assertGreaterEqual(len(sels), 3) for i in sels: lines[i] = lines[i][:-len(c31)] + "%neg_c63" k = next(i for i, ln in enumerate(lines) if ln.startswith(c31 + " = OpConstant")) lines.insert(k + 1, "%neg_c63 = OpConstant %uint 63") - with self.assertRaises(si.UndefinedResult): - run("\n".join(lines) + "\n") + got = run("\n".join(lines) + "\n") + self.assertNotEqual(got, EXPECTED) + # v2 readlane(40) sees lane 40 as absent and redirects to lane 0 (= 1) instead of wrapping to lane 8 (= 25). + self.assertEqual(got[0], 1) if __name__ == "__main__": diff --git a/tests/semantic/test_wave32_pixel_subgroup64.py b/tests/semantic/test_wave32_pixel_subgroup64.py index 3447ab2d12..c818602578 100644 --- a/tests/semantic/test_wave32_pixel_subgroup64.py +++ b/tests/semantic/test_wave32_pixel_subgroup64.py @@ -156,6 +156,47 @@ def test_readfirstlane_with_zero_exec_falls_back_to_first_running_lane(self): with self.subTest(subgroup_size=subgroup_size): self.assertEqual(run_ps(spv, subgroup_size, inputs, lanes), expected) + def test_scalar_spill_vgpr_survives_absent_lanes(self): + # Pure scalar-spill VGPRs (v_writelane_b32 / v_readlane_b32 with immediate lanes and non-VGPR + # sources, never used as vector operands) must be parked in %sgpr rather than shuffled from + # physical subgroup lanes: in fragment waves for small triangles or after discards, target + # lanes (e.g. 0..3 or 16..19) may not be running at all, making OpGroupNonUniformShuffle UB. + spv = support.translate_lines("ps_wave32_scalar_spill_absent_lanes", [ + "s_mov_b32 s20, 0x11112222", + "s_mov_b32 s21, 0x33334444", + "s_mov_b32 s22, 0x55556666", + "s_mov_b32 s23, 0x77778888", + "v_writelane_b32 v48, s20, 0", + "v_writelane_b32 v48, s21, 1", + "v_writelane_b32 v48, s22, 16", + "v_writelane_b32 v48, s23, 19", + "s_mov_b32 s20, 0", + "s_mov_b32 s21, 0", + "s_mov_b32 s22, 0", + "s_mov_b32 s23, 0", + "v_readlane_b32 s4, v48, 0", + "v_readlane_b32 s5, v48, 1", + "v_readlane_b32 s6, v48, 16", + "v_readlane_b32 s7, v48, 19", + "v_mov_b32_e32 v6, s4", + "v_mov_b32_e32 v7, s5", + "v_mov_b32_e32 v8, s6", + "v_mov_b32_e32 v9, s7", + "exp mrt0 v6, v7, v8, v9 done vm", + "s_endpgm", + ]) + self.assertNotIn("OpGroupNonUniformShuffle", spv) + want = (0x11112222, 0x33334444, 0x55556666, 0x77778888) + for name, lanes in ( + ("lanes_0_3_absent", [lane for lane in range(64) if lane % 32 >= 4]), + ("single_quad_only", [lane for lane in range(64) if lane % 32 < 4]), + ): + inputs = [0.0] * len(lanes) + expected = [want] * len(lanes) + for subgroup_size in (32, 64): + with self.subTest(case=name, subgroup_size=subgroup_size): + self.assertEqual(run_ps(spv, subgroup_size, inputs, lanes), expected) + if __name__ == "__main__": unittest.main() diff --git a/tests/semantic/test_wave64_cross_half.py b/tests/semantic/test_wave64_cross_half.py index 13a7f15387..52f7fd9828 100644 --- a/tests/semantic/test_wave64_cross_half.py +++ b/tests/semantic/test_wave64_cross_half.py @@ -13,12 +13,10 @@ on 32-wide subgroups). The tests pin which results stay exact there and which do not: - ds_bpermute_b32 never crosses halves, so all eight words stay exact; - v_writelane_b32 writes the right lane in both halves (the wave lane comes from LocalInvocationIndex); - - a v_readlane_b32 from the other half shuffles from lane >= 32 of a 32-wide subgroup, which SPIR-V leaves - undefined. Strictly that is UndefinedResult. Under the wrap model (lane Id mod 32, the symptom in issue - #94, an observation and not the specification) the expected words below are what a 32-wide GPU without - --wave64-emulate shows. Measured: NVIDIA GeForce RTX 4070 SUPER (subgroup 32), driver 610.88, Vulkan SDK - 1.4.363.0, `vk_compute_test .spv 1 dump` on the non-emulated build of run_gpu_tests.py: all 24 - words equal WRAP32_EXPECTED. That is one driver's behaviour, not a requirement. + - a v_readlane_b32 from the other half asks for lane >= 32 of a 32-wide subgroup; the translator's present-lane + ballot guard detects that lane as absent and redirects the shuffle to the subgroup's first running lane instead + of issuing an out-of-range shuffle (no SPIR-V UB, still different from the 64-wide result without + --wave64-emulate). SUBGROUP32_EXPECTED pins those exact per-half words. Limits: --wave64-emulate output uses Workgroup memory and a round loop, which the interpreter rejects, so the emulated path is covered only by the GPU tests. The subgroup layout (invocation i in subgroup i // 32) is the @@ -45,16 +43,15 @@ "cs_w64x_bpermute": [36, 316, 253, 218, 435, 225, 0, 442], } -# Two 32-wide subgroups, wrap model. readlane: v2 = 3 * lane + 1 and each subgroup reads lane (S1 % 64) % 32 of -# its own half. The low half reads lane 8 for lane 40 (25), lane 0 for 32 (1) and lane 1 for 33 (4); the upper -# half reads lane 32 + 5 = 37 for lane 5 (112). Words stored by lanes of the half the source lane is in stay right: -# out[0] lane 0: s6 = v2[8] = 25 out[1] lane 33: s6 = v2[40] = 121 out[2] lane 63: s7 = v2[37] = 112 -# out[3] lane 0: s8 = v2[0] = 1 out[4] lane 45: s7 = v2[37] = 112 out[5] lane 7: s9 = v2[1] = 4 -# out[6] lane 60: s9 = v2[33] = 100 out[7] lane 63: v2[40] = 121 -# writelane: the writes are exact, the two readlanes from lanes 0 and 8 read lanes 8 and 31 of the low half, -# which nobody wrote (0). -WRAP32_EXPECTED = { - "cs_w64x_readlane": [25, 121, 112, 1, 112, 4, 100, 121], +# Two 32-wide subgroups with present-lane guarded v_readlane_b32: lane >= 32 is absent in both 32-wide subgroups, so +# it redirects to each subgroup's first running lane (lane 0 -> 1 in subgroup 0, lane 32 -> 97 in subgroup 1), while +# lane 5 is present in both (lane 5 -> 16 in subgroup 0, lane 32+5=37 -> 112 in subgroup 1): +# out[0] lane 0: s6 = v2[0] = 1 out[1] lane 33: s6 = v2[32] = 97 out[2] lane 63: s7 = v2[37] = 112 +# out[3] lane 0: s8 = v2[0] = 1 out[4] lane 45: s7 = v2[37] = 112 out[5] lane 7: s9 = v2[0] = 1 +# out[6] lane 60: s9 = v2[32] = 97 out[7] lane 63: s11 = v2[32] = 97 +# writelane: the writes are exact, the two readlanes from lanes 40 and 63 redirect to lane 0 of subgroup 0 (0). +SUBGROUP32_EXPECTED = { + "cs_w64x_readlane": [1, 97, 112, 1, 112, 1, 97, 97], "cs_w64x_writelane": [4660, 77, 99, 2748, 0, 0, 0, 0], "cs_w64x_bpermute": GPU_EXPECTED["cs_w64x_bpermute"], } @@ -92,23 +89,19 @@ def test_bpermute_stays_exact(self): spv = translate("cs_w64x_bpermute") self.assertEqual(run(spv, 32), GPU_EXPECTED["cs_w64x_bpermute"]) - def test_cross_half_readlane_is_undefined(self): - for name in ("cs_w64x_readlane", "cs_w64x_writelane"): + def test_cross_half_readlane_redirects_without_ub(self): + # Present-lane ballot guard prevents UndefinedResult on a 32-wide subgroup, redirecting absent lanes + # >= 32 to the subgroup's first running lane (still not exact for cross-half reads without emulation). + for name, want in SUBGROUP32_EXPECTED.items(): with self.subTest(shader=name): - with self.assertRaisesRegex(si.UndefinedResult, r"lane 40 of a 32-wide subgroup"): - run(translate(name), 32) - - def test_wrap_model_prediction(self): - for name, want in WRAP32_EXPECTED.items(): - with self.subTest(shader=name): - got = run(translate(name), 32, out_of_range="wrap") + got = run(translate(name), 32) self.assertEqual(got, want) wrong = [k for k in range(8) if got[k] != GPU_EXPECTED[name][k]] self.assertEqual(bool(wrong), name != "cs_w64x_bpermute", f"{name}: words {wrong} differ") def test_writelane_writes_are_exact(self): # out[0..5] are the written lanes and their untouched neighbours; only the readlanes (out[6..7]) cross. - got = run(translate("cs_w64x_writelane"), 32, out_of_range="wrap") + got = run(translate("cs_w64x_writelane"), 32) self.assertEqual(got[:6], GPU_EXPECTED["cs_w64x_writelane"][:6]) @@ -126,7 +119,7 @@ def sabotage(self, name, pattern, repl, count): def test_readlane_lane_select_mod_32(self): # v_readlane lane = S1 & 31 instead of & 63 (the issue #94 symptom, moved into the translator). got = self.sabotage("cs_w64x_readlane", - r"(OpBitwiseAnd %uint \S+ )%c3f(\n\s*%\w+ = OpGroupNonUniformShuffle)", r"\1%c1f\2", 5) + r"(OpBitwiseAnd %uint \S+ )%c3f(\n\s*%\w+ = OpGroupNonUniformBallot )", r"\1%c1f\2", 5) self.assertEqual(got[0], 25) # lane 40 -> lane 8 def test_bpermute_upper_half_reads_low_half(self): diff --git a/tests/semantic/test_wave64_emulate_opt.py b/tests/semantic/test_wave64_emulate_opt.py index 257429f72e..259ae2f1a5 100644 --- a/tests/semantic/test_wave64_emulate_opt.py +++ b/tests/semantic/test_wave64_emulate_opt.py @@ -399,7 +399,11 @@ def step_until_barrier(inv, step_budget): vals[res] = push_constants[w] if 0 <= w < len(push_constants) else 0 elif p[0] == "psb": assert p[1] % 4 == 0, f"unaligned PSB load {p[1]:#x}" - vals[res] = memory.get(p[1], 0) + kind = types.get(a[0], ("",)) + if kind[0] == "vec": # a uvecN: scalar_load's wide loads read N consecutive words + vals[res] = [memory.get(p[1] + 4 * i, 0) for i in range(kind[2])] + else: + vals[res] = memory.get(p[1], 0) else: v = p[0][p[1]] vals[res] = list(v) if isinstance(v, list) else v diff --git a/tests/semantic/test_wave64_halves.py b/tests/semantic/test_wave64_halves.py index ff4eba4631..a9e419b75f 100644 --- a/tests/semantic/test_wave64_halves.py +++ b/tests/semantic/test_wave64_halves.py @@ -1362,10 +1362,6 @@ def test_ps_w64_fixtures(self): for c in range(4): if exp[c] is not None: self.assertEqual(w64[lane][c], exp[c], f"{name} wave64 lane {lane} c{c}") - if name == "ps_w64_c_readlane": - with self.assertRaises(wi.UnsupportedConstruct): - _run_ps_cut(asm, 32, push=push) - continue w32 = _run_ps_cut(asm, 32, push=push, memory=mem32) if tier in ("A", "B"): self.assertEqual(w32, w64) diff --git a/tests/semantic/test_wide_scalar_load.py b/tests/semantic/test_wide_scalar_load.py new file mode 100644 index 0000000000..3754055c01 --- /dev/null +++ b/tests/semantic/test_wide_scalar_load.py @@ -0,0 +1,101 @@ +"""Multi-dword scalar loads as the fewest wide loads (uvec4, then uvec2), with the out-of-range result unchanged. + +s_buffer_load_dwordxN: dword i is 0, and memory is not read, when off + 4*i + 4 > limit (docs/design.md, +Scalar/buffer memory, measured on gfx1030 and gfx1036). The ends grow with i, so when the last dword is in range all +are: Gen.scalar_load then reads the N dwords as uvec4 / uvec2 loads, one branch for the whole instruction, and keeps +the per-dword path (in range: read; out of range: 0, not read) for a load that is partly out of range. s_load_dwordxN +has no bound and is always wide. The per-dword form made RADV emit one global_load_b32, one v_readfirstlane and one +64-bit compare per dword (6,048 / 5,935 / 5,448 in one FSPX program with 365 s_buffer_load_dwordx16). + +cs_wide_scalar_load.asm takes its V# from user SGPRs, so the bound is a run-time value: the fast path and the +per-dword path both run. test_scalar_mem_smem.py checks the addresses for every hardware rule on the same code. + + python -m unittest discover -s tests/semantic -p test_wide_scalar_load.py +""" +from pathlib import Path +import os +import sys +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +if HERE not in sys.path: + sys.path.insert(0, HERE) + +import support # noqa: E402 +import test_value_semantics as tv # noqa: E402 + +OUT = 0x2000 +OUT_V = 0x31016FAC # raw output V#, 0x100 bytes at OUT (as test_null_vsharp) +CB = 0x4000 # the constant buffer +CB_BYTES = 0x48 # NUM_RECORDS: 18 dwords +PTR = 0x6000 # the s_load pointer +# 12 user SGPRs: s[0:3] output V#, s[4:7] the constant buffer's V#, s[8:9] a pointer; 64x1x1 threads. +FSSM = tv._fssm(12 << 1, (64, 1, 1)) + + +def word(address): + return 0xA0000000 | address + + +class WideScalarLoad(unittest.TestCase): + def run_fixture(self): + text = support.translate_listing("cs_wide_scalar_load", + (Path(HERE) / "fixtures" / "cs_wide_scalar_load.asm").read_bytes(), + fssm=FSSM) + mem = tv.ReadLog({a: word(a) for base in (CB, PTR) for a in range(base, base + 0x100, 4)}) + support.run_fragment(text, inputs={"%wg_id": (0, 0, 0), "%local_id": (0, 0, 0)}, + push_constants=[OUT, 0, 0x100, OUT_V, CB, 0, CB_BYTES, OUT_V, PTR, 0] + [0] * 22, + memory=mem) + return text, mem + + def test_values(self): + _, mem = self.run_fixture() + got = [dict.get(mem, OUT + 4 * i) for i in range(16)] + self.assertEqual(got, [ + word(CB), word(CB + 0x14), word(CB + 0x28), word(CB + 0x3C), # x16 at 0, in range + word(CB + 0x40), word(CB + 0x44), 0, 0, # x8 at 0x40: dwords 18.. are 0 + word(CB + 0x10), word(CB + 0x1C), word(CB + 0x44), 0, # x4 at 0x10; x2 at 0x44: 2nd is 0 + word(PTR), word(PTR + 0xC), word(PTR + 0x10), word(PTR + 0x1C), # s_load_dwordx8, no bound + ]) + + def test_nothing_out_of_range_is_read(self): + _, mem = self.run_fixture() + cb_reads = sorted({a for a in mem.reads if CB <= a < CB + 0x100}) + self.assertEqual(cb_reads, list(range(CB, CB + CB_BYTES, 4))) + + def test_the_loads_are_wide(self): + text, _ = self.run_fixture() + # x16: 4, x8: 2, x4: 1, s_load x8: 2 uvec4 loads; x2: 1 uvec2 load. Each s_buffer_load width also emits + # ONE compact counted-loop fallback helper (%sbuf_slow_ro_x{2,4,8,16}) with a single OpLoad in its loop body + # (4 dword loads total, running only when partly out of range); the s_load has none. + self.assertEqual(text.count("OpLoad %v4uint_sl"), 9) + self.assertEqual(text.count("OpLoad %v2uint_sl"), 1) + self.assertEqual(sum("OpLoad %uint" in ln and "Aligned 4" in ln for ln in text.splitlines()), 4) + + def test_a_destination_that_is_its_own_vsharp(self): + # cs_wide_scalar_load_overlap.asm: s_buffer_load_dwordx4 s[20:23], s[20:23] with its V# from memory, under + # every NUM_RECORDS from nothing to all of both buffers; the dwords out of range are 0 and not read. + text = support.translate_listing("cs_wide_scalar_load_overlap", + (Path(HERE) / "fixtures" / "cs_wide_scalar_load_overlap.asm").read_bytes(), + fssm=tv._fssm(10 << 1, (64, 1, 1))) + cb0, cb1, table = 0x4000, 0x5000, 0x6000 + + def cb(base, nr, off): + return word(base + off) if off + 4 <= nr else 0 + for nr0 in (0, 4, 8, 12, 16, 20, 24, 0x100): + for nr1 in (0, 4, 8, 12, 16, 0x100): + with self.subTest(nr0=nr0, nr1=nr1): + mem = tv.ReadLog({a: word(a) for base in (cb0, cb1) for a in range(base, base + 0x40, 4)}) + mem.update({table: cb1, table + 4: 0, table + 8: nr1, table + 12: 0}) + support.run_fragment(text, inputs={"%wg_id": (0, 0, 0), "%local_id": (0, 0, 0)}, + push_constants=[OUT, 0, 0x100, OUT_V, cb0, 0, nr0, 0, table, 0] + [0] * 22, + memory=mem) + self.assertEqual([dict.get(mem, OUT + 4 * i) for i in range(8)], + [cb(cb0, nr0, 0), cb(cb0, nr0, 4), cb(cb1, nr1, 0), cb(cb1, nr1, 4), + cb(cb1, nr1, 8), cb(cb1, nr1, 12), cb(cb0, nr0, 8), cb(cb0, nr0, 20)]) + self.assertFalse([a for a in mem.reads if (cb0 <= a < cb0 + 0x40 and a - cb0 + 4 > nr0) or + (cb1 <= a < cb1 + 0x40 and a - cb1 + 4 > nr1)]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_writes_buffer_meta.py b/tests/semantic/test_writes_buffer_meta.py new file mode 100644 index 0000000000..75b0742d7a --- /dev/null +++ b/tests/semantic/test_writes_buffer_meta.py @@ -0,0 +1,151 @@ +"""Buffer-write metadata (`writes_buffer` and `buffer_write_slots`) tests (Item 3B.7). + +Verifies the agreed runtime metadata contract: + * `meta["writes_buffer"]` is always emitted (`bool`): + - `False` for read-only buffer shaders, image-store/image-atomic-only shaders, and LDS-only shaders. + - `True` for any shader with buffer/tbuffer/global/flat/scalar buffer stores or atomics. + * `meta["buffer_write_slots"]` is always emitted: + - `[]` when `writes_buffer == False`. + - Sorted list of integer root/table descriptor offsets when every buffer write is statically traceable. + - `"dynamic"` when any buffer store or atomic base cannot be statically traced. +""" +import unittest + +import support +import rdna2spirv + +EPILOGUE = ["exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] + + +def translate_meta(name, lines): + asm = support.translate_lines(name, lines) + return rdna2spirv.shader_meta(rdna2spirv.translate.last_gen, asm) + + +class WritesBufferMetaTests(unittest.TestCase): + def test_read_only_shader_has_writes_buffer_false(self): + meta = translate_meta("ps_ro_buf", [ + "v_mov_b32 v1, 0", + "buffer_load_dword v0, v1, s[4:7], 0 offen", + "global_load_dword v2, v1, s[0:1]", + "s_load_dword s8, s[0:1], 0", + "s_waitcnt vmcnt(0) lgkmcnt(0)", + ] + EPILOGUE) + self.assertIs(meta["writes_buffer"], False) + self.assertEqual(meta["buffer_write_slots"], []) + + def test_image_store_and_image_atomic_only_have_writes_buffer_false(self): + meta_store = translate_meta("ps_img_store_only", [ + "v_mov_b32 v0, 0x3f800000", + "v_mov_b32 v4, 1", + "v_mov_b32 v5, 2", + "image_store v[0:3], v[4:5], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_2D unorm", + "s_waitcnt vmcnt(0)", + ] + EPILOGUE) + self.assertIs(meta_store["writes_buffer"], False) + self.assertEqual(meta_store["buffer_write_slots"], []) + + meta_atom = translate_meta("ps_img_atomic_only", [ + "v_mov_b32 v0, 1", + "v_mov_b32 v4, 1", + "v_mov_b32 v5, 2", + "image_atomic_add v0, v[4:5], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc", + "s_waitcnt vmcnt(0)", + ] + EPILOGUE) + self.assertIs(meta_atom["writes_buffer"], False) + self.assertEqual(meta_atom["buffer_write_slots"], []) + + def test_buffer_store_root_vsharp_is_traceable(self): + meta = translate_meta("ps_buf_st_root", [ + "v_mov_b32 v0, 1", + "v_mov_b32 v1, 0", + "buffer_store_dword v0, v1, s[4:7], 0 offen", + "s_waitcnt vmcnt(0)", + ] + EPILOGUE) + self.assertIs(meta["writes_buffer"], True) + self.assertEqual(meta["buffer_write_slots"], [4]) + + def test_buffer_store_table_vsharp_at_const_offsets_is_traceable(self): + meta = translate_meta("ps_buf_st_table", [ + "s_mov_b32 s1, 0", + "s_load_dwordx4 s[8:11], s[0:1], 0x80", + "s_load_dwordx4 s[12:15], s[0:1], 0x40", + "s_waitcnt lgkmcnt(0)", + "v_mov_b32 v0, 1", + "v_mov_b32 v1, 0", + "buffer_store_dword v0, v1, s[8:11], 0 offen", + "buffer_store_format_x v0, v1, s[12:15], 0 offen", + "s_waitcnt vmcnt(0)", + ] + EPILOGUE) + self.assertIs(meta["writes_buffer"], True) + self.assertEqual(meta["buffer_write_slots"], [64, 128]) + + def test_buffer_atomic_sets_writes_buffer_true(self): + meta = translate_meta("ps_buf_atom", [ + "v_mov_b32 v0, 1", + "v_mov_b32 v1, 0", + "buffer_atomic_add v0, v1, s[4:7], 0 offen glc", + "s_waitcnt vmcnt(0)", + ] + EPILOGUE) + self.assertIs(meta["writes_buffer"], True) + self.assertEqual(meta["buffer_write_slots"], [4]) + + def test_global_store_and_atomic_root_vs_dynamic(self): + meta_root = translate_meta("ps_glob_st_root", [ + "v_mov_b32 v0, 1", + "v_mov_b32 v1, 0", + "global_store_dword v1, v0, s[2:3]", + "s_waitcnt vmcnt(0)", + ] + EPILOGUE) + self.assertIs(meta_root["writes_buffer"], True) + self.assertEqual(meta_root["buffer_write_slots"], [2]) + + meta_dyn = translate_meta("ps_glob_st_dyn", [ + "v_mov_b32 v0, 0x1000", + "v_mov_b32 v1, 0", + "v_mov_b32 v2, 7", + "global_store_dword v[0:1], v2, off", + "s_waitcnt vmcnt(0)", + ] + EPILOGUE) + self.assertIs(meta_dyn["writes_buffer"], True) + self.assertEqual(meta_dyn["buffer_write_slots"], "dynamic") + + meta_gatom = translate_meta("ps_glob_atom_dyn", [ + "v_mov_b32 v0, 0x1000", + "v_mov_b32 v1, 0", + "v_mov_b32 v2, 7", + "global_atomic_add v3, v[0:1], v2, off glc", + "s_waitcnt vmcnt(0)", + ] + EPILOGUE) + self.assertIs(meta_gatom["writes_buffer"], True) + self.assertEqual(meta_gatom["buffer_write_slots"], "dynamic") + + def test_dynamic_table_vsharp_store_reports_dynamic_slots(self): + meta = translate_meta("ps_buf_st_dyn_tab", [ + "s_mov_b32 s1, 0", + "s_load_dwordx4 s[8:11], s[0:1], s2", + "s_waitcnt lgkmcnt(0)", + "v_mov_b32 v0, 1", + "v_mov_b32 v1, 0", + "buffer_store_dword v0, v1, s[8:11], 0 offen", + "s_waitcnt vmcnt(0)", + ] + EPILOGUE) + self.assertIs(meta["writes_buffer"], True) + self.assertEqual(meta["buffer_write_slots"], "dynamic") + + def test_scalar_atomics_set_writes_buffer_true(self): + import shader_ir + import shader_meta + for line, want_slots in ( + ("s_atomic_add s4, s[0:1], 0", [0]), + ("s_buffer_atomic_add s8, s[4:7], 0", [4]), + ): + with self.subTest(line=line): + insns = [shader_ir.parse_line(line), shader_ir.parse_line("s_endpgm")] + info = shader_meta.analyse_instructions([insns], [[]]) + self.assertIs(info["writes_buffer"], True) + self.assertEqual(info["buffer_write_slots"], want_slots) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_absent_lane_gpu.py b/tests/test_absent_lane_gpu.py new file mode 100644 index 0000000000..bf4ecddfc3 --- /dev/null +++ b/tests/test_absent_lane_gpu.py @@ -0,0 +1,190 @@ +"""GPU regression test for absent-lane / inactive-lane subgroup safety on partial waves. + +Translates small hand-written synthetic RDNA2 shaders (wave32 5-thread partial CS, 1x1 partial-quad +wave32 PS, and 1x1 partial-quad wave64 PS) exercising `v_readfirstlane_b32` with `EXEC == 0` feeding +`s_load_dword`, `ds_append` with `EXEC == 0`, mixed-VGPR `v_writelane_b32`/`v_readlane_b32` on an +absent lane (lane 19), `v_permlanex16_b32` `FI=1` reading absent lane 16, `dpp8 fi:1` reading absent +lane 7, and `s_wqm_b32` on a partial quad. Assembles with `spirv-as`, validates with `spirv-val`, +verifies with `check_absent_lane_ub`, and executes via `vk_compute_test` and `vk_ps_sweep`. + +Set `MESA_VK_DEVICE_SELECT` (e.g. `1002:164e!`) and `LEONIDA_VK_VALIDATION=1` as needed. +Skips cleanly when `spirv-as`, `spirv-val`, or the built Vulkan test binaries are absent. +""" +import os +import shutil +import struct +import subprocess +import sys +import tempfile +import unittest + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +SEMANTIC = os.path.join(ROOT, "tests", "semantic") +if SEMANTIC not in sys.path: + sys.path.insert(0, SEMANTIC) + +import check_absent_lane_ub as checker # noqa: E402 +import support # noqa: E402 + +SPIRV_AS = shutil.which("spirv-as") +SPIRV_VAL = shutil.which("spirv-val") +VK_COMPUTE = os.path.join(ROOT, "runtime", "build", "vk_compute_test") +VK_PS_SWEEP = os.path.join(ROOT, "runtime", "build", "vk_ps_sweep") + +FULLSCREEN_VS_SPVASM = """OpCapability Shader +OpMemoryModel Logical GLSL450 +OpEntryPoint Vertex %main "main" %vid %pos +OpDecorate %vid BuiltIn VertexIndex +OpDecorate %pos BuiltIn Position +%void = OpTypeVoid +%bool = OpTypeBool +%fn = OpTypeFunction %void +%uint = OpTypeInt 32 0 +%float = OpTypeFloat 32 +%v4f = OpTypeVector %float 4 +%pin_u = OpTypePointer Input %uint +%pout_v4 = OpTypePointer Output %v4f +%vid = OpVariable %pin_u Input +%pos = OpVariable %pout_v4 Output +%c1 = OpConstant %uint 1 +%c2 = OpConstant %uint 2 +%fm1 = OpConstant %float -1.0 +%f3 = OpConstant %float 3.0 +%f0 = OpConstant %float 0.0 +%f1 = OpConstant %float 1.0 +%main = OpFunction %void None %fn +%entry = OpLabel +%i = OpLoad %uint %vid +%is1 = OpIEqual %bool %i %c1 +%is2 = OpIEqual %bool %i %c2 +%x = OpSelect %float %is1 %f3 %fm1 +%y = OpSelect %float %is2 %f3 %fm1 +%p = OpCompositeConstruct %v4f %x %y %f0 %f1 +OpStore %pos %p +OpReturn +OpFunctionEnd +""" + + +def assemble_and_check(spv_text, out_spv): + asm_path = out_spv + ".spvasm" + with open(asm_path, "w", encoding="utf-8") as f: + f.write(spv_text) + subprocess.run([SPIRV_AS, "--target-env", "vulkan1.3", asm_path, "-o", out_spv], check=True) + subprocess.run([SPIRV_VAL, "--target-env", "vulkan1.3", out_spv], check=True) + with open(out_spv, "rb") as f: + raw = f.read() + viols = checker.check_absent_lane_ub(raw) + if viols: + raise AssertionError(f"absent-lane UB violations in {out_spv}: {viols}") + + +@unittest.skipUnless(SPIRV_AS and SPIRV_VAL, "requires spirv-as and spirv-val") +class PartialWaveGpuTests(unittest.TestCase): + @unittest.skipUnless(os.path.isfile(VK_COMPUTE), "requires built runtime/build/vk_compute_test") + def test_partial_wave_compute_5_threads(self): + hdr = bytearray(0x148) + struct.pack_into("> 17) & 0xFFFFFFFF + x ^= (x << 5) & 0xFFFFFFFF + want_word0 = 0x3E800000 + (x % 0x01000000) + + for tag, exec_init, exec_zero, exec_all in ( + ("ps_w32", [], ["s_mov_b32 exec_lo, 0"], ["s_mov_b32 exec_lo, -1"]), + ("ps_w64", ["s_mov_b64 exec, -1"], ["s_mov_b64 exec, 0"], ["s_mov_b64 exec, -1"]), + ): + with self.subTest(stage=tag): + ps_text = support.translate_lines(tag + "_gpu_partial_1x1", exec_init + [ + "v_mov_b32_e32 v4, 0", + "v_mov_b32_e32 v5, 0", + ] + exec_zero + [ + "v_readfirstlane_b32 s10, v4", + "v_readfirstlane_b32 s11, v5", + "s_load_dword s12, s[10:11], 0x0", + "s_waitcnt lgkmcnt(0)", + ] + exec_all + [ + "v_mov_b32_e32 v20, 0x9999", + "s_mov_b32 s14, 0x3f800000", + "v_writelane_b32 v20, s14, 19", + "s_mov_b32 s14, 0", + "v_readlane_b32 s15, v20, 19", + "v_mov_b32_e32 v2, 50", + "v_permlanex16_b32 v6, v2, 0, 0 op_sel:[1,0]", + "v_add_nc_u32_dpp v7, v2, 2 dpp8:[7,7,7,7,7,7,7,7] fi:1", + "v_mov_b32_e32 v8, s12", + "v_mov_b32_e32 v9, s15", + "exp mrt0 v8, v9, v6, v7 done vm", + "s_endpgm", + ]) + ps_spv = os.path.join(td, tag + ".spv") + assemble_and_check(ps_text, ps_spv) + out_raw = os.path.join(td, tag + ".raw") + env = dict(os.environ, VKS_HEAP_FILL="0,16,7") + p = subprocess.run([VK_PS_SWEEP, vs_spv, ps_spv, out_raw, "1", "1", "1"], + env=env, capture_output=True, text=True) + self.assertEqual(p.returncode, 0, p.stdout + "\n" + p.stderr) + with open(out_raw, "rb") as f: + got = struct.unpack("<4I", f.read()) + self.assertEqual(got, (want_word0, 0x3F800000, 0, 2)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_desc_cache.py b/tests/test_desc_cache.py index 584d9a94c4..c0b5cb88c0 100644 --- a/tests/test_desc_cache.py +++ b/tests/test_desc_cache.py @@ -235,11 +235,16 @@ def test_lookup_result_is_broadcast_before_use(): bcast[ln.split()[0]] = ln.split()[-2] extracts = {ln.split()[0]: ln.split()[-2] for ln in lines if "OpCompositeExtract %uint" in ln and ln.split()[-2] in results} + # The T# here is in user SGPRs, no heap slot, so it is looked up, and the index word in its dword 6 is preferred + # where it carries the tag (docs/design.md, "Bindless index in the T#"): an OpPhi of the word and the extract, + # the lookup running only without the word (OpPhi %uint word pre lookup probe). + selects = {ln.split()[0]: ln.split()[-2] for ln in lines + if "OpPhi %uint" in ln and ln.split()[-2] in extracts} # A tagged entry returns (index, kind): each component is broadcast before use, so a broadcast reads the - # call or an extract of it. + # call, an extract of it, or that phi. assert results and bcast, (results, bcast) - assert all(src in results or extracts.get(src) in results for src in bcast.values()), \ - (results, extracts, bcast) + assert all(src in results or extracts.get(src) in results or extracts.get(selects.get(src)) in results + for src in bcast.values()), (results, extracts, selects, bcast) assert "OpCapability GroupNonUniform" in lines assert "OpCapability GroupNonUniformBallot" in lines or "OpCapability GroupNonUniformShuffle" in lines for ln in lines: diff --git a/tests/test_f64_float_controls.py b/tests/test_f64_float_controls.py index 0b14dfaa71..39bd345d5e 100644 --- a/tests/test_f64_float_controls.py +++ b/tests/test_f64_float_controls.py @@ -44,10 +44,10 @@ def test_f64_module_declares_the_64_bit_mode(self): self.assertIn(MODE_64, spv) # Core since SPIR-V 1.4, as for the 32-bit mode: no SPV_KHR_float_controls at vulkan1.2. self.assertNotIn("SPV_KHR_float_controls", spv) - # DenormPreserve 16 (SHADER-526) is declared in every module and its property comes after the two widths. + # DenormPreserve 16 (SHADER-526) and DenormFlushToZero 32 follow the SignedZeroInfNanPreserve widths. self.assertEqual(meta["float_controls"], ["shaderSignedZeroInfNanPreserveFloat32", "shaderSignedZeroInfNanPreserveFloat64", - "shaderDenormPreserveFloat16"]) + "shaderDenormPreserveFloat16", "shaderDenormFlushToZeroFloat32"]) self.assertIn("shaderFloat64", meta["features"]) def test_module_without_float64_keeps_only_the_32_bit_mode(self): @@ -56,7 +56,8 @@ def test_module_without_float64_keeps_only_the_32_bit_mode(self): self.assertIn(MODE_32, spv) self.assertNotIn(MODE_64, spv) self.assertEqual(meta["float_controls"], - ["shaderSignedZeroInfNanPreserveFloat32", "shaderDenormPreserveFloat16"]) + ["shaderSignedZeroInfNanPreserveFloat32", "shaderDenormPreserveFloat16", + "shaderDenormFlushToZeroFloat32"]) def test_no_float_controls_leaves_out_both_widths(self): saved = rdna2spirv.FLOAT_CONTROLS @@ -68,6 +69,7 @@ def test_no_float_controls_leaves_out_both_widths(self): self.assertIn("OpCapability Float64", spv) self.assertNotIn("SignedZeroInfNanPreserve", spv) self.assertNotIn("DenormPreserve", spv) + self.assertNotIn("DenormFlushToZero", spv) self.assertNotIn("float_controls", meta) diff --git a/tests/test_image_load_typed.py b/tests/test_image_load_typed.py index a57eaa8e64..fb1843834d 100644 --- a/tests/test_image_load_typed.py +++ b/tests/test_image_load_typed.py @@ -127,12 +127,20 @@ def value(self, x, word1, index, regs=None): return regs[p[1], r] if p[1] == "%vgpr" and self.vgprs is not None: return self.vgprs[r] - assert (p[1], r) == ("%sgpr", 1), "only T# word 1 is read" - return word1 + if (p[1], r) == ("%sgpr", 1): + return word1 + # The T# (s[0:7]) is not from a heap slot, so it is looked up, and its dword 6 wins where it carries + # the index tag (dword 3 says it names an image): 0 in both here, so the lookup's index is used. + assert (p[1], r) in (("%sgpr", 3), ("%sgpr", 6)), "only T# words 1, 3 and 6 are read" + return 0 var_op, v = self.defs[p[1]] assert var_op == "OpVariable" and v[1] == "Private", (var_op, v) words = self.defs[v[2]][1][1:] # OpConstantComposite %fmt_mask_arr return get(words[get(p[2])]) + if op == "OpPhi": + # The T#'s index: the dword-6 word or the lookup, which runs only without the word. The T# words read + # 0 here (below), so the word has no tag and the lookup's side (the second pair) is the value. + return get(a[3]) if op == "OpGroupNonUniformBroadcastFirst": # One invocation: return the value (a[1] is the scope). return get(a[2]) if op == "OpGroupNonUniformShuffle": # One invocation; subgroup shuffle returns its input. @@ -152,8 +160,12 @@ def value(self, x, word1, index, regs=None): return (u[0] >> u[1]) & ((1 << u[2]) - 1) if op == "OpShiftRightLogical": return u[0] >> u[1] + if op == "OpShiftLeftLogical": + return (u[0] << u[1]) & 0xffffffff if op == "OpBitwiseAnd": return u[0] & u[1] + if op == "OpBitwiseOr": + return u[0] | u[1] if op == "OpINotEqual": return u[0] != u[1] if op == "OpIEqual": diff --git a/tests/test_make_game_translator_flags.py b/tests/test_make_game_translator_flags.py index ffae8710d9..ec42a13275 100644 --- a/tests/test_make_game_translator_flags.py +++ b/tests/test_make_game_translator_flags.py @@ -191,7 +191,7 @@ class MainWiringTest(unittest.TestCase): """main() parses the fallback flags and hands the same tuple to preflight() and shaders().""" def run_main(self, *extra_argv, per_vertex=None, barycentric_fallback=None, max_push_constants=None, - mesh_crash=False): + mesh_crash=False, integer_dot=True): # An empty --out: main() reads the flags an existing translation was made with, and the default folder # is the user's own. out = tempfile.TemporaryDirectory() @@ -206,6 +206,7 @@ def run_main(self, *extra_argv, per_vertex=None, barycentric_fallback=None, max_ mock.patch("make_game.runtime_gpu_barycentric_fallback", return_value=barycentric_fallback), \ mock.patch("make_game.runtime_gpu_max_push_constants", return_value=max_push_constants), \ mock.patch("make_game.runtime_gpu_mesh_draws_crash", return_value=mesh_crash), \ + mock.patch("make_game.runtime_gpu_integer_dot_product", return_value=integer_dot), \ mock.patch("make_game.preflight") as preflight, \ mock.patch("make_game.shaders") as shaders, \ mock.patch("make_game.log"): @@ -264,6 +265,21 @@ def test_runtime_gpu_barycentric_fallback_requires_a_boolean_probe_result(self): with self.subTest(raw=raw), mock.patch("make_game.runtime_gpu_info", return_value=raw): self.assertIs(make_game.runtime_gpu_barycentric_fallback(), want) + def test_integer_dot_fallback_follows_the_device(self): + """On by itself where the GPU has no shaderIntegerDotProduct (a Vulkan 1.2 device), not where it has it or + can't tell; asked for explicitly, it is on everywhere.""" + self.assertEqual(self.run_main(integer_dot=False), (("--integer-dot-fallback",),) * 2) + self.assertEqual(self.run_main(integer_dot=True), ((), ())) + self.assertEqual(self.run_main(integer_dot=None), ((), ())) + self.assertEqual(self.run_main("--integer-dot-fallback", integer_dot=True), + (("--integer-dot-fallback",),) * 2) + + def test_runtime_gpu_integer_dot_product_requires_a_boolean_probe_result(self): + for raw, want in (({"integer_dot_product": True}, True), ({"integer_dot_product": False}, False), + ({}, None), ({"integer_dot_product": 1}, None)): + with self.subTest(raw=raw), mock.patch("make_game.runtime_gpu_info", return_value=raw): + self.assertIs(make_game.runtime_gpu_integer_dot_product(), want) + def test_pc_tail_ubo_follows_the_device(self): """On by itself where maxPushConstantsSize is below what the shaders need (144, or 152 with --mesh-compute), not where it fits or can't be read; asked for explicitly, it is on everywhere.""" diff --git a/tests/test_translate.py b/tests/test_translate.py index cf84235c9e..eabea55d82 100644 --- a/tests/test_translate.py +++ b/tests/test_translate.py @@ -829,15 +829,18 @@ def test_wave32_bpermute_zeroes_inactive_and_missing_source_lanes(make_shader): assert not rdna2spirv.translate.last_gen.wave64 shuffle = re.search( r"(%t\d+) = OpSelect %uint (%t\d+) %t\d+ %c0\n\s*" + r"(?:(?P%t\d+) = OpLoad %uint %sg_lane\n\s*)?" r"(%t\d+) = OpGroupNonUniformBallot %v4uint_bal %c3 %true\n\s*" - r"(%t\d+) = OpGroupNonUniformBallotBitExtract %bool %c3 \3 (%t\d+)\n\s*" - r"(%t\d+) = OpSelect %uint \4 \5 %t\d+\n\s*" - r"(%t\d+) = OpGroupNonUniformShuffle %uint %c3 \1 \6\n\s*" - r"(%t\d+) = OpSelect %uint \4 %cffffffff %c0\n\s*" - r"(?P%t\d+) = OpBitwiseAnd %uint \7 \8\n", + r"(%t\d+) = OpGroupNonUniformBallotBitExtract %bool %c3 \4 (%t\d+)\n\s*" + r"(%t\d+) = OpSelect %uint \5 \6 (%t\d+)\n\s*" + r"(%t\d+) = OpGroupNonUniformShuffle %uint %c3 \1 \7\n\s*" + r"(%t\d+) = OpSelect %uint \5 %cffffffff %c0\n\s*" + r"(?P%t\d+) = OpBitwiseAnd %uint \9 \10\n", asm, ) assert shuffle, "wave32 ds_bpermute must mask inactive and missing source lanes" + if shuffle.group("self") is not None: + assert shuffle.group(8) == shuffle.group("self"), "absent source lane must redirect to own subgroup lane" active_id = shuffle.group(2) assert (f"{active_id} = OpLoad %bool %active" in asm or f"OpStore %active {active_id}" in asm), \ "source mask must read the active lane predicate" @@ -848,14 +851,16 @@ def test_wave32_bpermute_zeroes_inactive_and_missing_source_lanes(make_shader): def test_wqm_on_a_lane_mask_gathers_the_quad_and_votes_scc(make_shader, monkeypatch): - """s_wqm on a lane mask ORs the lane's bit with its quad's (two OpGroupNonUniformQuadSwap, horizontal then - vertical) and SCC is the wave-wide any. Emulated, the four lanes of the quad come through %x_buf instead.""" + """s_wqm on a lane mask in compute gathers the lane's 4-bit quad nibble via ballot (safe on partial subgroups + without GroupNonUniformQuad or absent-lane shuffles) and SCC is the wave-wide any. Emulated, the four lanes + of the quad come through %x_buf instead.""" shader = make_shader(WQM_MASK, name="cs_wqm_mask_ci") asm = shader.translate() shader.validate(asm) - assert "OpCapability GroupNonUniformQuad" in asm - assert asm.count("OpGroupNonUniformQuadSwap %uint %c3") == 2 - assert re.search(r"OpGroupNonUniformQuadSwap %uint %c3 %t\d+ %c0\n(?:.*\n)*?.*OpGroupNonUniformQuadSwap %uint %c3 %t\d+ %c1\n", asm) + assert "OpCapability GroupNonUniformBallot" in asm + assert "QuadSwap" not in asm and "GroupNonUniformQuad" not in asm + assert "OpGroupNonUniformShuffle" not in asm + assert re.search(r"OpGroupNonUniformBallot %v4uint_bal %c3 %t\d+\n(?:.*\n)*?.*OpBitwiseAnd %uint %t\d+ %cf\n", asm) assert "OpGroupNonUniformAny" in asm # SCC: any bit of the result in the wave monkeypatch.setattr(rdna2spirv, "WAVE64_EMULATE", True) emulated = shader.translate() @@ -878,14 +883,15 @@ def test_wqm_on_data_is_a_bit_operation(make_shader): def test_wqm_without_quad_operations_outside_fragment_and_compute(make_shader): - """Quad operations are only guaranteed in fragment and compute shaders: a vertex shader shuffles from the four - lanes of the quad instead.""" + """Quad operations are only guaranteed in fragment shaders (with guaranteed 2x2 helper quads): a vertex shader + gathers the four lanes of its quad via ballot nibble extraction instead, avoiding absent-lane shuffles.""" shader = make_shader("v_cmp_gt_u32_e32 vcc_lo, 1, v0\ns_wqm_b32 s8, vcc_lo\nv_cndmask_b32_e64 v6, 0, 1, s8\n" "exp pos0 v6, v6, v6, v6 done\ns_endpgm\n", name="vs_wqm_ci") asm = shader.translate() shader.validate(asm) assert "QuadSwap" not in asm and "GroupNonUniformQuad" not in asm - assert asm.count("OpGroupNonUniformShuffle") == 4 + assert "OpGroupNonUniformShuffle" not in asm + assert re.search(r"OpGroupNonUniformBallot %v4uint_bal %c3 %t\d+\n(?:.*\n)*?.*OpBitwiseAnd %uint %t\d+ %cf\n", asm) def test_wave64_wqm_b32_changes_and_votes_only_its_half(make_shader): @@ -931,8 +937,14 @@ def test_float_controls_declared(stage, make_shader): assert "OpExecutionMode %main SignedZeroInfNanPreserve 32" in spv assert "OpCapability DenormPreserve" in spv assert "OpExecutionMode %main DenormPreserve 16" in spv + assert "OpCapability DenormFlushToZero" in spv + assert "OpExecutionMode %main DenormFlushToZero 32" in spv meta = rdna2spirv.shader_meta(rdna2spirv.translate.last_gen, spv) - assert meta["float_controls"] == ["shaderSignedZeroInfNanPreserveFloat32", "shaderDenormPreserveFloat16"] + assert meta["float_controls"] == [ + "shaderSignedZeroInfNanPreserveFloat32", + "shaderDenormPreserveFloat16", + "shaderDenormFlushToZeroFloat32", + ] def test_no_float_controls_leaves_them_out(make_shader, monkeypatch): @@ -944,6 +956,7 @@ def test_no_float_controls_leaves_them_out(make_shader, monkeypatch): shader.validate(spv) assert "SignedZeroInfNanPreserve" not in spv assert "DenormPreserve" not in spv + assert "DenormFlushToZero" not in spv meta = rdna2spirv.shader_meta(rdna2spirv.translate.last_gen, spv) assert "float_controls" not in meta @@ -1694,7 +1707,9 @@ def test_gather_d16_avoids_packhalf2x16(make_shader, suffix, last_addr): sh2.validate(asm2) assert "PackHalf2x16" not in asm2 assert "OpBitwiseOr %uint" in asm2 and "OpSelect %uint" in asm2 - for ty in ("%v4float", "%v4uint_st", "%v4int_st"): + uvec4 = re.search(r"(%\S+) = OpTypeVector %uint 4\b", asm2) + uvec4_ty = uvec4.group(1) if uvec4 else "%v4uint_st" + for ty in ("%v4float", uvec4_ty, "%v4int_st"): assert asm2.count(f"OpImageFetch {ty} ") == (0 if suffix == "lz" else 4) diff --git a/tests/test_vk_subgroup_info.py b/tests/test_vk_subgroup_info.py index 0ac52562f0..6e70e7f237 100644 --- a/tests/test_vk_subgroup_info.py +++ b/tests/test_vk_subgroup_info.py @@ -58,6 +58,7 @@ class FakeDevice: separate_depth_stencil_layouts: bool = True buffer_device_address: bool = True subgroup_size_control: bool = True + integer_dot_product: bool = True # shaderIntegerDotProduct, required by Vulkan 1.3 queue_flags: tuple[int, ...] = (vk_info.VK_QUEUE_GRAPHICS_BIT,) subgroup_size: int = 32 subgroup_supported_stages: int = ( @@ -249,6 +250,9 @@ def _get_physical_device_features2(self, phys_dev, p_features): ctypes.c_uint32.from_address( node_addr + vk_info.F13_DYNAMIC_RENDERING ).value = int(dev.dynamic_rendering) + ctypes.c_uint32.from_address( + node_addr + vk_info.F13_SHADER_INTEGER_DOT_PRODUCT + ).value = int(dev.integer_dot_product) elif stype == 1000044003: # VkPhysicalDeviceDynamicRenderingFeaturesKHR ctypes.c_uint32.from_address(node_addr + 16).value = int(dev.dynamic_rendering) elif stype == 1000314007: # VkPhysicalDeviceSynchronization2FeaturesKHR @@ -374,6 +378,7 @@ def test_feature_and_property_offsets(self): self.assertEqual(vk_info.F13_SUBGROUP_SIZE_CONTROL, 16 + 4 * 7) self.assertEqual(vk_info.F13_SYNCHRONIZATION2, 16 + 4 * 9) self.assertEqual(vk_info.F13_DYNAMIC_RENDERING, 16 + 4 * 12) + self.assertEqual(vk_info.F13_SHADER_INTEGER_DOT_PRODUCT, 16 + 4 * 13) self.assertEqual(vk_info.PROPS_API_VERSION, 0) self.assertEqual(vk_info.PROPS_DRIVER_VERSION, 4) self.assertEqual(vk_info.PROPS_VENDOR_ID, 8) @@ -822,6 +827,7 @@ def test_native64_conditions_and_boundaries(self): "per_vertex_inputs": True, "barycentric_fallback": False, "max_push_constants_size": 256, + "integer_dot_product": True, "vendor_id": 0, "device_id": 0, "driver_id": 1, @@ -829,6 +835,13 @@ def test_native64_conditions_and_boundaries(self): "rdna2_amd_windows": False, }) + def test_integer_dot_product(self): + """shaderIntegerDotProduct of a Vulkan 1.3 device (offset 68); a Vulkan 1.2 device never has it.""" + for have in (True, False): + with self.subTest(have=have): + res, _vk = self._run_query(FakeDevice(integer_dot_product=have)) + self.assertIs(res["integer_dot_product"], have) + def test_max_push_constants_size(self): """limits.maxPushConstantsSize is read from VkPhysicalDeviceProperties (offset 328 on 64-bit).""" for limit in (128, 256, 4096): diff --git a/tools/descriptor_source_census.py b/tools/descriptor_source_census.py new file mode 100644 index 0000000000..9264e2d82a --- /dev/null +++ b/tools/descriptor_source_census.py @@ -0,0 +1,326 @@ +r"""Where do the T#s and S#s of image instructions come from? (stdlib only; counts, no shader bytes) + +A translated shader turns the T# (8 SGPRs) and S# (4 SGPRs) of every image instruction into a bindless index. +Whether that index can travel inside the descriptor (docs/design.md, "Bindless index in the T#") depends on where +the descriptor words were loaded from: the layer rewrites the console resource heaps' copies and its own heaps, but +not the title's other memory, and not the S#s of console sampler heaps, which shaders read in place. + +This census follows the forward SGPR dataflow of tools/heap_index_census.py over every listing and classifies the +descriptor operand of each image instruction: + + * heap32 all words are one aligned descriptor of an s_load_dwordx8/x16 whose base is a 32-bit pointer in + an entry SGPR (a descriptor table or a directly indexed heap), static or dynamic offset; + * heap32-partial the word that carries the index (T#: word 6, S#: word 3) is such a load's, other words are not + (the shader edited the descriptor); + * ptr64 / loaded / system / other-base an s_load from a 64-bit entry pointer, a loaded pointer, a system SGPR, + anything else; + * vsharp an s_buffer_load through a V# (a constant or structured buffer of the title's); + * literal every word a translate-time constant; + * unknown the dataflow lost the words (a join of different loads, a v_readfirstlane, an ALU result). + +It also counts, per descriptor word, scalar instructions that read a word of a heap32 T# or S# for anything but the +image instruction itself (a shader doing its own maths on a field). + +Usage: + python -I tools/descriptor_source_census.py /shaders/dxbc/disasm [--json OUT] [--limit N] +""" +import argparse +import json +import os +import sys +from collections import Counter, defaultdict + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import descriptor_sources # noqa: E402 +import heap_index_census as hic # noqa: E402 +import shader_ir # noqa: E402 +import shader_meta # noqa: E402 +from report_paths import same_report_path # noqa: E402 + +LOADS = {"s_load_dwordx4": 4, "s_load_dwordx8": 8, "s_load_dwordx16": 16, + "s_buffer_load_dwordx4": 4, "s_buffer_load_dwordx8": 8, "s_buffer_load_dwordx16": 16} +INDEX_WORD = {"T#": 6, "S#": 3} +WIDTH = {"T#": 8, "S#": 4} + + +def _regs(a, n): + if a["k"] == "sgpr" and a.get("n", 1) >= n: + return [a["r"] + i for i in range(n)] + if a["k"] == "slist" and len(a["r"]) >= n and all(isinstance(r, int) for r in a["r"][:n]): + return list(a["r"][:n]) + return None + + +def descriptor_operands(ins): + """[(role, [sgpr numbers])] of an image instruction.""" + op = shader_meta.base_op(ins["op"]) + a = ins["args"] + out = [] + if not op.startswith("image_") or len(a) < 3: + return out + t = _regs(a[2], 8) + out.append(("T#", t)) + if op.startswith(shader_meta.SAMPLER_IMAGE_OPS) and len(a) >= 4: + out.append(("S#", _regs(a[3], 4))) + return out + + +def analyse(insns, stage, user_count): + blocks, succ = hic.blocks_of(insns) + system = set(hic.SYSTEM_SGPRS.get(stage, ())) + entry = [None] * len(blocks) + entry[0] = {r: ("in", r) for r in range(106)} + work = [0] + while work: + b = work.pop() + sym = dict(entry[b]) + for ins in blocks[b]: + if shader_meta.base_op(ins["op"]) == "s_endpgm": + break + hic.step(sym, ins) + for s in succ[b]: + merged = sym if entry[s] is None else {k: v for k, v in entry[s].items() if sym.get(k) == v} + if merged != entry[s]: + entry[s] = dict(merged) + work.append(s) + + loads = {} # pc -> (base class, offset kind, static offset) + + def load_class(ins, sym): + op = shader_meta.base_op(ins["op"]) + a = ins["args"] + if op.startswith("s_buffer_"): + return ("vsharp", None, None) + if len(a) < 2 or a[1]["k"] != "sgpr" or a[1].get("n") != 2: + return ("other-base", None, None) + b = a[1]["r"] + lo, hi = sym.get(b), sym.get(b + 1) + rlo, dyn = hic.root(lo) + off = hic._src(sym, a[2]) if len(a) >= 3 else ("const", 0) + static = off[1] if off is not None and off[0] == "const" and not dyn else None + kind = "static" if static is not None else "dynamic" + if rlo is not None and rlo[0] == "in": + n = rlo[1] + if n in system or n >= user_count: + return ("system", kind, static) + if hi == ("const", 0): + return ("heap32", kind, static) + return ("ptr64", kind, static) + if rlo is not None and rlo[0] == "ld": + return ("loaded", kind, static) + return ("other-base", kind, static) + + uses = [] # (pc, role, class) + heap_loads = defaultdict(set) # load pc -> roles of heap32 descriptors taken from it whole or in part + pending_reads = [] # (load pc, dword) read by a scalar instruction that is not an image instruction + for b in range(len(blocks)): + if entry[b] is None: + continue + sym = dict(entry[b]) + for ins in blocks[b]: + op = shader_meta.base_op(ins["op"]) + if op == "s_endpgm": + break + if op in LOADS and ins["args"] and ins["args"][0]["k"] == "sgpr": + loads[ins["pc"]] = load_class(ins, sym) + if op.startswith("image_"): + for role, regs in descriptor_operands(ins): + uses.append((ins["pc"], role, classify(role, regs, sym, loads, heap_loads))) + elif not op.startswith(("s_load_", "s_buffer_load_", "s_mov_b", "s_waitcnt")): + reads, _ = shader_meta._split_operands(ins) + for r in reads: + t = sym.get(r) + if t is not None and t[0] == "ld": + pending_reads.append((t[1], t[2], op)) + hic.step(sym, ins) + verdict = descriptor_sources.analyse(blocks, succ, user_count, system) + embedded = sum(1 for v in verdict.values() if v) + reads = Counter() + for pc, dword, op in pending_reads: + for role in heap_loads.get(pc, ()): + reads[(role, dword % WIDTH[role], op)] += 1 + return uses, reads, (embedded, len(verdict)) + + +def classify(role, regs, sym, loads, heap_loads): + if regs is None: + return "unknown" + tags = [sym.get(r) for r in regs] + if all(t is not None and t[0] == "const" for t in tags): + return "literal" + w = WIDTH[role] + first = tags[0] + whole = (first is not None and first[0] == "ld" and first[2] % w == 0 and + all(t == ("ld", first[1], first[2] + i) for i, t in enumerate(tags))) + idx = tags[INDEX_WORD[role]] + if whole: + cls, kind, static = loads.get(first[1], ("other-base", None, None)) + if cls == "heap32": + heap_loads[first[1]].add(role) + if kind == "static" and static % 16: + return "heap32-misaligned" + return f"heap32-{kind}" + return cls + if idx is not None and idx[0] == "ld" and idx[2] % w == INDEX_WORD[role]: + cls, kind, static = loads.get(idx[1], ("other-base", None, None)) + if cls == "heap32": + heap_loads[idx[1]].add(role) + return "heap32-partial" + return cls + "-partial" + return "unknown" + + +def fspx_user_count(disasm_dir, name): + """USER_SGPR [5:1] of an FSPX program's COMPUTE_PGM_RSRC2 (/../fspx/.json, tools/fspx_unpack.py; + the pipeline library's programs have no FSSM header), or None.""" + path = os.path.join(os.path.dirname(os.path.abspath(disasm_dir)), "fspx", name + ".json") + try: + with open(path, encoding="utf-8") as f: + return (int(json.load(f)["rsrc2"]) >> 1) & 31 + except (OSError, ValueError, KeyError, TypeError): + return None + + +def census(disasm_dir, limit=None, progress=None): + stages = hic.stage_index(disasm_dir) + names = sorted(n[:-2] for n in os.listdir(disasm_dir) if n.endswith(".s")) + if limit: + names = names[:limit] + skipped = Counter() + accesses = defaultdict(Counter) # role -> class -> image instructions + modules = defaultdict(Counter) # role -> class -> modules with at least one + only_heap = Counter() # role -> modules whose every operand of that role is heap32-* + with_role = Counter() + word_reads = Counter() + per_stage = defaultdict(Counter) # stage -> class (T#) -> accesses + index_word = Counter() # descriptor_sources.analyse, as the translator decides + shaders = 0 + for k, name in enumerate(names): + if progress and k % 2000 == 0: + progress(k, len(names)) + stage = stages.get(name) + if stage is None: + skipped["no stage"] += 1 + continue + info = shader_ir.parse_file(os.path.join(disasm_dir, name + ".s")) + if not info["insns"]: + skipped["no instructions"] += 1 + continue + if info["invalid"]: + skipped["embedded data words"] += 1 + continue + user = hic.USER_SGPRS + if stage == "cs": + user = hic.cs_user_count(disasm_dir, name) + if user is None: + user = fspx_user_count(disasm_dir, name) + if user is None: + skipped["no FSSM header"] += 1 + continue + try: + uses, reads, (emb, images) = analyse(info["insns"], stage, user) + except hic.Skip as e: + skipped[str(e)] += 1 + continue + shaders += 1 + index_word["image instructions"] += images + index_word["T# index from dword 6"] += emb + if images: + index_word["modules with images"] += 1 + if emb == images: + index_word["modules with no T# lookup"] += 1 + seen = defaultdict(set) + for _, role, cls in uses: + accesses[role][cls] += 1 + seen[role].add(cls) + if role == "T#": + per_stage[stage][cls] += 1 + for role, classes in seen.items(): + with_role[role] += 1 + for c in classes: + modules[role][c] += 1 + if all(c.startswith("heap32-") and c != "heap32-misaligned" for c in classes): + only_heap[role] += 1 + for (role, dword, op), n in reads.items(): + word_reads[(role, dword, op)] += n + return { + "shaders_read": len(names), "shaders_followed": shaders, "skipped": dict(skipped), + "accesses": {r: dict(c.most_common()) for r, c in accesses.items()}, + "modules": {r: dict(c.most_common()) for r, c in modules.items()}, + "modules_with_role": dict(with_role), + "modules_all_heap32": dict(only_heap), + "t_sharp_accesses_per_stage": {s: dict(c.most_common()) for s, c in sorted(per_stage.items())}, + "tsharp_index_word": dict(index_word), + "heap32_word_reads": [{"role": r, "word": d, "op": o, "count": n} + for (r, d, o), n in sorted(word_reads.items())], + } + + +def print_report(out): + print(f"shaders read: {out['shaders_read']}, followed: {out['shaders_followed']}; " + f"skipped: {out['skipped'] or 'none'}") + for role in ("T#", "S#"): + acc = out["accesses"].get(role, {}) + total = sum(acc.values()) + print(f"\n{role}: {total} image instructions in {out['modules_with_role'].get(role, 0)} modules; " + f"{out['modules_all_heap32'].get(role, 0)} modules take every {role} whole from a heap32 load") + for cls, n in acc.items(): + print(f" {cls:<24} {n:>9} accesses {out['modules'][role][cls]:>7} modules") + print("\nT# accesses per stage:") + for s, c in out["t_sharp_accesses_per_stage"].items(): + print(f" {s}: " + ", ".join(f"{k} {v}" for k, v in c.items())) + print("\nthe translator's verdict (tools/descriptor_sources.py): " + + ", ".join(f"{k} {v}" for k, v in out["tsharp_index_word"].items())) + words = Counter() + for row in out["heap32_word_reads"]: + words[(row["role"], row["word"])] += row["count"] + print("\nscalar reads of heap32 descriptor words (not by the image instruction):") + for (role, word), n in sorted(words.items()): + print(f" {role} word {word}: {n}") + + +def main(argv=None): + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("disasm", help="/shaders/dxbc/disasm") + ap.add_argument("--json", help="write the full census here (outside the disasm folder)") + ap.add_argument("--limit", type=shader_ir.positive_int, help="only the first N listings (sorted by name)") + args = ap.parse_args(argv) + if not os.path.isdir(args.disasm): + print(f"ERROR: {args.disasm} is not a folder", file=sys.stderr) + return 2 + if args.json: + disasm = os.path.realpath(args.disasm) + target = os.path.realpath(os.path.abspath(args.json)) + try: + inside = os.path.commonpath([disasm, target]) == disasm + except ValueError: + inside = False + index_path = os.path.join(os.path.dirname(os.path.abspath(args.disasm)), "index.json") + if inside or same_report_path(args.json, index_path): + print(f"ERROR: --json must not write inside or next to the folder it reads: {args.json}", + file=sys.stderr) + return 2 + try: + out = census(args.disasm, args.limit, + progress=lambda k, n: print(f" {k}/{n}", file=sys.stderr, flush=True)) + except (OSError, ValueError, KeyError, TypeError) as e: + print(f"ERROR: {e}", file=sys.stderr) + return 2 + print_report(out) + if args.json: + try: + with open(args.json, "w", encoding="utf-8", newline="\n") as f: + json.dump(out, f, indent=1, sort_keys=True) + f.write("\n") + except OSError as e: + print(f"ERROR: cannot write {args.json}: {e}", file=sys.stderr) + return 2 + return 0 + + +if __name__ == "__main__": + try: + sys.stdout.reconfigure(errors="replace") + except (AttributeError, ValueError, OSError): + pass + sys.exit(main()) diff --git a/tools/descriptor_sources.py b/tools/descriptor_sources.py new file mode 100644 index 0000000000..5a2b41e513 --- /dev/null +++ b/tools/descriptor_sources.py @@ -0,0 +1,269 @@ +r"""Which image instructions read a T# whose index word the layer wrote (docs/design.md, "Bindless index in the T#"). + +The layer writes the bindless index of every T# into dword 6 of the descriptor slot shaders load it from: the +copies of the console resource heaps it keeps (fix_console_slot) and its own shader-visible heaps (Create*View). +Shaders reach those heaps only through a descriptor-table or heap pointer, which arrives as a 32-bit pointer in an +entry SGPR (user data) with the high dword a constant 0 (docs/d3d12_vulkan.md section 3.4, D3D-329: 99.86% of the +corpus's descriptor loads). A T# loaded through anything else (a 64-bit pointer, a pointer read from memory, a +constant or structured buffer of the title's) or built from constants keeps the title's dword 6, so for those the +translator keeps the hash-table lookup. + +`analyse` follows a forward dataflow over the basic blocks, as tools/heap_index_census.py does, tagging each SGPR +with where its value came from, and answers, for every image instruction, whether the SGPR that holds its T#'s +dword 6 holds dword 6 of a heap slot: a dword of an s_load from such a pointer whose byte position in its 32-byte +slot is 24 (a static offset is known; a run-time offset, the heap index times the slot size, is taken as slot +aligned, which the shader's tag check guards). Where two paths join with loads of different instructions, the value +keeps its slot position when both are heap dwords at the same position, so a T# loaded in either arm of a branch +still counts. Any other write, and anything the dataflow cannot follow, gives the lookup. + +Standard library only; tools/rdna2spirv.py and tools/descriptor_source_census.py share it. +""" +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import heap_index_census as _hic # noqa: E402 +import shader_meta as _meta # noqa: E402 + +SLOT_BYTES = 32 # kDescriptorSize: one T# per slot, at its start +INDEX_DWORD = 6 # the T# dword that carries the index (gfx10_descriptors.h, tsharp_index_word) +ENTRY_SGPRS = 106 +SCALAR_LOADS = ("s_load_dword", "s_buffer_load_dword") + + +def _load_slot_base(ins, sym, user_count, system): + """For an s_load whose base is a 32-bit heap pointer in a user SGPR: the byte position in its slot of the load's + first dword (a static offset mod 32; 0 for a run-time one, the heap index times 32). None for any other load.""" + op = _meta.base_op(ins["op"]) + a = ins["args"] + if not op.startswith("s_load_dword") or len(a) < 2 or a[1]["k"] != "sgpr" or a[1].get("n") != 2: + return None + b = a[1]["r"] + lo, hi = sym.get(b), sym.get(b + 1) + t = lo + while t is not None and t[0] == "off": + if not t[2]: + return None # a constant added to the pointer whose value the tag does not keep: position unknown + t = t[1] + if t is None or t[0] != "in" or hi != ("const", 0): + return None + n = t[1] + if n in system or n >= user_count: + return None + off = _hic._src(sym, a[2]) if len(a) >= 3 else ("const", 0) + if off is not None and off[0] == "const": + return off[1] % SLOT_BYTES + return 0 # a run-time offset (the heap index times the slot size) on top of the table pointer + + +def _slot_pos(tag, heap_loads): + """The dword position in a heap slot of the value `tag` names, or None.""" + if tag is None: + return None + if tag[0] == "hw": + return tag[1] + if tag[0] == "ld" and tag[1] in heap_loads: + byte = heap_loads[tag[1]] + 4 * tag[2] + return (byte % SLOT_BYTES) // 4 if byte % 4 == 0 else None + return None + + +def _merge(old, new, heap_loads): + out = {} + for k, v in old.items(): + w = new.get(k) + if w == v: + out[k] = v + continue + p, q = _slot_pos(v, heap_loads), _slot_pos(w, heap_loads) + if p is not None and p == q: + out[k] = ("hw", p) + return out + + +def _vgprs(ins): + """Every VGPR an instruction names, read or written.""" + out = set() + for a in ins["args"]: + if a["k"] == "vgpr": + out.update(range(a["r"], a["r"] + a.get("n", 1))) + elif a["k"] == "vlist": + out.update(r for r in a["r"] if isinstance(r, int)) + return out + + +def _lane(sym, a): + """The constant lane of a v_readlane/v_writelane lane operand, or None.""" + t = _hic._src(sym, a) + return t[1] & 63 if t is not None and t[0] == "const" else None + + +def _spill_step(sym, ins, spill_vgprs): + """SGPR values parked in VGPR lanes (v_writelane_b32 / v_readlane_b32, a compiler's SGPR spill): the lane keeps the + tag of the SGPR written into it, as ("v", vgpr, lane), and a v_readlane of a constant lane gives it back. Any other + instruction naming the VGPR forgets its lanes. Run after heap_index_census.step, which has forgotten the + v_readlane's destination.""" + op = _meta.base_op(ins["op"]) + a = ins["args"] + if op == "v_readlane_b32": # reads the VGPR and leaves it as it is, whatever it writes (an SGPR, VCC) + if len(a) >= 3 and a[0]["k"] == "sgpr" and a[0].get("n", 1) == 1 and a[1]["k"] == "vgpr": + lane = _lane(sym, a[2]) + tag = sym.get(("v", a[1]["r"], lane)) if lane is not None else None + if tag is not None: + sym[a[0]["r"]] = tag + return + touched = _vgprs(ins) & spill_vgprs + if not touched: + return + before = None + if op == "v_writelane_b32" and len(a) >= 3 and a[0]["k"] == "vgpr": + lane = _lane(sym, a[2]) + if lane is not None: # only that lane changes; a source other than an SGPR (VCC, a constant) is unknown + src = sym.get(a[1]["t"]) if a[1]["k"] == "special" and a[1].get("t") in VCC_HALVES else \ + _hic._src(sym, a[1]) + before = (a[0]["r"], lane, src) + for k in [k for k in sym if isinstance(k, tuple) and k[1] in touched]: + if before is None or k[1] != before[0] or k[2] == before[1]: + del sym[k] + if before is not None and before[2] is not None: + sym[("v", before[0], before[1])] = before[2] + + +VCC_HALVES = ("vcc_lo", "vcc_hi") + + +def _vcc_names(a): + if a["k"] == "special" and a.get("t") in ("vcc", "vcc_lo", "vcc_hi"): + return {"vcc_lo", "vcc_hi"} if a["t"] == "vcc" else {a["t"]} + if a["k"] == "slist": + return {r for r in a["r"] if r in VCC_HALVES} + return set() + + +def _vcc_step(sym, ins): + """VCC used as two more SGPRs: a compiler short of SGPRs loads a T#'s last two dwords into vcc_lo and vcc_hi + (s_load_dwordx8 [s100, ..., s105, vcc_lo, vcc_hi]) or parks a pointer there. Their tags live under "vcc_lo" and + "vcc_hi". LLVM prints every VCC operand, the implicit ones of VOPC and carry instructions included, so any other + instruction naming VCC forgets them (a reader as well, which only loses precision). Run after + heap_index_census.step, which follows neither VCC nor a load into a register list.""" + op = _meta.base_op(ins["op"]) + a = ins["args"] + if not a: + return + if op.startswith(SCALAR_LOADS) and a[0]["k"] == "slist": + for i, r in enumerate(a[0]["r"]): + sym[r] = ("ld", ins["pc"], i) + return + if op.startswith("image_"): + return # reads its descriptor operands + names = set().union(*(_vcc_names(x) for x in a)) + if not names: + return + if op == "v_readlane_b32" and len(a) >= 3 and a[0]["k"] == "special" and a[0].get("t") in VCC_HALVES \ + and a[1]["k"] == "vgpr": + lane = _lane(sym, a[2]) + tag = sym.get(("v", a[1]["r"], lane)) if lane is not None else None + sym.pop(a[0]["t"], None) + if tag is not None: + sym[a[0]["t"]] = tag + return + if op in ("s_mov_b64", "s_mov_b32") and len(a) >= 2 and a[0]["k"] == "sgpr" and not _vcc_names(a[0]): + src = ["vcc_lo", "vcc_hi"] if op == "s_mov_b64" and a[1].get("t") == "vcc" else \ + [a[1]["t"]] if op == "s_mov_b32" and a[1].get("t") in VCC_HALVES else None + if src is not None: + for i, name in enumerate(src): + tag = sym.get(name) + if tag is not None: + sym[a[0]["r"] + i] = tag + return + for name in VCC_HALVES: + sym.pop(name, None) + + +def tsharp_operand(ins): + """The registers of an image instruction's T# (SGPR numbers, or "vcc_lo" / "vcc_hi" in a register list), or + None.""" + a = ins["args"] + if not _meta.base_op(ins["op"]).startswith("image_") or len(a) < 3: + return None + t = a[2] + if t["k"] == "sgpr" and t.get("n", 1) >= 8: + return [t["r"] + i for i in range(8)] + if t["k"] == "slist" and len(t["r"]) >= 8 and all(isinstance(r, int) or r in VCC_HALVES for r in t["r"][:8]): + return list(t["r"][:8]) + return None + + +def analyse(blocks, succ, user_count=32, system=()): + """{id(ins): bool} for every image instruction of `blocks` (the translator's basic blocks, `succ` their + successors): True when its T#'s dword 6 is dword 6 of a heap slot. Raises heap_index_census.Skip never; an + instruction the analysis cannot place is simply absent (the caller keeps the lookup).""" + system = set(system) + if not blocks: + return {} + # The tags name a load by its pc. A listing without encodings (a hand-written test program) gives every + # instruction the same pc, so the analysis then runs on copies numbered in order and maps its answers back. + flat = [ins for blk in blocks for ins in blk] + if len({ins["pc"] for ins in flat}) < len(flat): + copies, k = [], 0 + for blk in blocks: + copies.append([dict(ins, pc=4 * (k + n)) for n, ins in enumerate(blk)]) + k += len(blk) + answers = analyse(copies, succ, user_count, system) + return {id(ins): answers.get(id(copy), False) + for ins, copy in zip(flat, (c for blk in copies for c in blk))} + spill_vgprs = {ins["args"][0]["r"] for ins in flat if _meta.base_op(ins["op"]) == "v_writelane_b32" and + ins["args"] and ins["args"][0]["k"] == "vgpr"} + # A load is a heap load when every path reaching it brings a heap pointer. The fixpoint below decides that as it + # goes; a load first seen as one and later not (a join lost its pointer) is banned and the dataflow run again + # without it, so no slot position stays derived from a load that is not a heap load in the end. + banned = set() + while True: + heap_loads = {} # load pc -> byte position of its first dword in its slot + lost = set() + entry = [None] * len(blocks) + entry[0] = {r: ("in", r) for r in range(ENTRY_SGPRS)} + + def run(b, sym, out=None): + for ins in blocks[b]: + op = _meta.base_op(ins["op"]) + if op == "s_endpgm": + break + if op.startswith(SCALAR_LOADS): + pc = ins["pc"] + pos = None if pc in banned else _load_slot_base(ins, sym, user_count, system) + if pos is None or heap_loads.get(pc, pos) != pos: + if pc in heap_loads: + lost.add(pc) + heap_loads.pop(pc, None) + banned.add(pc) + else: + heap_loads[pc] = pos + if out is not None and op.startswith("image_"): + regs = tsharp_operand(ins) + out[id(ins)] = (regs is not None and + _slot_pos(sym.get(regs[INDEX_DWORD]), heap_loads) == INDEX_DWORD) + _hic.step(sym, ins) + if spill_vgprs: + _spill_step(sym, ins, spill_vgprs) + _vcc_step(sym, ins) + return sym + + work = [0] + while work: + b = work.pop() + sym = run(b, dict(entry[b])) + for s in succ[b]: + merged = dict(sym) if entry[s] is None else _merge(entry[s], sym, heap_loads) + if merged != entry[s]: + entry[s] = merged + work.append(s) + if lost: + continue + out = {} + for b in range(len(blocks)): + if entry[b] is not None: + run(b, dict(entry[b]), out) + if lost: + continue + return out diff --git a/tools/lane_masks.py b/tools/lane_masks.py index 07dddd6703..e7e0100a06 100644 --- a/tools/lane_masks.py +++ b/tools/lane_masks.py @@ -134,11 +134,11 @@ def _maskable_b32(x): ) -def lane_slot(vgpr, lane): +def lane_slot(vgpr, lane, wave64=True): """State key for a mask parked in one lane of a VGPR, or None unless both operands are plain.""" if vgpr["k"] != "vgpr" or lane["k"] != "imm": return None - return ("lane", vgpr["r"], lane["v"] & 63) + return ("lane", vgpr["r"], lane["v"] & (63 if wave64 else 31)) def wave32_vcc_pair_op(op, args): @@ -176,16 +176,17 @@ def step(state, ins, wave64=True): if op == "v_readfirstlane_b32" and len(a) == 2: # sD = vS, the same in every lane put(state, a[0], kind(state, a[1], wave64), wave64) return - if op == "v_writelane_b32" and len(a) == 3 and lane_slot(a[0], a[2]): # vD[lane] = sS + if op == "v_writelane_b32" and len(a) == 3 and lane_slot(a[0], a[2], wave64): # vD[lane] = sS state.pop(("v", a[0]["r"]), None) k = kind(state, a[1], wave64) + slot = lane_slot(a[0], a[2], wave64) if k is None: - state.pop(lane_slot(a[0], a[2]), None) + state.pop(slot, None) else: - state[lane_slot(a[0], a[2])] = k + state[slot] = k return if op == "v_readlane_b32" and len(a) == 3: # sD = vS[lane] - put(state, a[0], state.get(lane_slot(a[1], a[2])), wave64) + put(state, a[0], state.get(lane_slot(a[1], a[2], wave64)), wave64) return if op.startswith("v_cmp"): # Handle v_cmp before VGPR clobber (defensive for 2-operand forms with implicit vcc). @@ -275,19 +276,201 @@ def step(state, ins, wave64=True): put(state, a[1], MASK, wave64) # carry/sign/scale lane mask of VOP3b ops -def parked(blocks, masks): +def parked(blocks, masks, wave64=True): """The (vgpr, lane) slots some v_readlane_b32 fetches a mask from, given analyse()'s result.""" found = set() for blk in blocks: for ins in blk: a = ins["args"] if base_op(ins["op"]) == "v_readlane_b32" and len(a) == 3: - slot = lane_slot(a[1], a[2]) + slot = lane_slot(a[1], a[2], wave64) if slot in masks.get(id(ins), ()): found.add(slot[1:]) return sorted(found) +VGPR_MOVREL = ("v_movrels_b32", "v_movreld_b32", "v_movrelsd_b32", "v_movrelsd_2_b32", "v_swaprel_b32") + + +def scalar_spills(blocks, succ=None, wave64=True): + """The (vgpr, lane) slots of pure scalar-spill VGPRs: VGPRs touched only by constant-lane v_writelane_b32 + (non-VGPR source) and constant-lane v_readlane_b32, never read or written as a vector operand, never aliased by + v_movrel*/v_swaprel_b32, and with every v_readlane_b32 lane definitely written on all paths before it is read. + + On RDNA2 hardware v_writelane_b32 / v_readlane_b32 ignore EXEC and access physical lane K even when lane K is + inactive (e.g. a small triangle launching fewer than 32 fragment lanes or after a dither/alpha discard). In + Vulkan SPIR-V, OpGroupNonUniformShuffle from an inactive invocation is undefined and reads stale VGPR bits. + Parking these slots in the %sgpr array makes every wave32/wave64 stage exact regardless of active lanes.""" + mask = 63 if wave64 else 31 + written = {} + disqualified = set() + movrel_min = None + for blk in blocks: + for ins in blk: + op = base_op(ins["op"]) + a = ins["args"] + if op in VGPR_MOVREL: + for x in a: + if x.get("k") == "vgpr": + movrel_min = x["r"] if movrel_min is None else min(movrel_min, x["r"]) + if (op == "v_writelane_b32" and len(a) == 3 + and a[0].get("k") == "vgpr" and a[0].get("n", 1) == 1 + and a[2].get("k") == "imm" and not (a[2].get("neg") or a[2].get("abs")) + and a[1].get("k") != "vgpr"): + written.setdefault(a[0]["r"], set()).add(a[2]["v"] & mask) + continue + if (op == "v_readlane_b32" and len(a) == 3 + and a[0].get("k") != "vgpr" + and a[1].get("k") == "vgpr" and a[1].get("n", 1) == 1 + and a[2].get("k") == "imm" and not (a[2].get("neg") or a[2].get("abs"))): + continue + for x in a: + k = x.get("k") + if k == "vgpr": + disqualified.update(range(x["r"], x["r"] + x.get("n", 1))) + elif k == "vlist": + disqualified.update(x["r"]) + candidates = {vr for vr in written if vr not in disqualified and (movrel_min is None or vr < movrel_min)} + if not candidates: + return [] + # Must-def check over CFG: every v_readlane_b32 of (vr, lane) must be dominated by v_writelane_b32 of (vr, lane) + # on every path from entry, so entry-populated input VGPRs read before write are never misclassified. + if succ is None: + succ = [[i + 1] if i + 1 < len(blocks) else [] for i in range(len(blocks))] + entry = [None] * len(blocks) + if blocks: + entry[0] = set() + work = [0] if blocks else [] + while work: + n = work.pop() + st = set(entry[n]) + for ins in blocks[n]: + op, a = base_op(ins["op"]), ins["args"] + if op == "v_writelane_b32" and len(a) == 3 and a[0].get("k") == "vgpr" and a[0]["r"] in candidates: + st.add((a[0]["r"], a[2]["v"] & mask)) + for s in succ[n]: + merged = set(st) if entry[s] is None else (entry[s] & st) + if entry[s] is None or merged != entry[s]: + entry[s] = merged + work.append(s) + for n, blk in enumerate(blocks): + if entry[n] is None: + continue + st = set(entry[n]) + for ins in blk: + op, a = base_op(ins["op"]), ins["args"] + if op == "v_writelane_b32" and len(a) == 3 and a[0].get("k") == "vgpr" and a[0]["r"] in candidates: + st.add((a[0]["r"], a[2]["v"] & mask)) + elif op == "v_readlane_b32" and len(a) == 3 and a[1].get("k") == "vgpr" and a[1]["r"] in candidates: + if (a[1]["r"], a[2]["v"] & mask) not in st: + candidates.discard(a[1]["r"]) + return sorted((vr, lane) for vr in candidates for lane in written[vr]) + + +def definite_spill_reads(blocks, succ=None, wave64=True): + """Per-instruction definite constant-lane scalar spill reloads (works on mixed VGPRs too). + + Returns (read_ins_ids, slots) where `read_ins_ids` is the set of `id(ins)` for every constant-lane + `v_readlane_b32 sD, vR, K` where `(vR, K)` was definitely written by a constant-lane `v_writelane_b32 vR, sS, K` + (non-VGPR source) on every path from entry with no intervening write to `vR` (other than constant-lane + `v_writelane_b32` to a different lane). `slots` is the sorted list of `(vR, K)` slots needed by those reads. + + Parking those slots in `%sgpr` avoids `OpGroupNonUniformShuffle` on lanes that may be absent (partial fragment + waves, discards, or wave64 lanes >= 32 on 32-wide subgroups) even when the VGPR is reused as a vector register + elsewhere in the shader. + """ + mask = 63 if wave64 else 31 + + def _const_lane(a): + return a.get("k") == "imm" and not (a.get("neg") or a.get("abs")) + + def _kill_vgprs(st, regs): + if not regs or not st: + return + for key in [k for k in st if k[0] in regs]: + st.discard(key) + + def _step_spills(st, ins): + op, a = base_op(ins["op"]), ins["args"] + if op in ("s_swappc_b64", "s_setpc_b64", "s_call_b64"): + st.clear() + return + if not a or op.startswith(NO_DESTINATION): + return + mods = ins.get("mods", ()) + if op.startswith(("buffer_load", "tbuffer_load")) and "lds" in mods: + return + if op.startswith(("buffer_atomic", "global_atomic", "flat_atomic", "image_atomic", + "s_atomic", "s_buffer_atomic")) and "glc" not in mods: + return + if op.startswith("ds_") and not op.startswith(DS_HAS_DST) and "_rtn" not in op: + return + if op.startswith("v_cmp") or op == "v_readlane_b32": + return + if op == "v_writelane_b32" and len(a) == 3 and a[0].get("k") == "vgpr": + vr = a[0]["r"] + if a[0].get("n", 1) == 1 and _const_lane(a[2]) and a[1].get("k") != "vgpr": + st.add((vr, a[2]["v"] & mask)) + else: + _kill_vgprs(st, range(vr, vr + a[0].get("n", 1))) + return + if op == "v_swap_b32": + written = set() + for x in a[:2]: + if x.get("k") == "vgpr": + written.update(range(x["r"], x["r"] + x.get("n", 1))) + _kill_vgprs(st, written) + return + if op in VGPR_REL_DST: + bases = [x["r"] for x in (a[:2] if op == "v_swaprel_b32" else a[:1]) if x.get("k") == "vgpr"] + if bases: + lo = min(bases) + for key in [k for k in st if k[0] >= lo]: + st.discard(key) + return + k0 = a[0].get("k") + if k0 == "vgpr": + _kill_vgprs(st, range(a[0]["r"], a[0]["r"] + a[0].get("n", 1))) + elif k0 == "vlist": + _kill_vgprs(st, set(a[0]["r"])) + + if not blocks: + return set(), [] + if succ is None: + succ = [[i + 1] if i + 1 < len(blocks) else [] for i in range(len(blocks))] + entry = [None] * len(blocks) + entry[0] = set() + work = [0] + while work: + n = work.pop() + st = set(entry[n]) + for ins in blocks[n]: + _step_spills(st, ins) + for s in succ[n]: + merged = set(st) if entry[s] is None else (entry[s] & st) + if entry[s] is None or merged != entry[s]: + entry[s] = merged + work.append(s) + read_ids = set() + slots = set() + for n, blk in enumerate(blocks): + if entry[n] is None: + continue + st = set(entry[n]) + for ins in blk: + op, a = base_op(ins["op"]), ins["args"] + if (op == "v_readlane_b32" and len(a) == 3 + and a[0].get("k") != "vgpr" + and a[1].get("k") == "vgpr" and a[1].get("n", 1) == 1 + and _const_lane(a[2])): + slot = (a[1]["r"], a[2]["v"] & mask) + if slot in st: + read_ids.add(id(ins)) + slots.add(slot) + _step_spills(st, ins) + return read_ids, sorted(slots) + + def analyse(blocks, succ, *, include_either=False, wave64=True): entry = [None] * len(blocks) # None: not reached yet if blocks: diff --git a/tools/ptr_truncation_census.py b/tools/ptr_truncation_census.py index 7869f52247..e02cae7394 100644 --- a/tools/ptr_truncation_census.py +++ b/tools/ptr_truncation_census.py @@ -68,7 +68,7 @@ def __init__(self, blocks, succ, user_sgpr_limit, system_sgprs): self.args_ = (blocks, succ, user_sgpr_limit, system_sgprs) -def _capture(_path, _name, blocks, succ, user_sgpr_limit=32, system_sgprs=()): +def _capture(_path, _name, blocks, succ, user_sgpr_limit=32, system_sgprs=(), extra=None): raise _Reached(blocks, succ, user_sgpr_limit, system_sgprs) diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 7091396fcd..c6521242db 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -36,6 +36,7 @@ from replace_retry import replace as replace_retry # noqa: E402 from file_mode import published_mode # noqa: E402 import cfg_structure # noqa: E402 +import descriptor_sources # noqa: E402 import fssm_header # noqa: E402 import fssm_unpack # noqa: E402 import lane_masks # noqa: E402 @@ -66,6 +67,14 @@ # The kind word's bit positions, shared with runtime/src/descriptor_table.h. DESC_SAMPLED_BIT = 0 # bit i: the index is bound in dimension i's sampled array DESC_STORAGE_BIT = 8 # bit 8 + i: ... in its storage arrays (dimensions 0..4 have them) +# The bindless index in the T# (docs/design.md, "Bindless index in the T#"): the layer writes dword 6 of every T# in +# the heaps it keeps (runtime/src/gfx10_descriptors.h, tsharp_index_word) as TAG << 28 | storage kind << 23 | +# sampled kind << 16 | index, the kind being the table's kind bits 8..12 and 0..6. A module reads it, without the +# hash table, where tools/descriptor_sources.py shows the T#'s dword 6 was loaded from such a heap, and records +# TSHARP_INDEX in its meta, which tells the runtime to write the word. +TSHARP_INDEX = "dword6" +TSHARP_INDEX_DWORD = 6 +TSHARP_INDEX_TAG = 0xA WAVE64_EMULATE = False # --wave64-emulate: wave64 compute/mesh shaders exact on any subgroup size (Gen.x_round) # --wave64-emulate: use wave64_emulate_opt's inline structured form when it does not put an exchange barrier # under control flow only some invocations take (translate() re-runs this module without it when it does). @@ -84,6 +93,12 @@ # (1,0,0), (0,1,0), (0,0,1) at the triangle's three vertices; interpolating those gives the perspective-correct # barycentrics, so .y/.z are AMD's i/j as with BaryCoordKHR. BARY_FALLBACK = False +# --integer-dot-fallback: the 4x8-bit dot products (v_dot4_i32_i8, v_dot4c_i32_i8, v_dot4_u32_u8, v_dot4c_u32_u8) are +# four extracts, multiplies and adds, as before, instead of SPV_KHR_integer_dot_product's OpSDot / OpUDot and their +# saturating-accumulate forms (Gen.packed_dot4). For devices without shaderIntegerDotProduct (a Vulkan 1.2 device +# without VK_KHR_shader_integer_dot_product); Vulkan 1.3 requires the feature. docs/design.md, "Signed-byte dot +# products". +INTEGER_DOT_FALLBACK = False SHADER_CLOCK = False FMA_KHR = False # --fma khr: fused multiply-adds are OpFmaKHR (SPV_KHR_fma, VK_KHR_shader_fma), not GLSL Fma FMA_EXACT = False # --fma exact: fused multiply-adds are emulated from single-rounded f32 ops (Gen.fma_exact) @@ -93,6 +108,7 @@ # coordinate, so a per-pixel offset doesn't change the LOD. Gathers keep their Offset (shaderImageGatherExtended). TEXEL_OFFSET_FALLBACK = False FLOAT_CONTROLS = True # False (--no-float-controls): no SignedZeroInfNanPreserve, for drivers without the property +FTZ32 = True # False (--no-ftz32): keep software flush_f32() instead of DenormFlushToZero 32 # --mesh-compute: mesh shaders become compute shaders (same workgroup size and code) for devices without # VK_EXT_mesh_shader. Instead of SetMeshOutputs and the mesh outputs, the epilogue writes the vertex and primitive # counts, each lane's vertex and each lane's primitive into this workgroup's slot of a buffer whose device address is @@ -479,6 +495,8 @@ def __init__(self, stage, hoist_reg_ptrs=False, cache_active=False): self.atomic_volume_tsharps = set() # SGPR descriptor groups also used for 3D atomics self.reads_store_views = False # reserved for compatibility with main self.coherent_images = False # a glc image_load/image_store: the storage views are decorated Coherent + self.uses_vmm = False # glc/dlc buffer/global/scalar access: VulkanMemoryModel + DeviceScope + self.reads_glc_buffer = False # glc/dlc buffer/global/scalar load: runtime pre-dispatch barrier hint self.writes_depth = False self.uses_smul = False self.uses_minlod = False @@ -487,6 +505,13 @@ def __init__(self, stage, hoist_reg_ptrs=False, cache_active=False): self.round_mode = False # the program writes MODE.FP_ROUND[3:2] (f16/f64 rounding): kept in %mode_r16 self.uses_fhalf = False # %fhalf_g (0.5) constant self.uses_f64 = False + self.uses_psb_vec = False # scalar_load's read-only wide loads: uvec2/uvec4 NonWritable Block pointers + self.uses_psb_vec_rw = False # scalar_load's mutable wide loads: uvec2/uvec4 Block pointers without NonWritable + self.uses_psb_scalar_ro = False # scalar_load's read-only single-dword loads: uint NonWritable Block pointers + self.ftz32 = bool(FLOAT_CONTROLS and FTZ32) # DenormFlushToZero 32 active for this module + self.scalar_load_ro = None # None (unanalysed), True (all RO), or frozenset of id(ins) safe for NonWritable + self.sbuf_slow_fns: dict[tuple[int, bool], list[str]] = {} # (width, ro) -> %sbuf_slow_{ro|rw}_x{n} helper lines + self.uses_int_dot = False # packed_dot4 emitted OpSDot/OpUDot(AccSat): SPV_KHR_integer_dot_product self.uses_fma_khr = False # an OpFmaKHR was emitted: capability FMAKHR + extension SPV_KHR_fma self.uses_fma_khr32 = False # ... on f32 (feature shaderFmaFloat32) self.uses_fma_khr64 = False # ... on f64 (feature shaderFmaFloat64) @@ -535,7 +560,8 @@ def __init__(self, stage, hoist_reg_ptrs=False, cache_active=False): self.wave64 = False # compiled for 64-lane waves (64-bit EXEC writes, exec_hi, v_mbcnt_hi, ...) self.cur_uniform_readlane = False self.w64g = None # wave64 VS/PS/GS: wave64_halves.analyse() result (tier, reasons, rewrite sites) - self.w64_scalar_spills = set() # (vgpr, lane) pure scalar spill slots lowered to self.parked (SHADER-10) + self.scalar_spills = set() # (vgpr, lane) pure scalar spill slots lowered to self.parked (all waves/stages) + self.spill_readlanes = set() # id(ins) of mixed-VGPR v_readlane_b32 proven to reload a parked spill slot self.emulate = False # --wave64-emulate: exact wave64 on any subgroup size (cs/ms; see x_round) self.emulate_inline = False # emulate: current block emits direct inline barriers (no x_split) self.emulate_plan = None # emulate: structured plan from wave64_emulate_opt.plan_structured_emulation @@ -584,13 +610,23 @@ def __init__(self, stage, hoist_reg_ptrs=False, cache_active=False): 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.uses_fmt_enc_table = False # %fmt_enc_desc_tab: table-driven dynamic-format buffer store encoder + self.float_only_images = set() # id(ins) of image_load/image_sample ops provably float-only 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 self.sgpr_imm = {} # SGPR -> literal an s_mov_b32 put there earlier in this basic block (see gather_addr_modes) self.desc_cache = {} # (first SGPR, dwords) -> id of the %desc_lookup_fn result in the current basic block + # id(instruction) -> True when its T#'s dword 6 comes from a heap slot the layer writes (descriptor_sources) + self.tsharp_from_heap = {} + self.tsharp_index_reads = 0 # image instructions that take the T#'s index from dword 6 alone + self.tsharp_lookups = 0 # ... that also look the T# up in the hash table (its source is not known) self._scan = (None, 0, []) # (body list, lines already seen, open merge labels): see desc_cache_ok self.block_label = "%entry" # label of the SPIR-V block the current instruction starts in self.build_meta = {} # runtime build metadata from tools/shader_meta.py + self.literal_samplers = [] # ordered 4-dword literal S# tuples (matches meta["literal_samplers"]) + self.literal_sampler_index = {} # 4-dword tuple -> SpecId index (0..N-1) + self.literal_sampler_sites = {} # id(ins) -> 4-dword literal S# tuple + self.uses_lit_sampler_spec = False # emitted OpSpecConstant literal sampler bypass def tmp(self): self.n += 1 @@ -2527,6 +2563,23 @@ def swizzle(self, a, mods, ins): "buffer_store_byte": (1, True, False, None), "buffer_store_byte_d16_hi": (1, True, False, 1), "buffer_store_short": (2, True, False, None), "buffer_store_short_d16_hi": (2, True, False, 1)} + @staticmethod + def _is_coherent_mem(mods): + return "glc" in mods or "dlc" in mods + + def _psb_load_op(self, mods): + if self._is_coherent_mem(mods): + self.uses_vmm = True + self.reads_glc_buffer = True + return f"Aligned|MakePointerVisible|NonPrivatePointer 4 {self.cu(1)}" + return "Aligned 4" + + def _psb_store_op(self, mods): + if self._is_coherent_mem(mods): + self.uses_vmm = True + return f"Aligned|MakePointerAvailable|NonPrivatePointer 4 {self.cu(1)}" + return "Aligned 4" + def buffer_sub(self, op, a, mods): """The d16 8/16-bit MUBUF loads and the 8/16-bit stores (RDNA2 ISA); the plain buffer_load_{u,s}byte / {u,s}short are buffer_load_sub's. The _d16 loads write one 16-bit half of vdata (ubyte / sbyte extended to 16 bits) and @@ -2551,6 +2604,9 @@ def buffer_sub(self, op, a, mods): self.emit(f"OpSelectionMerge {lbl_end} None") self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") self.emit(f"{lbl_do} = OpLabel") + if store and self._is_coherent_mem(mods): + self.uses_vmm = True + load_mem = None if store else self._psb_load_op(mods) value = None for k in range(nbytes): va = addr @@ -2580,7 +2636,7 @@ def buffer_sub(self, op, a, mods): self.emit(f"{t2} = OpAtomicOr %uint {p} {self.cu(1)} {self.cu(0)} {vs}") else: w, b = self.tmp(), self.tmp() - self.emit(f"{w} = OpLoad %uint {p} Aligned 4") + self.emit(f"{w} = OpLoad %uint {p} {load_mem}") self.emit(f"{b} = OpBitFieldUExtract %uint {w} {sh} {self.cu(8)}") if value is None: value = b @@ -2622,6 +2678,8 @@ def buffer_load(self, op, a, mods): ptr, host = self.tmp(), self.host_addr(addr, "load", lambda: self.guard_delta(n, step)) self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {host}") + load_mem = self._psb_load_op(mods) + def guarded(cond, dwords): """One selection construct that loads these dwords when cond holds; the phis give 0 otherwise.""" lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end" @@ -2632,7 +2690,7 @@ def guarded(cond, dwords): loaded = [] for i in dwords: p, v_do = self.buf_dword_ptr(ptr, host, step, i), self.tmp() - self.emit(f"{v_do} = OpLoad %uint {p} Aligned 4") + self.emit(f"{v_do} = OpLoad %uint {p} {load_mem}") loaded.append(v_do) self.emit(f"OpBranch {lbl_end}") self.emit(f"{lbl_end} = OpLabel") @@ -2688,8 +2746,9 @@ def buffer_load_sub(self, op, a, mods): self.emit(f"{sh} = OpShiftLeftLogical %uint {b3} {self.cu(3)}") 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}") + load_mem = self._psb_load_op(mods) p0, w0 = self.buf_dword_ptr(ptr, host, step, 0), self.tmp() - self.emit(f"{w0} = OpLoad %uint {p0} Aligned 4") + self.emit(f"{w0} = OpLoad %uint {p0} {load_mem}") ext = "OpBitFieldSExtract" if signed else "OpBitFieldUExtract" val = self.tmp() if nbytes == 1: @@ -2699,7 +2758,7 @@ def buffer_load_sub(self, op, a, mods): self.emit(f"{cross} = OpIEqual %bool {b3} {self.cu(3)}") self.emit(f"{idx1} = OpSelect %uint {cross} {self.cu(1)} {self.cu(0)}") p1 = self.buf_dword_ptr(ptr, host, step, idx1, same_base=True) # idx1 0: the dword p0 reads - self.emit(f"{w1} = OpLoad %uint {p1} Aligned 4") + self.emit(f"{w1} = OpLoad %uint {p1} {load_mem}") self.emit(f"{lo_part} = OpShiftRightLogical %uint {w0} {sh}") self.emit(f"{hi_byte} = OpBitFieldUExtract %uint {w1} {self.cu(0)} {self.cu(8)}") self.emit(f"{hi_sh} = OpShiftLeftLogical %uint {hi_byte} {self.cu(8)}") @@ -2778,6 +2837,29 @@ def fmt_desc_table(cls): table.append(word) return table + # The run-time FORMAT encode (3B.6): packed into one 32-bit word per format code: + # bits [3:0] enc_kind (0..9), [6:4] ncomp (0..4), [12:7]..[30:25] widths[0..3], bit 31 = BGRA swap (50, 56). + ENC_NONE, ENC_F32, ENC_U32, ENC_I32, ENC_UINT, ENC_SINT, ENC_UNORM, ENC_SNORM, ENC_F16, ENC_UFLOAT = range(10) + ENC_KINDS = {"f32": ENC_F32, "u32": ENC_U32, "i32": ENC_I32, "uint": ENC_UINT, + "sint": ENC_SINT, "unorm": ENC_UNORM, "uscaled": ENC_UNORM, + "snorm": ENC_SNORM, "sscaled": ENC_SNORM, "f16": ENC_F16, "ufloat": ENC_UFLOAT} + + @classmethod + def fmt_enc_desc_table(cls): + """One uint per format code for table-driven buffer_store_format encoding.""" + table = [] + for code in range(128): + entry = cls.FORMATS.get(code) + kind = cls.ENC_KINDS.get(entry[1], cls.ENC_NONE) if entry else cls.ENC_NONE + widths = entry[2] if entry else () + word = kind | (len(widths) << 4) + for i in range(4): + word |= (widths[i] if i < len(widths) else 0) << (7 + 6 * i) + if code in (50, 56): + word |= 1 << 31 + table.append(word) + return table + @classmethod def fmt_norm_reps(cls): """The 64-bit repeat constants of the exact norm quotient, one per width (1..16). @@ -3877,13 +3959,14 @@ def buffer_load_format(self, op, a, mods, fixed_fmt=None): self.emit(f"{lbl_do} = OpLabel") ptr, host = self.tmp(), self.host_addr(aligned, "load", lambda: self.guard_delta(need, step)) self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {host}") + load_mem = self._psb_load_op(mods) loaded = [] for i in range(5): ok, idx, v = self.tmp(), self.tmp(), self.tmp() self.emit(f"{ok} = OpULessThan %bool {self.cu(i)} {need}") self.emit(f"{idx} = OpSelect %uint {ok} {self.cu(i)} {self.cu(0)}") p = self.buf_dword_ptr(ptr, host, step, idx) - self.emit(f"{v} = OpLoad %uint {p} Aligned 4") + self.emit(f"{v} = OpLoad %uint {p} {load_mem}") loaded.append(v) self.emit(f"OpBranch {lbl_end}") self.emit(f"{lbl_end} = OpLabel") @@ -4143,6 +4226,9 @@ def global_sub(self, op, a, mods): self.emit(f"OpSelectionMerge {lbl_end} None") self.emit(f"OpBranchConditional {act} {lbl_do} {lbl_end}") self.emit(f"{lbl_do} = OpLabel") + if store and self._is_coherent_mem(mods): + self.uses_vmm = True + load_mem = None if store else self._psb_load_op(mods) value = None for k in range(nbytes): va = full @@ -4160,7 +4246,7 @@ def global_sub(self, op, a, mods): self.emit(f"{t2} = OpAtomicOr %uint {p} {self.cu(1)} {self.cu(0)} {vs}") else: w, b = self.tmp(), self.tmp() - self.emit(f"{w} = OpLoad %uint {p} Aligned 4") + self.emit(f"{w} = OpLoad %uint {p} {load_mem}") self.emit(f"{b} = OpBitFieldUExtract %uint {w} {sh} {self.cu(8)}") if value is None: value = b @@ -4202,6 +4288,7 @@ def global_mem(self, op, a, mods): act = self.active_b() lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end" if load: + load_mem = self._psb_load_op(mods) # Inactive lanes don't load (and keep their registers): guard the access, merge with OpPhi per dword. olds = [self.load_reg("vgpr", data["r"] + i) for i in range(n)] pre = self.current_label_placeholder() @@ -4221,7 +4308,7 @@ def global_mem(self, op, a, mods): 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"{w} = OpLoad %uint {p0} {load_mem}") self.emit(f"{shb} = OpShiftLeftLogical %uint {b3} {self.cu(3)}") ext = "OpBitFieldSExtract" if signed else "OpBitFieldUExtract" if bits == 8: @@ -4235,7 +4322,7 @@ def global_mem(self, op, a, mods): self.emit(f"OpBranchConditional {cross} {lbl_cross} {lbl_cend}") self.emit(f"{lbl_cross} = OpLabel") self.emit(f"{p1} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(1)}") - self.emit(f"{w1} = OpLoad %uint {p1} Aligned 4") + self.emit(f"{w1} = OpLoad %uint {p1} {load_mem}") self.emit(f"{hi_byte} = OpBitFieldUExtract %uint {w1} {self.cu(0)} {self.cu(8)}") self.emit(f"{hi_sh} = OpShiftLeftLogical %uint {hi_byte} {self.cu(8)}") self.emit(f"{crossed} = OpBitwiseOr %uint {lo_part} {hi_sh}") @@ -4250,7 +4337,7 @@ def global_mem(self, op, a, mods): for i in range(n): p, v = self.tmp(), self.tmp() self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(i)}") - self.emit(f"{v} = OpLoad %uint {p} Aligned 4") + self.emit(f"{v} = OpLoad %uint {p} {load_mem}") vals.append(v) done_lbl = self.current_label_placeholder() self.emit(f"OpBranch {lbl_end}") @@ -4263,6 +4350,7 @@ def global_mem(self, op, a, mods): for i, ph in enumerate(phis): self.store_reg("vgpr", data["r"] + i, ph) else: + store_mem = self._psb_store_op(mods) vals = [self.load_reg("vgpr", data["r"] + i) for i in range(n)] self.emit(f"OpSelectionMerge {lbl_end} None") self.emit(f"OpBranchConditional {act} {lbl_do} {lbl_end}") @@ -4272,7 +4360,7 @@ def global_mem(self, op, a, mods): for i in range(n): p = self.tmp() self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(i)}") - self.emit(f"OpStore {p} {vals[i]} Aligned 4") + self.emit(f"OpStore {p} {vals[i]} {store_mem}") self.emit(f"OpBranch {lbl_end}") self.emit(f"{lbl_end} = OpLabel") @@ -4702,45 +4790,219 @@ def part(k): return addr, d3, in_b, (part if mode in (None, 0, 3) else None), step return addr, d3, in_b, step + def _fmt_enc_chan_body(self, mode, val, w, is_signed): + """Encode one channel of a dynamic-format buffer store (branch-free, shared across all 77 FORMATS).""" + # Clamp width 0 (unused channel) to 1 so shifts and (w - 1) stay well-defined. + w_is0, w_nz, w_lo, wm1, wm1_lo = (self.tmp() for _ in range(5)) + self.emit(f"{w_is0} = OpIEqual %bool {w} {self.cu(0)}") + self.emit(f"{w_nz} = OpSelect %uint {w_is0} {self.cu(1)} {w}") + self.emit(f"{w_lo} = OpBitwiseAnd %uint {w_nz} {self.cu(31)}") + self.emit(f"{wm1} = OpISub %uint {w_nz} {self.cu(1)}") + self.emit(f"{wm1_lo} = OpBitwiseAnd %uint {wm1} {self.cu(31)}") + + # Narrow UINT: saturate to (1 << w) - 1. + u_one, u_max, c_uint = (self.tmp() for _ in range(3)) + self.emit(f"{u_one} = OpShiftLeftLogical %uint {self.cu(1)} {w_lo}") + self.emit(f"{u_max} = OpISub %uint {u_one} {self.cu(1)}") + self.emit(f"{c_uint} = OpExtInst %uint %glsl UMin {val} {u_max}") + + # Narrow SINT: clamp signed 32-bit int to [-2^(w-1), 2^(w-1) - 1]. + s_half, s_hi_u, s_lo_u, s_clamped, c_sint = (self.tmp() for _ in range(5)) + self.emit(f"{s_half} = OpShiftLeftLogical %uint {self.cu(1)} {wm1_lo}") + self.emit(f"{s_hi_u} = OpISub %uint {s_half} {self.cu(1)}") + self.emit(f"{s_lo_u} = OpISub %uint {self.cu(0)} {s_half}") + self.emit(f"{s_clamped} = OpExtInst %int %glsl SClamp {self.as_int(val)} " + f"{self.as_int(s_lo_u)} {self.as_int(s_hi_u)}") + self.emit(f"{c_sint} = OpBitcast %uint {s_clamped}") + + # Exact single-rounded UNORM/SNORM (same 64-bit arithmetic as encode_norm_bits, with run-time scale). + nw, n_one, scale, scale64 = (self.tmp() for _ in range(4)) + self.emit(f"{nw} = OpSelect %uint {is_signed} {wm1_lo} {w_lo}") + self.emit(f"{n_one} = OpShiftLeftLogical %uint {self.cu(1)} {nw}") + self.emit(f"{scale} = OpISub %uint {n_one} {self.cu(1)}") + self.emit(f"{scale64} = OpUConvert %ulong {scale}") + sign, neg, a = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{sign} = OpShiftRightLogical %uint {val} {self.cu(31)}") + self.emit(f"{neg} = OpINotEqual %bool {sign} {self.cu(0)}") + self.emit(f"{a} = OpBitwiseAnd %uint {val} {self.cu(0x7FFFFFFF)}") + small, ge1, exp_, ec, ec2, shift, sh64, sh1, sh1_64 = (self.tmp() for _ in range(9)) + self.emit(f"{small} = OpULessThan %bool {a} {self.cu(0x37000000)}") + self.emit(f"{ge1} = OpUGreaterThanEqual %bool {a} {self.cu(0x3F800000)}") + self.emit(f"{exp_} = OpShiftRightLogical %uint {a} {self.cu(23)}") + self.emit(f"{ec} = OpExtInst %uint %glsl UMax {exp_} {self.cu(110)}") + self.emit(f"{ec2} = OpExtInst %uint %glsl UMin {ec} {self.cu(126)}") + self.emit(f"{shift} = OpISub %uint {self.cu(150)} {ec2}") + self.emit(f"{sh64} = OpUConvert %ulong {shift}") + self.emit(f"{sh1} = OpISub %uint {shift} {self.cu(1)}") + self.emit(f"{sh1_64} = OpUConvert %ulong {sh1}") + mant, m, m64, p, half, ps, q64, q, mag1, mag, nmag, neg_val, c_norm = (self.tmp() for _ in range(13)) + self.emit(f"{mant} = OpBitwiseAnd %uint {a} {self.cu(0x7FFFFF)}") + self.emit(f"{m} = OpBitwiseOr %uint {mant} {self.cu(0x800000)}") + self.emit(f"{m64} = OpUConvert %ulong {m}") + self.emit(f"{p} = OpIMul %ulong {m64} {scale64}") + self.emit(f"{half} = OpShiftLeftLogical %ulong {self.cl(1)} {sh1_64}") + self.emit(f"{ps} = OpIAdd %ulong {p} {half}") + self.emit(f"{q64} = OpShiftRightLogical %ulong {ps} {sh64}") + self.emit(f"{q} = OpUConvert %uint {q64}") + self.emit(f"{mag1} = OpSelect %uint {small} {self.cu(0)} {q}") + self.emit(f"{mag} = OpSelect %uint {ge1} {scale} {mag1}") + self.emit(f"{nmag} = OpISub %uint {self.cu(0)} {mag}") + self.emit(f"{neg_val} = OpSelect %uint {is_signed} {nmag} {self.cu(0)}") + self.emit(f"{c_norm} = OpSelect %uint {neg} {neg_val} {mag}") + + # F16: round toward zero with finite overflow clamping to +-65504. + c_f16 = self.mem_f16(self.tof(val)) + + # UFLOAT (10- or 11-bit unsigned float, mb = 5 or 6): same integer ops as ufloat_encode_bits. + is11, sh_base, sh_m, mmask, max_fin, inf_b = (self.tmp() for _ in range(6)) + self.emit(f"{is11} = OpIEqual %bool {w_nz} {self.cu(11)}") + self.emit(f"{sh_base} = OpSelect %uint {is11} {self.cu(130)} {self.cu(131)}") + self.emit(f"{sh_m} = OpSelect %uint {is11} {self.cu(17)} {self.cu(18)}") + self.emit(f"{mmask} = OpSelect %uint {is11} {self.cu(0x3F)} {self.cu(0x1F)}") + self.emit(f"{max_fin} = OpSelect %uint {is11} {self.cu((30 << 6) | 0x3F)} {self.cu((30 << 5) | 0x1F)}") + self.emit(f"{inf_b} = OpSelect %uint {is11} {self.cu(31 << 6)} {self.cu(31 << 5)}") + (sh0, shc, dn, nr0, nr, nm, nm1, nz, nmant, nanb, isnan, isinf, big, norm, + r0, r1, r2, snan, ng, r3, c_ufloat) = (self.tmp() for _ in range(21)) + self.emit(f"{sh0} = OpISub %uint {sh_base} {exp_}") + self.emit(f"{shc} = OpExtInst %uint %glsl UMin {sh0} {self.cu(31)}") + self.emit(f"{dn} = OpShiftRightLogical %uint {m} {shc}") + self.emit(f"{nr0} = OpISub %uint {a} {self.cu(112 << 23)}") + self.emit(f"{nr} = OpShiftRightLogical %uint {nr0} {sh_m}") + self.emit(f"{nm} = OpShiftRightLogical %uint {a} {sh_m}") + self.emit(f"{nm1} = OpBitwiseAnd %uint {nm} {mmask}") + self.emit(f"{nz} = OpIEqual %bool {nm1} {self.cu(0)}") + self.emit(f"{nmant} = OpSelect %uint {nz} {self.cu(1)} {nm1}") + self.emit(f"{nanb} = OpBitwiseOr %uint {nmant} {inf_b}") + self.emit(f"{isnan} = OpUGreaterThan %bool {a} {self.cu(0x7F800000)}") + self.emit(f"{isinf} = OpIEqual %bool {a} {self.cu(0x7F800000)}") + self.emit(f"{big} = OpUGreaterThanEqual %bool {a} {self.cu(0x47800000)}") + self.emit(f"{norm} = OpUGreaterThanEqual %bool {a} {self.cu(0x38800000)}") + self.emit(f"{r0} = OpSelect %uint {norm} {nr} {dn}") + self.emit(f"{r1} = OpSelect %uint {big} {max_fin} {r0}") + self.emit(f"{r2} = OpSelect %uint {isinf} {inf_b} {r1}") + self.emit(f"{r3} = OpSelect %uint {isnan} {nanb} {r2}") + self.emit(f"{snan} = OpLogicalNot %bool {isnan}") + self.emit(f"{ng} = OpLogicalAnd %bool {neg} {snan}") + self.emit(f"{c_ufloat} = OpSelect %uint {ng} {self.cu(0)} {r3}") + + # Pick conversion by mode (ENC_F32/ENC_U32/ENC_I32 pass val through unchanged). + res = val + for kind, cand in ((self.ENC_UINT, c_uint), (self.ENC_SINT, c_sint), + (self.ENC_UNORM, c_norm), (self.ENC_SNORM, c_norm), + (self.ENC_F16, c_f16), (self.ENC_UFLOAT, c_ufloat)): + eq, sel = self.tmp(), self.tmp() + self.emit(f"{eq} = OpIEqual %bool {mode} {self.cu(kind)}") + self.emit(f"{sel} = OpSelect %uint {eq} {cand} {res}") + res = sel + return res + def format_encode_call(self, fmt, fc, normalized, unorm_view, ic, signed_ic, two): """The 4 words of the element a typed store writes, per the run-time FORMAT, and its size in bytes (0 for a code - outside FORMATS: nothing is stored). One function per module like the decode (format_decode_call): inlined, every - store site carried every format's encode, three times the module of the older table (cs_store 169 KB -> 503 KB). + outside FORMATS: nothing is stored). Table-driven and branch-free (like format_decode_call / SHADER-849), + replacing the old 77-way OpSwitch with a single %fmt_enc_desc_tab lookup and shared %fmt_enc_chan helper. The five lists are 4 uint ids each: the raw float bits, the same with NaN -> 0 (NORM stores), the B/R-swapped view for 50 and 56, the integers and the sign-extended d16 integers; a component the instruction does not give is 0.""" if self.fmt_enc_fn is None: - names = ["%fe_fmt"] + [f"%fe_{g}{i}" for g in "fnvis" for i in range(4)] + [f"%fe_t{i}" for i in range(8)] + self.uses_fmt_enc_table = True + for v in Gen.fmt_enc_desc_table(): + self.cu(v) + self.cu(128) saved, self.body = self.body, [] + chan_res = self._fmt_enc_chan_body("%fec_mode", "%fec_val", "%fec_w", "%fec_signed") + chan_lines = self.body + self.body = [] + chan_fn = (["%fmt_enc_chan = OpFunction %uint None %fn_fmt_enc_chan", + "%fec_mode = OpFunctionParameter %uint", "%fec_val = OpFunctionParameter %uint", + "%fec_w = OpFunctionParameter %uint", "%fec_signed = OpFunctionParameter %bool", + "%fec_entry = OpLabel"] + chan_lines + [f"OpReturnValue {chan_res}", "OpFunctionEnd"]) + + names = ["%fe_fmt"] + [f"%fe_{g}{i}" for g in "fnvis" for i in range(4)] + [f"%fe_t{i}" for i in range(8)] params = names[1:21] tw = names[21:29] # the channels a two-component V# store takes: norm, float, int, signed int (2 each) lists = [params[4 * g:4 * g + 4] for g in range(5)] - # FORMAT is a 7-bit integer. One case per supported code, all other codes return zero. - cases = " ".join(f"{code} %fe_case_{code}" for code in self.FORMATS) - self.emit("OpSelectionMerge %fe_unknown None") - self.emit(f"OpSwitch %fe_fmt %fe_unknown {cases}") - for code, (_, kind, widths) in self.FORMATS.items(): - self.emit(f"%fe_case_{code} = OpLabel") - source = lists[1] if kind in ("unorm", "snorm", "uscaled", "sscaled") else lists[0] - if code in (50, 56): - source = lists[2] - integer_source = lists[4] if kind in ("i32", "sint") else lists[3] - if len(widths) == 2: - # through a V# a two-component format takes the channels DST_SEL picks (x, y; x, w; y, x; ...), swizzled - # at the store site like gfx1036 does it; tbuffer stores are encoded in line, with (x, y) - source = tw[0:2] if kind in ("unorm", "snorm", "uscaled", "sscaled") else tw[2:4] - integer_source = tw[6:8] if kind in ("i32", "sint") else tw[4:6] - words = self.encode_format(source[:len(widths)] + [self.cu(0)] * 4, - integer_source[:len(widths)] + [self.cu(0)] * 4, code) - words = (words + [self.cu(0)] * 4)[:4] - res = self.tmp() - self.emit(f"{res} = OpCompositeConstruct %v4uint_fmt " + " ".join(words)) - self.emit(f"OpReturnValue {res}") - self.emit("%fe_unknown = OpLabel") - zero = self.tmp() - self.emit(f"{zero} = OpCompositeConstruct %v4uint_fmt " + " ".join([self.cu(0)] * 4)) - self.emit(f"OpReturnValue {zero}") + + desc = self.fmt_table_get("%_ptr_Private_fmt_enc_elem", "%fmt_enc_desc_tab", "%fe_fmt") + mode, ncomp_r, ncomp, bgra_b, is_bgra, is_two = (self.tmp() for _ in range(6)) + self.emit(f"{mode} = OpBitwiseAnd %uint {desc} {self.cu(15)}") + self.emit(f"{ncomp_r} = OpShiftRightLogical %uint {desc} {self.cu(4)}") + self.emit(f"{ncomp} = OpBitwiseAnd %uint {ncomp_r} {self.cu(7)}") + self.emit(f"{bgra_b} = OpShiftRightLogical %uint {desc} {self.cu(31)}") + self.emit(f"{is_bgra} = OpINotEqual %bool {bgra_b} {self.cu(0)}") + self.emit(f"{is_two} = OpIEqual %bool {ncomp} {self.cu(2)}") + widths = [] + for i in range(4): + wr, wi = self.tmp(), self.tmp() + self.emit(f"{wr} = OpShiftRightLogical %uint {desc} {self.cu(7 + 6 * i)}") + self.emit(f"{wi} = OpBitwiseAnd %uint {wr} {self.cu(63)}") + widths.append(wi) + offsets = [self.cu(0)] + for i in range(1, 4): + o = self.tmp() + self.emit(f"{o} = OpIAdd %uint {offsets[-1]} {widths[i - 1]}") + offsets.append(o) + + is_unorm, is_snorm, is_norm = (self.tmp() for _ in range(3)) + self.emit(f"{is_unorm} = OpIEqual %bool {mode} {self.cu(self.ENC_UNORM)}") + self.emit(f"{is_snorm} = OpIEqual %bool {mode} {self.cu(self.ENC_SNORM)}") + self.emit(f"{is_norm} = OpLogicalOr %bool {is_unorm} {is_snorm}") + is_u32, is_uint, is_int_u = (self.tmp() for _ in range(3)) + self.emit(f"{is_u32} = OpIEqual %bool {mode} {self.cu(self.ENC_U32)}") + self.emit(f"{is_uint} = OpIEqual %bool {mode} {self.cu(self.ENC_UINT)}") + self.emit(f"{is_int_u} = OpLogicalOr %bool {is_u32} {is_uint}") + is_i32, is_sint, is_int_s = (self.tmp() for _ in range(3)) + self.emit(f"{is_i32} = OpIEqual %bool {mode} {self.cu(self.ENC_I32)}") + self.emit(f"{is_sint} = OpIEqual %bool {mode} {self.cu(self.ENC_SINT)}") + self.emit(f"{is_int_s} = OpLogicalOr %bool {is_i32} {is_sint}") + + words = [self.cu(0)] * 4 + # Channels 0..3 can only land in dwords: 0 -> (0,), 1 -> (0,1), 2 -> (0,1,2), 3 -> (0,1,3). + chan_dwords = ((0,), (0, 1), (0, 1, 2), (0, 1, 3)) + for c in range(4): + ns0 = self.tmp() + self.emit(f"{ns0} = OpSelect %uint {is_bgra} {lists[2][c]} {lists[1][c]}") + if c < 2: + ns, fs, us, ss = (self.tmp() for _ in range(4)) + self.emit(f"{ns} = OpSelect %uint {is_two} {tw[c]} {ns0}") + self.emit(f"{fs} = OpSelect %uint {is_two} {tw[2 + c]} {lists[0][c]}") + self.emit(f"{us} = OpSelect %uint {is_two} {tw[4 + c]} {lists[3][c]}") + self.emit(f"{ss} = OpSelect %uint {is_two} {tw[6 + c]} {lists[4][c]}") + else: + ns, fs, us, ss = ns0, lists[0][c], lists[3][c], lists[4][c] + s0, s1, src = (self.tmp() for _ in range(3)) + self.emit(f"{s0} = OpSelect %uint {is_norm} {ns} {fs}") + self.emit(f"{s1} = OpSelect %uint {is_int_u} {us} {s0}") + self.emit(f"{src} = OpSelect %uint {is_int_s} {ss} {s1}") + + field = self.tmp() + self.emit(f"{field} = OpFunctionCall %uint %fmt_enc_chan {mode} {src} {widths[c]} {is_snorm}") + active, w32, wlo, one, m1, mask, masked, bo, shifted, contrib = (self.tmp() for _ in range(10)) + self.emit(f"{active} = OpULessThan %bool {self.cu(c)} {ncomp}") + self.emit(f"{w32} = OpIEqual %bool {widths[c]} {self.cu(32)}") + self.emit(f"{wlo} = OpBitwiseAnd %uint {widths[c]} {self.cu(31)}") + self.emit(f"{one} = OpShiftLeftLogical %uint {self.cu(1)} {wlo}") + self.emit(f"{m1} = OpISub %uint {one} {self.cu(1)}") + self.emit(f"{mask} = OpSelect %uint {w32} {self.cu(0xFFFFFFFF)} {m1}") + self.emit(f"{masked} = OpBitwiseAnd %uint {field} {mask}") + self.emit(f"{bo} = OpBitwiseAnd %uint {offsets[c]} {self.cu(31)}") + self.emit(f"{shifted} = OpShiftLeftLogical %uint {masked} {bo}") + self.emit(f"{contrib} = OpSelect %uint {active} {shifted} {self.cu(0)}") + if c == 0: + words[0] = contrib + else: + wi = self.tmp() + self.emit(f"{wi} = OpShiftRightLogical %uint {offsets[c]} {self.cu(5)}") + for j in chan_dwords[c]: + hit, part, merged = (self.tmp() for _ in range(3)) + self.emit(f"{hit} = OpIEqual %bool {wi} {self.cu(j)}") + self.emit(f"{part} = OpSelect %uint {hit} {contrib} {self.cu(0)}") + self.emit(f"{merged} = OpBitwiseOr %uint {words[j]} {part}") + words[j] = merged + + res = self.tmp() + self.emit(f"{res} = OpCompositeConstruct %v4uint_fmt " + " ".join(words)) + self.emit(f"OpReturnValue {res}") lines, self.body = self.body, saved - self.fmt_enc_fn = (["%fmt_encode_fn = OpFunction %v4uint_fmt None %fn_fmt_encode"] + + self.fmt_enc_fn = (chan_fn + ["%fmt_encode_fn = OpFunction %v4uint_fmt None %fn_fmt_encode"] + [f"{q} = OpFunctionParameter %uint" for q in names] + ["%fe_entry = OpLabel"] + lines + ["OpFunctionEnd"]) r = self.tmp() @@ -4771,6 +5033,7 @@ def buffer_store(self, op, a, mods, fixed_fmt=None): bounds check uses its element size, whatever the V# says. Only active lanes store, inside a structured if.""" if any(m in mods for m in ("lds", "tfe", "d16")): raise Unsupported(op + " form") + store_mem = self._psb_store_op(mods) d16 = "_d16_" in op vd = a[0] dword_store = op.startswith("buffer_store_dword") @@ -4824,7 +5087,7 @@ def buffer_store(self, op, a, mods, fixed_fmt=None): self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") self.emit(f"{lbl_do} = OpLabel") p = self.buf_dword_ptr(ptr, host, step, i) - self.emit(f"OpStore {p} {w} Aligned 4") + self.emit(f"OpStore {p} {w} {store_mem}") self.emit(f"OpBranch {lbl_end}") self.emit(f"{lbl_end} = OpLabel") return @@ -4848,7 +5111,7 @@ def buffer_store(self, op, a, mods, fixed_fmt=None): if words is not None: for i, w in enumerate(words): p = self.buf_dword_ptr(ptr, host, step, i) - self.emit(f"OpStore {p} {w} Aligned 4") + self.emit(f"OpStore {p} {w} {store_mem}") else: fmt, comps, f32, fl, icomps = plans # Every format in FORMATS (the same table the loads decode); unknown formats store nothing. @@ -4920,7 +5183,7 @@ def swiz2(arr): if size >= 4: for k, w in enumerate(words[:size // 4]): pp = self.buf_dword_ptr(ptr, host, step, k) - self.emit(f"OpStore {pp} {w} Aligned 4") + self.emit(f"OpStore {pp} {w} {store_mem}") else: # 1- or 2-byte element: merge into its dword with atomics so neighbours are kept. al, sh, sh8, ap, mk, mks, inv, val, vs, t1, t2 = (self.tmp() for _ in range(11)) @@ -4955,7 +5218,7 @@ def swiz2(arr): self.emit(f"OpBranchConditional {big} {lk} {le}") self.emit(f"{lk} = OpLabel") pp = self.buf_dword_ptr(ptr, host, step, k) - self.emit(f"OpStore {pp} {words[k]} Aligned 4") + self.emit(f"OpStore {pp} {words[k]} {store_mem}") self.emit(f"OpBranch {le}") self.emit(f"{le} = OpLabel") # 1- or 2-byte element: merge into its dword with atomics so neighbours are kept. @@ -5378,9 +5641,14 @@ def ds_append(self, op, a, mods): val = read(fi) else: self.uses_subgroup = self.uses_ballot = True - fi, val = self.tmp(), self.tmp() - self.emit(f"{fi} = OpBitwiseAnd %uint {first} {self.cu(63 if self.wave64 else 31)}") - self.emit(f"{val} = OpGroupNonUniformShuffle %uint {self.cu(3)} {old} {fi}") + any_act, fi, bal, present, safe_fi, val = (self.tmp() for _ in range(6)) + sgl = self.subgroup_lane() + self.emit(f"{any_act} = OpLogicalOr %bool {lz} {hz}") + self.emit(f"{fi} = OpSelect %uint {any_act} {first} {sgl}") + self.emit(f"{bal} = OpGroupNonUniformBallot %v4uint_bal {self.cu(3)} %true") + self.emit(f"{present} = OpGroupNonUniformBallotBitExtract %bool {self.cu(3)} {bal} {fi}") + self.emit(f"{safe_fi} = OpSelect %uint {present} {fi} {sgl}") + self.emit(f"{val} = OpGroupNonUniformShuffle %uint {self.cu(3)} {old} {safe_fi}") self.dst(a[0], val) LDS_WORDS = {"b32": 1, "b64": 2, "b96": 3, "b128": 4} @@ -5824,28 +6092,48 @@ def wave32_ballot_word(self, ballot): self.emit(f"{word} = OpSelect %uint {upper} {hi} {lo}") return word - def wave32_first_running_lane(self): + def wave32_first_running_lane(self, ballot=None): """The lowest running lane of this wave32 fragment's 32-lane half (0-31): the lane a uniform value is read from. A fixed lane (0 of the half) need not be running: a quad with no covered sample, or helpers a driver - leaves out of subgroup operations, read as undefined (SHADER-1016).""" - ballot, any_, lsb, first = (self.tmp() for _ in range(4)) - self.emit(f"{ballot} = OpGroupNonUniformBallot %v4uint_bal {self.cu(3)} %true") + leaves out of subgroup operations, read as undefined (SHADER-1016). When the half's ballot word is empty, + fall back to this invocation's own logical lane (never lane 0, which may not be launched).""" + if ballot is None: + ballot = self.tmp() + self.emit(f"{ballot} = OpGroupNonUniformBallot %v4uint_bal {self.cu(3)} %true") + any_, lsb, first = (self.tmp() for _ in range(3)) word = self.wave32_ballot_word(ballot) - # An empty word (a helper a driver leaves out of its own ballot) reads lane 0, as v_readfirstlane does, - # never FindILsb's 0xFFFFFFFF. self.emit(f"{any_} = OpINotEqual %bool {word} {self.cu(0)}") self.emit(f"{lsb} = OpExtInst %uint %glsl FindILsb {word}") - self.emit(f"{first} = OpSelect %uint {any_} {lsb} {self.cu(0)}") + self.emit(f"{first} = OpSelect %uint {any_} {lsb} {self.wave_lane()}") + self.uses_subgroup = self.uses_ballot = True + return first + + def subgroup_first_running_lane(self, ballot=None): + """The lowest running physical lane in the subgroup (0..SubgroupSize-1), or this invocation's own subgroup + lane when the ballot is empty. Never falls back to lane 0, which may not be launched in a partial wave.""" + if ballot is None: + ballot = self.tmp() + self.emit(f"{ballot} = OpGroupNonUniformBallot %v4uint_bal {self.cu(3)} %true") + if self.stage == "vs": + lsb, any_ = self.ballot_lsb_by_words(ballot, with_any=True) + else: + self.uses_vote = True + lsb, any_ = self.tmp(), self.tmp() + self.emit(f"{lsb} = OpGroupNonUniformBallotFindLSB %uint {self.cu(3)} {ballot}") + self.emit(f"{any_} = OpGroupNonUniformAny %bool {self.cu(3)} %true") + first = self.tmp() + self.emit(f"{first} = OpSelect %uint {any_} {lsb} {self.subgroup_lane()}") self.uses_subgroup = self.uses_ballot = True return first - def ballot_lsb_by_words(self, bal): + def ballot_lsb_by_words(self, bal, with_any=False): """The lowest set bit of a subgroup ballot, from its four words with FindILsb: the lane OpGroupNonUniformBallotFindLSB gives (a ballot has no bit at or above the subgroup size), without asking for the subgroup size. MoltenVK lowers BallotFindLSB, like the SubgroupSize built-in, to Metal's threads_per_simdgroup input, which a vertex function can't declare (Apple M4, MoltenVK 1.4.2), so vertex - shaders use this form. Like the op, the result means nothing for an empty ballot; callers select 0 then.""" + shaders use this form. When `with_any` is True, also returns a %bool that is true iff any word is non-zero.""" r = None + any_ = None for k in (3, 2, 1, 0): # the lowest non-zero word wins, so it is selected last w, lsb = self.tmp(), self.tmp() self.emit(f"{w} = OpCompositeExtract %uint {bal} {k}") @@ -5854,14 +6142,21 @@ def ballot_lsb_by_words(self, bal): at = self.tmp() self.emit(f"{at} = OpIAdd %uint {lsb} {self.cu(32 * k)}") lsb = at + nz = self.tmp() if (r is not None or with_any) else None + if nz is not None: + self.emit(f"{nz} = OpINotEqual %bool {w} {self.cu(0)}") if r is None: r = lsb + any_ = nz else: - nz, pick = self.tmp(), self.tmp() - self.emit(f"{nz} = OpINotEqual %bool {w} {self.cu(0)}") + pick = self.tmp() self.emit(f"{pick} = OpSelect %uint {nz} {lsb} {r}") r = pick - return r + if with_any: + both = self.tmp() + self.emit(f"{both} = OpLogicalOr %bool {any_} {nz}") + any_ = both + return (r, any_) if with_any else r # ---- wave64 emulation (--wave64-emulate) ---- # A wave64 compute or mesh shader runs exact on any subgroup size. Each lane is one invocation as usual, but no @@ -6265,12 +6560,13 @@ def ds_lane_read(self, dst: dict, data: str, src: str, lane: str) -> None: self.g_shuffle(result, value, src) else: # Redirect absent source lanes before the shuffle: even a masked undefined result is undefined. - ballot, present, safe_src, shuffled, mask = (self.tmp() for _ in range(5)) + ballot, present, safe_phys, shuffled, mask = (self.tmp() for _ in range(5)) physical_src = self.wave_source_lane(src) + physical_self = self.subgroup_lane() self.emit(f"{ballot} = OpGroupNonUniformBallot %v4uint_bal %c3 %true") self.emit(f"{present} = OpGroupNonUniformBallotBitExtract %bool %c3 {ballot} {physical_src}") - self.emit(f"{safe_src} = OpSelect %uint {present} {src} {lane}") - self.emit(f"{shuffled} = OpGroupNonUniformShuffle %uint %c3 {value} {self.wave_source_lane(safe_src)}") + self.emit(f"{safe_phys} = OpSelect %uint {present} {physical_src} {physical_self}") + self.emit(f"{shuffled} = OpGroupNonUniformShuffle %uint %c3 {value} {safe_phys}") self.emit(f"{mask} = OpSelect %uint {present} {self.cu(0xFFFFFFFF)} {self.cu(0)}") self.emit(f"{result} = OpBitwiseAnd %uint {shuffled} {mask}") self.uses_subgroup = self.uses_ballot = True @@ -6332,13 +6628,10 @@ def ds_permute(self, a, mods): self.emit(f"{lane} = OpCopyObject %uint {self.wave_lane()}") self.emit(f"{rl} = OpBitwiseAnd %uint {lane} {self.cu(31)}") self.emit(f"{mine} = OpIAdd %uint {rl} {self.cu(1)}") + sgl = self.subgroup_lane() if self.wave64 or self.wave32_fragment: - sgl = self.tmp() - self.emit(f"{sgl} = OpLoad %uint %sg_lane") self.emit(f"{half} = OpBitwiseAnd %uint {sgl} {self.cu(32)}") - self_lane = sgl - else: - self_lane = lane + self_lane = sgl bal = self.tmp() self.emit(f"{bal} = OpGroupNonUniformBallot %v4uint_bal %c3 %true") acc = self.cu(0) @@ -6550,8 +6843,13 @@ def park_masks(self, blocks): # lane_masks merges a mask on one path with plain data on another by dropping the register, # so "not in cur_masks" does not prove it is data on every path. Keep a conservative set. self.ever_mask = {r for m in self.lane_masks.values() for r in m if isinstance(r, int)} - slots = lane_masks.parked(blocks[0], self.lane_masks) - self.parked = {slot: self.SGPRS + i for i, slot in enumerate(slots)} + slots = lane_masks.parked(blocks[0], self.lane_masks, wave64=self.wave64) + self.scalar_spills = set(lane_masks.scalar_spills(blocks[0], blocks[1], wave64=self.wave64)) + self.spill_readlanes, spill_read_slots = lane_masks.definite_spill_reads( + blocks[0], blocks[1], wave64=self.wave64 + ) + all_slots = sorted(set(slots) | self.scalar_spills | set(spill_read_slots)) + self.parked = {slot: self.SGPRS + i for i, slot in enumerate(all_slots)} def mask_half(self, a): """For a 32-bit lane-mask operand in wave64, return 'lo' (lanes 0-31), 'hi' (lanes 32-63), or None.""" @@ -6707,7 +7005,9 @@ def quad_any(self, v): o = self.tmp() self.emit(f"{o} = OpBitwiseOr %uint {acc} {w}") acc = o - elif self.stage in ("ps", "cs"): + elif self.stage == "ps": + # Fragment shaders always launch complete 2x2 pixel quads (including helper invocations), and Vulkan + # guarantees OpGroupNonUniformQuadSwap includes helpers in the quad. self.uses_subgroup = self.uses_quad = True acc = b for d in (0, 1): # horizontal, then vertical neighbour @@ -6716,19 +7016,26 @@ def quad_any(self, v): self.emit(f"{o} = OpBitwiseOr %uint {acc} {sw}") acc = o else: - # Quad operations are only guaranteed in fragment and compute shaders (quadOperationsInAllStages): - # vertex, geometry and mesh shaders shuffle from the four lanes of the quad instead. - self.uses_subgroup = True - lane, base = self.tmp(), self.tmp() - self.sub_lane(lane) - self.emit(f"{base} = OpBitwiseAnd %uint {lane} {self.cu(0xFFFFFFFC)}") - acc = b - for k in range(4): - i, w, o = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{i} = OpIAdd %uint {base} {self.cu(k)}") - self.g_shuffle(w, b, i) - self.emit(f"{o} = OpBitwiseOr %uint {acc} {w}") - acc = o + # Non-fragment stages (CS/VS/GS/MS) can have partial quads (subgroup size or thread count not a multiple + # of 4), where QuadSwap or unguarded shuffles from absent lanes are undefined in SPIR-V. Ballot sets bit l + # iff lane l is running with `v != 0`, so extracting this lane's 4-bit quad nibble is exact on any partial + # subgroup up to 128 lanes without needing GroupNonUniformQuad or any shuffle. + self.uses_subgroup = self.uses_ballot = True + nz = self.tmp_bool_nz(v) + bal, widx, word, qoff, shifted, acc = (self.tmp() for _ in range(6)) + self.emit(f"{bal} = OpGroupNonUniformBallot %v4uint_bal {self.cu(3)} {nz}") + sgl = self.subgroup_lane() + self.emit(f"{widx} = OpShiftRightLogical %uint {sgl} {self.cu(5)}") + self.emit(f"{word} = OpCompositeExtract %uint {bal} 0") + for k in (1, 2, 3): + wk, eq, pick = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{wk} = OpCompositeExtract %uint {bal} {k}") + self.emit(f"{eq} = OpIEqual %bool {widx} {self.cu(k)}") + self.emit(f"{pick} = OpSelect %uint {eq} {wk} {word}") + word = pick + self.emit(f"{qoff} = OpBitwiseAnd %uint {sgl} {self.cu(28)}") + self.emit(f"{shifted} = OpShiftRightLogical %uint {word} {qoff}") + self.emit(f"{acc} = OpBitwiseAnd %uint {shifted} {self.cu(0xF)}") r = self.tmp() self.emit(f"{r} = OpSelect %uint {self.tmp_bool_nz(acc)} {self.cu(0xFFFFFFFF)} {self.cu(0)}") return r @@ -7145,14 +7452,20 @@ def _validate_unary_f16(self, op, raw_op, a, mods): else: raise Unsupported(f"{op} modifier") - def flush_f32(self, f): + def flush_f32(self, f, *, force=False): """v_mad_f32, v_mac_f32, v_mad_legacy_f32 and default-mode v_mul_legacy_f32 flush f32 denormals: a subnormal operand or result reads as signed zero, whatever the MODE register says. LLVM's SITargetLowering::isFMADLegal forms v_mad_f32/v_mac_f32 only when f32 denormals are flushed (SIISelLowering.cpp, llvm-project 1922c0c); - v_mad_legacy_f32 is the same VALU. Emulated as |x| < FLT_MIN -> copysign(0, x): inf and NaN compare - false and pass through, and 0 keeps its sign. Counted over the corpus before writing this (SHADER-118): - 9,297 of the 26,503 shaders use at least one of the three, 440,858 occurrences (0.99% of the corpus).""" + v_mad_legacy_f32 is the same VALU. When hardware DenormFlushToZero 32 is active (self.ftz32), the f32 + arithmetic op itself flushes inputs and output; otherwise (or when force=True for GLSL.std.450 ops + like Exp2 where DenormFlushToZero 32 is not guaranteed to flush on all drivers) emulate as + |x| < FLT_MIN -> copysign(0, x): + inf and NaN compare false and pass through, and 0 keeps its sign. Counted over the corpus before + writing this (SHADER-118): 9,297 of the 26,503 shaders use at least one of the three, 440,858 + occurrences (0.99% of the corpus).""" + if self.ftz32 and not force: + return f a, small, sign, z, r = (self.tmp() for _ in range(5)) self.emit(f"{a} = OpExtInst %float %glsl FAbs {f}") self.emit(f"{small} = OpFOrdLessThan %bool {a} {self.fconst(2.0 ** -126)}") @@ -7873,17 +8186,32 @@ def selectors(key, count, limit): src_sg = self.tmp() self.emit(f"{src_sg} = OpBitwiseOr %uint {sg_group} {src_local}") if in_bounds is not None: - # Clamp an invalid source lane before the shuffle: its value is discarded below, but the lane index - # passed to OpGroupNonUniformShuffle must still be in range. + # Clamp an invalid source lane to own subgroup lane (always running, never lane 0 which may be absent). safe_sg = self.tmp() - self.emit(f"{safe_sg} = OpSelect %uint {in_bounds} {src_sg} {self.cu(0)}") + self.emit(f"{safe_sg} = OpSelect %uint {in_bounds} {src_sg} {sgl}") else: safe_sg = src_sg shuffle_src = safe_sg if fi: - # fi:1 fetches the inactive source as well; only an out-of-row lane is still invalid. - src_ok = in_bounds if in_bounds is not None else "%true" + # fi:1 fetches an EXEC-off source lane, but an unlaunched/absent lane in a partial subgroup must + # still be redirected to sgl before OpGroupNonUniformShuffle and treated as invalid. + if src.get("k") == "vgpr": + pbal, present = self.tmp(), self.tmp() + self.emit(f"{pbal} = OpGroupNonUniformBallot %v4uint_bal {self.cu(3)} %true") + self.uses_ballot = True + self.emit(f"{present} = OpGroupNonUniformBallotBitExtract %bool {self.cu(3)} {pbal} {safe_sg}") + present_e = self.eager("%bool", present) + if in_bounds is not None: + both = self.tmp() + self.emit(f"{both} = OpLogicalAnd %bool {in_bounds} {present_e}") + src_ok = both + else: + src_ok = present_e + shuffle_src = self.tmp() + self.emit(f"{shuffle_src} = OpSelect %uint {present} {safe_sg} {sgl}") + else: + src_ok = in_bounds if in_bounds is not None else "%true" else: ballot = self.tmp() self.emit(f"{ballot} = OpGroupNonUniformBallot %v4uint_bal {self.cu(3)} {self.active_b()}") @@ -8241,16 +8569,19 @@ def _insn(self, ins): self.emit(f"{first} = OpSelect %uint {lz} {l} {fh}") self.dst(a[0], read(first)) return - self.uses_subgroup = self.uses_ballot = self.uses_vote = True + self.uses_subgroup = self.uses_ballot = True v, act = self.src_u(a[1]), self.active_b() - bal, lsb, any_, first, r = (self.tmp() for _ in range(5)) + bal, first, r = (self.tmp() for _ in range(3)) self.emit(f"{bal} = OpGroupNonUniformBallot %v4uint_bal {self.cu(3)} {act}") if self.stage == "vs": - lsb = self.ballot_lsb_by_words(bal) + lsb, any_ = self.ballot_lsb_by_words(bal, with_any=True) else: + self.uses_vote = True + lsb, any_ = self.tmp(), self.tmp() self.emit(f"{lsb} = OpGroupNonUniformBallotFindLSB %uint {self.cu(3)} {bal}") - self.emit(f"{any_} = OpGroupNonUniformAny %bool {self.cu(3)} {act}") - self.emit(f"{first} = OpSelect %uint {any_} {lsb} {self.cu(0)}") + self.emit(f"{any_} = OpGroupNonUniformAny %bool {self.cu(3)} {act}") + fallback = self.subgroup_first_running_lane() + self.emit(f"{first} = OpSelect %uint {any_} {lsb} {fallback}") self.emit(f"{r} = OpGroupNonUniformShuffle %uint {self.cu(3)} {v} {first}") self.dst(a[0], r) elif op in ("image_gather4_c_lz", "image_gather4_c_lz_o"): @@ -8368,6 +8699,11 @@ def bits(name, default): width = 16 if ("_dot2_" in op or "_dot2c_" in op) else (8 if "_dot4" in op else 4) signed = op.endswith(("i16", "i4")) clamp = "clamp" in mods + if width == 8: + packed = self.packed_dot4(x, y, acc, signed=False, clamp=clamp) + if packed is not None: + self.dst(a[0], packed) + return ext = "OpBitFieldSExtract" if signed else "OpBitFieldUExtract" prods = [] for off in range(0, 32, width): @@ -9238,31 +9574,47 @@ def f64(sv): # shuffle would index a lane the 32-lane subgroup of a VS/PS/GS may not have (lane >= 32). self.dst(a[0], self.src_u(a[1])) return - slot = lane_masks.lane_slot(a[1], a[2]) + slot = lane_masks.lane_slot(a[1], a[2], self.wave64) + if slot and (slot[1:] in self.scalar_spills + or (id(self.cur_ins) in self.spill_readlanes and slot[1:] in self.parked)): + # Pure scalar-spill VGPR or definite mixed-VGPR spill reload: load from the parked scalar slot + # instead of shuffling from a lane that may be inactive (small fragment waves, discards, or + # wave64 lanes >= 32 on 32-wide subgroups). + self.dst(a[0], self.load_reg("sgpr", self.parked[slot[1:]])) + return if slot in self.cur_masks: # A lane mask parked there by v_writelane (a saved EXEC, when the shader ran out of SGPRs): this # lane's bit comes back, from the slot the write kept it in. The shuffle would hand every lane # the bit of the one lane the mask was parked in. self.dst(a[0], self.load_reg("sgpr", self.parked[slot[1:]])) return - if slot and slot[1:] in self.w64_scalar_spills: - # SHADER-10: wave64_halves proved this VGPR is pure scalar-spill storage (never read as a vector - # operand), so spills across all 64 lanes (including 32..63) reload from the parked scalar slot - # instead of shuffling from an out-of-range lane on a 32-wide subgroup. - self.dst(a[0], self.load_reg("sgpr", self.parked[slot[1:]])) - return self.uses_subgroup = True v, ln = self.src_u(a[1]), self.src_u(a[2]) m, r = self.tmp(), self.tmp() # RDNA2: wave64 uses S1[5:0] (mod 64); wave32 uses S1[4:0] (mod 32). Masking wave32 with 63 left # lane selects 32..63 pointing past a 32-wide subgroup (SHADER-52 / FUZZ-7). self.emit(f"{m} = OpBitwiseAnd %uint {ln} {self.cu(63 if self.wave64 else 31)}") - self.g_shuffle(r, v, m) + if self.emulate: + self.g_shuffle(r, v, m) + else: + # Guard against shuffling from an unlaunched/absent lane in a partial subgroup: redirect absent + # targets to the wave's first running lane so the result stays wave-uniform and never triggers UB. + self.uses_ballot = True + phys = self.wave_source_lane(m) + bal, present, safe_phys = (self.tmp() for _ in range(3)) + self.emit(f"{bal} = OpGroupNonUniformBallot %v4uint_bal {self.cu(3)} %true") + self.emit(f"{present} = OpGroupNonUniformBallotBitExtract %bool {self.cu(3)} {bal} {phys}") + if self.wave32_fragment: + fallback = self.wave_source_lane(self.wave32_first_running_lane(bal)) + else: + fallback = self.subgroup_first_running_lane(bal) + self.emit(f"{safe_phys} = OpSelect %uint {present} {phys} {fallback}") + self.emit(f"{r} = OpGroupNonUniformShuffle %uint {self.cu(3)} {v} {safe_phys}") self.dst(a[0], r) elif op == "v_writelane_b32": # vD[lane] = sS: only the named lane changes (independent of EXEC, as on hardware). - slot = lane_masks.lane_slot(a[0], a[2]) - if slot and slot[1:] in self.w64_scalar_spills: + slot = lane_masks.lane_slot(a[0], a[2], self.wave64) + if slot and slot[1:] in self.scalar_spills: self.store_reg("sgpr", self.parked[slot[1:]], self.src_u(a[1])) return self.uses_subgroup = True @@ -9317,10 +9669,24 @@ def f64(sv): # way. Measured on RDNA2 (issue #374). (fi, bc), _ = self.opsel_bits(mods, 2) if fi: - # FI=1 fetches the value of a source lane that is off in EXEC. - r = self.tmp() - self.g_shuffle(r, v, src) - self.dst(a[0], r) + # FI=1 fetches the value of a source lane that is off in EXEC. On a native subgroup, redirect + # unlaunched/absent lanes first so OpGroupNonUniformShuffle never targets a non-running lane. + if self.emulate: + r = self.tmp() + self.g_shuffle(r, v, src) + self.dst(a[0], r) + else: + ballot, present, safe_phys, shuf, mask, r = (self.tmp() for _ in range(6)) + physical_src = self.wave_source_lane(src) + physical_self = self.subgroup_lane() + self.emit(f"{ballot} = OpGroupNonUniformBallot %v4uint_bal %c3 %true") + self.emit(f"{present} = OpGroupNonUniformBallotBitExtract %bool %c3 {ballot} {physical_src}") + self.emit(f"{safe_phys} = OpSelect %uint {present} {physical_src} {physical_self}") + self.emit(f"{shuf} = OpGroupNonUniformShuffle %uint %c3 {v} {safe_phys}") + self.uses_subgroup = self.uses_ballot = True + self.emit(f"{mask} = OpSelect %uint {present} {self.cu(0xFFFFFFFF)} {self.cu(0)}") + self.emit(f"{r} = OpBitwiseAnd %uint {shuf} {mask}") + self.dst(a[0], r, eager=True) elif self.emulate: r = self.tmp() self.g_shuffle(r, v, src) @@ -9345,14 +9711,15 @@ def f64(sv): # aa217aeb the FI=0 lanes then read the source lane's value instead of keeping the old one (#5895). # Combine with bitwise masks instead, as #932 does for ds_bpermute: the ballot and the shuffles run # before lane predication. - sa, ballot, present, safe_src, r, act, got, ok, mask = (self.tmp() for _ in range(9)) + sa, ballot, present, safe_phys, r, act, got, ok, mask = (self.tmp() for _ in range(9)) self.emit(f"{sa} = OpSelect %uint {self.active_b()} {self.cu(1)} {self.cu(0)}") physical_src = self.wave_source_lane(src) + physical_self = self.subgroup_lane() self.emit(f"{ballot} = OpGroupNonUniformBallot %v4uint_bal %c3 %true") self.emit(f"{present} = OpGroupNonUniformBallotBitExtract %bool %c3 {ballot} {physical_src}") - self.emit(f"{safe_src} = OpSelect %uint {present} {src} {lane}") - self.emit(f"{r} = OpGroupNonUniformShuffle %uint %c3 {v} {self.wave_source_lane(safe_src)}") - self.emit(f"{act} = OpGroupNonUniformShuffle %uint %c3 {sa} {self.wave_source_lane(safe_src)}") + self.emit(f"{safe_phys} = OpSelect %uint {present} {physical_src} {physical_self}") + self.emit(f"{r} = OpGroupNonUniformShuffle %uint %c3 {v} {safe_phys}") + self.emit(f"{act} = OpGroupNonUniformShuffle %uint %c3 {sa} {safe_phys}") self.emit(f"{got} = OpINotEqual %bool {act} {self.cu(0)}") self.emit(f"{ok} = OpLogicalAnd %bool {present} {got}") self.uses_subgroup = self.uses_ballot = True @@ -10546,14 +10913,25 @@ def halves(s, is_full): # zero override gives +0 even when a negative subnormal operand becomes -0 after input flushing. # Flush the product before omod: otherwise FLT_MIN * 0.5 mul:2 becomes FLT_MIN, not zero. x, y = (self.src_f(t) for t in a[1:3]) - m, ax, ay, zx, zy, either, r = (self.tmp() for _ in range(7)) - self.emit(f"{m} = OpFMul %float {x} {y}") - self.emit(f"{ax} = OpExtInst %float %glsl FAbs {x}") - self.emit(f"{ay} = OpExtInst %float %glsl FAbs {y}") - self.emit(f"{zx} = OpFOrdLessThan %bool {ax} {self.fconst(2.0 ** -126)}") - self.emit(f"{zy} = OpFOrdLessThan %bool {ay} {self.fconst(2.0 ** -126)}") - self.emit(f"{either} = OpLogicalOr %bool {zx} {zy}") - self.emit(f"{r} = OpSelect %float {either} %f0 {self.flush_f32(m)}") + if self.ftz32: + # Under DenormFlushToZero 32, OpFOrdEqual flushes subnormal inputs to 0 and OpFMul flushes + # subnormal products to signed zero. Emit the canonical Mesa NIR fmulz pattern so RADV/ACO + # lowers it to a single native v_mul_legacy_f32. + m, zx, zy, either, r = (self.tmp() for _ in range(5)) + self.emit(f"{m} = OpFMul %float {x} {y}") + self.emit(f"{zx} = OpFOrdEqual %bool {x} %f0") + self.emit(f"{zy} = OpFOrdEqual %bool {y} %f0") + self.emit(f"{either} = OpLogicalOr %bool {zx} {zy}") + self.emit(f"{r} = OpSelect %float {either} %f0 {m}") + else: + m, ax, ay, zx, zy, either, r = (self.tmp() for _ in range(7)) + self.emit(f"{m} = OpFMul %float {x} {y}") + self.emit(f"{ax} = OpExtInst %float %glsl FAbs {x}") + self.emit(f"{ay} = OpExtInst %float %glsl FAbs {y}") + self.emit(f"{zx} = OpFOrdLessThan %bool {ax} {self.fconst(2.0 ** -126)}") + self.emit(f"{zy} = OpFOrdLessThan %bool {ay} {self.fconst(2.0 ** -126)}") + self.emit(f"{either} = OpLogicalOr %bool {zx} {zy}") + self.emit(f"{r} = OpSelect %float {either} %f0 {self.flush_f32(m)}") r = self.clamp_mods(r, mods) if any(mod in ("mul:2", "mul:4", "div:2") for mod in mods): r = self.flush_f32(r) @@ -12225,7 +12603,7 @@ def f64(sv): else: self.emit(f"{r} = OpExtInst %float %glsl {F1[op]} {x}") if op == "v_exp_f32": - r = self.flush_f32(r) + r = self.flush_f32(r, force=True) self.dst(a[0], self.tou(self.clamp_mods(r, mods))) elif op in ("v_frexp_mant_f32", "v_frexp_exp_i32_f32", "v_ldexp_f32"): # Bit-exact on the binary32 word (no float arithmetic). A normal input has biased exponent 1..254; @@ -13004,6 +13382,11 @@ def bits(name, default): raise Unsupported(op + " op_sel") x, y = self.src_u(a[1]), self.src_u(a[2]) acc = self.src_u(a[3]) if is_vop3p else self.src_u(a[0]) + packed = self.packed_dot4(self.dot4_halves(x, sel[0], selhi[0]), self.dot4_halves(y, sel[1], selhi[1]), + acc, signed=True, clamp=has_clamp) + if packed is not None: + self.dst(a[0], packed) + return x_offs = (16 * sel[0], 16 * sel[0] + 8, 16 * selhi[0], 16 * selhi[0] + 8) y_offs = (16 * sel[1], 16 * sel[1] + 8, 16 * selhi[1], 16 * selhi[1] + 8) dot = None @@ -13057,6 +13440,137 @@ def bits(name, default): else: raise Unsupported(op) + def dot4_halves(self, x, lo_half, hi_half): + """The dword a 4x8-bit dot product reads under op_sel: bytes 0..1 from 16-bit half `lo_half` of `x` and bytes + 2..3 from half `hi_half` (0 low, 1 high; the default is 0 and 1, `x` itself).""" + if (lo_half, hi_half) == (0, 1): + return x + lo, hi, r = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{lo} = OpBitFieldUExtract %uint {x} {self.cu(16 * lo_half)} {self.cu(16)}") + self.emit(f"{hi} = OpBitFieldUExtract %uint {x} {self.cu(16 * hi_half)} {self.cu(16)}") + self.emit(f"{r} = OpBitFieldInsert %uint {lo} {hi} {self.cu(16)} {self.cu(16)}") + return r + + def packed_dot4(self, x, y, acc, *, signed, clamp): + """acc + the dot product of the four bytes of x and y as one SPV_KHR_integer_dot_product instruction, or None + under --integer-dot-fallback (the caller expands it). + + OpSDot / OpUDot give the low 32 bits of the exact sum of the four products of the sign- (zero-) extended + bytes (PackedVectorFormat4x8Bit), the sum v_dot4_i32_i8 / v_dot4_u32_u8 form; adding acc wraps at 32 bits as + the instructions do without clamp. With clamp the hardware saturates acc + the exact sum (signed 32-bit for + i8, unsigned for u8; docs/design.md, "Signed-byte dot products" and "Packed integer dot products"), which is + OpSDotAccSat / OpUDotAccSat: "the correct result ... computed with enough precision to avoid overflow", + saturated to the result type. The signed forms use %int operands, so the signedness is the type's too.""" + if INTEGER_DOT_FALLBACK: + return None + self.uses_int_dot = True + fmt = "PackedVectorFormat4x8BitKHR" + if not signed: + r = self.tmp() + if clamp: + self.emit(f"{r} = OpUDotAccSatKHR %uint {x} {y} {acc} {fmt}") + else: + d = self.tmp() + self.emit(f"{d} = OpUDotKHR %uint {x} {y} {fmt}") + self.emit(f"{r} = OpIAdd %uint {acc} {d}") + return r + xi, yi = self.tmp(), self.tmp() + self.emit(f"{xi} = OpBitcast %int {x}") + self.emit(f"{yi} = OpBitcast %int {y}") + if clamp: + ai, s, r = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{ai} = OpBitcast %int {acc}") + self.emit(f"{s} = OpSDotAccSatKHR %int {xi} {yi} {ai} {fmt}") + self.emit(f"{r} = OpBitcast %uint {s}") + return r + d, du, r = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{d} = OpSDotKHR %int {xi} {yi} {fmt}") + self.emit(f"{du} = OpBitcast %uint {d}") + self.emit(f"{r} = OpIAdd %uint {acc} {du}") + return r + + def sbuf_slow_function(self, n, ro=False): + """Build (once per (width, ro) with n in {2, 4, 8, 16}) the partial-OOB helper %sbuf_slow_{ro|rw}_x{n}. + + Called from the cold lbl_slow branch of wide s_buffer_load_dwordxN when the last dword is past limit. + Uses a compact counted loop (DontUnroll) with ONE OpLoad in the loop body, storing into a zero-initialized + Function-scope %arr_sbuf_x{n} and returning OpLoad %arr_sbuf_x{n}: each dword i with off + 4*i + 4 <= lim + is loaded at host + 4*i (Aligned 4); out-of-range dwords stay 0 without reading past limit. + When ro=True, loads through NonWritable %_ptr_PSB_sl_blk1 so RADV/ACO keeps SMEM s_load_dword even inside + the slow path; when ro=False, loads through mutable %_ptr_PSB_arr.""" + ro = bool(ro) + key = (n, ro) + tag = "ro" if ro else "rw" + fn = f"%sbuf_slow_{tag}_x{n}" + if key not in self.sbuf_slow_fns: + p = f"%sbs_{tag}{n}_" + arr = f"%arr_sbuf_x{n}" + ptr_arr = f"%_ptr_Function_arr_sbuf_x{n}" + null_arr = f"%null_sbuf_x{n}" + c0 = self.cu(0) + c1 = self.cu(1) + self.cu(n) + cl2 = self.cl(2) + cln = self.cl(n) + if ro: + self.uses_psb_scalar_ro = True + lines = [ + f"{fn} = OpFunction {arr} None %fn_sbuf_slow_x{n}", + f"{p}host = OpFunctionParameter %ulong", + f"{p}off = OpFunctionParameter %ulong", + f"{p}lim = OpFunctionParameter %ulong", + f"{p}entry = OpLabel", + f"{p}out = OpVariable {ptr_arr} Function {null_arr}", + # Overflow-safe exact in-range dword count: + # off + 4*i + 4 <= lim <=> lim >= off and i < min((lim - off) >> 2, n). + f"{p}ge = OpUGreaterThanEqual %bool {p}lim {p}off", + f"{p}diff = OpISub %ulong {p}lim {p}off", + f"{p}avail = OpShiftRightLogical %ulong {p}diff {cl2}", + f"{p}lt_n = OpULessThan %bool {p}avail {cln}", + f"{p}cnt64 = OpSelect %ulong {p}lt_n {p}avail {cln}", + f"{p}cnt_u = OpUConvert %uint {p}cnt64", + f"{p}cnt = OpSelect %uint {p}ge {p}cnt_u {c0}", + ] + if not ro: + lines.append(f"{p}ptr = OpConvertUToPtr %_ptr_PSB_arr {p}host") + lines += [ + f"OpBranch {p}head", + f"{p}head = OpLabel", + f"{p}i = OpPhi %uint {c0} {p}entry {p}next {p}cont", + f"{p}cond = OpULessThan %bool {p}i {p}cnt", + f"OpLoopMerge {p}exit {p}cont DontUnroll", + f"OpBranchConditional {p}cond {p}body {p}exit", + f"{p}body = OpLabel", + ] + if ro: + lines += [ + f"{p}i64 = OpUConvert %ulong {p}i", + f"{p}boff = OpShiftLeftLogical %ulong {p}i64 {cl2}", + f"{p}addr = OpIAdd %ulong {p}host {p}boff", + f"{p}bptr = OpConvertUToPtr %_ptr_PSB_sl_blk1 {p}addr", + f"{p}qptr = OpAccessChain %_ptr_PSB_uint {p}bptr {c0}", + f"{p}val = OpLoad %uint {p}qptr Aligned 4", + ] + else: + lines += [ + f"{p}qptr = OpAccessChain %_ptr_PSB_uint {p}ptr {p}i", + f"{p}val = OpLoad %uint {p}qptr Aligned 4", + ] + lines += [ + f"{p}slot = OpAccessChain %_ptr_Function_uint {p}out {p}i", + f"OpStore {p}slot {p}val", + f"OpBranch {p}cont", + f"{p}cont = OpLabel", + f"{p}next = OpIAdd %uint {p}i {c1}", + f"OpBranch {p}head", + f"{p}exit = OpLabel", + f"{p}res = OpLoad {arr} {p}out", + f"OpReturnValue {p}res", + "OpFunctionEnd", + ] + self.sbuf_slow_fns[key] = lines + return fn + def scalar_load(self, op, a, mods): """s_load_dwordxN sD, s[p:p+1], off -> N dwords from a 64-bit pointer, no bound s_buffer_load_dwordxN sD, s[v:v+3], off -> N dwords from a V#, each checked against NUM_RECORDS @@ -13170,9 +13684,73 @@ def store_slot(slot, val): self.emit(f"{sh} = OpShiftLeftLogical %ulong {h64} %c64_32") 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, 'load', 4 * n)}") + host = self.host_addr(full, 'load', 4 * n) self.uses_psb = True + coherent = self._is_coherent_mem(mods) + load_mem = self._psb_load_op(mods) + ro = (not coherent) and (self.scalar_load_ro is None or self.scalar_load_ro is True or + (self.cur_ins is not None and id(self.cur_ins) in self.scalar_load_ro)) + scalar_ro = ro and self.scalar_load_ro is not None + ptr_cache = [None] + + def get_ptr(): + if ptr_cache[0] is None: + p = self.tmp() + self.emit(f"{p} = OpConvertUToPtr %_ptr_PSB_arr {host}") + ptr_cache[0] = p + return ptr_cache[0] + + def wide(count): + """Dwords 0..count-1 at the load's address as the fewest loads SPIR-V types allow: uvec4, then uvec2, + then one uint. Each is Aligned 4, the alignment SMEM has. One instruction's dwords are consecutive in + memory, so a driver can fetch them as one scalar or vector load instead of one per dword (RADV gave 6,048 + global_load_b32, 5,935 v_readfirstlane and 5,448 64-bit compares for the 365 s_buffer_load_dwordx16 + of an FSPX program loaded per dword). + + Provably non-aliasing scalar loads read through a NonWritable Block (%sl_blk1 / %sl_blk2 / %sl_blk4) + so RADV emits SMEM (s_load_b32..b512); loads that may alias a store/atomic in the same module read + through a mutable Block (%sl_rw_blk2 / %sl_rw_blk4) or %_ptr_PSB_arr so stores remain visible. Coherent + (glc/dlc) loads always use scalar mutable loads carrying MakePointerVisible|NonPrivatePointer.""" + got, k = [], 0 + while k < count: + w = 1 if coherent else (4 if count - k >= 4 else 2 if count - k >= 2 else 1) + if w == 1: + if scalar_ro: + self.uses_psb_scalar_ro = True + at = host + if k: + at = self.tmp() + self.emit(f"{at} = OpIAdd %ulong {host} {self.cl(4 * k)}") + b, q, v = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{b} = OpConvertUToPtr %_ptr_PSB_sl_blk1 {at}") + self.emit(f"{q} = OpAccessChain %_ptr_PSB_uint {b} {self.cu(0)}") + self.emit(f"{v} = OpLoad %uint {q} Aligned 4") + else: + q, v = self.tmp(), self.tmp() + self.emit(f"{q} = OpAccessChain %_ptr_PSB_uint {get_ptr()} {self.cu(k)}") + self.emit(f"{v} = OpLoad %uint {q} {load_mem}") + got.append(v) + else: + if ro: + self.uses_psb_vec = True + blk_ptr = f"%_ptr_PSB_sl_blk{w}" + else: + self.uses_psb_vec_rw = True + blk_ptr = f"%_ptr_PSB_sl_rw_blk{w}" + at = host + if k: + at = self.tmp() + self.emit(f"{at} = OpIAdd %ulong {host} {self.cl(4 * k)}") + b, q, v = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{b} = OpConvertUToPtr {blk_ptr} {at}") + self.emit(f"{q} = OpAccessChain %_ptr_PSB_v{w}uint_sl {b} {self.cu(0)}") + self.emit(f"{v} = OpLoad %v{w}uint_sl {q} Aligned 4") + for j in range(w): + e = self.tmp() + self.emit(f"{e} = OpCompositeExtract %uint {v} {j}") + got.append(e) + k += w + return got lim = None lim_val = None if sbuf: @@ -13193,61 +13771,107 @@ def store_slot(slot, val): self.emit(f"{raw} = OpIEqual %bool {stride} {self.cu(0)}") self.emit(f"{lim} = OpSelect %ulong {raw} {nr64} {prod}") guarded = {} - if lim is not None and not (lim_val is not None and reg is None): - # A run-time bound: dword i is in range when off + 4*i + 4 <= limit, and out of range it is 0 with memory - # not read. The ends grow with i, so "dword i in range" implies every dword before it is: one selection - # on dword 0 covers the load. Inside it each dword reads at index i when in range, else at index 0 (in - # range there, so nothing outside the buffer is touched), and the out-of-range ones are then 0. Before, - # each dword had its own selection: 2N blocks per s_buffer_load_dwordxN, 11,000 of the 17,000 blocks of - # the cascade-shadow CS whose pipeline NVIDIA's compiler could not build in 16 GB. - oks = [] + if lim is not None and not (lim_val is not None and reg is None) and n > 1: + # Every dword in range (the last one is, so all are): one wide load, the common case. Otherwise call + # the shared per-width partial-OOB loop helper %sbuf_slow_{ro|rw}_x{n}. + last_end, all_ok = self.tmp(), self.tmp() + if reg is not None: + self.emit(f"{last_end} = OpIAdd %ulong {o64} {self.cl(4 * n)}") + else: + last_end = self.cl(imm + 4 * n) + self.emit(f"{all_ok} = OpUGreaterThanEqual %bool {lim} {last_end}") + if coherent: + get_ptr() + lbl_fast, lbl_slow, lbl_join = self.tmp() + "_all", self.tmp() + "_part", self.tmp() + "_join" + self.emit(f"OpSelectionMerge {lbl_join} None") + self.emit(f"OpBranchConditional {all_ok} {lbl_fast} {lbl_slow}") + self.emit(f"{lbl_fast} = OpLabel") + fast = wide(n) + fast_exit = self.current_label_placeholder() + self.emit(f"OpBranch {lbl_join}") + self.emit(f"{lbl_slow} = OpLabel") + if not coherent: + slow_fn = self.sbuf_slow_function(n, ro=ro) + slow_arr = self.tmp() + self.emit(f"{slow_arr} = OpFunctionCall %arr_sbuf_x{n} {slow_fn} {host} {o64} {lim}") + slow_vals = [] + for i in range(n): + e = self.tmp() + self.emit(f"{e} = OpCompositeExtract %uint {slow_arr} {i}") + slow_vals.append(e) + else: + oks = [] + for i in range(n): + end, ok = self.tmp(), self.tmp() + if reg is not None: + self.emit(f"{end} = OpIAdd %ulong {o64} {self.cl(4 * i + 4)}") + else: + end = self.cl(imm + 4 * i + 4) + self.emit(f"{ok} = OpUGreaterThanEqual %bool {lim} {end}") + oks.append(ok) + lbl_cdo, lbl_cend = self.tmp() + "_cdo", self.tmp() + "_cend" + cpre = self.current_label_placeholder() + self.emit(f"OpSelectionMerge {lbl_cend} None") + self.emit(f"OpBranchConditional {oks[0]} {lbl_cdo} {lbl_cend}") + self.emit(f"{lbl_cdo} = OpLabel") + got_in = [] + for i in range(n): + idx, p, got, val = (self.tmp() for _ in range(4)) + if i == 0: + idx = self.cu(0) + else: + self.emit(f"{idx} = OpSelect %uint {oks[i]} {self.cu(i)} {self.cu(0)}") + self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {get_ptr()} {idx}") + self.emit(f"{got} = OpLoad %uint {p} {load_mem}") + if i == 0: + val = got + else: + self.emit(f"{val} = OpSelect %uint {oks[i]} {got} {self.cu(0)}") + got_in.append(val) + self.emit(f"OpBranch {lbl_cend}") + self.emit(f"{lbl_cend} = OpLabel") + slow_vals = [] + for i in range(n): + sv = self.tmp() + self.emit(f"{sv} = OpPhi %uint {got_in[i]} {lbl_cdo} {self.cu(0)} {cpre}") + slow_vals.append(sv) + slow_exit = self.current_label_placeholder() + self.emit(f"OpBranch {lbl_join}") + self.emit(f"{lbl_join} = OpLabel") for i in range(n): - end, ok = self.tmp(), self.tmp() - if reg is not None: - self.emit(f"{end} = OpIAdd %ulong {o64} {self.cl(4 * i + 4)}") - else: - end = self.cl(imm + 4 * i + 4) - self.emit(f"{ok} = OpUGreaterThanEqual %bool {lim} {end}") - oks.append(ok) + v = self.tmp() + self.emit(f"{v} = OpPhi %uint {fast[i]} {fast_exit} {slow_vals[i]} {slow_exit}") + guarded[i] = v + elif lim is not None and not (lim_val is not None and reg is None): + # Single-dword run-time bound: 0 without reading memory when off + 4 > limit. + end, ok = self.tmp(), self.tmp() + if reg is not None: + self.emit(f"{end} = OpIAdd %ulong {o64} {self.cl(4)}") + else: + end = self.cl(imm + 4) + self.emit(f"{ok} = OpUGreaterThanEqual %bool {lim} {end}") lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end" pre = self.current_label_placeholder() self.emit(f"OpSelectionMerge {lbl_end} None") - self.emit(f"OpBranchConditional {oks[0]} {lbl_do} {lbl_end}") + self.emit(f"OpBranchConditional {ok} {lbl_do} {lbl_end}") self.emit(f"{lbl_do} = OpLabel") - got_in = [] - for i in range(n): - idx, p, got, val = (self.tmp() for _ in range(4)) - if i == 0: - idx = self.cu(0) - else: - self.emit(f"{idx} = OpSelect %uint {oks[i]} {self.cu(i)} {self.cu(0)}") - self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {idx}") - self.emit(f"{got} = OpLoad %uint {p} Aligned 4") - if i == 0: - val = got - else: - self.emit(f"{val} = OpSelect %uint {oks[i]} {got} {self.cu(0)}") - got_in.append(val) + got = wide(1)[0] self.emit(f"OpBranch {lbl_end}") self.emit(f"{lbl_end} = OpLabel") - for i in range(n): - v = self.tmp() - self.emit(f"{v} = OpPhi %uint {got_in[i]} {lbl_do} {self.cu(0)} {pre}") - guarded[i] = v + v = self.tmp() + self.emit(f"{v} = OpPhi %uint {got} {lbl_do} {self.cu(0)} {pre}") + guarded[0] = v + if guarded: + vals = [guarded[i] for i in range(n)] + elif lim is None: + vals = wide(n) + else: + # A bound known at translate time (lim_val, constant offset). The dwords in range are a prefix (their + # ends grow with i): one wide load for them, 0 for the rest. + count = sum(lim_val >= imm + 4 * i + 4 for i in range(n)) + vals = wide(count) + [self.cu(0)] * (n - count) for i in range(n): - p, v = self.tmp(), self.tmp() - if i in guarded: - v = guarded[i] - elif lim is None: - self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(i)}") - self.emit(f"{v} = OpLoad %uint {p} Aligned 4") - else: # a bound known at translate time (lim_val, constant offset): fold each dword - end_val = imm + 4 * i + 4 - if lim_val >= end_val: - self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(i)}") - self.emit(f"{v} = OpLoad %uint {p} Aligned 4") - else: - v = self.cu(0) + v = vals[i] if single_special: if n == 2: # vcc pair: low dword -> vcc_lo, high dword -> vcc_hi (data, not a lane mask) self.emit(f"OpStore {'%vcc' if i == 0 else '%vcc_hi'} {v}") @@ -13265,7 +13889,7 @@ def store_slot(slot, val): # The last word is the pad word a plain module never reads; --descriptor-table tagged fills it with the kind. PROBES = 8 - def desc_lookup(self, words): + def desc_lookup(self, words, uniform=True): """words: 8 uint ids. Returns (bindless index, kind), kind being None with --descriptor-table plain. The probe is about 400 instructions, so it is one function in the module (%desc_lookup_fn) that every @@ -13290,16 +13914,43 @@ def desc_lookup(self, words): self.emit(f"{kind} = OpCompositeExtract %uint {r} 1") else: idx, kind = r, None + return self.desc_uniform(idx, kind) if uniform else (idx, kind) + + def tsharp_index_word(self, words): + """(index, kind, tagged) from the T#'s dword 6 as the layer writes it (TSHARP_INDEX): the bool `tagged` is + whether the word carries the tag and dword 3 names an image (TYPE >= 8, bit 31); index and kind are 0 when it + does not, index 0's fallback, which is what a T# that names no image reads. The words are SGPRs, so this is a + handful of scalar operations and no memory access beyond the T# the shader loaded anyway.""" + w3, w6 = words[3], words[TSHARP_INDEX_DWORD] + tag, tag_ok, img, img_ok, ok = (self.tmp() for _ in range(5)) + self.emit(f"{tag} = OpShiftRightLogical %uint {w6} {self.cu(28)}") + self.emit(f"{tag_ok} = OpIEqual %bool {tag} {self.cu(TSHARP_INDEX_TAG)}") + self.emit(f"{img} = OpShiftRightLogical %uint {w3} {self.cu(31)}") + self.emit(f"{img_ok} = OpINotEqual %bool {img} {self.cu(0)}") + self.emit(f"{ok} = OpLogicalAnd %bool {tag_ok} {img_ok}") + raw, idx, sampled, storage, storage_hi, both, kind = (self.tmp() for _ in range(7)) + self.emit(f"{raw} = OpBitwiseAnd %uint {w6} {self.cu(0xFFFF)}") + self.emit(f"{idx} = OpSelect %uint {ok} {raw} {self.cu(0)}") + self.emit(f"{sampled} = OpBitFieldUExtract %uint {w6} {self.cu(16)} {self.cu(7)}") + self.emit(f"{storage} = OpBitFieldUExtract %uint {w6} {self.cu(23)} {self.cu(5)}") + self.emit(f"{storage_hi} = OpShiftLeftLogical %uint {storage} {self.cu(DESC_STORAGE_BIT)}") + self.emit(f"{both} = OpBitwiseOr %uint {sampled} {storage_hi}") + self.emit(f"{kind} = OpSelect %uint {ok} {both} {self.cu(0)}") + return idx, kind, ok + + def desc_uniform(self, idx, kind): + """The index (and the kind, or None) made explicitly uniform, as the hash lookup's result always was.""" if self.emulate: return idx, kind if self.wave32_fragment: # Each 32-lane half of a wider subgroup is its own wave with its own SGPRs: broadcast from the half's # first running lane, as OpGroupNonUniformBroadcastFirst does for the whole subgroup below. + first = self.wave32_first_running_lane() b = self.tmp() - self.g_shuffle(b, idx, self.wave32_first_running_lane()) + self.g_shuffle(b, idx, first) if kind is not None: k = self.tmp() - self.g_shuffle(k, kind, self.wave32_first_running_lane()) + self.g_shuffle(k, kind, first) kind = k return b, kind # The descriptor words are SGPRs, so the index is the same in every invocation of the subgroup; the @@ -13929,6 +14580,52 @@ def gather_mip(image: str, cls: int, ty: str) -> str: self.image_read_typed(dim, self.sgpr_word(a[2], 1), img, img_idx, 0xf, vdata, d16, gather_mip) + def tsharp_index_sgpr(self, a): + """(index, kind) of the current instruction's T# operand `a` when the dataflow showed its dword 6 is a heap + slot's (Gen.tsharp_from_heap, tools/descriptor_sources.py), else None.""" + ins = self.cur_ins + if ins is None or not self.tsharp_from_heap.get(id(ins)): + return None + regs = descriptor_sources.tsharp_operand(ins) + if regs is None or tuple(regs) != self.tsharp_regs(a): + return None + self.uses_tex = True # set 0's image arrays, which the index reads, as desc_lookup declares them + idx, kind, _ = self.tsharp_index_word(self.sgpr_words(a, 8)) + self.tsharp_index_reads += 1 + return self.desc_uniform(idx, kind) + + def literal_sampler_lookup(self, a, slot): + """Sampler bindless index for compile-time literal S# `slot`: when OpSpecConstant %lit_smp_ is + specialized (!= 0xFFFFFFFF), use it directly without probing %desc_map; when unspecialized (0xFFFFFFFF), + fall back to the existing bindless hash-table probe.""" + self.uses_tex = True + self.uses_lit_sampler_spec = True + spec_id = f"%lit_smp_{slot}" + use_spec = self.tmp() + self.emit(f"{use_spec} = OpINotEqual %bool {spec_id} {self.cu(0xFFFFFFFF)}") + pre = self.current_label_placeholder() + lbl_probe, lbl_end = self.tmp() + "_sprobe", self.tmp() + "_send" + self.emit(f"OpSelectionMerge {lbl_end} None") + self.emit(f"OpBranchConditional {use_spec} {lbl_end} {lbl_probe}") + self.emit(f"{lbl_probe} = OpLabel") + words = self.sgpr_words(a, 4) + [self.cu(0xFFFFFFFF)] * 4 + probe_idx, _ = self.desc_lookup(words, uniform=False) + probe_exit = self.current_label_placeholder() + self.emit(f"OpBranch {lbl_end}") + self.emit(f"{lbl_end} = OpLabel") + out = self.tmp() + self.emit(f"{out} = OpPhi %uint {spec_id} {pre} {probe_idx} {probe_exit}") + return self.desc_uniform(out, None) + + def _literal_sampler_slot(self, a): + if not self.literal_sampler_index: + return None + words = self.literal_sampler_sites.get(id(self.cur_ins)) if self.cur_ins is not None else None + if words is None and a["k"] == "sgpr" and a.get("n", 1) >= 4: + if all((a["r"] + i) in self.sgpr_imm for i in range(4)): + words = tuple(self.sgpr_imm[a["r"] + i] & 0xFFFFFFFF for i in range(4)) + return self.literal_sampler_index.get(words) if words is not None else None + def desc_lookup_sgpr(self, a, n): """desc_lookup for an SGPR descriptor range (n=8: T#, n=4: S#), cached for the rest of the basic block. @@ -13937,12 +14634,25 @@ def desc_lookup_sgpr(self, a, n): array go through store_reg, including the 64-bit ones, which are two calls, s_load results, v_readlane/v_readfirstlane results and the spare slots lane masks are parked in) and cleared when a basic block starts. Only lookups made at the block's top level are remembered, see desc_cache_ok. Returns - (bindless index, kind), kind being None with --descriptor-table plain.""" + (bindless index, kind), kind being None with --descriptor-table plain. + + A T# (n=8) whose dword 6 the dataflow traced to a heap slot takes its index from that word alone + (tsharp_index_sgpr). Any other T# is looked up, and the dword-6 index wins where the word carries it: such a + T# may still come from a heap the layer writes, along a path the dataflow did not follow, and there its words + are not the key the table holds (the key is the descriptor as the title wrote it).""" + if n == 8: + direct = self.tsharp_index_sgpr(a) + if direct is not None: + return direct if a["k"] == "slist" and len(a["r"]) >= n: + if n == 4: + slot = self._literal_sampler_slot(a) + if slot is not None: + return self.literal_sampler_lookup(a, slot) words = self.sgpr_words(a, n) if n < 8: words = words + [self.cu(0xFFFFFFFF)] * (8 - n) - return self.desc_lookup(words) + return self.desc_lookup(words) if n < 8 else self.tsharp_lookup(words) if a["k"] != "sgpr" or a.get("n", 1) < n: raise Unsupported("descriptor operand") key = (a["r"], n) @@ -13950,14 +14660,43 @@ def desc_lookup_sgpr(self, a, n): if hit is not None: return hit top = self.desc_cache_ok() + if n == 4: + slot = self._literal_sampler_slot(a) + if slot is not None: + idx = self.literal_sampler_lookup(a, slot) + if top: + self.desc_cache[key] = idx + return idx words = self.sgpr_words(a, n) if n < 8: words = words + [self.cu(0xFFFFFFFF)] * (8 - n) - idx = self.desc_lookup(words) + idx = self.desc_lookup(words) if n < 8 else self.tsharp_lookup(words) if top: self.desc_cache[key] = idx return idx + def tsharp_lookup(self, words): + """A T# of unknown source: its dword-6 index where the word carries one, else the hash table's answer for its + words. The lookup sits in the branch taken only without the word: `ok` comes from SGPRs, so the branch is + uniform, and a T# from a heap the layer writes, along a path the dataflow did not follow, costs no probe.""" + self.tsharp_lookups += 1 + direct, direct_kind, ok = self.tsharp_index_word(words) + pre = self.current_label_placeholder() + probe, end = self.tmp() + "_probe", self.tmp() + "_tsharp" + self.emit(f"OpSelectionMerge {end} None") + self.emit(f"OpBranchConditional {ok} {end} {probe}") + self.emit(f"{probe} = OpLabel") + idx, kind = self.desc_lookup(words, uniform=False) + self.emit(f"OpBranch {end}") + self.emit(f"{end} = OpLabel") + out = self.tmp() + self.emit(f"{out} = OpPhi %uint {direct} {pre} {idx} {probe}") + out_kind = None + if kind is not None: + out_kind = self.tmp() + self.emit(f"{out_kind} = OpPhi %uint {direct_kind} {pre} {kind} {probe}") + return self.desc_uniform(out, out_kind) + # The dimension of an instruction's image array, indexed by STORE_DIMS' index (0 2D, 1 2D array, 2 3D, 3 1D). # A cube instruction reads the 2D-array binding: a cube is six layers of a 2D array. DIM_TAGS = {"dim:SQ_RSRC_IMG_2D": 0, "dim:SQ_RSRC_IMG_2D_ARRAY": 1, "dim:SQ_RSRC_IMG_CUBE": 1, @@ -14434,26 +15173,36 @@ def gather(image, cls, ty): self.emit(f"{uv} = OpCompositeConstruct %v2float {f[0]} {f[1]}") lod = f[ncoord] if kind == "_l" and len(f) > ncoord else "%f0" if typed_sample: + float_only = self._is_float_only_image_op(op, a, mods) # The aliases image_read_typed declares are indexed by the dimension it reads: a cube samples its # 6-layer 2D-array view, which is what `img` was loaded from above. di = self.STORE_DIMS[view_dim][0] - operands = f"Lod {lod}" - if typed_implicit: - # Compute the quad gradients before the per-image format branch. - dx, dy = self.tmp(), self.tmp() - self.emit(f"{dx} = OpDPdx %v2float {uv}") - self.emit(f"{dy} = OpDPdy %v2float {uv}") - operands = f"Grad {dx} {dy}" - - def sample(image, cls, ty): - sampled = sampled_image(image, cls, di) - result = self.tmp() - self.emit(f"{result} = OpImageSampleExplicitLod {ty} {sampled} {uv} {operands}") - return result - - self.uses_int_sampler = True - self.image_read_typed(view_dim, self.sgpr_word(a[2], 1), img, img_idx, - dmask, vdata, d16, sample) + if typed_implicit and float_only: + def sample(image, cls, ty): + sampled = sampled_image(image, cls, di) + result = self.tmp() + self.emit(f"{result} = OpImageSampleImplicitLod {ty} {sampled} {uv}") + return result + else: + operands = f"Lod {lod}" + if typed_implicit: + # Compute the quad gradients before the per-image format branch. + dx, dy = self.tmp(), self.tmp() + self.emit(f"{dx} = OpDPdx %v2float {uv}") + self.emit(f"{dy} = OpDPdy %v2float {uv}") + operands = f"Grad {dx} {dy}" + + def sample(image, cls, ty): + sampled = sampled_image(image, cls, di) + result = self.tmp() + self.emit(f"{result} = OpImageSampleExplicitLod {ty} {sampled} {uv} {operands}") + return result + + if not float_only: + self.uses_int_sampler = True + t1 = self.sgpr_word(a[2], 1) if (d16 or not float_only) else None + self.image_read_typed(view_dim, t1, img, img_idx, + dmask, vdata, d16, sample, float_only=float_only) return res = self.tmp() if off is not None and kind not in ("", "_lz", "_l", "_b", "_c_lz", "_c", "_c_b"): @@ -14709,15 +15458,40 @@ def image_fetch(self, img, coords, lod, ty, volume=None): self.emit(f"{result} = OpPhi {ty} {texel} {body} {zero} {miss}") return result + def _is_float_only_image_op(self, op, a=None, mods=()): + """Whether the current image op is provably float-only so uint/sint runtime branches can be elided. + + True when either: + 1. CFG consumer analysis (float_only_image_ops) proved every reachable consumer of its destination VGPRs + interprets them strictly as floating-point (f32, or f16 under d16), with at least one float consumer. + 2. It is a filtered image_sample* whose compile-time literal S# word 2 enables bilinear/aniso XY filtering + or linear mip filtering (undefined on integer formats in Vulkan and RDNA2).""" + if self.cur_ins is not None and id(self.cur_ins) in self.float_only_images: + return True + if op in ("image_sample", "image_sample_l", "image_sample_lz") and a is not None and len(a) >= 4: + w2 = None + if self.cur_ins is not None and id(self.cur_ins) in self.literal_sampler_sites: + w2 = self.literal_sampler_sites[id(self.cur_ins)][2] + elif a[3]["k"] == "sgpr" and a[3].get("n", 1) >= 4: + w2 = self.sgpr_imm.get(a[3]["r"] + 2) + if w2 is not None: + mag = (w2 >> 20) & 3 + min_f = (w2 >> 22) & 3 + mip = (w2 >> 26) & 3 + if mag in (1, 3) or min_f in (1, 3) or mip == 2: + return True + return False + def image_load_typed(self, dim, tsharp, iv, img, idx, dmask, vdata, *, lod, d16=False): """Supply the fetch to the shared typed-image dispatch used by both loads and gathers.""" - t1 = self.sgpr_word(tsharp, 1) + float_only = self._is_float_only_image_op("image_load") di = self.STORE_DIMS[dim][0] volume = self.synthetic_uav(tsharp) if di == 2 else None atomic_read = (volume is not None and self.tsharp_regs(tsharp) in self.atomic_volume_tsharps and lod == self.cu(0)) if img is None: return self.image_load_storage(dim, tsharp, iv, idx, dmask, vdata, d16) + t1 = self.sgpr_word(tsharp, 1) if (d16 or atomic_read or not float_only) else None def fetch(image, cls, ty): if cls != 1 or not atomic_read: @@ -14748,7 +15522,8 @@ def fetch(image, cls, ty): self.emit(f"{result} = OpPhi {ty} {raw} {storage} {texel} {fetch_done}") return result - self.image_read_typed(dim, t1, img, idx, dmask, vdata, d16, fetch) + self.image_read_typed(dim, t1, img, idx, dmask, vdata, d16, fetch, + float_only=float_only) def image_load_coherent(self, dim, tsharp, iv, idx, dmask, vdata, d16): """image_load with glc: a coherent read. On GFX10 a device-scope load is glc + dlc and a device-scope store @@ -14788,16 +15563,46 @@ def read(image, _cls, ty): res = self.tmp() self.emit(f"{res} = OpImageRead {ty} {image} {iv}") return res - self.image_read_typed(dim, self.sgpr_word(tsharp, 1), None, idx, dmask, vdata, d16, read, view) + float_only = self._is_float_only_image_op("image_load") + t1 = self.sgpr_word(tsharp, 1) if (d16 or not float_only) else None + self.image_read_typed(dim, t1, None, idx, dmask, vdata, d16, read, view, + float_only=float_only) - def image_read_typed(self, dim, t1, img, idx, dmask, vdata, d16, read, view=None): + def image_read_typed(self, dim, t1, img, idx, dmask, vdata, d16, read, view=None, float_only=False): """Read an image using the component type selected by FORMAT in T# word 1. read(image, cls, ty) emits the fetch or gather and returns its four components. The float view also handles a lookup miss: index zero holds the RGBA8_UNORM fallback. view(cls) loads the image of class cls (0 float, 1 uint, 2 sint); by default the sampled image img for float and, for UINT and SINT, typed aliases of the dimension's sampled binding (SHADER-151), so no storage image feature is needed. + When `float_only` is True, the dead uint/sint branches, format-mask lookups and typed alias arrays are elided. dmask selects the output components; d16 packs two per VGPR.""" di = self.STORE_DIMS[dim][0] + if float_only: + if d16: + self.uses_d16_image = True + is_norm_fmt, is_f32_fmt = self.fmt_float_flags(t1) if d16 else (None, None) + texel = read(view(0) if view is not None else img, 0, "%v4float") + xs = [] + for c in range(4): + if dmask >> c & 1: + comp = self.tmp() + self.emit(f"{comp} = OpCompositeExtract %float {texel} {c}") + xs.append(self.tou(comp)) + if not d16: + for k, x in enumerate(xs): + self.dst({"k": "vgpr", "r": vdata["r"] + k, "n": 1}, x) + return + for i in range(0, len(xs), 2): + dest = {"k": "vgpr", "r": vdata["r"] + i // 2, "n": 1} + if i + 1 == len(xs): + self.write_lo16(dest, self.d16_norm_f16(xs[i], is_norm_fmt, is_f32_fmt)) + continue + hi_s, w = self.tmp(), self.tmp() + self.emit(f"{hi_s} = OpShiftLeftLogical %uint " + f"{self.d16_norm_f16(xs[i + 1], is_norm_fmt, is_f32_fmt)} {self.cu(16)}") + self.emit(f"{w} = OpBitwiseOr %uint {self.d16_norm_f16(xs[i], is_norm_fmt, is_f32_fmt)} {hi_s}") + self.dst(dest, w) + return if view is None: self.uses_int_fetch.add(di) @@ -16515,6 +17320,7 @@ def assemble(gen): ["%fmt_norm_mask", "%fmt_f32_mask"] if gen.uses_d16_image else []) + \ (["%fmt_size_tab"] if gen.uses_fmt_size else []) + \ (["%fmt_desc_tab", "%fmt_norm_rep_tab"] if gen.uses_fmt_tables else []) + \ + (["%fmt_enc_desc_tab"] if gen.uses_fmt_enc_table else []) + \ [f"%stv{c}_{d}" for d in sorted(store_dims) for c in range(3)] + \ [f"%itx{c}_{d}" for d in sorted(gen.uses_int_fetch) for c in (1, 2)] psb = gen.uses_psb @@ -16578,6 +17384,8 @@ def assemble(gen): caps += [c for c in ("GroupNonUniform", "GroupNonUniformArithmetic") if c not in caps] if gen.uses_quad: caps += [c for c in ("GroupNonUniform", "GroupNonUniformQuad") if c not in caps] + if gen.uses_int_dot: + caps += ["DotProductKHR", "DotProductInput4x8BitPackedKHR"] # shaderIntegerDotProduct if gen.uses_f64: caps.append("Float64") if gen.uses_fma_khr: @@ -16617,8 +17425,12 @@ def assemble(gen): # Core in SPIR-V 1.4, so no extension at vulkan1.2; the runtime checks the properties in "float_controls" # (shaderSignedZeroInfNanPreserveFloat64 too for a module that uses Float64, SHADER-597). caps += ["SignedZeroInfNanPreserve", "DenormPreserve"] + if gen.ftz32: + caps.append("DenormFlushToZero") pops = gen.uses_pops and gen.stage == "ps" exts = (["SPV_KHR_physical_storage_buffer"] if psb else []) + (["SPV_EXT_descriptor_indexing"] if tex else []) + if gen.uses_int_dot: + exts.append("SPV_KHR_integer_dot_product") if gen.uses_fma_khr: exts.append("SPV_KHR_fma") if gen.uses_clock: @@ -16630,9 +17442,13 @@ def assemble(gen): if pops: caps.append("FragmentShaderPixelInterlockEXT") exts.append("SPV_EXT_fragment_shader_interlock") + if gen.uses_vmm: + caps += ["VulkanMemoryModel", "VulkanMemoryModelDeviceScope"] + exts.append("SPV_KHR_vulkan_memory_model") + gen.cu(1) hdr = [f"OpCapability {c}" for c in caps] + [f'OpExtension "{e}"' for e in exts] + \ ['%glsl = OpExtInstImport "GLSL.std.450"', - f"OpMemoryModel {'PhysicalStorageBuffer64' if psb else 'Logical'} GLSL450", + f"OpMemoryModel {'PhysicalStorageBuffer64' if psb else 'Logical'} {'Vulkan' if gen.uses_vmm else 'GLSL450'}", f"OpEntryPoint {model} %main \"main\" {' '.join(iface)}"] if cs: hdr.append("OpExecutionMode %main LocalSize {} {} {}".format(*gen.cs["size"])) @@ -16659,6 +17475,8 @@ def assemble(gen): # in modules that declare Float64; --no-float-controls leaves it out with the other modes. hdr.append("OpExecutionMode %main SignedZeroInfNanPreserve 64") hdr.append("OpExecutionMode %main DenormPreserve 16") + if gen.ftz32: + hdr.append("OpExecutionMode %main DenormFlushToZero 32") dec = [] if vs: dec.append("OpDecorate %vertex_index BuiltIn VertexIndex") @@ -16747,6 +17565,28 @@ def assemble(gen): "%rt_uint = OpTypeRuntimeArray %uint", "%_ptr_PSB_arr = OpTypePointer PhysicalStorageBuffer %rt_uint", "%_ptr_PSB_uint = OpTypePointer PhysicalStorageBuffer %uint"] dec.append("OpDecorate %rt_uint ArrayStride 4") + if gen.uses_psb_scalar_ro: + types += ["%sl_blk1 = OpTypeStruct %uint", + "%_ptr_PSB_sl_blk1 = OpTypePointer PhysicalStorageBuffer %sl_blk1"] + dec += ["OpDecorate %sl_blk1 Block", "OpMemberDecorate %sl_blk1 0 Offset 0", + "OpMemberDecorate %sl_blk1 0 NonWritable"] + if gen.uses_psb_vec or gen.uses_psb_vec_rw: # dedupe_types merges these with any other uvec2 / uvec4 + types += ["%v2uint_sl = OpTypeVector %uint 2", "%v4uint_sl = OpTypeVector %uint 4", + "%_ptr_PSB_v2uint_sl = OpTypePointer PhysicalStorageBuffer %v2uint_sl", + "%_ptr_PSB_v4uint_sl = OpTypePointer PhysicalStorageBuffer %v4uint_sl"] + if gen.uses_psb_vec: + types += ["%sl_blk2 = OpTypeStruct %v2uint_sl", "%sl_blk4 = OpTypeStruct %v4uint_sl", + "%_ptr_PSB_sl_blk2 = OpTypePointer PhysicalStorageBuffer %sl_blk2", + "%_ptr_PSB_sl_blk4 = OpTypePointer PhysicalStorageBuffer %sl_blk4"] + for blk in ("%sl_blk2", "%sl_blk4"): + dec += [f"OpDecorate {blk} Block", f"OpMemberDecorate {blk} 0 Offset 0", + f"OpMemberDecorate {blk} 0 NonWritable"] + if gen.uses_psb_vec_rw: + types += ["%sl_rw_blk2 = OpTypeStruct %v2uint_sl", "%sl_rw_blk4 = OpTypeStruct %v4uint_sl", + "%_ptr_PSB_sl_rw_blk2 = OpTypePointer PhysicalStorageBuffer %sl_rw_blk2", + "%_ptr_PSB_sl_rw_blk4 = OpTypePointer PhysicalStorageBuffer %sl_rw_blk4"] + for blk in ("%sl_rw_blk2", "%sl_rw_blk4"): + dec += [f"OpDecorate {blk} Block", f"OpMemberDecorate {blk} 0 Offset 0"] types += [f"{name} = OpConstant %ulong {v}" for v, name in sorted(gen.lconsts.items())] if tex: # Bindless set 0: images (binding 0), samplers (binding 1), descriptor hash table (binding 2). @@ -16824,14 +17664,27 @@ def assemble(gen): if gen.uses_fmt_tables: gen.cu(128) gen.cu(17) - if gen.uses_store_views or gen.uses_int_fetch: + if gen.uses_fmt_enc_table: + gen.cu(128) + for v in Gen.fmt_enc_desc_table(): + gen.cu(v) + if store_dims or gen.uses_int_fetch or gen.uses_d16_image: gen.cu(16) + if store_dims or gen.uses_int_fetch: for words in Gen.int_format_masks(): for w in words: gen.cu(w) + if gen.uses_d16_image: + for words in Gen.float_format_masks(): + for w in words: + gen.cu(w) gen.consts.setdefault(0, "%c0") for v, name in sorted(gen.consts.items()): types.append(f"{name} = OpConstant %uint {v}") + if gen.uses_lit_sampler_spec and gen.literal_samplers: + for i in range(len(gen.literal_samplers)): + dec.append(f"OpDecorate %lit_smp_{i} SpecId {i}") + types.append(f"%lit_smp_{i} = OpSpecConstant %uint 4294967295") # fconst's floats (%f0 and %f1 are declared with the types above). types += [f"{name} = OpConstant %float {float_literal(v)}" for v, name in sorted(gen.fconsts.items()) if v not in (0, 0x3F800000)] @@ -16851,6 +17704,11 @@ def assemble(gen): # --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") + for n in sorted({k[0] for k in gen.sbuf_slow_fns}): + types += [f"%arr_sbuf_x{n} = OpTypeArray %uint {gen.cu(n)}", + f"%_ptr_Function_arr_sbuf_x{n} = OpTypePointer Function %arr_sbuf_x{n}", + f"%null_sbuf_x{n} = OpConstantNull %arr_sbuf_x{n}", + f"%fn_sbuf_slow_x{n} = OpTypeFunction %arr_sbuf_x{n} %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: @@ -16859,6 +17717,7 @@ def assemble(gen): types.append("%fn_fmt_dec = OpTypeFunction %uint %uint %v4uint_fmt %uint") types.append("%fn_fmt_norm = OpTypeFunction %uint %uint %uint") if gen.fmt_enc_fn: + types.append("%fn_fmt_enc_chan = OpTypeFunction %uint %uint %uint %uint %bool") types.append("%fn_fmt_encode = OpTypeFunction %v4uint_fmt " + " ".join(["%uint"] * 29)) for arity, fn_type in sorted(gen.x_round_fn_types.items()): types.append(f"{fn_type} = OpTypeFunction %uint " + " ".join(["%uint"] * arity)) @@ -16921,6 +17780,13 @@ def assemble(gen): " ".join(gen.lconsts[v] for v in Gen.fmt_norm_reps())) gvars += ["%fmt_desc_tab = OpVariable %_ptr_Private_fmt_desc Private %fmt_desc_init", "%fmt_norm_rep_tab = OpVariable %_ptr_Private_fmt_rep Private %fmt_norm_rep_init"] + if gen.uses_fmt_enc_table: + types += [f"%fmt_enc_desc_arr = OpTypeArray %uint {gen.cu(128)}", + "%_ptr_Private_fmt_enc_desc = OpTypePointer Private %fmt_enc_desc_arr", + "%_ptr_Private_fmt_enc_elem = OpTypePointer Private %uint"] + types.append("%fmt_enc_desc_init = OpConstantComposite %fmt_enc_desc_arr " + + " ".join(gen.consts[v] for v in Gen.fmt_enc_desc_table())) + gvars += ["%fmt_enc_desc_tab = OpVariable %_ptr_Private_fmt_enc_desc Private %fmt_enc_desc_init"] if store_dims or gen.uses_int_fetch or gen.uses_d16_image: u, si = Gen.int_format_masks() types += ["%v4uint_st = OpTypeVector %uint 4", "%v4int_st = OpTypeVector %int 4", @@ -16928,9 +17794,12 @@ def assemble(gen): f"%fmt_mask_arr = OpTypeArray %uint {gen.cu(16)}", "%_ptr_Private_fmt = OpTypePointer Private %fmt_mask_arr", "%_ptr_Private_uint = OpTypePointer Private %uint"] - for nm, words in (("uint", u), ("sint", si)) + ( - (("norm", Gen.float_format_masks()[0]), ("f32", Gen.float_format_masks()[1])) - if gen.uses_d16_image else ()): + mask_tables = () + if store_dims or gen.uses_int_fetch: + mask_tables += (("uint", u), ("sint", si)) + if gen.uses_d16_image: + mask_tables += (("norm", Gen.float_format_masks()[0]), ("f32", Gen.float_format_masks()[1])) + for nm, words in mask_tables: ids = " ".join(gen.cu(w) for w in words) types += [f"%fmt_{nm}_init = OpConstantComposite %fmt_mask_arr {ids}"] gvars += [f"%fmt_{nm}_mask = OpVariable %_ptr_Private_fmt Private %fmt_{nm}_init"] @@ -16959,7 +17828,7 @@ def assemble(gen): f"%_ptr_UC_rt_stv{cls}_{di} = OpTypePointer UniformConstant %rt_stv{cls}_{di}", f"%_ptr_UC_stv{cls}_{di} = OpTypePointer UniformConstant %stimg{cls}_{di}"] dec += [f"OpDecorate %stv{cls}_{di} DescriptorSet 0", f"OpDecorate %stv{cls}_{di} Binding {base + cls}"] - if gen.coherent_images: + if gen.coherent_images and not gen.uses_vmm: dec.append(f"OpDecorate %stv{cls}_{di} Coherent") gvars += [f"%stv{cls}_{di} = OpVariable %_ptr_UC_rt_stv{cls}_{di} UniformConstant"] if gsx: @@ -17286,6 +18155,8 @@ def assemble(gen): helpers.extend(function) for function in gen.x_round_fns.values(): helpers.extend(function) + for key in sorted(gen.sbuf_slow_fns): + helpers.extend(gen.sbuf_slow_fns[key]) tree, nesting = (capped_tree(gen.succ, gen.out_pcs) if gen.blocks and not gen.emulate and not gen.bar_rounds else (None, None)) if nesting is not None: @@ -17545,10 +18416,56 @@ def label(prefix): tail = end_lock + " OpReturn\n OpFunctionEnd\n" if serial_close: gen.body = list(gen.body) + [(" " + l if " = OpLabel" not in l else l) for l in serial_close] + if gen.uses_vmm and gen.coherent_images: + # VulkanMemoryModel bans the Coherent decoration; use per-op MakeTexelVisible/Available|NonPrivateTexel. + c1 = gen.cu(1) + def _vmm_texel(line): + s = line.strip() + if " = OpImageRead " in s and len(s.split()) == 6: + return line + f" MakeTexelVisible|NonPrivateTexel {c1}" + if s.startswith("OpImageWrite ") and len(s.split()) == 4: + return line + f" MakeTexelAvailable|NonPrivateTexel {c1}" + return line + out = [_vmm_texel(l) for l in out] + gen.body = [_vmm_texel(l) for l in gen.body] insert_late_constants(gen, out, written) - return split_big_switch(no_contraction(dedupe_types( + assembled = dedupe_types( "\n".join(" " + l if not l.startswith("%") or " = " not in l else l for l in out) + - "\n" + "\n".join(gen.body) + "\n" + tail))) + "\n" + "\n".join(gen.body) + "\n" + tail) + if gen.scalar_load_ro is None: + assembled = scalar_loads_read_only(assembled) + return split_big_switch(no_contraction(assembled)) + + +_PSB_POINTER_TYPE = re.compile(r"(?m)^\s*(%[\w.]+) = OpTypePointer PhysicalStorageBuffer ") +_RESULT_OF_TYPE = re.compile(r"(?m)^\s*(%[\w.]+) = Op\w+ (%[\w.]+)") +_MEMORY_WRITE = re.compile(r"(?m)^\s*(?:(?:%[\w.]+ = )?(OpStore|OpAtomic\w+|OpCopyMemory\w*)\b(.*)|.*\b(OpImageWrite|" + r"OpImageTexelPointer)\b.*)$") + + +def scalar_loads_read_only(text): + """Keep scalar_load's NonWritable loads (%sl_blk1 / %sl_blk2 / %sl_blk4) only in a module that writes no memory. + + NonWritable lets the driver read them as SMEM (RADV: one s_load_b512 for an s_buffer_load_dwordx16), but also + lets it order them freely against the module's own stores, and an s_load / s_buffer_load sees what the same + program stored before it (docs/design.md, Scalar/buffer memory; tools/valu_fuzz.py --family mem stores and then + loads it back, and RADV read the old words in 18 of 600 programs with the decoration). A module with no store, + atomic or image write to any memory can't reach that: nothing this dispatch runs writes what it reads.""" + if "OpMemberDecorate %sl_blk" not in text: + return text + ptr_types = set(_PSB_POINTER_TYPE.findall(text)) + pointers = {r for r, t in _RESULT_OF_TYPE.findall(text) if t in ptr_types} + for m in _MEMORY_WRITE.finditer(text): + if m.group(3): + break # an image write or texel pointer: treat as a write + op, rest = m.group(1), m.group(2).split() + target = rest[0] if op in ("OpStore", "OpAtomicStore") or op.startswith("OpCopyMemory") else ( + rest[1] if len(rest) > 1 else None) # OpAtomicX %type %pointer ... + if target in pointers or op.startswith("OpCopyMemory"): + break + else: + return text + return re.sub(r"(?m)^\s*OpMemberDecorate %sl_blk[124] 0 NonWritable\n", "", text) # SPIR-V caps an instruction at 65,535 words. The dispatch loop's OpSwitch has one (literal, label) pair per block, @@ -17664,7 +18581,7 @@ def halves_analysis(g, blocks, succ): for slot in g.w64g.get("scalar_spills", ()): if slot not in g.parked: g.parked[slot] = g.SGPRS + len(g.parked) - g.w64_scalar_spills.add(slot) + g.scalar_spills.add(slot) W64G_COUNTS[g.w64g["tier"]] += 1 if g.w64g["tier"] == "C" and WAVE64_GRAPHICS == "error": raise Unsupported("wave64 graphics tier C: " + ", ".join(g.w64g["reasons"])) @@ -17819,6 +18736,338 @@ def sdwa_reads_dst(op: str, mods: list[str]) -> bool: "global_store", "flat_store", "scratch_store") +_FLOAT_ONLY_IMAGE_OPS = frozenset({"image_load", "image_load_mip", "image_sample", "image_sample_l", "image_sample_lz"}) + +# VALU ops whose VGPR source operands are strictly IEEE binary32 float (never raw integer/bitfield ops). +_F32_ONLY_CONSUMERS = frozenset({ + "v_add_f32", "v_sub_f32", "v_subrev_f32", "v_mul_f32", "v_mul_legacy_f32", + "v_mac_f32", "v_mac_legacy_f32", "v_fmac_f32", "v_fma_f32", "v_fma_legacy_f32", + "v_fmaak_f32", "v_fmamk_f32", "v_mad_f32", "v_mad_legacy_f32", "v_madak_f32", "v_madmk_f32", + "v_min_f32", "v_max_f32", "v_min3_f32", "v_max3_f32", "v_med3_f32", + "v_rcp_f32", "v_rcp_iflag_f32", "v_rsq_f32", "v_sqrt_f32", + "v_log_f32", "v_exp_f32", "v_sin_f32", "v_cos_f32", "v_floor_f32", "v_ceil_f32", "v_trunc_f32", + "v_rndne_f32", "v_fract_f32", "v_cvt_f16_f32", "v_cvt_pkrtz_f16_f32", "v_cvt_pknorm_i16_f32", + "v_cvt_pknorm_u16_f32", "v_cvt_u32_f32", "v_cvt_i32_f32", "v_cvt_f64_f32", + "v_cvt_rpi_i32_f32", "v_cvt_flr_i32_f32", "v_frexp_mant_f32", "v_frexp_exp_i32_f32", + "v_cubema_f32", "v_cubeid_f32", "v_cubesc_f32", "v_cubetc_f32", + "v_div_fixup_f32", "v_div_fmas_f32", "v_div_scale_f32", +}) + +# VALU ops whose VGPR source operands are strictly IEEE binary16 float (packed or scalar f16). +_F16_ONLY_CONSUMERS = frozenset({ + "v_add_f16", "v_sub_f16", "v_subrev_f16", "v_mul_f16", + "v_fma_f16", "v_fmac_f16", "v_fmaak_f16", "v_fmamk_f16", + "v_min_f16", "v_max_f16", "v_min3_f16", "v_max3_f16", "v_med3_f16", + "v_rcp_f16", "v_rsq_f16", "v_sqrt_f16", + "v_log_f16", "v_exp_f16", "v_sin_f16", "v_cos_f16", "v_floor_f16", "v_ceil_f16", + "v_trunc_f16", "v_rndne_f16", "v_fract_f16", + "v_pk_add_f16", "v_pk_mul_f16", "v_pk_fma_f16", "v_pk_fmac_f16", "v_pk_min_f16", "v_pk_max_f16", + "v_cvt_f32_f16", "v_cvt_u16_f16", "v_cvt_i16_f16", + "v_cvt_norm_i16_f16", "v_cvt_norm_u16_f16", "v_cvt_pknorm_i16_f16", "v_cvt_pknorm_u16_f16", + "v_div_fixup_f16", "v_frexp_mant_f16", "v_frexp_exp_i16_f16", +}) + + +def _arg_vgprs(arg): + """Set of VGPR indices named by a single parsed operand.""" + if arg["k"] == "vgpr": + return set(range(arg["r"], arg["r"] + arg.get("n", 1))) + if arg["k"] == "vlist": + return set(arg["r"]) + return set() + + +def _is_ds_dst_only(bop): + """Whether a DS op has a pure VGPR destination in a[0] (does not read a[0] as an address/data source).""" + return (bop.startswith(("ds_read", "ds_swizzle", "ds_permute", "ds_bpermute", "ds_append", "ds_consume")) + or "_rtn" in bop) + + +def _permlane_preserves_dst(bop, mods): + """Whether v_permlane16_b32 / v_permlanex16_b32 may preserve vdst (FI=0 and BOUND_CTRL=0).""" + if bop not in ("v_permlane16_b32", "v_permlanex16_b32"): + return False + if "fi:1" in mods or "bound_ctrl:1" in mods: + return False + sel = next((m for m in mods if m.startswith("op_sel:")), None) + if sel is not None: + try: + bits = [int(x) for x in sel.split("[")[1].rstrip("]").split(",")] + except (IndexError, ValueError): + return True + if (len(bits) >= 1 and bits[0]) or (len(bits) >= 2 and bits[1]): + return False + return True + + +def _vgpr_reads_of(ins): + """Set of VGPR indices read by instruction `ins` (matches read_before_write_vgprs + atomics/DS).""" + a, op = ins["args"], ins["op"] + if not a: + return set() + bop = base_op(op) + mods = ins.get("mods", ()) + reads_all = (op.startswith(VGPR_READ_ONLY_PREFIXES) + or bop.startswith(("buffer_atomic_", "image_atomic_", "flat_atomic_", "global_atomic_")) + or (bop.startswith(("buffer_load", "tbuffer_load")) and "lds" in mods) + or (bop.startswith("ds_") and not _is_ds_dst_only(bop))) + regs = set() + for x in (a if reads_all or sdwa_reads_dst(op, mods) else a[1:]): + if x["k"] == "vgpr": + regs.update(range(x["r"], x["r"] + x.get("n", 1))) + elif x["k"] == "vlist": + regs.update(x["r"]) + if (bop in DST_ALSO_READ or _permlane_preserves_dst(bop, mods) or + (op.startswith(("global_load_", "buffer_load_")) and "_d16" in op and "format" not in op) or + op == "buffer_load_format_d16_hi_x") and \ + a[0]["k"] == "vgpr": + regs.add(a[0]["r"]) + return regs + + +def _vgpr_full_writes_of(ins): + """Set of VGPR indices unconditionally and completely overwritten by `ins` (conservative).""" + a, op = ins["args"], ins["op"] + if not a or op.endswith(("_sdwa", "_dpp")): + return set() + bop = base_op(op) + mods = ins.get("mods", ()) + if bop == "v_writelane_b32" or _permlane_preserves_dst(bop, mods): + return set() + if bop.startswith(("buffer_atomic_", "image_atomic_", "flat_atomic_", "global_atomic_")): + return set() + if bop.startswith(("buffer_load", "tbuffer_load")) and "lds" in mods: + return set() + if bop.startswith("ds_") and not _is_ds_dst_only(bop): + return set() + reads_all = op.startswith(VGPR_READ_ONLY_PREFIXES) + if reads_all or a[0]["k"] != "vgpr": + return set() + if "_d16" in op or "d16" in mods: + return set() + if bop.startswith("image_"): + dm = next((m for m in mods if m.startswith("dmask:")), "dmask:0x1") + try: + ncomp = bin(int(dm.split(":")[1], 0)).count("1") + except ValueError: + return set() + if ncomp <= 0: + return set() + return set(range(a[0]["r"], a[0]["r"] + min(ncomp, a[0].get("n", 1)))) + # Scalar 16-bit VALU ops preserve the unwritten 16-bit half of a[0], so never kill the full 32-bit VGPR. + if (any(s in bop for s in ("_f16", "_u16", "_i16", "_b16")) + and not bop.startswith(("v_pk_", "v_cvt_pk", "v_cvt_f32_", "v_cvt_u32_", "v_cvt_i32_", + "v_pack_b32_", "v_dot2", "v_dot4", "v_dot8"))): + return set() + return set(vgpr_dest_registers(ins)) + + +def _exec_monotone_widen(ins): + """Whether a writes_exec instruction only turns ON lanes (EXEC_new >= EXEC_old).""" + bop = base_op(ins["op"]) + a = ins["args"] + if bop in ("s_or_saveexec_b32", "s_or_saveexec_b64"): + return True + if bop in ("s_or_b32", "s_or_b64") and len(a) >= 3 and a[0]["k"] == "special": + dst_t = a[0].get("t", "") + if dst_t in ("exec", "exec_lo", "exec_hi"): + return any(x["k"] == "special" and x.get("t") == dst_t for x in a[1:3]) + if bop in ("s_wqm_b32", "s_wqm_b64") and len(a) >= 2 and a[0]["k"] == "special" and a[1]["k"] == "special": + dst_t = a[0].get("t", "") + if dst_t in ("exec", "exec_lo", "exec_hi") and a[1].get("t") == dst_t: + return True + return False + + +def _is_float_consumer_of(ins, regs, d16): + """Whether `ins` strictly interprets every VGPR in `regs` it reads as floating-point (f16 if d16, else f32).""" + raw_op = ins["op"] + if raw_op.endswith("_sdwa"): + return False + bop = base_op(raw_op) + a = ins["args"] + mods = ins.get("mods", ()) + if bop in ("v_fma_mix_f32", "v_fma_mixlo_f16", "v_fma_mixhi_f16"): + selhi = next((m for m in mods if m.startswith("op_sel_hi:")), "op_sel_hi:[0,0,0]") + try: + hb = ([int(x) for x in selhi.split("[")[1].rstrip("]").split(",")] + [0, 0, 0])[:3] + except (IndexError, ValueError): + return False + f16_srcs, f32_srcs = set(), set() + for i in range(3): + if 1 + i < len(a): + (f16_srcs if hb[i] else f32_srcs).update(_arg_vgprs(a[1 + i])) + want, other = (f16_srcs, f32_srcs) if d16 else (f32_srcs, f16_srcs) + return bool(regs) and regs <= want and not (regs & other) + if d16: + if bop in _F16_ONLY_CONSUMERS: + return True + if bop.startswith(("v_cmp_", "v_cmpx_")) and bop.endswith("_f16"): + if "_class_" not in bop: + return True + src0_idx = 0 if (bop.startswith("v_cmpx_") or len(a) == 2) else 1 + s0 = _arg_vgprs(a[src0_idx]) if src0_idx < len(a) else set() + s1 = _arg_vgprs(a[src0_idx + 1]) if src0_idx + 1 < len(a) else set() + return bool(regs) and regs <= s0 and not (regs & s1) + if bop == "v_ldexp_f16": + s0 = _arg_vgprs(a[1]) if len(a) > 1 else set() + s1 = _arg_vgprs(a[2]) if len(a) > 2 else set() + return bool(regs) and regs <= s0 and not (regs & s1) + if bop in ("v_dot2_f32_f16", "v_dot2c_f32_f16"): + # src0 (a[1]) and src1 (a[2]) are f16x2; accumulator (a[3] / a[0]) is f32. + f16_srcs = (_arg_vgprs(a[1]) if len(a) > 1 else set()) | (_arg_vgprs(a[2]) if len(a) > 2 else set()) + acc_idx = 3 if bop == "v_dot2_f32_f16" else 0 + acc_regs = _arg_vgprs(a[acc_idx]) if acc_idx < len(a) else set() + return bool(regs) and regs <= f16_srcs and not (regs & acc_regs) + if bop == "v_pack_b32_f16" and not raw_op.endswith("_dpp") and len(a) >= 3: + # Plain v_pack_b32_f16 without sign/abs modifiers is also used to pack integer 16-bit halves + # (handled by transitive copy propagation below); with neg/abs it is strictly IEEE f16 sign/abs. + hit = [src for src in a[1:3] if _arg_vgprs(src) & regs] + return bool(hit) and all(src.get("neg") or src.get("abs") for src in hit) + return False + if bop in _F32_ONLY_CONSUMERS: + return True + if bop.startswith(("v_cmp_", "v_cmpx_")) and bop.endswith("_f32"): + if "_class_" not in bop: + return True + src0_idx = 0 if (bop.startswith("v_cmpx_") or len(a) == 2) else 1 + s0 = _arg_vgprs(a[src0_idx]) if src0_idx < len(a) else set() + s1 = _arg_vgprs(a[src0_idx + 1]) if src0_idx + 1 < len(a) else set() + return bool(regs) and regs <= s0 and not (regs & s1) + if bop == "v_ldexp_f32": + s0 = _arg_vgprs(a[1]) if len(a) > 1 else set() + s1 = _arg_vgprs(a[2]) if len(a) > 2 else set() + return bool(regs) and regs <= s0 and not (regs & s1) + if bop == "v_cvt_pk_u8_f32": + # src0 (a[1]) is f32; src1 (a[2], byte index) and src2 (a[3], packed u32) are integer. + s0 = _arg_vgprs(a[1]) if len(a) > 1 else set() + other = (_arg_vgprs(a[2]) if len(a) > 2 else set()) | (_arg_vgprs(a[3]) if len(a) > 3 else set()) + return bool(regs) and regs <= s0 and not (regs & other) + if bop in ("v_dot2_f32_f16", "v_dot2c_f32_f16"): + acc_idx = 3 if bop == "v_dot2_f32_f16" else 0 + acc_regs = _arg_vgprs(a[acc_idx]) if acc_idx < len(a) else set() + f16_srcs = (_arg_vgprs(a[1]) if len(a) > 1 else set()) | (_arg_vgprs(a[2]) if len(a) > 2 else set()) + return bool(regs) and regs <= acc_regs and not (regs & f16_srcs) + if not raw_op.endswith("_dpp") and not mods: + # VOP3 float sign/abs modifiers (-v / |v|) on v_mov_b32 / v_cndmask_b32 interpret f32 sign bit. + if bop == "v_mov_b32" and len(a) >= 2 and (_arg_vgprs(a[1]) & regs): + return bool(a[1].get("neg") or a[1].get("abs")) + if bop == "v_cndmask_b32" and len(a) >= 3: + hit = [src for src in a[1:3] if _arg_vgprs(src) & regs] + return bool(hit) and all(src.get("neg") or src.get("abs") for src in hit) + return False + + +def _copy_prop_dst(ins, regs, d16): + """If `ins` is a pure register copy/select/pack forwarding `regs` into a single VGPR, return that dst VGPR.""" + raw_op = ins["op"] + if raw_op.endswith(("_sdwa", "_dpp")): + return None + bop = base_op(raw_op) + a = ins["args"] + mods = ins.get("mods", ()) + if not a or a[0]["k"] != "vgpr" or a[0].get("n", 1) != 1: + return None + if bop == "v_mov_b32" and not mods and len(a) >= 2 and a[1]["k"] == "vgpr" and a[1].get("n", 1) == 1: + if not a[1].get("neg") and not a[1].get("abs"): + return a[0]["r"] + return None + if bop == "v_cndmask_b32" and not mods and len(a) >= 3: + if d16 and any((src.get("neg") or src.get("abs")) for src in a[1:3] if _arg_vgprs(src) & regs): + return None + return a[0]["r"] + if d16 and bop == "v_pack_b32_f16" and len(a) >= 3: + return a[0]["r"] + return None + + +def float_only_image_ops(blocks, succ): + """Set of id(ins) for image_load/image_sample ops whose dest VGPRs are consumed solely by float ops.""" + nb = len(blocks) + out = set() + for b_idx, blk in enumerate(blocks): + for i_idx, ins in enumerate(blk): + bop = base_op(ins["op"]) + if bop not in _FLOAT_ONLY_IMAGE_OPS: + continue + a = ins["args"] + if not a or a[0]["k"] != "vgpr": + continue + mods = ins.get("mods", ()) + d16 = "d16" in mods + dm = next((m for m in mods if m.startswith("dmask:")), "dmask:0x1") + try: + dmask = int(dm.split(":")[1], 0) + except ValueError: + continue + ncomp = bin(dmask).count("1") + nregs = (ncomp + 1) // 2 if d16 else ncomp + if nregs <= 0: + continue + dst_regs = set(range(a[0]["r"], a[0]["r"] + nregs)) + # Monotone forward dataflow from (b_idx, i_idx + 1): + # in_live[b]: union of tracked VGPRs (including transitive copies) reaching block b + # in_exec_sup[b]: True iff EVERY reaching path preserved EXEC >= EXEC_at_image_load + in_live = [None] * nb + in_exec_sup = [None] * nb + saw_float = False + ok = True + + def _scan(cb, start_i, live, exec_sup): + nonlocal saw_float, ok + ended = False + for u in blocks[cb][start_i:]: + ubop = base_op(u["op"]) + if ubop == "s_endpgm": + ended = True + break + if (ubop.startswith(("v_movrels", "v_movreld", "v_movrelsd", "v_swaprel")) + or ubop in ("s_swappc_b64", "s_setpc_b64", "s_call_b64")): + ok = False + return + r_used = live & _vgpr_reads_of(u) + copied_dst = None + if r_used: + if _is_float_consumer_of(u, r_used, d16): + saw_float = True + else: + copied_dst = _copy_prop_dst(u, r_used, d16) + if copied_dst is None: + ok = False + return + if writes_exec(u) and not _exec_monotone_widen(u): + exec_sup = False + if copied_dst is not None: + live.add(copied_dst) + elif exec_sup: + live -= _vgpr_full_writes_of(u) + if not live: + ended = True + break + if ok and not ended and live: + for nxt in succ[cb]: + if in_live[nxt] is None: + in_live[nxt] = set(live) + in_exec_sup[nxt] = exec_sup + work.append(nxt) + else: + new_live = in_live[nxt] | live + new_sup = in_exec_sup[nxt] and exec_sup + if len(new_live) != len(in_live[nxt]) or new_sup != in_exec_sup[nxt]: + in_live[nxt] = new_live + in_exec_sup[nxt] = new_sup + work.append(nxt) + + work = [] + _scan(b_idx, i_idx + 1, set(dst_regs), True) + while work and ok: + cb = work.pop() + _scan(cb, 0, set(in_live[cb]), in_exec_sup[cb]) + if ok and saw_float: + out.add(id(ins)) + return out + + def read_before_write_vgprs(insns): """VGPRs a shader reads before writing them: for a fetch-calling VS these are the fetched attributes. @@ -18814,6 +20063,878 @@ def barriers_under_control_flow(text): return False +_FTZ32_DISABLE_OPS = frozenset({"v_div_scale_f32", "v_div_fmas_f32", "s_denorm_mode"}) +_HWREG_MODE_RE = re.compile( + r"^hwreg\(\s*(\w+)(?:\s*,\s*(0x[0-9a-fA-F]+|\d+)(?:\s*,\s*(0x[0-9a-fA-F]+|\d+))?)?\s*\)$" +) + + +def _disables_ftz32(insns): + """Whether any instruction in `insns` requires disabling hardware DenormFlushToZero 32. + + v_div_scale_f32 and v_div_fmas_f32 preserve subnormal f32 inputs/intermediates on RDNA2 even under denorm32=0, + and s_denorm_mode / s_setreg* writing HW_REG_MODE bits [5:4] (FP_DENORM.fp32) to a non-zero or non-constant + value may disable f32 denormal flushing. Writes to disjoint MODE bit ranges (such as FP_ROUND.fp64_fp16 in + bits [3:2]) or immediate writes that set the overlapped [5:4] bits to 0 keep FTZ32 enabled.""" + for ins in insns: + op = base_op(ins["op"]) + if op in _FTZ32_DISABLE_OPS: + return True + if not op.startswith("s_setreg"): + continue + if not ins["args"]: + return True + a0 = ins["args"][0] + if a0.get("k") == "imm": + simm16 = a0["v"] & 0xFFFF + if (simm16 & 0x3F) != 1: + continue + offset = (simm16 >> 6) & 0x1F + size = ((simm16 >> 11) & 0x1F) + 1 + else: + t = a0.get("t", "") + m = _HWREG_MODE_RE.match(t) + if not m: + return True + reg_id = m.group(1) + if reg_id != "HW_REG_MODE": + try: + if int(reg_id, 0) != 1: + continue + except ValueError: + continue + offset = int(m.group(2), 0) if m.group(2) is not None else 0 + size = int(m.group(3), 0) if m.group(3) is not None else 32 + if offset < 0 or offset >= 32 or size <= 0 or size > 32: + return True + lo = max(offset, 4) + hi = min(offset + size, 6) + if lo >= hi: + continue + if op == "s_setreg_imm32_b32" and len(ins["args"]) >= 2 and ins["args"][1].get("k") == "imm" \ + and not ins["args"][1].get("abs"): + val = ins["args"][1]["v"] & 0xFFFFFFFF + mask = (1 << (hi - lo)) - 1 + if ((val >> (lo - offset)) & mask) != 0: + return True + continue + return True + return False + + +_PSB_WRITE_PREFIXES = ( + "buffer_store", "tbuffer_store", "buffer_atomic", + "global_store", "global_atomic", + "flat_store", "flat_atomic", + "scratch_store", + "s_store", "s_buffer_store", "s_atomic", "s_buffer_atomic", +) + + +def _scalar_operand_slots(arg): + """Return list of scalar slots (int SGPR index or 'vcc_lo'/'vcc_hi') for an operand, or None.""" + k = arg.get("k") + if k == "sgpr": + return list(range(arg["r"], arg["r"] + arg.get("n", 1))) + if k == "slist": + return list(arg["r"]) + if k == "special" and arg.get("t") in ("vcc", "vcc_lo", "vcc_hi"): + return ["vcc_lo", "vcc_hi"] if arg["t"] == "vcc" else [arg["t"]] + return None + + +def _symbolic_origin(tag): + """Return a non-constant symbolic descriptor/pointer origin tag, or None if unknown/constant.""" + if tag is None or tag[0] == "const": + return None + return tag + + +def _root_origin(tag): + """Unwrap an arithmetic-offset wrapper ('off', root) to its underlying symbolic root origin.""" + if tag is not None and tag[0] == "off": + return tag[1] + return tag + + +def _as_offset_origin(tag): + """Mark a symbolic pointer tag as having an untracked arithmetic offset (preserving code/rodata).""" + if tag is None or tag[0] in ("const", "code", "off"): + return tag + return ("off", tag) + + +def _origin_depth(tag): + """Nesting depth of a symbolic ('load'/'load_dyn', base, ...) origin tag.""" + d = 0 + cur = _root_origin(tag) + while cur is not None and cur[0] in ("load", "load_dyn"): + d += 1 + cur = _root_origin(cur[1]) + return d + + +def _merge_sym_tag(v1, v2): + """Join two symbolic provenance tags at a CFG merge or conditional select.""" + if v1 == v2: + return v1 + if v1 is None or v2 is None: + return None + r1, r2 = _root_origin(v1), _root_origin(v2) + if r1 is not None and r1 == r2 and r1[0] != "const": + return _as_offset_origin(r1) + if r1 is not None and r2 is not None and r1[0] in ("load", "load_dyn") and r2[0] in ("load", "load_dyn") and r1[1] == r2[1]: + return ("load_dyn", r1[1]) + return None + + +def _origins_may_alias(o1, o2): + """Conservative alias check between two symbolic descriptor/pointer origins.""" + if o1 is None or o2 is None: + return True + r1, r2 = _root_origin(o1), _root_origin(o2) + if r1 is None or r2 is None: + return True + if r1 == r2: + return True + if r1[0] == "code" or r2[0] == "code": + return False + if r1[0] == "load" and r2[0] == "load": + return r1[2] == r2[2] and _origins_may_alias(r1[1], r2[1]) + # Dynamic offset load from an aliasing base table may hit any static/dynamic slot in that table. + if r1[0] in ("load", "load_dyn") and r2[0] in ("load", "load_dyn"): + return _origins_may_alias(r1[1], r2[1]) + return False + + +def _origin_chain_aliases_known(origin, known_writes): + """Whether `origin` or any ancestor table pointer in its load chain aliases a write origin in `known_writes`.""" + cur = _root_origin(origin) + while cur is not None: + if any(_origins_may_alias(cur, wo) for wo in known_writes): + return True + cur = _root_origin(cur[1]) if cur[0] in ("load", "load_dyn") else None + return False + + +def _psb_write_origin(ins, sym): + """Extract the symbolic base-address origin of a PSB memory write instruction, or None if unknown.""" + op = base_op(ins["op"]) + a = ins["args"] + if op.startswith(("buffer_store", "tbuffer_store", "buffer_atomic")): + if len(a) >= 3: + slots = _scalar_operand_slots(a[2]) + if slots and len(slots) == 4: + return _symbolic_origin(sym.get(slots[0])) + return None + if op.startswith("global_store"): + if len(a) >= 3: + slots = _scalar_operand_slots(a[2]) + if slots and len(slots) == 2: + return _symbolic_origin(sym.get(slots[0])) + return None + if op.startswith("global_atomic"): + idx = 3 if "glc" in ins["mods"] else 2 + if len(a) > idx: + slots = _scalar_operand_slots(a[idx]) + if slots and len(slots) == 2: + return _symbolic_origin(sym.get(slots[0])) + return None + if op.startswith(("s_store", "s_buffer_store", "s_atomic", "s_buffer_atomic")): + if len(a) >= 2: + slots = _scalar_operand_slots(a[1]) + if slots: + return _symbolic_origin(sym.get(slots[0])) + return None + return None + + +def _sload_static_offset(ins, sym, is_sbuf): + """Return the normalized static byte offset of an s_load / s_buffer_load, or None if dynamic.""" + a = ins["args"] + off = a[2] if len(a) > 2 else {"k": "imm", "v": 0} + inst = [m.split(":", 1)[1] for m in ins["mods"] if m.startswith("offset:")] + if len(inst) > 1 or (inst and off["k"] == "imm"): + return None + imm = 0 + if inst: + try: + imm = int(inst[0], 0) + except ValueError: + return None + reg_const = None + if off["k"] == "imm": + imm = off["v"] + elif off["k"] == "special" and off.get("t") == "null": + reg_const = 0 + else: + slots = _scalar_operand_slots(off) + if not slots or len(slots) != 1: + return None + tag = sym.get(slots[0]) + if tag is None or tag[0] != "const": + return None + reg_const = tag[1] & 0xFFFFFFFC + if is_sbuf: + imm &= 0xFFFFFFFF + else: + imm = ((imm & 0x1FFFFF) ^ 0x100000) - 0x100000 + imm &= ~3 + return (reg_const + imm) if reg_const is not None else imm + + +def _read_scalar_tag(sym, arg): + """Read a 32-bit constant or symbolic provenance tag for a single scalar operand.""" + if arg["k"] == "imm": + return ("const", arg["v"] & 0xFFFFFFFF) + if arg["k"] == "special" and arg.get("t") == "null": + return ("const", 0) + slots = _scalar_operand_slots(arg) + if slots and len(slots) == 1: + return sym.get(slots[0]) + return None + + +def _const_lane(sym, arg): + """Constant lane index (0..63) for v_writelane_b32 / v_readlane_b32, or None if dynamic.""" + t = _read_scalar_tag(sym, arg) + return t[1] & 63 if t is not None and t[0] == "const" else None + + +def _step_scalar_provenance(sym, ins, desc_src=None): + """Advance forward SGPR/VCC/spill-VGPR provenance state across one instruction. + + When `desc_src` is given (slot -> frozenset of s_load instruction ids), also propagates which s_load + instructions originated each slot's value (through copies, selects, and VGPR spill lanes) so descriptor-only + loads can be verified.""" + op = base_op(ins["op"]) + a = ins["args"] + if op in ("s_swappc_b64", "s_setpc_b64", "s_call_b64") or op.startswith("s_movreld"): + sym.clear() + if desc_src is not None: + desc_src.clear() + return + if not a: + return + + def read_tag(arg): + return _read_scalar_tag(sym, arg) + + def clear_slots(slots): + if slots: + for s in slots: + sym.pop(s, None) + if desc_src is not None: + desc_src.pop(s, None) + + def clear_vgpr_lanes(vregs): + if not vregs: + return + for k in [k for k in sym if isinstance(k, tuple) and k[1] in vregs]: + del sym[k] + if desc_src is not None: + for k in [k for k in desc_src if isinstance(k, tuple) and k[1] in vregs]: + del desc_src[k] + + if op.startswith(("v_movreld", "v_movrelsd", "v_swaprel")): + for k in [k for k in sym if isinstance(k, tuple)]: + del sym[k] + if desc_src is not None: + for k in [k for k in desc_src if isinstance(k, tuple)]: + del desc_src[k] + return + + if op == "v_writelane_b32" and len(a) >= 3 and a[0]["k"] == "vgpr": + vr = a[0]["r"] + lane = _const_lane(sym, a[2]) + if lane is None: + clear_vgpr_lanes({vr}) + return + key = ("v", vr, lane) + t = read_tag(a[1]) + if t is not None: + sym[key] = t + else: + sym.pop(key, None) + if desc_src is not None: + src = _scalar_operand_slots(a[1]) + if src and len(src) == 1 and src[0] in desc_src: + desc_src[key] = desc_src[src[0]] + else: + desc_src.pop(key, None) + return + + if op == "v_readlane_b32": + dst = _scalar_operand_slots(a[0]) + if dst and len(dst) == 1 and len(a) >= 3 and a[1]["k"] == "vgpr": + lane = _const_lane(sym, a[2]) + if lane is not None: + key = ("v", a[1]["r"], lane) + t = sym.get(key) + if t is not None: + sym[dst[0]] = t + else: + sym.pop(dst[0], None) + if desc_src is not None: + if key in desc_src: + desc_src[dst[0]] = desc_src[key] + else: + desc_src.pop(dst[0], None) + return + clear_slots(dst) + return + + if op == "s_mov_b32" and len(a) >= 2: + dst = _scalar_operand_slots(a[0]) + if dst and len(dst) == 1: + t = read_tag(a[1]) + if t is not None: + sym[dst[0]] = t + else: + sym.pop(dst[0], None) + if desc_src is not None: + src = _scalar_operand_slots(a[1]) + if src and len(src) == 1 and src[0] in desc_src: + desc_src[dst[0]] = desc_src[src[0]] + else: + desc_src.pop(dst[0], None) + return + if op == "s_movk_i32" and len(a) >= 2 and a[1]["k"] == "imm": + dst = _scalar_operand_slots(a[0]) + if dst and len(dst) == 1: + v = a[1]["v"] & 0xFFFF + if v & 0x8000: + v |= 0xFFFF0000 + sym[dst[0]] = ("const", v & 0xFFFFFFFF) + if desc_src is not None: + desc_src.pop(dst[0], None) + return + if op in ("s_addk_i32", "s_mulk_i32") and len(a) >= 2 and a[1]["k"] == "imm": + dst = _scalar_operand_slots(a[0]) + if dst and len(dst) == 1: + v = a[1]["v"] & 0xFFFF + if v & 0x8000: + v -= 0x10000 + cur = sym.get(dst[0]) + if cur is not None and cur[0] == "const": + sym[dst[0]] = ("const", ((cur[1] + v) if op == "s_addk_i32" else (cur[1] * v)) & 0xFFFFFFFF) + elif op == "s_addk_i32" and _symbolic_origin(cur) is not None: + sym[dst[0]] = cur if v == 0 else _as_offset_origin(cur) + else: + sym.pop(dst[0], None) + if desc_src is not None: + desc_src.pop(dst[0], None) + return + if op == "s_mov_b64" and len(a) >= 2: + dst = _scalar_operand_slots(a[0]) + if dst and len(dst) == 2: + if a[1]["k"] == "imm": + v = a[1]["v"] + sym[dst[0]] = ("const", v & 0xFFFFFFFF) + sym[dst[1]] = ("const", (v >> 32) & 0xFFFFFFFF) + if desc_src is not None: + desc_src.pop(dst[0], None) + desc_src.pop(dst[1], None) + else: + src = _scalar_operand_slots(a[1]) + if src and len(src) == 2: + vals = [sym.get(src[0]), sym.get(src[1])] + dvals = [desc_src.get(src[0]), desc_src.get(src[1])] if desc_src is not None else None + for i, (d, v) in enumerate(zip(dst, vals)): + if v is not None: + sym[d] = v + else: + sym.pop(d, None) + if desc_src is not None: + if dvals[i] is not None: + desc_src[d] = dvals[i] + else: + desc_src.pop(d, None) + else: + clear_slots(dst) + return + if op in ("s_cselect_b32", "s_cmov_b32") and len(a) >= (3 if op == "s_cselect_b32" else 2): + dst = _scalar_operand_slots(a[0]) + if dst and len(dst) == 1: + x_arg, y_arg = (a[1], a[2]) if op == "s_cselect_b32" else (a[1], a[0]) + merged = _merge_sym_tag(read_tag(x_arg), read_tag(y_arg)) + if merged is not None: + sym[dst[0]] = merged + else: + sym.pop(dst[0], None) + if desc_src is not None: + sx = _scalar_operand_slots(x_arg) + sy = _scalar_operand_slots(y_arg) + dx = desc_src.get(sx[0]) if sx and len(sx) == 1 else None + dy = desc_src.get(sy[0]) if sy and len(sy) == 1 else None + union = (dx or frozenset()) | (dy or frozenset()) + if union: + desc_src[dst[0]] = union + else: + desc_src.pop(dst[0], None) + return + if op in ("s_cselect_b64", "s_cmov_b64") and len(a) >= (3 if op == "s_cselect_b64" else 2): + dst = _scalar_operand_slots(a[0]) + if dst and len(dst) == 2: + x_arg, y_arg = (a[1], a[2]) if op == "s_cselect_b64" else (a[1], a[0]) + + def _pair_tags(arg): + if arg["k"] == "imm": + v = arg["v"] + return [("const", v & 0xFFFFFFFF), ("const", (v >> 32) & 0xFFFFFFFF)], [None, None] + s = _scalar_operand_slots(arg) + if s and len(s) == 2: + return ([sym.get(s[0]), sym.get(s[1])], + [desc_src.get(s[0]), desc_src.get(s[1])] if desc_src is not None else [None, None]) + return [None, None], [None, None] + + xt, xd = _pair_tags(x_arg) + yt, yd = _pair_tags(y_arg) + for i, d in enumerate(dst): + merged = _merge_sym_tag(xt[i], yt[i]) + if merged is not None: + sym[d] = merged + else: + sym.pop(d, None) + if desc_src is not None: + union = (xd[i] or frozenset()) | (yd[i] or frozenset()) + if union: + desc_src[d] = union + else: + desc_src.pop(d, None) + return + if op == "s_getpc_b64": + dst = _scalar_operand_slots(a[0]) + if dst and len(dst) == 2: + sym[dst[0]] = ("code",) + sym[dst[1]] = ("code",) + if desc_src is not None: + desc_src.pop(dst[0], None) + desc_src.pop(dst[1], None) + return + if op in ("s_add_u32", "s_add_i32", "s_addc_u32", "s_sub_u32", "s_sub_i32", "s_subb_u32", + "s_and_b32", "s_or_b32", "s_xor_b32", "s_lshl_b32", "s_lshr_b32", "s_mul_i32", + "s_lshl1_add_u32", "s_lshl2_add_u32", "s_lshl3_add_u32", "s_lshl4_add_u32") and len(a) >= 3: + dst = _scalar_operand_slots(a[0]) + if dst and len(dst) == 1: + t0, t1 = read_tag(a[1]), read_tag(a[2]) + c0_flag = t0 is not None and t0[0] == "const" + c1_flag = t1 is not None and t1[0] == "const" + s0_slots = _scalar_operand_slots(a[1]) + s1_slots = _scalar_operand_slots(a[2]) + out = None + if op == "s_and_b32" and (t0 == ("const", 0) or t1 == ("const", 0)): + out = ("const", 0) + elif op in ("s_xor_b32", "s_sub_u32", "s_sub_i32") and s0_slots and s0_slots == s1_slots: + out = ("const", 0) + elif c0_flag and c1_flag: + c0, c1 = t0[1], t1[1] + if op in ("s_add_u32", "s_add_i32"): + out = ("const", (c0 + c1) & 0xFFFFFFFF) + elif op in ("s_sub_u32", "s_sub_i32"): + out = ("const", (c0 - c1) & 0xFFFFFFFF) + elif op == "s_and_b32": + out = ("const", c0 & c1) + elif op == "s_or_b32": + out = ("const", c0 | c1) + elif op == "s_xor_b32": + out = ("const", c0 ^ c1) + elif op == "s_lshl_b32": + out = ("const", (c0 << (c1 & 31)) & 0xFFFFFFFF) + elif op == "s_lshr_b32": + out = ("const", (c0 >> (c1 & 31)) & 0xFFFFFFFF) + elif op == "s_mul_i32": + out = ("const", (c0 * c1) & 0xFFFFFFFF) + elif op.startswith("s_lshl"): + sh = int(op[6]) + out = ("const", ((c0 << sh) + c1) & 0xFFFFFFFF) + elif op not in ("s_xor_b32", "s_lshl_b32", "s_lshr_b32", "s_mul_i32"): + s0, s1 = _symbolic_origin(t0), _symbolic_origin(t1) + if op.startswith("s_lshl"): + # (S0 << sh) + S1: shifting a base pointer left does not preserve its origin; + # only propagate S1 when the shifted index S0 is a known constant (marking as offset if non-zero). + if c0_flag and s1 is not None: + out = s1 if t0[1] == 0 else _as_offset_origin(s1) + elif s0 is not None and c1_flag: + noop = (op in ("s_add_u32", "s_add_i32", "s_sub_u32", "s_sub_i32", "s_or_b32") and t1[1] == 0) \ + or (op == "s_and_b32" and t1[1] == 0xFFFFFFFF) + out = s0 if noop else _as_offset_origin(s0) + elif s1 is not None and c0_flag and op not in ("s_sub_u32", "s_sub_i32", "s_subb_u32"): + noop = (op in ("s_add_u32", "s_add_i32", "s_or_b32") and t0[1] == 0) \ + or (op == "s_and_b32" and t0[1] == 0xFFFFFFFF) + out = s1 if noop else _as_offset_origin(s1) + elif op in ("s_and_b32", "s_or_b32") and s0 is not None and _root_origin(s0) == _root_origin(s1): + out = s0 if s0 == s1 else _as_offset_origin(s0) + if out is not None: + sym[dst[0]] = out + else: + sym.pop(dst[0], None) + if desc_src is not None: + desc_src.pop(dst[0], None) + return + if op.startswith(("s_load_dword", "s_buffer_load_dword")) and len(a) >= 2: + dst = _scalar_operand_slots(a[0]) + base = _scalar_operand_slots(a[1]) + if dst: + base_tag = _symbolic_origin(sym.get(base[0])) if base else None + base_root = _root_origin(base_tag) + if base_root is not None and _origin_depth(base_root) < 4: + off = None if base_tag[0] == "off" else _sload_static_offset(ins, sym, op.startswith("s_buffer")) + for i, slot in enumerate(dst): + sym[slot] = ("load", base_root, off + 4 * i) if off is not None else ("load_dyn", base_root) + else: + clear_slots(dst) + if desc_src is not None: + tag = frozenset((id(ins),)) if op.startswith("s_load_dword") else None + for slot in dst: + if tag is not None: + desc_src[slot] = tag + else: + desc_src.pop(slot, None) + return + # Any non-writelane instruction that writes a VGPR clears any spilled scalar lanes parked in that VGPR. + if (not op.startswith(VGPR_READ_ONLY_PREFIXES) + and not (op.startswith(("buffer_load", "tbuffer_load")) and "lds" in ins.get("mods", ())) + and not (op.startswith("ds_") and not _is_ds_dst_only(op))): + written_v = _arg_vgprs(a[0]) + if op == "v_swap_b32" and len(a) >= 2: + written_v |= _arg_vgprs(a[1]) + if written_v: + clear_vgpr_lanes(written_v) + # Any other instruction that writes scalar destination slots clears their provenance. + if op.startswith(("s_cmp", "s_bitcmp", "s_cbranch", "s_branch", "s_waitcnt", "s_nop", "s_endpgm", + "s_barrier", "s_sendmsg", "s_setreg", "s_round_mode", "s_store", "s_buffer_store", + "buffer_", "tbuffer_", "global_", "flat_", "scratch_", "image_", "ds_", "exp")): + return + if op.startswith("v_cmp"): + if not op.startswith("v_cmpx"): + dst = _scalar_operand_slots(a[0]) + clear_slots(dst if dst else ["vcc_lo", "vcc_hi"]) + elif op.startswith("s_") or op in ("v_readfirstlane_b32", "v_readlane_b32"): + clear_slots(_scalar_operand_slots(a[0])) + if len(a) >= 2 and op in ("v_add_co_u32", "v_add_co_ci_u32", "v_sub_co_u32", "v_sub_co_ci_u32", + "v_subrev_co_u32", "v_subrev_co_ci_u32", "v_mad_u64_u32", "v_mad_i64_i32", + "v_div_scale_f32", "v_div_scale_f64"): + clear_slots(_scalar_operand_slots(a[1])) + + +def _classify_scalar_uses(ins, sym, desc_src, used_as_desc, used_as_data, used_as_sload_base): + """Record whether scalar operands read by `ins` are used solely as descriptors (T#/S#/V#), as base pointers + of another s_load, or as general data.""" + if not desc_src: + return + op = base_op(ins["op"]) + a = ins["args"] + if not a: + return + if op in ("s_mov_b32", "s_mov_b64", "s_cselect_b32", "s_cselect_b64", "s_cmov_b32", "s_cmov_b64"): + dst = _scalar_operand_slots(a[0]) + want = 2 if op.endswith("_b64") else 1 + if dst and len(dst) == want: + # Pure copies/selects into tracked scalar slots propagate desc_src without classifying the value yet. + return + if op in ("s_swappc_b64", "s_setpc_b64", "s_call_b64") or op.startswith("s_movrel"): + for tags in desc_src.values(): + used_as_data.update(tags) + return + if op == "v_writelane_b32": + if len(a) >= 3 and a[0]["k"] == "vgpr": + lane = _const_lane(sym, a[2]) + # Lane index operand (if scalar reg) is data; source sS propagates into ("v", vr, lane) when lane is const. + for idx in ((2,) if lane is not None else (1, 2)): + slots = _scalar_operand_slots(a[idx]) + if slots: + for s in slots: + tags = desc_src.get(s) + if tags: + used_as_data.update(tags) + else: + for arg in a: + slots = _scalar_operand_slots(arg) + if slots: + for s in slots: + tags = desc_src.get(s) + if tags: + used_as_data.update(tags) + return + if op == "v_readlane_b32": + if len(a) >= 3 and a[1]["k"] == "vgpr": + lane = _const_lane(sym, a[2]) + slots = _scalar_operand_slots(a[2]) + if slots: + for s in slots: + tags = desc_src.get(s) + if tags: + used_as_data.update(tags) + if lane is None: + vr = a[1]["r"] + for k, tags in desc_src.items(): + if isinstance(k, tuple) and k[1] == vr: + used_as_data.update(tags) + return + if op.startswith(("v_movrels", "v_movreld", "v_movrelsd", "v_swaprel")): + for k, tags in desc_src.items(): + if isinstance(k, tuple): + used_as_data.update(tags) + else: + # Any non-readlane read of a spill VGPR consumes all descriptor tags parked in its lanes as general data. + vreads = _vgpr_reads_of(ins) + if vreads: + for k, tags in desc_src.items(): + if isinstance(k, tuple) and k[1] in vreads: + used_as_data.update(tags) + + # Identify operand indices that are pure descriptor reads (T#, S#, V#), s_load base ptrs, or write-only. + desc_idxs = set() + sload_base_idxs = set() + write_only_idxs = set() + if op.startswith("image_"): + if len(a) >= 3: + desc_idxs.add(2) # T# + if len(a) >= 4: + desc_idxs.add(3) # S# + if not op.startswith(("image_store", "image_atomic")): + write_only_idxs.add(0) + elif op.startswith(("buffer_", "tbuffer_")): + if "lds" in ins.get("mods", ()) and op.startswith(("buffer_load", "tbuffer_load")): + if len(a) >= 2: + desc_idxs.add(1) # V# (no vdata operand when lds is set) + else: + if len(a) >= 3: + desc_idxs.add(2) # V# + if op.startswith(("buffer_load", "tbuffer_load")): + write_only_idxs.add(0) + elif op.startswith("s_buffer_"): + if len(a) >= 2: + desc_idxs.add(1) # V# + if op.startswith("s_buffer_load"): + write_only_idxs.add(0) + elif op.startswith("s_load_dword"): + write_only_idxs.add(0) + if len(a) >= 2: + sload_base_idxs.add(1) + elif op.startswith("s_") and not op.startswith(("s_cmp", "s_bitcmp", "s_cbranch", "s_branch", "s_store", + "s_atomic", "s_setreg", "s_sendmsg", "s_waitcnt", "s_nop", + "s_endpgm", "s_barrier", "s_round_mode", "s_cmov", "s_bitset")): + write_only_idxs.add(0) + elif op.startswith("v_") and not op.startswith(("v_cmp", "v_cmpx")) and op not in DST_ALSO_READ: + write_only_idxs.add(0) + if op in ("v_add_co_u32", "v_add_co_ci_u32", "v_sub_co_u32", "v_sub_co_ci_u32", + "v_subrev_co_u32", "v_subrev_co_ci_u32", "v_mad_u64_u32", "v_mad_i64_i32", + "v_div_scale_f32", "v_div_scale_f64"): + write_only_idxs.add(1) + + child_id = id(ins) + for idx, arg in enumerate(a): + if idx in write_only_idxs: + continue + slots = _scalar_operand_slots(arg) + if not slots: + continue + if idx in sload_base_idxs: + for s in slots: + tags = desc_src.get(s) + if tags: + for parent_id in tags: + used_as_sload_base.setdefault(parent_id, set()).add(child_id) + continue + target = used_as_desc if idx in desc_idxs else used_as_data + for s in slots: + tags = desc_src.get(s) + if tags: + target.update(tags) + + +def analyse_scalar_load_ro(blocks, succ, user_limit=USER_SGPRS, sys_sgprs=()): + """Decide which s_load* / s_buffer_load* instructions may safely carry NonWritable (allowing RADV/ACO SMEM). + + Returns True when the shader performs no PhysicalStorageBuffer memory writes at all (all scalar loads are safe), + or a frozenset of id(ins) for scalar loads proven not to alias any PSB write in the module: + - If any s_dcache_* instruction is present alongside a PSB write, falls back conservatively to frozenset(). + - Descriptor-only s_load* (from a 32-bit or 64-bit user SGPR table pointer or multi-level table load, + including descriptors carried through scalar-spill VGPRs via v_writelane_b32/v_readlane_b32, whose origin + chain is not explicitly written and whose loaded dwords are consumed solely as T#/S#/V# descriptors or as + the base pointer of another descriptor-only s_load) and s_getpc_b64 code/rodata loads are read-only. + - Any scalar load with no PSB write reachable before it on any CFG path (`not store_reached`, including loop + back-edges) is read-only unless its known origin explicitly aliases a known PSB write reachable after it. + - Any scalar load whose symbolic descriptor/pointer origin (user SGPR root or static descriptor-table slot) is + strictly disjoint from every PSB write's origin in the module is read-only.""" + if not blocks: + return True + nb = len(blocks) + has_dcache = False + has_any_write = False + for b, blk in enumerate(blocks): + for ins in blk: + op = base_op(ins["op"]) + if op == "s_endpgm": + break + if op.startswith("s_dcache_"): + has_dcache = True + if op.startswith(_PSB_WRITE_PREFIXES): + has_any_write = True + if not has_any_write: + return True + if has_dcache: + return frozenset() + + # Forward SGPR/VCC/spill-VGPR descriptor provenance and s_load-origin dataflow (also discovers reachable blocks). + system = set(sys_sgprs) + entry_sym = [None] * nb + entry_dsrc = [None] * nb + entry_sym[0] = {r: ("in", r) for r in range(user_limit) if r not in system} + entry_dsrc[0] = {} + work = [0] + while work: + b = work.pop() + sym = dict(entry_sym[b]) + dsrc = dict(entry_dsrc[b]) + for ins in blocks[b]: + if base_op(ins["op"]) == "s_endpgm": + break + _step_scalar_provenance(sym, ins, dsrc) + for s in succ[b]: + if entry_sym[s] is None: + entry_sym[s] = dict(sym) + entry_dsrc[s] = dict(dsrc) + work.append(s) + else: + merged_sym = {} + for k, v in entry_sym[s].items(): + m = _merge_sym_tag(v, sym.get(k)) + if m is not None: + merged_sym[k] = m + # Join desc_src by union so any path on which a slot comes from an s_load sees all its uses. + merged_dsrc = dict(entry_dsrc[s]) + for k, v in dsrc.items(): + merged_dsrc[k] = merged_dsrc[k] | v if k in merged_dsrc else v + if merged_sym != entry_sym[s] or merged_dsrc != entry_dsrc[s]: + entry_sym[s] = merged_sym + entry_dsrc[s] = merged_dsrc + work.append(s) + + # Collect per-block PSB writes/origins, classify s_load uses, and record every scalar load at its exact point. + write_origins = set() + block_writes_list = [[] for _ in range(nb)] # per block: [(idx, origin_or_None), ...] + used_as_desc, used_as_data = set(), set() + used_as_sload_base = {} # parent s_load id -> set of child s_load ids + scalar_loads = [] # (ins, b, idx, is_desc_ptr, origin) + for b in range(nb): + if entry_sym[b] is None: + continue + sym = dict(entry_sym[b]) + dsrc = dict(entry_dsrc[b]) + for idx, ins in enumerate(blocks[b]): + op = base_op(ins["op"]) + if op == "s_endpgm": + break + _classify_scalar_uses(ins, sym, dsrc, used_as_desc, used_as_data, used_as_sload_base) + if op.startswith(_PSB_WRITE_PREFIXES): + wo = _psb_write_origin(ins, sym) + write_origins.add(wo) + block_writes_list[b].append((idx, wo)) + elif op.startswith(("s_load_dword", "s_buffer_load_dword")) and len(ins["args"]) >= 2: + base = _scalar_operand_slots(ins["args"][1]) + origin = _symbolic_origin(sym.get(base[0])) if base else None + hi_tag = sym.get(base[1]) if (base and len(base) == 2) else None + origin_root = _root_origin(origin) + hi_root = _root_origin(hi_tag) + is_desc_ptr = ( + op.startswith("s_load_dword") and base is not None and len(base) == 2 + and origin_root is not None and origin_root[0] in ("in", "load", "load_dyn") + and hi_root is not None and hi_root[0] in ("const", "in", "load", "load_dyn") + ) + scalar_loads.append((ins, b, idx, is_desc_ptr, origin)) + _step_scalar_provenance(sym, ins, dsrc) + + # Forward CFG store-reachability: whether any PSB write can precede entry to block b (including loop back-edges). + block_writes = [bool(block_writes_list[b]) for b in range(nb)] + write_in = [False] * nb + write_out = list(block_writes) + changed = True + while changed: + changed = False + for b in range(nb): + if write_out[b]: + for s in succ[b]: + if not write_in[s]: + write_in[s] = True + if not write_out[s]: + write_out[s] = True + changed = True + + # Backward CFG reachability: whether any PSB write (and which write origins, including None) can follow block b. + write_after_out = [False] * nb + write_after_in = list(block_writes) + write_after_out_origins = [set() for _ in range(nb)] + write_after_in_origins = [{wo for _, wo in block_writes_list[b]} for b in range(nb)] + changed = True + while changed: + changed = False + for b in range(nb): + if any(write_after_in[s] for s in succ[b]): + if not write_after_out[b]: + write_after_out[b] = True + if not write_after_in[b]: + write_after_in[b] = True + changed = True + for s in succ[b]: + if write_after_in_origins[s]: + before_o = len(write_after_out_origins[b]) + write_after_out_origins[b].update(write_after_in_origins[s]) + if len(write_after_out_origins[b]) != before_o: + write_after_in_origins[b].update(write_after_out_origins[b]) + changed = True + + # Least fixed point for multi-level descriptor-only s_load_dword* instructions. + known_write_origins = {wo for wo in write_origins if wo is not None} + desc_cand = set() + for ins, b, idx, is_desc_ptr, origin in scalar_loads: + lid = id(ins) + if (is_desc_ptr + and not _origin_chain_aliases_known(origin, known_write_origins) + and lid not in used_as_data + and (lid in used_as_desc or lid in used_as_sload_base)): + desc_cand.add(lid) + desc_only_ro = set() + changed = True + while changed: + changed = False + for lid in desc_cand: + if lid in desc_only_ro: + continue + children = used_as_sload_base.get(lid) + if children is None: + if lid in used_as_desc: + desc_only_ro.add(lid) + changed = True + elif children <= desc_only_ro: + desc_only_ro.add(lid) + changed = True + + ro = set() + for ins, b, idx, is_desc_ptr, origin in scalar_loads: + if origin == ("code",): + ro.add(id(ins)) + continue + if id(ins) in desc_only_ro: + ro.add(id(ins)) + continue + w_before = write_in[b] or any(w_idx < idx for w_idx, _ in block_writes_list[b]) + w_after = write_after_out[b] or any(w_idx > idx for w_idx, _ in block_writes_list[b]) + if not w_before and not w_after: + ro.add(id(ins)) + continue + if not w_before: + after_origins = write_after_out_origins[b] | {wo for w_idx, wo in block_writes_list[b] if w_idx > idx} + if origin is not None and None not in after_origins and not _origin_chain_aliases_known(origin, after_origins): + ro.add(id(ins)) + continue + if origin is not None and not _origin_chain_aliases_known(origin, write_origins): + ro.add(id(ins)) + return frozenset(ro) + + def _translate(path): global GUARD_MODULE_ID GUARD_MODULE_ID = fnv1a32(os.path.splitext(os.path.basename(path))[0]) @@ -18924,6 +21045,7 @@ def _translate(path): g.round_mode = any(i["op"] == "s_round_mode" or (i["op"].startswith("s_setreg") and "HW_REG_MODE" in i["args"][0].get("t", "")) for i in insns) + g.ftz32 = bool(FLOAT_CONTROLS and FTZ32 and not _disables_ftz32(insns)) w64_marks, code_w64, code_w32 = wave_markers(insns) # Authoritative wave size from the FSSM header flags at 0xD4 bit 5 (0x20 = wave32, 0 = wave64; # verified with 0 contradictions across all 26,503 corpus blobs). Falls back to the code-marker @@ -19207,10 +21329,18 @@ def _translate(path): g.vm_latch = stage == "ps" and exec_changes_after_vm([insns], [[]]) g.park_masks(([insns], [[]])) halves_analysis(g, [insns], [[]]) + meta_extra = {} g.build_meta = _shader_meta.collect(path, info["name"], [insns], [[]], - user_sgpr_limit=user_limit, system_sgprs=sys_sgprs) + user_sgpr_limit=user_limit, system_sgprs=sys_sgprs, extra=meta_extra) + if g.build_meta.get("literal_samplers"): + g.literal_samplers = [tuple(w) for w in g.build_meta["literal_samplers"]] + g.literal_sampler_index = {w: i for i, w in enumerate(g.literal_samplers)} + g.literal_sampler_sites = meta_extra.get("literal_sampler_sites", {}) g.fit_shared_memory() end = next((k for k, ins in enumerate(insns) if base_op(ins["op"]) == "s_endpgm"), len(insns)) + g.tsharp_from_heap = descriptor_sources.analyse([insns[:end]], [[]], user_limit, sys_sgprs) + g.scalar_load_ro = analyse_scalar_load_ro([insns[:end]], [[]], user_limit, sys_sgprs) + g.float_only_images = float_only_image_ops([insns[:end]], [[]]) g.exec_changes = any(g.may_write_exec(ins) for ins in insns[:end]) g.insns(insns[:end]) _translate.last_gen = g @@ -19277,10 +21407,18 @@ def target(ins): g.vm_latch = stage == "ps" and exec_changes_after_vm(blocks, succ) g.park_masks((blocks, succ)) halves_analysis(g, blocks, succ) + meta_extra = {} g.build_meta = _shader_meta.collect(path, info["name"], blocks, succ, - user_sgpr_limit=user_limit, system_sgprs=sys_sgprs) + user_sgpr_limit=user_limit, system_sgprs=sys_sgprs, extra=meta_extra) + if g.build_meta.get("literal_samplers"): + g.literal_samplers = [tuple(w) for w in g.build_meta["literal_samplers"]] + g.literal_sampler_index = {w: i for i, w in enumerate(g.literal_samplers)} + g.literal_sampler_sites = meta_extra.get("literal_sampler_sites", {}) g.bar_rounds = needs_barrier_rounds(g, blocks, succ) + g.tsharp_from_heap = descriptor_sources.analyse(blocks, succ, user_limit, sys_sgprs) + g.scalar_load_ro = analyse_scalar_load_ro(blocks, succ, user_limit, sys_sgprs) + g.float_only_images = float_only_image_ops(blocks, succ) folds, fold_chain, absorbed = {}, {}, set() if g.emulate: g.scc_live = wave64_emulate_opt.scc_live_outs(blocks, succ) @@ -20080,7 +22218,9 @@ def shader_meta(g, asm, src_path=None, fssm_path=None): "MinLod": "shaderResourceMinLod", "Image1D": "shaderImage1D? (core)", "Sampled1D": "core", "ClipDistance": "shaderClipDistance", "CullDistance": "shaderCullDistance", "ShaderLayer": "shaderOutputLayer", "ShaderViewportIndex": "shaderOutputViewportIndex", - "DrawParameters": "shaderDrawParameters", + "DrawParameters": "shaderDrawParameters", "DotProductKHR": "shaderIntegerDotProduct", + "VulkanMemoryModel": "vulkanMemoryModel", + "VulkanMemoryModelDeviceScope": "vulkanMemoryModelDeviceScope", } # FMAKHR: shaderFmaFloat32 / shaderFmaFloat64 (VK_KHR_shader_fma) by the width used, below m = {"stage": g.stage, "wave64": bool(g.wave64), "control_flow": getattr(g, "control_flow", "straight line"), # How fused multiply-adds were emitted. --fma khr is already implied by the FMAKHR capability, @@ -20108,6 +22248,13 @@ def shader_meta(g, asm, src_path=None, fssm_path=None): # The module reads the kind word from every table entry it hits: the runtime must fill it # (runtime/src/descriptor_table.h, docs/design.md "Images and samplers (T# dimension)"). m["descriptor_table"] = g.descriptor_table + # Every module of this translator reads a T#'s bindless index from its dword 6 where the word carries one, so the + # runtime must write that word into the heaps it keeps (docs/design.md, "Bindless index in the T#"). The counts + # say how many image instructions take it alone and how many still look the T# up in the hash table too. + m["tsharp_index"] = TSHARP_INDEX + if g.tsharp_index_reads or g.tsharp_lookups: + m["tsharp_index_reads"] = g.tsharp_index_reads + m["tsharp_lookups"] = g.tsharp_lookups if g.w64g: # SHADER-10: partition invariance on 32-wide subgroups. A and B are exact there (B: aggregated atomics up to # the order of the slots), C is not; the reasons name the construct (docs/design.md, Wave64 graphics). @@ -20133,6 +22280,8 @@ def shader_meta(g, asm, src_path=None, fssm_path=None): m["float_controls"] = [f"shaderSignedZeroInfNanPreserveFloat{w}" for w in widths] if "DenormPreserve" in caps: m["float_controls"].append("shaderDenormPreserveFloat16") + if "DenormFlushToZero" in caps: + m["float_controls"].append("shaderDenormFlushToZeroFloat32") if g.uses_codebase: m["uses_code_base"] = True if g.cs: @@ -20224,8 +22373,14 @@ def shader_meta(g, asm, src_path=None, fssm_path=None): m["f16_halves"] = {str(n): [lo, hi] for n, (lo, hi) in sorted(pairs.items())} if "mesh_compute" in m: # tools/mesh_compute_vs.py exports them from the slot's raw params m["mesh_compute"] = dict(m["mesh_compute"], f16_halves=m["f16_halves"]) + if getattr(g, "reads_glc_buffer", False): + m["reads_glc_buffer"] = True if g.build_meta: m.update(g.build_meta) + m.setdefault("writes_buffer", False) + m.setdefault("buffer_write_slots", []) + if getattr(g, "uses_lit_sampler_spec", False) and m.get("literal_samplers"): + m["literal_sampler_spec_base"] = 0 return m @@ -20526,9 +22681,12 @@ def main(): ap.add_argument("--dispatch-loop", action="store_true", help="emit control flow the old way, as one loop around a switch (to compare with the default)") ap.add_argument("--no-float-controls", action="store_true", - help="don't declare SignedZeroInfNanPreserve or DenormPreserve (for a driver whose " - "shaderSignedZeroInfNanPreserveFloat32 or shaderDenormPreserveFloat16 is false); NaN, inf, " - "-0 and f16 denormals are then not guaranteed") + help="don't declare SignedZeroInfNanPreserve, DenormPreserve or DenormFlushToZero (for a driver " + "whose float-control properties are false); NaN, inf, -0 and f16/f32 denormals are then not " + "guaranteed") + ap.add_argument("--no-ftz32", action="store_true", + help="don't declare DenormFlushToZero 32; keep software f32 denormal flushes instead (for a driver " + "whose shaderDenormFlushToZeroFloat32 is false, e.g. llvmpipe)") ap.add_argument("--wave64-emulate", action="store_true", help="wave64 compute and mesh shaders exact on any subgroup size (32-wide NVIDIA, Intel): " "cross-lane operations go through workgroup memory instead of subgroup operations") @@ -20536,6 +22694,9 @@ def main(): help="wave64 vertex, pixel and geometry shaders that are not exact on 32-wide subgroups (tier C of " "tools/wave64_halves.py): warn = count them in the summary and mark them in the index, " "error = refuse them (Unsupported), off = skip the analysis") + ap.add_argument("--integer-dot-fallback", action="store_true", + help="4x8-bit dot products (v_dot4_*) as extracts, multiplies and adds instead of " + "SPV_KHR_integer_dot_product, for devices without shaderIntegerDotProduct") ap.add_argument("--bary-fallback", action="store_true", help="pixel shaders that read raw barycentrics take them from an ordinary interpolated input " "(metadata: bary_fallback_input) instead of BaryCoordKHR, for devices without " @@ -20616,6 +22777,7 @@ def main(): DESCRIPTOR_TABLE = a.descriptor_table LOOP_LIMIT = a.loop_limit MAX_STRUCTURED_DEPTH = a.max_structured_depth + global INTEGER_DOT_FALLBACK global STRUCTURED, WAVE64_EMULATE, WAVE64_GRAPHICS, BARY_FALLBACK, TEXEL_OFFSET_FALLBACK, MESH_COMPUTE, FMA_KHR, SHADER_CLOCK, F16_HALVES, OPT_SPIRV global MESH_SERIAL_WAVES global PC_TAIL_UBO, ADDRESS_GUARD @@ -20626,11 +22788,13 @@ def main(): SHADER_CLOCK = a.shader_clock == "khr" FMA_EXACT = a.fma == "exact" STRUCTURED = not a.dispatch_loop - global FLOAT_CONTROLS + global FLOAT_CONTROLS, FTZ32 FLOAT_CONTROLS = not a.no_float_controls + FTZ32 = not a.no_ftz32 WAVE64_EMULATE = a.wave64_emulate WAVE64_GRAPHICS = a.wave64_graphics BARY_FALLBACK = a.bary_fallback + INTEGER_DOT_FALLBACK = a.integer_dot_fallback TEXEL_OFFSET_FALLBACK = a.texel_offset_fallback MESH_COMPUTE = a.mesh_compute MESH_SERIAL_WAVES = a.mesh_serial_waves diff --git a/tools/shader_diff.py b/tools/shader_diff.py index 1e3ab96df8..035e7a80e6 100644 --- a/tools/shader_diff.py +++ b/tools/shader_diff.py @@ -244,13 +244,18 @@ def run_one(name, lines, writers): _write_listing(spv_path, lines, with_export=True) with open(os.path.join(tmp, name + ".dxbc"), "wb") as f: f.write(STUB_DXBC) + prev_ftz32 = rdna2spirv.FTZ32 try: + # cpu_ref models IEEE binary32 with denormals preserved (tools/cpu_ref.py). + rdna2spirv.FTZ32 = False with warnings.catch_warnings(): warnings.simplefilter("ignore", ResourceWarning) spvasm = rdna2spirv.translate(spv_path) gc.collect() except rdna2spirv.Unsupported as e: return ("skip", f"translator unsupported: {e}") + finally: + rdna2spirv.FTZ32 = prev_ftz32 try: out = run_fragment(spvasm) except UnsupportedConstruct as e: diff --git a/tools/shader_meta.py b/tools/shader_meta.py index e08b16bb6e..2744b31d00 100644 --- a/tools/shader_meta.py +++ b/tools/shader_meta.py @@ -37,6 +37,15 @@ # Image instructions whose fourth operand a[3] is a 4-dword sampler descriptor (S#). SAMPLER_IMAGE_OPS = ("image_sample", "image_gather4", "image_get_lod") +# Buffer/BDA/global/flat store and atomic ops that mutate GPU buffer memory (not image_store/image_atomic/ds_write). +BUFFER_WRITE_PREFIXES = ( + "buffer_store", "tbuffer_store", "buffer_atomic", + "global_store", "global_atomic", + "flat_store", "flat_atomic", + "s_store_", "s_buffer_store_", + "s_atomic", "s_buffer_atomic", +) + # Scalar shift-add instructions: s_lshlK_add_u32 sD, sIdx, sBase -> sD = (sIdx << K) + sBase. LSHL_ADD_SHIFT = { "s_lshl1_add_u32": 1, @@ -226,6 +235,54 @@ def _valid_stride(n): return isinstance(n, int) and 4 <= n <= 4096 and n % 4 == 0 +def _trace_vsharp_write_slot(sym, a_op): + """Return integer root/table descriptor slot offset if V# operand `a_op` is statically traceable, else None.""" + slots = _sgpr_slots(a_op, 4) + if slots is None: + return None + tags = [_slot_tag(sym, s) for s in slots] + if all(t is not None and t[0] == "user" for t in tags): + u0 = tags[0][1] + if all(tags[i][1] == u0 + i for i in range(4)): + return u0 + if all(t is not None and t[0] == "table_desc" for t in tags): + base_u, off0 = tags[0][1], tags[0][2] + if all(tags[i][1] == base_u and tags[i][2] == off0 + 4 * i for i in range(4)): + return off0 + return None + + +def _trace_ptr_write_slot(sym, a_op): + """Return integer root SGPR offset if a 64-bit BDA pointer operand is a direct user SGPR pair, else None.""" + slots = _sgpr_slots(a_op, 2) + if slots is None: + return None + t0, t1 = _slot_tag(sym, slots[0]), _slot_tag(sym, slots[1]) + if t0 is not None and t0[0] == "user" and ((t1 is not None and t1[0] == "user") or t1 == ("const", 0)): + return t0[1] + return None + + +def _sload_const_offset(sym, ins): + """Constant byte offset of an s_load_dword* instruction, or None if dynamic.""" + a = ins["args"] + off = 0 + for m in ins.get("mods", ()): + if m.startswith("offset:"): + try: + off += int(m.split(":", 1)[1], 0) + except ValueError: + return None + if len(a) >= 3: + c = _const_of(sym, a[2]) + if c is None or c >= 0x100000: + return None + off += c + if off < 0 or off >= 0x100000: + return None + return off & ~3 + + def _step_state(sym, scale, ptr_stride, vscale, ins, events=None): """Advance symbolic SGPR origin/constants and descriptor-stride state by one instruction.""" op = base_op(ins["op"]) @@ -233,8 +290,27 @@ def _step_state(sym, scale, ptr_stride, vscale, ins, events=None): if not a: return - # Record pointer, descriptor, stride and literal-sampler observations BEFORE writes clobber operands. + # Record pointer, descriptor, stride, buffer-write and literal-sampler observations BEFORE writes clobber operands. if events is not None: + if op.startswith(BUFFER_WRITE_PREFIXES): + events["writes_buffer"] = True + slot = None + if op.startswith(("buffer_store", "tbuffer_store", "buffer_atomic")) and len(a) >= 3: + slot = _trace_vsharp_write_slot(sym, a[2]) + elif op.startswith(("s_buffer_store_", "s_buffer_atomic")) and len(a) >= 2: + slot = _trace_vsharp_write_slot(sym, a[1]) + elif op.startswith(("s_store_", "s_atomic")) and len(a) >= 2: + slot = _trace_ptr_write_slot(sym, a[1]) + elif op.startswith("global_store") and len(a) >= 3: + slot = _trace_ptr_write_slot(sym, a[2]) + elif op.startswith("global_atomic_"): + saddr_idx = 3 if "glc" in ins.get("mods", ()) else 2 + if len(a) > saddr_idx: + slot = _trace_ptr_write_slot(sym, a[saddr_idx]) + if slot is not None: + events["buffer_write_slots"].add(slot) + else: + events["buffer_write_dynamic"] = True if op.startswith(("s_load_dword", "s_store_dword")) and len(a) >= 2: slots = _sgpr_slots(a[1], 2) if slots is not None: @@ -284,7 +360,9 @@ def _step_state(sym, scale, ptr_stride, vscale, ins, events=None): if s_slots is not None: tags = [_slot_tag(sym, s) for s in s_slots] if all(t is not None and t[0] == "const" for t in tags): - events["literal_samplers"].add(tuple(t[1] for t in tags)) + words = tuple(t[1] for t in tags) + events["literal_samplers"].add(words) + events["literal_sampler_sites"][id(ins)] = words elif all(t is not None and t[0] == "user" for t in tags): for t in tags: events["ssharp"].add(t[1]) @@ -326,7 +404,17 @@ def _step_state(sym, scale, ptr_stride, vscale, ins, events=None): new_scale = {} new_pstride = {} - if op == "s_mov_b32" and len(a) >= 2 and a[0]["k"] == "sgpr" and a[0].get("n", 1) == 1: + if op.startswith("s_load_dword") and len(a) >= 2: + ptr_slots = _sgpr_slots(a[1], 2) + if ptr_slots is not None: + t0, t1 = _slot_tag(sym, ptr_slots[0]), _slot_tag(sym, ptr_slots[1]) + if t0 is not None and t0[0] == "user" and ((t1 is not None and t1[0] == "user") or t1 == ("const", 0)): + off = _sload_const_offset(sym, ins) + if off is not None: + dst_slots = _sgpr_regs(a[0]) + for i, dr in enumerate(dst_slots): + new_sym[dr] = ("table_desc", t0[1], off + 4 * i) + elif op == "s_mov_b32" and len(a) >= 2 and a[0]["k"] == "sgpr" and a[0].get("n", 1) == 1: d = a[0]["r"] c = _const_of(sym, a[1]) if c is not None: @@ -477,7 +565,7 @@ def _step_state(sym, scale, ptr_stride, vscale, ins, events=None): ptr_stride.pop(r, None) -def analyse_instructions(blocks, succ, user_sgpr_limit=32, system_sgprs=()): +def analyse_instructions(blocks, succ, user_sgpr_limit=32, system_sgprs=(), extra=None): """Analyse reachable RDNA2 basic blocks for user-SGPR reads/kinds, descriptor strides and literal samplers. Returns a dict with: @@ -490,7 +578,8 @@ def analyse_instructions(blocks, succ, user_sgpr_limit=32, system_sgprs=()): nblk = len(blocks) if nblk == 0: return {"user_sgpr_reads": [], "descriptor_strides": [], "literal_samplers": [], - "table_loads": False, "truncates_high": False} + "table_loads": False, "truncates_high": False, + "writes_buffer": False, "buffer_write_slots": []} sys_set = frozenset(system_sgprs) user_range = {r for r in range(user_sgpr_limit) if r not in sys_set} @@ -564,8 +653,12 @@ def merge_sets(dst, src): "ssharp": set(), "strides": set(), "literal_samplers": set(), + "literal_sampler_sites": {}, "table_loads": False, "truncates_high": False, + "writes_buffer": False, + "buffer_write_slots": set(), + "buffer_write_dynamic": False, } for b in range(nblk): if entry_written[b] is None: @@ -614,12 +707,25 @@ def promote(r, kind): row["pair"] = pairs[r] user_reads.append(row) + if extra is not None: + extra["literal_sampler_sites"] = events["literal_sampler_sites"] + + writes_buffer = bool(events["writes_buffer"]) + if not writes_buffer: + write_slots = [] + elif events["buffer_write_dynamic"]: + write_slots = "dynamic" + else: + write_slots = sorted(events["buffer_write_slots"]) + return { "user_sgpr_reads": user_reads, "descriptor_strides": sorted(events["strides"]), "literal_samplers": [list(s) for s in sorted(events["literal_samplers"])], "table_loads": events["table_loads"], "truncates_high": events["truncates_high"], + "writes_buffer": writes_buffer, + "buffer_write_slots": write_slots, } @@ -714,7 +820,7 @@ def fspx_state_sha256_file(disasm_path, name): return hashlib.sha256(f.read()).hexdigest() -def collect(disasm_path, name, blocks, succ, user_sgpr_limit=32, system_sgprs=()): +def collect(disasm_path, name, blocks, succ, user_sgpr_limit=32, system_sgprs=(), extra=None): """Collect all build-time runtime metadata for one translated shader.""" meta = {} digest = fssm_sha256_file(disasm_path, name) @@ -737,13 +843,15 @@ def collect(disasm_path, name, blocks, succ, user_sgpr_limit=32, system_sgprs=() if "input_signature" in dxbc_info: meta["input_signature"] = dxbc_info["input_signature"] - ins_info = analyse_instructions(blocks, succ, user_sgpr_limit=user_sgpr_limit, system_sgprs=system_sgprs) + ins_info = analyse_instructions(blocks, succ, user_sgpr_limit=user_sgpr_limit, system_sgprs=system_sgprs, extra=extra) if ins_info["user_sgpr_reads"]: meta["user_sgpr_reads"] = ins_info["user_sgpr_reads"] if ins_info["descriptor_strides"]: meta["descriptor_strides"] = ins_info["descriptor_strides"] if ins_info["literal_samplers"]: meta["literal_samplers"] = ins_info["literal_samplers"] + meta["writes_buffer"] = ins_info["writes_buffer"] + meta["buffer_write_slots"] = ins_info["buffer_write_slots"] has_sfi0 = "sfi0_resource_heap_directly_indexed" in dxbc_info if has_sfi0 or ins_info["table_loads"] or ins_info["truncates_high"]: diff --git a/tools/vk_subgroup_info.py b/tools/vk_subgroup_info.py index ec32e87a7c..a5609984d5 100644 --- a/tools/vk_subgroup_info.py +++ b/tools/vk_subgroup_info.py @@ -47,6 +47,9 @@ 2.0.283 (31.0.22044.1, compiler 23.20.44): there ps_bary reads a wrong third BaryCoordKHR component (0.992 where 0.0039 is expected). That bound is the one place the driver version matters; newer drivers keep native barycentrics. +integer_dot_product is the Vulkan 1.3 feature shaderIntegerDotProduct (required by Vulkan 1.3, so false only on a +Vulkan 1.2 device such as MoltenVK's): where it is false, the shaders are translated with --integer-dot-fallback. + max_push_constants_size is VkPhysicalDeviceProperties.limits.maxPushConstantsSize in bytes. The default shader contract uses 144 bytes (152 with --mesh-compute); where a device reports less (e.g. 128 on AMD's Windows driver for RDNA2 iGPUs and some Intel Arc drivers), make_game.py translates with --pc-tail-ubo. @@ -116,6 +119,7 @@ F13_SUBGROUP_SIZE_CONTROL = 16 + 4 * 7 F13_SYNCHRONIZATION2 = 16 + 4 * 9 F13_DYNAMIC_RENDERING = 16 + 4 * 12 +F13_SHADER_INTEGER_DOT_PRODUCT = 16 + 4 * 13 PROPS_DEVICE_TYPE = 16 # offsets in VkPhysicalDeviceProperties PROPS_VENDOR_ID = 8 PROPS_DEVICE_ID = 12 @@ -364,6 +368,7 @@ def query(*, stage_caps=False) -> dict: int.from_bytes(raw[PROPS_MAX_PUSH_CONSTANTS_SIZE:PROPS_MAX_PUSH_CONSTANTS_SIZE + 4], "little"), int.from_bytes(raw[PROPS_VENDOR_ID:PROPS_VENDOR_ID + 4], "little"), int.from_bytes(raw[PROPS_DEVICE_ID:PROPS_DEVICE_ID + 4], "little"), u32(drv, 16), + core13 and bool(u32(f13, F13_SHADER_INTEGER_DOT_PRODUCT)), driver_version) if chosen is None: if device_filter: @@ -373,7 +378,8 @@ def query(*, stage_caps=False) -> dict: ) raise RuntimeError("no Vulkan 1.3 GPU with the features and graphics queue the runtime needs") (name, subgroup_size, supported_stages, lo, hi, required_stages, max_workgroup_subgroups, - sgc, per_vertex, max_push_constants_size, vendor, device, driver, chosen_driver_version) = chosen + sgc, per_vertex, max_push_constants_size, vendor, device, driver, integer_dot, + chosen_driver_version) = chosen if per_vertex: # The feature counts only with its extension listed (RADV sets it on gfx90c without one). # Reuse the Vulkan 1.2 extension set already fetched above, and query Vulkan 1.3 devices only once chosen. @@ -402,6 +408,7 @@ def query(*, stage_caps=False) -> dict: "per_vertex_inputs": per_vertex, "barycentric_fallback": barycentric_fallback(vendor, device, driver, chosen_driver_version), "max_push_constants_size": max_push_constants_size, + "integer_dot_product": integer_dot, "vendor_id": vendor, "device_id": device, "driver_id": driver, diff --git a/tools/wave64_halves.py b/tools/wave64_halves.py index d7b9804ae1..89fe0843a4 100644 --- a/tools/wave64_halves.py +++ b/tools/wave64_halves.py @@ -359,7 +359,8 @@ def _find_pure_spill_vgprs(self): if x.get("k") == "vgpr": movrel_min = x["r"] if movrel_min is None else min(movrel_min, x["r"]) if op == "v_writelane_b32" and len(a) == 3 and a[0].get("k") == "vgpr" and a[0].get("n", 1) == 1 \ - and a[2].get("k") == "imm" and a[1].get("k") != "vgpr": + and a[2].get("k") == "imm" and not (a[2].get("neg") or a[2].get("abs")) \ + and a[1].get("k") != "vgpr": vr = a[0]["r"] slot = lane_masks.lane_slot(a[0], a[2]) if slot and (slot in self.masks.get(id(ins), {}) or self.is_mask(ins, a[1])): @@ -367,14 +368,13 @@ def _find_pure_spill_vgprs(self): else: candidates.add(vr) continue - if op == "v_readlane_b32" and len(a) == 3 and a[1].get("k") == "vgpr" and a[1].get("n", 1) == 1 \ - and a[2].get("k") == "imm": + if op == "v_readlane_b32" and len(a) == 3 and a[0].get("k") != "vgpr" \ + and a[1].get("k") == "vgpr" and a[1].get("n", 1) == 1 \ + and a[2].get("k") == "imm" and not (a[2].get("neg") or a[2].get("abs")): vr = a[1]["r"] slot = lane_masks.lane_slot(a[1], a[2]) if slot and slot in self.masks.get(id(ins), {}): disqualified.add(vr) - else: - candidates.add(vr) continue for x in a: for r in _regs(x):