From 9f98dcc617df5b21eb66b48a289914b551769029 Mon Sep 17 00:00:00 2001 From: Moriz82 <72836413+Moriz82@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:30:51 -0600 Subject: [PATCH 01/10] Improve post-load GPU memory and pipeline handling (RT-POST-LOAD-GPU-MEMORY) Fall back to a dedicated buffer allocation when the shared arena fills. Update console descriptors and resource backing, preserve pipeline cache entries, and replay mesh records using bounded indirect arguments. Keep scripted input available until read and cover the runtime and translator paths with synthetic tests. Co-authored-by: Plaaasma <47513553+Plaaasma@users.noreply.github.com> Co-authored-by: ivanepsilondelta <264061546+ivanepsilondelta@users.noreply.github.com> --- docs/buffer_bounds.md | 5 + docs/d3d12_vulkan.md | 220 +- docs/design.md | 5 +- docs/gameinput.md | 3 +- docs/shader_library.md | 21 +- runtime/CMakeLists.txt | 82 +- runtime/shims/d3d12_com.cpp | 201 +- runtime/shims/d3d12_com.h | 18 + runtime/shims/d3d12_compile_helper.h | 443 ++ runtime/shims/d3d12_compute_input_probe.h | 16 +- runtime/shims/d3d12_geometry_views.h | 3 + runtime/shims/d3d12_pipeline_compile.h | 186 +- runtime/shims/d3d12_precompile.h | 45 + runtime/shims/d3d12_title_buffer_windows.h | 40 + runtime/shims/d3d12_title_image_upload.h | 10 +- runtime/shims/d3d12_vulkan_device.cpp | 3808 +++++++++++++++-- runtime/shims/d3d12_xs_alloc_size.h | 50 +- runtime/shims/d3d12_xs_device.cpp | 309 +- runtime/shims/d3d12_xs_list_values.h | 4 +- runtime/shims/dxgi_swapchain.h | 20 +- runtime/shims/gameinput.cpp | 176 +- runtime/shims/keyboard_pad_connection.h | 67 + runtime/shims/xg_xs.cpp | 10 + runtime/shims/xg_xs_layout.h | 34 +- runtime/shims/xmem.cpp | 23 +- runtime/shims/xmem.h | 1 + runtime/src/buffer_va_index.h | 5 + runtime/src/command_list.h | 1 + runtime/src/console_heap_fix.comp | 292 ++ runtime/src/console_heap_fix.inc | 3163 ++++++++++++++ runtime/src/console_heap_fix_spv.h | 11 + runtime/src/console_heap_gpu.h | 1058 +++++ runtime/src/descriptor_range_changes.h | 46 + runtime/src/descriptor_table.h | 81 +- runtime/src/fsdraw_probe.h | 67 +- runtime/src/indirect_clamp.comp | 10 + runtime/src/indirect_clamp_spv.h | 264 +- runtime/src/main.cpp | 76 +- runtime/src/pipeline_cache_journal.h | 356 ++ runtime/src/pipeline_wait.h | 189 + runtime/src/queue_holds.h | 7 + runtime/src/shader_library.h | 85 + runtime/src/submit_phases.h | 11 +- runtime/src/thread_sampler.h | 43 +- runtime/src/thread_stacks.cpp | 30 +- runtime/src/thread_stacks.h | 4 + runtime/src/title_page_watch.h | 25 + runtime/src/title_texture_refresh.h | 53 +- runtime/src/title_va_alias.h | 85 +- runtime/src/vulkan13_features.h | 8 +- runtime/src/vulkan_backend.h | 706 ++- runtime/src/vulkan_bindless.h | 192 +- runtime/src/vulkan_device_fault.h | 497 ++- runtime/src/vulkan_indirect_clamp.h | 32 +- runtime/src/vulkan_present.h | 92 +- runtime/src/vulkan_present_splash.h | 10 +- runtime/src/vulkan_replay.h | 408 +- runtime/test/compile_helper_test.cpp | 176 + runtime/test/d3d12_compute_journal_test.cpp | 153 + runtime/test/d3d12_compute_test.cpp | 8 + runtime/test/d3d12_indirect_rt_test.cpp | 216 +- runtime/test/d3d12_m4_compute_test.cpp | 23 +- runtime/test/d3d12_mesh_test.cpp | 68 +- runtime/test/d3d12_pipeline_wait_test.cpp | 593 +++ runtime/test/d3d12_placed_depth_test.h | 13 + runtime/test/d3d12_title_va_test.cpp | 6 +- runtime/test/d3d12_unmapped_vsharp_test.cpp | 1 - runtime/test/d3d12_vulkan_device_test.cpp | 4 +- runtime/test/descriptor_table_test.cpp | 44 + .../test/glsl/cs_indirect_dispatch_count.comp | 5 +- runtime/test/indirect_clamp_safety_test.cpp | 6 +- runtime/test/keyboard_pad_retry_test.cpp | 137 + runtime/test/pipeline_cache_journal_test.cpp | 337 ++ runtime/test/shader_library_test.cpp | 74 + runtime/test/shaders/build.py | 4 + runtime/test/submit_mutex_test.cpp | 209 + runtime/test/title_va_alias_test.cpp | 38 + runtime/test/vk_bindless_test.cpp | 306 +- runtime/test/vk_console_heap_gpu_test.cpp | 584 +++ runtime/test/vk_descriptor_bench.cpp | 3 +- runtime/test/vk_harness.cpp | 3 +- runtime/test/vk_host_texture_order_test.cpp | 36 +- runtime/test/vk_image_fuzz.cpp | 2 +- runtime/test/vk_pipeline_check.cpp | 22 +- runtime/test/vk_presenter_sparse_capture.h | 192 + runtime/test/vk_presenter_sync_test.cpp | 18 +- runtime/test/vk_sampler_test.cpp | 5 +- runtime/test/vk_sandbox.cpp | 3 +- runtime/test/vk_semaphore_lifetime_test.cpp | 261 ++ runtime/test/vk_store_test.cpp | 14 +- runtime/test/vk_test_device.h | 3 + runtime/test/vk_texture_test.cpp | 2 +- runtime/test/xg_xs_test.cpp | 83 + runtime/test/xs_proxy_mock_test.cpp | 30 + scripts/check_compute_journal_overlay.py | 106 + scripts/compute_workers_win.py | 190 + scripts/translate_pipeline_compute.py | 208 +- tests/semantic/test_buffer_offset_wrap.py | 109 + tests/semantic/test_descriptor_hash.py | 2 +- tests/semantic/test_fspx_rules.py | 2 +- tests/semantic/test_loop_ballot_barrier.py | 10 +- tests/semantic/test_loop_iteration_guard.py | 27 +- tests/semantic/test_sampled_dynamic_index.py | 14 +- tests/semantic/test_tsharp_dimension.py | 151 + tests/semantic/test_vcc_tuple_fallback.py | 2 +- .../semantic/test_wave32_pixel_subgroup64.py | 2 +- tests/semantic/test_wave64_emulate_opt.py | 13 +- tests/test_desc_cache.py | 36 +- tests/test_indirect_clamp_telemetry.py | 56 + tests/test_translate_pipeline_compute.py | 143 +- tools/rdna2spirv.py | 292 +- 111 files changed, 17765 insertions(+), 987 deletions(-) create mode 100644 runtime/shims/d3d12_compile_helper.h create mode 100644 runtime/shims/d3d12_precompile.h create mode 100644 runtime/shims/keyboard_pad_connection.h create mode 100644 runtime/src/console_heap_fix.comp create mode 100644 runtime/src/console_heap_fix.inc create mode 100644 runtime/src/console_heap_fix_spv.h create mode 100644 runtime/src/console_heap_gpu.h create mode 100644 runtime/src/descriptor_range_changes.h create mode 100644 runtime/src/pipeline_cache_journal.h create mode 100644 runtime/src/pipeline_wait.h create mode 100644 runtime/test/compile_helper_test.cpp create mode 100644 runtime/test/d3d12_compute_journal_test.cpp create mode 100644 runtime/test/d3d12_pipeline_wait_test.cpp create mode 100644 runtime/test/keyboard_pad_retry_test.cpp create mode 100644 runtime/test/pipeline_cache_journal_test.cpp create mode 100644 runtime/test/submit_mutex_test.cpp create mode 100644 runtime/test/vk_console_heap_gpu_test.cpp create mode 100644 runtime/test/vk_presenter_sparse_capture.h create mode 100644 runtime/test/vk_semaphore_lifetime_test.cpp create mode 100644 scripts/check_compute_journal_overlay.py create mode 100644 scripts/compute_workers_win.py create mode 100644 tests/semantic/test_buffer_offset_wrap.py create mode 100644 tests/semantic/test_tsharp_dimension.py create mode 100644 tests/test_indirect_clamp_telemetry.py diff --git a/docs/buffer_bounds.md b/docs/buffer_bounds.md index f5b4e6a55a..a2d566bc1f 100644 --- a/docs/buffer_bounds.md +++ b/docs/buffer_bounds.md @@ -23,6 +23,11 @@ API-created CBVs mirror the observed inline console descriptor (mode 0, 16-byte - **RDNA2 follows Mesa's GFX11 column**, not the GFX10 one: of 732 cases, 729 match GFX11 and 696 match GFX10. Every GFX10 miss is an access that only partly fits, for example a raw buffer with `N = 3` read at offset 0. +- **The offset is not cut to 32 bits.** `index * stride` is a full product and `soffset` is added in 64 bits, so + index 0xFFFFFFFF with a 20-byte stride lands tens of GiB past the base and the access has no effect; in 32 bits it + would be the 20 bytes below the base, which modes 2 and 3 do not refuse. The translator treats an offset above + 0xFFFFFFFF as out of range in every mode. Observed on hardware by five-star-recomp (commit `b9b57e2`), not measured + here; `tests/semantic/test_buffer_offset_wrap.py`. - **In raw mode `soffset` is part of the checked offset.** The 3 cases that match neither column are raw reads at offset 8 with `soffset` 8 and `N = 18`: 8 + 8 + 4 > 18, out of range on hardware. - Loads and stores agree in every case. diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 6df6657bdf..ec39977c66 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -1283,11 +1283,18 @@ and any validation error fails them. `d3d12_stateful_indirect_counted_pixels`: positive D3D12-to-Vulkan graphics tests. Compare every readback pixel with both a direct-draw reference and a known pattern for each draw kind; the counted variant fills its argument and count buffers by GPU copy before use. -- `d3d12_indirect_rt_test`: a native Vulkan counted-draw reference (count 0 leaves the clear colour, - count 1 renders), a D3D12 command-signature creation check, and optional +- `d3d12_indirect_rt_test`: validates `ID3D12Device::CreateCommandSignature` + `ExecuteIndirect` with a GPU + `CountBuffer` (`vkCmdDrawIndirectCount`, `count = 0` skipped and `count = 1` rendered), a draw whose record asks + for four billion instances (clamped on the GPU, section 4.7), and a native Vulkan counted-draw reference over the + same suballocated argument/count offsets (`count = 0` leaves the clear colour, `count = 1` renders; it is + independent of the D3D12 command replay); optional `VK_KHR_acceleration_structure` + `VK_KHR_ray_query` (`GetRaytracingAccelerationStructurePrebuildInfo`, BLAS + TLAS `BuildRaytracingAccelerationStructure`, and a `RayQueryKHR` compute shader verifying hit vs. miss; clean SKIP on GPUs without RT). +- `indirect_clamp_test`: the `ExecuteIndirect` argument clamp pass itself (section 4.7), with no game files: every + argument kind (draw, draw indexed, dispatch, mesh dispatch) and the counted variants, in-range records + bit-identical, garbage records bounded, records and counts past `max_command_count` empty, and the per-batch work + budget saturating; clean SKIP without a Vulkan device. - `d3d12_gcl8_test`: the public `ID3D12GraphicsCommandList8` surface: `QueryInterface` for its IID, `OMSetFrontAndBackStencilRef(1, 2)` with the recorded values, and the reference count around the query. It creates only an allocator and a list, so it needs no GPU or Vulkan loader. @@ -2391,13 +2398,104 @@ Pipeline creation: has no active builds. These snapshots have an additional 512 MiB ceiling. The driver fills a mapped staging file directly. A successful snapshot atomically replaces the session. An interrupted write preserves the previous cache; the next launch removes unheld staging files older than ten minutes. + While the compute warm-up has builds queued that idle checkpoint never starts, and a boot that ends by a crash, + a device loss or a kill never reaches teardown, so neither file used to keep that boot's compute pipelines. + Compute pipelines are therefore journaled one file each (`src/pipeline_cache_journal.h`): + `pipeline_cache.d/cs-.bin` beside the session file, named by a hash of the SPIR-V words, the stage flags and + subgroup request, the push-constant range and the bindless layout. A build creates a `VkPipelineCache` from its + file (if the header names this device and pipeline-cache UUID) and creates the pipeline against it; when the + driver reports a compile (creation feedback without `APPLICATION_PIPELINE_CACHE_HIT`, or no file), that cache is + written back to the file at once, through a staging file renamed over it. Without a file, and with + `pipelineCreationCacheControl`, the shared cache is first asked with + `VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT` when it was seeded from a file, so the offline seed + still serves a first boot. NVIDIA 630.20 answers that flag with a compiled pipeline (seconds) instead of + `VK_PIPELINE_COMPILE_REQUIRED`, so the first answer that took 250 ms or more without the cache-hit bit stops the + asking, and that pipeline is built again against its journal cache so it gets a file (a fast answer without the + bit is the driver's own disk cache, and a valid one; `LEONIDA_PIPELINE_JOURNAL_ASK_SHARED=0`: never ask). All + driver calls of a compute build (shader module, journal cache, pipeline) run in one turn of the compile gate, with + no file I/O in it: from the journal a build takes milliseconds, the warm-up worker makes them back to back, and + three warm boots whose cache and module calls were outside the gate lost the device in a `vkQueueSubmit` 20-25 s + in (no GPU fault, no TDR). The files take 2-3 MiB a pipeline on that driver (about 3.6 GiB for the 1700 a boot + builds); `LEONIDA_PIPELINE_JOURNAL_BYTES` (32 GiB by default) caps them. At a device's first pipeline, staging files + older than ten minutes are removed and, past the budget, the least recently used files until three quarters of it + is left: a file's modification time is its last use (written, or touched, at most hourly, when a build finds its + pipeline there), so files no build names any more after a translator regeneration go first. + Measured on an RTX 4070 Ti (driver 630.20): 17 compute modules of 0.6-0.7 MB SPIR-V took 222 s to compile and + 0.04 s to create from their cache; a boot's ~1000 warm-up builds of 128 KiB or more took 81 s cold and 1.8 s from + the journal, and the submissions' compile-gate waits went from 77 s to none. Nsight Aftermath crash dumps + (`LEONIDA_AFTERMATH=1`) appear to make the driver compile again whatever the caches hold: boots loading the same + 317 MB session file logged no compute build of 2 s or more without Aftermath and 88-95 with it. The + VK_NV_device_diagnostics_config flags alone do not (vk_pipeline_check `--nv-diagnostics`: 17 of 17 cache hits). + `LEONIDA_PIPELINE_JOURNAL=0` (or `LEONIDA_PIPELINE_CACHE_BYTES=0`) turns the journal off. + `LEONIDA_PIPELINE_CACHE_DIR=` moves the journal with the other files, so builds of gta6rt in several + folders can share one; the file names and the driver's checks keep a pipeline from one build from being taken + for another's. + `gta6rt --precompile-pipelines [--threads N] [--big-threads N] [--all] [--smallest-first] [--limit N] + [--min-bytes N] [--max-bytes N] [--filter PART]... [--list]` fills the journal ahead of play, with no game: it + creates the Vulkan device as `--run` does (so the same environment gives the same journal names and driver keys: + LEONIDA_SHADERS, LEONIDA_PIPELINE_CACHE_DIR, and LEONIDA_DEVICE_FAULT/LEONIDA_AFTERMATH, whose diagnostics config + makes other pipelines) and builds every compute entry of the library through the dispatch path + (`build_compute_pipeline`), largest first, on below-normal-priority threads. Entries with a usable journal file are + skipped (only their header is read), so it can be stopped and started again. Running as gta6rt.exe it also fills + NVIDIA's disk cache, which that driver keys by the executable's name. Measured on an RTX 4070 Ti (driver 630.20), + 4 threads: modules of 3.6-5.8 MB took 46-145 s each, 12 in 312 s, about 3.5 GB of host memory each while in the + driver (14.5 GB peak for four). Graphics pipelines are not covered: they are built at a title's draw from its PSO + description and the bound formats, and take milliseconds. + `LEONIDA_COMPILE_HELPER=1` (`shims/d3d12_compile_helper.h`) keeps first-ever compiles out of the title's process: + the driver's locks, which a long `vkCreateComputePipelines` holds and a `vkQueueSubmit` of the same process waits + for, are per process. A compute build of `LEONIDA_COMPILE_HELPER_MIN_BYTES` or more (128 KiB) with no journal file + writes a request beside the journal (`requests/.req`: the entry and a priority, 0 for a use, the module size + for a warm-up) and starts the helper at the first one (`gta6rt --compile-server --parent `, the same executable + and environment, so the same device and journal names). With asynchronous builds (`LEONIDA_ASYNC_PIPELINES=1`, the + intended mode) nothing waits: the build answers deferred, the variant goes back to idle, the dispatch is skipped and + counted, and each later use looks at the request (a file check, the module is not read again) until the journal + file is there and the pipeline is created from it, a cache hit. A warm-up only asks, in either mode, so the warm-up + worker writes its requests ahead and the helper's threads (`LEONIDA_COMPILE_HELPER_THREADS`, 2) build them in + parallel, the most urgent first; a warm-up the helper builds is never held back while the title submits. Without + asynchronous builds a dispatch waits for its file, holding nothing of the driver's (`LEONIDA_COMPILE_HELPER_WAIT_MS`, + default 120 s, 0 for no limit). A failure (`requests/.failed`, the helper gone) builds the pipeline here as + before, and so does a request that is no longer listed (`.req` gone with no answer) or one still pending after + `LEONIDA_COMPILE_HELPER_PENDING_MS` (default 120 s): the helper cannot hold a dispatch forever. The helper + checks that its journal name is the one asked for before it compiles (the name is a hash of the module and the + device, no driver call), ends with the process that started it, runs alone per journal, + and with nothing asked fills the rest of the library, smallest module first, on + `LEONIDA_COMPILE_HELPER_IDLE_THREADS` (1, always one fewer than its threads) at idle priority; the journal names it + worked out are kept in `requests/names.idx` (with each module's size and time and what the names depend on), so a + later helper does not read every module again. `requests/.building` is a lock file a process holds for the + whole build (no sharing, deleted by the OS when that process ends, killed or not), whose contents name the process: + the helper and `--precompile-pipelines` leave an entry its holder is building to it, and a file no process holds is + stale whatever process id it names. Measured, RTX 4070 Ti, + driver 630.20, a boot with an empty journal and the helper waiting (no asynchronous builds): the helper compiled 171 + pipelines of 128 KiB or more (148 s in its driver), every one of them was a hit in the title's process (at most + 2 ms), and no submission waited at the compile gate. + Under Proton, pass a Wine path, for example + `LEONIDA_PIPELINE_CACHE_DIR='Z:\opt\leonida\cache'`. Async warm-up workers publish to the same directory. + For a disposable session, `LEONIDA_PIPELINE_JOURNAL_SEED_DIR=` can name a separate, + trusted read-only set of per-key compute journal files. The runtime prefers a compatible writable entry, then tries + the same key in the seed; both use the existing size and device/driver header checks. A seed hit neither copies an + entry nor refreshes its mtime. All writes, LRU touches, staging cleanup, eviction and byte accounting belong to the + writable journal only, including replacement of an incompatible local file. The seed must be distinct from the + writable `pipeline_cache.d`, not its ancestor or descendant; an explicitly unusable or overlapping root disables + the journal. This setting does not grant access or authenticate cache data. Use only trusted, privately produced + files on a read-only mount/ACL with stable, disjoint directories and no linked files between them. Leave unset for + the original single-directory behavior. Per-key names are unchanged: externally precompiled files for the same + pipeline identity can be read without a persistent *writable* shared journal. + During normal runtime, a compatible local or external entry is used before requesting the helper. + The offline precompiler and compile-server instead read and populate only the writable journal, even + when a separate seed is configured. An external hit is not a published response to a helper request; + its readiness check still requires a compatible file at the requested writable path. Both modes validate + the configured directory pair before enabling journaling. + To check the two tiers without game files, build `d3d12_compute_journal_test`, then run + `python scripts/check_compute_journal_overlay.py --require-hit`. + This uses four fresh processes, two authored compute shaders and a disposable cache. It checks dispatch results, + reported application-cache hits (where supported), local publications, and that old seed contents/mtime stay put. `LEONIDA_TRACE_PIPELINE_COMPILE=1` records each graphics and compute build's trigger, thread, elapsed time, SPIR-V size, shader names and Vulkan application-cache feedback (1 hit, 0 miss, -1 unavailable). It also times cache reads, merges, writes and draw/dispatch pipeline lookups that take at least 1 ms. - `LEONIDA_ASYNC_PIPELINES=1` schedules cold first-use builds on the warm-up worker ahead of speculative work. - Replay skips a draw or dispatch while its pipeline is pending. Later uses find the completed handle. - A skipped dispatch can lose a one-time resource update. Synchronous first use is the default and strict - replay always uses it. `LEONIDA_COMPUTE_WARMUP=0` restricts the worker to pipelines requested by the title. + `LEONIDA_ASYNC_PIPELINES=1` schedules cold first-use builds on the warm-up worker ahead of speculative work; how long + a submission waits for them, and what is skipped, is "Pipelines still being built" below. Strict replay builds + synchronously and waits for every build. `LEONIDA_COMPUTE_WARMUP=0` restricts the worker to pipelines requested by + the title. A queued build holds no reference to its PSO or device (`PipelineCompiler`, `runtime/shims/d3d12_pipeline_compile.h`). A PSO's last release drops its queued builds and returns at once; one already running is left to finish, and the worker deletes the PSO after it (`PipelineState::last_release`). The PSO's device reference goes at the release, so @@ -2450,6 +2548,74 @@ Pipeline creation: cache per thread, merged, was about as fast. Tested by `pipeline_workers`, `replay_pipeline_compiles` and `d3d12_pipeline_workers`. +**Pipelines still being built** (`runtime/src/pipeline_wait.h`, `PipelineState::replay_await` / `replay_get` in +`runtime/shims/d3d12_vulkan_device.cpp`). Lazy pipelines are built at first use, and on the 4070 Ti (NVIDIA 630.20) +a large compute pipeline takes the driver 3-10 s, some 37 s. Replay used to build or wait for them inside +`VulkanQueue::execute_now`'s prepare, holding `resource_mutex_` shared across the wait. A minidump of a native boot +just past the story load showed the cost: the submitting thread waited 9.5 s for a compute pipeline the warm-up +thread was building, a title thread creating a texture queued for the exclusive lock behind it, and every +submission behind that; per-submission replay time went 0.5 s, 2.8 s, 6 s, then submissions stopped. + +- **The pre-pass.** `VulkanQueue::execute` first collects, under a short shared `resource_mutex_` (only registry + lookups and a probe of each PSO's state), the pipelines the lists' `Dispatch`, `ExecuteIndirect` (dispatch) and + `Draw` commands need that are not built: each compute PSO once, each graphics PSO once per variant (the mask of + formatted slots the draw leaves unbound, `unbound_slots`, the same mask `prepare_draw` builds with). With the lock + released it asks for each of them, then waits for the ones still being built. No lock of the replay layer is held + while it waits; the PSOs stay alive because the lists hold them. Its time is the `pipes` column of the + `[rt] submit phases` line. +- **Budget.** `LEONIDA_PIPELINE_WAIT_MS` caps one submission's waiting, in all; 0 never waits, -1 waits for every + build (the old behaviour, without the lock). Unset, it is 24 with `LEONIDA_ASYNC_PIPELINES=1` and -1 without, so + the default mode never skips. The budget bounds waits for builds other threads run; a build the submitting thread + runs itself (synchronous mode) takes as long as it takes. `LEONIDA_PIPELINE_WAIT_FRAME_MS` (default 100, -1 off) caps + all submitting threads together between two presents (or per second without presents): a frame of many submissions + does not wait the per-submission budget each time. +- **Skip.** Prepare (`ComputePipeline::build`, `GraphicsPipeline::variant`) never waits for a build another thread + runs: a pipeline still in flight answers null, and the draw or dispatch is dropped as an unresolvable one is (a draw + emits nothing, not even its rendering scope; a dispatch, direct or indirect, binds and dispatches nothing). The + list's barriers, copies, clears, queries and descriptor binding all replay as recorded, so GPU state stays + consistent; what the skipped work would have written keeps its old contents. The build goes on, and a later + submission uses it. A skipped dispatch can lose a one-time update; a title whose progress waits on one keeps + waiting until the pipeline exists (then it runs), so a longer budget trades seconds of stall for fewer skips. +- **Who builds.** Each PSO variant has one state (idle, queued, running, done) under one mutex that no driver call + holds, and exactly one thread claims each build: a worker job that finds its variant claimed returns at once, so + nothing waits on a PSO's `variants_mutex_` behind a build. With `LEONIDA_ASYNC_PIPELINES=1` replay queues builds on + the compile worker at replay's priority (ahead of warm-ups), and does so at record time already: at + `SetPipelineState` for compute and at each draw for graphics, with the variant its bound targets give + (`request_pipeline_build`). Without it, the submitting thread builds a pipeline nobody has started in the pre-pass + (no lock held), and waits for one a warm-up is building (at most the budget, if one is set). After an exit stop + builds run in place; an unlimited wait looks again every 100 ms, so a queued job the stop dropped cannot leave it + waiting. A pipeline that cannot be built is not waited for again; its draws and dispatches are dropped (logged when + the build fails) where the list used to fail as a whole in synchronous mode; strict replay still fails it. + Builds keep the compile gate (`DriverTurn`, `SubmitMutex::CompileTurn`): a submission still waits at the gate for a + create already in the driver. +- **Warm-ups while the title submits.** That gate wait is what a long build costs the title, whoever asked for it: a + native boot's submissions waited 140 s in all at the gate behind compute warm-ups, and past the story load the + worker went through 694 warm-ups of modules over 128 KiB (those over 640 KiB take 4-25 s each) against 25 such + builds a dispatch asked for. So a warm-up of a module over `LEONIDA_COMPUTE_WARMUP_LIVE_MAX_BYTES` of SPIR-V + (default 128 KiB; 0: no limit) is not started while the title submits (a submission in the last second); the + pipeline is built at its first use instead. Smaller warm-ups, and every warm-up before the first submission, run + as before. +- **Log.** Every 10 s while anything happened: `[rt] pipeline waits t=..s: in 10.0 s N pipelines waited for (T ms in + all, L not built in time), D draws and C dispatches skipped, B pipelines still building; budget ...`. The first 32 + skipped pipelines are named once each (`[rt] pipeline-wait: ... skipped while it is being built`). +- **Measured** (native boots of the story load, RTX 4070 Ti, NVIDIA 630.20, `LEONIDA_RT_AS=off`). Before: within + 30 s of the loading screen ending the replay phase went from under 10 ms to 265 ms (max 26 s), 2.8 s and 6 s per + submission, and submissions stopped. With asynchronous builds: submissions kept 20-30/s (replay 4-6 ms) through the + end of the loading screen; in the 17 s after it 744 dispatches and 42 draws were skipped and 8 pipelines waited + for (172 ms in all). Three builds that missed the pipeline cache then took 4-10.5 s each, and the submissions + behind them waited at the compile gate (145 waits, 30 s in all, longest 10.5 s): the gate wait, not replay, is now + what a cold build costs. That boot then lost the device to a GPU hang in a compute dispatch (fault addresses of the + instruction-pointer kind, no invalid access); whether dispatches skipped before it fed it is open. Synchronous: + 34-40 submissions/s at 7-8 ms replay up to the end of the loading screen; past it, the boots ended in a title + crash seen in many boots without this change (a memset into reserved, uncommitted memory) or the early device + loss at 25-37 s (`vkQueueSubmit` 10 s in the driver with no pipeline create in it). +- **Test:** `d3d12_pipeline_wait_test async|sync` (ctest `d3d12_pipeline_wait_async`, `..._sync`) holds a build in + flight with a hook (`set_pipeline_build_hook`): with a 50 ms budget the submission returns within the budget and + its dispatch is skipped while the list's copies run; the next submission, once the build is let go, runs it; a 2 s + budget waits for a build let go 200 ms in and runs it; with -1 another thread creates and maps a buffer at once + while a submission waits; 0 skips without waiting; an exit stop during an unlimited wait builds in place + instead of waiting for a dropped job. RTX 4070 Ti, NVIDIA 630.20. + **Open:** whether the game uses `D3D12_PIPELINE_STATE_STREAM_DESC` for mesh/RT and which subobject types appear. The trace will enumerate them. @@ -3721,8 +3887,11 @@ will forward to. The queue-side calls ignore which queue they came on (one `VkQu - *Frame capture* (`LEONIDA_CAPTURE=`, `LEONIDA_CAPTURE_EVERY=`, `LEONIDA_CAPTURE_LIMIT=`): writes every n-th presented frame (default 30, at most 24) to `/frame_NNNNN.ppm`, a binary P6 of the swapchain image converted to 8-bit RGB, and appends one line per frame to `/index.txt` with the extent and the mean RGB. Off - unless the variable is set, and the folder is created. This is what a check reads when it has to know what the - layer actually presented: the window is not readable in every setup (under Wine it is not even mapped), and the + unless the variable is set, and the folder is created. Disk-only sampling copies frames 1, 1+n, 1+2n, … to host + staging until the file limit is reached; intervening frames still present normally. This avoids a full-image + transfer on every present when only occasional samples were requested. An explicit continuous readback request + and the temporary splash inspection still copy each frame they need. This lets a check inspect what the layer + actually presented: the window is not readable in every setup (under Wine it is not even mapped), and the mean is enough to tell a real frame from a black one. `d3d12_present_test` turns it on and checks the files against the colour it clears to. - *`SuspendX`/`ResumeX`*: suspend drops the interval, the origin event and the frames in flight, wakes blocked waits @@ -3912,6 +4081,26 @@ Not implemented yet: one Vulkan indirect call. Use a compute expansion pass that writes a Vulkan-shaped indirect buffer, or `VK_NV_device_generated_commands` on NVIDIA. Start with the simple signatures; the trace will show which signatures the game creates. +- The indirect arguments are clamped on the GPU before the command reads them (D3D-17's replay, + `runtime/src/vulkan_indirect_clamp.h`, shader `runtime/src/indirect_clamp.comp`). The title's own compute writes + them, and a pass the replay drops (an async pipeline that is not built yet, a stub pipeline, + `LEONIDA_SKIP_COMPUTE`) or mistranslates leaves whatever the memory held: a dispatch of billions of groups or a + draw of four billion vertices runs until the host resets the display driver. One small compute pass per + `ExecuteIndirect` call copies the active records into device-local scratch with their values bounded - 2^24 + vertices or indices, 2^26 vertex instances (count times instances), 65 535 groups per dimension, 2^20 groups per + dispatch and a 2^27-unit work budget per call that saturates through an atomic compare-and-swap - and writes an + empty record past `min(count, max_command_count)` and past the budget, and the clamped count word a `*Count` draw + then reads (so the count is at most `maxDrawCount`, VUID-vkCmdDrawIndirectCount-countBuffer-02717). The indirect + command reads that scratch. A draw emits the pass before its rendering scope opens: `vkCmdCopyBuffer` and a + memory barrier with a transfer access are not allowed inside a dynamic-rendering scope. The records are + bit-identical to the application's when they are within the limits, the argument and count buffers are left + untouched, and the scratch comes from a per-submission pool (`vulkan_scratch.h`) that a list with many indirect + calls reuses. `LEONIDA_INDIRECT_CLAMP=0` reads the application's buffer again, as before. The pass's counters + (records checked, records clamped, counts clamped, records past the budget) are copied to one host-visible slot + per call, read once the submission completes, logged in full at the first use and then rate-limited. Covered by + `indirect_clamp_test` (every kind and the counted variants, + in-range and garbage records, the budget), by `d3d12_m4_compute_test` (a garbage dispatch record beside the + in-range one) and by `d3d12_indirect_rt_test` (a draw whose instance count is garbage). - Predication (`SetPredication`) maps to `VK_EXT_conditional_rendering` (D3D-18). Done: `GraphicsCommandList:: SetPredication` records a `Predication` command (`runtime/src/command_list.h`; offset 8-byte aligned, op `EQUAL_ZERO` or `NOT_EQUAL_ZERO`, a null buffer turns it off). The replay (`runtime/src/vulkan_replay.h`) begins @@ -4171,7 +4360,8 @@ uint32 mask; // slot count - 1 struct entry { // 10 uints = 40 bytes uint32 key[8]; // T#: 8 dwords; S#: 4 dwords then 0xFFFFFFFF x4 uint32 index; // bindless index - uint32 pad; // unused by the shader + uint32 kind; // 0 empty; bit 31 occupied; bits 0..5 the sampled arrays the index is bound in, + // bits 8..11 its storage arrays (one bit per ImageDimension) } entries[mask + 1]; ``` @@ -4184,6 +4374,18 @@ struct entry { // 10 uints = 40 bytes `runtime/test/descriptor_table_test.cpp`. - Probe: `slot = (h + k) & mask` for `k = 0..7`; the first entry whose eight key dwords match yields its `index`; no match yields 0. +- `kind` says which arrays that index is good for, because it was given out in the T#'s own dimension's index space + (`runtime/src/vulkan_bindless.h`, `ImageDimension`): bit `d` is dimension `d`'s sampled array, bit `8 + d` its + storage arrays. A module whose `index.json` meta says `"descriptor_table": "tagged"` reads it and uses the index + only in an array the entry names, else index 0 of the array its instruction reads; an absent key is the old plain + layout, which reads only the index. `DescriptorTable::insert` takes the kind, and `BindlessSet::image_kind_at` + derives it from what was bound at the index (its own arrays, storage views, and the 2D copy of a 2D-array image's + first layer, whose slot records that image as its owner so another dimension's image with the same slot number does + not inherit it). One layout serves the device: any module whose meta says `tagged` makes the table tagged, because + the kind word is additive (a plain module ignores the word and reads the index, which the tagged layout keeps at + the same place), so a plain majority never turns it off; no tagged module is the old plain layout. + `LEONIDA_DESCRIPTOR_TABLE=plain|tagged` overrides, and the runtime says so loudly when an override forces plain + while tagged modules exist. - The layer must keep the table sparse enough that no live key needs more than eight probes. When all eight slots are occupied, the runtime tries to move one resident to the next empty slot within that resident's own probe window. A relocation requires an idle flush because it overwrites a live slot. Grow when this fails or when the next diff --git a/docs/design.md b/docs/design.md index eecb1cb844..acb56025f3 100644 --- a/docs/design.md +++ b/docs/design.md @@ -309,9 +309,10 @@ How the generated SPIR-V expects the runtime to work: | Scalar/buffer memory | `s_load*`, `s_buffer_load*`, `buffer_load*` and `buffer_store*` use buffer device addresses (`PhysicalStorageBuffer64`). LLVM `VCCTuple` scalar register lists ending in `vcc_lo,vcc_hi` (e.g. `[s100,s101,s102,s103,s104,s105,vcc_lo,vcc_hi]`, `[s92,...,s105,vcc_lo,vcc_hi]`, seen in 6 FidelityFX FSPX shaders) are parsed as `slist` operands in `tools/shader_ir.py`, clear `vcc` from the lane-mask state in `tools/lane_masks.py`, and route `sN` slots to `%sgpr` and `vcc_lo`/`vcc_hi` to `%vcc`/`%vcc_hi` across SMEM loads, T#/S#/V# descriptor reads, and `global_*` `saddr`. `src_scc` reads `%scc` (0 or 1, RDNA2 inline constant 253), matching `scc`. `image_atomic_*` and `image_atomic_cmpswap` accept `a16` packed 16-bit unsigned coordinates (low half first, matching `image_store`). CPU-checked by `tests/semantic/test_fspx_rules.py` and validated with `spirv-val` (native and `--wave64-emulate`). **Not GPU-verified.** The base comes from the 64-bit SGPR pointer or the V# (dword0 \ \| dword1[15:0] << 32), and the stride is V# dword1[29:16]. **The runtime must put the game's GPU heap in buffer-device-addressable memory at the same addresses the game writes into descriptors** (or remap them). `s_load*` and `s_buffer_load*` take an immediate or an SGPR offset, or both at once (llvm-mc prints `sOFF offset:IMM`). Rules, measured on AMD Radeon RX 6800 (gfx1030, Windows driver 32.0.21045.29003) by running the instructions as a raw compute kernel, wave32 and wave64 (155 runs, every result either 0 or the stored data, wave32 = wave64 in every dword): **address** = (base & ~3) + (sOFF & ~3) + (IMM & ~3) + 4·i for dword i: base, sOFF and IMM are each truncated to a multiple of 4, then added (`s_buffer_load_dword s9, s[24:27], 0x3` with base & 3 = 1 reads +0, not bytes 4..7; sOFF 3 + IMM 3 reads +0 and sOFF 2 + IMM 6 reads +4, where truncating the sum gives +4 and +8; sOFF 8 + IMM 4 reads +12; the same for `s_load*` with pointer & 3 = 1 or 3). **`s_buffer_load*` bound**: dword i is 0, and memory is not read, when (sOFF & ~3) + (IMM & ~3) + 4·i + 4 > limit, with limit = NUM_RECORDS (V# dword2) bytes when the stride is 0 and NUM_RECORDS × stride bytes when it is not. Per dword (x4 at 0xc with NUM_RECORDS 21: data, data, 0, 0; x8 at 0 with 21: five data, three 0), on the truncated offset (IMM 0x10 with NUM_RECORDS 18: 0; IMM 0x13 with 21: the dword at +0x10; sOFF 0xe + IMM 2 with 16: the dword at +0xc; sOFF 0x10 + IMM 4 with 20: 0), not seeing base & 3 (base & 3 = 3, IMM 0x13, NUM_RECORDS 20: data); with a stride the test is still on bytes (stride 4, NUM_RECORDS 5: IMM 0x10 data, 0x14 0; stride 1, NUM_RECORDS 17: IMM 0x10 is 0, so it is not an index test). IMM is unsigned (0xffffc reads +0xffffc). OOB_SELECT (V# word3[29:28]) 0, 1, 2 and 3 gave the same pattern (7 probes per value). **`s_load*`**: no bound (+0x1ffffc reads the dword there); IMM is sign-extended from 21 bits and added in 64 bits (sOFF 8 + IMM −4 reads +4 where zero-extension reads 4 GiB further; sOFF 0xb + IMM −1 reads +4, so the negative IMM is truncated on its own: −1 → −4). **Negative sums** (SHADER-336), measured on the integrated GPU of a Ryzen 9 9950X3D (gfx1036, RDNA2, Windows driver 32.0.21045.16010) with `tools/smem_neg_probe.py --oracle hw`, wave32 = wave64: `s_load` with IMM −4 or −0x40 and no sOFF, sOFF 4 + IMM −8, sOFF 0xc + IMM −0x20 and the x2 form with sOFF 4 + IMM −0x10 read below the pointer at the 64-bit signed sum, and sOFF 6 + IMM −1 reads +0 (4 + −4, each term truncated on its own). `s_buffer_load` adds sOFF and IMM without wrapping at 32 bits: sOFF 0xfffffffc + IMM 8 and sOFF 0xfffffff0 + IMM 0x20 give 0 (past NUM_RECORDS 0x100), and sOFF 0xfffffffc, 0x80000000 and 0x7ffffffc alone give 0 (the translator has the same rule in both offset forms since #1686). An `s_buffer_load` IMM with bit 20 set (llvm-mc rejects it; −4, −0x10, 0x100000 and 0x100004 were encoded by hand) reads data that is neither 0 nor the buffer's own words, differently in wave32 and wave64: the bound does not hold for that encoding, so no compiler output uses it and the translator does not model it. `SmemHardwareRuleTests` in `tests/semantic/test_scalar_mem_smem.py` runs these rows with sOFF in a register and with sOFF known. **Measured since** on native RDNA2 (gfx1036, the Radeon iGPU of a Ryzen 7 9800X3D, Windows driver 32.0.21042.62) through `tools/hw_oracle`, one raw kernel, wave32 = wave64 in every dword (22 cases): **`x16`** takes the per-dword bound like x8 (`s_buffer_load_dwordx16` at offset 0 with NUM_RECORDS 0x24 gives nine data dwords and seven 0; offset 0x20 with 0x40 gives eight and eight; offset 4 with 0x3d gives fourteen and two; stride 4 with NUM_RECORDS 9 gives nine and seven), and `s_load_dwordx16` reads all sixteen; **NUM_RECORDS ≥ 2^31** is compared unsigned (0x80000000 and 0xffffffff with offset 0x10, and 0x80000000 with an x4 at 0x2f0, all read data); **NUM_RECORDS × stride ≥ 2^32** does not wrap (stride 4 × 0x40000001, stride 0x100 × 0x01000001 and stride 0x40 × 0x04000004 wrap to 4, 0x100 and 0x100 in 32 bits, yet offsets 0x10, 0x200 and 0x2f0 read data), as the translator's 64-bit product assumes; **V# dword1[31:30]** = 1, 2 or 3 changes nothing (a dword at 0x10, an x4 at 0xf8 with NUM_RECORDS 0x100 giving two data and two 0, and the same with stride 8 and NUM_RECORDS 4 at 0x18). Not measured: gfx1013 (PS5) itself. **Bound edges**, measured on the same GPU and driver with `tools/hw_oracle` (wave32 = wave64, every read inside a seeded region): `s_buffer_load_dwordx16` is bounded per dword like x8 (NUM_RECORDS 0x14 gives d0..d4 and 0 for d5..d15; 0x20 with IMM or sOFF 8 gives d0..d5); NUM_RECORDS × stride is not cut to 32 bits (stride 0x1000 × 0x100000 and 0x2000 × 0x80000 = 2^32, stride 8 × 0x20000001 = 2^32 + 8: all four dwords of an x4 at 0 are data; stride 8 × 1 gives two); NUM_RECORDS 0x80000000 and 0xFFFFFFFF are unsigned (an x4 at 0 reads all four). These are the rules the translator already used; `SmemHardwareRuleTests` pins them too (a 32-bit product, a signed NUM_RECORDS or one bound for the whole load each fail a test). Not measured: `x16` (gets the x8 rule), NUM_RECORDS ≥ 2^31 and NUM_RECORDS × stride ≥ 2^32, V# dword1[31:30], and gfx1013 (PS5) itself. `s_load`/`s_buffer_load` with sOFF + IMM < 0 (a negative IMM without sOFF included; the translator uses the 64-bit signed sum, an inference), an `s_buffer_load` IMM with bit 20 set (llvm-mc rejects it) or a negative one (kept as the 32-bit value: for stride 0 that is past any NUM_RECORDS below 4 GiB), `x16` (gets the x8 rule), sOFF ≥ 2^31, NUM_RECORDS ≥ 2^31 and NUM_RECORDS × stride ≥ 2^32, V# dword1[31:30], and gfx1013 (PS5) itself. The translator checks each `s_buffer_load` dword with its own structured `if` and an `OpPhi` with 0, so an out-of-range dword issues no load (when descriptor limit and offset are compile-time constants, in-range dwords fold to straight-line loads and out-of-range dwords emit constant zero without branches); `s_load` stays straight-line. Before this the translator added base + sOFF + IMM unaligned, had no `s_buffer_load` bound and zero-extended a negative `s_load` IMM. Checked by `tests/semantic/test_scalar_mem_smem.py` (`SmemHardwareRuleTests`, the measurement's rows, values and the addresses read; `SmemSoffsetImmTranslatorTests`) and by the GPU tests `runtime/test/shaders/cs_smem_soffset_imm.asm`, `cs_smem_bounds.asm`, `cs_smem_stride_align.asm` and `cs_smem_sload_neg.asm` (never run that one with a translator that zero-extends the immediate: it reads 4 GiB past the heap), all in `check.py` and `scripts/run_gpu_tests.py`, which pass on the RX 6800 (Vulkan, driver 26.11.2). See *Buffer bounds checking* below for the MUBUF `num_records` checks. **A constant SGPR offset** (`s_mov_b32 s12, C`, folded at translate time) is added as the run-time path adds `sOFF`: zero-extended, `& ~3`, after the immediate has been normalised (unsigned for `s_buffer_load`, 21-bit signed for `s_load`), with no 32-bit wrap. Until 2026-11-22 (#1686) the fold added it before the truncation, so `s12 = -4` with `offset:20` read byte 16 instead of being out of range, and an `s_load` `sOFF` of 2^20 or more was sign-extended from 21 bits (found by @Impre-visible; hardware measured by @Pierre-Kookis on gfx1036: 0xFFFFFFFC + 20 reads 0). CPU-checked by `tests/semantic/test_smem_const_offset.py` (each case constant vs run-time offset, and against the measured rule). Where llvm-mc rejects such a tuple, `restore_vcc_tuples` decodes it from the blob, and with it the instructions its junk text swallowed, up to the next instruction llvm-mc printed (corpus count: `docs/shader_library.md`, section 5). | | 2D array resource dimensions | For `image_get_resinfo` on a 2D array, X/Y are the width/height at the requested mip, Z is the view layer count and W is its mip count. The query reads the sampled array at binding 3. A native gfx1036 kernel returned (19,11,5,3), (9,5,5,3) and (4,2,5,3) for the three mips of a synthetic array. On RTX 5080 and Radeon Graphics the translated query matched those tuples and returned (4,2,3,2) at relative mip 1 with a view starting at mip 1 and covering three layers. The registered `ps_array_resinfo` draw checks all 4096 pixels against (8,8,12,1). | | Images and samplers | `image_sample_l` on 2D arrays used to read its LOD from the array layer; it now reads the LOD after all coordinates. `image_get_lod` and `image_gather4_lz` also work on 2D arrays. With `d16` every sample result is f16, packed two to a VGPR from the low half (the packed D16 of GFX10, as LLVM returns D16 image data); `image_sample_c_lz`/`_c_lz_o` follow it too, and until 2026-11-21 their compare result was written as f32 bits, which read as 0 in the low half. Checked by `tests/test_translate.py` (`test_depth_compare_sample_result_width`) and GPU-checked with `runtime/test/shaders/ps_sample_c_lz.asm` (`vk_texture_test dref`: a D32 texture and a LESS_OR_EQUAL compare sampler) on an NVIDIA GeForce RTX 2060 SUPER (Linux, driver 620.70.06): 4096/4096 pixels exact for f32 and `d16`; with the old translator the `d16` result read 0 in the 2048 pixels whose compare passes. | +| Images and samplers (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, pad`. The key is a T# or a padded S#. FNV-1a over the eight key words selects the first slot by default. With `--descriptor-hash=fnv1a_fmix32` the shader applies MurmurHash3 fmix32 before masking the slot. Every translated module then records `"descriptor_hash": "fnv1a_fmix32"` in its index entry. An absent key means `fnv1a`. The runtime and shader must select the same hash. The shared SPIR-V lookup probes up to eight slots and returns index 0 on a miss. The runtime supplies a fallback at index 0 and maps live descriptor keys to bindless indices. Outside the wave64 emulation, the lookup's result goes through `OpGroupNonUniformBroadcastFirst` before it indexes the image or sampler array. The lookup key words come from SGPRs, so every invocation in a subgroup has the same index; the broadcast is an identity on all drivers and marks the value uniform for the compiler. It declares `GroupNonUniform` and `GroupNonUniformBallot`, without a shuffle capability or subgroup-lane input. The shader index records the capabilities; its `features` field lists optional Vulkan device features. Mesa ANV 26.2.7 on an Intel Alder Lake-S UHD (Xe-LP, Linux) segfaults in `vkCreate*Pipelines` on a sampler index taken straight from the probe loop when that sampler serves both a float and an integer image (`cs_sample_lz_int_d16`, `ps_ssharp`); with the broadcast both pass. Checked by the unit test `test_lookup_result_is_broadcast_before_use` in `tests/test_desc_cache.py` (standard library only: no GPU, LLVM or SPIRV-Tools). | +| 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). | | Run-time format decode cost | A `buffer_load_format_*` whose format comes from the V# is decoded by table, without a branch: one shared function per output component (`%fmt_dec_c0`…`%fmt_dec_c3`) reads the format's kind, channel count and channel widths from the module table `%fmt_desc_tab`, and the kind picks the conversion with `OpSelect`; the exact UNORM/SNORM quotient comes from the shared `%fmt_norm_bits`, whose width's 64-bit repeat constant is read from `%fmt_norm_rep_tab`. A code outside the table gives zeros, a format with fewer channels repeats its own (component *c* = *c* mod *n*), and the element size is selected from the format alone (`%fmt_size_tab`), the per-lane byte offset added once. Until 2026-11-23 the shared function instead held every format's decode and a binary search over the codes (`OpSelectionMerge` with `DontFlatten`): 3,498 instructions and 306 branches in the module of a shader with one dynamic-format load (250,869 bytes). Now the four functions hold 565 instructions and no branch, and that module is 56,763 bytes. The decode functions take the format code and the element's four dwords as a `v4uint`, so their function type has a structure of its own: a type of `uint` × 5 repeats the type of the `x_round` helpers, and SPIR-V forbids two non-aggregate types with the same structure. Over the 1.0.2.1 corpus the 11,400 shaders that use this path all translate and pass \spirv-val\ (the previous translator included), and their modules shrink from 11,163,872,428 to 10,454,474,528 bytes (-6.35%). The 15,103 shaders without a run-time FORMAT come out byte for byte identical (checked on a 297-shader sample, every 51st of them). The values are unchanged: every one of the 128 codes gives the same words as the branch search, checked by `tests/semantic/test_format_decode_table.py` (each code against a reference decoded from the raw bits with exact quotients, plus the branch-free and shared-per-component shape). The old translation was confirmed on an RTX 4090 (621.01) against the decode-everything translation: identical output buffers for all 128 codes in four configurations (four byte alignments, out-of-range records, constant DST_SEL), xyzw and d16_xyzw. The branch-free decode costs more ALU per load than the search (every kind's conversion is computed and one is kept), so it trades run time for module size and compile time. | | 3D explicit-gradient texture samples | For `image_sample_d` and `image_sample_d_cl` on a 3D view, the first six address VGPRs contain dP/dx.xyz and dP/dy.xyz. XYZ and the optional minimum LOD follow. With `a16`, the six derivative VGPRs still hold f32; the following two words contain packed f16 coordinates and the optional clamp. The hand-written `tests/semantic/fixtures/volume_gradients.asm` checks the source registers of both gradients, coordinates and clamp. LLVM gfx1030 assembles all four forms and their modules validate for Vulkan 1.2. [LLVM GFX10 address sizing](https://reviews.llvm.org/D102231) and [SPIR-V Grad operands](https://registry.khronos.org/SPIR-V/specs/unified1/SPIRV.html#Image_Operands) | | `image_sample_c_l` | Scalar 2D depth comparison (`dmask:0x1`) takes the f32 reference, XY coordinates and explicit mip in that order. Under A16 the reference stays full-width; XY share a VGPR and LOD uses the next low half. D16 returns the comparison in the low half of the destination. Confirmed against LLVM AMDGPU's `llvm.amdgcn.image.sample[.a16].dim.ll` lowering and synthetic Vulkan 1.2 modules in `test_explicit_mip_depth_compare`. | @@ -519,7 +520,7 @@ How the generated SPIR-V expects the runtime to work: | Wave64 graphics: partition invariance (SHADER-10) | A wave64 VS/PS/GS on a 32-wide subgroup is exact **iff its observable results do not change when the wave is cut into two 32-lane halves** (the host forms the subgroups of graphics stages, so there is no partner half to exchange with). `tools/wave64_halves.py` decides it from the code (forward taint dataflow over the basic blocks, plus control dependence on wave-wide votes) and the translator records it in `index.json` as `wave64_graphics` (`A`/`B`/`C`), `wave64_graphics_reasons` (tier C) and `wave64_graphics_idioms` (tier B). **A**: only per-lane arithmetic, votes that skip lane-masked work (`s_cbranch_execz/execnz`; `vccz/vccnz` whose run side starts by narrowing EXEC to that VCC and whose other side is the join, with no code of its own: a half that votes no runs that side, the wave does not; the same holds for `s_cbranch_execz/execnz`: the side that runs when EXEC is zero is taken by a half with no active lane, so it must be the join (or only jumps to it) or the exit of a loop the vote closes, else tier C `unsafe-execz-branch`; `s_cbranch_scc*` after a vote is the same kind of skip, any other reader of that SCC, `s_cselect`/`s_cmov`/`s_addc`, is tier C; a vote is on the mask register's value when it was taken, so a new value in that register before the branch (`v_cmp` into the pair or VCC, `s_mov_b64`, `s_cselect_b64`: none of them writes SCC) ends it, and the branch is judged as a plain SCC branch, SHADER-820), whole-quad masks, `ds_bpermute`/`ds_permute`/`v_permlane16`/`v_permlanex16`/`ds_swizzle` (they stay inside a half), a `ds_bpermute`/`ds_permute` address made from the lane id (`v_mbcnt_lo` then `v_mbcnt_hi` of -1) when it is the same modulo 128 bytes in the wave and in a half (the id is 0..63 there and 0..31 here, equal modulo 32 lanes; sums, differences and bitwise ops with invariant values keep that, a left shift by c multiplies the modulus by 2^c, and the permute uses address bits 2..6 of its half only: `(id ^ 1) << 2` is exact, `id << 1`, a right shift of the id or the low count alone stay tier C `lane-id`), loops closed by `execnz` with no scalar state carried, and the early exit of a pixel kill: `s_cbranch_scc0/scc1` (or `vccz/vccnz`) on a lane mask's own "not empty" (the last SCC writer is a 64-bit logic op into that mask, e.g. `s_andn2_b64 live, live, exec`, or `s_cmp_lg_u64 mask, 0`, and nothing rewrites the mask before the branch) to a block that only sets EXEC from that mask or 0 (`s_mov_b64 exec`, or `s_and_b64 exec` with it), may then export with that EXEC (an export is allowed, not required), and ends (no other code, store or successor), while the run side narrows EXEC into the mask's whole quads before anything but mask arithmetic (`s_mov_b64`, `s_and_b64`, `s_wqm_b64`) runs, the narrowing itself possibly an `s_and_saveexec_b64` / `s_andn2_saveexec_b64` (or `_wrexec_`) whose source is inside, and keeps it inside on every path from there, loops included (a must-dataflow: an EXEC write keeps it inside only when it is provably a subset: `v_cmpx`, `s_and_b64` with one operand known inside, `s_andn2_b64` / `s_andn2_saveexec_b64` whose first operand is, `s_and_saveexec_b64` while inside or from one that is, `s_andn1`/`s_or`/`s_xor_saveexec_b64` only while inside (the latter two also from one that is), and copies, `s_wqm_b64`, `s_or_b64` and `s_xor_b64` of operands known to be inside (0 counts as inside); a saveexec destination holds the old EXEC and a wrexec one the new, each inside only if that EXEC was), and no `exp ... vm` can run before the vote. A half whose mask is empty then writes nothing and discards its pixels in the exit, and in the wave its lanes are off to the end, so the wave discards them too; an exit shared by several kills reads a mask redefined behind the earlier votes and stays tier C. GPU-checked by `ps_w64_a_discard` (below). `s_cbranch_scc*` after a vote is the same kind of skip, any other reader of that SCC, `s_cselect`/`s_cmov`/`s_addc`, is tier C; a vote is on the mask register's value when it was taken, so a new value in that register before the branch (`v_cmp` into the pair or VCC, `s_mov_b64`, `s_cselect_b64`: none of them writes SCC) ends it, and the branch is judged as a plain SCC branch, SHADER-820), whole-quad masks, `ds_bpermute`/`v_permlane16` (they stay inside a half, not GPU-tested here: no fixture; `s_cbranch_scc*` after a vote is the same kind of skip, any other reader of that SCC, `s_cselect`/`s_cmov`/`s_addc`, is tier C), whole-quad masks, `ds_bpermute`/`v_permlane16` (they stay inside a half, not GPU-tested here: no fixture; `ds_swizzle` and `v_permlanex16` likewise; GPU-checked at required 64 and 32 lanes by `ps_w64_a_bpermute`, `ps_w64_a_permlane` (`v_permlane16` and `v_permlanex16`) and `ps_w64_a_swizzle` in `w64_graphics.py`, TEST-433), loops closed by `execnz` with no scalar state carried. `ds_swizzle` and `v_permlanex16` likewise), loops closed by `execnz` with no scalar state carried. A `vccz`/`vccnz` on a wave-uniform compare is no lane vote and is tier A too: a `v_cmp` made while EXEC is the launch mask from untainted immediates, scalars that are no lane mask and VGPRs written from them (optionally ANDed with EXEC, the LLVM form `s_and_b64 vcc, exec, s[..]`) gives every launch lane or none, so each half votes as the wave does and both sides may have code and scalars of their own (if/else, a uniform loop back edge; the mask itself read as data, e.g. exported, is still tier C `cross-lane`), while the same compare under a narrowed EXEC (a half with no active lane votes no and keeps its own scalars) or on a tainted value (`v_readfirstlane` of a varying VGPR, a lane count, an AND with a lane mask) stays tier C; confirmed on the wave interpreter (`UniformVote` in `tests/semantic/test_wave64_halves.py`: 64 lanes against two waves of 32, equal for the accepted forms with s4 = 9 and s4 = 1, different for each near miss) and by `ps_w64_a_uniform_vote`, which gives its derived words on an NVIDIA GeForce RTX 5080 (Linux, driver 580.65.06, 32 only). **B**: also a waterfall loop (`v_readfirstlane` of a varying value, `v_cmp_eq` against the same VGPR, `saveexec`, body, `s_xor exec`, `execnz`; the scalar only used inside the body), a wave-aggregated atomic (`s_bcnt1` of EXEC, `v_mbcnt` rank of that same EXEC, one `buffer_atomic_add` of that count (the count of the mask the rank ranks) by the rank-0 lane only, at a wave-uniform address (a uniform VGPR, or one the elected lane wrote from scalars and constants since EXEC last changed; a per-lane address such as a pixel coordinate is tier C `elected-lane`, since each half elects its own lane and bumps another counter), `v_readfirstlane` of the result with EXEC restored, base + rank as a store address, the rank counting the very mask the atomic's count was taken of (a rank of the entry EXEC or of a saved copy next to a base of the narrowed one is tier C `lane-rank`); the rank alone or the base alone is not a slot: exact as a set of slots, **the order of the slots within a wave is not preserved**, a 64-lane wave takes one run of slots, two halves take two), `v_readfirstlane` / `v_readlane` of a VGPR written from scalars and constants while EXEC was the launch mask (the same in every lane), a `v_writelane` / `v_readlane` spill pair on one constant lane below 32. **C**: anything else that reaches an export, a store's data, a branch or EXEC: lane count / rank / first-lane index / raw lane id (`v_mbcnt` of -1), `v_readlane` of a varying value at any lane (on a wave64 every lane gets hardware lane N, in halves each half gets its own lane N, so lane 7 is as wrong as lane 40; the research note's row 9 is too generous here); an analysis failure is tier C with reason `analysis-error` (the translation does not fail), `v_writelane` to a non-constant or >= 32 lane, a 32-bit access to half of a lane mask (`exec_hi`, `vcc_hi`, a mask pair's odd register), a mask read as data (including a mask combined by `s_and/or/andn2_b64` with a register that is not one: a user value, a loaded mask), a scalar defined behind a wave-wide vote and read where it may not have run (`s_add s5, s5, 1` after `s_cbranch_vccz`; a trip count in an SGPR of a divergent loop: the halves vote differently), a branch on a count, an elected-lane side effect that is not a count, `ds_append`/`ds_consume`. The check is conservative: unknown means C. `--wave64-graphics=warn` (default) marks tier C and counts it in the summary line, `error` refuses it (`Unsupported`), `off` skips the analysis; `python tools/wave64_halves.py --census /index.json` prints tier, reason and idiom counts (no names); it complements `tools/wave64_graphics_scan.py` (#1132), which counts candidate cross-half opcodes in the disassembly before translation and decides nothing. **Corpus census** (1.0.2.1, all 26,503 shaders translated at `main` `f847748c` with `--wave64-emulate`, `--census` over that index): 13,405 wave64 graphics shaders (2,236 VS, 10,974 PS, 195 GS, the FSSM header's wave size, see *Wave size*); tier A 4,033 (30.1%), B 85 (0.6%), C 9,287 (69.3%): VS 1,455/79/702, PS 2,383/6/8,585, GS 195/0/0. Tier C reasons (a shader can have several): unsafe-vote-branch 8,285, tainted-branch 6,547, tainted-exec 5,189, cross-lane 4,764, stale-scalar 3,415, mask-half 759, unsafe-execz-branch 583, first-lane 353, waterfall-scalar 161, lane-id 152, lane-count 1. Idiom tags, counted on every shader that carries one whatever its tier (`--census` prints them as "tier B idioms"; 85 shaders are tier B): readfirstlane-uniform 626, lane-spill 287, waterfall 35. (Earlier censuses counted 11,405 shaders, from when the wave size came from code markers: TEST-319 had A 1,919, B 17, C 9,469 with all 195 GS in C; its re-run with the GS ring rule below and #1982 had A 2,117, B 17, C 9,271 with all 195 GS in A.) The lane-id bpermute rule moves no corpus shader. (The TEST-319 census, from when the wave size came from code markers and before the GS ring-address rule below, counted 11,405 shaders: A 1,919, B 17, C 9,469, with all 195 GS in C.) The lane-id bpermute rule moves no corpus shader. **Corpus census** (TEST-319, 1.0.2.1, `--census` over the translated index, re-run with the GS ring rule below and #1982): 11,405 wave64 graphics shaders (1,179 VS, 10,031 PS, 195 GS); tier A 2,117 (18.6%), B 17 (0.1%), C 9,271 (81.3%): VS 479/14/686, PS 1,443/3/8,585, GS 195/0/0. Tier C reasons (a shader can have several): unsafe-vote-branch 8,285, tainted-branch 6,550, tainted-exec 5,189, cross-lane 4,760, stale-scalar 3,415, mask-half 758, unsafe-execz-branch 583, first-lane 353, waterfall-scalar 161, lane-id 152, lane-count 1. 11,405 wave64 graphics shaders (1,179 VS, 10,031 PS, 195 GS); tier A 1,919 (16.8%), B 17 (0.1%), C 9,469 (83.0%): VS 465/14/700, PS 1,454/3/8,574, GS 0/0/195. Tier C reasons (a shader can have several): unsafe-vote-branch 8,175, tainted-branch 6,582, cross-lane 6,111, tainted-exec 4,959, stale-scalar 3,162, mask-half 758, unsafe-execz-branch 583, first-lane 353, lane-id 277, waterfall-scalar 167, lane-count 1. Tier B idioms: readfirstlane-uniform 558, lane-spill 287, waterfall 35. The lane-id bpermute rule moves no corpus shader. **Corpus coverage is not measured here**: it needs a run over the game's shaders by someone who has them. **Rewrite (the only one the emission needs)**: `v_readlane_b32` of a proven-uniform VGPR reads the lane's own copy instead of shuffling from lane N, because a subgroup shuffle from lane >= 32 of a 32-wide subgroup is undefined (143 of 144 test shaders translate byte-identically to origin/main, only `ps_w64_b_readlane_uniform` changed). Everything else tier B needs is what the translator already emits per subgroup: the ballot/count/rank/first-lane words of `wave_mask` are the subgroup's own (the high word is 0), `v_readfirstlane` is the subgroup's first active lane, a waterfall runs once per distinct value of the subgroup. GPU-checked on AMD Radeon 880M (driver 26.11.2; `requiredSubgroupSizeStages` has FRAGMENT, size 32..64) with `runtime/test/shaders/w64_graphics.py`: each `ps_w64_*` fixture drawn with the fragment subgroup size required to 64 (one hardware wave) and to 32 (two halves). `ps_w64_a_skip`, `_b_waterfall`, `_b_readfirstlane`, `_b_readlane_uniform` and `_b_ballot_atomic` (counter 1024 and the 1024 slot words as a set; slot order differs) match each other and the words their headers derive; `_c_bcnt_export`, `_c_lane_id`, `_c_readlane`, `_c_vote_stale`, `_c_vote_else`, `_c_scc_vote`, `_c_execz_sgpr` (an SGPR written on the exec-zero side and exported) and `_c_waterfall_count` differ between 64 and 32 (the detector is right). `ps_w64_a_one_lane` is the case where only one pixel votes yes (so one half votes and the other does not, in the wave and in the halves): its skip regions (`execz`, `vccz`, `vccnz` with a jump-only fall-through) give equal images at 64 and 32; `_c_vote_else` (code on the vote's no side) and `_c_scc_vote` (SCC of a vote as data) differ. `ps_w64_a_discard` (three kills, two of them dropping whole regions so that some halves lose every pixel while the other half of their wave lives) was drawn on an AMD Radeon RX 580 (RADV, Mesa 26.0.8, required size 64, saved with `W64G_SAVE_REF`) and an NVIDIA GeForce RTX 5070 (32 only, driver 620.73.04, compared with `W64G_REF`): both equal the derived words, discarded pixels keeping the clear value, and each other. NVIDIA GeForce RTX 5070 Laptop (32 only, driver 617.42): tier A/B fixtures equal the derived words and the 880M@64 images (`W64G_SAVE_REF` / `W64G_REF`), tier C fixtures differ from the 880M@64 images. `ps_w64_a_permlane`, `_a_swizzle` and `_a_bpermute` (TEST-319: permlane16 neighbour selects, permlanex16 there and back, swizzle quad-permute, swap and broadcast modes, bpermute from lane-id addresses; every read stays in the pixel's 2x2 quad or comes back, so the words do not depend on how pixels are packed into lanes) give the derived words on an NVIDIA GeForce RTX 5070 (Linux, driver 620.73.04, 32 only). With an AMD Radeon RX 580 (Polaris, RADV Mesa 26.0.8) as the 64-lane reference (`W64G_SAVE_REF`; GCN has one subgroup size, 64, in every stage but no FRAGMENT in `requiredSubgroupSizeStages`, so `vk_harness` counts a requested size equal to a device's only size as applied), the RTX 5070 run of every fixture (`W64G_REF`) equals the reference for all 13 tier A/B fixtures and differs from it for all 11 tier C ones, pixel and vertex; the same reads in a vertex shader run on the wave interpreter (64 lanes against two waves of 32, equal) because a GPU's partial vertex waves leave the lanes they would read empty. Vertex shaders: the VS stage cannot be forced on the 880M (no VERTEX in `requiredSubgroupSizeStages`), so VS is covered by the strict wave interpreter (`tests/semantic/test_wave64_halves.py`: 64 lanes against two waves of 32; tier A/B equal, tier C differs); geometry shaders are not tested (the corpus ones are wave64, see *Wave size*; no fixture). 64 lanes against two waves of 32; tier A/B equal, tier C differs), and on RADV also on the GPU (TEST-251): RADV runs the VS stage (NGG) as wave64 by default and as wave32 with `RADV_PERFTEST=gewave32` (GFX10+, seen in the `RADV_DEBUG=shaders` dump: 64-bit EXEC operations against `exec_lo`), so `w64_graphics.py` draws each `vs_w64_*` fixture both ways, 960 zero-area vertices (`VKH_VERTICES`) that store four words each to the heap, with `vs_w64_c_lane_id` as the probe that the wave size changed (largest lane id 63, then 31). RADV packs 62 or 64 vertices into a wave64 and 30 or 32 into a wave32, so the 32-lane run repacks the vertices rather than halving the waves; tier A/B words are keyed on the vertex index, which makes this the stricter test. `vs_w64_a_skip`, `_b_waterfall`, `_b_readlane_uniform` (readfirstlane and readlane 40/63 of uniform VGPRs) and `_b_ballot_atomic` (240 slots as a set) give the derived words at both sizes; `_c_bcnt_export`, `_c_readlane` and `_c_lane_id` differ (the detector is right), on an RX 9070 XT (GFX1201) and a Ryzen 9800X3D iGPU (GFX1036, RDNA2), RADV Mesa 26.3.1; geometry shaders are not tested (no fixture; the corpus has 195 wave64 geometry shaders, all tier C, see the census). `_c_bcnt_export`, `_c_readlane` and `_c_lane_id` differ (the detector is right), on an RX 9070 XT (GFX1201) and a Ryzen 9800X3D iGPU (GFX1036, RDNA2), RADV Mesa 26.3.1; geometry shaders likewise (TEST-251): RADV runs the GS stage (NGG) as wave64 by default and as wave32 with `gewave32`, and `w64_graphics.py` draws each `gs_w64_*` fixture after `vs_ids` (960 vertices, 320 triangles, `VKH_GS`), each invocation finding its triangle from `vs_ids`'s vertex number and storing four words to the heap, with `gs_w64_c_lane_id` as the probe (largest lane id 41, RADV puts at most 42 GS invocations in a wave64, then 31). **LDS writes of a legacy GS:** `rdna2spirv.gs_ds` maps one to an output slot from its offset alone and drops the VGPR address (the lane's GSVS area), so `wave64_halves.py` checks only the data a GS `ds_write` writes, not its address; before, a lane id that only formed the GSVS base made the shader tier C `lane-id`. Confirmed three ways: a hand-written GS with the base `lane id * 96` translates, after `spirv-opt -O`, to the same instructions as without it; `gs_w64_a_ring` (that shape) gives the derived records at wave64 and wave32 on both GPUs; and `tests/semantic/test_wave64_halves.py` (`GeometryRing`) keeps the lane id in the written data, or in a memory store's address, tier C. The corpus GS were that false tier C: all 195 contain `v_mbcnt_hi`, all 195 were tier C in the TEST-319 census, and `wave64_halves.py --census` on the corpus translated at `f847748c` puts all 195 in tier A. `_c_bcnt_export`, `_c_readlane` and `_c_lane_id` differ (the detector is right), on an RX 9070 XT (GFX1201) and a Ryzen 9800X3D iGPU (GFX1036, RDNA2), RADV Mesa 26.3.1; geometry shaders are not tested (the corpus ones are wave64, see *Wave size*; no fixture). The corpus GS form their GSVS base from `v_mbcnt_lo/hi` (all 195 contain `v_mbcnt_hi`): they were all a false tier C, and the census above has all 195 at tier A. `wave64_halves.py --census` on a translated corpus shows it. `_c_bcnt_export`, `_c_readlane` and `_c_lane_id` differ (the detector is right), on an RX 9070 XT (GFX1201) and a Ryzen 9800X3D iGPU (GFX1036, RDNA2), RADV Mesa 26.3.1; geometry shaders are not tested (the corpus ones are wave32; no fixture). Not checked: helper lanes of partial quads; `VK_KHR_shader_maximal_reconvergence` is assumed for waterfall and election loops. Tiers A and B assume subgroups of at least 32 lanes: a fragment stage may run fewer live lanes than the subgroup size it reports (Intel UHD 770: gl_SubgroupSize 32, ballot count 16, a shuffle from lane L^16 returns garbage; measured by kapitche, TEST-433), so `w64_graphics.py` skips the tier A/B pixel fixtures on a device whose minimum subgroup size is below 32 when neither the 64 nor the 32 run took effect; deriving the skip from a measured live fragment width (ballot count) in `vk_harness` is a follow-up. **ADD_TID_ENABLE** (SHADER-833, finding by @shdann in #4571): an access with no `idxen` through a V# whose word3 is a literal (`s_mov_b32` earlier in the block, the notion `rdna2spirv` uses for `sgpr_imm`) with bit 23 set takes the wave lane as its index (`idxen` ignores the bit, see *Swizzled buffer addressing*), so its `buffer_load*`/`tbuffer_load*` result and its `buffer_store*`/`tbuffer_store*`/`buffer_atomic*` address carry the raw lane id: tier C `lane-id`. A literal with the bit clear, and every access with `idxen`, are unchanged. **Assumption**: through a run-time V# (loaded from memory or user data) tiers A and B take ADD_TID_ENABLE as 0 for an access without `idxen`; the code cannot say otherwise. The literal is tracked with the same folds `rdna2spirv` applies to `sgpr_imm` (mirrored in `Analysis.literal_sgpr`: `s_mov_b32/b64`, `s_movk_i32`, `s_pack_*`, `s_bfm_b32`, `s_not_b32`, `s_and/lshl/lshr_b32`, `s_mul_i32`; other folded ops count as run-time). The corpus census was not re-measured with this rule: its tier counts above are from before it and may change. Follow-up, needs the game: count the bound V#s with word3 bit 23 set at run time, and re-run `--census`. | | Wave64 graphics: a uniform vote under whole-quad EXEC (SHADER-W64-WQM-UVOTE) | SHADER-10 (the row above) takes a `vccz`/`vccnz` on a wave-uniform compare for no lane vote only while EXEC is the launch mask. A pixel shader that needs derivatives starts with `s_wqm_b64 exec, exec`, and LLVM branches on uniform conditions inside that region in the same form: `v_cmp_* sN, ` / `s_and_b64 vcc, exec, s[N:N+1]` / `s_cbranch_vccnz` (or the compare straight into VCC). **That is exact too, for a compare of immediates and scalars**: it is the same in every lane, so its mask is every lane of EXEC or none; EXEC is the whole quads of the launch mask, a quad is four consecutive lanes and never straddles the two 32-lane halves, and a half that runs has a launch lane, so EXEC has a lane in every half that runs and each half votes as the wave does. Both sides of the branch may then have code and scalars of their own (if/else, a uniform loop back edge), as under the launch mask. `tools/wave64_halves.py` carries it as a dataflow fact (`q`: EXEC is the whole quads of the launch mask), set by `s_wqm_b64 exec, exec` while EXEC is the launch mask and dropped by every other write to EXEC; `uniform_cmp` and the `s_and_b64 .., exec, ..` of a uniform mask accept it next to the launch mask. **What stays tier C, and why**: a VGPR source, even one SHADER-10 calls uniform (it was written under the launch mask, and the helper lanes EXEC now includes never got it, so they compare what they held; a VGPR written inside the region is refused as well, because the analysis does not tell the two apart); the whole quads of a narrowed EXEC, and any narrowing after the `s_wqm_b64` (a half can be empty); whole quads saved and put back later, or made in a register and copied to EXEC (only the write by `s_wqm_b64 exec, exec` is modelled); and a compare on a path where a scalar was read out of a uniform VGPR from a lane the launch mask may not have written, by `v_readlane_b32` at any time or by `v_readfirstlane_b32` while EXEC was not the launch mask (`qr`, kept for the rest of the path: SHADER-10 treats such a scalar as uniform, this rule does not build on that). **Corpus** (1.0.2.1, all 26,503, `wave64_halves.analyse` on every wave64 VS/PS/GS, with SHADER-W64-SDST-PAIR on `main` `3ed8e50b7` as the baseline, because the listings name the compare's destination by one register and without that rule the vote is hidden behind `tainted-branch`): **452 pixel shaders go from tier C to A**, no shader moves the other way and no vertex or geometry shader moves: A 5,267 to 5,719, B 397, C 7,741 to 7,289 (PS 3,545/34/7,395 to 3,997/34/6,943). Reasons: `unsafe-vote-branch` 7,362 to 6,861, `tainted-exec` 5,829 to 5,793, `stale-scalar` 3,287 to 3,254, the others unchanged; 802 shaders still have `unsafe-vote-branch` as their only reason. CPU-checked by `tests/semantic/test_wave64_halves_wqm_uvote.py`: the accepted forms in both printed forms of the destination, ten near misses that stay tier C, and a vertex and a pixel shader run on the wave interpreter as one wave of 64 lanes and as two of 32, equal and equal to the derived words with s4 = 9 and s4 = 1 (every lane covered there: the interpreters do not model a helper lane in a quad swap, so partial coverage rests on the argument above). GPU-checked by `ps_w64_a_wqm_uniform_vote` (`w64_graphics.py`: an if/else on a compare into VCC, the LLVM form through an SGPR pair and a loop closed by the vote, all under `s_wqm_b64 exec, exec`, EXEC put back before the export), which gives the words its header derives on an NVIDIA GeForce RTX 4070 Ti (Linux, driver 620.70.06, 32 only). That device has one subgroup size, so the 64-lane image was not drawn there and the full-screen draw has no partly covered quad; the run confirms the translated SPIR-V against the ISA reference, not native RDNA2 behaviour. | | GFX10.1 (console gfx1013) / GFX10.3 (gfx1030, gfx1036 oracle) opcode differences | Found by disassembling every opcode of every GFX10 encoding (SOP1/SOP2/SOPK/SOPC/SOPP, SMEM, VOP1/VOP2/VOPC/VOP3/VOP3P, DS, FLAT/GLOBAL/SCRATCH, MUBUF/MTBUF, MIMG) with LLVM 21 `llvm-mc` for `-mcpu=gfx1013` and for `gfx1030`/`gfx1036` (the two gfx103x lists are identical). Every other opcode slot decodes to the same mnemonic on both, so the hardware-oracle rows measured on gfx1036 are about the same instructions the console runs (the microarchitectures still differ, which no opcode table shows). **On gfx1013 only:** `v_mac_f32`/`v_mad_f32` (VOP2 0x1f, VOP3 0x11f/0x141) and `v_mac_legacy_f32`/`v_mad_legacy_f32` (VOP2 0x06, VOP3 0x106/0x140), translated (rows above; not measurable on gfx103x, where 0x06/0x106/0x140 are the fused `v_fmac_legacy_f32`/`v_fma_legacy_f32`); `v_mul_lo_i32` (VOP3 0x16b; `Unsupported` until #3504 translates it); `s_get_waveid_in_workgroup` (SMEM 0x2a), translated in compute and mesh shaders; scalar stores (`s_store_dword*`, `s_buffer_store_dword*`), scalar atomics (`s_atomic_*`, `s_buffer_atomic_*`, 32- and 64-bit), scalar scratch (`s_scratch_load/store_dword*`), `s_dcache_wb`, `s_dcache_discard(_x2)` and the 31 LDS `ds_*_src2_*` forms, all `Unsupported`. **On gfx103x only:** `v_dot2c_f32_f16`, `v_dot4c_i32_i8`, the VOP3P `v_dot2_f32_f16`, `v_dot2_i32_i16`/`u32_u16`, `v_dot4_i32_i8`/`u32_u8`, `v_dot8_i32_i4`/`u32_u4`, `v_fmac_legacy_f32`/`v_fma_legacy_f32`, `global_load/store_dword_addtid`, `global_atomic_csub`, `buffer_atomic_csub`. The console's code can't contain these; the translator handles the integer dot products (rows above, measured on gfx1036) and refuses the rest, so a listing disassembled for the wrong target (VOP2 0x06 printed as `v_fmac_legacy_f32`) fails loudly instead of being translated as a fused multiply-add. Not covered by the sweep: opcodes whose operand template did not decode on either target, and behaviour that differs without an opcode change. | -| Buffer bounds checking | MUBUF `buffer_load*`, `buffer_store*`, and `buffer_atomic*` enforce `num_records` (V# word 2). Out-of-bounds stores/atomics skip memory access completely and out-of-bounds loads return 0 without a load. **The RX 6800 measurement behind RAW loads** (`buffer_load_dword`/`x2`/`x3`/`x4`, stride 0, no `idxen`, OOB_SELECT 3; the per-mode rule below covers every mode, stride and `idxen`): the byte offset O = inst_offset + soffset + (offen ? vaddr : 0) is exact (nothing truncated, and the address keeps base & 3), and dword i is data when O + 4·i + 4 ≤ num_records, else 0, 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), for x1/x2/x4 with V# word3 0x31016fac (OOB_SELECT 3) at offsets 0..63 per lane, NUM_RECORDS 17..23 and 0x1000, base & 3 = 0 and 3: a dword at 0xf with NUM_RECORDS 18 is 0 (a start-only check reads it); x4 at 3 with 18 gives three data dwords and 0 for the fourth, which starts at 15 < 18 (so neither a whole-load nor a per-dword start check), and the zero is a whole 0, not partial bytes; x4 at offset:13 with 20 gives data, 0, 0, 0; inst_offset, soffset and offen are summed before the check; base & 3 = 3 flips at the same offsets. `x3` gets the rule without a measurement. **Per-mode check (V# OOB_SELECT, word3 bits [29:28])**, for every MUBUF/MTBUF access, as measured natively on RDNA2 (gfx1036, 732 cases, `docs/buffer_bounds.md`; Mesa's GFX11 column, not its GFX10 one). `idx` = `vindex` (0 without `idxen`), `off` = inst_offset + vaddr offset (offen), `offs` = `off` + soffset. A dword at byte 4·k of the access is out of range when: **0 STRUCTURED_WITH_OFFSET** `idx >= num_records` or `off + 4k + 4 > stride`; **1 STRUCTURED** `idx >= num_records` (no `idxen`: idx 0, so only `num_records == 0`); **2 DISABLED** `num_records == 0`; **3 RAW** `offs + 4k + 4 > num_records` (`idx * stride` is in the address, not in the check). A literal word3 (`s_mov_b32` earlier in the block) folds the mode, a run-time one selects with `OpSelect`. Multi-dword accesses, measured on the Radeon 880M (gfx1150, a valid proxy: gfx1036 follows the same column and gfx1150 matched it bit-exactly): in modes 0 and 3 **`buffer_load_dwordx2..x4` and `buffer_store_dwordx2..x4` are per dword**, for loads and stores alike (x4 at off 20 of 32 in RAW loads/stores 3 dwords, at 28 one, at 32 none; mode 0 likewise at the stride); modes 1 and 2 check once and always take the whole access. **A typed element (`buffer_load_format_*`, `buffer_store_format_*`) is all or nothing and ends at its format's size** (32_32_32_32 at off 20 of 32 reads or writes nothing), and an atomic checks its dword's end like a dword access. The translator does the same: per-dword guarded loads and stores for modes 0 and 3 (a store that straddled the edge used to write past it), the element size from the instruction's format, a literal word3 or the V#. The same oracle confirmed the terms (504 `buffer_load_dword` probes, idxen/offen/inst_offset/soffset at the stride and record edges, 0 disagreements): mode 0's `off` has `inst_offset` and no soffset, mode 1 reads nothing but the index, mode 3 adds inst_offset and soffset. `s_buffer_load` (SMEM) is separate: it keeps the `num_records` bound of the Scalar/buffer row and ignores OOB_SELECT (the same pattern for 0 to 3). **Swizzle**: SWIZZLE_ENABLE (V# word1 bit 31, Mesa `gfx10-rsrc.json` line 326; word1 [31:30] on GFX11, `gfx11-rsrc.json` line 259) and ADD_TID_ENABLE (word3 bit 23, line 337) change the address and the bounds in every mode and are modelled; see the Swizzled buffer addressing row. SWIZZLE_ENABLE and ADD_TID_ENABLE are modelled; see the Swizzled buffer addressing row. SWIZZLE_ENABLE (V# word1 bit 31, Mesa `gfx10-rsrc.json` line 326; word1 [31:30] on GFX11, `gfx11-rsrc.json` line 259) and ADD_TID_ENABLE (word3 bit 23, line 337) change the address and the bounds in every mode and are not modelled: a literal V# with either set is `Unsupported`, a run-time V# with them is translated unswizzled, which is silently wrong (known gap). Until 2026-11-22 the translator ignored OOB_SELECT and checked by stride alone (`offset < num_records`, `index < num_records`, or `offset < num_records * stride`): a V# with word3 = 0 (mode 0, stride 0) was fully readable and is now always out of range, as on hardware, so the test harnesses' output V# is `0x31016fac` now (`vk_compute_test`, the interpreter tests, `cs_bounds.asm`, `cs_fmt_1010102.asm`, `cs_store.asm`). **How confirmed**: the native RDNA2 measurement (gfx1036) and the gfx1150 oracle (RDNA3.5, same column); GPU test `cs_oob_select.asm` (every mode, literal and run-time V#, words derived from the rules) on an NVIDIA RTX 5070 and an AMD Radeon 880M, which checks the translation, not RDNA2; `tests/semantic/test_buffer_oob_select.py` (a hand-written table of 33 cases over the four modes, loads and stores, both V# forms, plus the multi-dword stores and typed elements); `cs_oob_tail.asm` pins the end-based edge, per-dword x4 loads and stores and the all-or-nothing element, where Mesa's GFX10 column gives other words. **RDNA1 (gfx1011, Navi 12) follows the same RDNA2/GFX11 column**: `tools/buffer_bounds_probe.py` ran 12 one-lane 4-byte `buffer_load_dword` cases at wave32 and wave64 through `tools/hw_oracle` (24 groups, 0 wave32/64 differences); all matched the measured column and 8 disagreed with Mesa's GFX10 column (SHADER-341, results in `docs/buffer_bounds.md`). **Unmeasured**: gfx1013/GFX10.1 itself (see `docs/buffer_bounds.md`), swizzle, unaligned addresses, and the mode 1/2 boundary of `buffer_load_dwordx2..x4` on RDNA2 hardware proper (the gfx1150 proxy shows all dwords in). Checked by `tests/semantic/test_value_semantics.py` (`RawBufferTailBounds`: the RX 6800 rows, values and the addresses loaded) and the GPU tests `runtime/test/shaders/cs_bounds.asm` (AMD Radeon RX 9070 XT, RX 6800), `cs_buf_tail.asm` (RX 6800, Vulkan, driver 26.11.2; aligned offsets only, since the translator's `Aligned 4` loads at byte-exact addresses were not checked on a Vulkan driver) `cs_oob_select.asm` and `cs_oob_tail.asm`. `cs_fmt_xy_xyz.asm` shows the whole element deciding for `_xy` and `_xyz` too, measured natively on a Radeon 680M (gfx1035, RDNA2): components that end inside num_records, in an element that doesn't, read 0 and store nothing. | +| Buffer bounds checking | MUBUF `buffer_load*`, `buffer_store*`, and `buffer_atomic*` enforce `num_records` (V# word 2). Out-of-bounds stores/atomics skip memory access completely and out-of-bounds loads return 0 without a load. **The RX 6800 measurement behind RAW loads** (`buffer_load_dword`/`x2`/`x3`/`x4`, stride 0, no `idxen`, OOB_SELECT 3; the per-mode rule below covers every mode, stride and `idxen`): the byte offset O = inst_offset + soffset + (offen ? vaddr : 0) is exact (nothing truncated, and the address keeps base & 3), and dword i is data when O + 4·i + 4 ≤ num_records, else 0, 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), for x1/x2/x4 with V# word3 0x31016fac (OOB_SELECT 3) at offsets 0..63 per lane, NUM_RECORDS 17..23 and 0x1000, base & 3 = 0 and 3: a dword at 0xf with NUM_RECORDS 18 is 0 (a start-only check reads it); x4 at 3 with 18 gives three data dwords and 0 for the fourth, which starts at 15 < 18 (so neither a whole-load nor a per-dword start check), and the zero is a whole 0, not partial bytes; x4 at offset:13 with 20 gives data, 0, 0, 0; inst_offset, soffset and offen are summed before the check; base & 3 = 3 flips at the same offsets. `x3` gets the rule without a measurement. **Per-mode check (V# OOB_SELECT, word3 bits [29:28])**, for every MUBUF/MTBUF access, as measured natively on RDNA2 (gfx1036, 732 cases, `docs/buffer_bounds.md`; Mesa's GFX11 column, not its GFX10 one). `idx` = `vindex` (0 without `idxen`), `off` = inst_offset + vaddr offset (offen), `offs` = `off` + soffset. A dword at byte 4·k of the access is out of range when: **0 STRUCTURED_WITH_OFFSET** `idx >= num_records` or `off + 4k + 4 > stride`; **1 STRUCTURED** `idx >= num_records` (no `idxen`: idx 0, so only `num_records == 0`); **2 DISABLED** `num_records == 0`; **3 RAW** `offs + 4k + 4 > num_records` (`idx * stride` is in the address, not in the check). A literal word3 (`s_mov_b32` earlier in the block) folds the mode, a run-time one selects with `OpSelect`. Multi-dword accesses, measured on the Radeon 880M (gfx1150, a valid proxy: gfx1036 follows the same column and gfx1150 matched it bit-exactly): in modes 0 and 3 **`buffer_load_dwordx2..x4` and `buffer_store_dwordx2..x4` are per dword**, for loads and stores alike (x4 at off 20 of 32 in RAW loads/stores 3 dwords, at 28 one, at 32 none; mode 0 likewise at the stride); modes 1 and 2 check once and always take the whole access. **A typed element (`buffer_load_format_*`, `buffer_store_format_*`) is all or nothing and ends at its format's size** (32_32_32_32 at off 20 of 32 reads or writes nothing), and an atomic checks its dword's end like a dword access. The translator does the same: per-dword guarded loads and stores for modes 0 and 3 (a store that straddled the edge used to write past it), the element size from the instruction's format, a literal word3 or the V#. The same oracle confirmed the terms (504 `buffer_load_dword` probes, idxen/offen/inst_offset/soffset at the stride and record edges, 0 disagreements): mode 0's `off` has `inst_offset` and no soffset, mode 1 reads nothing but the index, mode 3 adds inst_offset and soffset. **Offsets that do not fit 32 bits**: the hardware adds `idx * stride` (a full product) and soffset to the 48-bit base without wrapping, so `idx` 0xFFFFFFFF with a 20-byte stride lands tens of GiB past the base and has no effect, where a 32-bit offset would turn it into base − 20, inside a view that covers a whole pool (mode 3 does not check the index, mode 2 checks nothing). The translator forms `off + soffset + idx * stride` (and the swizzled offset) in 64 bits as well and treats a value above 0xFFFFFFFF as out of range in every mode; literal modes 0 and 1 without soffset skip it, their index check already bounds the product. Rule and hardware observation from five-star-recomp (ThatRecompDev, GPL-3, commit `b9b57e2`), not measured by us; CPU-checked by `tests/semantic/test_buffer_offset_wrap.py` (raw and disabled, literal and run-time V#, index −1 and off 0xFFFFFFF0 + soffset 0x20; each fails with 32-bit arithmetic). Until 2026-11-24 the offset was 32-bit. `s_buffer_load` (SMEM) is separate: it keeps the `num_records` bound of the Scalar/buffer row and ignores OOB_SELECT (the same pattern for 0 to 3). **Swizzle**: SWIZZLE_ENABLE (V# word1 bit 31, Mesa `gfx10-rsrc.json` line 326; word1 [31:30] on GFX11, `gfx11-rsrc.json` line 259) and ADD_TID_ENABLE (word3 bit 23, line 337) change the address and the bounds in every mode and are modelled; see the Swizzled buffer addressing row. SWIZZLE_ENABLE and ADD_TID_ENABLE are modelled; see the Swizzled buffer addressing row. SWIZZLE_ENABLE (V# word1 bit 31, Mesa `gfx10-rsrc.json` line 326; word1 [31:30] on GFX11, `gfx11-rsrc.json` line 259) and ADD_TID_ENABLE (word3 bit 23, line 337) change the address and the bounds in every mode and are not modelled: a literal V# with either set is `Unsupported`, a run-time V# with them is translated unswizzled, which is silently wrong (known gap). Until 2026-11-22 the translator ignored OOB_SELECT and checked by stride alone (`offset < num_records`, `index < num_records`, or `offset < num_records * stride`): a V# with word3 = 0 (mode 0, stride 0) was fully readable and is now always out of range, as on hardware, so the test harnesses' output V# is `0x31016fac` now (`vk_compute_test`, the interpreter tests, `cs_bounds.asm`, `cs_fmt_1010102.asm`, `cs_store.asm`). **How confirmed**: the native RDNA2 measurement (gfx1036) and the gfx1150 oracle (RDNA3.5, same column); GPU test `cs_oob_select.asm` (every mode, literal and run-time V#, words derived from the rules) on an NVIDIA RTX 5070 and an AMD Radeon 880M, which checks the translation, not RDNA2; `tests/semantic/test_buffer_oob_select.py` (a hand-written table of 33 cases over the four modes, loads and stores, both V# forms, plus the multi-dword stores and typed elements); `cs_oob_tail.asm` pins the end-based edge, per-dword x4 loads and stores and the all-or-nothing element, where Mesa's GFX10 column gives other words. **RDNA1 (gfx1011, Navi 12) follows the same RDNA2/GFX11 column**: `tools/buffer_bounds_probe.py` ran 12 one-lane 4-byte `buffer_load_dword` cases at wave32 and wave64 through `tools/hw_oracle` (24 groups, 0 wave32/64 differences); all matched the measured column and 8 disagreed with Mesa's GFX10 column (SHADER-341, results in `docs/buffer_bounds.md`). **Unmeasured**: gfx1013/GFX10.1 itself (see `docs/buffer_bounds.md`), swizzle, unaligned addresses, and the mode 1/2 boundary of `buffer_load_dwordx2..x4` on RDNA2 hardware proper (the gfx1150 proxy shows all dwords in). Checked by `tests/semantic/test_value_semantics.py` (`RawBufferTailBounds`: the RX 6800 rows, values and the addresses loaded) and the GPU tests `runtime/test/shaders/cs_bounds.asm` (AMD Radeon RX 9070 XT, RX 6800), `cs_buf_tail.asm` (RX 6800, Vulkan, driver 26.11.2; aligned offsets only, since the translator's `Aligned 4` loads at byte-exact addresses were not checked on a Vulkan driver) `cs_oob_select.asm` and `cs_oob_tail.asm`. `cs_fmt_xy_xyz.asm` shows the whole element deciding for `_xy` and `_xyz` too, measured natively on a Radeon 680M (gfx1035, RDNA2): components that end inside num_records, in an element that doesn't, read 0 and store nothing. | | 8/16-bit MUBUF d16 loads and stores | (The plain `buffer_load_{u,s}byte`/`{u,s}short` are `Gen.buffer_load_sub`'s; `tests/semantic/test_buffer_sub_dword.py` checks them too.) The `_d16` loads (`buffer_load_{u,s}byte_d16[_hi]`, `buffer_load_short_d16[_hi]`) write one 16-bit half of `vdata` (`_hi` the high one; a byte zero- or sign-extended to 16 bits) and keep the other. `buffer_store_byte`/`short` write the low 8/16 bits of `vdata` (the `_d16_hi` forms its high half). The address is `buffer_address`'s, and the bounds check covers the access's own size, 1 or 2 bytes, as for a typed element of that size (`elem="fmt"`, format 1 or 7). Out of range, a load gives 0 (in the half it writes, for d16; **not measured** for d16) and a store writes nothing. Each byte is its own access, so a 16-bit one that crosses a dword is exact; in a swizzled buffer the next dword is `step` bytes on. A store merges each byte into its dword with atomic and/or, as buffer byte format stores do. Inactive lanes neither load nor store, and the first-read analysis counts a d16 load's `vdata` as read. Until 2026-11-22 these ten raised `Unsupported`. CPU-checked by `tests/semantic/test_buffer_sub_dword.py` (every op at byte offsets 0 to 7, the edge of `num_records`, an inactive lane, rejected forms). GPU fixture `cs_w32_buffer_sub16` (the six d16 loads with their kept half and the sign extension, the two `_d16_hi` stores taking bits 23:16 / 31:16), passes on llvmpipe (Mesa 26.0.8) and on an NVIDIA RTX 5090 (595.99.02, @tylerstraub on #1864), all eight words; GPU fixture `cs_w32_buffer_store_sub` for the plain `buffer_store_byte`/`buffer_store_short` (Box16Rehydration's blocker, @YaBulochka on #1864), including a short at byte 3 that writes its high byte into the next dword, passes on llvmpipe with LLVM 21 and 23, and on an Apple M4 (MoltenVK 1.4.2) once the second dword of a 16-bit load is indexed from the first one's pointer instead of a second pointer converted from the same address, which Apple's compiler read as 0 (@sovljanskii on #1864). | | Swizzled buffer addressing (V# SWIZZLE_ENABLE, ADD_TID_ENABLE) | MUBUF/MTBUF `buffer_load*`, `buffer_store*`, `buffer_atomic*`, `buffer_load_format_*`/`buffer_store_format_*` and `tbuffer_load/store_format_*` follow the rules measured natively on RDNA2 (`AMD Radeon(TM) Graphics`, gfx1036, Windows driver `32.0.21042.62`, wave32 and wave64; `tools/buffer_swizzle_probe.py`, SHADER-343). MUBUF/MTBUF `buffer_load*`, `buffer_store*`, `buffer_atomic*`, `buffer_load_format_*`/`buffer_store_format_*` and `tbuffer_load_format_*` follow the RDNA2 ISA ("RDNA 2" Instruction Set Architecture, 8.1.5 Buffer Addressing, "Swizzled Buffer Addressing" and tables 33, 35 and 37). Fields, Mesa 24.0.6 `src/amd/registers/gfx10-rsrc.json` (`SQ_BUF_RSRC_WORD1`, `SQ_BUF_RSRC_WORD3` and its `_gfx103` twin, the same bits): `SWIZZLE_ENABLE` word1 bit 31, `STRIDE` word1 `[29:16]`, `INDEX_STRIDE` word3 `[22:21]` (`IS = 8 << n`, i.e., 8, 16, 32 or 64), `ADD_TID_ENABLE` word3 bit 23; element size is fixed at 4 bytes (`word3[20:19]` and `word1[30]` do not alter addressing or stepping). **Effective index:** `index = idxen ? vindex : 0)`, where `lane` is the wave lane (`thread_id[5:0]` within the wave, wrapping at 32 in wave32 and 64 in wave64; `Gen.wave_lane`); **`idxen = 1` completely ignores `ADD_TID_ENABLE`** (linear or swizzled, address and bounds, loads/stores/typed/atomics). **Activation:** `SWIZZLE_ENABLE` activates (`swz_active`) only when `idxen = 1` or `ADD_TID_ENABLE = 1`; with neither, addressing is linear (`base + soffset + off`) and `OOB_SELECT 3` stays RAW even when `stride ≠ 0`. **Address formula (when `swz_active`):** `off = uint32((offen ? vaddr : 0) + inst_offset)` (32-bit wrap), `buffer_offset = (index / IS · stride + (off & ~3)) · IS + (index % IS) · 4 + (off & 3)`, `address = base + soffset + buffer_offset` (confirmed byte-exact for IS 8/16/32/64, non-4-multiple strides, stride 0, and unaligned offsets). **Two swizzle sub-modes:** (1) **Scratch swizzle** (`SWIZZLE_ENABLE = 1`, `idxen = 0`, `ADD_TID_ENABLE = 1`): raw multi-dword `buffer_load/store_dwordx2..x4` step by **`+4 · IS`** bytes per dword (and unaligned 4-byte raw accesses crossing a dword boundary split across `+4 · IS` on hardware), while **typed formats > 4 bytes** (8/12/16-byte MUBUF and MTBUF loads/stores, regardless of component count) and **8-byte `buffer_atomic_*_x2`** are **suppressed** (loads return 0, stores/atomics are no-ops, even in `OOB_SELECT 2`); typed formats ≤ 4 bytes work normally. (2) **Indexed swizzle** (`SWIZZLE_ENABLE = 1`, `idxen = 1`, regardless of `ADD_TID_ENABLE`): raw `x2..x4`, typed formats (8/12/16 bytes), and `buffer_atomic_*_x2` step **linearly by `+4` bytes** from the swizzled base address, even across `IS` boundaries, and typed formats > 4 bytes execute normally. **Bounds (`OOB_SELECT`):** modes 0, 1 and 2 follow the Buffer bounds checking row with `idx = index`; **`OOB_SELECT 3` with `swz_active` and `stride ≠ 0`** checks **`uint64(index) + uint64(soffset) >= num_records` or `off + payload > stride`** (per-dword for raw `x1..x4`, whole element for typed), while inactive swizzle or `stride = 0` keeps the RAW check `uint64(off) + uint64(soffset) + payload > num_records` (no 32-bit wrap on `off + soffset`, whereas `vaddr + inst_offset` wraps at 32 bits before bounds checking). A literal word1 / word3 (`s_mov_b32` earlier in the block) folds each bit; a run-time V# selects dynamically with `L = swz_u · (3 + INDEX_STRIDE)` (IS = 1 gives the linear address). Until 2026-11-22 the translator added `vindex + lane` when `idxen = 1` and `ADD_TID_ENABLE = 1`, swizzled even when both were 0, stepped all swizzled multi-dword/typed accesses by `4 · IS`, allowed > 4-byte typed/atomic_x2 accesses in scratch-swizzle mode, omitted `soffset` from swizzled mode 3's index check, and wrapped `off + soffset` at 32 bits in RAW mode 3. **How confirmed:** native RDNA2 measurement on `AMD Radeon(TM) Graphics` (gfx1036, Windows driver `32.0.21042.62`, wave32 & wave64) via `tools/buffer_swizzle_probe.py --oracle both` (22/22 cases across 8 groups match bit-exactly, 0 unexpected mismatches, 0 unexpected wave32/64 diffs, 64-thread `ADD_TID_ENABLE` wave-lane wrap verified at both wave sizes); CPU semantic tests `tests/semantic/test_buffer_swizzle.py` (literal and run-time V#, both sub-modes, mode 3 `soffset`, 32-bit wrap, typed/`atomic_x2` suppression, and `cs_buf_swizzle.asm`); `tests/test_buffer_swizzle_probe.py`. **Remaining approximations / unmeasured:** unaligned raw accesses splitting across `+4 · IS` in scratch-swizzle mode (the translator uses `Aligned 4` PSB loads/stores), general typed-format / `buffer_atomic_*_x2` natural alignment suppression (`16_UINT` at odd offsets, `32_*` at non-4B offsets, `atomic_*_x2` at non-8B addresses, observed on gfx1036 in both linear and swizzled modes), and GFX11's two-bit `SWIZZLE_ENABLE` (`word1[31:30]`). SWIZZLE_ENABLE word1 bit 31, STRIDE word1 [29:16], INDEX_STRIDE word3 [22:21] (IS = 8, 16, 32 or 64 indices), ADD_TID_ENABLE word3 bit 23; there is no ELEMENT_SIZE field, the element is fixed at 4 bytes (ISA 8.1.5; LLVM `SIInstrInfo::getScratchRsrcWords23` sets it only up to GFX8). `index` = (idxen ? vindex : 0) + (ADD_TID_ENABLE ? lane : 0), where the lane is thread_id[5:0] within the wave (`Gen.wave_lane`), swizzled or not: table 33 adds the thread id with no swizzle condition and table 36's ring column is linear with add_tid. `offset` = (offen ? vaddr : 0) + inst_offset, without soffset. Swizzled: buffer_offset = (index / IS · stride + offset / 4 · 4) · IS + index % IS · 4 + offset % 4, address = base + soffset + buffer_offset, so dword k of a multi-dword access (and of a typed element over 4 bytes) is 4 · IS bytes after dword k − 1, not 4. Bounds as in Buffer bounds checking, with `idx` = `index` (the lane included), except that OOB_SELECT 3 with SWIZZLE_ENABLE and stride ≠ 0 checks `index >= num_records` or `off + 4k + 4 > stride` (table 35), like mode 0; stride 0 keeps the raw check. A literal word1 / word3 (`s_mov_b32` earlier in the block) folds each bit. A run-time word1 makes IS = 2^(SWIZZLE_ENABLE · (3 + INDEX_STRIDE)): IS = 1 is the linear address, so one formula serves both and nothing is selected but the mode 3 check; a run-time word3 multiplies the lane by ADD_TID_ENABLE. Cost, measured on the 116 shaders of `runtime/test/shaders` that both versions translate (all `spirv-val` clean before and after): the 56 with a MUBUF access through a run-time V# grow by 15.1 % in SPIR-V lines (+10.4 % over all 116), 30 to 45 instructions per access (address, lane, 4 per extra dword, a select per dword of the bounds check); a literal linear V# gives the same SPIR-V as before. Outside compute and mesh shaders the lane is `SubgroupLocalInvocationId`, so a VS, PS or GS with a run-time V# now declares `GroupNonUniform`. The offset arithmetic is 32-bit, like the linear address. Until 2026-11-22 a literal V# with either bit was `Unsupported` and a run-time one was translated unswizzled. **How confirmed**: Mesa/LLVM and AMD's ISA reference (fields and formula), not measured on hardware; `tests/semantic/test_buffer_swizzle.py` (hand-worked addresses for IS 8/16/64, index msb/lsb, soffset after the swizzle, the mode 3 rule with and without a stride, per-dword x2/x3/x4 loads and stores, a 16-byte typed element, ADD_TID on lane 5 linear and swizzled, each with a literal and a run-time V#); GPU test `runtime/test/shaders/cs_buf_swizzle.asm` (check.py, `scripts/run_gpu_tests.py`), which checks the translation, not RDNA2. **Unmeasured**: the swizzled layout on RDNA2 hardware, offsets that are not dword aligned (the ISA requires alignment for swizzled accesses; the translation adds offset % 4), wrap of the 32-bit offset, and GFX11's two-bit SWIZZLE_ENABLE (word1 [31:30]). **Unmeasured** (the layout itself is measured: `docs/shader_validation.md`, SHADER-343, gfx1036, 22 of 22 cases bit-exact): offsets that are not dword aligned (the ISA requires alignment for swizzled accesses; the translation adds offset % 4), wrap of the 32-bit offset, and GFX11's two-bit SWIZZLE_ENABLE (word1 [31:30]). In the corpus `SCRATCH_EN` is 0 in every CS, so a swizzled V# can only come from a descriptor the game writes itself. | | `v_permlane16_b32` / `v_permlanex16_b32` with the source lane off in EXEC (SHADER-74) | The VOP3 modifier `op_sel:[FI, BOUND_CTRL]` decides what a lane gets when the lane it reads is off in EXEC. **FI=1** (`op_sel` bit 0, encoding 0x0800): the source lane's value, as before. **FI=0** (the default): the destination lane is not written and keeps its old value when BOUND_CTRL=0, and gets 0 when BOUND_CTRL=1 (`op_sel` bit 1, 0x1000). A source lane that is on gives its value whatever FI / BOUND_CTRL are, and a lane that is itself off is never written (normal EXEC rule). The translator shuffles the active bit with the same selector as the value (also in `--wave64-emulate`, where it is a second exchange). On a native subgroup the two shuffles are combined with bitwise masks, not a scalar select: absent source lanes are redirected to the calling lane first (as `ds_lane_read`), the value and the activity bit are fetched through the redirected index, and `ok` masks the shuffled value over the old one (over zero with BOUND_CTRL=1) and the destination write is masked too, so the ballot and both shuffles run before lane predication — MoltenVK 1.4.2 and MoltenVK main at SPIRV-Cross aa217aeb lowered the scalar select to a short-circuiting Metal ternary and the FI=0 lanes read the source lane's value instead, which `cs_w32_permlane_fi` caught on an Apple M1 Max (#5895); `v_permlanex16_b32` pairs the rows 0↔1 and 2↔3 of a wave64 as before. Until SHADER-74 every case returned the source value (right only for FI=1). Source of the bit mapping: LLVM `llvm.amdgcn.permlane16/permlanex16 ` (IntrinsicsAMDGPU.td) is selected in `VOP3Instructions.td` (`PermlanePat`) with `fi` as the `src0` op_sel bit and `bound_control` as the `src1` one, and the CodeGen tests `llvm.amdgcn.permlane.ll` print `op_sel:[1,0]` for FI and `op_sel:[0,1]` for BOUND_CTRL; `llvm-mc -mcpu=gfx1013` encodes `op_sel:[1,0]` as 0x0800 and `op_sel:[0,1]` as 0x1000 in the second byte pair of the first word (0xD777 / 0xD778). Behaviour: hardware measurement on RDNA2 (Ryzen 7950X3D iGPU, raw kernel, wave64 and wave32 consistent; the same on RDNA3.5) by aslan2142 in [#374](https://github.com/ItsNotRexed/Leonida/issues/374#issuecomment-7071597516). Pinned by `runtime/test/shaders/cs_w32_permlane_fi.asm` (EXEC 0x55555555, every active lane's source is off; out[0..7] = 1000 0 4 1 1000 0 52 49) in `check.py` and `scripts/run_gpu_tests.py`, and on the CPU by `tests/semantic/test_permlane_fi.py`. | diff --git a/docs/gameinput.md b/docs/gameinput.md index 06c2013a5d..1301a4a49f 100644 --- a/docs/gameinput.md +++ b/docs/gameinput.md @@ -113,7 +113,8 @@ The title reads gamepads only, so keyboard input has to arrive as a gamepad. Wit shim attaches one SDL virtual gamepad named `Keyboard pad (Leonida)` and presses its buttons from the keyboard on every poll. It then goes through the same path as a real pad: a device object, the next free player slot, readings, reading and device callbacks, and UI navigation derived from its buttons. It reports no rumble motors. It is off by -default. +default. If SDL fails to attach or open the keyboard pad, the shim retries after one second while the pad is +enabled. Only the first failure in a continuous series is logged; turning the pad off and back on retries immediately. | key | button | |---|---| diff --git a/docs/shader_library.md b/docs/shader_library.md index 8cf131ca48..41cea06857 100644 --- a/docs/shader_library.md +++ b/docs/shader_library.md @@ -178,7 +178,7 @@ them and the state key is the record's state blob. The step is redone as a whole `llvm-mc`, the wave64 mode or the flags change (`library_build.json`, written last), and a clash of both keys between different modules fails it, as for the FSPX step. Graphics pipelines are not translated by the build. -### Resuming a compute-only batch on Linux +### Resuming a compute-only batch on Linux or native Windows Run `tools/shader_library.py` with `--stages cs --disasm --jobs 2` and the carved containers, or select the kind-6 hashes with `--compute-hashes`. For an unpacked library with its input `index.json`, use the compute batch. @@ -187,14 +187,27 @@ kind-6 hashes with `--compute-hashes`. For an unpacked library with its input `i python3 -I scripts/translate_pipeline_compute.py /path/to/unpacked --out /path/to/spirv/library --wave64-emulate ``` -Use a dedicated output folder. The two workers run at nice 19. Each has a 768 MiB address-space limit and uses one -SPIRV-Tools process at a time (four processes total). `--jobs 1` uses a single worker and `--memory-mib` changes -the per-process limit. A rerun checks each module against its checksum and the listing, source container, FSPX +Use a dedicated output folder and a stable, trusted SPIRV-Tools installation on PATH. On Linux the two workers +run at nice 19. Each has a 768 MiB address-space limit and uses one SPIRV-Tools process at a time (four processes +total). On native Windows CPython, a BelowNormal coordinator and up to two gated workers run with a 768 MiB +**committed memory** cap per process (not total virtual address space). Each worker's kill-on-close Job permits +only itself and one tool process. The parent verifies job membership before sending work; the child rechecks the +effective limits. A no-share file open keeps the pack exclusive through worker exit. An incompatible outer Job +or a failed limit/lock check stops the build; there is no unbounded Windows mode. A hard stop can leave temporary +scratch files, but cannot partially replace the index. `--jobs 1` uses a single translating worker and +`--memory-mib` changes the per-process limit. A rerun checks each module against its checksum and the listing, source container, FSPX sidecars, toolchain and wave mode. It retries failures. Only validated modules enter the runtime index. Its atomic replacement follows both workers, so an interrupted run leaves the previous index readable. A partial run exits nonzero and writes the reasons to `failures.json`, keyed by kind-6 and kind-0 SHA-256. Old modules can still be used by a runtime that already opened the preceding index. +The coordinator and each shard explicitly apply `--wave64-emulate`, `--loop-limit`, `--descriptor-hash` and +`--compact-spirv`; requesting compaction requires both translator support and `spirv-opt`. The cache key includes +those settings, compiler sources, builder and tool hashes. `.compute-cache/worker-receipt.json` records the exact +options and input-name digest for each shard; compare its `index_sha256` with the actual published index before +using it. This is an audit file, not a completion marker. A pre-upgrade cache key is not reused as evidence for +a new builder. + Among 2,680 compute programs, 46 start with two 12-byte literal-bearing VOP3 NOP hash carriers. Their body starts at byte 24. The three-record form starts at byte 36. The no-op measurements are in `docs/fspx.md`. A hash literal can resemble an instruction. `shader_library.py` excludes both complete carrier records before diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 5a32f794ca..be29643aec 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -790,6 +790,17 @@ if(BUILD_TESTING) add_executable(pipeline_cache_store_test test/pipeline_cache_store_test.cpp) add_test(NAME pipeline_cache_store COMMAND pipeline_cache_store_test) + # The per-pipeline journal files compute pipelines are kept in: naming, header check, atomic replacement. + add_executable(pipeline_cache_journal_test test/pipeline_cache_journal_test.cpp) + add_test(NAME pipeline_cache_journal COMMAND pipeline_cache_journal_test) + + # The compile helper's request files and building markers (shims/d3d12_compile_helper.h): Win32 file calls only. + if(WIN32) + add_executable(compile_helper_test test/compile_helper_test.cpp) + target_compile_definitions(compile_helper_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + add_test(NAME compile_helper COMMAND compile_helper_test) + endif() + add_executable(xdxr_build_output_test test/xdxr_build_output_test.cpp) add_test(NAME xdxr_build_output COMMAND xdxr_build_output_test) @@ -1677,6 +1688,12 @@ if(BUILD_TESTING) target_compile_options(active_input_test PRIVATE /W4 /permissive- /utf-8) endif() add_test(NAME active_input COMMAND active_input_test) + # The same keyboard connection lifecycle as the shim, with a fake clock and virtual-device backend only. + add_executable(keyboard_pad_retry_test test/keyboard_pad_retry_test.cpp) + if(MSVC) + target_compile_options(keyboard_pad_retry_test PRIVATE /W4 /permissive- /utf-8) + endif() + add_test(NAME keyboard_pad_retry COMMAND keyboard_pad_retry_test) if(WIN32 AND TARGET gameinput_no_sdl_test) add_test(NAME gameinput_no_sdl COMMAND gameinput_no_sdl_test) # LEONIDA_INPUT_SCRIPT without SDL3: the scripted pad, its device callbacks and its readings on a fake clock. @@ -1845,10 +1862,21 @@ if(TARGET Vulkan::Headers) add_executable(vulkan_device_fault_test test/vulkan_device_fault_test.cpp) target_link_libraries(vulkan_device_fault_test PRIVATE Vulkan::Headers) add_test(NAME vulkan_device_fault COMMAND vulkan_device_fault_test) + # The submit lock's owner tracking, waiter count, submit handoff and compile gate (SubmitMutex), on the CPU. + if(WIN32) + add_executable(submit_mutex_test test/submit_mutex_test.cpp) + target_link_libraries(submit_mutex_test PRIVATE Vulkan::Headers) + target_compile_definitions(submit_mutex_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + if(MSVC) + target_compile_options(submit_mutex_test PRIVATE /W4 /permissive- /utf-8) + endif() + add_test(NAME submit_mutex COMMAND submit_mutex_test) + set_tests_properties(submit_mutex PROPERTIES TIMEOUT 60) + endif() foreach(tool vk_harness vk_ps_sweep vk_texture_test vk_sampler_test vk_compute_test vk_store_test vk_pipeline_check vk_command_replay_test vk_bindless_test vk_image_fuzz vk_descriptor_bench depth24_convert_test vk_predicate_capture_test vk_predicated_copy_test - vk_xdxr_build_test vk_queue_test vk_sandbox) + vk_xdxr_build_test vk_queue_test vk_sandbox vk_console_heap_gpu_test) add_executable(${tool} test/${tool}.cpp) target_link_libraries(${tool} PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) if(WIN32) @@ -1936,7 +1964,7 @@ if(TARGET Vulkan::Headers) # Self-checking Vulkan tests with no shaders or game data; each exits 77 without a Vulkan device (TEST-514). # indirect_clamp is registered next to its own add_executable above, where tests/test_ctest_registration.py # can see it. - foreach(test vk_command_replay vk_predicated_copy vk_predicate_capture vk_queue) + foreach(test vk_command_replay vk_predicated_copy vk_predicate_capture vk_queue vk_console_heap_gpu) add_test(NAME ${test} COMMAND ${test}_test) set_tests_properties(${test} PROPERTIES SKIP_RETURN_CODE 77) endforeach() @@ -1969,6 +1997,23 @@ 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() + # 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) + target_link_libraries(vk_semaphore_lifetime_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) + if(WIN32) + target_compile_definitions(vk_semaphore_lifetime_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + else() + find_package(Threads REQUIRED) + target_link_libraries(vk_semaphore_lifetime_test PRIVATE Threads::Threads) + endif() + if(MSVC) + target_compile_options(vk_semaphore_lifetime_test PRIVATE /W4 /permissive- /utf-8) + endif() + if(BUILD_TESTING) + 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() # With LEONIDA_VK_VALIDATION=1: synchronization validation reports a missing barrier (and not a present one), so # the other GPU tests' "0 validation errors" was checked by an active layer. 77 without validation or a device. add_executable(vk_sync_validation_selftest test/vk_sync_validation_selftest.cpp) @@ -2193,13 +2238,14 @@ if(TARGET Vulkan::Headers) ENVIRONMENT "LEONIDA_VK_VALIDATION=1;VK_VALIDATE_SYNC=1") # VulkanPresenter tracker lock / failed-submit rollback and capture-buffer WAW synchronization. add_executable(vk_presenter_sync_test test/vk_presenter_sync_test.cpp) - target_link_libraries(vk_presenter_sync_test PRIVATE Vulkan::Headers user32) + target_link_libraries(vk_presenter_sync_test PRIVATE Vulkan::Headers user32 advapi32) target_compile_definitions(vk_presenter_sync_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) if(MSVC) target_compile_options(vk_presenter_sync_test PRIVATE /W4 /permissive- /utf-8) endif() add_test(NAME vk_presenter_sync COMMAND vk_presenter_sync_test) - set_tests_properties(vk_presenter_sync PROPERTIES SKIP_RETURN_CODE 77) + add_test(NAME vk_presenter_sparse_capture COMMAND vk_presenter_sync_test --sparse-capture) + set_tests_properties(vk_presenter_sync vk_presenter_sparse_capture PROPERTIES SKIP_RETURN_CODE 77) set(conformance_src ${CMAKE_CURRENT_SOURCE_DIR}/../tools/conformance/native/src) add_executable(vk_present_dump_test test/vk_present_dump_test.cpp ${conformance_src}/png_io.cpp ${conformance_src}/diagnostics.cpp) @@ -2829,6 +2875,23 @@ if(TARGET Vulkan::Headers) set_tests_properties(d3d12_indirect_group_budget PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_INDIRECT_GROUP_BUDGET=2") set_tests_properties(d3d12_indirect_dispatch_count PROPERTIES SKIP_RETURN_CODE 77) + + # A single ordinary compute PSO and direct dispatch for cold/warm production journal comparisons; + # only the authored two-counter shader is shared with the indirect test. + set(_journal_second_spv ${CMAKE_CURRENT_BINARY_DIR}/generated/cs_compute_journal_v2.spv) + add_custom_command(OUTPUT ${_journal_second_spv} + COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.2 -DTEST_COUNTER_TERM=2u + -o ${_journal_second_spv} ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_indirect_dispatch_count.comp + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_indirect_dispatch_count.comp + COMMENT "Compiling the second authored compute journal control" VERBATIM) + add_executable(d3d12_compute_journal_test test/d3d12_compute_journal_test.cpp + ${_indirect_count_spv} ${_journal_second_spv}) + target_link_libraries(d3d12_compute_journal_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_compute_journal_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_COUNTER_SPV="${_indirect_count_spv}" LEONIDA_TEST_COUNTER_V2_SPV="${_journal_second_spv}") + target_compile_options(d3d12_compute_journal_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_compute_journal COMMAND d3d12_compute_journal_test) + set_tests_properties(d3d12_compute_journal PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) endif() # The cache vk_pipeline_check saves has to hit on the runtime's device (docs/pipeline_check.md): the test @@ -3488,7 +3551,7 @@ if(TARGET Vulkan::Headers) target_compile_definitions(d3d12_unmapped_vsharp_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_VULKAN_DEVICE) target_compile_options(d3d12_unmapped_vsharp_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_unmapped_vsharp COMMAND d3d12_unmapped_vsharp_test) - set_tests_properties(d3d12_unmapped_vsharp PROPERTIES SKIP_RETURN_CODE 77) + set_tests_properties(d3d12_unmapped_vsharp PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_CONSOLE_FIX_US=0") add_executable(d3d12_indirect_zero_test test/d3d12_indirect_zero_test.cpp) target_link_libraries(d3d12_indirect_zero_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) target_compile_definitions(d3d12_indirect_zero_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) @@ -3640,6 +3703,15 @@ if(TARGET Vulkan::Headers) target_compile_options(d3d12_compile_teardown_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_compile_teardown COMMAND d3d12_compile_teardown_test) set_tests_properties(d3d12_compile_teardown PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 300) + # Bounded waits for pipelines still being built (src/pipeline_wait.h), with asynchronous builds and without. + add_executable(d3d12_pipeline_wait_test test/d3d12_pipeline_wait_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_TEST_CS}) + target_link_libraries(d3d12_pipeline_wait_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_pipeline_wait_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_CS_SPV="${LEONIDA_TEST_CS}") + target_compile_options(d3d12_pipeline_wait_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_pipeline_wait_async COMMAND d3d12_pipeline_wait_test async) + add_test(NAME d3d12_pipeline_wait_sync COMMAND d3d12_pipeline_wait_test sync) + set_tests_properties(d3d12_pipeline_wait_async d3d12_pipeline_wait_sync PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 300) # A buffer at the title's own VA (device slot 133) read by the same shader through a root view and a V#. add_executable(d3d12_title_va_test test/d3d12_title_va_test.cpp shims/d3d12_xs_device.cpp test/xmem_geometry_aliases_stub.cpp ${LEONIDA_TEST_CS}) diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 961514bcfb..8f6b1e031b 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -512,6 +512,15 @@ class GraphicsCommandList final blend_factor_ = value; } + // 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; + 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 (defer([=](GraphicsCommandList& l) { l.front_stencil_ref_ = l.back_stencil_ref_ = reference; })) return; @@ -569,6 +578,8 @@ class GraphicsCommandList final note_direct_heap_indexing(graphics_.layout); draw.mesh = true; draw.viewports = draw_viewports(); + draw.depth_bounds = depth_bounds_; + request_draw_pipeline(); check(list_.draw(std::move(draw))); } @@ -837,8 +848,7 @@ class GraphicsCommandList final d3d12_trace::record("ID3D12GraphicsCommandList::ClearRenderTargetView"); if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); if (!view.ptr || !color) return check(false); - // LOCAL DIAGNOSTIC: what the title clears, and with which colour - if (leonida::local_diagnostics()) { + if (leonida::fsdraw::enabled()) { // LOCAL DIAGNOSTIC: what the title clears, and with which colour static std::atomic clears{0}; const std::uint64_t n = ++clears; if (n <= 6 || n % 600 == 0) { @@ -1014,10 +1024,11 @@ class GraphicsCommandList final if (!leonida::indirect_records_fit(arg_desc.Width, argument_buffer_offset, max_command_count, stride, sig->packed_size())) return check(false); - if (kind == leonida::IndirectKind::dispatch_mesh) { - // Not replayed yet (#3777 replays it as vkCmdDrawMeshTasksIndirectEXT): nothing is recorded, and the - // first such call says so. The list stays valid. - leonida::indirect_stats::skip(leonida::indirect_stats::Event::record_skip, leonida::indirect_stats::mesh); + if (kind == leonida::IndirectKind::dispatch_mesh && !terminal_only) { + // A DISPATCH_MESH signature with root arguments before it is not replayed: nothing is recorded, and the + // first such call says so. The list stays valid. A terminal-only one is recorded below as a mesh draw + // (vkCmdDrawMeshTasksIndirect(Count)EXT). + leonida::indirect_stats::skip(leonida::indirect_stats::Event::record_skip, leonida::indirect_stats::compound); return; } if (!terminal_only && (kind == leonida::IndirectKind::draw || kind == leonida::IndirectKind::draw_indexed)) { @@ -1543,8 +1554,10 @@ class GraphicsCommandList final // 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 + } else { + if (descriptor_ring_diagnostics()) note_table_slots(va, p->table_descriptors); va = console_descriptor_table_va(va); + } 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); @@ -1571,6 +1584,9 @@ class GraphicsCommandList final ID3D12DescriptorHeap* sampler_heap_ = nullptr; D3D12_GPU_VIRTUAL_ADDRESS cbv_srv_uav_base_ = 0; D3D12_GPU_VIRTUAL_ADDRESS sampler_base_ = 0; + 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_{}; @@ -1595,6 +1611,7 @@ class GraphicsCommandList final bool draw_views_stale_ = true; leonida::TargetView depth_{}; std::array blend_factor_{1, 1, 1, 1}; + std::array depth_bounds_{0, 1}; // The root signatures and pipeline states this recording uses. D3D12 lets an application release them right // after Set*RootSignature / SetPipelineState; the list keeps them until Reset or its own release, so the root @@ -1642,6 +1659,7 @@ class GraphicsCommandList final hold(state); compute_pipeline_ = compute_pipeline_id(state); graphics_pipeline_ = graphics_pipeline_id(state); + if (compute_pipeline_) request_pipeline_build(compute_pipeline_, 0, false); // starts its build, if asynchronous // A pipeline this device never registered: a LEONIDA_STUB_PIPELINES stub (its translated shader is missing), // or one from another device. Its draws resolve to nothing in replay; its dispatches are no-ops too // (record_dispatch), so the list still closes. @@ -1656,6 +1674,81 @@ class GraphicsCommandList final cbv_srv_uav_base_ = cbv_base; sampler_heap_ = smp; sampler_base_ = smp_base; + 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; + } + } + + // note_table_slots runs on every descriptor-table bind of the title's recording threads, and takes a global lock + // whenever a list's mark rises (almost every bind of a ring): only with LEONIDA_DEVICE_FAULT=1 or + // LEONIDA_DESCRIPTOR_RING=1. + static bool descriptor_ring_diagnostics() { + static const bool on = [] { + char v[2]{}; + return (GetEnvironmentVariableA("LEONIDA_DEVICE_FAULT", v, 2) == 1 && (v[0] == '1' || v[0] == '2')) || + (GetEnvironmentVariableA("LEONIDA_DESCRIPTOR_RING", v, 2) == 1 && v[0] == '1'); + }(); + return on; + } + + // LOCAL DIAGNOSTIC (early device loss; VIctory 3827767, a title table ring past the slots the layer backs hung + // NVIDIA ~45 s in): the highest slot a descriptor table reaches in each bound heap, against the heap's slots. Logged + // when a heap's high-water mark passes another eighth of the heap, every new mark past its end, and the first + // tables that lie in no bound heap. A list only takes the shared lock when its own mark rises. + void note_table_slots(std::uint64_t va, std::uint32_t declared) { + if (!va) return; + D3D12_GPU_VIRTUAL_ADDRESS bases[3]{cbv_srv_uav_base_, sampler_base_, 0}; + std::uint64_t counts[3]{heap_slots_[0], heap_slots_[1], 0}; + int heap = -1; + for (int h = 0; h < 2; ++h) + if (bases[h] && counts[h] && va >= bases[h] && va < bases[h] + counts[h] * descriptor_size) + heap = h; + std::uint64_t console_bytes = 0; + if (heap < 0 && console_descriptor_heap_range(va, bases[2], console_bytes)) { + heap = 2; // a console descriptor heap (Xbox slot 14) in title memory, read from its arena copy + counts[2] = console_bytes / descriptor_size; + } + if (heap < 0) { + static std::atomic outside{0}; + if (outside.fetch_add(1) < 8) + std::fprintf(stderr, "[rt] descriptor-ring: table 0x%llx in no bound heap (view heap 0x%llx, %u slots; " + "sampler heap 0x%llx, %u slots)\n", + (unsigned long long)va, (unsigned long long)bases[0], heap_slots_[0], + (unsigned long long)bases[1], heap_slots_[1]); + return; + } + const std::uint64_t first = (va - bases[heap]) / descriptor_size; + const std::uint64_t end = first + (declared ? declared : 1); + if (heap == 2 && console_high_base_ != bases[2]) { + console_high_base_ = bases[2]; + table_high_[2] = 0; + } + if (end <= table_high_[heap]) return; + table_high_[heap] = end; + struct Mark { + std::uint64_t high = 0; + std::uint64_t logged = 0; + }; + static std::mutex mutex; + static std::map marks; // by heap base + std::lock_guard lock(mutex); + Mark& mark = marks[bases[heap]]; + if (end <= mark.high) return; + mark.high = end; + const std::uint64_t slots = counts[heap]; + const std::uint64_t step = (std::max)(slots / 8, std::uint64_t{1}); + if (end > slots || end >= mark.logged + step) { + mark.logged = end; + std::fprintf(stderr, "[rt] descriptor-ring: %s heap 0x%llx: highest slot %llu (table at %llu, %u declared) " + "of %llu backed%s\n", + heap == 2 ? "console" : heap ? "sampler" : "view", (unsigned long long)bases[heap], (unsigned long long)(end - 1), + (unsigned long long)first, declared, (unsigned long long)slots, + end > slots ? " -- PAST THE HEAP" : ""); + } } // D3D12 bundle rule: every non-null heap bound by a bundle's SetDescriptorHeaps must match the parent list's @@ -1673,19 +1766,25 @@ class GraphicsCommandList final void note_direct_heap_indexing(const RootArgumentLayout* layout) { if (!layout) return; + // Called at every draw and dispatch: each note has its own flag, so after its first time a site skips + // note_once's process-wide mutex, std::string and set lookup. + static std::atomic told[4]; + const auto once = [](int site, const char* what) { + if (!told[site].load(std::memory_order_relaxed) && !told[site].exchange(true)) note_once(what); + }; if (layout->flags & D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED) { if (!cbv_srv_uav_heap_) - note_once("draw/dispatch uses CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED with no CBV/SRV/UAV heap bound"); + once(0, "draw/dispatch uses CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED with no CBV/SRV/UAV heap bound"); else { remember_table(cbv_srv_uav_base_, cbv_srv_uav_heap_->GetDesc().NumDescriptors); - note_once("CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED heap base tracked on list"); + once(1, "CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED heap base tracked on list"); } } if (layout->flags & D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED) { if (!sampler_heap_) - note_once("draw/dispatch uses SAMPLER_HEAP_DIRECTLY_INDEXED with no sampler heap bound"); + once(2, "draw/dispatch uses SAMPLER_HEAP_DIRECTLY_INDEXED with no sampler heap bound"); else - note_once("SAMPLER_HEAP_DIRECTLY_INDEXED heap base tracked on list"); + once(3, "SAMPLER_HEAP_DIRECTLY_INDEXED heap base tracked on list"); } } @@ -1713,6 +1812,7 @@ class GraphicsCommandList final draw_views_stale_ = true; depth_ = {}; blend_factor_ = {1, 1, 1, 1}; + depth_bounds_ = {0, 1}; set_pipeline(state); } @@ -1840,9 +1940,12 @@ class GraphicsCommandList final } const std::uint32_t end = layout.graphics_arguments_end; if (end >= rt::rootsig::kMaxUserSgprs) { - note_once(layout.graphics_console - ? "graphics direct heaps: not supplied, the explicit arguments fill s8..s31" - : "graphics direct heaps: not supplied, the signature keeps the s0 graphics layout"); + static std::atomic told[2]; // per draw: the site's own flag before note_once's mutex + const int site = layout.graphics_console ? 0 : 1; + if (!told[site].load(std::memory_order_relaxed) && !told[site].exchange(true)) + note_once(layout.graphics_console + ? "graphics direct heaps: not supplied, the explicit arguments fill s8..s31" + : "graphics direct heaps: not supplied, the signature keeps the s0 graphics layout"); return graphics_.data; } static std::atomic logged{false}; @@ -1922,7 +2025,41 @@ class GraphicsCommandList final return draw_viewports_; } + // LEONIDA_ASYNC_PIPELINES=1: the variant this draw needs (by the targets it binds) starts building on the compile + // worker now, before the list is submitted (request_pipeline_build). + void request_draw_pipeline() const { + std::uint32_t bound = 0; + for (UINT slot = 0; slot < render_target_count_ && slot < render_targets_.size(); ++slot) + if (render_targets_[slot].resource) bound |= 1u << slot; + request_pipeline_build(graphics_pipeline_, bound, depth_.resource != 0); + } + + // One recorder for both entry points: the direct ExecuteIndirect call and a bundle call deferred into its + // parent list. A simple DRAW or DRAW_INDEXED signature becomes a stateful Draw (IndirectRasterDraw) carrying the + // graphics state frozen at the call; anything else stays a legacy ExecuteIndirect command. void record_indirect(leonida::IndirectKind kind, bool terminal_only, const leonida::IndirectDrawArgs& args) { + if (kind == leonida::IndirectKind::dispatch_mesh) { + // As DispatchMesh, with the group counts in the argument buffer: the replay draws the records with + // vkCmdDrawMeshTasksIndirect(Count)EXT after its clamp pass bounds them. + if (type_ != D3D12_COMMAND_LIST_TYPE_DIRECT) return check(false); + if (!args.max_count) return; + namespace stats = leonida::indirect_stats; + const auto skip = [](stats::Reason reason) { stats::skip(stats::Event::record_skip, reason); }; + if (indirect_draws_disabled()) return skip(stats::disabled); + if (!terminal_only) return skip(stats::compound); + if (!graphics_pipeline_) return skip(stats::pipeline); + if (!graphics_.layout) return skip(stats::root_layout); + if (!(viewport_.width > 0) || !(viewport_.height > 0)) return skip(stats::viewport); + leonida::Draw draw{graphics_pipeline_, graphics_user_data(), draw_views(), depth_, {}, 0, viewport_, + scissor_, blend_factor_, front_stencil_ref_, back_stencil_ref_, false, 0, 0, 0, 0, 0}; + note_direct_heap_indexing(graphics_.layout); + 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); + return check(recorded); + } if (kind == leonida::IndirectKind::draw || kind == leonida::IndirectKind::draw_indexed) { if (type_ != D3D12_COMMAND_LIST_TYPE_DIRECT) return check(false); // A valid zero-count call records nothing, even if graphics state has not been set. @@ -1973,8 +2110,12 @@ class GraphicsCommandList final note_direct_heap_indexing(graphics_.layout); // No viewport (never set, or unbound with RSSetViewports(0)) or every bound viewport empty: D3D12 rasterizes // nothing, and Vulkan forbids a 0x0 viewport, so the draw is not recorded. - // LOCAL DIAGNOSTIC: the state each draw is recorded with - if (leonida::local_diagnostics()) { + static const bool draw_diag = [] { + const char* value = std::getenv("LEONIDA_DRAW_DIAG"); + if (value) return std::strcmp(value, "0") != 0; + return leonida::local_diagnostics() || leonida::fsdraw::enabled(); + }(); + if (draw_diag) { static std::atomic draws{0}, skipped{0}; const bool skip = !any_nonempty_viewport(); const std::uint64_t n = ++draws, k = skip ? ++skipped : skipped.load(); @@ -1988,16 +2129,18 @@ class GraphicsCommandList final scissor_.left, scissor_.top, scissor_.right, scissor_.bottom, count, instances); // LOCAL DIAGNOSTIC (fsdraw): the first draw of each pipeline, and one frame's draws every ~300 frames, // with the pipeline's description, the root data and what the bound descriptor tables hold. + // Only with LEONIDA_FSDRAW_PROBE=1. static std::mutex seen_mutex; static std::set seen; - bool first_seen; - { + const bool fsdraw = leonida::fsdraw::enabled(); + bool first_seen = false; + if (fsdraw) { std::lock_guard lock(seen_mutex); first_seen = seen.insert(graphics_pipeline_).second; } const bool fullscreen = render_target_count_ >= 1 && count == 3 && viewport_.width >= 1000; if (fullscreen) leonida::fsdraw::note_target(render_targets_[0].resource); - if (first_seen || (n - 1) % 600 < 2 || (n > 2 && n < 9)) { + if (fsdraw && (first_seen || (n - 1) % 600 < 2 || (n > 2 && n < 9))) { std::fprintf(stderr, "[rt] fsdraw: draw #%llu pso %p%s rt0 0x%llx rts %u depth 0x%llx count %u x%u: %s\n", static_cast(n), reinterpret_cast(graphics_pipeline_), first_seen ? " (first use)" : "", static_cast(render_targets_[0].resource), @@ -2065,6 +2208,8 @@ class GraphicsCommandList final scissor_, blend_factor_, front_stencil_ref_, back_stencil_ref_, indexed, count, instances, first, base_vertex, first_instance}; 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); check(recorded); @@ -2147,6 +2292,11 @@ class Fence final return S_OK; } + // `fn` on the dispatcher's thread once the fence reaches `value` (rt::d3d12::fence_callback_at). + void callback_at(UINT64 value, std::function fn) { + context_.enqueue_fence_callback(fence_.semaphore(), value, std::move(fn)); + } + // Counts `waiter` down once this fence reaches `value`: now if it has, else via the centralized dispatcher. void notify(UINT64 value, std::shared_ptr waiter) { if (context_.is_device_lost() || fence_.completed() >= value) { @@ -2319,7 +2469,7 @@ 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() ? 0 : ++submits; + const std::uint64_t n = tables.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)); @@ -2377,6 +2527,10 @@ class CommandQueue final if (last_result_ != leonida::ReplayResult::success) std::fprintf(stderr, "[rt] d3d12: ExecuteCommandLists failed: %s; nothing was submitted\n", name(last_result_)); + // A batch or Signal that failed after its call returned (held, or on the queue's worker with + // LEONIDA_SUBMIT_ASYNC; reported on stderr there) is this call's result, one call late. + if (last_result_ == leonida::ReplayResult::success) + if (const auto held = queue_.take_held_failure(); held != leonida::ReplayResult::success) last_result_ = held; } // A copy list's timestamps go to COPY_QUEUE_TIMESTAMP heaps and every other list's to TIMESTAMP heaps. @@ -2803,6 +2957,13 @@ bool command_signature_info(ID3D12CommandSignature* signature, leonida::Indirect return true; } +bool fence_callback_at(ID3D12Fence* fence, std::uint64_t value, std::function fn) { + Fence* f = Fence::from(fence); + if (!f) return false; + f->callback_at(value, std::move(fn)); + return 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 849791a262..0b6b9a6ffb 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -101,6 +101,9 @@ struct VulkanDeviceInfo { std::vector compute_queues; std::vector copy_queues; 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. + bool pipeline_cache_control = false; bool device_fault_diagnostics = false; bool device_fault_info = false; bool device_checkpoints = false; @@ -276,6 +279,11 @@ HRESULT create_console_descriptor_heap(ID3D12Device* device, const D3D12_DESCRIP D3D12_GPU_VIRTUAL_ADDRESS console_address, std::uint64_t console_size, REFIID riid, void** out); +// Calls `fn` on the device's fence-wait thread once `fence` (a fence of such a device) reaches `value` (at once on that +// thread if it has). Released or device lost, `fn` still runs once: it must not use the fence then. False for a fence +// 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); + // 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#. @@ -518,6 +526,14 @@ struct RootArgumentLayout { const RootArgumentLayout* root_signature_layout(ID3D12RootSignature* signature); std::uintptr_t compute_pipeline_id(ID3D12PipelineState* pipeline); std::uintptr_t graphics_pipeline_id(ID3D12PipelineState* pipeline); +// Record time, for LEONIDA_ASYNC_PIPELINES=1: starts the pipeline's build on the compile worker before the list is +// submitted, without waiting (src/pipeline_wait.h). `id` is what compute_pipeline_id or graphics_pipeline_id gave (0: +// nothing). Compute: at SetPipelineState; graphics: at each draw, with the render-target slots it binds (bit per slot) +// and whether it binds a depth buffer. +void request_pipeline_build(std::uintptr_t id, std::uint32_t bound_targets, bool depth_bound); +// Tests: `hook` runs on the thread that builds a pipeline for replay (the compile worker, or a submitting thread +// building in place), with the PSO, before the driver is called; a hook that blocks holds that build in flight. +void set_pipeline_build_hook(std::function hook); // What each stage of a Vulkan device's PSO asked for (src/subgroup_size.h), in creation order; null for another PSO. const std::vector* pipeline_subgroup_requests(ID3D12PipelineState* pipeline); // PSOs of any Vulkan device not yet deleted, counting one whose deletion waits for its running build (tests). @@ -545,6 +561,8 @@ bool write_placed_texture_view(ID3D12Device* device, bool unordered, const std:: // The VA shaders read a descriptor table at: for one inside a console descriptor heap (Xbox slot 14) whose arena copy // lies elsewhere, the matching VA in that copy; any other VA unchanged. D3D12_GPU_VIRTUAL_ADDRESS console_descriptor_table_va(D3D12_GPU_VIRTUAL_ADDRESS va); +// The console descriptor heap holding `va` (its console VA and bytes); false when none with a copy holds it. +bool console_descriptor_heap_range(D3D12_GPU_VIRTUAL_ADDRESS va, std::uint64_t& console_va, std::uint64_t& bytes); // XDXR acceleration-structure commands (docs/d3d12_vulkan.md 4.8) of a list of `device`: every address the command // writes or reads, as the title named it, becomes the VA shaders reach that memory by (src/title_va_alias.h: a diff --git a/runtime/shims/d3d12_compile_helper.h b/runtime/shims/d3d12_compile_helper.h new file mode 100644 index 0000000000..59c6f4d7b1 --- /dev/null +++ b/runtime/shims/d3d12_compile_helper.h @@ -0,0 +1,443 @@ +// Out-of-process compute pipeline compiles: the compile helper (gta6rt --compile-server). +// +// A first build of a large compute module keeps the driver busy for tens of seconds to minutes, and on NVIDIA 630.20 a +// vkQueueSubmit of the same process waits for the lock that build holds (the compile gate makes it wait in our code +// instead, which still stops the title's frames). The driver's locks are per process. So with LEONIDA_COMPILE_HELPER=1 +// a build whose pipeline is in no journal file asks a helper process to make that file, and creates the pipeline from +// it once it is there: a cache hit of a few milliseconds. With asynchronous builds (LEONIDA_ASYNC_PIPELINES=1, the +// intended mode) nothing waits: the dispatch is skipped until the file is there. Without them a warm-up still only +// asks (so the helper's threads work ahead), and a dispatch waits for the file, holding nothing of the driver's. +// +// The helper is the same executable with the same environment, so it creates the same device and computes the same +// journal name; the file it writes is the one the game then reads. The protocol is files beside the journal: +// +// /requests/.req asked: "\t" (0: a dispatch waits for it; a +// warm-up asks with its module size), written whole +// /requests/.failed the helper could not: why, one line +// /requests/.building a lock file a process holds for the whole build (ownership is the open handle, +// which the OS closes when the process ends, killed or not; its contents name +// the process): precompile and helper runs skip an entry its holder is building +// /.bin done: the journal file itself +// +// The game starts the helper at its device's first pipeline (`--compile-server --parent `), and the helper ends +// with the game. With nothing asked it fills the rest of the library at idle priority. A request whose +// file appears another way (a precompile run) is answered the same way, so nothing has to agree on who builds what. +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../src/cached_pso.h" +#include "../src/pipeline_cache_journal.h" + +namespace rt::d3d12::compile_helper { + +inline std::filesystem::path requests_dir(const std::filesystem::path& journal_dir) { return journal_dir / "requests"; } + +inline std::filesystem::path sidecar(const std::filesystem::path& journal_file, const char* extension) { + return requests_dir(journal_file.parent_path()) / (journal_file.stem().string() + extension); +} +inline std::filesystem::path request_path(const std::filesystem::path& journal_file) { + return sidecar(journal_file, ".req"); +} +inline std::filesystem::path failed_path(const std::filesystem::path& journal_file) { + return sidecar(journal_file, ".failed"); +} +inline std::filesystem::path building_path(const std::filesystem::path& journal_file) { + return sidecar(journal_file, ".building"); +} + +// Whether another process (or thread) holds the entry's lock file: a build of it is running now. An open that asks to +// read conflicts with the holder's share mode 0; a leftover no one holds opens and is closed again at once. +inline bool building_held(const std::filesystem::path& journal_file) { + const std::filesystem::path marker = building_path(journal_file); + const HANDLE file = CreateFileW(marker.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (file != INVALID_HANDLE_VALUE) { + CloseHandle(file); + return false; + } + return GetLastError() == ERROR_SHARING_VIOLATION; +} + +inline std::string read_line(const std::filesystem::path& path) { + std::ifstream file(path, std::ios::binary); + std::string line; + std::getline(file, line); + while (!line.empty() && (line.back() == '\r' || line.back() == '\n')) line.pop_back(); + return line; +} + +inline std::error_code write_line(const std::filesystem::path& path, const std::string& text) { + const std::string line = text + "\n"; + return leonida::pipeline_journal::write_entry(path, line.data(), line.size()); +} + +// A request's line: "\t"; a bare name (an older writer) is priority 0. +struct RequestLine { + std::string name; + std::uint64_t priority = 0; +}; +inline RequestLine parse_request(const std::string& line) { + RequestLine out; + const auto tab = line.rfind('\t'); + if (tab == std::string::npos) { + out.name = line; + return out; + } + out.name = line.substr(0, tab); + out.priority = std::strtoull(line.c_str() + tab + 1, nullptr, 10); + return out; +} +inline std::string format_request(const std::string& name, std::uint64_t priority) { + return name + "\t" + std::to_string(priority); +} + +// This process builds for others (--compile-server, --precompile-pipelines): it never asks a helper or starts one, +// and its device keeps no session cache. +inline std::atomic build_host{false}; + +// LEONIDA_COMPILE_HELPER=1: modules of at least LEONIDA_COMPILE_HELPER_MIN_BYTES of SPIR-V (default 128 KiB). +inline std::size_t min_bytes() { + static const std::size_t bytes = [] { + char text[32]{}; + const DWORD n = GetEnvironmentVariableA("LEONIDA_COMPILE_HELPER", text, sizeof(text)); + if (!(n == 1 && text[0] == '1')) return SIZE_MAX; + const DWORD m = GetEnvironmentVariableA("LEONIDA_COMPILE_HELPER_MIN_BYTES", text, sizeof(text)); + const unsigned long long v = (m > 0 && m < sizeof(text)) ? std::strtoull(text, nullptr, 10) : 0; + return v ? static_cast(v) : std::size_t{128} << 10; + }(); + return bytes; +} +inline bool enabled() { return min_bytes() != SIZE_MAX && !build_host.load(); } +inline bool wanted(std::size_t spirv_bytes) { return enabled() && spirv_bytes >= min_bytes(); } + +// LOCAL FIX (compile helper: a killed helper's marker outlived a reused process id): the marker is a lock file, not a +// note naming its owner. It is created with no sharing and DELETE_ON_CLOSE, and the handle is held for the whole build: +// the OS closes it when the process ends, even on TerminateProcess, so a marker no process holds is one to take over +// and a leftover can never block a later run that happens to be given the same process id. The stems this process +// holds are kept here instead, which is what "another thread of this process has it" means. +inline std::mutex& markers_mutex() { + static std::mutex mutex; + return mutex; +} +inline std::map& held_markers() { // stem -> the handle that keeps its lock file + static std::map handles; + return handles; +} + +// Claims the entry for this process's build: false when this process or another one holds its lock file. +inline bool mark_building(const std::filesystem::path& journal_file) { + const auto marker = building_path(journal_file); + const std::string stem = journal_file.stem().string(); + std::error_code ec; + std::filesystem::create_directories(marker.parent_path(), ec); + { + std::lock_guard lock(markers_mutex()); + if (held_markers().count(stem)) return false; // another thread of this process is building it + } + // CREATE_NEW cannot say whether an existing file is held, so a create that finds it is followed by an open with + // no sharing: that succeeds on a leftover and fails with ERROR_SHARING_VIOLATION on a live build. + for (int attempt = 0; attempt < 2; ++attempt) { + HANDLE file = CreateFileW(marker.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_NEW, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, nullptr); + if (file == INVALID_HANDLE_VALUE) { + if (GetLastError() != ERROR_FILE_EXISTS) return true; // no marker can be kept: build anyway + file = CreateFileW(marker.c_str(), GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, nullptr); + if (file == INVALID_HANDLE_VALUE) { + if (GetLastError() == ERROR_SHARING_VIOLATION) return false; // a live build has it + continue; // it went away between the two calls: try the create once more + } + } + // Its contents are for a human reading the folder; nothing here reads them. + const std::string pid = std::to_string(GetCurrentProcessId()) + "\n"; + DWORD written = 0; + WriteFile(file, pid.data(), DWORD(pid.size()), &written, nullptr); + std::lock_guard lock(markers_mutex()); + held_markers()[stem] = file; + return true; + } + return true; // a marker that cannot be opened at all: build anyway +} + +// Drops the claim: closing the handle removes the lock file (DELETE_ON_CLOSE). +inline void unmark_building(const std::filesystem::path& journal_file) { + HANDLE handle = INVALID_HANDLE_VALUE; + { + std::lock_guard lock(markers_mutex()); + auto& handles = held_markers(); + const auto it = handles.find(journal_file.stem().string()); + if (it == handles.end()) return; + handle = it->second; + handles.erase(it); + } + CloseHandle(handle); +} + +// The game's side: one helper per process, started at the first request. +class Client { +public: + enum class State { ready, pending, failed, gone }; + + static Client& instance() { + static auto* client = new Client; // never destroyed: builds may still be asking at exit + return *client; + } + + // Asks for `journal_file` (the entry `name`) at `priority` without waiting; true when asked (or already there). + // A request is written again only for a more urgent priority. + bool request(const std::filesystem::path& journal_file, const std::string& name, std::uint64_t priority, + const leonida::cached_pso::Identity& identity, std::string* why) { + if (leonida::pipeline_journal::entry_usable(journal_file, identity)) return true; + if (!start(why)) return false; + const std::string stem = journal_file.stem().string(); + bool fresh = false; + { + std::lock_guard lock(mutex_); + const auto it = asked_.find(stem); + if (it != asked_.end() && it->second <= priority) return true; + fresh = it == asked_.end(); + asked_[stem] = priority; + } + // LOCAL FIX (compile helper: a failure of a request this session already wrote): only a fresh request drops an + // older failure, so asking again can retry. Bumping the priority of a request keeps it, since .failed is the + // answer to that same request and dropping it would put the caller back to waiting for a file nobody builds. + if (fresh) { + std::error_code ec; + std::filesystem::remove(failed_path(journal_file), ec); // an older failure: ask again + } + if (const std::error_code error = write_line(request_path(journal_file), format_request(name, priority))) { + if (why) *why = "could not write the request: " + error.message(); + std::lock_guard lock(mutex_); + asked_.erase(stem); + return false; + } + return true; + } + + // Where a request stands: its file is there, the helper gave up (*why), the helper is gone, or still pending. + State state(const std::filesystem::path& journal_file, const leonida::cached_pso::Identity& identity, + std::string* why) { + if (leonida::pipeline_journal::entry_usable(journal_file, identity)) return State::ready; + std::error_code ec; + const auto failed = failed_path(journal_file); + if (std::filesystem::exists(failed, ec)) { + if (why) *why = "the helper could not build it: " + read_line(failed); + forget(journal_file); + return State::failed; + } + const std::string stem = journal_file.stem().string(); + std::lock_guard lock(mutex_); + if (!process_ || WaitForSingleObject(process_, 0) == WAIT_OBJECT_0) { + drop(stem); + if (why) *why = "the helper exited"; + return State::gone; + } + // The helper takes .req away when it starts a build and holds the .building lock file until the journal file + // is written: an entry being built is pending however long the build takes (the title's big programs take + // minutes), and that time does not count against the pending bound below. + const auto now = std::chrono::steady_clock::now(); + if (building_held(journal_file)) { + pending_since_[stem] = now; + return State::pending; + } + // LOCAL FIX (compile helper: nothing bounded pending): the helper removes .req before it writes .failed and + // before the build that writes the journal file, so a request of ours that is neither listed nor being built + // has been answered another way or lost. Waiting would last as long as the helper lives, so answer failed here + // and the game builds the pipeline itself. (The journal file is checked once more: the build may have ended + // between the first check and the lock file's.) + if (!std::filesystem::exists(request_path(journal_file), ec)) { + if (leonida::pipeline_journal::entry_usable(journal_file, identity)) { + drop(stem); + return State::ready; + } + drop(stem); + if (why) *why = "its request is gone and its journal file is not usable"; + return State::failed; + } + // The helper is alive but may never build it (a module it cannot, a request it lost): the same bound as a + // failed request, so a skipped dispatch becomes a build here rather than a title that never dispatches. + const auto first = pending_since_.emplace(stem, now).first; + const unsigned long long limit = pending_ms(); + if (limit && now - first->second >= std::chrono::milliseconds(limit)) { + drop(stem); + if (why) *why = "the helper did not build it within " + std::to_string(limit) + " ms"; + return State::failed; + } + return State::pending; + } + + // Starts the helper now, so its device is up before the title's load needs it: made while the title fills video + // memory, the helper's device took 110 s in one boot. Called at the device's first pipeline. + void prestart() { + std::string why; + if (!start(&why)) std::fprintf(stderr, "[rt] d3d12: compile helper: %s\n", why.c_str()); + } + + // Asks and waits until the file is usable, the helper gives up or is gone, or LEONIDA_COMPILE_HELPER_WAIT_MS + // passes (default 120 s; 0: no limit). True when the file is there. + bool build(const std::filesystem::path& journal_file, const std::string& name, + const leonida::cached_pso::Identity& identity, std::string* why) { + if (!request(journal_file, name, 0, identity, why)) return false; + auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(wait_ms()); + for (;;) { + switch (state(journal_file, identity, why)) { + case State::ready: return true; + case State::failed: + case State::gone: return false; + case State::pending: break; + } + // A build in progress is waited for to its end: giving up would only start the same build here. + if (building_held(journal_file)) + deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(wait_ms()); + if (wait_ms() && std::chrono::steady_clock::now() >= deadline) { + if (why) *why = "timed out waiting for the helper"; + return false; + } + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + } + } + + // The helper is running for a test: state() and request() then answer for it without starting one (the test's own + // process handle stays alive, so the helper reads as running). + void pretend_helper_running_for_test() { + std::lock_guard lock(mutex_); + process_ = GetCurrentProcess(); + tried_ = true; + } + +private: + // Under mutex_ (or before it is taken): this process's bookkeeping for a request that is answered. + void drop(const std::string& stem) { + asked_.erase(stem); + pending_since_.erase(stem); + } + + void forget(const std::filesystem::path& journal_file) { + std::lock_guard lock(mutex_); + drop(journal_file.stem().string()); + } + + // How long a dispatch waits for the helper's file: LEONIDA_COMPILE_HELPER_WAIT_MS, default 120 s so a helper that + // cannot build a module never holds a dispatch for the whole boot; 0 keeps the old no-limit wait. + static unsigned long long wait_ms() { + static const unsigned long long ms = [] { + char text[32]{}; + const DWORD n = GetEnvironmentVariableA("LEONIDA_COMPILE_HELPER_WAIT_MS", text, sizeof(text)); + if (n == 0 || n >= sizeof(text)) return 120000ull; + return std::strtoull(text, nullptr, 10); + }(); + return ms; + } + + // How long a pending request may stay pending with the helper alive (LEONIDA_COMPILE_HELPER_PENDING_MS, default + // 120 s; 0: no limit). Read on each call so a test can set a short one. + static unsigned long long pending_ms() { + char text[32]{}; + const DWORD n = GetEnvironmentVariableA("LEONIDA_COMPILE_HELPER_PENDING_MS", text, sizeof(text)); + if (n == 0 || n >= sizeof(text)) return 120000ull; + return std::strtoull(text, nullptr, 10); + } + + // The helper's process handle, started once; null (and *why) when it could not be or has exited. + HANDLE start(std::string* why) { + std::lock_guard lock(mutex_); + if (process_ && WaitForSingleObject(process_, 0) != WAIT_OBJECT_0) return process_; + if (tried_) { + if (why) *why = process_ ? "the helper exited" : "the helper could not be started"; + return nullptr; + } + tried_ = true; + std::wstring exe(32768, L'\0'); + const DWORD length = GetModuleFileNameW(nullptr, exe.data(), DWORD(exe.size())); + if (!length || length >= exe.size()) { + if (why) *why = "no executable path"; + return nullptr; + } + exe.resize(length); + // LEONIDA_COMPILE_HELPER_THREADS (default 2): requests built at once, ~3.5 GB of host memory each for a module + // over 3 MB. LEONIDA_COMPILE_HELPER_IDLE_THREADS (default 1, at most THREADS - 1 so one is always free for a + // request): of those, how many fill the rest of the library at idle priority when nothing is asked. + const auto number = [](const char* variable, unsigned fallback) { + char text[16]{}; + const DWORD n = GetEnvironmentVariableA(variable, text, sizeof(text)); + return (n > 0 && n < sizeof(text)) ? unsigned(std::strtoul(text, nullptr, 10)) : fallback; + }; + const unsigned threads = (std::max)(1u, number("LEONIDA_COMPILE_HELPER_THREADS", 2)); + const unsigned idle = number("LEONIDA_COMPILE_HELPER_IDLE_THREADS", 1); + std::wstring command = L"\"" + exe + L"\" --compile-server --parent " + std::to_wstring(GetCurrentProcessId()) + + L" --threads " + std::to_wstring(threads) + L" --idle-threads " + std::to_wstring(idle); + STARTUPINFOW startup{sizeof(startup)}; + startup.dwFlags = STARTF_USESTDHANDLES; // its log lines go where the game's do + startup.hStdInput = GetStdHandle(STD_INPUT_HANDLE); + startup.hStdOutput = GetStdHandle(STD_ERROR_HANDLE); + startup.hStdError = GetStdHandle(STD_ERROR_HANDLE); + PROCESS_INFORMATION info{}; + // Normal priority: its requests are what the title's skipped dispatches wait for (at below normal a busy title + // starved its start for minutes). Only its library filling runs at idle priority. + if (!CreateProcessW(exe.c_str(), command.data(), nullptr, nullptr, TRUE, CREATE_NO_WINDOW, nullptr, nullptr, + &startup, &info)) { + if (why) *why = "CreateProcess failed (" + std::to_string(GetLastError()) + ")"; + return nullptr; + } + CloseHandle(info.hThread); + process_ = info.hProcess; + std::fprintf(stderr, "[rt] d3d12: compile helper started (process %lu, %u thread(s), %u filling the library " + "when idle)\n", info.dwProcessId, threads, idle); + return process_; + } + + std::mutex mutex_; + HANDLE process_ = nullptr; + bool tried_ = false; + std::map asked_; // stem -> priority of the request written + std::map pending_since_; // stem -> first seen pending +}; + +// One pending request, as the helper lists them. +struct Request { + std::string stem; // the journal file's stem: cs-<16 hex digits> + std::string name; // the library entry + std::uint64_t priority = 0; + std::filesystem::file_time_type asked{}; +}; + +// The requests in `dir`, most urgent first (priority, then age). +inline std::vector list_requests(const std::filesystem::path& dir) { + std::vector out; + std::error_code ec; + for (std::filesystem::directory_iterator it(dir, ec), end; !ec && it != end; it.increment(ec)) { + if (it->path().extension() != ".req") continue; + std::error_code stat; + const auto asked = it->last_write_time(stat); + if (stat) continue; + RequestLine line = parse_request(read_line(it->path())); + if (line.name.empty()) continue; + out.push_back({it->path().stem().string(), std::move(line.name), line.priority, asked}); + } + std::sort(out.begin(), out.end(), [](const Request& a, const Request& b) { + // The priority first, then the oldest: a stale request left by a killed session (a warm-up, so a high + // priority) cannot get ahead of this session's dispatches, which ask at 0 (LOCAL FIX, review). + return a.priority != b.priority ? a.priority < b.priority : a.asked < b.asked; + }); + return out; +} + +} // namespace rt::d3d12::compile_helper diff --git a/runtime/shims/d3d12_compute_input_probe.h b/runtime/shims/d3d12_compute_input_probe.h index 34042ebc13..70ac61e52c 100644 --- a/runtime/shims/d3d12_compute_input_probe.h +++ b/runtime/shims/d3d12_compute_input_probe.h @@ -7,6 +7,7 @@ #include "xmem.h" #include #include +#include #include #include #include @@ -251,11 +252,12 @@ void recheck(State& state) { if (heap->copy) scan("console", heap->shader_va, heap->copy, heap->bytes); } { - std::unique_lock lock(state.cbv_heap_mutex, std::try_to_lock); + std::unique_lock lock(state.visible_heap_mutex, std::try_to_lock); if (!lock.owns_lock()) std::fputs("[rt] compute-input: after loss, arena heaps locked\n", stderr); else - for (const auto& [offset, end] : state.cbv_heaps) - if (end <= state.arena.size) scan("arena", offset, state.arena.mapped + offset, end - offset); + 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); } } @@ -526,6 +528,14 @@ void inspect(State& state, std::span lists, s if (!d && (!ind || ind->kind != leonida::IndirectKind::dispatch)) continue; const char* name = state.context->diagnostic_compute_name(d ? d->pipeline : ind->pipeline); if (!matches(name)) continue; + // LEONIDA_COMPUTE_INPUT_LIMIT=: the first n matching dispatches in full, then one in 1,000 (a culling + // program runs several times a submission; 0 or unset: every one, as before). + static const unsigned limit = [] { + const char* v = std::getenv("LEONIDA_COMPUTE_INPUT_LIMIT"); + return v ? unsigned(std::strtoul(v, nullptr, 10)) : 0u; + }(); + static std::atomic matched{0}; + if (const unsigned n = ++matched; limit && n > limit && n % 1000) continue; const auto& roots = d ? d->user_data : ind->user_data; std::fprintf(stderr, "[rt] compute-input: execute=%llu list=%zu cmd=%zu queue=%s name=%s pso=%p %s groups=%u,%u,%u " "heap-base=0x%llx roots=[%s]\n", (unsigned long long)seq, l, i, queue, name, reinterpret_cast(d ? d->pipeline : ind->pipeline), diff --git a/runtime/shims/d3d12_geometry_views.h b/runtime/shims/d3d12_geometry_views.h index a9299d38cb..a72b6d8239 100644 --- a/runtime/shims/d3d12_geometry_views.h +++ b/runtime/shims/d3d12_geometry_views.h @@ -337,6 +337,9 @@ class GeometryViews { } } + // The blocks the copies live in (TitleBufferWindows::for_each_block), without the views' locks. + const TitleBufferWindows& pool() const { return pool_; } + bool lookup(VkDeviceAddress bda, std::uint64_t& host, std::uint64_t& bytes, std::uint64_t* source = nullptr, bool* populated = nullptr) const { std::shared_lock lock(structure_mutex_); diff --git a/runtime/shims/d3d12_pipeline_compile.h b/runtime/shims/d3d12_pipeline_compile.h index 3a5e045840..2889d7fd36 100644 --- a/runtime/shims/d3d12_pipeline_compile.h +++ b/runtime/shims/d3d12_pipeline_compile.h @@ -1,17 +1,21 @@ // Timing and scheduling for Vulkan pipeline creation on the D3D12 device. #pragma once +#include "../src/vulkan_device_fault.h" #include "../src/vulkan_replay.h" #include #include +#include #include #include #include #include #include #include +#include #include #include +#include #include namespace rt::d3d12 { @@ -31,6 +35,30 @@ inline bool async_replay_compile() { return on && !leonida::strict_replay(); } +// LOCAL FIX (post-load stalls): LEONIDA_FAST_PIPELINES=graphics, compute, or all (1 = all) creates those pipelines with +// VK_PIPELINE_CREATE_DISABLE_OPTIMIZATION_BIT. After the story load, graphics creates measured about 4.5 s each, and +// every submission waits at the compile gate while one is in the driver (frames stopped for 130 s); the title's large +// compute programs take 30-220 s each. Slower shaders, much shorter builds: the trade for reaching the world before +// it looks right. The flag is part of the compute journal key, so optimized and fast builds keep separate files. +inline VkPipelineCreateFlags fast_pipeline_flags(bool compute) { + static const unsigned mask = [] { + wchar_t v[16]{}; + const DWORD n = GetEnvironmentVariableW(L"LEONIDA_FAST_PIPELINES", v, 16); + unsigned m = 0; + if (n > 0 && n < 16) { + if (!wcscmp(v, L"1") || !_wcsicmp(v, L"all")) m = 3; + else if (!_wcsicmp(v, L"graphics")) m = 1; + else if (!_wcsicmp(v, L"compute")) m = 2; + else std::fprintf(stderr, "[rt] d3d12: LEONIDA_FAST_PIPELINES: unknown value, ignored (graphics, compute, all)\n"); + } + if (m) + std::fprintf(stderr, "[rt] d3d12: LEONIDA_FAST_PIPELINES: %s pipelines are built without driver optimization\n", + m == 3 ? "graphics and compute" : m == 1 ? "graphics" : "compute"); + return m; + }(); + return (mask & (compute ? 2u : 1u)) ? VkPipelineCreateFlags(VK_PIPELINE_CREATE_DISABLE_OPTIMIZATION_BIT) : 0; +} + // Absolute monotonic timestamps let trace readers distinguish time in the ICD from time queued for the worker. using CompileClock = std::chrono::steady_clock; inline long long compile_us() { @@ -59,31 +87,108 @@ struct CompileTrace { nullptr, &feedback, 0, nullptr}; long long started = 0; const char* key = "-"; + bool linked = false; // chain is in a create info's pNext chain template void begin(Info& info, bool supported, const char* trigger, const char* shaders, std::uint32_t variant, std::size_t bytes, const std::string& description_key) { if (!trace_pipeline_compile()) return; if (!description_key.empty()) key = description_key.c_str(); - if (supported) { - chain.pNext = info.pNext; - info.pNext = &chain; - } + if (supported) request_feedback(info); std::fprintf(stderr, "[rt] pipeline-compile-begin trigger=%s tid=%lu bytes=%zu variant=%u begin_ms=%lld key=%s shaders=%s\n", trigger, GetCurrentThreadId(), bytes, variant, compile_wall_ms(), key, shaders); started = compile_us(); } + // Chains the feedback struct ahead of info.pNext, once. begin() does when tracing; the pipeline journal does on a + // Vulkan 1.3 device (feedback is core there) to learn whether a pipeline came out of its cache. + template void request_feedback(Info& info) { + if (linked) return; + chain.pNext = info.pNext; + info.pNext = &chain; + linked = true; + } + + // 1 when the driver reports the pipeline was found in the application's VkPipelineCache, 0 when it reports it was + // not, -1 when it reported nothing (no feedback chained, or not VALID). + int hit() const { + return !(feedback.flags & VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT) ? -1 : + int((feedback.flags & VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT) != 0); + } + void end(const char* trigger, const char* shaders, std::uint32_t variant, std::size_t bytes, VkResult result) const { if (!started) return; const auto ended = compile_us(); - const int hit = !(feedback.flags & VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT) ? -1 : - int((feedback.flags & VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT) != 0); + const int hit = this->hit(); std::fprintf(stderr, "[rt] pipeline-compile trigger=%s tid=%lu start_us=%lld us=%lld hit=%d bytes=%zu " "variant=%u result=%d end_ms=%lld key=%s shaders=%s\n", trigger, GetCurrentThreadId(), started, ended - started, hit, bytes, variant, int(result), compile_wall_ms(), key, shaders); } }; +// The triggers of builds on the compile worker (PipelineCompiler): "warmup", "dispatch-worker", "draw-worker". +inline bool compile_worker_trigger(const char* trigger) { + if (!trigger) return false; + const std::size_t n = std::strlen(trigger); + return !std::strcmp(trigger, "warmup") || (n > 7 && !std::strcmp(trigger + n - 7, "-worker")); +} + +// LOCAL FIX (early device loss): one driver call that builds or drops shader code, kept out of the way of queue +// submissions (leonida::SubmitMutex). Before the call: +// - let_submit_finish: a submit in progress finishes first. The compile worker also lets the submitters queued +// behind it go first, and does so before its vkCreateShaderModule and vkDestroyShaderModule too; a title thread +// waits only for the holder, and only before a pipeline create (it may wait out a vkDeviceWaitIdle or a present: +// waits of 50 ms or more are logged). +// - a pipeline create passes the compile gate (SubmitMutex::CompileTurn) for the length of the call. +// - the compile worker, which runs below normal priority, runs the call at normal priority, so a preempted worker +// does not sit on a driver lock a submit waits for. +class DriverTurn { +public: + DriverTurn(leonida::SubmitMutex& submits, const char* trigger, const char* call, bool pipeline, + const char* name = nullptr) + : worker_(compile_worker_trigger(trigger)) { + // Normal priority first: a below-normal worker that waits its turn at normal priority cannot keep losing the + // race to the next submit, and holds the gate (below) only at normal priority. + if (worker_) { + const HANDLE self = GetCurrentThread(); + const int priority = GetThreadPriority(self); + if (priority != THREAD_PRIORITY_ERROR_RETURN && priority < THREAD_PRIORITY_NORMAL && + SetThreadPriority(self, THREAD_PRIORITY_NORMAL)) + restore_ = priority; + } + if (worker_ || pipeline) { + const std::int64_t waited = submits.let_submit_finish(worker_); + if (waited >= 50) note("waited for the submit lock", trigger, call, name, waited); + } + if (pipeline) { + gate_.emplace(submits); + if (gate_->waited_ms() >= 50) note("waited at the compile gate", trigger, call, name, gate_->waited_ms()); + } + } + ~DriverTurn() { + // Leave the gate before dropping back to below normal: a worker preempted while still counted in the gate + // would hold every submitter waiting there (each with the submit lock held) until the scheduler's starvation + // boost runs it again. + gate_.reset(); + if (restore_ != THREAD_PRIORITY_ERROR_RETURN) SetThreadPriority(GetCurrentThread(), restore_); + } + DriverTurn(const DriverTurn&) = delete; + DriverTurn& operator=(const DriverTurn&) = delete; + +private: + // Every wait of a second or more, and the first 32 of 50 ms or more. + static void note(const char* what, const char* trigger, const char* call, const char* name, std::int64_t ms) { + static std::atomic logged{0}; + if (ms < 1000 && logged.fetch_add(1, std::memory_order_relaxed) >= 32) return; + std::fprintf(stderr, "[rt] submit-handoff: %s (%s, %s) on thread %lu %s %lld ms at t=%.3f s\n", call, + trigger ? trigger : "-", name ? name : "-", GetCurrentThreadId(), what, static_cast(ms), + double(leonida::diagnostic_ms()) / 1000.0); + } + + bool worker_; + std::optional gate_; + int restore_ = THREAD_PRIORITY_ERROR_RETURN; +}; + // Demanded work has priority zero, speculative work is ordered by module size, and // an idle checkpoint runs last. No Vulkan call runs with the queue lock held. @@ -116,27 +221,32 @@ class PipelineCompiler { std::uint64_t deferred = 0; // after_running calls that left something to run after a running job }; - // False, with nothing queued, after stop_for_exit. - bool submit(const void* owner, const void* device, std::size_t priority, std::function work) { + // False, with nothing queued, after stop_for_exit. A `graphics` job (a graphics pipeline build) may also run on a + // second worker that takes only graphics jobs, so a compute build the driver takes minutes over does not hold + // up later graphics pipelines. LEONIDA_GRAPHICS_COMPILE_WORKER=0 uses one shared worker. + bool submit(const void* owner, const void* device, std::size_t priority, std::function work, + bool graphics = false) { std::lock_guard lock(mutex_); if (closed_) { ++stats_.refused; return false; } if (!worker_.joinable()) { - const std::uint64_t generation = ++generation_; - worker_ = std::thread([this, generation] { run(generation); }); + const std::uint64_t generation = generation_; + worker_ = std::thread([this, generation] { run(generation, false); }); + } + if (graphics && graphics_worker_enabled() && !graphics_worker_.joinable()) { + const std::uint64_t generation = generation_; + graphics_worker_ = std::thread([this, generation] { run(generation, true); }); } - jobs_.emplace(priority, Job{owner, device, std::move(work)}); + jobs_.emplace(priority, Job{owner, device, std::move(work), graphics}); ++stats_.submitted; - wake_.notify_one(); + wake_.notify_all(); return true; } - bool closed() { - std::lock_guard lock(mutex_); - return closed_; - } + // Lock-free: replay asks at every draw and dispatch whose pipeline is not built yet. + bool closed() const { return closed_flag_.load(std::memory_order_acquire); } bool has_compile_waiter() { std::lock_guard lock(mutex_); @@ -206,7 +316,7 @@ class PipelineCompiler { } void release() { std::vector dropped; - std::thread worker; + Workers worker; { std::lock_guard lock(mutex_); if (users_ && --users_) return; @@ -219,11 +329,12 @@ class PipelineCompiler { // one, so ExitProcess does not end the worker inside the driver. False when a job was still running. bool stop_for_exit(std::chrono::milliseconds wait) { std::vector dropped; - std::thread worker; + Workers worker; bool idle = true; { std::unique_lock lock(mutex_); closed_ = true; + closed_flag_.store(true, std::memory_order_release); worker = stop_locked(dropped); const auto me = std::this_thread::get_id(); idle = done_.wait_for(lock, wait, [&] { @@ -240,7 +351,7 @@ class PipelineCompiler { } bool worker_running() { std::lock_guard lock(mutex_); - return worker_.joinable(); + return worker_.joinable() || graphics_worker_.joinable(); } // Tests: called on the worker with each job's owner, once the job counts as running and before its work. void set_job_probe(std::function probe) { @@ -253,6 +364,18 @@ class PipelineCompiler { const void* owner = nullptr; const void* device = nullptr; std::function work; + bool graphics = false; // a graphics pipeline build: the graphics worker may take it too + }; + static bool graphics_worker_enabled() { + static const bool on = [] { + wchar_t v[2]{}; + return !(GetEnvironmentVariableW(L"LEONIDA_GRAPHICS_COMPILE_WORKER", v, 2) == 1 && v[0] == L'0'); + }(); + return on; + } + // Both workers: the general one, and the graphics one when it was started. + struct Workers { + std::thread general, graphics; }; struct Running { const void* owner; @@ -274,11 +397,11 @@ class PipelineCompiler { } } - std::thread stop_locked(std::vector& dropped) { + Workers stop_locked(std::vector& dropped) { drop_locked(dropped, [](const Job&) { return true; }); - ++generation_; // the worker returns when it next looks: after the job it is running, if any + ++generation_; // the workers return when they next look: after the job each is running, if any wake_.notify_all(); - return std::move(worker_); + return {std::move(worker_), std::move(graphics_worker_)}; } static void finish(std::thread worker, bool join) { @@ -286,19 +409,30 @@ class PipelineCompiler { if (join && worker.get_id() != std::this_thread::get_id()) worker.join(); else worker.detach(); } + static void finish(Workers workers, bool join) { + finish(std::move(workers.general), join); + finish(std::move(workers.graphics), join); + } Running& mine(std::thread::id me) { return *std::find_if(running_.begin(), running_.end(), [me](const Running& r) { return r.thread == me; }); } - void run(std::uint64_t generation) { + // The first job this worker may take, most urgent first: any job for the general worker, a graphics job for the + // graphics one. + std::multimap::iterator next_locked(bool graphics_only) { + if (!graphics_only) return jobs_.begin(); + return std::find_if(jobs_.begin(), jobs_.end(), [](const auto& entry) { return entry.second.graphics; }); + } + + void run(std::uint64_t generation, bool graphics_only) { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL); const auto me = std::this_thread::get_id(); std::unique_lock lock(mutex_); for (;;) { - wake_.wait(lock, [&] { return generation_ != generation || !jobs_.empty(); }); + wake_.wait(lock, [&] { return generation_ != generation || next_locked(graphics_only) != jobs_.end(); }); if (generation_ != generation) return; - auto first = jobs_.begin(); + auto first = next_locked(graphics_only); Job job = std::move(first->second); jobs_.erase(first); running_.push_back({job.owner, job.device, me}); @@ -338,9 +472,11 @@ class PipelineCompiler { std::multimap jobs_; std::vector running_; // one per worker; a stopped worker may still be finishing one std::thread worker_; + std::thread graphics_worker_; // graphics jobs only (submit's `graphics`), started at the first one std::uint64_t generation_ = 0; // a worker runs while this is the value it started with unsigned users_ = 0; // live devices (retain/release) bool closed_ = false; // stop_for_exit: nothing more is queued + std::atomic closed_flag_{false}; // closed_, for closed() Stats stats_; std::function probe_; }; diff --git a/runtime/shims/d3d12_precompile.h b/runtime/shims/d3d12_precompile.h new file mode 100644 index 0000000000..447c4db4e0 --- /dev/null +++ b/runtime/shims/d3d12_precompile.h @@ -0,0 +1,45 @@ +// gta6rt --precompile-pipelines: builds the compute pipelines of the whole translated shader library ahead of play. +// +// A first build of a large compute module takes the driver tens of seconds to minutes (3-4.6 MB of SPIR-V: 33-107 s +// on NVIDIA 630.20), and a title that dispatches one stalls its submissions behind it. Run with no game, this creates +// the Vulkan device exactly as `gta6rt --run` does (the same environment: LEONIDA_SHADERS, LEONIDA_PIPELINE_CACHE_DIR, +// LEONIDA_DEVICE_FAULT/LEONIDA_AFTERMATH, which change the pipelines) and builds every compute entry through the +// same path as a dispatch (build_compute_pipeline), so each lands in the pipeline journal +// (src/pipeline_cache_journal.h) under the name the game looks it up by, and in the driver's own disk cache, which +// NVIDIA keys by the executable's name. Entries whose journal file is there are skipped, so a run can be stopped at +// any time and started again. +#pragma once + +#include +#include +#include + +namespace rt::d3d12 { + +struct PrecompileOptions { + unsigned threads = 4; // worker threads, below normal priority + unsigned big_threads = 0; // of those, how many may build a module over big_bytes at once (0: threads) + std::size_t big_bytes = std::size_t{2} << 20; + bool rebuild = false; // --all: build entries whose journal file exists too + bool smallest_first = false; // default: the largest modules first (the ones that stall a title longest) + std::size_t limit = 0; // at most this many entries (0: all) + std::size_t min_bytes = 0, max_bytes = 0; // SPIR-V size bounds (0: none) + std::vector filters; // only entries whose name contains one of these + bool dry_run = false; // --list: print the plan, build nothing + bool via_helper = false; // --via-helper: as a title does with LEONIDA_COMPILE_HELPER=1 (a test) +}; + +// gta6rt --compile-server (d3d12_compile_helper.h). +struct CompileServerOptions { + unsigned long parent_pid = 0; // --parent: ends when that process does + unsigned threads = 2; // --threads + unsigned idle_threads = 1; // --idle-threads: of `threads`, how many fill the library when nothing is asked + unsigned idle_exit_s = 0; // --idle-exit: ends after this long with nothing asked (0: never) +}; +int compile_server(const CompileServerOptions& options); + +// Returns 0 when every selected entry was built or already journaled, 2 when some could not be built, 1 when the +// device or the library could not be had. +int precompile_compute_pipelines(const PrecompileOptions& options); + +} // namespace rt::d3d12 diff --git a/runtime/shims/d3d12_title_buffer_windows.h b/runtime/shims/d3d12_title_buffer_windows.h index c940d6138f..a47b3e2489 100644 --- a/runtime/shims/d3d12_title_buffer_windows.h +++ b/runtime/shims/d3d12_title_buffer_windows.h @@ -1,6 +1,9 @@ #pragma once #include +#include +#include +#include #include #include #include @@ -30,9 +33,41 @@ class TitleBufferWindows { bool failed_ = false; bool local_refused_ = false; // device-local blocks refused once: host memory from then on std::uint64_t quick_refusals_ = 0; + // The blocks' (device address, capacity), readable without the owner's lock: published in order, never removed + // before release(). + static constexpr std::size_t kPublished = 4096; + struct Published { + VkDeviceAddress address; + VkDeviceSize capacity; + std::uint8_t* mapped; + VkBuffer buffer; + }; + std::array published_{}; + std::atomic published_count_{0}; public: VkDeviceSize reserved() const { return reserved_; } + // f(device address, capacity) for each block made so far; from any thread. + template + void for_each_block(F&& f) const { + const std::size_t n = published_count_.load(std::memory_order_acquire); + for (std::size_t i = 0; i < n; ++i) f(published_[i].address, published_[i].capacity); + } + // The block whose mapping holds [p, p + bytes): its buffer and the offset of p in it. From any thread. + bool find_mapped(const std::uint8_t* p, std::size_t bytes, VkBuffer& buffer, VkDeviceSize& offset) const { + const std::size_t n = published_count_.load(std::memory_order_acquire); + for (std::size_t i = 0; i < n; ++i) { + const Published& b = published_[i]; + if (p >= b.mapped && p - b.mapped < std::ptrdiff_t(b.capacity) && + bytes <= std::size_t(b.capacity) - std::size_t(p - b.mapped)) { + buffer = b.buffer; + offset = VkDeviceSize(p - b.mapped); + return true; + } + } + return false; + } + std::size_t block_count() const { return published_count_.load(std::memory_order_acquire); } template bool allocate(Device& d, VkDeviceSize bytes, VkDeviceSize& offset, std::uint8_t*& mapped, @@ -107,6 +142,10 @@ class TitleBufferWindows { if (b.address && biased < (1ull << 47) && b.capacity <= (1ull << 47) - biased) { b.mapped = static_cast(host); blocks_.push_back(b); + if (const std::size_t n = published_count_.load(std::memory_order_relaxed); n < kPublished) { + published_[n] = {b.address, b.capacity, b.mapped, b.buffer}; + published_count_.store(n + 1, std::memory_order_release); + } reserved_ += req.size; if (blocks_.size() == 1 || !(blocks_.size() & (blocks_.size() - 1))) std::fprintf(stderr, "[rt] d3d12: title buffer shadows outside the arena: %zu blocks, " @@ -145,6 +184,7 @@ class TitleBufferWindows { d.context->vk.vkFreeMemory(d.info.device, b.memory, nullptr); } blocks_.clear(); + published_count_.store(0, std::memory_order_release); reserved_ = 0; } }; diff --git a/runtime/shims/d3d12_title_image_upload.h b/runtime/shims/d3d12_title_image_upload.h index 2bb092f999..a0be8360dc 100644 --- a/runtime/shims/d3d12_title_image_upload.h +++ b/runtime/shims/d3d12_title_image_upload.h @@ -219,11 +219,15 @@ class TitleImageUpload { transfer.pCommandBuffers = &slot.command; transfer.signalSemaphoreCount = 1; transfer.pSignalSemaphores = &ready_; - auto r = vk.vkQueueSubmit(d.info.queue, 1, &transfer, VK_NULL_HANDLE); + // 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_; + --value_; // nothing signalled it 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}; @@ -235,7 +239,7 @@ class TitleImageUpload { wait.pWaitSemaphores = &ready_; wait.pWaitDstStageMask = &stages; for (auto q : consumers_) - if ((r = vk.vkQueueSubmit(q, 1, &wait, VK_NULL_HANDLE)) != VK_SUCCESS) return r; + if ((r = d.context->queue_submit(q, 1, &wait, VK_NULL_HANDLE)) != VK_SUCCESS) return r; return VK_SUCCESS; } diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 36f3556090..3ea505429a 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -12,6 +12,8 @@ #include "d3d12_com.h" #include "d3d12_compile_exit.h" #include "d3d12_pipeline_compile.h" +#include "d3d12_precompile.h" +#include "d3d12_compile_helper.h" #include "d3d12_pipeline_checkpoint.h" #include "d3d12_feature_compat.h" @@ -46,6 +48,7 @@ #include "../src/pipeline_profile.h" #include "../src/submit_phases.h" #include "../src/pipeline_cache_store.h" +#include "../src/pipeline_cache_journal.h" #include "../src/conservative_raster.h" #include "../src/resource_detile.h" #include "../src/console_texture_layout.h" @@ -71,6 +74,7 @@ #include "../src/local_diagnostics.h" #include "../src/mem_probe.h" // LOCAL DIAGNOSTIC #include "../src/vulkan_aftermath.h" +#include "../src/console_heap_gpu.h" #include #ifdef _MSC_VER @@ -90,6 +94,7 @@ #include #include #include +#include #include #include #include @@ -98,11 +103,13 @@ #include #include #include +#include #include #include #include #include #include +#include #include #include @@ -253,6 +260,13 @@ 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; +} // 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; @@ -325,6 +339,13 @@ class ShadowPages { public: static constexpr std::uintptr_t kPage = 0x1000; static constexpr std::uintptr_t kBlock = 0x10000; // what one write fault makes writable again + // LEONIDA_SHADOW_GPU (DeviceState::gpu_copy_shadow): takes a copy of [from, from + bytes) to `to` for the GPU, or + // returns false and the CPU copies it. Set once by the device. + using GpuCopy = bool (*)(void* context, std::uint8_t* to, const std::uint8_t* from, std::size_t bytes); + static inline GpuCopy gpu_copy = nullptr; + static inline void* gpu_copy_context = nullptr; + // Bytes this tracker's refreshes handed to gpu_copy so far. + std::uint64_t gpu_bytes() const { return gpu_bytes_; } ShadowPages(const std::uint8_t* pages, std::uint8_t* shadow, std::size_t size, bool watch) : watch_(watch) { begin_ = reinterpret_cast(pages); @@ -385,6 +406,8 @@ class ShadowPages { // Brings every target up to date with the pages. Returns the bytes copied into them. With copy_aliased false, pages // xmem maps at another address too are left as they are this time (DeviceState::refresh_shadows throttles them). std::size_t refresh(bool copy_aliased = true) { + const auto walk_start = std::chrono::steady_clock::now(); + pieces_ = {}; copy_aliased_ = copy_aliased; jobs_.clear(); zeroed_.clear(); @@ -525,11 +548,15 @@ class ShadowPages { switch (how) { case Watch::clean: break; // write-watched, not written since it was copied case Watch::written: // write-watched: written since, or not known yet + // A page this tracker made read-only is opened first: dropping kProtected alone left it + // read-only with no owner, so the next write could fault. + unguard_ours(i, j); for (std::size_t k = i; k < j; ++k) state_[k] = std::uint8_t((state_[k] & ~(kZero | kProtected)) | kClean); add_job(i, j, streaming, Copy::write_watched); break; case Watch::open: // write-watched, but pinned for a kernel write: copied until the pin ends + unguard_ours(i, j); for (std::size_t k = i; k < j; ++k) state_[k] &= ~(kZero | kProtected | kClean); add_job(i, j, streaming, Copy::write_watched); break; @@ -544,6 +571,7 @@ class ShadowPages { } break; case Kind::unwatched: + unguard_ours(i0, i1); // as above: never drop kProtected over a page still read-only for us for (std::size_t i = i0; i < i1; ++i) state_[i] &= kAliased | kPinned | kWatched; add_job(i0, i1, streaming, Copy::copy_on_write); break; @@ -559,15 +587,55 @@ class ShadowPages { log_once("slot-133 shadow: VirtualProtect refused to watch the title's pages for writes, so they are " "copied at every submission; error", int(protect_error)); - // The copies run without the lock: a write that faults meanwhile is let through and copied next time. + // The copies run without the lock: a write that faults meanwhile is let through and copied next time. Pages + // copied because they are aliased go to the GPU when LEONIDA_SHADOW_GPU set gpu_copy and it takes them. + // LEONIDA_SHADOW_JOIN=1: pieces of one job that go on where the one before ended, in the pages and in the copy + // both, are one copy (one GPU region, one gpu_copy call); one the GPU refuses is copied by the CPU whole. + static const bool join = [] { + char value[4] = {}; + return GetEnvironmentVariableA("LEONIDA_SHADOW_JOIN", value, sizeof(value)) == 1 && value[0] == '1'; + }(); + const auto copy_start = std::chrono::steady_clock::now(); + pieces_.walk_ms = std::chrono::duration(copy_start - walk_start).count(); std::size_t copied = 0; - for (const Job& job : jobs_) + for (const Job& job : jobs_) { + std::uint8_t* run_dst = nullptr; + const std::uint8_t* run_src = nullptr; + std::size_t run_bytes = 0; + const auto flush = [&] { + if (!run_bytes) return; + ++pieces_.calls; + if (job.aliased && gpu_copy) ++pieces_.gpu_calls; + if (job.aliased && gpu_copy && gpu_copy(gpu_copy_context, run_dst, run_src, run_bytes)) + gpu_bytes_ += run_bytes; + else + copy_run(run_dst, run_src, run_bytes, job.streaming); + run_bytes = 0; + }; for_each_target(begin_ + job.offset, begin_ + job.offset + job.bytes, [&](const Target& t, std::uintptr_t from, std::uintptr_t to) { - copy_run(t.shadow + (from - t.begin), reinterpret_cast(from), - to - from, job.streaming); - copied += to - from; + std::uint8_t* dst = t.shadow + (from - t.begin); + const auto* src = reinterpret_cast(from); + const std::size_t n = to - from; + ++pieces_.pieces; + pieces_.short_pieces += n < kPage; + const bool follows = run_bytes && run_dst + run_bytes == dst && run_src + run_bytes == src; + pieces_.joinable += follows; + if (join && follows) { + run_bytes += n; + } else { + flush(); + run_dst = dst; + run_src = src; + run_bytes = n; + if (!join) flush(); + } + copied += n; }); + flush(); + } + pieces_.copy_ms = + std::chrono::duration(std::chrono::steady_clock::now() - copy_start).count(); refresh_queries_ = queries; return copied; } @@ -762,6 +830,15 @@ class ShadowPages { // read-only pages that are not this tracker's, copy-on-write pages, write-watched pages found written. enum class Copy { guarded, unguarded, aliased, pinned, read_only, copy_on_write, write_watched, count }; const std::array& copy_bytes() const { return copy_bytes_; } + // The last refresh()'s copies as pieces (one per job and target: a slot-133 buffer is a few KiB, so a run of + // pages over many of them is many pieces), those under 4 KiB, those that go on where the one before ended in both + // the title's pages and the copy (VItoriaBr's JOIN_COPIES case), the copy calls made after LEONIDA_SHADOW_JOIN + // joined those, and the milliseconds of the walk (queries, guards, under the lock) and of the copies. + struct Pieces { + std::uint64_t pieces = 0, short_pieces = 0, joinable = 0, calls = 0, gpu_calls = 0; + double walk_ms = 0, copy_ms = 0; + }; + const Pieces& pieces() const { return pieces_; } private: // How a committed, readable page is watched: by the kernel (clean, written or, pinned or aliased, open) or by @@ -906,6 +983,7 @@ class ShadowPages { struct Job { std::size_t offset, bytes; // from begin_ bool streaming; + bool aliased; // copied because xmem maps the pages elsewhere too (Copy::aliased) }; struct Target { std::uintptr_t begin, end; // the title's bytes @@ -934,12 +1012,13 @@ class ShadowPages { void add_job(std::size_t i, std::size_t j, bool streaming, Copy why) { const auto [offset, bytes] = span_of(i, j); copy_bytes_[unsigned(why)] += bytes; - if (!jobs_.empty() && jobs_.back().streaming == streaming && + const bool aliased = why == Copy::aliased; + if (!jobs_.empty() && jobs_.back().streaming == streaming && jobs_.back().aliased == aliased && jobs_.back().offset + jobs_.back().bytes == offset) { jobs_.back().bytes += bytes; return; } - jobs_.push_back({offset, bytes, streaming}); + jobs_.push_back({offset, bytes, streaming, aliased}); } // The targets sorted by start, the bytes they hold, and reach_[k], the furthest end among targets_[0..k]: the @@ -990,6 +1069,18 @@ class ShadowPages { ++refresh_protects_; } + // With the lock held: before pages [i, j) stop counting as ours (kProtected), the ones this tracker made read-only + // are given back their write access, so no page stays read-only with no guard to answer its writes. + void unguard_ours(std::size_t i, std::size_t j) { + for (std::size_t k = i; k < j; ++k) + if (state_[k] & kProtected) { + ++unguarded_on_drop_; + reopen_locked(first_ + i * kPage, first_ + j * kPage); + return; + } + } + std::uint64_t unguarded_on_drop_ = 0; // times unguard_ours found pages of ours to reopen (diagnostic) + // With the lock held: the pages in [from, to) this tracker made read-only are read-write again. void reopen_locked(std::uintptr_t from, std::uintptr_t to) { for (std::uintptr_t at = from; at < to;) { @@ -1043,6 +1134,8 @@ class ShadowPages { DWORD protect_error_ = 0; // a VirtualProtect refusal of this refresh(), logged after it std::array copy_bytes_{}; // refresh() only, likewise bool copy_aliased_ = true; // likewise + std::uint64_t gpu_bytes_ = 0; + Pieces pieces_; // refresh() only, likewise std::uint64_t refresh_queries_ = 0; std::uint64_t refresh_protects_ = 0; // VirtualProtect calls of the last refresh() bool refresh_walked_all_ = false; // the last refresh() queried every page (the title memory map changed) @@ -1076,6 +1169,49 @@ leonida::host_heap::vector& shadow_pages_list() { // pages at every submission (title_page_aliases), so the guard to look for is the faulting address's own. When none // answers for it (each guard reopens only what it protected), xmem makes the page writable again if its window is // (kernel_writes' unguarder): a read-only page nobody reopens would fault that write, and every later one, for good. +// A title write into a committed, private, read-only page of title memory that no guard owns (the geometry watch, +// the slot-133 shadows and the kernel-write unguarder all declined it): a guard of ours left behind, since the title +// never writes memory it made read-only itself on the console. Said for the first 32 pages, with whether a shadow's +// range still covers the page (its bookkeeping then calls the page unguarded). LEONIDA_STRAY_RO_HEAL=1: the page is +// made writable again and the write retried, so the title goes on (a shadow may then miss that page's next writes: +// the GPU copy may be stale for one frame). +bool stray_read_only(EXCEPTION_POINTERS* info, std::uintptr_t address) { + MEMORY_BASIC_INFORMATION m{}; + if (!VirtualQuery(reinterpret_cast(address), &m, sizeof m)) return false; + if (m.State != MEM_COMMIT || m.Type != MEM_PRIVATE || (m.Protect & 0xff) != PAGE_READONLY) return false; + std::uint64_t lo = 0, hi = 0; + if (!leonida::title_va_aliases().title_memory(address, lo, hi)) return false; + static const bool heal = [] { + const char* v = std::getenv("LEONIDA_STRAY_RO_HEAL"); + return v && *v == '1'; + }(); + unsigned covering = 0; + AcquireSRWLockShared(&g_shadow_pages_lock); + for (ShadowPages* pages : shadow_pages_list()) covering += pages->contains(address); + ReleaseSRWLockShared(&g_shadow_pages_lock); + static std::atomic told{0}, healed{0}; + const std::uintptr_t page = address & ~std::uintptr_t(0xfff); + bool ok = false; + if (heal) { + DWORD old = 0; + ok = VirtualProtect(reinterpret_cast(page), 0x1000, (m.Protect & ~DWORD(0xff)) | PAGE_READWRITE, &old) != 0; + if (ok) healed.fetch_add(1, std::memory_order_relaxed); + } + if (told.fetch_add(1, std::memory_order_relaxed) < 32) { + const auto rip = info && info->ContextRecord ? info->ContextRecord->Rip : 0; + std::fprintf(stderr, "[rt] d3d12: stray read-only title page 0x%llx (write to 0x%llx from rip 0x%llx; " + "allocation 0x%llx, protect 0x%lx): no guard owns it, %u shadow range(s) cover it; %s " + "(%u healed so far)\n", + static_cast(page), static_cast(address), + static_cast(rip), static_cast( + reinterpret_cast(m.AllocationBase)), + static_cast(m.Protect), covering, + !heal ? "left to fault (LEONIDA_STRAY_RO_HEAL=1 makes it writable)" : ok ? "made writable" : "could not be made writable", + healed.load(std::memory_order_relaxed)); + } + return ok; +} + LONG CALLBACK shadow_write_fault(EXCEPTION_POINTERS* info) { const EXCEPTION_RECORD* record = info ? info->ExceptionRecord : nullptr; if (!record || record->ExceptionCode != EXCEPTION_ACCESS_VIOLATION || record->NumberParameters < 2 || @@ -1098,6 +1234,7 @@ LONG CALLBACK shadow_write_fault(EXCEPTION_POINTERS* info) { if (!retry) if (const auto unguard = leonida::kernel_writes::state().unguarder.load(std::memory_order_acquire)) retry = unguard(address, address + 1); + if (!retry) retry = stray_read_only(info, address); return retry ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_CONTINUE_SEARCH; } @@ -1115,6 +1252,15 @@ void open_shadow_pages(std::uintptr_t from, std::uintptr_t to) { ReleaseSRWLockShared(&g_shadow_pages_lock); } +// fsdraw's backing hook: whether a slot-133 shadow keeps the GPU copy of a title VA (LEONIDA_FSDRAW_PROBE only). +const char* fsdraw_backing(std::uint64_t title_va) { + unsigned covering = 0; + AcquireSRWLockShared(&g_shadow_pages_lock); + for (ShadowPages* pages : shadow_pages_list()) covering += pages->contains(std::uintptr_t(title_va)); + ReleaseSRWLockShared(&g_shadow_pages_lock); + return covering ? "a slot-133 shadow" : "an alias with no slot-133 shadow (window, geometry view or import)"; +} + // Installs the handler once. false: it couldn't be, and shadows copy every page at every submission. bool watch_shadow_writes() { static const bool installed = [] { @@ -1239,6 +1385,36 @@ std::filesystem::path pipeline_cache_session_path() { return path; } +std::size_t pipeline_cache_save_limit(); + +// LOCAL FIX (pipeline journal, pipeline_cache_journal.h): where each compute pipeline's own cache file goes, beside +// the session file (so LEONIDA_PIPELINE_CACHE_DIR moves it too). Empty, and no journal, with LEONIDA_PIPELINE_JOURNAL=0 +// or LEONIDA_PIPELINE_CACHE_BYTES=0. +const leonida::pipeline_journal::Roots& pipeline_journal_roots() { + static const auto roots = []() -> leonida::pipeline_journal::Roots { + wchar_t value[2]{}; + if (GetEnvironmentVariableW(L"LEONIDA_PIPELINE_JOURNAL", value, 2) == 1 && value[0] == L'0') + return {}; + if (!pipeline_cache_save_limit()) return {}; + std::filesystem::path path = pipeline_cache_path(); + if (!path.empty()) path.replace_filename(L"pipeline_cache.d"); + std::wstring seed(32768, L'\0'); + const DWORD n = GetEnvironmentVariableW(L"LEONIDA_PIPELINE_JOURNAL_SEED_DIR", seed.data(), + static_cast(seed.size())); + if (n >= seed.size()) return {}; + seed.resize(n); + auto result = leonida::pipeline_journal::resolve_roots(path, seed); + if (!seed.empty() && result.writable.empty()) + std::fprintf(stderr, "[rt] d3d12: invalid or overlapping compute journal directories; journal disabled\n"); + return result; + }(); + return roots; +} + +const std::filesystem::path& pipeline_journal_dir() { + return pipeline_journal_roots().writable; +} + // LEONIDA_PIPELINE_CACHE_BYTES, in bytes; 0 turns the session file off. One line for a value that is not a number. std::size_t pipeline_cache_save_limit() { char text[32] = {}; @@ -1321,16 +1497,16 @@ VkPipelineCache create_seeded_pipeline_cache(PFN_vkCreatePipelineCache create_ca // and the session file cannot be handed over as one VkPipelineCacheCreateInfo -- Vulkan reads a single blob -- so the // session cache is created on its own and merged in. A missing, foreign or corrupt session file leaves the cache as // it was, and so does a driver that does not expose vkMergePipelineCaches. -void merge_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDevice device, VkPipelineCache cache, +bool merge_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDevice device, VkPipelineCache cache, const leonida::cached_pso::Identity& identity) { - if (!cache || !vk.vkCreatePipelineCache || !vk.vkDestroyPipelineCache || !vk.vkMergePipelineCaches) return; - if (!pipeline_cache_save_limit()) return; // LEONIDA_PIPELINE_CACHE_BYTES=0 turns the session file off + if (!cache || !vk.vkCreatePipelineCache || !vk.vkDestroyPipelineCache || !vk.vkMergePipelineCaches) return false; + if (!pipeline_cache_save_limit()) return false; // LEONIDA_PIPELINE_CACHE_BYTES=0 turns the session file off const auto start = compile_us(); const PipelineCacheSeed seed(pipeline_cache_session_path()); - if (!seed.data()) return; + if (!seed.data()) return false; if (!seed.compatible(identity)) { std::fprintf(stderr, "[rt] d3d12: pipeline_cache.session.bin does not match this Vulkan device\n"); - return; + return false; } const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, nullptr, 0, seed.size(), seed.data()}; @@ -1338,7 +1514,7 @@ void merge_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDe VkPipelineCache session = VK_NULL_HANDLE; if (vk.vkCreatePipelineCache(device, &create, nullptr, &session) != VK_SUCCESS) { std::fprintf(stderr, "[rt] d3d12: Vulkan declined pipeline_cache.session.bin\n"); - return; + return false; } const auto created = compile_us(); const VkResult result = vk.vkMergePipelineCaches(device, cache, 1, &session); @@ -1352,6 +1528,7 @@ void merge_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDe else std::fprintf(stderr, "[rt] d3d12: vkMergePipelineCaches on pipeline_cache.session.bin returned %d; ignored\n", static_cast(result)); + return result == VK_SUCCESS; } // LEONIDA_SKIP_COMPUTE=[,...]: compute programs whose library name contains one of the parts are @@ -1876,6 +2053,18 @@ class ConsoleHeapRanges { if (va >= r.console_va && va - r.console_va < r.bytes) return r.shader_va + (va - r.console_va); return va; } + // The console heap holding `va`: its console VA and size. False when no console heap with a copy holds it. + bool range_of(std::uint64_t va, std::uint64_t& console_va, std::uint64_t& bytes) const { + if (!count_.load(std::memory_order_acquire)) return false; + std::shared_lock lock(mutex_); + for (const Range& r : ranges_) + if (va >= r.console_va && va - r.console_va < r.bytes) { + console_va = r.console_va; + bytes = r.bytes; + return true; + } + return false; + } private: struct Range { @@ -1963,6 +2152,18 @@ struct DeviceState { leonida::cached_pso::Identity pso_identity; // what GetCachedBlob records and CachedPSO is checked against std::once_flag pipeline_cache_once; VkPipelineCache pipeline_cache_handle = VK_NULL_HANDLE; + // The shared cache started from a file (the offline seed or an earlier session): a compute pipeline the journal + // has no file for may still be in it (build_compute asks it first, when it can ask without a compile). + bool pipeline_cache_seeded = false; + std::atomic journal_hits{0}, journal_writes{0}, journal_shared_hits{0}; + std::atomic journal_bytes{0}; // on disk: counted at the cache's creation, then added to + std::uint64_t journal_budget = leonida::pipeline_journal::default_budget; + // Ask the shared cache first, with FAIL_ON_PIPELINE_COMPILE_REQUIRED, while the driver honours it. + // LEONIDA_PIPELINE_JOURNAL_ASK_SHARED=0: never. + std::atomic journal_ask_shared{[] { + wchar_t value[2]{}; + return !(GetEnvironmentVariableW(L"LEONIDA_PIPELINE_JOURNAL_ASK_SHARED", value, 2) == 1 && value[0] == L'0'); + }()}; std::atomic next_checkpoint{GetTickCount64() + 120000}; std::atomic active_compiles{0}; @@ -1971,20 +2172,45 @@ struct DeviceState { const auto& vk = context->vk; if (!vk.vkCreatePipelineCache || !vk.vkDestroyPipelineCache) return; if (pipeline_cache_save_limit()) clean_stale_cache_files(pipeline_cache_session_path()); - pipeline_cache_handle = create_seeded_pipeline_cache(vk.vkCreatePipelineCache, info.device, pso_identity); + // A build host (precompile, compile helper) journals every pipeline: no seed, no session file. + if (!compile_helper::build_host) + pipeline_cache_handle = create_seeded_pipeline_cache(vk.vkCreatePipelineCache, info.device, pso_identity); if (pipeline_cache_handle) { + pipeline_cache_seeded = true; merge_session_pipeline_cache(vk, info.device, pipeline_cache_handle, pso_identity); - } else if (pipeline_cache_save_limit() && direct_session_cache()) { + } else if (pipeline_cache_save_limit() && direct_session_cache() && !compile_helper::build_host) { // With no offline seed the session file can initialize the actual cache directly. pipeline_cache_handle = create_seeded_pipeline_cache(vk.vkCreatePipelineCache, info.device, pso_identity, true); + pipeline_cache_seeded = pipeline_cache_handle != VK_NULL_HANDLE; } if (!pipeline_cache_handle) { const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO}; if (vk.vkCreatePipelineCache(info.device, &create, nullptr, &pipeline_cache_handle) != VK_SUCCESS) pipeline_cache_handle = VK_NULL_HANDLE; - else if (!direct_session_cache()) - merge_session_pipeline_cache(vk, info.device, pipeline_cache_handle, pso_identity); - } + else if (!direct_session_cache() && !compile_helper::build_host) + pipeline_cache_seeded = merge_session_pipeline_cache(vk, info.device, pipeline_cache_handle, pso_identity); + } + if (!pipeline_journal_dir().empty()) { + char text[32] = {}; + size_t length = 0; + if (getenv_s(&length, text, "LEONIDA_PIPELINE_JOURNAL_BYTES") == 0 && length > 1) { + const auto budget = leonida::pipeline_cache_store::parse_save_limit(text); + if (budget.valid) journal_budget = budget.bytes; + } + // Old staging files out, and the least recently used files when over the budget: translator + // regenerations leave files no build names any more. + const auto tidy = leonida::pipeline_journal::tidy(pipeline_journal_dir(), journal_budget); + journal_bytes = tidy.bytes; + if (tidy.evicted || tidy.swept) + std::fprintf(stderr, "[rt] d3d12: pipeline journal: removed %zu least recently used file(s) over " + "the %llu-byte budget and %zu stale staging file(s); %zu file(s), %llu bytes " + "left\n", tidy.evicted, static_cast(journal_budget), + tidy.swept, tidy.entries, static_cast(tidy.bytes)); + } + if (!pipeline_journal_dir().empty()) + std::fprintf(stderr, "[rt] d3d12: compute pipelines are journaled one file each in %ls\n", + pipeline_journal_dir().c_str()); + if (compile_helper::enabled() && !pipeline_journal_dir().empty()) compile_helper::Client::instance().prestart(); }); // Without EXTERNALLY_SYNCHRONIZED_BIT the driver synchronizes concurrent pipeline creation using this cache. return pipeline_cache_handle; @@ -2060,6 +2286,7 @@ struct DeviceState { std::uint64_t shadow_asks = 0; // GetWriteWatch calls, likewise std::uint64_t shadow_written = 0; // write-watched pages they found written, likewise std::array shadow_copy_bytes{}; // by cause, likewise + ShadowPages::Pieces shadow_pieces; // summed over the refreshes since the last log line std::chrono::steady_clock::time_point shadow_alias_time{}; // the last refresh that copied aliased pages double shadow_ms = 0; // spent since the last log line double shadow_max_ms = 0; // the longest refresh since the last log line @@ -2147,6 +2374,14 @@ struct DeviceState { shadow_asks += s->refresh_asks(); shadow_written += s->refresh_written(); for (unsigned k = 0; k < shadow_copy_bytes.size(); ++k) shadow_copy_bytes[k] += s->copy_bytes()[k]; + const ShadowPages::Pieces& p = s->pieces(); + shadow_pieces.pieces += p.pieces; + shadow_pieces.short_pieces += p.short_pieces; + shadow_pieces.joinable += p.joinable; + shadow_pieces.calls += p.calls; + shadow_pieces.gpu_calls += p.gpu_calls; + shadow_pieces.walk_ms += p.walk_ms; + shadow_pieces.copy_ms += p.copy_ms; } const auto now = clock::now(); const double ms = std::chrono::duration(now - start).count(); @@ -2182,6 +2417,15 @@ struct DeviceState { kib(ShadowPages::Copy::guarded), kib(ShadowPages::Copy::unguarded), kib(ShadowPages::Copy::aliased), kib(ShadowPages::Copy::pinned), kib(ShadowPages::Copy::read_only), kib(ShadowPages::Copy::copy_on_write), kib(ShadowPages::Copy::write_watched)); + std::fprintf(stderr, + "[rt] d3d12: slot-133 shadow copies as pieces, a refresh: %.1f pieces (%.1f under 4 KiB, %.1f going on " + "where the one before ended), %.1f copy calls (%.1f offered to the GPU); walk %.3f ms, copies %.3f " + "ms\n", + double(shadow_pieces.pieces) / count, double(shadow_pieces.short_pieces) / count, + double(shadow_pieces.joinable) / count, double(shadow_pieces.calls) / count, + double(shadow_pieces.gpu_calls) / count, shadow_pieces.walk_ms / count, + shadow_pieces.copy_ms / count); + shadow_pieces = {}; shadow_copy_bytes = {}; shadow_logged = shadow_submissions; shadow_log_time = now; @@ -2197,6 +2441,9 @@ struct DeviceState { // defined after TitleTexture. std::mutex title_texture_mutex; std::map> title_textures; + leonida::TitleTextureRangeIndex texture_ranges; + std::map> mapped_title_textures; + void index_texture(const TitleTexture& t); 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); @@ -2227,6 +2474,7 @@ struct DeviceState { static constexpr std::uint64_t kPoolExtentMax = 1ull << 20; std::mutex title_window_mutex; // taken before shadow_mutex, never under it rt::d3d12::TitleBufferWindows external_windows; + std::atomic external_window_made{false}; // a window lies outside the arena: device_reachable looks there std::vector title_windows; std::atomic title_window_count{0}; // title_windows.size(), read without the mutex std::uint64_t title_window_bytes = 0; @@ -2335,7 +2583,9 @@ struct DeviceState { std::uint8_t* mapped{}; if (arena_allocate(size, kTitleWindowAlign, offset, arena_buffer)) { mapped = arena.mapped + offset; - } else if (!stream_windows() || !external_windows.allocate(*this, size, offset, mapped)) { + } else if (stream_windows() && external_windows.allocate(*this, size, offset, mapped)) { + external_window_made.store(true, std::memory_order_release); + } else { ++title_window_refusals; log_once("GPU address arena full (raise LEONIDA_ARENA_MB): title memory has no window; window KiB:", int(std::min(size >> 10, INT_MAX))); @@ -2438,8 +2688,52 @@ struct DeviceState { return true; } + // Whether a shader that forms heap_base + `va` reaches memory of the device's: the arena, a registered buffer (an + // upload or readback heap, an import, by its VA), a geometry copy, a title window outside the arena, or the copy + // of any title range (an address the layer already wrote for the title). A raw title address is none of these. + // A V#'s base is 48 bits and translated shaders sign-extend it (Gen.host_addr), so a wrapped one is also tried + // with its upper bits set. `buffers_checked`: the caller already asked the buffer index about `va` itself (the + // resolver does). Cheapest first; title_window_mutex only once a window outside the arena exists, and never + // called with it held. + bool device_reachable(std::uint64_t va, bool buffers_checked = false) { + if (va < arena.size) 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(); + for (int i = 0; i < (wrapped ? 2 : 1); ++i) { + const std::uint64_t at = candidates[i]; + if (aliases.shader_side(at)) return true; + std::uint64_t host = 0, room = 0; + if (geometry.cap() && geometry.lookup(arena.address + at, host, room)) return true; + if (external_window_made.load(std::memory_order_acquire)) { + std::lock_guard lock(title_window_mutex); + if (external_windows.lookup(arena.address + at, host, room)) return true; + } + if (context && !(i == 0 && buffers_checked) && context->knows_buffer_va(at)) return true; + } + return false; + } + + // One line per kind (and then at 2, 4, 8... of it): an address outside the title's memory that names nothing of + // the device's, written as a zero-size view (a V#) or 0 (a root view) instead of a raw address. + void note_unmapped(std::uint64_t va, std::uint64_t bytes) { + static std::atomic seen{0}; + const std::uint64_t n = seen.fetch_add(1, std::memory_order_relaxed) + 1; + if (n != 1 && (n & (n - 1))) return; + std::fprintf(stderr, + "[rt] d3d12: address 0x%llx (%llu bytes) is neither the title's memory nor any allocation of the " + "device's: the view is written with no base and no records (loads 0, stores dropped); %llu so " + "far\n", + static_cast(va), static_cast(bytes), + static_cast(n)); + } + // Called through title_va_aliases().resolve for an address with no copy yet. False: not the title's memory. - // True: it is, and `out` is its shader VA, 0 when no backing could be made (never the raw address). + // True: it is, and `out` is its shader VA, 0 when no backing could be made (never the raw address). An address + // past the arena that is not the title's memory either gets 0 too when nothing of the device's is there + // (device_reachable): heap_base + such an address is no allocation, and a shader that reads or writes through it + // takes an MMU fault (measured with Aftermath at world start: compute reads ~4 GiB and ~10 GiB above anything + // 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; @@ -2782,10 +3076,6 @@ struct DeviceState { --it; return addr < it->second && (addr-it->first) % kDescriptorSize == 0; } - // The shader-visible CBV/SRV/UAV heaps (arena offset -> end), for the scan of bound tables before a submission. - std::mutex cbv_heap_mutex; - std::map cbv_heaps; - // 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. @@ -2808,20 +3098,99 @@ struct DeviceState { // 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)); if (sampler) return; // S# words describe sampling state. They have no buffer address to translate. - // Each slot's V# and the counter V# in its second half, as a console heap's GPU copy (fix_vsharp): a base in - // the title's memory is rebased, one nothing backs becomes zero-size instead of a GPU fault at heap_base plus - // that address. - for (VkDeviceSize at = table_va; at + kDescriptorSize <= end; at += kDescriptorSize) { - auto* const w = reinterpret_cast(arena.mapped + at); - fix_vsharp(w, VsharpPath::table); - fix_vsharp(w + 4, VsharpPath::table); - } + for (VkDeviceSize at = table_va; at + 16 <= end; at += kDescriptorSize) { + auto* words = reinterpret_cast(arena.mapped + at); + 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]}; + bool unbacked = false; + if (!rebase_title_vsharp(words, aliases, true, &unbacked) && unbacked) { + // Title memory no window or geometry copy could back, or an address nothing backs: no base and no + // records, so a shader's load returns 0 and its store is dropped rather than written at heap_base + + // the raw address. The words are kept to look at again (retry_nulled_table_slot). The null form is the + // one a zero-size view has (base 0, no records): base 0 is the arena's zero page, which reads 0. + words[0] = 0; + words[1] &= 0xFFFF0000u; + words[2] = 0; + note_nulled_table_slot(at, original, words[3]); + } + // 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. Nothing + // retries it - a counter whose backing arrives later stays with no records until the title rewrites it. + if (at + kDescriptorSize <= end) fix_vsharp(words + 4, VsharpPath::table); + } + } + + // The table slots scan_title_table wrote null in place (the layer's heaps have no separate GPU copy), by arena + // offset, with the words the title gave them: at each later scan that still finds the null form there, the + // original is tried again, kNulledTableTries times at most, so a V# whose buffer or copy comes after the + // descriptor gets its base back. A slot the title rewrote meanwhile is forgotten and scanned as new. At most + // kNulledTableSlots are kept (past that a nulled slot stays null until rewritten). The null form is base 0 with no + // records, as a zero-size view has; a slot holding it is recognised by the rest of the words the title gave it, + // so a view Create*View wrote (also base 0) is only retried when its other words match a nulled slot's exactly. + struct NulledTableSlot { + std::uint32_t words[4]; + std::uint32_t tries; + }; + static constexpr std::size_t kNulledTableSlots = 65536; + static constexpr std::uint32_t kNulledTableTries = 16; + std::mutex nulled_table_mutex; + std::unordered_map nulled_table_slots; + std::atomic nulled_table_count{0}; + + void note_nulled_table_slot(VkDeviceSize at, const std::uint32_t (&original)[3], std::uint32_t word3) { + std::lock_guard lock(nulled_table_mutex); + if (nulled_table_slots.size() >= kNulledTableSlots) return; + nulled_table_slots[at] = {{original[0], original[1], original[2], word3}, 0}; + nulled_table_count.store(nulled_table_slots.size(), std::memory_order_relaxed); + } + + // A heap's arena range is released: what was noted in it is no longer anybody's slot. + void forget_nulled_table_slots(VkDeviceSize offset, VkDeviceSize bytes) { + if (!nulled_table_count.load(std::memory_order_relaxed)) return; + std::lock_guard lock(nulled_table_mutex); + std::erase_if(nulled_table_slots, [&](const auto& e) { return e.first - offset < bytes; }); + nulled_table_count.store(nulled_table_slots.size(), std::memory_order_relaxed); + } + + // True when `at` is a slot this scan nulled earlier and still holds that null form: tried again (and restored + // when its address is backed now), so the caller moves on. + bool retry_nulled_table_slot(VkDeviceSize at, std::uint32_t* words, leonida::TitleVaAliases& aliases) { + if (!nulled_table_count.load(std::memory_order_relaxed)) return false; + NulledTableSlot entry{}; + { + std::lock_guard lock(nulled_table_mutex); + const auto it = nulled_table_slots.find(at); + if (it == nulled_table_slots.end()) return false; + entry = it->second; + // entry.words[2] != 0: a view the title wrote with zero records is not one this scan nulled. + const bool still_null = words[0] == 0 && words[2] == 0 && entry.words[2] != 0 && + words[3] == entry.words[3] && words[1] == (entry.words[1] & 0xFFFF0000u); + if (!still_null || ++it->second.tries > kNulledTableTries) { + nulled_table_slots.erase(it); + nulled_table_count.store(nulled_table_slots.size(), std::memory_order_relaxed); + return still_null; // rewritten by the title: scanned as new; out of tries: left null + } + } + std::uint32_t retry[4] = {entry.words[0], entry.words[1], entry.words[2], words[3]}; + bool unbacked = false; + const bool rebased = rebase_title_vsharp(retry, aliases, true, &unbacked); + if (!rebased && unbacked) return true; // still nothing behind it: stays null, looked at again next scan + words[0] = retry[0]; + words[1] = retry[1]; + words[2] = retry[2]; + std::lock_guard lock(nulled_table_mutex); + nulled_table_slots.erase(at); + nulled_table_count.store(nulled_table_slots.size(), std::memory_order_relaxed); + return true; } // A buffer V# (its first four dwords at `w`) whose base is in the title's own memory gets the console VA of a GPU // copy of that memory, in place. False for anything else: a null slot, an image, a V# already in the arena, or - // memory no copy could be made of. - bool rebase_title_vsharp(std::uint32_t* w, leonida::TitleVaAliases& aliases, bool make_window = true) { + // memory no copy could be made of. `unbacked` (when given) is set for the last case: title memory with neither a + // window nor a geometry copy behind it, which the caller writes as a zero-size range. + bool rebase_title_vsharp(std::uint32_t* w, leonida::TitleVaAliases& aliases, bool make_window = true, + bool* unbacked = nullptr) { const std::uint32_t w0 = w[0], w1 = w[1], w2 = w[2], w3 = w[3]; if (!(w0 | w1 | w2 | w3) || (w3 >> 30)) return false; // null, or not a buffer V# (TYPE, dword 3 bits 30-31) const std::uint64_t base = std::uint64_t(w0) | (std::uint64_t(w1 & 0xFFFFu) << 32); @@ -2852,22 +3221,47 @@ struct DeviceState { if (!to) to = make_window ? aliases.resolve(base, span, leonida::TitleVaAliases::table_view) : aliases.shader_va(base, span); - if (to == base || (to >> 48)) return false; + // to == 0: the title's memory, and neither a window nor a geometry copy could back it, or an address that is + // nobody's (resolve_title_memory). to == base: no copy was asked for (a heap scan only looks existing ones up) + // or the address is left as it is; that holds only when the device can reach it (a raw title address, or one + // past every allocation, cannot be). A copy whose VA does not fit the V#'s 48 bits (an import below heap_base, + // off by default) cannot be named here either, and the raw base is no better. False in each case, and + // `unbacked` tells the caller to write it with no records instead of leaving a base a shader would add + // heap_base to. + if (!to || to == base || (to >> 48)) { + // The resolver (make_window) answers 0 for an address the device cannot reach, so a base it left as it + // is needs no second look; a heap scan only looked existing copies up and asks here. + if (unbacked) *unbacked = !to || (to >> 48) || (!make_window && !device_reachable(base)); + return false; + } w[0] = std::uint32_t(to); w[1] = (w1 & 0xFFFF0000u) | std::uint32_t((to >> 32) & 0xFFFFu); return true; } // Indexed by actual Vulkan address, never by a placed buffer's CPU address. + static bool filter_heap_releases() { + static const bool on = [] { + const auto* v = std::getenv("LEONIDA_CONSOLE_RELEASE_FILTER"); + return v && std::strcmp(v, "1") == 0; + }(); + return on; + } + leonida::DescriptorRangeChanges backing_changes; std::atomic released_backings{}; + std::atomic backing_generation{}; // every add and release std::mutex backing_mutex; leonida::BufferVaIndex gpu_backings; void backing(VkDeviceAddress address, uint64_t bytes, uint64_t id, bool add) { std::lock_guard lock(backing_mutex); + if (filter_heap_releases()) backing_changes.record(address, bytes); + backing_generation.fetch_add(1, std::memory_order_relaxed); if (add) gpu_backings.insert(address, bytes, id); else { gpu_backings.erase(address, id); released_backings.fetch_add(1, std::memory_order_release); + // LEONIDA_CONSOLE_HEAP_GPU: the key entries answering into it go at the next refresh. + if (heap_gpu) released_ranges.emplace_back(address - arena.address, bytes); } } @@ -2899,30 +3293,35 @@ struct DeviceState { uint64_t host{}, room{}; return geometry.cap() && geometry.lookup(bda, host, room) && room >= bytes; }; + const auto path = [this](unsigned p) { vsharp_paths[p].fetch_add(1, std::memory_order_relaxed); }; uint64_t to{}, room{}; if (aliases.range_of(base, to, room)) { - if (!to || room < bytes || !backed(to)) return 0; + if (!to || room < bytes || !backed(to)) return path(1), 0; aliases.note_translation(kind); - return to; + return path(0), to; } // 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; - if (backed(offset)) return offset; + if (backed(offset)) return path(2), offset; // 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); - if (to && encodable(to)) return to; + 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); uint64_t mapped{}; - if (to && aliases.range_of(base, mapped, room) && mapped == to && room >= bytes && backed(to)) return to; + if (to && aliases.range_of(base, mapped, room) && mapped == to && room >= bytes && backed(to)) + return path(4), to; } - return 0; + return path(5), 0; } + // vsharp_address's outcomes (diagnostics): alias hit, alias refused, arena VA, geometry copy, window, none. + static constexpr unsigned kVsharpPathCount = 6; + std::array, kVsharpPathCount> vsharp_paths{}; VsharpResult fix_vsharp(uint32_t* w, VsharpPath path) { if ((w[3] >> 30) || !w[2]) return VsharpResult::unchanged; // image, empty slot or raw pointer @@ -3087,6 +3486,7 @@ struct DeviceState { static_cast(arena.blocks.free_bytes() >> 10)); return false; } + // The V# writers look this range up by device address (vsharp_address): an allocation registers its backing. backing(arena.address + out, bytes, out, true); ++arena.allocations; arena.in_use += bytes; @@ -3108,21 +3508,29 @@ struct DeviceState { (unsigned long long)va, (unsigned long long)bytes); } - // Printed once at device release, so a run reports the size the arena needs. + // Printed once at device release, so a run reports the size the arena needs; the arena line also about once a + // minute with a console heap's log (report_arena_peak), since a run cut short never releases its device. void report_arena() { + report_arena_peak(); + report_title_memory(); + } + void report_arena_peak() { std::lock_guard lock(arena.mutex); if (!arena.size) return; const double mib = 1.0 / (1 << 20); std::fprintf(stderr, "[rt] d3d12: GPU address arena: peak end %.1f of %.1f MiB (%.1f%%), peak live %.1f MiB " - "(buffers %.1f, descriptor heaps %.1f, 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), %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, arena.use_peak[arena_shader] * 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, (unsigned long long)arena.allocations, (unsigned long long)arena.failures, arena.blocks.count(), arena.blocks.largest().size * mib, arena.blocks.free_bytes() * mib); + } + void report_title_memory() { { std::lock_guard windows(title_window_mutex); const auto geometry_spans = std::count_if(pool_spans.begin(), pool_spans.end(), @@ -3150,6 +3558,8 @@ struct DeviceState { backing(arena.address + offset, bytes, offset, false); arena.in_use -= bytes; arena.use_in_use[use] -= bytes; + // A heap copy re-fixes its slots when a backing has gone (released_backings): the range is no view's. + backing(arena.address + offset, bytes, offset, false); } if (fault != leonida::ArenaBlocks::Fault::none && arena_report_due()) { std::fprintf(stderr, @@ -3161,6 +3571,7 @@ struct DeviceState { static_cast(arena.blocks.free_bytes() >> 10), static_cast(arena.blocks.faults())); arena_report_suppressed("arena releases"); + } check_arena("a release"); } @@ -3196,8 +3607,8 @@ struct DeviceState { std::uint64_t console_va = 0; VkDeviceSize bytes = 0; std::uint64_t shader_va = 0; // where shaders read it - VkDeviceSize guard = 0; - bool resource_heap = false; + VkDeviceSize guard = 0; // null bytes after the GPU copy (heap_guard_bytes/heap_guard_for), its allocation + bool resource_heap = false; // a CBV/SRV/UAV heap; a sampler heap's S#s are copied as written bool imported = false; std::uint8_t* copy = nullptr; // writable GPU mirror of the console heap // Keep large scratch allocations out of the low addresses the title can use for its heap. @@ -3209,7 +3620,8 @@ struct DeviceState { VkDeviceMemory memory = VK_NULL_HANDLE; std::uint64_t pin = 0; // the imported pages' leonida::kernel_writes pin while `memory` lives std::size_t scan_at = 0; // the next slot the T# scan reads - uint64_t checked_generation{}, alias_generation{}; + uint64_t checked_generation{}, alias_generation{}, backing_cursor{}, alias_cursor{}; + uint64_t release_sweeps{}, release_candidates{}, release_fixes{}, release_rebases{}, release_full{}; // copy bool identity = false; ShadowPagesPtr pages; @@ -3221,6 +3633,12 @@ struct DeviceState { std::set empty_slots; std::uint32_t next_empty = 0; std::size_t retry_at = 0; // where retry_console_slots goes on + // V#s naming an address nothing backs that is not the title's memory: null in the copy, and looked at again a + // few times (kUnmappedTries, at most kUnmappedRetrySlots a submission) in case their buffer is made after the + // descriptor. + std::vector unmapped_tries; // per slot: 0, or the looks so far (it is in `unmapped`) + std::vector unmapped; + std::size_t unmapped_at = 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; @@ -3232,10 +3650,50 @@ struct DeviceState { std::uint64_t copied = 0, vsharps = 0, unbacked = 0, retried = 0; std::uint64_t images[5] = {}; // by TitleImage 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 + // how often an exact-key translation would be found again); rescans after a backing release and their cost. + std::uint64_t changed[4] = {}, vsharp_halves = 0, vsharp_repeats = 0; + std::uint64_t rescans = 0, rescanned = 0; + double rescan_ms = 0; + std::vector> seen_keys; + // LEONIDA_CONSOLE_HEAP_GPU (DeviceState::attach_console_heap_gpu): the translation pass's index of this heap + // (-1: fixed on the CPU), the import of `input` the pass reads, the slots holding a V# pair (translated again + // when a backing goes), and the slots queued for the pass since the last log line. + int gpu = -1; + VkBuffer input_buffer = VK_NULL_HANDLE; + VkDeviceMemory input_memory = VK_NULL_HANDLE; + std::vector vsharp_bits; + std::uint64_t gpu_queued = 0; + std::uint32_t gpu_high = 0; // one past the highest slot the title has written (a rescan's range) }; std::mutex console_heap_mutex; // taken before title_window_mutex, shadow_mutex and descriptor_mutex std::vector> console_heaps; + // 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 + // index past the heap read whatever the arena held after it, and a buffer V# made of those bytes sent loads and + // stores to heap_base + garbage (GPU MMU faults at world start). With the guard such an index reads a null + // descriptor instead (loads 0, stores dropped). As VIctory does for its host heaps (crates/victory-shader/src/emit + // "Heap indices": at least 2^21 slots, those past the title's own null). + // Two shapes: `heap_guard_bytes` is the fixed reach a directly indexed heap is given (2^21 slots, bounded so the + // heap and its guard stay inside a 32-bit shader offset, LEONIDA_HEAP_GUARD_MB overrides), and `heap_guard_for` + // is the per-heap guard a console heap's copy takes - as large as the heap, at least 1 MiB, at most + // `heap_guard_cap()` (64 MiB by default, 0: no guard). Either comes out of the arena every default-heap buffer is + // placed in; a heap the arena has no room for with its guard is made without one (logged). + static constexpr VkDeviceSize kHeapGuardFloor = VkDeviceSize(1) << 20; + static VkDeviceSize heap_guard_cap() { + static const VkDeviceSize bytes = [] { + constexpr VkDeviceSize fallback = VkDeviceSize(64) << 20; + char text[16] = {}; + const DWORD n = GetEnvironmentVariableA("LEONIDA_HEAP_GUARD_MB", text, sizeof(text)); + if (n == 0 || n >= sizeof(text)) return fallback; + for (DWORD i = 0; i < n; ++i) + if (text[i] < '0' || text[i] > '9') return fallback; // "-1" and the like: the default + return VkDeviceSize(std::min(std::strtoull(text, nullptr, 10), 1024)) << 20; + }(); + return bytes; + } static constexpr VkDeviceSize kHeapIndexReach = VkDeviceSize(1) << 26; // 2^21 slots of 32 bytes static VkDeviceSize heap_guard_bytes() { static const VkDeviceSize bytes = [] { @@ -3246,6 +3704,17 @@ struct DeviceState { }(); return bytes; } + // The null bytes after a heap of `bytes`: as many as the heap, at least `floor`, at most heap_guard_cap(); grown so + // heap and guard together end on a multiple of `align`. 0 with no cap. + static VkDeviceSize heap_guard_for(VkDeviceSize bytes, VkDeviceSize floor, VkDeviceSize align) { + const VkDeviceSize cap = heap_guard_cap(); + if (!cap || !bytes) return 0; + VkDeviceSize guard = std::min(std::max(bytes, floor), cap); + if (align > 1) guard = (bytes + guard + align - 1) / align * align - bytes; + return guard; + } + std::atomic arena_guard_bytes{0}; // the heap guards in the arena now (report_arena) + // [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) { @@ -3263,35 +3732,52 @@ struct DeviceState { } // Slot `slot` of a heap copy, as the title wrote it, fixed up as described above. True when it is settled: not a - // T# whose texture is still to come, nor a V# into the title's memory that got no copy. - bool fix_console_slot(ConsoleHeap& heap, std::size_t slot) { + // T# whose texture is still to come, nor a V# into the title's memory that got no copy. `unmapped` (when given) is + // set for a V# written null because its base is neither the title's memory nor anything of the device's: settled, + // but its buffer may still be made (the round-robin probe in refresh_console_heap). A sampler heap holds S#s: + // copied as written. + bool fix_console_slot(ConsoleHeap& heap, std::size_t slot, bool* unmapped = nullptr) { std::uint32_t w[kDescriptorSize / 4]; std::memcpy(w, heap.previous + slot * kDescriptorSize, kDescriptorSize); bool settled = true, empty = false; - if (!(w[3] >> 30)) { - const auto path = heap.scratch ? VsharpPath::scratch : VsharpPath::shadow; - const auto result = fix_vsharp(w, path); - const auto counter = fix_vsharp(w + 4, path); + if (unmapped) *unmapped = false; + const VsharpPath path = heap.scratch ? 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)) { + // A buffer V#: rewritten to the address its bytes are backed at (fix_vsharp: the console shadow, or the + // console scratch an imported heap rewrites). A base nothing backs is written with no base and no records, + // settled, and left for the bounded round-robin probe in refresh_console_heap in case its buffer is made + // after the descriptor. + const VsharpResult result = fix_vsharp(w, path); if (result == VsharpResult::rebased) ++heap.vsharps; - if (result == VsharpResult::empty || counter == VsharpResult::empty) { + if (result == VsharpResult::empty) { + // Only the GPU copy changes; the title's bytes (heap.previous) stay as written. + ++heap.unbacked; + empty = true; + } + // 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 left to retry_console_slots. + if (fix_vsharp(w + 4, path) == VsharpResult::empty) { ++heap.unbacked; empty = true; } } 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) - note_refused_tsharp(heap, slot * kDescriptorSize, words, why); - ++heap.images[unsigned(result)]; - settled = result != TitleImage::unknown && result != TitleImage::refused; - if (result == TitleImage::not_tsharp) std::memset(w, 0, 16); - } else { - ++heap.images[unsigned(TitleImage::not_tsharp)]; - std::memset(w, 0, 16); - } + const char* why = nullptr; + const TitleImage result = + leonida::gfx10::is_image(words) ? bind_title_image(*this, words, &why) : TitleImage::not_tsharp; + ++heap.images[unsigned(result)]; + settled = result != TitleImage::unknown && result != TitleImage::refused; + if (result == TitleImage::unknown || result == TitleImage::refused) + note_refused_tsharp(heap, slot * kDescriptorSize, words, why); + // 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 + // takes the slot as a V# (an index from data, or one past what the title filled) adds heap_base to + // words that name nothing: in the GPU copy the slot is null, and left to retry_console_slots. + if (result == TitleImage::not_tsharp) std::memset(w, 0, 16); } if (empty) heap.empty_slots.insert(std::uint32_t(slot)); else if (!heap.empty_slots.empty()) heap.empty_slots.erase(std::uint32_t(slot)); @@ -3300,6 +3786,34 @@ struct DeviceState { return settled; } + // Diagnostics only: the class of a changed slot, and whether its V# halves were seen before (ConsoleHeap::changed). + static void note_changed_slot(ConsoleHeap& heap, const std::uint8_t* bytes) { + std::uint32_t w[8]; + std::memcpy(w, bytes, sizeof(w)); + if (!(w[0] | w[1] | w[2] | w[3] | w[4] | w[5] | w[6] | w[7])) { + ++heap.changed[0]; + return; + } + if (w[3] >> 30) { + leonida::gfx10::ImageWords words; + std::memcpy(words.data(), w, sizeof(words)); + ++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]}; + } + } + // 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 @@ -3323,6 +3837,8 @@ struct DeviceState { const std::size_t slot = at / kDescriptorSize; if (!std::memcmp(heap.previous + at, heap.input + at, kDescriptorSize)) continue; std::memcpy(heap.previous + at, heap.input + at, kDescriptorSize); + if (heap.unmapped_tries[slot]) heap.unmapped_tries[slot] = 1; // new words: their looks start over + note_changed_slot(heap, heap.previous + at); if (budget_us && !heap.fix_over && !(++heap.fix_count & 15) && std::chrono::steady_clock::now() - heap.fix_start >= std::chrono::microseconds(budget_us)) heap.fix_over = true; @@ -3336,13 +3852,49 @@ struct DeviceState { } continue; } - if (fix_console_slot(heap, slot)) { + bool unmapped = false; + if (fix_console_slot(heap, slot, &unmapped)) { heap.retry[slot] = 0; } else if (!heap.retry[slot]) { heap.retry[slot] = 1; heap.retries.push_back(std::uint32_t(slot)); } + if (unmapped && !heap.unmapped_tries[slot]) { + heap.unmapped_tries[slot] = 1; + heap.unmapped.push_back(std::uint32_t(slot)); + } + } + } + + // The V#s fix_console_slot wrote null because nothing backs their base: looked at again, round robin, at most + // kUnmappedRetrySlots a submission, each kUnmappedTries times at most. A descriptor the title wrote before making + // its buffer (or a buffer another thread registers just after) then gets its base back; one that stays unmapped + // drops out of the list, so data the title keeps in its heap does not cost a lookup at every submission. + static constexpr std::size_t kUnmappedRetrySlots = 2048; + static constexpr std::uint8_t kUnmappedTries = 4; + void retry_unmapped_slots(ConsoleHeap& heap) { + std::size_t i = heap.unmapped_at; + // Each entry once a submission at most: the looks are a submission apart. + const std::size_t visits = std::min(kUnmappedRetrySlots, heap.unmapped.size()); + for (std::size_t visited = 0; visited < visits && !heap.unmapped.empty(); ++visited) { + if (i >= heap.unmapped.size()) i = 0; + const std::uint32_t slot = heap.unmapped[i]; + // Zeroed since (unmapped_tries reset), reachable now, or out of looks: out of the list. + bool done = !heap.unmapped_tries[slot]; + if (!done) { + bool unmapped = false; + fix_console_slot(heap, slot, &unmapped); + done = !unmapped || ++heap.unmapped_tries[slot] > kUnmappedTries; + } + if (done) { + heap.unmapped_tries[slot] = 0; + heap.unmapped[i] = heap.unmapped.back(); + heap.unmapped.pop_back(); + } else { + ++i; + } } + heap.unmapped_at = i; } // The slots of a heap copy not settled yet: fixed again, and kept while they are still not. Round robin, for at @@ -3401,6 +3953,7 @@ struct DeviceState { void refresh_console_heap(ConsoleHeap& heap) { // console_heap_mutex held if (heap.imported) return; // directly imported sampler heap + if (heap.gpu >= 0) return refresh_console_heap_gpu(heap); using clock = std::chrono::steady_clock; const auto ms = [](clock::time_point a, clock::time_point b) { return std::chrono::duration(b - a).count(); @@ -3413,7 +3966,10 @@ struct DeviceState { const auto first = std::uint32_t(offset / kDescriptorSize); const auto end = std::uint32_t((offset + bytes) / kDescriptorSize); heap.empty_slots.erase(heap.empty_slots.lower_bound(first), heap.empty_slots.lower_bound(end)); - for (auto slot = first; slot < end; ++slot) heap.retry[slot] = 0; + for (auto slot = first; slot < end; ++slot) { + heap.retry[slot] = 0; + heap.unmapped_tries[slot] = 0; + } heap.live_vsharps.clear_range(first, end); }); const auto t1 = clock::now(); @@ -3426,14 +3982,54 @@ struct DeviceState { if (heap.resource_heap && (generation != heap.checked_generation || alias_generation != heap.alias_generation)) { heap.alias_generation = alias_generation; heap.checked_generation = generation; + leonida::DescriptorRanges backing, aliases; + bool filtered = filter_heap_releases(); + if (filtered) { + { + std::lock_guard lock(backing_mutex); + filtered = backing_changes.read(heap.backing_cursor, backing); + } + filtered &= leonida::title_va_aliases().changed_ranges(heap.alias_cursor, aliases); + backing.merge(); + aliases.merge(); + } + ++heap.release_sweeps; + heap.release_full += !filtered; + const auto bda = [&](uint64_t base) { + if (signed_vsharp_offsets() && (base & (1ull << 47))) base |= ~((1ull << 48)-1); + return arena.address + base; + }; + const auto affected = [&](const uint32_t* src, const uint32_t* dst) { + if ((src[3] >> 30) || !src[2]) return false; + const uint64_t base = uint64_t(src[0]) | (uint64_t(src[1] & 0xffff) << 32); + const uint64_t fixed = uint64_t(dst[0]) | (uint64_t(dst[1] & 0xffff) << 32); + const auto stride = (src[1] >> 16) & 0x3fff; + const uint64_t bytes = uint64_t(src[2]) * (stride ? stride : 1); + return aliases.overlaps(base, 1) || backing.overlaps(bda(base), bytes) || + (dst[2] && backing.overlaps(bda(fixed), bytes)); + }; + const auto before = heap.vsharps; + ++heap.rescans; + const auto rescan_start = clock::now(); // Even an unchanged title slot may name a buffer released since the last submission. // Walk the host-RAM V# bitset instead of reading every slot of `heap.copy` (which may be uncached WC VRAM). heap.live_vsharps.for_each([&](std::size_t slot) { + ++heap.release_candidates; + if (filtered) { + const auto at = slot * kDescriptorSize; + const auto* src = reinterpret_cast(heap.previous + at); + const auto* dst = reinterpret_cast(heap.copy + at); + if (!affected(src, dst) && !affected(src + 4, dst + 4)) return; + } + ++heap.release_fixes; + ++heap.rescanned; if (!fix_console_slot(heap, slot) && !heap.retry[slot]) { heap.retry[slot] = 1; heap.retries.push_back(uint32_t(slot)); } }); + heap.release_rebases += heap.vsharps - before; + heap.rescan_ms += ms(rescan_start, clock::now()); } const auto t2 = clock::now(); // A settled zero can acquire GPU backing without a CPU map event. Probe at most eight in @@ -3452,6 +4048,7 @@ struct DeviceState { } } if (!heap.retries.empty()) retry_console_slots(heap); + if (!heap.unmapped.empty()) retry_unmapped_slots(heap); const auto t3 = clock::now(); heap.pages_ms += ms(t0, t1); heap.fix_ms += ms(t1, t2); @@ -3461,6 +4058,16 @@ struct DeviceState { // Before every submission, ahead of the slot-133 shadows. void refresh_console_heaps() { std::lock_guard lock(console_heap_mutex); + 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) {}); + struct GpuEnd { // after every heap's slots are queued, however the loop ends + DeviceState& state; + bool on; + ~GpuEnd() { + if (on) state.console_heap_gpu_end(); + } + } gpu_end{*this, heap_pass}; for (const auto& heap : console_heaps) { const auto start = std::chrono::steady_clock::now(); refresh_console_heap(*heap); @@ -3478,8 +4085,8 @@ struct DeviceState { "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, T#s %llu known, %llu bound, %llu naming no texture, %llu refused, %llu words " - "that are no T# (data)\n", + "no records (%zu naming nothing waiting for another look), 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", static_cast(heap->refreshes), "copied", double(heap->copied) / 1024.0 / count, @@ -3488,17 +4095,53 @@ struct DeviceState { double(heap->retried) / count, heap->retries.size(), static_cast(heap->pages ? heap->pages->faults() : 0), static_cast(heap->vsharps), - static_cast(heap->unbacked), + static_cast(heap->unbacked), heap->empty_slots.size(), static_cast(heap->images[unsigned(TitleImage::known)]), static_cast(heap->images[unsigned(TitleImage::bound)]), static_cast(heap->images[unsigned(TitleImage::unknown)]), static_cast(heap->images[unsigned(TitleImage::refused)]), static_cast(heap->images[unsigned(TitleImage::not_tsharp)])); + if (heap->release_sweeps && filter_heap_releases()) + std::fprintf(stderr, "[rt] CPU release filter: %llu sweeps, %llu live slots, %llu fixes, %llu rebases, %llu full fallbacks\n", + (unsigned long long)heap->release_sweeps, (unsigned long long)heap->release_candidates, + (unsigned long long)heap->release_fixes, (unsigned long long)heap->release_rebases, + (unsigned long long)heap->release_full); + heap->release_sweeps = heap->release_candidates = heap->release_fixes = heap->release_rebases = heap->release_full = 0; + if (heap->resource_heap) { + std::uint64_t paths[kVsharpPathCount]; + for (unsigned i = 0; i < kVsharpPathCount; ++i) + paths[i] = vsharp_paths[i].exchange(0, std::memory_order_relaxed); + std::fprintf(stderr, + "[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; rescans %llu (%.1f " + "V# slots and %.3f ms each); V# resolutions since the last line: alias %llu, alias " + "refused %llu, arena %llu, geometry %llu, window %llu, none %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, + heap->vsharp_halves ? 100.0 * double(heap->vsharp_repeats) / double(heap->vsharp_halves) + : 0.0, + static_cast(heap->rescans), + heap->rescans ? double(heap->rescanned) / double(heap->rescans) : 0.0, + heap->rescans ? heap->rescan_ms / double(heap->rescans) : 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])); + for (auto& n : heap->changed) n = 0; + heap->vsharp_halves = heap->vsharp_repeats = heap->rescans = heap->rescanned = 0; + heap->rescan_ms = 0; + } + if (heap->gpu >= 0) log_console_heap_gpu(*heap, count); 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)) { + arena_log_time = start; + report_arena_peak(); + } } } + std::chrono::steady_clock::time_point arena_log_time{}; // console_heap_mutex held // The heap's pages imported as host memory (see above): true with `heap` filled in, false when they cannot be // (no VK_EXT_external_memory_host, a page not committed or write-combined, a driver refusal, or a device address @@ -3590,13 +4233,46 @@ struct DeviceState { heap->bytes = bytes; // Self-written V#s must be rebased without changing the title's descriptor bytes. // A directly indexed heap can lie outside the main arena and still fit in a 32-bit shader offset. + // A resource heap's copy is followed by null slots (heap_guard_bytes), rounded so the whole stays 64 KiB + // aligned for an import. heap->resource_heap = resource_heap; // Round the guarded import up to Wine's allocation granularity. if (bytes > (1ull << 32)) return false; const VkDeviceSize requested = resource_heap ? heap_guard_bytes() : 0; const VkDeviceSize guard = requested && bytes + requested <= (1ull << 32) ? ((bytes + requested + 65535) & ~VkDeviceSize(65535)) - bytes : 0; - if (resource_heap && geometry.cap()) { + // 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 | + // previous] stay in host memory. No room in the arena: the import, as without the switch. + bool in_arena = false; + if (resource_heap && geometry.cap() && heap_gpu && console_heap_gpu_enabled() && console_heap_arena_enabled() && + bytes <= SIZE_MAX / 2) { + VkDeviceSize offset = 0; + const VkDeviceSize size = bytes + guard; + if (arena_allocate(size, 65536, offset, arena_descriptor_heap)) { + heap->scratch.reset(static_cast( + VirtualAlloc(nullptr, bytes * 2, MEM_TOP_DOWN | MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE))); + if (heap->scratch) { + heap->input = heap->scratch.get(); + heap->previous = heap->scratch.get() + bytes; + heap->shader_va = offset; + heap->copy = arena.mapped + offset; + heap->guard = guard; + heap->imported = false; + in_arena = true; + std::fprintf(stderr, "[rt] d3d12: LEONIDA_CONSOLE_HEAP_ARENA: console descriptor heap 0x%llx's " + "copy and %llu MiB guard in the arena at 0x%llx (memory type %u)\n", + static_cast(console_va), + static_cast(guard >> 20), + static_cast(offset), unsigned(arena.memory_type)); + } else { + arena_release(offset, size, arena_descriptor_heap); + } + } + } + if (in_arena) { + } else if (resource_heap && geometry.cap()) { if (bytes > (SIZE_MAX - guard) / 3) return false; // [copy | guard | input | previous]: the import covers the copy and its guard. heap->scratch.reset(static_cast(VirtualAlloc(nullptr, bytes * 3 + guard, MEM_TOP_DOWN | @@ -3652,6 +4328,7 @@ struct DeviceState { } heap->retry.assign(std::size_t(bytes / kDescriptorSize), 0); heap->live_vsharps.reset(std::size_t(bytes / kDescriptorSize)); + heap->unmapped_tries.assign(std::size_t(bytes / kDescriptorSize), 0); heap->pages = make_shadow_pages(reinterpret_cast(static_cast(console_va)), heap->input, std::size_t(bytes)); } @@ -3659,8 +4336,12 @@ struct DeviceState { if (shader_va != console_va) console_heap_ranges().add(console_va, bytes, shader_va); 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); { std::lock_guard lock(console_heap_mutex); + if (heap->gpu >= 0) gpu_heaps[std::size_t(heap->gpu)] = heap.get(); if (!imported) refresh_console_heap(*heap); if (heap->copy) { std::unique_lock ranges(console_copy_ranges_mutex); @@ -3669,13 +4350,14 @@ struct DeviceState { console_heaps.push_back(std::move(heap)); } std::fprintf(stderr, - "[rt] d3d12: console descriptor heap 0x%llx (%llu KiB): shaders read it at heap_base + 0x%llx, %s; " - "%llu KiB of null slots after it\n", - static_cast(console_va), static_cast(bytes >> 10), - static_cast(shader_va), + "[rt] d3d12: console %s descriptor heap 0x%llx (%llu KiB): shaders read it at heap_base + 0x%llx, " + "%s; %llu KiB of null slots after it%s\n", + resource_heap ? "CBV/SRV/UAV" : "sampler", static_cast(console_va), + static_cast(bytes >> 10), static_cast(shader_va), imported ? "the title's pages imported as host memory" : "a descriptor copy brought up to date before every submission", - static_cast(guarded >> 10)); + static_cast(guarded >> 10), + imported && resource_heap ? " (imported pages have no guard)" : ""); return true; } @@ -3702,9 +4384,21 @@ struct DeviceState { console_heaps.erase(it); 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) { + heap_gpu->remove_heap(heap->gpu); + gpu_heaps[std::size_t(heap->gpu)] = nullptr; + } } console_heap_ranges().remove(console_va); heap->pages.reset(); + 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. + while (heap_gpu->uncommitted()) Sleep(0); + context->wait_retire_ticket(context->submitted_retire_ticket()); + if (heap->input_buffer) context->vk.vkDestroyBuffer(info.device, heap->input_buffer, nullptr); + if (heap->input_memory) context->vk.vkFreeMemory(info.device, heap->input_memory, nullptr); + } if (heap->buffer) { // As for an imported slot-133 buffer: the title may free its pages right after, so the memory goes once // what was submitted retires, not through the deferred queue. @@ -3715,6 +4409,1108 @@ struct DeviceState { } else { arena_release(heap->shader_va, heap->bytes + heap->guard, arena_descriptor_heap); } + arena_guard_bytes.fetch_sub(heap->guard, std::memory_order_relaxed); + } + + // ---- LEONIDA_CONSOLE_HEAP_GPU=1: the console heaps' V#s rebased by a compute pass (src/console_heap_gpu.h) ---- + // Before every submission the CPU still finds the changed slots (the heap's ShadowPages, then a compare with the + // bytes each slot was last made from) and registers the T#s, as fix_console_slot does; every changed slot is then + // queued for the pass, which writes it into the copy at the start of the submission (the context's prelude). A + // V# half the pass's tables cannot answer is written with no records and comes back as a miss once its submission + // is done: resolved here with vsharp_address (which may make a geometry copy) within LEONIDA_CONSOLE_GPU_RESOLVE_US + // a refresh (2000 by default), its answer entered in the key table and its slots queued again. Words that got no + // backing are asked again every LEONIDA_CONSOLE_GPU_RETRY_MS (500), on a timer to bound the per-submission cost. + // When a backing or an alias range goes, the key entries that answered into it are dropped and every V# slot of + // the heap is translated again (on the GPU: a list of slot indices). + std::unique_ptr heap_gpu; + std::array gpu_heaps{}; // console_heap_mutex + std::vector> released_ranges; // (shader VA, bytes); backing_mutex + struct GpuKeyHash { + std::size_t operator()(const leonida::ConsoleHeapKeys::Key& k) const { + return leonida::ConsoleHeapKeys::hash(k); + } + }; + // The rest: console_heap_mutex. Unresolved words with the slots that missed on them (heap << 28 | slot), and + // whether the resolver has them. + struct GpuUnresolved { + std::vector slots; + bool asked = false; + }; + std::unordered_map gpu_unresolved; + // The resolver: a thread of ours that answers missed words with vsharp_address, off the submitting thread (one + // answer can wait milliseconds for the geometry worker's lock). + // Requests and answers pass under its own mutex; the refresh hands words over and takes answers, never waits. + struct GpuAnswer { + leonida::ConsoleHeapKeys::Key key; + std::uint64_t to, span; + bool retry; + }; + struct GpuResolver { + std::mutex mutex; + std::condition_variable wake; + bool stop = false; + std::vector> requests; // (words, a retry of no backing) + std::vector answers; + // T#s to register (bind_title_image), the slot's words: the refresh only decodes them. Resolver-only state: + // the words registered recently (not asked again) and those whose texture is still to come (asked again). + std::vector tsharps; + std::unordered_set registered; + std::deque> waiting; + std::thread thread; + ~GpuResolver() { halt(); } + void halt() { + { + std::lock_guard lock(mutex); + stop = true; + } + wake.notify_all(); + if (thread.joinable()) thread.join(); + } + }; + std::unique_ptr gpu_resolver; + std::array, 5> gpu_tsharps{}; // the resolver's T# registrations, by TitleImage + std::size_t gpu_asked = 0; // requests handed over and not answered yet + struct GpuUnbacked { + std::chrono::steady_clock::time_point at; // when it may be asked again + leonida::ConsoleHeapKeys::Key key; + std::uint32_t tries = 0; // asked again so far: the wait doubles each time, up to 64x retry_ms + }; + std::deque gpu_unbacked; // words answered "no backing", by when they may be asked again (roughly) + std::unordered_map gpu_unbacked_tries; // being asked + std::uint64_t gpu_alias_generation = ~0ull; + std::chrono::steady_clock::time_point gpu_ranges_at{}; + std::vector gpu_ranges; + leonida::ConsoleHeapSpans gpu_backed, gpu_ask; + std::uint64_t gpu_backed_generation = ~0ull, gpu_ask_generation = ~0ull; + std::size_t gpu_backed_blocks = ~std::size_t(0); + std::chrono::steady_clock::time_point gpu_backed_at{}; + std::vector gpu_queue_scratch; + bool gpu_rescan = false, gpu_rescan_after_resolve = false; + std::chrono::steady_clock::time_point gpu_rescan_asked{}; + // LEONIDA_CONSOLE_GPU_FILTER=1 (default: LEONIDA_CONSOLE_RELEASE_FILTER's value): a release, an alias range that + // went or a word answered since asks for a rescan of the slots it touches (the release filter's interval rule, + // 8a22e92c8) instead of every V# slot: the GPU passes over the rest on its device-local metadata. + // gpu_filter_shader: shader-VA spans (released backings, alias copies that went); gpu_filter_title: title VAs + // (words backed since). Overflows and key resets still rescan everything. + static bool gpu_filter_enabled() { + static const bool on = [] { + char text[8] = {}; + if (GetEnvironmentVariableA("LEONIDA_CONSOLE_GPU_FILTER", text, sizeof(text)) && text[0]) + return text[0] == '1'; + return GetEnvironmentVariableA("LEONIDA_CONSOLE_RELEASE_FILTER", text, sizeof(text)) && text[0] == '1'; + }(); + return on; + } + bool gpu_rescan_filtered = false; + leonida::ConsoleHeapSpans gpu_filter_shader, gpu_filter_title; + void request_rescan_after_resolve() { + if (!gpu_rescan_after_resolve) gpu_rescan_asked = std::chrono::steady_clock::now(); + gpu_rescan_after_resolve = true; + } + struct GpuMiss { + leonida::ConsoleHeapKeys::Key key; + std::uint32_t code; // heap << 28 | slot; UINT32_MAX once handled + }; + std::vector gpu_miss_scratch; + struct GpuCounts { + std::uint64_t misses = 0, resolved = 0, none = 0, flips = 0, rescans = 0, dropped = 0, released = 0; + std::uint64_t known_misses = 0, put_failed = 0, backed_rebuilds = 0, backed_cuts = 0, key_resets = 0; + std::uint64_t retried = 0, filtered_rescans = 0; + double backed_ms = 0; + double resolve_ms = 0, begin_ms = 0; + double part_ms[5] = {}; // before: alias probes, drain + releases, range table, backed table, ask table + } gpu_counts; + + // LEONIDA_SHADOW_GPU=1 copies aliased shadow pages on the GPU at the start of the submission. + // The source uses VK_EXT_external_memory_host to import the mapped title section. An import is + // made per 2 MiB-aligned window of the view, kept while xmem's map journal shows no change over it, and lives until + // the last pass that copies from it retires. Destinations outside the arena, and pages that will not import, are + // copied by the CPU as before. + static bool shadow_gpu_enabled() { + static const bool on = [] { + char value[4] = {}; + return GetEnvironmentVariableA("LEONIDA_SHADOW_GPU", value, sizeof(value)) == 1 && value[0] == '1'; + }(); + return on; + } + struct ShadowImport { + DeviceState* device = nullptr; + std::uintptr_t base = 0; + std::size_t bytes = 0; + VkBuffer buffer = VK_NULL_HANDLE; + VkDeviceMemory memory = VK_NULL_HANDLE; + std::uint64_t generation = 0; // title_memory_map's, when last found unchanged + ~ShadowImport() { + if (buffer) device->context->vk.vkDestroyBuffer(device->info.device, buffer, nullptr); + if (memory) device->context->vk.vkFreeMemory(device->info.device, memory, nullptr); + } + }; + std::mutex shadow_import_mutex; + std::map> shadow_imports; // by base + std::uint64_t shadow_import_bytes = 0; + struct ShadowGpuCounts { + std::uint64_t copies = 0, bytes = 0, imports = 0, imported = 0, dropped = 0, refused = 0, outside = 0; + } shadow_gpu_counts; // shadow_import_mutex + + static bool shadow_gpu_copy(void* context, std::uint8_t* to, const std::uint8_t* from, std::size_t bytes) { + return static_cast(context)->gpu_copy_shadow(to, from, bytes); + } + // Shadows with memory of their own (no room in the arena): their mapping and buffer, for gpu_copy_shadow. + struct CopyTarget { + std::size_t bytes; + VkBuffer buffer; + }; + std::map copy_targets; // shadow_import_mutex + void add_copy_target(const std::uint8_t* mapped, std::size_t bytes, VkBuffer buffer) { + if (!shadow_gpu_enabled() || !mapped || !buffer) return; + std::lock_guard lock(shadow_import_mutex); + copy_targets[mapped] = {bytes, buffer}; + } + // Before the buffer goes: no copy into it is recorded after this (one already recorded runs before it is freed: + // the buffer goes to the deferred queue, behind the submission that recorded it). + void remove_copy_target(const std::uint8_t* mapped) { + if (!shadow_gpu_enabled() || !mapped) return; + VkBuffer buffer = VK_NULL_HANDLE; + { + std::lock_guard lock(shadow_import_mutex); + const auto it = copy_targets.find(mapped); + if (it == copy_targets.end()) return; + buffer = it->second.buffer; + copy_targets.erase(it); + } + if (heap_gpu) heap_gpu->drop_copies_to(buffer); + } + // 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) { + buffer = arena.buffer; + offset = VkDeviceSize(to - arena.mapped); + return true; + } + if (external_windows.find_mapped(to, n, buffer, offset)) return true; + auto it = copy_targets.upper_bound(to); // shadow_import_mutex held + if (it == copy_targets.begin()) return false; + --it; + if (to < it->first || n > it->second.bytes || std::size_t(to - it->first) > it->second.bytes - n) return false; + buffer = it->second.buffer; + offset = VkDeviceSize(to - it->first); + return true; + } + bool gpu_copy_shadow(std::uint8_t* to, const std::uint8_t* from, std::size_t n) { + if (!heap_gpu || !n) return false; + std::lock_guard lock(shadow_import_mutex); + VkBuffer dst_buffer = VK_NULL_HANDLE; + VkDeviceSize dst_offset = 0; + if (!copy_destination(to, n, dst_buffer, dst_offset)) { + ++shadow_gpu_counts.outside; + return false; + } + const auto src = reinterpret_cast(from); + std::shared_ptr found; + auto it = shadow_imports.upper_bound(src); + if (it != shadow_imports.begin()) { + --it; + ShadowImport& cand = *it->second; + if (src >= cand.base && src + n <= cand.base + cand.bytes) { + std::uint64_t now = 0; + bool moved = false; + if (!leonida::title_memory_map::changes_since(cand.generation, now, cand.base, cand.base + cand.bytes, + [&](std::uintptr_t, std::uintptr_t) { moved = true; })) + moved = true; + if (moved) { + shadow_import_bytes -= cand.bytes; + shadow_imports.erase(it); + ++shadow_gpu_counts.dropped; + } else { + cand.generation = now; + found = it->second; + } + } + } + if (!found && !(found = make_shadow_import(src, n))) { + ++shadow_gpu_counts.refused; + return false; + } + heap_gpu->queue_copy(found->buffer, src - found->base, dst_buffer, dst_offset, n, found); + ++shadow_gpu_counts.copies; + shadow_gpu_counts.bytes += n; + return true; + } + // An import of the committed, readable view region around [src, src + n): its 2 MiB-aligned window, inside the + // region. Null when it does not hold all of it, the budget (LEONIDA_SHADOW_GPU_MB, 1024) is spent, or the driver + // refuses. shadow_import_mutex held. + std::shared_ptr make_shadow_import(std::uintptr_t src, std::size_t n) { + static const std::uint64_t budget = [] { + char text[16] = {}; + const DWORD c = GetEnvironmentVariableA("LEONIDA_SHADOW_GPU_MB", text, sizeof(text)); + return (c > 0 && c < sizeof(text) ? std::strtoull(text, nullptr, 10) : 1024ull) << 20; + }(); + const std::uint64_t generation = leonida::title_memory_map::generation(); + MEMORY_BASIC_INFORMATION region{}; + const auto refuse = [&](const char* why) -> std::shared_ptr { + static std::atomic logged{0}; + if (logged.fetch_add(1, std::memory_order_relaxed) < 8) + std::fprintf(stderr, "[rt] d3d12: LEONIDA_SHADOW_GPU: no import of 0x%llx (+%zu; state 0x%lx protect 0x%lx " + "type 0x%lx): %s; copied by the CPU\n", + static_cast(src), n, static_cast(region.State), + static_cast(region.Protect), static_cast(region.Type), why); + return nullptr; + }; + if (!VirtualQuery(reinterpret_cast(src), ®ion, sizeof(region))) return refuse("no region"); + if (region.State != MEM_COMMIT || !region.Protect || + (region.Protect & (PAGE_NOACCESS | PAGE_GUARD | PAGE_WRITECOMBINE | PAGE_NOCACHE))) + return refuse("not committed and readable"); + // This import path supports mapped section views. + if (region.Type != MEM_MAPPED) return refuse("not a section view"); + constexpr std::uintptr_t kWindow = 2u << 20; + const auto region_base = reinterpret_cast(region.BaseAddress); + const std::uintptr_t region_end = region_base + region.RegionSize; + const std::uintptr_t base = std::max(region_base, src & ~(kWindow - 1)); + const std::uintptr_t end = std::min(region_end, (src + n + kWindow - 1) & ~(kWindow - 1)); + if (src + n > end) return refuse("the run crosses the view's end"); + if (shadow_import_bytes + (end - base) > budget) return refuse("LEONIDA_SHADOW_GPU_MB spent"); + auto imp = std::make_shared(); + imp->device = this; + imp->base = base; + imp->bytes = end - base; + imp->generation = generation; + VkDeviceAddress address = 0; + if (!import_host_range(reinterpret_cast(base), imp->bytes, imp->buffer, imp->memory, address)) + return refuse("the driver refused the import"); + // Older imports over these pages are stale or redundant. + for (auto it = shadow_imports.lower_bound(base > (64ull << 20) ? base - (64ull << 20) : 0); + it != shadow_imports.end() && it->first < end;) { + if (it->first + it->second->bytes > base) { + shadow_import_bytes -= it->second->bytes; + it = shadow_imports.erase(it); + } else { + ++it; + } + } + shadow_imports[base] = imp; + shadow_import_bytes += imp->bytes; + ++shadow_gpu_counts.imports; + shadow_gpu_counts.imported += imp->bytes; + return imp; + } + + static bool console_heap_gpu_enabled() { + static const bool on = [] { + char value[4] = {}; + return GetEnvironmentVariableA("LEONIDA_CONSOLE_HEAP_GPU", value, sizeof(value)) == 1 && value[0] == '1'; + }(); + return on; + } + static bool console_heap_arena_enabled() { + static const bool on = [] { + char value[4] = {}; + return GetEnvironmentVariableA("LEONIDA_CONSOLE_HEAP_ARENA", value, sizeof(value)) == 1 && value[0] == '1'; + }(); + return on; + } + + void setup_console_heap_gpu(PFN_vkGetDeviceProcAddr get_device) { + if ((!console_heap_gpu_enabled() && !shadow_gpu_enabled()) || !context || !get_device) return; + auto gpu = std::make_unique(get_device, info.device, memory); + if (!gpu->init()) { + std::fprintf(stderr, "[rt] d3d12: LEONIDA_CONSOLE_HEAP_GPU: the translation pass could not be made; the " + "console heaps are fixed on the CPU\n"); + return; + } + heap_gpu = std::move(gpu); + heap_gpu->set_signed_offsets(signed_vsharp_offsets()); + leonida::title_va_aliases().record_removals(true); + context->set_prelude([this](VkCommandBuffer cb) { return heap_gpu->record(cb); }, + [this](bool submitted, std::uint64_t ticket) { heap_gpu->commit(submitted, ticket); }); + gpu_resolver = std::make_unique(); + gpu_resolver->thread = std::thread([this, r = gpu_resolver.get()] { + SetThreadDescription(GetCurrentThread(), L"leonida console heap resolver"); + const auto words_hash = [](const leonida::gfx10::ImageWords& w) { + std::uint64_t h = 1469598103934665603ull; + for (const std::uint32_t x : w) h = (h ^ x) * 1099511628211ull; + return h; + }; + const auto bind = [&](const leonida::gfx10::ImageWords& w) { + const TitleImage result = bind_title_image(*this, w); + gpu_tsharps[unsigned(result)].fetch_add(1, std::memory_order_relaxed); + if (result == TitleImage::unknown || result == TitleImage::refused) { + if (r->waiting.size() < 65536) r->waiting.emplace_back(std::chrono::steady_clock::now(), w); + } else { + if (r->registered.size() > (1u << 20)) r->registered.clear(); + r->registered.insert(words_hash(w)); + } + }; + for (;;) { + std::vector> batch; + std::vector tsharps; + { + std::unique_lock lock(r->mutex); + // Woken for work, or every 100 ms for the T#s whose texture is still to come. + r->wake.wait_for(lock, std::chrono::milliseconds(100), + [r] { return r->stop || !r->requests.empty() || !r->tsharps.empty(); }); + if (r->stop) return; + batch.swap(r->requests); + tsharps.swap(r->tsharps); + } + 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. + const auto now = std::chrono::steady_clock::now(); + for (int n = 0; n < 256 && !r->waiting.empty() && + now - r->waiting.front().first >= std::chrono::milliseconds(500); + ++n) { + const auto w = r->waiting.front().second; + r->waiting.pop_front(); + bind(w); + } + for (const auto& [key, retry] : batch) { + std::uint64_t span = 0; + const std::uint64_t to = resolve_vsharp_words(key, span); + std::lock_guard lock(r->mutex); + if (r->stop) return; + r->answers.push_back({key, to, span, retry}); + } + } + }); + if (shadow_gpu_enabled()) { + ShadowPages::gpu_copy_context = this; + ShadowPages::gpu_copy = &shadow_gpu_copy; + std::fprintf(stderr, "[rt] d3d12: LEONIDA_SHADOW_GPU=1: slot-133 shadows' aliased pages are copied by the " + "GPU from imports of the title's pages\n"); + } + if (console_heap_gpu_enabled()) + std::fprintf(stderr, "[rt] d3d12: LEONIDA_CONSOLE_HEAP_GPU=1: console heap V#s are rebased by a compute pass " + "at the start of each submission\n"); + } + + // `bytes` of host memory at `host` as a buffer the GPU reads by its device address. False: not importable. + bool import_host_range(void* host, VkDeviceSize bytes, VkBuffer& buffer, VkDeviceMemory& out, + VkDeviceAddress& address) { + auto& vk = context->vk; + const VkDeviceSize alignment = info.host_pointer_alignment; + if (!get_host_pointer_properties || !alignment || (reinterpret_cast(host) % alignment) || + (bytes % alignment)) + return false; + VkExternalMemoryBufferCreateInfo external{VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO}; + external.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT; + VkBufferCreateInfo create{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, &external}; + create.size = bytes; + create.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | + VK_BUFFER_USAGE_TRANSFER_SRC_BIT; + share(create); + buffer = VK_NULL_HANDLE; + out = VK_NULL_HANDLE; + if (vk.vkCreateBuffer(info.device, &create, nullptr, &buffer) != VK_SUCCESS) return false; + const auto fail = [&] { + if (buffer) vk.vkDestroyBuffer(info.device, buffer, nullptr); + if (out) vk.vkFreeMemory(info.device, out, nullptr); + buffer = VK_NULL_HANDLE; + out = VK_NULL_HANDLE; + return false; + }; + VkMemoryRequirements requirements{}; + vk.vkGetBufferMemoryRequirements(info.device, buffer, &requirements); + VkMemoryHostPointerPropertiesEXT pointer{VK_STRUCTURE_TYPE_MEMORY_HOST_POINTER_PROPERTIES_EXT}; + if (get_host_pointer_properties(info.device, VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT, host, + &pointer) != VK_SUCCESS) + return fail(); + const std::uint32_t types = pointer.memoryTypeBits & requirements.memoryTypeBits; + if (!types || bytes < requirements.size) return fail(); + VkImportMemoryHostPointerInfoEXT import{VK_STRUCTURE_TYPE_IMPORT_MEMORY_HOST_POINTER_INFO_EXT}; + import.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT; + import.pHostPointer = host; + VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO, &import}; + flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; + for (const VkMemoryPropertyFlags want : + {VkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT), + VkMemoryPropertyFlags(0)}) { + for (std::uint32_t i = 0; i < memory.memoryTypeCount && !out; ++i) { + if (!(types & (1u << i)) || (memory.memoryTypes[i].propertyFlags & want) != want) continue; + VkMemoryAllocateInfo allocate{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, &flags}; + allocate.allocationSize = bytes; + allocate.memoryTypeIndex = i; + if (vk.vkAllocateMemory(info.device, &allocate, nullptr, &out) != VK_SUCCESS) out = VK_NULL_HANDLE; + } + if (out) break; + } + if (!out || vk.vkBindBufferMemory(info.device, buffer, out, 0) != VK_SUCCESS) return fail(); + VkBufferDeviceAddressInfo bda{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; + bda.buffer = buffer; + address = vk.vkGetBufferDeviceAddress(info.device, &bda); + if (!address) return fail(); + return true; + } + + // A resource heap with its 3x scratch (copy, input, previous) goes to the pass: `input` imported, the copy + // written by the pass where shaders read it (arena.address + shader_va: the scratch import or the arena range). + void attach_console_heap_gpu(ConsoleHeap& heap) { + VkDeviceAddress input = 0; + if (!import_host_range(heap.input, heap.bytes, heap.input_buffer, heap.input_memory, input)) { + std::fprintf(stderr, "[rt] d3d12: LEONIDA_CONSOLE_HEAP_GPU: console descriptor heap 0x%llx: its mirror " + "could not be imported; fixed on the CPU\n", + static_cast(heap.console_va)); + return; + } + const int index = heap_gpu->add_heap(input, arena.address + heap.shader_va, + std::uint32_t(heap.bytes / kDescriptorSize)); + if (index < 0) { + context->vk.vkDestroyBuffer(info.device, heap.input_buffer, nullptr); + context->vk.vkFreeMemory(info.device, heap.input_memory, nullptr); + heap.input_buffer = VK_NULL_HANDLE; + heap.input_memory = VK_NULL_HANDLE; + return; + } + heap.gpu = index; + heap.vsharp_bits.assign((heap.bytes / kDescriptorSize + 63) / 64, 0); + std::fprintf(stderr, "[rt] d3d12: LEONIDA_CONSOLE_HEAP_GPU: console descriptor heap 0x%llx (%llu slots) is " + "translated by the pass (heap %d)\n", + static_cast(heap.console_va), + static_cast(heap.bytes / kDescriptorSize), index); + } + + static void set_vsharp_bit(ConsoleHeap& heap, std::size_t slot, bool on) { + const std::uint64_t bit = 1ull << (slot & 63); + auto& word = heap.vsharp_bits[slot >> 6]; + word = on ? word | bit : word & ~bit; + } + + // The T# in a slot's title bytes, registered as fix_console_slot does (no write: the pass copies it). 0: not + // settled (a T# whose texture is still to come); 1: settled; 2: settled, and the slot holds words that are no + // buffer pair and no T# that decodes, whose dwords 0-3 the pass writes as zeros, as fix_console_slot does. + int console_tsharp_check(ConsoleHeap& heap, std::size_t slot) { + leonida::gfx10::ImageWords words; + std::memcpy(words.data(), heap.previous + slot * kDescriptorSize, sizeof(words)); + if (!(words[3] >> 30)) return 1; + if (!leonida::gfx10::is_image(words)) { + ++heap.images[unsigned(TitleImage::not_tsharp)]; + return 2; + } + const char* why = nullptr; + const TitleImage result = bind_title_image(*this, words, &why); + if (result == TitleImage::unknown || result == TitleImage::refused) + note_refused_tsharp(heap, slot * kDescriptorSize, words, why); + ++heap.images[unsigned(result)]; + if (result == TitleImage::not_tsharp) return 2; + return result != TitleImage::unknown && result != TitleImage::refused ? 1 : 0; + } + + // LEONIDA_CONSOLE_GPU_TSHARPS=0 keeps T# registration on the submitting thread (fix_console_slot's way, under the + // fix budget); by default the resolver does it and the refresh only decodes. + static bool tsharps_off_thread_enabled() { + static const bool on = [] { + char value[4] = {}; + return !(GetEnvironmentVariableA("LEONIDA_CONSOLE_GPU_TSHARPS", value, sizeof(value)) == 1 && value[0] == '0'); + }(); + return on; + } + std::vector tsharp_jobs; // console_heap_mutex + void refresh_console_heap_gpu(ConsoleHeap& heap) { // console_heap_mutex held + const bool tsharps_off_thread = tsharps_off_thread_enabled() && gpu_resolver; + 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) : 4000ull; + }(); + using clock = std::chrono::steady_clock; + const auto ms = [](clock::time_point a, clock::time_point b) { + return std::chrono::duration(b - a).count(); + }; + const auto t0 = clock::now(); + heap.copied += heap.pages->refresh(); + auto& queued = gpu_queue_scratch; + queued.clear(); + // The tracker zeroed these in `input` too: the pass copies the zeros. + heap.pages->for_each_zeroed([&](std::size_t offset, std::size_t bytes) { + std::memset(heap.previous + offset, 0, bytes); + for (std::size_t slot = offset / kDescriptorSize; + slot * kDescriptorSize < offset + bytes && slot < heap.retry.size(); ++slot) { + heap.retry[slot] = 0; + set_vsharp_bit(heap, slot, false); + queued.push_back(std::uint32_t(slot)); + } + }); + const auto t1 = clock::now(); + std::uint32_t binds = 0; + bool over = false; + heap.pages->for_each_copied([&](std::size_t offset, std::size_t bytes) { + const std::size_t end = std::min(offset + bytes, std::size_t(heap.bytes)); + for (std::size_t at = offset & ~std::size_t(kDescriptorSize - 1); at + kDescriptorSize <= end; + at += kDescriptorSize) { + if (!std::memcmp(heap.previous + at, heap.input + at, kDescriptorSize)) continue; + std::memcpy(heap.previous + at, heap.input + at, kDescriptorSize); + note_changed_slot(heap, heap.previous + at); + const std::size_t slot = at / kDescriptorSize; + heap.gpu_high = std::max(heap.gpu_high, std::uint32_t(slot + 1)); + const auto* w = reinterpret_cast(heap.previous + at); + if (!(w[3] >> 30)) { + queued.push_back(std::uint32_t(slot)); + set_vsharp_bit(heap, slot, w[2] || w[6]); + heap.retry[slot] = 0; + continue; + } + set_vsharp_bit(heap, slot, false); + if (tsharps_off_thread) { + // Only decoded here: words that are no T# are zeroed by the pass; a T# goes to the resolver to + // be registered (shaders find it by its words; until then they get the fallback). + leonida::gfx10::ImageWords words; + std::memcpy(words.data(), w, sizeof(words)); + leonida::gfx10::Image image{}; + const bool tsharp = leonida::gfx10::is_image(words) && leonida::gfx10::decode(words, image); + queued.push_back(std::uint32_t(slot) | (tsharp ? 0u : leonida::ConsoleHeapGpu::kZeroFirst)); + if (tsharp) tsharp_jobs.push_back(words); + else ++heap.images[unsigned(TitleImage::not_tsharp)]; + heap.retry[slot] = 0; + continue; + } + // Past LEONIDA_CONSOLE_FIX_US of registering T#s, the rest wait for retry_console_tsharps (copied as + // they are meanwhile). + if (budget_us && !over && !(++binds & 15) && + clock::now() - t1 >= std::chrono::microseconds(budget_us)) + over = true; + const int check = over ? 0 : console_tsharp_check(heap, slot); + queued.push_back(std::uint32_t(slot) | (check == 2 ? leonida::ConsoleHeapGpu::kZeroFirst : 0u)); + if (check) { + heap.retry[slot] = 0; + } else { + if (over) ++heap.deferred_fixes; + if (!heap.retry[slot]) { + heap.retry[slot] = 1; + heap.retries.push_back(std::uint32_t(slot)); + } + } + } + }); + heap_gpu->queue(heap.gpu, queued.begin(), queued.end()); + heap.gpu_queued += queued.size(); + if (!tsharp_jobs.empty()) { + { + std::lock_guard lock(gpu_resolver->mutex); + gpu_resolver->tsharps.insert(gpu_resolver->tsharps.end(), tsharp_jobs.begin(), tsharp_jobs.end()); + } + gpu_resolver->wake.notify_one(); + tsharp_jobs.clear(); + } + const auto t2 = clock::now(); + if (!heap.retries.empty()) retry_console_tsharps(heap); + const auto t3 = clock::now(); + heap.pages_ms += ms(t0, t1); + heap.fix_ms += ms(t1, t2); + heap.retry_ms += ms(t2, t3); + } + + // retry_console_slots for the GPU mode: only T#s wait there, and nothing is written. + void retry_console_tsharps(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; + const int check = heap.retry[slot] ? console_tsharp_check(heap, slot) : 1; + if (check == 2) heap_gpu->queue(heap.gpu, slot | leonida::ConsoleHeapGpu::kZeroFirst); + if (check) { + 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; + } + heap.retry_at = i; + heap.retried += visited; + } + + // What fix_vsharp's console path (VsharpPath::scratch) answers for the four words of a V# half: the shader VA, or 0 + // (no backing). `span` gets the V#'s span. + std::uint64_t resolve_vsharp_words(const leonida::ConsoleHeapKeys::Key& k, std::uint64_t& span) { + const std::uint64_t base = std::uint64_t(k[0]) | (std::uint64_t(k[1] & 0xffff) << 32); + const std::uint32_t stride = (k[1] >> 16) & 0x3fffu; + span = std::uint64_t(k[2]) * (stride ? stride : 1); + const leonida::gfx10::BufferWords words{k[0], k[1], k[2], k[3]}; + leonida::gfx10::Buffer desc{}; + const bool copy_geometry = leonida::gfx10::decode(words, desc) && + (span <= kTitleWindowMax || (desc.format && leonida::gfx10::encode(desc) == words)); + return vsharp_address(base, span, leonida::TitleVaAliases::table_view, false, copy_geometry); + } + + // vsharp_address's backed(): [offset, offset + bytes) of the shader VAs is a live allocation or geometry copy. + bool shader_range_backed(std::uint64_t offset, std::uint64_t bytes) { + constexpr std::uint64_t mask = (1ull << 48) - 1; + if (!bytes) return false; + const std::uint64_t limit = signed_vsharp_offsets() ? mask / 2 : mask; + const bool encodable = offset <= limit ? bytes - 1 <= limit - offset + : signed_vsharp_offsets() && offset >= UINT64_MAX - limit && + bytes - 1 <= limit - offset; + if (!encodable) return false; + const auto bda = arena.address + offset; + { + std::lock_guard lock(backing_mutex); + if (gpu_backings.covers(bda, bytes)) return true; + } + std::uint64_t host{}, room{}; + return geometry.cap() && geometry.lookup(bda, host, room) && room >= bytes; + } + + // The range table from the alias table: a range keeps its check while it and its backing stay; `gone` (shader + // VA ranges released since the last one) clears it. True when a checked range lost its backing. + bool rebuild_gpu_ranges(const std::vector>& gone) { + std::vector mappings; + leonida::title_va_aliases().mappings(mappings); + const auto overlaps_gone = [&](std::uint64_t start, std::uint64_t end) { + for (const auto& [s, n] : gone) + if (s < end && start < s + n) return true; + return false; + }; + bool lost = false; + std::vector ranges; + ranges.reserve(mappings.size()); + for (const auto& m : mappings) { + const std::uint64_t bytes = m.end - m.title_va; + const bool released = !gone.empty() && overlaps_gone(m.shader_va, m.shader_va + bytes); + auto it = std::lower_bound(gpu_ranges.begin(), gpu_ranges.end(), m.title_va, + [](const leonida::ConsoleHeapRange& r, std::uint64_t va) { return r.title_va < va; }); + bool checked; + if (it != gpu_ranges.end() && it->title_va == m.title_va && it->end == m.end && + it->shader_va == m.shader_va && !released) { + checked = it->checked; + } else { + checked = shader_range_backed(m.shader_va, bytes); + if (released && it != gpu_ranges.end() && it->title_va == m.title_va && it->checked) lost = true; + } + ranges.push_back({m.title_va, m.end, m.shader_va, checked}); + } + // A checked range that is gone from the table altogether had its slots answered from it. + if (!lost) { + for (const auto& r : gpu_ranges) { + if (!r.checked) continue; + auto it = std::lower_bound(ranges.begin(), ranges.end(), r.title_va, + [](const leonida::ConsoleHeapRange& a, std::uint64_t va) { return a.title_va < va; }); + if (it == ranges.end() || it->title_va != r.title_va || it->shader_va != r.shader_va || !it->checked) { + lost = true; + break; + } + } + } + gpu_ranges = ranges; + heap_gpu->set_ranges(std::move(ranges)); + return lost; + } + + // The backed table (src/console_heap_gpu.h): every live allocation's shader VAs and the geometry copies' blocks, + // merged, and clipped to what a V# can name. Rebuilt from gpu_backings when allocations changed, at most every + // 100 ms (one made since is a miss the CPU answers meanwhile); a release in between is cut out of it at once, so + // the pass never leaves a V# on memory that is going (an overlapping allocation that stays is then a miss too + // until the next rebuild). + void update_gpu_backed(const std::vector>& gone) { + const auto start = std::chrono::steady_clock::now(); + const std::uint64_t generation = backing_generation.load(std::memory_order_relaxed); + const std::size_t blocks = geometry.pool().block_count() + external_windows.block_count(); + const bool changed = generation != gpu_backed_generation || blocks != gpu_backed_blocks; + if (changed && (gpu_backed_generation == ~0ull || start - gpu_backed_at >= std::chrono::milliseconds(100))) { + gpu_backed_generation = generation; + gpu_backed_blocks = blocks; + gpu_backed_at = start; + gpu_backed.clear(); + { + std::lock_guard lock(backing_mutex); + gpu_backings.for_each([&](std::uint64_t va, std::uint64_t bytes) { + const std::uint64_t offset = va - arena.address; + if (bytes && offset <= UINT64_MAX - bytes) gpu_backed.emplace_back(offset, offset + bytes); + }); + } + const auto block = [&](VkDeviceAddress address, VkDeviceSize bytes) { + const std::uint64_t offset = address - arena.address; + if (address && bytes && offset <= UINT64_MAX - bytes) gpu_backed.emplace_back(offset, offset + bytes); + }; + geometry.pool().for_each_block(block); + external_windows.for_each_block(block); + leonida::merge_console_heap_spans(gpu_backed); + // What a V# can name: 48 bits, or +-2^47 around heap_base with signed offsets. + constexpr std::uint64_t k47 = 1ull << 47, k48 = 1ull << 48; + leonida::ConsoleHeapSpans clipped; + for (const auto& [a, b] : gpu_backed) { + if (signed_vsharp_offsets()) { + if (a < k47) clipped.emplace_back(a, std::min(b, k47)); + else if (a >= 0ull - k47) clipped.emplace_back(a, b); + } else if (a < k48) { + clipped.emplace_back(a, std::min(b, k48)); + } + } + gpu_backed.swap(clipped); + heap_gpu->set_spans(leonida::ConsoleHeapGpu::backed_table, gpu_backed); + ++gpu_counts.backed_rebuilds; + } else if (!gone.empty() && !gpu_backed.empty()) { + leonida::ConsoleHeapSpans out; + for (const auto& [s0, bytes] : gone) { + const std::uint64_t e0 = bytes > UINT64_MAX - s0 ? UINT64_MAX : s0 + bytes; + out.clear(); + for (const auto& [a, b] : gpu_backed) { + if (b <= s0 || a >= e0) { + out.emplace_back(a, b); + continue; + } + if (a < s0) out.emplace_back(a, s0); + if (b > e0) out.emplace_back(e0, b); + } + gpu_backed.swap(out); + } + heap_gpu->set_spans(leonida::ConsoleHeapGpu::backed_table, gpu_backed); + ++gpu_counts.backed_cuts; + } + gpu_counts.backed_ms += std::chrono::duration(std::chrono::steady_clock::now() - start).count(); + } + + // The ask table: the title's memory and both addresses of its GPU-window pairs. A V# base outside them that the + // other tables do not answer is one vsharp_address could only answer 0 for. + void update_gpu_ask() { + auto& aliases = leonida::title_va_aliases(); + const std::uint64_t generation = + aliases.memory_generation() * 1000003ull + std::uint64_t(leonida::title_gpu_views::count()); + if (generation == gpu_ask_generation) return; + gpu_ask_generation = generation; + gpu_ask = aliases.title_memory_ranges(); + leonida::ConsoleHeapSpans views; + leonida::title_gpu_views::spans(views); + gpu_ask.insert(gpu_ask.end(), views.begin(), views.end()); + leonida::merge_console_heap_spans(gpu_ask); + heap_gpu->set_spans(leonida::ConsoleHeapGpu::ask_table, gpu_ask); + } + + // Once, when xmem's aliased pages are many: can they be imported as host memory (VK_EXT_external_memory_host)? + // A successful import lets the GPU copy the section. Release the diagnostic import after the check. + void probe_alias_imports() { + static bool probed = false; + if (probed) return; + std::vector pages; + const std::size_t total = leonida::title_page_aliases::sample(pages, 8); + if (total < 256) return; + probed = true; + int ok = 0; + for (const std::uintptr_t va : pages) { + VkBuffer buffer = VK_NULL_HANDLE; + VkDeviceMemory imported = VK_NULL_HANDLE; + VkDeviceAddress address = 0; + MEMORY_BASIC_INFORMATION region{}; + VirtualQuery(reinterpret_cast(va), ®ion, sizeof(region)); + const bool done = import_host_range(reinterpret_cast(va), leonida::title_page_aliases::kPageSize, + buffer, imported, address); + ok += done; + std::fprintf(stderr, + "[rt] d3d12: alias import probe: page 0x%llx (state 0x%lx protect 0x%lx type 0x%lx): %s, " + "device address 0x%llx\n", + static_cast(va), static_cast(region.State), + static_cast(region.Protect), static_cast(region.Type), + done ? "imported" : "refused", static_cast(address)); + if (buffer) context->vk.vkDestroyBuffer(info.device, buffer, nullptr); + if (imported) context->vk.vkFreeMemory(info.device, imported, nullptr); + } + std::fprintf(stderr, "[rt] d3d12: alias import probe: %d of %zu sampled pages imported (%zu aliased pages)\n", ok, + pages.size(), total); + } + + // Before the heaps of a refresh: the misses of the passes that are done, the backings and alias ranges gone, the + // range table. console_heap_mutex held. + void console_heap_gpu_begin() { + const auto start = std::chrono::steady_clock::now(); + auto lap = [last = start](double& to) mutable { + const auto now = std::chrono::steady_clock::now(); + to += std::chrono::duration(now - last).count(); + last = now; + }; + probe_alias_imports(); + lap(gpu_counts.part_ms[0]); + auto& misses = gpu_miss_scratch; + misses.clear(); + heap_gpu->drain( + context->completed_retire_ticket(), + [&](int h, std::uint32_t slot, std::uint32_t half) { + ConsoleHeap* heap = h >= 0 && unsigned(h) < gpu_heaps.size() ? gpu_heaps[std::size_t(h)] : nullptr; + ++gpu_counts.misses; + if (!heap || slot >= heap->retry.size()) return; + const auto* k = reinterpret_cast(heap->previous + slot * kDescriptorSize) + 4 * half; + if ((k[3] >> 30) || !k[2]) return; // rewritten since: queued by its change + misses.push_back({{k[0], k[1], k[2], k[3]}, (std::uint32_t(h) << 28) | slot}); + }, + // A list that ran over: every V# slot again once what it did hold is resolved (at once would only + // overflow it again with the same words). + [&](int) { request_rescan_after_resolve(); }); + if (!misses.empty()) { + // Words the table has now (entered after that pass was recorded): only the slot again. The rest wait to + // be resolved. + std::vector again; + heap_gpu->with_keys([&](leonida::ConsoleHeapKeys& keys) { + for (auto& m : misses) + if (keys.find(m.key) >= 0) again.push_back(m.code), m.code = UINT32_MAX; + return 0; + }); + for (const std::uint32_t code : again) + if (gpu_heaps[code >> 28]) heap_gpu->queue(int(code >> 28), code & ((1u << 28) - 1)); + gpu_counts.known_misses += again.size(); + for (const auto& m : misses) { + if (m.code == UINT32_MAX) continue; + auto& slots = gpu_unresolved[m.key].slots; + // Words shared by very many slots: the rest are found by the rescan after the answer. + if (slots.size() < 4096) slots.push_back(m.code); + else request_rescan_after_resolve(); + } + } + std::vector> gone, removed; + { + std::lock_guard lock(backing_mutex); + gone.swap(released_ranges); + } + auto& aliases = leonida::title_va_aliases(); + aliases.take_removed(removed); + gpu_counts.released += gone.size() + removed.size(); + std::size_t dropped = 0; + if (!gone.empty() || !removed.empty()) + dropped = heap_gpu->with_keys([&](leonida::ConsoleHeapKeys& keys) { + std::size_t n = 0; + for (const auto& [s, bytes] : gone) n += keys.erase_overlapping(s, s + bytes); + for (const auto& [s, bytes] : removed) n += keys.erase_overlapping(s, s + bytes); + return n; + }); + gpu_counts.dropped += dropped; + lap(gpu_counts.part_ms[1]); + bool lost = false; + const std::uint64_t generation = aliases.generation(); + // At once when something went (the pass must not answer from it), else at most every 50 ms: a range added + // since is a miss the resolver answers meanwhile (the alias table changes at most submissions). + if ((generation != gpu_alias_generation && + (!removed.empty() || start - gpu_ranges_at >= std::chrono::milliseconds(50))) || + !gone.empty()) { + gpu_alias_generation = generation; + gpu_ranges_at = start; + lost = rebuild_gpu_ranges(gone); + } + lap(gpu_counts.part_ms[2]); + if (dropped || lost) { + if (gpu_filter_enabled()) { + gpu_rescan_filtered = true; + for (const auto& [s, bytes] : gone) gpu_filter_shader.emplace_back(s, s + bytes); + for (const auto& [s, bytes] : removed) gpu_filter_shader.emplace_back(s, s + bytes); + } else { + gpu_rescan = true; + } + } + update_gpu_backed(gone); + lap(gpu_counts.part_ms[3]); + update_gpu_ask(); + lap(gpu_counts.part_ms[4]); + gpu_counts.begin_ms += std::chrono::duration(std::chrono::steady_clock::now() - start).count(); + } + + // After the heaps: hand the missed words to the resolver, take its answers (entered in the key table, their slots + // queued again), ask again for words that got no backing, and translate every V# slot again when something they + // were answered from went. Nothing here waits for an answer. + void console_heap_gpu_end() { + static const std::uint64_t retry_ms = [] { + char text[16] = {}; + const DWORD n = GetEnvironmentVariableA("LEONIDA_CONSOLE_GPU_RETRY_MS", text, sizeof(text)); + return n > 0 && n < sizeof(text) ? std::strtoull(text, nullptr, 10) : 2000ull; + }(); + using clock = std::chrono::steady_clock; + const auto start = clock::now(); + std::vector answers; + std::vector> requests; + for (auto& [key, u] : gpu_unresolved) + if (!u.asked) { + u.asked = true; + requests.emplace_back(key, false); + } + // Words with no backing, asked again once retry_ms old: at most 256 a refresh, and while the resolver has + // fewer than 4096 waiting. + const auto now = clock::now(); + for (int n = 0; n < 256 && !gpu_unbacked.empty() && gpu_asked + requests.size() < 4096 && + now >= gpu_unbacked.front().at; + ++n) { + requests.emplace_back(gpu_unbacked.front().key, true); + gpu_unbacked_tries[gpu_unbacked.front().key] = gpu_unbacked.front().tries + 1; + gpu_unbacked.pop_front(); + ++gpu_counts.retried; + } + { + std::lock_guard lock(gpu_resolver->mutex); + answers.swap(gpu_resolver->answers); + gpu_resolver->requests.insert(gpu_resolver->requests.end(), requests.begin(), requests.end()); + } + if (!requests.empty()) gpu_resolver->wake.notify_one(); + gpu_asked += requests.size(); + gpu_asked -= std::min(gpu_asked, answers.size()); + const auto queue_slots = [&](const std::vector& slots) { + for (const std::uint32_t code : slots) { + const std::uint32_t h = code >> 28; + if (h < gpu_heaps.size() && gpu_heaps[h]) heap_gpu->queue(int(h), code & ((1u << 28) - 1)); + } + }; + for (const GpuAnswer& a : answers) { + if (a.retry) { + if (!a.to) { + // Still no backing: asked again after twice the wait, at most 64x retry_ms. + const auto t = gpu_unbacked_tries.find(a.key); + const std::uint32_t tries = t == gpu_unbacked_tries.end() ? 1 : t->second; + if (t != gpu_unbacked_tries.end()) gpu_unbacked_tries.erase(t); + const auto wait = std::chrono::milliseconds(retry_ms << std::min(tries, 6)); + gpu_unbacked.push_back({clock::now() + wait, a.key, tries}); + continue; + } + gpu_unbacked_tries.erase(a.key); + // Backed now: every slot that read "no backing" for these words, once all are in. + const bool entered = heap_gpu->with_keys([&](leonida::ConsoleHeapKeys& keys) { + std::uint64_t to = 0; + bool none = false; + return keys.lookup(a.key, to, none) && none && keys.put(a.key, a.to, a.span, false); + }); + if (entered) { + ++gpu_counts.flips; + if (gpu_filter_enabled()) { + // The slots that read "no backing" for these words: those with this title base. + const std::uint64_t base = a.key[0] | (std::uint64_t(a.key[1] & 0xffff) << 32); + gpu_filter_title.emplace_back(base, base + 1); + gpu_rescan_filtered = true; + } else { + gpu_rescan = true; + } + } + continue; + } + ++gpu_counts.resolved; + const auto it = gpu_unresolved.find(a.key); + if (!heap_gpu->with_keys([&](leonida::ConsoleHeapKeys& keys) { return keys.put(a.key, a.to, a.span, !a.to); })) + ++gpu_counts.put_failed; // every probe slot holds other words: these slots stay without records + else if (it != gpu_unresolved.end()) + queue_slots(it->second.slots); + if (it != gpu_unresolved.end()) gpu_unresolved.erase(it); + if (!a.to) { + ++gpu_counts.none; + gpu_unbacked.push_back({clock::now() + std::chrono::milliseconds(retry_ms), a.key, 0}); + } + } + while (gpu_unbacked.size() > 65536) gpu_unbacked.pop_front(); // those stay "no backing" until a rescan + // A key table past 60 % full: emptied at once (the next pass clears the GPU's), and every V# slot again. + const auto [key_count, key_capacity] = heap_gpu->with_keys( + [](leonida::ConsoleHeapKeys& k) { return std::pair(k.size(), k.capacity()); }); + if (key_count * 10 > key_capacity * 6) { + heap_gpu->reset_keys(); + gpu_unbacked.clear(); + gpu_unresolved.clear(); + ++gpu_counts.key_resets; + gpu_rescan = true; + } + // Asked for after an overflow: once the misses are resolved, or a second later if new ones keep coming. + if (gpu_rescan_after_resolve && + (gpu_unresolved.empty() || clock::now() - gpu_rescan_asked >= std::chrono::seconds(1))) { + gpu_rescan_after_resolve = false; + gpu_rescan = true; + } + if (gpu_rescan) { + gpu_rescan = false; + ++gpu_counts.rescans; + // On the GPU: one dispatch over the slots the title has written, pairs only (ConsoleHeapGpu::rescan). + for (unsigned h = 0; h < gpu_heaps.size(); ++h) + if (ConsoleHeap* heap = gpu_heaps[h]) heap_gpu->rescan(int(h), heap->gpu_high); + gpu_rescan_filtered = false; // the full one covers it + gpu_filter_shader.clear(); + gpu_filter_title.clear(); + } else if (gpu_rescan_filtered) { + gpu_rescan_filtered = false; + ++gpu_counts.filtered_rescans; + // The spans go to the pass once (its change tables serve every heap). + bool first = true; + const leonida::ConsoleHeapSpans none; + for (unsigned h = 0; h < gpu_heaps.size(); ++h) + if (ConsoleHeap* heap = gpu_heaps[h]) { + heap_gpu->rescan_filtered(int(h), heap->gpu_high, first ? gpu_filter_shader : none, + first ? gpu_filter_title : none); + first = false; + } + gpu_filter_shader.clear(); + gpu_filter_title.clear(); + } + gpu_counts.resolve_ms += std::chrono::duration(clock::now() - start).count(); + } + + void log_console_heap_gpu(ConsoleHeap& heap, double count) { + const auto stats = heap_gpu->take_stats(); + const std::size_t keys = heap_gpu->with_keys([](leonida::ConsoleHeapKeys& k) { return k.size(); }); + std::size_t checked = 0; + for (const auto& r : gpu_ranges) checked += r.checked; + std::fprintf(stderr, + "[rt] d3d12: console descriptor heap 0x%llx on the GPU: %.1f slots queued a submission; passes " + "%llu (%llu slots, %llu key updates, %llu misses, %llu overflowed, %llu not submitted); resolved " + "%llu words (%llu with no backing, %llu asked again, %llu answered later, %llu not entered), %llu " + "misses already " + "entered, %zu waiting (%zu with the resolver), %zu unbacked; %llu rescans (%llu slots), " + "%llu filtered rescans (%llu slots looked at), %llu key entries dropped for %llu releases; %zu keys (%llu resets), %zu ranges (%zu checked), %zu " + "backed spans (%llu rebuilds, %llu cuts, %.3f ms a submission), %zu ask spans; %.3f ms before " + "and %.3f ms resolving a submission\n", + static_cast(heap.console_va), double(heap.gpu_queued) / count, + static_cast(stats.passes), static_cast(stats.slots), + static_cast(stats.updates), static_cast(stats.misses), + static_cast(stats.overflows), static_cast(stats.failed), + static_cast(gpu_counts.resolved), + static_cast(gpu_counts.none), + static_cast(gpu_counts.retried), + static_cast(gpu_counts.flips), + static_cast(gpu_counts.put_failed), + static_cast(gpu_counts.known_misses), gpu_unresolved.size(), gpu_asked, + gpu_unbacked.size(), static_cast(gpu_counts.rescans), + static_cast(stats.rescanned), + static_cast(gpu_counts.filtered_rescans), + static_cast(stats.filtered), + static_cast(gpu_counts.dropped), + static_cast(gpu_counts.released), keys, + static_cast(gpu_counts.key_resets), gpu_ranges.size(), checked, + gpu_backed.size(), static_cast(gpu_counts.backed_rebuilds), + static_cast(gpu_counts.backed_cuts), gpu_counts.backed_ms / count, + gpu_ask.size(), + gpu_counts.begin_ms / count, gpu_counts.resolve_ms / count); + std::fprintf(stderr, + "[rt] d3d12: console heap pass, before the heaps, ms a submission: alias probes %.3f, misses and " + "releases %.3f, range table %.3f, backed table %.3f, ask table %.3f\n", + gpu_counts.part_ms[0] / count, gpu_counts.part_ms[1] / count, gpu_counts.part_ms[2] / count, + gpu_counts.part_ms[3] / count, gpu_counts.part_ms[4] / count); + if (tsharps_off_thread_enabled()) { + std::uint64_t t[5]; + for (unsigned i = 0; i < 5; ++i) t[i] = gpu_tsharps[i].exchange(0, std::memory_order_relaxed); + std::fprintf(stderr, + "[rt] d3d12: console heap T#s registered by the resolver: %llu known, %llu bound, %llu naming no " + "texture, %llu refused\n", + static_cast(t[0]), static_cast(t[1]), + static_cast(t[2]), static_cast(t[3])); + } + if (shadow_gpu_enabled()) { + ShadowGpuCounts c; + std::size_t imports = 0; + std::uint64_t imported_bytes = 0; + { + std::lock_guard lock(shadow_import_mutex); + c = std::exchange(shadow_gpu_counts, ShadowGpuCounts{}); + imports = shadow_imports.size(); + imported_bytes = shadow_import_bytes; + } + std::fprintf(stderr, + "[rt] d3d12: slot-133 shadows on the GPU: %llu copies (%.1f KiB a submission), %llu imports made " + "(%llu MiB), %llu dropped after a map change, %llu refused, %llu with no GPU destination; %zu imports " + "live (%llu MiB); passes copied %llu regions\n", + static_cast(c.copies), double(c.bytes) / 1024.0 / count, + static_cast(c.imports), static_cast(c.imported >> 20), + static_cast(c.dropped), static_cast(c.refused), + static_cast(c.outside), imports, + static_cast(imported_bytes >> 20), + static_cast(stats.copies)); + } + heap.gpu_queued = 0; + gpu_counts = {}; } // LOCAL DIAGNOSTIC (desc-probe): which console-heap slots our API wrote and which the title wrote itself, what @@ -3736,6 +5532,16 @@ struct DeviceState { unsigned recent_count = 0; }; std::mutex probe_mutex; // never under console_heap_mutex' callees; takes descriptor_mutex inside + // LEONIDA_DESC_PROBE=1 turns the diagnostic on (so does the compute input probe, which reads these records). Off + // by default: at every submission it hashes each slot of every bound table, and formats a line under + // descriptor_mutex for each slot the title wrote itself. + static bool probe_enabled() { + static const bool on = [] { + const char* v = std::getenv("LEONIDA_DESC_PROBE"); + return (v && *v == '1') || rt::compute_probe::enabled(); + }(); + return on; + } std::vector> probes; std::uint64_t probe_submissions = 0; static constexpr const char* kProbeKinds[8] = {"V# in arena", "V# title memory", "V# other", "T# key known", @@ -3744,7 +5550,7 @@ struct DeviceState { std::atomic probe_view_logs{0}; // Where a Create*View / CopyDescriptors* write landed, for the first ones. void probe_view(const char* what, SIZE_T ptr, UINT count) { - if (!leonida::local_diagnostics() || probe_view_logs.fetch_add(1) >= 48) return; + if (!probe_enabled() || probe_view_logs.fetch_add(1) >= 48) return; std::lock_guard lock(probe_mutex); for (const auto& p : probes) if (ptr >= p->console_va && ptr < p->console_va + p->slots * kDescriptorSize) { @@ -3769,8 +5575,7 @@ struct DeviceState { return !(q[0] | q[1] | q[2] | q[3]); } void probe_add(std::uint64_t console_va, std::uint64_t shader_va, std::size_t slots, bool shadowed) { - // Nothing reads a probe unless one of the two diagnostics is on; without probes the other probe_* are no-ops. - if (!leonida::local_diagnostics() && !rt::compute_probe::enabled()) return; + if (!probe_enabled() && !rt::compute_probe::enabled()) return; auto probe = std::make_unique(); probe->console_va = console_va; probe->shader_va = shader_va; @@ -3790,11 +5595,12 @@ struct DeviceState { shader_va + slots * kDescriptorSize <= arena.size ? "inside" : "PAST"); } void probe_remove(std::uint64_t console_va) { + if (!probe_enabled()) return; std::lock_guard lock(probe_mutex); std::erase_if(probes, [console_va](const std::unique_ptr& p) { return p->console_va == console_va; }); } void probe_api(SIZE_T ptr, UINT count, const char* what = "CopyDescriptors") { - if (!ptr || !count) return; + if (!ptr || !count || !probe_enabled()) return; std::lock_guard lock(probe_mutex); for (const auto& p : probes) { if (ptr < p->console_va || ptr >= p->console_va + p->slots * kDescriptorSize) continue; @@ -3866,6 +5672,7 @@ struct DeviceState { } // At a descriptor-table scan (ExecuteCommandLists): the slots a bound table in a console heap declares. void probe_table(std::uint64_t table_va, std::uint32_t descriptors) { + if (!probe_enabled()) return; std::lock_guard lock(probe_mutex); for (const auto& p : probes) { const std::uint64_t span = p->slots * kDescriptorSize; @@ -3924,7 +5731,7 @@ struct DeviceState { } // Before a submission, after the console heaps' copies are refreshed: the whole heap, now and then. void probe_census() { - if (!leonida::local_diagnostics()) return; + if (!probe_enabled()) return; const std::uint64_t n = ++probe_submissions; if (n != 1 && n != 64 && n != 512 && n != 2048 && n % 4096) return; std::lock_guard lock(probe_mutex); @@ -4379,8 +6186,14 @@ struct DeviceState { VkImageView sampled; VkImageView storage; // the same range without a component mapping, for the storage bindings; or null std::uint64_t address; + // A 2D view of the first layer in the 2D arrays (a 2D-array image's slice 0, BindlessSet::MirrorViews); or null + VkImageView mirror_sampled = VK_NULL_HANDLE; + VkImageView mirror_storage = VK_NULL_HANDLE; }; std::unique_ptr bindless; + // 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; 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}; @@ -4467,6 +6280,10 @@ struct DeviceState { context->defer_destroy(leonida::DeferredDeletionQueue::Kind::bindless_slot, slot_handle); if (entry.sampled) context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image_view, entry.sampled); if (entry.storage) context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image_view, entry.storage); + if (entry.mirror_sampled) + context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image_view, entry.mirror_sampled); + if (entry.mirror_storage) + context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image_view, entry.mirror_storage); } struct PendingSample { @@ -4659,8 +6476,11 @@ struct DeviceState { } } leonida::StorageViews views{}; + VkImageViewCreateInfo storage_info{}; + bool storage_info_valid = false; if (storage) { - VkImageViewCreateInfo storage_info = view_info; + storage_info = view_info; + storage_info_valid = true; storage_info.components = {}; storage_info.format = storage_format; VkImageViewUsageCreateInfo storage_usage{VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO}; @@ -4682,9 +6502,42 @@ struct DeviceState { (numeric == 1 ? views.as_uint : numeric == 2 ? views.as_sint : views.as_float) = entry.storage; if (storage_format == VK_FORMAT_R32_UINT) views.r32ui = entry.storage; } + // A 2D-array or cube image also gets a 2D view of its first layer, which the bindless set binds at the same + // index in the 2D arrays: a 2D instruction reading this T# addresses slice 0 (BindlessSet::MirrorViews). + leonida::BindlessSet::MirrorViews mirror{}; + if (dimension == leonida::ImageDimension::dim_2d_array) { + const auto make_mirror = [&](const VkImageViewCreateInfo& base, VkImageView* out) { + VkImageViewCreateInfo layer = base; + layer.viewType = VK_IMAGE_VIEW_TYPE_2D; + layer.subresourceRange.baseArrayLayer = image.first_layer; + layer.subresourceRange.layerCount = 1; + return vk.vkCreateImageView(info.device, &layer, nullptr, out) == VK_SUCCESS; + }; + if (make_mirror(view_info, &entry.mirror_sampled)) { + mirror.sampled = entry.mirror_sampled; + mirror.sampled_layout = VK_IMAGE_LAYOUT_GENERAL; + if (storage_info_valid && make_mirror(storage_info, &entry.mirror_storage)) { + const int numeric = numeric_class(storage_info.format); + (numeric == 1 ? mirror.storage.as_uint : numeric == 2 ? mirror.storage.as_sint + : mirror.storage.as_float) = entry.mirror_storage; + if (storage_info.format == VK_FORMAT_R32_UINT) mirror.storage.r32ui = entry.mirror_storage; + } + } else { + log_once("no 2D view of this image's first layer; a 2D instruction reading its T# reads the fallback", + int(image.type)); + } + } // Every state a shader can read or write the texture in is GENERAL (ResourceBinding::sampled_in_general). - entry.index = bindless->add_image(dimension, entry.sampled, VK_IMAGE_LAYOUT_GENERAL, views, sampled_class); + // `kind` says which arrays the index is bound in; a tagged module reads it from the table (insert_key). + 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_storage) { + vk.vkDestroyImageView(info.device, entry.mirror_storage, nullptr); + entry.mirror_storage = VK_NULL_HANDLE; + } if (first_diagnostic("a bindless image array is full; dimension", int(dimension))) { // Whether the array holds live textures or stale views: the T#s it holds, the textures they name, // and the most T#s of one texture (a texture whose T#s keep changing, a streamed mip clamp say, @@ -4715,7 +6568,10 @@ struct DeviceState { image_entries.emplace(words, entry); image_keys.emplace(image.address, words); } - bindless->insert_key(words, entry.index); + // 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 return true; } @@ -4729,6 +6585,26 @@ struct DeviceState { std::lock_guard lock(descriptor_mutex); images_by_address[address] = resource; } + // 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). + static void trace_image(std::uint64_t address, leonida::ResourceId id, const char* where) { + static const std::vector traced = [] { + std::vector out; + const char* v = std::getenv("LEONIDA_TRACE_TEXTURE"); + for (const char* p = v; p && *p;) { + char* end = nullptr; + const std::uint64_t a = std::strtoull(p, &end, 16); + if (end == p) break; + out.push_back(a); + p = *end == ',' ? end + 1 : end; + } + return out; + }(); + if (traced.empty() || std::find(traced.begin(), traced.end(), address) == traced.end()) return; + std::fprintf(stderr, "[rt] trace-texture: address 0x%llx is resource 0x%llx (%s)\n", + static_cast(address), static_cast(id), where); + leonida::fsdraw::note_target(id); // read back with the captures (numbers: mean, nonzero texels) + } // The texture registered at `address` (a title-placed texture's address can be taken over by a later one). const void* image_owner(std::uint64_t address) { std::lock_guard lock(descriptor_mutex); @@ -5327,9 +7203,10 @@ class DescriptorHeap final desc_.NumDescriptors >= 65536 ? DeviceState::heap_guard_bytes() : 0; - if (guard && device.arena_allocate(bytes + guard, 256, arena_offset_, DeviceState::arena_descriptor_heap)) + if (guard && device.arena_allocate(bytes + guard, 256, arena_offset_, DeviceState::arena_descriptor_heap)) { guard_ = guard; - else if (!device.arena_allocate(bytes, 256, arena_offset_, DeviceState::arena_descriptor_heap)) { + device.arena_guard_bytes.fetch_add(guard, std::memory_order_relaxed); + } else if (!device.arena_allocate(bytes, 256, arena_offset_, DeviceState::arena_descriptor_heap)) { log_once("GPU address arena full (raise LEONIDA_ARENA_MB); shader-visible heap size in KiB:", int(std::min(bytes / 1024, INT_MAX))); return; @@ -5341,10 +7218,6 @@ class DescriptorHeap final std::lock_guard lock(device.visible_heap_mutex); device.visible_heaps[arena_offset_] = {arena_offset_ + bytes, desc.Type}; } - if (desc.Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) { - std::lock_guard lock(device.cbv_heap_mutex); - device.cbv_heaps[arena_offset_] = arena_offset_ + bytes; - } } else { storage_.reset(new std::byte[std::size_t(bytes)]()); cpu_ = reinterpret_cast(storage_.get()); @@ -5368,9 +7241,13 @@ class DescriptorHeap final std::lock_guard lock(device_.visible_heap_mutex); device_.visible_heaps.erase(arena_offset_); } + if (in_arena_ && desc_.Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) { + device_.forget_nulled_table_slots(arena_offset_, VkDeviceSize(desc_.NumDescriptors) * kDescriptorSize); + } if (in_arena_) device_.arena_release(arena_offset_, VkDeviceSize(desc_.NumDescriptors) * kDescriptorSize + guard_, DeviceState::arena_descriptor_heap); + if (guard_) device_.arena_guard_bytes.fetch_sub(guard_, std::memory_order_relaxed); } bool ok() const { return cpu_ != nullptr; } @@ -5498,6 +7375,7 @@ class Resource final device_.context->remove_resource(id()); // Before the memory goes to the deferred queue: no submission copies into it after this. if (shadow_) device_.remove_shadow(shadow_); + if (shadow_ && !in_arena_) device_.remove_copy_target(shadow_); if (host_import_) { // VK_EXT_external_memory_host needs the caller's pages to stay valid for the imported memory's whole // lifetime, and a title may free them right after releasing the resource. So the memory is not left to @@ -5622,13 +7500,12 @@ class Resource final const bool host = cpu_visible(); leonida::ResourceBinding binding{}; // a buffer: no image binding.size = desc_.Width; - if (!host && device_.arena.mapped) { - if (!device_.arena_allocate(desc_.Width, D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT, arena_offset_, - DeviceState::arena_buffer)) { - log_once("GPU address arena full (raise LEONIDA_ARENA_MB); buffer size in KiB:", - int(desc_.Width / 1024)); - return E_OUTOFMEMORY; - } + const bool use_arena = !host && device_.arena.mapped; + 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)); va_ = arena_offset_; @@ -5657,6 +7534,8 @@ class Resource final device_.context->add_resource(id(), binding); return S_OK; } + if (use_arena) + log_once("GPU address arena full; using a dedicated default buffer, size in KiB:", int(desc_.Width / 1024)); const bool addressable = device_.arena.buffer != VK_NULL_HANDLE; const bool need_bda = device_.info.buffer_device_address || device_.info.ray_tracing; VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; @@ -5694,8 +7573,8 @@ class Resource final VkBufferDeviceAddressInfo address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; address.buffer = buffer_; va_ = vk.vkGetBufferDeviceAddress(device_.info.device, &address) - device_.arena.address; - device_.log_va(heap_.Type == D3D12_HEAP_TYPE_READBACK ? "readback buffer" : "upload buffer", va_, - desc_.Width); + const char* name = heap_.Type == D3D12_HEAP_TYPE_READBACK ? "readback buffer" : "upload buffer"; + device_.log_va(host ? name : "default buffer", va_, desc_.Width); } if (host) { if (vk.vkMapMemory(device_.info.device, memory_, 0, VK_WHOLE_SIZE, 0, &mapped_) != VK_SUCCESS) @@ -6010,6 +7889,7 @@ class Resource final vk.vkMapMemory(device_.info.device, memory_, 0, VK_WHOLE_SIZE, 0, &shadow) != VK_SUCCESS) return E_OUTOFMEMORY; shadow_ = static_cast(shadow); + device_.add_copy_target(shadow_, std::size_t(desc_.Width), buffer_); // LEONIDA_SHADOW_GPU device_.add_shadow(pages, shadow_, std::size_t(desc_.Width)); // Map() answers the title's own pages, as the imported buffer does: a write to the shadow's memory would be // overwritten by the next copy. @@ -6108,6 +7988,7 @@ class Resource final aspects_ = format.aspects; image_address_ = device_.next_image_address.fetch_add(256); device_.note_image_address(image_address_, this); + DeviceState::trace_image(image_address_, id(), "registered"); binding_.image = image_; binding_.format = format_; binding_.aspects = aspects_; @@ -6453,6 +8334,7 @@ class Resource final aspects_ = format.aspects; image_address_ = device_.next_image_address.fetch_add(256); device_.note_image_address(image_address_, this); + DeviceState::trace_image(image_address_, id(), "registered"); binding.deferred_memory = deferred_attachment_.get(); if (origin == TitleImageOrigin::placed && leonida::mem_probe::interval_seconds()) binding.replay_seen = &replay_seen_; @@ -6676,6 +8558,7 @@ class Resource final device_.forget_image(va); // an earlier texture placed at this address, still alive: its views are stale image_address_ = va; device_.note_image_address(image_address_, this); + DeviceState::trace_image(image_address_, id(), "registered"); } // The title's own address for a texture Xbox slot 133 placed. The image is still the committed fallback, so its // pixels do not alias the title's pages yet; the address is what GetGPUVirtualAddress answers (XCL PR #168's @@ -6747,6 +8630,27 @@ class Resource final // no pointer to give (its layout is the driver's), so D3D12 only lets it be mapped with a null pointer, before // WriteToSubresource/ReadFromSubresource. HRESULT STDMETHODCALLTYPE Map(UINT subresource, const D3D12_RANGE* read, void** data) override { + // LOCAL DIAGNOSTIC: LEONIDA_LOCK_TRACE=1 logs the first 256 texture Maps with a read range: the title's + // texture lock passes the subresource's byte range there, computed from its XG computer's + // layout, and adds the range's start to the pointer this answers. + static const bool lock_trace = [] { + char value[2]{}; + return GetEnvironmentVariableA("LEONIDA_LOCK_TRACE", value, sizeof(value)) == 1 && value[0] == '1'; + }(); + if (lock_trace && read && image_) { + static std::atomic logged{0}; + if (logged.fetch_add(1, std::memory_order_relaxed) < 256) { + const auto caller = reinterpret_cast(_ReturnAddress()); + std::fprintf(stderr, + "[rt] d3d12: LOCAL DIAGNOSTIC: Map sub %u range 0x%llx..0x%llx of texture %llux%ux%u " + "fmt %d flags 0x%x at 0x%llx, caller 0x%llx\n", + subresource, static_cast(read->Begin), + static_cast(read->End), static_cast(desc_.Width), + desc_.Height, unsigned(desc_.DepthOrArraySize), int(desc_.Format), unsigned(desc_.Flags), + static_cast(reinterpret_cast(title_address_)), + static_cast(caller)); + } + } // A texture whose lease says its title memory is linear (title_linear_) and that also has a placement // address (slot 133; the video planes among them) has two answers. The placement address, with the title // texture registry filling the image, is the one the retail boot ran through the intro movie and the story @@ -7137,6 +9041,7 @@ class Resource final if (!device_.staging_queue) { device_.staging_queue = std::make_unique(*device_.context, device_.info.queue, device_.info.queue_family); + device_.staging_queue->make_synchronous(); // waited for at once (idle below) } if (device_.staging_queue->ok()) { const leonida::CommandList* lists[] = {&list}; @@ -7811,6 +9716,7 @@ struct PipelineStream { D3D12_SHADER_BYTECODE as{}; bool has_cs = false; bool has_graphics_stage = false; // VS, PS, DS, HS, GS, AS or MS + bool depth_bounds = false; // DEPTH_STENCIL1/2 DepthBoundsTestEnable (not in the plain graphics desc) }; // Console stream retry adapted from Kokonotcu, ubiquitarianism/leonida #496 (GPL-3.0). @@ -7949,9 +9855,7 @@ HRESULT parse_pipeline_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, Pipe case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1: { D3D12_DEPTH_STENCIL_DESC1 d{}; take(d); - if (ok && d.DepthBoundsTestEnable) { - return stream_unsupported("depth-bounds tests are not supported yet; stream subobject", int(type)); - } + if (ok) out.depth_bounds = d.DepthBoundsTestEnable != FALSE; g.DepthStencilState = {d.DepthEnable, d.DepthWriteMask, d.DepthFunc, d.StencilEnable, d.StencilReadMask, d.StencilWriteMask, d.FrontFace, d.BackFace}; break; @@ -7960,9 +9864,7 @@ HRESULT parse_pipeline_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, Pipe D3D12_DEPTH_STENCIL_DESC2 d{}; take(d); if (!ok) break; - if (d.DepthBoundsTestEnable) { - return stream_unsupported("depth-bounds tests are not supported yet; stream subobject", int(type)); - } + out.depth_bounds = d.DepthBoundsTestEnable != FALSE; // Each face has its own read and write mask (OPTIONS14.IndependentFrontAndBackStencilRefMaskSupported): // the description takes the front face's, back_stencil the back face's. out.back_masks = true; @@ -8020,6 +9922,415 @@ HRESULT parse_pipeline_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, Pipe // A pipeline state, compute (create_compute) or graphics (create_graphics): each shader is found by the SHA-256 of // its FSSM program in the translator's index, and the FSSM blob is copied into the arena as the shader's code base. std::atomic live_pipeline_state_count{0}; // live_pipeline_states() +// set_pipeline_build_hook (tests): called on the building thread with the PSO, once a replay build is claimed and +// before it calls the driver. +std::mutex pipeline_build_hook_mutex; +std::function pipeline_build_hook; + +// What the bindless set layout was made from, for a compute pipeline's journal name: a pipeline built against another +// layout is another pipeline. Field by field, so padding never reaches the hash. +void hash_bindless_layout(leonida::pipeline_journal::Hasher& hash, const leonida::BindlessFeatures& features) { + for (const std::uint32_t count : features.counts) hash.value(count); + hash.value(std::uint8_t(features.update_after_bind)); + hash.value(std::uint8_t(features.partially_bound)); + hash.value(std::uint8_t(features.null_descriptor)); + for (const VkSampleCountFlagBits samples : features.ms_samples) hash.value(std::uint32_t(samples)); +} + +// Opt in on this branch. Async workers normally compile while other queues submit. +std::unique_lock compute_driver_turn(DeviceState& device) { + static const bool enabled = [] { + wchar_t value[2]{}; + return GetEnvironmentVariableW(L"LEONIDA_COMPILE_GATE", value, 2) == 1 && value[0] == L'1'; + }(); + std::unique_lock turn(device.context->submit_mutex(), std::defer_lock); + if (enabled) turn.lock(); + return turn; +} + +// LOCAL FIX (pipeline journal, pipeline_cache_journal.h): one compute pipeline's own VkPipelineCache for the length +// of its build. load() reads the journal file, before any driver call. In the build's one compile-gate turn, +// create() makes the cache from the file's contents (seeded) or empty, and finish() takes the cache's data when the +// pipeline had to be compiled and destroys the cache. publish(), after the turn, writes the file, or refreshes its +// last use after a hit: no file I/O in the turn. Nothing else uses the cache, so it needs no synchronization beyond +// the build's own. +class JournalCache { +public: + VkPipelineCache cache = VK_NULL_HANDLE; + bool seeded = false; // made from the file's contents + + JournalCache(DeviceState& device, leonida::SubmitMutex& submits, const char* trigger, const char* name) + : device_(device), submits_(&submits), trigger_(trigger), name_(name) {} + // A build outside the submit lock's owners (the async compile workers' own turn helper): compute_driver_turn. + JournalCache(DeviceState& device, const char* name) : device_(device), name_(name) {} + JournalCache(const JournalCache&) = delete; + JournalCache& operator=(const JournalCache&) = delete; + ~JournalCache() { + if (!cache) return; // finish() always destroys it; this is only for a build that left early + if (submits_) { + const DriverTurn turn(*submits_, trigger_, "vkDestroyPipelineCache", true, name_); + device_.context->vk.vkDestroyPipelineCache(device_.info.device, cache, nullptr); + } else { + const auto turn = compute_driver_turn(device_); + device_.context->vk.vkDestroyPipelineCache(device_.info.device, cache, nullptr); + } + } + + bool enabled() const { return enabled_; } + bool has_file_data() const { return !file_.data.empty(); } + bool found() const { return enabled_ && built_ && !write_; } // the pipeline came out of the journal file + bool written() const { return written_; } // publish() wrote the file + + void load(std::filesystem::path path) { + const auto& vk = device_.context->vk; + if (!vk.vkCreatePipelineCache || !vk.vkDestroyPipelineCache || !vk.vkGetPipelineCacheData) return; + enabled_ = true; + path_ = std::move(path); + namespace journal = leonida::pipeline_journal; + const auto role = compile_helper::build_host.load() ? journal::ReadRole::materialize_local : journal::ReadRole::runtime; + file_ = journal::read_with_seed(path_, pipeline_journal_roots().seed, device_.pso_identity, role); + } + + // In the build's driver turn. + void create() { + if (!enabled_) return; + const auto& vk = device_.context->vk; + VkPipelineCacheCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, nullptr, 0, file_.data.size(), + file_.data.empty() ? nullptr : file_.data.data()}; + if (!file_.data.empty() && vk.vkCreatePipelineCache(device_.info.device, &info, nullptr, &cache) == VK_SUCCESS) { + seeded = true; + } else { + cache = VK_NULL_HANDLE; // no file, or one the driver declined: start empty, and the build rewrites it + info.initialDataSize = 0; + info.pInitialData = nullptr; + if (vk.vkCreatePipelineCache(device_.info.device, &info, nullptr, &cache) != VK_SUCCESS) cache = VK_NULL_HANDLE; + } + std::vector().swap(file_.data); // the driver has its own copy + } + + // In the build's driver turn, after the create against `cache`. `built`: that create made the pipeline; `hit`: + // its creation feedback; `driver_ms`: the vkCreateComputePipelines call alone. + void finish(bool built, int hit, std::uint64_t driver_ms) { + if (!cache) return; + const auto& vk = device_.context->vk; + built_ = built; + write_ = built && leonida::pipeline_journal::should_write(seeded, hit, driver_ms); + if (write_) { + std::size_t size = 0; + result_ = vk.vkGetPipelineCacheData(device_.info.device, cache, &size, nullptr); + if (result_ == VK_SUCCESS && size > leonida::pipeline_cache_store::header_bytes && + size <= leonida::pipeline_journal::entry_read_limit) { + blob_.resize(size); + result_ = vk.vkGetPipelineCacheData(device_.info.device, cache, &size, blob_.data()); + blob_.resize(result_ == VK_SUCCESS ? size : 0); + } + data_size_ = size; + } + vk.vkDestroyPipelineCache(device_.info.device, cache, nullptr); + cache = VK_NULL_HANDLE; + } + + // The shared cache had the pipeline (FAIL_ON_PIPELINE_COMPILE_REQUIRED gave it, as a hit or quickly). + void found_in_shared() { report(device_.journal_shared_hits.fetch_add(1) + 1, "found in the shared cache"); } + + // After the driver turn. + void publish() { + namespace journal = leonida::pipeline_journal; + if (!enabled_ || !built_) return; + if (!write_) { + report(device_.journal_hits.fetch_add(1) + 1, "found in their journal file"); + journal::touch_local_hit(path_, file_, std::filesystem::file_time_type::clock::now()); + return; + } + if (blob_.size() <= leonida::pipeline_cache_store::header_bytes) { + std::fprintf(stderr, "[rt] d3d12: pipeline journal: no cache data for %s (VkResult %d, %zu bytes)\n", + name_, int(result_), data_size_); + return; + } + // A rewrite replaces the file's old size. Two builds of one name at once may both count: the next boot's + // tidy counts again. + if (journal::replace_bytes(device_.journal_bytes.load(), file_.bytes, blob_.size()) > device_.journal_budget) { + static std::atomic said{false}; + if (!said.exchange(true)) + std::fprintf(stderr, "[rt] d3d12: pipeline journal: %llu bytes on disk, the %llu-byte budget " + "(LEONIDA_PIPELINE_JOURNAL_BYTES) is spent; nothing more is written this boot\n", + static_cast(device_.journal_bytes.load()), + static_cast(device_.journal_budget)); + return; + } + if (const std::error_code error = journal::write_entry(path_, blob_.data(), blob_.size())) { + static std::atomic said{false}; + if (!said.exchange(true)) + std::fprintf(stderr, "[rt] d3d12: pipeline journal: could not write %ls: %s\n", path_.c_str(), + error.message().c_str()); + return; + } + auto total = device_.journal_bytes.load(); + while (!device_.journal_bytes.compare_exchange_weak(total, journal::replace_bytes(total, file_.bytes, blob_.size()))) { + } + written_ = true; + report(device_.journal_writes.fetch_add(1) + 1, "compiled and written to their journal file"); + } + +private: + // The first of each kind, then every 100th, with all three counts. + void report(unsigned count, const char* what) const { + if (count != 1 && count % 100) return; + std::fprintf(stderr, "[rt] d3d12: pipeline journal: %u compute pipeline(s) %s (so far: %u from journal files, " + "%u written, %u from the shared cache)\n", count, what, + device_.journal_hits.load(), device_.journal_writes.load(), device_.journal_shared_hits.load()); + } + + DeviceState& device_; + leonida::SubmitMutex* submits_ = nullptr; // null: compute_driver_turn, for a build outside the submit lock + const char* trigger_ = ""; + const char* name_; + bool enabled_ = false; + bool built_ = false; + bool write_ = false; + bool written_ = false; + std::filesystem::path path_; + leonida::pipeline_journal::EntryFile file_; + std::vector blob_; + std::size_t data_size_ = 0; + VkResult result_ = VK_SUCCESS; +}; + +// What one compute pipeline build did (build_compute_pipeline). +struct ComputeBuild { + VkPipeline pipeline = VK_NULL_HANDLE; // the caller's from here on + VkResult result = VK_ERROR_UNKNOWN; + std::size_t bytes = 0; // SPIR-V + ULONGLONG ms = 0; // the whole build + std::filesystem::path journal_path; // its journal file's name (empty with the journal off) + bool skipped = false; // ComputeBuildOptions::skip_journaled and the journal file was there: nothing built + bool busy = false; // ComputeBuildOptions::mark_building and another process is building it: nothing built + bool deferred = false; // asked of the compile helper without waiting: nothing built yet + bool journal_hit = false; // found in its journal file + bool journaled = false; // compiled and written to its journal file + bool from_shared = false; // found in the shared cache +}; + +struct ComputeBuildOptions { + const char* trigger = "dispatch"; // what asked: dispatch, warmup, dispatch-worker, precompile... + const std::string* cache_key = nullptr; // the title's PSO description key, for the compile trace + bool serialize_big = true; // modules over 128 KiB one at a time (LEONIDA_SERIAL_BIG_COMPILES=0: no) + bool skip_journaled = false; // precompile: leave a pipeline whose journal file exists alone + bool use_helper = true; // LEONIDA_COMPILE_HELPER: a missing journal file comes from the helper + bool helper_wait = true; // wait for the helper's file (false: ask, and answer deferred) + std::uint64_t helper_priority = 0; // the request's urgency: 0 a dispatch, else the warm-up's module size + bool mark_building = false; // precompile, helper: claim the entry, skip it when another process has it + bool key_only = false; // only name the journal file (journal_path), build nothing +}; + +// A compute pipeline from a library entry: what a PSO's first dispatch, the warm-up worker and gta6rt +// --precompile-pipelines all build, so their journal names and the driver's keys are the same. `layout` is the push +// range of leonida::ShaderUserData, with the device's bindless set 0 when the entry declares bindings; `subgroup` is +// leonida::decide_subgroup_size's answer for the entry. +ComputeBuild build_compute_pipeline(DeviceState& device, const leonida::ShaderEntry& compute_entry, + VkPipelineLayout layout, const leonida::SubgroupRequest& subgroup, + const ComputeBuildOptions& options) { + ComputeBuild out; + CompileActivity activity(device.active_compiles); + const char* const trigger = options.trigger; + std::filesystem::path marked; // mark_building: released on the way out + struct Unmark { + std::filesystem::path& path; + ~Unmark() { + if (!path.empty()) compile_helper::unmark_building(path); + } + } unmark{marked}; + static const std::string no_key; + auto& vk = device.context->vk; + const VkDevice dev = device.info.device; + const leonida::ShaderLibrary* library = device.library(); + const leonida::ShaderEntry* entry = &compute_entry; + if (!library) return out; + // The driver's compiler needs hundreds of MiB per very large module; several at once exhausted host memory. + // Modules over 128 KiB compile one at a time (LEONIDA_SERIAL_BIG_COMPILES=0: as many as are asked for). + static const bool serial_big = [] { + wchar_t v[2]{}; + return !(GetEnvironmentVariableW(L"LEONIDA_SERIAL_BIG_COMPILES", v, 2) == 1 && v[0] == L'0'); + }(); + static std::mutex big_compile; + std::unique_lock big_lock(big_compile, std::defer_lock); // taken below, only for a compile here + auto words = library->spirv(*entry); + if (words.empty()) { + std::fprintf(stderr, "[rt] d3d12: %s.spv is missing or not SPIR-V\n", entry->name.c_str()); + return out; + } + const std::size_t bytes = words.size() * sizeof(std::uint32_t); + out.bytes = bytes; + 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"; + VkPipelineShaderStageRequiredSubgroupSizeCreateInfo required_size{}; + leonida::apply_subgroup_request(subgroup, required_size, pipeline_info.stage); + pipeline_info.layout = layout; + pipeline_info.flags |= fast_pipeline_flags(true); // before the journal key, which hashes the flags + const VkPipelineCache shared = device.pipeline_cache(); + auto& submits = device.context->submit_mutex(); + + // LOCAL FIX (pipeline journal, pipeline_cache_journal.h): the pipeline is created against its own cache, made + // from its journal file or empty and written back after a compile, so a boot killed or crashed later keeps it. + // The file is named by what the pipeline is made of and read here, before the driver turn. Without a file + // the shared cache (seeded from the offline corpus or the last session) is asked first, without a compile. + JournalCache journal(device, submits, trigger, entry->name.c_str()); + if (const std::filesystem::path& journal_dir = pipeline_journal_dir(); !journal_dir.empty()) { + leonida::pipeline_journal::Hasher key; + key.text("cs"); + key.value(std::uint64_t(words.size())); + key.bytes(words.data(), bytes); + key.text(pipeline_info.stage.pName); + key.value(std::uint32_t(pipeline_info.flags)); + key.value(std::uint32_t(pipeline_info.stage.flags)); + 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)); + // 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. + if (device.info.device_diagnostics_config) { + key.text("nv-diagnostics-config"); + key.value(std::uint32_t(leonida::aftermath::extra_config_flags())); + } + if (entry->binding_count) hash_bindless_layout(key, device.bindless->features()); + const auto path = leonida::pipeline_journal::entry_path(journal_dir, "cs", key.digest()); + out.journal_path = path; + if (options.key_only) return out; + // Precompile: a usable file is there already, so the pipeline is not built (only its header is read). + if (options.skip_journaled && leonida::pipeline_journal::entry_usable(path, device.pso_identity)) { + out.skipped = true; + return out; + } + journal.load(path); + // LOCAL FIX (compile helper, d3d12_compile_helper.h): no file, so this would be a compile in this process, + // 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)) { + auto& helper = compile_helper::Client::instance(); + std::string why; + if (!options.helper_wait) { + if (helper.request(path, entry->name, options.helper_priority, device.pso_identity, &why)) { + out.deferred = true; + return out; + } + std::fprintf(stderr, "[rt] d3d12: compile helper: %s for %s; built here\n", why.c_str(), + entry->name.c_str()); + } else { + const ULONGLONG asked = GetTickCount64(); + if (helper.build(path, entry->name, device.pso_identity, &why)) { + journal.load(path); + std::fprintf(stderr, "[rt] d3d12: compile helper built %s in %.1f s (%zu B SPIR-V, %s)\n", + entry->name.c_str(), double(GetTickCount64() - asked) / 1000.0, bytes, trigger); + } else { + std::fprintf(stderr, "[rt] d3d12: compile helper: %s for %s after %.1f s; built here\n", + why.c_str(), entry->name.c_str(), double(GetTickCount64() - asked) / 1000.0); + } + } + } + // Precompile and helper: another process compiling this entry is left to it. + if (options.mark_building && !journal.has_file_data()) { + if (!compile_helper::mark_building(path)) { + out.busy = true; + return out; + } + marked = path; + } + } + // Only a compile here is serialized: a pipeline from its journal file takes milliseconds. + if (!journal.has_file_data() && options.serialize_big && serial_big && bytes > 128 * 1024) big_lock.lock(); + const bool ask_shared = journal.enabled() && !journal.has_file_data() && shared && device.pipeline_cache_seeded && + device.info.pipeline_cache_control && device.journal_ask_shared.load(); + + VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + module_info.codeSize = bytes; + module_info.pCode = words.data(); + VkShaderModule module = VK_NULL_HANDLE; + const ULONGLONG started = GetTickCount64(); + VkPipeline built = VK_NULL_HANDLE; + CompileTrace trace; + trace.begin(pipeline_info, device.info.pipeline_creation_feedback, trigger, entry->name.c_str(), 0, bytes, options.cache_key ? *options.cache_key : no_key); + // Was it in the cache? Core feedback on a Vulkan 1.3 device; pipeline_cache_control implies one. + if (journal.enabled() && device.info.pipeline_cache_control) trace.request_feedback(pipeline_info); + const leonida::pipeline_profile::DriverCall profile("cs", trigger, entry->name.c_str()); + // LOCAL DIAGNOSTIC (early device loss): a vkQueueSubmit was measured blocking 10 s and losing the device + // while another thread sat in this call. Name what is building (once past the gate: in the driver), and log + // the start of big ones. + auto& compiling = leonida::driver_compile; + VkResult created = VK_ERROR_UNKNOWN; + bool from_shared = false, probe_compiled = false; + ULONGLONG probe_ms = 0, driver_ms = 0; + { + // Every driver call of the build (shader module, journal cache, pipeline) in one turn through the compile + // gate: from the journal a build takes milliseconds and the warm-up worker makes them back to back, and + // three warm boots lost the device in a vkQueueSubmit (no GPU fault, no TDR) while only the create was + // gated. No file I/O in here. + const DriverTurn turn(submits, trigger, "vkCreateComputePipelines", true, entry->name.c_str()); + { + const leonida::aftermath::ShaderName named(entry->name); + if (vk.vkCreateShaderModule(dev, &module_info, nullptr, &module) != VK_SUCCESS) return out; + } + pipeline_info.stage.module = module; + journal.create(); + const VkPipelineCache cache = journal.cache ? journal.cache : shared; + compiling.bytes.store(bytes, std::memory_order_relaxed); + compiling.trigger.store(trigger, std::memory_order_relaxed); + compiling.since_ms.store(leonida::diagnostic_ms(), std::memory_order_relaxed); + compiling.name.store(entry->name.c_str(), std::memory_order_release); + if (bytes >= 128 * 1024) + std::fprintf(stderr, "[rt] d3d12: compute pipeline %s (%zu B SPIR-V, %s) build starts at t=%.3f s\n", + entry->name.c_str(), bytes, trigger, double(leonida::diagnostic_ms()) / 1000.0); + if (ask_shared) { + // VK_PIPELINE_COMPILE_REQUIRED (a success code, no pipeline) when the shared cache does not have it. + pipeline_info.flags |= VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT; + const ULONGLONG asked = GetTickCount64(); + created = vk.vkCreateComputePipelines(dev, shared, 1, &pipeline_info, nullptr, &built); + probe_ms = GetTickCount64() - asked; + pipeline_info.flags &= ~VkPipelineCreateFlags(VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT); + from_shared = created == VK_SUCCESS && built; + if (from_shared && leonida::pipeline_journal::probe_compiled(trace.hit(), probe_ms)) { + // NVIDIA 630.20 compiled it instead of answering VK_PIPELINE_COMPILE_REQUIRED, into the shared + // cache. Built once more against the journal cache below, so it is journaled; asking stops. + vk.vkDestroyPipeline(dev, built, nullptr); + from_shared = false; + probe_compiled = true; + } + if (!from_shared) built = VK_NULL_HANDLE; + } + if (!from_shared) { + const ULONGLONG at = GetTickCount64(); + created = vk.vkCreateComputePipelines(dev, cache, 1, &pipeline_info, nullptr, &built); + driver_ms = GetTickCount64() - at; + } + compiling.name.store(nullptr, std::memory_order_release); + vk.vkDestroyShaderModule(dev, module, nullptr); // Vulkan lets a module go once the pipeline exists + journal.finish(!from_shared && created == VK_SUCCESS && built, trace.hit(), driver_ms); + } + std::vector().swap(words); + profile.finish(int(created)); + trace.end(trigger, entry->name.c_str(), 0, bytes, created); + if (big_lock.owns_lock()) big_lock.unlock(); + if (probe_compiled && device.journal_ask_shared.exchange(false)) + std::fprintf(stderr, "[rt] d3d12: pipeline journal: the driver compiled %s for " + "FAIL_ON_PIPELINE_COMPILE_REQUIRED (%llu ms, no cache hit); built again for its journal " + "file, and the shared cache is no longer asked first\n", entry->name.c_str(), + static_cast(probe_ms)); + if (from_shared) journal.found_in_shared(); + journal.publish(); + out.pipeline = built; + out.result = created; + out.from_shared = from_shared; + out.journal_hit = journal.found(); + out.journaled = journal.written(); + out.ms = GetTickCount64() - started; + if (created == VK_SUCCESS && built && out.ms >= 2000) + std::fprintf(stderr, "[rt] d3d12: compute pipeline %s took %.1f s to build (%zu B SPIR-V)\n", + entry->name.c_str(), double(out.ms) / 1000.0, bytes); + return out; +} class PipelineState final : public Childvk; const VkDevice dev = device_.info.device; if (pipeline_.pipeline) vk.vkDestroyPipeline(dev, pipeline_.pipeline, nullptr); @@ -8085,6 +10402,16 @@ class PipelineState final // Asks for the subgroup size the shader was translated for, where the device allows (src/subgroup_size.h): the // stage gets VkPipelineShaderStageRequiredSubgroupSizeCreateInfo in `storage` (which must outlive pipeline // creation) and, for compute, REQUIRE_FULL_SUBGROUPS. A size the device cannot give is reported, not hidden. + // decide_subgroup_size's answer for a compute entry, reported and recorded as subgroup_size_for does; the build + // applies it (build_compute_pipeline). + leonida::SubgroupRequest subgroup_request_for(const leonida::ShaderEntry& entry) { + const leonida::SubgroupRequest request = leonida::decide_subgroup_size(entry, device_.info.subgroup); + if (request.outcome == leonida::SubgroupOutcome::unavailable) + report_subgroup_unavailable(entry, request, device_.info.subgroup); + subgroup_requests_.push_back(request); + return request; + } + void subgroup_size_for(const leonida::ShaderEntry& entry, VkPipelineShaderStageRequiredSubgroupSizeCreateInfo& storage, VkPipelineShaderStageCreateInfo& stage) { const leonida::SubgroupRequest request = leonida::decide_subgroup_size(entry, device_.info.subgroup); @@ -8221,7 +10548,7 @@ class PipelineState final if (seen.insert(line).second) std::fprintf(stderr, "%s\n", line); } HRESULT create_graphics(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc, const D3D12_SHADER_BYTECODE* ms = nullptr, - const D3D12_SHADER_BYTECODE* as = nullptr, const StencilFaceMasks* back_masks = nullptr) { + const D3D12_SHADER_BYTECODE* as = nullptr, const StencilFaceMasks* back_masks = nullptr, bool depth_bounds = false) { auto& vk = device_.context->vk; const VkDevice dev = device_.info.device; const bool mesh = ms && ms->pShaderBytecode && ms->BytecodeLength; @@ -8730,6 +11057,10 @@ class PipelineState final depth.front = stencil_face(ds.FrontFace, ds.StencilReadMask, ds.StencilWriteMask); depth.back = back_masks ? stencil_face(ds.BackFace, back_masks->read, back_masks->write) : stencil_face(ds.BackFace, ds.StencilReadMask, ds.StencilWriteMask); + // The depth-bounds test (DEPTH_STENCIL1/2): the bounds are dynamic, set from OMSetDepthBounds at each draw. + depth.depthBoundsTestEnable = depth_bounds ? VK_TRUE : VK_FALSE; + depth.minDepthBounds = 0.0f; + depth.maxDepthBounds = 1.0f; std::vector blends(desc.NumRenderTargets); for (UINT i = 0; i < desc.NumRenderTargets; ++i) { @@ -8773,6 +11104,13 @@ class PipelineState final // State that needs a Vulkan feature the device did not enable (VulkanDeviceInfo::features) is refused, rather // than handed to the driver against the spec. const VkPhysicalDeviceFeatures& features = device_.info.features; + if (depth_bounds && !features.depthBounds) + return stream_unsupported("depth-bounds tests need depthBounds, which the device lacks; stream subobject", 21); + if (depth_bounds) { // how many PSOs use the test (they were all refused before) + static std::atomic made{0}; + const unsigned n = ++made; + if ((n & (n - 1)) == 0) std::fprintf(stderr, "[rt] d3d12: depth-bounds PSO #%u\n", n); + } if (raster.polygonMode != VK_POLYGON_MODE_FILL && !features.fillModeNonSolid) return stream_unsupported("wireframe fill needs fillModeNonSolid, which the device lacks; fill mode", r.FillMode); @@ -8896,6 +11234,7 @@ 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; recipe_.mesh = mesh; recipe_.stages = std::move(stage_infos); recipe_.attributes = std::move(attributes); @@ -8919,11 +11258,15 @@ class PipelineState final // A cache-only create that the driver would have to compile stays null: the first draw builds it. if (!graphics_.pipeline && !(cache_only && compile_status == VK_PIPELINE_COMPILE_REQUIRED)) return E_FAIL; } // lazy: graphics_.pipeline stays null and the first draw builds it as variant 0 - graphics_.async_build = async_replay_compile(); + // Replay asks through replay_get (prepare, never waiting on another thread's build) and replay_await (the + // submission's pre-pass, with no lock held): a null handle may mean the variant is still being built. + if (graphics_.pipeline) ready0_.store(graphics_.pipeline, std::memory_order_release); + graphics_.async_build = true; graphics_.variant = [this](std::uint32_t unbound) { - return replay_pipeline("draw", [&] { - return graphics_.async_build ? queue_build(false, unbound) : variant(unbound, "draw"); - }); + return replay_pipeline("draw", [&] { return replay_get(false, unbound); }); + }; + graphics_.await = [this](std::uint32_t unbound, std::int64_t until, bool* pending) { + return replay_await(false, unbound, until, pending); }; graphics_.built = [this](std::uint32_t unbound) { std::unique_lock lock(variants_mutex_, std::try_to_lock); // held: another thread is compiling one @@ -8941,8 +11284,7 @@ class PipelineState final code_base_ = offset; graphics_.code_base = offset; } - // LOCAL DIAGNOSTIC: what this pipeline is, for the fsdraw probe's draw lines - if (leonida::local_diagnostics()) { + if (leonida::fsdraw::enabled()) { // LOCAL DIAGNOSTIC: what this pipeline is, for the fsdraw probe's draw lines const auto& rt0 = desc.BlendState.RenderTarget[0]; char text[640]; std::snprintf(text, sizeof text, @@ -9083,12 +11425,15 @@ class PipelineState final }; pipeline_.build_context = this; } else if (lazy_compute) { - pipeline_.async_build = async_replay_compile(); + // As for graphics: replay_get at prepare, replay_await in the submission's pre-pass; null may mean the + // pipeline is still being built, and the dispatch is skipped. + pipeline_.async_build = true; pipeline_.build = [](void* self) { auto* pso = static_cast(self); - return replay_pipeline("dispatch", [&] { - return pso->pipeline_.async_build ? pso->queue_build(true, 0) : pso->build_compute("dispatch"); - }); + return replay_pipeline("dispatch", [&] { return pso->replay_get(true, 0); }); + }; + pipeline_.await = [](void* self, std::int64_t until, bool* pending) { + return static_cast(self)->replay_await(true, 0, until, pending); }; pipeline_.build_context = this; pipeline_.built = [](void* self) { @@ -9121,66 +11466,63 @@ class PipelineState final // it (the replay layer calls ComputePipeline::build) or by the warm-up thread. Null when it cannot be built; the // failure is logged and not retried. VkPipeline build_compute(const char* trigger) { - CompileActivity activity(device_.active_compiles); std::lock_guard lock(variants_mutex_); if (pipeline_.pipeline || compute_failed_) return pipeline_.pipeline; - compute_failed_ = true; // until the pipeline exists - auto& vk = device_.context->vk; - const VkDevice dev = device_.info.device; - const leonida::ShaderLibrary* library = device_.library(); const leonida::ShaderEntry* entry = compute_entry_; - if (!library || !entry) return VK_NULL_HANDLE; - static std::mutex big_compile; - std::unique_lock big_lock(big_compile, std::defer_lock); - if (serial_big_compile(stage_bytes_)) big_lock.lock(); - auto words = library->spirv(*entry); - if (words.empty()) { - std::fprintf(stderr, "[rt] d3d12: %s.spv is missing or not SPIR-V\n", entry->name.c_str()); + if (!device_.library() || !entry) { + compute_failed_ = true; return VK_NULL_HANDLE; } - VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - module_info.codeSize = words.size() * 4; - module_info.pCode = words.data(); - VkShaderModule module = VK_NULL_HANDLE; - { - const leonida::aftermath::ShaderName named(entry->name); - if (vk.vkCreateShaderModule(dev, &module_info, nullptr, &module) != VK_SUCCESS) return VK_NULL_HANDLE; + // LOCAL FIX (compile helper, d3d12_compile_helper.h): asynchronous builds and warm-ups only ask the helper and + // are deferred (build_claimed puts the variant back to idle, so its next use asks again). While the helper is + // still making the file this answers at once, without reading the module; a use asks with replay's priority. + // Only replay's own and the warm-up's triggers may answer deferred: compute-create (LEONIDA_LAZY_COMPUTE=0) is + // a create whose caller needs a pipeline now, so it waits for the file as a dispatch does in a strict replay + // (LOCAL FIX, review: with LEONIDA_ASYNC_PIPELINES=1 it was deferred and returned E_FAIL). + const bool warmup = !std::strcmp(trigger, "warmup"); + const bool replay_trigger = !std::strcmp(trigger, "dispatch") || !std::strcmp(trigger, "dispatch-worker"); + const bool helper_nowait = warmup || (replay_trigger && async_replay_compile()); + if (!helper_file_.empty()) { + auto& helper = compile_helper::Client::instance(); + std::string why; + const auto state = helper.state(helper_file_, device_.pso_identity, &why); + if (state == compile_helper::Client::State::pending) { + if (!warmup) helper.request(helper_file_, entry->name, 0, device_.pso_identity, nullptr); + if (helper_nowait) { + helper_deferred_ = true; + return VK_NULL_HANDLE; + } + } else if (state != compile_helper::Client::State::ready) { + std::fprintf(stderr, "[rt] d3d12: compile helper: %s for %s; built here\n", why.c_str(), + entry->name.c_str()); + helper_refused_ = true; + } + helper_file_.clear(); } - const auto bytes = module_info.codeSize; - std::vector().swap(words); // vkCreateShaderModule consumed pCode - VkComputePipelineCreateInfo pipeline_info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; - pipeline_info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; - pipeline_info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; - pipeline_info.stage.module = module; - pipeline_info.stage.pName = "main"; - VkPipelineShaderStageRequiredSubgroupSizeCreateInfo required_size{}; - subgroup_size_for(*entry, required_size, pipeline_info.stage); - pipeline_info.layout = pipeline_.layout; - const VkPipelineCache cache = device_.pipeline_cache(); - - const ULONGLONG started = GetTickCount64(); - VkPipeline built = VK_NULL_HANDLE; - CompileTrace trace; - trace.begin(pipeline_info, device_.info.pipeline_creation_feedback, trigger, entry->name.c_str(), 0, bytes, cache_key_); - const leonida::pipeline_profile::DriverCall profile("cs", trigger, entry->name.c_str()); - const VkResult created = vk.vkCreateComputePipelines(dev, cache, 1, &pipeline_info, nullptr, &built); - profile.finish(int(created)); - trace.end(trigger, entry->name.c_str(), 0, bytes, created); - if (big_lock.owns_lock()) big_lock.unlock(); - vk.vkDestroyShaderModule(dev, module, nullptr); // Vulkan lets a module go once the pipeline exists - const ULONGLONG took = GetTickCount64() - started; - if (created != VK_SUCCESS || !built) { + compute_failed_ = true; // until the pipeline exists + ComputeBuildOptions options; + options.trigger = trigger; + options.cache_key = &cache_key_; + options.use_helper = !helper_refused_; + options.helper_wait = !helper_nowait; + options.helper_priority = warmup ? stage_bytes_ : 0; + const ComputeBuild build = build_compute_pipeline(device_, *entry, pipeline_.layout, subgroup_request_for(*entry), + options); + if (build.deferred) { + compute_failed_ = false; + helper_file_ = build.journal_path; + helper_deferred_ = true; + return VK_NULL_HANDLE; + } + if (build.result != VK_SUCCESS || !build.pipeline) { std::fprintf(stderr, "[rt] d3d12: compute pipeline %s could not be built (VkResult %d); its dispatches are " - "dropped\n", entry->name.c_str(), int(created)); + "dropped\n", entry->name.c_str(), int(build.result)); return VK_NULL_HANDLE; } - if (took >= 2000) - std::fprintf(stderr, "[rt] d3d12: compute pipeline %s took %.1f s to build (%zu B SPIR-V)\n", - entry->name.c_str(), double(took) / 1000.0, bytes); - maybe_checkpoint(cache); - pipeline_.pipeline = built; + maybe_checkpoint(device_.pipeline_cache()); + pipeline_.pipeline = build.pipeline; compute_failed_ = false; - return built; + return build.pipeline; } // Lazy compute pipelines are also built in the background, smallest module first, so most exist before their @@ -9210,54 +11552,295 @@ class PipelineState final if (!queued) device_.next_checkpoint.store(now + 120000); // refused after an exit stop, or out of memory } - VkPipeline queue_build(bool compute, std::uint32_t unbound, std::size_t warm_bytes = 0) { - static std::mutex publication; // ready handles only; no compiler call holds this lock - const bool warm = warm_bytes != 0; - // After an exit stop (stop_pipeline_compiles) nothing is queued: a warm-up is skipped, and a draw or dispatch - // builds in place, as without LEONIDA_ASYNC_PIPELINES, rather than waiting for a build that never comes. - if (PipelineCompiler::instance().closed()) { - if (warm) return VK_NULL_HANDLE; - return compute ? build_compute("dispatch") : variant(unbound, "draw"); + // Replay's builds of this pipeline, by variant (compute: 0; graphics: the unbound mask of + // leonida::GraphicsPipeline::variant), under builds_mutex() with builds_changed(); no driver call holds the lock. + // A variant is idle until something asks for it, queued once a compile-worker job for it is (a warm-up, or one at + // replay's priority), running once a thread has claimed it (the worker, or a submitting thread that builds it in + // place), and done with its handle (null: it cannot be built). Exactly one thread builds each variant: a worker job + // that finds its variant claimed returns at once, so a replay never waits on variants_mutex_ behind a build. + struct Build { + enum State : std::uint8_t { idle, queued, running, done } state = idle; + bool demanded = false; // a job at replay's priority (0) is queued: a warm-up queued by module size is not enough + bool wanted = false; // replay asked for it before it was done: counted in pipeline_wait's "still building" + VkPipeline handle = VK_NULL_HANDLE; + unsigned long long skips = 0; // draws or dispatches skipped while it was being built + }; + static std::mutex& builds_mutex() { + static std::mutex mutex; + return mutex; + } + static std::condition_variable& builds_changed() { + static std::condition_variable changed; + return changed; + } + + VkPipeline build_variant(bool compute, std::uint32_t unbound, const char* trigger) { + return compute ? build_compute(trigger) : variant(unbound, trigger); + } + + // Takes the build for this thread unless another thread has it or it is done. + static bool claim_locked(Build& b) { + if (b.state == Build::running || b.state == Build::done) return false; + b.state = Build::running; + return true; + } + + static void want_locked(Build& b) { + if (b.wanted || b.state == Build::done) return; + b.wanted = true; + leonida::pipeline_wait::stats().building.fetch_add(1, std::memory_order_relaxed); + } + + // A claimed build's result, published for replay, and every waiter woken. + void finish_build(std::uint32_t unbound, VkPipeline built, bool compute) { + unsigned long long skipped = 0; + { + std::lock_guard lock(builds_mutex()); + Build& b = builds_[unbound]; + b.state = Build::done; + b.handle = built; + if (b.wanted) { + b.wanted = false; + leonida::pipeline_wait::stats().building.fetch_sub(1, std::memory_order_relaxed); + } + skipped = b.skips; + if (!unbound && built) ready0_.store(built, std::memory_order_release); + } + builds_changed().notify_all(); + if (skipped && trace_pipeline_compile()) + std::fprintf(stderr, "[rt] pipeline-deferred type=%s skipped=%llu ready=%d\n", compute ? "compute" : "graphics", + skipped, int(built != VK_NULL_HANDLE)); + } + + // Builds the claimed variant on this thread and publishes it. + VkPipeline build_claimed(bool compute, std::uint32_t unbound, const char* trigger) { + VkPipeline built = VK_NULL_HANDLE; + try { + std::function hook; + { + std::lock_guard lock(pipeline_build_hook_mutex); + hook = pipeline_build_hook; + } + if (hook) hook(static_cast(this)); + built = build_variant(compute, unbound, trigger); + } catch (const std::exception& e) { + std::fprintf(stderr, "[rt] pipeline build failed: %s\n", e.what()); + } catch (...) { + std::fprintf(stderr, "[rt] pipeline build failed\n"); // still finished below, or waiters would never be } - std::lock_guard lock(publication); - if (!warm) { - if (!requested_) requested_ = std::make_unique(); - auto [it, inserted] = requested_->try_emplace(unbound); - if (!it->second.handle) ++it->second.skips; - if (!inserted) return it->second.handle; + if (compute && helper_deferred_.exchange(false)) { + defer_build(unbound); + return VK_NULL_HANDLE; } + finish_build(unbound, built, compute); + return built; + } + + // The compile helper is making the variant's journal file (build_compute): not done, so its next use asks again. + // Waiters are not woken for it: a bounded wait ends at its deadline, an unlimited one looks again every 100 ms. + void defer_build(std::uint32_t unbound) { + std::lock_guard lock(builds_mutex()); + Build& b = builds_[unbound]; + b.state = Build::idle; + b.demanded = false; + } + + // A compile-worker job for the variant at `priority` (0: replay asked for it; a module size: a warm-up). False when + // it could not be queued (refused after an exit stop, or out of memory). With builds_mutex() held. + bool queue_locked(Build& b, bool compute, std::uint32_t unbound, std::size_t priority) { bool queued = false; try { - queued = PipelineCompiler::instance().submit(compile_owner(), &device_, warm_bytes, [this, compute, warm, unbound] { - VkPipeline built{}; - try { - built = compute ? build_compute(warm ? "warmup" : "dispatch-worker") - : variant(unbound, "draw-worker"); - if (async_replay_compile()) { - unsigned long long skipped = 0; - { - std::lock_guard publish(publication); - if (!requested_) requested_ = std::make_unique(); - auto& entry = (*requested_)[unbound]; - if (!entry.handle) skipped = entry.skips; - entry.handle = built; - } - if (skipped && trace_pipeline_compile()) - std::fprintf(stderr, "[rt] pipeline-deferred type=%s skipped=%llu ready=%d\n", - compute ? "compute" : "graphics", skipped, int(built != VK_NULL_HANDLE)); + const bool warm = priority != 0; + queued = PipelineCompiler::instance().submit(compile_owner(), &device_, priority, [this, compute, unbound, warm, + priority] { + { + std::lock_guard lock(builds_mutex()); + Build& b = builds_[unbound]; + if (warm && !b.demanded && b.state == Build::queued && warmup_waits_for_quiet(priority)) { + b.state = Build::idle; // left to its first use + return; } - } catch (const std::exception& e) { - std::fprintf(stderr, "[rt] pipeline compile worker failed: %s\n", e.what()); + if (!claim_locked(b)) return; // built, or being built by a submitting thread } - }); + build_claimed(compute, unbound, compute ? (warm ? "warmup" : "dispatch-worker") : "draw-worker"); + }, !compute); // a graphics build may also take the graphics worker } catch (...) { } - // Not queued (refused by a stop that came after the check above, or out of memory): no request stays - // recorded, so the next use asks again instead of waiting for a build that never comes. - if (!queued && !warm) requested_->erase(unbound); + if (queued && b.state == Build::idle) b.state = Build::queued; + if (queued && !priority) b.demanded = true; + return queued; + } + + // Asynchronous builds: the handle once built; otherwise makes sure a job at replay's priority is on its way and + // answers null, with `pending` false only when nothing is on its way (it could not be queued). builds_mutex() held. + VkPipeline request_locked(Build& b, bool compute, std::uint32_t unbound, bool& pending) { + pending = false; + if (b.state == Build::done) return b.handle; + pending = b.state == Build::running || (b.state == Build::queued && b.demanded) || + queue_locked(b, compute, unbound, 0); + if (pending) want_locked(b); return VK_NULL_HANDLE; } + // The first skips of each still-building variant are named (32 in all), the rest only counted (pipeline_wait.h). + void note_skip(bool compute, std::uint32_t unbound, bool first) const { + leonida::pipeline_wait::count_skip(compute); + static std::atomic logged{0}; + if (!first || logged.fetch_add(1, std::memory_order_relaxed) >= 32) return; + std::fprintf(stderr, "[rt] pipeline-wait: %s of %s pipeline %s (variant %u) skipped while it is being built, at " + "t=%.3f s\n", compute ? "dispatches" : "draws", compute ? "compute" : "graphics", + describe().c_str(), unbound, double(leonida::diagnostic_ms()) / 1000.0); + } + + std::string describe() const { + if (compute_entry_) return compute_entry_->name; + std::string names; + for (const StageSource& source : sources_) { + if (!source.entry) continue; + if (!names.empty()) names += '+'; + names += source.entry->name; + } + return names.empty() ? std::string("-") : names; + } + +public: + // Prepare's handle for the variant (ComputePipeline::build, GraphicsPipeline::variant), called with the context's + // resource lock held: never waits for a build another thread runs. Asynchronous builds (LEONIDA_ASYNC_PIPELINES=1) + // queue one at replay's priority and answer null; the draw or dispatch is skipped and counted. Otherwise a variant + // nobody has started is built here, as before (the submission's pre-pass, replay_await, normally did it with no + // lock held), and one running elsewhere (a warm-up) answers null. After an exit stop it is built here. + VkPipeline replay_get(bool compute, std::uint32_t unbound) { + if (!unbound) + if (const VkPipeline ready = ready0_.load(std::memory_order_acquire)) return ready; + bool build_here = false, pending = false, first = false; + VkPipeline handle = VK_NULL_HANDLE; + { + std::lock_guard lock(builds_mutex()); + Build& b = builds_[unbound]; + if (b.state == Build::done) return b.handle; + const bool async = async_replay_compile() && !PipelineCompiler::instance().closed(); + if (!async && claim_locked(b)) { + build_here = true; + } else { + if (async) { + handle = request_locked(b, compute, unbound, pending); + } else { + pending = true; // claimed by another thread + want_locked(b); + } + if (pending) first = b.skips++ == 0; + } + } + if (build_here) return build_claimed(compute, unbound, compute ? "dispatch" : "draw"); + if (pending) note_skip(compute, unbound, first); + return handle; + } + + // The submission's pre-pass (ComputePipeline::await, GraphicsPipeline::await), with no lock of the replay layer + // held. `until` as in pipeline_wait.h: probe answers what is built and starts nothing; otherwise a variant nobody + // has started is queued at replay's priority (asynchronous builds) or built here, and one still in flight is + // waited for until `until`. `*pending`: the null answer means "not built yet" (false: built, or cannot be). + // An unlimited wait looks again every 100 ms, so a job dropped from the queue (an exit stop) cannot leave it + // waiting for a build nobody will run: after a stop the variant is built here. + VkPipeline replay_await(bool compute, std::uint32_t unbound, std::int64_t until, bool* pending_out) { + namespace wait = leonida::pipeline_wait; + const auto answer = [pending_out](VkPipeline handle, bool pending) { + if (pending_out) *pending_out = pending && !handle; + return handle; + }; + if (!unbound) + if (const VkPipeline ready = ready0_.load(std::memory_order_acquire)) return answer(ready, false); + std::unique_lock lock(builds_mutex()); + Build& b = builds_[unbound]; // a std::map node: the reference stays valid + for (;;) { + if (b.state == Build::done) return answer(b.handle, false); + if (until == wait::probe) return answer(VK_NULL_HANDLE, true); + const bool async = async_replay_compile() && !PipelineCompiler::instance().closed(); + bool pending = false; + if (!async) { + if (claim_locked(b)) { + lock.unlock(); + return answer(build_claimed(compute, unbound, compute ? "dispatch" : "draw"), false); + } + pending = true; // claimed by another thread (a warm-up): waited for below + want_locked(b); + } else { + request_locked(b, compute, unbound, pending); + } + if (!pending) { + // Refused by an exit stop that came after the closed() check above: round again to build it here. + if (async && PipelineCompiler::instance().closed()) continue; + return answer(VK_NULL_HANDLE, false); + } + if (until <= wait::now_ns()) return answer(VK_NULL_HANDLE, true); + const auto done = [&] { return b.state == Build::done; }; + const std::int64_t slice = until == wait::forever ? wait::now_ns() + 100000000 : until; + builds_changed().wait_until(lock, std::chrono::steady_clock::time_point(std::chrono::nanoseconds(slice)), + done); + if (b.state == Build::done) return answer(b.handle, false); + if (until != wait::forever && until <= wait::now_ns()) return answer(VK_NULL_HANDLE, true); + // An unlimited wait, still pending: ask again (after an exit stop the variant is built here). + } + } + + // Record time (SetPipelineState for compute, a draw for graphics, with the render-target slots it binds and + // whether it binds a depth buffer): asynchronous builds start on the compile worker before the list is submitted. + // Never waits; nothing to do when the variant is the last one asked for here. + void request_early(std::uint32_t bound_targets, bool depth_bound) { + if (!async_replay_compile() || !registered_) return; + std::uint32_t unbound = 0; + if (is_graphics_) { + for (std::size_t slot = 0; slot < graphics_.color_formats.size() && slot < 8; ++slot) + if (graphics_.color_formats[slot] != VK_FORMAT_UNDEFINED && !(bound_targets & (1u << slot))) + unbound |= 1u << slot; + if (graphics_.depth_format != VK_FORMAT_UNDEFINED && !depth_bound) + unbound |= leonida::GraphicsPipeline::unbound_depth; + if (!unbound && graphics_.pipeline) return; + } else if (!pipeline_.build || pipeline_.skipped) { + return; // an eager pipeline has no build; a built lazy one is caught by ready0_ below + } + if (!unbound && ready0_.load(std::memory_order_relaxed)) return; + if (early_.exchange(unbound + 1, std::memory_order_relaxed) == unbound + 1) return; + if (PipelineCompiler::instance().closed()) return; + std::lock_guard lock(builds_mutex()); + bool pending = false; + request_locked(builds_[unbound], !is_graphics_, unbound, pending); + } + +private: + // A warm-up of a module over LEONIDA_COMPUTE_WARMUP_LIVE_MAX_BYTES of SPIR-V (default 128 KiB, 0: no limit) is not + // started while the title submits (a submission in the last second): it is left to the pipeline's first use. A + // create holds the compile gate (SubmitMutex::CompileTurn) for its whole length and every submission waits behind + // it; on NVIDIA 630.20 the modules over 640 KiB take 4-25 s each. Measured in a native boot past the story load: + // 694 warm-ups of modules over 128 KiB against 25 such builds a dispatch asked for, and one run's submissions + // waited 140 s in all at the gate behind warm-ups. + static bool warmup_waits_for_quiet(std::size_t bytes) { + static const std::size_t limit = [] { + char text[32]{}; + const DWORD n = GetEnvironmentVariableA("LEONIDA_COMPUTE_WARMUP_LIVE_MAX_BYTES", text, sizeof(text)); + return (n > 0 && n < sizeof(text)) ? static_cast(std::strtoull(text, nullptr, 10)) + : std::size_t{128} << 10; + }(); + if (!limit || bytes <= limit || !leonida::pipeline_wait::title_submitting()) return false; + if (compile_helper::wanted(bytes)) return false; // the helper compiles it, in its own process + if (leonida::pipeline_wait::stats().warmups_left.fetch_add(1, std::memory_order_relaxed) == 0) { + static std::atomic logged{false}; + if (!logged.exchange(true)) + std::fprintf(stderr, "[rt] d3d12: compute warm-ups over %zu KiB are left to their first use while the " + "title submits (LEONIDA_COMPUTE_WARMUP_LIVE_MAX_BYTES), from t=%.3f s\n", + limit >> 10, double(leonida::diagnostic_ms()) / 1000.0); + } + return true; + } + + // A warm-up of the compute pipeline on the compile worker, queued by module size, unless something asked already. + void queue_warmup(std::size_t bytes) { + if (PipelineCompiler::instance().closed()) return; + std::lock_guard lock(builds_mutex()); + Build& b = builds_[0]; + if (b.state == Build::idle) queue_locked(b, true, 0, bytes); + } + static void warmup_enqueue(PipelineState* pso, std::size_t bytes) { static const std::size_t max_bytes = [] { char text[32]{}; @@ -9269,7 +11852,7 @@ class PipelineState final wchar_t v[2]{}; return !(GetEnvironmentVariableW(L"LEONIDA_COMPUTE_WARMUP", v, 2) == 1 && v[0] == L'0'); }(); - if (on && bytes && bytes <= max_bytes) pso->queue_build(true, 0, bytes); + if (on && bytes && bytes <= max_bytes) pso->queue_warmup(bytes); } // What a graphics pipeline is made from, so variants can be built at draw time. @@ -9355,6 +11938,7 @@ class PipelineState final dyn_list[dyn_count++] = VK_DYNAMIC_STATE_STENCIL_REFERENCE; dyn_list[dyn_count++] = VK_DYNAMIC_STATE_BLEND_CONSTANTS; if (!r.mesh && !r.bindings.empty()) dyn_list[dyn_count++] = VK_DYNAMIC_STATE_VERTEX_INPUT_BINDING_STRIDE; + if (r.depth.depthBoundsTestEnable) dyn_list[dyn_count++] = VK_DYNAMIC_STATE_DEPTH_BOUNDS; VkPipelineDynamicStateCreateInfo dynamic{VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO}; dynamic.dynamicStateCount = dyn_count; dynamic.pDynamicStates = dyn_list; @@ -9459,6 +12043,7 @@ class PipelineState final info.pDynamicState = &dynamic; info.flags=flags; info.layout = graphics_.layout; + info.flags |= fast_pipeline_flags(false); VkPipeline pipeline = VK_NULL_HANDLE; const auto cache = device_.pipeline_cache(); const char* program = "-", *fragment = "-"; @@ -9589,9 +12174,14 @@ class PipelineState final unsigned rgba4_mask_ = 0; // graphics: the B4G4R4A4 targets stored as RGBA8 that the pixel shader is quantised for bool dual_source_ = false; // graphics: a SRC1 blend factor; the pixel shader's SV_Target1 is Location 0, Index 1 std::vector sources_; - struct Request { VkPipeline handle{}; unsigned long long skips = 0; }; - using Requests = std::map; - std::unique_ptr requested_; + std::map builds_; // under builds_mutex() + std::atomic ready0_{VK_NULL_HANDLE}; // variant 0 once built: read without the lock + // Compile helper (build_compute, under variants_mutex_): the journal file asked for and not there yet; whether + // the helper gave up on this pipeline (it is then built here); a build just deferred (read by build_claimed). + std::filesystem::path helper_file_; + bool helper_refused_ = false; + std::atomic helper_deferred_{false}; + std::atomic early_{0}; // request_early: the last mask asked for, plus one std::string profile_shaders_; // populated only with compile tracing enabled std::size_t stage_bytes_ = 0; std::mutex variants_mutex_; @@ -10137,7 +12727,7 @@ struct TitleTexture { // misses. Video planes, rewritten whole every frame, are caught by the sampled one first. std::uint64_t full_hash = 0; bool full_hashed = false; - bool every_byte() const { return mapped && layout.layout.size <= (4u << 20); } + bool every_byte() const { return mapped && (async_texture_refresh() || layout.layout.size <= (4u << 20)); } std::uint64_t fills = 0; }; @@ -10168,12 +12758,18 @@ bool title_xg_layout(const Resource& r, rt::xg_xs::Texture& out, std::arraysecond->resource != resource) return; TitleTexture& t = *it->second; t.mapped = true; + if (async_texture_refresh() && !t.gpu_written) mapped_title_textures[address] = it->second; t.memory.retry(); // The title computes the layout of what it writes right before it maps: take it when no view gave one. if (!t.gpu_written && (t.layout_guessed || !t.layout_known) && @@ -10181,6 +12777,7 @@ void DeviceState::title_texture_mapped(const void* resource, std::uint64_t addre t.layout_known = true; t.layout_guessed = false; t.layout_from_xg = true; + index_texture(t); t.hashed = false; } static std::atomic logged{0}; @@ -10232,7 +12829,12 @@ void DeviceState::title_texture_gone(const void* resource, std::uint64_t address gpu_placements.remove(address, resource); } const auto it = title_textures.find(address); - if (it != title_textures.end() && it->second->resource == resource) title_textures.erase(it); + if (it != title_textures.end() && it->second->resource == resource) { + texture_ranges.erase(address); + mapped_title_textures.erase(address); + it->second->resource = nullptr; + title_textures.erase(it); + } } void DeviceState::drain_titles_gone() { @@ -10898,6 +13500,8 @@ 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_before_execute([this] { 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 @@ -10931,7 +13535,11 @@ class Device final state_.geometry.refresh(DeviceState::copy_geometry); } const phases::Scope timed(phases::textures); - refresh_title_textures(); + if (async_texture_refresh()) { + if (!t_in_title_textures) request_title_refresh(); + } else { + refresh_title_textures(); + } }); { char text[16] = {}; @@ -11253,6 +13861,41 @@ class Device final std::fprintf(stderr, "[rt] d3d12: descriptor hash: %s (all %zu modules)\n", leonida::descriptor_hash_kind_name(descriptor_hash), hash_modules.total()); } + // Which entry layout the loaded modules read (descriptor_table.h): a tagged module reads the kind word next to + // each index and uses it to tell which array that index is bound in (a 3D T# read by a 2D op is not another + // image), and the inserts below fill it. A plain library reads only the index, exactly as before. The kind + // word is additive, so one tagged module needs the tagged layout whatever the plain count (the library's + // vote); chosen once here, like the hash kind, and LEONIDA_DESCRIPTOR_TABLE overrides. + leonida::DescriptorTableCensus table_modules{}; + leonida::DescriptorTableLayout descriptor_table = leonida::DescriptorTableLayout::plain; + if (const leonida::ShaderLibrary* library = state_.library()) { + table_modules = library->descriptor_table_census(); + descriptor_table = library->descriptor_table_layout(); + } + leonida::DescriptorTableLayout override_table = descriptor_table; + if (leonida::descriptor_table_layout_from_env(std::getenv("LEONIDA_DESCRIPTOR_TABLE"), &override_table)) { + std::fprintf(stderr, + "[rt] d3d12: descriptor table: %s (LEONIDA_DESCRIPTOR_TABLE; %zu tagged / %zu plain modules)\n", + leonida::descriptor_table_layout_name(override_table), table_modules.tagged, + table_modules.plain); + descriptor_table = override_table; + // Under a plain table a tagged module reads no kind at all, so every image an instruction reads through + // another dimension's array takes that array's fallback. That is what the override asks for; say so. + if (override_table == leonida::DescriptorTableLayout::plain && table_modules.tagged) + std::fprintf(stderr, + "[rt] d3d12: LEONIDA_DESCRIPTOR_TABLE forces the plain descriptor table while %zu " + "module(s) read the kind word; their image lookups through another dimension's array " + "take the fallback\n", + table_modules.tagged); + } else if (table_modules.tagged && table_modules.plain) { + std::fprintf(stderr, "[rt] d3d12: descriptor table: %zu tagged / %zu plain modules; using %s\n", + table_modules.tagged, table_modules.plain, + leonida::descriptor_table_layout_name(descriptor_table)); + } else { + std::fprintf(stderr, "[rt] d3d12: descriptor table: %s (all %zu modules)\n", + leonida::descriptor_table_layout_name(descriptor_table), table_modules.total()); + } + state_.descriptor_table_tagged = descriptor_table == leonida::DescriptorTableLayout::tagged; const auto get_properties = reinterpret_cast( state_.info.get_instance_proc(state_.info.instance, "vkGetPhysicalDeviceProperties2")); if (get_properties) { @@ -11327,6 +13970,7 @@ class Device final // after it, so the generations flush() retires are free at once. { std::lock_guard submit(context.submit_mutex()); + const leonida::SubmitMutex::SubmitTurn turn(context.submit_mutex()); // the compile gate context.observe_result(context.vk.vkDeviceWaitIdle(state_.info.device), "vkDeviceWaitIdle"); } state_.bindless_idle_waits.fetch_add(1, std::memory_order_relaxed); @@ -11416,7 +14060,14 @@ class Device final if (!vk.vkGetBufferDeviceAddress) return false; char text[16] = {}; size_t length = 0; - const bool set = getenv_s(&length, text, "LEONIDA_ARENA_MB") == 0 && length > 1; + bool set = getenv_s(&length, text, "LEONIDA_ARENA_MB") == 0 && length > 1; + // A value the CRT's copy of the environment does not give (or one past this buffer): asked of Windows too, + // then report the size applied to the arena. + if (!set) { + const DWORD n = GetEnvironmentVariableA("LEONIDA_ARENA_MB", text, sizeof(text)); + 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}; leonida::ArenaSize size = leonida::decide_arena_size(set ? text : nullptr, limits); auto& arena = state_.arena; @@ -11501,6 +14152,8 @@ class Device final return false; } 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"); // 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) @@ -11552,6 +14205,7 @@ class Device final 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::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); // Copy only registered title data. Each immutable upload stays alive in the queue command slot @@ -11624,6 +14278,7 @@ class Device final if (state_.context) { { std::lock_guard lock(state_.context->submit_mutex()); + const leonida::SubmitMutex::SubmitTurn turn(state_.context->submit_mutex()); // the compile gate state_.context->observe_result(state_.context->vk.vkDeviceWaitIdle(state_.info.device), "vkDeviceWaitIdle"); } @@ -11633,6 +14288,8 @@ class Device final state_.context->set_bindless_current(nullptr); // the retired generations go with state_.bindless below } if (state_.context) { + if (state_.gpu_resolver) state_.gpu_resolver->halt(); // it calls into the geometry copies + ShadowPages::gpu_copy = nullptr; state_.geometry.release(state_); state_.external_windows.release(state_); std::lock_guard upload(state_.title_upload_mutex); @@ -11660,7 +14317,7 @@ class Device final if (const unsigned building = state_.active_compiles.load()) std::fprintf(stderr, "[rt] d3d12: %u pipeline build(s) still running at device teardown; " "pipeline_cache.session.bin not written\n", building); - else + else if (!compile_helper::build_host) save_session_pipeline_cache(state_.context->vk, state_.info.device, state_.pipeline_cache_handle); state_.context->vk.vkDestroyPipelineCache(state_.info.device, state_.pipeline_cache_handle, nullptr); } @@ -11671,6 +14328,8 @@ class Device final } bool ok() const { return state_.context && state_.context->loaded(); } + // gta6rt --precompile-pipelines builds against the device's own state (precompile_compute_pipelines). + DeviceState& build_state() { return state_; } const VulkanDeviceInfo& info() const { return state_.info; } // Acceleration-structure resources work: KHR builds, or the XDXR records (which need the GPU address arena). bool acceleration_structures() const { @@ -11847,7 +14506,8 @@ class Device final d.height, unsigned(d.depth_or_array), d.format, unsigned(srv.Format), unsigned(d.mips), unsigned(written)); if (!written && stats.refusals == refusals) refuse_title_view("no reason recorded", d, address); if (!written) ++stats.null_views; - if (stats.views == 64 || !(stats.views % 2048)) log_title_census("slot-70 texture views"); + if (leonida::fsdraw::enabled() && (stats.views == 64 || !(stats.views % 2048))) + log_title_census("slot-70 texture views"); } state_.drain_titles_gone(); return written; @@ -11944,6 +14604,8 @@ class Device final } auto& slot = state_.title_textures[address]; 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; } @@ -11990,7 +14652,11 @@ class Device final // 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. - const auto entries = leonida::title_texture_snapshot(state_.title_textures); + // 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; title_pass_ = true; std::uint64_t checked = 0, filled = 0, fill_pass_ns = 0; const auto visit = [&](TitleTexture& t) { @@ -12012,7 +14678,8 @@ class Device final } std::uint64_t hash = 0; if (!title_texture_readable(t)) return; - checked += hashed_bytes(span); + 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) { @@ -12021,11 +14688,33 @@ class Device final stats.hash_ns += std::chrono::duration_cast(clock::now() - start).count(); return ok; }; - if (!timed_hash(hash)) { + 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 || t.layout.layout.size != span || t.fills != fills) return; + ++stats.mapped_checks; + if (!ok) { + t.memory.defer(); + t.stale = true; + return; + } + 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 (t.hashed && hash == t.hash && !t.stale) { + 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; @@ -12042,7 +14731,10 @@ class Device final return; } const auto fill_start = clock::now(); - filled += fill_title_texture(t, false); + 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; @@ -12068,25 +14760,53 @@ class Device final if (!written.empty() || overflow || map_all || !title_map_changes_.empty()) { stats.written_ranges += written.size(); leonida::merge_title_writes(written); - for (const auto& entry : entries) { - TitleTexture& t = *entry.second; - if (t.gpu_written || !t.layout_known) continue; - const std::uint64_t begin = t.cpu, end = t.cpu + t.layout.layout.size; - if (map_all || leonida::title_write_overlaps(title_map_changes_, begin, end)) t.memory.retry(); - if (leonida::title_write_overlaps(written, begin, end)) { - t.memory.retry(); - t.stale = true; - } - if (overflow) { - t.memory.retry(); - t.hashed = false; + const auto invalidate = [&](TitleTexture& t, bool write) { + if (t.gpu_written || !t.layout_known) return; + t.memory.retry(); + 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); + if (write || map_all || overflow || leonida::title_write_overlaps(title_map_changes_, t.cpu, end)) + invalidate(t, write); } + } 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); + 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(); + 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) { + if (async ? !entry.second->mapped && entry.second->stale : entry.second->mapped || entry.second->stale) { + if (async) { + 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); } @@ -12095,7 +14815,15 @@ class Device final const auto first_bytes = checked, first_hash_ns = stats.hash_ns; if (check_budget) { const auto sweep_start = clock::now(); - leonida::poll_title_textures(entries, title_refresh_cursor_, visit, [&] { + // 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; @@ -12119,7 +14847,14 @@ class Device final 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; - log_title_census("refresh"); + 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; + } + if (leonida::fsdraw::enabled()) log_title_census("refresh"); } inside.reset(); lock.unlock(); @@ -12129,6 +14864,7 @@ class Device final private: struct TitleTextureStats { + std::uint64_t mapped_checks = 0, mapped_changed = 0, mapped_fills = 0; // (format, Layout word, dimension, mips) of the slot-70 texture views -> views std::map, std::uint64_t> asked; std::map refused; // why a view is a null view -> views @@ -12170,7 +14906,7 @@ class Device final std::condition_variable wake; std::deque queue; // texture addresses std::unordered_set queued; - bool stop = false; + bool stop = false, refresh = 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) @@ -12186,12 +14922,24 @@ class Device final }; std::unique_ptr title_filler_; std::once_flag title_filler_once_; - void queue_title_fill(std::uint64_t address) { + void start_title_filler() { std::call_once(title_filler_once_, [this] { title_filler_ = std::make_unique(); TitleFiller* f = title_filler_.get(); f->thread = std::thread([this, f] { run_title_filler(*f); }); }); + } + 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(); { std::lock_guard lock(title_filler_->mutex); if (!title_filler_->queued.insert(address).second) return; @@ -12204,14 +14952,21 @@ class Device final auto since = clock::now(); for (;;) { std::uint64_t address = 0; + bool refresh = false, fill = false; { std::unique_lock lock(f.mutex); - f.wake.wait(lock, [&] { return f.stop || !f.queue.empty(); }); + f.wake.wait(lock, [&] { return f.stop || f.refresh || !f.queue.empty(); }); if (f.stop) return; - address = f.queue.front(); - f.queue.pop_front(); - f.queued.erase(address); + refresh = std::exchange(f.refresh, false); + fill = !f.queue.empty(); + if (fill) { + address = f.queue.front(); + f.queue.pop_front(); + f.queued.erase(address); + } } + if (refresh) refresh_title_textures(); + if (!fill) continue; 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 @@ -12239,6 +14994,7 @@ class Device final every_byte = t.every_byte(); } else { filled = fill_title_texture(t, true) != 0; + if (!filled) t.stale = true; } } } @@ -12353,6 +15109,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_map_generation_ = 0; // likewise: the map changes the passes have seen std::chrono::steady_clock::time_point title_retry_all_{}; // likewise @@ -12449,6 +15206,7 @@ class Device final 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 { @@ -12467,6 +15225,7 @@ class Device final 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); textures.erase(address); t = make_title_texture(d, words, srv, address, same_shape ? formats : std::vector{}); } else if (t) { @@ -12566,6 +15325,7 @@ class Device final } ++title_stats_.made; TitleTexture* t = entry.get(); + state_.index_texture(*entry); state_.title_textures[address] = std::move(entry); if (title_fill_async() && !t->memory.pending()) queue_title_fill(address); return t; @@ -13809,7 +16569,7 @@ class Device final pipeline->attach_device(identity()); const HRESULT hr = stream.has_cs ? pipeline->create_compute(stream.compute) : pipeline->create_graphics(stream.graphics, &stream.ms, &stream.as, - stream.back_masks ? &stream.back_stencil : nullptr); + stream.back_masks ? &stream.back_stencil : nullptr, stream.depth_bounds); if (FAILED(hr)) { pipeline->Release(); return finish(hr); @@ -14087,8 +16847,7 @@ class Device final words[3] = 0x0002403Cu; } std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); - // LOCAL DIAGNOSTIC: the CBVs the title makes, where they go and what V# they get - if (leonida::local_diagnostics()) { + if (leonida::fsdraw::enabled()) { // LOCAL DIAGNOSTIC: the CBVs the title makes, where they go and what V# they get static std::atomic made{0}; const std::uint64_t n = ++made; if (n <= 8 || n % 600 == 0 || n % 600 == 1) @@ -14293,8 +17052,7 @@ class Device final } } write_image_descriptor(*r, view, destination, ImageViewUse::sampled); - // LOCAL DIAGNOSTIC: the texture SRVs the title makes, where they go and the T# they get - if (leonida::local_diagnostics()) { + if (leonida::fsdraw::enabled()) { // LOCAL DIAGNOSTIC: the texture SRVs the title makes, where they go and the T# they get static std::atomic made{0}; const std::uint64_t n = ++made; if (n <= 8 || n % 600 == 0 || n % 600 == 1) { @@ -15601,7 +18359,7 @@ class Device final if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS2)) return d3d12_trace::result(method, E_INVALIDARG); auto* opts = static_cast(data); *opts = {}; - opts->DepthBoundsTestSupported = FALSE; + opts->DepthBoundsTestSupported = state_.info.features.depthBounds ? TRUE : FALSE; opts->ProgrammableSamplePositionsTier = D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER_NOT_SUPPORTED; return d3d12_trace::result(method, S_OK); } @@ -16984,6 +19742,9 @@ bool save_pipeline_caches_at_exit(unsigned wait_ms) { HRESULT create_vulkan_device(const VulkanDeviceInfo& info, REFIID riid, void** out) { if (!out) return E_POINTER; *out = nullptr; + // An unset LEONIDA_PIPELINE_WAIT_MS: a bounded wait (then a skip) only where builds are asynchronous; without them + // a submission waits for every build, as before, but with no lock held (src/pipeline_wait.h). + leonida::pipeline_wait::default_submission_ms().store(async_replay_compile() ? 24 : -1); auto* device = new Device(info); if (!device->ok()) { device->Release(); @@ -17117,6 +19878,18 @@ std::uintptr_t graphics_pipeline_id(ID3D12PipelineState* pipeline) { return p && p->resolve_type(true) ? p->id() : 0; } +void set_pipeline_build_hook(std::function hook) { + std::lock_guard lock(pipeline_build_hook_mutex); + pipeline_build_hook = std::move(hook); +} + +void request_pipeline_build(std::uintptr_t id, std::uint32_t bound_targets, bool depth_bound) { + if (!id || !async_replay_compile()) return; + // The id is the PSO's own ID3D12PipelineState pointer (PipelineState::id), which the list keeps a reference to. + auto* pso = static_cast(reinterpret_cast(id)); + pso->request_early(bound_targets, depth_bound); +} + const std::vector* pipeline_subgroup_requests(ID3D12PipelineState* pipeline) { const PipelineState* p = PipelineState::from(pipeline); return p && (p->compute() || p->graphics()) ? &p->subgroup_requests() : nullptr; @@ -17144,6 +19917,10 @@ D3D12_GPU_VIRTUAL_ADDRESS console_descriptor_table_va(D3D12_GPU_VIRTUAL_ADDRESS return console_heap_ranges().shader_va(va); } +bool console_descriptor_heap_range(D3D12_GPU_VIRTUAL_ADDRESS va, std::uint64_t& console_va, std::uint64_t& bytes) { + return console_heap_ranges().range_of(va, console_va, bytes); +} + // The device a command list of this module belongs to: its attached device is the d3d12_xs proxy when the title made // the list through one (Device::identity), which does not answer Device's tag itself. Device* list_device(IUnknown* device) { @@ -18267,6 +21044,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin enable.logicOp = chosen_features.logicOp; enable.depthClamp = chosen_features.depthClamp; enable.multiViewport = chosen_features.multiViewport; + enable.depthBounds = chosen_features.depthBounds; // DEPTH_STENCIL1/2 DepthBoundsTestEnable, OMSetDepthBounds enable.geometryShader = chosen_features.geometryShader; // translated geometry shaders (195 in the corpus) // What translated shaders declare (the index's `features`): 64-bit integers in most of the corpus (25,803 of // 26,503 entries), doubles, 16-bit integers, clip and cull distances in a few vertex shaders, formatless image @@ -18407,6 +21185,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin v13.add_extensions(device_extensions); if (info.depth_range_unrestricted) device_extensions.push_back(VK_EXT_DEPTH_RANGE_UNRESTRICTED_EXTENSION_NAME); info.pipeline_creation_feedback = v13.core || has_device_extension(VK_EXT_PIPELINE_CREATION_FEEDBACK_EXTENSION_NAME); + info.pipeline_cache_control = v13.core && v13.pipeline_creation_cache_control; if (trace_pipeline_compile() && !v13.core && info.pipeline_creation_feedback) device_extensions.push_back(VK_EXT_PIPELINE_CREATION_FEEDBACK_EXTENSION_NAME); if (info.conservative_rasterization) device_extensions.push_back(VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME); @@ -18452,12 +21231,16 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin leonida::DeviceFaultFeatures fault_features; const bool aftermath = leonida::aftermath::enable(); // already on, before the instance: see above char device_fault[2]{}; + // LEONIDA_DEVICE_FAULT=1: fault info, checkpoints and NVIDIA's diagnostics config. =2: fault info and checkpoints + // only — the diagnostics config compiles pipelines with debug info under other cache keys, so =2 keeps the warmed + // pipeline journal usable for a boot that only wants the fault report. if (GetEnvironmentVariableA("LEONIDA_DEVICE_FAULT", device_fault, sizeof(device_fault)) == 1 && - device_fault[0] == '1') { + (device_fault[0] == '1' || device_fault[0] == '2')) { info.device_fault_diagnostics = true; + const bool with_config = device_fault[0] == '1'; const auto fault = fault_features.enable(info.physical, vkGetPhysicalDeviceFeatures2, extensions, device_extensions, device_info, - {true, true, leonida::aftermath::extra_config_flags()}); + {true, with_config, leonida::aftermath::extra_config_flags()}); info.device_fault_info = fault.fault; info.device_checkpoints = fault.checkpoints; info.device_diagnostics_config = fault.diagnostics_config; @@ -18515,6 +21298,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin chosen.limits.maxPushConstantsSize); } + leonida::pipeline_wait::default_submission_ms().store(async_replay_compile() ? 24 : -1); // as create_vulkan_device auto* device = new Device(info); device->own(owned); // destroyed with the device from here on, even on failure if (!device->ok()) { @@ -18524,6 +21308,532 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin return hand_out(device, riid, out); } +// A Vulkan device made as `gta6rt --run` makes it, for building the library's compute pipelines with no title +// (--precompile-pipelines, --compile-server), with the two layouts create_compute makes. +class BuildHost { +public: + explicit BuildHost(const char* tag) : tag_(tag) {} + BuildHost(const BuildHost&) = delete; + BuildHost& operator=(const BuildHost&) = delete; + ~BuildHost() { + if (!d3d_) return; + if (device_) { + auto& vk = device_->context->vk; + if (plain_) vk.vkDestroyPipelineLayout(device_->info.device, plain_, nullptr); + if (with_set0_) vk.vkDestroyPipelineLayout(device_->info.device, with_set0_, nullptr); + } + d3d_->Release(); + } + + bool open() { + // The GPU address arena holds nothing here and does not change a pipeline: 64 MB, not a title's 2 GB. + _putenv_s("LEONIDA_ARENA_MB", "64"); + compile_helper::build_host = true; + if (FAILED(create_vulkan_device_standalone(__uuidof(ID3D12Device), reinterpret_cast(&d3d_), + QueueTestSettings::ignore)) || !d3d_) { + d3d_ = nullptr; + std::fprintf(stderr, "%s the Vulkan device could not be created\n", tag_); + return false; + } + Device* device = Device::from(d3d_); + if (!device) return false; + device_ = &device->build_state(); + DeviceState& state = *device_; + library_ = state.library(); + if (!library_) { + std::fprintf(stderr, "%s no translated shader library (LEONIDA_SHADERS)\n", tag_); + return false; + } + if (pipeline_journal_dir().empty()) + std::fprintf(stderr, "%s the pipeline journal is off (LEONIDA_PIPELINE_JOURNAL=0 or " + "LEONIDA_PIPELINE_CACHE_BYTES=0): only the driver's own cache is filled\n", tag_); + state.pipeline_cache(); // the shared cache and the journal's upkeep, as at a title's first pipeline + // Every pipeline goes into a journal file: one found in the shared cache would not be. + state.journal_ask_shared = false; + auto& vk = state.context->vk; + const VkDevice dev = state.info.device; + if (state.info.max_push_constants_size && state.info.max_push_constants_size < sizeof(leonida::ShaderUserData)) { + std::fprintf(stderr, "%s maxPushConstantsSize %u is under the shaders' %zu bytes: the runtime builds no " + "compute pipeline on this device\n", + tag_, state.info.max_push_constants_size, sizeof(leonida::ShaderUserData)); + return false; + } + const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(leonida::ShaderUserData)}; + VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; + layout_info.pushConstantRangeCount = 1; + layout_info.pPushConstantRanges = &push; + if (vk.vkCreatePipelineLayout(dev, &layout_info, nullptr, &plain_) != VK_SUCCESS) return false; + if (state.bindless) { + const VkDescriptorSetLayout set0 = state.bindless->layout(); + layout_info.setLayoutCount = 1; + layout_info.pSetLayouts = &set0; + if (vk.vkCreatePipelineLayout(dev, &layout_info, nullptr, &with_set0_) != VK_SUCCESS) + with_set0_ = VK_NULL_HANDLE; + } + if (const auto get_props = reinterpret_cast( + state.info.get_instance_proc + ? state.info.get_instance_proc(state.info.instance, "vkGetPhysicalDeviceProperties") + : nullptr)) { + VkPhysicalDeviceProperties props{}; + get_props(state.info.physical, &props); + max_shared_ = props.limits.maxComputeSharedMemorySize; + } + return true; + } + + DeviceState& state() { return *device_; } + const leonida::ShaderLibrary* library() const { return library_; } + + // Why create_compute would refuse the entry, or null. + const char* unbuildable(const leonida::ShaderEntry& entry, std::size_t bytes) const { + if (!bytes) return "no .spv"; + if (skip_compute(entry.name)) return "LEONIDA_SKIP_COMPUTE"; + if (entry.binding_count && !with_set0_) return "set-0 bindings and no bindless set"; + if (entry.lds_bytes && max_shared_ && entry.lds_bytes > max_shared_) return "workgroup memory over the limit"; + return nullptr; + } + + ComputeBuild build(const leonida::ShaderEntry& entry, const ComputeBuildOptions& options) { + const leonida::SubgroupRequest subgroup = leonida::decide_subgroup_size(entry, device_->info.subgroup); + return build_compute_pipeline(*device_, entry, entry.binding_count ? with_set0_ : plain_, subgroup, options); + } + + void destroy(VkPipeline pipeline) { + if (pipeline) device_->context->vk.vkDestroyPipeline(device_->info.device, pipeline, nullptr); + } + +private: + const char* tag_; + ID3D12Device* d3d_ = nullptr; + DeviceState* device_ = nullptr; + const leonida::ShaderLibrary* library_ = nullptr; + VkPipelineLayout plain_ = VK_NULL_HANDLE, with_set0_ = VK_NULL_HANDLE; + std::uint32_t max_shared_ = 0; +}; + +// gta6rt --precompile-pipelines (d3d12_precompile.h). +int precompile_compute_pipelines(const PrecompileOptions& options) { + using Clock = std::chrono::steady_clock; + const auto began = Clock::now(); + BuildHost host("[precompile]"); + if (!host.open()) return 1; + const leonida::ShaderLibrary* library = host.library(); + + // What to build: every compute entry the runtime could create a pipeline for. + struct Job { + const leonida::ShaderEntry* entry; + std::size_t bytes; + }; + std::vector jobs; + std::size_t not_buildable = 0, filtered = 0; + for (const leonida::ShaderEntry* entry : library->stage_entries("cs")) { + if (!options.filters.empty() && + std::none_of(options.filters.begin(), options.filters.end(), + [&](const std::string& part) { return entry->name.find(part) != std::string::npos; })) { + ++filtered; + continue; + } + const std::size_t bytes = library->spirv_bytes(*entry); + if ((options.min_bytes && bytes < options.min_bytes) || (options.max_bytes && bytes > options.max_bytes)) { + ++filtered; + continue; + } + if (const char* why = host.unbuildable(*entry, bytes)) { + ++not_buildable; + std::fprintf(stderr, "[precompile] %s: not built (%s)\n", entry->name.c_str(), why); + continue; + } + jobs.push_back({entry, bytes}); + } + std::stable_sort(jobs.begin(), jobs.end(), [&](const Job& a, const Job& b) { + return options.smallest_first ? a.bytes < b.bytes : a.bytes > b.bytes; + }); + if (options.limit && jobs.size() > options.limit) jobs.resize(options.limit); + std::uint64_t total_bytes = 0; + for (const Job& job : jobs) total_bytes += job.bytes; + const unsigned threads = (std::max)(1u, options.threads); + const unsigned big_threads = options.big_threads ? (std::min)(options.big_threads, threads) : threads; + std::fprintf(stderr, "[precompile] %zu compute entries to build (%.1f MB of SPIR-V; %zu filtered out, %zu not " + "buildable), %s first, %u thread(s), at most %u on modules over %zu bytes; journal %ls\n", + jobs.size(), double(total_bytes) / 1e6, filtered, not_buildable, + options.smallest_first ? "smallest" : "largest", threads, big_threads, options.big_bytes, + pipeline_journal_dir().c_str()); + if (options.dry_run) { + for (const Job& job : jobs) std::printf("%zu %s\n", job.bytes, job.entry->name.c_str()); + return 0; + } + + std::atomic next{0}; + std::mutex progress_mutex; + std::size_t done = 0, compiled = 0, skipped = 0, hits = 0, failed = 0; + std::uint64_t done_bytes = 0; + std::mutex big_mutex; + std::condition_variable big_free; + unsigned big_running = 0; + auto worker = [&] { + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL); + for (;;) { + const std::size_t i = next.fetch_add(1); + if (i >= jobs.size()) return; + const Job& job = jobs[i]; + const bool big = job.bytes > options.big_bytes; + if (big) { + std::unique_lock lock(big_mutex); + big_free.wait(lock, [&] { return big_running < big_threads; }); + ++big_running; + } + ComputeBuildOptions build_options; + build_options.trigger = "precompile"; + build_options.serialize_big = false; // nothing else is building; big_threads bounds them instead + build_options.skip_journaled = !options.rebuild; + build_options.use_helper = options.via_helper; + build_options.mark_building = !options.via_helper; // an entry another process is compiling is left to it + ComputeBuild build; + try { + build = host.build(*job.entry, build_options); + } catch (const std::exception& e) { + std::fprintf(stderr, "[precompile] %s: %s\n", job.entry->name.c_str(), e.what()); + } + host.destroy(build.pipeline); + if (big) { + std::lock_guard lock(big_mutex); + --big_running; + big_free.notify_one(); + } + std::lock_guard lock(progress_mutex); + ++done; + done_bytes += job.bytes; + const char* what = "failed"; + if (build.skipped) ++skipped, what = "journaled already"; + else if (build.busy) ++skipped, what = "being built by another process"; + else if (build.result != VK_SUCCESS || (!build.pipeline && !build.skipped)) ++failed; + else if (build.journal_hit || build.from_shared) ++hits, what = "found in a cache"; + else ++compiled, what = build.journaled ? "compiled and journaled" : "compiled (not journaled)"; + const double elapsed = std::chrono::duration(Clock::now() - began).count(); + const double eta = done_bytes ? elapsed / double(done_bytes) * double(total_bytes - done_bytes) : 0.0; + // Skips are not logged one by one (a resumed run skips thousands); every 100th is, with the counts. + if (!build.skipped || done % 100 == 0 || done == jobs.size()) + std::fprintf(stderr, "[precompile] %zu/%zu %s (%zu B): %s in %.1f s (VkResult %d) | %zu compiled, %zu " + "from a cache, %zu skipped, %zu failed; %.0f s elapsed, ~%.0f s left by size\n", + done, jobs.size(), job.entry->name.c_str(), job.bytes, what, double(build.ms) / 1000.0, + int(build.result), compiled, hits, skipped, failed, elapsed, eta); + } + }; + std::vector pool; + for (unsigned t = 0; t < threads; ++t) pool.emplace_back(worker); + for (std::thread& t : pool) t.join(); + std::fprintf(stderr, "[precompile] done: %zu compiled, %zu from a cache, %zu journaled already, %zu failed, %zu " + "not buildable, in %.0f s\n", compiled, hits, skipped, failed, not_buildable, + std::chrono::duration(Clock::now() - began).count()); + return failed ? 2 : 0; +} + +// What a compute pipeline's journal name depends on besides its module: a name remembered for a module is good for +// another run while this is unchanged (compile_server's index). +std::uint64_t journal_name_context(DeviceState& state) { + leonida::pipeline_journal::Hasher hash; + hash.text("journal-name-context"); + hash.value(std::uint32_t(sizeof(leonida::ShaderUserData))); + const leonida::SubgroupSizeCaps& sub = state.info.subgroup; + hash.value(std::uint32_t(sub.subgroup_size_control)); + hash.value(std::uint32_t(sub.compute_full_subgroups)); + hash.value(sub.min_size); + hash.value(sub.max_size); + hash.value(sub.default_size); + hash.value(std::uint32_t(sub.required_stages)); + hash.value(std::uint32_t(state.info.device_diagnostics_config)); + if (state.info.device_diagnostics_config) hash.value(std::uint32_t(leonida::aftermath::extra_config_flags())); + if (state.bindless) hash_bindless_layout(hash, state.bindless->features()); + return hash.digest(); +} + +// gta6rt --compile-server (d3d12_compile_helper.h): builds what the games using this journal ask for, most urgent +// first, and with nothing asked fills the rest of the library, smallest module first, at idle priority. +int compile_server(const CompileServerOptions& options) { + namespace helper = compile_helper; + namespace journal = leonida::pipeline_journal; + const std::filesystem::path& dir = pipeline_journal_dir(); + if (dir.empty()) { + std::fprintf(stderr, "[compile-server] the pipeline journal is off: nothing to serve\n"); + return 1; + } + const auto requests = helper::requests_dir(dir); + std::error_code ec; + std::filesystem::create_directories(requests, ec); + // One helper per journal: a second (two games, or one started by hand) leaves the requests to the first. + journal::Hasher dir_hash; + dir_hash.text(dir.string().c_str()); + const std::wstring mutex_name = L"Local\\leonida-compile-server-" + std::to_wstring(dir_hash.digest()); + const HANDLE single = CreateMutexW(nullptr, TRUE, mutex_name.c_str()); + if (!single || GetLastError() == ERROR_ALREADY_EXISTS) { + std::fprintf(stderr, "[compile-server] another helper serves %ls\n", dir.c_str()); + return 0; + } + // It ends with the game that started it, at once: whatever it was building is in no file yet, and a file is + // written whole or not at all. A .building marker it leaves names a dead process and is taken over. + if (options.parent_pid) { + const HANDLE parent = OpenProcess(SYNCHRONIZE, FALSE, options.parent_pid); + if (!parent) { + std::fprintf(stderr, "[compile-server] process %lu is gone\n", options.parent_pid); + return 0; + } + std::thread([parent] { + WaitForSingleObject(parent, INFINITE); + TerminateProcess(GetCurrentProcess(), 0); + }).detach(); + } + BuildHost host("[compile-server]"); + if (!host.open()) return 1; + const leonida::ShaderLibrary* library = host.library(); + const std::vector entries = library->stage_entries("cs"); + std::map by_name; + for (const leonida::ShaderEntry* entry : entries) by_name.emplace(entry->name, entry); + const unsigned threads = (std::max)(1u, options.threads); + const unsigned idle_threads = (std::min)(options.idle_threads, threads - 1); // one is always free for a request + std::fprintf(stderr, "[compile-server] serving %ls: %u thread(s) for requests, %u of them filling the library " + "when nothing is asked, %zu compute entries\n", requests.c_str(), threads, idle_threads, + entries.size()); + + std::mutex mutex; + std::condition_variable wake; + std::vector pending; // the last listing, most urgent first + std::set busy; // stems being built here + std::map elsewhere; // stems another process is building + bool stop = false; + std::atomic requests_done{0}, filled{0}; + + // A request this helper can take: listed, not being built here, not one another process was building a moment ago. + auto take_locked = [&](helper::Request& out) { + const auto now = std::chrono::steady_clock::now(); + for (const helper::Request& request : pending) { + if (busy.count(request.stem)) continue; + if (const auto it = elsewhere.find(request.stem); it != elsewhere.end() && now - it->second < std::chrono::seconds(5)) + continue; + busy.insert(request.stem); + out = request; + return true; + } + return false; + }; + auto build_entry = [&](const leonida::ShaderEntry& entry, const char* trigger) { + ComputeBuildOptions build_options; + build_options.trigger = trigger; + build_options.serialize_big = false; + build_options.skip_journaled = true; + build_options.use_helper = false; + build_options.mark_building = true; + ComputeBuild build = host.build(entry, build_options); + host.destroy(build.pipeline); + build.pipeline = VK_NULL_HANDLE; + return build; + }; + auto serve = [&] { // normal priority: a title waits for these + for (;;) { + helper::Request request; + { + std::unique_lock lock(mutex); + wake.wait_for(lock, std::chrono::milliseconds(100), [&] { return stop || take_locked(request); }); + if (stop) return; + if (request.stem.empty()) continue; + } + std::string failure; + bool leave = false; // another process is building it: its file answers the request + const auto it = by_name.find(request.name); + const leonida::ShaderEntry* entry = it == by_name.end() ? nullptr : it->second; + const std::size_t bytes = entry ? library->spirv_bytes(*entry) : 0; + if (!entry) failure = "no compute entry of that name in this library"; + else if (const char* why = host.unbuildable(*entry, bytes)) failure = why; + // LOCAL FIX (compile helper: the journal name was checked after the build): the name is hashed from the + // module and this device's environment, which costs no driver call. A request from a game whose environment + // differs is answered before a compile is spent on a file that game never reads; the build below would only + // have found the same mismatch. + if (failure.empty()) { + ComputeBuildOptions key_options; + key_options.trigger = "compile-server"; + key_options.key_only = true; + key_options.use_helper = false; + const std::filesystem::path key_path = host.build(*entry, key_options).journal_path; + if (!key_path.empty() && key_path.stem().string() != request.stem) + failure = "its journal name here is " + key_path.stem().string() + + ": the helper's environment differs from the game's"; + } + if (failure.empty()) { + ComputeBuild build; + try { + build = build_entry(*entry, "compile-server"); + } catch (const std::exception& e) { + failure = e.what(); + } + if (failure.empty()) { + if (build.busy) + leave = true; + else if (!build.skipped && (build.result != VK_SUCCESS || !(build.journaled || build.journal_hit))) + failure = "not built or not journaled (VkResult " + std::to_string(int(build.result)) + ")"; + else if (!leonida::pipeline_journal::entry_usable(build.journal_path, host.state().pso_identity)) + failure = "requested writable journal file is missing or incompatible"; + else + std::fprintf(stderr, "[compile-server] %s (%zu B, priority %llu): %s in %.1f s\n", + request.name.c_str(), bytes, static_cast(request.priority), + build.skipped ? "journaled already" : "built and journaled", + double(build.ms) / 1000.0); + } + } + std::error_code ignored; + // LOCAL FIX (compile helper: a .failed left with its .request listed): the .req goes first. A request with + // no .req and no .failed is one the game reads as answered, so it builds the pipeline itself instead of + // waiting for a file that is not coming (Client::state). + if (!leave) std::filesystem::remove(requests / (request.stem + ".req"), ignored); + if (!failure.empty()) { + helper::write_line(requests / (request.stem + ".failed"), failure); + std::fprintf(stderr, "[compile-server] %s: %s\n", request.name.c_str(), failure.c_str()); + } + if (!leave) ++requests_done; + std::lock_guard lock(mutex); + busy.erase(request.stem); + if (leave) elsewhere[request.stem] = std::chrono::steady_clock::now(); + } + }; + + // The rest of the library, smallest module first, while nothing is asked. The journal names of modules looked at + // before are kept in requests/names.idx (with each module's size and time, and what the names depend on), so a + // later helper finds what is missing without reading every module again. + struct Indexed { + std::uint64_t size = 0; + long long mtime = 0; + std::string stem; + }; + std::map index; + std::mutex index_mutex; + const auto index_file = requests / "names.idx"; + const std::string signature = "v1 " + std::to_string(journal_name_context(host.state())); + { + std::ifstream in(index_file, std::ios::binary); + std::string line; + if (std::getline(in, line) && line == signature) { + while (std::getline(in, line)) { + const auto t1 = line.find('\t'), t2 = line.find('\t', t1 + 1), t3 = line.find('\t', t2 + 1); + if (t3 == std::string::npos) continue; + index[line.substr(0, t1)] = {std::strtoull(line.c_str() + t1 + 1, nullptr, 10), + std::strtoll(line.c_str() + t2 + 1, nullptr, 10), line.substr(t3 + 1)}; + } + } + } + auto save_index = [&] { + std::string text = signature + "\n"; + std::lock_guard lock(index_mutex); + for (const auto& [name, item] : index) + text += name + "\t" + std::to_string(item.size) + "\t" + std::to_string(item.mtime) + "\t" + item.stem + "\n"; + journal::write_entry(index_file, text.data(), text.size()); + }; + std::vector fill_order = entries; + std::vector fill_bytes(fill_order.size()); + { + std::vector> sized; + for (const leonida::ShaderEntry* entry : entries) sized.emplace_back(library->spirv_bytes(*entry), entry); + std::stable_sort(sized.begin(), sized.end(), [](const auto& x, const auto& y) { return x.first < y.first; }); + for (std::size_t i = 0; i < sized.size(); ++i) { + fill_order[i] = sized[i].second; + fill_bytes[i] = sized[i].first; + } + } + std::atomic fill_next{0}; + std::atomic fill_unsaved{0}; + auto fill = [&] { + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_IDLE); + for (;;) { + { + // Requests first: wait while one is listed that this helper could take. + std::unique_lock lock(mutex); + wake.wait_for(lock, std::chrono::milliseconds(200), [&] { + if (stop) return true; + for (const helper::Request& request : pending) + if (!busy.count(request.stem)) return false; + return true; + }); + if (stop) return; + bool asked = false; + for (const helper::Request& request : pending) + if (!busy.count(request.stem)) asked = true; + if (asked) continue; + } + const std::size_t i = fill_next.fetch_add(1); + if (i >= fill_order.size()) { + if (i == fill_order.size()) { + save_index(); + std::fprintf(stderr, "[compile-server] the library is in the journal (%u built while idle)\n", + filled.load()); + } + return; + } + const leonida::ShaderEntry& entry = *fill_order[i]; + if (host.unbuildable(entry, fill_bytes[i])) continue; + std::error_code stat; + const auto spv = library->spirv_file(entry); + const long long mtime = static_cast(std::filesystem::last_write_time(spv, stat).time_since_epoch().count()); + std::filesystem::path path; + { + std::lock_guard lock(index_mutex); + const auto it = index.find(entry.name); + if (it != index.end() && it->second.size == fill_bytes[i] && it->second.mtime == mtime) + path = dir / (it->second.stem + ".bin"); + } + if (path.empty()) { + ComputeBuildOptions key_options; + key_options.key_only = true; + key_options.use_helper = false; + path = host.build(entry, key_options).journal_path; + if (path.empty()) continue; + { + std::lock_guard lock(index_mutex); + index[entry.name] = {fill_bytes[i], mtime, path.stem().string()}; + } + if (++fill_unsaved % 200 == 0) save_index(); + } + if (journal::entry_usable(path, host.state().pso_identity)) continue; + ComputeBuild build; + try { + build = build_entry(entry, "idle-fill"); + } catch (const std::exception& e) { + std::fprintf(stderr, "[compile-server] %s: %s\n", entry.name.c_str(), e.what()); + continue; + } + if (!build.skipped && !build.busy && build.result == VK_SUCCESS && build.journaled) { + ++filled; + std::fprintf(stderr, "[compile-server] idle: %s (%zu B) built and journaled in %.1f s (%zu/%zu)\n", + entry.name.c_str(), fill_bytes[i], double(build.ms) / 1000.0, i + 1, fill_order.size()); + } + } + }; + + std::vector pool; + for (unsigned t = 0; t < threads - idle_threads; ++t) pool.emplace_back(serve); + for (unsigned t = 0; t < idle_threads; ++t) pool.emplace_back(fill); + auto quiet_since = std::chrono::steady_clock::now(); + for (;;) { + auto listing = helper::list_requests(requests); + { + std::lock_guard lock(mutex); + pending = std::move(listing); + if (!pending.empty() || !busy.empty()) quiet_since = std::chrono::steady_clock::now(); + } + wake.notify_all(); + if (options.idle_exit_s && + std::chrono::steady_clock::now() - quiet_since > std::chrono::seconds(options.idle_exit_s)) + break; + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + } + { + std::lock_guard lock(mutex); + stop = true; + } + wake.notify_all(); + for (std::thread& t : pool) t.join(); + save_index(); + std::fprintf(stderr, "[compile-server] nothing asked for %u s: done (%u requests, %u built while idle)\n", + options.idle_exit_s, requests_done.load(), filled.load()); + return 0; +} + bool has_global_realtime_privilege() { const int override_state = g_global_realtime_privilege_override.load(std::memory_order_relaxed); if (override_state >= 0) return override_state != 0; diff --git a/runtime/shims/d3d12_xs_alloc_size.h b/runtime/shims/d3d12_xs_alloc_size.h index 7f1948eccd..751f05a4c6 100644 --- a/runtime/shims/d3d12_xs_alloc_size.h +++ b/runtime/shims/d3d12_xs_alloc_size.h @@ -199,6 +199,40 @@ inline bool console_texture_layout(const D3D12_RESOURCE_DESC& desc, UINT64& size return true; } +// The console's size of a texture the GPU writes through unordered access (no render-target or depth-stencil flag, +// which have their own rules above) whose layout word names its swizzle mode: row-major (1), or 0x100 | mode. That +// is XG's layout of it; 0 when the rule does not apply (any other description, or a mode XG's model lacks). +// `title_layout` is the layout word as the title wrote it: the PC form of the description (pc_resource_desc) has +// lost it. +// +// Why: the title also writes such a texture with the CPU, through its texture lock, at the offsets +// and over the bytes XG's layout gives. Measured: a 32x32x36 R32_UINT 3D texture with layout 0x100 (linear) is +// 0x48000 bytes on the console (256-byte rows, 36 slices of 8 KiB), the PC device sizes it 0x30000, the title placed +// the next resource 0x30000 after it, and its lock clears all 0x48000 bytes - 0x18000 of them in the neighbour. +// Like the render-target rule this only ever makes a size larger than the PC device's own answer, never smaller +// (console_placement). +inline UINT64 console_unordered_access_size(const D3D12_RESOURCE_DESC& desc, UINT title_layout) { + if (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE1D && desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D && + desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE3D) + return 0; + constexpr UINT targets = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; + if (!(desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) || (desc.Flags & targets) || + desc.SampleDesc.Count != 1) + return 0; + if (title_layout != 1 && (title_layout & ~0x1fu) != rt::xg_xs::kSwizzled) return 0; // XG picks the mode + static_assert(sizeof(rt::xg_xs::ResourceDesc) == sizeof(D3D12_RESOURCE_DESC)); + rt::xg_xs::ResourceDesc xg{}; + std::memcpy(&xg, &desc, sizeof(xg)); + xg.alignment = 0; + xg.quality = 0; + xg.flags = 0; + xg.layout = title_layout; + static thread_local rt::xg_xs::Texture texture; // 7 KiB: not on a title thread's stack + texture = {}; + if (!rt::xg_xs::build_texture(xg, texture) || !texture.layout.size) return 0; + return texture.layout.size; +} + // Rounds up to a multiple of `to`, stopping at the last multiple below 2^64 instead of wrapping (as the PC device's // totals do). inline UINT64 align_up_saturating(UINT64 value, UINT64 to) { @@ -214,15 +248,22 @@ inline UINT64 align_up_saturating(UINT64 value, UINT64 to) { // Returns false, and writes nothing, when no description is a console render target that grows, or when the PC // device refuses one: the PC answer then stands. A true answer is never below what the PC device gave for the same // descriptions laid out in that way. +// +// `title_descs` is the title's own array when `descs` is its PC form, for the layout words the PC form drops +// (console_unordered_access_size); null when `descs` is the title's array. template bool console_placement(const D3D12_RESOURCE_DESC* descs, UINT count, PcOne pc_one, - D3D12_RESOURCE_ALLOCATION_INFO& total, D3D12_RESOURCE_ALLOCATION_INFO1* each) { + D3D12_RESOURCE_ALLOCATION_INFO& total, D3D12_RESOURCE_ALLOCATION_INFO1* each, + const D3D12_RESOURCE_DESC* title_descs = nullptr) { if (!descs) return false; + const auto unordered_access = [&](UINT i) { + return console_unordered_access_size(descs[i], static_cast((title_descs ? title_descs : descs)[i].Layout)); + }; bool any_target = false; for (UINT i = 0; i < count && !any_target; ++i) { UINT64 xg_size = 0, xg_alignment = 0; any_target = console_render_target_size(descs[i]) != 0 || console_depth_stencil_size(descs[i]) != 0 || - console_texture_layout(descs[i], xg_size, xg_alignment); + console_texture_layout(descs[i], xg_size, xg_alignment) || unordered_access(i) != 0; } if (!any_target) return false; // Two passes when `each` is wanted: the first decides, the second writes, so a refusal or a list that does not @@ -246,6 +287,11 @@ bool console_placement(const D3D12_RESOURCE_DESC* descs, UINT count, PcOne pc_on size = align_up_saturating(console, one.Alignment); grows = true; } + // A texture the title also locks and writes with the CPU takes its console layout when that is larger. + if (const UINT64 written = unordered_access(i); written > size) { + size = align_up_saturating(written, one.Alignment); + grows = true; + } // A depth-stencil target takes its console size whichever way it differs (console_depth_stencil_size). if (const UINT64 depth = console_depth_stencil_size(descs[i])) { const UINT64 planes = align_up_saturating(depth, one.Alignment); diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 61e795d449..791c169fc4 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -32,6 +32,7 @@ #endif #include "d3d12_xs_placed_depth.h" #include "d3d12_trace.h" +#include "../src/fsdraw_probe.h" // LEONIDA_FSDRAW_PROBE gates the fsdraw lines here #include "../src/native_pso.h" #include "xmem.h" // rt::xmem::copy_page_mappings_fn for queue slot 31 #include "d3d12_xs_alloc_size.h" @@ -1070,9 +1071,9 @@ struct FenceMirror; // Queue slots that take queue_order: the ones that may put work on the queue or change page mappings. Not the debug // markers (SetMarker, BeginEvent, EndEvent: 11-13 in both layouts) and not slot 18, a getter in both layouts (the // older layout's GetDesc, the newer one's GetTimestampFrequency). The title's render thread calls slot 18 every frame -// (t+0x2484180, vtable +0x90, then 1/frequency), and under queue_order it waited for whole submissions on the submit -// thread (15-20 ms each, ~24 a frame): 44 % of its samples in speed-26. Slots 16-17 and 19-20 keep the lock: which of -// them are getters depends on the layout (16-17 are Signal/Wait in the newer one). +// and a queued frequency query can wait for whole submissions. Slots 16-17 and 19-20 keep the lock here: +// which of them are getters depends on the layout (16-17 are Signal/Wait in the newer one). The caller drops the lock +// for a 16/17 call that passes no fence: that is the older layout's frequency/calibration getter, not Signal/Wait. constexpr bool queue_slot_orders_work(unsigned slot) { if (slot < 8 || slot > kQueueExecuteCommandListsX) return false; if (slot >= 11 && slot <= 13) return false; // SetMarker, BeginEvent, EndEvent @@ -1096,7 +1097,7 @@ struct ChildProxy { std::mutex queue_order; // serializes queue work across a host-side page remap // Queue slot 31's fence, made at its first call and signalled with a rising value at each (under queue_order); // kept for the queue's life. It was a new fence a call: a Vulkan timeline semaphore made and destroyed per batch. - Microsoft::WRL::ComPtr map_fence; + ID3D12Fence* map_fence = nullptr; std::uint64_t map_fence_value = 0; std::atomic queue_layout{kQueueLayoutUnknown}; // Allocators only: callback and context recorded by console slot 9 (SetAllocatorCallbackX). @@ -1213,8 +1214,30 @@ void reset_child_stats() { // // The descriptor's code pointer is not called: the measured run goes on without it, and its contract (when it runs, // on which thread, with what) is not known. The first call is logged with its arguments. +// LEONIDA_MIRROR_LAG=1: how late the mirror shows a value the GPU has reached. Each mirror also has the device's +// fence-wait thread call back the moment the timeline reaches the next value (it only notes when); the refresh that +// then writes that value adds now - that moment to the stats. LEONIDA_MIRROR_EXACT=1: that callback writes the +// mirror itself and asks for the next value, so the title sees a completion as soon as our dispatcher does (the +// thread-pool wait stays as the backstop for rewinds). +struct FenceMirror; +struct MirrorLink { // shared with the fence-wait callbacks; destroy_child clears `mirror` before the fence goes + SRWLOCK lock = SRWLOCK_INIT; + FenceMirror* mirror = nullptr; // under lock + std::atomic reached_value{0}; // the value the callback saw, 0: none outstanding + std::atomic reached_at{0}; // QueryPerformanceCounter when it saw it +}; +bool mirror_lag_enabled() { + static const bool on = [] { const char* v = std::getenv("LEONIDA_MIRROR_LAG"); return v && *v == '1'; }(); + return on; +} +bool mirror_exact_enabled() { + static const bool on = [] { const char* v = std::getenv("LEONIDA_MIRROR_EXACT"); return v && *v == '1'; }(); + return on; +} + struct FenceMirror { alignas(8) volatile std::uint64_t completed = 0; // what the title reads through slot 12's pointer + std::shared_ptr link; // LEONIDA_MIRROR_LAG / LEONIDA_MIRROR_EXACT only ID3D12Fence* fence = nullptr; // the real fence; the proxy holds the reference SRWLOCK lock = SRWLOCK_INIT; // orders refreshes HANDLE event = nullptr; // auto-reset; the real fence sets it at the armed value @@ -1223,14 +1246,89 @@ struct FenceMirror { std::atomic arm_failed{false}; }; -std::uint64_t refresh_mirror(FenceMirror* m) { +void note_mirror_lag(std::int64_t ticks, bool exact); + +std::uint64_t refresh_mirror(FenceMirror* m, bool exact = false) { AcquireSRWLockExclusive(&m->lock); const std::uint64_t value = m->fence->GetCompletedValue(); - if (m->completed != value) m->completed = value; + const bool advanced = m->completed != value; + if (advanced) m->completed = value; ReleaseSRWLockExclusive(&m->lock); + if (advanced && m->link && value != ~std::uint64_t{0}) { + std::uint64_t reached = m->link->reached_value.load(std::memory_order_acquire); + if (reached && reached <= value && m->link->reached_value.compare_exchange_strong(reached, 0)) { + LARGE_INTEGER now; + QueryPerformanceCounter(&now); + note_mirror_lag(now.QuadPart - m->link->reached_at.load(std::memory_order_acquire), exact); + } + } return value; } +// Every 10 s with LEONIDA_MIRROR_LAG: from our dispatcher seeing a fence reach a value to the mirror showing it. +void note_mirror_lag(std::int64_t ticks, bool exact) { + static LARGE_INTEGER frequency = [] { LARGE_INTEGER f; QueryPerformanceFrequency(&f); return f; }(); + static std::atomic count{0}, total_us{0}, max_us{0}, over_1ms{0}, exact_count{0}; + static std::atomic last{0}; + const std::uint64_t us = ticks > 0 ? std::uint64_t(ticks) * 1000000 / std::uint64_t(frequency.QuadPart) : 0; + count.fetch_add(1, std::memory_order_relaxed); + exact_count.fetch_add(exact, std::memory_order_relaxed); + total_us.fetch_add(us, std::memory_order_relaxed); + over_1ms.fetch_add(us > 1000, std::memory_order_relaxed); + for (std::uint64_t m = max_us.load(); us > m && !max_us.compare_exchange_weak(m, us);) { + } + const ULONGLONG now = GetTickCount64(); + ULONGLONG was = last.load(std::memory_order_relaxed); + if (!was) { + last.compare_exchange_strong(was, now); + return; + } + if (now - was < 10000 || !last.compare_exchange_strong(was, now)) return; + const std::uint64_t n = count.exchange(0); + std::fprintf(stderr, "[rt] d3d12_xs: fence slot 12 mirror lag (dispatcher saw the value -> mirror shows it): %llu " + "updates in %.0f s (%llu written by the exact callback), avg %.0f us, max %llu us, %llu over 1 ms\n", + static_cast(n), double(now - was) / 1000.0, + static_cast(exact_count.exchange(0)), + n ? double(total_us.exchange(0)) / double(n) : 0.0, + static_cast(max_us.exchange(0)), static_cast(over_1ms.exchange(0))); +} + +// Asks the fence-wait thread for a callback when the fence reaches `value`. Once per call chain: the dispatcher runs a +// callback at once when it is stopping or the device is lost, which would otherwise ask again without end. +thread_local int t_mirror_arming = 0; // this thread is inside arm_mirror_callback + +void arm_mirror_callback(const std::shared_ptr& link, ID3D12Fence* fence, std::uint64_t value) { +#ifndef LEONIDA_VULKAN_DEVICE + (void)link, (void)fence, (void)value; // no fence-wait thread to ask: the thread-pool wait alone +#else + if (t_mirror_arming) return; + ++t_mirror_arming; + rt::d3d12::fence_callback_at(fence, value, [link] { + // Run at once inside the arming call (dispatcher stopping): this thread may hold link->lock already. + if (t_mirror_arming) return; + LARGE_INTEGER now; + QueryPerformanceCounter(&now); + AcquireSRWLockExclusive(&link->lock); + FenceMirror* m = link->mirror; + if (m) { + const std::uint64_t seen = m->fence->GetCompletedValue(); + if (seen != ~std::uint64_t{0}) { + // Only a value the mirror does not show yet: one another path (slot 12, a CPU Signal) already wrote + // would otherwise stay outstanding until the next advance and count that wait as lag. + if (!link->reached_value.load(std::memory_order_acquire) && m->completed < seen) { + link->reached_at.store(now.QuadPart, std::memory_order_release); + link->reached_value.store(seen, std::memory_order_release); + } + if (mirror_exact_enabled()) refresh_mirror(m, true); + arm_mirror_callback(link, m->fence, seen + 1); + } + } + ReleaseSRWLockExclusive(&link->lock); + }); + --t_mirror_arming; +#endif +} + void wait_for_fence_progress(FenceMirror* mirror) { constexpr LONGLONG kRewindPollInterval = -10 * 10'000; // 10 ms in relative 100 ns units ULARGE_INTEGER due{}; @@ -1287,6 +1385,11 @@ FenceMirror* fence_mirror(ChildProxy* self) { if (!m && (m = new (std::nothrow) FenceMirror)) { m->fence = reinterpret_cast(self->real); refresh_mirror(m); + if (mirror_lag_enabled() || mirror_exact_enabled()) { + m->link = std::make_shared(); + m->link->mirror = m; + arm_mirror_callback(m->link, m->fence, m->completed + 1); + } m->event = CreateEventW(nullptr, FALSE, FALSE, nullptr); if (m->event) m->wait = CreateThreadpoolWait(on_fence_progress, m, nullptr); if (m->wait) { @@ -1344,7 +1447,14 @@ void destroy_child(ChildProxy* self) { CloseThreadpoolWait(mirror->wait); g_mirrors_live.fetch_sub(1, std::memory_order_relaxed); } + if (mirror && mirror->link) { // a fence-wait callback still pending (or running) no longer reaches the mirror + AcquireSRWLockExclusive(&mirror->link->lock); + mirror->link->mirror = nullptr; + ReleaseSRWLockExclusive(&mirror->link->lock); + } + ID3D12Fence* const map_fence = self->map_fence; // queue slot 31's; an async mapping in flight holds its own delete self; + if (map_fence) map_fence->Release(); const unsigned long left = real ? real->Release() : 0; if (mirror) { if (mirror->event && left == 0) CloseHandle(mirror->event); @@ -1928,8 +2038,8 @@ bool slot31_async() { struct AsyncMapping { CopyPageMappingsHook map; - Microsoft::WRL::ComPtr fence; - std::uint64_t value; + ID3D12Fence* fence = nullptr; + std::uint64_t value = 0; std::vector batches; std::vector> ranges; std::uintptr_t pool; @@ -1957,6 +2067,7 @@ struct AsyncMapper { } const auto t0 = clock::now(); HRESULT hr = job.fence->SetEventOnCompletion(job.value, nullptr); + job.fence->Release(); // the reference the call took for this job: the queue may be gone by now const auto t1 = clock::now(); bool ok = SUCCEEDED(hr) && job.map(std::uint32_t(job.batches.size()), job.batches.data(), job.pool, job.pages, job.flags); @@ -2081,6 +2192,9 @@ bool copy_page_mappings_default(std::uint32_t count, const xmem::PageBatch* batc // call return before the remap, as on the console; an error is logged and counted then, not returned. // With LEONIDA_LIST_VALUES=0 (no gates), without the value fences or the list-value threads, or when the queue's Wait // for the remap cannot be submitted, the call waits for the earlier work, however long, as it did before. +// With LEONIDA_SLOT31_ASYNC=1 neither: the call signals the queue map fence and returns, and the async worker +// maps once the GPU passes it (slot31_async), in call order. The remap runs xmem's copy_page_mappings +// (g_copy_page_mappings) on every path, deferred or not. HRESULT queue_copy_page_mappings(ChildProxy* self, UINT count, const xmem::PageBatch* batches, std::uintptr_t pool, UINT pages, UINT flags) { auto map = g_copy_page_mappings.load(std::memory_order_acquire); @@ -2088,13 +2202,19 @@ HRESULT queue_copy_page_mappings(ChildProxy* self, UINT count, const xmem::PageB if (!map || !count) return S_OK; if (!batches || flags) return E_INVALIDARG; auto* queue = reinterpret_cast(self->real); - if (list_values::enabled() && !self->values) + using clock = std::chrono::steady_clock; + const auto t0 = clock::now(); + HRESULT hr = S_OK; + bool deferred = false; // the remap is the list-value releaser's now: nothing is mapped here + // LEONIDA_SLOT31_ASYNC=1 asks for the async worker below instead of the bounded wait and the gate. + const bool gated = list_values::enabled() && !slot31_async(); + if (gated && !self->values) self->values = list_values::QueueValues::create(self->device->real, queue); - if (list_values::QueueValues* values = list_values::enabled() ? self->values.get() : nullptr) { + if (list_values::QueueValues* values = gated ? self->values.get() : nullptr) { auto& counters = list_values::counters(); list_values::Pump& pump = list_values::Pump::get(); const std::uint64_t point = ++values->written_value; - HRESULT hr = queue->Signal(values->written, point); + hr = queue->Signal(values->written, point); if (FAILED(hr)) return hr; // The bound is kept with a high-resolution timer: a plain timed wait rounds to the system tick (15.6 ms), // which would defer at once or hold queue_order for two ticks. Neither handle is ever closed: a fence may still @@ -2102,14 +2222,12 @@ HRESULT queue_copy_page_mappings(ChildProxy* self, UINT count, const xmem::PageB static thread_local const HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); static thread_local const HANDLE timer = CreateWaitableTimerExW(nullptr, nullptr, CREATE_WAITABLE_TIMER_HIGH_RESOLUTION, TIMER_ALL_ACCESS); - using Clock = std::chrono::steady_clock; - const auto started = Clock::now(); - const auto deadline = started + std::chrono::milliseconds(kPageMappingWaitMs); + const auto deadline = t0 + std::chrono::milliseconds(kPageMappingWaitMs); bool reached = values->written->GetCompletedValue() >= point; if (!reached && event && SUCCEEDED(values->written->SetEventOnCompletion(point, event))) { for (;;) { reached = values->written->GetCompletedValue() >= point; - const auto now = Clock::now(); + const auto now = clock::now(); if (reached || now >= deadline) break; const auto left = std::chrono::duration_cast(deadline - now).count(); LARGE_INTEGER due{}; @@ -2124,7 +2242,7 @@ HRESULT queue_copy_page_mappings(ChildProxy* self, UINT count, const xmem::PageB } list_values::raise_to(counters.remap_wait_us_max, static_cast(std::chrono::duration_cast( - Clock::now() - started) + clock::now() - t0) .count())); // After stop_list_values (the process is ending) the queue's gates are not signalled any more and its earlier // work may never run: the remap is done now rather than holding queue_order until ExitProcess. @@ -2153,55 +2271,51 @@ HRESULT queue_copy_page_mappings(ChildProxy* self, UINT count, const xmem::PageB error, copy->batches.size(), reinterpret_cast(copy->pool), copy->pages); })) { - const std::uint64_t deferred = + const std::uint64_t so_far = counters.remaps_deferred.fetch_add(1, std::memory_order_relaxed) + 1; - if (deferred == 1 || (deferred & (deferred - 1)) == 0) + if (so_far == 1 || (so_far & (so_far - 1)) == 0) std::fprintf(stderr, "[rt] d3d12_xs: CopyPageMappingsBatchX waits behind held queue work: " "the remap runs when the queue gets there (%llu deferred so far)\n", - static_cast(deferred)); - return S_OK; + static_cast(so_far)); + deferred = true; } - // stop_list_values came in between: nothing opens the gate any more; the remap is done now. + // Otherwise stop_list_values came in between: nothing opens the gate any more; the remap is done now. } else { hr = values->written->SetEventOnCompletion(point, nullptr); // not deferred: wait, as before if (FAILED(hr)) return hr; } } - if (values->written->GetCompletedValue() == UINT64_MAX) return DXGI_ERROR_DEVICE_REMOVED; - list_values::bump(counters.remaps_now); - if (!map(count, batches, pool, pages, flags)) { - const DWORD error = GetLastError(); - return error ? HRESULT_FROM_WIN32(error) : E_FAIL; + if (!deferred) { + if (values->written->GetCompletedValue() == UINT64_MAX) hr = DXGI_ERROR_DEVICE_REMOVED; + else list_values::bump(counters.remaps_now); } - return S_OK; - } - HRESULT hr = S_OK; - if (!self->map_fence) { - hr = self->device->real->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(self->map_fence.GetAddressOf())); - if (FAILED(hr)) return hr; - if (!self->map_fence) return E_FAIL; - } - ID3D12Fence* const fence = self->map_fence.Get(); - const std::uint64_t value = ++self->map_fence_value; - using clock = std::chrono::steady_clock; - const auto t0 = clock::now(); - hr = queue->Signal(fence, value); - if (SUCCEEDED(hr) && slot31_async()) { - AsyncMapping job{map, self->map_fence, value, {}, {}, pool, pages, flags}; - job.batches.assign(batches, batches + count); - job.ranges.resize(count); - for (UINT b = 0; b < count; ++b) { - if (batches[b].count && batches[b].ranges) - job.ranges[b].assign(batches[b].ranges, batches[b].ranges + batches[b].count); - job.batches[b].ranges = job.ranges[b].data(); + } else { + if (!self->map_fence) { + hr = self->device->real->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&self->map_fence)); + if (FAILED(hr)) return hr; + if (!self->map_fence) return E_FAIL; } - async_mapper().push(std::move(job)); - return S_OK; + ID3D12Fence* const fence = self->map_fence; + const std::uint64_t value = ++self->map_fence_value; + hr = queue->Signal(fence, value); + if (SUCCEEDED(hr) && slot31_async()) { + AsyncMapping job{map, fence, value, {}, {}, pool, pages, flags}; + job.batches.assign(batches, batches + count); + job.ranges.resize(count); + for (UINT b = 0; b < count; ++b) { + if (batches[b].count && batches[b].ranges) + job.ranges[b].assign(batches[b].ranges, batches[b].ranges + batches[b].count); + job.batches[b].ranges = job.ranges[b].data(); + } + fence->AddRef(); // the worker releases it: destroy_child releases the queue's own reference + async_mapper().push(std::move(job)); + return S_OK; + } + if (SUCCEEDED(hr)) hr = fence->SetEventOnCompletion(value, nullptr); + if (SUCCEEDED(hr) && fence->GetCompletedValue() == UINT64_MAX) hr = DXGI_ERROR_DEVICE_REMOVED; } - if (SUCCEEDED(hr)) hr = fence->SetEventOnCompletion(value, nullptr); - if (SUCCEEDED(hr) && fence->GetCompletedValue() == UINT64_MAX) hr = DXGI_ERROR_DEVICE_REMOVED; const auto t1 = clock::now(); - if (SUCCEEDED(hr) && !map(count, batches, pool, pages, flags)) { + if (SUCCEEDED(hr) && !deferred && !map(count, batches, pool, pages, flags)) { const DWORD error = GetLastError(); hr = error ? HRESULT_FROM_WIN32(error) : E_FAIL; } @@ -2260,8 +2374,28 @@ std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_ } else { note_child_slot(Slot); std::unique_lock queue_order; - if constexpr (K == ChildKind::queue && queue_slot_orders_work(Slot)) - queue_order = std::unique_lock(self->queue_order); + // Both queue-order fixes: only work that orders on the queue takes queue_order. The markers do not, and + // neither does slot 18 - an ExecuteCommandListsX holds it for its whole replay, which can include building a + // pipeline for minutes, while the title's render thread asks the timestamp frequency every frame (a frozen + // frame loop, measured). 16/17 keep the lock when a fence comes with them (the newer layout's Signal/Wait); + // without one they are the older layout's frequency/calibration getter. 19/20 are the newer layout's + // GetClockCalibration and GetDesc (PC 17/18 shifted by two): getters there, so no lock once that layout is + // known (the title uses it natively); in the older layout they keep it. Queues only: for other proxy kinds + // a1 is not an object pointer and must not be read. + if constexpr (K == ChildKind::queue) { + bool orders = queue_slot_orders_work(Slot); + if (orders && (Slot == 16 || Slot == 17)) + orders = proxy_real_object(reinterpret_cast(a1)) != nullptr; + if (orders && (Slot == 19 || Slot == 20)) { + const unsigned char own = self->queue_layout.load(std::memory_order_relaxed); + const bool newer = own == ChildProxy::kQueueLayoutNewer || + (own == ChildProxy::kQueueLayoutUnknown && + self->device->console_layout.load(std::memory_order_relaxed) == + ChildProxy::kQueueLayoutNewer); + if (newer) orders = false; + } + if (orders) queue_order = std::unique_lock(self->queue_order); + } // CopyPageMappingsBatchX when something can remap: a hook (set_copy_page_mappings_hook) or xmem. Without // either (a proxy compiled without xmem) the slot keeps the answer every unmodelled queue slot past the // public chain gets below: console-only S_OK, or E_NOTIMPL on a queue whose presentation is managed outside. @@ -3442,10 +3576,38 @@ void WINAPI list_clear_depth_stencil_view(ListProxy* self, D3D12_CPU_DESCRIPTOR_ reinterpret_cast(real_vtable[pc])(self->real, translated, flags, depth, stencil, num_rects, rects); } +// OMSetDepthBoundsX (console slot 70 in the newer layout, this package's) -> ID3D12GraphicsCommandList1:: +// OMSetDepthBounds (PC slot 62). Its FLOAT arguments arrive in XMM1 and XMM2, which list_slot's integer thunk would +// lose, so it has a typed thunk too. In the older layout slot 70 is a memory write (console_value_op), which this +// thunk cannot see: LEONIDA_DEPTH_BOUNDS_SLOT70=0 keeps the generic thunk for such a title. +constexpr unsigned kConsoleOMSetDepthBounds = 70, kPcOMSetDepthBounds = 62; +void WINAPI list_om_set_depth_bounds(ListProxy* self, FLOAT min, FLOAT max) { + std::uint32_t lo = 0, hi = 0; + std::memcpy(&lo, &min, sizeof lo); + std::memcpy(&hi, &max, sizeof hi); + const unsigned char layout = self->device->console_layout.load(std::memory_order_relaxed); + note_list_slot(kConsoleOMSetDepthBounds, lo, hi, 0, 0, layout); + if (layout == kConsoleLayoutOlder) { + static std::atomic warned{false}; + if (!warned.exchange(true, std::memory_order_relaxed)) + std::fprintf(stderr, "[rt] d3d12_xs: list slot 70 in the older layout is a memory write the depth-bounds " + "thunk drops; run with LEONIDA_DEPTH_BOUNDS_SLOT70=0\n"); + return; + } + if (kPcOMSetDepthBounds >= self->pc_slot_count) return; + using Fn = void(WINAPI*)(IUnknown*, FLOAT, FLOAT); + auto** const real_vtable = *reinterpret_cast(self->real); + reinterpret_cast(real_vtable[kPcOMSetDepthBounds])(self->real, min, max); +} + template void fill_list_vtable(void** vtable, std::index_sequence) { ((vtable[I] = reinterpret_cast(&list_slot(I)>) ), ...); vtable[kConsoleClearDepthStencilView] = reinterpret_cast(&list_clear_depth_stencil_view); + wchar_t v[4]{}; + const DWORD n = GetEnvironmentVariableW(L"LEONIDA_DEPTH_BOUNDS_SLOT70", v, 4); + if (!(n == 1 && v[0] == L'0')) + vtable[kConsoleOMSetDepthBounds] = reinterpret_cast(&list_om_set_depth_bounds); } void** get_list_vtable() { @@ -4354,8 +4516,7 @@ HRESULT proxy_create_descriptor_heap(DeviceProxy* self, const D3D12_DESCRIPTOR_H hr = create_heap_proxy(heap, self, *riid, out, custom_cpu_start, custom_byte_size, real_cpu_start, custom_cpu_start ? free_fn : nullptr, stride); - // LOCAL DIAGNOSTIC (fsdraw): which CPU start the title gets for this heap - if (leonida::local_diagnostics()) { + if (leonida::fsdraw::enabled()) { // LOCAL DIAGNOSTIC (fsdraw): which CPU start the title gets for this heap static std::atomic logged{0}; if (logged.fetch_add(1) < 32) std::fprintf(stderr, "[rt] fsdraw: heap type %d num %u flags 0x%x console %d: title CPU start 0x%llx (custom " @@ -4469,8 +4630,7 @@ void proxy_copy_descriptors_simple(DeviceProxy* self, UINT num_descriptors, D3D1 const D3D12_CPU_DESCRIPTOR_HANDLE src = translate_cpu_handle(self, src_start); self->real->CopyDescriptorsSimple(num_descriptors, dest, src, type); local_write_through(self, dest_start, num_descriptors); - // LOCAL DIAGNOSTIC (fsdraw): where the title copies its descriptors, and what lands there - if (leonida::local_diagnostics()) { + if (leonida::fsdraw::enabled()) { // LOCAL DIAGNOSTIC (fsdraw): where the title copies its descriptors, and what lands there static std::atomic copies{0}; const std::uint64_t n = ++copies; if (n <= 24 || n % 600 == 0 || n % 600 == 1) { @@ -5740,7 +5900,8 @@ HRESULT proxy_create_state_object(DeviceProxy* self, const D3D12_STATE_OBJECT_DE // D3D12_RESOURCE_FLAGS are normalized on the copy before the PC call. void apply_console_placement(const D3D12_RESOURCE_DESC* descs, UINT count, D3D12_RESOURCE_ALLOCATION_INFO& info, D3D12_RESOURCE_ALLOCATION_INFO1* each, - const std::function& pc_one, unsigned slot); + const std::function& pc_one, unsigned slot, + const D3D12_RESOURCE_DESC* title_descs); std::uint64_t proxy_get_resource_allocation_info2(DeviceProxy* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, std::uint64_t a4, std::uint64_t a5) { @@ -5815,7 +5976,7 @@ std::uint64_t proxy_get_resource_allocation_info2(DeviceProxy* self, std::uint64 if (info1 && !pc.empty()) apply_console_placement(pc.data(), count, *ret, info1, [&](UINT i) { return D3D12_RESOURCE_ALLOCATION_INFO{info1[i].SizeInBytes, info1[i].Alignment}; - }, 108); + }, 108, raw_descs); return reinterpret_cast(ret); } @@ -6103,13 +6264,15 @@ StructReturnCall struct_return_call(std::uint64_t a0, std::uint64_t a1) { // The console size of a list of descriptions (d3d12_xs_alloc_size.h): the PC device's answer with every console render // target laid out at its console size, each at its own alignment. `info` is the PC answer and is replaced only when -// the console layout is larger. `each` is the per-description array of slot 56, or null. +// the console layout is larger. `each` is the per-description array of slot 56, or null. `title_descs` is the +// title's own array when `descs` is its PC form (the layout words the PC form drops), else null. void apply_console_placement(const D3D12_RESOURCE_DESC* descs, UINT count, D3D12_RESOURCE_ALLOCATION_INFO& info, D3D12_RESOURCE_ALLOCATION_INFO1* each, - const std::function& pc_one, unsigned slot) { + const std::function& pc_one, unsigned slot, + const D3D12_RESOURCE_DESC* title_descs) { if (info.SizeInBytes == UINT64_MAX) return; D3D12_RESOURCE_ALLOCATION_INFO console{}; - if (!console_placement(descs, count, pc_one, console, each)) return; + if (!console_placement(descs, count, pc_one, console, each, title_descs)) return; static std::atomic logged{false}; if (!logged.exchange(true, std::memory_order_relaxed)) std::fprintf(stderr, @@ -6117,6 +6280,22 @@ void apply_console_placement(const D3D12_RESOURCE_DESC* descs, UINT count, D3D12 "description(s)\n", slot, static_cast(console.SizeInBytes), static_cast(info.SizeInBytes), static_cast(count)); + // The first few textures the title writes with the CPU through its lock that took their console layout's size + // (console_unordered_access_size). + static std::atomic uav_logged{0}; + for (UINT i = 0; descs && i < count && uav_logged.load(std::memory_order_relaxed) < 8; ++i) { + const D3D12_RESOURCE_DESC& d = descs[i]; + const UINT layout = static_cast((title_descs ? title_descs : descs)[i].Layout); + const UINT64 written = console_unordered_access_size(d, layout); + if (!written || uav_logged.fetch_add(1, std::memory_order_relaxed) >= 8) continue; + std::fprintf(stderr, + "[rt] d3d12_xs: slot %u: unordered-access texture dimension %d %llux%ux%u mips %u format %d " + "layout 0x%x takes its console layout's %llu B (list %llu B, PC %llu B)\n", + slot, static_cast(d.Dimension), static_cast(d.Width), d.Height, + unsigned(d.DepthOrArraySize), unsigned(d.MipLevels), static_cast(d.Format), layout, + static_cast(written), static_cast(console.SizeInBytes), + static_cast(info.SizeInBytes)); + } // A list with a depth-stencil target may come out smaller than the PC answer (console_depth_stencil_size). bool depth = false; for (UINT i = 0; descs && i < count && !depth; ++i) { @@ -6185,7 +6364,7 @@ void* WINAPI proxy_get_resource_allocation_info(std::uint64_t a0, std::uint64_t // own code and tests, which compare with the PC device) gets the PC device's answer unchanged. if (call.console_abi) apply_console_placement(descs, desc_count, info, nullptr, - [&](UINT i) { return real->GetResourceAllocationInfo(mask, 1, &descs[i]); }, 25); + [&](UINT i) { return real->GetResourceAllocationInfo(mask, 1, &descs[i]); }, 25, title_descs); // LEONIDA_LOG_ALLOCINFO=1: every call, with the calling thread (the title sums a batch of these against a fixed // pool and asserts when the batch does not fit). static const bool log_all = [] { @@ -6238,7 +6417,7 @@ void* WINAPI proxy_get_resource_allocation_info1(std::uint64_t a0, std::uint64_t auto& info = *static_cast(call.ret); apply_console_placement(descs, n, info, each, [&](UINT i) { return D3D12_RESOURCE_ALLOCATION_INFO{each[i].SizeInBytes, each[i].Alignment}; - }, 56); + }, 56, nullptr); } return returned; } diff --git a/runtime/shims/d3d12_xs_list_values.h b/runtime/shims/d3d12_xs_list_values.h index 2a30b4b964..e49eefa989 100644 --- a/runtime/shims/d3d12_xs_list_values.h +++ b/runtime/shims/d3d12_xs_list_values.h @@ -602,7 +602,9 @@ class Pump { stall_logged_ = false; return; } - const std::uint64_t ms = GetTickCount64() - since; + // `since` is the start tick with its low bit set (never 0 while inside), so it can be one past now. + const std::uint64_t now = GetTickCount64(); + const std::uint64_t ms = now > since ? now - since : 0; if (ms < kStallMs || stall_logged_) return; stall_logged_ = true; bump(counters().release_stalls); diff --git a/runtime/shims/dxgi_swapchain.h b/runtime/shims/dxgi_swapchain.h index ebe3bc0279..477bc29b2e 100644 --- a/runtime/shims/dxgi_swapchain.h +++ b/runtime/shims/dxgi_swapchain.h @@ -111,7 +111,7 @@ class VulkanSwapchain { public: VulkanSwapchain(PFN_vkGetInstanceProcAddr gipa, VkInstance instance, VkPhysicalDevice physical, PFN_vkGetDeviceProcAddr gdpa, VkDevice device, VkQueue queue, std::uint32_t queue_family, - std::mutex& submit_mutex, DeviceFaultDiagnostics* diagnostics) + SubmitMutex& submit_mutex, DeviceFaultDiagnostics* diagnostics) : instance_(instance), physical_(physical), device_(device), queue_(queue), queue_family_(queue_family), submit_mutex_(submit_mutex), diagnostics_(diagnostics) { loaded_ = fn_.load(gipa, instance, gdpa, device); @@ -220,6 +220,7 @@ class VulkanSwapchain { pi.pSwapchains = &swapchain_; pi.pImageIndices = &image_index; std::lock_guard lock(submit_mutex_); + const SubmitMutex::SubmitTurn turn(submit_mutex_); // a queue operation: the compile gate const VkResult r = observe(fn_.queue_present(queue_, &pi), "vkQueuePresentKHR (DXGI)"); return r == VK_SUCCESS || r == VK_SUBOPTIMAL_KHR; } @@ -400,8 +401,12 @@ class VulkanSwapchain { VkSubmitInfo si{VK_STRUCTURE_TYPE_SUBMIT_INFO}; si.commandBufferCount = 1; si.pCommandBuffers = &blit_cmd_; - if (fn_.queue_submit(queue_, 1, &si, blit_fence_) != VK_SUCCESS || - fn_.wait_for_fences(device_, 1, &blit_fence_, VK_TRUE, UINT64_MAX) != VK_SUCCESS) { + bool submitted = false; + { + const SubmitMutex::SubmitTurn turn(submit_mutex_); // a queue operation: the compile gate + submitted = fn_.queue_submit(queue_, 1, &si, blit_fence_) == VK_SUCCESS; + } + if (!submitted || fn_.wait_for_fences(device_, 1, &blit_fence_, VK_TRUE, UINT64_MAX) != VK_SUCCESS) { destroy_offscreen(); return false; } @@ -486,7 +491,12 @@ class VulkanSwapchain { } bool submit_blit_and_wait(const VkSubmitInfo& submit) { - return observe(fn_.queue_submit(queue_, 1, &submit, blit_fence_), "vkQueueSubmit (DXGI)") == VK_SUCCESS && + VkResult submitted; + { + const SubmitMutex::SubmitTurn turn(submit_mutex_); // the compile gate (VulkanContext::queue_submit) + submitted = fn_.queue_submit(queue_, 1, &submit, blit_fence_); + } + return observe(submitted, "vkQueueSubmit (DXGI)") == VK_SUCCESS && observe(fn_.wait_for_fences(device_, 1, &blit_fence_, VK_TRUE, UINT64_MAX), "vkWaitForFences (DXGI blit)") == VK_SUCCESS; } @@ -595,7 +605,7 @@ class VulkanSwapchain { VkDevice device_ = VK_NULL_HANDLE; VkQueue queue_ = VK_NULL_HANDLE; std::uint32_t queue_family_ = 0; - std::mutex& submit_mutex_; + SubmitMutex& submit_mutex_; DeviceFaultDiagnostics* diagnostics_; VkSurfaceKHR surface_ = VK_NULL_HANDLE; VkSwapchainKHR swapchain_ = VK_NULL_HANDLE; diff --git a/runtime/shims/gameinput.cpp b/runtime/shims/gameinput.cpp index 47e9aa9412..fa5889d6a8 100644 --- a/runtime/shims/gameinput.cpp +++ b/runtime/shims/gameinput.cpp @@ -45,6 +45,7 @@ #include #include #include +#include #include #include #include @@ -53,6 +54,7 @@ #include "gameinput.h" #include "gameinput_abi.h" #include "gameinput_script.h" +#include "keyboard_pad_connection.h" #include "shims.h" using namespace gi; @@ -1004,6 +1006,9 @@ leonida::InputFamily family_of(SDL_JoystickID jid, SDL_Gamepad* p) { // in bits 0-7, forced in bit 8, the generation from bit 16. leonida::ActiveInputTracker g_tracker; std::atomic g_active{0}; +// GetCurrentReading calls so far, any device: a scripted press is held until the title has read the pads a few +// times since it began (update_keyboard_pad). +std::atomic g_reading_calls{0}; void publish_active() { g_active.store(static_cast(g_tracker.active()) | (g_tracker.forced() ? 1ull << 8 : 0) | @@ -1766,10 +1771,7 @@ std::atomic g_key_down{async_key_down}; std::atomic g_has_focus{foreground_is_ours}; std::atomic g_cursor_pos{system_cursor_pos}; -struct KeyboardPad { - SDL_JoystickID id = 0; - SDL_Joystick* js = nullptr; - bool failed = false; // attaching failed once; not retried every 2 ms +struct KeyboardPad : rt::gameinput::detail::KeyboardPadConnection { int right_x = 0, right_y = 0; // the mouse's right stick, SDL axis units (+Y down) int cursor_x = 0, cursor_y = 0; // the cursor at the last poll bool have_cursor = false; // cursor_x/y are valid; false after focus loss, so the first poll moves nothing @@ -1778,13 +1780,6 @@ KeyboardPad g_keyboard; bool is_keyboard_pad(SDL_JoystickID jid) { return jid != 0 && jid == g_keyboard.id; } -void detach_keyboard_pad() { - if (g_keyboard.js) SDL_CloseJoystick(g_keyboard.js); - if (g_keyboard.id) SDL_DetachVirtualJoystick(g_keyboard.id); - if (g_keyboard.id) std::fprintf(stderr, "[rt] gameinput: keyboard pad removed\n"); - g_keyboard = {}; -} - // Keeps the cursor inside the game window while it has focus, so a click cannot land on another window, and releases // it on focus loss. Only with raw input (a clipped plain cursor would stop the stick at the window edge) and only for // a real foreground window of this process: not KeyboardPadMode::Always over a terminal, nor a test's fake focus. @@ -1812,29 +1807,34 @@ void clip_cursor(bool want) { } } -bool attach_keyboard_pad() { - SDL_VirtualJoystickDesc d; - SDL_INIT_INTERFACE(&d); - d.type = SDL_JOYSTICK_TYPE_GAMEPAD; - d.naxes = SDL_GAMEPAD_AXIS_COUNT; - d.nbuttons = SDL_GAMEPAD_BUTTON_COUNT; - d.button_mask = (1u << SDL_GAMEPAD_BUTTON_COUNT) - 1; - d.axis_mask = (1u << SDL_GAMEPAD_AXIS_COUNT) - 1; - d.name = "Keyboard pad (Leonida)"; - g_keyboard.id = SDL_AttachVirtualJoystick(&d); - g_keyboard.js = g_keyboard.id ? SDL_OpenJoystick(g_keyboard.id) : nullptr; - if (!g_keyboard.js) { +struct KeyboardPadBackend { + static uint64_t now() { return now_us(); } + static SDL_JoystickID attach() { + SDL_VirtualJoystickDesc d; + SDL_INIT_INTERFACE(&d); + d.type = SDL_JOYSTICK_TYPE_GAMEPAD; + d.naxes = SDL_GAMEPAD_AXIS_COUNT; + d.nbuttons = SDL_GAMEPAD_BUTTON_COUNT; + d.button_mask = (1u << SDL_GAMEPAD_BUTTON_COUNT) - 1; + d.axis_mask = (1u << SDL_GAMEPAD_AXIS_COUNT) - 1; + d.name = "Keyboard pad (Leonida)"; + return SDL_AttachVirtualJoystick(&d); + } + static SDL_Joystick* open(SDL_JoystickID id) { return SDL_OpenJoystick(id); } + static void close(SDL_Joystick* js) { SDL_CloseJoystick(js); } + static bool detach(SDL_JoystickID id) { return SDL_DetachVirtualJoystick(id); } + static bool is_virtual(SDL_JoystickID id) { return SDL_IsJoystickVirtual(id); } + static void removed() { std::fprintf(stderr, "[rt] gameinput: keyboard pad removed\n"); } + static void failed() { std::fprintf(stderr, "[rt] gameinput: cannot attach the keyboard pad: %s\n", SDL_GetError()); - detach_keyboard_pad(); - g_keyboard.failed = true; - return false; } - std::fprintf(stderr, "[rt] gameinput: keyboard pad attached (arrows d-pad, Enter A, Backspace B, X X, Y Y, " - "Q/E shoulders, Esc Menu, Tab View, WASD left stick, mouse right stick, right/left " - "button LT/RT)\n"); - start_raw_mouse(); - return true; -} + static void attached() { + std::fprintf(stderr, "[rt] gameinput: keyboard pad attached (arrows d-pad, Enter A, Backspace B, X X, Y Y, " + "Q/E shoulders, Esc Menu, Tab View, WASD left stick, mouse right stick, right/left " + "button LT/RT)\n"); + start_raw_mouse(); + } +}; // Before SDL_UpdateGamepads, so the buttons set here are in this poll's reading. void update_keyboard_pad() { @@ -1845,13 +1845,14 @@ void update_keyboard_pad() { mode = g().config.keyboard_pad; sens = g().config.mouse_sensitivity; } - if (mode == rt::gameinput::KeyboardPadMode::Off) { + KeyboardPadBackend backend; + const bool enabled = mode != rt::gameinput::KeyboardPadMode::Off; + if (!enabled) { clip_cursor(false); - if (g_keyboard.id) detach_keyboard_pad(); - g_keyboard.failed = false; - return; + g_keyboard.right_x = g_keyboard.right_y = 0; + g_keyboard.have_cursor = false; } - if (!g_keyboard.js && (g_keyboard.failed || !attach_keyboard_pad())) return; + if (!g_keyboard.update(enabled, backend)) return; bool down[SDL_GAMEPAD_BUTTON_COUNT] = {}; int lx = 0, ly = 0; @@ -1901,7 +1902,26 @@ void update_keyboard_pad() { if (!scripted.empty()) { static const ULONGLONG origin = GetTickCount64(); const double now = (GetTickCount64() - origin) / 1000.0; - const script::Held held = script::held_at(scripted, now); + script::Held held{}; + static constexpr uint64_t kReads = 6; + static constexpr double kMaxHold = 5.0; + static std::vector began(scripted.presses.size(), 0); + static std::vector started(scripted.presses.size(), 0); + const uint64_t calls = g_reading_calls.load(std::memory_order_relaxed); + for (std::size_t i = 0; i < scripted.presses.size(); ++i) { + const auto& press = scripted.presses[i]; + bool active = false; + if (now >= press.at && now < press.at + kMaxHold) { + if (!started[i]) { + started[i] = 1; + began[i] = calls; + } + active = now < press.at + 0.3 || calls - began[i] < kReads; + } + if (!active) continue; + if (press.stick) held.stick = press.stick; + else held.buttons |= press.button; + } if (held.stick) right_y = held.stick > 0 ? -kStickFull : kStickFull; // SDL's +Y is down for (const script::Button& b : script::kButtons) { if (!(scripted.named & b.bit)) continue; @@ -1959,6 +1979,10 @@ void poll_once() { SDL_JoystickID* ids = SDL_GetGamepads(&count); std::vector present(ids, ids + (ids ? count : 0)); SDL_free(ids); + // An unopened virtual device may still be waiting for SDL to finish detaching it. + // Do not advertise it to the title until it has a working keyboard handle. + if (g_keyboard.id && !g_keyboard.js) + present.erase(std::remove(present.begin(), present.end(), g_keyboard.id), present.end()); std::vector connected; { @@ -2411,7 +2435,75 @@ class GameInput final : public IGameInput { uint64_t STDMETHODCALLTYPE GetCurrentTimestamp() override { return now_us(); } + // LEONIDA_INPUT_STATS=1 (diagnostic): every 10 s, how the title asked for readings (by method and device + // argument) and what it got (by the reading's device, and whether a gamepad button was down in it). + static void note_reading(int method, IGameInputDevice* asked, HRESULT hr, IGameInputReading* got) { + static const bool on = env("LEONIDA_INPUT_STATS") == "1"; + if (!on) return; + struct Stats { + std::mutex mu; + uint64_t calls[3][3] = {}; // method x (null, aggregate, a device) + uint64_t found[3] = {}, pressed[3] = {}; + std::map> by_device; // name -> (readings, with buttons) + uint64_t since = 0; + }; + static Stats st; + std::string name; + bool buttons = false; + if (SUCCEEDED(hr) && got) { + IGameInputDevice* d = nullptr; + got->GetDevice(&d); + if (d) { + name = as_device(d)->name; + d->Release(); + } + GameInputGamepadState g{}; + if (got->GetGamepadState(&g)) buttons = g.buttons != 0; + } + const int arg = !asked ? 0 : as_device(asked)->info.deviceFamily == GameInputFamilyAggregate ? 1 : 2; + std::lock_guard lock(st.mu); + ++st.calls[method][arg]; + if (SUCCEEDED(hr) && got) { + ++st.found[method]; + st.pressed[method] += buttons; + auto& e = st.by_device[name]; + ++e.first; + e.second += buttons; + } + const uint64_t now = now_us(); + if (!st.since) st.since = now; + if (now - st.since < 10'000'000) return; + static const char* methods[] = {"GetCurrentReading", "GetNextReading", "GetPreviousReading"}; + std::string line; + for (int m = 0; m < 3; ++m) { + char t[200]; + std::snprintf(t, sizeof(t), " %s %llu/%llu/%llu found %llu pressed %llu;", methods[m], + (unsigned long long)st.calls[m][0], (unsigned long long)st.calls[m][1], + (unsigned long long)st.calls[m][2], (unsigned long long)st.found[m], + (unsigned long long)st.pressed[m]); + line += t; + } + for (const auto& [n, c] : st.by_device) { + char t[160]; + std::snprintf(t, sizeof(t), " [%s: %llu readings, %llu with buttons]", n.c_str(), (unsigned long long)c.first, + (unsigned long long)c.second); + line += t; + } + std::fprintf(stderr, "[rt] gameinput stats (calls null/aggregate/device): %s\n", line.c_str()); + std::memset(st.calls, 0, sizeof(st.calls)); + std::memset(st.found, 0, sizeof(st.found)); + std::memset(st.pressed, 0, sizeof(st.pressed)); + st.by_device.clear(); + st.since = now; + } + HRESULT STDMETHODCALLTYPE GetCurrentReading(uint32_t kind, IGameInputDevice* device, IGameInputReading** out) override { + g_reading_calls.fetch_add(1, std::memory_order_relaxed); + const HRESULT hr = current_reading(kind, device, out); + note_reading(0, device, hr, out ? *out : nullptr); + return hr; + } + HRESULT current_reading(uint32_t kind, IGameInputDevice* device, IGameInputReading** out) { if (!out) return E_POINTER; *out = nullptr; if (kind != GameInputKindUnknown && !(kind & kSupportedKinds)) return GAMEINPUT_E_READING_NOT_FOUND; @@ -2445,11 +2537,15 @@ class GameInput final : public IGameInput { HRESULT STDMETHODCALLTYPE GetNextReading(IGameInputReading* ref, uint32_t kind, IGameInputDevice* device, IGameInputReading** out) override { - return find_reading(ref, kind, device, out, true); + const HRESULT hr = find_reading(ref, kind, device, out, true); + note_reading(1, device, hr, out ? *out : nullptr); + return hr; } HRESULT STDMETHODCALLTYPE GetPreviousReading(IGameInputReading* ref, uint32_t kind, IGameInputDevice* device, IGameInputReading** out) override { - return find_reading(ref, kind, device, out, false); + const HRESULT hr = find_reading(ref, kind, device, out, false); + note_reading(2, device, hr, out ? *out : nullptr); + return hr; } // E_NOTIMPL is GameInput v0's own answer: Microsoft's reference page says the method "was never implemented in // v0" and returns E_NOTIMPL, and v1 removed it. A history lookup here would give a title what no GameInput does. diff --git a/runtime/shims/keyboard_pad_connection.h b/runtime/shims/keyboard_pad_connection.h new file mode 100644 index 0000000000..fff655f2a4 --- /dev/null +++ b/runtime/shims/keyboard_pad_connection.h @@ -0,0 +1,67 @@ +#pragma once + +#include + +namespace rt::gameinput::detail { + +// Owned by the poll lock. Keep the virtual device ID until SDL confirms detachment; +// a successful attach followed by a failed open still leaves a device to release. +template +struct KeyboardPadConnection { + Id id{}; + Handle js{}; + + template + bool update(bool enabled, Backend& b) { + if (enabled != enabled_) { + enabled_ = enabled; + waiting_ = warned_ = false; // changing mode never waits for the previous mode's retry + } + if (enabled && js) return true; + if (!enabled && !id) return false; + if (waiting_ && b.now() - failed_at_ < 1'000'000) return false; + + if (js) { // switching off a connected pad + b.close(js); + js = {}; + } + if (id) { // switching off, or cleanup was incomplete on the previous poll + if (!release(b)) return wait(b); + if (announced_) b.removed(); + announced_ = false; + } + if (!enabled) return false; + + id = b.attach(); + if (id) js = b.open(id); + if (!js) { + if (!warned_) b.failed(); // preserve the attach/open error before cleanup + warned_ = true; + if (id) release(b); + return wait(b); + } + waiting_ = warned_ = false; + announced_ = true; + b.attached(); + return true; + } + +private: + template + bool release(Backend& b) { + // An already-removed ID also fails SDL_DetachVirtualJoystick. Retain only a still-live virtual device. + if (!b.detach(id) && b.is_virtual(id)) return false; + id = {}; + return true; + } + template + bool wait(Backend& b) { + failed_at_ = b.now(); // measure from completion, not from the start of a slow attempt + waiting_ = true; + return false; + } + std::uint64_t failed_at_ = 0; + bool enabled_ = false, waiting_ = false, warned_ = false, announced_ = false; +}; + +} // namespace rt::gameinput::detail diff --git a/runtime/shims/xg_xs.cpp b/runtime/shims/xg_xs.cpp index 7a9066d5d8..891ba0ec92 100644 --- a/runtime/shims/xg_xs.cpp +++ b/runtime/shims/xg_xs.cpp @@ -747,6 +747,16 @@ HRESULT __stdcall XGCreateTextureComputer(const void* desc, void** out) { } } trace_desc(calls, "create", _ReturnAddress(), desc ? &d : nullptr, out, 0, hr, t.mode, t.layout.size); + // A refused computer is not harmless: the title's texture lock reads the layout it would have written + // without checking, so say which descriptions are refused (at most 32 lines). + static std::atomic refused{0}; + if (desc && FAILED(hr) && refused.fetch_add(1, std::memory_order_relaxed) < 32) + std::fprintf(stderr, + "[rt] xg_xs: XGCreateTextureComputer refuses dim=%u %llux%ux%u mips=%u fmt=%u samples=%u " + "layout=%#x flags=%#x (hr 0x%08x), caller %s\n", + d.dimension, static_cast(d.width), d.height, unsigned(d.depth_or_array), + unsigned(d.mips), d.format, d.samples, d.layout, d.flags, uint32_t(hr), + rt::shims::module_offset(reinterpret_cast(_ReturnAddress())).c_str()); // LOCAL DIAGNOSTIC: LEONIDA_XG_TRACE_FORMAT= logs the first 256 computers of that format whatever // LEONIDA_XG_TRACE's cap, with the layout the title asked for (which tiling its CPU writes use). static const uint32_t only = [] { diff --git a/runtime/shims/xg_xs_layout.h b/runtime/shims/xg_xs_layout.h index 36d6c0db30..939c9e892d 100644 --- a/runtime/shims/xg_xs_layout.h +++ b/runtime/shims/xg_xs_layout.h @@ -114,6 +114,14 @@ inline uint32_t align_up(uint32_t value, uint32_t alignment) { // contracts by floor division, while physical pitch/height use ShiftCeil on // the base extent in elements. A slice stores the tail block, then its // unpacked mips from smallest to largest. +// +// A render-target or depth-stencil flag only matters when the layout word +// leaves the mode to XG (select_mode then picks a Z/R mode this model lacks); +// with an explicit mode the layout is that mode's, as on the console. +// +// A linear 3D texture is thin (addrlib's HwlComputeSurfaceInfoLinear): every +// depth slice holds the whole mip chain, rows aligned to 256 bytes, so the +// slices are plane.slice_bytes apart and a mip's size spans all its slices. inline bool build_texture(const ResourceDesc& desc, Texture& texture) { // Exposure readback uses the explicit linear Series layout, including the // console flag set by its render-target descriptor builder. @@ -145,8 +153,12 @@ inline bool build_texture(const ResourceDesc& desc, Texture& texture) { default: return false; } const bool volume = desc.dimension == kTexture3D; - if (volume && mode != k4kbS) return false; - if (volume && (mips != 1 || format.side != 1)) { + if (volume && mode != k4kbS && mode != kLinear) return false; + // Linear 3D is measured with one mip only (256-byte rows, slice after slice). Whether a linear 3D chain is laid + // out slice-major or mip-major is not measured, and the two put mips 1+ at different offsets: refused, as before. + if (volume && mode == kLinear && mips > 1) return false; + const bool thick = volume && mode != kLinear; // GFX10 3D S modes: blocks span tile_depth slices + if (thick && (mips != 1 || format.side != 1)) { static const bool enabled = [] { const char* value = std::getenv("LEONIDA_VOLUME_MIPS"); return !value || std::strcmp(value, "0") != 0; @@ -169,7 +181,7 @@ inline bool build_texture(const ResourceDesc& desc, Texture& texture) { texture.tile_width = tw; texture.tile_height = th; texture.array = volume ? 1u : desc.depth_or_array; - if (volume) { + if (thick) { // Dimensions in elements (4x4 blocks for BC formats). constexpr uint32_t blocks[5][3] = {{16, 16, 16}, {8, 16, 16}, {8, 16, 8}, {8, 8, 8}, {4, 8, 8}}; texture.tile_width = tw = blocks[element_bits][0]; @@ -189,11 +201,11 @@ inline bool build_texture(const ResourceDesc& desc, Texture& texture) { plane.standard_mips = mips; // AMD addrlib Gfx10Lib::ComputeSurfaceInfoMacroTiled and Lib::GetMipTailDim. // A 4 KiB thick block has five tail levels and halves height. BC extents are in blocks. - const unsigned max_tail = volume ? 5u : tile_bits - 4; - uint32_t tail_w = volume ? tw : tw / 2, tail_h = volume ? th / 2 : th; + const unsigned max_tail = thick ? 5u : tile_bits - 4; + uint32_t tail_w = thick ? tw : tw / 2, tail_h = thick ? th / 2 : th; constexpr uint32_t micro3d[5][3] = {{8,4,8}, {4,4,8}, {4,4,4}, {4,2,4}, {2,2,4}}; - const uint32_t micro_w = volume ? micro3d[element_bits][0] : 1u << ((8 - element_bits + 1) / 2); - const uint32_t micro_h = volume ? micro3d[element_bits][1] : 256 / (format.bytes * micro_w); + const uint32_t micro_w = thick ? micro3d[element_bits][0] : 1u << ((8 - element_bits + 1) / 2); + const uint32_t micro_h = thick ? micro3d[element_bits][1] : 256 / (format.bytes * micro_w); uint32_t tail_depth = 0; uint64_t chain_bytes = 0; @@ -222,7 +234,7 @@ inline bool build_texture(const ResourceDesc& desc, Texture& texture) { if (mip.in_tail) { const unsigned index = max_tail - 1 - (i - plane.standard_mips); mip.offset = index > 6 ? 16u << index : index * 256u; - if (volume) { + if (thick) { texture.volume_mips[i].tail_x = ((index >> 1) & 1u) * micro_w; texture.volume_mips[i].tail_y = ((index & 1u) | ((index >> 1) & 2u)) * micro_h; mip.offset *= align_up(tail_depth, micro3d[element_bits][2]) / micro3d[element_bits][2]; @@ -244,7 +256,7 @@ inline bool build_texture(const ResourceDesc& desc, Texture& texture) { mip.slice_bytes = uint64_t(mip.pitch_bytes) * mip.padded_height; mip.size = mip.slice_bytes * (volume ? mip.padded_depth : 1u); } - if (volume) { + if (thick) { uint64_t macro = chain_bytes; chain_bytes *= align_up(tail_depth, texture.tile_depth) / texture.tile_depth; for (unsigned i = plane.standard_mips; i > 0; --i) { @@ -262,10 +274,10 @@ inline bool build_texture(const ResourceDesc& desc, Texture& texture) { for (unsigned i = plane.standard_mips; i > 0; --i) { auto& mip = plane.mips[i - 1]; mip.offset = chain_bytes; - chain_bytes += mip.size; + chain_bytes += mip.slice_bytes; // one slice's share: a linear 3D mip's size spans every depth slice } plane.slice_bytes = chain_bytes; - plane.size = layout.size = chain_bytes * texture.array; + plane.size = layout.size = chain_bytes * (volume ? desc.depth_or_array : texture.array); return true; } diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp index 40bc28f2a9..0184642e3d 100644 --- a/runtime/shims/xmem.cpp +++ b/runtime/shims/xmem.cpp @@ -78,7 +78,7 @@ void note_attributes(const char* api, uint64_t attributes, size_t size, const vo rt::startup_trace::event("xmem_attributes", fields); } -// LEONIDA_TITLE_HEAP=1: the title's XMemAlloc blocks come from a heap of their own instead of the CRT heap. Slot-133 +// 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 @@ -89,8 +89,9 @@ struct TitleHeapHeader { }; HANDLE title_heap() { static const HANDLE heap = [] { + // Set LEONIDA_TITLE_HEAP=0 to use the CRT heap. const char* v = std::getenv("LEONIDA_TITLE_HEAP"); - if (!v || std::strcmp(v, "1") != 0) return HANDLE(nullptr); + if (v && std::strcmp(v, "0") == 0) return HANDLE(nullptr); const HANDLE h = HeapCreate(0, 0, 0); std::fprintf(stderr, "[rt] xmem: XMemAlloc blocks come from a heap of their own (%p)\n", h); return h; @@ -391,7 +392,7 @@ uintptr_t stream_cpu, stream_gpu, stream_size; bool mirror_stream; leonida::host_heap::map stream_offsets; std::mutex g_phys_mutex; -std::map g_windows; // base -> window +leonida::host_heap::map g_windows; // base -> window (host_heap: see g_pages) // The same table for the fault handler, which may not wait for g_phys_mutex: a holder of that mutex allocates // (g_mapped, g_windows) and the faulting title thread can hold the process heap's lock (see g_fault_lock). Host heap, // read and written under g_fault_lock. @@ -400,7 +401,10 @@ leonida::host_heap::map g_fault_windows; // until the title releases them (TitleVirtualFree). With the windows these are the title's reserved memory: the only // place the fault handler commits a mapped section page it has no view of (commit_title_section_page). leonida::host_heap::map g_title_placeholders; -std::unordered_map g_pages; // page number -> backing +// Keep page table nodes on the runtime heap alongside the window table. +std::unordered_map, std::equal_to, + leonida::host_heap::Allocator>> + g_pages; // page number -> backing std::vector g_free_slots; uint64_t g_next_slot = 1; // A mapped run: `count` pages of one section at consecutive offsets, mapped as one view at its base. One view per run @@ -797,10 +801,15 @@ void* WINAPI XMemVirtualAlloc(void* address, SIZE_T size, DWORD allocation_type, const DWORD host_type = allocation_type & kXmemHostAllocationTypeMask; if (result && host_type && !(host_type & MEM_COMMIT)) { const bool gpu_only = (protect & kPageGraphicsMask) && host_protect(protect) == PAGE_NOACCESS; - if (leonida::title_gpu_views::note_reservation(reinterpret_cast(result), size, gpu_only)) - std::fprintf(stderr, "[rt] xmem: GPU-only view %p (%llu MiB, protect 0x%lx) reads at the CPU view %p\n", + const auto base = reinterpret_cast(result); + const bool stream_queue_view = allocation_type == 0x20402000 && gpu_only && + reinterpret_cast(_ReturnAddress()) - kTitleImage == 0x1e1d03e && + rt::xmem::slot31_runs() && rt::xmem::queue_page_mappings_enabled(); + if (leonida::title_gpu_views::note_reservation(base, size, gpu_only, stream_queue_view)) + std::fprintf(stderr, "[rt] xmem: GPU-only view %p (%llu MiB, protect 0x%lx) paired with CPU view %p (%s)\n", result, static_cast(size >> 20), static_cast(protect), - reinterpret_cast(leonida::title_gpu_views::to_cpu(reinterpret_cast(result)))); + reinterpret_cast(leonida::title_gpu_views::other_view(base)), + stream_queue_view ? "separate queue mappings" : "CPU backing"); else if (gpu_only && size >= (64u << 20)) std::fprintf(stderr, "[rt] xmem: GPU-only reservation %p (%llu MiB, protect 0x%lx) has no CPU view\n", result, static_cast(size >> 20), static_cast(protect)); diff --git a/runtime/shims/xmem.h b/runtime/shims/xmem.h index 9a7df46c5b..96fb89e7ea 100644 --- a/runtime/shims/xmem.h +++ b/runtime/shims/xmem.h @@ -24,6 +24,7 @@ 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(); +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/buffer_va_index.h b/runtime/src/buffer_va_index.h index 6fbba5b05c..3ab8edf82c 100644 --- a/runtime/src/buffer_va_index.h +++ b/runtime/src/buffer_va_index.h @@ -91,6 +91,11 @@ class BufferVaIndex { std::size_t size() const { return ranges_.size(); } std::uint64_t longest() const { return longest_; } + // f(first VA, bytes) for every range, in VA order. + template + void for_each(F&& f) const { + for (const auto& [key, bytes] : ranges_) f(key.first, bytes); + } private: static constexpr Id max_id() { return ~Id(0); } diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h index b68b413fc9..d7d7396408 100644 --- a/runtime/src/command_list.h +++ b/runtime/src/command_list.h @@ -462,6 +462,7 @@ struct Draw { std::uint32_t first_instance = 0; bool mesh = false; std::shared_ptr viewports; // non-null when >1 viewport or >1 scissor was bound + std::array depth_bounds{0, 1}; // OMSetDepthBounds (min, max); used by depth-bounds pipelines only }; // Only indirect draws allocate this extra payload. Copies of the IR share both its diff --git a/runtime/src/console_heap_fix.comp b/runtime/src/console_heap_fix.comp new file mode 100644 index 0000000000..85b5d1787c --- /dev/null +++ b/runtime/src/console_heap_fix.comp @@ -0,0 +1,292 @@ +// Console descriptor heap translation on the GPU (LEONIDA_CONSOLE_HEAP_GPU=1, shims/d3d12_console_heap_gpu.h). +// The title writes 32-byte RDNA2 records into its console descriptor heap; shaders read a copy in which every buffer +// V# whose base is the title's own memory names the GPU copy of that memory instead (DeviceState::fix_vsharp). This +// pass makes that copy: for each listed slot it reads the title's bytes (a host mirror of the heap's pages), rewrites +// the V# halves, and writes the record where shaders read it. T#s and other words are copied as they are (T#s are +// found by their exact words in the bindless table; the CPU registers them). +// console_heap_fix_spv.h is this file compiled with `glslc --target-env=vulkan1.2 -O -mfmt=c` (see the header); +// keep them together. runtime/test/vk_console_heap_gpu_test.cpp checks it against the CPU reference +// (console_heap_gpu_reference in d3d12_console_heap_gpu.h). +// +// A V# half (dwords 0-3, and 4-7 when dword 3 says the slot is a buffer pair) is translated like fix_vsharp: +// - skipped when its TYPE bits (dword 3, bits 30-31) are set or it has no records (dword 2 zero); +// - base 0: written with no records; +// - base inside a range of the range table (the alias table: slot-133 buffers, title windows, pool extents), sorted +// by title VA: rebased to the range's shader VA when the range was checked backed on the CPU and holds the V#'s +// whole span; written with no records when it does not hold it (vsharp_address answers 0 there too). An +// unchecked range falls through; +// - the base as a shader VA (sign-extended from bit 47 with FLAG_SIGNED) with its whole span inside a span of the +// backed table (live allocations, geometry blocks): left as it is, as vsharp_address's backed() leaves it; +// - otherwise its exact 16 bytes are looked up in the key table (an open-addressed table the CPU fills with what +// vsharp_address answered for those words: a shader VA, or "no backing"); found: rebased, or written with no +// records; +// - not found: written with no records; when the base is in the ask table (the title's memory and GPU windows, with +// FLAG_ASK), or there is no ask table, the half is recorded in the miss list, which the CPU reads once the +// submission is done, resolves (making the copy if it can) and enters in the key table. +// "No records" is what fix_vsharp writes: dwords 0, 1 and 2 zero, so loads return 0 and stores are dropped, and no +// shader adds heap_base to a raw title address. +// +// MODE_UPDATE writes the key table entries the CPU changed (one thread each) before MODE_TRANSLATE runs, so the +// table only ever changes in GPU order, between passes. +// +// Addresses are 64-bit buffer device addresses passed as uvec2 (GL_EXT_buffer_reference_uvec2): only the +// bufferDeviceAddress feature is needed, no shaderInt64. +#version 460 +#extension GL_EXT_buffer_reference : require +#extension GL_EXT_buffer_reference_uvec2 : require + +layout(local_size_x = 64) in; + +layout(buffer_reference, std430, buffer_reference_align = 16) buffer Slots { + uvec4 v[]; +}; +layout(buffer_reference, std430, buffer_reference_align = 4) buffer Words { + uint w[]; +}; + +const uint MODE_TRANSLATE = 0u; +const uint MODE_UPDATE = 1u; + +const uint RANGE_WORDS = 8u; // title_va (2), end (2), shader_va (2), flags, pad +const uint RANGE_CHECKED = 1u; // the CPU found the whole range backed +const uint KEY_WORDS = 8u; // key (4), to.x, to.y | flags << 16, pad (2) +const uint KEY_USED = 1u; +const uint KEY_NONE = 2u; // vsharp_address answered 0: no records +const uint KEY_PROBES = 16u; +const uint UPDATE_WORDS = 12u; // index, pad (3), entry (8) +const uint MISS_HEADER = 4u; // count, capacity, overflowed, pad +const uint SPAN_WORDS = 4u; // start (2), end (2) +const uint FLAG_SIGNED = 1u; +const uint FLAG_ASK = 2u; +const uint FLAG_RANGE = 4u; // MODE_TRANSLATE over slots pc.work.x + i, not a list: a rescan, V# pairs only +const uint FLAG_FILTER = 8u; // with FLAG_RANGE: only slots whose metadata meets a change span (below) + +layout(push_constant) uniform Params { + uvec2 input_slots; // the title's bytes of the heap (its host mirror) + uvec2 copy_slots; // the heap where shaders read it + uvec2 work; // slot indices (MODE_TRANSLATE) + uvec2 ranges; // range table + uvec2 keys; // key table + uvec2 misses; // miss list + uvec2 backed; // backed spans + uvec2 ask; // ask spans + uvec2 meta; // per slot and half, device-local: what the pass last made of it (meta_of); 0: none + uvec2 cshader; // a filtered rescan's change spans in shader VAs (backings and alias copies that went) + uvec2 ctitle; // and in title VAs (alias ranges that went, words answered since) + uint count; // work items or updates + uint range_count; + uint key_mask; // key table entries - 1 (a power of two) + uint mode; + uint heap; // the heap's index (< 8), kept in each miss + uint backed_count; + uint ask_count; + uint flags; + uint cshader_count; + uint ctitle_count; +} pc; +// MODE_UPDATE reads its records at pc.work (the push constants hold 128 bytes). + +uvec2 add64(uvec2 a, uvec2 b) { + uint carry; + uint lo = uaddCarry(a.x, b.x, carry); + return uvec2(lo, a.y + b.y + carry); +} +uvec2 sub64(uvec2 a, uvec2 b) { + uint borrow; + uint lo = usubBorrow(a.x, b.x, borrow); + return uvec2(lo, a.y - b.y - borrow); +} +bool less64(uvec2 a, uvec2 b) { return a.y < b.y || (a.y == b.y && a.x < b.x); } +uvec2 offset(uvec2 base, uint word) { + uint carry; + uint lo = uaddCarry(base.x, word * 4u, carry); + return uvec2(lo, base.y + carry); +} +uint load(uvec2 base, uint word) { return Words(offset(base, word)).w[0]; } +uvec2 load2(uvec2 base, uint word) { return uvec2(load(base, word), load(base, word + 1u)); } + +// FNV-1a over the four dwords, then MurmurHash3's fmix32: without the finalizer the low bits (the table index) depend +// only on the low bits of each dword, and V#s whose bases differ only above bit 20 all fell into one probe chain. +uint key_hash(uvec4 k) { + uint h = 2166136261u; + h = (h ^ k.x) * 16777619u; + h = (h ^ k.y) * 16777619u; + h = (h ^ k.z) * 16777619u; + h = (h ^ k.w) * 16777619u; + h ^= h >> 16; + h *= 0x85EBCA6Bu; + h ^= h >> 13; + h *= 0xC2B2AE35u; + h ^= h >> 16; + return h; +} + +// [v, v + n) inside one of `count` sorted, disjoint spans at `spans`. +bool spans_hold(uvec2 spans, uint count, uvec2 v, uvec2 n) { + uint lo = 0u, hi = count; + while (lo < hi) { + const uint mid = (lo + hi) >> 1u; + if (less64(v, load2(spans, SPAN_WORDS * mid))) hi = mid; + else lo = mid + 1u; + } + if (lo == 0u) return false; + const uvec2 end = load2(spans, SPAN_WORDS * (lo - 1u) + 2u); + return less64(v, end) && !less64(sub64(end, v), n); +} + +// Some span of `count` sorted, disjoint spans at `spans` overlaps [v, v + n). +bool spans_meet(uvec2 spans, uint count, uvec2 v, uvec2 n) { + const uvec2 last = add64(v, n); // spans starting below it + uint lo = 0u, hi = count; + while (lo < hi) { + const uint mid = (lo + hi) >> 1u; + if (less64(load2(spans, SPAN_WORDS * mid), last)) lo = mid + 1u; + else hi = mid; + } + if (lo == 0u) return false; + return less64(v, load2(spans, SPAN_WORDS * (lo - 1u) + 2u)); +} + +// A 48-bit V# base as the shader VA it names: sign-extended from bit 47 with FLAG_SIGNED. +uvec2 shader_va(uvec2 base48) { + uvec2 v = uvec2(base48.x, base48.y & 0xffffu); + if ((pc.flags & FLAG_SIGNED) != 0u && (v.y & 0x8000u) != 0u) v.y |= 0xffff0000u; + return v; +} + +// Metadata of one V# half: its title base and span before the pass, and the base it got (0: no records). +// x = title base low, y = title base bits 32-47 | result bits 32-47 << 16, z = result low, w = span (saturated). +uvec4 meta_of(uvec4 before, uvec4 after) { + if ((before.w >> 30) != 0u || before.z == 0u) return uvec4(0u); + const uint stride = (before.y >> 16) & 0x3fffu; + uvec2 span; + umulExtended(before.z, stride == 0u ? 1u : stride, span.y, span.x); + const uvec2 to = after.z == 0u ? uvec2(0u) : uvec2(after.x, after.y & 0xffffu); + return uvec4(before.x, (before.y & 0xffffu) | (to.y << 16), to.x, span.y != 0u ? 0xffffffffu : span.x); +} + +// The half's metadata meets a change span: its title base in a title span, or its base or result (with its span) in +// a shader span. What DeviceState's CPU release filter asks of a slot (LEONIDA_CONSOLE_RELEASE_FILTER). +bool affected(uvec4 m) { + if (m.x == 0u && m.y == 0u && m.z == 0u) return false; + const uvec2 base = uvec2(m.x, m.y & 0xffffu); + const uvec2 span = uvec2(m.w, 0u); + if (pc.ctitle_count != 0u && spans_meet(pc.ctitle, pc.ctitle_count, base, uvec2(1u, 0u))) return true; + if (pc.cshader_count == 0u) return false; + if (spans_meet(pc.cshader, pc.cshader_count, shader_va(base), span)) return true; + const uvec2 to = uvec2(m.z, m.y >> 16); + return !(to.x == 0u && to.y == 0u) && spans_meet(pc.cshader, pc.cshader_count, shader_va(to), span); +} + +void rebase(inout uvec4 k, uvec2 to) { + k.x = to.x; + k.y = (k.y & 0xffff0000u) | (to.y & 0xffffu); +} +void no_records(inout uvec4 k) { + k.x = 0u; + k.y = 0u; + k.z = 0u; +} + +// 0: left as it is, 1: rebased or written with no records by a table, 2: missed (written with no records). +uint translate(inout uvec4 k) { + if ((k.w >> 30) != 0u || k.z == 0u) return 0u; + const uvec2 base = uvec2(k.x, k.y & 0xffffu); + if (base.x == 0u && base.y == 0u) { + no_records(k); + return 1u; + } + const uint stride = (k.y >> 16) & 0x3fffu; + uvec2 span; + umulExtended(k.z, stride == 0u ? 1u : stride, span.y, span.x); + // The last range that starts at or below base. + uint lo = 0u, hi = pc.range_count; + while (lo < hi) { + const uint mid = (lo + hi) >> 1u; + if (less64(base, load2(pc.ranges, RANGE_WORDS * mid))) hi = mid; + else lo = mid + 1u; + } + if (lo > 0u) { + const uint e = RANGE_WORDS * (lo - 1u); + const uvec2 end = load2(pc.ranges, e + 2u); + if (less64(base, end) && (load(pc.ranges, e + 6u) & RANGE_CHECKED) != 0u) { + if (less64(sub64(end, base), span)) { + no_records(k); + } else { + const uvec2 start = load2(pc.ranges, e); + rebase(k, add64(load2(pc.ranges, e + 4u), sub64(base, start))); + } + return 1u; + } + } + uvec2 shader = base; + if ((pc.flags & FLAG_SIGNED) != 0u && (base.y & 0x8000u) != 0u) shader.y |= 0xffff0000u; + if (pc.backed_count != 0u && spans_hold(pc.backed, pc.backed_count, shader, span.x == 0u && span.y == 0u ? uvec2(1u, 0u) : span)) + return 1u; + const uint h = key_hash(k); + for (uint p = 0u; p < KEY_PROBES; ++p) { + const uint at = KEY_WORDS * ((h + p) & pc.key_mask); + const uint flags = load(pc.keys, at + 5u) >> 16; + if ((flags & KEY_USED) == 0u) continue; + if (load(pc.keys, at) != k.x || load(pc.keys, at + 1u) != k.y || load(pc.keys, at + 2u) != k.z || + load(pc.keys, at + 3u) != k.w) + continue; + if ((flags & KEY_NONE) != 0u) no_records(k); + else rebase(k, uvec2(load(pc.keys, at + 4u), load(pc.keys, at + 5u) & 0xffffu)); + return 1u; + } + no_records(k); + if ((pc.flags & FLAG_ASK) != 0u && !spans_hold(pc.ask, pc.ask_count, base, uvec2(1u, 0u))) return 1u; + return 2u; +} + +void miss(uint code) { + Words m = Words(pc.misses); + const uint at = atomicAdd(m.w[0], 1u); + if (at < m.w[1]) m.w[MISS_HEADER + at] = code; + else m.w[2] = 1u; +} + +void main() { + const uint i = gl_GlobalInvocationID.x; + if (i >= pc.count) return; + if (pc.mode == MODE_UPDATE) { + const uvec2 record = offset(pc.work, UPDATE_WORDS * i); + const uint index = Words(record).w[0]; + Words table = Words(offset(pc.keys, KEY_WORDS * index)); + for (uint j = 0u; j < KEY_WORDS; ++j) table.w[j] = Words(record).w[4u + j]; + return; + } + // A work item is a slot index; bit 31: the CPU found the slot neither a buffer pair nor a T# it can decode, and + // dwords 0-3 are written as zeros (fix_console_slot's rule: such words must not reach a shader as a descriptor). + const bool range = (pc.flags & FLAG_RANGE) != 0u; + const uint item = range ? pc.work.x + i : Words(pc.work).w[i]; + const uint slot = item & 0x7fffffffu; + const bool has_meta = !(pc.meta.x == 0u && pc.meta.y == 0u); + // A filtered rescan reads only the device-local metadata of a slot it leaves alone, not the title's bytes. + if (range && (pc.flags & FLAG_FILTER) != 0u && has_meta) { + Slots m = Slots(pc.meta); + if (!affected(m.v[2u * slot]) && !affected(m.v[2u * slot + 1u])) return; + } + Slots source = Slots(pc.input_slots); + uvec4 a = source.v[2u * slot]; + uvec4 b = source.v[2u * slot + 1u]; + // A rescan rewrites buffer pairs only: every other slot keeps what its last listed pass wrote. + if (range && (a.w >> 30) != 0u) return; + if ((item >> 31) != 0u && (a.w >> 30) != 0u) a = uvec4(0u); + const uvec4 a0 = a, b0 = b; + if ((a.w >> 30) == 0u) { + // A miss is (heap << 29) | (slot << 1) | half: up to eight heaps of 2^28 slots. + if (translate(a) == 2u) miss((pc.heap << 29) | (slot << 1u)); + if (translate(b) == 2u) miss((pc.heap << 29) | (slot << 1u) | 1u); + } + Slots target = Slots(pc.copy_slots); + target.v[2u * slot] = a; + target.v[2u * slot + 1u] = b; + if (has_meta) { + Slots m = Slots(pc.meta); + const bool pair = (a0.w >> 30) == 0u; + m.v[2u * slot] = pair ? meta_of(a0, a) : uvec4(0u); + m.v[2u * slot + 1u] = pair ? meta_of(b0, b) : uvec4(0u); + } +} diff --git a/runtime/src/console_heap_fix.inc b/runtime/src/console_heap_fix.inc new file mode 100644 index 0000000000..2e2882f6d3 --- /dev/null +++ b/runtime/src/console_heap_fix.inc @@ -0,0 +1,3163 @@ +{0x07230203,0x00010500,0x000d000b,0x000021a5, +0x00000000,0x00020011,0x00000001,0x00020011, +0x000014e3,0x0006000b,0x00000001,0x4c534c47, +0x6474732e,0x3035342e,0x00000000,0x0003000e, +0x000014e4,0x00000001,0x0007000f,0x00000005, +0x00000004,0x6e69616d,0x00000000,0x00000180, +0x000003f8,0x00060010,0x00000004,0x00000011, +0x00000040,0x00000001,0x00000001,0x00040047, +0x000000b2,0x00000006,0x00000004,0x00030047, +0x000000b3,0x00000002,0x00050048,0x000000b3, +0x00000000,0x00000023,0x00000000,0x00030047, +0x0000017e,0x00000002,0x00050048,0x0000017e, +0x00000000,0x00000023,0x00000000,0x00050048, +0x0000017e,0x00000001,0x00000023,0x00000008, +0x00050048,0x0000017e,0x00000002,0x00000023, +0x00000010,0x00050048,0x0000017e,0x00000003, +0x00000023,0x00000018,0x00050048,0x0000017e, +0x00000004,0x00000023,0x00000020,0x00050048, +0x0000017e,0x00000005,0x00000023,0x00000028, +0x00050048,0x0000017e,0x00000006,0x00000023, +0x00000030,0x00050048,0x0000017e,0x00000007, +0x00000023,0x00000038,0x00050048,0x0000017e, +0x00000008,0x00000023,0x00000040,0x00050048, +0x0000017e,0x00000009,0x00000023,0x00000048, +0x00050048,0x0000017e,0x0000000a,0x00000023, +0x00000050,0x00050048,0x0000017e,0x0000000b, +0x00000023,0x00000058,0x00050048,0x0000017e, +0x0000000c,0x00000023,0x0000005c,0x00050048, +0x0000017e,0x0000000d,0x00000023,0x00000060, +0x00050048,0x0000017e,0x0000000e,0x00000023, +0x00000064,0x00050048,0x0000017e,0x0000000f, +0x00000023,0x00000068,0x00050048,0x0000017e, +0x00000010,0x00000023,0x0000006c,0x00050048, +0x0000017e,0x00000011,0x00000023,0x00000070, +0x00050048,0x0000017e,0x00000012,0x00000023, +0x00000074,0x00050048,0x0000017e,0x00000013, +0x00000023,0x00000078,0x00050048,0x0000017e, +0x00000014,0x00000023,0x0000007c,0x00040047, +0x000003f8,0x0000000b,0x0000001c,0x00040047, +0x00000469,0x00000006,0x00000010,0x00030047, +0x0000046a,0x00000002,0x00050048,0x0000046a, +0x00000000,0x00000023,0x00000000,0x00040047, +0x00000517,0x0000000b,0x00000019,0x00020013, +0x00000002,0x00030021,0x00000003,0x00000002, +0x00040015,0x00000006,0x00000020,0x00000000, +0x00040017,0x00000007,0x00000006,0x00000002, +0x00020014,0x00000012,0x00040017,0x00000027, +0x00000006,0x00000004,0x0004002b,0x00000006, +0x00000058,0x00000000,0x0004001e,0x0000005e, +0x00000006,0x00000006,0x0004002b,0x00000006, +0x00000063,0x00000001,0x0004002b,0x00000006, +0x0000009e,0x00000004,0x00030027,0x000000b1, +0x000014e5,0x0003001d,0x000000b2,0x00000006, +0x0003001e,0x000000b3,0x000000b2,0x00040020, +0x000000b1,0x000014e5,0x000000b3,0x00040015, +0x000000b5,0x00000020,0x00000001,0x0004002b, +0x000000b5,0x000000b6,0x00000000,0x00040020, +0x000000b7,0x000014e5,0x00000006,0x0004002b, +0x00000006,0x000000cb,0x811c9dc5,0x0004002b, +0x00000006,0x000000d0,0x01000193,0x0004002b, +0x00000006,0x000000d8,0x00000002,0x0004002b, +0x00000006,0x000000de,0x00000003,0x0004002b, +0x000000b5,0x000000e4,0x00000010,0x0004002b, +0x00000006,0x000000e8,0x85ebca6b,0x0004002b, +0x000000b5,0x000000ec,0x0000000d,0x0004002b, +0x00000006,0x000000f0,0xc2b2ae35,0x0003002a, +0x00000012,0x0000011e,0x0004002b,0x00000006, +0x0000017b,0x0000ffff,0x0017001e,0x0000017e, +0x00000007,0x00000007,0x00000007,0x00000007, +0x00000007,0x00000007,0x00000007,0x00000007, +0x00000007,0x00000007,0x00000007,0x00000006, +0x00000006,0x00000006,0x00000006,0x00000006, +0x00000006,0x00000006,0x00000006,0x00000006, +0x00000006,0x00040020,0x0000017f,0x00000009, +0x0000017e,0x0004003b,0x0000017f,0x00000180, +0x00000009,0x0004002b,0x000000b5,0x00000181, +0x00000012,0x00040020,0x00000182,0x00000009, +0x00000006,0x0004002b,0x00000006,0x0000018b, +0x00008000,0x0004002b,0x00000006,0x00000191, +0xffff0000,0x0004002b,0x000000b5,0x0000019b, +0x0000001e,0x0007002c,0x00000027,0x000001a7, +0x00000058,0x00000058,0x00000058,0x00000058, +0x0004002b,0x00000006,0x000001ad,0x00003fff, +0x0005002c,0x00000007,0x000001c2,0x00000058, +0x00000058,0x0004002b,0x00000006,0x000001dc, +0xffffffff,0x0004002b,0x000000b5,0x00000201, +0x00000014,0x0004002b,0x000000b5,0x00000207, +0x0000000a,0x0005002c,0x00000007,0x00000208, +0x00000063,0x00000058,0x00040020,0x0000020a, +0x00000009,0x00000007,0x00030029,0x00000012, +0x00000217,0x0004002b,0x000000b5,0x00000219, +0x00000013,0x0004002b,0x000000b5,0x00000220, +0x00000009,0x0004002b,0x000000b5,0x0000029a, +0x0000000c,0x0004002b,0x000000b5,0x000002aa, +0x00000003,0x0004002b,0x00000006,0x000002ab, +0x00000008,0x0004002b,0x00000006,0x000002d5, +0x00000006,0x0004002b,0x000000b5,0x00000325, +0x00000006,0x0004002b,0x00000006,0x0000034a, +0x00000010,0x0004002b,0x000000b5,0x00000355, +0x00000004,0x0004002b,0x00000006,0x00000357, +0x00000005,0x0004002b,0x000000b5,0x000003bc, +0x00000001,0x0004002b,0x000000b5,0x000003c8, +0x00000007,0x0004002b,0x000000b5,0x000003c9, +0x00000011,0x0004002b,0x000000b5,0x000003dd, +0x00000005,0x0004002b,0x000000b5,0x000003f3, +0x00000002,0x00040017,0x000003f6,0x00000006, +0x00000003,0x00040020,0x000003f7,0x00000001, +0x000003f6,0x0004003b,0x000003f7,0x000003f8, +0x00000001,0x00040020,0x000003f9,0x00000001, +0x00000006,0x0004002b,0x000000b5,0x000003fd, +0x0000000b,0x0004002b,0x000000b5,0x00000404, +0x0000000e,0x0004002b,0x00000006,0x0000044e, +0x7fffffff,0x0004002b,0x000000b5,0x00000451, +0x00000008,0x00030027,0x00000468,0x000014e5, +0x0003001d,0x00000469,0x00000027,0x0003001e, +0x0000046a,0x00000469,0x00040020,0x00000468, +0x000014e5,0x0000046a,0x00040020,0x00000474, +0x000014e5,0x00000027,0x0004002b,0x000000b5, +0x000004a5,0x0000001f,0x0004002b,0x000000b5, +0x000004c2,0x0000000f,0x0004002b,0x000000b5, +0x000004c5,0x0000001d,0x0004002b,0x00000006, +0x00000516,0x00000040,0x0006002c,0x000003f6, +0x00000517,0x00000516,0x00000063,0x00000063, +0x00030001,0x00000006,0x00001da1,0x0004002b, +0x00000006,0x0000218f,0x00000020,0x0004002b, +0x00000006,0x00002193,0x00000030,0x00040017, +0x0000219a,0x00000012,0x00000004,0x00050036, +0x00000002,0x00000004,0x00000000,0x00000003, +0x000200f8,0x00000005,0x000300f7,0x00000518, +0x00000000,0x000300fb,0x00000058,0x00000519, +0x000200f8,0x00000519,0x00050041,0x000003f9, +0x000003fa,0x000003f8,0x00000058,0x0004003d, +0x00000006,0x000003fb,0x000003fa,0x00050041, +0x00000182,0x000003fe,0x00000180,0x000003fd, +0x0004003d,0x00000006,0x000003ff,0x000003fe, +0x000500ae,0x00000012,0x00000400,0x000003fb, +0x000003ff,0x000300f7,0x00000402,0x00000000, +0x000400fa,0x00000400,0x00000401,0x00000402, +0x000200f8,0x00000401,0x000200f9,0x00000518, +0x000200f8,0x00000402,0x00050041,0x00000182, +0x00000405,0x00000180,0x00000404,0x0004003d, +0x00000006,0x00000406,0x00000405,0x000500aa, +0x00000012,0x00000407,0x00000406,0x00000063, +0x000300f7,0x00000409,0x00000000,0x000400fa, +0x00000407,0x00000408,0x00000409,0x000200f8, +0x00000408,0x00050041,0x0000020a,0x0000040f, +0x00000180,0x000003f3,0x0004003d,0x00000007, +0x00000410,0x0000040f,0x00050051,0x00000006, +0x0000053b,0x00000410,0x00000000,0x00050084, +0x00000006,0x0000053d,0x000003fb,0x00002193, +0x00050095,0x0000005e,0x0000053e,0x0000053b, +0x0000053d,0x00050051,0x00000006,0x0000053f, +0x0000053e,0x00000001,0x00050051,0x00000006, +0x00000540,0x0000053e,0x00000000,0x00050051, +0x00000006,0x00000543,0x00000410,0x00000001, +0x00050080,0x00000006,0x00000545,0x00000543, +0x0000053f,0x00050050,0x00000007,0x00000546, +0x00000540,0x00000545,0x0004007c,0x000000b1, +0x00000415,0x00000546,0x00060041,0x000000b7, +0x00000416,0x00000415,0x000000b6,0x000000b6, +0x0006003d,0x00000006,0x00000417,0x00000416, +0x00000002,0x00000004,0x00050041,0x0000020a, +0x0000041c,0x00000180,0x00000355,0x0004003d, +0x00000007,0x0000041d,0x0000041c,0x00050051, +0x00000006,0x0000054c,0x0000041d,0x00000000, +0x00050084,0x00000006,0x0000054e,0x00000417, +0x0000218f,0x00050095,0x0000005e,0x0000054f, +0x0000054c,0x0000054e,0x00050051,0x00000006, +0x00000550,0x0000054f,0x00000001,0x00050051, +0x00000006,0x00000551,0x0000054f,0x00000000, +0x00050051,0x00000006,0x00000554,0x0000041d, +0x00000001,0x00050080,0x00000006,0x00000556, +0x00000554,0x00000550,0x00050050,0x00000007, +0x00000557,0x00000551,0x00000556,0x0004007c, +0x000000b1,0x00000420,0x00000557,0x000200f9, +0x00000422,0x000200f8,0x00000422,0x000700f5, +0x00000006,0x00002123,0x00000058,0x00000408, +0x00000433,0x00000423,0x000500b0,0x00000012, +0x00000428,0x00002123,0x000002ab,0x000400f6, +0x00000424,0x00000423,0x00000000,0x000400fa, +0x00000428,0x00000423,0x00000424,0x000200f8, +0x00000423,0x00050080,0x00000006,0x0000042e, +0x0000009e,0x00002123,0x00060041,0x000000b7, +0x0000042f,0x00000415,0x000000b6,0x0000042e, +0x0006003d,0x00000006,0x00000430,0x0000042f, +0x00000002,0x00000004,0x00060041,0x000000b7, +0x00000431,0x00000420,0x000000b6,0x00002123, +0x0005003e,0x00000431,0x00000430,0x00000002, +0x00000004,0x00050080,0x00000006,0x00000433, +0x00002123,0x000003bc,0x000200f9,0x00000422, +0x000200f8,0x00000424,0x000200f9,0x00000518, +0x000200f8,0x00000409,0x00050041,0x00000182, +0x00000437,0x00000180,0x00000181,0x0004003d, +0x00000006,0x00000438,0x00000437,0x000500c7, +0x00000006,0x00000439,0x00000438,0x0000009e, +0x000500ab,0x00000012,0x0000043a,0x00000439, +0x00000058,0x000300f7,0x0000043f,0x00000000, +0x000400fa,0x0000043a,0x0000043e,0x00000444, +0x000200f8,0x00000444,0x00050041,0x0000020a, +0x00000445,0x00000180,0x000003f3,0x0004003d, +0x00000007,0x00000446,0x00000445,0x0004007c, +0x000000b1,0x00000447,0x00000446,0x00060041, +0x000000b7,0x00000449,0x00000447,0x000000b6, +0x000003fb,0x0006003d,0x00000006,0x0000044a, +0x00000449,0x00000002,0x00000004,0x000200f9, +0x0000043f,0x000200f8,0x0000043e,0x00060041, +0x00000182,0x00000440,0x00000180,0x000003f3, +0x00000058,0x0004003d,0x00000006,0x00000441, +0x00000440,0x00050080,0x00000006,0x00000443, +0x00000441,0x000003fb,0x000200f9,0x0000043f, +0x000200f8,0x0000043f,0x000700f5,0x00000006, +0x00001ce6,0x00000443,0x0000043e,0x0000044a, +0x00000444,0x000500c7,0x00000006,0x0000044f, +0x00001ce6,0x0000044e,0x00060041,0x00000182, +0x00000452,0x00000180,0x00000451,0x00000058, +0x0004003d,0x00000006,0x00000453,0x00000452, +0x000500aa,0x00000012,0x00000454,0x00000453, +0x00000058,0x000300f7,0x00000456,0x00000000, +0x000400fa,0x00000454,0x00000455,0x00000456, +0x000200f8,0x00000455,0x00060041,0x00000182, +0x00000457,0x00000180,0x00000451,0x00000063, +0x0004003d,0x00000006,0x00000458,0x00000457, +0x000500aa,0x00000012,0x00000459,0x00000458, +0x00000058,0x000200f9,0x00000456,0x000200f8, +0x00000456,0x000700f5,0x00000012,0x0000045a, +0x00000454,0x0000043f,0x00000459,0x00000455, +0x000400a8,0x00000012,0x0000045b,0x0000045a, +0x000300f7,0x0000045e,0x00000000,0x000400fa, +0x0000043a,0x0000045d,0x0000045e,0x000200f8, +0x0000045d,0x000500c7,0x00000006,0x00000461, +0x00000438,0x000002ab,0x000500ab,0x00000012, +0x00000462,0x00000461,0x00000058,0x000200f9, +0x0000045e,0x000200f8,0x0000045e,0x000700f5, +0x00000012,0x00000463,0x0000043a,0x00000456, +0x00000462,0x0000045d,0x000500a7,0x00000012, +0x00000465,0x00000463,0x0000045b,0x000300f7, +0x00000467,0x00000000,0x000400fa,0x00000465, +0x00000466,0x00000467,0x000200f8,0x00000466, +0x00050041,0x0000020a,0x0000046d,0x00000180, +0x00000451,0x0004003d,0x00000007,0x0000046e, +0x0000046d,0x0004007c,0x00000468,0x0000046f, +0x0000046e,0x00050084,0x00000006,0x00000472, +0x000000d8,0x0000044f,0x00060041,0x00000474, +0x00000475,0x0000046f,0x000000b6,0x00000472, +0x0006003d,0x00000027,0x00000476,0x00000475, +0x00000002,0x00000010,0x000300f7,0x000005c0, +0x00000000,0x000300fb,0x00000058,0x0000056d, +0x000200f8,0x0000056d,0x00050051,0x00000006, +0x0000056f,0x00000476,0x00000000,0x000500aa, +0x00000012,0x00000570,0x0000056f,0x00000058, +0x000300f7,0x00000575,0x00000000,0x000400fa, +0x00000570,0x00000571,0x00000575,0x000200f8, +0x00000571,0x00050051,0x00000006,0x00000573, +0x00000476,0x00000001,0x000500aa,0x00000012, +0x00000574,0x00000573,0x00000058,0x000200f9, +0x00000575,0x000200f8,0x00000575,0x000700f5, +0x00000012,0x00000576,0x00000570,0x0000056d, +0x00000574,0x00000571,0x000300f7,0x0000057b, +0x00000000,0x000400fa,0x00000576,0x00000577, +0x0000057b,0x000200f8,0x00000577,0x00050051, +0x00000006,0x00000579,0x00000476,0x00000002, +0x000500aa,0x00000012,0x0000057a,0x00000579, +0x00000058,0x000200f9,0x0000057b,0x000200f8, +0x0000057b,0x000700f5,0x00000012,0x0000057c, +0x00000576,0x00000575,0x0000057a,0x00000577, +0x000300f7,0x0000057e,0x00000000,0x000400fa, +0x0000057c,0x0000057d,0x0000057e,0x000200f8, +0x0000057d,0x000200f9,0x000005c0,0x000200f8, +0x0000057e,0x00050051,0x00000006,0x00000582, +0x00000476,0x00000001,0x000500c7,0x00000006, +0x00000583,0x00000582,0x0000017b,0x00050051, +0x00000006,0x00000586,0x00000476,0x00000003, +0x00050041,0x00000182,0x00000588,0x00000180, +0x00000201,0x0004003d,0x00000006,0x00000589, +0x00000588,0x000500ab,0x00000012,0x0000058a, +0x00000589,0x00000058,0x000300f7,0x00000592, +0x00000000,0x000400fa,0x0000058a,0x0000058b, +0x00000592,0x000200f8,0x0000058b,0x00050041, +0x0000020a,0x0000058c,0x00000180,0x00000207, +0x0004003d,0x00000007,0x0000058d,0x0000058c, +0x000300f7,0x000005fd,0x00000000,0x000300fb, +0x00000058,0x000005d4,0x000200f8,0x000005d4, +0x00050095,0x0000005e,0x00000607,0x0000056f, +0x00000063,0x00050051,0x00000006,0x00000608, +0x00000607,0x00000001,0x00050051,0x00000006, +0x00000609,0x00000607,0x00000000,0x00050080, +0x00000006,0x00000611,0x00000583,0x00000608, +0x000200f9,0x000005d9,0x000200f8,0x000005d9, +0x000700f5,0x00000006,0x00001ce8,0x00000589, +0x000005d4,0x00002194,0x000005ef,0x000700f5, +0x00000006,0x00001ce7,0x00000058,0x000005d4, +0x00002124,0x000005ef,0x000500b0,0x00000012, +0x000005dd,0x00001ce7,0x00001ce8,0x000400f6, +0x000005f0,0x000005ef,0x00000000,0x000400fa, +0x000005dd,0x000005de,0x000005f0,0x000200f8, +0x000005de,0x00050080,0x00000006,0x000005e1, +0x00001ce7,0x00001ce8,0x000500c2,0x00000006, +0x000005e2,0x000005e1,0x00000063,0x00050084, +0x00000006,0x000005e4,0x0000009e,0x000005e2, +0x00050051,0x00000006,0x00000630,0x0000058d, +0x00000000,0x00050084,0x00000006,0x00000632, +0x000005e2,0x0000034a,0x00050095,0x0000005e, +0x00000633,0x00000630,0x00000632,0x00050051, +0x00000006,0x00000634,0x00000633,0x00000001, +0x00050051,0x00000006,0x00000635,0x00000633, +0x00000000,0x00050051,0x00000006,0x00000638, +0x0000058d,0x00000001,0x00050080,0x00000006, +0x0000063a,0x00000638,0x00000634,0x00050050, +0x00000007,0x0000063b,0x00000635,0x0000063a, +0x0004007c,0x000000b1,0x00000628,0x0000063b, +0x00060041,0x000000b7,0x00000629,0x00000628, +0x000000b6,0x000000b6,0x0006003d,0x00000006, +0x0000062a,0x00000629,0x00000002,0x00000004, +0x00050080,0x00000006,0x0000061d,0x000005e4, +0x00000063,0x00050084,0x00000006,0x0000064d, +0x0000061d,0x0000009e,0x00050095,0x0000005e, +0x0000064e,0x00000630,0x0000064d,0x00050051, +0x00000006,0x0000064f,0x0000064e,0x00000001, +0x00050051,0x00000006,0x00000650,0x0000064e, +0x00000000,0x00050080,0x00000006,0x00000655, +0x00000638,0x0000064f,0x00050050,0x00000007, +0x00000656,0x00000650,0x00000655,0x0004007c, +0x000000b1,0x00000643,0x00000656,0x00060041, +0x000000b7,0x00000644,0x00000643,0x000000b6, +0x000000b6,0x0006003d,0x00000006,0x00000645, +0x00000644,0x00000002,0x00000004,0x000500b0, +0x00000012,0x0000065d,0x00000645,0x00000611, +0x000400a8,0x00000012,0x0000065e,0x0000065d, +0x000300f7,0x0000066d,0x00000000,0x000400fa, +0x0000065e,0x0000065f,0x0000066d,0x000200f8, +0x0000065f,0x000500aa,0x00000012,0x00000664, +0x00000645,0x00000611,0x000300f7,0x0000066b, +0x00000000,0x000400fa,0x00000664,0x00000665, +0x0000066b,0x000200f8,0x00000665,0x000500b0, +0x00000012,0x0000066a,0x0000062a,0x00000609, +0x000200f9,0x0000066b,0x000200f8,0x0000066b, +0x000700f5,0x00000012,0x0000066c,0x00000664, +0x0000065f,0x0000066a,0x00000665,0x000200f9, +0x0000066d,0x000200f8,0x0000066d,0x000700f5, +0x00000012,0x0000066e,0x0000065d,0x000005de, +0x0000066c,0x0000066b,0x000300f7,0x000005ee, +0x00000000,0x000400fa,0x0000066e,0x000005e9, +0x000005ec,0x000200f8,0x000005ec,0x000200f9, +0x000005ee,0x000200f8,0x000005e9,0x00050080, +0x00000006,0x000005eb,0x000005e2,0x00000063, +0x000200f9,0x000005ee,0x000200f8,0x000005ee, +0x000700f5,0x00000006,0x00002124,0x000005eb, +0x000005e9,0x00001ce7,0x000005ec,0x000600a9, +0x00000006,0x00002194,0x0000066e,0x00001ce8, +0x000005e2,0x000200f9,0x000005ef,0x000200f8, +0x000005ef,0x000200f9,0x000005d9,0x000200f8, +0x000005f0,0x000500aa,0x00000012,0x000005f2, +0x00001ce7,0x00000058,0x000300f7,0x000005f4, +0x00000000,0x000400fa,0x000005f2,0x000005f3, +0x000005f4,0x000200f8,0x000005f3,0x000200f9, +0x000005fd,0x000200f8,0x000005f4,0x00050082, +0x00000006,0x000005f6,0x00001ce7,0x00000063, +0x00050084,0x00000006,0x000005f7,0x0000009e, +0x000005f6,0x00050080,0x00000006,0x000005f8, +0x000005f7,0x000000d8,0x00050051,0x00000006, +0x0000068c,0x0000058d,0x00000000,0x00050084, +0x00000006,0x0000068e,0x000005f8,0x0000009e, +0x00050095,0x0000005e,0x0000068f,0x0000068c, +0x0000068e,0x00050051,0x00000006,0x00000690, +0x0000068f,0x00000001,0x00050051,0x00000006, +0x00000691,0x0000068f,0x00000000,0x00050051, +0x00000006,0x00000694,0x0000058d,0x00000001, +0x00050080,0x00000006,0x00000696,0x00000694, +0x00000690,0x00050050,0x00000007,0x00000697, +0x00000691,0x00000696,0x0004007c,0x000000b1, +0x00000684,0x00000697,0x00060041,0x000000b7, +0x00000685,0x00000684,0x000000b6,0x000000b6, +0x0006003d,0x00000006,0x00000686,0x00000685, +0x00000002,0x00000004,0x00050080,0x00000006, +0x00000679,0x000005f7,0x000000de,0x00050084, +0x00000006,0x000006a9,0x00000679,0x0000009e, +0x00050095,0x0000005e,0x000006aa,0x0000068c, +0x000006a9,0x00050051,0x00000006,0x000006ab, +0x000006aa,0x00000001,0x00050051,0x00000006, +0x000006ac,0x000006aa,0x00000000,0x00050080, +0x00000006,0x000006b1,0x00000694,0x000006ab, +0x00050050,0x00000007,0x000006b2,0x000006ac, +0x000006b1,0x0004007c,0x000000b1,0x0000069f, +0x000006b2,0x00060041,0x000000b7,0x000006a0, +0x0000069f,0x000000b6,0x000000b6,0x0006003d, +0x00000006,0x000006a1,0x000006a0,0x00000002, +0x00000004,0x000500b0,0x00000012,0x000006b9, +0x00000583,0x000006a1,0x000400a8,0x00000012, +0x000006ba,0x000006b9,0x000300f7,0x000006c9, +0x00000000,0x000400fa,0x000006ba,0x000006bb, +0x000006c9,0x000200f8,0x000006bb,0x000500aa, +0x00000012,0x000006c0,0x00000583,0x000006a1, +0x000300f7,0x000006c7,0x00000000,0x000400fa, +0x000006c0,0x000006c1,0x000006c7,0x000200f8, +0x000006c1,0x000500b0,0x00000012,0x000006c6, +0x0000056f,0x00000686,0x000200f9,0x000006c7, +0x000200f8,0x000006c7,0x000700f5,0x00000012, +0x000006c8,0x000006c0,0x000006bb,0x000006c6, +0x000006c1,0x000200f9,0x000006c9,0x000200f8, +0x000006c9,0x000700f5,0x00000012,0x000006ca, +0x000006b9,0x000005f4,0x000006c8,0x000006c7, +0x000200f9,0x000005fd,0x000200f8,0x000005fd, +0x000700f5,0x00000012,0x00001ce9,0x0000011e, +0x000005f3,0x000006ca,0x000006c9,0x000200f9, +0x00000592,0x000200f8,0x00000592,0x000700f5, +0x00000012,0x00000593,0x0000058a,0x0000057e, +0x00001ce9,0x000005fd,0x000300f7,0x00000595, +0x00000000,0x000400fa,0x00000593,0x00000594, +0x00000595,0x000200f8,0x00000594,0x000200f9, +0x000005c0,0x000200f8,0x00000595,0x00050041, +0x00000182,0x00000596,0x00000180,0x00000219, +0x0004003d,0x00000006,0x00000597,0x00000596, +0x000500aa,0x00000012,0x00000598,0x00000597, +0x00000058,0x000300f7,0x0000059a,0x00000000, +0x000400fa,0x00000598,0x00000599,0x0000059a, +0x000200f8,0x00000599,0x000200f9,0x000005c0, +0x000200f8,0x0000059a,0x00050050,0x00000007, +0x000006d3,0x0000056f,0x00000583,0x000500c7, +0x00000006,0x000006d6,0x00000438,0x00000063, +0x000500ab,0x00000012,0x000006d7,0x000006d6, +0x00000058,0x000300f7,0x000006dd,0x00000000, +0x000400fa,0x000006d7,0x000006d8,0x000006dd, +0x000200f8,0x000006d8,0x000500c7,0x00000006, +0x000006db,0x00000582,0x0000018b,0x000500ab, +0x00000012,0x000006dc,0x000006db,0x00000058, +0x000200f9,0x000006dd,0x000200f8,0x000006dd, +0x000700f5,0x00000012,0x000006de,0x000006d7, +0x0000059a,0x000006dc,0x000006d8,0x000300f7, +0x000006e4,0x00000000,0x000400fa,0x000006de, +0x000006df,0x000006e4,0x000200f8,0x000006df, +0x000500c5,0x00000006,0x000006e2,0x00000583, +0x00000191,0x00060052,0x00000007,0x00001ab3, +0x000006e2,0x000006d3,0x00000001,0x000200f9, +0x000006e4,0x000200f8,0x000006e4,0x000700f5, +0x00000007,0x00001ceb,0x000006d3,0x000006dd, +0x00001ab3,0x000006df,0x00050041,0x0000020a, +0x0000059d,0x00000180,0x00000220,0x0004003d, +0x00000007,0x0000059e,0x0000059d,0x000300f7, +0x00000721,0x00000000,0x000300fb,0x00000058, +0x000006f8,0x000200f8,0x000006f8,0x00050051, +0x00000006,0x00000728,0x00001ceb,0x00000000, +0x00050095,0x0000005e,0x0000072b,0x00000728, +0x00000586,0x00050051,0x00000006,0x0000072c, +0x0000072b,0x00000001,0x00050051,0x00000006, +0x0000072d,0x0000072b,0x00000000,0x00050051, +0x00000006,0x00000730,0x00001ceb,0x00000001, +0x00050080,0x00000006,0x00000735,0x00000730, +0x0000072c,0x000200f9,0x000006fd,0x000200f8, +0x000006fd,0x000700f5,0x00000006,0x00001ced, +0x00000597,0x000006f8,0x00002195,0x00000713, +0x000700f5,0x00000006,0x00001cec,0x00000058, +0x000006f8,0x0000212a,0x00000713,0x000500b0, +0x00000012,0x00000701,0x00001cec,0x00001ced, +0x000400f6,0x00000714,0x00000713,0x00000000, +0x000400fa,0x00000701,0x00000702,0x00000714, +0x000200f8,0x00000702,0x00050080,0x00000006, +0x00000705,0x00001cec,0x00001ced,0x000500c2, +0x00000006,0x00000706,0x00000705,0x00000063, +0x00050084,0x00000006,0x00000708,0x0000009e, +0x00000706,0x00050051,0x00000006,0x00000754, +0x0000059e,0x00000000,0x00050084,0x00000006, +0x00000756,0x00000706,0x0000034a,0x00050095, +0x0000005e,0x00000757,0x00000754,0x00000756, +0x00050051,0x00000006,0x00000758,0x00000757, +0x00000001,0x00050051,0x00000006,0x00000759, +0x00000757,0x00000000,0x00050051,0x00000006, +0x0000075c,0x0000059e,0x00000001,0x00050080, +0x00000006,0x0000075e,0x0000075c,0x00000758, +0x00050050,0x00000007,0x0000075f,0x00000759, +0x0000075e,0x0004007c,0x000000b1,0x0000074c, +0x0000075f,0x00060041,0x000000b7,0x0000074d, +0x0000074c,0x000000b6,0x000000b6,0x0006003d, +0x00000006,0x0000074e,0x0000074d,0x00000002, +0x00000004,0x00050080,0x00000006,0x00000741, +0x00000708,0x00000063,0x00050084,0x00000006, +0x00000771,0x00000741,0x0000009e,0x00050095, +0x0000005e,0x00000772,0x00000754,0x00000771, +0x00050051,0x00000006,0x00000773,0x00000772, +0x00000001,0x00050051,0x00000006,0x00000774, +0x00000772,0x00000000,0x00050080,0x00000006, +0x00000779,0x0000075c,0x00000773,0x00050050, +0x00000007,0x0000077a,0x00000774,0x00000779, +0x0004007c,0x000000b1,0x00000767,0x0000077a, +0x00060041,0x000000b7,0x00000768,0x00000767, +0x000000b6,0x000000b6,0x0006003d,0x00000006, +0x00000769,0x00000768,0x00000002,0x00000004, +0x000500b0,0x00000012,0x00000781,0x00000769, +0x00000735,0x000400a8,0x00000012,0x00000782, +0x00000781,0x000300f7,0x00000791,0x00000000, +0x000400fa,0x00000782,0x00000783,0x00000791, +0x000200f8,0x00000783,0x000500aa,0x00000012, +0x00000788,0x00000769,0x00000735,0x000300f7, +0x0000078f,0x00000000,0x000400fa,0x00000788, +0x00000789,0x0000078f,0x000200f8,0x00000789, +0x000500b0,0x00000012,0x0000078e,0x0000074e, +0x0000072d,0x000200f9,0x0000078f,0x000200f8, +0x0000078f,0x000700f5,0x00000012,0x00000790, +0x00000788,0x00000783,0x0000078e,0x00000789, +0x000200f9,0x00000791,0x000200f8,0x00000791, +0x000700f5,0x00000012,0x00000792,0x00000781, +0x00000702,0x00000790,0x0000078f,0x000300f7, +0x00000712,0x00000000,0x000400fa,0x00000792, +0x0000070d,0x00000710,0x000200f8,0x00000710, +0x000200f9,0x00000712,0x000200f8,0x0000070d, +0x00050080,0x00000006,0x0000070f,0x00000706, +0x00000063,0x000200f9,0x00000712,0x000200f8, +0x00000712,0x000700f5,0x00000006,0x0000212a, +0x0000070f,0x0000070d,0x00001cec,0x00000710, +0x000600a9,0x00000006,0x00002195,0x00000792, +0x00001ced,0x00000706,0x000200f9,0x00000713, +0x000200f8,0x00000713,0x000200f9,0x000006fd, +0x000200f8,0x00000714,0x000500aa,0x00000012, +0x00000716,0x00001cec,0x00000058,0x000300f7, +0x00000718,0x00000000,0x000400fa,0x00000716, +0x00000717,0x00000718,0x000200f8,0x00000717, +0x000200f9,0x00000721,0x000200f8,0x00000718, +0x00050082,0x00000006,0x0000071a,0x00001cec, +0x00000063,0x00050084,0x00000006,0x0000071b, +0x0000009e,0x0000071a,0x00050080,0x00000006, +0x0000071c,0x0000071b,0x000000d8,0x00050051, +0x00000006,0x000007b0,0x0000059e,0x00000000, +0x00050084,0x00000006,0x000007b2,0x0000071c, +0x0000009e,0x00050095,0x0000005e,0x000007b3, +0x000007b0,0x000007b2,0x00050051,0x00000006, +0x000007b4,0x000007b3,0x00000001,0x00050051, +0x00000006,0x000007b5,0x000007b3,0x00000000, +0x00050051,0x00000006,0x000007b8,0x0000059e, +0x00000001,0x00050080,0x00000006,0x000007ba, +0x000007b8,0x000007b4,0x00050050,0x00000007, +0x000007bb,0x000007b5,0x000007ba,0x0004007c, +0x000000b1,0x000007a8,0x000007bb,0x00060041, +0x000000b7,0x000007a9,0x000007a8,0x000000b6, +0x000000b6,0x0006003d,0x00000006,0x000007aa, +0x000007a9,0x00000002,0x00000004,0x00050080, +0x00000006,0x0000079d,0x0000071b,0x000000de, +0x00050084,0x00000006,0x000007cd,0x0000079d, +0x0000009e,0x00050095,0x0000005e,0x000007ce, +0x000007b0,0x000007cd,0x00050051,0x00000006, +0x000007cf,0x000007ce,0x00000001,0x00050051, +0x00000006,0x000007d0,0x000007ce,0x00000000, +0x00050080,0x00000006,0x000007d5,0x000007b8, +0x000007cf,0x00050050,0x00000007,0x000007d6, +0x000007d0,0x000007d5,0x0004007c,0x000000b1, +0x000007c3,0x000007d6,0x00060041,0x000000b7, +0x000007c4,0x000007c3,0x000000b6,0x000000b6, +0x0006003d,0x00000006,0x000007c5,0x000007c4, +0x00000002,0x00000004,0x000500b0,0x00000012, +0x000007dd,0x00000730,0x000007c5,0x000400a8, +0x00000012,0x000007de,0x000007dd,0x000300f7, +0x000007ed,0x00000000,0x000400fa,0x000007de, +0x000007df,0x000007ed,0x000200f8,0x000007df, +0x000500aa,0x00000012,0x000007e4,0x00000730, +0x000007c5,0x000300f7,0x000007eb,0x00000000, +0x000400fa,0x000007e4,0x000007e5,0x000007eb, +0x000200f8,0x000007e5,0x000500b0,0x00000012, +0x000007ea,0x00000728,0x000007aa,0x000200f9, +0x000007eb,0x000200f8,0x000007eb,0x000700f5, +0x00000012,0x000007ec,0x000007e4,0x000007df, +0x000007ea,0x000007e5,0x000200f9,0x000007ed, +0x000200f8,0x000007ed,0x000700f5,0x00000012, +0x000007ee,0x000007dd,0x00000718,0x000007ec, +0x000007eb,0x000200f9,0x00000721,0x000200f8, +0x00000721,0x000700f5,0x00000012,0x00001cee, +0x0000011e,0x00000717,0x000007ee,0x000007ed, +0x000300f7,0x000005a4,0x00000000,0x000400fa, +0x00001cee,0x000005a3,0x000005a4,0x000200f8, +0x000005a3,0x000200f9,0x000005c0,0x000200f8, +0x000005a4,0x00050051,0x00000006,0x000005a6, +0x00000476,0x00000002,0x000500c2,0x00000006, +0x000005a9,0x00000582,0x000000e4,0x000500aa, +0x00000012,0x000005ad,0x000005a6,0x00000058, +0x000300f7,0x000005b2,0x00000000,0x000400fa, +0x000005ad,0x000005ae,0x000005b2,0x000200f8, +0x000005ae,0x000500aa,0x00000012,0x000005b1, +0x000005a9,0x00000058,0x000200f9,0x000005b2, +0x000200f8,0x000005b2,0x000700f5,0x00000012, +0x000005b3,0x000005ad,0x000005a4,0x000005b1, +0x000005ae,0x000400a8,0x00000012,0x000005b4, +0x000005b3,0x000300f7,0x000005be,0x00000000, +0x000400fa,0x000005b4,0x000005b5,0x000005be, +0x000200f8,0x000005b5,0x000500c7,0x00000006, +0x000007f6,0x000005a9,0x0000017b,0x00050050, +0x00000007,0x000007f7,0x000005a6,0x000007f6, +0x000300f7,0x00000801,0x00000000,0x000400fa, +0x000006d7,0x000007fc,0x00000801,0x000200f8, +0x000007fc,0x000500c7,0x00000006,0x000007ff, +0x000005a9,0x0000018b,0x000500ab,0x00000012, +0x00000800,0x000007ff,0x00000058,0x000200f9, +0x00000801,0x000200f8,0x00000801,0x000700f5, +0x00000012,0x00000802,0x000006d7,0x000005b5, +0x00000800,0x000007fc,0x000300f7,0x00000808, +0x00000000,0x000400fa,0x00000802,0x00000803, +0x00000808,0x000200f8,0x00000803,0x000500c5, +0x00000006,0x00000806,0x000007f6,0x00000191, +0x00060052,0x00000007,0x00001ad5,0x00000806, +0x000007f7,0x00000001,0x000200f9,0x00000808, +0x000200f8,0x00000808,0x000700f5,0x00000007, +0x00001cf0,0x000007f7,0x00000801,0x00001ad5, +0x00000803,0x000300f7,0x00000845,0x00000000, +0x000300fb,0x00000058,0x0000081c,0x000200f8, +0x0000081c,0x00050051,0x00000006,0x0000084c, +0x00001cf0,0x00000000,0x00050095,0x0000005e, +0x0000084f,0x0000084c,0x00000586,0x00050051, +0x00000006,0x00000850,0x0000084f,0x00000001, +0x00050051,0x00000006,0x00000851,0x0000084f, +0x00000000,0x00050051,0x00000006,0x00000854, +0x00001cf0,0x00000001,0x00050080,0x00000006, +0x00000859,0x00000854,0x00000850,0x000200f9, +0x00000821,0x000200f8,0x00000821,0x000700f5, +0x00000006,0x00001cf2,0x00000597,0x0000081c, +0x00002196,0x00000837,0x000700f5,0x00000006, +0x00001cf1,0x00000058,0x0000081c,0x00002130, +0x00000837,0x000500b0,0x00000012,0x00000825, +0x00001cf1,0x00001cf2,0x000400f6,0x00000838, +0x00000837,0x00000000,0x000400fa,0x00000825, +0x00000826,0x00000838,0x000200f8,0x00000826, +0x00050080,0x00000006,0x00000829,0x00001cf1, +0x00001cf2,0x000500c2,0x00000006,0x0000082a, +0x00000829,0x00000063,0x00050084,0x00000006, +0x0000082c,0x0000009e,0x0000082a,0x00050051, +0x00000006,0x00000878,0x0000059e,0x00000000, +0x00050084,0x00000006,0x0000087a,0x0000082a, +0x0000034a,0x00050095,0x0000005e,0x0000087b, +0x00000878,0x0000087a,0x00050051,0x00000006, +0x0000087c,0x0000087b,0x00000001,0x00050051, +0x00000006,0x0000087d,0x0000087b,0x00000000, +0x00050051,0x00000006,0x00000880,0x0000059e, +0x00000001,0x00050080,0x00000006,0x00000882, +0x00000880,0x0000087c,0x00050050,0x00000007, +0x00000883,0x0000087d,0x00000882,0x0004007c, +0x000000b1,0x00000870,0x00000883,0x00060041, +0x000000b7,0x00000871,0x00000870,0x000000b6, +0x000000b6,0x0006003d,0x00000006,0x00000872, +0x00000871,0x00000002,0x00000004,0x00050080, +0x00000006,0x00000865,0x0000082c,0x00000063, +0x00050084,0x00000006,0x00000895,0x00000865, +0x0000009e,0x00050095,0x0000005e,0x00000896, +0x00000878,0x00000895,0x00050051,0x00000006, +0x00000897,0x00000896,0x00000001,0x00050051, +0x00000006,0x00000898,0x00000896,0x00000000, +0x00050080,0x00000006,0x0000089d,0x00000880, +0x00000897,0x00050050,0x00000007,0x0000089e, +0x00000898,0x0000089d,0x0004007c,0x000000b1, +0x0000088b,0x0000089e,0x00060041,0x000000b7, +0x0000088c,0x0000088b,0x000000b6,0x000000b6, +0x0006003d,0x00000006,0x0000088d,0x0000088c, +0x00000002,0x00000004,0x000500b0,0x00000012, +0x000008a5,0x0000088d,0x00000859,0x000400a8, +0x00000012,0x000008a6,0x000008a5,0x000300f7, +0x000008b5,0x00000000,0x000400fa,0x000008a6, +0x000008a7,0x000008b5,0x000200f8,0x000008a7, +0x000500aa,0x00000012,0x000008ac,0x0000088d, +0x00000859,0x000300f7,0x000008b3,0x00000000, +0x000400fa,0x000008ac,0x000008ad,0x000008b3, +0x000200f8,0x000008ad,0x000500b0,0x00000012, +0x000008b2,0x00000872,0x00000851,0x000200f9, +0x000008b3,0x000200f8,0x000008b3,0x000700f5, +0x00000012,0x000008b4,0x000008ac,0x000008a7, +0x000008b2,0x000008ad,0x000200f9,0x000008b5, +0x000200f8,0x000008b5,0x000700f5,0x00000012, +0x000008b6,0x000008a5,0x00000826,0x000008b4, +0x000008b3,0x000300f7,0x00000836,0x00000000, +0x000400fa,0x000008b6,0x00000831,0x00000834, +0x000200f8,0x00000834,0x000200f9,0x00000836, +0x000200f8,0x00000831,0x00050080,0x00000006, +0x00000833,0x0000082a,0x00000063,0x000200f9, +0x00000836,0x000200f8,0x00000836,0x000700f5, +0x00000006,0x00002130,0x00000833,0x00000831, +0x00001cf1,0x00000834,0x000600a9,0x00000006, +0x00002196,0x000008b6,0x00001cf2,0x0000082a, +0x000200f9,0x00000837,0x000200f8,0x00000837, +0x000200f9,0x00000821,0x000200f8,0x00000838, +0x000500aa,0x00000012,0x0000083a,0x00001cf1, +0x00000058,0x000300f7,0x0000083c,0x00000000, +0x000400fa,0x0000083a,0x0000083b,0x0000083c, +0x000200f8,0x0000083b,0x000200f9,0x00000845, +0x000200f8,0x0000083c,0x00050082,0x00000006, +0x0000083e,0x00001cf1,0x00000063,0x00050084, +0x00000006,0x0000083f,0x0000009e,0x0000083e, +0x00050080,0x00000006,0x00000840,0x0000083f, +0x000000d8,0x00050051,0x00000006,0x000008d4, +0x0000059e,0x00000000,0x00050084,0x00000006, +0x000008d6,0x00000840,0x0000009e,0x00050095, +0x0000005e,0x000008d7,0x000008d4,0x000008d6, +0x00050051,0x00000006,0x000008d8,0x000008d7, +0x00000001,0x00050051,0x00000006,0x000008d9, +0x000008d7,0x00000000,0x00050051,0x00000006, +0x000008dc,0x0000059e,0x00000001,0x00050080, +0x00000006,0x000008de,0x000008dc,0x000008d8, +0x00050050,0x00000007,0x000008df,0x000008d9, +0x000008de,0x0004007c,0x000000b1,0x000008cc, +0x000008df,0x00060041,0x000000b7,0x000008cd, +0x000008cc,0x000000b6,0x000000b6,0x0006003d, +0x00000006,0x000008ce,0x000008cd,0x00000002, +0x00000004,0x00050080,0x00000006,0x000008c1, +0x0000083f,0x000000de,0x00050084,0x00000006, +0x000008f1,0x000008c1,0x0000009e,0x00050095, +0x0000005e,0x000008f2,0x000008d4,0x000008f1, +0x00050051,0x00000006,0x000008f3,0x000008f2, +0x00000001,0x00050051,0x00000006,0x000008f4, +0x000008f2,0x00000000,0x00050080,0x00000006, +0x000008f9,0x000008dc,0x000008f3,0x00050050, +0x00000007,0x000008fa,0x000008f4,0x000008f9, +0x0004007c,0x000000b1,0x000008e7,0x000008fa, +0x00060041,0x000000b7,0x000008e8,0x000008e7, +0x000000b6,0x000000b6,0x0006003d,0x00000006, +0x000008e9,0x000008e8,0x00000002,0x00000004, +0x000500b0,0x00000012,0x00000901,0x00000854, +0x000008e9,0x000400a8,0x00000012,0x00000902, +0x00000901,0x000300f7,0x00000911,0x00000000, +0x000400fa,0x00000902,0x00000903,0x00000911, +0x000200f8,0x00000903,0x000500aa,0x00000012, +0x00000908,0x00000854,0x000008e9,0x000300f7, +0x0000090f,0x00000000,0x000400fa,0x00000908, +0x00000909,0x0000090f,0x000200f8,0x00000909, +0x000500b0,0x00000012,0x0000090e,0x0000084c, +0x000008ce,0x000200f9,0x0000090f,0x000200f8, +0x0000090f,0x000700f5,0x00000012,0x00000910, +0x00000908,0x00000903,0x0000090e,0x00000909, +0x000200f9,0x00000911,0x000200f8,0x00000911, +0x000700f5,0x00000012,0x00000912,0x00000901, +0x0000083c,0x00000910,0x0000090f,0x000200f9, +0x00000845,0x000200f8,0x00000845,0x000700f5, +0x00000012,0x00001cf3,0x0000011e,0x0000083b, +0x00000912,0x00000911,0x000200f9,0x000005be, +0x000200f8,0x000005be,0x000700f5,0x00000012, +0x000005bf,0x000005b4,0x000005b2,0x00001cf3, +0x00000845,0x000200f9,0x000005c0,0x000200f8, +0x000005c0,0x000d00f5,0x00000012,0x00001cf4, +0x0000011e,0x0000057d,0x00000217,0x00000594, +0x0000011e,0x00000599,0x00000217,0x000005a3, +0x000005bf,0x000005be,0x000400a8,0x00000012, +0x00000478,0x00001cf4,0x000300f7,0x0000047a, +0x00000000,0x000400fa,0x00000478,0x00000479, +0x0000047a,0x000200f8,0x00000479,0x00050080, +0x00000006,0x0000047e,0x00000472,0x00000063, +0x00060041,0x00000474,0x00000480,0x0000046f, +0x000000b6,0x0000047e,0x0006003d,0x00000027, +0x00000481,0x00000480,0x00000002,0x00000010, +0x000300f7,0x0000097b,0x00000000,0x000300fb, +0x00000058,0x00000928,0x000200f8,0x00000928, +0x00050051,0x00000006,0x0000092a,0x00000481, +0x00000000,0x000500aa,0x00000012,0x0000092b, +0x0000092a,0x00000058,0x000300f7,0x00000930, +0x00000000,0x000400fa,0x0000092b,0x0000092c, +0x00000930,0x000200f8,0x0000092c,0x00050051, +0x00000006,0x0000092e,0x00000481,0x00000001, +0x000500aa,0x00000012,0x0000092f,0x0000092e, +0x00000058,0x000200f9,0x00000930,0x000200f8, +0x00000930,0x000700f5,0x00000012,0x00000931, +0x0000092b,0x00000928,0x0000092f,0x0000092c, +0x000300f7,0x00000936,0x00000000,0x000400fa, +0x00000931,0x00000932,0x00000936,0x000200f8, +0x00000932,0x00050051,0x00000006,0x00000934, +0x00000481,0x00000002,0x000500aa,0x00000012, +0x00000935,0x00000934,0x00000058,0x000200f9, +0x00000936,0x000200f8,0x00000936,0x000700f5, +0x00000012,0x00000937,0x00000931,0x00000930, +0x00000935,0x00000932,0x000300f7,0x00000939, +0x00000000,0x000400fa,0x00000937,0x00000938, +0x00000939,0x000200f8,0x00000938,0x000200f9, +0x0000097b,0x000200f8,0x00000939,0x00050051, +0x00000006,0x0000093d,0x00000481,0x00000001, +0x000500c7,0x00000006,0x0000093e,0x0000093d, +0x0000017b,0x00050051,0x00000006,0x00000941, +0x00000481,0x00000003,0x00050041,0x00000182, +0x00000943,0x00000180,0x00000201,0x0004003d, +0x00000006,0x00000944,0x00000943,0x000500ab, +0x00000012,0x00000945,0x00000944,0x00000058, +0x000300f7,0x0000094d,0x00000000,0x000400fa, +0x00000945,0x00000946,0x0000094d,0x000200f8, +0x00000946,0x00050041,0x0000020a,0x00000947, +0x00000180,0x00000207,0x0004003d,0x00000007, +0x00000948,0x00000947,0x000300f7,0x000009b8, +0x00000000,0x000300fb,0x00000058,0x0000098f, +0x000200f8,0x0000098f,0x00050095,0x0000005e, +0x000009c2,0x0000092a,0x00000063,0x00050051, +0x00000006,0x000009c3,0x000009c2,0x00000001, +0x00050051,0x00000006,0x000009c4,0x000009c2, +0x00000000,0x00050080,0x00000006,0x000009cc, +0x0000093e,0x000009c3,0x000200f9,0x00000994, +0x000200f8,0x00000994,0x000700f5,0x00000006, +0x00001cf6,0x00000944,0x0000098f,0x00002197, +0x000009aa,0x000700f5,0x00000006,0x00001cf5, +0x00000058,0x0000098f,0x00002136,0x000009aa, +0x000500b0,0x00000012,0x00000998,0x00001cf5, +0x00001cf6,0x000400f6,0x000009ab,0x000009aa, +0x00000000,0x000400fa,0x00000998,0x00000999, +0x000009ab,0x000200f8,0x00000999,0x00050080, +0x00000006,0x0000099c,0x00001cf5,0x00001cf6, +0x000500c2,0x00000006,0x0000099d,0x0000099c, +0x00000063,0x00050084,0x00000006,0x0000099f, +0x0000009e,0x0000099d,0x00050051,0x00000006, +0x000009eb,0x00000948,0x00000000,0x00050084, +0x00000006,0x000009ed,0x0000099d,0x0000034a, +0x00050095,0x0000005e,0x000009ee,0x000009eb, +0x000009ed,0x00050051,0x00000006,0x000009ef, +0x000009ee,0x00000001,0x00050051,0x00000006, +0x000009f0,0x000009ee,0x00000000,0x00050051, +0x00000006,0x000009f3,0x00000948,0x00000001, +0x00050080,0x00000006,0x000009f5,0x000009f3, +0x000009ef,0x00050050,0x00000007,0x000009f6, +0x000009f0,0x000009f5,0x0004007c,0x000000b1, +0x000009e3,0x000009f6,0x00060041,0x000000b7, +0x000009e4,0x000009e3,0x000000b6,0x000000b6, +0x0006003d,0x00000006,0x000009e5,0x000009e4, +0x00000002,0x00000004,0x00050080,0x00000006, +0x000009d8,0x0000099f,0x00000063,0x00050084, +0x00000006,0x00000a08,0x000009d8,0x0000009e, +0x00050095,0x0000005e,0x00000a09,0x000009eb, +0x00000a08,0x00050051,0x00000006,0x00000a0a, +0x00000a09,0x00000001,0x00050051,0x00000006, +0x00000a0b,0x00000a09,0x00000000,0x00050080, +0x00000006,0x00000a10,0x000009f3,0x00000a0a, +0x00050050,0x00000007,0x00000a11,0x00000a0b, +0x00000a10,0x0004007c,0x000000b1,0x000009fe, +0x00000a11,0x00060041,0x000000b7,0x000009ff, +0x000009fe,0x000000b6,0x000000b6,0x0006003d, +0x00000006,0x00000a00,0x000009ff,0x00000002, +0x00000004,0x000500b0,0x00000012,0x00000a18, +0x00000a00,0x000009cc,0x000400a8,0x00000012, +0x00000a19,0x00000a18,0x000300f7,0x00000a28, +0x00000000,0x000400fa,0x00000a19,0x00000a1a, +0x00000a28,0x000200f8,0x00000a1a,0x000500aa, +0x00000012,0x00000a1f,0x00000a00,0x000009cc, +0x000300f7,0x00000a26,0x00000000,0x000400fa, +0x00000a1f,0x00000a20,0x00000a26,0x000200f8, +0x00000a20,0x000500b0,0x00000012,0x00000a25, +0x000009e5,0x000009c4,0x000200f9,0x00000a26, +0x000200f8,0x00000a26,0x000700f5,0x00000012, +0x00000a27,0x00000a1f,0x00000a1a,0x00000a25, +0x00000a20,0x000200f9,0x00000a28,0x000200f8, +0x00000a28,0x000700f5,0x00000012,0x00000a29, +0x00000a18,0x00000999,0x00000a27,0x00000a26, +0x000300f7,0x000009a9,0x00000000,0x000400fa, +0x00000a29,0x000009a4,0x000009a7,0x000200f8, +0x000009a7,0x000200f9,0x000009a9,0x000200f8, +0x000009a4,0x00050080,0x00000006,0x000009a6, +0x0000099d,0x00000063,0x000200f9,0x000009a9, +0x000200f8,0x000009a9,0x000700f5,0x00000006, +0x00002136,0x000009a6,0x000009a4,0x00001cf5, +0x000009a7,0x000600a9,0x00000006,0x00002197, +0x00000a29,0x00001cf6,0x0000099d,0x000200f9, +0x000009aa,0x000200f8,0x000009aa,0x000200f9, +0x00000994,0x000200f8,0x000009ab,0x000500aa, +0x00000012,0x000009ad,0x00001cf5,0x00000058, +0x000300f7,0x000009af,0x00000000,0x000400fa, +0x000009ad,0x000009ae,0x000009af,0x000200f8, +0x000009ae,0x000200f9,0x000009b8,0x000200f8, +0x000009af,0x00050082,0x00000006,0x000009b1, +0x00001cf5,0x00000063,0x00050084,0x00000006, +0x000009b2,0x0000009e,0x000009b1,0x00050080, +0x00000006,0x000009b3,0x000009b2,0x000000d8, +0x00050051,0x00000006,0x00000a47,0x00000948, +0x00000000,0x00050084,0x00000006,0x00000a49, +0x000009b3,0x0000009e,0x00050095,0x0000005e, +0x00000a4a,0x00000a47,0x00000a49,0x00050051, +0x00000006,0x00000a4b,0x00000a4a,0x00000001, +0x00050051,0x00000006,0x00000a4c,0x00000a4a, +0x00000000,0x00050051,0x00000006,0x00000a4f, +0x00000948,0x00000001,0x00050080,0x00000006, +0x00000a51,0x00000a4f,0x00000a4b,0x00050050, +0x00000007,0x00000a52,0x00000a4c,0x00000a51, +0x0004007c,0x000000b1,0x00000a3f,0x00000a52, +0x00060041,0x000000b7,0x00000a40,0x00000a3f, +0x000000b6,0x000000b6,0x0006003d,0x00000006, +0x00000a41,0x00000a40,0x00000002,0x00000004, +0x00050080,0x00000006,0x00000a34,0x000009b2, +0x000000de,0x00050084,0x00000006,0x00000a64, +0x00000a34,0x0000009e,0x00050095,0x0000005e, +0x00000a65,0x00000a47,0x00000a64,0x00050051, +0x00000006,0x00000a66,0x00000a65,0x00000001, +0x00050051,0x00000006,0x00000a67,0x00000a65, +0x00000000,0x00050080,0x00000006,0x00000a6c, +0x00000a4f,0x00000a66,0x00050050,0x00000007, +0x00000a6d,0x00000a67,0x00000a6c,0x0004007c, +0x000000b1,0x00000a5a,0x00000a6d,0x00060041, +0x000000b7,0x00000a5b,0x00000a5a,0x000000b6, +0x000000b6,0x0006003d,0x00000006,0x00000a5c, +0x00000a5b,0x00000002,0x00000004,0x000500b0, +0x00000012,0x00000a74,0x0000093e,0x00000a5c, +0x000400a8,0x00000012,0x00000a75,0x00000a74, +0x000300f7,0x00000a84,0x00000000,0x000400fa, +0x00000a75,0x00000a76,0x00000a84,0x000200f8, +0x00000a76,0x000500aa,0x00000012,0x00000a7b, +0x0000093e,0x00000a5c,0x000300f7,0x00000a82, +0x00000000,0x000400fa,0x00000a7b,0x00000a7c, +0x00000a82,0x000200f8,0x00000a7c,0x000500b0, +0x00000012,0x00000a81,0x0000092a,0x00000a41, +0x000200f9,0x00000a82,0x000200f8,0x00000a82, +0x000700f5,0x00000012,0x00000a83,0x00000a7b, +0x00000a76,0x00000a81,0x00000a7c,0x000200f9, +0x00000a84,0x000200f8,0x00000a84,0x000700f5, +0x00000012,0x00000a85,0x00000a74,0x000009af, +0x00000a83,0x00000a82,0x000200f9,0x000009b8, +0x000200f8,0x000009b8,0x000700f5,0x00000012, +0x00001cf7,0x0000011e,0x000009ae,0x00000a85, +0x00000a84,0x000200f9,0x0000094d,0x000200f8, +0x0000094d,0x000700f5,0x00000012,0x0000094e, +0x00000945,0x00000939,0x00001cf7,0x000009b8, +0x000300f7,0x00000950,0x00000000,0x000400fa, +0x0000094e,0x0000094f,0x00000950,0x000200f8, +0x0000094f,0x000200f9,0x0000097b,0x000200f8, +0x00000950,0x00050041,0x00000182,0x00000951, +0x00000180,0x00000219,0x0004003d,0x00000006, +0x00000952,0x00000951,0x000500aa,0x00000012, +0x00000953,0x00000952,0x00000058,0x000300f7, +0x00000955,0x00000000,0x000400fa,0x00000953, +0x00000954,0x00000955,0x000200f8,0x00000954, +0x000200f9,0x0000097b,0x000200f8,0x00000955, +0x00050050,0x00000007,0x00000a8e,0x0000092a, +0x0000093e,0x000500c7,0x00000006,0x00000a91, +0x00000438,0x00000063,0x000500ab,0x00000012, +0x00000a92,0x00000a91,0x00000058,0x000300f7, +0x00000a98,0x00000000,0x000400fa,0x00000a92, +0x00000a93,0x00000a98,0x000200f8,0x00000a93, +0x000500c7,0x00000006,0x00000a96,0x0000093d, +0x0000018b,0x000500ab,0x00000012,0x00000a97, +0x00000a96,0x00000058,0x000200f9,0x00000a98, +0x000200f8,0x00000a98,0x000700f5,0x00000012, +0x00000a99,0x00000a92,0x00000955,0x00000a97, +0x00000a93,0x000300f7,0x00000a9f,0x00000000, +0x000400fa,0x00000a99,0x00000a9a,0x00000a9f, +0x000200f8,0x00000a9a,0x000500c5,0x00000006, +0x00000a9d,0x0000093e,0x00000191,0x00060052, +0x00000007,0x00001b11,0x00000a9d,0x00000a8e, +0x00000001,0x000200f9,0x00000a9f,0x000200f8, +0x00000a9f,0x000700f5,0x00000007,0x00001cf9, +0x00000a8e,0x00000a98,0x00001b11,0x00000a9a, +0x00050041,0x0000020a,0x00000958,0x00000180, +0x00000220,0x0004003d,0x00000007,0x00000959, +0x00000958,0x000300f7,0x00000adc,0x00000000, +0x000300fb,0x00000058,0x00000ab3,0x000200f8, +0x00000ab3,0x00050051,0x00000006,0x00000ae3, +0x00001cf9,0x00000000,0x00050095,0x0000005e, +0x00000ae6,0x00000ae3,0x00000941,0x00050051, +0x00000006,0x00000ae7,0x00000ae6,0x00000001, +0x00050051,0x00000006,0x00000ae8,0x00000ae6, +0x00000000,0x00050051,0x00000006,0x00000aeb, +0x00001cf9,0x00000001,0x00050080,0x00000006, +0x00000af0,0x00000aeb,0x00000ae7,0x000200f9, +0x00000ab8,0x000200f8,0x00000ab8,0x000700f5, +0x00000006,0x00001cfb,0x00000952,0x00000ab3, +0x00002198,0x00000ace,0x000700f5,0x00000006, +0x00001cfa,0x00000058,0x00000ab3,0x0000213c, +0x00000ace,0x000500b0,0x00000012,0x00000abc, +0x00001cfa,0x00001cfb,0x000400f6,0x00000acf, +0x00000ace,0x00000000,0x000400fa,0x00000abc, +0x00000abd,0x00000acf,0x000200f8,0x00000abd, +0x00050080,0x00000006,0x00000ac0,0x00001cfa, +0x00001cfb,0x000500c2,0x00000006,0x00000ac1, +0x00000ac0,0x00000063,0x00050084,0x00000006, +0x00000ac3,0x0000009e,0x00000ac1,0x00050051, +0x00000006,0x00000b0f,0x00000959,0x00000000, +0x00050084,0x00000006,0x00000b11,0x00000ac1, +0x0000034a,0x00050095,0x0000005e,0x00000b12, +0x00000b0f,0x00000b11,0x00050051,0x00000006, +0x00000b13,0x00000b12,0x00000001,0x00050051, +0x00000006,0x00000b14,0x00000b12,0x00000000, +0x00050051,0x00000006,0x00000b17,0x00000959, +0x00000001,0x00050080,0x00000006,0x00000b19, +0x00000b17,0x00000b13,0x00050050,0x00000007, +0x00000b1a,0x00000b14,0x00000b19,0x0004007c, +0x000000b1,0x00000b07,0x00000b1a,0x00060041, +0x000000b7,0x00000b08,0x00000b07,0x000000b6, +0x000000b6,0x0006003d,0x00000006,0x00000b09, +0x00000b08,0x00000002,0x00000004,0x00050080, +0x00000006,0x00000afc,0x00000ac3,0x00000063, +0x00050084,0x00000006,0x00000b2c,0x00000afc, +0x0000009e,0x00050095,0x0000005e,0x00000b2d, +0x00000b0f,0x00000b2c,0x00050051,0x00000006, +0x00000b2e,0x00000b2d,0x00000001,0x00050051, +0x00000006,0x00000b2f,0x00000b2d,0x00000000, +0x00050080,0x00000006,0x00000b34,0x00000b17, +0x00000b2e,0x00050050,0x00000007,0x00000b35, +0x00000b2f,0x00000b34,0x0004007c,0x000000b1, +0x00000b22,0x00000b35,0x00060041,0x000000b7, +0x00000b23,0x00000b22,0x000000b6,0x000000b6, +0x0006003d,0x00000006,0x00000b24,0x00000b23, +0x00000002,0x00000004,0x000500b0,0x00000012, +0x00000b3c,0x00000b24,0x00000af0,0x000400a8, +0x00000012,0x00000b3d,0x00000b3c,0x000300f7, +0x00000b4c,0x00000000,0x000400fa,0x00000b3d, +0x00000b3e,0x00000b4c,0x000200f8,0x00000b3e, +0x000500aa,0x00000012,0x00000b43,0x00000b24, +0x00000af0,0x000300f7,0x00000b4a,0x00000000, +0x000400fa,0x00000b43,0x00000b44,0x00000b4a, +0x000200f8,0x00000b44,0x000500b0,0x00000012, +0x00000b49,0x00000b09,0x00000ae8,0x000200f9, +0x00000b4a,0x000200f8,0x00000b4a,0x000700f5, +0x00000012,0x00000b4b,0x00000b43,0x00000b3e, +0x00000b49,0x00000b44,0x000200f9,0x00000b4c, +0x000200f8,0x00000b4c,0x000700f5,0x00000012, +0x00000b4d,0x00000b3c,0x00000abd,0x00000b4b, +0x00000b4a,0x000300f7,0x00000acd,0x00000000, +0x000400fa,0x00000b4d,0x00000ac8,0x00000acb, +0x000200f8,0x00000acb,0x000200f9,0x00000acd, +0x000200f8,0x00000ac8,0x00050080,0x00000006, +0x00000aca,0x00000ac1,0x00000063,0x000200f9, +0x00000acd,0x000200f8,0x00000acd,0x000700f5, +0x00000006,0x0000213c,0x00000aca,0x00000ac8, +0x00001cfa,0x00000acb,0x000600a9,0x00000006, +0x00002198,0x00000b4d,0x00001cfb,0x00000ac1, +0x000200f9,0x00000ace,0x000200f8,0x00000ace, +0x000200f9,0x00000ab8,0x000200f8,0x00000acf, +0x000500aa,0x00000012,0x00000ad1,0x00001cfa, +0x00000058,0x000300f7,0x00000ad3,0x00000000, +0x000400fa,0x00000ad1,0x00000ad2,0x00000ad3, +0x000200f8,0x00000ad2,0x000200f9,0x00000adc, +0x000200f8,0x00000ad3,0x00050082,0x00000006, +0x00000ad5,0x00001cfa,0x00000063,0x00050084, +0x00000006,0x00000ad6,0x0000009e,0x00000ad5, +0x00050080,0x00000006,0x00000ad7,0x00000ad6, +0x000000d8,0x00050051,0x00000006,0x00000b6b, +0x00000959,0x00000000,0x00050084,0x00000006, +0x00000b6d,0x00000ad7,0x0000009e,0x00050095, +0x0000005e,0x00000b6e,0x00000b6b,0x00000b6d, +0x00050051,0x00000006,0x00000b6f,0x00000b6e, +0x00000001,0x00050051,0x00000006,0x00000b70, +0x00000b6e,0x00000000,0x00050051,0x00000006, +0x00000b73,0x00000959,0x00000001,0x00050080, +0x00000006,0x00000b75,0x00000b73,0x00000b6f, +0x00050050,0x00000007,0x00000b76,0x00000b70, +0x00000b75,0x0004007c,0x000000b1,0x00000b63, +0x00000b76,0x00060041,0x000000b7,0x00000b64, +0x00000b63,0x000000b6,0x000000b6,0x0006003d, +0x00000006,0x00000b65,0x00000b64,0x00000002, +0x00000004,0x00050080,0x00000006,0x00000b58, +0x00000ad6,0x000000de,0x00050084,0x00000006, +0x00000b88,0x00000b58,0x0000009e,0x00050095, +0x0000005e,0x00000b89,0x00000b6b,0x00000b88, +0x00050051,0x00000006,0x00000b8a,0x00000b89, +0x00000001,0x00050051,0x00000006,0x00000b8b, +0x00000b89,0x00000000,0x00050080,0x00000006, +0x00000b90,0x00000b73,0x00000b8a,0x00050050, +0x00000007,0x00000b91,0x00000b8b,0x00000b90, +0x0004007c,0x000000b1,0x00000b7e,0x00000b91, +0x00060041,0x000000b7,0x00000b7f,0x00000b7e, +0x000000b6,0x000000b6,0x0006003d,0x00000006, +0x00000b80,0x00000b7f,0x00000002,0x00000004, +0x000500b0,0x00000012,0x00000b98,0x00000aeb, +0x00000b80,0x000400a8,0x00000012,0x00000b99, +0x00000b98,0x000300f7,0x00000ba8,0x00000000, +0x000400fa,0x00000b99,0x00000b9a,0x00000ba8, +0x000200f8,0x00000b9a,0x000500aa,0x00000012, +0x00000b9f,0x00000aeb,0x00000b80,0x000300f7, +0x00000ba6,0x00000000,0x000400fa,0x00000b9f, +0x00000ba0,0x00000ba6,0x000200f8,0x00000ba0, +0x000500b0,0x00000012,0x00000ba5,0x00000ae3, +0x00000b65,0x000200f9,0x00000ba6,0x000200f8, +0x00000ba6,0x000700f5,0x00000012,0x00000ba7, +0x00000b9f,0x00000b9a,0x00000ba5,0x00000ba0, +0x000200f9,0x00000ba8,0x000200f8,0x00000ba8, +0x000700f5,0x00000012,0x00000ba9,0x00000b98, +0x00000ad3,0x00000ba7,0x00000ba6,0x000200f9, +0x00000adc,0x000200f8,0x00000adc,0x000700f5, +0x00000012,0x00001cfc,0x0000011e,0x00000ad2, +0x00000ba9,0x00000ba8,0x000300f7,0x0000095f, +0x00000000,0x000400fa,0x00001cfc,0x0000095e, +0x0000095f,0x000200f8,0x0000095e,0x000200f9, +0x0000097b,0x000200f8,0x0000095f,0x00050051, +0x00000006,0x00000961,0x00000481,0x00000002, +0x000500c2,0x00000006,0x00000964,0x0000093d, +0x000000e4,0x000500aa,0x00000012,0x00000968, +0x00000961,0x00000058,0x000300f7,0x0000096d, +0x00000000,0x000400fa,0x00000968,0x00000969, +0x0000096d,0x000200f8,0x00000969,0x000500aa, +0x00000012,0x0000096c,0x00000964,0x00000058, +0x000200f9,0x0000096d,0x000200f8,0x0000096d, +0x000700f5,0x00000012,0x0000096e,0x00000968, +0x0000095f,0x0000096c,0x00000969,0x000400a8, +0x00000012,0x0000096f,0x0000096e,0x000300f7, +0x00000979,0x00000000,0x000400fa,0x0000096f, +0x00000970,0x00000979,0x000200f8,0x00000970, +0x000500c7,0x00000006,0x00000bb1,0x00000964, +0x0000017b,0x00050050,0x00000007,0x00000bb2, +0x00000961,0x00000bb1,0x000300f7,0x00000bbc, +0x00000000,0x000400fa,0x00000a92,0x00000bb7, +0x00000bbc,0x000200f8,0x00000bb7,0x000500c7, +0x00000006,0x00000bba,0x00000964,0x0000018b, +0x000500ab,0x00000012,0x00000bbb,0x00000bba, +0x00000058,0x000200f9,0x00000bbc,0x000200f8, +0x00000bbc,0x000700f5,0x00000012,0x00000bbd, +0x00000a92,0x00000970,0x00000bbb,0x00000bb7, +0x000300f7,0x00000bc3,0x00000000,0x000400fa, +0x00000bbd,0x00000bbe,0x00000bc3,0x000200f8, +0x00000bbe,0x000500c5,0x00000006,0x00000bc1, +0x00000bb1,0x00000191,0x00060052,0x00000007, +0x00001b33,0x00000bc1,0x00000bb2,0x00000001, +0x000200f9,0x00000bc3,0x000200f8,0x00000bc3, +0x000700f5,0x00000007,0x00001cfe,0x00000bb2, +0x00000bbc,0x00001b33,0x00000bbe,0x000300f7, +0x00000c00,0x00000000,0x000300fb,0x00000058, +0x00000bd7,0x000200f8,0x00000bd7,0x00050051, +0x00000006,0x00000c07,0x00001cfe,0x00000000, +0x00050095,0x0000005e,0x00000c0a,0x00000c07, +0x00000941,0x00050051,0x00000006,0x00000c0b, +0x00000c0a,0x00000001,0x00050051,0x00000006, +0x00000c0c,0x00000c0a,0x00000000,0x00050051, +0x00000006,0x00000c0f,0x00001cfe,0x00000001, +0x00050080,0x00000006,0x00000c14,0x00000c0f, +0x00000c0b,0x000200f9,0x00000bdc,0x000200f8, +0x00000bdc,0x000700f5,0x00000006,0x00001d00, +0x00000952,0x00000bd7,0x00002199,0x00000bf2, +0x000700f5,0x00000006,0x00001cff,0x00000058, +0x00000bd7,0x00002142,0x00000bf2,0x000500b0, +0x00000012,0x00000be0,0x00001cff,0x00001d00, +0x000400f6,0x00000bf3,0x00000bf2,0x00000000, +0x000400fa,0x00000be0,0x00000be1,0x00000bf3, +0x000200f8,0x00000be1,0x00050080,0x00000006, +0x00000be4,0x00001cff,0x00001d00,0x000500c2, +0x00000006,0x00000be5,0x00000be4,0x00000063, +0x00050084,0x00000006,0x00000be7,0x0000009e, +0x00000be5,0x00050051,0x00000006,0x00000c33, +0x00000959,0x00000000,0x00050084,0x00000006, +0x00000c35,0x00000be5,0x0000034a,0x00050095, +0x0000005e,0x00000c36,0x00000c33,0x00000c35, +0x00050051,0x00000006,0x00000c37,0x00000c36, +0x00000001,0x00050051,0x00000006,0x00000c38, +0x00000c36,0x00000000,0x00050051,0x00000006, +0x00000c3b,0x00000959,0x00000001,0x00050080, +0x00000006,0x00000c3d,0x00000c3b,0x00000c37, +0x00050050,0x00000007,0x00000c3e,0x00000c38, +0x00000c3d,0x0004007c,0x000000b1,0x00000c2b, +0x00000c3e,0x00060041,0x000000b7,0x00000c2c, +0x00000c2b,0x000000b6,0x000000b6,0x0006003d, +0x00000006,0x00000c2d,0x00000c2c,0x00000002, +0x00000004,0x00050080,0x00000006,0x00000c20, +0x00000be7,0x00000063,0x00050084,0x00000006, +0x00000c50,0x00000c20,0x0000009e,0x00050095, +0x0000005e,0x00000c51,0x00000c33,0x00000c50, +0x00050051,0x00000006,0x00000c52,0x00000c51, +0x00000001,0x00050051,0x00000006,0x00000c53, +0x00000c51,0x00000000,0x00050080,0x00000006, +0x00000c58,0x00000c3b,0x00000c52,0x00050050, +0x00000007,0x00000c59,0x00000c53,0x00000c58, +0x0004007c,0x000000b1,0x00000c46,0x00000c59, +0x00060041,0x000000b7,0x00000c47,0x00000c46, +0x000000b6,0x000000b6,0x0006003d,0x00000006, +0x00000c48,0x00000c47,0x00000002,0x00000004, +0x000500b0,0x00000012,0x00000c60,0x00000c48, +0x00000c14,0x000400a8,0x00000012,0x00000c61, +0x00000c60,0x000300f7,0x00000c70,0x00000000, +0x000400fa,0x00000c61,0x00000c62,0x00000c70, +0x000200f8,0x00000c62,0x000500aa,0x00000012, +0x00000c67,0x00000c48,0x00000c14,0x000300f7, +0x00000c6e,0x00000000,0x000400fa,0x00000c67, +0x00000c68,0x00000c6e,0x000200f8,0x00000c68, +0x000500b0,0x00000012,0x00000c6d,0x00000c2d, +0x00000c0c,0x000200f9,0x00000c6e,0x000200f8, +0x00000c6e,0x000700f5,0x00000012,0x00000c6f, +0x00000c67,0x00000c62,0x00000c6d,0x00000c68, +0x000200f9,0x00000c70,0x000200f8,0x00000c70, +0x000700f5,0x00000012,0x00000c71,0x00000c60, +0x00000be1,0x00000c6f,0x00000c6e,0x000300f7, +0x00000bf1,0x00000000,0x000400fa,0x00000c71, +0x00000bec,0x00000bef,0x000200f8,0x00000bef, +0x000200f9,0x00000bf1,0x000200f8,0x00000bec, +0x00050080,0x00000006,0x00000bee,0x00000be5, +0x00000063,0x000200f9,0x00000bf1,0x000200f8, +0x00000bf1,0x000700f5,0x00000006,0x00002142, +0x00000bee,0x00000bec,0x00001cff,0x00000bef, +0x000600a9,0x00000006,0x00002199,0x00000c71, +0x00001d00,0x00000be5,0x000200f9,0x00000bf2, +0x000200f8,0x00000bf2,0x000200f9,0x00000bdc, +0x000200f8,0x00000bf3,0x000500aa,0x00000012, +0x00000bf5,0x00001cff,0x00000058,0x000300f7, +0x00000bf7,0x00000000,0x000400fa,0x00000bf5, +0x00000bf6,0x00000bf7,0x000200f8,0x00000bf6, +0x000200f9,0x00000c00,0x000200f8,0x00000bf7, +0x00050082,0x00000006,0x00000bf9,0x00001cff, +0x00000063,0x00050084,0x00000006,0x00000bfa, +0x0000009e,0x00000bf9,0x00050080,0x00000006, +0x00000bfb,0x00000bfa,0x000000d8,0x00050051, +0x00000006,0x00000c8f,0x00000959,0x00000000, +0x00050084,0x00000006,0x00000c91,0x00000bfb, +0x0000009e,0x00050095,0x0000005e,0x00000c92, +0x00000c8f,0x00000c91,0x00050051,0x00000006, +0x00000c93,0x00000c92,0x00000001,0x00050051, +0x00000006,0x00000c94,0x00000c92,0x00000000, +0x00050051,0x00000006,0x00000c97,0x00000959, +0x00000001,0x00050080,0x00000006,0x00000c99, +0x00000c97,0x00000c93,0x00050050,0x00000007, +0x00000c9a,0x00000c94,0x00000c99,0x0004007c, +0x000000b1,0x00000c87,0x00000c9a,0x00060041, +0x000000b7,0x00000c88,0x00000c87,0x000000b6, +0x000000b6,0x0006003d,0x00000006,0x00000c89, +0x00000c88,0x00000002,0x00000004,0x00050080, +0x00000006,0x00000c7c,0x00000bfa,0x000000de, +0x00050084,0x00000006,0x00000cac,0x00000c7c, +0x0000009e,0x00050095,0x0000005e,0x00000cad, +0x00000c8f,0x00000cac,0x00050051,0x00000006, +0x00000cae,0x00000cad,0x00000001,0x00050051, +0x00000006,0x00000caf,0x00000cad,0x00000000, +0x00050080,0x00000006,0x00000cb4,0x00000c97, +0x00000cae,0x00050050,0x00000007,0x00000cb5, +0x00000caf,0x00000cb4,0x0004007c,0x000000b1, +0x00000ca2,0x00000cb5,0x00060041,0x000000b7, +0x00000ca3,0x00000ca2,0x000000b6,0x000000b6, +0x0006003d,0x00000006,0x00000ca4,0x00000ca3, +0x00000002,0x00000004,0x000500b0,0x00000012, +0x00000cbc,0x00000c0f,0x00000ca4,0x000400a8, +0x00000012,0x00000cbd,0x00000cbc,0x000300f7, +0x00000ccc,0x00000000,0x000400fa,0x00000cbd, +0x00000cbe,0x00000ccc,0x000200f8,0x00000cbe, +0x000500aa,0x00000012,0x00000cc3,0x00000c0f, +0x00000ca4,0x000300f7,0x00000cca,0x00000000, +0x000400fa,0x00000cc3,0x00000cc4,0x00000cca, +0x000200f8,0x00000cc4,0x000500b0,0x00000012, +0x00000cc9,0x00000c07,0x00000c89,0x000200f9, +0x00000cca,0x000200f8,0x00000cca,0x000700f5, +0x00000012,0x00000ccb,0x00000cc3,0x00000cbe, +0x00000cc9,0x00000cc4,0x000200f9,0x00000ccc, +0x000200f8,0x00000ccc,0x000700f5,0x00000012, +0x00000ccd,0x00000cbc,0x00000bf7,0x00000ccb, +0x00000cca,0x000200f9,0x00000c00,0x000200f8, +0x00000c00,0x000700f5,0x00000012,0x00001d01, +0x0000011e,0x00000bf6,0x00000ccd,0x00000ccc, +0x000200f9,0x00000979,0x000200f8,0x00000979, +0x000700f5,0x00000012,0x0000097a,0x0000096f, +0x0000096d,0x00001d01,0x00000c00,0x000200f9, +0x0000097b,0x000200f8,0x0000097b,0x000d00f5, +0x00000012,0x00001d02,0x0000011e,0x00000938, +0x00000217,0x0000094f,0x0000011e,0x00000954, +0x00000217,0x0000095e,0x0000097a,0x00000979, +0x000400a8,0x00000012,0x00000483,0x00001d02, +0x000200f9,0x0000047a,0x000200f8,0x0000047a, +0x000700f5,0x00000012,0x00000484,0x00000478, +0x000005c0,0x00000483,0x0000097b,0x000300f7, +0x00000486,0x00000000,0x000400fa,0x00000484, +0x00000485,0x00000486,0x000200f8,0x00000485, +0x000200f9,0x00000518,0x000200f8,0x00000486, +0x000200f9,0x00000467,0x000200f8,0x00000467, +0x00050041,0x0000020a,0x00000489,0x00000180, +0x000000b6,0x0004003d,0x00000007,0x0000048a, +0x00000489,0x0004007c,0x00000468,0x0000048b, +0x0000048a,0x00050084,0x00000006,0x0000048f, +0x000000d8,0x0000044f,0x00060041,0x00000474, +0x00000490,0x0000048b,0x000000b6,0x0000048f, +0x0006003d,0x00000027,0x00000491,0x00000490, +0x00000002,0x00000010,0x00050080,0x00000006, +0x00000496,0x0000048f,0x00000063,0x00060041, +0x00000474,0x00000497,0x0000048b,0x000000b6, +0x00000496,0x0006003d,0x00000027,0x00000498, +0x00000497,0x00000002,0x00000010,0x000300f7, +0x0000049b,0x00000000,0x000400fa,0x0000043a, +0x0000049a,0x0000049b,0x000200f8,0x0000049a, +0x00050051,0x00000006,0x0000049d,0x00000491, +0x00000003,0x000500c2,0x00000006,0x0000049e, +0x0000049d,0x0000019b,0x000500ab,0x00000012, +0x0000049f,0x0000049e,0x00000058,0x000200f9, +0x0000049b,0x000200f8,0x0000049b,0x000700f5, +0x00000012,0x000004a0,0x0000043a,0x00000467, +0x0000049f,0x0000049a,0x000300f7,0x000004a2, +0x00000000,0x000400fa,0x000004a0,0x000004a1, +0x000004a2,0x000200f8,0x000004a1,0x000200f9, +0x00000518,0x000200f8,0x000004a2,0x000500c2, +0x00000006,0x000004a6,0x00001ce6,0x000004a5, +0x000500ab,0x00000012,0x000004a7,0x000004a6, +0x00000058,0x000300f7,0x000004a9,0x00000000, +0x000400fa,0x000004a7,0x000004a8,0x000004a9, +0x000200f8,0x000004a8,0x00050051,0x00000006, +0x000004ab,0x00000491,0x00000003,0x000500c2, +0x00000006,0x000004ac,0x000004ab,0x0000019b, +0x000500ab,0x00000012,0x000004ad,0x000004ac, +0x00000058,0x000200f9,0x000004a9,0x000200f8, +0x000004a9,0x000700f5,0x00000012,0x000004ae, +0x000004a7,0x000004a2,0x000004ad,0x000004a8, +0x00070050,0x0000219a,0x0000219b,0x000004ae, +0x000004ae,0x000004ae,0x000004ae,0x000600a9, +0x00000027,0x0000219c,0x0000219b,0x000001a7, +0x00000491,0x00050051,0x00000006,0x000004b6, +0x0000219c,0x00000003,0x000500c2,0x00000006, +0x000004b7,0x000004b6,0x0000019b,0x000500aa, +0x00000012,0x000004b8,0x000004b7,0x00000058, +0x000300f7,0x000004ba,0x00000000,0x000400fa, +0x000004b8,0x000004b9,0x000004ba,0x000200f8, +0x000004b9,0x000300f7,0x00000e39,0x00000000, +0x000300fb,0x00000058,0x00000d15,0x000200f8, +0x00000d15,0x000500ab,0x00000012,0x00000d19, +0x000004b7,0x00000058,0x000400a8,0x00000012, +0x00000d1a,0x00000d19,0x000300f7,0x00000d1f, +0x00000000,0x000400fa,0x00000d1a,0x00000d1b, +0x00000d1f,0x000200f8,0x00000d1b,0x00050051, +0x00000006,0x00000d1d,0x0000219c,0x00000002, +0x000500aa,0x00000012,0x00000d1e,0x00000d1d, +0x00000058,0x000200f9,0x00000d1f,0x000200f8, +0x00000d1f,0x000700f5,0x00000012,0x00000d20, +0x00000d19,0x00000d15,0x00000d1e,0x00000d1b, +0x000300f7,0x00000d22,0x00000000,0x000400fa, +0x00000d20,0x00000d21,0x00000d22,0x000200f8, +0x00000d21,0x000200f9,0x00000e39,0x000200f8, +0x00000d22,0x00050051,0x00000006,0x00000d24, +0x0000219c,0x00000000,0x00050051,0x00000006, +0x00000d26,0x0000219c,0x00000001,0x000500c7, +0x00000006,0x00000d27,0x00000d26,0x0000017b, +0x00050050,0x00000007,0x00000d28,0x00000d24, +0x00000d27,0x000500aa,0x00000012,0x00000d2b, +0x00000d24,0x00000058,0x000300f7,0x00000d30, +0x00000000,0x000400fa,0x00000d2b,0x00000d2c, +0x00000d30,0x000200f8,0x00000d2c,0x000500aa, +0x00000012,0x00000d2f,0x00000d27,0x00000058, +0x000200f9,0x00000d30,0x000200f8,0x00000d30, +0x000700f5,0x00000012,0x00000d31,0x00000d2b, +0x00000d22,0x00000d2f,0x00000d2c,0x000300f7, +0x00000d36,0x00000000,0x000400fa,0x00000d31, +0x00000d32,0x00000d36,0x000200f8,0x00000d32, +0x00060052,0x00000027,0x00001b56,0x00000058, +0x0000219c,0x00000000,0x00060052,0x00000027, +0x00001b58,0x00000058,0x00001b56,0x00000001, +0x00060052,0x00000027,0x00001b5a,0x00000058, +0x00001b58,0x00000002,0x000200f9,0x00000e39, +0x000200f8,0x00000d36,0x000500c2,0x00000006, +0x00000d39,0x00000d26,0x000000e4,0x000500c7, +0x00000006,0x00000d3a,0x00000d39,0x000001ad, +0x00050051,0x00000006,0x00000d3c,0x0000219c, +0x00000002,0x000500aa,0x00000012,0x00000d3e, +0x00000d3a,0x00000058,0x000600a9,0x00000006, +0x00000d40,0x00000d3e,0x00000063,0x00000d3a, +0x00050097,0x0000005e,0x00000d43,0x00000d3c, +0x00000d40,0x00050051,0x00000006,0x00000d44, +0x00000d43,0x00000000,0x00050051,0x00000006, +0x00000d45,0x00000d43,0x00000001,0x00050050, +0x00000007,0x0000218e,0x00000d44,0x00000d45, +0x00050041,0x00000182,0x00000d46,0x00000180, +0x0000029a,0x0004003d,0x00000006,0x00000d47, +0x00000d46,0x000200f9,0x00000d48,0x000200f8, +0x00000d48,0x000700f5,0x00000006,0x00001d55, +0x00000d47,0x00000d36,0x0000219d,0x00000d5f, +0x000700f5,0x00000006,0x00001d54,0x00000058, +0x00000d36,0x00002148,0x00000d5f,0x000500b0, +0x00000012,0x00000d4c,0x00001d54,0x00001d55, +0x000400f6,0x00000d60,0x00000d5f,0x00000000, +0x000400fa,0x00000d4c,0x00000d4d,0x00000d60, +0x000200f8,0x00000d4d,0x00050080,0x00000006, +0x00000d50,0x00001d54,0x00001d55,0x000500c2, +0x00000006,0x00000d51,0x00000d50,0x00000063, +0x00050084,0x00000006,0x00000d53,0x000002ab, +0x00000d51,0x00050041,0x0000020a,0x00000d54, +0x00000180,0x000002aa,0x0004003d,0x00000007, +0x00000d55,0x00000d54,0x00050051,0x00000006, +0x00000e5c,0x00000d55,0x00000000,0x00050084, +0x00000006,0x00000e5e,0x00000d51,0x0000218f, +0x00050095,0x0000005e,0x00000e5f,0x00000e5c, +0x00000e5e,0x00050051,0x00000006,0x00000e60, +0x00000e5f,0x00000001,0x00050051,0x00000006, +0x00000e61,0x00000e5f,0x00000000,0x00050051, +0x00000006,0x00000e64,0x00000d55,0x00000001, +0x00050080,0x00000006,0x00000e66,0x00000e64, +0x00000e60,0x00050050,0x00000007,0x00000e67, +0x00000e61,0x00000e66,0x0004007c,0x000000b1, +0x00000e54,0x00000e67,0x00060041,0x000000b7, +0x00000e55,0x00000e54,0x000000b6,0x000000b6, +0x0006003d,0x00000006,0x00000e56,0x00000e55, +0x00000002,0x00000004,0x00050080,0x00000006, +0x00000e49,0x00000d53,0x00000063,0x00050084, +0x00000006,0x00000e79,0x00000e49,0x0000009e, +0x00050095,0x0000005e,0x00000e7a,0x00000e5c, +0x00000e79,0x00050051,0x00000006,0x00000e7b, +0x00000e7a,0x00000001,0x00050051,0x00000006, +0x00000e7c,0x00000e7a,0x00000000,0x00050080, +0x00000006,0x00000e81,0x00000e64,0x00000e7b, +0x00050050,0x00000007,0x00000e82,0x00000e7c, +0x00000e81,0x0004007c,0x000000b1,0x00000e6f, +0x00000e82,0x00060041,0x000000b7,0x00000e70, +0x00000e6f,0x000000b6,0x000000b6,0x0006003d, +0x00000006,0x00000e71,0x00000e70,0x00000002, +0x00000004,0x000500b0,0x00000012,0x00000e89, +0x00000d27,0x00000e71,0x000400a8,0x00000012, +0x00000e8a,0x00000e89,0x000300f7,0x00000e99, +0x00000000,0x000400fa,0x00000e8a,0x00000e8b, +0x00000e99,0x000200f8,0x00000e8b,0x000500aa, +0x00000012,0x00000e90,0x00000d27,0x00000e71, +0x000300f7,0x00000e97,0x00000000,0x000400fa, +0x00000e90,0x00000e91,0x00000e97,0x000200f8, +0x00000e91,0x000500b0,0x00000012,0x00000e96, +0x00000d24,0x00000e56,0x000200f9,0x00000e97, +0x000200f8,0x00000e97,0x000700f5,0x00000012, +0x00000e98,0x00000e90,0x00000e8b,0x00000e96, +0x00000e91,0x000200f9,0x00000e99,0x000200f8, +0x00000e99,0x000700f5,0x00000012,0x00000e9a, +0x00000e89,0x00000d4d,0x00000e98,0x00000e97, +0x000300f7,0x00000d5e,0x00000000,0x000400fa, +0x00000e9a,0x00000d59,0x00000d5b,0x000200f8, +0x00000d5b,0x00050080,0x00000006,0x00000d5d, +0x00000d51,0x00000063,0x000200f9,0x00000d5e, +0x000200f8,0x00000d59,0x000200f9,0x00000d5e, +0x000200f8,0x00000d5e,0x000700f5,0x00000006, +0x00002148,0x00001d54,0x00000d59,0x00000d5d, +0x00000d5b,0x000600a9,0x00000006,0x0000219d, +0x00000e9a,0x00000d51,0x00001d55,0x000200f9, +0x00000d5f,0x000200f8,0x00000d5f,0x000200f9, +0x00000d48,0x000200f8,0x00000d60,0x000500ac, +0x00000012,0x00000d62,0x00001d54,0x00000058, +0x000300f7,0x00000d96,0x00000000,0x000400fa, +0x00000d62,0x00000d63,0x00000d96,0x000200f8, +0x00000d63,0x00050082,0x00000006,0x00000d65, +0x00001d54,0x00000063,0x00050084,0x00000006, +0x00000d66,0x000002ab,0x00000d65,0x00050080, +0x00000006,0x00000d68,0x00000d66,0x000000d8, +0x00050041,0x0000020a,0x00000d69,0x00000180, +0x000002aa,0x0004003d,0x00000007,0x00000d6a, +0x00000d69,0x00050051,0x00000006,0x00000eb8, +0x00000d6a,0x00000000,0x00050084,0x00000006, +0x00000eba,0x00000d68,0x0000009e,0x00050095, +0x0000005e,0x00000ebb,0x00000eb8,0x00000eba, +0x00050051,0x00000006,0x00000ebc,0x00000ebb, +0x00000001,0x00050051,0x00000006,0x00000ebd, +0x00000ebb,0x00000000,0x00050051,0x00000006, +0x00000ec0,0x00000d6a,0x00000001,0x00050080, +0x00000006,0x00000ec2,0x00000ec0,0x00000ebc, +0x00050050,0x00000007,0x00000ec3,0x00000ebd, +0x00000ec2,0x0004007c,0x000000b1,0x00000eb0, +0x00000ec3,0x00060041,0x000000b7,0x00000eb1, +0x00000eb0,0x000000b6,0x000000b6,0x0006003d, +0x00000006,0x00000eb2,0x00000eb1,0x00000002, +0x00000004,0x00050080,0x00000006,0x00000ea5, +0x00000d66,0x000000de,0x00050084,0x00000006, +0x00000ed5,0x00000ea5,0x0000009e,0x00050095, +0x0000005e,0x00000ed6,0x00000eb8,0x00000ed5, +0x00050051,0x00000006,0x00000ed7,0x00000ed6, +0x00000001,0x00050051,0x00000006,0x00000ed8, +0x00000ed6,0x00000000,0x00050080,0x00000006, +0x00000edd,0x00000ec0,0x00000ed7,0x00050050, +0x00000007,0x00000ede,0x00000ed8,0x00000edd, +0x0004007c,0x000000b1,0x00000ecb,0x00000ede, +0x00060041,0x000000b7,0x00000ecc,0x00000ecb, +0x000000b6,0x000000b6,0x0006003d,0x00000006, +0x00000ecd,0x00000ecc,0x00000002,0x00000004, +0x000500b0,0x00000012,0x00000ee5,0x00000d27, +0x00000ecd,0x000400a8,0x00000012,0x00000ee6, +0x00000ee5,0x000300f7,0x00000ef5,0x00000000, +0x000400fa,0x00000ee6,0x00000ee7,0x00000ef5, +0x000200f8,0x00000ee7,0x000500aa,0x00000012, +0x00000eec,0x00000d27,0x00000ecd,0x000300f7, +0x00000ef3,0x00000000,0x000400fa,0x00000eec, +0x00000eed,0x00000ef3,0x000200f8,0x00000eed, +0x000500b0,0x00000012,0x00000ef2,0x00000d24, +0x00000eb2,0x000200f9,0x00000ef3,0x000200f8, +0x00000ef3,0x000700f5,0x00000012,0x00000ef4, +0x00000eec,0x00000ee7,0x00000ef2,0x00000eed, +0x000200f9,0x00000ef5,0x000200f8,0x00000ef5, +0x000700f5,0x00000012,0x00000ef6,0x00000ee5, +0x00000d63,0x00000ef4,0x00000ef3,0x000300f7, +0x00000d77,0x00000000,0x000400fa,0x00000ef6, +0x00000d6f,0x00000d77,0x000200f8,0x00000d6f, +0x00050080,0x00000006,0x00000d71,0x00000d66, +0x000002d5,0x00050084,0x00000006,0x00000f08, +0x00000d71,0x0000009e,0x00050095,0x0000005e, +0x00000f09,0x00000eb8,0x00000f08,0x00050051, +0x00000006,0x00000f0a,0x00000f09,0x00000001, +0x00050051,0x00000006,0x00000f0b,0x00000f09, +0x00000000,0x00050080,0x00000006,0x00000f10, +0x00000ec0,0x00000f0a,0x00050050,0x00000007, +0x00000f11,0x00000f0b,0x00000f10,0x0004007c, +0x000000b1,0x00000efe,0x00000f11,0x00060041, +0x000000b7,0x00000eff,0x00000efe,0x000000b6, +0x000000b6,0x0006003d,0x00000006,0x00000f00, +0x00000eff,0x00000002,0x00000004,0x000500c7, +0x00000006,0x00000d75,0x00000f00,0x00000063, +0x000500ab,0x00000012,0x00000d76,0x00000d75, +0x00000058,0x000200f9,0x00000d77,0x000200f8, +0x00000d77,0x000700f5,0x00000012,0x00000d78, +0x00000ef6,0x00000ef5,0x00000d76,0x00000d6f, +0x000300f7,0x00000d95,0x00000000,0x000400fa, +0x00000d78,0x00000d79,0x00000d95,0x000200f8, +0x00000d79,0x00050096,0x0000005e,0x00000f1a, +0x00000eb2,0x00000d24,0x00050051,0x00000006, +0x00000f1b,0x00000f1a,0x00000001,0x00050051, +0x00000006,0x00000f1c,0x00000f1a,0x00000000, +0x00050082,0x00000006,0x00000f22,0x00000ecd, +0x00000d27,0x00050082,0x00000006,0x00000f24, +0x00000f22,0x00000f1b,0x000500b0,0x00000012, +0x00000f2c,0x00000f24,0x00000d45,0x000400a8, +0x00000012,0x00000f2d,0x00000f2c,0x000300f7, +0x00000f3c,0x00000000,0x000400fa,0x00000f2d, +0x00000f2e,0x00000f3c,0x000200f8,0x00000f2e, +0x000500aa,0x00000012,0x00000f33,0x00000f24, +0x00000d45,0x000300f7,0x00000f3a,0x00000000, +0x000400fa,0x00000f33,0x00000f34,0x00000f3a, +0x000200f8,0x00000f34,0x000500b0,0x00000012, +0x00000f39,0x00000f1c,0x00000d44,0x000200f9, +0x00000f3a,0x000200f8,0x00000f3a,0x000700f5, +0x00000012,0x00000f3b,0x00000f33,0x00000f2e, +0x00000f39,0x00000f34,0x000200f9,0x00000f3c, +0x000200f8,0x00000f3c,0x000700f5,0x00000012, +0x00000f3d,0x00000f2c,0x00000d79,0x00000f3b, +0x00000f3a,0x000300f7,0x00000d94,0x00000000, +0x000400fa,0x00000f3d,0x00000d7f,0x00000d83, +0x000200f8,0x00000d83,0x00050084,0x00000006, +0x00000f61,0x00000d65,0x0000218f,0x00050095, +0x0000005e,0x00000f62,0x00000eb8,0x00000f61, +0x00050051,0x00000006,0x00000f63,0x00000f62, +0x00000001,0x00050051,0x00000006,0x00000f64, +0x00000f62,0x00000000,0x00050080,0x00000006, +0x00000f69,0x00000ec0,0x00000f63,0x00050050, +0x00000007,0x00000f6a,0x00000f64,0x00000f69, +0x0004007c,0x000000b1,0x00000f57,0x00000f6a, +0x00060041,0x000000b7,0x00000f58,0x00000f57, +0x000000b6,0x000000b6,0x0006003d,0x00000006, +0x00000f59,0x00000f58,0x00000002,0x00000004, +0x00050080,0x00000006,0x00000f4c,0x00000d66, +0x00000063,0x00050084,0x00000006,0x00000f7c, +0x00000f4c,0x0000009e,0x00050095,0x0000005e, +0x00000f7d,0x00000eb8,0x00000f7c,0x00050051, +0x00000006,0x00000f7e,0x00000f7d,0x00000001, +0x00050051,0x00000006,0x00000f7f,0x00000f7d, +0x00000000,0x00050080,0x00000006,0x00000f84, +0x00000ec0,0x00000f7e,0x00050050,0x00000007, +0x00000f85,0x00000f7f,0x00000f84,0x0004007c, +0x000000b1,0x00000f72,0x00000f85,0x00060041, +0x000000b7,0x00000f73,0x00000f72,0x000000b6, +0x000000b6,0x0006003d,0x00000006,0x00000f74, +0x00000f73,0x00000002,0x00000004,0x00050080, +0x00000006,0x00000d89,0x00000d66,0x0000009e, +0x00050084,0x00000006,0x00000fa5,0x00000d89, +0x0000009e,0x00050095,0x0000005e,0x00000fa6, +0x00000eb8,0x00000fa5,0x00050051,0x00000006, +0x00000fa7,0x00000fa6,0x00000001,0x00050051, +0x00000006,0x00000fa8,0x00000fa6,0x00000000, +0x00050080,0x00000006,0x00000fad,0x00000ec0, +0x00000fa7,0x00050050,0x00000007,0x00000fae, +0x00000fa8,0x00000fad,0x0004007c,0x000000b1, +0x00000f9b,0x00000fae,0x00060041,0x000000b7, +0x00000f9c,0x00000f9b,0x000000b6,0x000000b6, +0x0006003d,0x00000006,0x00000f9d,0x00000f9c, +0x00000002,0x00000004,0x00050080,0x00000006, +0x00000f90,0x00000d66,0x00000357,0x00050084, +0x00000006,0x00000fc0,0x00000f90,0x0000009e, +0x00050095,0x0000005e,0x00000fc1,0x00000eb8, +0x00000fc0,0x00050051,0x00000006,0x00000fc2, +0x00000fc1,0x00000001,0x00050051,0x00000006, +0x00000fc3,0x00000fc1,0x00000000,0x00050080, +0x00000006,0x00000fc8,0x00000ec0,0x00000fc2, +0x00050050,0x00000007,0x00000fc9,0x00000fc3, +0x00000fc8,0x0004007c,0x000000b1,0x00000fb6, +0x00000fc9,0x00060041,0x000000b7,0x00000fb7, +0x00000fb6,0x000000b6,0x000000b6,0x0006003d, +0x00000006,0x00000fb8,0x00000fb7,0x00000002, +0x00000004,0x00050096,0x0000005e,0x00000fd2, +0x00000d24,0x00000f59,0x00050051,0x00000006, +0x00000fd3,0x00000fd2,0x00000001,0x00050051, +0x00000006,0x00000fd4,0x00000fd2,0x00000000, +0x00050082,0x00000006,0x00000fda,0x00000d27, +0x00000f74,0x00050082,0x00000006,0x00000fdc, +0x00000fda,0x00000fd3,0x00050095,0x0000005e, +0x00000fe6,0x00000f9d,0x00000fd4,0x00050051, +0x00000006,0x00000fe7,0x00000fe6,0x00000001, +0x00050051,0x00000006,0x00000fe8,0x00000fe6, +0x00000000,0x00050080,0x00000006,0x00000fee, +0x00000fb8,0x00000fdc,0x00050080,0x00000006, +0x00000ff0,0x00000fee,0x00000fe7,0x00060052, +0x00000027,0x00001b99,0x00000fe8,0x0000219c, +0x00000000,0x000500c7,0x00000006,0x00000ff8, +0x00000d26,0x00000191,0x000500c7,0x00000006, +0x00000ffb,0x00000ff0,0x0000017b,0x000500c5, +0x00000006,0x00000ffc,0x00000ff8,0x00000ffb, +0x00060052,0x00000027,0x00001b9d,0x00000ffc, +0x00001b99,0x00000001,0x000200f9,0x00000d94, +0x000200f8,0x00000d7f,0x00060052,0x00000027, +0x00001b82,0x00000058,0x0000219c,0x00000000, +0x00060052,0x00000027,0x00001b84,0x00000058, +0x00001b82,0x00000001,0x00060052,0x00000027, +0x00001b86,0x00000058,0x00001b84,0x00000002, +0x000200f9,0x00000d94,0x000200f8,0x00000d94, +0x000700f5,0x00000027,0x00001df7,0x00001b86, +0x00000d7f,0x00001b9d,0x00000d83,0x000200f9, +0x00000e39,0x000200f8,0x00000d95,0x000200f9, +0x00000d96,0x000200f8,0x00000d96,0x000500c7, +0x00000006,0x00000d9a,0x00000438,0x00000063, +0x000500ab,0x00000012,0x00000d9b,0x00000d9a, +0x00000058,0x000300f7,0x00000da1,0x00000000, +0x000400fa,0x00000d9b,0x00000d9c,0x00000da1, +0x000200f8,0x00000d9c,0x000500c7,0x00000006, +0x00000d9f,0x00000d26,0x0000018b,0x000500ab, +0x00000012,0x00000da0,0x00000d9f,0x00000058, +0x000200f9,0x00000da1,0x000200f8,0x00000da1, +0x000700f5,0x00000012,0x00000da2,0x00000d9b, +0x00000d96,0x00000da0,0x00000d9c,0x000300f7, +0x00000da8,0x00000000,0x000400fa,0x00000da2, +0x00000da3,0x00000da8,0x000200f8,0x00000da3, +0x000500c5,0x00000006,0x00000da6,0x00000d27, +0x00000191,0x00060052,0x00000007,0x00001ba1, +0x00000da6,0x00000d28,0x00000001,0x000200f9, +0x00000da8,0x000200f8,0x00000da8,0x000700f5, +0x00000007,0x00001d58,0x00000d28,0x00000da1, +0x00001ba1,0x00000da3,0x00050041,0x00000182, +0x00000da9,0x00000180,0x000000e4,0x0004003d, +0x00000006,0x00000daa,0x00000da9,0x000500ab, +0x00000012,0x00000dab,0x00000daa,0x00000058, +0x000300f7,0x00000dbe,0x00000000,0x000400fa, +0x00000dab,0x00000dac,0x00000dbe,0x000200f8, +0x00000dac,0x000500aa,0x00000012,0x00000daf, +0x00000d44,0x00000058,0x000300f7,0x00000db4, +0x00000000,0x000400fa,0x00000daf,0x00000db0, +0x00000db4,0x000200f8,0x00000db0,0x000500aa, +0x00000012,0x00000db3,0x00000d45,0x00000058, +0x000200f9,0x00000db4,0x000200f8,0x00000db4, +0x000700f5,0x00000012,0x00000db5,0x00000daf, +0x00000dac,0x00000db3,0x00000db0,0x000600a9, +0x00000007,0x00000db7,0x00000db5,0x00000208, +0x0000218e,0x00050041,0x0000020a,0x00000db8, +0x00000180,0x00000325,0x0004003d,0x00000007, +0x00000db9,0x00000db8,0x000300f7,0x00001042, +0x00000000,0x000300fb,0x00000058,0x00001012, +0x000200f8,0x00001012,0x000200f9,0x00001014, +0x000200f8,0x00001014,0x000700f5,0x00000006, +0x00001d5a,0x00000daa,0x00001012,0x0000219e, +0x0000102a,0x000700f5,0x00000006,0x00001d59, +0x00000058,0x00001012,0x0000214e,0x0000102a, +0x000500b0,0x00000012,0x00001018,0x00001d59, +0x00001d5a,0x000400f6,0x0000102b,0x0000102a, +0x00000000,0x000400fa,0x00001018,0x00001019, +0x0000102b,0x000200f8,0x00001019,0x00050080, +0x00000006,0x0000101c,0x00001d59,0x00001d5a, +0x000500c2,0x00000006,0x0000101d,0x0000101c, +0x00000063,0x00050084,0x00000006,0x0000101f, +0x0000009e,0x0000101d,0x00050051,0x00000006, +0x00001061,0x00000db9,0x00000000,0x00050084, +0x00000006,0x00001063,0x0000101d,0x0000034a, +0x00050095,0x0000005e,0x00001064,0x00001061, +0x00001063,0x00050051,0x00000006,0x00001065, +0x00001064,0x00000001,0x00050051,0x00000006, +0x00001066,0x00001064,0x00000000,0x00050051, +0x00000006,0x00001069,0x00000db9,0x00000001, +0x00050080,0x00000006,0x0000106b,0x00001069, +0x00001065,0x00050050,0x00000007,0x0000106c, +0x00001066,0x0000106b,0x0004007c,0x000000b1, +0x00001059,0x0000106c,0x00060041,0x000000b7, +0x0000105a,0x00001059,0x000000b6,0x000000b6, +0x0006003d,0x00000006,0x0000105b,0x0000105a, +0x00000002,0x00000004,0x00050080,0x00000006, +0x0000104e,0x0000101f,0x00000063,0x00050084, +0x00000006,0x0000107e,0x0000104e,0x0000009e, +0x00050095,0x0000005e,0x0000107f,0x00001061, +0x0000107e,0x00050051,0x00000006,0x00001080, +0x0000107f,0x00000001,0x00050051,0x00000006, +0x00001081,0x0000107f,0x00000000,0x00050080, +0x00000006,0x00001086,0x00001069,0x00001080, +0x00050050,0x00000007,0x00001087,0x00001081, +0x00001086,0x0004007c,0x000000b1,0x00001074, +0x00001087,0x00060041,0x000000b7,0x00001075, +0x00001074,0x000000b6,0x000000b6,0x0006003d, +0x00000006,0x00001076,0x00001075,0x00000002, +0x00000004,0x00050051,0x00000006,0x0000108b, +0x00001d58,0x00000001,0x000500b0,0x00000012, +0x0000108e,0x0000108b,0x00001076,0x000400a8, +0x00000012,0x0000108f,0x0000108e,0x000300f7, +0x0000109e,0x00000000,0x000400fa,0x0000108f, +0x00001090,0x0000109e,0x000200f8,0x00001090, +0x000500aa,0x00000012,0x00001095,0x0000108b, +0x00001076,0x000300f7,0x0000109c,0x00000000, +0x000400fa,0x00001095,0x00001096,0x0000109c, +0x000200f8,0x00001096,0x00050051,0x00000006, +0x00001098,0x00001d58,0x00000000,0x000500b0, +0x00000012,0x0000109b,0x00001098,0x0000105b, +0x000200f9,0x0000109c,0x000200f8,0x0000109c, +0x000700f5,0x00000012,0x0000109d,0x00001095, +0x00001090,0x0000109b,0x00001096,0x000200f9, +0x0000109e,0x000200f8,0x0000109e,0x000700f5, +0x00000012,0x0000109f,0x0000108e,0x00001019, +0x0000109d,0x0000109c,0x000300f7,0x00001029, +0x00000000,0x000400fa,0x0000109f,0x00001024, +0x00001026,0x000200f8,0x00001026,0x00050080, +0x00000006,0x00001028,0x0000101d,0x00000063, +0x000200f9,0x00001029,0x000200f8,0x00001024, +0x000200f9,0x00001029,0x000200f8,0x00001029, +0x000700f5,0x00000006,0x0000214e,0x00001d59, +0x00001024,0x00001028,0x00001026,0x000600a9, +0x00000006,0x0000219e,0x0000109f,0x0000101d, +0x00001d5a,0x000200f9,0x0000102a,0x000200f8, +0x0000102a,0x000200f9,0x00001014,0x000200f8, +0x0000102b,0x000500aa,0x00000012,0x0000102d, +0x00001d59,0x00000058,0x000300f7,0x0000102f, +0x00000000,0x000400fa,0x0000102d,0x0000102e, +0x0000102f,0x000200f8,0x0000102e,0x000200f9, +0x00001042,0x000200f8,0x0000102f,0x00050082, +0x00000006,0x00001031,0x00001d59,0x00000063, +0x00050084,0x00000006,0x00001032,0x0000009e, +0x00001031,0x00050080,0x00000006,0x00001033, +0x00001032,0x000000d8,0x00050051,0x00000006, +0x000010bd,0x00000db9,0x00000000,0x00050084, +0x00000006,0x000010bf,0x00001033,0x0000009e, +0x00050095,0x0000005e,0x000010c0,0x000010bd, +0x000010bf,0x00050051,0x00000006,0x000010c1, +0x000010c0,0x00000001,0x00050051,0x00000006, +0x000010c2,0x000010c0,0x00000000,0x00050051, +0x00000006,0x000010c5,0x00000db9,0x00000001, +0x00050080,0x00000006,0x000010c7,0x000010c5, +0x000010c1,0x00050050,0x00000007,0x000010c8, +0x000010c2,0x000010c7,0x0004007c,0x000000b1, +0x000010b5,0x000010c8,0x00060041,0x000000b7, +0x000010b6,0x000010b5,0x000000b6,0x000000b6, +0x0006003d,0x00000006,0x000010b7,0x000010b6, +0x00000002,0x00000004,0x00050080,0x00000006, +0x000010aa,0x00001032,0x000000de,0x00050084, +0x00000006,0x000010da,0x000010aa,0x0000009e, +0x00050095,0x0000005e,0x000010db,0x000010bd, +0x000010da,0x00050051,0x00000006,0x000010dc, +0x000010db,0x00000001,0x00050051,0x00000006, +0x000010dd,0x000010db,0x00000000,0x00050080, +0x00000006,0x000010e2,0x000010c5,0x000010dc, +0x00050050,0x00000007,0x000010e3,0x000010dd, +0x000010e2,0x0004007c,0x000000b1,0x000010d0, +0x000010e3,0x00060041,0x000000b7,0x000010d1, +0x000010d0,0x000000b6,0x000000b6,0x0006003d, +0x00000006,0x000010d2,0x000010d1,0x00000002, +0x00000004,0x00050051,0x00000006,0x000010e7, +0x00001d58,0x00000001,0x000500b0,0x00000012, +0x000010ea,0x000010e7,0x000010d2,0x000400a8, +0x00000012,0x000010eb,0x000010ea,0x000300f7, +0x000010fa,0x00000000,0x000400fa,0x000010eb, +0x000010ec,0x000010fa,0x000200f8,0x000010ec, +0x000500aa,0x00000012,0x000010f1,0x000010e7, +0x000010d2,0x000300f7,0x000010f8,0x00000000, +0x000400fa,0x000010f1,0x000010f2,0x000010f8, +0x000200f8,0x000010f2,0x00050051,0x00000006, +0x000010f4,0x00001d58,0x00000000,0x000500b0, +0x00000012,0x000010f7,0x000010f4,0x000010b7, +0x000200f9,0x000010f8,0x000200f8,0x000010f8, +0x000700f5,0x00000012,0x000010f9,0x000010f1, +0x000010ec,0x000010f7,0x000010f2,0x000200f9, +0x000010fa,0x000200f8,0x000010fa,0x000700f5, +0x00000012,0x000010fb,0x000010ea,0x0000102f, +0x000010f9,0x000010f8,0x000300f7,0x00001040, +0x00000000,0x000400fa,0x000010fb,0x00001039, +0x00001040,0x000200f8,0x00001039,0x00050051, +0x00000006,0x00001103,0x00001d58,0x00000000, +0x00050096,0x0000005e,0x00001104,0x000010b7, +0x00001103,0x00050051,0x00000006,0x00001105, +0x00001104,0x00000001,0x00050051,0x00000006, +0x00001106,0x00001104,0x00000000,0x00050082, +0x00000006,0x0000110c,0x000010d2,0x000010e7, +0x00050082,0x00000006,0x0000110e,0x0000110c, +0x00001105,0x00050051,0x00000006,0x00001115, +0x00000db7,0x00000001,0x000500b0,0x00000012, +0x00001116,0x0000110e,0x00001115,0x000400a8, +0x00000012,0x00001117,0x00001116,0x000300f7, +0x00001126,0x00000000,0x000400fa,0x00001117, +0x00001118,0x00001126,0x000200f8,0x00001118, +0x000500aa,0x00000012,0x0000111d,0x0000110e, +0x00001115,0x000300f7,0x00001124,0x00000000, +0x000400fa,0x0000111d,0x0000111e,0x00001124, +0x000200f8,0x0000111e,0x00050051,0x00000006, +0x00001122,0x00000db7,0x00000000,0x000500b0, +0x00000012,0x00001123,0x00001106,0x00001122, +0x000200f9,0x00001124,0x000200f8,0x00001124, +0x000700f5,0x00000012,0x00001125,0x0000111d, +0x00001118,0x00001123,0x0000111e,0x000200f9, +0x00001126,0x000200f8,0x00001126,0x000700f5, +0x00000012,0x00001127,0x00001116,0x00001039, +0x00001125,0x00001124,0x000400a8,0x00000012, +0x0000103f,0x00001127,0x000200f9,0x00001040, +0x000200f8,0x00001040,0x000700f5,0x00000012, +0x00001041,0x000010fb,0x000010fa,0x0000103f, +0x00001126,0x000200f9,0x00001042,0x000200f8, +0x00001042,0x000700f5,0x00000012,0x00001d5b, +0x0000011e,0x0000102e,0x00001041,0x00001040, +0x000200f9,0x00000dbe,0x000200f8,0x00000dbe, +0x000700f5,0x00000012,0x00000dbf,0x00000dab, +0x00000da8,0x00001d5b,0x00001042,0x000300f7, +0x00000dc1,0x00000000,0x000400fa,0x00000dbf, +0x00000dc0,0x00000dc1,0x000200f8,0x00000dc0, +0x000200f9,0x00000e39,0x000200f8,0x00000dc1, +0x000500c6,0x00000006,0x0000112e,0x000000cb, +0x00000d24,0x00050084,0x00000006,0x0000112f, +0x0000112e,0x000000d0,0x000500c6,0x00000006, +0x00001133,0x0000112f,0x00000d26,0x00050084, +0x00000006,0x00001134,0x00001133,0x000000d0, +0x000500c6,0x00000006,0x00001138,0x00001134, +0x00000d3c,0x00050084,0x00000006,0x00001139, +0x00001138,0x000000d0,0x000500c6,0x00000006, +0x0000113d,0x00001139,0x000004b6,0x00050084, +0x00000006,0x0000113e,0x0000113d,0x000000d0, +0x000500c2,0x00000006,0x00001140,0x0000113e, +0x000000e4,0x000500c6,0x00000006,0x00001142, +0x0000113e,0x00001140,0x00050084,0x00000006, +0x00001144,0x00001142,0x000000e8,0x000500c2, +0x00000006,0x00001146,0x00001144,0x000000ec, +0x000500c6,0x00000006,0x00001148,0x00001144, +0x00001146,0x00050084,0x00000006,0x0000114a, +0x00001148,0x000000f0,0x000500c2,0x00000006, +0x0000114c,0x0000114a,0x000000e4,0x000500c6, +0x00000006,0x0000114e,0x0000114a,0x0000114c, +0x000200f9,0x00000dc4,0x000200f8,0x00000dc4, +0x000700f5,0x00000006,0x00001d6c,0x00000058, +0x00000dc1,0x00000e22,0x00000e20,0x000500b0, +0x00000012,0x00000dc7,0x00001d6c,0x0000034a, +0x000400f6,0x00000e23,0x00000e20,0x00000000, +0x000400fa,0x00000dc7,0x00000dc8,0x00000e23, +0x000200f8,0x00000dc8,0x00050080,0x00000006, +0x00000dcb,0x0000114e,0x00001d6c,0x00050041, +0x00000182,0x00000dcc,0x00000180,0x000000ec, +0x0004003d,0x00000006,0x00000dcd,0x00000dcc, +0x000500c7,0x00000006,0x00000dce,0x00000dcb, +0x00000dcd,0x00050084,0x00000006,0x00000dcf, +0x000002ab,0x00000dce,0x00050080,0x00000006, +0x00000dd1,0x00000dcf,0x00000357,0x00050041, +0x0000020a,0x00000dd2,0x00000180,0x00000355, +0x0004003d,0x00000007,0x00000dd3,0x00000dd2, +0x00050051,0x00000006,0x0000115f,0x00000dd3, +0x00000000,0x00050084,0x00000006,0x00001161, +0x00000dd1,0x0000009e,0x00050095,0x0000005e, +0x00001162,0x0000115f,0x00001161,0x00050051, +0x00000006,0x00001163,0x00001162,0x00000001, +0x00050051,0x00000006,0x00001164,0x00001162, +0x00000000,0x00050051,0x00000006,0x00001167, +0x00000dd3,0x00000001,0x00050080,0x00000006, +0x00001169,0x00001167,0x00001163,0x00050050, +0x00000007,0x0000116a,0x00001164,0x00001169, +0x0004007c,0x000000b1,0x00001157,0x0000116a, +0x00060041,0x000000b7,0x00001158,0x00001157, +0x000000b6,0x000000b6,0x0006003d,0x00000006, +0x00001159,0x00001158,0x00000002,0x00000004, +0x000500c2,0x00000006,0x00000dd5,0x00001159, +0x000000e4,0x000500c7,0x00000006,0x00000dd7, +0x00000dd5,0x00000063,0x000500aa,0x00000012, +0x00000dd8,0x00000dd7,0x00000058,0x000300f7, +0x00000dda,0x00000000,0x000400fa,0x00000dd8, +0x00000dd9,0x00000dda,0x000200f8,0x00000dd9, +0x000200f9,0x00000e20,0x000200f8,0x00000dda, +0x00050084,0x00000006,0x0000117c,0x00000dce, +0x0000218f,0x00050095,0x0000005e,0x0000117d, +0x0000115f,0x0000117c,0x00050051,0x00000006, +0x0000117e,0x0000117d,0x00000001,0x00050051, +0x00000006,0x0000117f,0x0000117d,0x00000000, +0x00050080,0x00000006,0x00001184,0x00001167, +0x0000117e,0x00050050,0x00000007,0x00001185, +0x0000117f,0x00001184,0x0004007c,0x000000b1, +0x00001172,0x00001185,0x00060041,0x000000b7, +0x00001173,0x00001172,0x000000b6,0x000000b6, +0x0006003d,0x00000006,0x00001174,0x00001173, +0x00000002,0x00000004,0x000500ab,0x00000012, +0x00000de1,0x00001174,0x00000d24,0x000400a8, +0x00000012,0x00000de2,0x00000de1,0x000300f7, +0x00000dec,0x00000000,0x000400fa,0x00000de2, +0x00000de3,0x00000dec,0x000200f8,0x00000de3, +0x00050080,0x00000006,0x00000de5,0x00000dcf, +0x00000063,0x00050084,0x00000006,0x00001197, +0x00000de5,0x0000009e,0x00050095,0x0000005e, +0x00001198,0x0000115f,0x00001197,0x00050051, +0x00000006,0x00001199,0x00001198,0x00000001, +0x00050051,0x00000006,0x0000119a,0x00001198, +0x00000000,0x00050080,0x00000006,0x0000119f, +0x00001167,0x00001199,0x00050050,0x00000007, +0x000011a0,0x0000119a,0x0000119f,0x0004007c, +0x000000b1,0x0000118d,0x000011a0,0x00060041, +0x000000b7,0x0000118e,0x0000118d,0x000000b6, +0x000000b6,0x0006003d,0x00000006,0x0000118f, +0x0000118e,0x00000002,0x00000004,0x000500ab, +0x00000012,0x00000deb,0x0000118f,0x00000d26, +0x000200f9,0x00000dec,0x000200f8,0x00000dec, +0x000700f5,0x00000012,0x00000ded,0x00000de1, +0x00000dda,0x00000deb,0x00000de3,0x000400a8, +0x00000012,0x00000dee,0x00000ded,0x000300f7, +0x00000df8,0x00000000,0x000400fa,0x00000dee, +0x00000def,0x00000df8,0x000200f8,0x00000def, +0x00050080,0x00000006,0x00000df1,0x00000dcf, +0x000000d8,0x00050084,0x00000006,0x000011b2, +0x00000df1,0x0000009e,0x00050095,0x0000005e, +0x000011b3,0x0000115f,0x000011b2,0x00050051, +0x00000006,0x000011b4,0x000011b3,0x00000001, +0x00050051,0x00000006,0x000011b5,0x000011b3, +0x00000000,0x00050080,0x00000006,0x000011ba, +0x00001167,0x000011b4,0x00050050,0x00000007, +0x000011bb,0x000011b5,0x000011ba,0x0004007c, +0x000000b1,0x000011a8,0x000011bb,0x00060041, +0x000000b7,0x000011a9,0x000011a8,0x000000b6, +0x000000b6,0x0006003d,0x00000006,0x000011aa, +0x000011a9,0x00000002,0x00000004,0x000500ab, +0x00000012,0x00000df7,0x000011aa,0x00000d3c, +0x000200f9,0x00000df8,0x000200f8,0x00000df8, +0x000700f5,0x00000012,0x00000df9,0x00000ded, +0x00000dec,0x00000df7,0x00000def,0x000400a8, +0x00000012,0x00000dfa,0x00000df9,0x000300f7, +0x00000e04,0x00000000,0x000400fa,0x00000dfa, +0x00000dfb,0x00000e04,0x000200f8,0x00000dfb, +0x00050080,0x00000006,0x00000dfd,0x00000dcf, +0x000000de,0x00050084,0x00000006,0x000011cd, +0x00000dfd,0x0000009e,0x00050095,0x0000005e, +0x000011ce,0x0000115f,0x000011cd,0x00050051, +0x00000006,0x000011cf,0x000011ce,0x00000001, +0x00050051,0x00000006,0x000011d0,0x000011ce, +0x00000000,0x00050080,0x00000006,0x000011d5, +0x00001167,0x000011cf,0x00050050,0x00000007, +0x000011d6,0x000011d0,0x000011d5,0x0004007c, +0x000000b1,0x000011c3,0x000011d6,0x00060041, +0x000000b7,0x000011c4,0x000011c3,0x000000b6, +0x000000b6,0x0006003d,0x00000006,0x000011c5, +0x000011c4,0x00000002,0x00000004,0x000500ab, +0x00000012,0x00000e03,0x000011c5,0x000004b6, +0x000200f9,0x00000e04,0x000200f8,0x00000e04, +0x000700f5,0x00000012,0x00000e05,0x00000df9, +0x00000df8,0x00000e03,0x00000dfb,0x000300f7, +0x00000e07,0x00000000,0x000400fa,0x00000e05, +0x00000e06,0x00000e07,0x000200f8,0x00000e06, +0x000200f9,0x00000e20,0x000200f8,0x00000e07, +0x000500c7,0x00000006,0x00000e09,0x00000dd5, +0x000000d8,0x000500ab,0x00000012,0x00000e0a, +0x00000e09,0x00000058,0x000300f7,0x00000e1f, +0x00000000,0x000400fa,0x00000e0a,0x00000e0b, +0x00000e0f,0x000200f8,0x00000e0f,0x00050080, +0x00000006,0x00000e11,0x00000dcf,0x0000009e, +0x00050084,0x00000006,0x000011ec,0x00000e11, +0x0000009e,0x00050095,0x0000005e,0x000011ed, +0x0000115f,0x000011ec,0x00050051,0x00000006, +0x000011ee,0x000011ed,0x00000001,0x00050051, +0x00000006,0x000011ef,0x000011ed,0x00000000, +0x00050080,0x00000006,0x000011f4,0x00001167, +0x000011ee,0x00050050,0x00000007,0x000011f5, +0x000011ef,0x000011f4,0x0004007c,0x000000b1, +0x000011e2,0x000011f5,0x00060041,0x000000b7, +0x000011e3,0x000011e2,0x000000b6,0x000000b6, +0x0006003d,0x00000006,0x000011e4,0x000011e3, +0x00000002,0x00000004,0x0006003d,0x00000006, +0x000011ff,0x00001158,0x00000002,0x00000004, +0x00060052,0x00000027,0x00001be0,0x000011e4, +0x0000219c,0x00000000,0x000500c7,0x00000006, +0x00001217,0x00000d26,0x00000191,0x000500c7, +0x00000006,0x0000121a,0x000011ff,0x0000017b, +0x000500c5,0x00000006,0x0000121b,0x00001217, +0x0000121a,0x00060052,0x00000027,0x00001be4, +0x0000121b,0x00001be0,0x00000001,0x000200f9, +0x00000e1f,0x000200f8,0x00000e0b,0x00060052, +0x00000027,0x00001bd5,0x00000058,0x0000219c, +0x00000000,0x00060052,0x00000027,0x00001bd7, +0x00000058,0x00001bd5,0x00000001,0x00060052, +0x00000027,0x00001bd9,0x00000058,0x00001bd7, +0x00000002,0x000200f9,0x00000e1f,0x000200f8, +0x00000e1f,0x000700f5,0x00000027,0x00001d86, +0x00001bd9,0x00000e0b,0x00001be4,0x00000e0f, +0x000200f9,0x00000e23,0x000200f8,0x00000e20, +0x00050080,0x00000006,0x00000e22,0x00001d6c, +0x000003bc,0x000200f9,0x00000dc4,0x000200f8, +0x00000e23,0x000700f5,0x00000006,0x00001d91, +0x00001da1,0x00000dc4,0x00000063,0x00000e1f, +0x000700f5,0x00000027,0x00001d85,0x0000219c, +0x00000dc4,0x00001d86,0x00000e1f,0x000700f5, +0x00000012,0x00001d71,0x0000011e,0x00000dc4, +0x00000217,0x00000e1f,0x000300f7,0x00000e25, +0x00000000,0x000400fa,0x00001d71,0x00000e39, +0x00000e25,0x000200f8,0x00000e25,0x00060052, +0x00000027,0x00001be6,0x00000058,0x00001d85, +0x00000000,0x00060052,0x00000027,0x00001be8, +0x00000058,0x00001be6,0x00000001,0x00060052, +0x00000027,0x00001bea,0x00000058,0x00001be8, +0x00000002,0x000500c7,0x00000006,0x00000e2b, +0x00000438,0x000000d8,0x000500ab,0x00000012, +0x00000e2c,0x00000e2b,0x00000058,0x000300f7, +0x00000e35,0x00000000,0x000400fa,0x00000e2c, +0x00000e2d,0x00000e35,0x000200f8,0x00000e2d, +0x00050041,0x0000020a,0x00000e2e,0x00000180, +0x000003c8,0x0004003d,0x00000007,0x00000e2f, +0x00000e2e,0x00050041,0x00000182,0x00000e30, +0x00000180,0x000003c9,0x0004003d,0x00000006, +0x00000e31,0x00000e30,0x000300f7,0x00001265, +0x00000000,0x000300fb,0x00000058,0x00001235, +0x000200f8,0x00001235,0x000200f9,0x00001237, +0x000200f8,0x00001237,0x000700f5,0x00000006, +0x00001d88,0x00000e31,0x00001235,0x0000219f, +0x0000124d,0x000700f5,0x00000006,0x00001d87, +0x00000058,0x00001235,0x00002165,0x0000124d, +0x000500b0,0x00000012,0x0000123b,0x00001d87, +0x00001d88,0x000400f6,0x0000124e,0x0000124d, +0x00000000,0x000400fa,0x0000123b,0x0000123c, +0x0000124e,0x000200f8,0x0000123c,0x00050080, +0x00000006,0x0000123f,0x00001d87,0x00001d88, +0x000500c2,0x00000006,0x00001240,0x0000123f, +0x00000063,0x00050084,0x00000006,0x00001242, +0x0000009e,0x00001240,0x00050051,0x00000006, +0x00001284,0x00000e2f,0x00000000,0x00050084, +0x00000006,0x00001286,0x00001240,0x0000034a, +0x00050095,0x0000005e,0x00001287,0x00001284, +0x00001286,0x00050051,0x00000006,0x00001288, +0x00001287,0x00000001,0x00050051,0x00000006, +0x00001289,0x00001287,0x00000000,0x00050051, +0x00000006,0x0000128c,0x00000e2f,0x00000001, +0x00050080,0x00000006,0x0000128e,0x0000128c, +0x00001288,0x00050050,0x00000007,0x0000128f, +0x00001289,0x0000128e,0x0004007c,0x000000b1, +0x0000127c,0x0000128f,0x00060041,0x000000b7, +0x0000127d,0x0000127c,0x000000b6,0x000000b6, +0x0006003d,0x00000006,0x0000127e,0x0000127d, +0x00000002,0x00000004,0x00050080,0x00000006, +0x00001271,0x00001242,0x00000063,0x00050084, +0x00000006,0x000012a1,0x00001271,0x0000009e, +0x00050095,0x0000005e,0x000012a2,0x00001284, +0x000012a1,0x00050051,0x00000006,0x000012a3, +0x000012a2,0x00000001,0x00050051,0x00000006, +0x000012a4,0x000012a2,0x00000000,0x00050080, +0x00000006,0x000012a9,0x0000128c,0x000012a3, +0x00050050,0x00000007,0x000012aa,0x000012a4, +0x000012a9,0x0004007c,0x000000b1,0x00001297, +0x000012aa,0x00060041,0x000000b7,0x00001298, +0x00001297,0x000000b6,0x000000b6,0x0006003d, +0x00000006,0x00001299,0x00001298,0x00000002, +0x00000004,0x000500b0,0x00000012,0x000012b1, +0x00000d27,0x00001299,0x000400a8,0x00000012, +0x000012b2,0x000012b1,0x000300f7,0x000012c1, +0x00000000,0x000400fa,0x000012b2,0x000012b3, +0x000012c1,0x000200f8,0x000012b3,0x000500aa, +0x00000012,0x000012b8,0x00000d27,0x00001299, +0x000300f7,0x000012bf,0x00000000,0x000400fa, +0x000012b8,0x000012b9,0x000012bf,0x000200f8, +0x000012b9,0x000500b0,0x00000012,0x000012be, +0x00000d24,0x0000127e,0x000200f9,0x000012bf, +0x000200f8,0x000012bf,0x000700f5,0x00000012, +0x000012c0,0x000012b8,0x000012b3,0x000012be, +0x000012b9,0x000200f9,0x000012c1,0x000200f8, +0x000012c1,0x000700f5,0x00000012,0x000012c2, +0x000012b1,0x0000123c,0x000012c0,0x000012bf, +0x000300f7,0x0000124c,0x00000000,0x000400fa, +0x000012c2,0x00001247,0x00001249,0x000200f8, +0x00001249,0x00050080,0x00000006,0x0000124b, +0x00001240,0x00000063,0x000200f9,0x0000124c, +0x000200f8,0x00001247,0x000200f9,0x0000124c, +0x000200f8,0x0000124c,0x000700f5,0x00000006, +0x00002165,0x00001d87,0x00001247,0x0000124b, +0x00001249,0x000600a9,0x00000006,0x0000219f, +0x000012c2,0x00001240,0x00001d88,0x000200f9, +0x0000124d,0x000200f8,0x0000124d,0x000200f9, +0x00001237,0x000200f8,0x0000124e,0x000500aa, +0x00000012,0x00001250,0x00001d87,0x00000058, +0x000300f7,0x00001252,0x00000000,0x000400fa, +0x00001250,0x00001251,0x00001252,0x000200f8, +0x00001251,0x000200f9,0x00001265,0x000200f8, +0x00001252,0x00050082,0x00000006,0x00001254, +0x00001d87,0x00000063,0x00050084,0x00000006, +0x00001255,0x0000009e,0x00001254,0x00050080, +0x00000006,0x00001256,0x00001255,0x000000d8, +0x00050051,0x00000006,0x000012e0,0x00000e2f, +0x00000000,0x00050084,0x00000006,0x000012e2, +0x00001256,0x0000009e,0x00050095,0x0000005e, +0x000012e3,0x000012e0,0x000012e2,0x00050051, +0x00000006,0x000012e4,0x000012e3,0x00000001, +0x00050051,0x00000006,0x000012e5,0x000012e3, +0x00000000,0x00050051,0x00000006,0x000012e8, +0x00000e2f,0x00000001,0x00050080,0x00000006, +0x000012ea,0x000012e8,0x000012e4,0x00050050, +0x00000007,0x000012eb,0x000012e5,0x000012ea, +0x0004007c,0x000000b1,0x000012d8,0x000012eb, +0x00060041,0x000000b7,0x000012d9,0x000012d8, +0x000000b6,0x000000b6,0x0006003d,0x00000006, +0x000012da,0x000012d9,0x00000002,0x00000004, +0x00050080,0x00000006,0x000012cd,0x00001255, +0x000000de,0x00050084,0x00000006,0x000012fd, +0x000012cd,0x0000009e,0x00050095,0x0000005e, +0x000012fe,0x000012e0,0x000012fd,0x00050051, +0x00000006,0x000012ff,0x000012fe,0x00000001, +0x00050051,0x00000006,0x00001300,0x000012fe, +0x00000000,0x00050080,0x00000006,0x00001305, +0x000012e8,0x000012ff,0x00050050,0x00000007, +0x00001306,0x00001300,0x00001305,0x0004007c, +0x000000b1,0x000012f3,0x00001306,0x00060041, +0x000000b7,0x000012f4,0x000012f3,0x000000b6, +0x000000b6,0x0006003d,0x00000006,0x000012f5, +0x000012f4,0x00000002,0x00000004,0x000500b0, +0x00000012,0x0000130d,0x00000d27,0x000012f5, +0x000400a8,0x00000012,0x0000130e,0x0000130d, +0x000300f7,0x0000131d,0x00000000,0x000400fa, +0x0000130e,0x0000130f,0x0000131d,0x000200f8, +0x0000130f,0x000500aa,0x00000012,0x00001314, +0x00000d27,0x000012f5,0x000300f7,0x0000131b, +0x00000000,0x000400fa,0x00001314,0x00001315, +0x0000131b,0x000200f8,0x00001315,0x000500b0, +0x00000012,0x0000131a,0x00000d24,0x000012da, +0x000200f9,0x0000131b,0x000200f8,0x0000131b, +0x000700f5,0x00000012,0x0000131c,0x00001314, +0x0000130f,0x0000131a,0x00001315,0x000200f9, +0x0000131d,0x000200f8,0x0000131d,0x000700f5, +0x00000012,0x0000131e,0x0000130d,0x00001252, +0x0000131c,0x0000131b,0x000300f7,0x00001263, +0x00000000,0x000400fa,0x0000131e,0x0000125c, +0x00001263,0x000200f8,0x0000125c,0x00050096, +0x0000005e,0x00001327,0x000012da,0x00000d24, +0x00050051,0x00000006,0x00001328,0x00001327, +0x00000001,0x00050051,0x00000006,0x00001329, +0x00001327,0x00000000,0x00050082,0x00000006, +0x0000132f,0x000012f5,0x00000d27,0x00050082, +0x00000006,0x00001331,0x0000132f,0x00001328, +0x000500aa,0x00000012,0x00001340,0x00001331, +0x00000058,0x000300f7,0x00001347,0x00000000, +0x000400fa,0x00001340,0x00001341,0x00001347, +0x000200f8,0x00001341,0x000500b0,0x00000012, +0x00001346,0x00001329,0x00000063,0x000200f9, +0x00001347,0x000200f8,0x00001347,0x000700f5, +0x00000012,0x00001348,0x00001340,0x0000125c, +0x00001346,0x00001341,0x000400a8,0x00000012, +0x00001262,0x00001348,0x000200f9,0x00001263, +0x000200f8,0x00001263,0x000700f5,0x00000012, +0x00001264,0x0000131e,0x0000131d,0x00001262, +0x00001347,0x000200f9,0x00001265,0x000200f8, +0x00001265,0x000700f5,0x00000012,0x00001d89, +0x0000011e,0x00001251,0x00001264,0x00001263, +0x000400a8,0x00000012,0x00000e34,0x00001d89, +0x000200f9,0x00000e35,0x000200f8,0x00000e35, +0x000700f5,0x00000012,0x00000e36,0x00000e2c, +0x00000e25,0x00000e34,0x00001265,0x000300f7, +0x00000e38,0x00000000,0x000400fa,0x00000e36, +0x00000e37,0x00000e38,0x000200f8,0x00000e37, +0x000200f9,0x00000e39,0x000200f8,0x00000e38, +0x000200f9,0x00000e39,0x000200f8,0x00000e39, +0x001100f5,0x00000027,0x00001df6,0x0000219c, +0x00000d21,0x00001b5a,0x00000d32,0x00001df7, +0x00000d94,0x0000219c,0x00000dc0,0x00001d85, +0x00000e23,0x00001bea,0x00000e37,0x00001bea, +0x00000e38,0x001100f5,0x00000006,0x00001d90, +0x00000058,0x00000d21,0x00000063,0x00000d32, +0x00000063,0x00000d94,0x00000063,0x00000dc0, +0x00001d91,0x00000e23,0x00000063,0x00000e37, +0x000000d8,0x00000e38,0x000500aa,0x00000012, +0x000004bf,0x00001d90,0x000000d8,0x000300f7, +0x000004c1,0x00000000,0x000400fa,0x000004bf, +0x000004c0,0x000004c1,0x000200f8,0x000004c0, +0x00050041,0x00000182,0x000004c3,0x00000180, +0x000004c2,0x0004003d,0x00000006,0x000004c4, +0x000004c3,0x000500c4,0x00000006,0x000004c6, +0x000004c4,0x000004c5,0x000500c4,0x00000006, +0x000004c8,0x0000044f,0x00000063,0x000500c5, +0x00000006,0x000004c9,0x000004c6,0x000004c8, +0x00050041,0x0000020a,0x0000134e,0x00000180, +0x000003dd,0x0004003d,0x00000007,0x0000134f, +0x0000134e,0x0004007c,0x000000b1,0x00001350, +0x0000134f,0x00060041,0x000000b7,0x00001352, +0x00001350,0x000000b6,0x000000b6,0x000700ea, +0x00000006,0x00001353,0x00001352,0x00000063, +0x00000058,0x00000063,0x00060041,0x000000b7, +0x00001356,0x00001350,0x000000b6,0x000003bc, +0x0006003d,0x00000006,0x00001357,0x00001356, +0x00000002,0x00000004,0x000500b0,0x00000012, +0x00001358,0x00001353,0x00001357,0x000300f7, +0x00001362,0x00000000,0x000400fa,0x00001358, +0x00001359,0x0000135f,0x000200f8,0x0000135f, +0x00060041,0x000000b7,0x00001361,0x00001350, +0x000000b6,0x000003f3,0x0005003e,0x00001361, +0x00000063,0x00000002,0x00000004,0x000200f9, +0x00001362,0x000200f8,0x00001359,0x00050080, +0x00000006,0x0000135c,0x0000009e,0x00001353, +0x00060041,0x000000b7,0x0000135e,0x00001350, +0x000000b6,0x0000135c,0x0005003e,0x0000135e, +0x000004c9,0x00000002,0x00000004,0x000200f9, +0x00001362,0x000200f8,0x00001362,0x000200f9, +0x000004c1,0x000200f8,0x000004c1,0x000300f7, +0x000014ce,0x00000000,0x000300fb,0x00000058, +0x000013aa,0x000200f8,0x000013aa,0x00050051, +0x00000006,0x000013ac,0x00000498,0x00000003, +0x000500c2,0x00000006,0x000013ad,0x000013ac, +0x0000019b,0x000500ab,0x00000012,0x000013ae, +0x000013ad,0x00000058,0x000400a8,0x00000012, +0x000013af,0x000013ae,0x000300f7,0x000013b4, +0x00000000,0x000400fa,0x000013af,0x000013b0, +0x000013b4,0x000200f8,0x000013b0,0x00050051, +0x00000006,0x000013b2,0x00000498,0x00000002, +0x000500aa,0x00000012,0x000013b3,0x000013b2, +0x00000058,0x000200f9,0x000013b4,0x000200f8, +0x000013b4,0x000700f5,0x00000012,0x000013b5, +0x000013ae,0x000013aa,0x000013b3,0x000013b0, +0x000300f7,0x000013b7,0x00000000,0x000400fa, +0x000013b5,0x000013b6,0x000013b7,0x000200f8, +0x000013b6,0x000200f9,0x000014ce,0x000200f8, +0x000013b7,0x00050051,0x00000006,0x000013b9, +0x00000498,0x00000000,0x00050051,0x00000006, +0x000013bb,0x00000498,0x00000001,0x000500c7, +0x00000006,0x000013bc,0x000013bb,0x0000017b, +0x00050050,0x00000007,0x000013bd,0x000013b9, +0x000013bc,0x000500aa,0x00000012,0x000013c0, +0x000013b9,0x00000058,0x000300f7,0x000013c5, +0x00000000,0x000400fa,0x000013c0,0x000013c1, +0x000013c5,0x000200f8,0x000013c1,0x000500aa, +0x00000012,0x000013c4,0x000013bc,0x00000058, +0x000200f9,0x000013c5,0x000200f8,0x000013c5, +0x000700f5,0x00000012,0x000013c6,0x000013c0, +0x000013b7,0x000013c4,0x000013c1,0x000300f7, +0x000013cb,0x00000000,0x000400fa,0x000013c6, +0x000013c7,0x000013cb,0x000200f8,0x000013c7, +0x00060052,0x00000027,0x00001c10,0x00000058, +0x00000498,0x00000000,0x00060052,0x00000027, +0x00001c12,0x00000058,0x00001c10,0x00000001, +0x00060052,0x00000027,0x00001c14,0x00000058, +0x00001c12,0x00000002,0x000200f9,0x000014ce, +0x000200f8,0x000013cb,0x000500c2,0x00000006, +0x000013ce,0x000013bb,0x000000e4,0x000500c7, +0x00000006,0x000013cf,0x000013ce,0x000001ad, +0x00050051,0x00000006,0x000013d1,0x00000498, +0x00000002,0x000500aa,0x00000012,0x000013d3, +0x000013cf,0x00000058,0x000600a9,0x00000006, +0x000013d5,0x000013d3,0x00000063,0x000013cf, +0x00050097,0x0000005e,0x000013d8,0x000013d1, +0x000013d5,0x00050051,0x00000006,0x000013d9, +0x000013d8,0x00000000,0x00050051,0x00000006, +0x000013da,0x000013d8,0x00000001,0x00050050, +0x00000007,0x00002190,0x000013d9,0x000013da, +0x00050041,0x00000182,0x000013db,0x00000180, +0x0000029a,0x0004003d,0x00000006,0x000013dc, +0x000013db,0x000200f9,0x000013dd,0x000200f8, +0x000013dd,0x000700f5,0x00000006,0x00001eae, +0x000013dc,0x000013cb,0x000021a0,0x000013f4, +0x000700f5,0x00000006,0x00001ead,0x00000058, +0x000013cb,0x0000216b,0x000013f4,0x000500b0, +0x00000012,0x000013e1,0x00001ead,0x00001eae, +0x000400f6,0x000013f5,0x000013f4,0x00000000, +0x000400fa,0x000013e1,0x000013e2,0x000013f5, +0x000200f8,0x000013e2,0x00050080,0x00000006, +0x000013e5,0x00001ead,0x00001eae,0x000500c2, +0x00000006,0x000013e6,0x000013e5,0x00000063, +0x00050084,0x00000006,0x000013e8,0x000002ab, +0x000013e6,0x00050041,0x0000020a,0x000013e9, +0x00000180,0x000002aa,0x0004003d,0x00000007, +0x000013ea,0x000013e9,0x00050051,0x00000006, +0x000014f1,0x000013ea,0x00000000,0x00050084, +0x00000006,0x000014f3,0x000013e6,0x0000218f, +0x00050095,0x0000005e,0x000014f4,0x000014f1, +0x000014f3,0x00050051,0x00000006,0x000014f5, +0x000014f4,0x00000001,0x00050051,0x00000006, +0x000014f6,0x000014f4,0x00000000,0x00050051, +0x00000006,0x000014f9,0x000013ea,0x00000001, +0x00050080,0x00000006,0x000014fb,0x000014f9, +0x000014f5,0x00050050,0x00000007,0x000014fc, +0x000014f6,0x000014fb,0x0004007c,0x000000b1, +0x000014e9,0x000014fc,0x00060041,0x000000b7, +0x000014ea,0x000014e9,0x000000b6,0x000000b6, +0x0006003d,0x00000006,0x000014eb,0x000014ea, +0x00000002,0x00000004,0x00050080,0x00000006, +0x000014de,0x000013e8,0x00000063,0x00050084, +0x00000006,0x0000150e,0x000014de,0x0000009e, +0x00050095,0x0000005e,0x0000150f,0x000014f1, +0x0000150e,0x00050051,0x00000006,0x00001510, +0x0000150f,0x00000001,0x00050051,0x00000006, +0x00001511,0x0000150f,0x00000000,0x00050080, +0x00000006,0x00001516,0x000014f9,0x00001510, +0x00050050,0x00000007,0x00001517,0x00001511, +0x00001516,0x0004007c,0x000000b1,0x00001504, +0x00001517,0x00060041,0x000000b7,0x00001505, +0x00001504,0x000000b6,0x000000b6,0x0006003d, +0x00000006,0x00001506,0x00001505,0x00000002, +0x00000004,0x000500b0,0x00000012,0x0000151e, +0x000013bc,0x00001506,0x000400a8,0x00000012, +0x0000151f,0x0000151e,0x000300f7,0x0000152e, +0x00000000,0x000400fa,0x0000151f,0x00001520, +0x0000152e,0x000200f8,0x00001520,0x000500aa, +0x00000012,0x00001525,0x000013bc,0x00001506, +0x000300f7,0x0000152c,0x00000000,0x000400fa, +0x00001525,0x00001526,0x0000152c,0x000200f8, +0x00001526,0x000500b0,0x00000012,0x0000152b, +0x000013b9,0x000014eb,0x000200f9,0x0000152c, +0x000200f8,0x0000152c,0x000700f5,0x00000012, +0x0000152d,0x00001525,0x00001520,0x0000152b, +0x00001526,0x000200f9,0x0000152e,0x000200f8, +0x0000152e,0x000700f5,0x00000012,0x0000152f, +0x0000151e,0x000013e2,0x0000152d,0x0000152c, +0x000300f7,0x000013f3,0x00000000,0x000400fa, +0x0000152f,0x000013ee,0x000013f0,0x000200f8, +0x000013f0,0x00050080,0x00000006,0x000013f2, +0x000013e6,0x00000063,0x000200f9,0x000013f3, +0x000200f8,0x000013ee,0x000200f9,0x000013f3, +0x000200f8,0x000013f3,0x000700f5,0x00000006, +0x0000216b,0x00001ead,0x000013ee,0x000013f2, +0x000013f0,0x000600a9,0x00000006,0x000021a0, +0x0000152f,0x000013e6,0x00001eae,0x000200f9, +0x000013f4,0x000200f8,0x000013f4,0x000200f9, +0x000013dd,0x000200f8,0x000013f5,0x000500ac, +0x00000012,0x000013f7,0x00001ead,0x00000058, +0x000300f7,0x0000142b,0x00000000,0x000400fa, +0x000013f7,0x000013f8,0x0000142b,0x000200f8, +0x000013f8,0x00050082,0x00000006,0x000013fa, +0x00001ead,0x00000063,0x00050084,0x00000006, +0x000013fb,0x000002ab,0x000013fa,0x00050080, +0x00000006,0x000013fd,0x000013fb,0x000000d8, +0x00050041,0x0000020a,0x000013fe,0x00000180, +0x000002aa,0x0004003d,0x00000007,0x000013ff, +0x000013fe,0x00050051,0x00000006,0x0000154d, +0x000013ff,0x00000000,0x00050084,0x00000006, +0x0000154f,0x000013fd,0x0000009e,0x00050095, +0x0000005e,0x00001550,0x0000154d,0x0000154f, +0x00050051,0x00000006,0x00001551,0x00001550, +0x00000001,0x00050051,0x00000006,0x00001552, +0x00001550,0x00000000,0x00050051,0x00000006, +0x00001555,0x000013ff,0x00000001,0x00050080, +0x00000006,0x00001557,0x00001555,0x00001551, +0x00050050,0x00000007,0x00001558,0x00001552, +0x00001557,0x0004007c,0x000000b1,0x00001545, +0x00001558,0x00060041,0x000000b7,0x00001546, +0x00001545,0x000000b6,0x000000b6,0x0006003d, +0x00000006,0x00001547,0x00001546,0x00000002, +0x00000004,0x00050080,0x00000006,0x0000153a, +0x000013fb,0x000000de,0x00050084,0x00000006, +0x0000156a,0x0000153a,0x0000009e,0x00050095, +0x0000005e,0x0000156b,0x0000154d,0x0000156a, +0x00050051,0x00000006,0x0000156c,0x0000156b, +0x00000001,0x00050051,0x00000006,0x0000156d, +0x0000156b,0x00000000,0x00050080,0x00000006, +0x00001572,0x00001555,0x0000156c,0x00050050, +0x00000007,0x00001573,0x0000156d,0x00001572, +0x0004007c,0x000000b1,0x00001560,0x00001573, +0x00060041,0x000000b7,0x00001561,0x00001560, +0x000000b6,0x000000b6,0x0006003d,0x00000006, +0x00001562,0x00001561,0x00000002,0x00000004, +0x000500b0,0x00000012,0x0000157a,0x000013bc, +0x00001562,0x000400a8,0x00000012,0x0000157b, +0x0000157a,0x000300f7,0x0000158a,0x00000000, +0x000400fa,0x0000157b,0x0000157c,0x0000158a, +0x000200f8,0x0000157c,0x000500aa,0x00000012, +0x00001581,0x000013bc,0x00001562,0x000300f7, +0x00001588,0x00000000,0x000400fa,0x00001581, +0x00001582,0x00001588,0x000200f8,0x00001582, +0x000500b0,0x00000012,0x00001587,0x000013b9, +0x00001547,0x000200f9,0x00001588,0x000200f8, +0x00001588,0x000700f5,0x00000012,0x00001589, +0x00001581,0x0000157c,0x00001587,0x00001582, +0x000200f9,0x0000158a,0x000200f8,0x0000158a, +0x000700f5,0x00000012,0x0000158b,0x0000157a, +0x000013f8,0x00001589,0x00001588,0x000300f7, +0x0000140c,0x00000000,0x000400fa,0x0000158b, +0x00001404,0x0000140c,0x000200f8,0x00001404, +0x00050080,0x00000006,0x00001406,0x000013fb, +0x000002d5,0x00050084,0x00000006,0x0000159d, +0x00001406,0x0000009e,0x00050095,0x0000005e, +0x0000159e,0x0000154d,0x0000159d,0x00050051, +0x00000006,0x0000159f,0x0000159e,0x00000001, +0x00050051,0x00000006,0x000015a0,0x0000159e, +0x00000000,0x00050080,0x00000006,0x000015a5, +0x00001555,0x0000159f,0x00050050,0x00000007, +0x000015a6,0x000015a0,0x000015a5,0x0004007c, +0x000000b1,0x00001593,0x000015a6,0x00060041, +0x000000b7,0x00001594,0x00001593,0x000000b6, +0x000000b6,0x0006003d,0x00000006,0x00001595, +0x00001594,0x00000002,0x00000004,0x000500c7, +0x00000006,0x0000140a,0x00001595,0x00000063, +0x000500ab,0x00000012,0x0000140b,0x0000140a, +0x00000058,0x000200f9,0x0000140c,0x000200f8, +0x0000140c,0x000700f5,0x00000012,0x0000140d, +0x0000158b,0x0000158a,0x0000140b,0x00001404, +0x000300f7,0x0000142a,0x00000000,0x000400fa, +0x0000140d,0x0000140e,0x0000142a,0x000200f8, +0x0000140e,0x00050096,0x0000005e,0x000015af, +0x00001547,0x000013b9,0x00050051,0x00000006, +0x000015b0,0x000015af,0x00000001,0x00050051, +0x00000006,0x000015b1,0x000015af,0x00000000, +0x00050082,0x00000006,0x000015b7,0x00001562, +0x000013bc,0x00050082,0x00000006,0x000015b9, +0x000015b7,0x000015b0,0x000500b0,0x00000012, +0x000015c1,0x000015b9,0x000013da,0x000400a8, +0x00000012,0x000015c2,0x000015c1,0x000300f7, +0x000015d1,0x00000000,0x000400fa,0x000015c2, +0x000015c3,0x000015d1,0x000200f8,0x000015c3, +0x000500aa,0x00000012,0x000015c8,0x000015b9, +0x000013da,0x000300f7,0x000015cf,0x00000000, +0x000400fa,0x000015c8,0x000015c9,0x000015cf, +0x000200f8,0x000015c9,0x000500b0,0x00000012, +0x000015ce,0x000015b1,0x000013d9,0x000200f9, +0x000015cf,0x000200f8,0x000015cf,0x000700f5, +0x00000012,0x000015d0,0x000015c8,0x000015c3, +0x000015ce,0x000015c9,0x000200f9,0x000015d1, +0x000200f8,0x000015d1,0x000700f5,0x00000012, +0x000015d2,0x000015c1,0x0000140e,0x000015d0, +0x000015cf,0x000300f7,0x00001429,0x00000000, +0x000400fa,0x000015d2,0x00001414,0x00001418, +0x000200f8,0x00001418,0x00050084,0x00000006, +0x000015f6,0x000013fa,0x0000218f,0x00050095, +0x0000005e,0x000015f7,0x0000154d,0x000015f6, +0x00050051,0x00000006,0x000015f8,0x000015f7, +0x00000001,0x00050051,0x00000006,0x000015f9, +0x000015f7,0x00000000,0x00050080,0x00000006, +0x000015fe,0x00001555,0x000015f8,0x00050050, +0x00000007,0x000015ff,0x000015f9,0x000015fe, +0x0004007c,0x000000b1,0x000015ec,0x000015ff, +0x00060041,0x000000b7,0x000015ed,0x000015ec, +0x000000b6,0x000000b6,0x0006003d,0x00000006, +0x000015ee,0x000015ed,0x00000002,0x00000004, +0x00050080,0x00000006,0x000015e1,0x000013fb, +0x00000063,0x00050084,0x00000006,0x00001611, +0x000015e1,0x0000009e,0x00050095,0x0000005e, +0x00001612,0x0000154d,0x00001611,0x00050051, +0x00000006,0x00001613,0x00001612,0x00000001, +0x00050051,0x00000006,0x00001614,0x00001612, +0x00000000,0x00050080,0x00000006,0x00001619, +0x00001555,0x00001613,0x00050050,0x00000007, +0x0000161a,0x00001614,0x00001619,0x0004007c, +0x000000b1,0x00001607,0x0000161a,0x00060041, +0x000000b7,0x00001608,0x00001607,0x000000b6, +0x000000b6,0x0006003d,0x00000006,0x00001609, +0x00001608,0x00000002,0x00000004,0x00050080, +0x00000006,0x0000141e,0x000013fb,0x0000009e, +0x00050084,0x00000006,0x0000163a,0x0000141e, +0x0000009e,0x00050095,0x0000005e,0x0000163b, +0x0000154d,0x0000163a,0x00050051,0x00000006, +0x0000163c,0x0000163b,0x00000001,0x00050051, +0x00000006,0x0000163d,0x0000163b,0x00000000, +0x00050080,0x00000006,0x00001642,0x00001555, +0x0000163c,0x00050050,0x00000007,0x00001643, +0x0000163d,0x00001642,0x0004007c,0x000000b1, +0x00001630,0x00001643,0x00060041,0x000000b7, +0x00001631,0x00001630,0x000000b6,0x000000b6, +0x0006003d,0x00000006,0x00001632,0x00001631, +0x00000002,0x00000004,0x00050080,0x00000006, +0x00001625,0x000013fb,0x00000357,0x00050084, +0x00000006,0x00001655,0x00001625,0x0000009e, +0x00050095,0x0000005e,0x00001656,0x0000154d, +0x00001655,0x00050051,0x00000006,0x00001657, +0x00001656,0x00000001,0x00050051,0x00000006, +0x00001658,0x00001656,0x00000000,0x00050080, +0x00000006,0x0000165d,0x00001555,0x00001657, +0x00050050,0x00000007,0x0000165e,0x00001658, +0x0000165d,0x0004007c,0x000000b1,0x0000164b, +0x0000165e,0x00060041,0x000000b7,0x0000164c, +0x0000164b,0x000000b6,0x000000b6,0x0006003d, +0x00000006,0x0000164d,0x0000164c,0x00000002, +0x00000004,0x00050096,0x0000005e,0x00001667, +0x000013b9,0x000015ee,0x00050051,0x00000006, +0x00001668,0x00001667,0x00000001,0x00050051, +0x00000006,0x00001669,0x00001667,0x00000000, +0x00050082,0x00000006,0x0000166f,0x000013bc, +0x00001609,0x00050082,0x00000006,0x00001671, +0x0000166f,0x00001668,0x00050095,0x0000005e, +0x0000167b,0x00001632,0x00001669,0x00050051, +0x00000006,0x0000167c,0x0000167b,0x00000001, +0x00050051,0x00000006,0x0000167d,0x0000167b, +0x00000000,0x00050080,0x00000006,0x00001683, +0x0000164d,0x00001671,0x00050080,0x00000006, +0x00001685,0x00001683,0x0000167c,0x00060052, +0x00000027,0x00001c53,0x0000167d,0x00000498, +0x00000000,0x000500c7,0x00000006,0x0000168d, +0x000013bb,0x00000191,0x000500c7,0x00000006, +0x00001690,0x00001685,0x0000017b,0x000500c5, +0x00000006,0x00001691,0x0000168d,0x00001690, +0x00060052,0x00000027,0x00001c57,0x00001691, +0x00001c53,0x00000001,0x000200f9,0x00001429, +0x000200f8,0x00001414,0x00060052,0x00000027, +0x00001c3c,0x00000058,0x00000498,0x00000000, +0x00060052,0x00000027,0x00001c3e,0x00000058, +0x00001c3c,0x00000001,0x00060052,0x00000027, +0x00001c40,0x00000058,0x00001c3e,0x00000002, +0x000200f9,0x00001429,0x000200f8,0x00001429, +0x000700f5,0x00000027,0x00001f7f,0x00001c40, +0x00001414,0x00001c57,0x00001418,0x000200f9, +0x000014ce,0x000200f8,0x0000142a,0x000200f9, +0x0000142b,0x000200f8,0x0000142b,0x000500c7, +0x00000006,0x0000142f,0x00000438,0x00000063, +0x000500ab,0x00000012,0x00001430,0x0000142f, +0x00000058,0x000300f7,0x00001436,0x00000000, +0x000400fa,0x00001430,0x00001431,0x00001436, +0x000200f8,0x00001431,0x000500c7,0x00000006, +0x00001434,0x000013bb,0x0000018b,0x000500ab, +0x00000012,0x00001435,0x00001434,0x00000058, +0x000200f9,0x00001436,0x000200f8,0x00001436, +0x000700f5,0x00000012,0x00001437,0x00001430, +0x0000142b,0x00001435,0x00001431,0x000300f7, +0x0000143d,0x00000000,0x000400fa,0x00001437, +0x00001438,0x0000143d,0x000200f8,0x00001438, +0x000500c5,0x00000006,0x0000143b,0x000013bc, +0x00000191,0x00060052,0x00000007,0x00001c5b, +0x0000143b,0x000013bd,0x00000001,0x000200f9, +0x0000143d,0x000200f8,0x0000143d,0x000700f5, +0x00000007,0x00001eb1,0x000013bd,0x00001436, +0x00001c5b,0x00001438,0x00050041,0x00000182, +0x0000143e,0x00000180,0x000000e4,0x0004003d, +0x00000006,0x0000143f,0x0000143e,0x000500ab, +0x00000012,0x00001440,0x0000143f,0x00000058, +0x000300f7,0x00001453,0x00000000,0x000400fa, +0x00001440,0x00001441,0x00001453,0x000200f8, +0x00001441,0x000500aa,0x00000012,0x00001444, +0x000013d9,0x00000058,0x000300f7,0x00001449, +0x00000000,0x000400fa,0x00001444,0x00001445, +0x00001449,0x000200f8,0x00001445,0x000500aa, +0x00000012,0x00001448,0x000013da,0x00000058, +0x000200f9,0x00001449,0x000200f8,0x00001449, +0x000700f5,0x00000012,0x0000144a,0x00001444, +0x00001441,0x00001448,0x00001445,0x000600a9, +0x00000007,0x0000144c,0x0000144a,0x00000208, +0x00002190,0x00050041,0x0000020a,0x0000144d, +0x00000180,0x00000325,0x0004003d,0x00000007, +0x0000144e,0x0000144d,0x000300f7,0x000016d7, +0x00000000,0x000300fb,0x00000058,0x000016a7, +0x000200f8,0x000016a7,0x000200f9,0x000016a9, +0x000200f8,0x000016a9,0x000700f5,0x00000006, +0x00001eb3,0x0000143f,0x000016a7,0x000021a1, +0x000016bf,0x000700f5,0x00000006,0x00001eb2, +0x00000058,0x000016a7,0x00002171,0x000016bf, +0x000500b0,0x00000012,0x000016ad,0x00001eb2, +0x00001eb3,0x000400f6,0x000016c0,0x000016bf, +0x00000000,0x000400fa,0x000016ad,0x000016ae, +0x000016c0,0x000200f8,0x000016ae,0x00050080, +0x00000006,0x000016b1,0x00001eb2,0x00001eb3, +0x000500c2,0x00000006,0x000016b2,0x000016b1, +0x00000063,0x00050084,0x00000006,0x000016b4, +0x0000009e,0x000016b2,0x00050051,0x00000006, +0x000016f6,0x0000144e,0x00000000,0x00050084, +0x00000006,0x000016f8,0x000016b2,0x0000034a, +0x00050095,0x0000005e,0x000016f9,0x000016f6, +0x000016f8,0x00050051,0x00000006,0x000016fa, +0x000016f9,0x00000001,0x00050051,0x00000006, +0x000016fb,0x000016f9,0x00000000,0x00050051, +0x00000006,0x000016fe,0x0000144e,0x00000001, +0x00050080,0x00000006,0x00001700,0x000016fe, +0x000016fa,0x00050050,0x00000007,0x00001701, +0x000016fb,0x00001700,0x0004007c,0x000000b1, +0x000016ee,0x00001701,0x00060041,0x000000b7, +0x000016ef,0x000016ee,0x000000b6,0x000000b6, +0x0006003d,0x00000006,0x000016f0,0x000016ef, +0x00000002,0x00000004,0x00050080,0x00000006, +0x000016e3,0x000016b4,0x00000063,0x00050084, +0x00000006,0x00001713,0x000016e3,0x0000009e, +0x00050095,0x0000005e,0x00001714,0x000016f6, +0x00001713,0x00050051,0x00000006,0x00001715, +0x00001714,0x00000001,0x00050051,0x00000006, +0x00001716,0x00001714,0x00000000,0x00050080, +0x00000006,0x0000171b,0x000016fe,0x00001715, +0x00050050,0x00000007,0x0000171c,0x00001716, +0x0000171b,0x0004007c,0x000000b1,0x00001709, +0x0000171c,0x00060041,0x000000b7,0x0000170a, +0x00001709,0x000000b6,0x000000b6,0x0006003d, +0x00000006,0x0000170b,0x0000170a,0x00000002, +0x00000004,0x00050051,0x00000006,0x00001720, +0x00001eb1,0x00000001,0x000500b0,0x00000012, +0x00001723,0x00001720,0x0000170b,0x000400a8, +0x00000012,0x00001724,0x00001723,0x000300f7, +0x00001733,0x00000000,0x000400fa,0x00001724, +0x00001725,0x00001733,0x000200f8,0x00001725, +0x000500aa,0x00000012,0x0000172a,0x00001720, +0x0000170b,0x000300f7,0x00001731,0x00000000, +0x000400fa,0x0000172a,0x0000172b,0x00001731, +0x000200f8,0x0000172b,0x00050051,0x00000006, +0x0000172d,0x00001eb1,0x00000000,0x000500b0, +0x00000012,0x00001730,0x0000172d,0x000016f0, +0x000200f9,0x00001731,0x000200f8,0x00001731, +0x000700f5,0x00000012,0x00001732,0x0000172a, +0x00001725,0x00001730,0x0000172b,0x000200f9, +0x00001733,0x000200f8,0x00001733,0x000700f5, +0x00000012,0x00001734,0x00001723,0x000016ae, +0x00001732,0x00001731,0x000300f7,0x000016be, +0x00000000,0x000400fa,0x00001734,0x000016b9, +0x000016bb,0x000200f8,0x000016bb,0x00050080, +0x00000006,0x000016bd,0x000016b2,0x00000063, +0x000200f9,0x000016be,0x000200f8,0x000016b9, +0x000200f9,0x000016be,0x000200f8,0x000016be, +0x000700f5,0x00000006,0x00002171,0x00001eb2, +0x000016b9,0x000016bd,0x000016bb,0x000600a9, +0x00000006,0x000021a1,0x00001734,0x000016b2, +0x00001eb3,0x000200f9,0x000016bf,0x000200f8, +0x000016bf,0x000200f9,0x000016a9,0x000200f8, +0x000016c0,0x000500aa,0x00000012,0x000016c2, +0x00001eb2,0x00000058,0x000300f7,0x000016c4, +0x00000000,0x000400fa,0x000016c2,0x000016c3, +0x000016c4,0x000200f8,0x000016c3,0x000200f9, +0x000016d7,0x000200f8,0x000016c4,0x00050082, +0x00000006,0x000016c6,0x00001eb2,0x00000063, +0x00050084,0x00000006,0x000016c7,0x0000009e, +0x000016c6,0x00050080,0x00000006,0x000016c8, +0x000016c7,0x000000d8,0x00050051,0x00000006, +0x00001752,0x0000144e,0x00000000,0x00050084, +0x00000006,0x00001754,0x000016c8,0x0000009e, +0x00050095,0x0000005e,0x00001755,0x00001752, +0x00001754,0x00050051,0x00000006,0x00001756, +0x00001755,0x00000001,0x00050051,0x00000006, +0x00001757,0x00001755,0x00000000,0x00050051, +0x00000006,0x0000175a,0x0000144e,0x00000001, +0x00050080,0x00000006,0x0000175c,0x0000175a, +0x00001756,0x00050050,0x00000007,0x0000175d, +0x00001757,0x0000175c,0x0004007c,0x000000b1, +0x0000174a,0x0000175d,0x00060041,0x000000b7, +0x0000174b,0x0000174a,0x000000b6,0x000000b6, +0x0006003d,0x00000006,0x0000174c,0x0000174b, +0x00000002,0x00000004,0x00050080,0x00000006, +0x0000173f,0x000016c7,0x000000de,0x00050084, +0x00000006,0x0000176f,0x0000173f,0x0000009e, +0x00050095,0x0000005e,0x00001770,0x00001752, +0x0000176f,0x00050051,0x00000006,0x00001771, +0x00001770,0x00000001,0x00050051,0x00000006, +0x00001772,0x00001770,0x00000000,0x00050080, +0x00000006,0x00001777,0x0000175a,0x00001771, +0x00050050,0x00000007,0x00001778,0x00001772, +0x00001777,0x0004007c,0x000000b1,0x00001765, +0x00001778,0x00060041,0x000000b7,0x00001766, +0x00001765,0x000000b6,0x000000b6,0x0006003d, +0x00000006,0x00001767,0x00001766,0x00000002, +0x00000004,0x00050051,0x00000006,0x0000177c, +0x00001eb1,0x00000001,0x000500b0,0x00000012, +0x0000177f,0x0000177c,0x00001767,0x000400a8, +0x00000012,0x00001780,0x0000177f,0x000300f7, +0x0000178f,0x00000000,0x000400fa,0x00001780, +0x00001781,0x0000178f,0x000200f8,0x00001781, +0x000500aa,0x00000012,0x00001786,0x0000177c, +0x00001767,0x000300f7,0x0000178d,0x00000000, +0x000400fa,0x00001786,0x00001787,0x0000178d, +0x000200f8,0x00001787,0x00050051,0x00000006, +0x00001789,0x00001eb1,0x00000000,0x000500b0, +0x00000012,0x0000178c,0x00001789,0x0000174c, +0x000200f9,0x0000178d,0x000200f8,0x0000178d, +0x000700f5,0x00000012,0x0000178e,0x00001786, +0x00001781,0x0000178c,0x00001787,0x000200f9, +0x0000178f,0x000200f8,0x0000178f,0x000700f5, +0x00000012,0x00001790,0x0000177f,0x000016c4, +0x0000178e,0x0000178d,0x000300f7,0x000016d5, +0x00000000,0x000400fa,0x00001790,0x000016ce, +0x000016d5,0x000200f8,0x000016ce,0x00050051, +0x00000006,0x00001798,0x00001eb1,0x00000000, +0x00050096,0x0000005e,0x00001799,0x0000174c, +0x00001798,0x00050051,0x00000006,0x0000179a, +0x00001799,0x00000001,0x00050051,0x00000006, +0x0000179b,0x00001799,0x00000000,0x00050082, +0x00000006,0x000017a1,0x00001767,0x0000177c, +0x00050082,0x00000006,0x000017a3,0x000017a1, +0x0000179a,0x00050051,0x00000006,0x000017aa, +0x0000144c,0x00000001,0x000500b0,0x00000012, +0x000017ab,0x000017a3,0x000017aa,0x000400a8, +0x00000012,0x000017ac,0x000017ab,0x000300f7, +0x000017bb,0x00000000,0x000400fa,0x000017ac, +0x000017ad,0x000017bb,0x000200f8,0x000017ad, +0x000500aa,0x00000012,0x000017b2,0x000017a3, +0x000017aa,0x000300f7,0x000017b9,0x00000000, +0x000400fa,0x000017b2,0x000017b3,0x000017b9, +0x000200f8,0x000017b3,0x00050051,0x00000006, +0x000017b7,0x0000144c,0x00000000,0x000500b0, +0x00000012,0x000017b8,0x0000179b,0x000017b7, +0x000200f9,0x000017b9,0x000200f8,0x000017b9, +0x000700f5,0x00000012,0x000017ba,0x000017b2, +0x000017ad,0x000017b8,0x000017b3,0x000200f9, +0x000017bb,0x000200f8,0x000017bb,0x000700f5, +0x00000012,0x000017bc,0x000017ab,0x000016ce, +0x000017ba,0x000017b9,0x000400a8,0x00000012, +0x000016d4,0x000017bc,0x000200f9,0x000016d5, +0x000200f8,0x000016d5,0x000700f5,0x00000012, +0x000016d6,0x00001790,0x0000178f,0x000016d4, +0x000017bb,0x000200f9,0x000016d7,0x000200f8, +0x000016d7,0x000700f5,0x00000012,0x00001eb4, +0x0000011e,0x000016c3,0x000016d6,0x000016d5, +0x000200f9,0x00001453,0x000200f8,0x00001453, +0x000700f5,0x00000012,0x00001454,0x00001440, +0x0000143d,0x00001eb4,0x000016d7,0x000300f7, +0x00001456,0x00000000,0x000400fa,0x00001454, +0x00001455,0x00001456,0x000200f8,0x00001455, +0x000200f9,0x000014ce,0x000200f8,0x00001456, +0x000500c6,0x00000006,0x000017c3,0x000000cb, +0x000013b9,0x00050084,0x00000006,0x000017c4, +0x000017c3,0x000000d0,0x000500c6,0x00000006, +0x000017c8,0x000017c4,0x000013bb,0x00050084, +0x00000006,0x000017c9,0x000017c8,0x000000d0, +0x000500c6,0x00000006,0x000017cd,0x000017c9, +0x000013d1,0x00050084,0x00000006,0x000017ce, +0x000017cd,0x000000d0,0x000500c6,0x00000006, +0x000017d2,0x000017ce,0x000013ac,0x00050084, +0x00000006,0x000017d3,0x000017d2,0x000000d0, +0x000500c2,0x00000006,0x000017d5,0x000017d3, +0x000000e4,0x000500c6,0x00000006,0x000017d7, +0x000017d3,0x000017d5,0x00050084,0x00000006, +0x000017d9,0x000017d7,0x000000e8,0x000500c2, +0x00000006,0x000017db,0x000017d9,0x000000ec, +0x000500c6,0x00000006,0x000017dd,0x000017d9, +0x000017db,0x00050084,0x00000006,0x000017df, +0x000017dd,0x000000f0,0x000500c2,0x00000006, +0x000017e1,0x000017df,0x000000e4,0x000500c6, +0x00000006,0x000017e3,0x000017df,0x000017e1, +0x000200f9,0x00001459,0x000200f8,0x00001459, +0x000700f5,0x00000006,0x00001ec5,0x00000058, +0x00001456,0x000014b7,0x000014b5,0x000500b0, +0x00000012,0x0000145c,0x00001ec5,0x0000034a, +0x000400f6,0x000014b8,0x000014b5,0x00000000, +0x000400fa,0x0000145c,0x0000145d,0x000014b8, +0x000200f8,0x0000145d,0x00050080,0x00000006, +0x00001460,0x000017e3,0x00001ec5,0x00050041, +0x00000182,0x00001461,0x00000180,0x000000ec, +0x0004003d,0x00000006,0x00001462,0x00001461, +0x000500c7,0x00000006,0x00001463,0x00001460, +0x00001462,0x00050084,0x00000006,0x00001464, +0x000002ab,0x00001463,0x00050080,0x00000006, +0x00001466,0x00001464,0x00000357,0x00050041, +0x0000020a,0x00001467,0x00000180,0x00000355, +0x0004003d,0x00000007,0x00001468,0x00001467, +0x00050051,0x00000006,0x000017f4,0x00001468, +0x00000000,0x00050084,0x00000006,0x000017f6, +0x00001466,0x0000009e,0x00050095,0x0000005e, +0x000017f7,0x000017f4,0x000017f6,0x00050051, +0x00000006,0x000017f8,0x000017f7,0x00000001, +0x00050051,0x00000006,0x000017f9,0x000017f7, +0x00000000,0x00050051,0x00000006,0x000017fc, +0x00001468,0x00000001,0x00050080,0x00000006, +0x000017fe,0x000017fc,0x000017f8,0x00050050, +0x00000007,0x000017ff,0x000017f9,0x000017fe, +0x0004007c,0x000000b1,0x000017ec,0x000017ff, +0x00060041,0x000000b7,0x000017ed,0x000017ec, +0x000000b6,0x000000b6,0x0006003d,0x00000006, +0x000017ee,0x000017ed,0x00000002,0x00000004, +0x000500c2,0x00000006,0x0000146a,0x000017ee, +0x000000e4,0x000500c7,0x00000006,0x0000146c, +0x0000146a,0x00000063,0x000500aa,0x00000012, +0x0000146d,0x0000146c,0x00000058,0x000300f7, +0x0000146f,0x00000000,0x000400fa,0x0000146d, +0x0000146e,0x0000146f,0x000200f8,0x0000146e, +0x000200f9,0x000014b5,0x000200f8,0x0000146f, +0x00050084,0x00000006,0x00001811,0x00001463, +0x0000218f,0x00050095,0x0000005e,0x00001812, +0x000017f4,0x00001811,0x00050051,0x00000006, +0x00001813,0x00001812,0x00000001,0x00050051, +0x00000006,0x00001814,0x00001812,0x00000000, +0x00050080,0x00000006,0x00001819,0x000017fc, +0x00001813,0x00050050,0x00000007,0x0000181a, +0x00001814,0x00001819,0x0004007c,0x000000b1, +0x00001807,0x0000181a,0x00060041,0x000000b7, +0x00001808,0x00001807,0x000000b6,0x000000b6, +0x0006003d,0x00000006,0x00001809,0x00001808, +0x00000002,0x00000004,0x000500ab,0x00000012, +0x00001476,0x00001809,0x000013b9,0x000400a8, +0x00000012,0x00001477,0x00001476,0x000300f7, +0x00001481,0x00000000,0x000400fa,0x00001477, +0x00001478,0x00001481,0x000200f8,0x00001478, +0x00050080,0x00000006,0x0000147a,0x00001464, +0x00000063,0x00050084,0x00000006,0x0000182c, +0x0000147a,0x0000009e,0x00050095,0x0000005e, +0x0000182d,0x000017f4,0x0000182c,0x00050051, +0x00000006,0x0000182e,0x0000182d,0x00000001, +0x00050051,0x00000006,0x0000182f,0x0000182d, +0x00000000,0x00050080,0x00000006,0x00001834, +0x000017fc,0x0000182e,0x00050050,0x00000007, +0x00001835,0x0000182f,0x00001834,0x0004007c, +0x000000b1,0x00001822,0x00001835,0x00060041, +0x000000b7,0x00001823,0x00001822,0x000000b6, +0x000000b6,0x0006003d,0x00000006,0x00001824, +0x00001823,0x00000002,0x00000004,0x000500ab, +0x00000012,0x00001480,0x00001824,0x000013bb, +0x000200f9,0x00001481,0x000200f8,0x00001481, +0x000700f5,0x00000012,0x00001482,0x00001476, +0x0000146f,0x00001480,0x00001478,0x000400a8, +0x00000012,0x00001483,0x00001482,0x000300f7, +0x0000148d,0x00000000,0x000400fa,0x00001483, +0x00001484,0x0000148d,0x000200f8,0x00001484, +0x00050080,0x00000006,0x00001486,0x00001464, +0x000000d8,0x00050084,0x00000006,0x00001847, +0x00001486,0x0000009e,0x00050095,0x0000005e, +0x00001848,0x000017f4,0x00001847,0x00050051, +0x00000006,0x00001849,0x00001848,0x00000001, +0x00050051,0x00000006,0x0000184a,0x00001848, +0x00000000,0x00050080,0x00000006,0x0000184f, +0x000017fc,0x00001849,0x00050050,0x00000007, +0x00001850,0x0000184a,0x0000184f,0x0004007c, +0x000000b1,0x0000183d,0x00001850,0x00060041, +0x000000b7,0x0000183e,0x0000183d,0x000000b6, +0x000000b6,0x0006003d,0x00000006,0x0000183f, +0x0000183e,0x00000002,0x00000004,0x000500ab, +0x00000012,0x0000148c,0x0000183f,0x000013d1, +0x000200f9,0x0000148d,0x000200f8,0x0000148d, +0x000700f5,0x00000012,0x0000148e,0x00001482, +0x00001481,0x0000148c,0x00001484,0x000400a8, +0x00000012,0x0000148f,0x0000148e,0x000300f7, +0x00001499,0x00000000,0x000400fa,0x0000148f, +0x00001490,0x00001499,0x000200f8,0x00001490, +0x00050080,0x00000006,0x00001492,0x00001464, +0x000000de,0x00050084,0x00000006,0x00001862, +0x00001492,0x0000009e,0x00050095,0x0000005e, +0x00001863,0x000017f4,0x00001862,0x00050051, +0x00000006,0x00001864,0x00001863,0x00000001, +0x00050051,0x00000006,0x00001865,0x00001863, +0x00000000,0x00050080,0x00000006,0x0000186a, +0x000017fc,0x00001864,0x00050050,0x00000007, +0x0000186b,0x00001865,0x0000186a,0x0004007c, +0x000000b1,0x00001858,0x0000186b,0x00060041, +0x000000b7,0x00001859,0x00001858,0x000000b6, +0x000000b6,0x0006003d,0x00000006,0x0000185a, +0x00001859,0x00000002,0x00000004,0x000500ab, +0x00000012,0x00001498,0x0000185a,0x000013ac, +0x000200f9,0x00001499,0x000200f8,0x00001499, +0x000700f5,0x00000012,0x0000149a,0x0000148e, +0x0000148d,0x00001498,0x00001490,0x000300f7, +0x0000149c,0x00000000,0x000400fa,0x0000149a, +0x0000149b,0x0000149c,0x000200f8,0x0000149b, +0x000200f9,0x000014b5,0x000200f8,0x0000149c, +0x000500c7,0x00000006,0x0000149e,0x0000146a, +0x000000d8,0x000500ab,0x00000012,0x0000149f, +0x0000149e,0x00000058,0x000300f7,0x000014b4, +0x00000000,0x000400fa,0x0000149f,0x000014a0, +0x000014a4,0x000200f8,0x000014a4,0x00050080, +0x00000006,0x000014a6,0x00001464,0x0000009e, +0x00050084,0x00000006,0x00001881,0x000014a6, +0x0000009e,0x00050095,0x0000005e,0x00001882, +0x000017f4,0x00001881,0x00050051,0x00000006, +0x00001883,0x00001882,0x00000001,0x00050051, +0x00000006,0x00001884,0x00001882,0x00000000, +0x00050080,0x00000006,0x00001889,0x000017fc, +0x00001883,0x00050050,0x00000007,0x0000188a, +0x00001884,0x00001889,0x0004007c,0x000000b1, +0x00001877,0x0000188a,0x00060041,0x000000b7, +0x00001878,0x00001877,0x000000b6,0x000000b6, +0x0006003d,0x00000006,0x00001879,0x00001878, +0x00000002,0x00000004,0x0006003d,0x00000006, +0x00001894,0x000017ed,0x00000002,0x00000004, +0x00060052,0x00000027,0x00001c9a,0x00001879, +0x00000498,0x00000000,0x000500c7,0x00000006, +0x000018ac,0x000013bb,0x00000191,0x000500c7, +0x00000006,0x000018af,0x00001894,0x0000017b, +0x000500c5,0x00000006,0x000018b0,0x000018ac, +0x000018af,0x00060052,0x00000027,0x00001c9e, +0x000018b0,0x00001c9a,0x00000001,0x000200f9, +0x000014b4,0x000200f8,0x000014a0,0x00060052, +0x00000027,0x00001c8f,0x00000058,0x00000498, +0x00000000,0x00060052,0x00000027,0x00001c91, +0x00000058,0x00001c8f,0x00000001,0x00060052, +0x00000027,0x00001c93,0x00000058,0x00001c91, +0x00000002,0x000200f9,0x000014b4,0x000200f8, +0x000014b4,0x000700f5,0x00000027,0x00001edf, +0x00001c93,0x000014a0,0x00001c9e,0x000014a4, +0x000200f9,0x000014b8,0x000200f8,0x000014b5, +0x00050080,0x00000006,0x000014b7,0x00001ec5, +0x000003bc,0x000200f9,0x00001459,0x000200f8, +0x000014b8,0x000700f5,0x00000006,0x00001eea, +0x00001da1,0x00001459,0x00000063,0x000014b4, +0x000700f5,0x00000027,0x00001ede,0x00000498, +0x00001459,0x00001edf,0x000014b4,0x000700f5, +0x00000012,0x00001eca,0x0000011e,0x00001459, +0x00000217,0x000014b4,0x000300f7,0x000014ba, +0x00000000,0x000400fa,0x00001eca,0x000014ce, +0x000014ba,0x000200f8,0x000014ba,0x00060052, +0x00000027,0x00001ca0,0x00000058,0x00001ede, +0x00000000,0x00060052,0x00000027,0x00001ca2, +0x00000058,0x00001ca0,0x00000001,0x00060052, +0x00000027,0x00001ca4,0x00000058,0x00001ca2, +0x00000002,0x000500c7,0x00000006,0x000014c0, +0x00000438,0x000000d8,0x000500ab,0x00000012, +0x000014c1,0x000014c0,0x00000058,0x000300f7, +0x000014ca,0x00000000,0x000400fa,0x000014c1, +0x000014c2,0x000014ca,0x000200f8,0x000014c2, +0x00050041,0x0000020a,0x000014c3,0x00000180, +0x000003c8,0x0004003d,0x00000007,0x000014c4, +0x000014c3,0x00050041,0x00000182,0x000014c5, +0x00000180,0x000003c9,0x0004003d,0x00000006, +0x000014c6,0x000014c5,0x000300f7,0x000018fa, +0x00000000,0x000300fb,0x00000058,0x000018ca, +0x000200f8,0x000018ca,0x000200f9,0x000018cc, +0x000200f8,0x000018cc,0x000700f5,0x00000006, +0x00001ee1,0x000014c6,0x000018ca,0x000021a2, +0x000018e2,0x000700f5,0x00000006,0x00001ee0, +0x00000058,0x000018ca,0x00002188,0x000018e2, +0x000500b0,0x00000012,0x000018d0,0x00001ee0, +0x00001ee1,0x000400f6,0x000018e3,0x000018e2, +0x00000000,0x000400fa,0x000018d0,0x000018d1, +0x000018e3,0x000200f8,0x000018d1,0x00050080, +0x00000006,0x000018d4,0x00001ee0,0x00001ee1, +0x000500c2,0x00000006,0x000018d5,0x000018d4, +0x00000063,0x00050084,0x00000006,0x000018d7, +0x0000009e,0x000018d5,0x00050051,0x00000006, +0x00001919,0x000014c4,0x00000000,0x00050084, +0x00000006,0x0000191b,0x000018d5,0x0000034a, +0x00050095,0x0000005e,0x0000191c,0x00001919, +0x0000191b,0x00050051,0x00000006,0x0000191d, +0x0000191c,0x00000001,0x00050051,0x00000006, +0x0000191e,0x0000191c,0x00000000,0x00050051, +0x00000006,0x00001921,0x000014c4,0x00000001, +0x00050080,0x00000006,0x00001923,0x00001921, +0x0000191d,0x00050050,0x00000007,0x00001924, +0x0000191e,0x00001923,0x0004007c,0x000000b1, +0x00001911,0x00001924,0x00060041,0x000000b7, +0x00001912,0x00001911,0x000000b6,0x000000b6, +0x0006003d,0x00000006,0x00001913,0x00001912, +0x00000002,0x00000004,0x00050080,0x00000006, +0x00001906,0x000018d7,0x00000063,0x00050084, +0x00000006,0x00001936,0x00001906,0x0000009e, +0x00050095,0x0000005e,0x00001937,0x00001919, +0x00001936,0x00050051,0x00000006,0x00001938, +0x00001937,0x00000001,0x00050051,0x00000006, +0x00001939,0x00001937,0x00000000,0x00050080, +0x00000006,0x0000193e,0x00001921,0x00001938, +0x00050050,0x00000007,0x0000193f,0x00001939, +0x0000193e,0x0004007c,0x000000b1,0x0000192c, +0x0000193f,0x00060041,0x000000b7,0x0000192d, +0x0000192c,0x000000b6,0x000000b6,0x0006003d, +0x00000006,0x0000192e,0x0000192d,0x00000002, +0x00000004,0x000500b0,0x00000012,0x00001946, +0x000013bc,0x0000192e,0x000400a8,0x00000012, +0x00001947,0x00001946,0x000300f7,0x00001956, +0x00000000,0x000400fa,0x00001947,0x00001948, +0x00001956,0x000200f8,0x00001948,0x000500aa, +0x00000012,0x0000194d,0x000013bc,0x0000192e, +0x000300f7,0x00001954,0x00000000,0x000400fa, +0x0000194d,0x0000194e,0x00001954,0x000200f8, +0x0000194e,0x000500b0,0x00000012,0x00001953, +0x000013b9,0x00001913,0x000200f9,0x00001954, +0x000200f8,0x00001954,0x000700f5,0x00000012, +0x00001955,0x0000194d,0x00001948,0x00001953, +0x0000194e,0x000200f9,0x00001956,0x000200f8, +0x00001956,0x000700f5,0x00000012,0x00001957, +0x00001946,0x000018d1,0x00001955,0x00001954, +0x000300f7,0x000018e1,0x00000000,0x000400fa, +0x00001957,0x000018dc,0x000018de,0x000200f8, +0x000018de,0x00050080,0x00000006,0x000018e0, +0x000018d5,0x00000063,0x000200f9,0x000018e1, +0x000200f8,0x000018dc,0x000200f9,0x000018e1, +0x000200f8,0x000018e1,0x000700f5,0x00000006, +0x00002188,0x00001ee0,0x000018dc,0x000018e0, +0x000018de,0x000600a9,0x00000006,0x000021a2, +0x00001957,0x000018d5,0x00001ee1,0x000200f9, +0x000018e2,0x000200f8,0x000018e2,0x000200f9, +0x000018cc,0x000200f8,0x000018e3,0x000500aa, +0x00000012,0x000018e5,0x00001ee0,0x00000058, +0x000300f7,0x000018e7,0x00000000,0x000400fa, +0x000018e5,0x000018e6,0x000018e7,0x000200f8, +0x000018e6,0x000200f9,0x000018fa,0x000200f8, +0x000018e7,0x00050082,0x00000006,0x000018e9, +0x00001ee0,0x00000063,0x00050084,0x00000006, +0x000018ea,0x0000009e,0x000018e9,0x00050080, +0x00000006,0x000018eb,0x000018ea,0x000000d8, +0x00050051,0x00000006,0x00001975,0x000014c4, +0x00000000,0x00050084,0x00000006,0x00001977, +0x000018eb,0x0000009e,0x00050095,0x0000005e, +0x00001978,0x00001975,0x00001977,0x00050051, +0x00000006,0x00001979,0x00001978,0x00000001, +0x00050051,0x00000006,0x0000197a,0x00001978, +0x00000000,0x00050051,0x00000006,0x0000197d, +0x000014c4,0x00000001,0x00050080,0x00000006, +0x0000197f,0x0000197d,0x00001979,0x00050050, +0x00000007,0x00001980,0x0000197a,0x0000197f, +0x0004007c,0x000000b1,0x0000196d,0x00001980, +0x00060041,0x000000b7,0x0000196e,0x0000196d, +0x000000b6,0x000000b6,0x0006003d,0x00000006, +0x0000196f,0x0000196e,0x00000002,0x00000004, +0x00050080,0x00000006,0x00001962,0x000018ea, +0x000000de,0x00050084,0x00000006,0x00001992, +0x00001962,0x0000009e,0x00050095,0x0000005e, +0x00001993,0x00001975,0x00001992,0x00050051, +0x00000006,0x00001994,0x00001993,0x00000001, +0x00050051,0x00000006,0x00001995,0x00001993, +0x00000000,0x00050080,0x00000006,0x0000199a, +0x0000197d,0x00001994,0x00050050,0x00000007, +0x0000199b,0x00001995,0x0000199a,0x0004007c, +0x000000b1,0x00001988,0x0000199b,0x00060041, +0x000000b7,0x00001989,0x00001988,0x000000b6, +0x000000b6,0x0006003d,0x00000006,0x0000198a, +0x00001989,0x00000002,0x00000004,0x000500b0, +0x00000012,0x000019a2,0x000013bc,0x0000198a, +0x000400a8,0x00000012,0x000019a3,0x000019a2, +0x000300f7,0x000019b2,0x00000000,0x000400fa, +0x000019a3,0x000019a4,0x000019b2,0x000200f8, +0x000019a4,0x000500aa,0x00000012,0x000019a9, +0x000013bc,0x0000198a,0x000300f7,0x000019b0, +0x00000000,0x000400fa,0x000019a9,0x000019aa, +0x000019b0,0x000200f8,0x000019aa,0x000500b0, +0x00000012,0x000019af,0x000013b9,0x0000196f, +0x000200f9,0x000019b0,0x000200f8,0x000019b0, +0x000700f5,0x00000012,0x000019b1,0x000019a9, +0x000019a4,0x000019af,0x000019aa,0x000200f9, +0x000019b2,0x000200f8,0x000019b2,0x000700f5, +0x00000012,0x000019b3,0x000019a2,0x000018e7, +0x000019b1,0x000019b0,0x000300f7,0x000018f8, +0x00000000,0x000400fa,0x000019b3,0x000018f1, +0x000018f8,0x000200f8,0x000018f1,0x00050096, +0x0000005e,0x000019bc,0x0000196f,0x000013b9, +0x00050051,0x00000006,0x000019bd,0x000019bc, +0x00000001,0x00050051,0x00000006,0x000019be, +0x000019bc,0x00000000,0x00050082,0x00000006, +0x000019c4,0x0000198a,0x000013bc,0x00050082, +0x00000006,0x000019c6,0x000019c4,0x000019bd, +0x000500aa,0x00000012,0x000019d5,0x000019c6, +0x00000058,0x000300f7,0x000019dc,0x00000000, +0x000400fa,0x000019d5,0x000019d6,0x000019dc, +0x000200f8,0x000019d6,0x000500b0,0x00000012, +0x000019db,0x000019be,0x00000063,0x000200f9, +0x000019dc,0x000200f8,0x000019dc,0x000700f5, +0x00000012,0x000019dd,0x000019d5,0x000018f1, +0x000019db,0x000019d6,0x000400a8,0x00000012, +0x000018f7,0x000019dd,0x000200f9,0x000018f8, +0x000200f8,0x000018f8,0x000700f5,0x00000012, +0x000018f9,0x000019b3,0x000019b2,0x000018f7, +0x000019dc,0x000200f9,0x000018fa,0x000200f8, +0x000018fa,0x000700f5,0x00000012,0x00001ee2, +0x0000011e,0x000018e6,0x000018f9,0x000018f8, +0x000400a8,0x00000012,0x000014c9,0x00001ee2, +0x000200f9,0x000014ca,0x000200f8,0x000014ca, +0x000700f5,0x00000012,0x000014cb,0x000014c1, +0x000014ba,0x000014c9,0x000018fa,0x000300f7, +0x000014cd,0x00000000,0x000400fa,0x000014cb, +0x000014cc,0x000014cd,0x000200f8,0x000014cc, +0x000200f9,0x000014ce,0x000200f8,0x000014cd, +0x000200f9,0x000014ce,0x000200f8,0x000014ce, +0x001100f5,0x00000027,0x00001f7e,0x00000498, +0x000013b6,0x00001c14,0x000013c7,0x00001f7f, +0x00001429,0x00000498,0x00001455,0x00001ede, +0x000014b8,0x00001ca4,0x000014cc,0x00001ca4, +0x000014cd,0x001100f5,0x00000006,0x00001ee9, +0x00000058,0x000013b6,0x00000063,0x000013c7, +0x00000063,0x00001429,0x00000063,0x00001455, +0x00001eea,0x000014b8,0x00000063,0x000014cc, +0x000000d8,0x000014cd,0x000500aa,0x00000012, +0x000004d0,0x00001ee9,0x000000d8,0x000300f7, +0x000004d2,0x00000000,0x000400fa,0x000004d0, +0x000004d1,0x000004d2,0x000200f8,0x000004d1, +0x00050041,0x00000182,0x000004d3,0x00000180, +0x000004c2,0x0004003d,0x00000006,0x000004d4, +0x000004d3,0x000500c4,0x00000006,0x000004d5, +0x000004d4,0x000004c5,0x000500c4,0x00000006, +0x000004d7,0x0000044f,0x00000063,0x000500c5, +0x00000006,0x000004d8,0x000004d5,0x000004d7, +0x000500c5,0x00000006,0x000004d9,0x000004d8, +0x00000063,0x00050041,0x0000020a,0x000019e3, +0x00000180,0x000003dd,0x0004003d,0x00000007, +0x000019e4,0x000019e3,0x0004007c,0x000000b1, +0x000019e5,0x000019e4,0x00060041,0x000000b7, +0x000019e7,0x000019e5,0x000000b6,0x000000b6, +0x000700ea,0x00000006,0x000019e8,0x000019e7, +0x00000063,0x00000058,0x00000063,0x00060041, +0x000000b7,0x000019eb,0x000019e5,0x000000b6, +0x000003bc,0x0006003d,0x00000006,0x000019ec, +0x000019eb,0x00000002,0x00000004,0x000500b0, +0x00000012,0x000019ed,0x000019e8,0x000019ec, +0x000300f7,0x000019f7,0x00000000,0x000400fa, +0x000019ed,0x000019ee,0x000019f4,0x000200f8, +0x000019f4,0x00060041,0x000000b7,0x000019f6, +0x000019e5,0x000000b6,0x000003f3,0x0005003e, +0x000019f6,0x00000063,0x00000002,0x00000004, +0x000200f9,0x000019f7,0x000200f8,0x000019ee, +0x00050080,0x00000006,0x000019f1,0x0000009e, +0x000019e8,0x00060041,0x000000b7,0x000019f3, +0x000019e5,0x000000b6,0x000019f1,0x0005003e, +0x000019f3,0x000004d9,0x00000002,0x00000004, +0x000200f9,0x000019f7,0x000200f8,0x000019f7, +0x000200f9,0x000004d2,0x000200f8,0x000004d2, +0x000200f9,0x000004ba,0x000200f8,0x000004ba, +0x000700f5,0x00000027,0x00001fbe,0x00000498, +0x000004a9,0x00001f7e,0x000004d2,0x000700f5, +0x00000027,0x00001f8b,0x0000219c,0x000004a9, +0x00001df6,0x000004d2,0x00050041,0x0000020a, +0x000004dd,0x00000180,0x000003bc,0x0004003d, +0x00000007,0x000004de,0x000004dd,0x0004007c, +0x00000468,0x000004df,0x000004de,0x00060041, +0x00000474,0x000004e4,0x000004df,0x000000b6, +0x0000048f,0x0005003e,0x000004e4,0x00001f8b, +0x00000002,0x00000010,0x00060041,0x00000474, +0x000004ea,0x000004df,0x000000b6,0x00000496, +0x0005003e,0x000004ea,0x00001fbe,0x00000002, +0x00000010,0x000300f7,0x000004ed,0x00000000, +0x000400fa,0x0000045b,0x000004ec,0x000004ed, +0x000200f8,0x000004ec,0x00050041,0x0000020a, +0x000004ef,0x00000180,0x00000451,0x0004003d, +0x00000007,0x000004f0,0x000004ef,0x0004007c, +0x00000468,0x000004f1,0x000004f0,0x000300f7, +0x000004fd,0x00000000,0x000400fa,0x000004b8, +0x000004fc,0x00000503,0x000200f8,0x00000503, +0x000200f9,0x000004fd,0x000200f8,0x000004fc, +0x000300f7,0x00001a40,0x00000000,0x000300fb, +0x00000058,0x00001a01,0x000200f8,0x00001a01, +0x000500ab,0x00000012,0x00001a05,0x000004b7, +0x00000058,0x000400a8,0x00000012,0x00001a06, +0x00001a05,0x000300f7,0x00001a0b,0x00000000, +0x000400fa,0x00001a06,0x00001a07,0x00001a0b, +0x000200f8,0x00001a07,0x00050051,0x00000006, +0x00001a09,0x0000219c,0x00000002,0x000500aa, +0x00000012,0x00001a0a,0x00001a09,0x00000058, +0x000200f9,0x00001a0b,0x000200f8,0x00001a0b, +0x000700f5,0x00000012,0x00001a0c,0x00001a05, +0x00001a01,0x00001a0a,0x00001a07,0x000300f7, +0x00001a0e,0x00000000,0x000400fa,0x00001a0c, +0x00001a0d,0x00001a0e,0x000200f8,0x00001a0d, +0x000200f9,0x00001a40,0x000200f8,0x00001a0e, +0x00050051,0x00000006,0x00001a10,0x0000219c, +0x00000001,0x000500c2,0x00000006,0x00001a11, +0x00001a10,0x000000e4,0x000500c7,0x00000006, +0x00001a12,0x00001a11,0x000001ad,0x00050051, +0x00000006,0x00001a14,0x0000219c,0x00000002, +0x000500aa,0x00000012,0x00001a16,0x00001a12, +0x00000058,0x000600a9,0x00000006,0x00001a18, +0x00001a16,0x00000063,0x00001a12,0x00050097, +0x0000005e,0x00001a1b,0x00001a14,0x00001a18, +0x00050051,0x00000006,0x00001a1c,0x00001a1b, +0x00000000,0x00050051,0x00000006,0x00001a1d, +0x00001a1b,0x00000001,0x00050051,0x00000006, +0x00001a1f,0x00001f8b,0x00000002,0x000500aa, +0x00000012,0x00001a20,0x00001a1f,0x00000058, +0x000300f7,0x00001a29,0x00000000,0x000400fa, +0x00001a20,0x00001a21,0x00001a22,0x000200f8, +0x00001a22,0x00050051,0x00000006,0x00001a24, +0x00001f8b,0x00000000,0x00050051,0x00000006, +0x00001a26,0x00001f8b,0x00000001,0x000500c7, +0x00000006,0x00001a27,0x00001a26,0x0000017b, +0x00050050,0x00000007,0x00001a28,0x00001a24, +0x00001a27,0x000200f9,0x00001a29,0x000200f8, +0x00001a21,0x000200f9,0x00001a29,0x000200f8, +0x00001a29,0x000700f5,0x00000007,0x00002069, +0x000001c2,0x00001a21,0x00001a28,0x00001a22, +0x00050051,0x00000006,0x00001a2c,0x0000219c, +0x00000000,0x000500c7,0x00000006,0x00001a2f, +0x00001a10,0x0000017b,0x00050051,0x00000006, +0x00001a31,0x00002069,0x00000001,0x000500c4, +0x00000006,0x00001a32,0x00001a31,0x000000e4, +0x000500c5,0x00000006,0x00001a33,0x00001a2f, +0x00001a32,0x00050051,0x00000006,0x00001a35, +0x00002069,0x00000000,0x000500ab,0x00000012, +0x00001a38,0x00001a1d,0x00000058,0x000600a9, +0x00000006,0x000021a3,0x00001a38,0x000001dc, +0x00001a1c,0x00070050,0x00000027,0x00001a3f, +0x00001a2c,0x00001a33,0x00001a35,0x000021a3, +0x000200f9,0x00001a40,0x000200f8,0x00001a40, +0x000700f5,0x00000027,0x0000206b,0x000001a7, +0x00001a0d,0x00001a3f,0x00001a29,0x000200f9, +0x000004fd,0x000200f8,0x000004fd,0x000700f5, +0x00000027,0x0000206c,0x0000206b,0x00001a40, +0x000001a7,0x00000503,0x00060041,0x00000474, +0x00000505,0x000004f1,0x000000b6,0x0000048f, +0x0005003e,0x00000505,0x0000206c,0x00000002, +0x00000010,0x000300f7,0x0000050d,0x00000000, +0x000400fa,0x000004b8,0x0000050c,0x00000513, +0x000200f8,0x00000513,0x000200f9,0x0000050d, +0x000200f8,0x0000050c,0x000300f7,0x00001a8a, +0x00000000,0x000300fb,0x00000058,0x00001a4b, +0x000200f8,0x00001a4b,0x00050051,0x00000006, +0x00001a4d,0x00000498,0x00000003,0x000500c2, +0x00000006,0x00001a4e,0x00001a4d,0x0000019b, +0x000500ab,0x00000012,0x00001a4f,0x00001a4e, +0x00000058,0x000400a8,0x00000012,0x00001a50, +0x00001a4f,0x000300f7,0x00001a55,0x00000000, +0x000400fa,0x00001a50,0x00001a51,0x00001a55, +0x000200f8,0x00001a51,0x00050051,0x00000006, +0x00001a53,0x00000498,0x00000002,0x000500aa, +0x00000012,0x00001a54,0x00001a53,0x00000058, +0x000200f9,0x00001a55,0x000200f8,0x00001a55, +0x000700f5,0x00000012,0x00001a56,0x00001a4f, +0x00001a4b,0x00001a54,0x00001a51,0x000300f7, +0x00001a58,0x00000000,0x000400fa,0x00001a56, +0x00001a57,0x00001a58,0x000200f8,0x00001a57, +0x000200f9,0x00001a8a,0x000200f8,0x00001a58, +0x00050051,0x00000006,0x00001a5a,0x00000498, +0x00000001,0x000500c2,0x00000006,0x00001a5b, +0x00001a5a,0x000000e4,0x000500c7,0x00000006, +0x00001a5c,0x00001a5b,0x000001ad,0x00050051, +0x00000006,0x00001a5e,0x00000498,0x00000002, +0x000500aa,0x00000012,0x00001a60,0x00001a5c, +0x00000058,0x000600a9,0x00000006,0x00001a62, +0x00001a60,0x00000063,0x00001a5c,0x00050097, +0x0000005e,0x00001a65,0x00001a5e,0x00001a62, +0x00050051,0x00000006,0x00001a66,0x00001a65, +0x00000000,0x00050051,0x00000006,0x00001a67, +0x00001a65,0x00000001,0x00050051,0x00000006, +0x00001a69,0x00001fbe,0x00000002,0x000500aa, +0x00000012,0x00001a6a,0x00001a69,0x00000058, +0x000300f7,0x00001a73,0x00000000,0x000400fa, +0x00001a6a,0x00001a6b,0x00001a6c,0x000200f8, +0x00001a6c,0x00050051,0x00000006,0x00001a6e, +0x00001fbe,0x00000000,0x00050051,0x00000006, +0x00001a70,0x00001fbe,0x00000001,0x000500c7, +0x00000006,0x00001a71,0x00001a70,0x0000017b, +0x00050050,0x00000007,0x00001a72,0x00001a6e, +0x00001a71,0x000200f9,0x00001a73,0x000200f8, +0x00001a6b,0x000200f9,0x00001a73,0x000200f8, +0x00001a73,0x000700f5,0x00000007,0x0000211f, +0x000001c2,0x00001a6b,0x00001a72,0x00001a6c, +0x00050051,0x00000006,0x00001a76,0x00000498, +0x00000000,0x000500c7,0x00000006,0x00001a79, +0x00001a5a,0x0000017b,0x00050051,0x00000006, +0x00001a7b,0x0000211f,0x00000001,0x000500c4, +0x00000006,0x00001a7c,0x00001a7b,0x000000e4, +0x000500c5,0x00000006,0x00001a7d,0x00001a79, +0x00001a7c,0x00050051,0x00000006,0x00001a7f, +0x0000211f,0x00000000,0x000500ab,0x00000012, +0x00001a82,0x00001a67,0x00000058,0x000600a9, +0x00000006,0x000021a4,0x00001a82,0x000001dc, +0x00001a66,0x00070050,0x00000027,0x00001a89, +0x00001a76,0x00001a7d,0x00001a7f,0x000021a4, +0x000200f9,0x00001a8a,0x000200f8,0x00001a8a, +0x000700f5,0x00000027,0x00002121,0x000001a7, +0x00001a57,0x00001a89,0x00001a73,0x000200f9, +0x0000050d,0x000200f8,0x0000050d,0x000700f5, +0x00000027,0x00002122,0x00002121,0x00001a8a, +0x000001a7,0x00000513,0x00060041,0x00000474, +0x00000515,0x000004f1,0x000000b6,0x00000496, +0x0005003e,0x00000515,0x00002122,0x00000002, +0x00000010,0x000200f9,0x000004ed,0x000200f8, +0x000004ed,0x000200f9,0x00000518,0x000200f8, +0x00000518,0x000100fd,0x00010038} diff --git a/runtime/src/console_heap_fix_spv.h b/runtime/src/console_heap_fix_spv.h new file mode 100644 index 0000000000..026f1c794f --- /dev/null +++ b/runtime/src/console_heap_fix_spv.h @@ -0,0 +1,11 @@ +#pragma once +#include + +namespace leonida { + +// console_heap_fix.comp compiled with: glslc --target-env=vulkan1.2 -O -mfmt=c console_heap_fix.comp -o console_heap_fix.inc +inline constexpr std::uint32_t console_heap_fix_spirv[] = +#include "console_heap_fix.inc" +; + +} // namespace leonida diff --git a/runtime/src/console_heap_gpu.h b/runtime/src/console_heap_gpu.h new file mode 100644 index 0000000000..b3a4c0ba4c --- /dev/null +++ b/runtime/src/console_heap_gpu.h @@ -0,0 +1,1058 @@ +// Console descriptor heap translation on the GPU (LEONIDA_CONSOLE_HEAP_GPU=1): the buffer V#s the title writes into +// its console descriptor heaps are rebased by a compute pass (console_heap_fix.comp) at the start of the submission +// that reads them, instead of one by one on the submitting thread (DeviceState::fix_console_slot). +// +// What stays on the CPU (shims/d3d12_vulkan_device.cpp): finding the changed slots (the heap's ShadowPages and a +// compare against the bytes each slot was last made from), registering the T#s (they are copied as they are; shaders +// find them by their words), and every lookup that can make something: a V# the pass cannot answer is written with no +// records and recorded in the pass's miss list; once the submission is done the CPU resolves its words with +// vsharp_address (which may make a geometry copy), enters the answer in the key table, and queues the slot again. +// +// The pass answers a V# half from four tables, in vsharp_address's order: +// - the range table: the title-VA ranges of the alias table (src/title_va_alias.h), sorted, each with the shader VA +// of its copy and whether the CPU found that copy backed. Rebuilt when the alias table or the backings change; +// - the backed table: the shader-VA spans of the live GPU allocations (DeviceState's gpu_backings, merged) and of +// the geometry copies' blocks. A base already inside one (a V# our API wrote, or the title copied) is left as it +// is, as vsharp_address's backed() leaves it. Merged neighbours make it a superset of what backed() accepts, but +// never of memory that is not there; +// - the key table: the exact 16 bytes of a V# half and what vsharp_address answered for them (a shader VA, or no +// backing), open addressed with up to kProbes slots per key (FNV-1a and fmix32). The CPU keeps the +// mirror below; its changes reach the GPU as updates the pass applies first, so the table changes in GPU order; +// - the ask table: the title's memory and its GPU windows. A base outside them that nothing above answered gets no +// records (vsharp_address could only answer 0); one inside them is a miss, for the CPU. +// When a backing or an alias range goes, every key entry whose answer falls in its shader VAs is dropped and every V# +// slot of the heap is translated again. +// +// ConsoleHeapKeys and console_heap_translate_slot are the CPU reference of the pass (vk_console_heap_gpu_test checks +// the GPU against them); ConsoleHeapGpu records the pass. +#pragma once +#ifndef VK_NO_PROTOTYPES +#define VK_NO_PROTOTYPES +#endif +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "console_heap_fix_spv.h" +#include "vulkan_aftermath.h" +#include "vulkan_memory.h" + +namespace leonida { + +struct ConsoleHeapRange { + std::uint64_t title_va = 0, end = 0, shader_va = 0; + bool checked = false; // the whole [shader_va, shader_va + end - title_va) is backed +}; + +// Sorted, disjoint [start, end) spans: the backed and ask tables. +using ConsoleHeapSpans = std::vector>; + +// Sorts and merges spans (overlapping or touching ones become one); empty and wrapping ones are dropped. +inline void merge_console_heap_spans(ConsoleHeapSpans& spans) { + std::erase_if(spans, [](const auto& s) { return s.second <= s.first; }); + std::sort(spans.begin(), spans.end()); + std::size_t out = 0; + for (std::size_t i = 0; i < spans.size(); ++i) { + if (out && spans[i].first <= spans[out - 1].second) spans[out - 1].second = std::max(spans[out - 1].second, spans[i].second); + else spans[out++] = spans[i]; + } + spans.resize(out); +} + +// [v, v + bytes) inside one span (bytes 0 counts as 1). +inline bool console_heap_spans_hold(const ConsoleHeapSpans& spans, std::uint64_t v, std::uint64_t bytes) { + auto it = std::upper_bound(spans.begin(), spans.end(), v, + [](std::uint64_t x, const auto& s) { return x < s.first; }); + if (it == spans.begin()) return false; + --it; + const std::uint64_t n = std::max(bytes, 1); + return v < it->second && n <= it->second - v; +} + +// What the reference (and the pass) answers from, besides the key table. +struct ConsoleHeapTables { + std::vector ranges; + ConsoleHeapSpans backed; + ConsoleHeapSpans ask; + bool use_ask = false; // without it every unanswered half is a miss + bool signed_offsets = false; // LEONIDA_IMPORT_BELOW_ARENA: a base with bit 47 set is a negative offset +}; + +// The key table's CPU mirror. An entry's GPU form is 8 dwords: the key, the answer's low 32 bits, its bits 32-47 and +// the flags in bits 16-31 of the sixth, two pad dwords. +class ConsoleHeapKeys { +public: + using Key = std::array; + static constexpr std::uint32_t kProbes = 16; + static constexpr std::uint32_t kUsed = 1, kNone = 2; + static constexpr std::uint32_t kEntryWords = 8, kUpdateWords = 12; + + explicit ConsoleHeapKeys(std::uint32_t log2_entries = 20) + : mask_((1u << std::min(log2_entries, 26)) - 1), entries_(std::size_t(mask_) + 1), + dirty_flag_(std::size_t(mask_) + 1, 0) {} + + // FNV-1a over the four dwords, then MurmurHash3's fmix32 (console_heap_fix.comp key_hash): the finalizer makes + // the low bits, which index the table, depend on every bit of the key. Bare FNV-1a put every V# whose base + // differed only above bit 20 into one probe chain, and the 17th of them found no slot. + static std::uint32_t hash(const Key& k) { + std::uint32_t h = 2166136261u; + for (const std::uint32_t w : k) h = (h ^ w) * 16777619u; + h ^= h >> 16; + h *= 0x85EBCA6Bu; + h ^= h >> 13; + h *= 0xC2B2AE35u; + h ^= h >> 16; + return h; + } + + std::uint32_t mask() const { return mask_; } + std::size_t size() const { return used_; } + std::size_t capacity() const { return entries_.size(); } + + // The entry's index, or -1. + std::int64_t find(const Key& k) const { + const std::uint32_t h = hash(k); + for (std::uint32_t p = 0; p < kProbes; ++p) { + const std::uint32_t at = (h + p) & mask_; + if (entries_[at].flags & kUsed && entries_[at].key == k) return at; + } + return -1; + } + // True with the answer when the key is entered: `none` for no backing. + bool lookup(const Key& k, std::uint64_t& to, bool& none) const { + const std::int64_t at = find(k); + if (at < 0) return false; + to = entries_[std::size_t(at)].to; + none = entries_[std::size_t(at)].flags & kNone; + return true; + } + + // Enters (or replaces) the answer for `k`: the shader VA `to` reaching `span` bytes, or no backing. False when all + // of the key's probe slots hold other keys. + bool put(const Key& k, std::uint64_t to, std::uint64_t span, bool none) { + std::int64_t at = find(k); + if (at < 0) { + const std::uint32_t h = hash(k); + for (std::uint32_t p = 0; p < kProbes && at < 0; ++p) + if (!(entries_[(h + p) & mask_].flags & kUsed)) at = (h + p) & mask_; + if (at < 0) return false; + ++used_; + } else { + unindex(std::uint32_t(at)); + } + Entry& e = entries_[std::size_t(at)]; + e.key = k; + e.to = to; + e.span = span; + e.flags = kUsed | (none ? kNone : 0); + if (!none) { + by_to_.emplace(to, std::uint32_t(at)); + longest_ = std::max(longest_, span); + } + touch(std::uint32_t(at)); + return true; + } + + bool erase(const Key& k) { + const std::int64_t at = find(k); + if (at < 0) return false; + erase_at(std::uint32_t(at)); + return true; + } + + // Every answer reaching into [start, end) of the shader VAs: dropped. Returns how many. + std::size_t erase_overlapping(std::uint64_t start, std::uint64_t end) { + if (end <= start || by_to_.empty()) return 0; + const std::uint64_t from = start > longest_ ? start - longest_ : 0; + std::vector gone; + for (auto it = by_to_.lower_bound(from); it != by_to_.end() && it->first < end; ++it) { + const Entry& e = entries_[it->second]; + if (e.to + std::max(e.span, 1) > start) gone.push_back(it->second); + } + for (const std::uint32_t at : gone) erase_at(at); + return gone.size(); + } + + // Every "no backing" answer, for a caller that asks again after something changed: their keys. + void take_none(std::vector& out, std::size_t at_most) { + out.clear(); + for (std::uint32_t at = 0; at < entries_.size() && out.size() < at_most; ++at) { + if ((entries_[at].flags & (kUsed | kNone)) != (kUsed | kNone)) continue; + out.push_back(entries_[at].key); + erase_at(at); + } + } + + void clear() { + for (std::uint32_t at = 0; at < entries_.size(); ++at) + if (entries_[at].flags & kUsed) erase_at(at); + by_to_.clear(); + longest_ = 0; + } + // Everything gone with no updates: for a GPU table that is cleared as a whole (ConsoleHeapGpu::reset_keys). + void clear_silent() { + std::fill(entries_.begin(), entries_.end(), Entry{}); + for (const std::uint32_t at : dirty_) dirty_flag_[at] = 0; + dirty_.clear(); + by_to_.clear(); + used_ = 0; + longest_ = 0; + } + + void gpu_words(std::uint32_t at, std::uint32_t out[kEntryWords]) const { + const Entry& e = entries_[at]; + std::memset(out, 0, kEntryWords * 4); + if (!(e.flags & kUsed)) return; + for (int i = 0; i < 4; ++i) out[i] = e.key[i]; + out[4] = std::uint32_t(e.to); + out[5] = std::uint32_t((e.to >> 32) & 0xffffu) | (std::uint32_t(e.flags) << 16); + } + + // The entries changed since the last take, as update records (index, 3 pad dwords, the entry's 8 dwords). + void take_updates(std::vector& out) { + out.clear(); + out.reserve(dirty_.size() * kUpdateWords); + for (const std::uint32_t at : dirty_) { + dirty_flag_[at] = 0; + const std::size_t base = out.size(); + out.resize(base + kUpdateWords, 0); + out[base] = at; + gpu_words(at, out.data() + base + 4); + } + dirty_.clear(); + } + bool has_updates() const { return !dirty_.empty(); } + // Every entry again (a new GPU table, or updates that never reached the GPU). + void touch_all() { + for (std::uint32_t at = 0; at < entries_.size(); ++at) + if (entries_[at].flags & kUsed) touch(at); + } + void touch(std::uint32_t at) { + if (!dirty_flag_[at]) { + dirty_flag_[at] = 1; + dirty_.push_back(at); + } + } + +private: + struct Entry { + Key key{}; + std::uint64_t to = 0; + std::uint64_t span = 0; + std::uint32_t flags = 0; + }; + void unindex(std::uint32_t at) { + const Entry& e = entries_[at]; + if (!(e.flags & kUsed) || (e.flags & kNone)) return; + auto [lo, hi] = by_to_.equal_range(e.to); + for (auto it = lo; it != hi; ++it) + if (it->second == at) { + by_to_.erase(it); + break; + } + } + void erase_at(std::uint32_t at) { + if (!(entries_[at].flags & kUsed)) return; + unindex(at); + entries_[at] = Entry{}; + --used_; + touch(at); + } + + std::uint32_t mask_; + std::vector entries_; + std::size_t used_ = 0; + std::multimap by_to_; // positive answers by shader VA + std::uint64_t longest_ = 0; + std::vector dirty_; + std::vector dirty_flag_; +}; + +// What the pass does to one V# half (console_heap_fix.comp translate()): 0 left as it is, 1 answered by a table +// (rebased, written with no records, or left as it is), 2 missed (written with no records). +inline unsigned console_heap_translate_half(std::uint32_t k[4], const ConsoleHeapTables& t, + const ConsoleHeapKeys& keys) { + if ((k[3] >> 30) || !k[2]) return 0; + const auto no_records = [k] { k[0] = k[1] = k[2] = 0; }; + const auto rebase = [k](std::uint64_t to) { + k[0] = std::uint32_t(to); + k[1] = (k[1] & 0xffff0000u) | std::uint32_t((to >> 32) & 0xffffu); + }; + const std::uint64_t base = std::uint64_t(k[0]) | (std::uint64_t(k[1] & 0xffffu) << 32); + if (!base) return no_records(), 1; + const std::uint32_t stride = (k[1] >> 16) & 0x3fffu; + const std::uint64_t span = std::uint64_t(k[2]) * (stride ? stride : 1); + auto it = std::upper_bound(t.ranges.begin(), t.ranges.end(), base, + [](std::uint64_t va, const ConsoleHeapRange& r) { return va < r.title_va; }); + if (it != t.ranges.begin()) { + const ConsoleHeapRange& r = *std::prev(it); + if (base < r.end && r.checked) { + if (r.end - base < span) no_records(); + else rebase(r.shader_va + (base - r.title_va)); + return 1; + } + } + std::uint64_t offset = base; + if (t.signed_offsets && (base & (1ull << 47))) offset |= ~((1ull << 48) - 1); + if (console_heap_spans_hold(t.backed, offset, span)) return 1; + const ConsoleHeapKeys::Key key{k[0], k[1], k[2], k[3]}; + std::uint64_t to = 0; + bool none = false; + if (keys.lookup(key, to, none)) { + if (none) no_records(); + else rebase(to); + return 1; + } + no_records(); + if (t.use_ask && !console_heap_spans_hold(t.ask, base, 1)) return 1; + return 2; +} + +// One 32-byte slot as the pass writes it; the bit of each half that missed (1: dwords 0-3, 2: dwords 4-7). +// `zero_first`: the work item's bit 31 (ConsoleHeapGpu::kZeroFirst). +inline unsigned console_heap_translate_slot(std::uint32_t w[8], const ConsoleHeapTables& t, + const ConsoleHeapKeys& keys, bool zero_first = false) { + if (w[3] >> 30) { + if (zero_first) w[0] = w[1] = w[2] = w[3] = 0; + else return 0; + } + unsigned missed = 0; + if (console_heap_translate_half(w, t, keys) == 2) missed |= 1; + if (console_heap_translate_half(w + 4, t, keys) == 2) missed |= 2; + return missed; +} + +// The pass itself: the key table on the GPU, the range table's versions, the slots to translate per heap, and the +// passes in flight with their miss lists. Every method takes the object's own lock (a leaf: it takes no other). +class ConsoleHeapGpu { +public: + static constexpr unsigned kMaxHeaps = 8; + // A queued slot's bit 31: the slot is neither a buffer pair nor a T# the CPU could decode, and the pass writes its + // dwords 0-3 as zeros. The last queue() of a slot before a pass decides it. + static constexpr std::uint32_t kZeroFirst = 0x80000000u; + static constexpr std::uint32_t kMissCapacity = 1u << 16; + static constexpr std::uint32_t kMissHeader = 4; + + struct Stats { + std::uint64_t passes = 0, slots = 0, updates = 0, misses = 0, overflows = 0, tables = 0, resets = 0; + std::uint64_t rescanned = 0; // slots of rescan() dispatches + std::uint64_t filtered = 0; // slots of rescan_filtered() dispatches + std::uint64_t copies = 0, copy_bytes = 0; // queue_copy() + std::uint64_t failed = 0; // passes whose submission did not reach the queue (their work went back) + }; + enum TableKind : unsigned { range_table, backed_table, ask_table, change_shader_table, change_title_table, table_count }; + + ConsoleHeapGpu(PFN_vkGetDeviceProcAddr get, VkDevice device, const VkPhysicalDeviceMemoryProperties& memory, + std::uint32_t log2_keys = 20) + : get_(get), device_(device), memory_(memory), keys_(log2_keys) {} + ~ConsoleHeapGpu() { + std::lock_guard lock(mutex_); + for (auto& pass : in_flight_) free_buffer(pass.buffer); + for (Heap& h : heaps_) free_buffer(h.meta); + for (auto& b : retired_) free_buffer(b); + for (auto& buffer : pool_) free_buffer(buffer); + for (Table& t : tables_) { + for (auto& [version, buffer] : t.old) free_buffer(buffer); + for (auto& buffer : t.pool) free_buffer(buffer); + 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); + } + ConsoleHeapGpu(const ConsoleHeapGpu&) = delete; + ConsoleHeapGpu& operator=(const ConsoleHeapGpu&) = delete; + + // The pipeline and the GPU key table (device-local, zeroed by the first pass). False: the pass cannot run. + bool init() { + std::lock_guard lock(mutex_); + if (pipeline_) return true; + if (!make_pipeline()) return false; + const VkDeviceSize bytes = VkDeviceSize(keys_.capacity()) * ConsoleHeapKeys::kEntryWords * 4; + if (!make_buffer(bytes, false, key_table_)) return false; + clear_keys_ = true; + return true; + } + + // A heap the pass writes: its title bytes (`input`) and the copy shaders read (`copy`), `slots` 32-byte slots. + // -1 when there is no room. + // Each heap also gets device-local metadata, 32 bytes a slot (what the pass last made of each V# half), which + // lets a filtered rescan pass over the slots no change touches without reading their words (rescan_filtered). + int add_heap(VkDeviceAddress input, VkDeviceAddress copy, std::uint32_t slots) { + std::lock_guard lock(mutex_); + for (unsigned i = 0; i < kMaxHeaps; ++i) { + if (heaps_[i].slots) continue; + Heap& h = heaps_[i]; + h = Heap{}; + h.input = input; + h.copy = copy; + h.slots = slots; + h.queued.assign(slots, 0); + if (make_buffer(VkDeviceSize(slots) * 32, false, h.meta)) h.meta_clear = true; + return int(i); + } + return -1; + } + void remove_heap(int heap) { + std::lock_guard lock(mutex_); + if (heap < 0 || unsigned(heap) >= kMaxHeaps) return; + if (heaps_[heap].meta.buffer) retired_.push_back(heaps_[heap].meta); // a pass in flight may still write it + heaps_[heap] = Heap{}; + } + + void queue(int heap, std::uint32_t slot) { + std::lock_guard lock(mutex_); + queue_locked(heap, slot); + } + // A buffer copy for the start of the next pass, before the heap translation (LEONIDA_SHADOW_GPU: a slot-133 shadow's + // pages copied from an import of the title's pages). `keep` (the source import) lives until that pass retires. + void queue_copy(VkBuffer src, VkDeviceSize src_offset, VkBuffer dst, VkDeviceSize dst_offset, VkDeviceSize bytes, + std::shared_ptr keep) { + std::lock_guard lock(mutex_); + copies_.push_back({src, dst, {src_offset, dst_offset, bytes}}); + if (keep) keeps_.push_back(std::move(keep)); + } + + // Queued copies into `dst` dropped (its buffer is about to go); copies already recorded stay with their pass. + void drop_copies_to(VkBuffer dst) { + std::lock_guard lock(mutex_); + std::erase_if(copies_, [dst](const Copy& c) { return c.dst == dst; }); + } + + // Every buffer pair of slots [0, slots) translated again by the next pass: one dispatch over the range, no list + // (the pass reads each slot's words and leaves the slots that hold no pair as they are). + void rescan(int heap, std::uint32_t slots) { + std::lock_guard lock(mutex_); + if (heap < 0 || unsigned(heap) >= kMaxHeaps) return; + heaps_[heap].rescan = std::max(heaps_[heap].rescan, std::min(slots, heaps_[heap].slots)); + } + // Like rescan(), but only the slots whose metadata meets a change span: `shader` spans of shader VAs (backings and + // alias copies that went: a half whose title base or result reaches into one) and `title` spans of title VAs + // (alias ranges that went, words answered since: a half whose title base is in one). Without metadata, every + // slot of the range, as rescan(). + void rescan_filtered(int heap, std::uint32_t slots, const ConsoleHeapSpans& shader, const ConsoleHeapSpans& title) { + std::lock_guard lock(mutex_); + if (heap < 0 || unsigned(heap) >= kMaxHeaps) return; + heaps_[heap].rescan_filtered = std::max(heaps_[heap].rescan_filtered, std::min(slots, heaps_[heap].slots)); + change_shader_.insert(change_shader_.end(), shader.begin(), shader.end()); + change_title_.insert(change_title_.end(), title.begin(), title.end()); + } + template + void queue(int heap, It first, It last) { + std::lock_guard lock(mutex_); + for (; first != last; ++first) queue_locked(heap, *first); + } + + // A new range table for the next pass (sorted by title VA, not overlapping). + void set_ranges(const std::vector& ranges) { + std::lock_guard lock(mutex_); + Table& t = tables_[range_table]; + t.words.clear(); + for (const ConsoleHeapRange& r : ranges) + t.words.insert(t.words.end(), {std::uint32_t(r.title_va), std::uint32_t(r.title_va >> 32), + std::uint32_t(r.end), std::uint32_t(r.end >> 32), + std::uint32_t(r.shader_va), std::uint32_t(r.shader_va >> 32), + r.checked ? 1u : 0u, 0u}); + t.count = std::uint32_t(ranges.size()); + t.dirty = true; + } + // New backed or ask spans (merged) for the next pass. + void set_spans(TableKind kind, const ConsoleHeapSpans& spans) { + std::lock_guard lock(mutex_); + spans_locked(kind, spans); + } + void spans_locked(TableKind kind, const ConsoleHeapSpans& spans) { + Table& t = tables_[kind]; + t.words.clear(); + for (const auto& [start, end] : spans) + t.words.insert(t.words.end(), {std::uint32_t(start), std::uint32_t(start >> 32), std::uint32_t(end), + std::uint32_t(end >> 32)}); + t.count = std::uint32_t(spans.size()); + t.dirty = true; + if (kind == ask_table) use_ask_ = true; + } + void set_signed_offsets(bool on) { + std::lock_guard lock(mutex_); + signed_offsets_ = on; + } + // Every key entry gone at once (the GPU table is cleared by the next pass), for a table filling up. + void reset_keys() { + std::lock_guard lock(mutex_); + keys_.clear_silent(); + clear_keys_ = true; + ++stats_.resets; + } + + template + auto with_keys(F&& f) { + std::lock_guard lock(mutex_); + return f(keys_); + } + + bool pending() { + std::lock_guard lock(mutex_); + return pending_locked(); + } + + // Records the pass into `cb`, ahead of the submission's lists: the key table updates, then each heap's queued + // slots, between barriers that order it after earlier work on the queue and before everything after it (and the + // host's read of the miss list). True when something was recorded; commit() must follow the submit. + bool record(VkCommandBuffer cb) { + std::lock_guard lock(mutex_); + if (!pipeline_ || !pending_locked() || in_flight_.size() >= 64) return false; + if (clear_keys_) keys_.touch_all(); + std::vector updates; + keys_.take_updates(updates); + const std::uint32_t update_count = std::uint32_t(updates.size() / ConsoleHeapKeys::kUpdateWords); + std::size_t work = 0; + for (const Heap& h : heaps_) work += h.work.size(); + const VkDeviceSize bytes = VkDeviceSize(kMissHeader + kMissCapacity) * 4 + VkDeviceSize(work) * 4 + + VkDeviceSize(updates.size()) * 4 + 64; + Pass pass{}; + if (!acquire_buffer(bytes, pass.buffer)) { + for (std::size_t i = 0; i < updates.size(); i += ConsoleHeapKeys::kUpdateWords) keys_.touch(updates[i]); + return false; + } + // A filtered rescan's change spans, merged, as this pass's change tables. + bool filtered = false; + for (const Heap& h : heaps_) filtered |= h.rescan_filtered && !h.rescan; + ConsoleHeapSpans change_shader, change_title; + if (filtered) { + change_shader = change_shader_; + change_title = change_title_; + merge_console_heap_spans(change_shader); + merge_console_heap_spans(change_title); + spans_locked(change_shader_table, change_shader); + spans_locked(change_title_table, change_title); + } + for (unsigned kind = 0; kind < table_count; ++kind) { + if (tables_[kind].dirty && !publish(tables_[kind], kind == range_table ? 32 : 16)) { + pool_.push_back(pass.buffer); + for (std::size_t i = 0; i < updates.size(); i += ConsoleHeapKeys::kUpdateWords) keys_.touch(updates[i]); + return false; + } + pass.versions[kind] = tables_[kind].version; + } + auto* words = static_cast(pass.buffer.mapped); + words[0] = 0; + words[1] = kMissCapacity; + words[2] = 0; + words[3] = 0; + std::size_t at = kMissHeader + kMissCapacity; + const VkDeviceAddress base = pass.buffer.address; + 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"); + // 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"); + for (std::size_t i = 0; i < copies_.size();) { + std::size_t j = i; + regions.clear(); + while (j < copies_.size() && copies_[j].src == copies_[i].src && copies_[j].dst == copies_[i].dst) { + regions.push_back(copies_[j].region); + stats_.copy_bytes += copies_[j].region.size; + ++j; + } + copy(cb, copies_[i].src, copies_[i].dst, std::uint32_t(regions.size()), regions.data()); + stats_.copies += regions.size(); + i = j; + } + VkMemoryBarrier copied{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + copied.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + copied.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; + barrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1, &copied, 0, nullptr, 0, + nullptr); + pass.copies = std::move(copies_); + pass.keeps = std::move(keeps_); + copies_.clear(); + keeps_.clear(); + } + // No barrier against the queue's earlier work: one from ALL_COMMANDS made every submission wait for the one + // 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_); + Push p{}; + const auto address = [&](TableKind kind) { return tables_[kind].current ? tables_[kind].current->address : 0; }; + p.ranges = address(range_table); + p.backed = address(backed_table); + p.ask = address(ask_table); + p.keys = key_table_.address; + p.misses = base; + p.range_count = tables_[range_table].current ? tables_[range_table].count : 0; + p.backed_count = tables_[backed_table].current ? tables_[backed_table].count : 0; + p.ask_count = tables_[ask_table].current ? tables_[ask_table].count : 0; + 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); + 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; + barrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 1, &filled, 0, + nullptr, 0, nullptr); + } + // New heaps' metadata starts at zero (no half known). + 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); + h.meta_clear = false; + meta_filled = true; + pass.filled.push_back(int(&h - heaps_.data())); + } + if (meta_filled) { + 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; + barrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 1, &filled, 0, + nullptr, 0, nullptr); + } + if (update_count) { + p.work = update_address; // MODE_UPDATE's records + p.count = update_count; + p.mode = 1; + push(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(p), &p); + dispatch(cb, (update_count + 63) / 64, 1, 1); + VkMemoryBarrier written{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + written.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; + written.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; + barrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 1, &written, 0, + nullptr, 0, nullptr); + } + p.mode = 0; + p.cshader = filtered ? address(change_shader_table) : 0; + p.ctitle = filtered ? address(change_title_table) : 0; + p.cshader_count = filtered && tables_[change_shader_table].current ? tables_[change_shader_table].count : 0; + p.ctitle_count = filtered && tables_[change_title_table].current ? tables_[change_title_table].count : 0; + for (unsigned i = 0; i < kMaxHeaps; ++i) { + Heap& h = heaps_[i]; + const bool full = h.rescan != 0; + const std::uint32_t slots = full ? std::max(h.rescan, h.rescan_filtered) : h.rescan_filtered; + if (!slots) continue; + // Before the listed slots, so a slot both rewritten and rescanned ends with its listed (newer) form. + p.input_slots = h.input; + p.copy_slots = h.copy; + p.meta = h.meta.address; + p.heap = i; + const std::uint32_t flags = p.flags; + p.flags |= 4u; // FLAG_RANGE + if (!full) p.flags |= 8u; // FLAG_FILTER + for (std::uint32_t first = 0; first < slots; first += 65535u * 64u) { + const std::uint32_t n = std::min(slots - first, 65535u * 64u); + p.work = first; + p.count = n; + push(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(p), &p); + dispatch(cb, (n + 63) / 64, 1, 1); + (full ? stats_.rescanned : stats_.filtered) += n; + } + p.flags = flags; + pass.rescans.push_back({int(i), slots, !full}); + h.rescan = h.rescan_filtered = 0; + } + if (filtered) { + pass.change_shader = std::move(change_shader); + pass.change_title = std::move(change_title); + } + change_shader_.clear(); + change_title_.clear(); + if (!pass.rescans.empty()) { // the listed slots' writes land after the rescan's + VkMemoryBarrier rescanned{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + rescanned.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; + rescanned.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; + barrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 1, &rescanned, + 0, nullptr, 0, nullptr); + } + for (unsigned i = 0; i < kMaxHeaps; ++i) { + Heap& h = heaps_[i]; + if (h.work.empty()) continue; + std::memcpy(words + at, h.work.data(), h.work.size() * 4); + pass.work.push_back({int(i), std::move(h.work)}); + const auto& list = pass.work.back().second; + for (const std::uint32_t item : list) h.queued[item & ~kZeroFirst] = 0; + h.work.clear(); + p.input_slots = h.input; + p.copy_slots = h.copy; + p.meta = h.meta.address; + p.heap = i; + // At most 65535 groups a dispatch (the guaranteed limit). + for (std::size_t first = 0; first < list.size(); first += 65535ull * 64) { + const std::uint32_t n = std::uint32_t(std::min(list.size() - first, 65535ull * 64)); + p.work = base + (at + first) * 4; + p.count = n; + push(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(p), &p); + dispatch(cb, (n + 63) / 64, 1, 1); + stats_.slots += n; + } + at += list.size(); + } + VkMemoryBarrier after{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + after.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; + after.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT | VK_ACCESS_HOST_READ_BIT; + barrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, + 0, 1, &after, 0, nullptr, 0, nullptr); + pass.updates = std::move(updates); + pass.cleared = clear_keys_; + clear_keys_ = false; + stats_.updates += update_count; + ++stats_.passes; + in_flight_.push_back(std::move(pass)); + return true; + } + + // After the submit of the command buffer record() wrote into: `ticket` is a retire ticket at or after that + // submission. Not submitted: its slots and updates are queued again. + void commit(bool submitted, std::uint64_t ticket) { + std::lock_guard lock(mutex_); + for (auto it = in_flight_.rbegin(); it != in_flight_.rend(); ++it) { + if (it->committed) continue; + if (submitted) { + it->committed = true; + it->ticket = ticket; + return; + } + ++stats_.failed; + for (const auto& [heap, list] : it->work) + if (heaps_[heap].slots) + for (const std::uint32_t item : list) queue_locked(heap, item); + for (const auto& r : it->rescans) { + if (!heaps_[r.heap].slots) continue; + auto& to = r.filtered ? heaps_[r.heap].rescan_filtered : heaps_[r.heap].rescan; + to = std::max(to, r.slots); + } + change_shader_.insert(change_shader_.end(), it->change_shader.begin(), it->change_shader.end()); + change_title_.insert(change_title_.end(), it->change_title.begin(), it->change_title.end()); + for (const int heap : it->filled) + if (heaps_[heap].slots) heaps_[heap].meta_clear = true; + copies_.insert(copies_.end(), it->copies.begin(), it->copies.end()); + keeps_.insert(keeps_.end(), it->keeps.begin(), it->keeps.end()); + for (std::size_t i = 0; i < it->updates.size(); i += ConsoleHeapKeys::kUpdateWords) + keys_.touch(it->updates[i]); + if (it->cleared) clear_keys_ = true; + pool_.push_back(it->buffer); + in_flight_.erase(std::next(it).base()); + return; + } + } + + // The passes done by `completed` (a completed retire ticket): `miss(heap, slot, half)` for each V# half they + // could not answer, `overflow(heap)` for a heap whose misses ran past the list (-1: every heap). + template + void drain(std::uint64_t completed, Miss&& miss, Overflow&& overflow) { + std::vector done; + { + std::lock_guard lock(mutex_); + for (auto it = in_flight_.begin(); it != in_flight_.end();) { + if (!it->committed || it->ticket > completed) { + ++it; + continue; + } + done.push_back(std::move(*it)); + it = in_flight_.erase(it); + } + // Tables no pass in flight still reads go back to their pool. + for (unsigned kind = 0; kind < table_count; ++kind) { + Table& t = tables_[kind]; + std::uint64_t oldest = t.version; + for (const Pass& pass : in_flight_) oldest = std::min(oldest, pass.versions[kind]); + for (auto it = t.old.begin(); it != t.old.end();) { + if (it->first < oldest) { + if (t.pool.size() < 8) t.pool.push_back(it->second); + else free_buffer(it->second); + it = t.old.erase(it); + } else { + ++it; + } + } + } + } + for (Pass& pass : done) { + const auto* words = static_cast(pass.buffer.mapped); + const std::uint32_t count = std::min(words[0], kMissCapacity); + for (std::uint32_t i = 0; i < count; ++i) { + const std::uint32_t code = words[kMissHeader + i]; + miss(int(code >> 29), (code >> 1) & ((1u << 28) - 1), code & 1u); + } + if (words[2]) overflow(-1); + std::lock_guard lock(mutex_); + stats_.misses += count; + stats_.overflows += words[2] ? 1 : 0; + pool_.push_back(pass.buffer); + } + } + + std::size_t in_flight() { + std::lock_guard lock(mutex_); + return in_flight_.size(); + } + // A pass recorded and not yet committed: its command buffer is on its way to the queue. + bool uncommitted() { + std::lock_guard lock(mutex_); + return std::any_of(in_flight_.begin(), in_flight_.end(), [](const Pass& p) { return !p.committed; }); + } + Stats take_stats() { + std::lock_guard lock(mutex_); + return std::exchange(stats_, Stats{}); + } + +private: + struct Buffer { + VkBuffer buffer = VK_NULL_HANDLE; + VkDeviceMemory memory = VK_NULL_HANDLE; + VkDeviceAddress address = 0; + VkDeviceSize size = 0; + void* mapped = nullptr; + }; + struct Heap { + VkDeviceAddress input = 0, copy = 0; + std::uint32_t slots = 0; + std::vector work; + std::vector queued; // per slot: its position in `work` + 1, 0 when not queued + std::uint32_t rescan = 0; // slots [0, rescan) to translate again (rescan()) + std::uint32_t rescan_filtered = 0; // the same, filtered by the change spans (rescan_filtered()) + Buffer meta; // device-local, 32 bytes a slot (console_heap_fix.comp meta_of) + bool meta_clear = false; + }; + struct Copy { + VkBuffer src, dst; + VkBufferCopy region; + }; + struct Pass { + Buffer buffer; + std::array versions{}; + struct Rescan { + int heap; + std::uint32_t slots; + bool filtered; + }; + std::vector rescans; + ConsoleHeapSpans change_shader, change_title; + std::vector filled; // heaps whose metadata this pass zeroed + std::vector copies; + std::vector> keeps; + std::vector>> work; + std::vector updates; + bool cleared = false, committed = false; + std::uint64_t ticket = 0; + }; + struct Push { + VkDeviceAddress input_slots, copy_slots, work, ranges, keys, misses, backed, ask, meta, cshader, ctitle; + std::uint32_t count, range_count, key_mask, mode, heap, backed_count, ask_count, flags, cshader_count, + ctitle_count; + }; + static_assert(sizeof(Push) == 128); // the guaranteed maxPushConstantsSize + // A table the CPU rebuilds whole (range, backed, ask): each version is its own buffer, kept until no pass in + // flight reads it, then reused. + struct Table { + std::vector words; + std::uint32_t count = 0; + bool dirty = false; + std::unique_ptr current; + std::uint64_t version = 0; + std::vector> old; + std::vector pool; + }; + + template + T fn(const char* name) const { + return reinterpret_cast(get_(device_, name)); + } + + void queue_locked(int heap, std::uint32_t item) { + if (heap < 0 || unsigned(heap) >= kMaxHeaps) return; + Heap& h = heaps_[heap]; + const std::uint32_t slot = item & ~kZeroFirst; + if (slot >= h.slots) return; + if (const std::uint32_t at = h.queued[slot]) { + h.work[at - 1] = item; + return; + } + h.work.push_back(item); + h.queued[slot] = std::uint32_t(h.work.size()); + } + bool pending_locked() const { + if (keys_.has_updates() || clear_keys_ || !copies_.empty()) return true; + for (const Heap& h : heaps_) + if (!h.work.empty() || h.rescan || h.rescan_filtered) return true; + return false; + } + + bool publish(Table& t, std::size_t entry_bytes) { + Buffer table{}; + if (t.count) { + // A version no pass reads any more, when one is big enough: the tables change at most submissions. + const VkDeviceSize bytes = VkDeviceSize(t.count) * entry_bytes; + for (auto it = t.pool.begin(); it != t.pool.end(); ++it) + if (it->size >= bytes) { + table = *it; + t.pool.erase(it); + break; + } + // Device-local and host-visible where there is such memory: the pass's binary searches read it a few + // dozen times per slot, and from system memory each step was a trip over the bus. + if (!table.buffer && !make_buffer(std::max(bytes + bytes / 2, 64 * 1024), true, table, true)) + return false; + std::memcpy(table.mapped, t.words.data(), t.words.size() * 4); + } + if (t.current) t.old.emplace_back(t.version, *t.current); + t.current.reset(); + if (table.buffer) t.current = std::make_unique(table); + ++t.version; + t.dirty = false; + ++stats_.tables; + return true; + } + + bool acquire_buffer(VkDeviceSize bytes, Buffer& out) { + for (auto it = pool_.begin(); it != pool_.end(); ++it) { + if (it->size < bytes) continue; + out = *it; + pool_.erase(it); + return true; + } + // Room to grow: the next pass of about this size reuses it. + return make_buffer(std::max(bytes + bytes / 2, 1 << 20), true, out); + } + + bool make_buffer(VkDeviceSize bytes, bool host, Buffer& out, bool host_device_local = false) { + out = {}; + 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; + VkMemoryRequirements requirements{}; + fn("vkGetBufferMemoryRequirements")(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; + 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 = requirements.size; + // Host-visible: system memory first (not the ReBAR heap the title's windows need). + std::vector order; + if (host && host_device_local) { + order = memory_type_order(memory_, requirements.memoryTypeBits, required | VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, + 0, requirements.size); + for (const std::uint32_t t : memory_type_order(memory_, requirements.memoryTypeBits, required, 0, + requirements.size)) + if (std::find(order.begin(), order.end(), t) == order.end()) order.push_back(t); + } else if (host) { + order = memory_type_order(memory_, requirements.memoryTypeBits, required | VK_MEMORY_PROPERTY_HOST_CACHED_BIT, + 0, requirements.size); + for (const std::uint32_t t : memory_type_order(memory_, requirements.memoryTypeBits, required, 0, + requirements.size)) + if (std::find(order.begin(), order.end(), t) == order.end()) order.push_back(t); + } 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; + 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_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.size = bytes; + if (!out.address) { + free_buffer(out); + return false; + } + 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 + 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; + 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; + 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; + 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); + if (!ok) { + if (pipeline) fn("vkDestroyPipeline")(device_, pipeline, nullptr); + if (layout) fn("vkDestroyPipelineLayout")(device_, layout, nullptr); + return false; + } + layout_ = layout; + pipeline_ = pipeline; + return true; + } + + PFN_vkGetDeviceProcAddr get_; + VkDevice device_; + VkPhysicalDeviceMemoryProperties memory_; + std::mutex mutex_; + VkPipelineLayout layout_ = VK_NULL_HANDLE; + VkPipeline pipeline_ = VK_NULL_HANDLE; + ConsoleHeapKeys keys_; + Buffer key_table_; + bool clear_keys_ = false; + std::array heaps_{}; + std::array tables_{}; + bool use_ask_ = false, signed_offsets_ = false; + std::vector in_flight_; + std::vector pool_; + std::vector copies_; + std::vector> keeps_; + ConsoleHeapSpans change_shader_, change_title_; // pending rescan_filtered() spans + std::vector retired_; // removed heaps' metadata + Stats stats_; +}; + +} // namespace leonida diff --git a/runtime/src/descriptor_range_changes.h b/runtime/src/descriptor_range_changes.h new file mode 100644 index 0000000000..5a4d7717f2 --- /dev/null +++ b/runtime/src/descriptor_range_changes.h @@ -0,0 +1,46 @@ +#pragma once +#include +#include +#include +#include + +namespace leonida { +// A separate cursor per console heap. The owning backing/alias registry locks record() and read(). +struct DescriptorRanges { + struct Range { uint64_t first, last; }; // inclusive, including UINT64_MAX + std::vector ranges; + void merge() { + std::sort(ranges.begin(), ranges.end(), [](auto a, auto b) { return a.first < b.first; }); + size_t n = 0; + for (auto r : ranges) { + if (n && r.first <= ranges[n-1].last) + ranges[n-1].last = (std::max)(ranges[n-1].last, r.last); + else ranges[n++] = r; + } + ranges.resize(n); + } + bool overlaps(uint64_t base, uint64_t bytes) const { + if (!bytes) return false; + auto it = std::lower_bound(ranges.begin(), ranges.end(), base, + [](auto r, uint64_t v) { return r.last < v; }); + return it != ranges.end() && (it->first <= base || it->first - base < bytes); + } +}; +class DescriptorRangeChanges { + std::array ring_{}; + uint64_t serial_{}; +public: + void record(uint64_t start, uint64_t bytes) { + if (bytes) { + ring_[serial_++ % ring_.size()] = {start, start + (std::min)(UINT64_MAX-start, bytes-1)}; + } + } + bool read(uint64_t& cursor, DescriptorRanges& out) const { + const auto previous = cursor; + cursor = serial_; + if (serial_ - previous > ring_.size()) return false; + for (auto i = previous; i != serial_; ++i) out.ranges.push_back(ring_[i % ring_.size()]); + return true; + } +}; +} diff --git a/runtime/src/descriptor_table.h b/runtime/src/descriptor_table.h index a0d80968a8..82fa19dbfc 100644 --- a/runtime/src/descriptor_table.h +++ b/runtime/src/descriptor_table.h @@ -19,7 +19,21 @@ namespace leonida { inline constexpr std::uint32_t kFnvOffsetBasis = 2166136261u; inline constexpr std::uint32_t kFnvPrime = 16777619u; inline constexpr std::uint32_t kDescriptorProbes = 8; -inline constexpr std::uint32_t kSlotOccupiedMarker = 0xA11CA7EDu; +// An entry's last dword is 0 while the slot is empty. This bit marks it occupied, and the low bits (kKindMask) say +// what the index is good for: one bit per array the image is bound in, sampled and storage. +inline constexpr std::uint32_t kSlotOccupiedMarker = 0x80000000u; +inline constexpr std::uint32_t kKindMask = 0x1FFFu; // bits 0..6 sampled, 8..12 storage + +// What an index is bound in, for the library whose modules read it (`descriptor_table` tagged in their index.json +// meta; tools/rdna2spirv.py reads the same bits with OpBitFieldUExtract). Bit `dimension` is that dimension's +// sampled array (dimensions 0..6, ImageDimension in vulkan_bindless.h); bit 8 + dimension its storage arrays +// (dimensions 0..4 have them). A table for a plain library leaves every kind bit zero. +inline constexpr std::uint32_t kind_sampled_bit(std::uint32_t dimension) { + return dimension < 7 ? (1u << dimension) : 0u; +} +inline constexpr std::uint32_t kind_storage_bit(std::uint32_t dimension) { + return dimension < 5 ? (1u << (8 + dimension)) : 0u; +} // Key types: // T# key is 8 dwords. @@ -93,14 +107,20 @@ inline DescriptorKey make_ssharp_key(const std::uint32_t ssharp[4]) { return k; } -// Memory layout of each entry in the table: 10 uint32s = 40 bytes. +// Memory layout of each entry in the table: 10 uint32s = 40 bytes. The last word is the kind a translated shader +// reads next to the index, and its occupied bit; a module that does not read it never looks at it. struct DescriptorEntry { std::uint32_t key[8] = {}; std::uint32_t index = 0; - std::uint32_t pad = 0; // 0 when empty, kSlotOccupiedMarker when occupied + std::uint32_t kind = 0; // 0 when empty, kSlotOccupiedMarker | (kKindMask bits) when occupied }; static_assert(sizeof(DescriptorEntry) == 40); +inline constexpr bool slot_occupied(const DescriptorEntry& entry) { + return (entry.kind & kSlotOccupiedMarker) != 0; +} +inline constexpr std::uint32_t slot_kind(const DescriptorEntry& entry) { return entry.kind & kKindMask; } + class DescriptorTable { public: enum class InsertResult { added, unchanged, replaced, added_with_relocation }; @@ -122,22 +142,23 @@ class DescriptorTable { // The kind this table places and finds keys with (immutable after construction). DescriptorHashKind hash_kind() const { return hash_kind_; } - // Inserts or updates a key -> index mapping. - // If the key already exists in one of the 8 probe slots, its index is updated. - // Try one bounded relocation before growing. Load never exceeds 50%. - bool insert(const std::uint32_t key[8], std::uint32_t index) { - insert_or_update(key, index); + // Inserts or updates a key -> (index, kind) mapping. If the key already exists in one of the 8 probe slots, + // its entry is updated. Try one bounded relocation before growing. Load never exceeds 50%. `kind` is what a + // shader that reads it (a `descriptor_table` tagged module) uses to tell which array the index is bound in; a + // sampler's entry has none. + bool insert(const std::uint32_t key[8], std::uint32_t index, std::uint32_t kind = 0) { + insert_or_update(key, index, kind); return true; } // Report the change under the same lock so the GPU caller can synchronize writes to live slots. - InsertResult insert_or_update(const std::uint32_t key[8], std::uint32_t index) { + InsertResult insert_or_update(const std::uint32_t key[8], std::uint32_t index, std::uint32_t kind = 0) { std::lock_guard lock(mutex_); - return insert_locked(key, index); + return insert_locked(key, index, kind); } - bool insert(const DescriptorKey& key, std::uint32_t index) { - return insert(key.data(), index); + bool insert(const DescriptorKey& key, std::uint32_t index, std::uint32_t kind = 0) { + return insert(key.data(), index, kind); } // Queries the index associated with key. Returns 0 if not found. @@ -147,7 +168,7 @@ class DescriptorTable { for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) { const std::uint32_t slot = (h + k) & mask_; const auto& entry = entries_[slot]; - if (entry.pad == kSlotOccupiedMarker && std::memcmp(entry.key, key, sizeof(entry.key)) == 0) { + if (slot_occupied(entry) && std::memcmp(entry.key, key, sizeof(entry.key)) == 0) { return entry.index; } } @@ -164,7 +185,7 @@ class DescriptorTable { for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) { const std::uint32_t slot = (h + k) & mask_; const auto& entry = entries_[slot]; - if (entry.pad == kSlotOccupiedMarker && std::memcmp(entry.key, key, sizeof(entry.key)) == 0) { + if (slot_occupied(entry) && std::memcmp(entry.key, key, sizeof(entry.key)) == 0) { return true; } } @@ -222,8 +243,8 @@ class DescriptorTable { } // Exports the table buffer format consumed by SPIR-V set 0, binding 2. - // Word 0 is mask; followed by entries[mask + 1] of 10 dwords: key[8], index, pad. - std::vector build_gpu_buffer(bool clear_pad = false) const { + // Word 0 is mask; followed by entries[mask + 1] of 10 dwords: key[8], index, kind. + std::vector build_gpu_buffer(bool clear_occupied = false) const { std::lock_guard lock(mutex_); std::vector out(1 + entries_.size() * 10, 0); out[0] = mask_; @@ -231,7 +252,7 @@ class DescriptorTable { const std::size_t base = 1 + s * 10; std::memcpy(&out[base], entries_[s].key, sizeof(entries_[s].key)); out[base + 8] = entries_[s].index; - out[base + 9] = clear_pad ? 0 : entries_[s].pad; + out[base + 9] = clear_occupied ? slot_kind(entries_[s]) : entries_[s].kind; } return out; } @@ -252,7 +273,7 @@ class DescriptorTable { return changes; } - // One slot's 10 dwords (key[8], index, pad) to `dest`; false when the slot is out of range. + // One slot's 10 dwords (key[8], index, kind) to `dest`; false when the slot is out of range. bool read_slot(std::uint32_t slot, std::uint32_t* dest) const { return read_slots(slot, 1, dest); } // `count` consecutive slots' 10 dwords each to `dest`, under one lock; false when any is out of range. @@ -264,13 +285,13 @@ class DescriptorTable { const DescriptorEntry& entry = entries_[first + i]; std::memcpy(dest + i * 10, entry.key, sizeof(entry.key)); dest[i * 10 + 8] = entry.index; - dest[i * 10 + 9] = entry.pad; + dest[i * 10 + 9] = entry.kind; } return true; } // Serializes directly into `dest` (must hold at least size_bytes()) without allocating a temporary vector. - void write_to_buffer(void* dest, bool clear_pad = false) const { + void write_to_buffer(void* dest, bool clear_occupied = false) const { if (!dest) return; std::lock_guard lock(mutex_); auto* out = static_cast(dest); @@ -280,7 +301,7 @@ class DescriptorTable { std::uint32_t slot[10]; std::memcpy(slot, entry.key, sizeof(entry.key)); slot[8] = entry.index; - slot[9] = clear_pad ? 0 : entry.pad; + slot[9] = clear_occupied ? slot_kind(entry) : entry.kind; std::memcpy(out, slot, sizeof(slot)); out += sizeof(slot); } @@ -298,7 +319,7 @@ class DescriptorTable { const auto mask = static_cast(entries.size() - 1); for (auto offset = kDescriptorProbes; offset < 2 * kDescriptorProbes - 1; ++offset) { const auto hole = (hash + offset) & mask; - if (entries[hole].pad == kSlotOccupiedMarker) continue; + if (slot_occupied(entries[hole])) continue; for (auto k = kDescriptorProbes; k > 0; --k) { const auto slot = (hash + k - 1) & mask; const auto home = hash_descriptor_key(entries[slot].key, kind); @@ -313,7 +334,7 @@ class DescriptorTable { return -1; } - InsertResult insert_locked(const std::uint32_t key[8], std::uint32_t index) { + InsertResult insert_locked(const std::uint32_t key[8], std::uint32_t index, std::uint32_t kind) { while (true) { const std::uint32_t h = hash_descriptor_key(key, hash_kind_); int empty_slot = -1; @@ -321,10 +342,12 @@ class DescriptorTable { for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) { const std::uint32_t slot = (h + k) & mask_; auto& entry = entries_[slot]; - if (entry.pad == kSlotOccupiedMarker) { + if (slot_occupied(entry)) { if (std::memcmp(entry.key, key, sizeof(entry.key)) == 0) { - if (entry.index == index) return InsertResult::unchanged; + if (entry.index == index && slot_kind(entry) == kind) return InsertResult::unchanged; + // A new index or a new kind: either way the slot's copy of the entry must reach the GPU. entry.index = index; + entry.kind = kSlotOccupiedMarker | (kind & kKindMask); mark(slot); return InsertResult::replaced; } @@ -356,7 +379,7 @@ class DescriptorTable { auto& entry = entries_[empty_slot]; std::memcpy(entry.key, key, sizeof(entry.key)); entry.index = index; - entry.pad = kSlotOccupiedMarker; + entry.kind = kSlotOccupiedMarker | (kind & kKindMask); ++occupied_count_; if (relocate) mark(moved_to); mark(std::uint32_t(empty_slot)); @@ -374,7 +397,7 @@ class DescriptorTable { for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) { const std::uint32_t slot = (h + k) & mask_; const auto& entry = entries_[slot]; - if (entry.pad == kSlotOccupiedMarker && std::memcmp(entry.key, key, sizeof(entry.key)) == 0) { + if (slot_occupied(entry) && std::memcmp(entry.key, key, sizeof(entry.key)) == 0) { found_slot = slot; found = true; break; @@ -398,12 +421,12 @@ class DescriptorTable { bool rehash_ok = true; for (const auto& old : entries_) { - if (old.pad != kSlotOccupiedMarker) continue; + if (!slot_occupied(old)) continue; const std::uint32_t h = hash_descriptor_key(old.key, hash_kind_); int slot = -1; for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) { const std::uint32_t s = (h + k) & new_mask; - if (new_entries[s].pad != kSlotOccupiedMarker) { + if (!slot_occupied(new_entries[s])) { slot = static_cast(s); break; } diff --git a/runtime/src/fsdraw_probe.h b/runtime/src/fsdraw_probe.h index 180b02b369..367f793cb6 100644 --- a/runtime/src/fsdraw_probe.h +++ b/runtime/src/fsdraw_probe.h @@ -38,7 +38,26 @@ inline State& state() { return s; } +// What backs a title VA on the GPU side (set by the device: "slot-133 shadow", ...), for the CB comparison below. +inline std::atomic& backing_hook() { + static std::atomic hook{nullptr}; + return hook; +} + +// LEONIDA_FSDRAW_PROBE=1 turns the records and lines on (so does LEONIDA_COMPUTE_INPUTS, whose probe reads the T# +// and CBV records). Off by default: they take this mutex at every T# registered, CBV made, pipeline created and +// table submitted. The arena mapping (note_arena) is kept either way. +inline bool enabled() { + static const bool on = [] { + const char* v = std::getenv("LEONIDA_FSDRAW_PROBE"); + const char* inputs = std::getenv("LEONIDA_COMPUTE_INPUTS"); + return (v && *v == '1') || (inputs && *inputs); + }(); + return on; +} + inline void note_pipeline(std::uintptr_t id, std::string text) { + if (!enabled()) return; std::lock_guard lock(state().mutex); state().pipelines[id] = std::move(text); } @@ -55,6 +74,7 @@ inline std::string pipeline(std::uintptr_t id) { } inline void note_tsharp(const std::uint32_t* words) { + if (!enabled()) return; std::array key{}; std::memcpy(key.data(), words, sizeof(key)); std::lock_guard lock(state().mutex); @@ -62,6 +82,7 @@ inline void note_tsharp(const std::uint32_t* words) { } inline bool has_tsharp(const std::uint32_t* words) { + if (!enabled()) return false; std::array key{}; std::memcpy(key.data(), words, sizeof(key)); std::lock_guard lock(state().mutex); @@ -84,22 +105,25 @@ inline void forget_arena(const std::uint8_t* mapped) { } } -// A render target a fullscreen draw wrote: the present-probe reads it back with the source (at most 4 kept). +// A render target a fullscreen draw wrote, or a traced texture (LEONIDA_TRACE_TEXTURE): the present-probe reads it back +// with the source (at most 24 kept). inline void note_target(std::uint64_t id) { - if (!id) return; + if (!id || !enabled()) return; std::lock_guard lock(state().mutex); auto& r = state().readback; for (const std::uint64_t x : r) if (x == id) return; - if (r.size() < 4) r.push_back(id); + if (r.size() < 24) r.push_back(id); } inline std::vector targets() { + if (!enabled()) return {}; std::lock_guard lock(state().mutex); return state().readback; } inline void note_table(std::uint64_t translated, std::uint64_t original) { + if (!enabled()) return; std::lock_guard lock(state().mutex); auto& m = state().table_origin; if (m.size() > 8192) m.clear(); @@ -107,12 +131,14 @@ inline void note_table(std::uint64_t translated, std::uint64_t original) { } inline std::uint64_t table_origin(std::uint64_t va) { + if (!enabled()) return va; std::lock_guard lock(state().mutex); const auto it = state().table_origin.find(va); return it == state().table_origin.end() ? va : it->second; } inline void note_cbv(std::uint64_t base, std::uint64_t location, std::uint32_t size) { + if (!enabled()) return; std::lock_guard lock(state().mutex); auto& m = state().cbv_origin; if (m.size() > 8192) m.clear(); @@ -120,6 +146,7 @@ inline void note_cbv(std::uint64_t base, std::uint64_t location, std::uint32_t s } inline bool cbv_origin(std::uint64_t base, std::uint64_t& location) { + if (!enabled()) return false; std::lock_guard lock(state().mutex); const auto it = state().cbv_origin.find(base); if (it == state().cbv_origin.end()) return false; @@ -157,7 +184,13 @@ inline std::uint64_t arena_size() { // arena has its first 16 dwords printed from the arena. inline void describe_table(const char* tag, std::uint64_t va, std::uint32_t slots, const std::uint8_t* cpu, const char* heap_kind) { - const std::uint32_t shown = slots < 4 ? slots : 4; + // LEONIDA_FSDRAW_SLOTS=: how many of a table's slots are shown (4 by default; a composite's textures sit later). + static const std::uint32_t limit = [] { + const char* v = std::getenv("LEONIDA_FSDRAW_SLOTS"); + const unsigned long n = v ? std::strtoul(v, nullptr, 10) : 0; + return n ? std::uint32_t(n < 64 ? n : 64) : 4u; + }(); + const std::uint32_t shown = slots < limit ? slots : limit; std::fprintf(stderr, "[rt] fsdraw: %s table va 0x%llx slots %u heap %s (arena size 0x%llx)\n", tag, static_cast(va), slots, heap_kind, static_cast(arena_size())); for (std::uint32_t i = 0; i < shown; ++i) { @@ -187,6 +220,32 @@ inline void describe_table(const char* tag, std::uint64_t va, std::uint32_t slot if (!all.empty() && arena_words(base, all.data(), all.size())) for (const std::uint32_t x : all) nonzero += x != 0; } + // A V# in the arena: the title bytes it was copied from, beside the arena copy the GPU reads, and what + // keeps that copy (a coherence gap shows as title nonzero / arena zero, repeatedly). + std::uint64_t source = 0, range_va = 0, range_bytes = 0; + if (in_arena && title_va_aliases().title_of_shader(base, source, range_va, range_bytes)) { + std::uint64_t lo = 0, hi = 0; + std::uint32_t title_words[16]{}; + const bool title_readable = + title_va_aliases().title_memory(source, lo, hi) && hi - source >= sizeof title_words; + if (title_readable) + std::memcpy(title_words, reinterpret_cast(static_cast(source)), + sizeof title_words); + const auto hook = backing_hook().load(std::memory_order_acquire); + std::fprintf(stderr, "[rt] fsdraw: %s slot %u arena 0x%llx comes from title 0x%llx (alias range 0x%llx, " + "%llu bytes; backing %s): title [%s]%s\n", + tag, i, static_cast(base), static_cast(source), + static_cast(range_va), static_cast(range_bytes), + hook ? hook(source) : "unknown", + title_readable ? hex_words(title_words, 16).c_str() : "not readable", + !title_readable ? "" + // Only the alias range's own bytes (at most the 64 shown): the rest is another object's. + : std::memcmp(title_words, data, std::size_t(std::min( + sizeof data, range_va + range_bytes - source))) ? " DIFFER" : " SAME"); + } else if (in_arena) { + std::fprintf(stderr, "[rt] fsdraw: %s slot %u arena 0x%llx: no title range maps to it (the layer's own memory)\n", + tag, i, static_cast(base)); + } std::uint64_t location = 0; const bool made = cbv_origin(base, location); std::fprintf(stderr, "[rt] fsdraw: %s slot %u V# base 0x%llx stride %u records %u -> %s [%s] nonzero dwords " diff --git a/runtime/src/indirect_clamp.comp b/runtime/src/indirect_clamp.comp index 565a19463d..3b99da59ab 100644 --- a/runtime/src/indirect_clamp.comp +++ b/runtime/src/indirect_clamp.comp @@ -117,6 +117,16 @@ void main() { const uint asked_x = p.arguments.data[src]; const uint asked_y = p.arguments.data[src + 1u]; const uint asked_z = p.arguments.data[src + 2u]; + if (p.kind == 3u) { + // Before the clamp: how many mesh records ask for more than one group in y or z, and the largest y and z + // asked (stats words 8-11), which y = z = 1 below would cut. + atomicAdd(p.stats.data[8], 1u); + if (asked_y > 1u || asked_z > 1u) { + atomicAdd(p.stats.data[9], 1u); + atomicMax(p.stats.data[10], asked_y); + atomicMax(p.stats.data[11], asked_z); + } + } uint x = min(asked_x, max_group_dimension); uint y = min(asked_y, max_group_dimension); uint z = min(asked_z, max_group_dimension); diff --git a/runtime/src/indirect_clamp_spv.h b/runtime/src/indirect_clamp_spv.h index 50253df78b..653e0543f6 100644 --- a/runtime/src/indirect_clamp_spv.h +++ b/runtime/src/indirect_clamp_spv.h @@ -3,7 +3,7 @@ #include namespace leonida { inline constexpr std::uint32_t indirect_clamp_spirv[] = { - 0x07230203u, 0x00010500u, 0x0008000bu, 0x000002d0u, 0x00000000u, 0x00020011u, 0x00000001u, 0x00020011u, + 0x07230203u, 0x00010500u, 0x0008000bu, 0x000002fau, 0x00000000u, 0x00020011u, 0x00000001u, 0x00020011u, 0x000014e3u, 0x0006000bu, 0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu, 0x000014e4u, 0x00000001u, 0x0007000fu, 0x00000005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00000026u, 0x0000005au, 0x00060010u, 0x00000004u, 0x00000011u, 0x00000040u, 0x00000001u, 0x00000001u, 0x00030003u, @@ -42,7 +42,7 @@ inline constexpr std::uint32_t indirect_clamp_spirv[] = { 0x00000006u, 0x00000004u, 0x00030047u, 0x00000022u, 0x00000002u, 0x00050048u, 0x00000022u, 0x00000000u, 0x00000023u, 0x00000000u, 0x00040047u, 0x00000023u, 0x00000006u, 0x00000004u, 0x00030047u, 0x00000024u, 0x00000002u, 0x00050048u, 0x00000024u, 0x00000000u, 0x00000023u, 0x00000000u, 0x00040047u, 0x0000005au, - 0x0000000bu, 0x0000001cu, 0x00040047u, 0x00000209u, 0x0000000bu, 0x00000019u, 0x00020013u, 0x00000002u, + 0x0000000bu, 0x0000001cu, 0x00040047u, 0x00000227u, 0x0000000bu, 0x00000019u, 0x00020013u, 0x00000002u, 0x00030021u, 0x00000003u, 0x00000002u, 0x00040015u, 0x00000006u, 0x00000020u, 0x00000000u, 0x00040020u, 0x00000007u, 0x00000007u, 0x00000006u, 0x00020014u, 0x00000008u, 0x0004002bu, 0x00000006u, 0x0000000eu, 0x00000000u, 0x00030029u, 0x00000008u, 0x00000012u, 0x00030027u, 0x00000015u, 0x000014e5u, 0x00030027u, @@ -75,16 +75,16 @@ inline constexpr std::uint32_t indirect_clamp_spirv[] = { 0x00000006u, 0x00000079u, 0x00040020u, 0x00000115u, 0x00000007u, 0x00000114u, 0x0008002cu, 0x00000114u, 0x00000117u, 0x0000000eu, 0x0000000eu, 0x0000000eu, 0x0000000eu, 0x0000000eu, 0x0004002bu, 0x00000006u, 0x0000012eu, 0x01000000u, 0x0004002bu, 0x00000006u, 0x00000132u, 0x04000000u, 0x0004002bu, 0x00000006u, - 0x0000014du, 0x00000002u, 0x0004002bu, 0x00000006u, 0x0000017cu, 0x0000ffffu, 0x0004002bu, 0x00000006u, - 0x000001b0u, 0x00100000u, 0x0004002bu, 0x00000006u, 0x000001cbu, 0x00000080u, 0x0004002bu, 0x00000006u, - 0x000001ccu, 0x00000040u, 0x0006002cu, 0x00000058u, 0x00000209u, 0x000001ccu, 0x0000002fu, 0x0000002fu, - 0x00030001u, 0x00000008u, 0x00000288u, 0x00050036u, 0x00000002u, 0x00000004u, 0x00000000u, 0x00000003u, - 0x000200f8u, 0x00000005u, 0x0004003bu, 0x00000115u, 0x00000116u, 0x00000007u, 0x000300f7u, 0x0000020au, - 0x00000000u, 0x000300fbu, 0x0000000eu, 0x0000020bu, 0x000200f8u, 0x0000020bu, 0x00050041u, 0x0000005bu, + 0x0000014du, 0x00000002u, 0x0004002bu, 0x00000006u, 0x0000019au, 0x0000ffffu, 0x0004002bu, 0x00000006u, + 0x000001ceu, 0x00100000u, 0x0004002bu, 0x00000006u, 0x000001e9u, 0x00000080u, 0x0004002bu, 0x00000006u, + 0x000001eau, 0x00000040u, 0x0006002cu, 0x00000058u, 0x00000227u, 0x000001eau, 0x0000002fu, 0x0000002fu, + 0x00030001u, 0x00000008u, 0x000002acu, 0x00050036u, 0x00000002u, 0x00000004u, 0x00000000u, 0x00000003u, + 0x000200f8u, 0x00000005u, 0x0004003bu, 0x00000115u, 0x00000116u, 0x00000007u, 0x000300f7u, 0x00000228u, + 0x00000000u, 0x000300fbu, 0x0000000eu, 0x00000229u, 0x000200f8u, 0x00000229u, 0x00050041u, 0x0000005bu, 0x0000005cu, 0x0000005au, 0x0000000eu, 0x0004003du, 0x00000006u, 0x0000005du, 0x0000005cu, 0x00050041u, 0x00000060u, 0x00000061u, 0x00000026u, 0x0000005fu, 0x0004003du, 0x00000006u, 0x00000062u, 0x00000061u, 0x000500aeu, 0x00000008u, 0x00000063u, 0x0000005du, 0x00000062u, 0x000300f7u, 0x00000065u, 0x00000000u, - 0x000400fau, 0x00000063u, 0x00000064u, 0x00000065u, 0x000200f8u, 0x00000064u, 0x000200f9u, 0x0000020au, + 0x000400fau, 0x00000063u, 0x00000064u, 0x00000065u, 0x000200f8u, 0x00000064u, 0x000200f9u, 0x00000228u, 0x000200f8u, 0x00000065u, 0x00050041u, 0x00000060u, 0x00000069u, 0x00000026u, 0x00000068u, 0x0004003du, 0x00000006u, 0x0000006au, 0x00000069u, 0x00050080u, 0x00000006u, 0x0000006cu, 0x0000006au, 0x0000005du, 0x00050041u, 0x00000060u, 0x0000006fu, 0x00000026u, 0x0000006eu, 0x0004003du, 0x00000006u, 0x00000070u, @@ -92,8 +92,8 @@ inline constexpr std::uint32_t indirect_clamp_spirv[] = { 0x00000000u, 0x000400fau, 0x00000071u, 0x00000073u, 0x0000007bu, 0x000200f8u, 0x00000073u, 0x000500aau, 0x00000008u, 0x00000077u, 0x00000070u, 0x0000000eu, 0x000600a9u, 0x00000006u, 0x0000007au, 0x00000077u, 0x00000078u, 0x00000079u, 0x000200f9u, 0x00000074u, 0x000200f8u, 0x0000007bu, 0x000200f9u, 0x00000074u, - 0x000200f8u, 0x00000074u, 0x000700f5u, 0x00000006u, 0x00000246u, 0x0000007au, 0x00000073u, 0x0000007cu, - 0x0000007bu, 0x00050084u, 0x00000006u, 0x00000081u, 0x0000005du, 0x00000246u, 0x00050041u, 0x00000060u, + 0x000200f8u, 0x00000074u, 0x000700f5u, 0x00000006u, 0x00000264u, 0x0000007au, 0x00000073u, 0x0000007cu, + 0x0000007bu, 0x00050084u, 0x00000006u, 0x00000081u, 0x0000005du, 0x00000264u, 0x00050041u, 0x00000060u, 0x00000085u, 0x00000026u, 0x00000084u, 0x0004003du, 0x00000006u, 0x00000086u, 0x00000085u, 0x000500c7u, 0x00000006u, 0x00000087u, 0x00000086u, 0x0000002fu, 0x000500abu, 0x00000008u, 0x00000088u, 0x00000087u, 0x0000000eu, 0x00050041u, 0x00000060u, 0x0000008bu, 0x00000026u, 0x0000008au, 0x0004003du, 0x00000006u, @@ -112,32 +112,32 @@ inline constexpr std::uint32_t indirect_clamp_spirv[] = { 0x00060041u, 0x0000002du, 0x000000acu, 0x000000abu, 0x0000002cu, 0x00000091u, 0x000700eau, 0x00000006u, 0x000000adu, 0x000000acu, 0x0000002fu, 0x0000000eu, 0x0000002fu, 0x000200f9u, 0x000000a8u, 0x000200f8u, 0x000000a8u, 0x000200f9u, 0x0000009du, 0x000200f8u, 0x0000009du, 0x000200f9u, 0x0000008fu, 0x000200f8u, - 0x0000008fu, 0x000700f5u, 0x00000006u, 0x0000024cu, 0x0000008cu, 0x00000074u, 0x00000099u, 0x0000009du, - 0x000500aeu, 0x00000008u, 0x000000b0u, 0x0000006cu, 0x0000024cu, 0x000300f7u, 0x000000b2u, 0x00000000u, + 0x0000008fu, 0x000700f5u, 0x00000006u, 0x0000026au, 0x0000008cu, 0x00000074u, 0x00000099u, 0x0000009du, + 0x000500aeu, 0x00000008u, 0x000000b0u, 0x0000006cu, 0x0000026au, 0x000300f7u, 0x000000b2u, 0x00000000u, 0x000400fau, 0x000000b0u, 0x000000b1u, 0x000000b2u, 0x000200f8u, 0x000000b1u, 0x000200f9u, 0x000000b4u, - 0x000200f8u, 0x000000b4u, 0x000700f5u, 0x00000006u, 0x000002c2u, 0x0000000eu, 0x000000b1u, 0x000000c5u, - 0x000000b5u, 0x000500b0u, 0x00000008u, 0x000000bbu, 0x000002c2u, 0x00000246u, 0x000400f6u, 0x000000b6u, + 0x000200f8u, 0x000000b4u, 0x000700f5u, 0x00000006u, 0x000002ecu, 0x0000000eu, 0x000000b1u, 0x000000c5u, + 0x000000b5u, 0x000500b0u, 0x00000008u, 0x000000bbu, 0x000002ecu, 0x00000264u, 0x000400f6u, 0x000000b6u, 0x000000b5u, 0x00000000u, 0x000400fau, 0x000000bbu, 0x000000b5u, 0x000000b6u, 0x000200f8u, 0x000000b5u, 0x00050041u, 0x000000bdu, 0x000000beu, 0x00000026u, 0x000000bcu, 0x0004003du, 0x00000017u, 0x000000bfu, - 0x000000beu, 0x00050080u, 0x00000006u, 0x000000c2u, 0x00000081u, 0x000002c2u, 0x00060041u, 0x0000002du, + 0x000000beu, 0x00050080u, 0x00000006u, 0x000000c2u, 0x00000081u, 0x000002ecu, 0x00060041u, 0x0000002du, 0x000000c3u, 0x000000bfu, 0x0000002cu, 0x000000c2u, 0x0005003eu, 0x000000c3u, 0x0000000eu, 0x00000002u, - 0x00000004u, 0x00050080u, 0x00000006u, 0x000000c5u, 0x000002c2u, 0x00000091u, 0x000200f9u, 0x000000b4u, - 0x000200f8u, 0x000000b6u, 0x000200f9u, 0x0000020au, 0x000200f8u, 0x000000b2u, 0x00050041u, 0x00000060u, + 0x00000004u, 0x00050080u, 0x00000006u, 0x000000c5u, 0x000002ecu, 0x00000091u, 0x000200f9u, 0x000000b4u, + 0x000200f8u, 0x000000b6u, 0x000200f9u, 0x00000228u, 0x000200f8u, 0x000000b2u, 0x00050041u, 0x00000060u, 0x000000cau, 0x00000026u, 0x000000c9u, 0x0004003du, 0x00000006u, 0x000000cbu, 0x000000cau, 0x00050084u, 0x00000006u, 0x000000ccu, 0x0000005du, 0x000000cbu, 0x000200f9u, 0x000000cfu, 0x000200f8u, 0x000000cfu, - 0x000700f5u, 0x00000008u, 0x00000257u, 0x00000012u, 0x000000b2u, 0x000000e4u, 0x000000d2u, 0x000700f5u, - 0x00000006u, 0x00000252u, 0x0000000eu, 0x000000b2u, 0x000000e6u, 0x000000d2u, 0x000500b0u, 0x00000008u, - 0x000000d6u, 0x00000252u, 0x00000246u, 0x000400f6u, 0x000000d1u, 0x000000d2u, 0x00000000u, 0x000400fau, + 0x000700f5u, 0x00000008u, 0x00000275u, 0x00000012u, 0x000000b2u, 0x000000e4u, 0x000000d2u, 0x000700f5u, + 0x00000006u, 0x00000270u, 0x0000000eu, 0x000000b2u, 0x000000e6u, 0x000000d2u, 0x000500b0u, 0x00000008u, + 0x000000d6u, 0x00000270u, 0x00000264u, 0x000400f6u, 0x000000d1u, 0x000000d2u, 0x00000000u, 0x000400fau, 0x000000d6u, 0x000000d0u, 0x000000d1u, 0x000200f8u, 0x000000d0u, 0x000300f7u, 0x000000d9u, 0x00000000u, - 0x000400fau, 0x00000257u, 0x000000d8u, 0x000000d9u, 0x000200f8u, 0x000000d8u, 0x00050041u, 0x000000dau, + 0x000400fau, 0x00000275u, 0x000000d8u, 0x000000d9u, 0x000200f8u, 0x000000d8u, 0x00050041u, 0x000000dau, 0x000000dbu, 0x00000026u, 0x0000002cu, 0x0004003du, 0x00000015u, 0x000000dcu, 0x000000dbu, 0x00050080u, - 0x00000006u, 0x000000dfu, 0x000000ccu, 0x00000252u, 0x00060041u, 0x0000002du, 0x000000e0u, 0x000000dcu, + 0x00000006u, 0x000000dfu, 0x000000ccu, 0x00000270u, 0x00060041u, 0x0000002du, 0x000000e0u, 0x000000dcu, 0x0000002cu, 0x000000dfu, 0x0006003du, 0x00000006u, 0x000000e1u, 0x000000e0u, 0x00000002u, 0x00000004u, 0x000500aau, 0x00000008u, 0x000000e3u, 0x000000e1u, 0x000000e2u, 0x000200f9u, 0x000000d9u, 0x000200f8u, - 0x000000d9u, 0x000700f5u, 0x00000008u, 0x000000e4u, 0x00000257u, 0x000000d0u, 0x000000e3u, 0x000000d8u, - 0x000200f9u, 0x000000d2u, 0x000200f8u, 0x000000d2u, 0x00050080u, 0x00000006u, 0x000000e6u, 0x00000252u, + 0x000000d9u, 0x000700f5u, 0x00000008u, 0x000000e4u, 0x00000275u, 0x000000d0u, 0x000000e3u, 0x000000d8u, + 0x000200f9u, 0x000000d2u, 0x000200f8u, 0x000000d2u, 0x00050080u, 0x00000006u, 0x000000e6u, 0x00000270u, 0x00000091u, 0x000200f9u, 0x000000cfu, 0x000200f8u, 0x000000d1u, 0x000400a8u, 0x00000008u, 0x000000e8u, - 0x00000257u, 0x000300f7u, 0x000000eau, 0x00000000u, 0x000400fau, 0x000000e8u, 0x000000e9u, 0x000000eau, + 0x00000275u, 0x000300f7u, 0x000000eau, 0x00000000u, 0x000400fau, 0x000000e8u, 0x000000e9u, 0x000000eau, 0x000200f8u, 0x000000e9u, 0x000500aau, 0x00000008u, 0x000000edu, 0x00000070u, 0x0000007cu, 0x000300f7u, 0x000000efu, 0x00000000u, 0x000400fau, 0x000000edu, 0x000000eeu, 0x000000efu, 0x000200f8u, 0x000000eeu, 0x00050041u, 0x000000dau, 0x000000f0u, 0x00000026u, 0x0000002cu, 0x0004003du, 0x00000015u, 0x000000f1u, @@ -145,21 +145,21 @@ inline constexpr std::uint32_t indirect_clamp_spirv[] = { 0x00000006u, 0x000000f4u, 0x000000f3u, 0x00000002u, 0x00000004u, 0x000500aau, 0x00000008u, 0x000000f5u, 0x000000f4u, 0x000000e2u, 0x000200f9u, 0x000000efu, 0x000200f8u, 0x000000efu, 0x000700f5u, 0x00000008u, 0x000000f6u, 0x000000edu, 0x000000e9u, 0x000000f5u, 0x000000eeu, 0x000200f9u, 0x000000eau, 0x000200f8u, - 0x000000eau, 0x000700f5u, 0x00000008u, 0x000000f7u, 0x00000257u, 0x000000d1u, 0x000000f6u, 0x000000efu, + 0x000000eau, 0x000700f5u, 0x00000008u, 0x000000f7u, 0x00000275u, 0x000000d1u, 0x000000f6u, 0x000000efu, 0x000300f7u, 0x000000f9u, 0x00000000u, 0x000400fau, 0x000000f7u, 0x000000f8u, 0x000000f9u, 0x000200f8u, - 0x000000f8u, 0x000200f9u, 0x000000fbu, 0x000200f8u, 0x000000fbu, 0x000700f5u, 0x00000006u, 0x000002beu, - 0x0000000eu, 0x000000f8u, 0x0000010au, 0x000000fcu, 0x000500b0u, 0x00000008u, 0x00000102u, 0x000002beu, - 0x00000246u, 0x000400f6u, 0x000000fdu, 0x000000fcu, 0x00000000u, 0x000400fau, 0x00000102u, 0x000000fcu, + 0x000000f8u, 0x000200f9u, 0x000000fbu, 0x000200f8u, 0x000000fbu, 0x000700f5u, 0x00000006u, 0x000002e8u, + 0x0000000eu, 0x000000f8u, 0x0000010au, 0x000000fcu, 0x000500b0u, 0x00000008u, 0x00000102u, 0x000002e8u, + 0x00000264u, 0x000400f6u, 0x000000fdu, 0x000000fcu, 0x00000000u, 0x000400fau, 0x00000102u, 0x000000fcu, 0x000000fdu, 0x000200f8u, 0x000000fcu, 0x00050041u, 0x000000bdu, 0x00000103u, 0x00000026u, 0x000000bcu, 0x0004003du, 0x00000017u, 0x00000104u, 0x00000103u, 0x00050080u, 0x00000006u, 0x00000107u, 0x00000081u, - 0x000002beu, 0x00060041u, 0x0000002du, 0x00000108u, 0x00000104u, 0x0000002cu, 0x00000107u, 0x0005003eu, - 0x00000108u, 0x0000000eu, 0x00000002u, 0x00000004u, 0x00050080u, 0x00000006u, 0x0000010au, 0x000002beu, + 0x000002e8u, 0x00060041u, 0x0000002du, 0x00000108u, 0x00000104u, 0x0000002cu, 0x00000107u, 0x0005003eu, + 0x00000108u, 0x0000000eu, 0x00000002u, 0x00000004u, 0x00050080u, 0x00000006u, 0x0000010au, 0x000002e8u, 0x00000091u, 0x000200f9u, 0x000000fbu, 0x000200f8u, 0x000000fdu, 0x00050041u, 0x00000029u, 0x0000010bu, 0x00000026u, 0x000000a9u, 0x0004003du, 0x00000019u, 0x0000010cu, 0x0000010bu, 0x00060041u, 0x0000002du, 0x0000010du, 0x0000010cu, 0x0000002cu, 0x0000002cu, 0x000700eau, 0x00000006u, 0x0000010eu, 0x0000010du, 0x0000002fu, 0x0000000eu, 0x0000002fu, 0x00060041u, 0x0000002du, 0x00000111u, 0x0000010cu, 0x0000002cu, 0x0000009eu, 0x000700eau, 0x00000006u, 0x00000112u, 0x00000111u, 0x0000002fu, 0x0000000eu, 0x0000002fu, - 0x000200f9u, 0x0000020au, 0x000200f8u, 0x000000f9u, 0x0003003eu, 0x00000116u, 0x00000117u, 0x000300f7u, + 0x000200f9u, 0x00000228u, 0x000200f8u, 0x000000f9u, 0x0003003eu, 0x00000116u, 0x00000117u, 0x000300f7u, 0x0000011eu, 0x00000000u, 0x000400fau, 0x00000071u, 0x0000011du, 0x00000165u, 0x000200f8u, 0x0000011du, 0x00050041u, 0x000000dau, 0x00000120u, 0x00000026u, 0x0000002cu, 0x0004003du, 0x00000015u, 0x00000121u, 0x00000120u, 0x00060041u, 0x0000002du, 0x00000123u, 0x00000121u, 0x0000002cu, 0x000000ccu, 0x0006003du, @@ -169,13 +169,13 @@ inline constexpr std::uint32_t indirect_clamp_spirv[] = { 0x0000012fu, 0x00000001u, 0x00000026u, 0x00000124u, 0x0000012eu, 0x0007000cu, 0x00000006u, 0x00000134u, 0x00000001u, 0x00000029u, 0x0000012fu, 0x0000002fu, 0x00050086u, 0x00000006u, 0x00000135u, 0x00000132u, 0x00000134u, 0x0007000cu, 0x00000006u, 0x00000136u, 0x00000001u, 0x00000026u, 0x0000012bu, 0x00000135u, - 0x000500aau, 0x00000008u, 0x00000138u, 0x0000012fu, 0x0000000eu, 0x000600a9u, 0x00000006u, 0x000002c9u, + 0x000500aau, 0x00000008u, 0x00000138u, 0x0000012fu, 0x0000000eu, 0x000600a9u, 0x00000006u, 0x000002f3u, 0x00000138u, 0x0000000eu, 0x00000136u, 0x000500abu, 0x00000008u, 0x0000013du, 0x0000012fu, 0x00000124u, - 0x000500abu, 0x00000008u, 0x00000140u, 0x000002c9u, 0x0000012bu, 0x000500a6u, 0x00000008u, 0x00000141u, + 0x000500abu, 0x00000008u, 0x00000140u, 0x000002f3u, 0x0000012bu, 0x000500a6u, 0x00000008u, 0x00000141u, 0x0000013du, 0x00000140u, 0x000600a9u, 0x00000006u, 0x00000142u, 0x00000141u, 0x0000002fu, 0x0000000eu, - 0x00050084u, 0x00000006u, 0x00000145u, 0x0000012fu, 0x000002c9u, 0x00050041u, 0x00000007u, 0x00000147u, + 0x00050084u, 0x00000006u, 0x00000145u, 0x0000012fu, 0x000002f3u, 0x00050041u, 0x00000007u, 0x00000147u, 0x00000116u, 0x0000002cu, 0x0003003eu, 0x00000147u, 0x0000012fu, 0x00050041u, 0x00000007u, 0x00000149u, - 0x00000116u, 0x00000091u, 0x0003003eu, 0x00000149u, 0x000002c9u, 0x00050080u, 0x00000006u, 0x0000014eu, + 0x00000116u, 0x00000091u, 0x0003003eu, 0x00000149u, 0x000002f3u, 0x00050080u, 0x00000006u, 0x0000014eu, 0x000000ccu, 0x0000014du, 0x00060041u, 0x0000002du, 0x0000014fu, 0x00000121u, 0x0000002cu, 0x0000014eu, 0x0006003du, 0x00000006u, 0x00000150u, 0x0000014fu, 0x00000002u, 0x00000004u, 0x00050041u, 0x00000007u, 0x00000151u, 0x00000116u, 0x000000bcu, 0x0003003eu, 0x00000151u, 0x00000150u, 0x00050080u, 0x00000006u, @@ -194,94 +194,106 @@ inline constexpr std::uint32_t indirect_clamp_spirv[] = { 0x00060041u, 0x0000002du, 0x00000171u, 0x00000168u, 0x0000002cu, 0x00000170u, 0x0006003du, 0x00000006u, 0x00000172u, 0x00000171u, 0x00000002u, 0x00000004u, 0x00050080u, 0x00000006u, 0x00000177u, 0x000000ccu, 0x0000014du, 0x00060041u, 0x0000002du, 0x00000178u, 0x00000168u, 0x0000002cu, 0x00000177u, 0x0006003du, - 0x00000006u, 0x00000179u, 0x00000178u, 0x00000002u, 0x00000004u, 0x0007000cu, 0x00000006u, 0x0000017du, - 0x00000001u, 0x00000026u, 0x0000016bu, 0x0000017cu, 0x0007000cu, 0x00000006u, 0x00000180u, 0x00000001u, - 0x00000026u, 0x00000172u, 0x0000017cu, 0x0007000cu, 0x00000006u, 0x00000183u, 0x00000001u, 0x00000026u, - 0x00000179u, 0x0000017cu, 0x000500aau, 0x00000008u, 0x00000186u, 0x00000070u, 0x0000007cu, 0x000600a9u, - 0x00000006u, 0x000002cau, 0x00000186u, 0x0000002fu, 0x00000183u, 0x000600a9u, 0x00000006u, 0x000002cbu, - 0x00000186u, 0x0000002fu, 0x00000180u, 0x000500c2u, 0x00000006u, 0x0000018cu, 0x00000086u, 0x0000002fu, - 0x000500abu, 0x00000008u, 0x0000018eu, 0x0000018cu, 0x0000000eu, 0x000500abu, 0x00000008u, 0x00000190u, - 0x0000017du, 0x0000000eu, 0x000500a7u, 0x00000008u, 0x00000191u, 0x0000018eu, 0x00000190u, 0x000500abu, - 0x00000008u, 0x00000193u, 0x000002cbu, 0x0000000eu, 0x000500a7u, 0x00000008u, 0x00000194u, 0x00000191u, - 0x00000193u, 0x000500abu, 0x00000008u, 0x00000196u, 0x000002cau, 0x0000000eu, 0x000500a7u, 0x00000008u, - 0x00000197u, 0x00000194u, 0x00000196u, 0x000300f7u, 0x00000199u, 0x00000000u, 0x000400fau, 0x00000197u, - 0x00000198u, 0x00000199u, 0x000200f8u, 0x00000198u, 0x0007000cu, 0x00000006u, 0x0000019cu, 0x00000001u, - 0x00000026u, 0x0000017du, 0x0000018cu, 0x00050086u, 0x00000006u, 0x000001a0u, 0x0000018cu, 0x0000019cu, - 0x0007000cu, 0x00000006u, 0x000001a1u, 0x00000001u, 0x00000026u, 0x000002cbu, 0x000001a0u, 0x00050086u, - 0x00000006u, 0x000001a7u, 0x000001a0u, 0x000001a1u, 0x0007000cu, 0x00000006u, 0x000001a8u, 0x00000001u, - 0x00000026u, 0x000002cau, 0x000001a7u, 0x000200f9u, 0x00000199u, 0x000200f8u, 0x00000199u, 0x000700f5u, - 0x00000006u, 0x00000260u, 0x000002cbu, 0x00000165u, 0x000001a1u, 0x00000198u, 0x000700f5u, 0x00000006u, - 0x0000025fu, 0x0000017du, 0x00000165u, 0x0000019cu, 0x00000198u, 0x000700f5u, 0x00000006u, 0x0000025eu, - 0x000002cau, 0x00000165u, 0x000001a8u, 0x00000198u, 0x000500abu, 0x00000008u, 0x000001aau, 0x0000025eu, - 0x0000000eu, 0x000300f7u, 0x000001acu, 0x00000000u, 0x000400fau, 0x000001aau, 0x000001abu, 0x000001acu, - 0x000200f8u, 0x000001abu, 0x00050084u, 0x00000006u, 0x000001afu, 0x0000025fu, 0x00000260u, 0x00050086u, - 0x00000006u, 0x000001b2u, 0x000001b0u, 0x0000025eu, 0x000500acu, 0x00000008u, 0x000001b3u, 0x000001afu, - 0x000001b2u, 0x000200f9u, 0x000001acu, 0x000200f8u, 0x000001acu, 0x000700f5u, 0x00000008u, 0x000001b4u, - 0x000001aau, 0x00000199u, 0x000001b3u, 0x000001abu, 0x000600a9u, 0x00000006u, 0x000002ccu, 0x000001b4u, - 0x0000000eu, 0x0000025eu, 0x000600a9u, 0x00000006u, 0x000002cdu, 0x000001b4u, 0x0000000eu, 0x00000260u, - 0x000600a9u, 0x00000006u, 0x000002ceu, 0x000001b4u, 0x0000000eu, 0x0000025fu, 0x000500abu, 0x00000008u, - 0x000001b9u, 0x000002ceu, 0x0000016bu, 0x000500abu, 0x00000008u, 0x000001bcu, 0x000002cdu, 0x00000172u, - 0x000500a6u, 0x00000008u, 0x000001bdu, 0x000001b9u, 0x000001bcu, 0x000500abu, 0x00000008u, 0x000001c0u, - 0x000002ccu, 0x00000179u, 0x000500a6u, 0x00000008u, 0x000001c1u, 0x000001bdu, 0x000001c0u, 0x000600a9u, - 0x00000006u, 0x000001c2u, 0x000001c1u, 0x0000002fu, 0x0000000eu, 0x00050084u, 0x00000006u, 0x000001c5u, - 0x000002ceu, 0x000002cdu, 0x00050084u, 0x00000006u, 0x000001c7u, 0x000001c5u, 0x000002ccu, 0x000600a9u, - 0x00000006u, 0x000001cdu, 0x00000186u, 0x000001cbu, 0x000001ccu, 0x00050084u, 0x00000006u, 0x000001ceu, - 0x000001c7u, 0x000001cdu, 0x00050041u, 0x00000007u, 0x000001d0u, 0x00000116u, 0x0000002cu, 0x0003003eu, - 0x000001d0u, 0x000002ceu, 0x00050041u, 0x00000007u, 0x000001d2u, 0x00000116u, 0x00000091u, 0x0003003eu, - 0x000001d2u, 0x000002cdu, 0x00050041u, 0x00000007u, 0x000001d4u, 0x00000116u, 0x000000bcu, 0x0003003eu, - 0x000001d4u, 0x000002ccu, 0x000200f9u, 0x0000011eu, 0x000200f8u, 0x0000011eu, 0x000700f5u, 0x00000006u, - 0x00000292u, 0x00000142u, 0x0000015du, 0x000001c2u, 0x000001acu, 0x000700f5u, 0x00000006u, 0x00000278u, - 0x00000145u, 0x0000015du, 0x000001ceu, 0x000001acu, 0x000500abu, 0x00000008u, 0x000001d6u, 0x00000278u, - 0x0000000eu, 0x000300f7u, 0x000001d8u, 0x00000000u, 0x000400fau, 0x000001d6u, 0x000001d7u, 0x000001d8u, - 0x000200f8u, 0x000001d7u, 0x000300f7u, 0x00000244u, 0x00000000u, 0x000300fbu, 0x0000000eu, 0x0000021cu, - 0x000200f8u, 0x0000021cu, 0x000500aau, 0x00000008u, 0x0000021eu, 0x00000278u, 0x0000000eu, 0x000300f7u, - 0x00000220u, 0x00000000u, 0x000400fau, 0x0000021eu, 0x0000021fu, 0x00000220u, 0x000200f8u, 0x0000021fu, - 0x000200f9u, 0x00000244u, 0x000200f8u, 0x00000220u, 0x00050041u, 0x00000029u, 0x00000221u, 0x00000026u, - 0x00000028u, 0x0004003du, 0x00000019u, 0x00000222u, 0x00000221u, 0x00060041u, 0x0000002du, 0x00000223u, - 0x00000222u, 0x0000002cu, 0x0000002cu, 0x000700eau, 0x00000006u, 0x00000224u, 0x00000223u, 0x0000002fu, - 0x0000000eu, 0x0000000eu, 0x000200f9u, 0x00000225u, 0x000200f8u, 0x00000225u, 0x000700f5u, 0x00000006u, - 0x0000027au, 0x00000224u, 0x00000220u, 0x00000239u, 0x00000240u, 0x000500b0u, 0x00000008u, 0x00000228u, - 0x0000027au, 0x00000037u, 0x000400f6u, 0x00000241u, 0x00000240u, 0x00000000u, 0x000400fau, 0x00000228u, - 0x00000229u, 0x00000241u, 0x000200f8u, 0x00000229u, 0x00050082u, 0x00000006u, 0x0000022bu, 0x00000037u, - 0x0000027au, 0x000500acu, 0x00000008u, 0x0000022eu, 0x00000278u, 0x0000022bu, 0x000300f7u, 0x00000230u, - 0x00000000u, 0x000400fau, 0x0000022eu, 0x0000022fu, 0x00000230u, 0x000200f8u, 0x0000022fu, 0x000200f9u, - 0x00000241u, 0x000200f8u, 0x00000230u, 0x00050080u, 0x00000006u, 0x00000233u, 0x0000027au, 0x00000278u, - 0x000900e6u, 0x00000006u, 0x00000239u, 0x00000223u, 0x0000002fu, 0x0000000eu, 0x0000000eu, 0x00000233u, - 0x0000027au, 0x000500aau, 0x00000008u, 0x0000023cu, 0x00000239u, 0x0000027au, 0x000300f7u, 0x0000023eu, - 0x00000000u, 0x000400fau, 0x0000023cu, 0x0000023du, 0x0000023eu, 0x000200f8u, 0x0000023du, 0x000200f9u, - 0x00000241u, 0x000200f8u, 0x0000023eu, 0x000200f9u, 0x00000240u, 0x000200f8u, 0x00000240u, 0x000200f9u, - 0x00000225u, 0x000200f8u, 0x00000241u, 0x000900f5u, 0x00000008u, 0x0000027fu, 0x00000288u, 0x00000225u, - 0x00000041u, 0x0000022fu, 0x00000012u, 0x0000023du, 0x000900f5u, 0x00000008u, 0x0000027cu, 0x00000041u, - 0x00000225u, 0x00000012u, 0x0000022fu, 0x00000012u, 0x0000023du, 0x000300f7u, 0x00000243u, 0x00000000u, - 0x000400fau, 0x0000027cu, 0x00000244u, 0x00000243u, 0x000200f8u, 0x00000243u, 0x000200f9u, 0x00000244u, - 0x000200f8u, 0x00000244u, 0x000900f5u, 0x00000008u, 0x0000027eu, 0x00000012u, 0x0000021fu, 0x0000027fu, - 0x00000241u, 0x00000041u, 0x00000243u, 0x000400a8u, 0x00000008u, 0x000001dcu, 0x0000027eu, 0x000200f9u, - 0x000001d8u, 0x000200f8u, 0x000001d8u, 0x000700f5u, 0x00000008u, 0x000001ddu, 0x000001d6u, 0x0000011eu, - 0x000001dcu, 0x00000244u, 0x000300f7u, 0x000001dfu, 0x00000000u, 0x000400fau, 0x000001ddu, 0x000001deu, - 0x000001dfu, 0x000200f8u, 0x000001deu, 0x00050041u, 0x00000029u, 0x000001e0u, 0x00000026u, 0x000000a9u, - 0x0004003du, 0x00000019u, 0x000001e1u, 0x000001e0u, 0x00060041u, 0x0000002du, 0x000001e2u, 0x000001e1u, - 0x0000002cu, 0x000000bcu, 0x000700eau, 0x00000006u, 0x000001e3u, 0x000001e2u, 0x0000002fu, 0x0000000eu, - 0x0000002fu, 0x0003003eu, 0x00000116u, 0x00000117u, 0x000200f9u, 0x000001dfu, 0x000200f8u, 0x000001dfu, - 0x000600a9u, 0x00000006u, 0x000002cfu, 0x000001ddu, 0x0000002fu, 0x00000292u, 0x000500abu, 0x00000008u, - 0x000001e5u, 0x000002cfu, 0x0000000eu, 0x000300f7u, 0x000001e7u, 0x00000000u, 0x000400fau, 0x000001e5u, - 0x000001e6u, 0x000001e7u, 0x000200f8u, 0x000001e6u, 0x00050041u, 0x00000029u, 0x000001e8u, 0x00000026u, - 0x000000a9u, 0x0004003du, 0x00000019u, 0x000001e9u, 0x000001e8u, 0x00060041u, 0x0000002du, 0x000001eau, - 0x000001e9u, 0x0000002cu, 0x0000002cu, 0x000700eau, 0x00000006u, 0x000001ebu, 0x000001eau, 0x0000002fu, - 0x0000000eu, 0x0000002fu, 0x00050041u, 0x00000007u, 0x000001ecu, 0x00000116u, 0x0000002cu, 0x0004003du, - 0x00000006u, 0x000001edu, 0x000001ecu, 0x000500aau, 0x00000008u, 0x000001eeu, 0x000001edu, 0x0000000eu, - 0x000300f7u, 0x000001f0u, 0x00000000u, 0x000400fau, 0x000001eeu, 0x000001efu, 0x000001f0u, 0x000200f8u, - 0x000001efu, 0x00060041u, 0x0000002du, 0x000001f3u, 0x000001e9u, 0x0000002cu, 0x0000009eu, 0x000700eau, - 0x00000006u, 0x000001f4u, 0x000001f3u, 0x0000002fu, 0x0000000eu, 0x0000002fu, 0x000200f9u, 0x000001f0u, - 0x000200f8u, 0x000001f0u, 0x000200f9u, 0x000001e7u, 0x000200f8u, 0x000001e7u, 0x000200f9u, 0x000001f6u, - 0x000200f8u, 0x000001f6u, 0x000700f5u, 0x00000006u, 0x00000297u, 0x0000000eu, 0x000001e7u, 0x00000208u, - 0x000001f7u, 0x000500b0u, 0x00000008u, 0x000001fdu, 0x00000297u, 0x00000246u, 0x000400f6u, 0x000001f8u, - 0x000001f7u, 0x00000000u, 0x000400fau, 0x000001fdu, 0x000001f7u, 0x000001f8u, 0x000200f8u, 0x000001f7u, - 0x00050041u, 0x000000bdu, 0x000001feu, 0x00000026u, 0x000000bcu, 0x0004003du, 0x00000017u, 0x000001ffu, - 0x000001feu, 0x00050080u, 0x00000006u, 0x00000202u, 0x00000081u, 0x00000297u, 0x00050041u, 0x00000007u, - 0x00000204u, 0x00000116u, 0x00000297u, 0x0004003du, 0x00000006u, 0x00000205u, 0x00000204u, 0x00060041u, - 0x0000002du, 0x00000206u, 0x000001ffu, 0x0000002cu, 0x00000202u, 0x0005003eu, 0x00000206u, 0x00000205u, - 0x00000002u, 0x00000004u, 0x00050080u, 0x00000006u, 0x00000208u, 0x00000297u, 0x00000091u, 0x000200f9u, - 0x000001f6u, 0x000200f8u, 0x000001f8u, 0x000200f9u, 0x0000020au, 0x000200f8u, 0x0000020au, 0x000100fdu, - 0x00010038u, + 0x00000006u, 0x00000179u, 0x00000178u, 0x00000002u, 0x00000004u, 0x000500aau, 0x00000008u, 0x0000017cu, + 0x00000070u, 0x0000007cu, 0x000300f7u, 0x0000017eu, 0x00000000u, 0x000400fau, 0x0000017cu, 0x0000017du, + 0x0000017eu, 0x000200f8u, 0x0000017du, 0x00050041u, 0x00000029u, 0x0000017fu, 0x00000026u, 0x000000a9u, + 0x0004003du, 0x00000019u, 0x00000180u, 0x0000017fu, 0x00060041u, 0x0000002du, 0x00000181u, 0x00000180u, + 0x0000002cu, 0x0000005fu, 0x000700eau, 0x00000006u, 0x00000182u, 0x00000181u, 0x0000002fu, 0x0000000eu, + 0x0000002fu, 0x000500acu, 0x00000008u, 0x00000184u, 0x00000172u, 0x0000002fu, 0x000500acu, 0x00000008u, + 0x00000186u, 0x00000179u, 0x0000002fu, 0x000500a6u, 0x00000008u, 0x00000187u, 0x00000184u, 0x00000186u, + 0x000300f7u, 0x00000189u, 0x00000000u, 0x000400fau, 0x00000187u, 0x00000188u, 0x00000189u, 0x000200f8u, + 0x00000188u, 0x00060041u, 0x0000002du, 0x0000018cu, 0x00000180u, 0x0000002cu, 0x00000068u, 0x000700eau, + 0x00000006u, 0x0000018du, 0x0000018cu, 0x0000002fu, 0x0000000eu, 0x0000002fu, 0x00060041u, 0x0000002du, + 0x00000190u, 0x00000180u, 0x0000002cu, 0x0000008au, 0x000700efu, 0x00000006u, 0x00000192u, 0x00000190u, + 0x0000002fu, 0x0000000eu, 0x00000172u, 0x00060041u, 0x0000002du, 0x00000195u, 0x00000180u, 0x0000002cu, + 0x00000084u, 0x000700efu, 0x00000006u, 0x00000197u, 0x00000195u, 0x0000002fu, 0x0000000eu, 0x00000179u, + 0x000200f9u, 0x00000189u, 0x000200f8u, 0x00000189u, 0x000200f9u, 0x0000017eu, 0x000200f8u, 0x0000017eu, + 0x0007000cu, 0x00000006u, 0x0000019bu, 0x00000001u, 0x00000026u, 0x0000016bu, 0x0000019au, 0x0007000cu, + 0x00000006u, 0x0000019eu, 0x00000001u, 0x00000026u, 0x00000172u, 0x0000019au, 0x0007000cu, 0x00000006u, + 0x000001a1u, 0x00000001u, 0x00000026u, 0x00000179u, 0x0000019au, 0x000600a9u, 0x00000006u, 0x000002f4u, + 0x0000017cu, 0x0000002fu, 0x000001a1u, 0x000600a9u, 0x00000006u, 0x000002f5u, 0x0000017cu, 0x0000002fu, + 0x0000019eu, 0x000500c2u, 0x00000006u, 0x000001aau, 0x00000086u, 0x0000002fu, 0x000500abu, 0x00000008u, + 0x000001acu, 0x000001aau, 0x0000000eu, 0x000500abu, 0x00000008u, 0x000001aeu, 0x0000019bu, 0x0000000eu, + 0x000500a7u, 0x00000008u, 0x000001afu, 0x000001acu, 0x000001aeu, 0x000500abu, 0x00000008u, 0x000001b1u, + 0x000002f5u, 0x0000000eu, 0x000500a7u, 0x00000008u, 0x000001b2u, 0x000001afu, 0x000001b1u, 0x000500abu, + 0x00000008u, 0x000001b4u, 0x000002f4u, 0x0000000eu, 0x000500a7u, 0x00000008u, 0x000001b5u, 0x000001b2u, + 0x000001b4u, 0x000300f7u, 0x000001b7u, 0x00000000u, 0x000400fau, 0x000001b5u, 0x000001b6u, 0x000001b7u, + 0x000200f8u, 0x000001b6u, 0x0007000cu, 0x00000006u, 0x000001bau, 0x00000001u, 0x00000026u, 0x0000019bu, + 0x000001aau, 0x00050086u, 0x00000006u, 0x000001beu, 0x000001aau, 0x000001bau, 0x0007000cu, 0x00000006u, + 0x000001bfu, 0x00000001u, 0x00000026u, 0x000002f5u, 0x000001beu, 0x00050086u, 0x00000006u, 0x000001c5u, + 0x000001beu, 0x000001bfu, 0x0007000cu, 0x00000006u, 0x000001c6u, 0x00000001u, 0x00000026u, 0x000002f4u, + 0x000001c5u, 0x000200f9u, 0x000001b7u, 0x000200f8u, 0x000001b7u, 0x000700f5u, 0x00000006u, 0x00000284u, + 0x000002f5u, 0x0000017eu, 0x000001bfu, 0x000001b6u, 0x000700f5u, 0x00000006u, 0x00000283u, 0x0000019bu, + 0x0000017eu, 0x000001bau, 0x000001b6u, 0x000700f5u, 0x00000006u, 0x00000282u, 0x000002f4u, 0x0000017eu, + 0x000001c6u, 0x000001b6u, 0x000500abu, 0x00000008u, 0x000001c8u, 0x00000282u, 0x0000000eu, 0x000300f7u, + 0x000001cau, 0x00000000u, 0x000400fau, 0x000001c8u, 0x000001c9u, 0x000001cau, 0x000200f8u, 0x000001c9u, + 0x00050084u, 0x00000006u, 0x000001cdu, 0x00000283u, 0x00000284u, 0x00050086u, 0x00000006u, 0x000001d0u, + 0x000001ceu, 0x00000282u, 0x000500acu, 0x00000008u, 0x000001d1u, 0x000001cdu, 0x000001d0u, 0x000200f9u, + 0x000001cau, 0x000200f8u, 0x000001cau, 0x000700f5u, 0x00000008u, 0x000001d2u, 0x000001c8u, 0x000001b7u, + 0x000001d1u, 0x000001c9u, 0x000600a9u, 0x00000006u, 0x000002f6u, 0x000001d2u, 0x0000000eu, 0x00000282u, + 0x000600a9u, 0x00000006u, 0x000002f7u, 0x000001d2u, 0x0000000eu, 0x00000284u, 0x000600a9u, 0x00000006u, + 0x000002f8u, 0x000001d2u, 0x0000000eu, 0x00000283u, 0x000500abu, 0x00000008u, 0x000001d7u, 0x000002f8u, + 0x0000016bu, 0x000500abu, 0x00000008u, 0x000001dau, 0x000002f7u, 0x00000172u, 0x000500a6u, 0x00000008u, + 0x000001dbu, 0x000001d7u, 0x000001dau, 0x000500abu, 0x00000008u, 0x000001deu, 0x000002f6u, 0x00000179u, + 0x000500a6u, 0x00000008u, 0x000001dfu, 0x000001dbu, 0x000001deu, 0x000600a9u, 0x00000006u, 0x000001e0u, + 0x000001dfu, 0x0000002fu, 0x0000000eu, 0x00050084u, 0x00000006u, 0x000001e3u, 0x000002f8u, 0x000002f7u, + 0x00050084u, 0x00000006u, 0x000001e5u, 0x000001e3u, 0x000002f6u, 0x000600a9u, 0x00000006u, 0x000001ebu, + 0x0000017cu, 0x000001e9u, 0x000001eau, 0x00050084u, 0x00000006u, 0x000001ecu, 0x000001e5u, 0x000001ebu, + 0x00050041u, 0x00000007u, 0x000001eeu, 0x00000116u, 0x0000002cu, 0x0003003eu, 0x000001eeu, 0x000002f8u, + 0x00050041u, 0x00000007u, 0x000001f0u, 0x00000116u, 0x00000091u, 0x0003003eu, 0x000001f0u, 0x000002f7u, + 0x00050041u, 0x00000007u, 0x000001f2u, 0x00000116u, 0x000000bcu, 0x0003003eu, 0x000001f2u, 0x000002f6u, + 0x000200f9u, 0x0000011eu, 0x000200f8u, 0x0000011eu, 0x000700f5u, 0x00000006u, 0x000002b8u, 0x00000142u, + 0x0000015du, 0x000001e0u, 0x000001cau, 0x000700f5u, 0x00000006u, 0x0000029cu, 0x00000145u, 0x0000015du, + 0x000001ecu, 0x000001cau, 0x000500abu, 0x00000008u, 0x000001f4u, 0x0000029cu, 0x0000000eu, 0x000300f7u, + 0x000001f6u, 0x00000000u, 0x000400fau, 0x000001f4u, 0x000001f5u, 0x000001f6u, 0x000200f8u, 0x000001f5u, + 0x000300f7u, 0x00000262u, 0x00000000u, 0x000300fbu, 0x0000000eu, 0x0000023au, 0x000200f8u, 0x0000023au, + 0x000500aau, 0x00000008u, 0x0000023cu, 0x0000029cu, 0x0000000eu, 0x000300f7u, 0x0000023eu, 0x00000000u, + 0x000400fau, 0x0000023cu, 0x0000023du, 0x0000023eu, 0x000200f8u, 0x0000023du, 0x000200f9u, 0x00000262u, + 0x000200f8u, 0x0000023eu, 0x00050041u, 0x00000029u, 0x0000023fu, 0x00000026u, 0x00000028u, 0x0004003du, + 0x00000019u, 0x00000240u, 0x0000023fu, 0x00060041u, 0x0000002du, 0x00000241u, 0x00000240u, 0x0000002cu, + 0x0000002cu, 0x000700eau, 0x00000006u, 0x00000242u, 0x00000241u, 0x0000002fu, 0x0000000eu, 0x0000000eu, + 0x000200f9u, 0x00000243u, 0x000200f8u, 0x00000243u, 0x000700f5u, 0x00000006u, 0x0000029eu, 0x00000242u, + 0x0000023eu, 0x00000257u, 0x0000025eu, 0x000500b0u, 0x00000008u, 0x00000246u, 0x0000029eu, 0x00000037u, + 0x000400f6u, 0x0000025fu, 0x0000025eu, 0x00000000u, 0x000400fau, 0x00000246u, 0x00000247u, 0x0000025fu, + 0x000200f8u, 0x00000247u, 0x00050082u, 0x00000006u, 0x00000249u, 0x00000037u, 0x0000029eu, 0x000500acu, + 0x00000008u, 0x0000024cu, 0x0000029cu, 0x00000249u, 0x000300f7u, 0x0000024eu, 0x00000000u, 0x000400fau, + 0x0000024cu, 0x0000024du, 0x0000024eu, 0x000200f8u, 0x0000024du, 0x000200f9u, 0x0000025fu, 0x000200f8u, + 0x0000024eu, 0x00050080u, 0x00000006u, 0x00000251u, 0x0000029eu, 0x0000029cu, 0x000900e6u, 0x00000006u, + 0x00000257u, 0x00000241u, 0x0000002fu, 0x0000000eu, 0x0000000eu, 0x00000251u, 0x0000029eu, 0x000500aau, + 0x00000008u, 0x0000025au, 0x00000257u, 0x0000029eu, 0x000300f7u, 0x0000025cu, 0x00000000u, 0x000400fau, + 0x0000025au, 0x0000025bu, 0x0000025cu, 0x000200f8u, 0x0000025bu, 0x000200f9u, 0x0000025fu, 0x000200f8u, + 0x0000025cu, 0x000200f9u, 0x0000025eu, 0x000200f8u, 0x0000025eu, 0x000200f9u, 0x00000243u, 0x000200f8u, + 0x0000025fu, 0x000900f5u, 0x00000008u, 0x000002a3u, 0x000002acu, 0x00000243u, 0x00000041u, 0x0000024du, + 0x00000012u, 0x0000025bu, 0x000900f5u, 0x00000008u, 0x000002a0u, 0x00000041u, 0x00000243u, 0x00000012u, + 0x0000024du, 0x00000012u, 0x0000025bu, 0x000300f7u, 0x00000261u, 0x00000000u, 0x000400fau, 0x000002a0u, + 0x00000262u, 0x00000261u, 0x000200f8u, 0x00000261u, 0x000200f9u, 0x00000262u, 0x000200f8u, 0x00000262u, + 0x000900f5u, 0x00000008u, 0x000002a2u, 0x00000012u, 0x0000023du, 0x000002a3u, 0x0000025fu, 0x00000041u, + 0x00000261u, 0x000400a8u, 0x00000008u, 0x000001fau, 0x000002a2u, 0x000200f9u, 0x000001f6u, 0x000200f8u, + 0x000001f6u, 0x000700f5u, 0x00000008u, 0x000001fbu, 0x000001f4u, 0x0000011eu, 0x000001fau, 0x00000262u, + 0x000300f7u, 0x000001fdu, 0x00000000u, 0x000400fau, 0x000001fbu, 0x000001fcu, 0x000001fdu, 0x000200f8u, + 0x000001fcu, 0x00050041u, 0x00000029u, 0x000001feu, 0x00000026u, 0x000000a9u, 0x0004003du, 0x00000019u, + 0x000001ffu, 0x000001feu, 0x00060041u, 0x0000002du, 0x00000200u, 0x000001ffu, 0x0000002cu, 0x000000bcu, + 0x000700eau, 0x00000006u, 0x00000201u, 0x00000200u, 0x0000002fu, 0x0000000eu, 0x0000002fu, 0x0003003eu, + 0x00000116u, 0x00000117u, 0x000200f9u, 0x000001fdu, 0x000200f8u, 0x000001fdu, 0x000600a9u, 0x00000006u, + 0x000002f9u, 0x000001fbu, 0x0000002fu, 0x000002b8u, 0x000500abu, 0x00000008u, 0x00000203u, 0x000002f9u, + 0x0000000eu, 0x000300f7u, 0x00000205u, 0x00000000u, 0x000400fau, 0x00000203u, 0x00000204u, 0x00000205u, + 0x000200f8u, 0x00000204u, 0x00050041u, 0x00000029u, 0x00000206u, 0x00000026u, 0x000000a9u, 0x0004003du, + 0x00000019u, 0x00000207u, 0x00000206u, 0x00060041u, 0x0000002du, 0x00000208u, 0x00000207u, 0x0000002cu, + 0x0000002cu, 0x000700eau, 0x00000006u, 0x00000209u, 0x00000208u, 0x0000002fu, 0x0000000eu, 0x0000002fu, + 0x00050041u, 0x00000007u, 0x0000020au, 0x00000116u, 0x0000002cu, 0x0004003du, 0x00000006u, 0x0000020bu, + 0x0000020au, 0x000500aau, 0x00000008u, 0x0000020cu, 0x0000020bu, 0x0000000eu, 0x000300f7u, 0x0000020eu, + 0x00000000u, 0x000400fau, 0x0000020cu, 0x0000020du, 0x0000020eu, 0x000200f8u, 0x0000020du, 0x00060041u, + 0x0000002du, 0x00000211u, 0x00000207u, 0x0000002cu, 0x0000009eu, 0x000700eau, 0x00000006u, 0x00000212u, + 0x00000211u, 0x0000002fu, 0x0000000eu, 0x0000002fu, 0x000200f9u, 0x0000020eu, 0x000200f8u, 0x0000020eu, + 0x000200f9u, 0x00000205u, 0x000200f8u, 0x00000205u, 0x000200f9u, 0x00000214u, 0x000200f8u, 0x00000214u, + 0x000700f5u, 0x00000006u, 0x000002bdu, 0x0000000eu, 0x00000205u, 0x00000226u, 0x00000215u, 0x000500b0u, + 0x00000008u, 0x0000021bu, 0x000002bdu, 0x00000264u, 0x000400f6u, 0x00000216u, 0x00000215u, 0x00000000u, + 0x000400fau, 0x0000021bu, 0x00000215u, 0x00000216u, 0x000200f8u, 0x00000215u, 0x00050041u, 0x000000bdu, + 0x0000021cu, 0x00000026u, 0x000000bcu, 0x0004003du, 0x00000017u, 0x0000021du, 0x0000021cu, 0x00050080u, + 0x00000006u, 0x00000220u, 0x00000081u, 0x000002bdu, 0x00050041u, 0x00000007u, 0x00000222u, 0x00000116u, + 0x000002bdu, 0x0004003du, 0x00000006u, 0x00000223u, 0x00000222u, 0x00060041u, 0x0000002du, 0x00000224u, + 0x0000021du, 0x0000002cu, 0x00000220u, 0x0005003eu, 0x00000224u, 0x00000223u, 0x00000002u, 0x00000004u, + 0x00050080u, 0x00000006u, 0x00000226u, 0x000002bdu, 0x00000091u, 0x000200f9u, 0x00000214u, 0x000200f8u, + 0x00000216u, 0x000200f9u, 0x00000228u, 0x000200f8u, 0x00000228u, 0x000100fdu, 0x00010038u, }; } // namespace leonida diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp index 094aaa3211..76b180475b 100644 --- a/runtime/src/main.cpp +++ b/runtime/src/main.cpp @@ -9,6 +9,13 @@ // gta6rt --init [--game-dir DIR] [--overlay DIR] // The same mapping, then each loaded DLL's TLS callbacks and DllMain(DLL_PROCESS_ATTACH) are run. // +// gta6rt --precompile-pipelines [--threads N] [--big-threads N] [--big-bytes N] [--all] [--smallest-first] +// [--limit N] [--min-bytes N] [--max-bytes N] [--filter PART]... [--list] +// No game: creates the Vulkan device as --run does and builds every compute pipeline of the shader library +// (LEONIDA_SHADERS) into the pipeline journal and the driver's cache, so a title's first dispatch of a large one +// does not stall it. Resumable: entries already journaled are skipped (--all: built anyway). See +// shims/d3d12_precompile.h. +// // gta6rt --run [--game-dir DIR] [--overlay DIR] [--trace-d3d12] [--trace FILE] [-- game arguments...] // The same, then the EXE's own TLS callbacks and its entry point, on a game thread. The game's argv and // command line are plus the arguments after "--"; exit/ExitProcess from the game end the run @@ -156,7 +163,9 @@ void start_title_peek(std::uint8_t* base) { #include "../shims/d3d12_xs_device.h" #include "../shims/file_system.h" #ifdef LEONIDA_VULKAN_DEVICE +#include "vulkan_device_fault.h" #include "../shims/d3d12_compile_exit.h" +#include "../shims/d3d12_precompile.h" #include "../shims/package_splash.h" #endif #include "../shims/process_shim.h" @@ -224,10 +233,66 @@ int usage() { "usage: gta6rt --dry-run [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace FILE]\n" " gta6rt --init [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace-d3d12] [--trace FILE]\n" " gta6rt --first-run-ui [--game-dir DIR] [--overlay DIR] [--trace FILE]\n" - " gta6rt --run [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace-d3d12] [--trace FILE] [-- game arguments...]\n"); + " gta6rt --run [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace-d3d12] [--trace FILE] [-- game arguments...]\n" + " gta6rt --precompile-pipelines [--threads N] [--big-threads N] [--big-bytes N] [--all] [--smallest-first] [--limit N] [--min-bytes N] [--max-bytes N] [--filter PART]... [--list] [--via-helper]\n" + " gta6rt --compile-server [--parent PID] [--threads N] [--idle-threads N] [--idle-exit SECONDS]\n"); return 2; } +#ifdef LEONIDA_VULKAN_DEVICE +// gta6rt --precompile-pipelines ...: argv[1] is the mode. +int precompile_main(int argc, wchar_t** argv) { + rt::d3d12::PrecompileOptions options; + const auto number = [&](int& i, auto& out) { + if (i + 1 >= argc) return false; + wchar_t* end = nullptr; + const unsigned long long v = std::wcstoull(argv[++i], &end, 10); + if (!end || *end) return false; + out = static_cast>(v); + return true; + }; + for (int i = 2; i < argc; ++i) { + const std::wstring a = argv[i]; + bool ok = true; + if (a == L"--threads") ok = number(i, options.threads); + else if (a == L"--big-threads") ok = number(i, options.big_threads); + else if (a == L"--big-bytes") ok = number(i, options.big_bytes); + else if (a == L"--limit") ok = number(i, options.limit); + else if (a == L"--min-bytes") ok = number(i, options.min_bytes); + else if (a == L"--max-bytes") ok = number(i, options.max_bytes); + else if (a == L"--all") options.rebuild = true; + else if (a == L"--smallest-first") options.smallest_first = true; + else if (a == L"--list") options.dry_run = true; + else if (a == L"--via-helper") options.via_helper = true; + else if (a == L"--filter" && i + 1 < argc) { + const std::wstring part = argv[++i]; + options.filters.emplace_back(part.begin(), part.end()); // library names are ASCII + } else ok = false; + if (!ok) return usage(); + } + return rt::d3d12::precompile_compute_pipelines(options); +} + +// gta6rt --compile-server [--parent PID] [--threads N] [--idle-threads N] [--idle-exit SECONDS] +// (shims/d3d12_compile_helper.h). +int compile_server_main(int argc, wchar_t** argv) { + rt::d3d12::CompileServerOptions options; + for (int i = 2; i < argc; ++i) { + const std::wstring a = argv[i]; + if (i + 1 >= argc) return usage(); + wchar_t* end = nullptr; + const unsigned long long v = std::wcstoull(argv[++i], &end, 10); + if (!end || *end) return usage(); + if (a == L"--parent") options.parent_pid = static_cast(v); + else if (a == L"--threads") options.threads = static_cast(v); + else if (a == L"--idle-threads") options.idle_threads = static_cast(v); + else if (a == L"--idle-exit") options.idle_exit_s = static_cast(v); + else return usage(); + } + return rt::d3d12::compile_server(options); +} +#endif + } // namespace #ifdef LEONIDA_VULKAN_DEVICE @@ -292,6 +357,10 @@ static BOOL WINAPI show_package_window(HWND window, int command) { #endif int wmain(int argc, wchar_t** argv) { +#ifdef LEONIDA_VULKAN_DEVICE + if (argc > 1 && std::wstring(argv[1]) == L"--precompile-pipelines") return precompile_main(argc, argv); + if (argc > 1 && std::wstring(argv[1]) == L"--compile-server") return compile_server_main(argc, argv); +#endif std::filesystem::path image, game_dir, overlay_dir, mods_dir; uint32_t archetype_lookup_rva = 0; // --archetype-lookup RVA[,ARG]: the game's archetype lookup by hash int archetype_lookup_arg = 0; @@ -436,6 +505,8 @@ int wmain(int argc, wchar_t** argv) { rt::d3d12_trace::set_enabled(trace_d3d12); // Slot 133 imports the title's pages; xmem commits them on first touch, so they are committed first. rt::d3d12_xs::set_placed_at_va_pages_hook(&rt::xmem::commit_physical_range); + if (rt::xmem::slot31_runs() && rt::xmem::queue_page_mappings_enabled()) + rt::d3d12_xs::set_copy_page_mappings_hook(&rt::xmem::copy_page_mappings); // So do the file shims' reads, whose kernel writes do not fault them in: on ERROR_NOACCESS (title_page_watch.h). leonida::geometry_writes::aliases.store(&rt::xmem::geometry_aliases); leonida::kernel_writes::set_committer(&rt::xmem::commit_physical_range); @@ -567,6 +638,9 @@ int wmain(int argc, wchar_t** argv) { previous_fatal_filter = SetUnhandledExceptionFilter(&save_caches_on_fatal_exception); #endif int code; +#ifdef LEONIDA_VULKAN_DEVICE + leonida::thread_stack_hook.store(&rt::print_thread_stacks_now, std::memory_order_release); +#endif { auto stacks = rt::start_thread_stacks(); code = rt::process::run_entry(main_module.base + main_module.entry_rva); diff --git a/runtime/src/pipeline_cache_journal.h b/runtime/src/pipeline_cache_journal.h new file mode 100644 index 0000000000..6a72d07f03 --- /dev/null +++ b/runtime/src/pipeline_cache_journal.h @@ -0,0 +1,356 @@ +// One Vulkan pipeline cache file per compiled compute pipeline: the "pipeline journal". +// +// The session cache (pipeline_cache_store.h) is one blob written at device teardown or at an idle checkpoint. A boot +// that ends by a crash, a device loss or `timeout` never tears the device down, and while the compute warm-up thread +// has builds queued the idle checkpoint never runs, so the hundreds of large compute pipelines a boot compiles were +// compiled again on every boot. The journal keeps each one in its own small cache file the moment it is built: +// +// /pipeline_cache.d/cs-<16 hex digits>.bin +// +// The name is a hash of what the pipeline is made of (the SPIR-V words, the stage's subgroup request and the layout). +// Each file is a complete VkPipelineCache blob holding one pipeline. A build reads the file, if any, into a +// VkPipelineCache of its own and creates the pipeline against it: the driver finds the pipeline there (a hit, a few +// milliseconds where the compile took seconds) or compiles it and the file is written again. Files are published +// whole (write_pipeline_cache_file: a closed staging file renamed over the target), so a process killed mid-write +// leaves the previous file or none, and a boot that dies keeps everything it built before. +// +// The hash only picks the file. Whether the pipeline in it may be used is the driver's decision: it checks the blob +// header (vendor, device, pipeline-cache UUID; checked here first too, so a driver update starts over) and its own key. +// +// Upkeep (tidy, at the first pipeline of a device): staging files a killed writer left behind are removed once they are +// ten minutes old, and past LEONIDA_PIPELINE_JOURNAL_BYTES the least recently used files go until three quarters of +// it is left. A file's modification time is its last use: written, or touched when a build found its pipeline there. +// +// Pure stdlib apart from pipeline_cache_file.h's Windows rename retry; tested by pipeline_cache_journal_test. +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cached_pso.h" +#include "pipeline_cache_store.h" // before pipeline_cache_file.h, whose may define max +#include "pipeline_cache_file.h" + +namespace leonida::pipeline_journal { + +// Bumped when what goes into a key changes, so files named under the old scheme are no longer looked up. +inline constexpr std::uint32_t key_version = 1; + +// A file larger than this is not read (a corrupt or foreign file; one pipeline's cache is a few MiB at most). +inline constexpr std::size_t entry_read_limit = std::size_t{256} << 20; + +// 64-bit FNV-1a. Not cryptographic: it names a file, and a collision costs one compile, not a wrong pipeline. +class Hasher { +public: + Hasher() { value(key_version); } + + void bytes(const void* data, std::size_t size) { + const auto* p = static_cast(data); + std::uint64_t h = hash_; + for (std::size_t i = 0; i < size; ++i) { + h ^= p[i]; + h *= 0x100000001b3ull; + } + hash_ = h; + } + + template void value(const T& v) { + static_assert(std::is_trivially_copyable_v); + bytes(&v, sizeof(v)); + } + + void text(const char* s) { + const std::string_view view(s ? s : ""); + value(std::uint64_t(view.size())); + bytes(view.data(), view.size()); + } + + std::uint64_t digest() const { return hash_; } + +private: + std::uint64_t hash_ = 0xcbf29ce484222325ull; +}; + +// /-.bin +inline std::filesystem::path entry_path(const std::filesystem::path& dir, const char* kind, std::uint64_t key) { + char name[64]; + std::snprintf(name, sizeof(name), "%s-%016llx.bin", kind, static_cast(key)); + return dir / name; +} + +// Resolve the two roots once, not on the compile path. With no seed keep the original single-root behavior. +// An explicit bad/overlapping pair disables the journal rather than accidentally publishing into the seed. +// This is a configuration check, not a substitute for a read-only mount/ACL and stable parent directories. +struct Roots { + std::filesystem::path writable; + std::filesystem::path seed; +}; + +inline Roots resolve_roots(const std::filesystem::path& local, const std::filesystem::path& seed) { + namespace fs = std::filesystem; + if (seed.empty() || local.empty()) return {local, {}}; + std::error_code ec; + if (!seed.is_absolute() || !fs::is_directory(seed, ec) || ec) return {}; + const auto source = fs::canonical(seed, ec); + if (ec) return {}; + const auto abs_local = fs::absolute(local, ec); + if (ec) return {}; + const auto dest = fs::weakly_canonical(abs_local, ec); // The writable leaf need not exist yet. + if (ec) return {}; + const bool dest_exists = fs::exists(dest, ec); + if (ec || (dest_exists && !fs::is_directory(dest, ec))) return {}; + // Use directory identity, not string prefixes: NTFS aliases and case differences still identify one directory. + auto overlaps = [&](const fs::path& existing, fs::path path) { + for (;;) { + if (fs::exists(path, ec) && fs::equivalent(existing, path, ec)) return true; + if (ec) return true; + const auto parent = path.parent_path(); + if (parent == path || parent.empty()) return false; + path = parent; + } + }; + if (overlaps(source, dest) || (dest_exists && overlaps(dest, source))) return {}; + return {dest, source}; +} + +// The selected compatible bytes plus metadata for the *writable* leaf as the build found it. +struct EntryFile { + std::vector data; // compatible local bytes, else compatible seed bytes; empty when neither is usable + bool from_seed = false; // an external hit must not refresh either the immutable seed or a stale local file + std::uint64_t bytes = 0; // its size on disk, whatever its contents (0: none): what a rewrite replaces + std::filesystem::file_time_type used{}; // its modification time: its last use +}; + +inline EntryFile read_entry_file(const std::filesystem::path& path, const cached_pso::Identity& identity, + std::size_t limit = entry_read_limit) { + EntryFile entry; + std::error_code ec; + const auto size = std::filesystem::file_size(path, ec); + if (ec) return entry; + entry.bytes = size; + entry.used = std::filesystem::last_write_time(path, ec); + if (ec || size < pipeline_cache_store::header_bytes || size > limit) return entry; + std::ifstream file(path, std::ios::binary); + if (!file) return entry; + entry.data.resize(static_cast(size)); + if (!file.read(entry.data.data(), static_cast(entry.data.size())) || + !pipeline_cache_store::header_matches(entry.data.data(), entry.data.size(), identity)) + entry.data.clear(); + return entry; +} + +// The file's bytes, or empty when it is missing, unreadable, over `limit`, or its header does not name `identity`. +inline std::vector read_entry(const std::filesystem::path& path, const cached_pso::Identity& identity, + std::size_t limit = entry_read_limit) { + return read_entry_file(path, identity, limit).data; +} + +// Whether the file is there with a header naming this device and driver: only the header is read (gta6rt +// --precompile-pipelines asks this of thousands of files of a few MiB). +inline bool entry_usable(const std::filesystem::path& path, const cached_pso::Identity& identity, + std::size_t limit = entry_read_limit) { + // A helper-ready file must also fit the consumer's bounded read. Check metadata, not the full payload. + std::error_code ec; + const auto size = std::filesystem::file_size(path, ec); + if (ec || size < pipeline_cache_store::header_bytes || size > limit) return false; + std::ifstream file(path, std::ios::binary); + char header[pipeline_cache_store::header_bytes]; + return file && file.read(header, sizeof(header)) && + pipeline_cache_store::header_matches(header, sizeof(header), identity); +} + +enum class ReadRole { runtime, materialize_local }; + +// A write always replaces the local file, not the seed. Keep its size and timestamp even if its +// data is unusable. A seed miss adds no writable bytes; the seed directory is never scanned. +inline EntryFile read_with_seed(const std::filesystem::path& local_entry, const std::filesystem::path& seed, + const cached_pso::Identity& identity, ReadRole role, std::size_t limit = entry_read_limit) { + auto local = read_entry_file(local_entry, identity, limit); + // Build hosts promise a file in the writable journal. External data must not satisfy such a request. + if (role == ReadRole::runtime && local.data.empty() && !seed.empty()) { + local.data = read_entry_file(seed / local_entry.filename(), identity, limit).data; + local.from_seed = !local.data.empty(); + } + return local; +} + +// A create this long, with no feedback to say, was a compile. +inline constexpr std::uint64_t unreported_compile_ms = 1000; +// NVIDIA 630.20 answers FAIL_ON_PIPELINE_COMPILE_REQUIRED with a compiled pipeline (seconds) instead of +// VK_PIPELINE_COMPILE_REQUIRED. A pipeline from its own disk cache comes back fast and without the application-cache +// hit bit too, and is no sign of that. +inline constexpr std::uint64_t probe_compile_ms = 250; + +// Whether a build writes its journal file. `seeded`: its cache was made from the file; `hit`: the creation feedback +// (1 found in that cache, 0 not, -1 not reported); `driver_ms`: the vkCreateComputePipelines call alone. +inline bool should_write(bool seeded, int hit, std::uint64_t driver_ms) { + if (!seeded) return true; // the pipeline is in no file yet + if (hit >= 0) return hit == 0; + return driver_ms >= unreported_compile_ms; +} + +// Whether a pipeline the shared cache gave for FAIL_ON_PIPELINE_COMPILE_REQUIRED was compiled after all. +inline bool probe_compiled(int hit, std::uint64_t driver_ms) { return hit == 0 && driver_ms >= probe_compile_ms; } + +// The journal's size after a file of `old_bytes` (0: none) is replaced by one of `new_bytes`. +inline std::uint64_t replace_bytes(std::uint64_t total, std::uint64_t old_bytes, std::uint64_t new_bytes) { + return total - (std::min)(total, old_bytes) + new_bytes; +} + +// A file's last use is refreshed when it is more than this old, not at every hit. +inline constexpr std::chrono::hours touch_after{1}; + +inline void touch(const std::filesystem::path& path, std::filesystem::file_time_type now) { + std::error_code ec; + std::filesystem::last_write_time(path, now, ec); +} + +// Called only after a journal cache hit. Only the local entry that supplied the hit is eligible for LRU. +inline void touch_local_hit(const std::filesystem::path& local_entry, const EntryFile& file, + std::filesystem::file_time_type now) { + if (!file.from_seed && file.bytes && now - file.used >= touch_after) + touch(local_entry, now); +} + +namespace detail { +inline bool digits(std::string_view s) { + return !s.empty() && s.find_first_not_of("0123456789") == std::string_view::npos; +} +inline bool hex(std::string_view s) { + return !s.empty() && s.find_first_not_of("0123456789abcdef") == std::string_view::npos; +} +} // namespace detail + +// -<16 hex digits>.bin, as entry_path names them. +inline bool entry_name(std::string_view name) { + constexpr std::string_view ext = ".bin"; + const auto dash = name.find('-'); + if (dash == std::string_view::npos || dash == 0 || name.size() != dash + 1 + 16 + ext.size() || + name.substr(name.size() - ext.size()) != ext) + return false; + return detail::hex(name.substr(dash + 1, 16)); +} + +// What write_pipeline_cache_file stages an entry in: .tmp... +inline bool staging_name(std::string_view name) { + constexpr std::string_view mark = ".tmp."; + const auto at = name.rfind(mark); + if (at == std::string_view::npos || !entry_name(name.substr(0, at))) return false; + const auto suffix = name.substr(at + mark.size()); + const auto dot = suffix.find('.'); + return dot != std::string_view::npos && detail::digits(suffix.substr(0, dot)) && + detail::digits(suffix.substr(dot + 1)); +} + +struct EntryInfo { + std::filesystem::path path; + std::uint64_t bytes = 0; + std::filesystem::file_time_type used{}; +}; + +// Which entries go, least recently used first, when they hold more than `budget`: as many as leave at most `target`. +inline std::vector plan_eviction(const std::vector& entries, std::uint64_t budget, + std::uint64_t target) { + std::uint64_t total = 0; + for (const EntryInfo& entry : entries) total += entry.bytes; + std::vector out; + if (total <= budget) return out; + std::vector order(entries.size()); + for (std::size_t i = 0; i < order.size(); ++i) order[i] = i; + std::sort(order.begin(), order.end(), [&](std::size_t a, std::size_t b) { + if (entries[a].used != entries[b].used) return entries[a].used < entries[b].used; + return entries[a].path < entries[b].path; + }); + for (const std::size_t i : order) { + if (total <= target) break; + out.push_back(i); + total -= entries[i].bytes; + } + return out; +} + +struct TidyResult { + std::uint64_t bytes = 0; // what the entries left take + std::size_t entries = 0; // how many are left + std::size_t evicted = 0; // entries removed for the budget + std::size_t swept = 0; // staging files removed +}; + +// Removes staging files older than `staging_age` (a writer still holding one keeps it: Windows refuses to delete an +// open file not shared for deletion), then, past `budget`, the least recently used entries until three quarters of +// it is left. Other files in `dir` are left alone and not counted. +inline TidyResult tidy(const std::filesystem::path& dir, std::uint64_t budget, + std::chrono::seconds staging_age = std::chrono::minutes(10), + std::filesystem::file_time_type now = std::filesystem::file_time_type::clock::now()) { + TidyResult result; + std::vector entries; + std::error_code ec; + for (std::filesystem::directory_iterator it(dir, ec), end; !ec && it != end; it.increment(ec)) { + std::error_code stat; + if (!it->is_regular_file(stat) || stat) continue; + const std::string name = it->path().filename().string(); + const auto used = it->last_write_time(stat); + if (stat) continue; + if (staging_name(name)) { + std::error_code removed; + if (now - used >= staging_age && std::filesystem::remove(it->path(), removed) && !removed) ++result.swept; + continue; + } + if (!entry_name(name)) continue; + const auto size = it->file_size(stat); + if (!stat) entries.push_back({it->path(), size, used}); + } + std::vector gone(entries.size()); + for (const std::size_t i : plan_eviction(entries, budget, budget / 4 * 3)) { + std::error_code removed; + if (std::filesystem::remove(entries[i].path, removed) && !removed) { + gone[i] = true; + ++result.evicted; + } + } + for (std::size_t i = 0; i < entries.size(); ++i) { + if (gone[i]) continue; + result.bytes += entries[i].bytes; + ++result.entries; + } + return result; +} + +// What the journal's files take on disk now: the sizes of the regular files in `dir` (0 when it does not exist). +inline std::uint64_t directory_bytes(const std::filesystem::path& dir) { + std::uint64_t total = 0; + std::error_code ec; + for (std::filesystem::directory_iterator it(dir, ec), end; !ec && it != end; it.increment(ec)) { + std::error_code stat; + if (it->is_regular_file(stat) && !stat) { + const auto size = it->file_size(stat); + if (!stat) total += size; + } + } + return total; +} + +// LEONIDA_PIPELINE_JOURNAL_BYTES: how much the journal may hold. A compute pipeline's file is 2-5 MiB on NVIDIA: the +// ~1700 a boot builds take ~4 GiB, the whole library's ~5400 (gta6rt --precompile-pipelines) about 15. A boot writes +// nothing past it; the next one's tidy makes room. +inline constexpr std::uint64_t default_budget = std::uint64_t{32} << 30; + +// Publishes `data` as the file at `path`, creating its directory. The previous file stays until the rename. +inline std::error_code write_entry(const std::filesystem::path& path, const void* data, std::size_t size) { + std::error_code ec; + std::filesystem::create_directories(path.parent_path(), ec); + if (ec) return ec; + return write_pipeline_cache_file(path, static_cast(data), size); +} + +} // namespace leonida::pipeline_journal diff --git a/runtime/src/pipeline_wait.h b/runtime/src/pipeline_wait.h new file mode 100644 index 0000000000..b8ee526ca7 --- /dev/null +++ b/runtime/src/pipeline_wait.h @@ -0,0 +1,189 @@ +#pragma once +// How long a submission waits for pipelines that are still being built (docs/d3d12_vulkan.md, "Pipelines still being +// built"). Before VulkanQueue::execute takes any lock of ours it asks for the pipelines its lists' draws and dispatches +// need (ComputePipeline::await, GraphicsPipeline::await) and waits for the ones being built, at most: +// LEONIDA_PIPELINE_WAIT_MS per submission, in all. 0: never waits; -1: waits for every build to finish (the +// behaviour before this existed, without a lock held). Unset: 24 ms with +// LEONIDA_ASYNC_PIPELINES=1, -1 without (nothing is skipped in the default mode). +// LEONIDA_PIPELINE_WAIT_FRAME_MS per frame (between two presents, or one second without a present), shared by every +// submitting thread (default 100). -1: no frame budget. +// A draw or dispatch whose pipeline is still not built when the wait ends is skipped by replay (recorded as nothing); +// the build goes on, and a later submission uses the pipeline. LEONIDA_STRICT_REPLAY=1 waits for every build. The +// budget bounds waits for builds other threads run: without asynchronous builds, a pipeline nobody has started is +// built by the submitting thread in place, however long that takes (with no lock of the replay layer held). +// Every 10 s while anything happened, one line counts the pipelines waited for, the time, the draws and dispatches +// skipped and the pipelines replay asked for that are still being built. +// No windows.h here: vulkan_replay.h includes this, and translation units without NOMINMAX include that. +#include +#include +#include +#include +#include +#include +#include +#include + +namespace leonida::pipeline_wait { + +// Times are steady-clock nanoseconds (submit_phases::now_ns). ComputePipeline::await / GraphicsPipeline::await read +// `until` as: `probe` - the handle if built, never starting anything; a time already past (`no_wait`) - start the build +// when nobody has, without waiting for one another thread runs; a later time - and wait for it until then; `forever`. +// Their `pending` answer says whether a null handle means "not built yet" (false: built, or it cannot be built). +inline constexpr std::int64_t probe = 0; +inline constexpr std::int64_t no_wait = 1; +inline constexpr std::int64_t forever = (std::numeric_limits::max)(); + +// The clock of submit_phases::now_ns. +inline std::int64_t now_ns() { + return std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()) + .count(); +} + +inline int env_ms(const char* name, int fallback) { + const char* text = std::getenv(name); + if (!text || !*text) return fallback; + char* end = nullptr; + const long value = std::strtol(text, &end, 10); + if (end == text) return fallback; + return value < 0 ? -1 : int((std::min)(value, 600000)); +} + +// Milliseconds; -1 for no limit. Atomics so a test can change them (set_budgets). +inline constexpr int unset = -2; +inline std::atomic& submission_ms() { + static std::atomic value{env_ms("LEONIDA_PIPELINE_WAIT_MS", unset)}; + return value; +} +// What an unset LEONIDA_PIPELINE_WAIT_MS means; the D3D12 device sets it (24 with asynchronous builds, else -1). +inline std::atomic& default_submission_ms() { + static std::atomic value{24}; + return value; +} +inline int effective_submission_ms() { + const int value = submission_ms().load(std::memory_order_relaxed); + return value == unset ? default_submission_ms().load(std::memory_order_relaxed) : value; +} +inline std::atomic& frame_ms() { + static std::atomic value{env_ms("LEONIDA_PIPELINE_WAIT_FRAME_MS", 100)}; + return value; +} +inline void set_budgets(int submission, int frame) { + submission_ms().store(submission); + frame_ms().store(frame); +} + +// Presents, counted by the swap chain: a frame's budget starts again at each one. +inline std::atomic& presents() { + static std::atomic value{0}; + return value; +} +inline void note_present() { presents().fetch_add(1, std::memory_order_relaxed); } + +// What a waiting thread took of its frame's budget (take), and gives back unused (give_back). +struct Grant { + std::int64_t ns = 0; + std::uint64_t frame = 0; + bool limited = false; // false: the frame budget is off and nothing was taken from it +}; + +struct FrameBudget { + std::mutex mutex; + std::uint64_t frame = ~0ull; // the present count the budget belongs to + std::int64_t started = 0; // when it began: one second without a present starts a new one + std::int64_t spent = 0; +}; +inline FrameBudget& frame_budget() { + static FrameBudget value; + return value; +} + +// Up to `want` ns of the current frame's budget, which the caller may wait; the rest of the frame's budget stays for +// the other submitting threads. +inline Grant take(std::int64_t want) { + const int budget = frame_ms().load(std::memory_order_relaxed); + if (budget < 0) return {want, 0, false}; + FrameBudget& f = frame_budget(); + std::lock_guard lock(f.mutex); + const std::uint64_t frame = presents().load(std::memory_order_relaxed); + const std::int64_t now = now_ns(); + if (frame != f.frame || now - f.started >= 1000000000) { + f.frame = frame; + f.started = now; + f.spent = 0; + } + const std::int64_t left = (std::max)(0, std::int64_t(budget) * 1000000 - f.spent); + const std::int64_t granted = (std::min)(want, left); + f.spent += granted; + return {granted, f.frame, true}; +} +inline void give_back(const Grant& grant, std::int64_t unused) { + if (!grant.limited || unused <= 0) return; + FrameBudget& f = frame_budget(); + std::lock_guard lock(f.mutex); + if (f.frame == grant.frame) f.spent = (std::max)(0, f.spent - (std::min)(unused, grant.ns)); +} + +// The last submission (VulkanQueue::execute). While the title submits, compute warm-ups of big modules are left to +// their first use (LEONIDA_COMPUTE_WARMUP_LIVE_MAX_BYTES, runtime/shims/d3d12_vulkan_device.cpp): a create holds the +// compile gate for its whole length, and every submission waits behind it. +inline std::atomic& last_submission() { + static std::atomic value{0}; + return value; +} +inline void note_submission() { last_submission().store(now_ns(), std::memory_order_relaxed); } +inline bool title_submitting(std::int64_t within_ns = 1000000000) { + const std::int64_t last = last_submission().load(std::memory_order_relaxed); + return last && now_ns() - last < within_ns; +} + +struct Stats { + std::atomic waited{0}; // pipelines a submission waited for + std::atomic wait_ns{0}; // the time it waited for them + std::atomic late{0}; // waits that ended before the pipeline was built + std::atomic skipped_draws{0}; + std::atomic skipped_dispatches{0}; + std::atomic building{0}; // pipelines replay asked for that are still being built + std::atomic warmups_left{0}; // big warm-ups left to their first use while the title submits + std::atomic last_report{0}; +}; +inline Stats& stats() { + static Stats value; + return value; +} + +inline void count_skip(bool dispatch) { + (dispatch ? stats().skipped_dispatches : stats().skipped_draws).fetch_add(1, std::memory_order_relaxed); +} + +// The 10 s line. One thread wins it; counted since the last line. `age` gives the process's age in seconds +// (submit_phases::process_age), read only when the line is printed. +template void maybe_report(Age&& age) { + constexpr std::int64_t period = 10000000000; + Stats& s = stats(); + const std::int64_t now = now_ns(); + std::int64_t last = s.last_report.load(std::memory_order_relaxed); + if (!last) { + s.last_report.compare_exchange_strong(last, now, std::memory_order_relaxed); + return; + } + if (now - last < period || !s.last_report.compare_exchange_strong(last, now, std::memory_order_relaxed)) return; + const std::uint64_t waited = s.waited.exchange(0, std::memory_order_relaxed); + const std::uint64_t wait_ns = s.wait_ns.exchange(0, std::memory_order_relaxed); + const std::uint64_t late = s.late.exchange(0, std::memory_order_relaxed); + const std::uint64_t draws = s.skipped_draws.exchange(0, std::memory_order_relaxed); + const std::uint64_t dispatches = s.skipped_dispatches.exchange(0, std::memory_order_relaxed); + const std::int64_t building = s.building.load(std::memory_order_relaxed); + const std::uint64_t left = s.warmups_left.exchange(0, std::memory_order_relaxed); + if (!waited && !draws && !dispatches && building <= 0 && !left) return; + std::fprintf(stderr, + "[rt] pipeline waits t=%.0fs: in %.1f s %llu pipelines waited for (%.0f ms in all, %llu not built in " + "time), %llu draws and %llu dispatches skipped, %lld pipelines still building; budget %d ms per " + "submission, %d ms per frame; %llu big warm-ups left to first use\n", + double(age()), double(now - last) * 1e-9, static_cast(waited), + double(wait_ns) * 1e-6, static_cast(late), static_cast(draws), + static_cast(dispatches), static_cast(building), + effective_submission_ms(), frame_ms().load(std::memory_order_relaxed), + static_cast(left)); +} + +} // namespace leonida::pipeline_wait diff --git a/runtime/src/queue_holds.h b/runtime/src/queue_holds.h index 2839d4210d..40cc331170 100644 --- a/runtime/src/queue_holds.h +++ b/runtime/src/queue_holds.h @@ -93,6 +93,13 @@ class QueueHolds { return it == fences_.end() || it->second < 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; + } + // 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_); diff --git a/runtime/src/shader_library.h b/runtime/src/shader_library.h index a359287cb1..7699dfbb0d 100644 --- a/runtime/src/shader_library.h +++ b/runtime/src/shader_library.h @@ -897,6 +897,47 @@ inline DescriptorHashKind majority_descriptor_hash_kind(const DescriptorHashCens return census.fnv1a_fmix32 > census.fnv1a ? DescriptorHashKind::fnv1a_fmix32 : DescriptorHashKind::fnv1a; } +// Which descriptor-table entry layout the loaded modules read (descriptor_table.h, tools/rdna2spirv.py +// --descriptor-table). A module whose meta carries `"descriptor_table": "tagged"` also reads the kind word next to +// each index and uses it to tell which array an index belongs to; an absent key is the old plain layout, which reads +// only the index. The runtime fills the kind word for a tagged table and leaves it alone for a plain one, so a +// library translated before the marker (or with --descriptor-table plain) behaves exactly as it did. +enum class DescriptorTableLayout : std::uint8_t { plain = 0, tagged = 1 }; + +inline constexpr const char* descriptor_table_layout_name(DescriptorTableLayout layout) { + return layout == DescriptorTableLayout::tagged ? "tagged" : "plain"; +} + +struct DescriptorTableCensus { + std::size_t plain = 0; + std::size_t tagged = 0; + std::size_t total() const { return plain + tagged; } +}; + +// The tagged layout when any module reads it. The kind word is additive: a tagged module reads it and a plain +// module ignores it (it reads the index at the same place), so one tagged module in the corpus needs the tagged +// layout, however many plain ones there are. Counting entries would let a merged or partial index whose plain +// modules outnumber the tagged ones hand every tagged module an all-zero kind, and every image of another +// dimension would then fall back. No tagged module is the old plain layout. +inline DescriptorTableLayout majority_descriptor_table_layout(const DescriptorTableCensus& census) { + return census.tagged > 0 ? DescriptorTableLayout::tagged : DescriptorTableLayout::plain; +} + +// 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) { + if (!value || !*value) return false; + if (std::strcmp(value, "tagged") == 0) { + if (layout) *layout = DescriptorTableLayout::tagged; + return true; + } + if (std::strcmp(value, "plain") == 0) { + if (layout) *layout = DescriptorTableLayout::plain; + return true; + } + return false; +} + // LEONIDA_DESCRIPTOR_HASH=fnv1a|fnv1a_fmix32 overrides the modules' majority. False when `value` is null, empty or not // one of the two kinds (an unrecognised value is ignored rather than failing startup). inline bool descriptor_hash_kind_from_env(const char* value, DescriptorHashKind* kind) { @@ -973,6 +1014,7 @@ class ShaderLibrary { bvh_count_ = 0; exe_count_ = 0; descriptor_hash_census_ = {}; + descriptor_table_census_ = {}; for (const char* folder : {"fspx", "fspx_gfx"}) { try { const auto ignore = [](const std::string&) { return false; }; @@ -994,6 +1036,13 @@ class ShaderLibrary { // LEONIDA_DESCRIPTOR_HASH names a kind. const DescriptorHashCensus& descriptor_hash_census() const { return descriptor_hash_census_; } DescriptorHashKind descriptor_hash_kind() const { return majority_descriptor_hash_kind(descriptor_hash_census_); } + // The entry layouts the loaded modules read, and the layout to use: tagged as soon as one module reads the kind + // word (it is additive, see majority_descriptor_table_layout), plain when none does. The device takes this once, + // before its descriptor table's first insert, unless LEONIDA_DESCRIPTOR_TABLE names a layout. + const DescriptorTableCensus& descriptor_table_census() const { return descriptor_table_census_; } + DescriptorTableLayout descriptor_table_layout() const { + return majority_descriptor_table_layout(descriptor_table_census_); + } // Entries loaded from /fspx/index.json and /library/index.json. A corpus of RPF containers never // reaches these: their programs come from FidelityFX DLLs and the pipeline library, so callers comparing reached // entries with size() must leave them out. @@ -1069,6 +1118,19 @@ class ShaderLibrary { return all; } + // The module's file: /.spv, or the index's spv file name when that one is missing. + std::filesystem::path spirv_file(const ShaderEntry& entry) const { + std::error_code ec; + auto path = dir_; + path += "/" + entry.name + ".spv"; + if (!std::filesystem::exists(path, ec) && !entry.spv_file.empty()) { + auto alt = dir_; + alt += "/" + entry.spv_file; + return alt; + } + return path; + } + // The size of the module's file in bytes, or 0 when it is missing: what spirv() would read, without reading it. std::size_t spirv_bytes(const ShaderEntry& entry) const { std::error_code ec; @@ -1083,6 +1145,20 @@ class ShaderLibrary { return ec ? 0 : static_cast(size); } + // Every entry of `stage` once, in name order, from every index (an entry reachable both by its FSSM and its FSPX + // hash is one entry). gta6rt --precompile-pipelines builds them all. + std::vector stage_entries(std::string_view stage) const { + std::map, const ShaderEntry*> unique; + for (const Entries* map : {&entries_, &fspx_entries_}) + for (const auto& [key, list] : *map) + for (const ShaderEntry& e : list) + if (e.stage == stage) unique.emplace(std::pair{e.name, e.spv_file}, &e); + std::vector out; + out.reserve(unique.size()); + for (const auto& [key, e] : unique) out.push_back(e); + return out; + } + // The module's words, or empty when /.spv is missing or not SPIR-V. std::vector spirv(const ShaderEntry& entry) const { auto path = dir_; @@ -1146,6 +1222,7 @@ class ShaderLibrary { bvh_count_ = 0; exe_count_ = 0; descriptor_hash_census_ = {}; + descriptor_table_census_ = {}; } for (const auto& [name, meta] : root.object) { const Json* hash = meta.find("fssm_sha256"); @@ -1241,6 +1318,13 @@ class ShaderLibrary { ++descriptor_hash_census_.fnv1a_fmix32; else ++descriptor_hash_census_.fnv1a; + // Which entry layout this module reads (descriptor_table.h). Absent, or not a layout this runtime knows, + // is the old plain one. + if (const Json* dt = meta.find("descriptor_table"); + dt && dt->kind == Json::Kind::string && dt->string == "tagged") + ++descriptor_table_census_.tagged; + else + ++descriptor_table_census_.plain; 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_; @@ -1264,6 +1348,7 @@ class ShaderLibrary { Entries entries_; Entries fspx_entries_; DescriptorHashCensus descriptor_hash_census_; + DescriptorTableCensus descriptor_table_census_; }; } // namespace leonida diff --git a/runtime/src/submit_phases.h b/runtime/src/submit_phases.h index 84ea77b028..54171f60e7 100644 --- a/runtime/src/submit_phases.h +++ b/runtime/src/submit_phases.h @@ -24,12 +24,14 @@ enum Phase : unsigned { shadows, // slot-133 shadow buffers and title windows (ShadowPages::refresh) geometry, // GeometryViews::refresh textures, // Device::refresh_title_textures + pipelines, // VulkanQueue::await_pipelines: asking for and waiting on pipelines still being built (pipeline_wait.h) replay, // the rest of execute_now: preparing, recording and submitting the lists kCount }; inline const char* name(unsigned p) { - static const char* const names[kCount] = {"wait", "heaps", "shadows", "geometry", "textures", "replay"}; + static const char* const names[kCount] = {"wait", "heaps", "shadows", "geometry", "textures", "pipes", + "replay"}; return p < kCount ? names[p] : "?"; } @@ -120,14 +122,15 @@ inline void submitted() { all += total; } std::fprintf(stderr, - "[rt] submit phases t=%.0fs: %llu submissions in %.1f s (%.2f/s, %llu in all), %.2f frames/s; ms per submission " - "(max): %s %.2f (%.0f) %s %.2f (%.0f) %s %.2f (%.0f) %s %.2f (%.0f) %s %.2f (%.0f) %s %.2f (%.0f); " + "[rt] submit phases t=%.0fs: %llu submissions in %.1f s (%.2f/s, %llu in all), %.2f frames/s; ms per " + "submission (max): %s %.2f (%.0f) %s %.2f (%.0f) %s %.2f (%.0f) %s %.2f (%.0f) %s %.2f (%.0f) %s %.2f " + "(%.0f) %s %.2f (%.0f); " "%.0f%% of the wall time\n", process_age(), static_cast(n), seconds, double(n) / seconds, static_cast(t.all_submissions.load(std::memory_order_relaxed)), double(frames) / seconds, name(0), ms[0], max_ms[0], name(1), ms[1], max_ms[1], name(2), ms[2], max_ms[2], name(3), ms[3], max_ms[3], name(4), - ms[4], max_ms[4], name(5), ms[5], max_ms[5], 100.0 * all * 1e-3 / seconds); + ms[4], max_ms[4], name(5), ms[5], max_ms[5], name(6), ms[6], max_ms[6], 100.0 * all * 1e-3 / seconds); } } // namespace leonida::submit_phases diff --git a/runtime/src/thread_sampler.h b/runtime/src/thread_sampler.h index 282eb20dd1..0c18949cea 100644 --- a/runtime/src/thread_sampler.h +++ b/runtime/src/thread_sampler.h @@ -44,6 +44,9 @@ struct Sampler { // LEONIDA_SAMPLE_DETAIL=[,...]: for these threads, the 10 most frequent chains, 16 frames deep, each as a // share of that thread's samples (thread ids are stable from boot to boot: the title's main, render and submit). std::vector detail; + // LEONIDA_SAMPLE_FIND=[,...] (title function starts): which threads have the function on their stack + // (48 frames deep), how often, and their most frequent chain under it, every report. + std::vector find; }; // Per title thread (one with a title frame in its chain): how many samples were inside our runtime, and through which @@ -151,6 +154,7 @@ inline DWORD WINAPI run(LPVOID parameter) { constexpr int kDetailFrames = 16; using DetailChain = std::array; std::map, std::uint64_t> detail_chains; + std::map, std::map> found; // (rva, thread) -> chains std::uint64_t total = 0; ULONGLONG listed = 0, reported = GetTickCount64(); const auto cpu_of = [](HANDLE h) { @@ -205,11 +209,20 @@ inline DWORD WINAPI run(LPVOID parameter) { unwind(context, deep); ++detail_chains[{it->first, deep}]; } - if (s.shims) { + if (s.shims || !s.find.empty()) { DeepChain deep{}; const int n = unwind(context, deep); std::copy_n(deep.begin(), kFrames, chain.begin()); - count_shims(s, deep, n, moved, shim_counts[it->first]); + if (s.shims) count_shims(s, deep, n, moved, shim_counts[it->first]); + const auto title = reinterpret_cast(s.title); + for (const std::uint64_t rva : s.find) + for (int f = 0; f < n; ++f) + if (deep[f] == title + rva) { + DetailChain inner{}; + std::copy_n(deep.begin(), (std::min)(kDetailFrames, n), inner.begin()); + ++found[{rva, it->first}][inner]; + break; + } } else { unwind(context, chain); } @@ -299,6 +312,23 @@ inline DWORD WINAPI run(LPVOID parameter) { } } detail_chains.clear(); + for (const auto& [key, chains_of] : found) { + std::uint64_t all = 0; + const DetailChain* top = nullptr; + std::uint64_t top_n = 0; + for (const auto& [c, n] : chains_of) { + all += n; + if (n > top_n) top_n = n, top = &c; + } + std::string frames; + for (int f = 0; top && f < kDetailFrames && (*top)[f]; ++f) frames += (f ? " < " : "") + name_of(s, (*top)[f]); + const auto t = threads.find(key.second); + std::fprintf(stderr, "[rt] sampler: find t+%llx: thread %lu %llu samples of %llu; top chain (%llu): %s\n", + static_cast(key.first), key.second, static_cast(all), + static_cast(t == threads.end() ? 0 : t->second.samples), + static_cast(top_n), frames.c_str()); + } + found.clear(); if (s.shims) { // Title threads by their samples inside our runtime: where the title's own threads (its main, render and // Subrender workers, streaming) spend time in our shims, waiting or running. @@ -386,6 +416,15 @@ inline void start(std::uint8_t* title, std::uint64_t title_size) { if (id) s.detail.push_back(DWORD(id)); at = *end == ',' ? end + 1 : end; } + char finds[256] = {}; + if (const DWORD n = GetEnvironmentVariableA("LEONIDA_SAMPLE_FIND", finds, sizeof(finds)); n && n < sizeof(finds)) + for (char* at = finds; *at;) { + char* end = nullptr; + const std::uint64_t rva = std::strtoull(at, &end, 16); + if (end == at) break; + if (rva) s.find.push_back(rva); + at = *end == ',' ? end + 1 : end; + } char shims[4] = {}; s.shims = GetEnvironmentVariableA("LEONIDA_SAMPLE_SHIMS", shims, sizeof(shims)) == 1 && shims[0] == '1'; if (const auto self = reinterpret_cast(GetModuleHandleW(nullptr))) { diff --git a/runtime/src/thread_stacks.cpp b/runtime/src/thread_stacks.cpp index 67188d9086..38d7cc2a44 100644 --- a/runtime/src/thread_stacks.cpp +++ b/runtime/src/thread_stacks.cpp @@ -121,10 +121,10 @@ struct ThreadTrace { size_t count = 0; }; -void print_traces(unsigned at, const std::vector& traces) { - std::string out = "[rt] stacks t=" + std::to_string(at) + ": " + std::to_string(traces.size()) + " threads\n"; +void print_traces(const std::string& tag, const std::vector& traces) { + std::string out = "[rt] stacks " + tag + ": " + std::to_string(traces.size()) + " threads\n"; for (auto it = traces.begin(); it != traces.end(); ++it) { - out += "[rt] stacks t=" + std::to_string(at) + " thread " + std::to_string(it->tid) + " (" + it->label + "):\n"; + out += "[rt] stacks " + tag + " thread " + std::to_string(it->tid) + " (" + it->label + "):\n"; const auto same = std::find_if(traces.begin(), it, [&](const ThreadTrace& earlier) { return it->count && it->count == earlier.count && std::equal(it->frames.begin(), it->frames.begin() + it->count, earlier.frames.begin()); @@ -142,10 +142,11 @@ void print_traces(unsigned at, const std::vector& traces) { std::fflush(stderr); } -void snapshot_threads(unsigned at, StackSampler& sampler, GetDescription describe, QueryThread query) { +void snapshot_threads(const std::string& tag, StackSampler& sampler, GetDescription describe, QueryThread query, + DWORD only = 0) { const HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); if (snapshot == INVALID_HANDLE_VALUE) { - std::fprintf(stderr, "[rt] stacks t=%u: thread list failed (error %lu)\n", at, GetLastError()); + std::fprintf(stderr, "[rt] stacks %s: thread list failed (error %lu)\n", tag.c_str(), GetLastError()); return; } std::vector traces; @@ -157,6 +158,7 @@ void snapshot_threads(unsigned at, StackSampler& sampler, GetDescription describ for (BOOL ok = Thread32First(snapshot, &entry); ok; ok = Thread32Next(snapshot, &entry)) { entry.dwSize = sizeof(entry); if (entry.th32OwnerProcessID != pid || entry.th32ThreadID == self) continue; + if (only && entry.th32ThreadID != only) continue; const HANDLE thread = OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, FALSE, entry.th32ThreadID); if (!thread) continue; @@ -169,7 +171,7 @@ void snapshot_threads(unsigned at, StackSampler& sampler, GetDescription describ CloseHandle(thread); } CloseHandle(snapshot); - print_traces(at, traces); + print_traces(tag, traces); } } // namespace @@ -207,6 +209,20 @@ bool parse_stack_times(std::string_view text, std::vector& seconds) { return true; } +void print_thread_stacks_now(std::uint32_t tid, const char* why) noexcept { + static std::mutex mutex; + try { + std::lock_guard lock(mutex); + static StackSampler sampler; + const auto describe = reinterpret_cast(reinterpret_cast( + GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "GetThreadDescription"))); + const auto query = reinterpret_cast(reinterpret_cast( + GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "NtQueryInformationThread"))); + snapshot_threads(why ? why : "now", sampler, describe, query, tid); + } catch (...) { + } +} + std::jthread start_thread_stacks() { const auto start = Clock::now(); char spec[1024]; @@ -229,7 +245,7 @@ std::jthread start_thread_stacks() { for (const unsigned at : times) { wake.wait_until(lock, stop, start + std::chrono::seconds(at), [] { return false; }); if (stop.stop_requested()) break; - snapshot_threads(at, sampler, describe, query); + snapshot_threads("t=" + std::to_string(at), sampler, describe, query); } }); } diff --git a/runtime/src/thread_stacks.h b/runtime/src/thread_stacks.h index 523c7b2663..1edc1b3501 100644 --- a/runtime/src/thread_stacks.h +++ b/runtime/src/thread_stacks.h @@ -35,4 +35,8 @@ bool parse_stack_times(std::string_view text, std::vector& seconds); // sampler before unmapping the title image. std::jthread start_thread_stacks(); +// The call chain of thread `tid` now, or of every other thread when `tid` is 0, printed as LEONIDA_STACKS does under +// the tag `why`. One call at a time; the device-loss diagnostics call it (vulkan_device_fault.h thread_stack_hook). +void print_thread_stacks_now(std::uint32_t tid, const char* why) noexcept; + } // namespace rt diff --git a/runtime/src/title_page_watch.h b/runtime/src/title_page_watch.h index ccc085466c..9d0a2ccfc1 100644 --- a/runtime/src/title_page_watch.h +++ b/runtime/src/title_page_watch.h @@ -204,6 +204,18 @@ inline void set(std::uintptr_t va, bool aliased) { // Bumped by every change of set(). inline std::uint64_t generation() { return state().generation.load(std::memory_order_acquire); } +// Up to `n` aliased pages, and how many there are (a probe's sample; no order). +inline std::size_t sample(std::vector& out, std::size_t n) { + State& s = state(); + out.clear(); + std::shared_lock lock(s.mutex); + for (const std::uintptr_t va : s.aliased) { + if (out.size() >= n) break; + out.push_back(va); + } + return s.aliased.size(); +} + // Calls `f(va)` for each aliased 64 KiB page overlapping [begin, end). template void for_each_in(std::uintptr_t begin, std::uintptr_t end, F&& f) { @@ -258,6 +270,19 @@ inline bool note_reservation(std::uintptr_t base, std::uintptr_t size, bool gpu_ return true; } +// Both addresses of every pair, as [start, end) ranges (LEONIDA_CONSOLE_HEAP_GPU's ask table); `count()` changes +// with them. +inline void spans(std::vector>& out) { + State& s = state(); + out.clear(); + if (!s.count.load(std::memory_order_acquire)) return; + std::shared_lock lock(s.mutex); + for (const View& v : s.views) { + out.emplace_back(v.gpu, v.gpu + v.size); + out.emplace_back(v.cpu, v.cpu + v.size); + } +} +inline std::size_t count() { return state().count.load(std::memory_order_acquire); } // Marks the pair whose GPU-only range starts at `gpu` as one whose GPU-only range has pages of its own (queue slot 31 // or XMemMapPhysicalPages map them at that address, not through the CPU view): the host reads it there (to_cpu) and // a slot-133 buffer over it is a shadow, not an import (independently_mapped). False when no pair starts at `gpu`. diff --git a/runtime/src/title_texture_refresh.h b/runtime/src/title_texture_refresh.h index ed7c0f2b67..a652e6281d 100644 --- a/runtime/src/title_texture_refresh.h +++ b/runtime/src/title_texture_refresh.h @@ -1,5 +1,7 @@ #pragma once #include +#include +#include #include #include #include @@ -8,6 +10,48 @@ namespace leonida { using TitleWriteRanges = std::vector>; +// 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 { + using Address = std::uint64_t; + struct Range { Address first, last; }; + using PageKey = std::pair; // page, registry key + std::map> pages_; + std::map> location_; + static Address page(Address at, unsigned shift) { return shift == 64 ? 0 : at >> shift; } + +public: + void erase(Address key) { + const auto where = location_.find(key); + if (where == location_.end()) return; + const auto [shift, number] = where->second; + auto level = pages_.find(shift); + level->second.erase({number, key}); + if (level->second.empty()) pages_.erase(level); + location_.erase(where); + } + 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 unsigned shift = unsigned(std::bit_width(first ^ last)); + const Address number = page(first, shift); + pages_[shift][{number, key}] = {first, last}; + location_[key] = {shift, number}; + } + template + void overlapping(Address from, Address to, Visit visit) const { + if (from >= to) return; + for (const auto& [shift, entries] : pages_) { + const Address last = page(to - 1, shift); + for (auto it = entries.lower_bound({page(from, shift), 0}); + it != entries.end() && it->first.first <= last; ++it) { + if (it->second.first < to && from <= it->second.last) visit(it->first.second); + } + } + } +}; + // Sorted, disjoint half-open intervals let each texture find its first possible writer by end address. inline void merge_title_writes(TitleWriteRanges& writes) { std::sort(writes.begin(), writes.end()); @@ -34,10 +78,13 @@ inline bool title_write_overlaps(const TitleWriteRanges& writes, std::uintptr_t // the walk would step through a freed node. The list holds a reference to each entry, so an entry erased during the // pass is still alive when its turn comes. template -std::vector> title_texture_snapshot(const Registry& textures) { +std::vector> title_texture_snapshot( + const Registry& textures, std::uint64_t start = 0, std::size_t limit = SIZE_MAX) { std::vector> entries; - entries.reserve(textures.size()); - for (const auto& [address, texture] : textures) entries.emplace_back(address, texture); + 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); return entries; } diff --git a/runtime/src/title_va_alias.h b/runtime/src/title_va_alias.h index b3de5ce706..8d97764d55 100644 --- a/runtime/src/title_va_alias.h +++ b/runtime/src/title_va_alias.h @@ -16,7 +16,10 @@ // that makes a GPU copy for an address in the title's memory that has none yet, and a scanner that rewrites the // buffer V#s of a bound descriptor table before a submission. Without hooks the table only translates what was // added to it, so it is tested without a GPU (title_va_alias_test). +#include "descriptor_range_changes.h" #include +#include "buffer_va_index.h" + #include #include #include @@ -49,8 +52,11 @@ class TitleVaAliases { if (!bytes || title_va > UINT64_MAX - bytes) return false; std::unique_lock lock(mutex_); erase_overlapping(title_va, title_va + bytes); + changes_.record(title_va, bytes); ranges_[title_va] = {title_va + bytes, shader_va}; + by_shader_.insert(shader_va, bytes, title_va); count_.store(ranges_.size(), std::memory_order_release); + generation_.fetch_add(1, std::memory_order_release); return true; } @@ -68,8 +74,12 @@ class TitleVaAliases { std::unique_lock lock(mutex_); const auto it = ranges_.find(title_va); if (it != ranges_.end() && it->second.shader_va == shader_va) { + changes_.record(it->first, it->second.end - it->first); + by_shader_.erase(shader_va, title_va); + note_removed(it->second.shader_va, it->second.end - it->first); ranges_.erase(it); invalidations_.fetch_add(1, std::memory_order_release); + generation_.fetch_add(1, std::memory_order_release); } count_.store(ranges_.size(), std::memory_order_release); } @@ -113,6 +123,16 @@ class TitleVaAliases { for (const auto& [start, range] : ranges_) out.push_back({start, range.end, range.shader_va}); } + // Whether `shader_va` lies in the copy of a range added so far: an address the layer itself wrote for the title + // (a window, a geometry copy, a slot-133 shadow or import), which a later scan of the same descriptor sees again. + // A binary search over the copies' addresses (source_of_vsharp walks every range). + bool shader_side(std::uint64_t shader_va) const { + if (!count_.load(std::memory_order_acquire)) return false; + std::shared_lock lock(mutex_); + BufferVaIndex::Hit hit{}; + return by_shader_.find(shader_va, hit); + } + // Debug-only inverse lookup. V#s retain 48 bits, so an import below heap_base wraps. bool source_of_vsharp(std::uint64_t base, std::uint64_t& title, std::uint64_t& available) const { constexpr std::uint64_t mask = (1ull << 48) - 1; @@ -208,11 +228,15 @@ class TitleVaAliases { it = memory_.erase(it); } memory_[begin] = end; + memory_generation_.fetch_add(1, std::memory_order_release); } void remove_title_memory(std::uint64_t base) { std::unique_lock lock(memory_mutex_); memory_.erase(base); + memory_generation_.fetch_add(1, std::memory_order_release); } + // Bumped whenever title_memory_ranges() changes. + std::uint64_t memory_generation() const { return memory_generation_.load(std::memory_order_acquire); } // LOCAL DIAGNOSTIC (mem probe): every title range, [begin, end), in address order. std::vector> title_memory_ranges() const { std::shared_lock lock(memory_mutex_); @@ -314,6 +338,34 @@ class TitleVaAliases { std::size_t size() const { return count_.load(std::memory_order_acquire); } std::uint64_t invalidations() const { return invalidations_.load(std::memory_order_acquire); } + bool changed_ranges(uint64_t& cursor, DescriptorRanges& ranges) const { + std::shared_lock lock(mutex_); + return changes_.read(cursor, ranges); + } + // Bumped by every add and every removal: a copy of mappings() is current while it has not moved. + std::uint64_t generation() const { return generation_.load(std::memory_order_acquire); } + // Diagnostics (fsdraw): the title VA a shader VA was made from, the reverse of translate; a linear scan. + bool title_of_shader(std::uint64_t shader_va, std::uint64_t& title_va, std::uint64_t& range_va, + std::uint64_t& range_bytes) const { + std::shared_lock lock(mutex_); + for (const auto& [va, r] : ranges_) + if (shader_va >= r.shader_va && shader_va - r.shader_va < r.end - va) { + title_va = va + (shader_va - r.shader_va); + range_va = va; + range_bytes = r.end - va; + return true; + } + return false; + } + // LEONIDA_CONSOLE_HEAP_GPU: the shader-VA ranges of the ranges removed (or replaced) since the last take, so a + // GPU table translated through them can drop what it derived. Nothing is kept until recording is turned on. + void record_removals(bool on) { record_removals_.store(on, std::memory_order_relaxed); } + void take_removed(std::vector>& out) { + out.clear(); + if (!record_removals_.load(std::memory_order_relaxed)) return; + std::unique_lock lock(mutex_); + out.swap(removed_); + } void note_translation(Kind kind) { translated_[kind].fetch_add(1, std::memory_order_relaxed); } std::uint64_t translated(Kind kind) const { return translated_[kind].load(std::memory_order_relaxed); } std::uint64_t untranslated(Kind kind) const { return untranslated_[kind].load(std::memory_order_relaxed); } @@ -331,13 +383,28 @@ class TitleVaAliases { if (previous->second.end > begin) it = previous; } if (it != ranges_.end() && it->first < end) invalidations_.fetch_add(1, std::memory_order_release); - while (it != ranges_.end() && it->first < end) it = ranges_.erase(it); + while (it != ranges_.end() && it->first < end) { + changes_.record(it->first, it->second.end - it->first); + by_shader_.erase(it->second.shader_va, it->first); + note_removed(it->second.shader_va, it->second.end - it->first); + it = ranges_.erase(it); + } + } + + // mutex_ held exclusively. + void note_removed(std::uint64_t shader_va, std::uint64_t bytes) { + if (record_removals_.load(std::memory_order_relaxed)) removed_.push_back({shader_va, bytes}); } + DescriptorRangeChanges changes_; mutable std::shared_mutex mutex_; std::map ranges_; // by title VA + BufferVaIndex by_shader_; // the same ranges by shader VA (id: the title VA); copies may overlap std::atomic count_{0}; std::atomic invalidations_{}; + std::atomic generation_{}; + std::atomic record_removals_{false}; + std::vector> removed_; // (shader VA, bytes), when recorded std::mutex hook_mutex_; void* hook_context_ = nullptr; void* maker_context_ = nullptr; @@ -352,6 +419,7 @@ class TitleVaAliases { std::atomic scans_{0}, scan_ns_{0}, scan_max_ns_{0}; mutable std::shared_mutex memory_mutex_; std::map memory_; // the title's memory: base -> end + std::atomic memory_generation_{}; }; // The process's table: the device's title ranges and hooks, read by the command lists and descriptor writers. @@ -360,10 +428,23 @@ inline TitleVaAliases& title_va_aliases() { return aliases; } -// One diagnostic per descriptor-writing path. +// One diagnostic per descriptor-writing path. Called per descriptor write on the unbacked path, so the sites already +// told (string literals: their addresses) are looked up without the lock first. inline void note_unbacked_view(const char* site, std::uint64_t va, std::uint64_t bytes) { + static std::atomic told[8] = {}; + for (const auto& t : told) + if (t.load(std::memory_order_relaxed) == site) return; static std::mutex mutex; static std::map sites; + { + std::lock_guard lock(mutex); + for (auto& t : told) { + const char* none = nullptr; + if (t.load(std::memory_order_relaxed) == site || + t.compare_exchange_strong(none, site, std::memory_order_relaxed)) + break; + } + } { std::lock_guard lock(mutex); if (!sites.emplace(site, true).second) return; diff --git a/runtime/src/vulkan13_features.h b/runtime/src/vulkan13_features.h index 8f2dd61f83..0cb843cef3 100644 --- a/runtime/src/vulkan13_features.h +++ b/runtime/src/vulkan13_features.h @@ -40,6 +40,9 @@ class Vulkan13Features { bool subgroup_size_control = false; bool compute_full_subgroups = false; bool extended_dynamic_state = false; // core on 1.3; on 1.2 both VK_EXT_extended_dynamic_state(2) extensions + // 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; bool usable() const { return dynamic_rendering && synchronization2; } @@ -49,7 +52,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 = false; + extended_dynamic_state = pipeline_creation_cache_control = false; if (!features2) return; if (core) { VkPhysicalDeviceVulkan13Features f13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES}; @@ -60,6 +63,7 @@ class Vulkan13Features { synchronization2 = f13.synchronization2 == VK_TRUE; subgroup_size_control = f13.subgroupSizeControl == VK_TRUE; compute_full_subgroups = f13.computeFullSubgroups == VK_TRUE; + pipeline_creation_cache_control = f13.pipelineCreationCacheControl == VK_TRUE; extended_dynamic_state = true; // core in 1.3, no feature bit return; } @@ -108,6 +112,7 @@ class Vulkan13Features { subgroup_size_control = from.subgroup_size_control; compute_full_subgroups = from.compute_full_subgroups; extended_dynamic_state = from.extended_dynamic_state; + pipeline_creation_cache_control = from.pipeline_creation_cache_control; } // The structs that enable both features, ahead of `chain`; returns their head for VkPhysicalDeviceVulkan12Features' @@ -120,6 +125,7 @@ class Vulkan13Features { enable13_.synchronization2 = VK_TRUE; 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; return &enable13_; } if (subgroup_size_control) { diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index ac84df7a4d..2cd24d3c06 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -124,11 +124,11 @@ struct VulkanDeviceFunctions { X(vkCmdPushConstants) X(vkCmdDispatch) \ X(vkCmdBindVertexBuffers2) X(vkCmdBindIndexBuffer) X(vkCmdSetViewport) X(vkCmdSetScissor) \ X(vkCmdSetViewportWithCount) X(vkCmdSetScissorWithCount) \ - X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) \ + X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) X(vkCmdSetDepthBounds) \ X(vkCmdSetBlendConstants) X(vkCmdDraw) \ X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) X(vkGetImageSparseMemoryRequirements) \ X(vkCreatePipelineCache) X(vkDestroyPipelineCache) X(vkGetPipelineCacheData) X(vkMergePipelineCaches) \ - X(vkCreateEvent) X(vkDestroyEvent) X(vkResetEvent) X(vkCmdSetEvent) X(vkCmdWaitEvents) X(vkCmdDrawMeshTasksEXT) \ + X(vkCreateEvent) X(vkDestroyEvent) X(vkResetEvent) X(vkCmdSetEvent) X(vkCmdWaitEvents) X(vkCmdDrawMeshTasksEXT) X(vkCmdDrawMeshTasksIndirectEXT) X(vkCmdDrawMeshTasksIndirectCountEXT) \ X(vkCreateRenderPass2) X(vkDestroyRenderPass) X(vkCreateFramebuffer) X(vkDestroyFramebuffer) \ X(vkCmdBeginRenderPass) X(vkCmdEndRenderPass) #define LEONIDA_VK_MEMBER(name) PFN_##name name = nullptr; @@ -618,6 +618,8 @@ inline Stats& stats(int kind) { static Stats s[3]; return s[kind < 0 || kind > 2 ? 0 : kind]; } +inline void held_tick(int kind); // below: the held-operations line, due on the same 10 s + inline void done(int kind, std::chrono::steady_clock::time_point submitted) { using clock = std::chrono::steady_clock; const auto now = clock::now(); @@ -641,36 +643,66 @@ inline void done(int kind, std::chrono::steady_clock::time_point submitted) { s.sum_ms = s.max_ms = s.busy_ms = 0; s.since = now; } + held_tick(kind); } // A held queue operation (Wait before Signal), released: how long it waited on the CPU before it could run. -inline void held(int kind, int op, std::chrono::steady_clock::time_point at) { +// A held queue operation (Wait before Signal), released: how long it waited on the CPU before it could run, and for +// the longest one of the window the fence (semaphore handle) and value it waited for, so the slow signaller can be +// named. The line is due every 10 s: held() prints it, and so does done() (held_tick), so a window with nothing +// released still reports. +struct HeldStats { + std::mutex mutex; + std::uint64_t count[3] = {}; + double sum_ms = 0, max_ms = 0; + std::uint64_t max_fence = 0, max_value = 0; + int max_op = 0; + std::chrono::steady_clock::time_point since = std::chrono::steady_clock::now(); +}; +inline HeldStats& held_stats(int kind) { + static HeldStats h[3]; + return h[kind < 0 || kind > 2 ? 0 : kind]; +} +// held_stats(kind).mutex held. +inline void held_report_locked(int kind, HeldStats& s, std::chrono::steady_clock::time_point now) { + if (now - s.since < std::chrono::seconds(10)) return; + const std::uint64_t all = s.count[0] + s.count[1] + s.count[2]; + std::fprintf(stderr, "[rt] gpu latency (%s): %llu held operations released in %.0f s (%llu batches, %llu " + "signals, %llu markers), held %.2f ms on average, %.1f ms the longest", + kind == 0 ? "direct" : kind == 1 ? "compute" : "copy", static_cast(all), + std::chrono::duration(now - s.since).count(), static_cast(s.count[0]), + static_cast(s.count[1]), static_cast(s.count[2]), + all ? s.sum_ms / double(all) : 0.0, s.max_ms); + if (all && s.max_fence) + std::fprintf(stderr, " (a %s waiting for fence 0x%llx value %llu)", + s.max_op == 0 ? "batch" : s.max_op == 1 ? "Signal" : "marker", + static_cast(s.max_fence), static_cast(s.max_value)); + std::fputc('\n', stderr); + s.count[0] = s.count[1] = s.count[2] = 0; + s.sum_ms = s.max_ms = 0; + s.max_fence = s.max_value = 0; + s.since = now; +} +inline void held(int kind, int op, std::chrono::steady_clock::time_point at, std::uint64_t fence = 0, + std::uint64_t value = 0) { using clock = std::chrono::steady_clock; - struct Held { - std::mutex mutex; - std::uint64_t count[3] = {}; - double sum_ms = 0, max_ms = 0; - clock::time_point since = clock::now(); - }; - static Held h[3]; - Held& s = h[kind < 0 || kind > 2 ? 0 : kind]; + HeldStats& s = held_stats(kind); const auto now = clock::now(); const double ms = std::chrono::duration(now - at).count(); std::lock_guard lock(s.mutex); ++s.count[op < 0 || op > 2 ? 0 : op]; s.sum_ms += ms; - s.max_ms = (std::max)(s.max_ms, ms); - if (now - s.since >= std::chrono::seconds(10)) { - const std::uint64_t all = s.count[0] + s.count[1] + s.count[2]; - std::fprintf(stderr, "[rt] gpu latency (%s): %llu held operations released in %.0f s (%llu batches, %llu " - "signals, %llu markers), held %.2f ms on average, %.1f ms the longest\n", - kind == 0 ? "direct" : kind == 1 ? "compute" : "copy", static_cast(all), - std::chrono::duration(now - s.since).count(), static_cast(s.count[0]), - static_cast(s.count[1]), static_cast(s.count[2]), - all ? s.sum_ms / double(all) : 0.0, s.max_ms); - s.count[0] = s.count[1] = s.count[2] = 0; - s.sum_ms = s.max_ms = 0; - s.since = now; + if (ms > s.max_ms) { + s.max_ms = ms; + s.max_fence = fence; + s.max_value = value; + s.max_op = op; } + held_report_locked(kind, s, now); +} +inline void held_tick(int kind) { + HeldStats& s = held_stats(kind); + std::lock_guard lock(s.mutex); + held_report_locked(kind, s, std::chrono::steady_clock::now()); } } // namespace gpu_latency @@ -1148,8 +1180,11 @@ class VulkanContext { replay_.set_primitive_restart_enable = vk.vkCmdSetPrimitiveRestartEnable; replay_.set_stencil_reference = vk.vkCmdSetStencilReference; replay_.set_blend_constants = vk.vkCmdSetBlendConstants; + replay_.set_depth_bounds = vk.vkCmdSetDepthBounds; replay_.draw = vk.vkCmdDraw; replay_.draw_mesh_tasks = vk.vkCmdDrawMeshTasksEXT; // null unless VK_EXT_mesh_shader is enabled + replay_.draw_mesh_tasks_indirect = vk.vkCmdDrawMeshTasksIndirectEXT; + replay_.draw_mesh_tasks_indirect_count = vk.vkCmdDrawMeshTasksIndirectCountEXT; replay_.draw_indexed = vk.vkCmdDrawIndexed; replay_.graphics_pipeline = [this](std::uintptr_t id) -> const GraphicsPipeline* { const auto it = graphics_pipelines_.find(id); @@ -1280,6 +1315,7 @@ class VulkanContext { void configure_device_fault(PFN_vkGetDeviceProcAddr get, DeviceFaultExtensions enabled) { device_fault_ = std::make_unique(get, device_, enabled); + device_fault_->set_submit_lock(&submit_mutex_); if (fence_dispatcher_) fence_dispatcher_->set_device_fault(device_fault_.get()); if (loaded_) progress_watch_ = std::jthread([this](std::stop_token stop) { watch_queue_progress(stop); }); } @@ -1329,12 +1365,16 @@ class VulkanContext { const VkPhysicalDeviceLimits& limits, ScratchBuffers::Allocate allocate, std::vector families = {}) { std::unique_lock lock(resource_mutex_); + // An enabled clamp is required: a call whose scratch preparation fails is refused (unsupported) instead of + // 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; 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; return; } // The preparation callback needs this submission's counter-slot batch, so it is set per ExecuteCommandLists @@ -1585,6 +1625,44 @@ class VulkanContext { 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)); + } + 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. @@ -1595,7 +1673,13 @@ class VulkanContext { if (tracker_.layout(id, subresource) != VK_IMAGE_LAYOUT_GENERAL) return VK_NOT_READY; if (image_work_pending_) { ++host_texture_stats_.waits; - const auto result = observe_result(vk.vkDeviceWaitIdle(device_), "vkDeviceWaitIdle (title texture upload)"); + // 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_); + 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; } @@ -1613,7 +1697,8 @@ class VulkanContext { LayoutPieces pieces; if (!tracker_.pieces(id, range, pieces) || pieces.empty()) return VK_ERROR_UNKNOWN; if (image_work_pending_) { - const auto r = observe_result(vk.vkDeviceWaitIdle(device_), "vkDeviceWaitIdle (title staging)"); + const SubmitMutex::SubmitTurn turn(submit_mutex_); // 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; } @@ -1738,7 +1823,6 @@ class VulkanContext { // `before` is called at the start of every submission of command lists (a held batch: when it is released), // before any lock here is taken: the device re-copies its slot-133 shadow buffers from the title's pages there. // Set once, before the first queue exists. - void set_before_execute(std::function before) { before_execute_ = std::move(before); } // Table VAs are offsets in this device's arena. Install its scanner before creating any queues. // (The per-device scan is from the patch descriptor-table-refresh, part 2, of @@ -1780,6 +1864,17 @@ class VulkanContext { const auto it = device_fault_->pipeline_names.find(id); return it == device_fault_->pipeline_names.end() ? nullptr : it->second[0]; } + void set_before_execute(std::function before) { before_execute_ = std::move(before); } + // 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 + // after it). Every other queue's next submission then waits for that one, as for a bindless table upload: a + // queue that records nothing itself may run lists that read what the pass wrote. Called with tracker_mutex_ + // held, so passes and those waits follow submission order. Set once, before the first queue exists. + void set_prelude(std::function record, std::function commit) { + prelude_record_ = std::move(record); + prelude_commit_ = std::move(commit); + } void set_bindless_prepare(std::function prepare) { std::unique_lock lock(resource_mutex_); @@ -1934,7 +2029,14 @@ class VulkanContext { VulkanDeviceFunctions vk; // Vulkan requires external synchronisation of a VkQueue; every D3D12 queue of the device may share one. - std::mutex& submit_mutex() { return submit_mutex_; } + SubmitMutex& submit_mutex() { return submit_mutex_; } + + // vkQueueSubmit through the compile gate (SubmitMutex::SubmitTurn): it waits here, not in the driver, while a + // pipeline create is in the driver. Called with the submit lock held; the caller observes the result. + VkResult queue_submit(VkQueue queue, std::uint32_t count, const VkSubmitInfo* submits, VkFence fence) { + const SubmitMutex::SubmitTurn turn(submit_mutex_); + return vk.vkQueueSubmit(queue, count, submits, fence); + } void mark_device_lost(const char* where = "a Vulkan call returned VK_ERROR_DEVICE_LOST") noexcept { set_device_lost(device_lost_, where); @@ -2104,19 +2206,32 @@ class VulkanContext { using Watch = SubmissionProgressWatch; Watch watch; std::uint64_t retired = 0; + std::int64_t reported_hold = -1; + std::int64_t busy_since = -1; + SubmitMutex::GateStats gate_logged; + unsigned tick = 0; std::mutex timer_mutex; std::condition_variable_any timer; std::unique_lock timer_lock(timer_mutex); + // LOCAL DIAGNOSTIC (post-load GPU hangs): with the device-fault report on, sample every 250 ms, so a loss the + // driver has already reset is seen (and its checkpoints read) before a watchdog outside kills the process. + const auto period = device_fault_ ? std::chrono::milliseconds(250) : std::chrono::milliseconds(1000); + const unsigned per_10s = unsigned(std::chrono::seconds(10) / period); while (!stop.stop_requested()) { - timer.wait_for(timer_lock, stop, std::chrono::seconds(1), [] { return false; }); + timer.wait_for(timer_lock, stop, period, [] { return false; }); if (stop.stop_requested() || is_device_lost()) break; auto state = Watch::State::submit_lock_busy; VkResult result = VK_SUCCESS; std::uint64_t submitted; { // Keep queue timelines alive as in completed_retire_ticket(). A submit or idle wait - // blocked inside the driver can hold this mutex indefinitely. + // blocked inside the driver can hold this mutex indefinitely. Under heavy submission one try finds + // it busy most of the time: a few more within a millisecond or two. std::unique_lock lock(submit_mutex_, std::try_to_lock); + for (int retry = 0; !lock.owns_lock() && retry < 20; ++retry) { + std::this_thread::sleep_for(std::chrono::microseconds(100)); + if (lock.try_lock()) break; + } submitted = submitted_retire_ticket(); if (lock.owns_lock()) { if (is_device_lost()) break; @@ -2124,12 +2239,49 @@ class VulkanContext { state = retired < submitted ? Watch::State::pending : Watch::State::idle; } } + // LOCAL DIAGNOSTIC (early device loss): a submission unfinished for 4 s dumps the recent submissions with + // their semaphore counters (unreadable once the device is lost); a hold of the submit lock of 3 s names + // its thread and prints its call chain, once per hold. + // A vkQueueSubmit stuck in the driver (measured: 10 s, then VK_ERROR_DEVICE_LOST) also blocks + // vkGetSemaphoreCounterValue, so with the lock busy the watch stays out of the driver: the holder report + // samples stacks only, and the counters are read once the lock is free again. + if (state == Watch::State::submit_lock_busy) { + const std::uint32_t owner = submit_mutex_.owner(); + const std::int64_t since = submit_mutex_.since_ms(); + const std::int64_t held = diagnostic_ms() - since; + if (owner && held >= 3000 && since != reported_hold) { + reported_hold = since; + device_fault_->report_submit_lock_holder(owner, held); + } + // Busy at every sample but changing hands: contended, not stuck. Only a hold that lasts (the same + // holder since the same time) counts toward the 15 s stall report. + if (since != busy_since) { + busy_since = since; + state = Watch::State::idle; + } + } else { + device_fault_->check_submit_progress(); + } if (result == VK_ERROR_DEVICE_LOST) { mark_device_lost(); break; } // A failed counter query does not measure GPU progress. if (result != VK_SUCCESS) state = Watch::State::idle; + // Every 10 s while it changes: what the compile gate has cost so far (SubmitMutex::CompileTurn). + if (++tick % per_10s == 0) { + const SubmitMutex::GateStats gate = submit_mutex_.gate_stats(); + if (gate.submits != gate_logged.submits || gate.creates != gate_logged.creates) { + gate_logged = gate; + std::fprintf(stderr, "[rt] compile-gate: t=%.0f s: %llu submissions waited for pipeline creates " + "(%lld ms in all, longest %lld ms); %llu creates waited behind a submission " + "(%lld ms in all, longest %lld ms)\n", + double(diagnostic_ms()) / 1000.0, static_cast(gate.submits), + static_cast(gate.submit_ms), static_cast(gate.submit_max_ms), + static_cast(gate.creates), static_cast(gate.create_ms), + static_cast(gate.create_max_ms)); + } + } // LEONIDA_HANG_EXIT_S= (for boots): work pending and retirement still for s seconds is a GPU hang // the driver may recover from without Vulkan ever reporting the device lost (Xid 109: the title then // waits forever, the window frozen). The stall is reported (with the checkpoints under @@ -2157,7 +2309,9 @@ class VulkanContext { } if (watch.sample(state, retired, Watch::Clock::now())) device_fault_->report_stall(state == Watch::State::pending ? "queue retirement has not advanced" - : "could not sample the submit lock", + : submit_mutex_.gate_waiter() && submit_mutex_.gate_waiter() == submit_mutex_.owner() + ? "could not sample the submit lock (its holder waits at the compile gate)" + : "could not sample the submit lock", submitted, retired); } } @@ -2170,7 +2324,13 @@ class VulkanContext { alignas(64) std::shared_mutex resource_mutex_; // shared for prepare lookups, unique for add/remove alignas(64) std::mutex tracker_mutex_; alignas(64) std::mutex views_mutex_; - alignas(64) std::mutex submit_mutex_; + // Lock hierarchy (see VulkanQueue::execute): resource_mutex_ -> tracker_mutex_ -> submit_mutex_. A PSO build + // (shims/d3d12_vulkan_device.cpp, PipelineState::build_compute / build) holds its variants_mutex_ and the + // static big_compile mutex while it waits for the submit lock (SubmitMutex::let_submit_finish) or at the compile + // gate: variants_mutex_ -> big_compile -> submit_mutex_, and nothing holding submit_mutex_ takes either. The + // 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_; @@ -2220,6 +2380,11 @@ class VulkanContext { VkSemaphore bindless_upload_semaphore_ = VK_NULL_HANDLE; std::uint64_t bindless_upload_value_ = 0; std::uint64_t bindless_upload_version_ = 0; + std::function prelude_record_; + std::function prelude_commit_; + VkSemaphore prelude_semaphore_ = VK_NULL_HANDLE; // the queue whose submission recorded the last prelude + std::uint64_t prelude_value_ = 0; + std::uint64_t prelude_version_ = 0; std::unique_ptr depth24_; std::unique_ptr scratch_; // copies staged through a buffer (depth <-> colour) std::function bindless_commit_; @@ -2257,7 +2422,19 @@ class VulkanFence { } ~VulkanFence() { if (!semaphore_) return; + // LOCAL DIAGNOSTIC (early device loss): a fence released while a Signal the GPU has not run yet names it. + if (!context_.is_device_lost()) { + const std::uint64_t submitted = context_.holds().submitted_value(semaphore_); + std::uint64_t reached = 0; + if (submitted && context_.vk.vkGetSemaphoreCounterValue(context_.device(), semaphore_, &reached) == VK_SUCCESS && + reached < submitted) + std::fprintf(stderr, "[rt] d3d12: fence semaphore %p destroyed with a Signal pending (submitted %llu, " + "reached %llu) at t=%.3f s\n", + static_cast(semaphore_), static_cast(submitted), + static_cast(reached), double(diagnostic_ms()) / 1000.0); + } context_.holds().remove_fence(semaphore_); // batches held on it can never run: dropped and reported + if (DeviceFaultDiagnostics* ring = context_.device_fault()) ring->forget(semaphore_); // no report reads it context_.vk.vkDestroySemaphore(context_.device(), semaphore_, nullptr); } VulkanFence(const VulkanFence&) = delete; @@ -2391,16 +2568,24 @@ class VulkanQueue : private QueueHolds::Holder { ~VulkanQueue() { auto& vk = context_.vk; + stop_async(); // LEONIDA_SUBMIT_ASYNC: what is queued runs first + 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 report_held_at_teardown(); context_.holds().pump_ready(); // presents queued behind what was just dropped can run if (queue_) { std::lock_guard lock(context_.submit_mutex()); + const SubmitMutex::SubmitTurn turn(context_.submit_mutex()); // a queue operation: the compile gate for (; open_labels_; --open_labels_) context_.labels_.queue_end(queue_); const VkResult idle_result = context_.observe_result(vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle"); if (idle_result == VK_SUCCESS) { if (progress_) context_.retire_queue_idle_locked(progress_); } else { + // Any failure here makes every fence read ~0 from now on: say so when it is not a real loss. + if (idle_result != VK_ERROR_DEVICE_LOST) + std::fprintf(stderr, "[rt] d3d12: vkQueueWaitIdle at queue teardown returned %d; the device is " + "treated as lost\n", int(idle_result)); context_.mark_device_lost(); } } @@ -2415,9 +2600,15 @@ class VulkanQueue : private QueueHolds::Holder { // finished: the next submission on another queue must not wait on a semaphore that is about to go. std::lock_guard lock(context_.storage_mutex_); if (context_.storage_init_semaphore_ == progress_) context_.storage_init_semaphore_ = VK_NULL_HANDLE; + // The same for the bindless table upload: a queue that had not seen its version yet would otherwise + // wait on this destroyed semaphore in its next vkQueueSubmit. + if (context_.bindless_upload_semaphore_ == progress_) context_.bindless_upload_semaphore_ = VK_NULL_HANDLE; } if (pool_) vk.vkDestroyCommandPool(context_.device(), pool_, nullptr); - if (progress_) vk.vkDestroySemaphore(context_.device(), progress_, nullptr); + if (progress_) { + if (DeviceFaultDiagnostics* ring = context_.device_fault()) ring->forget(progress_); // no report reads it + vk.vkDestroySemaphore(context_.device(), progress_, nullptr); + } destroy_khr_stages(khr_stage_pool_); destroy_khr_as_queries(khr_as_query_pool_); for (auto& slot : buffers_) { @@ -2432,6 +2623,8 @@ class VulkanQueue : private QueueHolds::Holder { VulkanQueue& operator=(const VulkanQueue&) = delete; 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; } // 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). @@ -2440,6 +2633,7 @@ class VulkanQueue : private QueueHolds::Holder { template 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); @@ -2487,6 +2681,7 @@ class VulkanQueue : private QueueHolds::Holder { 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); @@ -2507,6 +2702,27 @@ class VulkanQueue : private QueueHolds::Holder { return bind_tiles(dst, target->second, changes); } + // The pipelines the lists' draws and dispatches need that are not built yet are asked for (queued on the compile + // worker, or built here when builds are not asynchronous) and waited for at most the budget (pipeline_wait.h), + // holding none of our locks: a build that takes seconds no longer holds resource_mutex_ (shared) across its wait, + // where a title thread creating a resource queued behind it for the exclusive lock and every submission behind + // that. What is still being built after the wait is skipped by prepare and used by a later submission. + void await_pipelines(std::span lists) { + const submit_phases::Scope timed(submit_phases::pipelines); + pipeline_wait::note_submission(); + // The queue's scratch, kept for its capacity. Its own lock is a leaf: what runs under it takes resource_mutex_ + // (shared, for the lookups), a PSO's build state lock and the compile worker's queue lock, none of which is + // held by anything that takes this one. + std::lock_guard scratch(awaits_mutex_); + { + std::shared_lock lock(context_.resource_mutex_); // the registry lookups; no build or wait under it + collect_pipeline_awaits(lists, context_.replay_, awaits_, await_seen_); + } + if (!awaits_.empty()) leonida::await_pipelines(awaits_, pipeline_wait_budget_ns()); + awaits_.clear(); // the captured callbacks go before the lists' pipeline states may + pipeline_wait::maybe_report([] { return submit_phases::process_age(); }); + } + // 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 @@ -2519,8 +2735,23 @@ class VulkanQueue : private QueueHolds::Holder { using PinFn = std::function()>; ReplayResult execute(std::span lists, const PinFn& pin = {}) { + await_pipelines(lists); // before any lock of ours: prepare then never waits for a pipeline build auto* diagnostics = context_.device_fault(); const auto execute_call = diagnostics ? diagnostics->next_execute_call() : 0; + 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.lists.reserve(lists.size()); + for (const CommandList* list : lists) call.lists.push_back(*list); + if (pin) call.pin = pin(); + enqueue(std::move(call)); + return ReplayResult::success; + } + return execute_sync(lists, pin, execute_call); + } + + 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 @@ -2551,6 +2782,19 @@ class VulkanQueue : private QueueHolds::Holder { // 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. 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; + if (pin) call.pin = pin(); + enqueue(std::move(call)); + return true; + } + return signal_sync(fence, value, pin); + } + + bool signal_sync(VkSemaphore fence, std::uint64_t value, const PinFn& pin) { bool ok = true; std::vector> retired; { @@ -2564,6 +2808,10 @@ class VulkanQueue : private QueueHolds::Holder { hold(std::move(op)); } else { ok = submit(VK_NULL_HANDLE, fence, value); + // 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()}); } drain_pins(retired); } @@ -2576,6 +2824,19 @@ class VulkanQueue : private QueueHolds::Holder { // batch, so it is kept and attached to the next submission (held on the CPU if no Signal reaches it yet). // `pin` returns what keeps the fence object alive until then (a D3D12 queue holds its fences). void wait(VkSemaphore fence, std::uint64_t value, const PinFn& pin = {}) { + if (async_on()) { + Call call; + call.kind = Call::Kind::wait; + call.fence = fence; + call.value = value; + if (pin) call.pin = pin(); + enqueue(std::move(call)); + return; + } + wait_sync(fence, value, pin); + } + + void wait_sync(VkSemaphore fence, std::uint64_t value, const PinFn& pin) { std::vector> retired; // fences whose submission has completed: released unlocked { std::lock_guard state(state_mutex_); @@ -2596,6 +2857,18 @@ 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 (async_on()) { + Call call; + call.kind = Call::Kind::marker; + call.marker_kind = kind; + call.label = label ? label : ""; + enqueue(std::move(call)); + return; + } + marker_sync(kind, label); + } + + void marker_sync(DebugMarker::Kind kind, const char* label) { std::vector> retired; std::lock_guard state(state_mutex_); drain_pins(retired); // destroyed after the lock (reverse declaration order) @@ -2611,7 +2884,9 @@ class VulkanQueue : private QueueHolds::Holder { } bool idle() { + flush_async(); std::lock_guard lock(context_.submit_mutex()); + const SubmitMutex::SubmitTurn turn(context_.submit_mutex()); // a queue operation: the compile gate return context_.observe_result(context_.vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle") == VK_SUCCESS; } @@ -2621,6 +2896,9 @@ class VulkanQueue : private QueueHolds::Holder { std::vector khr_stage_pool_; std::vector khr_as_query_pool_; std::vector xdxr_ranges_; // stage_xdxr_table's snapshot, kept for its capacity + std::mutex awaits_mutex_; // await_pipelines' scratch (not thread_local, see there) + std::vector awaits_; + std::unordered_set await_seen_; void destroy_khr_stages(std::vector& stages) { for (const auto& stage : stages) { @@ -3331,6 +3609,25 @@ class VulkanQueue : private QueueHolds::Holder { auto pieces = detail::current(&next_tracker, id, range, VK_IMAGE_LAYOUT_UNDEFINED); detail::initialize(replay, command_buffer, *image, id, pieces, VK_IMAGE_LAYOUT_GENERAL, &next_tracker); } + // 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); + // 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); + }(); + { + 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_); + } + prelude_seen_ = context_.prelude_version_; + } bool wrote_readback = false; VkPipelineStageFlags2 readback_stages = 0; std::uint32_t open_labels = 0; // events may span the lists of one ExecuteCommandLists @@ -3418,6 +3715,16 @@ class VulkanQueue : private QueueHolds::Holder { ++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 (wait_previous && !submitted && !waits_.empty()) { // a failed submit keeps the waits for the next one waits_.pop_back(); wait_values_.pop_back(); @@ -3538,7 +3845,9 @@ 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) { - op.seq = context_.holds().next_seq(); + // 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(); if (op.kind != Deferred::Kind::marker) { op.waits = std::move(waits_); op.wait_values = std::move(wait_values_); @@ -3549,6 +3858,7 @@ 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); context_.holds().held_changed(1); } @@ -3595,7 +3905,21 @@ class VulkanQueue : private QueueHolds::Holder { 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). bool release_ready() override { + if (async_started_.load(std::memory_order_acquire) && t_worker_of_ != this) { + { + std::lock_guard lock(inbox_mutex_); + release_requested_ = true; + } + inbox_cv_.notify_one(); + return false; + } + return release_held(); + } + + bool release_held() { std::vector> retired; bool released = false; { @@ -3604,8 +3928,19 @@ class VulkanQueue : private QueueHolds::Holder { Deferred op = std::move(held_.front()); held_.pop_front(); context_.holds().held_changed(-1); - if (gpu_latency::enabled()) gpu_latency::held(int(kind_), int(op.kind), op.held_at); + 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; } drain_pins(retired); @@ -3630,13 +3965,22 @@ class VulkanQueue : private QueueHolds::Holder { it = held_.erase(it); context_.holds().held_changed(-1); } + held_front_seq_.store(held_.empty() ? 0 : held_.front().seq, std::memory_order_release); } } // Holder: the sequence number of the oldest held operation. std::uint64_t oldest_held_seq() override { - std::lock_guard state(state_mutex_); - return held_.empty() ? 0 : held_.front().seq; + if (!async_on()) { + std::lock_guard state(state_mutex_); + return held_.empty() ? 0 : held_.front().seq; + } + // 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; } // A queue destroyed with held work. Reported, not waited for: nothing was submitted for it, so the VkQueue is @@ -3662,6 +4006,7 @@ class VulkanQueue : private QueueHolds::Holder { if (op.kind == Deferred::Kind::signal) context_.cancel_fence_waits(op.fence); context_.holds().held_changed(-static_cast(held_.size())); dropped.swap(held_); + held_front_seq_.store(0, std::memory_order_release); } // The pins (fences, pipeline states) are released here, outside the lock. } @@ -3796,8 +4141,12 @@ class VulkanQueue : private QueueHolds::Holder { pending_bindings_.push_back(std::move(pending)); { std::lock_guard lock(context_.submit_mutex()); - const auto result = context_.observe_result(vk.vkQueueBindSparse(queue_, 1, &info, VK_NULL_HANDLE), - "vkQueueBindSparse"); + VkResult bound; + { + const SubmitMutex::SubmitTurn turn(context_.submit_mutex()); // a queue operation: the compile gate + bound = vk.vkQueueBindSparse(queue_, 1, &info, VK_NULL_HANDLE); + } + const auto result = context_.observe_result(bound, "vkQueueBindSparse"); if (result != VK_SUCCESS) { if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost(); pending_bindings_.pop_back(); @@ -4021,10 +4370,32 @@ class VulkanQueue : private QueueHolds::Holder { if (diagnostics) pass_trace(*diagnostics); // Publish before the driver can execute a marker or a concurrent fence wait can see the loss. if (diagnostics) context_.device_fault()->publish(std::move(*diagnostics)); - const auto label_fence=context_.gpu_labels_.submit_fence(command_buffer); - res = context_.observe_result(context_.vk.vkQueueSubmit(queue_, 1, &submit, label_fence), + DeviceFaultDiagnostics* const ring = context_.device_fault(); + std::size_t ring_at = 0; + const std::int64_t submit_start = diagnostic_ms(); + if (ring) { + SubmitRecord record; + record.at_ms = submit_start; + record.queue = queue_; + record.kind = kind_ == QueueKind::direct ? "direct" : kind_ == QueueKind::compute ? "compute" : "copy"; + record.progress = progress_; + record.ticket = ticket; + record.buffers = submit.commandBufferCount; + if (signals_fence) { + record.fence = fence; + record.fence_value = value; + } + record.waits = std::uint32_t(semaphores.size()); + for (std::size_t i = 0; i < semaphores.size() && i < SubmitRecord::max_waits; ++i) { + record.wait_semaphores[i] = semaphores[i]; + record.wait_values[i] = values[i]; + } + ring_at = ring->begin_submit(record); + } + res = context_.observe_result(context_.queue_submit(queue_, 1, &submit, context_.gpu_labels_.submit_fence(command_buffer)), "vkQueueSubmit"); - context_.gpu_labels_.submitted(command_buffer,res==VK_SUCCESS); + 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); @@ -4063,6 +4434,7 @@ class VulkanQueue : private QueueHolds::Holder { 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 prelude_seen_ = 0; // the prelude_version_ this queue has waited for (or recorded) std::uint64_t last_sparse_ = 0; std::deque pending_bindings_; std::vector waits_; @@ -4072,6 +4444,258 @@ class VulkanQueue : private QueueHolds::Holder { std::vector prepared_; std::uint32_t open_labels_ = 0; // queue labels begun and not ended bool ok_ = false; + // ---- LEONIDA_SUBMIT_ASYNC=: the queue's calls run on a worker of its own ----------------------------------- + // ExecuteCommandLists, Signal, Wait and the markers are queued in call order and return at once; one worker per + // queue runs each through the synchronous path (execute_sync & co.), so the replay, the before-submission + // refreshes and vkQueueSubmit leave the caller's thread and overlap with its next frame. At most n batches wait per + // queue; the caller of the next one waits for room (the in-flight bound). A queued call counts as held work + // (QueueHolds), numbered when it was called, so a Present behind it still waits for it and cross-queue order is + // the call order. Calls that use the queue's state at once (tile mappings, idle, the destructor) first wait for + // what is queued. A batch that fails is reported as a held one is (stderr, take_held_failure()). Off (0) by + // default: every call runs on the caller's thread, as before. + static unsigned async_depth() { + static const unsigned depth = [] { + const char* v = std::getenv("LEONIDA_SUBMIT_ASYNC"); + const int n = v && *v ? std::atoi(v) : 0; + return n > 0 ? unsigned(n) : 0u; + }(); + return depth; + } + + 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 + 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; + std::string label; + std::chrono::steady_clock::time_point queued_at{}; + }; + + struct AsyncStats { // under inbox_mutex_, since the last line + std::uint64_t calls = 0, batches = 0, room_waits = 0, room_wait_ns = 0, run_ns = 0, lag_ns = 0, lag_max_ns = 0; + std::size_t depth_max = 0; + std::chrono::steady_clock::time_point since = std::chrono::steady_clock::now(); + }; + + void enqueue(Call&& call) { + const bool batch = call.kind == Call::Kind::execute; + std::unique_lock lock(inbox_mutex_); + if (!worker_.joinable()) { + 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())); + }; + if (!room()) { + const auto start = std::chrono::steady_clock::now(); + room_cv_.wait(lock, room); + ++async_stats_.room_waits; + async_stats_.room_wait_ns += std::uint64_t( + std::chrono::duration_cast(std::chrono::steady_clock::now() - start).count()); + } + if (batch) { + ++inbox_batches_; + ++async_stats_.batches; + } + ++async_stats_.calls; + call.seq = context_.holds().next_seq(); + call.queued_at = std::chrono::steady_clock::now(); + context_.holds().held_changed(1); + inbox_.push_back(std::move(call)); + 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; + for (;;) { + Call call; + bool have = false, release = false; + { + 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 (!inbox_.empty()) { + call = std::move(inbox_.front()); + inbox_.pop_front(); + running_seq_ = call.seq; + have = true; + } else if (!release) { + return; // stopping, nothing queued + } + worker_busy_ = true; + } + if (release) release_held(); + std::uint64_t ran_ns = 0; + 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); + } + { + std::lock_guard lock(inbox_mutex_); + running_seq_ = 0; + worker_busy_ = false; + if (have && call.kind == Call::Kind::execute) --inbox_batches_; + if (have) 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(); + } + } + + // An exception on the worker would end the process (std::terminate) and leave the queue's callers waiting: it is + // turned into a held failure and a lost device instead, as a failed submission would be, and the worker goes on + // (each later call fails at once on the lost device). + void run_call(Call& call) { + try { + run_call_unguarded(call); + } catch (const std::exception& e) { + worker_threw(call, e.what()); + } catch (...) { + worker_threw(call, "not a std::exception"); + } + async_seq_ = 0; + } + + void worker_threw(const Call& call, const char* what) { + int none = static_cast(ReplayResult::success); + held_failure_.compare_exchange_strong(none, static_cast(ReplayResult::unsupported)); + std::fprintf(stderr, "[rt] d3d12: the queue's worker caught an exception running a queued %s (%s); the device is " + "marked lost\n", + call.kind == Call::Kind::execute ? "ExecuteCommandLists" + : call.kind == Call::Kind::signal ? "Signal" + : call.kind == Call::Kind::wait ? "Wait" + : "marker", + what); + context_.mark_device_lost(); + } + + 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); + 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 queued ExecuteCommandLists failed on the queue's worker (result " + "%d); nothing was submitted for it\n", + static_cast(result)); + } + break; + } + case Call::Kind::signal: + if (!signal_sync(call.fence, call.value, pin)) { + 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_); + } + } + + // 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(); + const double s = std::chrono::duration(now - async_stats_.since).count(); + if (s < 10.0) return; + static constexpr const char* kinds[] = {"direct", "compute", "copy"}; + const AsyncStats& a = async_stats_; + 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", + 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), + 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{}; + } + + // What was queued before this call has run (held work may stay held, as without the worker). A worker that does + // not come back (a GPU hang inside wait_for_room, say) is reported every 10 s, and after 60 s the caller goes on + // without it: false. + 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_; }; + 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, " + "running call %llu)%s\n", + slice * 10, inbox_.size(), static_cast(running_seq_), + slice == 6 ? "; going on without it" : ""); + } + return false; + } + + void stop_async() { + if (!async_started_.load(std::memory_order_acquire)) return; + const bool drained = flush_async(); + { + std::lock_guard lock(inbox_mutex_); + async_stop_ = true; + } + inbox_cv_.notify_all(); + room_cv_.notify_all(); + if (!worker_.joinable()) return; + if (drained) { + worker_.join(); + return; + } + // A worker stuck for a minute holds this queue's objects: it is left running rather than joined forever + // (only at teardown; the process is ending or the device is gone). + std::fprintf(stderr, "[rt] d3d12: a queue's worker did not finish; it is detached at the queue's destruction\n"); + worker_.detach(); + } + + std::mutex inbox_mutex_; + 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 + bool worker_busy_ = false, release_requested_ = false, async_stop_ = false; + AsyncStats async_stats_; + std::atomic async_started_{false}; + bool synchronous_ = false; // make_synchronous() + 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 resource_mutex_ -> tracker_mutex_ -> submit_mutex_) and // guards the members above that execute, signal, wait and marker touch. std::mutex state_mutex_; diff --git a/runtime/src/vulkan_bindless.h b/runtime/src/vulkan_bindless.h index e72225396b..da6d680f02 100644 --- a/runtime/src/vulkan_bindless.h +++ b/runtime/src/vulkan_bindless.h @@ -25,6 +25,14 @@ // and samplers it adds and keeps them alive while they are in the set; this class owns only the fallbacks and the // table's buffer. // +// The T#'s own type is the truth: the index was given out in ITS dimension's space, so a shader reading it through +// another dimension's array (a 2D instruction on a 2D-array or cube T#, say) must not use it blindly. Every entry +// therefore carries, next to the index, which arrays the index is bound in (descriptor_table.h's kind bits), and a +// translated module of the tagged contract reads that word: it uses the index only in an array the entry names and +// otherwise takes that array's fallback. For the one mismatch the hardware reads rather than drops - a 2D +// instruction on a 2D-array or cube T#, which addresses slice 0 - add_image's MirrorViews bind a view of that slice +// at the same index in the 2D arrays and name 2D in the kind, so the instruction finds it. +// // The fallbacks stand for the console's null descriptors (a zero T#, a T# whose image the layer refused or never // saw): each is of the kind the instruction asks for, since the translator picks the binding by the instruction's // dimension and the view by the T#'s numeric class, and a miss at any of them reads zeros. On the console a store or @@ -68,6 +76,7 @@ #include #include +#include #include #include #include @@ -398,6 +407,8 @@ class BindlessSet { BindlessSet& operator=(const BindlessSet&) = delete; bool ok() const { return ok_; } + // What the set layout was made from (the pipeline journal names compute pipelines by it). + const BindlessFeatures& features() const { return features_; } bool supports_ms_class(std::uint32_t component_class) const { return component_class < classes && features_.ms_samples[component_class] != VK_SAMPLE_COUNT_1_BIT; } @@ -461,29 +472,109 @@ class BindlessSet { &done, 0, nullptr, 0, nullptr); } + // A second view of the same image in the 2D arrays: the slice a 2D instruction reads through a 2D-array or cube + // T# (its first layer). The hardware addresses such a read as slice 0, and the translated shader reads binding 0 + // with the identity the table gives, so the runtime binds this copy at the image's own index and records that + // index as valid in the 2D array too (kind_sampled_bit), owned by this image (mirror_of): another dimension's + // image with the same slot number does not inherit it. The storage views follow the same rule when the image has + // them, so a 2D store or atomic lands on layer 0. + struct MirrorViews { + VkImageView sampled = VK_NULL_HANDLE; + VkImageLayout sampled_layout = VK_IMAGE_LAYOUT_GENERAL; + StorageViews storage{}; + }; + // Gives an image an index in its dimension's bindings: 0 when the dimension is full. `sampled` goes to the // sampled array in `sampled_layout` (the layout the image is in when shaders read it); the storage views go to // the storage arrays in GENERAL. For MS views, sampled_class selects the float, uint or sint sampled array. - // The caller maps the T# to the index with insert_key(). Takes effect at flush(). + // `mirror` adds the same index in the 2D arrays (a 2D-array or cube image's slice 0): the slot must then be free + // in both index spaces. `kind_out`, when given, receives what the index is bound in (descriptor_table.h's kind + // bits), which the caller records with insert_key. The caller maps the T# to the index with insert_key(). Takes + // effect at flush(). std::uint32_t add_image(ImageDimension dimension, VkImageView sampled, VkImageLayout sampled_layout, - const StorageViews& storage = {}, std::uint32_t sampled_class = 0) { + const StorageViews& storage = {}, std::uint32_t sampled_class = 0, + const MirrorViews* mirror = nullptr, std::uint32_t* kind_out = nullptr) { 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::uint32_t index = stores ? 0 : allocate(used, low_end, std::uint32_t(used.size())); - if (!index) index = allocate(used, 1, low_end); - if (index) write_image(dimension, index, sampled, sampled_layout, storage, sampled_class); + 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; + } + // 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)); + 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 (!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; + } + } + 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 (!index) return 0; + assert(!used_2d || !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) { + 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_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); + } return index; } - // New views or a new layout for an index add_image returned (a texture's state changed, say). + // New views or a new layout for an index add_image returned (a texture's state changed, say). `mirror` is + // refreshed too when the image was added with one (mirror_of says whose 2D slot it is). The slot bookkeeping + // follows what was written, and `kind_out`, when given, receives the index's kind word afterwards for a + // re-insert: the table keeps the kind it was given, so a caller that adds or drops storage views re-records it. void update_image(ImageDimension dimension, std::uint32_t index, VkImageView sampled, VkImageLayout sampled_layout, - const StorageViews& storage = {}, std::uint32_t sampled_class = 0) { + const StorageViews& storage = {}, std::uint32_t sampled_class = 0, + const MirrorViews* mirror = nullptr, std::uint32_t* kind_out = nullptr) { const auto& used = image_used_[std::uint32_t(dimension)]; - if (index && index < used.size() && used[index] == in_use) + const bool live = index && index < used.size() && used[index] == in_use; + if (live) { write_image(dimension, index, sampled, sampled_layout, storage, sampled_class); + const bool stores = storage.as_float || storage.as_uint || storage.as_sint || storage.r32ui; + if (index < storage_used_[std::uint32_t(dimension)].size()) + storage_used_[std::uint32_t(dimension)][index] = stores ? 1 : 0; + } + if (live && mirror && mirror->sampled && mirror_of(dimension, index)) { + write_image(ImageDimension::dim_2d, index, mirror->sampled, mirror->sampled_layout, mirror->storage, 0); + if (index < mirror_storage_used_.size()) 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 = image_kind_at(dimension, index); } // Returns the index to the fallback and frees it. The caller removes the image's keys with erase_key() first. @@ -495,7 +586,22 @@ class BindlessSet { 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}); + // 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}); + } } // 0 when the sampler array is full. @@ -512,15 +618,37 @@ class BindlessSet { if (table_dirty_) held_samplers_.push_back(index); } - // T# and S# keys to the indices above: the table of binding 2 (descriptor_table.h). Changes reach the shaders - // at flush(). - bool insert_key(const DescriptorKey& key, std::uint32_t index) { - const auto result = table_.insert_or_update(key.data(), index); + // What an index of `dimension` is bound in, from what add_image wrote: that dimension's sampled bit, its storage + // bit when the slot holds storage views, and the 2D bits when this image owns the slot at the same number in the + // 2D arrays as its mirror (mirror_of). + std::uint32_t image_kind_at(ImageDimension dimension, std::uint32_t index) const { + const auto set = [&](const std::vector& used) { + return index < used.size() && used[index] != 0; + }; + const std::uint32_t d = std::uint32_t(dimension); + std::uint32_t kind = kind_sampled_bit(d) | (set(storage_used_[d]) ? kind_storage_bit(d) : 0); + if (mirror_of(dimension, index)) { + kind |= kind_sampled_bit(std::uint32_t(ImageDimension::dim_2d)); + if (set(mirror_storage_used_)) kind |= kind_storage_bit(std::uint32_t(ImageDimension::dim_2d)); + } + return kind; + } + + // T# and S# keys to the indices above: the table of binding 2 (descriptor_table.h). `kind` is what the index is + // bound in, for the modules that read it (descriptor_table.h's kind bits); a sampler's entry has none. Changes + // reach the shaders at flush(). + bool insert_key(const DescriptorKey& key, std::uint32_t index, std::uint32_t kind = 0) { + const auto result = table_.insert_or_update(key.data(), index, kind); table_dirty_ |= result != DescriptorTable::InsertResult::unchanged; existing_entries_changed_ |= result == DescriptorTable::InsertResult::replaced || result == DescriptorTable::InsertResult::added_with_relocation; return true; } + // The T#'s own dimension, whose kind the set derives from the index it gave out (image_kind_at): a caller that + // knows the T#'s TYPE needs to pass no bits. + bool insert_key(const DescriptorKey& key, std::uint32_t index, ImageDimension dimension) { + return insert_key(key, index, image_kind_at(dimension, index)); + } // Erasing empties only the key's own slot; no other entry moves (DescriptorTable::erase), so it needs no idle. // The caller erases a key once no submitted work uses it (its texture is gone), like D3D12 requires. bool erase_key(const DescriptorKey& key) { @@ -754,6 +882,34 @@ class BindlessSet { 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; + } + return 0; + } + + // A mirror is worth binding only when it has a view; its storage views make the 2D storage arrays valid too. + static bool mirror_storage(const MirrorViews* mirror) { + return mirror && (mirror->storage.as_float || mirror->storage.as_uint || mirror->storage.as_sint || + mirror->storage.r32ui); + } + + // True when the 2D slot at `index` is the mirror of the image whose index is `index` in `dimension` (add_image's + // MirrorViews). A bare per-slot flag cannot say so: every dimension's index space is dense and independent, so + // the Nth image of one dimension shares its slot number with the Nth 2D-array image's mirror slot in the 2D + // arrays. The owner is the dimension + 1 (0: no mirror). + bool mirror_of(ImageDimension dimension, std::uint32_t index) const { + if (dimension == ImageDimension::dim_2d) return false; + return index < mirror_owner_.size() && mirror_owner_[index] == std::uint8_t(std::uint32_t(dimension) + 1); + } + std::uint32_t memory_type(std::uint32_t allowed, VkMemoryPropertyFlags wanted) const { for (std::uint32_t i = 0; i < memory_.memoryTypeCount; ++i) if ((allowed & (1u << i)) && (memory_.memoryTypes[i].propertyFlags & wanted) == wanted) return i; @@ -778,6 +934,10 @@ class BindlessSet { image_used_[d].assign(image_capacity(ImageDimension(d)), 0); image_used_[d][0] = 1; } + 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); sampler_used_[0] = 1; return true; @@ -1282,6 +1442,14 @@ class BindlessSet { VkSampler fallback_sampler_ = VK_NULL_HANDLE; bool fallbacks_ready_ = false; std::array, dimensions> image_used_; + // 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 + // (dimension + 1, 0 for none) and mirror_storage_used_ whether it has storage views: the 2D slot numbers line up + // with another dimension's indices, so the slot alone does not identify its owner. + std::array, dimensions> storage_used_; + std::vector mirror_owner_; + std::vector mirror_storage_used_; std::vector sampler_used_; std::vector> held_images_; // removed, not yet free (remove_image) std::vector held_samplers_; diff --git a/runtime/src/vulkan_device_fault.h b/runtime/src/vulkan_device_fault.h index d60367491d..18f2529c32 100644 --- a/runtime/src/vulkan_device_fault.h +++ b/runtime/src/vulkan_device_fault.h @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -15,6 +16,8 @@ #include #include #include +#include +#include #include #include #include @@ -244,6 +247,302 @@ inline void run_device_lost_hook() noexcept { if (const auto hook = device_lost_hook.load(std::memory_order_acquire)) hook(); } +// LOCAL DIAGNOSTIC (early device loss): what the submit lock, the recent submissions and the other threads were +// doing when a submission stalled or the device was lost. +inline std::int64_t diagnostic_ms() { + static const auto start = std::chrono::steady_clock::now(); + return std::chrono::duration_cast(std::chrono::steady_clock::now() - start).count(); +} + +#ifdef _WIN32 +extern "C" __declspec(dllimport) unsigned long __stdcall GetCurrentThreadId(void); +inline std::uint32_t diagnostic_thread_id() { return static_cast(GetCurrentThreadId()); } +#else +inline std::uint32_t diagnostic_thread_id() { return 0; } +#endif + +// Set by gta6rt's main (src/thread_stacks.cpp): prints the call chain of thread `tid`, or of every other thread +// when `tid` is 0. Unset in the tests. +inline std::atomic thread_stack_hook{nullptr}; + +inline void print_thread_stacks(std::uint32_t tid, const char* why) noexcept { + if (const auto hook = thread_stack_hook.load(std::memory_order_acquire)) hook(tid, why); +} + +// The compute pipeline vkCreateComputePipelines is building now (one at a time is enough: the reports name the one +// set last), for the submit-lock hold report. Names are ShaderLibrary strings, valid until device teardown. +struct DriverCompile { + std::atomic name{nullptr}; + std::atomic trigger{nullptr}; + std::atomic since_ms{0}; + std::atomic bytes{0}; +}; +inline DriverCompile driver_compile; + +// VulkanContext's submit lock, which also remembers who holds it, since when and how many threads wait for it. A +// submit or an idle wait blocked inside the driver holds it for as long as it blocks; the stall watchdog and the loss +// report name that thread, and a hold of a second or more is logged when it ends. +class SubmitMutex { +public: + static constexpr std::int64_t kLongHoldMs = 1000; + // How long let_submit_finish(true) keeps letting queued submitters go first before the caller goes ahead anyway, + // so a steady stream of submits cannot hold the compile worker back for ever. Waiting out the holder itself is + // not capped: entering the driver while a submit is inside it is what lost the device. + static constexpr std::int64_t kHandoffCapMs = 250; + + void lock() { + if (mutex_.try_lock()) { + taken(); + return; + } + // Counted until this thread owns the lock (owner_ set), so let_submit_finish never sees neither. + waiting_.fetch_add(1, std::memory_order_relaxed); + mutex_.lock(); + taken(); + waiting_.fetch_sub(1, std::memory_order_relaxed); + } + bool try_lock() { + if (!mutex_.try_lock()) return false; + taken(); + return true; + } + void unlock() { + const std::int64_t since = since_.load(std::memory_order_relaxed); + const std::uint32_t owner = owner_.load(std::memory_order_relaxed); + owner_.store(0, std::memory_order_relaxed); + releases_.fetch_add(1); // seq_cst with the handoff_waiters_ load: no let_submit_finish misses this release + mutex_.unlock(); + if (handoff_waiters_.load()) { + std::lock_guard lock(handoff_mutex_); + released_.notify_all(); + } + const std::int64_t now = diagnostic_ms(); + if (now - since >= kLongHoldMs) + std::fprintf(stderr, "[rt] submit-lock: held %lld ms by thread %u, t=%.3f..%.3f s\n", + static_cast(now - since), owner, double(since) / 1000.0, double(now) / 1000.0); + } + + std::uint32_t owner() const { return owner_.load(std::memory_order_relaxed); } + std::int64_t since_ms() const { return since_.load(std::memory_order_relaxed); } + // Threads blocked in lock() (try_lock never counts). + std::uint32_t waiting() const { return waiting_.load(std::memory_order_relaxed); } + + // Called before the driver calls that build pipelines: waits for a submit in progress to finish (unless this + // thread is the one submitting). Measured on NVIDIA 630.20 (three early losses): back-to-back pipeline creates on + // the compile worker keep re-taking a driver lock that vkQueueSubmit waits for; after 10 s of that wait the driver + // returns VK_ERROR_DEVICE_LOST, with no GPU fault and no TDR. Not entering the driver while a submit is in it lets + // the submit take that lock between two creates. + // `queued` (the compile worker): also lets the submitters queued behind the holder go first - std::mutex is not + // fair, so without that the worker's next create could get in ahead of them - for at most `cap_ms`; past it the + // hold in progress is the last one waited for. The wait never takes the lock itself (taking it could queue behind + // every submitter that re-takes it), it waits for the hold it saw to end. Returns how many milliseconds it waited. + std::int64_t let_submit_finish(bool queued = true, std::int64_t cap_ms = kHandoffCapMs) { + const std::uint32_t self = diagnostic_thread_id(); + if (owner_.load(std::memory_order_relaxed) == self) return 0; // this thread submits: nothing to let through + const auto queue = [&] { return queued && waiting_.load(std::memory_order_relaxed) != 0; }; + std::uint64_t seen = releases_.load(); + const auto held = [&] { + seen = releases_.load(); // read before the owner: a hold that ends after this changes it + return owner_.load() != 0; + }; + if (!held() && !queue()) return 0; + const std::int64_t start = diagnostic_ms(); + for (;;) { + const bool over = diagnostic_ms() - start >= cap_ms; + if (held()) { + wait_release(seen); + if (!queued || over) break; + } else if (!queue() || over) { + break; + } else { + std::this_thread::yield(); // a queued submitter is between its wake-up and taking the lock + } + } + return diagnostic_ms() - start; + } + + // The compile gate. A queue submission never enters the driver while a pipeline create is in it: measured on + // NVIDIA 630.20 (wf6), a vkQueueSubmit that entered while the warm-up thread was inside one long + // vkCreateComputePipelines waited 10 s in the driver and returned VK_ERROR_DEVICE_LOST; let_submit_finish cannot + // help once the create is already running. Creates pass the gate shared, a submission exclusively, and a create + // that arrives while a submission waits queues behind it, so a submission waits only for the creates already in + // the driver. A long compile then stalls the submitting thread here, in our code, instead of in the driver. + // No deadlock: a create holds the gate only across its vkCreate*Pipelines and a submission only across its + // vkQueueSubmit, and neither driver call waits for anything of ours. LEONIDA_COMPILE_GATE=0 turns it off. + class CompileTurn { // around vkCreate*Pipelines + public: + explicit CompileTurn(SubmitMutex& gate) : gate_(gate), waited_(gate.enter_compile()) {} + ~CompileTurn() { gate_.leave_compile(); } + CompileTurn(const CompileTurn&) = delete; + CompileTurn& operator=(const CompileTurn&) = delete; + std::int64_t waited_ms() const { return waited_; } + + private: + SubmitMutex& gate_; + std::int64_t waited_; + }; + class SubmitTurn { // around vkQueueSubmit, with the submit lock held + public: + explicit SubmitTurn(SubmitMutex& gate) : gate_(gate) { gate.enter_submit(); } + ~SubmitTurn() { gate_.leave_submit(); } + SubmitTurn(const SubmitTurn&) = delete; + SubmitTurn& operator=(const SubmitTurn&) = delete; + + private: + SubmitMutex& gate_; + }; + + static bool compile_gate_enabled() { + static const bool on = [] { + const char* value = std::getenv("LEONIDA_COMPILE_GATE"); + return !(value && !std::strcmp(value, "0")); + }(); + return on; + } + + // The thread waiting in enter_submit for creates to leave the driver, or 0. + std::uint32_t gate_waiter() const { return gate_waiter_.load(std::memory_order_relaxed); } + + struct GateStats { + std::uint64_t submits = 0; // submissions that had to wait for a create + std::int64_t submit_ms = 0, submit_max_ms = 0; + std::uint64_t creates = 0; // creates that waited behind a submission + std::int64_t create_ms = 0, create_max_ms = 0; + }; + GateStats gate_stats() { + std::lock_guard lock(gate_mutex_); + return stats_; + } + + std::int64_t enter_compile() { + if (!compile_gate_enabled()) return 0; + std::unique_lock lock(gate_mutex_); + std::int64_t waited = 0; + if (submits_) { + const std::int64_t start = diagnostic_ms(); + gate_changed_.wait(lock, [&] { return submits_ == 0; }); + waited = diagnostic_ms() - start; + ++stats_.creates; + stats_.create_ms += waited; + stats_.create_max_ms = (std::max)(stats_.create_max_ms, waited); + } + ++compiles_; + return waited; + } + void leave_compile() { + if (!compile_gate_enabled()) return; + std::lock_guard lock(gate_mutex_); + if (--compiles_ == 0 && submits_) gate_changed_.notify_all(); + } + + std::int64_t enter_submit() { + if (!compile_gate_enabled()) return 0; + std::unique_lock lock(gate_mutex_); + ++submits_; + if (!compiles_) return 0; + const std::uint32_t self = diagnostic_thread_id(); + gate_waiter_.store(self, std::memory_order_relaxed); + const std::int64_t start = diagnostic_ms(); + const GateWait what{self, compiles_, driver_compile.name.load(std::memory_order_acquire), + driver_compile.trigger.load(std::memory_order_relaxed), + driver_compile.bytes.load(std::memory_order_relaxed)}; + std::int64_t next_note = 2000; + while (!gate_changed_.wait_for(lock, std::chrono::milliseconds(250), [&] { return compiles_ == 0; })) { + const std::int64_t waited = diagnostic_ms() - start; + if (waited < next_note) continue; + next_note = waited + 5000; + note_gate_wait("has waited", what, waited); + } + gate_waiter_.store(0, std::memory_order_relaxed); + const std::int64_t waited = diagnostic_ms() - start; + ++stats_.submits; + stats_.submit_ms += waited; + stats_.submit_max_ms = (std::max)(stats_.submit_max_ms, waited); + // Every wait of 500 ms or more, and the first 32 of 50 ms or more. + if (waited >= 500 || (waited >= 50 && logged_waits_ < 32)) { + ++logged_waits_; + note_gate_wait("waited", what, waited); + } + return waited; + } + void leave_submit() { + if (!compile_gate_enabled()) return; + std::lock_guard lock(gate_mutex_); + if (--submits_ == 0) gate_changed_.notify_all(); + } + +private: + void taken() { + since_.store(diagnostic_ms(), std::memory_order_relaxed); + owner_.store(diagnostic_thread_id(), std::memory_order_relaxed); + } + + // Until a hold ends after `seen` releases. + void wait_release(std::uint64_t seen) { + handoff_waiters_.fetch_add(1); + { + std::unique_lock lock(handoff_mutex_); + released_.wait(lock, [&] { return releases_.load() != seen; }); + } + handoff_waiters_.fetch_sub(1); + } + + // With gate_mutex_ held. + // The creates a submission found in the driver: how many, and the compute one named last (graphics creates are + // not named). Names are ShaderLibrary strings, valid until device teardown. + struct GateWait { + std::uint32_t thread; + std::uint32_t creates; + const char* name; + const char* trigger; + std::size_t bytes; + }; + void note_gate_wait(const char* how, const GateWait& what, std::int64_t waited) const { + std::fprintf(stderr, "[rt] compile-gate: vkQueueSubmit on thread %u %s %lld ms for %u pipeline create(s) to " + "leave the driver (compute %s, %zu B SPIR-V, %s) at t=%.3f s; %llu such waits so far, " + "%lld ms in all, longest %lld ms\n", + what.thread, how, static_cast(waited), what.creates, what.name ? what.name : "-", + what.name ? what.bytes : std::size_t{0}, what.name && what.trigger ? what.trigger : "-", + double(diagnostic_ms()) / 1000.0, static_cast(stats_.submits), + static_cast(stats_.submit_ms), static_cast(stats_.submit_max_ms)); + } + + std::mutex mutex_; + std::atomic owner_{0}; + std::atomic since_{0}; + std::atomic waiting_{0}; + std::atomic releases_{0}; // unlocks so far + std::atomic handoff_waiters_{0}; + std::mutex handoff_mutex_; // leaf + std::condition_variable released_; + + std::mutex gate_mutex_; // leaf: guards the gate counts and stats + std::condition_variable gate_changed_; + std::uint32_t compiles_ = 0; // creates in the driver + std::uint32_t submits_ = 0; // submissions waiting for them or in the driver + std::atomic gate_waiter_{0}; + GateStats stats_; + unsigned logged_waits_ = 0; +}; + +// One vkQueueSubmit of a VulkanQueue: its waits, its signals and how long the call took (-1: not returned yet). +struct SubmitRecord { + static constexpr std::size_t max_waits = 6; + std::int64_t at_ms = 0; + std::int64_t took_ms = -1; + int result = 1; + VkQueue queue = VK_NULL_HANDLE; + const char* kind = ""; + VkSemaphore progress = VK_NULL_HANDLE; + std::uint64_t ticket = 0; + VkSemaphore fence = VK_NULL_HANDLE; + std::uint64_t fence_value = 0; + std::uint32_t buffers = 0; + std::uint32_t waits = 0; + std::array wait_semaphores{}; + std::array wait_values{}; +}; + class DeviceFaultDiagnostics { public: DeviceFaultDiagnostics(PFN_vkGetDeviceProcAddr get, VkDevice device, DeviceFaultExtensions enabled) @@ -254,6 +553,7 @@ class DeviceFaultDiagnostics { LEONIDA_FAULT_LOAD(vkCmdSetCheckpointNV); LEONIDA_FAULT_LOAD(vkGetQueueCheckpointDataNV); } + LEONIDA_FAULT_LOAD(vkGetSemaphoreCounterValue); #undef LEONIDA_FAULT_LOAD std::fprintf(stderr, "[rt] device-fault: enabled (fault info %s, checkpoints %s, NVIDIA diagnostics config %s)\n", vkGetDeviceFaultInfoEXT ? "on" : "unavailable", checkpoint_command() ? "on" : "unavailable", @@ -272,6 +572,141 @@ class DeviceFaultDiagnostics { std::uint64_t next_execute_call() { return ++execute_calls_; } + void set_submit_lock(const SubmitMutex* lock) { submit_lock_ = lock; } + + // Called under the submit lock, before and after the vkQueueSubmit it describes. + std::size_t begin_submit(const SubmitRecord& record) { + std::lock_guard lock(mutex_); + const std::size_t at = submit_count_++; + submits_[at % submits_.size()] = record; + return at; + } + void end_submit(std::size_t at, std::int64_t took_ms, VkResult result) { + std::lock_guard lock(mutex_); + if (submit_count_ - at > submits_.size()) return; + auto& record = submits_[at % submits_.size()]; + record.took_ms = took_ms; + record.result = int(result); + } + + // The holder of the submit lock has kept it for `held_ms`: its call chain and what was submitted last. + void report_submit_lock_holder(std::uint32_t owner, std::int64_t held_ms) { + std::fprintf(stderr, "[rt] submit-lock: thread %u has held it for %lld ms (t=%.3f s)\n", owner, + static_cast(held_ms), double(diagnostic_ms()) / 1000.0); + if (const char* name = driver_compile.name.load(std::memory_order_acquire)) { + const char* trigger = driver_compile.trigger.load(std::memory_order_relaxed); + std::fprintf(stderr, "[rt] submit-lock: vkCreateComputePipelines has been building %s (%zu B SPIR-V, %s) " + "for %lld ms\n", + name, driver_compile.bytes.load(std::memory_order_relaxed), trigger ? trigger : "?", + static_cast(diagnostic_ms() - driver_compile.since_ms.load(std::memory_order_relaxed))); + } + if (submit_lock_ && submit_lock_->gate_waiter() == owner) { + // Not in the driver: waiting at the compile gate for the create named above (SubmitMutex::CompileTurn). + std::fprintf(stderr, "[rt] submit-lock: thread %u is waiting at the compile gate, not in the driver\n", owner); + return; + } + // Every thread, the holder included: what the driver waits for may be another thread's work. No counters + // here (dump_submits would block in the driver behind the holder); the loss report has them. A long hold can + // also be a legitimate vkDeviceWaitIdle: the stacks of the first three holds, then at most one a minute. + const std::int64_t now = diagnostic_ms(); + if (stack_reports_ >= 3 && now - last_stack_report_ms_ < 60000) return; + ++stack_reports_; + last_stack_report_ms_ = now; + print_thread_stacks(0, "submit-lock hold"); + } + + // Before `semaphore` is destroyed (~VulkanFence, ~VulkanQueue): the ring stops naming it, so no report reads the + // counter of a destroyed semaphore. Waits for a report that is reading counters now. + void forget(VkSemaphore semaphore) { + if (!semaphore) return; + std::lock_guard reading(read_mutex_); + if (stalled_progress_ == semaphore) stalled_progress_ = VK_NULL_HANDLE; + std::lock_guard lock(mutex_); + for (auto& r : submits_) { + if (r.progress == semaphore) r.progress = VK_NULL_HANDLE; + if (r.fence == semaphore) r.fence = VK_NULL_HANDLE; + for (auto& wait : r.wait_semaphores) + if (wait == semaphore) wait = VK_NULL_HANDLE; + } + } + + // Once a second from the progress watch, without the submit lock: when the oldest submission in the ring that + // has not finished is 4 s old, the ring with every counter as it is now, once per such submission. + void check_submit_progress() { + std::lock_guard reading(read_mutex_); // the semaphores read below outlive this call (forget) + const std::vector records = submit_records(); + if (!vkGetSemaphoreCounterValue) return; + const std::int64_t now = diagnostic_ms(); + for (const auto& r : records) { + if (r.took_ms < 0 || r.result != VK_SUCCESS || !r.progress) continue; + std::uint64_t done = 0; + if (vkGetSemaphoreCounterValue(device_, r.progress, &done) != VK_SUCCESS) return; + if (done >= r.ticket) continue; + // Age from when vkQueueSubmit returned: the call itself may have waited at the compile gate. + if (now - (r.at_ms + r.took_ms) < 4000) return; // the oldest unfinished one is young + if (r.progress == stalled_progress_ && r.ticket == stalled_ticket_) return; + stalled_progress_ = r.progress; + stalled_ticket_ = r.ticket; + std::fprintf(stderr, "[rt] gpu-stall: %s queue %p ticket %llu submitted at t=%.3f s not done after %lld ms " + "(progress %llu)\n", + r.kind, static_cast(r.queue), static_cast(r.ticket), + double(r.at_ms) / 1000.0, static_cast(now - r.at_ms), + static_cast(done)); + dump_submits_reading(); + return; + } + } + + // The last submissions, oldest first, with every semaphore's counter now (? once the device is lost, or for a + // semaphore destroyed since). + void dump_submits() { + std::lock_guard reading(read_mutex_); + dump_submits_reading(); + } + +private: + std::vector submit_records() { + std::vector records; + std::lock_guard lock(mutex_); + const std::size_t n = std::min(submit_count_, submits_.size()); + records.reserve(n); + for (std::size_t i = submit_count_ - n; i < submit_count_; ++i) records.push_back(submits_[i % submits_.size()]); + return records; + } + + // dump_submits with read_mutex_ held. + void dump_submits_reading() { + const std::vector records = submit_records(); + // Every semaphore the ring names is non-null when recorded: null is one destroyed since (forget). + const auto counter = [&](VkSemaphore semaphore) -> std::string { + std::uint64_t value = 0; + if (!semaphore) return "destroyed"; + if (!vkGetSemaphoreCounterValue || vkGetSemaphoreCounterValue(device_, semaphore, &value) != VK_SUCCESS) + return "?"; + return std::to_string(value); + }; + const std::int64_t now = diagnostic_ms(); + for (const auto& r : records) { + std::string line = "[rt] submit-ring: t=" + std::to_string(double(r.at_ms) / 1000.0) + " s " + r.kind + + " queue=" + std::to_string(reinterpret_cast(r.queue)) + + " buffers=" + std::to_string(r.buffers) + " ticket=" + std::to_string(r.ticket) + + " progress=" + counter(r.progress) + " took=" + + (r.took_ms < 0 ? "pending(" + std::to_string(now - r.at_ms) + " ms)" + : std::to_string(r.took_ms) + " ms") + + " result=" + std::to_string(r.result); + if (r.fence || r.fence_value) + line += " signal=" + std::to_string(pipeline_handle(r.fence)) + ":" + std::to_string(r.fence_value) + + " now " + counter(r.fence); + for (std::uint32_t i = 0; i < r.waits && i < SubmitRecord::max_waits; ++i) + line += " wait=" + std::to_string(pipeline_handle(r.wait_semaphores[i])) + ":" + + std::to_string(r.wait_values[i]) + " now " + counter(r.wait_semaphores[i]); + if (r.waits > SubmitRecord::max_waits) line += " (+" + std::to_string(r.waits - SubmitRecord::max_waits) + " waits)"; + line += '\n'; + std::fputs(line.c_str(), stderr); + } + } + +public: // Accessed under the context's resource lock. Reports read the names copied into the ring instead. std::unordered_map pipeline_names; @@ -292,7 +727,16 @@ class DeviceFaultDiagnostics { static VkResult observe(DeviceFaultDiagnostics* diagnostics, VkResult result, const char* operation) noexcept { if (result == VK_ERROR_DEVICE_LOST) { - if (diagnostics) diagnostics->report(operation); + if (diagnostics) { + diagnostics->report(operation); + } else { + // Without LEONIDA_DEVICE_FAULT a loss was silent: the title only saw ~0 in its fence words. + static std::atomic logged{false}; + if (!logged.exchange(true, std::memory_order_relaxed)) + std::fprintf(stderr, "[rt] vulkan: VK_ERROR_DEVICE_LOST from %s at t=%.3f s on thread %u " + "(LEONIDA_DEVICE_FAULT=1 for the fault report)\n", + operation, double(diagnostic_ms()) / 1000.0, diagnostic_thread_id()); + } run_device_lost_hook(); } return result; @@ -354,6 +798,16 @@ class DeviceFaultDiagnostics { void report(const char* operation) noexcept { if (reported_.exchange(true, std::memory_order_relaxed)) return; std::fprintf(stderr, "[rt] device-fault: VK_ERROR_DEVICE_LOST from %s\n", operation); + try { + const std::int64_t now = diagnostic_ms(); + const std::uint32_t owner = submit_lock_ ? submit_lock_->owner() : 0; + std::fprintf(stderr, "[rt] device-fault: t=%.3f s on thread %u; submit lock held by thread %u for %lld ms\n", + double(now) / 1000.0, diagnostic_thread_id(), owner, + owner ? static_cast(now - submit_lock_->since_ms()) : 0LL); + dump_submits(); + print_thread_stacks(0, "device lost"); + } catch (...) { + } dump_dispatches(); try { std::function hook; @@ -455,6 +909,36 @@ class DeviceFaultDiagnostics { pipeline.shaders[2] ? pipeline.shaders[2] : "-"); } } + // LOCAL DIAGNOSTIC (post-load GPU faults): the work in flight is between the bottom-of-pipe checkpoint (last + // command finished) and the top-of-pipe one (last command started) of the same list. Every pipeline bound in + // that window, so the faulting program is among them; the dispatch ring above only keeps the last 64 + // dispatches of all queues, and those were from another queue in the fault this was added for. + for (std::uint32_t i = 0; i < count; ++i) { + const auto top = CheckpointMarker::decode(reinterpret_cast(data[i].pCheckpointMarker)); + if (!top.submission || !(static_cast(data[i].stage) & VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT)) + continue; + std::uint32_t from = 0; // no bottom-of-pipe checkpoint in this list: from its start + for (std::uint32_t j = 0; j < count; ++j) { + const auto bottom = CheckpointMarker::decode(reinterpret_cast(data[j].pCheckpointMarker)); + if (bottom.submission == top.submission && bottom.list == top.list && + (static_cast(data[j].stage) & VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT)) + from = bottom.command; + } + const auto& entry = recent_[top.submission % recent_.size()]; + if (entry.sequence != top.submission || entry.queue != queue || top.list >= entry.lists.size()) continue; + const auto& shaders = entry.lists[top.list].shaders; + // The pipeline bound when `from` ran, then every change up to the top-of-pipe command. + auto it = std::upper_bound(shaders.begin(), shaders.end(), from, + [](auto command, const auto& change) { return command < change.command; }); + if (it != shaders.begin()) --it; + for (; it != shaders.end() && it->command <= top.command; ++it) + std::fprintf(stderr, "[rt] device-fault: in flight (submission %u list %u, commands %u..%u): command %u " + "pipeline=0x%" PRIx64 " shaders=%s %s %s\n", + top.submission, top.list, from, top.command, unsigned(it->command), + pipeline_handle(it->pipeline.handle), it->pipeline.shaders[0] ? it->pipeline.shaders[0] : "-", + it->pipeline.shaders[1] ? it->pipeline.shaders[1] : "-", + it->pipeline.shaders[2] ? it->pipeline.shaders[2] : "-"); + } } template @@ -467,9 +951,20 @@ class DeviceFaultDiagnostics { PFN_vkGetDeviceFaultInfoEXT vkGetDeviceFaultInfoEXT = nullptr; PFN_vkCmdSetCheckpointNV vkCmdSetCheckpointNV = nullptr; PFN_vkGetQueueCheckpointDataNV vkGetQueueCheckpointDataNV = nullptr; + PFN_vkGetSemaphoreCounterValue vkGetSemaphoreCounterValue = nullptr; + const SubmitMutex* submit_lock_ = nullptr; + std::array submits_{}; // under mutex_ + std::size_t submit_count_ = 0; + unsigned stack_reports_ = 0; // report_submit_lock_holder: the progress watch's thread only + std::int64_t last_stack_report_ms_ = 0; + VkSemaphore stalled_progress_ = VK_NULL_HANDLE; // under read_mutex_ + std::uint64_t stalled_ticket_ = 0; std::atomic reported_{false}; std::atomic execute_calls_{0}; std::uint32_t sequence_ = 0; + // Held while a report reads the counters of the semaphores in the ring, and by forget before one is destroyed. + // Before mutex_; the submit path never takes it. + std::mutex read_mutex_; std::mutex mutex_; // leaf lock, guards queues_ and recent_ std::vector queues_; const bool include_roots_ = [] { diff --git a/runtime/src/vulkan_indirect_clamp.h b/runtime/src/vulkan_indirect_clamp.h index 3eb192d0f8..1822d96146 100644 --- a/runtime/src/vulkan_indirect_clamp.h +++ b/runtime/src/vulkan_indirect_clamp.h @@ -37,6 +37,7 @@ #include #include #include +#include #include #include #include @@ -161,6 +162,11 @@ class IndirectArgumentClamp { std::uint64_t zeroed = 0; std::uint64_t unclamped_calls = 0; // the fallbacks: calls the pool or the limits left to the replay std::uint64_t uncounted_calls = 0; // clamped with no counter slot free: their counters are not read back + // Mesh records before the clamp: all active ones, those with y > 1 or z > 1, and the largest y and z asked. + std::uint64_t mesh_records = 0; + std::uint64_t mesh_yz_records = 0; + std::uint32_t mesh_max_y = 0; + std::uint32_t mesh_max_z = 0; }; // One submission's clamp state: the counter slots its calls claimed, read and released together once that @@ -226,7 +232,7 @@ class IndirectArgumentClamp { VkDeviceMemory memory = VK_NULL_HANDLE; std::uint8_t* host = nullptr; std::uint32_t slots = 0; - static constexpr std::uint32_t slot_bytes = 32; // 16 bytes of counters, 16 of padding + static constexpr std::uint32_t slot_bytes = 64; // 48 bytes of counters (words 4-7 unused), 16 of padding }; 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 @@ -258,6 +264,7 @@ class IndirectArgumentClamp { std::vector free_slots_; Counters counters_{}; std::uint64_t next_report_frame_ = 0; + std::chrono::steady_clock::time_point next_mesh_report_{}; }; namespace detail { @@ -440,9 +447,13 @@ inline void IndirectArgumentClamp::release(std::vector& slots, bool read) delta.counts_clamped += words[1]; delta.over_budget += words[2]; delta.zeroed += words[3]; + delta.mesh_records += words[8]; + delta.mesh_yz_records += words[9]; + delta.mesh_max_y = std::max(delta.mesh_max_y, words[10]); + delta.mesh_max_z = std::max(delta.mesh_max_z, words[11]); // Clear after reading so a later aborted batch that reuses this slot without submitting never // double-counts a previous submission's counters. - std::memset(words, 0, 4 * sizeof(std::uint32_t)); + std::memset(words, 0, HostArea::slot_bytes); } free_slots_.push_back(slot); } @@ -450,6 +461,20 @@ inline void IndirectArgumentClamp::release(std::vector& slots, bool read) counters_.counts_clamped += delta.counts_clamped; counters_.over_budget += delta.over_budget; counters_.zeroed += delta.zeroed; + counters_.mesh_records += delta.mesh_records; + counters_.mesh_yz_records += delta.mesh_yz_records; + counters_.mesh_max_y = std::max(counters_.mesh_max_y, delta.mesh_max_y); + counters_.mesh_max_z = std::max(counters_.mesh_max_z, delta.mesh_max_z); + // One line every 10 s while mesh records are clamped: does the console's mesh dispatch use y or z? + const auto now = std::chrono::steady_clock::now(); + if (read && counters_.mesh_records && now >= next_mesh_report_) { + next_mesh_report_ = now + std::chrono::seconds(10); + std::fprintf(stderr, "[rt] indirect clamp mesh: %llu records, %llu with y > 1 or z > 1 (forced to 1), " + "max y %u, max z %u\n", + static_cast(counters_.mesh_records), + static_cast(counters_.mesh_yz_records), counters_.mesh_max_y, + counters_.mesh_max_z); + } const auto frame = submit_phases::totals().present_serial.load(std::memory_order_relaxed); if (read && calls && frame >= next_report_frame_) { next_report_frame_ = frame + 60; @@ -562,6 +587,7 @@ inline void IndirectArgumentClamp::emit(VkCommandBuffer cb, const ClampedIndirec // 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); + fn("vkCmdFillBuffer")(cb, job.buffer, job.stats_scratch_offset + 32, 16, 0); // mesh words 8-11 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; @@ -600,7 +626,7 @@ inline void IndirectArgumentClamp::emit(VkCommandBuffer cb, const ClampedIndirec 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); - VkBufferCopy copy{job.stats_scratch_offset, job.stats_offset, 4 * sizeof(std::uint32_t)}; + VkBufferCopy copy{job.stats_scratch_offset, job.stats_offset, 12 * sizeof(std::uint32_t)}; fn("vkCmdCopyBuffer")(cb, job.buffer, job.stats_buffer, 1, ©); } // The indirect command reads the records, and nothing else may read them while it does. diff --git a/runtime/src/vulkan_present.h b/runtime/src/vulkan_present.h index d494233d3a..013c9467b0 100644 --- a/runtime/src/vulkan_present.h +++ b/runtime/src/vulkan_present.h @@ -183,7 +183,7 @@ class VulkanPresenter { std::error_code created; std::filesystem::create_directories(capture_dir_, created); capture_to_disk_ = true; - capture_ = true; // the swapchain needs TRANSFER_SRC, and every frame copies into a staging buffer + capture_ = true; // provision TRANSFER_SRC and staging; disk-only copies follow the requested cadence if (const char* every = std::getenv("LEONIDA_CAPTURE_EVERY")) capture_every_ = std::max(1, std::atoi(every)); if (const char* limit = std::getenv("LEONIDA_CAPTURE_LIMIT")) capture_limit_ = std::max(1, std::atoi(limit)); std::fprintf(stderr, "[rt] present: capture on: every %d presented frame(s), at most %d, into %s\n", @@ -212,6 +212,7 @@ class VulkanPresenter { const VkDevice device = context_.device(); { std::lock_guard lock(context_.submit_mutex()); + const SubmitMutex::SubmitTurn turn(context_.submit_mutex()); // a queue operation: the compile gate context_.observe_result(vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle (present)"); // A WSI layer may perform a device-wide idle while destroying the swapchain. // Keep that implicit idle serialized with submits from every context queue. @@ -348,15 +349,9 @@ class VulkanPresenter { // Call before the first present. bool enable_capture() { std::lock_guard lock(present_mutex_); - if (!ok_) return false; splash_capture_only_ = false; - capture_ = true; - stale_ = true; - if (!recreate(vsync_, swapchain_srgb_, swapchain_hdr_req_) || (swapchain_ && !capture_buffer_)) { - capture_ = false; - return false; - } - return true; + continuous_readback_ = enable_capture_storage(); + return continuous_readback_; } // Present the shell image immediately. Keep it on screen until the window has a non-black title frame. @@ -365,7 +360,7 @@ class VulkanPresenter { // The last presented frame as the swapchain stores it (4 bytes a texel, rows tightly packed, format() order). // Waits for the frame to finish. False when nothing was presented since enable_capture(), after a present // that was skipped because the window is minimised (it returned VK_SUCCESS but showed nothing), until the next - // frame that is shown (the frame before it is not what the window was last asked to show), or when the wait fails. + // frame that is shown, on an unsampled disk-only present, or when the wait fails. bool read_back(std::vector& pixels, VkExtent2D* extent, VkFormat* format) { std::lock_guard lock(present_mutex_); if (!capture_ || !capture_ptr_ || !captured_) return false; @@ -416,6 +411,19 @@ class VulkanPresenter { } private: + // Called with present_mutex_ held. Reserving staging for the splash or rare disk samples + // is distinct from promising the caller a copy of every frame through read_back(). + bool enable_capture_storage() { + if (!ok_) return false; + capture_ = true; + stale_ = true; + if (!recreate(vsync_, swapchain_srgb_, swapchain_hdr_req_) || (swapchain_ && !capture_buffer_)) { + capture_ = false; + return false; + } + return true; + } + bool should_abort() { std::function abort; { @@ -507,14 +515,13 @@ class VulkanPresenter { if ((binding || planes) && !(format_features(format_) & VK_FORMAT_FEATURE_BLIT_DST_BIT)) return VK_ERROR_FORMAT_NOT_SUPPORTED; if (planes && !prepare_compose()) return VK_ERROR_FORMAT_NOT_SUPPORTED; - auto& vk = context_.vk; const VkDevice device = context_.device(); Frame& frame = frames_[frame_index_ % frames_.size()]; if (const VkResult waited = context_.observe_result( vkWaitForFences_(device, 1, &frame.done, VK_TRUE, UINT64_MAX), "vkWaitForFences (present)"); waited != VK_SUCCESS) return stop(waited); - // Every submit copies into the same mapped buffer, even if its frame is outside the disk capture stride. + // 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); std::uint32_t image = 0; @@ -537,6 +544,15 @@ class VulkanPresenter { // An out-of-date retry above may have given the swapchain another extent: the compose target follows it. if (planes && !prepare_compose()) return give_back(frame, VK_ERROR_FORMAT_NOT_SUPPORTED); + // The ordinal counts accepted presents, not submissions or deferred requests. Decide after + // draining the previous disk sample and any acquire/recreate retry; an unshown attempt consumes no slot. + const bool disk_sample = capture_to_disk_ && capture_written_ < capture_limit_ && + presented_ % std::uint64_t(capture_every_) == 0; + const bool inspect = splash_owner_ && capture_ptr_; + // Merely allocating a temporary splash buffer does not require a copy. In particular, a minimized + // initial splash can return before taking ownership; later ordinary frames must not become continuous. + const bool copy_frame = capture_buffer_ && ((capture_ && (disk_sample || continuous_readback_ || inspect)) || dump_.due(presented_)); + captured_ = false; // never expose a stale sample after an unsampled or unshown frame bool recorded = false; std::unique_lock tracker_lock(context_.tracker_mutex_, std::defer_lock); bool rollback_source = false; @@ -561,7 +577,8 @@ class VulkanPresenter { plane_rollbacks[i].tracked = context_.tracker_.tracked(plane_rollbacks[i].id); if (plane_rollbacks[i].tracked) plane_rollbacks[i].layout = context_.tracker_.layout(plane_rollbacks[i].id, 0); } - recorded = record_planes(frame, std::uint32_t(frame_index_ % frames_.size()), current, *planes, image); + recorded = record_planes(frame, std::uint32_t(frame_index_ % frames_.size()), current, *planes, + image, copy_frame); } } } else if (binding) { @@ -574,11 +591,11 @@ class VulkanPresenter { tracker_lock.lock(); rollback_source = context_.tracker_.tracked(source); if (rollback_source) prev_layout = context_.tracker_.layout(source, 0); - record(frame.commands, *current, source, image, source_rect); + record(frame.commands, *current, source, image, source_rect, copy_frame); recorded = true; } } else { - record_blank(frame.commands, image); + record_blank(frame.commands, image, copy_frame); recorded = true; } const auto rollback = [&] { @@ -624,7 +641,6 @@ class VulkanPresenter { const bool tearing = false; (void)tear; #endif - const bool inspect = splash_owner_ && capture_ptr_; bool show_title = false; if (inspect) { submit_info.signalSemaphoreCount = 0; // signal ready only after choosing the image the window will show @@ -633,7 +649,10 @@ class VulkanPresenter { VkResult submitted, result = VK_SUCCESS; { std::lock_guard lock(context_.submit_mutex()); - submitted = context_.observe_result(vk.vkQueueSubmit(queue_, 1, &submit_info, frame.done), + // One turn of the compile gate for the submit and the present after it: no pipeline create enters the + // driver between the two (queue_submit's own turn nests inside this one). + const SubmitMutex::SubmitTurn turn(context_.submit_mutex()); // 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(); @@ -655,6 +674,7 @@ class VulkanPresenter { } if (submitted != VK_SUCCESS) return give_back(frame, submitted); ++frame_index_; + pipeline_wait::note_present(); // a new frame's budget for waits on pipelines still being built // 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. if (result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR) { @@ -674,14 +694,12 @@ class VulkanPresenter { last_tore_ = true; ++tear_presents_; } - if (capture_to_disk_ && capture_ && capture_ptr_ && capture_written_ < capture_limit_ && - (presented_ - 1) % std::uint64_t(capture_every_) == 0) - pending_capture_ = frame.done; - } - if (capture_ && capture_ptr_) { - captured_ = true; - captured_extent_ = extent_; - captured_format_ = format_; + if (copy_frame && capture_ptr_) { // a temporary splash-only allocation may have just been released + captured_ = true; + captured_extent_ = extent_; + captured_format_ = format_; + if (disk_sample) pending_capture_ = frame.done; + } } if (result == VK_ERROR_SURFACE_LOST_KHR) { // The surface was lost during the present (display disconnected, a driver reset of the window's @@ -913,7 +931,7 @@ class VulkanPresenter { VkResult submitted; { std::lock_guard lock(context_.submit_mutex()); - submitted = context_.observe_result(vk.vkQueueSubmit(queue_, 1, &submit_info, probe_fence_), + 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(); } @@ -1034,7 +1052,7 @@ class VulkanPresenter { VkResult submitted; { std::lock_guard lock(context_.submit_mutex()); - submitted = context_.observe_result(context_.vk.vkQueueSubmit(queue_, 1, &submit_info, frame.done), + submitted = context_.observe_result(context_.queue_submit(queue_, 1, &submit_info, frame.done), "vkQueueSubmit (return present image)"); } if (submitted != VK_SUCCESS) return stop(failure); @@ -1066,6 +1084,7 @@ class VulkanPresenter { const VkDevice device = context_.device(); { std::lock_guard lock(context_.submit_mutex()); + const SubmitMutex::SubmitTurn turn(context_.submit_mutex()); // a queue operation: the compile gate // The old swapchain's images and semaphores may still be in use. context_.observe_result(vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle (present)"); release(swapchain_); @@ -1079,7 +1098,7 @@ class VulkanPresenter { } void record(VkCommandBuffer commands, const ResourceBinding& binding, ResourceId source, std::uint32_t image, - const PresentRect* source_rect) { + const PresentRect* source_rect, bool copy_frame) { auto& vk = context_.vk; const ReplayFunctions& fn = context_.replay_; vk.vkResetCommandBuffer(commands, 0); @@ -1122,7 +1141,7 @@ class VulkanPresenter { VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, sw == dw && sh == dh ? VK_FILTER_NEAREST : blit_filter(binding.format)); - finish_image(commands, image); + finish_image(commands, image, copy_frame); for (const auto& piece : pieces) detail::image_barrier(fn, commands, binding, piece.range, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, piece.layout, VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, any, @@ -1156,6 +1175,7 @@ class VulkanPresenter { return true; { std::lock_guard lock(context_.submit_mutex()); + const SubmitMutex::SubmitTurn turn(context_.submit_mutex()); // a queue operation: the compile gate // The old target may still be in use. context_.observe_result(context_.vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle (present)"); } @@ -1166,7 +1186,7 @@ class VulkanPresenter { // Records the composition of `planes` and its copy to swapchain image `image`. False, with nothing recorded and the // tracker untouched, when a view cannot be made. The caller holds the resource and tracker locks. bool record_planes(Frame& frame, std::uint32_t slot, const std::array& current, - const PresentPlanes& planes, std::uint32_t image) { + const PresentPlanes& planes, std::uint32_t image, bool copy_frame) { auto& vk = context_.vk; const ReplayFunctions& fn = context_.replay_; if (composer_->target() == VK_NULL_HANDLE || composer_->extent().width != extent_.width || @@ -1254,7 +1274,7 @@ class VulkanPresenter { blit.dstOffsets[1] = {std::int32_t(extent_.width), std::int32_t(extent_.height), 1}; vkCmdBlitImage_(commands, composer_->target(), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, images_[image], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, VK_FILTER_NEAREST); - finish_image(commands, image); + finish_image(commands, image, copy_frame); for (std::uint32_t i = 0; i < planes.count; ++i) { if (i == 1 && same) continue; for (const auto& piece : pieces[i]) @@ -1291,7 +1311,7 @@ class VulkanPresenter { } // Clears the swapchain image to opaque black. - void record_blank(VkCommandBuffer commands, std::uint32_t image) { + void record_blank(VkCommandBuffer commands, std::uint32_t image, bool copy_frame) { auto& vk = context_.vk; const ReplayFunctions& fn = context_.replay_; vk.vkResetCommandBuffer(commands, 0); @@ -1304,18 +1324,18 @@ class VulkanPresenter { VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); const VkClearColorValue black{{0.0f, 0.0f, 0.0f, 1.0f}}; vkCmdClearColorImage_(commands, images_[image], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &black, 1, &range); - finish_image(commands, image); + finish_image(commands, image, copy_frame); vk.vkEndCommandBuffer(commands); } // The swapchain image is written (TRANSFER_DST): optionally copy it to the capture buffer, then hand it to // the presentation engine. - void finish_image(VkCommandBuffer commands, std::uint32_t image) { + void finish_image(VkCommandBuffer commands, std::uint32_t image, bool copy_frame) { const ReplayFunctions& fn = context_.replay_; const VkImageSubresourceRange range{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; VkImageLayout layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; VkAccessFlags access = VK_ACCESS_TRANSFER_WRITE_BIT; - if (capture_buffer_ && (capture_ || dump_.due(presented_))) { + if (copy_frame) { // Two frames may be in flight and share `capture_buffer_`: serialize the prior frame's capture copy // before overwriting it, while moving this frame's swapchain image to TRANSFER_SRC. VkBufferMemoryBarrier capture_waw{VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER}; @@ -1512,6 +1532,7 @@ class VulkanPresenter { const VkDevice device = context_.device(); { std::lock_guard lock(context_.submit_mutex()); + const SubmitMutex::SubmitTurn turn(context_.submit_mutex()); // a queue operation: the compile gate // The old swapchain's images and semaphores may still be in use. context_.observe_result(vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle (present)"); } @@ -1819,6 +1840,7 @@ class VulkanPresenter { bool capture_ = false; present_dump::PresentDump dump_; bool dump_pq_ = false; + bool continuous_readback_ = false; // explicit enable_capture(), independent of disk sampling VkBuffer capture_buffer_ = VK_NULL_HANDLE; VkDeviceMemory capture_memory_ = VK_NULL_HANDLE; VkDeviceSize capture_size_ = 0; diff --git a/runtime/src/vulkan_present_splash.h b/runtime/src/vulkan_present_splash.h index affc9a92b2..450b06296b 100644 --- a/runtime/src/vulkan_present_splash.h +++ b/runtime/src/vulkan_present_splash.h @@ -13,7 +13,7 @@ inline bool VulkanPresenter::present_splash(ResourceId source, std::shared_ptrimage) return false; splash_binding_ = *binding; } - if (!capture_) splash_capture_only_ = enable_capture(); + if (!capture_) splash_capture_only_ = enable_capture_storage(); const auto before = presented(); if (present(source, true) != VK_SUCCESS || presented() == before) return false; const Frame& frame = frames_[(frame_index_ - 1) % frames_.size()]; @@ -61,14 +61,16 @@ inline VkResult VulkanPresenter::finish_startup_frame(Frame& frame, std::uint32_ VkSubmitInfo ready{VK_STRUCTURE_TYPE_SUBMIT_INFO}; ready.signalSemaphoreCount = 1; ready.pSignalSemaphores = &ready_[image]; - if (show_title) return context_.vk.vkQueueSubmit(queue_, 1, &ready, VK_NULL_HANDLE); + if (show_title) return context_.queue_submit(queue_, 1, &ready, VK_NULL_HANDLE); // The acquire was consumed and the title commands finished. Overwrite the same image before presenting it. - record(frame.commands, splash_binding_, splash_source_, image, nullptr); + // The inspected copy contains the black title frame. Overwrite staging with the + // splash actually shown; this is the copy an active disk/readback consumer must see. + record(frame.commands, splash_binding_, splash_source_, image, nullptr, true); result = vkResetFences_(device, 1, &frame.done); if (result != VK_SUCCESS) return result; ready.commandBufferCount = 1; ready.pCommandBuffers = &frame.commands; - return context_.vk.vkQueueSubmit(queue_, 1, &ready, frame.done); + return context_.queue_submit(queue_, 1, &ready, frame.done); } } // namespace leonida diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 5a3e569dd6..8b90a9070f 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -48,6 +48,7 @@ #include "vulkan_indirect_dispatch_count.h" #include "vulkan_indirect_clamp.h" #include "xdxr_build.h" +#include "pipeline_wait.h" #include #include @@ -61,8 +62,10 @@ #include #include #include +#include #include #include +#include #include #include @@ -860,8 +863,9 @@ struct ComputePipeline { VkPipelineLayout layout = VK_NULL_HANDLE; std::uint64_t code_base = 0; VkDescriptorSet bindless_set = VK_NULL_HANDLE; // set 0 of the layout, bound at every dispatch; null: none - // A pipeline built on first use: with `pipeline` null, `build(build_context)` returns the handle (building it if - // nobody has yet), or null when it cannot be built. Null `build`: `pipeline` is final. + // A pipeline built on first use: with `pipeline` null, `build(build_context)` returns the handle, or null when it + // cannot be built or (async_build) is still being built - it never waits for a build another thread runs, since + // prepare calls it with the resource lock held. Null `build`: `pipeline` is final. VkPipeline (*build)(void*) = nullptr; void* build_context = nullptr; bool async_build = false; // a null handle may be waiting for the compile worker @@ -869,6 +873,11 @@ struct ComputePipeline { // first use is always built where prepare() meets it. Not used with async_build. See PipelineCompiles. VkPipeline (*built)(void*) = nullptr; bool large = false; // compiled one after another with the other large ones (PipelineCompiles) + // With `build`: the submission's pre-pass (await_pipelines) asks for the pipeline and waits for it with no lock of + // the replay layer held, up to `until_ns` (pipeline_wait.h: probe, no_wait, a steady-clock time, forever). The + // handle, or null with `*pending` saying whether it is still to be built (false: it cannot be). Null: the pre-pass + // leaves the pipeline to `build`. + VkPipeline (*await)(void* context, std::int64_t until_ns, bool* pending) = nullptr; bool skipped = false; // never built on request (LEONIDA_SKIP_COMPUTE): its dispatches are dropped }; @@ -888,6 +897,7 @@ struct GraphicsPipeline { std::uint32_t strip_cut = 0; // D3D12_INDEX_BUFFER_STRIP_CUT_VALUE (0: off, 1: 0xFFFF, 2: 0xFFFFFFFF) bool mesh = false; // a mesh shader instead of a vertex shader: drawn by DispatchMesh only bool viewport_with_count = false; // pipeline uses VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT / SCISSOR_WITH_COUNT + bool depth_bounds = false; // depthBoundsTestEnable: the bounds are dynamic (vkCmdSetDepthBounds) // The same pipeline with some attachment formats VK_FORMAT_UNDEFINED, for a draw that leaves those slots // unbound (D3D12 allows it; dynamic rendering needs the formats to agree). Bit i: colour slot i, bit 8: depth // and stencil. Null when it cannot be built. @@ -900,11 +910,26 @@ struct GraphicsPipeline { // ComputePipeline::built. std::function built; bool large = false; // as ComputePipeline::large + // As ComputePipeline::await, for the variant with the `unbound` slots (unbound_slots). Null: left to `variant`. + std::function await; std::uint32_t samples = 1; // rasterizationSamples; every bound attachment must have this count bool async_build = false; bool nonunit_vertex_divisor = false; // an actual instance divisor > 1, not a zero-stride emulation }; +// The slots a draw leaves unbound that `pipeline` has a format for: the variant prepare_draw builds the draw with +// (GraphicsPipeline::variant). A render target or depth buffer that does not resolve drops the draw instead. +inline std::uint32_t unbound_slots(const Draw& draw, const GraphicsPipeline& pipeline) { + std::uint32_t unbound = 0; + const std::uint32_t bound = draw.views ? draw.views->render_target_count : 0; + for (std::size_t slot = 0; slot < pipeline.color_formats.size() && slot < 8; ++slot) + if (pipeline.color_formats[slot] != VK_FORMAT_UNDEFINED && + !(slot < bound && draw.views->render_targets[slot].resource)) + unbound |= 1u << slot; + if (pipeline.depth_format != VK_FORMAT_UNDEFINED && !draw.depth.resource) unbound |= GraphicsPipeline::unbound_depth; + return unbound; +} + // The 144-byte push-constant block every translated shader declares: s0..s31, heap base, code base. struct ShaderUserData { std::uint32_t s[32]; @@ -1116,9 +1141,13 @@ struct ReplayFunctions { PFN_vkCmdSetPrimitiveRestartEnable set_primitive_restart_enable = nullptr; PFN_vkCmdSetStencilReference set_stencil_reference = nullptr; PFN_vkCmdSetBlendConstants set_blend_constants = nullptr; + PFN_vkCmdSetDepthBounds set_depth_bounds = nullptr; // for depth-bounds pipelines only PFN_vkCmdDraw draw = nullptr; unsigned* mesh_draw_count = nullptr; // opt-in count for this submission PFN_vkCmdDrawMeshTasksEXT draw_mesh_tasks = nullptr; // VK_EXT_mesh_shader; null: mesh draws are unsupported + // ExecuteIndirect with a DISPATCH_MESH signature. Its 12-byte record is VkDrawMeshTasksIndirectCommandEXT. + PFN_vkCmdDrawMeshTasksIndirectEXT draw_mesh_tasks_indirect = nullptr; + PFN_vkCmdDrawMeshTasksIndirectCountEXT draw_mesh_tasks_indirect_count = nullptr; PFN_vkCmdDrawIndexed draw_indexed = nullptr; std::function graphics_pipeline; // The buffer and offset a console VA range starts in (from ResourceBinding::va), false when none does. `size` is @@ -1192,6 +1221,7 @@ struct ReplayFunctions { std::function prepare_indirect_clamp; std::function emit_indirect_clamp; + bool external_graphics_scope = false; // Caller supplies the rendering scope, pipeline and bindings for legacy draws. bool require_indirect_clamp = false; // an enabled device refuses an indirect if scratch preparation fails // Optional VK_KHR_acceleration_structure: BuildRaytracingAccelerationStructure. PFN_vkCmdBuildAccelerationStructuresKHR build_acceleration_structures = nullptr; @@ -1296,7 +1326,7 @@ struct Prepared { PredicateCapture predicate; std::vector predicated_copy; CountedDispatch counted_dispatch; - ClampedIndirect indirect_clamp; // ExecuteIndirect: the clamped arguments the command reads, or null + ClampedIndirect indirect_clamp; // an indirect command's clamped arguments it reads, or null ResourceBinding binding; VkImageSubresourceRange range{}; // the barrier range, or the cleared view (cleared aspects only) VkImageView view = VK_NULL_HANDLE; @@ -2561,7 +2591,9 @@ ReplayResult prepare_draw(const Draw& draw, const IndirectDrawArgs* arguments, R const ReplayFunctions& vk, PreparedDraw& p) { if (arguments) { const IndirectDrawArgs& arg = *arguments; - const VkDeviceSize record_size = draw.indexed ? sizeof(VkDrawIndexedIndirectCommand) : sizeof(VkDrawIndirectCommand); + const VkDeviceSize record_size = draw.mesh ? sizeof(VkDrawMeshTasksIndirectCommandEXT) + : draw.indexed ? sizeof(VkDrawIndexedIndirectCommand) + : sizeof(VkDrawIndirectCommand); if (!arg.argument_buffer || !arg.max_count || arg.stride < record_size || (arg.stride | arg.argument_offset | arg.count_offset) % 4 || (!arg.count_buffer && arg.count_offset)) return ReplayResult::invalid_indirect_arguments; @@ -2569,8 +2601,10 @@ ReplayResult prepare_draw(const Draw& draw, const IndirectDrawArgs* arguments, R // independently of the supplied maxDrawCount. On a device with a smaller limit an // arbitrary D3D12 count requires a GPU clamp pass; keep that case guarded for now. const bool counted = arg.count_buffer != 0; - const bool entry_available = counted ? (draw.indexed ? vk.draw_indexed_indirect_count : vk.draw_indirect_count) != nullptr - : (draw.indexed ? vk.draw_indexed_indirect : vk.draw_indirect) != nullptr; + const bool entry_available = + draw.mesh ? (counted ? vk.draw_mesh_tasks_indirect_count != nullptr : vk.draw_mesh_tasks_indirect != nullptr) + : counted ? (draw.indexed ? vk.draw_indexed_indirect_count : vk.draw_indirect_count) != nullptr + : (draw.indexed ? vk.draw_indexed_indirect : vk.draw_indirect) != nullptr; // The GPU supplies firstIndex/indexCount at execution (VUID-08798). A sized binding alone // does not guarantee a robust fetch, and the legacy binding covers the backing buffer's tail. const auto skip = [&](indirect_stats::Reason reason) { @@ -2578,11 +2612,13 @@ ReplayResult prepare_draw(const Draw& draw, const IndirectDrawArgs* arguments, R p.skipped = true; return ReplayResult::success; }; - if (draw.mesh) return skip(indirect_stats::mesh); + // A mesh draw has no topology, first instance or index buffer; its records go through the clamp pass, + // which bounds x and sets y = z = 1 (the console's mesh dispatch is one-dimensional), or it is not drawn. + if (draw.mesh && (!entry_available || !leonida::indirect_clamp_enabled())) return skip(indirect_stats::mesh); static_assert(indirect_stats::topology_supported(topology_rect_list) && !indirect_stats::topology_supported(topology_quad_list)); - if (!indirect_stats::topology_supported(draw.topology)) return skip(indirect_stats::topology); - if (!vk.draw_indirect_first_instance) return skip(indirect_stats::first_instance); + if (!draw.mesh && !indirect_stats::topology_supported(draw.topology)) return skip(indirect_stats::topology); + if (!draw.mesh && !vk.draw_indirect_first_instance) return skip(indirect_stats::first_instance); if (!entry_available) return skip(indirect_stats::entry); if (draw.indexed && !vk.bind_robust_index_view) return skip(indirect_stats::robust_index); if (arg.max_count > vk.max_draw_indirect_count) return skip(indirect_stats::count_limit); @@ -2626,6 +2662,7 @@ ReplayResult prepare_draw(const Draw& draw, const IndirectDrawArgs* arguments, R if (draw.mesh && !vk.draw_mesh_tasks) return unsupported_at(__LINE__); if (pipeline->viewport_with_count && (!vk.set_viewport_with_count || !vk.set_scissor_with_count)) return unsupported_at(__LINE__); + if (pipeline->depth_bounds && !vk.set_depth_bounds) return unsupported_at(__LINE__); if (pipeline->bindless_set && !vk.bind_descriptor_sets) return unsupported_at(__LINE__); if (pipeline->color_formats.size() > max_render_targets) return unsupported_at(__LINE__); p.graphics = pipeline; @@ -2690,6 +2727,7 @@ ReplayResult prepare_draw(const Draw& draw, const IndirectDrawArgs* arguments, R // Slots the pipeline has a format for but the draw leaves unbound take a variant whose format there is // VK_FORMAT_UNDEFINED: D3D12 discards those writes, Vulkan wants the formats to match the attachments. + // The same mask as unbound_slots, which the submission's pre-pass asked for (await_pipelines). std::uint32_t unbound = 0; if (pipeline->rectangle_variant_topology && draw.topology == pipeline->rectangle_variant_topology) unbound |= GraphicsPipeline::rectangle_stage; @@ -3243,6 +3281,114 @@ inline bool zero_clear_unavailable(const PreparedList& prepared, const ReplayFun return false; } +// A pipeline a submission needs that may still be in the making (ComputePipeline::await / GraphicsPipeline::await), +// once per pipeline and variant: collected by collect_pipeline_awaits with the caller's resource lock held (the +// lookups read the registry), waited for by await_pipelines after it is released. The pipeline states stay alive +// meanwhile: the command lists that name them hold them (D3D12 lets them go only once the call has returned). +struct PipelineAwait { + std::uintptr_t id = 0; + std::uint32_t unbound = 0; + VkPipeline (*compute)(void*, std::int64_t, bool*) = nullptr; + void* context = nullptr; + std::function graphics; + VkPipeline handle = VK_NULL_HANDLE; + bool pending = true; // not built yet (false once built, or known not to build) + void call(std::int64_t until) { + handle = compute ? compute(context, until, &pending) : graphics(unbound, until, &pending); + if (handle) pending = false; + } +}; + +// The pipelines `lists` draw and dispatch with that are not built yet: every one whose handle replay asks for at +// prepare time (ComputePipeline::build, GraphicsPipeline::variant), probed without starting anything. `seen` is the +// caller's scratch (not a thread_local: one with a destructor in gta6rt.exe adds TLS callbacks to the image, which +// the loader's TLS index-0 move must not have, pe_loader.cpp reserve_tls_index0). +inline void collect_pipeline_awaits(std::span lists, const ReplayFunctions& vk, + std::vector& out, std::unordered_set& seen) { + out.clear(); + seen.clear(); + if (!vk.compute_pipeline && !vk.graphics_pipeline) return; + std::uint64_t last = ~0ull; + const auto first_time = [&](std::uintptr_t id, std::uint32_t unbound) { + const std::uint64_t key = std::uint64_t(id) ^ (std::uint64_t(unbound) << 52); + if (key == last) return false; + last = key; + return seen.insert(key).second; + }; + const auto compute = [&](std::uintptr_t id) { + if (!id || !vk.compute_pipeline || !first_time(id, 0)) return; + const ComputePipeline* pipeline = vk.compute_pipeline(id); + if (!pipeline || pipeline->pipeline || pipeline->skipped || !pipeline->await) return; + bool pending = false; + if (pipeline->await(pipeline->build_context, pipeline_wait::probe, &pending) || !pending) return; + PipelineAwait& a = out.emplace_back(); + a.id = id; + a.compute = pipeline->await; + a.context = pipeline->build_context; + }; + for (const CommandList* list : lists) { + for (const auto& command : list->commands()) { + if (const auto* dispatch = std::get_if(&command)) { + compute(dispatch->pipeline); + } else if (const auto* ind = std::get_if(&command)) { + if (ind->kind == IndirectKind::dispatch) compute(ind->pipeline); + } else if (const auto* draw = draw_command(command).state) { // direct and stateful indirect draws + if (!draw->pipeline || !vk.graphics_pipeline) continue; + const GraphicsPipeline* pipeline = vk.graphics_pipeline(draw->pipeline); + if (!pipeline || !pipeline->await) continue; + const std::uint32_t unbound = unbound_slots(*draw, *pipeline); + if ((!unbound && pipeline->pipeline) || !first_time(draw->pipeline, unbound)) continue; + bool pending = false; + if (pipeline->await(unbound, pipeline_wait::probe, &pending) || !pending) continue; + PipelineAwait& a = out.emplace_back(); + a.id = draw->pipeline; + a.unbound = unbound; + a.graphics = pipeline->await; + } + } + } +} + +// Asks for every pipeline in `awaits` (a build each nobody has started: queued on the compile worker, or built here +// when builds are not asynchronous), then waits for the ones still being built, together at most `budget_ns` +// (negative: as long as they take) and what the frame's budget has left (pipeline_wait::take). Holds no lock while it +// waits. The ones not built by then are skipped by replay. Returns how long it waited. +inline std::int64_t await_pipelines(std::vector& awaits, std::int64_t budget_ns) { + for (PipelineAwait& a : awaits) a.call(pipeline_wait::no_wait); + std::size_t pending = 0; + for (const PipelineAwait& a : awaits) pending += a.pending; + if (!pending || budget_ns == 0) return 0; + const pipeline_wait::Grant grant = + budget_ns < 0 ? pipeline_wait::Grant{pipeline_wait::forever, 0, false} : pipeline_wait::take(budget_ns); + if (grant.ns <= 0) return 0; + const std::int64_t start = pipeline_wait::now_ns(); + const std::int64_t until = budget_ns < 0 ? pipeline_wait::forever : start + grant.ns; + auto& stats = pipeline_wait::stats(); + for (PipelineAwait& a : awaits) { + if (!a.pending) continue; + if (until != pipeline_wait::forever && pipeline_wait::now_ns() >= until) { + stats.late.fetch_add(1, std::memory_order_relaxed); // no time left for it + continue; + } + const std::int64_t began = pipeline_wait::now_ns(); + a.call(until); + stats.waited.fetch_add(1, std::memory_order_relaxed); + stats.wait_ns.fetch_add(std::uint64_t(pipeline_wait::now_ns() - began), std::memory_order_relaxed); + if (a.pending) stats.late.fetch_add(1, std::memory_order_relaxed); + } + const std::int64_t waited = pipeline_wait::now_ns() - start; + if (grant.limited) pipeline_wait::give_back(grant, grant.ns - waited); + return waited; +} + +// The budget for one submission (pipeline_wait.h): nanoseconds, negative for no limit. Strict replay waits for every +// build, so nothing is skipped. +inline std::int64_t pipeline_wait_budget_ns() { + if (strict_replay()) return -1; + const int ms = pipeline_wait::effective_submission_ms(); + return ms < 0 ? -1 : std::int64_t(ms) * 1000000; +} + // Resolves and checks every command. Nothing is written to a command buffer. // Resolve maps a ResourceId to a const ResourceBinding* (nullptr: unknown). // statistics_helpers promises a statistics segment pool at QueryReplay::plan(). Keep the default for replay() @@ -3879,6 +4025,58 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun return ReplayResult::invalid_indirect_arguments; p.source = *cnt; } + if (ind->kind != IndirectKind::dispatch && !vk.external_graphics_scope) continue; + // The clamp pass (vulkan_indirect_clamp.h): the arguments are copied on the GPU into scratch with their + // values bounded before the indirect command reads them, so a stale or garbage record left by a skipped or + // mistranslated compute pass cannot run for seconds and reset the display driver. A counted call has its + // count clamped to max_command_count too. It is a helper dispatch, so it needs the statistics segments of + // a pipeline-statistics query. Every clamp of this list shares one work budget: a list of many calls does + // not multiply the per-list limit. + const bool clamp_command_available = + ind->kind == IndirectKind::dispatch + ? vk.dispatch_indirect != nullptr + : ind->kind == IndirectKind::draw + ? (ind->count_buffer ? vk.draw_indirect_count != nullptr : vk.draw_indirect != nullptr) + : (ind->count_buffer ? vk.draw_indexed_indirect_count != nullptr + : vk.draw_indexed_indirect != nullptr); + const bool clamped = + leonida::indirect_clamp_enabled() && vk.prepare_indirect_clamp && vk.emit_indirect_clamp && + clamp_command_available && !(statistics_active && !statistics_helpers) && + vk.prepare_indirect_clamp(p.binding.buffer, p.binding.buffer_offset + ind->argument_offset, + ind->count_buffer ? p.source.buffer : VK_NULL_HANDLE, + ind->count_buffer ? p.source.buffer_offset + ind->count_offset : 0, + static_cast(ind->kind), ind->stride, ind->max_count, + p.indirect_clamp); + if (clamped) p.indirect_clamp.share_list_budget(indirect_list_budget); + // A device with the pass enabled refuses an indirect call whose clamp could not be prepared: reading the + // application's buffer is what the clamp exists to avoid. Otherwise the fallbacks below apply. + if (!clamped && vk.require_indirect_clamp) return unsupported_at(__LINE__); + // Nothing else to resolve when clamped: the clamp's scratch is the indirect buffer and its count word. + if (!clamped) { + if (ind->kind == IndirectKind::dispatch) { + if (ind->count_buffer || indirect_group_budget()) { + // Vulkan lacks vkCmdDispatchIndirectCount. Copy the GPU-visible commands to private scratch + // and replace commands past min(count, max_count) with zero-group dispatches - or, with + // LEONIDA_INDIRECT_GROUP_BUDGET and no count buffer, keep the whole batch inside its work + // budget. `source` is the count binding, null without one. + if (!ind->pipeline || !vk.dispatch_indirect || !vk.prepare_counted_dispatch || + !vk.emit_counted_dispatch || (statistics_active && !statistics_helpers) || + !vk.prepare_counted_dispatch(p.binding.buffer, p.binding.buffer_offset + ind->argument_offset, + p.source.buffer, p.source.buffer_offset + ind->count_offset, + ind->stride, ind->max_count, p.counted_dispatch)) + return unsupported_at(__LINE__); + } else if (!vk.dispatch_indirect) { + return unsupported_at(__LINE__); + } + } else if (!clamp_command_available) { + // A legacy graphics indirect draw is still emitted (a caller that opened its own rendering scope + // around the replay, as the tests do); without vkCmdDrawIndirect[Count] there is nothing to emit. + return unsupported_at(__LINE__); + } + } + // 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 && 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); @@ -3890,28 +4088,6 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (!found) return unresolved_at(__LINE__); if (pipeline->bindless_set && !vk.bind_descriptor_sets) return unsupported_at(__LINE__); } - if (ind->kind == IndirectKind::dispatch && vk.require_indirect_clamp) { - if (!ind->pipeline || !vk.dispatch_indirect || !vk.prepare_indirect_clamp || !vk.emit_indirect_clamp || - (statistics_active && !statistics_helpers) || - !vk.prepare_indirect_clamp(p.binding.buffer, p.binding.buffer_offset + ind->argument_offset, - p.source.buffer, p.source.buffer_offset + ind->count_offset, indirect_clamp_dispatch, - ind->stride, ind->max_count, p.indirect_clamp)) - return unsupported_at(__LINE__); - p.indirect_clamp.share_list_budget(indirect_list_budget); - } else if (ind->kind == IndirectKind::dispatch && (ind->count_buffer || indirect_group_budget())) { - // Vulkan lacks vkCmdDispatchIndirectCount. Copy the GPU-visible commands to private scratch - // and replace commands past min(count, max_count) with zero-group dispatches. - if (!ind->pipeline || !vk.dispatch_indirect || !vk.prepare_counted_dispatch || - !vk.emit_counted_dispatch || (statistics_active && !statistics_helpers) || - !vk.prepare_counted_dispatch(p.binding.buffer, p.binding.buffer_offset + ind->argument_offset, - p.source.buffer, p.source.buffer_offset + ind->count_offset, - ind->stride, ind->max_count, p.counted_dispatch)) - return unsupported_at(__LINE__); - } else if (ind->kind == IndirectKind::dispatch && !vk.dispatch_indirect) { - return unsupported_at(__LINE__); - } - // Legacy graphics IR carries no graphics state. Validate its resource ranges above, - // but never emit it; stateful graphics indirects use Draw and its rendering scope. } else if (const auto* build = std::get_if(&command)) { p.khr_instances = 0; if (vk.xdxr_check) { @@ -4052,19 +4228,49 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (const auto r = detail::prepare_quad_indices(*draw.state, vk, prepared_draw); r != ReplayResult::success) return r; } - if (draw.arguments && !prepared_draw.skipped && vk.require_indirect_clamp) { - const auto& arg = *draw.arguments; - if (!vk.prepare_indirect_clamp || !vk.emit_indirect_clamp || (statistics_active && !statistics_helpers) || - !vk.prepare_indirect_clamp(prepared_draw.indirect_buffer, prepared_draw.indirect_offset, - prepared_draw.indirect_count_buffer, prepared_draw.indirect_count_offset, - draw.state->indexed ? indirect_clamp_draw_indexed : indirect_clamp_draw, - arg.stride, arg.max_count, p.indirect_clamp)) + // 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 + // then reads that scratch. Recorded in this command's Prepared so the emit phase records the pass before + // vkCmdBeginRendering - outside the scope and outside a pipeline-statistics query. A draw that was already + // dropped, or whose indirect entry point or scratch is missing, keeps the application's argument buffer. + if (draw.arguments && !prepared_draw.skipped) { + const IndirectDrawArgs& arg = *draw.arguments; + const ResourceBinding* args_of = resolve(arg.argument_buffer); + const ResourceBinding* count = arg.count_buffer ? resolve(arg.count_buffer) : nullptr; + const bool indexed = draw.state->indexed; + const bool mesh = draw.state->mesh; + const bool clamp_command_available = + mesh ? (arg.count_buffer ? vk.draw_mesh_tasks_indirect_count != nullptr + : vk.draw_mesh_tasks_indirect != nullptr) + : arg.count_buffer + ? (indexed ? vk.draw_indexed_indirect_count != nullptr : vk.draw_indirect_count != nullptr) + : (indexed ? vk.draw_indexed_indirect != nullptr : vk.draw_indirect != nullptr); + const bool clamped = + args_of && args_of->buffer && clamp_command_available && leonida::indirect_clamp_enabled() && + vk.prepare_indirect_clamp && vk.emit_indirect_clamp && !(statistics_active && !statistics_helpers) && + vk.prepare_indirect_clamp(args_of->buffer, args_of->buffer_offset + arg.argument_offset, + count ? count->buffer : VK_NULL_HANDLE, + count ? count->buffer_offset + arg.count_offset : 0, + static_cast(mesh ? IndirectKind::dispatch_mesh + : indexed ? IndirectKind::draw_indexed + : IndirectKind::draw), + arg.stride, arg.max_count, p.indirect_clamp); + if (clamped) { + // Clamped: p.indirect_clamp names the scratch this draw reads; nothing else to resolve. Its budget + // is the list's (one per command list, shared with the legacy ExecuteIndirect clamps above), and + // the prepared draw carries the clamped arguments too. + p.indirect_clamp.share_list_budget(indirect_list_budget); + prepared_draw.indirect_buffer = p.indirect_clamp.buffer; + prepared_draw.indirect_offset = p.indirect_clamp.offset; + prepared_draw.indirect_count_buffer = p.indirect_clamp.count_buffer; + prepared_draw.indirect_count_offset = p.indirect_clamp.count_offset; + } else if (mesh) { + // Unclamped, a mesh record's y and z are whatever the title left there: not drawn. + indirect_stats::skip(indirect_stats::Event::replay_skip, indirect_stats::mesh); + prepared_draw.skipped = true; + } else if (vk.require_indirect_clamp) { return unsupported_at(__LINE__); - p.indirect_clamp.share_list_budget(indirect_list_budget); - prepared_draw.indirect_buffer = p.indirect_clamp.buffer; - prepared_draw.indirect_offset = p.indirect_clamp.offset; - prepared_draw.indirect_count_buffer = p.indirect_clamp.count_buffer; - prepared_draw.indirect_count_offset = p.indirect_clamp.count_offset; + } } } } @@ -4387,13 +4593,8 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ // draw's own rendering scope begins. The index expansion of an indexed quad list runs here too: outside the // rendering scope, and between the segments so that no query counts its dispatch (D3D-162). It stays inside // the predicate, which skips it together with its draw. - if (p.indirect_clamp.buffer) { - 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(); - } else if (!p.counted_dispatch.indirect && (raster.state || std::holds_alternative(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) vk.emit_quad_indices(command_buffer, prepared.draws[p.draw].quad_indices); @@ -4998,17 +5199,64 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ VK_PIPELINE_STAGE_TRANSFER_BIT); vk.copy_buffer(command_buffer, p.source.buffer, p.binding.buffer, 1, p.buffer_copies.data()); } else if (const auto* ind = std::get_if(&command)) { - if (ind->kind != IndirectKind::dispatch) { + if (ind->kind != IndirectKind::dispatch && !vk.external_graphics_scope) { indirect_stats::skip(indirect_stats::Event::replay_skip, indirect_stats::stateless); continue; } + // The clamp pass (vulkan_indirect_clamp.h) runs before anything reads the indirect arguments, and before + // the drawing scope an indirect draw opens around itself. It is a helper dispatch: a pipeline-statistics + // query must not count it, and it runs even under a false predicate (the draw it feeds may be the one + // the predicate discards, and a later command may read the same scratch). + const bool clamped = p.indirect_clamp.buffer != VK_NULL_HANDLE; + if (clamped) { + 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(); + } + // What the indirect command reads: the clamped scratch, the application's own buffer, or for a counted + // DISPATCH (Vulkan has no vkCmdDispatchIndirectCount, and LEONIDA_INDIRECT_GROUP_BUDGET packs a batch + // without one too) the zero-filled copy the replay made. + const bool counted_dispatch = !clamped && p.counted_dispatch.indirect; + const VkBuffer indirect_buffer = clamped ? p.indirect_clamp.buffer + : counted_dispatch ? p.counted_dispatch.indirect + : p.binding.buffer; + const VkDeviceSize arguments = clamped ? p.indirect_clamp.offset + : counted_dispatch ? p.counted_dispatch.offset + : p.binding.buffer_offset + ind->argument_offset; + const VkBuffer count_buffer = clamped ? p.indirect_clamp.count_buffer : p.source.buffer; + const VkDeviceSize count_offset = clamped ? p.indirect_clamp.count_offset : p.source.buffer_offset + ind->count_offset; + const std::uint32_t records = clamped ? p.indirect_clamp.records : ind->max_count; + const std::uint32_t stride = clamped ? p.indirect_clamp.stride + : counted_dispatch ? std::uint32_t(sizeof(VkDispatchIndirectCommand)) + : ind->stride; + // 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 (ind->count_buffer) { + if (ind->kind == IndirectKind::draw) + vk.draw_indirect_count(command_buffer, indirect_buffer, arguments, count_buffer, count_offset, + records, stride); + else + vk.draw_indexed_indirect_count(command_buffer, indirect_buffer, arguments, count_buffer, + count_offset, records, stride); + } else if (ind->kind == IndirectKind::draw) { + vk.draw_indirect(command_buffer, indirect_buffer, arguments, records, stride); + } else { + vk.draw_indexed_indirect(command_buffer, indirect_buffer, arguments, records, stride); + } + continue; + } if (ind->pipeline && !p.pipeline.pipeline && (p.pipeline.async_build || p.pipeline.skipped)) continue; if constexpr (Checkpoints) checkpoints->dispatch(command_buffer, i, p.pipeline.pipeline, ind->pipeline, ind->user_data, {}, true, - ind->argument_buffer, ind->argument_offset, ind->count_buffer, - ind->count_offset, ind->max_count, ind->stride); - const VkDeviceSize arguments = p.binding.buffer_offset + ind->argument_offset; - if (p.counted_dispatch.indirect) { + reinterpret_cast(indirect_buffer), + clamped || counted_dispatch ? arguments : ind->argument_offset, + ind->count_buffer ? reinterpret_cast(count_buffer) : 0, + clamped ? count_offset : ind->count_offset, records, stride); + if (counted_dispatch) { // No D3D12 query must count this internal compute pass as an application dispatch. end_statistics(); vk.emit_counted_dispatch(command_buffer, p.counted_dispatch); @@ -5028,13 +5276,8 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ vk.push_constants(command_buffer, p.pipeline.layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(data), &data); } - for (std::uint32_t k = 0; k < ind->max_count; ++k) { - vk.dispatch_indirect(command_buffer, - p.indirect_clamp.buffer ? p.indirect_clamp.buffer : - p.counted_dispatch.indirect ? p.counted_dispatch.indirect : p.binding.buffer, - (p.indirect_clamp.buffer ? p.indirect_clamp.offset + VkDeviceSize(k) * p.indirect_clamp.stride - : p.counted_dispatch.indirect ? p.counted_dispatch.offset + VkDeviceSize(k) * 12 - : arguments + VkDeviceSize(k) * ind->stride)); + for (std::uint32_t k = 0; k < records; ++k) { + vk.dispatch_indirect(command_buffer, indirect_buffer, arguments + VkDeviceSize(k) * stride); } } else if (const auto* xdxr_build = std::get_if(&command); xdxr_build && vk.xdxr_record) { @@ -5156,6 +5399,16 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ 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); @@ -5265,6 +5518,12 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ 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], @@ -5279,14 +5538,29 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ 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); } - const auto stride = p.indirect_clamp.buffer ? p.indirect_clamp.stride : arg.stride; - if (arg.count_buffer) { + // 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, d.indirect_buffer, d.indirect_offset, d.indirect_count_buffer, - d.indirect_count_offset, arg.max_count, stride); + 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, d.indirect_buffer, d.indirect_offset, arg.max_count, stride); + 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); diff --git a/runtime/test/compile_helper_test.cpp b/runtime/test/compile_helper_test.cpp new file mode 100644 index 0000000000..7ef8d176e6 --- /dev/null +++ b/runtime/test/compile_helper_test.cpp @@ -0,0 +1,176 @@ +// The compile helper's file protocol (shims/d3d12_compile_helper.h): request lines, their order, and the markers that +// keep two processes from compiling one entry at once. No Vulkan, no helper process. +#include "../shims/d3d12_compile_helper.h" + +#include +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; +namespace helper = rt::d3d12::compile_helper; + +#define CHECK(condition) do { \ + if (!(condition)) { \ + std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); \ + return 1; \ + } \ +} while (0) + +static int test_lines() { + const auto line = helper::parse_request(helper::format_request("fspx_compute/lib_cs_00001_ab", 4096)); + CHECK(line.name == "fspx_compute/lib_cs_00001_ab" && line.priority == 4096); + const auto bare = helper::parse_request("name only"); + CHECK(bare.name == "name only" && bare.priority == 0); // an older writer's request is urgent + return 0; +} + +static int test_paths() { + const fs::path file = fs::path("J") / "cs-0123456789abcdef.bin"; + CHECK(helper::request_path(file) == fs::path("J") / "requests" / "cs-0123456789abcdef.req"); + CHECK(helper::failed_path(file) == fs::path("J") / "requests" / "cs-0123456789abcdef.failed"); + CHECK(helper::building_path(file) == fs::path("J") / "requests" / "cs-0123456789abcdef.building"); + return 0; +} + +static int test_order(const fs::path& dir) { + const auto requests = dir / "requests"; + fs::create_directories(requests); + const auto now = fs::file_time_type::clock::now(); + const auto put = [&](const char* stem, const std::string& line, std::chrono::seconds age) { + const auto path = requests / (std::string(stem) + ".req"); + std::ofstream(path, std::ios::binary) << line << "\n"; + fs::last_write_time(path, now - age); + }; + put("cs-0000000000000001", helper::format_request("warm-old", 500000), std::chrono::seconds(30)); + put("cs-0000000000000002", helper::format_request("dispatch-new", 0), std::chrono::seconds(1)); + put("cs-0000000000000003", helper::format_request("dispatch-old", 0), std::chrono::seconds(20)); + put("cs-0000000000000004", helper::format_request("warm-small", 1000), std::chrono::seconds(5)); + std::ofstream(requests / "cs-0000000000000005.failed") << "not a request\n"; + const auto list = helper::list_requests(requests); + CHECK(list.size() == 4); + // Urgent (dispatch) first, oldest first among equals, then warm-ups by size. + CHECK(list[0].name == "dispatch-old" && list[1].name == "dispatch-new"); + CHECK(list[2].name == "warm-small" && list[3].name == "warm-old"); + CHECK(list[0].stem == "cs-0000000000000003"); + return 0; +} + +static int test_markers(const fs::path& dir) { + const auto file = dir / "cs-00000000000000aa.bin"; + CHECK(helper::mark_building(file)); + CHECK(!helper::mark_building(file)); // this process has it already + helper::unmark_building(file); + CHECK(!fs::exists(helper::building_path(file))); // the held handle's close removes the lock file + CHECK(helper::mark_building(file)); + helper::unmark_building(file); + // A marker left behind names a process that no longer holds it (a killed helper) and is taken over: it is named + // after this very process, which is the reused process id that used to make it look busy forever. + std::ofstream(helper::building_path(file), std::ios::binary | std::ios::trunc) + << std::to_string(GetCurrentProcessId()) << "\n"; + CHECK(fs::exists(helper::building_path(file))); + CHECK(helper::mark_building(file)); + helper::unmark_building(file); + CHECK(!fs::exists(helper::building_path(file))); + // A lock file another opener holds is a live build: no claim, and nothing removes it. + const HANDLE held = CreateFileW(helper::building_path(file).c_str(), GENERIC_WRITE, 0, nullptr, CREATE_NEW, + FILE_ATTRIBUTE_NORMAL, nullptr); + CHECK(held != INVALID_HANDLE_VALUE); + CHECK(!helper::mark_building(file)); + CHECK(fs::exists(helper::building_path(file))); + CloseHandle(held); + fs::remove(helper::building_path(file)); + CHECK(helper::mark_building(file)); + helper::unmark_building(file); + return 0; +} + +// What state() answers for a request the helper has taken: no .req and no .failed means it is not coming (the helper +// removes .req before it writes .failed and before the build that writes the journal file), so it is failed rather +// than pending for as long as the helper lives. +static int test_state(const fs::path& dir) { + auto& client = helper::Client::instance(); + client.pretend_helper_running_for_test(); // no helper process is started + const leonida::cached_pso::Identity identity; + const auto file = dir / "cs-00000000000000bb.bin"; + std::string why; + CHECK(client.request(file, "fspx_compute/lib_cs_00001", 4000, identity, &why)); + CHECK(fs::exists(helper::request_path(file))); + CHECK(client.state(file, identity, &why) == helper::Client::State::pending); + // A bump of the priority keeps a .failed: it is the answer to this same request. + helper::write_line(helper::failed_path(file), "no compute entry of that name"); + CHECK(client.request(file, "fspx_compute/lib_cs_00001", 0, identity, &why)); + CHECK(fs::exists(helper::failed_path(file))); + CHECK(helper::read_line(helper::failed_path(file)) == "no compute entry of that name"); + why.clear(); + CHECK(client.state(file, identity, &why) == helper::Client::State::failed); + CHECK(why.find("no compute entry of that name") != std::string::npos); + // A fresh request drops an older failure, so asking again can retry. + CHECK(client.request(file, "fspx_compute/lib_cs_00001", 0, identity, &why)); + CHECK(!fs::exists(helper::failed_path(file))); + // .req gone, no .failed, no journal file: failed. + const auto gone = dir / "cs-00000000000000cc.bin"; + CHECK(client.request(gone, "fspx_compute/lib_cs_00002", 0, identity, &why)); + CHECK(client.state(gone, identity, &why) == helper::Client::State::pending); + fs::remove(helper::request_path(gone)); + why.clear(); + CHECK(client.state(gone, identity, &why) == helper::Client::State::failed); + CHECK(!why.empty()); + // .req gone because the helper has started building it (it holds the lock file): pending, also past the pending + // bound, since giving up would only start the same build in the game. Failed once the lock is let go with no file. + const auto building = dir / "cs-00000000000000ee.bin"; + SetEnvironmentVariableA("LEONIDA_COMPILE_HELPER_PENDING_MS", "100"); + CHECK(client.request(building, "fspx_compute/lib_cs_00004", 0, identity, &why)); + const HANDLE lock = CreateFileW(helper::building_path(building).c_str(), GENERIC_WRITE, 0, nullptr, CREATE_NEW, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, nullptr); + CHECK(lock != INVALID_HANDLE_VALUE); + fs::remove(helper::request_path(building)); + CHECK(helper::building_held(building)); + CHECK(client.state(building, identity, &why) == helper::Client::State::pending); + std::this_thread::sleep_for(std::chrono::milliseconds(250)); + CHECK(client.state(building, identity, &why) == helper::Client::State::pending); + CloseHandle(lock); + CHECK(!helper::building_held(building)); + why.clear(); + CHECK(client.state(building, identity, &why) == helper::Client::State::failed); + SetEnvironmentVariableA("LEONIDA_COMPILE_HELPER_PENDING_MS", nullptr); + return 0; +} + +// A pending request the helper never answers is failed after LEONIDA_COMPILE_HELPER_PENDING_MS, so a skipped dispatch +// becomes a build here instead of never running. +static int test_pending_bound(const fs::path& dir) { + auto& client = helper::Client::instance(); + client.pretend_helper_running_for_test(); + const leonida::cached_pso::Identity identity; + const auto file = dir / "cs-00000000000000dd.bin"; + SetEnvironmentVariableA("LEONIDA_COMPILE_HELPER_PENDING_MS", "150"); + std::string why; + CHECK(client.request(file, "fspx_compute/lib_cs_00003", 0, identity, &why)); + CHECK(client.state(file, identity, &why) == helper::Client::State::pending); + std::this_thread::sleep_for(std::chrono::milliseconds(300)); + why.clear(); + CHECK(client.state(file, identity, &why) == helper::Client::State::failed); + CHECK(why.find("150 ms") != std::string::npos); + SetEnvironmentVariableA("LEONIDA_COMPILE_HELPER_PENDING_MS", nullptr); + return 0; +} + +int main() { + const auto dir = fs::temp_directory_path() / + ("leonida_compile_helper_test_" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())); + std::error_code ec; + fs::create_directories(dir, ec); + int failed = test_lines(); + if (!failed) failed = test_paths(); + if (!failed) failed = test_order(dir); + if (!failed) failed = test_markers(dir); + if (!failed) failed = test_state(dir); + if (!failed) failed = test_pending_bound(dir); + fs::remove_all(dir, ec); + if (failed) return failed; + std::printf("compile_helper_test: ok\n"); + return 0; +} diff --git a/runtime/test/d3d12_compute_journal_test.cpp b/runtime/test/d3d12_compute_journal_test.cpp new file mode 100644 index 0000000000..f250767595 --- /dev/null +++ b/runtime/test/d3d12_compute_journal_test.cpp @@ -0,0 +1,153 @@ +// Exercise one production compute PSO in each invocation. The same authored module, root signature and device +// should give the same journal key in separate cold/warm processes. The readback proves the dispatch actually ran; +// a journal hit or write is a separate observation from the production runtime, not inferred from these words. +#include "vk_test_device.h" +#include "d3d12_test_shaders.h" +#include "shader_fixture_path.h" +#include "test_temp_dir.h" +#include "../shims/d3d12_com.h" +#include "../src/shader_library.h" + +#include +#include +#include +#include + +using namespace d3d12test; + +#define CHECK(expr) do { if (!(expr)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #expr); return 1; } } while (0) + +namespace { +int dispatch_once(ID3D12Device* dev, const std::vector& container, UINT expected_sum) { + D3D12_ROOT_PARAMETER param{}; + param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; + root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + root_desc.Desc_1_0 = {1, ¶m, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + const auto bytes = serialize_root_signature(root_desc); + CHECK(!bytes.empty()); + Ref root; + CHECK(SUCCEEDED(dev->CreateRootSignature(0, bytes.data(), bytes.size(), IID_PPV_ARGS(&root.p)))); + D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature = root.p; + desc.CS = {container.data(), container.size()}; + Ref pso; + CHECK(SUCCEEDED(dev->CreateComputePipelineState(&desc, IID_PPV_ARGS(&pso.p)))); + + using Counters = std::array; + const auto buffer = [&](Ref& dst, D3D12_HEAP_TYPE type, D3D12_RESOURCE_STATES state, + D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) { + const D3D12_HEAP_PROPERTIES heap{type}; + const auto resource = buffer_desc(sizeof(Counters), flags); + return SUCCEEDED(dev->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &resource, state, nullptr, + IID_PPV_ARGS(&dst.p))); + }; + Ref upload, result, readback; + CHECK(buffer(upload, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ)); + CHECK(buffer(result, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)); + CHECK(buffer(readback, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST)); + const D3D12_RANGE none{0, 0}, both{0, sizeof(Counters)}; + void* mapped = nullptr; + CHECK(SUCCEEDED(upload->Map(0, &none, &mapped)) && mapped); + std::memset(mapped, 0, sizeof(Counters)); + upload->Unmap(0, &both); + + constexpr auto type = D3D12_COMMAND_LIST_TYPE_COMPUTE; + const D3D12_COMMAND_QUEUE_DESC queue_desc{type}; + Ref queue; + Ref allocator; + Ref list; + Ref fence; + CHECK(SUCCEEDED(dev->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + CHECK(SUCCEEDED(dev->CreateCommandAllocator(type, IID_PPV_ARGS(&allocator.p)))); + CHECK(SUCCEEDED(dev->CreateCommandList(0, type, allocator.p, nullptr, IID_PPV_ARGS(&list.p)))); + CHECK(SUCCEEDED(dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + + list->CopyBufferRegion(result.p, 0, upload.p, 0, sizeof(Counters)); + const auto ready = transition(result.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + list->ResourceBarrier(1, &ready); + list->SetComputeRootSignature(root.p); + list->SetPipelineState(pso.p); + const auto va = result->GetGPUVirtualAddress(); + CHECK(va != 0); + list->SetComputeRootUnorderedAccessView(0, va); + list->Dispatch(4, 1, 1); // each group adds 1 to counter 0 and groupID.x + the authored term to counter 1 + const auto copy = transition(result.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, ©); + list->CopyBufferRegion(readback.p, 0, result.p, 0, sizeof(Counters)); + CHECK(SUCCEEDED(list->Close())); + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + CHECK(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); + CHECK(SUCCEEDED(queue->Signal(fence.p, 1))); + CHECK(SUCCEEDED(fence->SetEventOnCompletion(1, nullptr))); + mapped = nullptr; + CHECK(SUCCEEDED(readback->Map(0, &both, &mapped)) && mapped); + Counters got{}; + std::memcpy(got.data(), mapped, sizeof(got)); + readback->Unmap(0, &none); + if (got[0] != 4 || got[1] != expected_sum) { + std::fprintf(stderr, "compute journal: expected (4,%u), got (%u,%u)\n", expected_sum, got[0], got[1]); + return 1; + } + return 0; +} +} // namespace + +int main(int argc, char** argv) { + const bool second = argc == 2 && std::strcmp(argv[1], "--second-shader") == 0; + if (argc != 1 && !second) { + std::fputs("usage: d3d12_compute_journal_test [--second-shader]\n", stderr); + return 2; + } + // One additional constant per group in the second module: (1+2+3+4) versus (2+3+4+5). + const UINT expected_sum = second ? 14u : 10u; + const testfiles::ScratchDir scratch("leonida_compute_journal_test"); + // Default CTest runs use disposable caches. An explicit cache directory lets the host preserve the exact + // same state for the second process; never infer a hit from runtime duration. + if (!GetEnvironmentVariableW(L"LEONIDA_PIPELINE_CACHE_DIR", nullptr, 0)) { + CHECK(SetEnvironmentVariableW(L"LEONIDA_PIPELINE_CACHE_DIR", (scratch.path() / "cache").c_str())); + } + { + vktest::Device vk; + vk.request_buffer_device_address = true; + const auto status = vk.initialize(); + if (status == vktest::DeviceStatus::unavailable) return 77; + CHECK(status == vktest::DeviceStatus::ready); + if (!vk.buffer_device_address || !vk.pipeline_cache_control_enabled()) { + std::puts("SKIP: requires bufferDeviceAddress and enabled Vulkan 1.3 pipelineCreationCacheControl"); + return 77; + } + const auto program = fssm_program({second ? 0x4a435332u : 0x4a435331u, 0x10203040u}); + const auto container = shader_container(program); + const auto shader = vktest::shader_fixture_path(second ? LEONIDA_TEST_COUNTER_V2_SPV : LEONIDA_TEST_COUNTER_SPV); + CHECK(testfiles::copy_file(shader, scratch.path() / "counter.spv")); + std::ofstream index(scratch.path() / "index.json", std::ios::binary); + index << "{\"counter\":{\"stage\":\"cs\",\"fssm_sha256\":\"" << leonida::sha256_hex(program) + << "\",\"bindings\":[],\"push_constant_bytes\":144,\"local_size\":[1,1,1]," + "\"uses_code_base\":false,\"wave64\":false}}"; + index.close(); + CHECK(index); + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = vk.instance_proc; + info.instance = vk.instance; + info.physical = vk.physical; + info.device = vk.device; + info.queue = vk.queue; + info.queue_family = vk.family; + info.buffer_device_address = vk.buffer_device_address; + info.pipeline_cache_control = vk.pipeline_cache_control_enabled(); + info.shader_dir = scratch.path().string(); + Ref dev; + CHECK(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&dev.p)))); + if (rt::d3d12::device_max_push_constants_size(dev.p) < 144) { + std::puts("SKIP: authored shader requires 144 push-constant bytes"); + return 77; + } + CHECK(dispatch_once(dev.p, container, expected_sum) == 0); + } + CHECK(vktest::validation_error_count() == 0); // includes device teardown + std::printf("compute journal: direct Dispatch(4,1,1) copied both expected words (4,%u)\n", expected_sum); + return 0; +} diff --git a/runtime/test/d3d12_compute_test.cpp b/runtime/test/d3d12_compute_test.cpp index e1dcef0fdb..20abc5ba2e 100644 --- a/runtime/test/d3d12_compute_test.cpp +++ b/runtime/test/d3d12_compute_test.cpp @@ -495,6 +495,14 @@ int main() { D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&inside.p)))); EXPECT(inside->GetGPUVirtualAddress() + (1u << 20) <= capped_arena); + // The existing buffer and the reserved range prevent a contiguous arena-sized allocation. + // A valid default buffer can still use a dedicated allocation and report a usable relative VA. + const auto no_slice = buffer_desc(capped_arena, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + Ref dedicated; + EXPECT(SUCCEEDED(capped->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &no_slice, + D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&dedicated.p)))); + EXPECT(dedicated->GetGPUVirtualAddress() >= capped_arena); EXPECT(capped->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &too_large, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&past.p)) == E_OUTOFMEMORY && !past.p); std::printf("arena: %llu MiB (device limits: maxBufferSize %llu MiB, maxMemoryAllocationSize %llu MiB); " diff --git a/runtime/test/d3d12_indirect_rt_test.cpp b/runtime/test/d3d12_indirect_rt_test.cpp index 3a58e48c0a..04cd271ca3 100644 --- a/runtime/test/d3d12_indirect_rt_test.cpp +++ b/runtime/test/d3d12_indirect_rt_test.cpp @@ -1,12 +1,18 @@ // Real GPU test for: -// 1) D3D12 draw-signature creation and a native Vulkan counted-draw pixel reference. -// The pixel reference tests suballocated argument/count offsets, not D3D12 command replay. +// Real GPU test for: +// 1) ExecuteIndirect with CountBuffer (ID3D12Device::CreateCommandSignature + +// ID3D12GraphicsCommandList::ExecuteIndirect -> vkCmdDrawIndirectCount, Vulkan 1.2 core), and the argument clamp +// pass (runtime/src/vulkan_indirect_clamp.h): a draw record asking for four billion instances is clamped on the +// GPU and renders the same triangle as the in-range one, instead of running until the host resets the driver. +// The same pixel reference is also run natively: D3D12 draw-signature creation and a Vulkan counted-draw pixel +// reference over suballocated argument/count offsets, independent of the D3D12 command replay. // 2) Hardware Ray Tracing / BVH (ID3D12Device5::GetRaytracingAccelerationStructurePrebuildInfo + // ID3D12GraphicsCommandList4::BuildRaytracingAccelerationStructure BLAS + TLAS + RayQueryKHR // hit vs. miss; clean SKIP on GPUs without VK_KHR_acceleration_structure / VK_KHR_ray_query). // Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation (Core + Synchronization Validation). #include "../shims/d3d12_com.h" +#include "../src/vulkan_indirect_clamp.h" #include "vulkan_loader.h" #include "../src/vulkan_device_filter.h" @@ -500,6 +506,51 @@ int main() { cbai.commandBufferCount = 1; vkAllocateCommandBuffers(vk_dev, &cbai, &cb); + leonida::ReplayFunctions rf{}; + rf.external_graphics_scope = true; // bind the graphics pipeline inside our own rendering scope below + rf.draw_indirect_count = vkCmdDrawIndirectCount; + // The argument clamp pass (runtime/src/vulkan_indirect_clamp.h), installed as gta6rt installs it: every + // record of the ExecuteIndirect is copied on the GPU into scratch with its values bounded before the draw + // reads it, so a record left by a skipped compute pass cannot ask for four billion vertices or instances. + // A device without bufferDeviceAddress keeps the raw path. + VkPhysicalDeviceMemoryProperties mem_props{}; + reinterpret_cast( + gipa(instance, "vkGetPhysicalDeviceMemoryProperties"))(physical, &mem_props); + const auto clamp_allocate = [&](const VkMemoryRequirements& requirements) -> VkDeviceMemory { + VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO}; + flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; + VkMemoryAllocateInfo ai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, &flags}; + ai.allocationSize = requirements.size; + const auto allocate = reinterpret_cast(gdpa(vk_dev, "vkAllocateMemory")); + for (const std::uint32_t type : leonida::memory_type_order(mem_props, requirements.memoryTypeBits, + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 0, + requirements.size)) { + ai.memoryTypeIndex = type; + VkDeviceMemory out = VK_NULL_HANDLE; + if (allocate(vk_dev, &ai, nullptr, &out) == VK_SUCCESS) return out; + } + return VK_NULL_HANDLE; + }; + leonida::IndirectArgumentClamp clamp(gdpa, vk_dev, mem_props, chosen.limits, clamp_allocate); + auto clamp_batch = clamp.batch(); + // LEONIDA_INDIRECT_CLAMP=0 turns the pass off at replay time, and then the raw argument buffer is read + // again: this test must not record its own pass either. + const bool clamp_on = clamp.loaded() && leonida::indirect_clamp_enabled(); + if (clamp_on) { + rf.prepare_indirect_clamp = [&clamp_batch](VkBuffer args, VkDeviceSize args_offset, VkBuffer count, + VkDeviceSize count_offset, std::uint32_t kind, + std::uint32_t stride, std::uint32_t max_count, + leonida::ClampedIndirect& out) { + return clamp_batch->prepare(args, args_offset, count, count_offset, kind, stride, max_count, out); + }; + rf.emit_indirect_clamp = [&clamp](VkCommandBuffer buffer, const leonida::ClampedIndirect& job) { + clamp.emit(buffer, job); + }; + } + + // The native reference draws the same suballocated offsets with vkCmdDrawIndirectCount directly: a + // Vulkan-level pixel oracle for the counted draw, not a D3D12 command replay. Both bindings start after + // poison prefixes, and the buffer holds the same two records the command list replays below. auto run_native_count = [&](VkDeviceSize count_offset, std::uint8_t exp_r, std::uint8_t exp_g, std::uint8_t exp_b) -> int { VkCommandBufferBeginInfo bi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; @@ -580,8 +631,166 @@ int main() { return 0; }; + // The same two records through the D3D12 command list and leonida::replay, so the ExecuteIndirect + // CountBuffer path - and the clamp pass it emits - is exercised, not just the native Vulkan call. + auto run_indirect_count = [&](std::uint64_t count_offset, std::uint8_t exp_r, std::uint8_t exp_g, + std::uint8_t exp_b) -> int { + leonida::CommandList ir; + ir.execute_indirect({leonida::IndirectKind::draw, sizeof(D3D12_DRAW_ARGUMENTS), 2u, + rt::d3d12::resource_id(arg_buf), 0, rt::d3d12::resource_id(count_buf), + count_offset}); + ir.close(); + + // The clamp pass is recorded here, before the drawing scope: vkCmdCopyBuffer and a memory barrier with + // a transfer access are outside it (VUID-vkCmdCopyBuffer-renderpass), which is also where gta6rt + // emits it for an indirect draw. replay then reads the clamped scratch whose records it is told about. + leonida::ClampedIndirect clamped{}; + const bool has_clamp = clamp_on; + if (has_clamp) { + if (!clamp_batch->prepare(rt::d3d12::vulkan_buffer(arg_buf), argument_base, + rt::d3d12::vulkan_buffer(count_buf), count_base + count_offset, + leonida::indirect_clamp_draw, sizeof(D3D12_DRAW_ARGUMENTS), 2u, clamped)) + return fail("clamp prepare"); + } + + VkCommandBufferBeginInfo bi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; + bi.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + vkBeginCommandBuffer(cb, &bi); + if (has_clamp) clamp.emit(cb, clamped); + + VkImageMemoryBarrier b_to_rt{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; + b_to_rt.srcAccessMask = 0; + b_to_rt.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + b_to_rt.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; + b_to_rt.newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + b_to_rt.image = rt::d3d12::vulkan_image(rt); + b_to_rt.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, 0, 0, nullptr, 0, nullptr, 1, + &b_to_rt); + + VkRenderingAttachmentInfo att{VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO}; + att.imageView = rt_view; + att.imageLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + att.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; + att.storeOp = VK_ATTACHMENT_STORE_OP_STORE; + att.clearValue.color.float32[3] = 1.0f; + VkRenderingInfo ri{VK_STRUCTURE_TYPE_RENDERING_INFO}; + ri.renderArea = {{0, 0}, {kW, kH}}; + ri.layerCount = 1; + ri.colorAttachmentCount = 1; + ri.pColorAttachments = &att; + vkCmdBeginRendering(cb, &ri); + VkViewport vp{0, 0, float(kW), float(kH), 0, 1}; + VkRect2D sc{{0, 0}, {kW, kH}}; + vkCmdSetViewport(cb, 0, 1, &vp); + vkCmdSetScissor(cb, 0, 1, &sc); + vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, pso); + + const auto resolver = [&](leonida::ResourceId id) -> const leonida::ResourceBinding* { + // Treat the two upload buffers as backing stores for slices that start after a prefix. + static leonida::ResourceBinding arg_b{}, cnt_b{}; + arg_b.buffer = rt::d3d12::vulkan_buffer(arg_buf); + arg_b.buffer_offset = argument_base; + arg_b.size = buffer_size - argument_base; + cnt_b.buffer = rt::d3d12::vulkan_buffer(count_buf); + cnt_b.buffer_offset = count_base; + cnt_b.size = buffer_size - count_base; + if (id == rt::d3d12::resource_id(arg_buf)) return &arg_b; + if (id == rt::d3d12::resource_id(count_buf)) return &cnt_b; + return nullptr; + }; + if (has_clamp) { + rf.prepare_indirect_clamp = [&clamped](VkBuffer, VkDeviceSize, VkBuffer, VkDeviceSize, std::uint32_t, + std::uint32_t, std::uint32_t, + leonida::ClampedIndirect& out) { + out = clamped; // prepared and emitted above, before the drawing scope + return true; + }; + rf.emit_indirect_clamp = [](VkCommandBuffer, const leonida::ClampedIndirect&) {}; + } else { + rf.prepare_indirect_clamp = {}; + rf.emit_indirect_clamp = {}; + } + const auto replayed = leonida::replay(ir, cb, resolver, rf); + if (replayed != leonida::ReplayResult::success) { + std::fprintf(stderr, "replay result %d (clamped=%d)\n", int(replayed), int(has_clamp)); + return fail("leonida::replay(ExecuteIndirect CountBuffer)"); + } + + vkCmdEndRendering(cb); + + VkImageMemoryBarrier b_to_src{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; + b_to_src.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + b_to_src.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; + b_to_src.oldLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + b_to_src.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; + b_to_src.image = rt::d3d12::vulkan_image(rt); + b_to_src.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, + 0, 0, nullptr, 0, nullptr, 1, &b_to_src); + + VkBufferImageCopy bic{}; + bic.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; + bic.imageExtent = {kW, kH, 1}; + vkCmdCopyImageToBuffer(cb, rt::d3d12::vulkan_image(rt), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, + rt::d3d12::vulkan_buffer(rb), 1, &bic); + + VkMemoryBarrier host_b{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + host_b.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + host_b.dstAccessMask = VK_ACCESS_HOST_READ_BIT; + vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, 1, &host_b, 0, + nullptr, 0, nullptr); + if (vkEndCommandBuffer(cb) != VK_SUCCESS) return fail("end replayed counted draw"); + + VkSubmitInfo si{VK_STRUCTURE_TYPE_SUBMIT_INFO}; + si.commandBufferCount = 1; + si.pCommandBuffers = &cb; + vkQueueSubmit(vk_queue, 1, &si, VK_NULL_HANDLE); + vkQueueWaitIdle(vk_queue); + // The clamp's record scratch is idle now: hand it back for the next run, as a completed submission does. + clamp.retire(VK_NULL_HANDLE, 0); + clamp.collect(); + + void* mp = nullptr; + if (FAILED(rb->Map(0, nullptr, &mp)) || !mp) return fail("map replayed counted-draw readback"); + const auto* px = static_cast(mp); + const bool ok = std::abs(int(px[0]) - int(exp_r)) <= 1 && std::abs(int(px[1]) - int(exp_g)) <= 1 && + std::abs(int(px[2]) - int(exp_b)) <= 1 && px[3] == 255; + rb->Unmap(0, nullptr); + if (!ok) return fail("replayed counted-draw pixel mismatch"); + return 0; + }; + if (run_native_count(0, 0, 0, 0) != 0) return 1; // count = 0 -> black if (run_native_count(4, 32, 160, 240) != 0) return 1; // count = 1 -> triangle + if (run_indirect_count(0, 0, 0, 0) != 0) return 1; // count = 0 -> black, through replay + if (run_indirect_count(4, 32, 160, 240) != 0) return 1; // count = 1 -> triangle, through replay + if (clamp_on) { + // What a skipped or mistranslated compute pass leaves: an instance count of four billion, and a count + // buffer past max_command_count. The clamp cuts the instances to 2^26 / 3 and the count to + // max_command_count, so this draw completes in milliseconds instead of running until the host resets + // the display driver - and the triangle it renders is the same one. + void* mapped = nullptr; + if (FAILED(arg_buf->Map(0, nullptr, &mapped))) return fail("Map(indirect arguments) again"); + auto* draws = reinterpret_cast(static_cast(mapped) + argument_base); + draws[0] = {3, 0xFFFFFFFFu, 0, 0}; + arg_buf->Unmap(0, nullptr); + if (FAILED(count_buf->Map(0, nullptr, &mapped))) return fail("Map(indirect count) again"); + *reinterpret_cast(static_cast(mapped) + count_base) = 0xFFFFFFFFu; + count_buf->Unmap(0, nullptr); + if (run_indirect_count(0, 32, 160, 240) != 0) return 1; // count is clamped to max_command_count + // Read the pass's counters: destroying the batch releases its slots, as a completed submission does. + clamp_batch.reset(); + const auto counters = clamp.counters(); + if (counters.records_clamped != 1 || counters.counts_clamped != 1) + return fail("clamp counters after a garbage record"); + std::printf(" [PASS] a draw record of 0xFFFFFFFF instances is clamped on the GPU (%llu record(s), " + "%llu count(s), %llu over the batch budget)\n", + static_cast(counters.records_clamped), + static_cast(counters.counts_clamped), + static_cast(counters.over_budget)); + } vkDestroyCommandPool(vk_dev, pool, nullptr); vkDestroyImageView(vk_dev, rt_view, nullptr); @@ -590,7 +799,8 @@ int main() { rb->Release(); rt->Release(); std::printf(" [PASS] native Vulkan counted-draw reference with suballocated argument/count offsets " - "(count=0 black, count=1 solid triangle)\n"); + "(count=0 black, count=1 solid triangle), and the same records through the D3D12\n" + " ExecuteIndirect replay (count=0 black, count=1 triangle)\n"); } else { std::printf(" [SKIP] native counted-draw reference: drawIndirectCount unsupported\n"); } diff --git a/runtime/test/d3d12_m4_compute_test.cpp b/runtime/test/d3d12_m4_compute_test.cpp index 97a4e8600f..05d6fe1530 100644 --- a/runtime/test/d3d12_m4_compute_test.cpp +++ b/runtime/test/d3d12_m4_compute_test.cpp @@ -28,6 +28,7 @@ #include "vk_test_device.h" #include "d3d12_test_shaders.h" #include "../shims/d3d12_com.h" +#include "../shims/d3d12_pipeline_compile.h" #include "../shims/d3d12_xs_device.h" #include "../src/shader_library.h" #include "../src/vulkan_indirect_clamp.h" @@ -96,7 +97,8 @@ Reference reference() { } // namespace -int main() { +int main(int argc, char** argv) { + const bool check_journal = argc == 2 && std::strcmp(argv[1], "--check-async-journal") == 0; vktest::Device d; d.queue_count_wanted = 2; // the copy queue and the compute queue each get a VkQueue where the family has two const auto device_status = d.initialize(); @@ -129,6 +131,7 @@ int main() { info.queue_family = d.family; if (distinct_queues) info.command_queues = d.queues; info.buffer_device_address = true; + info.pipeline_cache_control = d.pipeline_cache_control(); info.bindless = d.bindless; info.bindless_partially_bound = d.partially_bound; info.image_view_min_lod = d.image_view_min_lod; @@ -167,6 +170,24 @@ int main() { pso_desc.CS = {indirect_container.data(), indirect_container.size()}; EXPECT(SUCCEEDED(device->CreateComputePipelineState(&pso_desc, IID_PPV_ARGS(&pso_indirect.p)))); + if (check_journal) { + // Check publication while the device and both PSOs are still alive. The async policy can + // drop a dispatch whose worker has not yet published its handle, so wait for these two. + EXPECT(rt::d3d12::async_replay_compile()); + const auto deadline = GetTickCount64() + 30000; + while (rt::d3d12::PipelineCompiler::instance().stats().completed < 2 && GetTickCount64() < deadline) + Sleep(1); + EXPECT(rt::d3d12::PipelineCompiler::instance().stats().completed >= 2); + const auto* cache_dir = _wgetenv(L"LEONIDA_PIPELINE_CACHE_DIR"); + EXPECT(cache_dir && *cache_dir); + unsigned entries = 0; + const auto dir = std::filesystem::path(cache_dir) / L"pipeline_cache.d"; + EXPECT(std::filesystem::is_directory(dir)); + for (const auto& file : std::filesystem::directory_iterator(dir)) + if (file.path().extension() == L".bin" && file.file_size() > 32) ++entries; + EXPECT(entries == 2); + } + D3D12_INDIRECT_ARGUMENT_DESC argument{}; argument.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH; D3D12_COMMAND_SIGNATURE_DESC signature_desc{}; diff --git a/runtime/test/d3d12_mesh_test.cpp b/runtime/test/d3d12_mesh_test.cpp index 2d9bc5212e..775cfeb581 100644 --- a/runtime/test/d3d12_mesh_test.cpp +++ b/runtime/test/d3d12_mesh_test.cpp @@ -5,15 +5,16 @@ // - With it: MeshShaderTier 1; CreatePipelineState builds an MS + PS PSO and a VS + PS PSO from streams laid out as // d3dx12.h lays them out (each subobject a type and its description, pointer-aligned); streams the PC runtime // refuses (MS with VS, CS with PS, a subobject twice or in two versions, an unknown type, a truncated stream) are E_INVALIDARG, and -// state not built yet (an amplification shader, a depth-bounds test) is E_NOTIMPL. +// state not built yet (an amplification shader) is E_NOTIMPL; a depth-bounds test builds where the device +// reports DepthBoundsTestSupported, and is E_NOTIMPL where it does not. // - Draws: DispatchMesh(2, 2, 1) with root constants (0, 0) and a red tint fills the top-left quadrant; // DispatchMesh(1, 1, 2) moved by (1, -1) with a green tint fills the top half of the bottom-right one, so the // Y and Z counts reach the shader; the stream's VS PSO draws a full-screen triangle through a viewport on the // bottom-left quadrant (yellow). Each pixel is read back and compared. // - A vertex draw with the mesh PSO, and DispatchMesh with the VS one, fail at execution (ReplayResult:: // invalid_draw); a mesh grid beyond D3D12's limits fails at Close; an empty grid records nothing. -// - A DISPATCH_MESH command signature is created only with the extension; ExecuteIndirect with it records nothing -// yet, so its list closes. +// - A DISPATCH_MESH command signature is created only with the extension; ExecuteIndirect with it draws as +// DispatchMesh (one record {2, 1, 1} fills two cells), and without graphics state it records nothing and closes. // The shaders are GLSL written to the translator's contract (test/glsl/ms_draw.mesh, ps_draw.frag, vs_fullscreen.vert). // No game data. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. #include "vk_test_device.h" @@ -317,7 +318,14 @@ int main(int argc, char** argv) { D3D12_DEPTH_STENCIL_DESC1 bounds{}; bounds.DepthBoundsTestEnable = TRUE; bad.add(DepthStencil1Subobject{.inner = bounds}); - EXPECT(create(device.p, bad, refused) == E_NOTIMPL && !refused.p); + { + D3D12_FEATURE_DATA_D3D12_OPTIONS2 o2{}; + EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS2, &o2, sizeof o2))); + Ref with_bounds; + const HRESULT bounds_hr = create(device.p, bad, with_bounds); + EXPECT(o2.DepthBoundsTestSupported ? SUCCEEDED(bounds_hr) && with_bounds.p + : bounds_hr == E_NOTIMPL && !with_bounds.p); + } // A console stream: its numbering has no gap at 23, so its mesh shader is 24 (the PC's AS) and its // RASTERIZER1 26 (the PC's DEPTH_STENCIL2). An AS without an MS is no PC stream, so the layer reads it with the @@ -468,6 +476,54 @@ int main(int argc, char** argv) { EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); std::memcpy(pixels.data(), mapped, pixels.size()); + // ExecuteIndirect with a DISPATCH_MESH signature draws as DispatchMesh (vkCmdDrawMeshTasksIndirectEXT after + // the clamp pass): one record {2, 1, 1} at upload + 768 fills columns 0 and 1 of row 0, the top half of the + // top-left quadrant, red; the rest of the cleared target stays blue. + { + const std::uint32_t record[3] = {2, 1, 1}; + std::memcpy(up + 768, record, sizeof record); + const D3D12_INDIRECT_ARGUMENT_DESC mesh_arg{D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH}; + const D3D12_COMMAND_SIGNATURE_DESC mesh_sig{12, 1, &mesh_arg, 0}; + Ref sig; + Ref indirect_fence; + EXPECT(SUCCEEDED(device->CreateCommandSignature(&mesh_sig, nullptr, IID_PPV_ARGS(&sig.p))) && sig.p); + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&indirect_fence.p)))); + EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, mesh_pso.p))); + D3D12_RESOURCE_BARRIER again = + transition(target.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET); + list->ResourceBarrier(1, &again); + list->ClearRenderTargetView(rtv, blue, 0, nullptr); + list->SetGraphicsRootSignature(root.p); + list->RSSetViewports(1, &viewport); + list->RSSetScissorRects(1, &scissor); + list->OMSetRenderTargets(1, &rtv, FALSE, nullptr); + list->SetGraphicsRoot32BitConstants(0, 2, origin, 0); + list->SetGraphicsRootConstantBufferView(1, upload_va); + list->ExecuteIndirect(sig.p, 1, upload.p, 768, nullptr, 0); + list->ResourceBarrier(1, &to_copy); + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + EXPECT(list->Close() == S_OK); + queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); + EXPECT(SUCCEEDED(queue->Signal(indirect_fence.p, 1)) && + SUCCEEDED(indirect_fence->SetEventOnCompletion(1, nullptr))); + unsigned wrong = 0; + for (UINT row = 0; row < size; ++row) { + for (UINT col = 0; col < size; ++col) { + const bool red = row < size / 4 && col < size / 2; + const std::uint8_t want[4] = {std::uint8_t(red ? 255 : 0), 0, std::uint8_t(red ? 0 : 255), 255}; + const auto* got = static_cast(mapped) + row * 256 + col * 4; + if (std::equal(want, want + 4, got)) continue; + if (wrong++ < 6) + std::fprintf(stderr, "indirect mesh pixel (%u, %u): got %u,%u,%u,%u want %u,%u,%u,%u\n", col, + row, got[0], got[1], got[2], got[3], want[0], want[1], want[2], want[3]); + } + } + EXPECT(!wrong); + std::printf("ExecuteIndirect DISPATCH_MESH {2, 1, 1} drew as DispatchMesh(2, 1, 1): %u pixels matched\n", + size * size); + } + // The wrong kind of draw for the pipeline fails at execution: a vertex draw with the mesh PSO, then // DispatchMesh with the VS PSO. for (const bool vertex_draw : {true, false}) { @@ -591,8 +647,8 @@ int main(int argc, char** argv) { enabled ? "" : " (LEONIDA_GRAPHICS_DIRECT_HEAPS=0: not written)"); } // A DISPATCH_MESH command signature (D3D12_DISPATCH_MESH_ARGUMENTS, 12 bytes) is created; a stride below its - // 12 bytes is refused as the PC runtime refuses it. ExecuteIndirect with it records nothing yet (#3777 replays - // it), so the list still closes. + // 12 bytes is refused as the PC runtime refuses it. ExecuteIndirect with it and no viewport records + // nothing, so the list still closes. { const D3D12_INDIRECT_ARGUMENT_DESC mesh_arg{D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH}; const D3D12_COMMAND_SIGNATURE_DESC mesh_sig{12, 1, &mesh_arg, 0}; diff --git a/runtime/test/d3d12_pipeline_wait_test.cpp b/runtime/test/d3d12_pipeline_wait_test.cpp new file mode 100644 index 0000000000..14c9f1a4ce --- /dev/null +++ b/runtime/test/d3d12_pipeline_wait_test.cpp @@ -0,0 +1,593 @@ +// Bounded waits for pipelines still being built (src/pipeline_wait.h, docs/d3d12_vulkan.md "Pipelines still being +// built"). A build hook (set_pipeline_build_hook) holds one compute PSO's build in flight - claimed by the thread that +// builds it, before the driver call - so "still being built" is a state the test holds, not a race. Run as +// async LEONIDA_ASYNC_PIPELINES=1: the build is a compile-worker job, queued when SetPipelineState is recorded; +// sync asynchronous builds off: the build is the PSO's warm-up on the compile worker. +// Each case's list copies a sentinel into the output buffer, dispatches, and copies the output to a readback buffer: +// a skipped dispatch leaves the sentinel, so the rest of the list (barriers and copies) is seen to have run. +// skip budget 50 ms: ExecuteCommandLists returns within the budget, the dispatch is skipped and counted. +// later the build let go: the next submission runs the dispatch with the pipeline. +// in time budget 2 s, the build let go 200 ms into the wait: the submission waited, and the dispatch ran. +// no lock budget -1 (wait for the build): while a submission waits, another thread creates and maps a buffer at +// once (the wait holds no lock a resource creation needs); let go, the dispatch runs. +// zero budget 0: no wait, skipped at once. +// exit (async) budget -1 with the PSO's job still queued when the compiler stops for exit: the waiting +// submission builds the pipeline in place and runs instead of waiting for ever. +// No game data: the shader is test/glsl/cs_user_data.comp, the programs are made-up FSSM bytes. +#include "shader_fixture_path.h" +#include "test_temp_dir.h" +#include "vk_test_device.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_compile_exit.h" +#include "../shims/d3d12_pipeline_compile.h" +#include "../shims/d3d12_xs_device.h" +#include "../src/pipeline_wait.h" +#include "../src/shader_library.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef LEONIDA_TEST_CS_SPV +#error "LEONIDA_TEST_CS_SPV must name the compiled test shader" +#endif + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +namespace { + +using XboxComputePipelineFn = HRESULT(WINAPI*)(void* device, const D3D12_COMPUTE_PIPELINE_STATE_DESC*, std::uint64_t, + std::uint64_t, const IID*, void**); +using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slots 9/10: handle in RAX +using SerializeFn = HRESULT(WINAPI*)(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC*, ID3DBlob**, ID3DBlob**); +using Clock = std::chrono::steady_clock; + +constexpr unsigned kPrograms = 5; +constexpr std::uint32_t kSentinel = 0x5e5e5e5eu; + +void* slot(void* object, unsigned index) { return (*reinterpret_cast(object))[index]; } + +void put32(std::vector& out, std::uint32_t v) { + for (int i = 0; i < 4; ++i) out.push_back(std::uint8_t(v >> (8 * i))); +} + +std::vector zlib_stored(const std::vector& data) { + std::vector out = {0x78, 0x01, 0x01}; + const auto length = std::uint16_t(data.size()); + out.insert(out.end(), {std::uint8_t(length), std::uint8_t(length >> 8), std::uint8_t(~length), + std::uint8_t(~length >> 8)}); + out.insert(out.end(), data.begin(), data.end()); + std::uint32_t a = 1, b = 0; + for (const std::uint8_t x : data) { + a = (a + x) % 65521; + b = (b + a) % 65521; + } + const std::uint32_t adler = (b << 16) | a; + out.insert(out.end(), {std::uint8_t(adler >> 24), std::uint8_t(adler >> 16), std::uint8_t(adler >> 8), + std::uint8_t(adler)}); + return out; +} + +// DXBC { DXIL { stub, XDAT { 0x0D: XBCH + zlib(fssm) } } }, as in d3d12_compute_test. +std::vector shader_container(const std::vector& fssm) { + const auto stream = zlib_stored(fssm); + std::vector xbch = {'X', 'B', 'C', 'H'}; + for (const std::uint32_t v : {1u, std::uint32_t(stream.size()), 0u, std::uint32_t(fssm.size()), 0u}) put32(xbch, v); + xbch.insert(xbch.end(), stream.begin(), stream.end()); + std::vector dxil(16, 0); + dxil.insert(dxil.end(), {'X', 'D', 'A', 'T'}); + put32(dxil, 1); + put32(dxil, 12); + put32(dxil, 0x0d); + put32(dxil, 16 + 12 + 12); + put32(dxil, std::uint32_t(xbch.size())); + dxil.insert(dxil.end(), xbch.begin(), xbch.end()); + std::vector out = {'D', 'X', 'B', 'C'}; + out.resize(28, 0); + put32(out, 1); + put32(out, 36); + out.insert(out.end(), {'D', 'X', 'I', 'L'}); + put32(out, std::uint32_t(dxil.size())); + out.insert(out.end(), dxil.begin(), dxil.end()); + return out; +} + +// Program i: a made-up FSSM blob whose code word (dword 1, which the shader reads through its code base) differs. +std::uint32_t code_word(unsigned i) { return 9100 + i; } +std::vector program(unsigned i) { + std::vector fssm = {'F', 'S', 'S', 'M'}; + put32(fssm, code_word(i)); + for (std::uint32_t w = 0; w < 14; ++w) put32(fssm, 0xbf810000u + w); + return fssm; +} + +std::vector serialize(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC& desc) { + const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); + const auto fn = d3d12 ? reinterpret_cast( + reinterpret_cast(GetProcAddress(d3d12, "D3D12SerializeVersionedRootSignature"))) + : nullptr; + std::vector out; + ID3DBlob* blob = nullptr; + if (fn && SUCCEEDED(fn(&desc, &blob, nullptr)) && blob) { + const auto* p = static_cast(blob->GetBufferPointer()); + out.assign(p, p + blob->GetBufferSize()); + blob->Release(); + } + return out; +} + +D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes, D3D12_RESOURCE_FLAGS flags) { + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = bytes; + desc.Height = 1; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + desc.Flags = flags; + return desc; +} + +struct Event { + HANDLE handle = CreateEventW(nullptr, TRUE, FALSE, nullptr); + Event() = default; + Event(const Event&) = delete; + Event& operator=(const Event&) = delete; + ~Event() { CloseHandle(handle); } + void set() const { SetEvent(handle); } + void reset() const { ResetEvent(handle); } + bool wait(DWORD ms = 30000) const { return WaitForSingleObject(handle, ms) == WAIT_OBJECT_0; } + bool is_set() const { return WaitForSingleObject(handle, 0) == WAIT_OBJECT_0; } +}; + +using rt::d3d12::PipelineCompiler; + +// Waits until the worker has run everything queued so far: a last-priority marker job. +bool drain(PipelineCompiler& compiler) { + Event done; + static const int marker = 0; + if (!compiler.submit(&marker, nullptr, SIZE_MAX, [&done] { done.set(); })) return false; + return done.wait(120000); +} + +// Holds the worker in a job of no device until open() (or the end of the scope). +struct Gate { + Event entered, opened, left; + explicit Gate(PipelineCompiler& compiler) { + static const int gate = 0; + compiler.submit(&gate, nullptr, 0, [this] { + entered.set(); + opened.wait(INFINITE); + left.set(); + }); + entered.wait(); + } + void open() { opened.set(); } + ~Gate() { + opened.set(); + left.wait(); + } +}; + +// Holds the build of `target` (once claimed, before the driver call) until let_go(). +struct Hold { + std::atomic target{nullptr}; + Event entered, proceed; + Hold() { + rt::d3d12::set_pipeline_build_hook([this](ID3D12PipelineState* pso) { + if (pso != target.load()) return; + entered.set(); + proceed.wait(INFINITE); + }); + } + void let_go() { proceed.set(); } + ~Hold() { + proceed.set(); + rt::d3d12::set_pipeline_build_hook(nullptr); + } +}; + +struct Outcome { + std::vector words; + long long execute_ms = 0; + leonida::ReplayResult result = leonida::ReplayResult::unsupported; +}; + +std::uint32_t expected(unsigned program_index, std::uint32_t i) { + static constexpr std::uint32_t table_values[4] = {1000, 2000, 3000, 4000}; + return 7 + 3 * i + table_values[i % 4] + code_word(program_index); +} + +struct Session { + ID3D12Device* device = nullptr; + ID3D12RootSignature* root = nullptr; + std::vector psos; + + int open(vktest::Device& d, const std::filesystem::path& library) { + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = d.instance_proc; + info.instance = d.instance; + info.physical = d.physical; + info.device = d.device; + info.queue = d.queue; + info.queue_family = d.family; + info.buffer_device_address = true; + info.subgroup = d.subgroup; + info.shader_dir = library.string(); + ID3D12Device* inner = nullptr; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); + const HRESULT proxied = rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), + reinterpret_cast(&device), false); + if (FAILED(proxied)) inner->Release(); + EXPECT(SUCCEEDED(proxied)); + rt::d3d12::set_device_outer(inner, device); + + D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, 1, 0, 0}; + D3D12_ROOT_PARAMETER params[3] = {}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[0].Constants = {0, 0, 2}; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + params[1].Descriptor = {0, 0}; + params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[2].DescriptorTable = {1, &range}; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; + root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + root_desc.Desc_1_0 = {3, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + const auto blob = serialize(root_desc); + EXPECT(!blob.empty()); + EXPECT(SUCCEEDED(device->CreateRootSignature(0, blob.data(), blob.size(), IID_PPV_ARGS(&root)))); + return 0; + } + + int add(unsigned program_index, ID3D12PipelineState*& pso) { + const auto container = shader_container(program(program_index)); + D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature = root; + desc.CS = {container.data(), container.size()}; + const IID iid = __uuidof(ID3D12PipelineState); + pso = nullptr; + EXPECT(SUCCEEDED(reinterpret_cast(slot(device, 62))( + device, &desc, 0, 0, &iid, reinterpret_cast(&pso)))); + psos.push_back(pso); + return 0; + } + + // A list: sentinel copy into the output, the dispatch, the output copied to readback. `before_execute` runs just + // before ExecuteCommandLists (after the list is recorded); only that call is timed. + int dispatch(ID3D12PipelineState* pso, Outcome& outcome, const std::function& before_execute = {}) { + constexpr UINT elements = 64, bytes = elements * 4; + static constexpr std::uint32_t table_values[4] = {1000, 2000, 3000, 4000}; + 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}; + const auto uav = buffer_desc(bytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + const auto upload_desc = buffer_desc(512, D3D12_RESOURCE_FLAG_NONE); + const auto readback_desc = buffer_desc(bytes, D3D12_RESOURCE_FLAG_NONE); + ID3D12Resource *out = nullptr, *upload = nullptr, *readback = nullptr; + ID3D12DescriptorHeap* heap = nullptr; + ID3D12CommandQueue* queue = nullptr; + ID3D12CommandAllocator* allocator = nullptr; + ID3D12GraphicsCommandList* list = nullptr; + ID3D12Fence* fence = nullptr; + struct Releaser { + std::vector all; + ~Releaser() { + for (IUnknown** p : all) + if (*p) (*p)->Release(); + } + } releaser{{reinterpret_cast(&out), reinterpret_cast(&upload), + reinterpret_cast(&readback), reinterpret_cast(&heap), + reinterpret_cast(&queue), reinterpret_cast(&allocator), + reinterpret_cast(&list), reinterpret_cast(&fence)}}; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &uav, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&out)))); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &upload_desc, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + IID_PPV_ARGS(&upload)))); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback)))); + // Bytes 0..15: the CBV's table values; 256..511: the sentinel the output starts as. + void* mapped = nullptr; + EXPECT(SUCCEEDED(upload->Map(0, nullptr, &mapped))); + std::memcpy(mapped, table_values, sizeof(table_values)); + for (UINT i = 0; i < elements; ++i) std::memcpy(static_cast(mapped) + 256 + 4 * i, &kSentinel, 4); + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 8, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap)))); + const std::uint64_t cpu = reinterpret_cast(slot(heap, 9))(heap); + const std::uint64_t gpu = reinterpret_cast(slot(heap, 10))(heap); + EXPECT(cpu && gpu >= 0x10000 && gpu < (1ull << 32)); + const std::uint64_t target = upload->GetGPUVirtualAddress(); + std::memcpy(reinterpret_cast(cpu), &target, sizeof(target)); + + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue)))); + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)))); + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator, pso, + IID_PPV_ARGS(&list)))); + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)))); + list->CopyBufferRegion(out, 0, upload, 256, bytes); + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Transition = {out, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS}; + list->ResourceBarrier(1, &barrier); + list->SetDescriptorHeaps(1, &heap); + list->SetComputeRootSignature(root); + list->SetComputeRoot32BitConstant(0, 7, 0); + list->SetComputeRoot32BitConstant(0, 3, 1); + list->SetComputeRootUnorderedAccessView(1, out->GetGPUVirtualAddress()); + list->SetComputeRootDescriptorTable(2, D3D12_GPU_DESCRIPTOR_HANDLE{gpu}); + list->Dispatch(1, 1, 1); + barrier.Transition = {out, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_SOURCE}; + list->ResourceBarrier(1, &barrier); + list->CopyBufferRegion(readback, 0, out, 0, bytes); + EXPECT(list->Close() == S_OK); + if (before_execute) before_execute(); + ID3D12CommandList* lists[] = {list}; + const auto start = Clock::now(); + queue->ExecuteCommandLists(1, lists); + outcome.execute_ms = std::chrono::duration_cast(Clock::now() - start).count(); + outcome.result = rt::d3d12::last_execute_result(queue); + EXPECT(outcome.result == leonida::ReplayResult::success); + EXPECT(SUCCEEDED(queue->Signal(fence, 1))); + EXPECT(SUCCEEDED(fence->SetEventOnCompletion(1, nullptr))); + void* results = nullptr; + EXPECT(SUCCEEDED(readback->Map(0, nullptr, &results))); + outcome.words.assign(elements, 0); + std::memcpy(outcome.words.data(), results, bytes); + return 0; + } + + ~Session() { + if (device) device->Release(); + if (root) root->Release(); + for (ID3D12PipelineState* pso : psos) pso->Release(); + } +}; + +bool ran(const Outcome& o, unsigned program_index) { + for (std::uint32_t i = 0; i < o.words.size(); ++i) + if (o.words[i] != expected(program_index, i)) return false; + return !o.words.empty(); +} +bool skipped(const Outcome& o) { + for (const std::uint32_t w : o.words) + if (w != kSentinel) return false; + return !o.words.empty(); +} + +std::uint64_t skips() { return leonida::pipeline_wait::stats().skipped_dispatches.load(); } + +} // namespace + +int main(int argc, char** argv) { + const bool async = argc > 1 && !std::strcmp(argv[1], "async"); + if (argc < 2 || (!async && std::strcmp(argv[1], "sync"))) { + std::fprintf(stderr, "usage: d3d12_pipeline_wait_test async|sync\n"); + return 2; + } + _putenv_s("LEONIDA_LAZY_COMPUTE", "1"); + _putenv_s("LEONIDA_COMPUTE_WARMUP", async ? "0" : "1"); + _putenv_s("LEONIDA_ASYNC_PIPELINES", async ? "1" : "0"); + _putenv_s("LEONIDA_STRICT_REPLAY", "0"); + const testfiles::ScratchDir scratch(async ? "leonida_pipeline_wait_async" : "leonida_pipeline_wait_sync"); + const auto library = scratch.path() / "spirv"; + std::filesystem::create_directories(library); + _putenv_s("LEONIDA_PIPELINE_CACHE_DIR", (scratch.path() / "cache").string().c_str()); + + vktest::Device d; + const auto device_status = d.initialize(); + if (device_status == vktest::DeviceStatus::unavailable) { + std::fprintf(stderr, "SKIP: no usable Vulkan 1.3 device\n"); + return 77; + } + EXPECT(device_status == vktest::DeviceStatus::ready); + { + std::ofstream index(library / "index.json", std::ios::binary); + index << "{"; + for (unsigned i = 0; i < kPrograms; ++i) { + const std::string name = "cs_wait_" + std::to_string(i); + EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), library / (name + ".spv"))); + index << (i ? ",\n" : "") << "\"" << name << "\": {\"stage\": \"cs\", \"fssm_sha256\": \"" + << leonida::sha256_hex(program(i)) << "\", \"bindings\": [], \"push_constant_bytes\": 144, " + << "\"local_size\": [64, 1, 1], \"uses_code_base\": true, \"wave64\": false}"; + } + index << "}"; + } + + auto& compiler = PipelineCompiler::instance(); + auto& stats = leonida::pipeline_wait::stats(); + Session s; + if (s.open(d, library)) return 1; + const char* mode = async ? "async" : "sync"; + + // A PSO whose build `hold` holds once claimed. Sync: its warm-up, queued behind a gate so the hold knows the PSO + // before the worker reaches it, is held at once. Async: its job is queued when the list records SetPipelineState, + // and held then (the caller waits for hold.entered before executing). + const auto held_pso = [&](unsigned program_index, Hold& hold, ID3D12PipelineState*& pso) -> int { + { + Gate gate(compiler); + if (s.add(program_index, pso)) return 1; + hold.target = pso; + } + if (!async) EXPECT(hold.entered.wait()); + return 0; + }; + const auto entered = [](Hold& hold) { return [&hold] { hold.entered.wait(); }; }; + + // --- skip: budget 50 ms --------------------------------------------------------------------------------------- + ID3D12PipelineState* first = nullptr; + { + Hold hold; + if (held_pso(0, hold, first)) return 1; + leonida::pipeline_wait::set_budgets(50, -1); + const std::uint64_t skips_before = skips(), waited_before = stats.waited.load(); + Outcome o; + if (s.dispatch(first, o, entered(hold))) return 1; + std::printf("%s skip: ExecuteCommandLists returned in %lld ms with the build held; dispatch %s\n", mode, + o.execute_ms, skipped(o) ? "skipped (sentinel kept, the copies ran)" : "NOT skipped"); + EXPECT(skipped(o)); + EXPECT(o.execute_ms < 50 + 450); + EXPECT(skips() == skips_before + 1); + EXPECT(stats.waited.load() == waited_before + 1); + EXPECT(stats.building.load() >= 1); + hold.let_go(); + EXPECT(drain(compiler)); + } + // --- later: the build finished in the background; the next submission uses it --------------------------------- + { + const std::uint64_t skips_before = skips(); + Outcome o; + if (s.dispatch(first, o)) return 1; + std::printf("%s later: ran with the pipeline built in the background (%lld ms)\n", mode, o.execute_ms); + EXPECT(ran(o, 0)); + EXPECT(skips() == skips_before); + } + // --- in time: budget 2 s, the build let go 200 ms into the wait ------------------------------------------------ + { + Hold hold; + ID3D12PipelineState* pso = nullptr; + if (held_pso(1, hold, pso)) return 1; + leonida::pipeline_wait::set_budgets(2000, -1); + const std::uint64_t skips_before = skips(); + Event executing; + Outcome o; + int status = 1; + std::thread title([&] { + status = s.dispatch(pso, o, [&] { + hold.entered.wait(); + executing.set(); + }); + }); + EXPECT(executing.wait()); + Sleep(200); + hold.let_go(); + title.join(); + EXPECT(status == 0); + std::printf("%s in time: waited %lld ms for a build let go 200 ms in; dispatch %s\n", mode, o.execute_ms, + ran(o, 1) ? "ran" : "did NOT run"); + EXPECT(ran(o, 1)); + EXPECT(o.execute_ms >= 150 && o.execute_ms < 2000); + EXPECT(skips() == skips_before); + } + // --- no lock: budget -1; a resource is created and mapped while a submission waits ----------------------------- + { + Hold hold; + ID3D12PipelineState* pso = nullptr; + if (held_pso(2, hold, pso)) return 1; + leonida::pipeline_wait::set_budgets(-1, -1); + Event executing, executed; + Outcome o; + int status = 1; + std::thread title([&] { + status = s.dispatch(pso, o, [&] { + hold.entered.wait(); + executing.set(); + }); + executed.set(); + }); + EXPECT(executing.wait()); + Sleep(200); + const auto start = Clock::now(); + ID3D12Resource* buffer = nullptr; + const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}; + const auto desc = buffer_desc(1 << 20, D3D12_RESOURCE_FLAG_NONE); + const HRESULT created = s.device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &desc, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + IID_PPV_ARGS(&buffer)); + void* mapped = nullptr; + const HRESULT map = SUCCEEDED(created) ? buffer->Map(0, nullptr, &mapped) : E_FAIL; + const auto took = std::chrono::duration_cast(Clock::now() - start).count(); + if (buffer) buffer->Release(); + const bool still_waiting = !executed.is_set(); + hold.let_go(); + title.join(); + EXPECT(status == 0); + std::printf("%s no lock: a buffer was created and mapped in %lld ms while a submission waited (still waiting: " + "%s); the submission then ran the dispatch after %lld ms\n", + mode, static_cast(took), still_waiting ? "yes" : "no", o.execute_ms); + EXPECT(SUCCEEDED(created) && SUCCEEDED(map)); + EXPECT(took < 500); + EXPECT(still_waiting); + EXPECT(ran(o, 2)); + } + // --- zero: budget 0 ------------------------------------------------------------------------------------------- + { + Hold hold; + ID3D12PipelineState* pso = nullptr; + if (held_pso(3, hold, pso)) return 1; + leonida::pipeline_wait::set_budgets(0, -1); + const std::uint64_t skips_before = skips(), waited_before = stats.waited.load(); + Outcome o; + if (s.dispatch(pso, o, entered(hold))) return 1; + std::printf("%s zero: returned in %lld ms, dispatch %s\n", mode, o.execute_ms, + skipped(o) ? "skipped" : "NOT skipped"); + EXPECT(skipped(o)); + EXPECT(o.execute_ms < 200); + EXPECT(skips() == skips_before + 1); + EXPECT(stats.waited.load() == waited_before); + hold.let_go(); + EXPECT(drain(compiler)); + } + // A PSO never held: built (in place when synchronous) and run in its first submission. + { + ID3D12PipelineState* pso = nullptr; + if (s.add(4, pso)) return 1; + leonida::pipeline_wait::set_budgets(2000, -1); + Outcome o; + if (s.dispatch(pso, o)) return 1; + std::printf("%s first use: %s (%lld ms)\n", mode, ran(o, 4) ? "ran" : "did NOT run", o.execute_ms); + EXPECT(ran(o, 4)); + } + // --- exit (async): budget -1, the PSO's job still queued behind a gate when the compiler stops for exit (its queue + // dropped): the waiting submission does not wait for ever, it builds the pipeline in place and runs the dispatch. + if (async) { + leonida::pipeline_wait::set_budgets(-1, -1); + Event executing, executed; + Outcome o; + int status = 1; + { + Gate gate(compiler); // the worker is held, so the job SetPipelineState queues stays queued + ID3D12PipelineState* queued = nullptr; + if (s.add(1, queued)) return 1; // program 1 again: a second PSO, with its own build + std::thread title([&] { + status = s.dispatch(queued, o, [&] { executing.set(); }); + executed.set(); + }); + EXPECT(executing.wait()); + Sleep(200); + const bool waiting = !executed.is_set(); + const bool idle = rt::d3d12::stop_pipeline_compiles(100); // the gate's job is still running: false + const auto stopped = Clock::now(); + const bool finished = executed.wait(5000); + const auto after = std::chrono::duration_cast(Clock::now() - stopped).count(); + gate.open(); + title.join(); + std::printf("async exit: a submission waiting without limit for a queued build (waiting: %s) went on %lld " + "ms after the exit stop (worker idle: %s) and %s\n", + waiting ? "yes" : "no", static_cast(after), idle ? "yes" : "no", + ran(o, 1) ? "ran the dispatch" : "did NOT run the dispatch"); + EXPECT(waiting && !idle && finished); + EXPECT(status == 0); + EXPECT(ran(o, 1)); + } + } + EXPECT(stats.building.load() == 0); + std::printf("%s: all cases passed\n", mode); + return 0; +} diff --git a/runtime/test/d3d12_placed_depth_test.h b/runtime/test/d3d12_placed_depth_test.h index 5ef9f88a98..73818e19b1 100644 --- a/runtime/test/d3d12_placed_depth_test.h +++ b/runtime/test/d3d12_placed_depth_test.h @@ -34,6 +34,19 @@ inline bool check_alias_lifetime(ID3D12Device* device, ID3D12Device* xbox, bool const D3D12_CLEAR_VALUE* clear = nullptr) { return create(xbox, va, &shape, UINT_MAX, clear, IID_PPV_ARGS(&result.p)); }; + if (opaque) { + auto packed = xbox_desc; + packed.Format = static_cast(118); + packed.Width = 1280; + packed.Height = 720; + Ptr target; + // The image is privately backed; reserve a full placement for its title VA. + Pages packed_pages{VirtualAlloc(nullptr, 8u << 20, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)}; + const auto packed_va = reinterpret_cast(packed_pages.ptr); + if (!packed_va || FAILED(place(packed_va, packed, target)) || + target->GetGPUVirtualAddress() != packed_va) return false; + target.reset(); + } Ptr first, alias, next, invalid; if (FAILED(place(address, xbox_desc, first)) || FAILED(place(address, xbox_desc, alias)) || FAILED(place(address + allocation.SizeInBytes, xbox_desc, next))) return false; diff --git a/runtime/test/d3d12_title_va_test.cpp b/runtime/test/d3d12_title_va_test.cpp index 81a3b2fe53..706976642a 100644 --- a/runtime/test/d3d12_title_va_test.cpp +++ b/runtime/test/d3d12_title_va_test.cpp @@ -13,7 +13,7 @@ // into a bound table itself, a created CBV and a root view. // Negative controls: a second title buffer with other data must not be what the first one's V# reads; an arena // buffer's V# keeps its VA; the title's range is forgotten when the buffer is released; a raw arena V# and a -// T#-shaped slot in a scanned table keep their bytes; a reserved, uncommitted address is left alone. The shader is test/glsl/cs_user_data.comp. No game data. LEONIDA_VK_VALIDATION=1 for the +// T#-shaped slot in a scanned table keep their bytes; a reserved, uncommitted title address and memory that is nobody's get zero-size views. The shader is test/glsl/cs_user_data.comp. No game data. LEONIDA_VK_VALIDATION=1 for the // Khronos validation layer. #include "shader_fixture_path.h" #include "test_temp_dir.h" @@ -731,7 +731,9 @@ int check_title_memory(Context& c, int& checks, bool geometry) { static_cast(aliases.translated(leonida::TitleVaAliases::root_view) - root_before)); EXPECT(raw_ok == kElements && cbv_ok == kElements && root_ok == kElements); EXPECT(rewritten && arena_kept && image_kept); - // Neither unrelated host memory nor a reserved-only title page has a GPU copy. + // Committed memory that is not the title's (the runtime's own, say) and that no allocation of the device's holds: + // heap_base + its address is no allocation either, so its view gets no base and no records, as a title range + // with no committed page does (it gets no copy). Neither is counted as left untranslated, and neither has a copy. const std::uint64_t untranslated_before = aliases.untranslated(leonida::TitleVaAliases::created_view); void* host = VirtualAlloc(nullptr, 65536, MEM_TOP_DOWN | MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); void* gone = VirtualAlloc(nullptr, 65536, MEM_TOP_DOWN | MEM_RESERVE, PAGE_READWRITE); diff --git a/runtime/test/d3d12_unmapped_vsharp_test.cpp b/runtime/test/d3d12_unmapped_vsharp_test.cpp index 83fe2c0901..2e072ce407 100644 --- a/runtime/test/d3d12_unmapped_vsharp_test.cpp +++ b/runtime/test/d3d12_unmapped_vsharp_test.cpp @@ -152,7 +152,6 @@ int check_inline_table(ID3D12Device* device, ID3D12CommandQueue* queue, ID3D12Fe std::memcpy(cpu + slot * kDescriptor, w.data(), sizeof(w)); }; put(0, raw_vsharp(unmapped)); - for (int i = 4; i < 131; ++i) put(i, raw_vsharp(unmapped)); put(1, raw_vsharp(b.arena_va)); put(2, raw_vsharp(b.upload_va & 0xFFFFFFFFFFFFull)); auto image_like = raw_vsharp(unmapped); diff --git a/runtime/test/d3d12_vulkan_device_test.cpp b/runtime/test/d3d12_vulkan_device_test.cpp index 9df462d3fd..e8439da51d 100644 --- a/runtime/test/d3d12_vulkan_device_test.cpp +++ b/runtime/test/d3d12_vulkan_device_test.cpp @@ -2423,8 +2423,8 @@ int compare_feature_options(ID3D12Device* ours, const rt::d3d12::VulkanDeviceInf fail("unknown feature unexpectedly answered"); // Local invariants for what this layer actually implements. - if (o2.DepthBoundsTestSupported || - o2.ProgrammableSamplePositionsTier != D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER_NOT_SUPPORTED) + // DepthBoundsTestSupported follows the device's depthBounds feature. + if (o2.ProgrammableSamplePositionsTier != D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER_NOT_SUPPORTED) fail("OPTIONS2 unexpected support"); if (o3.CastingFullyTypedFormatSupported || o3.WriteBufferImmediateSupportFlags != D3D12_COMMAND_LIST_SUPPORT_FLAG_NONE || diff --git a/runtime/test/descriptor_table_test.cpp b/runtime/test/descriptor_table_test.cpp index 387bd0c606..287d68cded 100644 --- a/runtime/test/descriptor_table_test.cpp +++ b/runtime/test/descriptor_table_test.cpp @@ -546,6 +546,49 @@ int test_capacity_overflow() { return 0; } +// The entry's last dword is what a `descriptor_table` tagged module reads next to the index: the occupied bit and +// the arrays the index is bound in (kind_sampled_bit / kind_storage_bit). A plain module never reads it, so a table +// inserted without a kind must serialize exactly as before (marker, no kind bits). +int test_kind_word() { + DescriptorTable table(16); + const DescriptorKey image = make_tsharp_key(std::array{0x00001000u, 0x00000000u, 0u, 0u, + 0u, 0u, 0u, 0u}.data()); + const std::uint32_t kind = kind_sampled_bit(1) | kind_storage_bit(1); + EXPECT(table.insert(image, 5, kind)); + EXPECT(table.lookup(image) == 5); + const auto words = table.build_gpu_buffer(); + EXPECT(words[0] == 15); + const std::uint32_t slot = (hash_descriptor_key(image.data(), DescriptorHashKind::fnv1a) & 15); + if (words[1 + slot * 10 + 8] != 5) return 1; // find the slot the key landed in + EXPECT((words[1 + slot * 10 + 9] & kSlotOccupiedMarker) != 0); + EXPECT((words[1 + slot * 10 + 9] & kKindMask) == kind); + + // A plain entry: the marker and no kind bits, as before the marker existed. + const DescriptorKey plain = make_tsharp_key(std::array{0x00002000u, 0u, 0u, 0u, 0u, 0u, 0u, + 0u}.data()); + EXPECT(table.insert(plain, 6)); + std::uint32_t found[10]; + EXPECT(table.read_slot(slot, found)); + (void)found; + DescriptorEntry entry{}; + entry.kind = kSlotOccupiedMarker; + EXPECT(slot_occupied(entry) && slot_kind(entry) == 0); + + // The same index with a new kind is a change the GPU copy needs. + EXPECT(table.insert_or_update(image.data(), 5, kind_sampled_bit(2)) == + DescriptorTable::InsertResult::replaced); + EXPECT(table.insert_or_update(image.data(), 5, kind_sampled_bit(2)) == + DescriptorTable::InsertResult::unchanged); + const auto changed = table.take_changes(); + EXPECT(!changed.slots.empty() || changed.all); + + // clear_occupied drops the marker but keeps the kind, which is what a shader reads. + const auto gpu = table.build_gpu_buffer(true); + EXPECT((gpu[1 + slot * 10 + 9] & kSlotOccupiedMarker) == 0); + EXPECT((gpu[1 + slot * 10 + 9] & kKindMask) == kind_sampled_bit(2)); + return 0; +} + int main() { EXPECT(test_unresolvable_hash_collision() == 0); EXPECT(test_capacity_overflow() == 0); @@ -565,6 +608,7 @@ int main() { EXPECT(test_multithreaded_insert_and_lookup() == 0); EXPECT(test_clear_resets_table() == 0); EXPECT(test_erase_and_reinsert() == 0); + EXPECT(test_kind_word() == 0); std::printf("descriptor_table_test: all tests passed (0 failures)\n"); return 0; diff --git a/runtime/test/glsl/cs_indirect_dispatch_count.comp b/runtime/test/glsl/cs_indirect_dispatch_count.comp index 05bc685179..e08053790f 100644 --- a/runtime/test/glsl/cs_indirect_dispatch_count.comp +++ b/runtime/test/glsl/cs_indirect_dispatch_count.comp @@ -3,6 +3,9 @@ // which start at s4), plus the 144-byte user-data contract. #extension GL_EXT_buffer_reference : require #extension GL_EXT_buffer_reference_uvec2 : require +#ifndef TEST_COUNTER_TERM +#define TEST_COUNTER_TERM 1u +#endif layout(local_size_x = 1) in; layout(buffer_reference, std430, buffer_reference_align = 4) buffer Words { uint w[]; }; layout(push_constant) uniform UserData { uint s[32]; uvec2 heap_base; uvec2 code_base; } pc; @@ -14,5 +17,5 @@ uvec2 add64(uvec2 a, uvec2 b) { void main() { Words result = Words(add64(pc.heap_base, uvec2(pc.s[4], pc.s[5]))); atomicAdd(result.w[0], 1u); - atomicAdd(result.w[1], gl_WorkGroupID.x + 1u); + atomicAdd(result.w[1], gl_WorkGroupID.x + TEST_COUNTER_TERM); } diff --git a/runtime/test/indirect_clamp_safety_test.cpp b/runtime/test/indirect_clamp_safety_test.cpp index f051c0085b..3a296e91b0 100644 --- a/runtime/test/indirect_clamp_safety_test.cpp +++ b/runtime/test/indirect_clamp_safety_test.cpp @@ -320,12 +320,14 @@ int main() { area_buf = job1.stats_buffer; slot_off = job1.stats_offset; std::uint8_t* host = state.buffer_host.at(reinterpret_cast(area_buf)); - const std::uint32_t gpu_written[4] = {5u, 1u, 2u, 3u}; + const std::uint32_t gpu_written[12] = {5u, 1u, 2u, 3u, 0u, 0u, 0u, 0u, 7u, 4u, 3u, 2u}; std::memcpy(host + slot_off, gpu_written, sizeof(gpu_written)); } const auto after1 = clamp.counters(); CHECK(after1.records_clamped == 5 && after1.counts_clamped == 1 && after1.over_budget == 2 && after1.zeroed == 3); + CHECK(after1.mesh_records == 7 && after1.mesh_yz_records == 4 && + after1.mesh_max_y == 3 && after1.mesh_max_z == 2); // Batch 2 reuses the exact same slot (LIFO free_slots_) and is destroyed without GPU submission. { @@ -337,6 +339,8 @@ int main() { const auto after2 = clamp.counters(); CHECK(after2.records_clamped == 5 && after2.counts_clamped == 1 && after2.over_budget == 2 && after2.zeroed == 3); + CHECK(after2.mesh_records == 7 && after2.mesh_yz_records == 4 && + after2.mesh_max_y == 3 && after2.mesh_max_z == 2); } // 4. Non-4-byte-aligned argument_offset or count_offset is rejected before allocating scratch. diff --git a/runtime/test/keyboard_pad_retry_test.cpp b/runtime/test/keyboard_pad_retry_test.cpp new file mode 100644 index 0000000000..6c4e417573 --- /dev/null +++ b/runtime/test/keyboard_pad_retry_test.cpp @@ -0,0 +1,137 @@ +// No SDL, Windows, window, input sampling or worker. The shim instantiates this exact lifecycle with its SDL backend. +#include "../shims/keyboard_pad_connection.h" + +#include +#include +#include +#include + +#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #x); std::exit(1); } } while (0) + +namespace { +using Connection = rt::gameinput::detail::KeyboardPadConnection; + +struct Fake { + std::uint64_t clock = 0; + unsigned clock_reads = 0; + int live = 0, handle = 0, serial = 0; + bool attach_ok = true, open_ok = true, detach_ok = true; + std::string events; + + std::uint64_t now() { ++clock_reads; return clock; } + int attach() { + CHECK(!live && !handle); // never leak or create two virtual devices + events += 'A'; + return attach_ok ? (live = ++serial) : 0; + } + int open(int id) { + CHECK(id && id == live && !handle); + events += 'O'; + return open_ok ? (handle = live + 10) : 0; + } + void close(int js) { + CHECK(js && js == handle); + events += 'C'; + handle = 0; + } + bool detach(int id) { + CHECK(id && id == serial && !handle); + events += 'D'; + if (id != live) return false; // SDL returns false for an already-removed device + if (detach_ok) live = 0; + return detach_ok; + } + bool is_virtual(int id) const { return id != 0 && id == live; } + void failed() { events += '!'; } + void attached() { CHECK(handle); events += '+'; } + void removed() { CHECK(!live && !handle); events += '-'; } +}; + +void throttled_recovery() { + Connection pad; + Fake b; + b.attach_ok = false; + CHECK(!pad.update(false, b) && b.events.empty() && !b.clock_reads); + CHECK(!pad.update(true, b) && b.events == "A!"); // first failure, including at clock zero + for (b.clock = 2'000; b.clock < 1'000'000; b.clock += 2'000) CHECK(!pad.update(true, b)); + b.clock = 999'999; + CHECK(!pad.update(true, b) && b.events == "A!"); + ++b.clock; + CHECK(!pad.update(true, b) && b.events == "A!A"); // no extra warning + b.clock += 8'500'000; + CHECK(!pad.update(true, b) && b.events == "A!AA"); // one attempt, no catch-up loop + b.attach_ok = true; + b.clock += 999'999; + CHECK(!pad.update(true, b)); + ++b.clock; + CHECK(pad.update(true, b) && b.events == "A!AAAO+"); + CHECK(pad.id == b.live && pad.js == b.handle); + const unsigned previous = b.clock_reads; + for (int n = 0; n < 500; ++n) CHECK(pad.update(true, b)); + CHECK(b.events == "A!AAAO+" && previous == b.clock_reads); // hot path does not even read the retry clock + CHECK(!pad.update(false, b) && b.events == "A!AAAO+CD-" && !pad.id && !pad.js); + CHECK(!pad.update(false, b) && b.events == "A!AAAO+CD-"); + b.attach_ok = false; + CHECK(!pad.update(true, b) && b.events == "A!AAAO+CD-A!"); // new outage reports once + CHECK(!pad.update(false, b)); + b.attach_ok = true; + CHECK(pad.update(true, b) && b.events == "A!AAAO+CD-A!AO+"); // no old cooldown after off +} + +void partial_open_and_cleanup() { + Connection pad; + Fake b; + b.open_ok = false; + CHECK(!pad.update(true, b) && b.events == "AO!D" && !pad.id && !pad.js); + b.clock += 1'000'000; + b.detach_ok = false; + CHECK(!pad.update(true, b) && b.events == "AO!DAOD"); + CHECK(pad.id == b.live && !pad.js); + b.clock += 1'000'000; + CHECK(!pad.update(true, b) && b.events == "AO!DAODD"); // no new attach while old ID is owned + b.open_ok = b.detach_ok = true; + b.clock += 1'000'000; + CHECK(pad.update(true, b) && b.events == "AO!DAODDDAO+"); + b.events.clear(); + b.detach_ok = false; + CHECK(!pad.update(false, b) && b.events == "CD" && !pad.js && pad.id); + CHECK(!pad.update(false, b) && b.events == "CD"); // no second close/removal or per-poll detach + b.clock += 1'000'000; + CHECK(!pad.update(false, b) && b.events == "CDD"); + b.detach_ok = true; + CHECK(pad.update(true, b) && b.events == "CDDD-AO+"); // finish real removal before reattaching + CHECK(!pad.update(false, b) && b.events == "CDDD-AO+CD-"); +} + +void elapsed_clock_rollover() { + Connection pad; + Fake b; + b.clock = std::numeric_limits::max() - 9; + b.attach_ok = false; + CHECK(!pad.update(true, b)); + b.clock += 999'999; + b.attach_ok = true; + CHECK(!pad.update(true, b) && b.events == "A!"); + ++b.clock; + CHECK(pad.update(true, b) && b.events == "A!AO+"); +} + +void already_removed_during_cleanup() { + Connection pad; + Fake b; + b.open_ok = b.detach_ok = false; + CHECK(!pad.update(true, b) && b.events == "AO!D" && pad.id == b.live && !pad.js); + b.live = 0; // SDL no longer owns this virtual ID when cleanup retries + b.clock += 1'000'000; + b.open_ok = b.detach_ok = true; + CHECK(pad.update(true, b) && b.events == "AO!DDAO+" && pad.id == 2); +} +} // namespace + +int main() { + throttled_recovery(); + partial_open_and_cleanup(); + elapsed_clock_rollover(); + already_removed_during_cleanup(); + std::puts("keyboard pad retry: cadence, recovery, partial ownership, off/re-enable and rollover passed"); +} diff --git a/runtime/test/pipeline_cache_journal_test.cpp b/runtime/test/pipeline_cache_journal_test.cpp new file mode 100644 index 0000000000..c3793c96cf --- /dev/null +++ b/runtime/test/pipeline_cache_journal_test.cpp @@ -0,0 +1,337 @@ +// The pipeline journal's file naming, reading and writing (pipeline_cache_journal.h). No Vulkan, no GPU. +#include "../src/pipeline_cache_journal.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; +namespace journal = leonida::pipeline_journal; +namespace store = leonida::pipeline_cache_store; + +#define CHECK(condition) do { \ + if (!(condition)) { \ + std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); \ + return 1; \ + } \ +} while (0) + +static void put32(std::uint8_t* p, std::uint32_t value) { + for (int i = 0; i < 4; ++i) p[i] = static_cast(value >> (8 * i)); +} + +static leonida::cached_pso::Identity identity() { + leonida::cached_pso::Identity id; + id.vendor = 0x10de; + id.device = 0x2782; + for (int i = 0; i < 16; ++i) id.cache_uuid[i] = static_cast(0xa0 + i); + return id; +} + +// A VkPipelineCacheHeaderVersionOne for `id` followed by `payload` bytes. +static std::vector blob(const leonida::cached_pso::Identity& id, std::size_t payload) { + std::vector out(store::header_bytes + payload, '\x5a'); + auto* p = reinterpret_cast(out.data()); + put32(p, store::header_bytes); + put32(p + 4, store::header_version_one); + put32(p + 8, id.vendor); + put32(p + 12, id.device); + std::memcpy(p + 16, id.cache_uuid, sizeof(id.cache_uuid)); + return out; +} + +static int test_hash() { + const std::uint32_t words[] = {0x07230203, 0x00010600, 1, 2, 3}; + journal::Hasher a, b, c; + a.text("cs"); + a.bytes(words, sizeof(words)); + a.value(std::uint32_t(32)); + b.text("cs"); + b.bytes(words, sizeof(words)); + b.value(std::uint32_t(32)); + CHECK(a.digest() == b.digest()); // deterministic: the next boot finds the same file + c.text("cs"); + c.bytes(words, sizeof(words)); + c.value(std::uint32_t(64)); // another subgroup size is another pipeline + CHECK(a.digest() != c.digest()); + journal::Hasher d, e; + d.text("ab"); + d.text("c"); + e.text("a"); + e.text("bc"); + CHECK(d.digest() != e.digest()); // text is length-prefixed + return 0; +} + +static int test_path() { + const auto path = journal::entry_path("dir", "cs", 0x0123456789abcdefull); + CHECK(path.filename().string() == "cs-0123456789abcdef.bin"); + CHECK(journal::entry_path("dir", "cs", 1).filename().string() == "cs-0000000000000001.bin"); + return 0; +} + +static int test_files(const fs::path& dir) { + const auto id = identity(); + const auto path = journal::entry_path(dir / "pipeline_cache.d", "cs", 42); + CHECK(journal::read_entry(path, id).empty()); // missing + + // write_entry creates the directory and publishes the whole blob. + const auto data = blob(id, 1000); + CHECK(!journal::write_entry(path, data.data(), data.size())); + CHECK(journal::read_entry(path, id) == data); + + // A second write replaces the first. + const auto next = blob(id, 10); + CHECK(!journal::write_entry(path, next.data(), next.size())); + CHECK(journal::read_entry(path, id) == next); + + // Another device or driver (pipeline-cache UUID): not read, so the build starts over and rewrites it. + auto other = id; + other.cache_uuid[3] ^= 1; + CHECK(journal::read_entry(path, other).empty()); + other = id; + other.device = 0x1234; + CHECK(journal::read_entry(path, other).empty()); + + // Truncated to less than a header, or over the read limit: not read. + { + std::ofstream(path, std::ios::binary | std::ios::trunc).write(next.data(), 16); + } + CHECK(journal::read_entry(path, id).empty()); + CHECK(!journal::write_entry(path, data.data(), data.size())); + CHECK(journal::read_entry(path, id, data.size() - 1).empty()); + CHECK(journal::read_entry(path, id, data.size()) == data); + + CHECK(journal::directory_bytes(path.parent_path()) == data.size()); + CHECK(journal::directory_bytes(dir / "missing") == 0); + + // No staging files are left behind. + std::size_t files = 0; + for (const auto& item : fs::directory_iterator(path.parent_path())) { + (void)item; + ++files; + } + CHECK(files == 1); + return 0; +} + +// When a build writes its file, and when the shared cache's answer was a compile. +static int test_policy() { + // No file (or one the driver declined): always written, whatever the feedback or time. + CHECK(journal::should_write(false, 1, 0)); + CHECK(journal::should_write(false, -1, 0)); + CHECK(journal::should_write(false, 0, 0)); + // From the file: the feedback decides; without feedback, the length of the driver call. + CHECK(!journal::should_write(true, 1, 5000)); + CHECK(journal::should_write(true, 0, 1)); + CHECK(!journal::should_write(true, -1, journal::unreported_compile_ms - 1)); + CHECK(journal::should_write(true, -1, journal::unreported_compile_ms)); + // FAIL_ON_PIPELINE_COMPILE_REQUIRED: a slow pipeline without the hit bit was compiled; a fast one came out of + // the driver's own disk cache, and a hit or no feedback is never taken for a compile. + CHECK(journal::probe_compiled(0, journal::probe_compile_ms)); + CHECK(!journal::probe_compiled(0, journal::probe_compile_ms - 1)); + CHECK(!journal::probe_compiled(1, 60000)); + CHECK(!journal::probe_compiled(-1, 60000)); + return 0; +} + +static int test_accounting() { + CHECK(journal::replace_bytes(100, 0, 30) == 130); // a new file + CHECK(journal::replace_bytes(100, 40, 30) == 90); // a rewrite replaces the old size + CHECK(journal::replace_bytes(10, 40, 30) == 30); // never below zero + const auto t0 = fs::file_time_type::clock::now(); + using std::chrono::hours; + const std::vector entries = { + {"a", 40, t0 - hours(3)}, {"b", 40, t0 - hours(1)}, {"c", 40, t0 - hours(2)}, {"d", 40, t0}}; + CHECK(journal::plan_eviction(entries, 160, 120).empty()); // at the budget: nothing goes + // Over it: least recently used first (a, then c), until the target holds. + const auto out = journal::plan_eviction(entries, 150, 100); + CHECK(out.size() == 2 && out[0] == 0 && out[1] == 2); + CHECK(journal::plan_eviction(entries, 0, 0).size() == 4); + return 0; +} + +static int test_names() { + CHECK(journal::entry_name("cs-0123456789abcdef.bin")); + CHECK(!journal::entry_name("cs-0123456789abcde.bin")); // 15 digits + CHECK(!journal::entry_name("cs-0123456789ABCDEF.bin")); // entry_path writes lowercase + CHECK(!journal::entry_name("-0123456789abcdef.bin")); + CHECK(!journal::entry_name("pipeline_cache.session.bin")); + CHECK(journal::staging_name("cs-0123456789abcdef.bin.tmp.123456.0")); + CHECK(!journal::staging_name("cs-0123456789abcdef.bin.tmp.123456")); + CHECK(!journal::staging_name("cs-0123456789abcdef.bin.tmp.12x.0")); + CHECK(!journal::staging_name("pipeline_cache.session.bin.tmp.1.0")); // the session file's, swept elsewhere + return 0; +} + +static void put_file(const fs::path& path, std::size_t bytes, fs::file_time_type when) { + std::ofstream(path, std::ios::binary | std::ios::trunc) << std::string(bytes, 'x'); + fs::last_write_time(path, when); +} + +static int test_tidy(const fs::path& root) { + const auto dir = root / "tidy"; + fs::create_directories(dir); + const auto now = fs::file_time_type::clock::now(); + using std::chrono::hours; + using std::chrono::minutes; + const auto a = journal::entry_path(dir, "cs", 0xa), b = journal::entry_path(dir, "cs", 0xb), + c = journal::entry_path(dir, "cs", 0xc); + put_file(a, 400, now - hours(5)); + put_file(b, 400, now - hours(1)); + put_file(c, 400, now - hours(3)); + const fs::path old_stage = a.string() + ".tmp.111.0", new_stage = b.string() + ".tmp.222.1"; + put_file(old_stage, 50, now - minutes(30)); + put_file(new_stage, 50, now - minutes(2)); + put_file(dir / "notes.txt", 999, now - hours(9)); + + // Under the budget: only the old staging file goes; the young one may still be being written. + auto result = journal::tidy(dir, 2000, minutes(10), now); + CHECK(result.swept == 1 && result.evicted == 0 && result.entries == 3 && result.bytes == 1200); + CHECK(!fs::exists(old_stage) && fs::exists(new_stage) && fs::exists(dir / "notes.txt")); + + // Over it: the least recently used go until three quarters is left (1200 > 1000; 750 holds b alone). + result = journal::tidy(dir, 1000, minutes(10), now); + CHECK(result.evicted == 2 && result.entries == 1 && result.bytes == 400); + CHECK(!fs::exists(a) && !fs::exists(c) && fs::exists(b)); + + // A hit refreshes a file's last use, which keeps it over older ones. + put_file(a, 400, now - hours(5)); + journal::touch(a, now); + put_file(c, 400, now - hours(3)); + result = journal::tidy(dir, 1000, minutes(10), now); // 1200 again: c (3 h) is now the oldest, then b (1 h) + CHECK(fs::exists(a) && !fs::exists(c) && !fs::exists(b) && result.entries == 1); + CHECK(journal::tidy(root / "missing", 1000).entries == 0); + return 0; +} + +static int test_entry_file(const fs::path& dir) { + const auto id = identity(); + const auto path = journal::entry_path(dir, "cs", 77); + auto missing = journal::read_entry_file(path, id); + CHECK(missing.data.empty() && missing.bytes == 0); + // A foreign file still reports its size, which its rewrite replaces in the budget. + auto other = id; + other.device ^= 1; + const auto data = blob(other, 100); + CHECK(!journal::write_entry(path, data.data(), data.size())); + const auto foreign = journal::read_entry_file(path, id); + CHECK(foreign.data.empty() && foreign.bytes == data.size()); + const auto own = journal::read_entry_file(path, other); + CHECK(own.data == data && own.bytes == data.size()); + return 0; +} + +static int test_overlay(const fs::path& dir) { + using std::chrono::hours; + const auto local = dir / "overlay" / "pipeline_cache.d", seed = dir / "seed"; + const auto dst = journal::entry_path(local, "cs", 1), src = journal::entry_path(seed, "cs", 1); + const auto id = identity(); + auto wrong = id; + wrong.cache_uuid[0] ^= 1; + const auto donor = blob(id, 32), rebuilt = blob(id, 53), stale = blob(wrong, 45); + CHECK(!journal::write_entry(src, donor.data(), donor.size())); + const auto now = fs::file_time_type::clock::now(); + fs::last_write_time(src, now - hours(8)); + const auto donor_time = fs::last_write_time(src); + const auto roots = journal::resolve_roots(local, seed); + CHECK(!roots.writable.empty() && fs::equivalent(roots.seed, seed)); + + // No local entry: donor bytes may seed the driver, but do not count against the writable budget. + constexpr auto runtime = journal::ReadRole::runtime; + constexpr auto builder = journal::ReadRole::materialize_local; + auto entry = journal::read_with_seed(dst, roots.seed, id, runtime); + CHECK(entry.from_seed && entry.data == donor && entry.bytes == 0 && entry.used == fs::file_time_type{}); + // Same roots, but the host building a requested local file must still see a miss. + CHECK(!journal::entry_usable(dst, id) && journal::entry_usable(src, id)); + const auto missing_build = journal::read_with_seed(dst, roots.seed, id, builder); + CHECK(missing_build.data.empty() && !missing_build.from_seed && missing_build.bytes == 0); + journal::touch_local_hit(dst, entry, now); + CHECK(!fs::exists(local) && fs::last_write_time(src) == donor_time); + CHECK(journal::replace_bytes(1000, entry.bytes, rebuilt.size()) == 1000 + rebuilt.size()); + CHECK(journal::read_with_seed(dst, {}, id, runtime).data.empty()); + CHECK(journal::read_with_seed(dst, seed, wrong, runtime).data.empty()); + CHECK(journal::read_with_seed(dst, seed, id, runtime, donor.size() - 1).data.empty()); + CHECK(journal::read_with_seed(dst, seed, id, runtime, donor.size()).data == donor); + CHECK(journal::read_with_seed(journal::entry_path(local, "cs", 2), seed, id, runtime).data.empty()); + + // Even with a stale local object the recorded byte count and LRU timestamp belong to that object. + CHECK(!journal::write_entry(dst, stale.data(), stale.size())); + fs::last_write_time(dst, now - hours(3)); + const auto stale_time = fs::last_write_time(dst); + entry = journal::read_with_seed(dst, seed, id, runtime); + CHECK(entry.from_seed && entry.data == donor && entry.bytes == stale.size() && entry.used == stale_time); + const auto stale_build = journal::read_with_seed(dst, roots.seed, id, builder); + CHECK(stale_build.data.empty() && !stale_build.from_seed && stale_build.bytes == stale.size() && + stale_build.used == stale_time && !journal::entry_usable(dst, id)); + journal::touch_local_hit(dst, entry, now); + CHECK(fs::last_write_time(dst) == stale_time && fs::last_write_time(src) == donor_time); + CHECK(journal::read_entry(dst, wrong) == stale); // neither promoted nor rewritten by the hit + auto used = journal::tidy(roots.writable, stale.size()); + CHECK(used.entries == 1 && used.bytes == stale.size() && used.evicted == 0); + CHECK(journal::replace_bytes(used.bytes, entry.bytes, rebuilt.size()) == rebuilt.size()); + + CHECK(!journal::write_entry(dst, rebuilt.data(), 3)); // truncated local is not a seed hit on the local file + entry = journal::read_with_seed(dst, seed, id, runtime); + CHECK(entry.from_seed && entry.data == donor && entry.bytes == 3 && fs::file_size(dst) == 3); + CHECK(!journal::write_entry(dst, rebuilt.data(), rebuilt.size())); + fs::last_write_time(dst, now - hours(3)); + entry = journal::read_with_seed(dst, seed, id, runtime); + CHECK(!entry.from_seed && entry.data == rebuilt && entry.bytes == rebuilt.size()); + CHECK(journal::entry_usable(dst, id)); + CHECK(!journal::entry_usable(dst, id, rebuilt.size() - 1) && journal::entry_usable(dst, id, rebuilt.size())); + const auto ready_build = journal::read_with_seed(dst, roots.seed, id, builder); + CHECK(!ready_build.from_seed && ready_build.data == rebuilt && ready_build.bytes == rebuilt.size()); + journal::touch_local_hit(dst, entry, now); + const auto refreshed = fs::last_write_time(dst); + CHECK(refreshed > entry.used); + entry = journal::read_with_seed(dst, seed, id, runtime); + journal::touch_local_hit(dst, entry, now + std::chrono::minutes(30)); + CHECK(fs::last_write_time(dst) == refreshed); + used = journal::tidy(roots.writable, 0); + CHECK(used.evicted == 1 && used.bytes == 0 && !fs::exists(dst)); + CHECK(journal::read_entry(src, id) == donor && fs::last_write_time(src) == donor_time); + + const auto unset = journal::resolve_roots(local, {}); + CHECK(unset.writable == local && unset.seed.empty()); + const auto disabled = [](const fs::path& sink, const fs::path& source) { + const auto r = journal::resolve_roots(sink, source); + return r.writable.empty() && r.seed.empty(); + }; + CHECK(disabled({}, seed) && disabled(local, "relative") && disabled(local, dir / "no-seed")); + CHECK(disabled(local, src) && disabled(src, seed)); + CHECK(disabled(seed / ".", seed) && disabled(seed / "missing" / "journal", seed) && disabled(dir, seed)); +#ifdef _WIN32 + if (fs::exists(dir / "SEED")) CHECK(disabled(dir / "SEED", seed)); +#endif + return 0; +} + +int main() { + const auto dir = fs::temp_directory_path() / + ("leonida_pipeline_journal_test_" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())); + std::error_code ec; + fs::create_directories(dir, ec); + if (ec) { + std::fprintf(stderr, "cannot create %s\n", dir.string().c_str()); + return 1; + } + int failed = test_hash(); + if (!failed) failed = test_path(); + if (!failed) failed = test_files(dir); + if (!failed) failed = test_policy(); + if (!failed) failed = test_accounting(); + if (!failed) failed = test_names(); + if (!failed) failed = test_tidy(dir); + if (!failed) failed = test_entry_file(dir); + if (!failed) failed = test_overlay(dir); + fs::remove_all(dir, ec); + if (failed) return failed; + std::printf("pipeline_cache_journal_test: ok\n"); + return 0; +} diff --git a/runtime/test/shader_library_test.cpp b/runtime/test/shader_library_test.cpp index 2448ab7b82..ee49c48ebb 100644 --- a/runtime/test/shader_library_test.cpp +++ b/runtime/test/shader_library_test.cpp @@ -820,6 +820,80 @@ int main() { std::filesystem::remove_all(dir); } + // 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 + // partial index holds; counting entries would let a plain majority hand every tagged module an all-zero kind, and + // every image read through another dimension's array would fall back. LEONIDA_DESCRIPTOR_TABLE overrides in the + // device, through descriptor_table_layout_from_env. + { + const auto root = dir / "table_layouts"; + const auto write_index = [](const std::filesystem::path& folder, const std::string& modules) { + std::filesystem::create_directories(folder); + std::ofstream index(folder / "index.json", std::ios::binary); + index << "{" << modules << "}"; + }; + const auto module = [](const char* name, const char* marker) { + std::string out = "{\"stage\": \"vs\", \"fssm_sha256\": \"" + std::string(name) + "\""; + if (marker) out += ", \"descriptor_table\": \"" + std::string(marker) + "\""; + return out + "}"; + }; + const auto census = [](const ShaderLibrary& library, std::size_t tagged, std::size_t plain) { + return library.descriptor_table_census().tagged == tagged && + library.descriptor_table_census().plain == plain; + }; + + // A library translated before the kind word (or with --descriptor-table plain) is plain. + write_index(root, "\"a\": " + module("aa", nullptr) + ", \"b\": " + module("bb", nullptr)); + ShaderLibrary all_plain; + CHECK(all_plain.load(root.string(), &error)); + CHECK(census(all_plain, 0, 2) && + all_plain.descriptor_table_layout() == DescriptorTableLayout::plain); + + write_index(root, "\"a\": " + module("aa", "tagged") + ", \"b\": " + module("bb", "tagged")); + ShaderLibrary all_tagged; + CHECK(all_tagged.load(root.string(), &error)); + CHECK(census(all_tagged, 2, 0) && + all_tagged.descriptor_table_layout() == DescriptorTableLayout::tagged); + + // One tagged module among plain ones: the tagged layout (the old vote gave the plain majority's choice and + // every image of another dimension fell back). + write_index(root, "\"a\": " + module("aa", "tagged") + ", \"b\": " + module("bb", nullptr) + ", \"c\": " + + module("cc", "plain") + ", \"d\": " + module("dd", nullptr)); + ShaderLibrary tagged_minority; + CHECK(tagged_minority.load(root.string(), &error)); + CHECK(census(tagged_minority, 1, 3) && + tagged_minority.descriptor_table_layout() == DescriptorTableLayout::tagged); + + write_index(root, "\"a\": " + module("aa", nullptr) + ", \"b\": " + module("bb", "tagged")); + ShaderLibrary tied; + CHECK(tied.load(root.string(), &error)); + CHECK(census(tied, 1, 1) && tied.descriptor_table_layout() == DescriptorTableLayout::tagged); + + // A sub-index's marker counts too, and loading a folder replaces the census rather than adding to it. + write_index(root, "\"a\": " + module("aa", nullptr) + ", \"b\": " + module("bb", nullptr)); + write_index(root / "fspx", "\"upscaler\": " + module("cc", "tagged")); + ShaderLibrary sub_index; + CHECK(sub_index.load(root.string(), &error)); + CHECK(census(sub_index, 1, 2) && sub_index.descriptor_table_layout() == DescriptorTableLayout::tagged); + CHECK(sub_index.load(root.string(), &error) && census(sub_index, 1, 2)); // reload, not accumulate + std::filesystem::remove_all(root / "fspx"); + CHECK(sub_index.load(root.string(), &error) && census(sub_index, 0, 2) && + sub_index.descriptor_table_layout() == DescriptorTableLayout::plain); + + // LEONIDA_DESCRIPTOR_TABLE: an exact layout name wins over the vote; anything else is ignored, and a refused + // value leaves the caller's layout alone. + DescriptorTableLayout chosen = DescriptorTableLayout::tagged; + CHECK(descriptor_table_layout_from_env("plain", &chosen) && chosen == DescriptorTableLayout::plain); + CHECK(descriptor_table_layout_from_env("tagged", &chosen) && chosen == DescriptorTableLayout::tagged); + CHECK(!descriptor_table_layout_from_env(nullptr, &chosen)); + CHECK(!descriptor_table_layout_from_env("", &chosen)); + CHECK(!descriptor_table_layout_from_env("Plain", &chosen)); + CHECK(!descriptor_table_layout_from_env("other", &chosen)); + CHECK(chosen == DescriptorTableLayout::tagged); + std::filesystem::remove_all(dir); + } + if (const int line = fspx_checks()) return line; // FSPX entries: found by fspx_code_sha256, in the main index or in /fspx/index.json (named "fspx/"). diff --git a/runtime/test/shaders/build.py b/runtime/test/shaders/build.py index 03a7ecd229..377f7025e0 100644 --- a/runtime/test/shaders/build.py +++ b/runtime/test/shaders/build.py @@ -198,6 +198,10 @@ def translate_tests(work, names): # 128-byte push constants: the tail in a set-1 uniform block. The values the test programs accept (vk_pc_tail.h). if (os.environ.get("LEONIDA_PC_TAIL_UBO") or "").strip().lower() in ("1", "true", "yes", "on"): cmd.append("--pc-tail-ubo") + # The descriptor-table entry layout: tagged (the default) is what the runtime fills. plain is the old one, for a + # module translated before the kind word existed (and for the runtime test that must show the old behaviour). + if os.environ.get("LEONIDA_DESCRIPTOR_TABLE"): + cmd += ["--descriptor-table", os.environ["LEONIDA_DESCRIPTOR_TABLE"]] return subprocess.run(cmd).returncode diff --git a/runtime/test/submit_mutex_test.cpp b/runtime/test/submit_mutex_test.cpp new file mode 100644 index 0000000000..345f308871 --- /dev/null +++ b/runtime/test/submit_mutex_test.cpp @@ -0,0 +1,209 @@ +// leonida::SubmitMutex (src/vulkan_device_fault.h), on the CPU: the submit lock's owner and hold tracking, its waiter +// count, let_submit_finish (the handoff a pipeline create makes to submits before entering the driver) and the +// compile gate between pipeline creates and queue submissions. Windows only: the owner is a Win32 thread id. No GPU, +// no game data. +#include "../src/vulkan_device_fault.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 { + +using leonida::SubmitMutex; +using namespace std::chrono_literals; + +std::int64_t now_ms() { return leonida::diagnostic_ms(); } + +// Polls `done` for up to two seconds. +template bool eventually(Done&& done) { + for (int i = 0; i < 2000; ++i) { + if (done()) return true; + std::this_thread::sleep_for(1ms); + } + return done(); +} + +int owner_tracking() { + SubmitMutex m; + EXPECT(m.owner() == 0 && m.waiting() == 0); + const std::int64_t before = now_ms(); + m.lock(); + EXPECT(m.owner() == GetCurrentThreadId()); + EXPECT(m.since_ms() >= before && m.since_ms() <= now_ms()); + // The holder's own thread: nothing to let through, no wait (it would deadlock on the lock it holds). + EXPECT(m.let_submit_finish(true) == 0); + EXPECT(m.let_submit_finish(false) == 0); + m.unlock(); + EXPECT(m.owner() == 0); + EXPECT(m.try_lock()); + EXPECT(m.owner() == GetCurrentThreadId()); + m.unlock(); + // Free: no wait at all. + EXPECT(m.let_submit_finish(true) == 0); + std::printf("owner and hold tracking, holder's own thread returns at once\n"); + return 0; +} + +int waits_for_holder() { + SubmitMutex m; + std::atomic held{false}, released{false}; + std::thread holder([&] { + m.lock(); + held = true; + std::this_thread::sleep_for(200ms); + released = true; + m.unlock(); + }); + EXPECT(eventually([&] { return held.load(); })); + EXPECT(m.owner() != 0 && m.owner() != GetCurrentThreadId()); + const std::int64_t waited = m.let_submit_finish(false); + const bool after_release = released.load(); + holder.join(); + EXPECT(after_release); + EXPECT(waited >= 100); + std::printf("let_submit_finish(false) waited %lld ms for another thread's hold\n", static_cast(waited)); + return 0; +} + +int waits_for_queued_submitter() { + // A holds the lock, B queues behind it in lock(); the worker's handoff returns only after B has had its turn. + SubmitMutex m; + std::atomic a_held{false}, b_done{false}; + std::atomic b_released_at{0}; + std::thread a([&] { + m.lock(); + a_held = true; + std::this_thread::sleep_for(150ms); + m.unlock(); + }); + EXPECT(eventually([&] { return a_held.load(); })); + std::thread b([&] { + m.lock(); + std::this_thread::sleep_for(100ms); + b_released_at = now_ms(); + b_done = true; + m.unlock(); + }); + EXPECT(eventually([&] { return m.waiting() == 1; })); // B is counted while it waits + const std::int64_t waited = m.let_submit_finish(true); + const bool b_had_turn = b_done.load(); + const std::int64_t returned_at = now_ms(); + a.join(); + b.join(); + EXPECT(b_had_turn); + EXPECT(returned_at >= b_released_at.load()); + EXPECT(m.waiting() == 0 && m.owner() == 0); + std::printf("let_submit_finish(true) let a queued submitter go first (%lld ms)\n", static_cast(waited)); + return 0; +} + +int handoff_is_capped() { + // Two threads keep the lock busy back to back (one always queued): the worker still gets its turn after the cap. + SubmitMutex m; + std::atomic stop{false}; + auto churn = [&] { + while (!stop) { + m.lock(); + std::this_thread::sleep_for(10ms); + m.unlock(); + } + }; + std::thread a(churn), b(churn); + EXPECT(eventually([&] { return m.owner() != 0 && m.waiting() != 0; })); + const std::int64_t waited = m.let_submit_finish(true, 100); + stop = true; + a.join(); + b.join(); + std::printf("capped handoff: %lld ms\n", static_cast(waited)); + EXPECT(waited >= 90 && waited < 600); + std::printf("let_submit_finish(true, 100) under a steady stream of submits returned after %lld ms\n", + static_cast(waited)); + return 0; +} + +int compile_gate() { + if (!SubmitMutex::compile_gate_enabled()) { + std::printf("compile gate off (LEONIDA_COMPILE_GATE=0): not checked\n"); + return 0; + } + SubmitMutex m; + // Nothing in the driver: a submission passes at once. + { + const std::int64_t start = now_ms(); + const SubmitMutex::SubmitTurn turn(m); + EXPECT(now_ms() - start < 50); + } + // A submission waits for the create in the driver; a create arriving meanwhile waits behind the submission. + std::atomic creating{false}; + std::atomic create_left_at{0}, submit_entered_at{0}, submit_left_at{0}, second_entered_at{0}; + std::atomic second_waited{-1}; + std::thread create([&] { + const SubmitMutex::CompileTurn turn(m); + creating = true; + std::this_thread::sleep_for(250ms); + create_left_at = now_ms(); + }); + EXPECT(eventually([&] { return creating.load(); })); + std::thread submit([&] { + m.lock(); // as a submitter does: the submit lock, then the gate around vkQueueSubmit + { + const SubmitMutex::SubmitTurn turn(m); + submit_entered_at = now_ms(); + std::this_thread::sleep_for(100ms); + submit_left_at = now_ms(); + } + m.unlock(); + }); + EXPECT(eventually([&] { return m.gate_waiter() != 0; })); // waiting at the gate, with the submit lock held + EXPECT(m.owner() == m.gate_waiter()); + std::thread second([&] { + const SubmitMutex::CompileTurn turn(m); + second_entered_at = now_ms(); + second_waited = turn.waited_ms(); + }); + create.join(); + submit.join(); + second.join(); + EXPECT(submit_entered_at.load() >= create_left_at.load()); // never in the driver together with a create + EXPECT(second_entered_at.load() >= submit_left_at.load()); // the waiting submission went first + EXPECT(second_waited.load() >= 50); + EXPECT(m.gate_waiter() == 0); + const SubmitMutex::GateStats stats = m.gate_stats(); + EXPECT(stats.submits == 1 && stats.submit_max_ms >= 100); + EXPECT(stats.creates == 1 && stats.create_max_ms >= 50); + std::printf("compile gate: submission waited %lld ms for a create, a later create waited %lld ms behind it\n", + static_cast(stats.submit_max_ms), static_cast(stats.create_max_ms)); + // Creates share the gate. + { + const SubmitMutex::CompileTurn first(m); + std::atomic other_waited{-1}; + std::thread other([&] { + const SubmitMutex::CompileTurn turn(m); + other_waited = turn.waited_ms(); + }); + other.join(); + EXPECT(other_waited.load() == 0); + } + std::printf("compile gate: creates pass it together\n"); + return 0; +} + +} // namespace + +int main() { + std::setvbuf(stdout, nullptr, _IONBF, 0); + if (owner_tracking() || waits_for_holder() || waits_for_queued_submitter() || handoff_is_capped() || + compile_gate()) + return 1; + std::printf("submit_mutex_test: all passed\n"); + return 0; +} diff --git a/runtime/test/title_va_alias_test.cpp b/runtime/test/title_va_alias_test.cpp index fe378a3bf2..f2f8693915 100644 --- a/runtime/test/title_va_alias_test.cpp +++ b/runtime/test/title_va_alias_test.cpp @@ -85,6 +85,44 @@ int main() { a.remove(title, arena); a.remove(title + 0x40000, 0x7000000); EXPECT(a.size() == 0); + // Replacing part of an alias removes the entire old interval. Other heaps read independently. + std::uint64_t cursor = 0; + leonida::DescriptorRanges past; + EXPECT(a.changed_ranges(cursor, past)); + auto second = cursor; + EXPECT(a.add(title, size, arena)); + EXPECT(a.add(title+16, 32, arena+4096)); + for (auto* reader : {&cursor, &second}) { + leonida::DescriptorRanges delta; + EXPECT(a.changed_ranges(*reader, delta)); + delta.merge(); + EXPECT(delta.overlaps(title+size-1, 1) && delta.overlaps(title-16, 17)); + EXPECT(!delta.overlaps(title+size, 1) && !delta.overlaps(title-16, 16)); + } + leonida::DescriptorRangeChanges backing; + for (unsigned i = 0; i < 4097; ++i) backing.record(UINT64_MAX-3, 4); + cursor = 0; + EXPECT(!backing.read(cursor, past)); + backing.record(UINT64_MAX-3, 4); + leonida::DescriptorRanges last; + EXPECT(backing.read(cursor,last)); + last.merge(); + EXPECT(last.overlaps(UINT64_MAX,1) && !last.overlaps(0,1)); + // shader_side: whether an address is one the layer wrote for the title (inside some range's copy), so a scan that + // sees an already rewritten V# again leaves it alone rather than taking it for an unmapped address. + EXPECT(!a.shader_side(arena)); + EXPECT(a.add(title, size, arena) && a.add_twin(title + 0x200000, title + 0x400000, 0x1000, 0x9000000)); + EXPECT(a.shader_side(arena) && a.shader_side(arena + size - 1) && !a.shader_side(arena + size)); + EXPECT(a.shader_side(0x9000fff) && !a.shader_side(0x9001000) && !a.shader_side(title)); + a.remove(title + 0x200000, 0x9000000); + EXPECT(a.shader_side(0x9000000)); // the twin still names it + a.remove(title + 0x400000, 0x9000000); + EXPECT(!a.shader_side(0x9000000)); + // A range replaced by an overlapping one leaves the index with the new copy only. + EXPECT(a.add(title + 0x100, 0x100, 0xA000000)); + 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)); 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/vk_bindless_test.cpp b/runtime/test/vk_bindless_test.cpp index 194df74a9b..dc33e7d918 100644 --- a/runtime/test/vk_bindless_test.cpp +++ b/runtime/test/vk_bindless_test.cpp @@ -738,6 +738,222 @@ int main(int argc, char** argv) { return submit() == VK_SUCCESS && ok; }; + const float orange_pixel[4] = {1.0f, 128.0f / 255.0f, 0.0f, 1.0f}; + const float fallback_pixels[4] = {0.0f, 0.0f, 0.0f, 0.0f}; + + // The mirror (BindlessSet::MirrorViews): a 2D-array T# read by a 2D op finds its slice 0 bound in the 2D + // arrays at the T#'s own index. The index spaces are per dimension and dense, so slot N of one dimension + // and a 2D-array image's mirror slot N coincide: the set records which image owns a mirror slot, not just + // that it is used. + { + // A 2D-array image of two layers (layer 0 orange, layer 1 blue) with its own 2D-array and storage views + // plus a 2D view of layer 0, which is what a mirror binds. The storage view puts the index in the + // storage range, as in the index-space checks below. + const auto make_layered = [&](VkImage* image, VkImageView* layers, VkImageView* layer0) { + VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; + ii.imageType = VK_IMAGE_TYPE_2D; + ii.format = VK_FORMAT_R8G8B8A8_UNORM; + ii.extent = {1, 1, 1}; + ii.mipLevels = 1; + ii.arrayLayers = 2; + ii.samples = VK_SAMPLE_COUNT_1_BIT; + ii.tiling = VK_IMAGE_TILING_OPTIMAL; + ii.usage = sampled_usage | VK_IMAGE_USAGE_STORAGE_BIT; + VkResult r = vkCreateImage(dev, &ii, nullptr, image); + if (r) return r; + VkMemoryRequirements mr; + vkGetImageMemoryRequirements(dev, *image, &mr); + VkMemoryAllocateInfo ai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; + ai.allocationSize = mr.size; + ai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); + VkDeviceMemory m = VK_NULL_HANDLE; + if ((r = vkAllocateMemory(dev, &ai, nullptr, &m))) return r; + allocations.push_back(m); + if ((r = vkBindImageMemory(dev, *image, m, 0))) return r; + VkImageViewCreateInfo vi{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; + vi.image = *image; + vi.viewType = VK_IMAGE_VIEW_TYPE_2D_ARRAY; + vi.format = VK_FORMAT_R8G8B8A8_UNORM; + vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 2}; + if ((r = vkCreateImageView(dev, &vi, nullptr, layers))) return r; + vi.viewType = VK_IMAGE_VIEW_TYPE_2D; + vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + return vkCreateImageView(dev, &vi, nullptr, layer0); + }; + const auto upload_layered = [&](VkImage image) { + constexpr std::uint32_t blue = 0xffff0000u; // r = 0, g = 0, b = 255, a = 255 + std::memcpy(static_cast(upload_map) + 1028, &blue, 4); + VkResult r = vkResetCommandBuffer(cmd, 0); + if (r) return r; + if ((r = vkBeginCommandBuffer(cmd, &begin))) return r; + VkImageMemoryBarrier b{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; + b.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; + b.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + b.image = image; + b.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 2}; + b.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + b.srcQueueFamilyIndex = b.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, + nullptr, 0, nullptr, 1, &b); + for (std::uint32_t layer = 0; layer < 2; ++layer) { + VkBufferImageCopy c{}; + c.bufferOffset = 1024 + layer * 4; + c.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, layer, 1}; + c.imageExtent = {1, 1, 1}; + vkCmdCopyBufferToImage(cmd, upload, image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &c); + } + b.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + b.newLayout = VK_IMAGE_LAYOUT_GENERAL; // sampled and storage + b.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + b.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; + vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, + nullptr, 0, nullptr, 1, &b); + return submit(); + }; + // A 3D image with a storage view: its own index space, whose slot numbers are the 2D arrays' too. + const auto make_volume = [&](VkImage* image, VkImageView* view) { + VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; + ii.imageType = VK_IMAGE_TYPE_3D; + ii.format = VK_FORMAT_R8G8B8A8_UNORM; + ii.extent = {1, 1, 1}; + ii.mipLevels = 1; + ii.arrayLayers = 1; + ii.samples = VK_SAMPLE_COUNT_1_BIT; + ii.tiling = VK_IMAGE_TILING_OPTIMAL; + ii.usage = sampled_usage | VK_IMAGE_USAGE_STORAGE_BIT; + VkResult r = vkCreateImage(dev, &ii, nullptr, image); + if (r) return r; + VkMemoryRequirements mr; + vkGetImageMemoryRequirements(dev, *image, &mr); + VkMemoryAllocateInfo ai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; + ai.allocationSize = mr.size; + ai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); + VkDeviceMemory m = VK_NULL_HANDLE; + if ((r = vkAllocateMemory(dev, &ai, nullptr, &m))) return r; + allocations.push_back(m); + if ((r = vkBindImageMemory(dev, *image, m, 0))) return r; + VkImageViewCreateInfo vi{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; + vi.image = *image; + vi.viewType = VK_IMAGE_VIEW_TYPE_3D; + vi.format = VK_FORMAT_R8G8B8A8_UNORM; + vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + return vkCreateImageView(dev, &vi, nullptr, view); + }; + const auto add_mirrored = [&](VkImageView layers, VkImageView layer0, std::uint32_t* index, + std::uint32_t* kind) { + StorageViews storage; + storage.as_float = layers; + BindlessSet::MirrorViews mirror{}; + mirror.sampled = layer0; + mirror.sampled_layout = VK_IMAGE_LAYOUT_GENERAL; + mirror.storage.as_float = layer0; + *index = set.add_image(ImageDimension::dim_2d_array, layers, VK_IMAGE_LAYOUT_GENERAL, storage, 0, + &mirror, kind); + return *index != 0; + }; + const auto draw_with = [&](const DescriptorKey& key) { + std::memcpy(static_cast(heap_map) + table_va, key.data(), 32); + return draw(); + }; + + const std::uint32_t free_2d = set.free_images(ImageDimension::dim_2d); + const std::uint32_t free_array = set.free_images(ImageDimension::dim_2d_array); + VkImage layered = VK_NULL_HANDLE; + VkImageView layered_view = VK_NULL_HANDLE, layer0 = VK_NULL_HANDLE; + CHECK(make_layered(&layered, &layered_view, &layer0)); + CHECK(upload_layered(layered)); + + std::uint32_t index = 0, kind = 0; + EXPECT(add_mirrored(layered_view, layer0, &index, &kind)); + // The allocation is in both index spaces: the T#'s dimension and the 2D arrays (the mirror's slot). + EXPECT(set.free_images(ImageDimension::dim_2d) == free_2d - 1); + EXPECT(set.free_images(ImageDimension::dim_2d_array) == free_array - 1); + // The entry names the 2D-array arrays and their storage arrays, and the 2D ones the mirror is bound in. + EXPECT(kind == (kind_sampled_bit(1) | kind_storage_bit(1) | kind_sampled_bit(0) | kind_storage_bit(0))); + EXPECT(set.image_kind_at(ImageDimension::dim_2d_array, index) == kind); + EXPECT(set.image_kind_at(ImageDimension::dim_2d, index) == + (kind_sampled_bit(0) | kind_storage_bit(0))); + EXPECT(set.insert_key(tsharp, index, kind)); + EXPECT(flush()); + CHECK(draw()); + compare("mirror: a 2D-array T# read by a 2D op", orange_pixel); + // Removing the image puts the 2D slot back to its fallback. Its entry still names 2D (the kind it had), + // so a 2D op reads that slot: it must hold zeros, not the removed mirror. + EXPECT(set.erase_key(tsharp)); + set.remove_image(ImageDimension::dim_2d_array, index); + EXPECT(flush()); + EXPECT((set.image_kind_at(ImageDimension::dim_2d_array, index) & kind_sampled_bit(0)) == 0); + EXPECT(set.free_images(ImageDimension::dim_2d) == free_2d); + EXPECT(set.free_images(ImageDimension::dim_2d_array) == free_array); + EXPECT(set.insert_key(tsharp, index, kind)); + EXPECT(flush()); + CHECK(draw()); + compare("mirror: removed, the 2D slot holds the fallback", fallback_pixels); + EXPECT(set.erase_key(tsharp)); + + // The aliasing scenario the owner records: a 2D-array image with its mirror at slot N and a 3D image at + // its own index N (both index spaces are dense, so both take the lowest storage slot). Neither may claim + // the other's slot, and removing either must leave the other's binding alone. + VkImage layered2 = VK_NULL_HANDLE; + VkImageView layered2_view = VK_NULL_HANDLE, layer0_2 = VK_NULL_HANDLE; + CHECK(make_layered(&layered2, &layered2_view, &layer0_2)); + CHECK(upload_layered(layered2)); + std::uint32_t array_index = 0, array_kind = 0; + EXPECT(add_mirrored(layered2_view, layer0_2, &array_index, &array_kind)); + VkImage volume = VK_NULL_HANDLE; + VkImageView volume_view = VK_NULL_HANDLE; + CHECK(make_volume(&volume, &volume_view)); + StorageViews volume_storage; + volume_storage.as_float = volume_view; + const std::uint32_t volume_index = set.add_image(ImageDimension::dim_3d, volume_view, + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, volume_storage); + EXPECT(volume_index != 0 && volume_index == array_index); // the same slot number, two index spaces + const std::uint32_t volume_kind = set.image_kind_at(ImageDimension::dim_3d, volume_index); + // The 3D image does not own the 2D mirror: a 2D op reading its T# takes the 2D fallback. + EXPECT(volume_kind == (kind_sampled_bit(2) | kind_storage_bit(2))); + EXPECT((volume_kind & kind_sampled_bit(0)) == 0); + EXPECT(set.image_kind_at(ImageDimension::dim_2d_array, array_index) == array_kind); + DescriptorKey volume_key = tsharp; // the same FORMAT (word 1), a different key + volume_key[7] ^= 0x10u; + EXPECT(set.insert_key(tsharp, array_index, array_kind)); + EXPECT(set.insert_key(volume_key, volume_index, volume_kind)); + EXPECT(flush()); + CHECK(draw_with(volume_key)); + compare("alias: a 3D T# at another image's mirror slot", fallback_pixels); + CHECK(draw_with(tsharp)); + compare("alias: the mirror, with the 3D image at the same slot", orange_pixel); + // Removing the 3D image must not take the 2D-array image's mirror with it. + EXPECT(set.erase_key(volume_key)); + set.remove_image(ImageDimension::dim_3d, volume_index); + EXPECT(flush()); + EXPECT(set.image_kind_at(ImageDimension::dim_2d_array, array_index) == array_kind); + CHECK(draw_with(tsharp)); + compare("alias: the mirror survives the 3D image's removal", orange_pixel); + // And removing the 2D-array image frees the 2D slot: a 3D image at that slot number names no mirror. + const std::uint32_t volume_again = set.add_image(ImageDimension::dim_3d, volume_view, + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, volume_storage); + EXPECT(volume_again == volume_index); + EXPECT(set.insert_key(volume_key, volume_again, set.image_kind_at(ImageDimension::dim_3d, volume_again))); + EXPECT(set.erase_key(tsharp)); + set.remove_image(ImageDimension::dim_2d_array, array_index); + EXPECT(flush()); + EXPECT((set.image_kind_at(ImageDimension::dim_3d, volume_again) & kind_sampled_bit(0)) == 0); + EXPECT(set.free_images(ImageDimension::dim_2d) == free_2d); + CHECK(draw_with(volume_key)); + compare("alias: no mirror once the 2D-array image is gone", fallback_pixels); + EXPECT(set.erase_key(volume_key)); + set.remove_image(ImageDimension::dim_3d, volume_again); + EXPECT(flush()); + // The steps below expect tsharp at the heap's T# again. + std::memcpy(static_cast(heap_map) + table_va, tsharp.data(), 32); + vkDestroyImageView(dev, volume_view, nullptr); + vkDestroyImage(dev, volume, nullptr); + for (const VkImageView view : {layered_view, layer0, layered2_view, layer0_2}) + vkDestroyImageView(dev, view, nullptr); + vkDestroyImage(dev, layered, nullptr); + vkDestroyImage(dev, layered2, nullptr); + } + // Index spaces. An image with storage views gets an index the storage arrays hold; one without goes above // them where the dimension has room. A dimension that is full gives 0, and removed indices come back. StorageViews as_storage; @@ -763,6 +979,61 @@ int main(int argc, char** argv) { const std::uint32_t sampler_index = set.add_sampler(nearest); EXPECT(decoy_sampler == 1 && sampler_index == 2 && set.free_samplers() == set.sampler_capacity() - 3); + // The T#'s own type is the truth. This shader samples in 2D; the 3D image's index is 1 in the 3D arrays, + // and index 1 of the 2D arrays is `stored_view` (its own image, a red texel). The entry says the index is + // bound in the 3D arrays only, so the 2D read must use the 2D array's fallback and read zeros - not + // `stored_view`, which is what indexing the instruction's array with the other dimension's index would do. + { + EXPECT(stored_index == 1); + VkImage volume = VK_NULL_HANDLE; + VkImageView volume_view = VK_NULL_HANDLE; + { + const VkImageUsageFlags usage = + VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_STORAGE_BIT; + VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; + ii.imageType = VK_IMAGE_TYPE_3D; + ii.format = VK_FORMAT_R8G8B8A8_UNORM; + ii.extent = {2, 2, 2}; + ii.mipLevels = 1; + ii.arrayLayers = 1; + ii.samples = VK_SAMPLE_COUNT_1_BIT; + ii.tiling = VK_IMAGE_TILING_OPTIMAL; + ii.usage = usage; + CHECK(vkCreateImage(dev, &ii, nullptr, &volume)); + VkMemoryRequirements mr; + vkGetImageMemoryRequirements(dev, volume, &mr); + VkMemoryAllocateInfo ai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; + ai.allocationSize = mr.size; + ai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); + VkDeviceMemory memory = VK_NULL_HANDLE; + CHECK(vkAllocateMemory(dev, &ai, nullptr, &memory)); + allocations.push_back(memory); + CHECK(vkBindImageMemory(dev, volume, memory, 0)); + VkImageViewCreateInfo vi{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; + vi.image = volume; + vi.viewType = VK_IMAGE_VIEW_TYPE_3D; + vi.format = VK_FORMAT_R8G8B8A8_UNORM; + vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + CHECK(vkCreateImageView(dev, &vi, nullptr, &volume_view)); + } + // A storage view puts it in the low index region, so its index is 1: the same slot number as + // `stored_view` in the 2D arrays, which a dimension-blind read would pick up. + StorageViews volume_storage; + volume_storage.as_float = volume_view; + const std::uint32_t volume_index = set.add_image(ImageDimension::dim_3d, volume_view, + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, volume_storage); + EXPECT(volume_index == stored_index); // the same slot number, a different index space + EXPECT(set.insert_key(tsharp, volume_index, ImageDimension::dim_3d)); + EXPECT(flush()); + EXPECT(draw() == VK_SUCCESS); + const float zeros[4] = {0.0f, 0.0f, 0.0f, 0.0f}; + compare("a 3D T# read by a 2D op", zeros); + EXPECT(set.erase_key(tsharp)); + set.remove_image(ImageDimension::dim_3d, volume_index); + vkDestroyImageView(dev, volume_view, nullptr); + vkDestroyImage(dev, volume, nullptr); + } + if (atomic_mode) { // ps_imgatomic.asm: image_atomic_umax/umin/or on three 8x8 r32ui images and umax on a 4x4x4 one, from // every pixel of the 64x64 draw (64 pixels per 2D texel), each found through its own T# key. Odd @@ -815,7 +1086,8 @@ int main(int argc, char** argv) { indices[k] = set.add_image(k == 3 ? ImageDimension::dim_3d : ImageDimension::dim_2d, views[k], VK_IMAGE_LAYOUT_GENERAL, storage); EXPECT(indices[k] != 0); - EXPECT(set.insert_key(keys[k], indices[k])); + EXPECT(set.insert_key(keys[k], indices[k], + k == 3 ? ImageDimension::dim_3d : ImageDimension::dim_2d)); } EXPECT(flush()); @@ -963,9 +1235,10 @@ int main(int argc, char** argv) { const auto target = (slots - 4 + i % kDescriptorProbes) & (slots - 1); while ((hash_descriptor_key(key) & (slots - 1)) != target) ++key[7]; } - for (std::uint32_t i = 0; i < kDescriptorProbes; ++i) set.insert_key(keys[i], decoy_index); + for (std::uint32_t i = 0; i < kDescriptorProbes; ++i) + set.insert_key(keys[i], decoy_index, ImageDimension::dim_2d); EXPECT(!set.flush_replaces_table() && flush()); - EXPECT(set.insert_key(keys.back(), gradient_index)); + EXPECT(set.insert_key(keys.back(), gradient_index, ImageDimension::dim_2d)); EXPECT(slot_count() == slots && set.flush_replaces_table()); EXPECT(flush() && !set.flush_replaces_table()); for (const auto& key : keys) { @@ -979,12 +1252,13 @@ int main(int argc, char** argv) { std::uint32_t ahead = 0; for (std::uint32_t k = 1; ahead < 3; ++k) { if ((hash_descriptor_key(numbered(k)) & (slots - 1)) != home) continue; - set.insert_key(numbered(k), decoy_index); + set.insert_key(numbered(k), decoy_index, ImageDimension::dim_2d); ++ahead; } - set.insert_key(tsharp, gradient_index); + set.insert_key(tsharp, gradient_index, ImageDimension::dim_2d); set.insert_key(make_ssharp_key(ssharp.data()), sampler_index); - for (std::uint32_t k = 100000; k < 100006; ++k) set.insert_key(numbered(k), decoy_index); + for (std::uint32_t k = 100000; k < 100006; ++k) + set.insert_key(numbered(k), decoy_index, ImageDimension::dim_2d); const std::uint32_t depth = probe_depth(table.build_gpu_buffer(), tsharp); EXPECT(slot_count() == slots && depth == 3 && !set.flush_replaces_table()); EXPECT(flush()); @@ -1000,9 +1274,10 @@ int main(int argc, char** argv) { compare("2 miss", zeros); // 3. The table grows: a new, larger buffer behind binding 2. - set.insert_key(tsharp, gradient_index); + set.insert_key(tsharp, gradient_index, ImageDimension::dim_2d); EXPECT(!set.flush_replaces_table()); // one more entry, in place - for (std::uint32_t k = 200000; k < 200200; ++k) set.insert_key(numbered(k), decoy_index); + for (std::uint32_t k = 200000; k < 200200; ++k) + set.insert_key(numbered(k), decoy_index, ImageDimension::dim_2d); EXPECT(slot_count() > slots && table.lookup(tsharp) == gradient_index && set.flush_replaces_table()); const VkDescriptorSet before_growth = set.set(); const std::uint64_t made_before = set.generations_made(); @@ -1020,12 +1295,13 @@ int main(int argc, char** argv) { const float orange_colour[4] = {1.0f, 128.0f / 255.0f, 0.0f, 1.0f}; // Rewriting the same mapping is a no-op. Changing it makes a new generation even with no table growth. const std::uint32_t grown_slots = slot_count(); - EXPECT(set.insert_key(tsharp, gradient_index) && !set.flush_replaces_table()); - EXPECT(set.insert_key(tsharp, decoy_index) && slot_count() == grown_slots && set.flush_replaces_table()); + EXPECT(set.insert_key(tsharp, gradient_index, ImageDimension::dim_2d) && !set.flush_replaces_table()); + EXPECT(set.insert_key(tsharp, decoy_index, ImageDimension::dim_2d) && slot_count() == grown_slots && + set.flush_replaces_table()); EXPECT(flush() && !set.flush_replaces_table()); CHECK(draw()); compare("4 rebound", orange_colour); - EXPECT(set.insert_key(tsharp, gradient_index) && set.flush_replaces_table()); + EXPECT(set.insert_key(tsharp, gradient_index, ImageDimension::dim_2d) && set.flush_replaces_table()); EXPECT(flush()); CHECK(draw()); compare("5 restored", nullptr); @@ -1033,7 +1309,7 @@ int main(int argc, char** argv) { // A submit that never reached the queue must keep the table upload pending: the retry has to see the new // mapping instead of the fallback or the old index (a recovered submit failure, the case a device reports // through table_upload_result(false)). - EXPECT(set.insert_key(tsharp, decoy_index) && set.flush_replaces_table()); + EXPECT(set.insert_key(tsharp, decoy_index, ImageDimension::dim_2d) && set.flush_replaces_table()); vkResetCommandBuffer(cmd, 0); CHECK(vkBeginCommandBuffer(cmd, &begin)); EXPECT(set.flush(cmd, 1)); // recorded in a command buffer that is never submitted @@ -1043,7 +1319,7 @@ int main(int argc, char** argv) { EXPECT(flush()); CHECK(draw()); compare("6 rebound after a failed submit", orange_colour); - EXPECT(set.insert_key(tsharp, gradient_index) && set.flush_replaces_table()); + EXPECT(set.insert_key(tsharp, gradient_index, ImageDimension::dim_2d) && set.flush_replaces_table()); EXPECT(flush()); // Another view at the same index, then removal of the index. @@ -1066,7 +1342,7 @@ int main(int argc, char** argv) { far_image = set.add_image(ImageDimension::dim_2d, gradient_view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); for (std::uint32_t i = 0; i < 2100; ++i) far_sampler = set.add_sampler(nearest); EXPECT(far_image > 5000 && far_sampler > 2100); - set.insert_key(tsharp, far_image); + set.insert_key(tsharp, far_image, ImageDimension::dim_2d); set.insert_key(make_ssharp_key(ssharp.data()), far_sampler); EXPECT(flush()); CHECK(draw()); @@ -1087,7 +1363,7 @@ int main(int argc, char** argv) { const float blue[4] = {0, 0, 128.0f / 255.0f, 1}; // stored image uses the first gradient texel compare("11 reused high slot", blue); - EXPECT(set.insert_key(tsharp, neighbour)); + EXPECT(set.insert_key(tsharp, neighbour, ImageDimension::dim_2d)); EXPECT(flush()); CHECK(draw()); compare("12 live neighbour", orange_colour); diff --git a/runtime/test/vk_console_heap_gpu_test.cpp b/runtime/test/vk_console_heap_gpu_test.cpp new file mode 100644 index 0000000000..9ac34f52b0 --- /dev/null +++ b/runtime/test/vk_console_heap_gpu_test.cpp @@ -0,0 +1,584 @@ +// The console heap translation pass (src/console_heap_fix.comp, src/console_heap_gpu.h) against its CPU reference: +// synthetic descriptor words only (no game data). Checks the key table mirror on the CPU first, then that the GPU +// writes every slot exactly as console_heap_translate_slot does and records the same misses, through key table +// updates, a new range table, a submission that failed (its work queued again) and a miss list that overflows. +// Exits 77 without a Vulkan device with bufferDeviceAddress. +#include "vk_test_device.h" +#include "../src/console_heap_gpu.h" + +#include +#include +#include +#include +#include +#include + +#define EXPECT(x) \ + do { \ + if (!(x)) { \ + std::fprintf(stderr, "line %d: %s\n", __LINE__, #x); \ + return 1; \ + } \ + } while (0) + +namespace { + +using leonida::ConsoleHeapKeys; +using leonida::ConsoleHeapRange; +using leonida::ConsoleHeapTables; + +// A buffer V# half: base, stride, records and dword 3 with TYPE bits 30-31 clear. +void vsharp(std::uint32_t* w, std::uint64_t base, std::uint32_t stride, std::uint32_t records, std::uint32_t dword3) { + w[0] = std::uint32_t(base); + w[1] = std::uint32_t((base >> 32) & 0xffff) | (stride << 16); + w[2] = records; + w[3] = dword3 & 0x3fffffffu; +} + +int keys_on_cpu() { + ConsoleHeapKeys keys(6); // 64 entries: probe chains overlap + const ConsoleHeapKeys::Key a{1, 2, 3, 4}, b{5, 6, 7, 8}; + EXPECT(keys.find(a) < 0); + EXPECT(keys.put(a, 0x1000, 0x100, false)); + EXPECT(keys.put(b, 0, 0x40, true)); + std::uint64_t to = 0; + bool none = true; + EXPECT(keys.lookup(a, to, none) && to == 0x1000 && !none); + EXPECT(keys.lookup(b, to, none) && none); + EXPECT(keys.size() == 2); + // Only positive answers fall in a released shader range; the edge is exclusive. + EXPECT(keys.erase_overlapping(0x1100, 0x2000) == 0); + EXPECT(keys.erase_overlapping(0x10ff, 0x1100) == 1); + EXPECT(keys.find(a) < 0 && keys.find(b) >= 0); + // Replacing an answer keeps one entry and moves its index. + EXPECT(keys.put(b, 0x5000, 0x10, false)); + EXPECT(keys.size() == 1); + EXPECT(keys.erase_overlapping(0x5008, 0x5009) == 1); + EXPECT(keys.size() == 0); + // Fill one probe chain: the 17th key with the same start finds no slot. + // V#s whose words differ only in high bits (bases megabytes apart): the hash must still spread them. Bare FNV-1a + // put all of these in one probe chain. + { + ConsoleHeapKeys big(20); + for (std::uint32_t i = 0; i < 20000; ++i) { + const ConsoleHeapKeys::Key k{(i & 0xfffu) << 20, ((i >> 12) << 8) | (64u << 16), 256, 0x2000}; + EXPECT(big.put(k, 0x100000ull * i, 256, false)); + } + EXPECT(big.size() == 20000); + } + std::vector same; + for (std::uint32_t i = 0; same.size() < ConsoleHeapKeys::kProbes + 1 && i < 1u << 20; ++i) { + const ConsoleHeapKeys::Key k{i, 0, 1, 0}; + if ((ConsoleHeapKeys::hash(k) & keys.mask()) == 7) same.push_back(k); + } + EXPECT(same.size() == ConsoleHeapKeys::kProbes + 1); + for (std::size_t i = 0; i < ConsoleHeapKeys::kProbes; ++i) EXPECT(keys.put(same[i], 0x100 * i, 1, false)); + EXPECT(!keys.put(same.back(), 1, 1, false)); + std::vector updates; + keys.take_updates(updates); + EXPECT(!updates.empty() && updates.size() % ConsoleHeapKeys::kUpdateWords == 0); + EXPECT(!keys.has_updates()); + // The reference: ranges first (checked only), then keys, else a miss. + ConsoleHeapTables ranges; + ranges.ranges = {{0x10000, 0x20000, 0x400000, true}, {0x30000, 0x40000, 0x500000, false}}; + ConsoleHeapKeys k2(8); + std::uint32_t w[8] = {}; + vsharp(w, 0x10100, 16, 4, 0); + EXPECT(leonida::console_heap_translate_slot(w, ranges, k2) == 0); + EXPECT(w[0] == 0x400100 && (w[1] & 0xffff) == 0 && w[2] == 4); + vsharp(w, 0x1ff00, 16, 32, 0); // 512 bytes past a range with 256 left: no records + EXPECT(leonida::console_heap_translate_slot(w, ranges, k2) == 0 && !w[0] && !w[1] && !w[2]); + vsharp(w, 0x30000, 0, 64, 0); // an unchecked range: the key table, then a miss + EXPECT(leonida::console_heap_translate_slot(w, ranges, k2) == 1 && !w[2]); + // Backed spans leave a base as it is (before the key table); outside the ask table nothing is a miss. + ranges.backed = {{0x80000, 0x90000}}; + ranges.ask = {{0x30000, 0x40000}}; + ranges.use_ask = true; + vsharp(w, 0x80100, 0, 64, 0); + EXPECT(leonida::console_heap_translate_slot(w, ranges, k2) == 0 && w[0] == 0x80100 && w[2] == 64); + vsharp(w, 0x8ffc0, 0, 128, 0); // runs past the span: not backed, outside ask: no records, no miss + EXPECT(leonida::console_heap_translate_slot(w, ranges, k2) == 0 && !w[2]); + vsharp(w, 0x30000, 0, 64, 0); // in ask: a miss + EXPECT(leonida::console_heap_translate_slot(w, ranges, k2) == 1); + // Signed offsets: a base with bit 47 set is the negative shader VA it names. + ranges.signed_offsets = true; + ranges.backed = {{0xffff800000000000ull, 0xffff800000010000ull}}; + vsharp(w, 0x800000000100ull, 0, 64, 0); + EXPECT(leonida::console_heap_translate_slot(w, ranges, k2) == 0 && w[2] == 64); + std::vector> spans{{10, 20}, {15, 30}, {30, 40}, {50, 60}, {5, 5}}; + leonida::merge_console_heap_spans(spans); + EXPECT(spans.size() == 2 && spans[0].first == 10 && spans[0].second == 40 && spans[1].first == 50); + return 0; +} + +struct Case { + ConsoleHeapTables t; + std::vector& ranges = t.ranges; + ConsoleHeapKeys keys{14}; +}; + +// Random slot words over a mix of classes; bases drawn from the ranges and keys so every path is taken. +void make_slots(std::mt19937& rng, std::uint32_t* words, std::size_t slots, Case& c, + std::vector& entered) { + std::uniform_int_distribution any; + for (std::size_t s = 0; s < slots; ++s) { + std::uint32_t* w = words + 8 * s; + for (int i = 0; i < 8; ++i) w[i] = any(rng); + const std::uint32_t kind = any(rng) % 10; + if (kind == 0) { // T#: TYPE >= 8 + w[3] = (w[3] & 0x0fffffffu) | 0x80000000u; + continue; + } + if (kind == 1) { // other words with bits 30-31 set + w[3] |= 0x40000000u; + continue; + } + if (kind == 2) { + std::memset(w, 0, 32); + continue; + } + for (int half = 0; half < 2; ++half) { + std::uint32_t* k = w + 4 * half; + const std::uint32_t pick = any(rng) % 8; + const std::uint32_t stride = any(rng) % 3 == 0 ? 0 : any(rng) % 64; + const std::uint32_t records = 1 + any(rng) % 256; + if (pick < 3 && !c.ranges.empty()) { + const auto& r = c.ranges[any(rng) % c.ranges.size()]; + vsharp(k, r.title_va + any(rng) % (r.end - r.title_va), stride, records, any(rng)); + } else if (pick < 5) { + vsharp(k, 0x200000000ull + (any(rng) % 4096) * 64, stride, records, any(rng)); + if (pick == 3) { + const ConsoleHeapKeys::Key key{k[0], k[1], k[2], k[3]}; + const bool none = any(rng) % 4 == 0; + if (c.keys.put(key, 0x10000000ull + (any(rng) % 65536) * 256, 4096, none)) entered.push_back(key); + } + } else if (pick == 5) { + vsharp(k, 0, stride, records, any(rng)); + } else if (pick == 6) { + vsharp(k, 0x300000000ull + any(rng), stride, 0, any(rng)); // no records: left as it is + } else if (half == 1) { + k[3] |= 0x40000000u; // a counter half that is no V# + } else { + vsharp(k, 0x400000000ull + any(rng), stride, records, any(rng)); // nowhere: a miss + } + } + } +} + +} // namespace + +int main() { + if (const int failed = keys_on_cpu()) return failed; + std::puts("console heap keys (CPU): ok"); + + vktest::Device d; + d.request_buffer_device_address = true; + const auto status = d.initialize(); + if (status == vktest::DeviceStatus::unavailable || (status == vktest::DeviceStatus::ready && !d.buffer_device_address)) { + std::printf("vk_console_heap_gpu_test: no Vulkan device with bufferDeviceAddress, skipped\n"); + return 77; + } + if (status != vktest::DeviceStatus::ready) return 1; + VkPhysicalDeviceMemoryProperties memory{}; + d.instance_fn("vkGetPhysicalDeviceMemoryProperties")(d.physical, &memory); + + leonida::ConsoleHeapGpu gpu(d.device_proc, d.device, memory, 14); + EXPECT(gpu.init()); + + constexpr std::uint32_t kSlots = 6000; + void* input_data = nullptr; + void* copy_data = nullptr; + const VkBuffer input = d.buffer(VkDeviceSize(kSlots) * 32, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &input_data); + const VkBuffer copy = d.buffer(VkDeviceSize(kSlots) * 32, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, ©_data); + EXPECT(input && copy && input_data && copy_data); + const int heap = gpu.add_heap(d.device_address(input), d.device_address(copy), kSlots); + EXPECT(heap >= 0); + auto* in = static_cast(input_data); + auto* out = static_cast(copy_data); + + std::mt19937 rng(1234); + Case c; + c.ranges = {{0x10000, 0x30000, 0x100000, true}, + {0x40000, 0x48000, 0x0000ffff00000000ull, true}, // bits 32-47 of the answer + {0x50000, 0x60000, 0x200000, false}, + {0x100000000ull, 0x100100000ull, 0x300000, true}}; + std::vector entered; + make_slots(rng, in, kSlots, c, entered); + // The GPU's mirror gets the same keys. + gpu.with_keys([&](ConsoleHeapKeys& k) { + for (const auto& key : entered) { + std::uint64_t to = 0; + bool none = false; + c.keys.lookup(key, to, none); + k.put(key, to, 4096, none); + } + return 0; + }); + gpu.set_ranges(c.ranges); + + // One round: the listed slots are written as the reference says, the others keep the marker, and the misses + // are the reference's. + auto round = [&](const std::vector& listed, std::uint64_t ticket, bool expect_overflow) -> int { + std::memset(out, 0xcd, std::size_t(kSlots) * 32); + gpu.queue(heap, listed.begin(), listed.end()); + bool recorded = false; + EXPECT(d.run([&](VkCommandBuffer cb) { return recorded = gpu.record(cb); })); + EXPECT(recorded); + gpu.commit(true, ticket); + std::set misses; + bool overflowed = false; + gpu.drain(ticket, [&](int h, std::uint32_t slot, std::uint32_t half) { + if (h == heap) misses.insert(slot * 2 + half); + }, [&](int) { overflowed = true; }); + EXPECT(gpu.in_flight() == 0); + EXPECT(overflowed == expect_overflow); + std::set expected_misses; + std::vector is_listed(kSlots, 0); + for (const std::uint32_t s : listed) is_listed[s] = 1; + for (std::uint32_t s = 0; s < kSlots; ++s) { + std::uint32_t w[8]; + std::memcpy(w, in + 8 * s, 32); + if (!is_listed[s]) { + for (int i = 0; i < 8; ++i) EXPECT(out[8 * s + i] == 0xcdcdcdcdu); + continue; + } + const unsigned missed = leonida::console_heap_translate_slot(w, c.t, c.keys); + if (missed & 1) expected_misses.insert(s * 2); + if (missed & 2) expected_misses.insert(s * 2 + 1); + if (std::memcmp(w, out + 8 * s, 32)) { + std::fprintf(stderr, "slot %u: in %08x %08x %08x %08x %08x %08x %08x %08x\n", s, in[8 * s], + in[8 * s + 1], in[8 * s + 2], in[8 * s + 3], in[8 * s + 4], in[8 * s + 5], in[8 * s + 6], + in[8 * s + 7]); + std::fprintf(stderr, " gpu %08x %08x %08x %08x %08x %08x %08x %08x\n", out[8 * s], out[8 * s + 1], + out[8 * s + 2], out[8 * s + 3], out[8 * s + 4], out[8 * s + 5], out[8 * s + 6], + out[8 * s + 7]); + std::fprintf(stderr, " cpu %08x %08x %08x %08x %08x %08x %08x %08x\n", w[0], w[1], w[2], w[3], w[4], + w[5], w[6], w[7]); + return 1; + } + } + if (!expect_overflow) EXPECT(misses == expected_misses); + else EXPECT(misses.size() == leonida::ConsoleHeapGpu::kMissCapacity); + std::printf(" %zu slots, %zu misses\n", listed.size(), misses.size()); + return 0; + }; + + std::vector all(kSlots); + for (std::uint32_t s = 0; s < kSlots; ++s) all[s] = s; + EXPECT(round(all, 1, false) == 0); + std::puts("console heap pass, every slot: ok"); + + // Key table updates and a new range table: erase some keys, enter answers for some misses, move a range. + std::vector some; + for (std::uint32_t s = 0; s < kSlots; s += 3) some.push_back(s); + std::size_t erased = 0, added = 0; + for (std::size_t i = 0; i < entered.size(); i += 2) { + c.keys.erase(entered[i]); + gpu.with_keys([&](ConsoleHeapKeys& k) { return k.erase(entered[i]); }); + ++erased; + } + for (std::uint32_t s = 0; s < kSlots && added < 200; ++s) { + std::uint32_t w[8]; + std::memcpy(w, in + 8 * s, 32); + std::uint32_t copy_w[8]; + std::memcpy(copy_w, w, 32); + const unsigned missed = leonida::console_heap_translate_slot(copy_w, c.t, c.keys); + if (!(missed & 1)) continue; + const ConsoleHeapKeys::Key key{w[0], w[1], w[2], w[3]}; + c.keys.put(key, 0x7000000000ull + added * 64, 64, added % 5 == 0); + gpu.with_keys([&](ConsoleHeapKeys& k) { return k.put(key, 0x7000000000ull + added * 64, 64, added % 5 == 0); }); + ++added; + } + c.ranges[0].shader_va = 0x900000; + c.ranges[2].checked = true; + gpu.set_ranges(c.ranges); + EXPECT(round(some, 2, false) == 0); + std::printf("console heap pass, %zu keys erased, %zu entered, ranges moved: ok\n", erased, added); + + // A submission that did not reach the queue: its slots and updates come back for the next pass. + { + const ConsoleHeapKeys::Key key{in[8 * 5], in[8 * 5 + 1], in[8 * 5 + 2], in[8 * 5 + 3]}; + gpu.queue(heap, 5); + bool recorded = false; + EXPECT(d.run([&](VkCommandBuffer cb) { return recorded = gpu.record(cb); })); + EXPECT(recorded && !gpu.pending()); + gpu.commit(false, 0); + EXPECT(gpu.pending() && gpu.in_flight() == 0); + (void)key; + } + EXPECT(round({5}, 3, false) == 0); + // Backed and ask tables: part of the keyed bases become backed (answered before the key table), and only bases + // in the ask span miss. + c.t.backed = {{0x200000000ull, 0x200008000ull}, {0x10000ull, 0x18000ull}}; + c.t.ask = {{0x400000000ull, 0x500000000ull}}; + c.t.use_ask = true; + gpu.set_spans(leonida::ConsoleHeapGpu::backed_table, c.t.backed); + gpu.set_spans(leonida::ConsoleHeapGpu::ask_table, c.t.ask); + EXPECT(round(all, 7, false) == 0); + std::puts("console heap pass, backed and ask tables: ok"); + { + // kZeroFirst: words that are no buffer pair and no T# get dwords 0-3 zeroed; the last queue() decides. + std::vector flagged; + for (std::uint32_t s2 = 0; s2 < kSlots && flagged.size() < 64; ++s2) + if (in[8 * s2 + 3] >> 30) flagged.push_back(s2); + EXPECT(flagged.size() == 64); + std::memset(out, 0xcd, std::size_t(kSlots) * 32); + for (std::size_t i = 0; i < flagged.size(); ++i) { + gpu.queue(heap, flagged[i] | leonida::ConsoleHeapGpu::kZeroFirst); + if (i % 2) gpu.queue(heap, flagged[i]); // queued again without the bit: copied as it is + } + bool recorded = false; + EXPECT(d.run([&](VkCommandBuffer cb) { return recorded = gpu.record(cb); })); + gpu.commit(true, 8); + gpu.drain(8, [](int, std::uint32_t, std::uint32_t) {}, [](int) {}); + EXPECT(recorded); + for (std::size_t i = 0; i < flagged.size(); ++i) { + std::uint32_t w[8]; + std::memcpy(w, in + 8 * flagged[i], 32); + leonida::console_heap_translate_slot(w, c.t, c.keys, i % 2 == 0); + EXPECT(!std::memcmp(w, out + 8 * flagged[i], 32)); + if (i % 2 == 0) EXPECT(!out[8 * flagged[i]] && !out[8 * flagged[i] + 3]); + } + } + std::puts("console heap pass, words that are no descriptor: ok"); + { + // rescan(): one range dispatch rewrites the buffer pairs of [0, n) and leaves every other slot as it was. + constexpr std::uint32_t n = 4000; + std::memset(out, 0xcd, std::size_t(kSlots) * 32); + gpu.rescan(heap, n); + EXPECT(gpu.pending()); + bool recorded = false; + EXPECT(d.run([&](VkCommandBuffer cb) { return recorded = gpu.record(cb); })); + gpu.commit(true, 9); + std::set misses; + gpu.drain(9, [&](int h, std::uint32_t slot, std::uint32_t half) { if (h == heap) misses.insert(slot * 2 + half); }, + [](int) {}); + EXPECT(recorded); + std::set expected; + std::size_t pairs = 0; + for (std::uint32_t s2 = 0; s2 < kSlots; ++s2) { + std::uint32_t w[8]; + std::memcpy(w, in + 8 * s2, 32); + if (s2 >= n || (w[3] >> 30)) { + for (int i = 0; i < 8; ++i) EXPECT(out[8 * s2 + i] == 0xcdcdcdcdu); + continue; + } + ++pairs; + const unsigned missed = leonida::console_heap_translate_slot(w, c.t, c.keys); + if (missed & 1) expected.insert(s2 * 2); + if (missed & 2) expected.insert(s2 * 2 + 1); + EXPECT(!std::memcmp(w, out + 8 * s2, 32)); + } + EXPECT(misses == expected && pairs > 1000); + EXPECT(!gpu.pending()); + } + std::puts("console heap pass, range rescan: ok"); + { + // rescan_filtered(): only the slots whose metadata (left by the last pass over them, the rescan above) meets a + // change span are translated again: a title span holding one slot's base, a shader span holding another's + // result. The rest keep what they hold, without the title's words being read. + constexpr std::uint32_t n = 4000; + struct Half { + std::uint64_t base, to, span; + }; + std::vector> meta(n); + std::vector pair(n, false); + for (std::uint32_t s2 = 0; s2 < n; ++s2) { + std::uint32_t w[8]; + std::memcpy(w, in + 8 * s2, 32); + if (w[3] >> 30) continue; + pair[s2] = true; + std::uint32_t before[8]; + std::memcpy(before, w, 32); + leonida::console_heap_translate_slot(w, c.t, c.keys); + for (int h = 0; h < 2; ++h) { + const std::uint32_t* b = before + 4 * h; + const std::uint32_t* a = w + 4 * h; + if (!b[2]) { + meta[s2][h] = {}; + continue; + } + const std::uint64_t stride = (b[1] >> 16) & 0x3fff; + const std::uint64_t span = std::min(std::uint64_t(b[2]) * std::max(stride, 1), + 0xffffffffull); + meta[s2][h] = {b[0] | (std::uint64_t(b[1] & 0xffff) << 32), + a[2] ? a[0] | (std::uint64_t(a[1] & 0xffff) << 32) : 0, span}; + } + } + std::uint32_t by_title = UINT32_MAX, by_result = UINT32_MAX; + for (std::uint32_t s2 = 0; s2 < n; ++s2) { + if (!pair[s2] || !meta[s2][0].span) continue; + if (by_title == UINT32_MAX) by_title = s2; + else if (meta[s2][0].to && meta[s2][0].to != meta[by_title][0].base) { + by_result = s2; + break; + } + } + EXPECT(by_title != UINT32_MAX && by_result != UINT32_MAX); + const leonida::ConsoleHeapSpans title{{meta[by_title][0].base, meta[by_title][0].base + 1}}; + const leonida::ConsoleHeapSpans shader{{meta[by_result][0].to, meta[by_result][0].to + 1}}; + const auto meets = [](const leonida::ConsoleHeapSpans& spans, std::uint64_t v, std::uint64_t bytes) { + for (const auto& [a, b] : spans) + if (v < b && a < v + bytes) return true; + return false; + }; + std::set touched; + for (std::uint32_t s2 = 0; s2 < n; ++s2) + for (const Half& h : meta[s2]) { + if (!pair[s2] || !h.span) continue; + if (meets(title, h.base, 1) || meets(shader, h.base, h.span) || (h.to && meets(shader, h.to, h.span))) + touched.insert(s2); + } + EXPECT(touched.count(by_title) && touched.count(by_result) && touched.size() < 1000); + std::memset(out, 0xcd, std::size_t(kSlots) * 32); + const auto before = gpu.take_stats(); + (void)before; + gpu.rescan_filtered(heap, n, shader, title); + EXPECT(gpu.pending()); + bool recorded = false; + EXPECT(d.run([&](VkCommandBuffer cb) { return recorded = gpu.record(cb); })); + gpu.commit(true, 10); + gpu.drain(10, [](int, std::uint32_t, std::uint32_t) {}, [](int) {}); + EXPECT(recorded && !gpu.pending()); + for (std::uint32_t s2 = 0; s2 < kSlots; ++s2) { + if (!touched.count(s2)) { + for (int i = 0; i < 8; ++i) EXPECT(out[8 * s2 + i] == 0xcdcdcdcdu); + continue; + } + std::uint32_t w[8]; + std::memcpy(w, in + 8 * s2, 32); + leonida::console_heap_translate_slot(w, c.t, c.keys); + EXPECT(!std::memcmp(w, out + 8 * s2, 32)); + } + EXPECT(gpu.take_stats().filtered == n); + // A failed submission: the filtered rescan and its spans come back, and the next pass does them. + std::memset(out, 0xcd, std::size_t(kSlots) * 32); + gpu.rescan_filtered(heap, n, shader, title); + EXPECT(d.run([&](VkCommandBuffer cb) { return recorded = gpu.record(cb); })); + gpu.commit(false, 0); + EXPECT(gpu.pending()); + EXPECT(d.run([&](VkCommandBuffer cb) { return recorded = gpu.record(cb); })); + gpu.commit(true, 11); + gpu.drain(11, [](int, std::uint32_t, std::uint32_t) {}, [](int) {}); + std::size_t rewritten = 0; + for (std::uint32_t s2 = 0; s2 < n; ++s2) rewritten += out[8 * s2] != 0xcdcdcdcdu || out[8 * s2 + 3] != 0xcdcdcdcdu; + EXPECT(rewritten == touched.size()); + std::printf("console heap pass, filtered rescan: ok (%zu of %u slots)\n", touched.size(), n); + } + { + // queue_copy(): buffer copies recorded at the start of the pass; their keepalive goes once the pass retires. + constexpr VkDeviceSize kBytes = 64 * 1024; + void* src_data = nullptr; + void* dst_data = nullptr; + const VkBuffer src = d.buffer(kBytes, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &src_data); + const VkBuffer dst = d.buffer(kBytes, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &dst_data); + EXPECT(src && dst && src_data && dst_data); + auto* sw = static_cast(src_data); + for (std::size_t i = 0; i < kBytes / 4; ++i) sw[i] = std::uint32_t(i * 2654435761u); + std::memset(dst_data, 0, kBytes); + auto keep = std::make_shared(7); + std::weak_ptr watch = keep; + gpu.queue_copy(src, 4096, dst, 0, 8192, keep); + gpu.queue_copy(src, 0, dst, 32768, 4096, keep); + keep.reset(); + EXPECT(gpu.pending() && !watch.expired()); + bool recorded = false; + EXPECT(d.run([&](VkCommandBuffer cb) { return recorded = gpu.record(cb); })); + EXPECT(recorded && !watch.expired()); + gpu.commit(true, 10); + gpu.drain(10, [](int, std::uint32_t, std::uint32_t) {}, [](int) {}); + EXPECT(watch.expired()); + const auto* dw = static_cast(dst_data); + EXPECT(!std::memcmp(dw, static_cast(src_data) + 4096, 8192)); + EXPECT(!std::memcmp(dw + 32768, src_data, 4096)); + EXPECT(dw[8192] == 0 && dw[32768 + 4096] == 0); + } + std::puts("console heap pass, queued copies: ok"); + c.t.backed.clear(); + c.t.ask = {{0, ~0ull}}; // everything asks again: the overflow cases below need their misses + gpu.set_spans(leonida::ConsoleHeapGpu::backed_table, c.t.backed); + gpu.set_spans(leonida::ConsoleHeapGpu::ask_table, c.t.ask); + std::puts("console heap pass, failed submission queued again: ok"); + + // More misses than the list holds: the overflow is reported, and the slots are still written. + { + constexpr std::uint32_t kStride = 0; + for (std::uint32_t s = 0; s < kSlots; ++s) { + vsharp(in + 8 * s, 0x500000000ull + s * 0x100, kStride, 16, 0); + vsharp(in + 8 * s + 4, 0x600000000ull + s * 0x100, kStride, 16, 0); + } + std::vector many; + for (std::uint32_t s = 0; s < kSlots; ++s) many.push_back(s); + // 12,000 misses fit; list them twice over with a second heap view of the same buffers to pass 65,536. + const int heap2 = gpu.add_heap(d.device_address(input), d.device_address(copy), kSlots); + EXPECT(heap2 >= 0); + std::size_t total = 0; + for (int h = 0; h < 6; ++h) { // 6 x 12,000 = 72,000 misses in one pass over the two heaps + gpu.queue(h % 2 ? heap2 : heap, many.begin(), many.end()); + total += 2 * many.size(); + } + (void)total; + bool recorded = false; + EXPECT(d.run([&](VkCommandBuffer cb) { return recorded = gpu.record(cb); })); + // Queued twice per heap only counts once: 2 heaps x 12,000 = 24,000 misses, under the list. Queue a heap of + // its own instead to pass it. + gpu.commit(true, 4); + std::size_t misses = 0; + bool overflowed = false; + gpu.drain(4, [&](int, std::uint32_t, std::uint32_t) { ++misses; }, [&](int) { overflowed = true; }); + EXPECT(recorded && misses == 24000 && !overflowed); + gpu.remove_heap(heap2); + } + std::puts("console heap pass, a slot queued twice is translated once: ok"); + { + // Six heap views of the same buffers: 6 x 12,000 = 72,000 misses, past the list's 65,536. + std::vector views; + for (int i = 0; i < 5; ++i) views.push_back(gpu.add_heap(d.device_address(input), d.device_address(copy), kSlots)); + std::vector many; + for (std::uint32_t s = 0; s < kSlots; ++s) many.push_back(s); + gpu.queue(heap, many.begin(), many.end()); + for (const int v : views) { + EXPECT(v >= 0); + gpu.queue(v, many.begin(), many.end()); + } + bool recorded = false; + EXPECT(d.run([&](VkCommandBuffer cb) { return recorded = gpu.record(cb); })); + gpu.commit(true, 5); + std::size_t misses = 0; + bool overflowed = false; + gpu.drain(5, [&](int, std::uint32_t, std::uint32_t) { ++misses; }, [&](int) { overflowed = true; }); + EXPECT(recorded && overflowed && misses == leonida::ConsoleHeapGpu::kMissCapacity); + for (std::uint32_t s = 0; s < kSlots; ++s) EXPECT(out[8 * s] == 0 && out[8 * s + 2] == 0); + for (const int v : views) gpu.remove_heap(v); + } + std::puts("console heap pass, miss list overflow: ok"); + { + // Clustered words (bases a megabyte apart) entered in both tables: every slot answered, none missed. + Case clustered; + for (std::uint32_t s2 = 0; s2 < 3000; ++s2) { + for (int half = 0; half < 2; ++half) { + const std::uint32_t i = 2 * s2 + std::uint32_t(half); + std::uint32_t* k = in + 8 * s2 + 4 * half; + vsharp(k, 0x700000000ull + (std::uint64_t(i) << 20), 16, 8, 0x2000); + const ConsoleHeapKeys::Key key{k[0], k[1], k[2], k[3]}; + EXPECT(clustered.keys.put(key, 0x1000000ull + i * 256ull, 128, (i % 7) == 0)); + EXPECT(gpu.with_keys([&](ConsoleHeapKeys& keys) { + return keys.put(key, 0x1000000ull + i * 256ull, 128, (i % 7) == 0); + })); + } + } + std::swap(c.keys, clustered.keys); + c.ranges.clear(); + gpu.set_ranges(c.ranges); + EXPECT(round(all, 6, false) == 0); + } + std::puts("console heap pass, clustered words: ok"); + const auto stats = gpu.take_stats(); + std::printf("console heap pass: %llu passes, %llu slots, %llu updates, %llu misses, %llu overflows, %llu failed\n", + (unsigned long long)stats.passes, (unsigned long long)stats.slots, (unsigned long long)stats.updates, + (unsigned long long)stats.misses, (unsigned long long)stats.overflows, + (unsigned long long)stats.failed); + EXPECT(d.validation_errors() == 0); + std::puts("vk_console_heap_gpu_test: ok"); + return 0; +} diff --git a/runtime/test/vk_descriptor_bench.cpp b/runtime/test/vk_descriptor_bench.cpp index 3dd1792687..c048f3745d 100644 --- a/runtime/test/vk_descriptor_bench.cpp +++ b/runtime/test/vk_descriptor_bench.cpp @@ -710,7 +710,8 @@ bool build_dataset(std::uint32_t entry_count, TableDataset& out) { for (std::uint32_t i = 0; i < out.t_count; ++i) { t_keys[i] = make_bench_tsharp(i + 1u); - table.insert(t_keys[i], 1u + i); + // The T#s name sampled 2D images (the tagged contract's kind word): a bench entry carries the same word. + table.insert(t_keys[i], 1u + i, leonida::kind_sampled_bit(0)); } for (std::uint32_t i = 0; i < out.s_count; ++i) { s_keys[i] = make_bench_ssharp(i + 1u); diff --git a/runtime/test/vk_harness.cpp b/runtime/test/vk_harness.cpp index cd374e8b6f..872e30b936 100644 --- a/runtime/test/vk_harness.cpp +++ b/runtime/test/vk_harness.cpp @@ -929,7 +929,8 @@ int main(int argc, char** argv) { LOADD(vkCreateSampler); LOADD(vkCreateDescriptorPool); LOADD(vkAllocateDescriptorSets); LOADD(vkUpdateDescriptorSets); leonida::DescriptorTable desc_table(16); - desc_table.insert(tsharp, 1); + // The translated modules read the entry's kind (descriptor_table.h): this T# is a sampled 2D image. + desc_table.insert(tsharp, 1, leonida::kind_sampled_bit(0)); desc_table.insert(ssharp, 1); const auto table = desc_table.build_gpu_buffer(true); VkBuffer tb = VK_NULL_HANDLE; diff --git a/runtime/test/vk_host_texture_order_test.cpp b/runtime/test/vk_host_texture_order_test.cpp index 34120f00e5..f7aae702f9 100644 --- a/runtime/test/vk_host_texture_order_test.cpp +++ b/runtime/test/vk_host_texture_order_test.cpp @@ -7,13 +7,21 @@ namespace { unsigned waits = 0; VkResult wait_result = VK_SUCCESS; -VkResult VKAPI_CALL idle(VkDevice) { ++waits; return wait_result; } +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) { + ++waits; + last_timeout = timeout; + return info && info->semaphoreCount ? wait_result : VK_ERROR_UNKNOWN; +} +VkResult VKAPI_CALL device_idle(VkDevice) { return VK_ERROR_UNKNOWN; } // must not be called any more PFN_vkVoidFunction VKAPI_CALL no_proc(VkDevice, const char*) { return nullptr; } } int main() { leonida::VulkanContext ctx(no_proc, VK_NULL_HANDLE, false); - ctx.vk.vkDeviceWaitIdle = idle; + ctx.vk.vkWaitSemaphores = wait_semaphores; + ctx.vk.vkDeviceWaitIdle = device_idle; leonida::ResourceBinding binding{}; binding.image = reinterpret_cast(1); binding.mip_levels = 1; @@ -32,14 +40,22 @@ int main() { contender.join(); return !raced; }; - ctx.note_image_work_locked(); - if (ctx.write_host_texture(2, 0, copy) != VK_NOT_READY || copies || waits) return 1; - if (ctx.write_host_texture(1, 0, copy) != VK_SUCCESS || copies != 1 || waits != 1) return 1; - if (ctx.write_host_texture(1, 0, copy) != VK_SUCCESS || copies != 2 || waits != 1) return 1; - ctx.note_image_work_locked(); + const auto progress = reinterpret_cast(std::uintptr_t{0x10}); + const auto submit = [&] { // a queue submission in flight: a retirement ticket, and image work pending + 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 != 2) return 1; + 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 != 2) return 1; - std::puts("ordered texture upload: layout, submit exclusion, wait reuse, wait failure passed"); + if (stats.copies != 2 || stats.waits != 3) return 7; + std::puts("ordered texture upload: layout, submit exclusion, bounded timeline wait, reuse, timeout, loss passed"); } diff --git a/runtime/test/vk_image_fuzz.cpp b/runtime/test/vk_image_fuzz.cpp index 52b59d6e04..cc645e6d3c 100644 --- a/runtime/test/vk_image_fuzz.cpp +++ b/runtime/test/vk_image_fuzz.cpp @@ -495,7 +495,7 @@ int main(int argc, char** argv) { std::fprintf(stderr, "FAILED add_image -> 0 (line %d)\n", __LINE__); return 1; } - set->insert_key(make_tsharp_key(spec.tsharp), index); + set->insert_key(make_tsharp_key(spec.tsharp), index, ImageDimension::dim_2d); const VkPushConstantRange push{.stageFlags = VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, .size = push_bytes}; const VkDescriptorSetLayout set_layout = set->layout(); VkPipelineLayoutCreateInfo pli{.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, diff --git a/runtime/test/vk_pipeline_check.cpp b/runtime/test/vk_pipeline_check.cpp index 0e39d0f621..3e76f7a625 100644 --- a/runtime/test/vk_pipeline_check.cpp +++ b/runtime/test/vk_pipeline_check.cpp @@ -30,6 +30,9 @@ // --cache-feedback count each stage's successful pipelines by VkPipelineCreationFeedback: hits (VALID and // APPLICATION_PIPELINE_CACHE_HIT), no hit reported (VALID only) and unavailable (no VALID bit, or a // pre-1.3 device without VK_EXT_pipeline_creation_feedback). The three add up to the ok count. +// --nv-diagnostics create the device with VK_NV_device_diagnostics_config and the flags the runtime's +// LEONIDA_DEVICE_FAULT=1 / LEONIDA_AFTERMATH=1 use (shader debug info, resource tracking, automatic +// checkpoints), to measure what that does to compile times and to cache hits // --isolate check in child processes, --isolate-batch modules at a time (default 256), so a module // that kills the driver is recorded as failed ("MODULE CRASH") and the pass // goes on. A crashed batch is bisected to the module. Children run one after the other and share @@ -806,7 +809,7 @@ int main(int argc, char** argv) { unsigned large_parallel = 0; // 0 = by the memory budget double slow = 30.0; std::string stage_filter = "all"; - bool cache_feedback = false, isolate = false, iso_child = false; + bool cache_feedback = false, isolate = false, iso_child = false, nv_diagnostics = false; size_t isolate_batch = 256; for (int i = 2; i < argc; i++) { std::string a = argv[i]; @@ -851,6 +854,7 @@ int main(int argc, char** argv) { else if (a == "--skip-file") valid = !(skip_path = value()).empty(); else if (a == "--cache-feedback") cache_feedback = true; else if (a == "--isolate") isolate = true; + else if (a == "--nv-diagnostics") nv_diagnostics = true; else if (a == "--isolate-child") iso_child = true; // internal: the parent's child runs else if (a == "--isolate-batch") { // parsed like the other numbers (#1735); at least one per batch valid = number(isolate_batch); @@ -1158,6 +1162,13 @@ int main(int argc, char** argv) { #endif VkPhysicalDeviceShaderClockFeaturesKHR clock{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_CLOCK_FEATURES_KHR}; const bool ext_clock = link(&clock, reinterpret_cast(&clock), VK_KHR_SHADER_CLOCK_EXTENSION_NAME, want_clock); + VkPhysicalDeviceDiagnosticsConfigFeaturesNV diag_features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DIAGNOSTICS_CONFIG_FEATURES_NV}; + const bool ext_diag = link(&diag_features, reinterpret_cast(&diag_features), + VK_NV_DEVICE_DIAGNOSTICS_CONFIG_EXTENSION_NAME, nv_diagnostics); + if (nv_diagnostics && !ext_diag) { + std::fprintf(stderr, "--nv-diagnostics: the device has no %s\n", VK_NV_DEVICE_DIAGNOSTICS_CONFIG_EXTENSION_NAME); + return 1; + } const bool ext_exe = link(&exe, reinterpret_cast(&exe), VK_KHR_PIPELINE_EXECUTABLE_PROPERTIES_EXTENSION_NAME, !stats_path.empty()); if (!stats_path.empty() && !ext_exe) { @@ -1201,6 +1212,15 @@ int main(int argc, char** argv) { VkDeviceCreateInfo dci{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO}; dci.queueCreateInfoCount = 1; dci.pQueueCreateInfos = &qci; dci.pNext = &f2; dci.enabledExtensionCount = uint32_t(enable.size()); dci.ppEnabledExtensionNames = enable.data(); + VkDeviceDiagnosticsConfigCreateInfoNV diag_config{VK_STRUCTURE_TYPE_DEVICE_DIAGNOSTICS_CONFIG_CREATE_INFO_NV}; + if (ext_diag) { + diag_config.flags = VK_DEVICE_DIAGNOSTICS_CONFIG_ENABLE_SHADER_DEBUG_INFO_BIT_NV | + VK_DEVICE_DIAGNOSTICS_CONFIG_ENABLE_RESOURCE_TRACKING_BIT_NV | + VK_DEVICE_DIAGNOSTICS_CONFIG_ENABLE_AUTOMATIC_CHECKPOINTS_BIT_NV; + diag_config.pNext = dci.pNext; + dci.pNext = &diag_config; + std::printf("device: VK_NV_device_diagnostics_config on (shader debug info, resource tracking, checkpoints)\n"); + } VkDevice dev; if (VkResult r = vkCreateDevice(pd, &dci, nullptr, &dev)) { std::fprintf(stderr, "vkCreateDevice %d\n", r); return 1; } leonida::SubgroupSizeCaps runtime_subgroups; diff --git a/runtime/test/vk_presenter_sparse_capture.h b/runtime/test/vk_presenter_sparse_capture.h new file mode 100644 index 0000000000..fc833e4ad0 --- /dev/null +++ b/runtime/test/vk_presenter_sparse_capture.h @@ -0,0 +1,192 @@ +// The positive-only cadence oracle in vk_presenter_sync_test.cpp. Included after its driver counters. +#pragma once + +namespace sparse_test { +namespace fs = std::filesystem; +using RGB = std::array; +constexpr RGB red{255, 0, 0}, blue{0, 0, 255}, black{0, 0, 0}; + +// Own a newly created owner/SYSTEM-only directory. Never reuse or recursively remove an existing tree. +struct Folder { + fs::path path; + bool create(const char* tag) { + auto candidate = fs::temp_directory_path() / (std::string("leonida-sparse-") + tag + "-" + + std::to_string(GetCurrentProcessId()) + "-" + std::to_string(GetTickCount64())); + PSECURITY_DESCRIPTOR sd = nullptr; + if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(L"D:P(A;OICI;FA;;;OW)(A;OICI;FA;;;SY)", + SDDL_REVISION_1, &sd, nullptr)) return false; + SECURITY_ATTRIBUTES sa{sizeof(sa), sd, FALSE}; + const bool fresh = CreateDirectoryW(candidate.c_str(), &sa) != FALSE; + LocalFree(sd); + if (fresh) path = std::move(candidate); + return fresh; + } + ~Folder() { + if (path.empty()) return; + std::error_code ec; + for (auto name : {"index.txt", "frame_00001.ppm", "frame_00004.ppm"}) fs::remove(path / name, ec); + fs::remove(path, ec); // leave unknown contents alone on failure + } +}; +const char* sdr_format(VkFormat f) { + switch (f) { + case VK_FORMAT_B8G8R8A8_UNORM: return "VK_FORMAT_B8G8R8A8_UNORM"; + case VK_FORMAT_B8G8R8A8_SRGB: return "VK_FORMAT_B8G8R8A8_SRGB"; + case VK_FORMAT_R8G8B8A8_UNORM: return "VK_FORMAT_R8G8B8A8_UNORM"; + case VK_FORMAT_R8G8B8A8_SRGB: return "VK_FORMAT_R8G8B8A8_SRGB"; + default: return nullptr; + } +} +bool disk_matches(const fs::path& dir, VkExtent2D extent, VkFormat fmt, RGB fourth) { + std::set names; + for (const auto& e : fs::directory_iterator(dir)) { + if (!fs::is_regular_file(e.symlink_status())) return false; + names.insert(e.path().filename()); + } + if (names != std::set{"index.txt", "frame_00001.ppm", "frame_00004.ppm"} || !sdr_format(fmt)) return false; + const auto w=extent.width, h=extent.height; + if (!w || !h || w>1024 || h>1024) return false; + const std::string header="P6\n"+std::to_string(w)+" "+std::to_string(h)+"\n255\n"; + std::ifstream index(dir/"index.txt"); + for (const int n : {1,4}) { + const RGB color = n==1 ? red : fourth; + const fs::path file=dir/(n==1 ? "frame_00001.ppm":"frame_00004.ppm"); + if (fs::file_size(file)!=header.size()+3ull*w*h) return false; + std::string expected=header; + expected.reserve(header.size()+3ull*w*h); + for (size_t i=0; i(c)); + std::ifstream img(file,std::ios::binary); + std::string got(expected.size(),'\0'); + if (!img.read(got.data(),static_cast(got.size())) || got!=expected) return false; + const auto row="frame "+std::to_string(n)+" format "+std::to_string(int(fmt))+" ("+sdr_format(fmt)+") extent "+ + std::to_string(w)+"x"+std::to_string(h)+" mean rgb "+std::to_string(color[0])+".00 "+ + std::to_string(color[1])+".00 "+std::to_string(color[2])+".00"; + if (!std::getline(index,got) || got!=row) return false; + } + return index.peek()==std::char_traits::eof(); +} + +int run(vktest::Device& d, HWND window) { + using namespace leonida; + VulkanContext context(driver::get_device,d.device,true); + VulkanQueue queue(context,d.queue,d.family); + EXPECT(context.loaded() && queue.ok()); + const auto surface_fn=reinterpret_cast(d.instance_proc(d.instance,"vkCreateWin32SurfaceKHR")); + EXPECT(surface_fn); + // Two immutable RGBA8 test sources, filled on this queue once. present_blank supplies the third color. + for (ResourceId id : {1u,2u}) { + ResourceBinding rb{}; + rb.width=64;rb.height=64;rb.format=VK_FORMAT_R8G8B8A8_UNORM;rb.depth=rb.mip_levels=rb.array_layers=1; + rb.samples=1;rb.color_attachment=true;rb.sampled=true;rb.aspects=VK_IMAGE_ASPECT_COLOR_BIT; + rb.image=d.image(rb.format,rb.width,rb.height,1,VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | + VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT); + EXPECT(rb.image); + context.add_resource(id,rb,VK_IMAGE_LAYOUT_UNDEFINED); + CommandList list; + EXPECT(list.transition({id,0,d3d12_state::common,d3d12_state::render_target})); + EXPECT(list.clear_render_target({id,0,0,1},{id==1?1.f:0.f,0,id==2?1.f:0.f,1})); + EXPECT(list.transition({id,0,d3d12_state::render_target,d3d12_state::common}) && list.close()); + const CommandList* input=&list; + EXPECT(queue.execute({&input,1})==ReplayResult::success); + } + EXPECT(queue.idle()); + EXPECT(!_putenv_s("LEONIDA_CAPTURE_EVERY","3") && !_putenv_s("LEONIDA_CAPTURE_LIMIT","2") && + !_putenv_s("LEONIDA_CAPTURE_SOURCE","0")); + enum class Phase { sparse, final_pending, continuous, splash, composed }; + for (Phase p : {Phase::sparse,Phase::final_pending,Phase::continuous,Phase::splash,Phase::composed}) { + Folder folder; + EXPECT(folder.create(p==Phase::sparse?"sparse":p==Phase::final_pending?"pending":p==Phase::continuous?"explicit": + p==Phase::splash?"splash":"composed")); + EXPECT(!_putenv_s("LEONIDA_CAPTURE",folder.path.string().c_str())); + VkExtent2D extent{};VkFormat fmt{}; + { + VkWin32SurfaceCreateInfoKHR info{VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR}; + info.hinstance=GetModuleHandleW(nullptr);info.hwnd=window; + VkSurfaceKHR surface{};EXPECT(surface_fn(d.instance,&info,nullptr,&surface)==VK_SUCCESS); + VulkanPresenter present(context,driver::get_instance,d.instance,d.physical,d.queue,d.family,surface); + EXPECT(present.ok()); + if (p==Phase::continuous) EXPECT(present.enable_capture()); + const unsigned last = p==Phase::final_pending?4:p==Phase::splash?7:8; + for (unsigned n=1; n<=last; ++n) { + const bool disk=n==1 || n==4; + const bool replaced=p==Phase::splash && n>=2 && n<=4; + const bool handoff=p==Phase::splash && n==5; + const RGB expected=n==1 || replaced ? red : n==4 || handoff ? blue : n%2 ? red : black; + driver::capture_copies=0; driver::capture_waw_barriers=0; driver::saw_capture_waw=false; + driver::observe_capture=true; + if (p==Phase::splash && n==1) { + EXPECT(present.present_splash(1,std::make_shared(0))); + } else if (replaced || expected==black) EXPECT(present.present_blank(true)==VK_SUCCESS); + else if (p==Phase::composed) { + const auto before=present.composed_presents(); + PresentPlanes planes{}; + planes.plane[0].source=expected==red?1:2; + EXPECT(present.present_planes(planes,true)==VK_SUCCESS && present.composed_presents()==before+1); + } else EXPECT(present.present(expected==red?1:2,true)==VK_SUCCESS); + driver::observe_capture=false; + EXPECT(present.presented()==n); + const unsigned copies=replaced?2u : disk || p==Phase::continuous || handoff ? 1u : 0u; + EXPECT(driver::capture_copies==copies && driver::capture_waw_barriers==copies && + !driver::saw_capture_waw); // also reject a WAW on a frame with no copy + std::vector pixels{77};VkExtent2D e{17,18};VkFormat f=VK_FORMAT_UNDEFINED; + EXPECT(present.read_back(pixels,&e,&f)==(copies!=0)); + if (copies) { + if (n==1) {extent=e;fmt=f;} + EXPECT(e.width==extent.width && e.height==extent.height && f==fmt && sdr_format(f)); + const bool bgra=f==VK_FORMAT_B8G8R8A8_UNORM || f==VK_FORMAT_B8G8R8A8_SRGB; + EXPECT(presenter_capture_matches_rgb(pixels,e.width,e.height,bgra,expected,0)); + } else EXPECT(pixels.size()==1 && pixels[0]==77 && e.width==17 && e.height==18 && f==VK_FORMAT_UNDEFINED); + } + if (p==Phase::final_pending) { + EXPECT(fs::exists(folder.path/"frame_00001.ppm") && !fs::exists(folder.path/"frame_00004.ppm")); + } + } // pending final frame 4 is written here, without another present + EXPECT(disk_matches(folder.path,extent,fmt,p==Phase::splash?red:blue)); + } + // Splash-only storage is not an ongoing readback request. No disk path, no enable_capture(). + EXPECT(_putenv_s("LEONIDA_CAPTURE", "") == 0); + { + VkWin32SurfaceCreateInfoKHR info{VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR}; + info.hinstance = GetModuleHandleW(nullptr); + info.hwnd = window; + VkSurfaceKHR surface{}; + EXPECT(surface_fn(d.instance, &info, nullptr, &surface) == VK_SUCCESS); + VulkanPresenter present(context, driver::get_instance, d.instance, d.physical, d.queue, d.family, surface); + EXPECT(present.ok()); + auto owner = std::make_shared(0); + std::weak_ptr held = owner; + for (unsigned n = 1; n <= 5; ++n) { + driver::capture_copies = 0; + driver::capture_waw_barriers = 0; + driver::saw_capture_waw = false; + driver::observe_capture = true; + if (n == 1) EXPECT(present.present_splash(1, std::move(owner))); // show the red shell + else if (n == 3 || n == 5) EXPECT(present.present(2, true) == VK_SUCCESS); // blue title + else EXPECT(present.present_blank(true) == VK_SUCCESS); + driver::observe_capture = false; + + // Initial shell: zero copies. Held black: inspect, then overwrite with the red shell. First blue: + // inspect once and release. Subsequent black and blue are ordinary frames, with no copies. + const unsigned expected_copies = n == 2 ? 2 : n == 3 ? 1 : 0; + EXPECT(present.presented() == n && driver::capture_copies == expected_copies && + driver::capture_waw_barriers == expected_copies && !driver::saw_capture_waw); + EXPECT(held.expired() == (n >= 3)); + std::vector pixels{77}; + VkExtent2D extent{17, 18}; + VkFormat format = VK_FORMAT_UNDEFINED; + if (n == 2) { + EXPECT(present.read_back(pixels, &extent, &format) && sdr_format(format)); + const bool bgra = format == VK_FORMAT_B8G8R8A8_UNORM || format == VK_FORMAT_B8G8R8A8_SRGB; + EXPECT(presenter_capture_matches_rgb(pixels, extent.width, extent.height, bgra, red, 0)); + } else { + EXPECT(!present.read_back(pixels, &extent, &format)); + EXPECT(pixels.size() == 1 && pixels[0] == 77 && extent.width == 17 && extent.height == 18 && + format == VK_FORMAT_UNDEFINED); + } + } + } + EXPECT(queue.idle());context.remove_resource(1);context.remove_resource(2); + std::puts("sparse capture: frames 1/4, cap, last-fence drain, explicit readback, disk and splash-only handoffs verified"); + return 0; +} +} // namespace sparse_test diff --git a/runtime/test/vk_presenter_sync_test.cpp b/runtime/test/vk_presenter_sync_test.cpp index a54bf6662c..ee75ad86f1 100644 --- a/runtime/test/vk_presenter_sync_test.cpp +++ b/runtime/test/vk_presenter_sync_test.cpp @@ -16,6 +16,7 @@ #endif #define VK_USE_PLATFORM_WIN32_KHR #include +#include #include "vk_presenter_capture_colour.h" #include "vk_test_device.h" @@ -28,7 +29,10 @@ #include #include #include +#include +#include #include +#include #include #include #include @@ -182,10 +186,14 @@ void install(PFN_vkGetInstanceProcAddr instance_proc, VkInstance instance, VkDev } } // namespace driver +#include "vk_presenter_sparse_capture.h" + } // namespace -int main() { +int main(int argc, char** argv) { using namespace leonida; + const bool sparse = argc==2 && std::string_view(argv[1])=="--sparse-capture"; + if (argc!=1 && !sparse) return 2; vktest::Device d; if (!d.create(true)) { @@ -202,7 +210,7 @@ int main() { constexpr std::uint32_t width = 128, height = 96; RECT fr{0, 0, LONG(width), LONG(height)}; AdjustWindowRect(&fr, WS_OVERLAPPEDWINDOW, FALSE); - HWND window = CreateWindowExW(0, wc.lpszClassName, L"Leonida presenter sync test", WS_OVERLAPPEDWINDOW, 80, 80, + HWND window = CreateWindowExW(sparse ? WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW : 0, wc.lpszClassName, L"Leonida presenter sync test", WS_OVERLAPPEDWINDOW, 80, 80, fr.right - fr.left, fr.bottom - fr.top, nullptr, nullptr, wc.hInstance, nullptr); EXPECT(window); ShowWindow(window, SW_SHOWNOACTIVATE); @@ -210,6 +218,12 @@ int main() { pump(); driver::install(d.instance_proc, d.instance, d.device); + if (sparse) { // positive-only: never enter the failure/concurrency regressions below + const int result = sparse_test::run(d, window); + DestroyWindow(window); + UnregisterClassW(wc.lpszClassName, wc.hInstance); + return result || d.validation_errors() ? 1 : 0; + } { VulkanContext context(driver::get_device, d.device, true); EXPECT(context.loaded()); diff --git a/runtime/test/vk_sampler_test.cpp b/runtime/test/vk_sampler_test.cpp index 98206931b1..a35806d8f5 100644 --- a/runtime/test/vk_sampler_test.cpp +++ b/runtime/test/vk_sampler_test.cpp @@ -265,9 +265,10 @@ int main(int argc, char** argv) { VkBufferDeviceAddressInfo address_info{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; address_info.buffer = heap; const VkDeviceAddress heap_base = vkGetBufferDeviceAddress(dev, &address_info); - // Descriptor hash table: the T# names image 1, the S# sampler 1. Index 0 of each is a magenta fallback. + // Descriptor hash table: the T# names image 1, the S# sampler 1. Index 0 of each is a magenta fallback. The + // module is tagged (build.py), so the T# entry names the array its index is bound in: a sampled 2D image. leonida::DescriptorTable table(16); - table.insert(tsharp.data(), 1); + table.insert(tsharp.data(), 1, leonida::kind_sampled_bit(0)); table.insert(leonida::make_ssharp_key(ssharp.data()).data(), 1); const auto table_words = table.build_gpu_buffer(true); VkBuffer table_buffer; diff --git a/runtime/test/vk_sandbox.cpp b/runtime/test/vk_sandbox.cpp index 7ae9e8db6a..11718190d2 100644 --- a/runtime/test/vk_sandbox.cpp +++ b/runtime/test/vk_sandbox.cpp @@ -395,7 +395,8 @@ int main(int argc, char** argv) { }; const uint32_t nimg = uint32_t(scene.textures.size()) + 1; // image 0: 1x1 white for untextured draws leonida::DescriptorTable table(2 * (nimg + 2)); - for (uint32_t i = 0; i < nimg; ++i) table.insert(tsharp(i).data(), i); + // The module is tagged (build.py), so each T# entry names the array its index is bound in: a sampled 2D image. + for (uint32_t i = 0; i < nimg; ++i) table.insert(tsharp(i).data(), i, leonida::kind_sampled_bit(0)); uint32_t ssharp[8] = {1024, 12582912, 418381824, 0, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu}; // the PS's literal S# table.insert(ssharp, 0); for (uint32_t d = 0; d < ndraw; ++d) { diff --git a/runtime/test/vk_semaphore_lifetime_test.cpp b/runtime/test/vk_semaphore_lifetime_test.cpp new file mode 100644 index 0000000000..6ee7ffd9b3 --- /dev/null +++ b/runtime/test/vk_semaphore_lifetime_test.cpp @@ -0,0 +1,261 @@ +// Semaphore lifetimes across fence and queue teardown (src/vulkan_backend.h, src/vulkan_device_fault.h). No shaders, +// no game data. +// 1. A fence released right after an unheld Signal: the queue keeps the fence, and so its timeline semaphore, +// until the GPU has run the signal (destroying a semaphore a pending submission signals is undefined, +// VUID-vkDestroySemaphore-semaphore-05149). The Signal is kept pending on the GPU by a wait on a semaphore the +// host signals later. +// 2. The queue whose submission uploaded the bindless table is destroyed, then another queue submits: that +// submission must not wait on the destroyed queue's progress semaphore. +// 3. With the device-fault diagnostics on, the submit ring forgets both semaphores before they are destroyed: its +// progress watch (once a second) and a dump after the teardown never read the counter of a destroyed one. +// The driver calls are intercepted, so 2 and 3 are checked with or without the validation layer; set +// LEONIDA_VK_VALIDATION=1 to also run under VK_LAYER_KHRONOS_validation (any validation error fails the test). +#include "vk_test_device.h" +#include "../src/vulkan_backend.h" + +#include +#include +#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 driver { +PFN_vkGetDeviceProcAddr real_get = nullptr; +PFN_vkQueueSubmit real_submit = nullptr; +PFN_vkCreateSemaphore real_create = nullptr; +PFN_vkDestroySemaphore real_destroy = nullptr; +PFN_vkGetSemaphoreCounterValue real_counter = nullptr; + +std::mutex mutex; +std::set destroyed; // destroyed and not made again +std::vector last_signals; // of the last vkQueueSubmit +std::vector waits_seen; // every wait semaphore submitted since the last reset +std::atomic dead_waits{0}; // submissions that waited on a destroyed semaphore +std::atomic dead_reads{0}; // counter reads of a destroyed semaphore +std::atomic live_reads{0}; + +VKAPI_ATTR VkResult VKAPI_CALL submit(VkQueue queue, std::uint32_t count, const VkSubmitInfo* submits, VkFence fence) { + { + std::lock_guard lock(mutex); + last_signals.clear(); + for (std::uint32_t i = 0; i < count; ++i) { + for (std::uint32_t w = 0; w < submits[i].waitSemaphoreCount; ++w) { + const VkSemaphore s = submits[i].pWaitSemaphores[w]; + waits_seen.push_back(s); + if (destroyed.count(s)) dead_waits.fetch_add(1); + } + for (std::uint32_t s = 0; s < submits[i].signalSemaphoreCount; ++s) + last_signals.push_back(submits[i].pSignalSemaphores[s]); + } + } + return real_submit(queue, count, submits, fence); +} + +VKAPI_ATTR VkResult VKAPI_CALL create(VkDevice device, const VkSemaphoreCreateInfo* info, + const VkAllocationCallbacks* alloc, VkSemaphore* out) { + const VkResult result = real_create(device, info, alloc, out); + if (result == VK_SUCCESS) { + std::lock_guard lock(mutex); + destroyed.erase(*out); // a handle value the driver hands out again is alive again + } + return result; +} + +VKAPI_ATTR void VKAPI_CALL destroy(VkDevice device, VkSemaphore semaphore, const VkAllocationCallbacks* alloc) { + if (semaphore) { + std::lock_guard lock(mutex); + destroyed.insert(semaphore); + } + real_destroy(device, semaphore, alloc); +} + +VKAPI_ATTR VkResult VKAPI_CALL counter(VkDevice device, VkSemaphore semaphore, std::uint64_t* value) { + { + std::lock_guard lock(mutex); + if (destroyed.count(semaphore)) { + dead_reads.fetch_add(1); + *value = 0; + return VK_ERROR_UNKNOWN; // never reaches the driver with a dead handle + } + } + live_reads.fetch_add(1); + return real_counter(device, semaphore, value); +} + +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get(VkDevice device, const char* name) { + if (!std::strcmp(name, "vkQueueSubmit")) return reinterpret_cast(submit); + if (!std::strcmp(name, "vkCreateSemaphore")) return reinterpret_cast(create); + if (!std::strcmp(name, "vkDestroySemaphore")) return reinterpret_cast(destroy); + if (!std::strcmp(name, "vkGetSemaphoreCounterValue") || !std::strcmp(name, "vkGetSemaphoreCounterValueKHR")) + return reinterpret_cast(counter); + return real_get(device, name); +} +} // namespace driver + +// A timeline semaphore the test signals from the host, unknown to the queues' holds (so a wait on it is not held on +// the CPU: it is submitted, and the GPU waits). Like the runtime's own owners (~VulkanFence, ~VulkanQueue) it tells +// the submit ring before it goes. +struct HostGate { + const vktest::Device& d; + DeviceFaultDiagnostics* ring; + VkSemaphore semaphore = VK_NULL_HANDLE; + HostGate(const vktest::Device& device, DeviceFaultDiagnostics* diagnostics) : d(device), ring(diagnostics) { + VkSemaphoreTypeCreateInfo type{VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO}; + type.semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE; + VkSemaphoreCreateInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, &type}; + driver::create(d.device, &info, nullptr, &semaphore); + } + ~HostGate() { + if (!semaphore) return; + if (ring) ring->forget(semaphore); + driver::destroy(d.device, semaphore, nullptr); + } + bool open(std::uint64_t value) const { + VkSemaphoreSignalInfo signal{VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO}; + signal.semaphore = semaphore; + signal.value = value; + return d.fn("vkSignalSemaphore")(d.device, &signal) == VK_SUCCESS; + } +}; + +int run(vktest::Device& d) { + driver::real_get = d.device_proc; + driver::real_submit = d.fn("vkQueueSubmit"); + driver::real_create = d.fn("vkCreateSemaphore"); + driver::real_destroy = d.fn("vkDestroySemaphore"); + driver::real_counter = d.fn("vkGetSemaphoreCounterValue"); + EXPECT(driver::real_submit && driver::real_create && driver::real_destroy && driver::real_counter); + + VulkanContext context(driver::get, d.device, true); + EXPECT(context.loaded()); + context.configure_device_fault(driver::get, DeviceFaultExtensions{}); // the submit ring and its progress watch + EXPECT(context.device_fault()); + bool arm_upload = false; + context.set_bindless_prepare([&](VkCommandBuffer) { + if (std::exchange(arm_upload, false)) context.note_bindless_upload(); // as a replacing bindless flush does + return true; + }); + + void* map = nullptr; + constexpr VkDeviceSize kSize = 4096; + const VkBufferUsageFlags usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; + VkBuffer a = d.buffer(kSize, usage, &map), b = d.buffer(kSize, usage, &map); + EXPECT(a && b); + ResourceBinding binding; + binding.size = kSize; + binding.buffer = a; + context.add_resource(1, binding); + binding.buffer = b; + context.add_resource(2, binding); + CommandList copy; + EXPECT(copy.copy_buffer({2, 0, 1, 0, kSize})); + EXPECT(copy.close()); + const CommandList* lists[] = {©}; + + auto stay = std::make_unique(context, d.queue, d.family); + EXPECT(stay->ok()); + + // 1. Release a fence right after an unheld Signal that the GPU cannot run yet. + { + HostGate gate(d, context.device_fault()); + EXPECT(gate.semaphore); + auto fence = std::make_shared(context, 0); + const VkSemaphore fence_semaphore = fence->semaphore(); + EXPECT(fence_semaphore); + std::weak_ptr watch = fence; + stay->wait(gate.semaphore, 1); // the next submission waits for the host on the GPU + EXPECT(stay->signal(fence_semaphore, 1, [&fence] { return std::shared_ptr(fence); })); + fence.reset(); // the title's last Release + { + std::lock_guard lock(driver::mutex); + EXPECT(!driver::destroyed.count(fence_semaphore)); + } + EXPECT(!watch.expired()); // the queue keeps it while the Signal is pending + EXPECT(gate.open(1)); + // Each execute drains the pins whose submissions are done. + bool released = false; + for (int i = 0; i < 200 && !released; ++i) { + context.wait_retire_ticket(context.submitted_retire_ticket()); + EXPECT(stay->execute(lists) == ReplayResult::success); + released = watch.expired(); + if (!released) std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + EXPECT(released); // and lets it go once the GPU has run it + std::lock_guard lock(driver::mutex); + EXPECT(driver::destroyed.count(fence_semaphore)); + std::printf("fence released after an unheld Signal: kept until the signal ran, then destroyed\n"); + } + + // 2. The queue that uploaded the bindless table goes; another queue submits next. + VkSemaphore uploader_progress = VK_NULL_HANDLE; + { + auto uploader = std::make_unique(context, d.queue, d.family); + EXPECT(uploader->ok()); + arm_upload = true; + EXPECT(uploader->execute(lists) == ReplayResult::success); + EXPECT(!arm_upload); + { + std::lock_guard lock(driver::mutex); + EXPECT(!driver::last_signals.empty()); + uploader_progress = driver::last_signals[0]; // a queue's submission signals its progress timeline first + } + uploader.reset(); + } + { + std::lock_guard lock(driver::mutex); + EXPECT(driver::destroyed.count(uploader_progress)); + driver::waits_seen.clear(); + } + EXPECT(stay->execute(lists) == ReplayResult::success); + { + std::lock_guard lock(driver::mutex); + EXPECT(std::find(driver::waits_seen.begin(), driver::waits_seen.end(), uploader_progress) == + driver::waits_seen.end()); + } + EXPECT(driver::dead_waits.load() == 0); + std::printf("bindless upload queue destroyed: the next submission on another queue does not wait on it\n"); + + // 3. The ring: the progress watch reads counters once a second; a dump now reads every semaphore it still names. + std::this_thread::sleep_for(std::chrono::milliseconds(2200)); + const unsigned reads_before = driver::live_reads.load(); + context.device_fault()->dump_submits(); + EXPECT(driver::live_reads.load() > reads_before); // it did read the live ones + EXPECT(driver::dead_reads.load() == 0); + std::printf("submit ring: no counter read of a destroyed semaphore (%u live reads)\n", driver::live_reads.load()); + + stay.reset(); + context.remove_resource(1); + context.remove_resource(2); + return 0; +} + +} // namespace + +int main() { + std::setvbuf(stdout, nullptr, _IONBF, 0); + vktest::Device d; + const auto status = d.initialize(); + if (status == vktest::DeviceStatus::unavailable) { + std::printf("SKIP: no usable Vulkan device\n"); + return 77; + } + if (status != vktest::DeviceStatus::ready) return 1; + const int rc = run(d); + const unsigned errors = d.validation_errors(); + std::printf("Vulkan validation errors: %u%s\n", errors, d.validation ? "" : " (validation off)"); + return rc ? rc : errors ? 1 : 0; +} diff --git a/runtime/test/vk_store_test.cpp b/runtime/test/vk_store_test.cpp index 0b4c3c6f90..13390e39e4 100644 --- a/runtime/test/vk_store_test.cpp +++ b/runtime/test/vk_store_test.cpp @@ -54,7 +54,10 @@ static uint32_t key_hash(const uint32_t k[8]) { // same FNV-1a as the transl return h; } -static void table_insert(std::vector& t, const uint32_t key[8], uint32_t index) { +// `kind` is what the translated modules read next to the index (descriptor_table.h): the arrays this image is +// bound in, sampled and storage. +static void table_insert(std::vector& t, const uint32_t key[8], uint32_t index, + uint32_t kind) { uint32_t mask = t[0], h = key_hash(key); for (uint32_t k = 0; k < 8; k++) { uint32_t base = ((h + k) & mask) * 10; @@ -63,6 +66,7 @@ static void table_insert(std::vector& t, const uint32_t key[8], uint32 if (used) continue; for (int j = 0; j < 8; j++) t[base + 1 + j] = key[j]; t[base + 9] = index; + t[base + 10] = kind; return; } } @@ -236,10 +240,10 @@ int main(int argc, char** argv) { for (uint32_t k = 0; k < 3; k++) { uint32_t t[8] = {0x1000 * (k + 1), fmts[k] << 20}; for (int j = 2; j < 8; j++) t[j] = 0x11 * (k + 1); - table_insert(table, t, k + 1); // its index in the 2D arrays; 0 is the fallback, as in the runtime + table_insert(table, t, k + 1, leonida::kind_sampled_bit(0) | leonida::kind_storage_bit(0)); // its index in the 2D arrays; 0 is the fallback, as in the runtime if (cube_mode) { // the cube T# (cs_imgstore_cube.asm): word3 also has TYPE = 0xB, index k + 1 of the 2D arrays t[3] |= 0xB0000000u; - table_insert(table, t, k + 1); + table_insert(table, t, k + 1, leonida::kind_sampled_bit(0) | leonida::kind_storage_bit(0)); } } // Index 4: a 16x4 rgba8 image with its whole mip chain (16x4, 8x2, 4x1, 2x1, 1x1) for image_get_resinfo. Its key @@ -249,13 +253,13 @@ int main(int argc, char** argv) { wide_desc.address = 0x400000; wide_desc.format = fmts[0]; wide_desc.width = WIDE_W; wide_desc.height = WIDE_H; wide_desc.mip_count = wide_desc.resource_mips = WIDE_MIPS; const leonida::gfx10::ImageWords wide_key = leonida::gfx10::encode(wide_desc); - table_insert(table, wide_key.data(), 4); + table_insert(table, wide_key.data(), 4, leonida::kind_sampled_bit(0)); // image_get_resinfo reads binding 0 // The volume of the 3D atomics: index 1 of the 3D arrays, behind a T# of the 2D images' pattern (k = 4). const uint32_t VOL = 4; { // The volume uses the D3D12 layer's whole-mip UAV tag (FirstWSlice=0, WSize=4). uint32_t t[8] = {0x5000, fmts[1] << 20, 0x55, 0x55, 0x80000055, 0x55, 0x55, 0xd7801800}; - table_insert(table, t, 1); + table_insert(table, t, 1, leonida::kind_sampled_bit(2) | leonida::kind_storage_bit(2)); } VkBuffer tb; void* tbp; CHECK(make_buffer(table.size() * 4, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &tb, &tbp)); diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h index fd63fca665..e561f72889 100644 --- a/runtime/test/vk_test_device.h +++ b/runtime/test/vk_test_device.h @@ -130,6 +130,7 @@ class Device { std::uint32_t max_draw_indirect_count = 0; bool request_draw_indirect_first_instance = false; // enable the core feature only for positive indirect draws bool request_debug_utils = false; // set before create(): enable VK_EXT_debug_utils when the loader has it + bool pipeline_cache_control() const { return v13_.core && v13_.pipeline_creation_cache_control; } bool request_buffer_device_address = false; // set before create(): enable bufferDeviceAddress where supported bool buffer_device_address = false; // enabled: buffer() memory and buffers can be addressed (device_address()) bool conservative_rasterization = false; // VK_EXT_conservative_rasterization enabled where available @@ -189,6 +190,7 @@ class Device { unsigned validation_errors() const { return validation_error_count(); } unsigned known_validation_errors() const { return known_validation_error_count(); } + bool pipeline_cache_control_enabled() const { return v13_.core && v13_.pipeline_creation_cache_control; } // presentation: also enable VK_KHR_surface + VK_KHR_win32_surface and VK_KHR_swapchain (Windows only). bool create(bool presentation = false) { return initialize(presentation) == DeviceStatus::ready; } @@ -492,6 +494,7 @@ class Device { enable.multiViewport = features.features.multiViewport; // d3d12_multi_viewport_test, where available enable.geometryShader = features.features.geometryShader; // d3d12_geometry_test, where available enable.dualSrcBlend = features.features.dualSrcBlend; // d3d12_translated_draw_test --dual-source + enable.depthBounds = features.features.depthBounds; // depth-bounds PSOs (d3d12_mesh_test), where available const char* conditional_extension = VK_EXT_CONDITIONAL_RENDERING_EXTENSION_NAME; // VK_EXT_host_image_copy where the device has it, for the D3D12 layer's CPU texture copies. diff --git a/runtime/test/vk_texture_test.cpp b/runtime/test/vk_texture_test.cpp index 3dafcaef64..8c3368b257 100644 --- a/runtime/test/vk_texture_test.cpp +++ b/runtime/test/vk_texture_test.cpp @@ -327,7 +327,7 @@ int main(int argc, char** argv) { leonida::DescriptorTable desc_table(16); // The heap already holds the original key. Change only the registered key for the miss control. if (fetch_miss) tsharp[7] ^= 1; - desc_table.insert(tsharp, 1); + desc_table.insert(tsharp, 1, leonida::kind_sampled_bit(cube ? 1 : 0)); desc_table.insert(ssharp, 1); const auto table = desc_table.build_gpu_buffer(true); VkBuffer tb; VkDeviceMemory tbm; void* tbp; diff --git a/runtime/test/xg_xs_test.cpp b/runtime/test/xg_xs_test.cpp index 18356cb416..2535b1a926 100644 --- a/runtime/test/xg_xs_test.cpp +++ b/runtime/test/xg_xs_test.cpp @@ -435,6 +435,42 @@ int main() { check(registry.size() == 32, "the registry kept the re-registrations made during the pass"); } + { + leonida::TitleTextureRangeIndex index; + std::map> ranges; + for (unsigned id = 1; id <= 60; ++id) { + const auto begin = (id * 17) % 31; + ranges[id] = {begin, begin + id}; + index.set(id, begin, id); + } + index.erase(12); + ranges.erase(12); + index.set(13, 5, 9); + ranges[13] = {5, 14}; + index.set(2, 0, 0); + ranges.erase(2); + bool same = true; + for (unsigned from = 0; from < 100; ++from) { + for (unsigned to = from; to <= 100; ++to) { + std::vector got, want; + index.overlapping(from, to, [&](auto key) { got.push_back(key); }); + std::sort(got.begin(), got.end()); + for (const auto& [key, range] : ranges) + if (from < to && range.first < to && from < range.second) want.push_back(key); + same &= got == want; + } + } + check(same, "indexed invalidation matches all CPU overlaps after alias, replacement and removal"); + index.set(99, (UINT64_MAX >> 1) - 2, 16); + unsigned hits = 0; + index.overlapping(UINT64_MAX >> 1, (UINT64_MAX >> 1) + 1, [&](auto id) { hits += id == 99; }); + check(hits == 1, "an interval across bit 63 is indexed without a word-width shift"); + const auto slice = leonida::title_texture_snapshot(ranges, 12, 4); + check(slice.size() == 4 && slice.front().first == 13 && slice.back().first == 16, + "bounded refresh resumes at the next live address"); + check(leonida::title_texture_snapshot(ranges, 61, 4).empty(), "end of sweep permits wrap"); + } + { leonida::TitleWriteRanges writes{{20, 30}, {10, 20}, {15, 17}, {60, 75}, {60, 67}, {90, 90}}; const auto original = writes; @@ -699,6 +735,53 @@ int main() { check(create(&d, &computer) == E_NOTIMPL && computer, "unsupported texture keeps a safe fallback object"); check(slot(computer, 2)(computer, &l) == E_NOTIMPL && l.size == 8192 && slot(computer, 1)(computer) == 1, "fallback leaves caller outputs untouched and is safe to release"); + + // A linear 3D texture (layout 0x100) is thin (addrlib HwlComputeSurfaceInfoLinear): rows of 256 bytes, every + // depth slice a whole mip chain. The title's texture lock reads mip 0's offset and size from this + // computer and, when creation fails, its own uninitialised stack instead: measured with the 32x32x36 R32_UINT + // 3D texture it clears 0x48000 bytes at that pointer, which is this layout's size exactly. + d = {4, 0, 32, 32, 36, 1, DXGI_FORMAT_R32_UINT, 1, 0, 0x100, 0x300004}; + if (!make(create, d, computer, "create linear 3D computer")) return 1; + std::memset(&l, 0xa5, sizeof(l)); + check(slot(computer, 2)(computer, &l) == S_OK && l.size == 0x48000 && l.alignment == 256 && + l.mips == 1 && l.dimension == 4 && l.plane[0].slice_bytes == 8192 && + l.plane[0].mips[0].offset == 0 && l.plane[0].mips[0].size == 0x48000 && + l.plane[0].mips[0].slice_bytes == 8192 && l.plane[0].mips[0].pitch_bytes == 256, + "linear 3D 32x32x36 R32 is 36 slices of 32 rows of 256 bytes"); + check(slot(computer, 3)(computer) == 0x48000 && slot(computer, 4)(computer) == 256, + "linear 3D size and alignment agree with slot 2"); + check(slot(computer, 6)(computer, 0, 0, 3, 2, 5, 0, nullptr) == 5 * 8192 + 2 * 256 + 3 * 4, + "linear 3D element offset is slice, row, column"); + { + // A mip-0 copy through slots 8 and 9: padded source rows and slices land at 256-byte rows, 8 KiB slices. + constexpr unsigned row = 32 * 4 + 12, slice = row * 32 + 20; + std::vector source(slice * 36), read_back(source.size(), 0), memory(l.size, 0); + for (size_t i = 0; i < source.size(); ++i) source[i] = uint8_t(i * 7 + 3); + check(slot(computer, 8)(computer, memory.data(), 0, 0, source.data(), row, slice) == S_OK && + std::memcmp(&memory[35 * 8192 + 31 * 256], &source[35 * slice + 31 * row], 32 * 4) == 0 && + slot(computer, 9)(computer, read_back.data(), 0, 0, 0, memory.data(), row, slice) == S_OK && + std::memcmp(&read_back[35 * slice + 31 * row], &source[35 * slice + 31 * row], 32 * 4) == 0, + "slots 8 and 9 copy a linear 3D mip slice by slice"); + check(slot(computer, 8)(computer, memory.data(), 0, 1, source.data(), row, slice) == E_INVALIDARG, + "a 3D texture has no second subresource"); + } + slot(computer, 1)(computer); + + // A linear 3D texture with more than one mip: its chain layout (slice-major or mip-major) is not measured, so the + // description is refused rather than given offsets that may be wrong for mips 1+. + d = {4, 0, 32, 16, 8, 3, DXGI_FORMAT_R8_UNORM, 1, 0, 0x100, 0}; + check(!build_texture(d, texture), "linear 3D with mips is refused until a title texture measures it"); + + // A render-target or depth flag with an explicit mode takes that mode's layout (measured: 1x1 RGBA32F + // descriptions with layout 0x100 and the render-target bit reach the title's CPU upload). + d = {3, 0, 1, 1, 1, 1, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 0, 0x100, 0x300001}; + if (!make(create, d, computer, "create linear render-target computer")) return 1; + check(slot(computer, 2)(computer, &l) == S_OK && l.size == 256 && l.alignment == 256, + "explicit linear render target is one 256-byte row"); + slot(computer, 1)(computer); + void* none = nullptr; + d.layout = 0; + check(create(&d, &none) == E_NOTIMPL, "a render target without a mode still needs SW_64KB_R_X, which XG lacks"); std::printf("%d checks, %d failures\n", g_checks, g_failures); return g_failures ? 1 : 0; } diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index 27af09aec3..7c671ed1bd 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -2952,6 +2952,36 @@ int check_render_target_sizes() { mips.MipLevels = 3; EXPECT(ask(&mips, 1).SizeInBytes == (135 + 40 + 12) * 65536ull); + // A texture the GPU writes through unordered access and the title also clears with the CPU through its lock + // with a layout word naming its mode: 0x100, linear. Its console layout is 36 slices of 32 rows + // of 256 bytes, 0x48000 bytes, where the PC device says 0x30000; the larger size wins, rounded to the + // description's alignment. The title's own layout word decides, though the PC form of the description has lost it. + D3D12_RESOURCE_DESC grid{}; + grid.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D; + grid.Width = 32; + grid.Height = 32; + grid.DepthOrArraySize = 36; + grid.MipLevels = 1; + grid.Format = DXGI_FORMAT_R32_UINT; + grid.SampleDesc.Count = 1; + grid.Layout = static_cast(0x100); + grid.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + EXPECT(ask(&grid, 1).SizeInBytes == 0x50000); + // In a list it takes its console size at its own offset. + const D3D12_RESOURCE_DESC grid_and_target[] = {grid, hd}; + EXPECT(ask(grid_and_target, 2).SizeInBytes == 0x50000 + 8847360); + // The rule only grows: a mode XG lays out smaller (4 KiB thick blocks, 32x32x40 x 4 B = 0x28000) keeps the PC + // size, and so does a layout word that leaves the mode to XG, or a mode XG's model lacks. + D3D12_RESOURCE_DESC smaller = grid; + smaller.Layout = static_cast(0x105); + EXPECT(ask(&smaller, 1).SizeInBytes == 0x30000); + D3D12_RESOURCE_DESC no_mode = grid; + no_mode.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; + EXPECT(ask(&no_mode, 1).SizeInBytes == 0x30000); + D3D12_RESOURCE_DESC unknown_mode = grid; + unknown_mode.Layout = static_cast(0x11b); // SW_64KB_R_X + EXPECT(ask(&unknown_mode, 1).SizeInBytes == 0x30000); + // The PC form (this in RCX, the buffer in RDX) is not the title's call: it gets the PC device's own size, 127 // units of 64 KiB for the mock, so code that compares the proxy with the PC device still agrees. D3D12_RESOURCE_ALLOCATION_INFO pc{}; diff --git a/scripts/check_compute_journal_overlay.py b/scripts/check_compute_journal_overlay.py new file mode 100644 index 0000000000..c346436f9a --- /dev/null +++ b/scripts/check_compute_journal_overlay.py @@ -0,0 +1,106 @@ +"""Check a disposable journal against two locally generated compute PSOs. No game files needed. + +Build d3d12_compute_journal_test first, then run this script with the path to that executable. +--require-hit also requires the driver's application-cache-hit bit (not a timing heuristic). +""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import tempfile +import time + + +def require(ok, message): + if not ok: + raise RuntimeError(message) + + +def entries(cache): + d = cache / "pipeline_cache.d" + if not d.exists(): + return {} + out = {} + for p in d.iterdir(): + require(re.fullmatch(r"cs-[0-9a-f]{16}\.bin", p.name) and p.is_file() and + 32 < p.stat().st_size <= 8 << 20, "unexpected file in one-PSO journal") + out[p.name] = (hashlib.sha256(p.read_bytes()).digest(), p.stat().st_mtime_ns) + return out + + +def run(exe, root, device, strict): + seed = root / "cold" + before = None + results = {} + adapter = None + for label, second in (("cold", False), ("external-A", False), + ("new-B", True), ("local-B", True)): + cache = root / label + cache.mkdir() + if label == "local-B": + # Bring only B into a fresh process; no session or shared cache crosses this boundary. + (cache / "pipeline_cache.d").mkdir() + src, = (root / "new-B" / "pipeline_cache.d").iterdir() + shutil.copy2(src, cache / "pipeline_cache.d" / src.name) + local_before = entries(cache) + env = {k: v for k, v in os.environ.items() if not k.upper().startswith("LEONIDA_")} + env.update(LEONIDA_PIPELINE_CACHE_DIR=str(cache), LEONIDA_TRACE_PIPELINE_COMPILE="1", + LEONIDA_PIPELINE_CACHE_BYTES=str(8 << 20), LEONIDA_PIPELINE_JOURNAL_BYTES=str(8 << 20), + LEONIDA_PIPELINE_JOURNAL="1") + if device: + env["LEONIDA_VK_DEVICE"] = device + if label != "cold": + env["LEONIDA_PIPELINE_JOURNAL_SEED_DIR"] = str(seed / "pipeline_cache.d") + p = subprocess.run([str(exe)] + (["--second-shader"] if second else []), + stdin=subprocess.DEVNULL, capture_output=True, text=True, errors="replace", + cwd=cache, env=env, timeout=60) + if p.returncode == 77: + print("SKIP: the authored compute fixture is unsupported on this device") + return 77 + expected = 14 if second else 10 + require(p.returncode == 0 and + f"compute journal: direct Dispatch(4,1,1) copied both expected words (4,{expected})" + in p.stdout.splitlines(), f"{label}: GPU readback did not match") + devices = [x.removeprefix("device: ") for x in p.stdout.splitlines() if x.startswith("device: ")] + require(len(devices) == 1 and (adapter is None or adapter == devices[0]), "inconsistent GPU selection") + adapter = devices[0] + calls = [x for x in p.stderr.splitlines() if x.startswith("[rt] pipeline-compile trigger=")] + require(len(calls) == 1, f"{label}: expected one compute creation") + m = re.search(r" hit=(-1|0|1) bytes=\d+ variant=\d+ result=0 ", calls[0]) + require(m is not None, f"{label}: missing feedback field or unsuccessful create") + hit = int(m[1]) + local = entries(cache) + if label == "cold": + require(len(local) == 1, "cold A was not journaled") + source, = (seed / "pipeline_cache.d").iterdir() + # Make an erroneous hourly LRU touch observable without making the probe depend on system time. + old = time.time_ns() - 48 * 3600 * 10**9 + os.utime(source, ns=(old, old)) + before = entries(seed) + elif label == "new-B": + require(len(local) == 1 and not (local.keys() & before.keys()), "missing distinct local B") + else: + if strict: + require(hit == 1, f"{label}: driver reported no application-cache hit") + if hit == 1: + require(local == local_before, f"{label}: cache hit changed disposable journal") + require(entries(seed) == before, f"{label}: seed contents or last-write time changed") + results[label] = {"readback": [4, expected], "driver_hit": hit, "local_entries": len(local)} + print(json.dumps({"device": adapter, "runs": results}, sort_keys=True)) + return 0 + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("executable", type=Path, help="built d3d12_compute_journal_test.exe") + parser.add_argument("--device", help="optional LEONIDA_VK_DEVICE selector") + parser.add_argument("--require-hit", action="store_true") + args = parser.parse_args() + exe = args.executable.resolve(strict=True) + require(exe.name.lower() == "d3d12_compute_journal_test.exe", "expected the compute test, not the game") + with tempfile.TemporaryDirectory(prefix="leonida-authored-journal-") as tmp: + raise SystemExit(run(exe, Path(tmp), args.device, args.require_hit)) diff --git a/scripts/compute_workers_win.py b/scripts/compute_workers_win.py new file mode 100644 index 0000000000..04eab8adb3 --- /dev/null +++ b/scripts/compute_workers_win.py @@ -0,0 +1,190 @@ +"""Windows process/lock adapter for translate_pipeline_compute.py (CPython, no extra packages). + +Only a small bootstrap runs before job assignment. It receives no input path or work until the +parent verifies its job and opens the gate. Parent death closes the gate or the kill-on-close job. +""" +import contextlib +import ctypes as c +from ctypes import wintypes as w +import json +import os +from pathlib import Path +import subprocess +import sys +import time + +kernel = c.WinDLL("kernel32", use_last_error=True) +H, D, Z = w.HANDLE, w.DWORD, c.c_size_t + + +def api(name, result, *args): + f = getattr(kernel, name) + f.argtypes, f.restype = args, result + return f + + +def check(value): + if not value: + raise c.WinError(c.get_last_error()) + return value + + +class Basic(c.Structure): + _fields_ = [("time", c.c_int64 * 2), ("flags", D), ("min_ws", Z), ("max_ws", Z), + ("processes", D), ("affinity", Z), ("priority", D), ("scheduling", D)] + + +class Extended(c.Structure): + _fields_ = [("basic", Basic), ("io", c.c_uint64 * 6), ("process_mem", Z), + ("job_mem", Z), ("peak_process", Z), ("peak_job", Z)] + + +class Accounting(c.Structure): + _fields_ = [("time", c.c_int64 * 4), ("faults", D), ("total", D), ("active", D), ("ended", D)] + + +close = api("CloseHandle", w.BOOL, H) +create_job = api("CreateJobObjectW", H, H, w.LPCWSTR) +set_job = api("SetInformationJobObject", w.BOOL, H, D, H, D) +query_job = api("QueryInformationJobObject", w.BOOL, H, D, H, D, H) +assign = api("AssignProcessToJobObject", w.BOOL, H, H) +inside = api("IsProcessInJob", w.BOOL, H, H, c.POINTER(w.BOOL)) +terminate = api("TerminateJobObject", w.BOOL, H, D) +current = api("GetCurrentProcess", H) +priority = api("GetPriorityClass", D, H) +create_file = api("CreateFileW", H, w.LPCWSTR, D, D, H, D, D, H) +LOW = subprocess.BELOW_NORMAL_PRIORITY_CLASS +PROCESS_MEMORY, PRIORITY, TWO_ACTIVE, KILL_ON_CLOSE = 0x100, 0x20, 0x8, 0x2000 + + +def flags(worker): + return PROCESS_MEMORY | PRIORITY | ((TWO_ACTIVE | KILL_ON_CLOSE) if worker else 0) + + +def verify(job, process, mib, worker): + info, member = Extended(), w.BOOL() + check(inside(process, job, c.byref(member))) + check(query_job(job, 9, c.byref(info), c.sizeof(info), None)) + if (not member.value or info.basic.flags != flags(worker) or info.process_mem != mib << 20 or + info.basic.priority != LOW or priority(process) != LOW or + (worker and info.basic.processes != 2)): + raise RuntimeError("Windows compute job limits not in force") + + +@contextlib.contextmanager +def job(mib, worker): + if not 0 < mib <= ((1 << (c.sizeof(Z)*8))-1) >> 20: + raise ValueError("invalid --memory-mib for Windows job") + h = check(create_job(None, None)) # unnamed, never inherited; no breakaway + try: + info = Extended() + info.basic.flags, info.basic.priority = flags(worker), LOW + info.basic.processes, info.process_mem = (2 if worker else 0), mib << 20 + check(set_job(h, 9, c.byref(info), c.sizeof(info))) + yield h + finally: + check(close(h)) + + +def budget_coordinator(mib): + # No KILL_ON_CLOSE for the caller itself. Its limits survive handle close until process exit. + with job(mib, False) as h: + check(assign(h, current())) + verify(h, current(), mib, False) + + +@contextlib.contextmanager +def output_lock(path): + # One nonblocking, no-share open; duplicated into workers so an interrupted parent cannot + # release exclusivity before the last worker has actually left. Never delete/recreate the lock. + h = create_file(str(path), 0xc0000000, 0, None, 4, 0x80, None) + if h == H(-1).value: + raise c.WinError(c.get_last_error()) + try: + yield h + finally: + check(close(h)) + + +def drain(h): + check(terminate(h, 1)) + end = time.monotonic()+10 + while True: + a = Accounting() + check(query_job(h, 1, c.byref(a), c.sizeof(a), None)) + if not a.active: + return + if time.monotonic() >= end: + raise RuntimeError("Windows compute job did not drain") + time.sleep(.02) + + +@contextlib.contextmanager +def start(request, mib, lock): + with job(mib, True) as h: + si = subprocess.STARTUPINFO(lpAttributeList={"handle_list": [lock]}) + os.set_handle_inheritable(lock, True) + try: + p = subprocess.Popen([sys.executable, "-I", "-B", str(Path(__file__).resolve()), "--shard"], + stdin=subprocess.PIPE, startupinfo=si, close_fds=True, creationflags=LOW) + finally: + os.set_handle_inheritable(lock, False) + attached = False + try: + check(assign(h, int(p._handle))) + attached = True + verify(h, int(p._handle), mib, True) + # A single framed gate. EOF, even after a short write, is not permission to start. + gate = (json.dumps([str(request), mib, lock])+"\n").encode("ascii") + if len(gate)>65536: + raise ValueError("compute worker gate too large") + p.stdin.write(gate) + p.stdin.close() + yield p + finally: + try: + if attached: + drain(h) # also stop/wait for a descendant if the Python worker died early + elif p.poll() is None: + p.kill() # gated bootstrap, no descendant or input path + finally: + try: + if not p.stdin.closed: + p.stdin.close() + finally: + p.wait(timeout=10) + + +def run(requests, mib, lock): + with contextlib.ExitStack() as stack: + procs = [stack.enter_context(start(p, mib, lock)) for p in requests] + while True: + codes = [p.poll() for p in procs] + if any(rc not in (None, 0) for rc in codes): + raise RuntimeError(f"Windows translation worker failed: {codes}") + if all(rc == 0 for rc in codes): + return + time.sleep(.05) + + +def child(): + line = sys.stdin.buffer.readline(65537) + if not line.endswith(b"\n") or len(line)>65536: + raise ValueError("no complete Windows compute gate") + request, mib, lock = json.loads(line) + # NULL queries this worker's immediate job. No job handle in a worker can keep it alive after + # coordinator death. No library/source inputs touched before membership and effective limits. + verify(None, current(), mib, True) + os.set_handle_inheritable(lock, False) + try: + sys.path.insert(0, str(Path(__file__).resolve().parent)) + from translate_pipeline_compute import run_request + run_request(Path(request)) + finally: + check(close(lock)) + + +if __name__ == "__main__": + if sys.argv[1:] != ["--shard"]: + raise SystemExit(2) + child() diff --git a/scripts/translate_pipeline_compute.py b/scripts/translate_pipeline_compute.py index 4e691110b4..cb6e17768d 100644 --- a/scripts/translate_pipeline_compute.py +++ b/scripts/translate_pipeline_compute.py @@ -1,26 +1,70 @@ -"""Build an interrupted or new pipeline compute pack from shader_library.py output (Linux). +"""Build an interrupted or new pipeline compute pack from shader_library.py output (Linux or Windows). -Two translation processes, including the parent, each run at most one SPIRV-Tools process. +Up to two translation processes each run at most one SPIRV-Tools process. Validated modules and their receipts survive interruption. The runtime index is published last. """ import argparse -import fcntl +import contextlib +from dataclasses import dataclass, asdict import hashlib +import inspect import json import os -import resource import shutil import sys import tempfile from pathlib import Path ROOT = Path(__file__).resolve().parents[1] -sys.path[:0] = [str(ROOT / "tools"), str(ROOT)] +sys.path[:0] = [str(ROOT / "tools"), str(ROOT), str(ROOT / "scripts")] from make_game import file_sha256 as digest, translation_sources_digest import rdna2spirv as translator +@dataclass(frozen=True) +class Options: + wave64_emulate: bool + loop_limit: int + descriptor_hash: str + compact_spirv: bool + + def __post_init__(self): + if (type(self.wave64_emulate) is not bool or type(self.compact_spirv) is not bool or + type(self.loop_limit) is not int or not 0 <= self.loop_limit <= 0xffffffff or + self.descriptor_hash not in translator.DESCRIPTOR_HASHES): + raise ValueError("invalid compute options") + + def apply(self): + translator.WAVE64_EMULATE = self.wave64_emulate + translator.LOOP_LIMIT = self.loop_limit + translator.DESCRIPTOR_HASH = self.descriptor_hash + + +def observed(compact): + return asdict(Options(translator.WAVE64_EMULATE, translator.LOOP_LIMIT, translator.DESCRIPTOR_HASH, compact)) + + +def recipe(options): + if options.compact_spirv and "compact" not in inspect.signature(translator.assemble_spirv).parameters: + raise ValueError("this translator does not implement --compact-spirv") + binaries = {} + for tool in ["spirv-as", "spirv-val"] + (["spirv-opt"] if options.compact_spirv else []): + binary = shutil.which(tool) + if not binary: + raise ValueError(tool + " is required") + binaries[tool] = digest(Path(binary)) + return {"sources": translation_sources_digest(), "builder": digest(Path(__file__)), + "windows_adapter": digest(Path(__file__).with_name("compute_workers_win.py")), + "tools": binaries, "options": asdict(options)} + + +def object_digest(value): + return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(",", ":")).encode()).hexdigest() + + def build_one(src, out, name, settings, compact=False): + if observed(compact) != settings["options"]: + raise ValueError("translation options differ from cache recipe") listing = src / "disasm" / (name + ".s") side = src / "fspx" / name code, state = (Path(str(side) + suffix) for suffix in (".code", ".state")) @@ -28,12 +72,13 @@ def build_one(src, out, name, settings, compact=False): container = src / (name + ".dxbc") inputs = [settings, name, code_key, state_key, digest(listing), digest(Path(str(side) + ".json")), digest(container) if container.is_file() else None] - key = hashlib.sha256(json.dumps(inputs).encode()).hexdigest() + key = object_digest(inputs) receipt = out / ".compute-cache" / (key + ".json") if receipt.exists(): try: row = json.loads(receipt.read_text(encoding="utf-8")) - if (row["meta"]["fspx_code_sha256"], row["meta"]["fspx_state_sha256"]) == (code_key, state_key): + if row["options"] == settings["options"] and ( + row["meta"]["fspx_code_sha256"], row["meta"]["fspx_state_sha256"]) == (code_key, state_key): module_hash = row["module"] if len(module_hash) == 64 and all(c in "0123456789abcdef" for c in module_hash): if digest(out / (name + "_" + module_hash + ".spv")) == module_hash: @@ -45,7 +90,9 @@ def build_one(src, out, name, settings, compact=False): with tempfile.TemporaryDirectory(dir=out / ".compute-cache") as tmp: sa, sv = Path(tmp) / "module.spvasm", Path(tmp) / "module.spv" sa.write_text(asm, encoding="utf-8", newline="\n") - result = translator.assemble_spirv(str(sa), str(sv), asm_text=asm, compact=compact) + # Older translators support ordinary assembly but do not accept the compact keyword. + # Explicit compact is gated by recipe() before either worker starts; never drop it. + result = translator.assemble_spirv(str(sa), str(sv), asm_text=asm, **({"compact": True} if compact else {})) if result.returncode: raise translator.Unsupported((result.stderr.splitlines() or ["SPIR-V tool failed"])[0]) meta = translator.shader_meta(translator.translate.last_gen, asm, src_path=str(listing)) @@ -53,50 +100,97 @@ def build_one(src, out, name, settings, compact=False): "cs", code_key, state_key): raise ValueError("compute stage or FSPX identity mismatch") module_hash = digest(sv) - sv.replace(out / (name + "_" + module_hash + ".spv")) - row = {"meta": meta, "module": module_hash} + translator.replace_retry(sv, out / (name + "_" + module_hash + ".spv")) + row = {"meta": meta, "module": module_hash, "options": observed(compact)} translator.write_index(str(receipt), row) return row -def build_part(src, out, names, settings, report, compact=False): +def build_part(src, out, names, settings, report, shard): + options = Options(**settings["options"]) + options.apply() # identically on the POSIX parent/fork child and a newly spawned Windows interpreter + if recipe(options) != settings or observed(options.compact_spirv) != settings["options"]: + raise RuntimeError("compute worker recipe differs from coordinator") rows, failures = {}, {} for number, name in enumerate(names, 1): try: - rows[name] = build_one(src, out, name, settings, compact) + rows[name] = build_one(src, out, name, settings, options.compact_spirv) except (translator.Unsupported, MemoryError) as e: failures[name] = str(e) or type(e).__name__ if number % 100 == 0 or number == len(names): print(f"worker {os.getpid()}: {number}/{len(names)}, {len(failures)} failed", flush=True) - translator.write_index(str(report), {"rows": rows, "failures": failures}) + audit = {"shard": shard, "recipe_sha256": object_digest(settings), "names_sha256": object_digest(names), + "options": observed(options.compact_spirv), "accepted": len(rows), "failed": len(failures)} + translator.write_index(str(report), {"audit": audit, "rows": rows, "failures": failures}) + + +def run_request(path): + q = json.loads(path.read_text(encoding="utf-8")) + build_part(Path(q["src"]), Path(q["out"]), q["names"], q["settings"], Path(q["report"]), q["shard"]) -def build(src, out, names, settings, jobs, compact=False): +@contextlib.contextmanager +def output_lock(path): + if os.name == "nt": + import compute_workers_win as win + with win.output_lock(path) as lock: + yield lock + else: + import fcntl + with path.open("ab") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + yield lock + + +def run_parts(src, out, names, settings, jobs, reports, mib, lock): + if os.name == "nt": + import compute_workers_win as win + requests = [] + for i, report in enumerate(reports): + request = report.with_suffix(".request") + translator.write_index(str(request), {"src": str(src), "out": str(out), "names": names[i::jobs], + "settings": settings, "report": str(report), "shard": i}) + requests.append(request) + win.run(requests, mib, lock) + return + pid = os.fork() if jobs == 2 else None + if pid == 0: + try: + build_part(src, out, names[1::2], settings, reports[1], 1) + except BaseException: + import traceback + traceback.print_exc() + os._exit(1) + os._exit(0) + try: + build_part(src, out, names[::jobs], settings, reports[0], 0) + finally: + if pid and os.waitpid(pid, 0)[1]: + raise RuntimeError("second translation worker failed") + + +def build(src, out, names, settings, jobs, mib): cache = out / ".compute-cache" cache.mkdir(exist_ok=True) - with (cache / "lock").open("ab") as lock, tempfile.TemporaryDirectory(dir=cache) as tmp: - fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + with output_lock(cache / "lock") as lock, tempfile.TemporaryDirectory(dir=cache) as tmp: reports = [Path(tmp) / str(i) for i in range(jobs)] - pid = os.fork() if jobs == 2 else None - if pid == 0: - try: - build_part(src, out, names[1::2], settings, reports[1], compact) - except BaseException: - import traceback - traceback.print_exc() - os._exit(1) - os._exit(0) - try: - build_part(src, out, names[::jobs], settings, reports[0], compact) - finally: - if pid and os.waitpid(pid, 0)[1]: - raise RuntimeError("second translation worker failed") + run_parts(src, out, names, settings, jobs, reports, mib, lock) index, failures, pairs = {}, {}, {} - for report in reports: + audits = [] + for i, report in enumerate(reports): part = json.loads(report.read_text(encoding="utf-8")) + accepted, failed = set(part["rows"]), set(part["failures"]) + expected = names[i::jobs] + audit = {"shard": i, "recipe_sha256": object_digest(settings), "names_sha256": object_digest(expected), + "options": settings["options"], "accepted": len(accepted), "failed": len(failed)} + if part["audit"] != audit or accepted & failed or accepted | failed != set(expected): + raise ValueError("compute shard options or coverage mismatch") + audits.append(audit) failures.update(part["failures"]) for name, row in part["rows"].items(): + if row["options"] != settings["options"]: + raise ValueError("cached compute row options mismatch") module, meta = row["module"], row["meta"] pair = meta["fspx_code_sha256"], meta["fspx_state_sha256"] if pairs.setdefault(pair, module) != module: @@ -110,7 +204,13 @@ def build(src, out, names, settings, jobs, compact=False): state = digest(src / "fspx" / (name + ".state")) by_hash.setdefault(code, {})[state] = reason translator.write_index(str(out / "failures.json"), by_hash) - translator.write_index(str(out / "index.json"), index) + # An audit, not a publication marker. Associate it with the actual index bytes after commit. + candidate = Path(tmp)/"final-index.json" + translator.write_index(str(candidate), index) + index_hash = digest(candidate) + translator.write_index(str(cache / "worker-receipt.json"), + {"schema": 1, "recipe": settings, "index_sha256": index_hash, "shards": audits}) + translator.replace_retry(candidate, out / "index.json") print(f"{len(index)}/{len(names)} valid, {len(failures)} failed") return int(bool(failures)) @@ -120,7 +220,8 @@ def main(): ap.add_argument("inputs", type=Path, help="unpacked library with index.json, disasm/ and fspx/") ap.add_argument("--out", type=Path, required=True, help="dedicated runtime library subdirectory") ap.add_argument("--jobs", type=int, choices=(1, 2), default=2) - ap.add_argument("--memory-mib", type=int, default=768, help="virtual memory per process (default 768 MiB)") + ap.add_argument("--memory-mib", type=int, default=768, + help="per-process limit: virtual space (Linux) or committed memory (Windows); default 768 MiB") ap.add_argument("--descriptor-hash", choices=translator.DESCRIPTOR_HASHES, default="fnv1a", help="bindless descriptor table hash shared with the runtime") ap.add_argument("--loop-limit", type=translator.spirv_loop_guard.parse_limit, @@ -133,21 +234,21 @@ def main(): src, out = args.inputs.resolve(), args.out.resolve() if out == src or src in out.parents or out in src.parents: ap.error("input and output directories must be separate") - os.setpriority(os.PRIO_PROCESS, 0, 19) - soft, hard = resource.getrlimit(resource.RLIMIT_AS) - bound = min(n for n in (args.memory_mib << 20, soft, hard) if n != resource.RLIM_INFINITY) - resource.setrlimit(resource.RLIMIT_AS, (bound, hard)) - versions = [] - required_tools = ["spirv-as", "spirv-val"] - if args.compact_spirv: - required_tools.append("spirv-opt") - for tool in required_tools: - binary = shutil.which(tool) - if not binary: - ap.error(tool + " is required") - versions.append(digest(Path(binary))) - settings = [translation_sources_digest(), digest(Path(__file__)), versions, args.wave64_emulate, - args.loop_limit, args.descriptor_hash] + if os.name == "nt": + import compute_workers_win as win + win.budget_coordinator(args.memory_mib) + else: + import resource + os.setpriority(os.PRIO_PROCESS, 0, 19) + soft, hard = resource.getrlimit(resource.RLIMIT_AS) + bound = min(n for n in (args.memory_mib << 20, soft, hard) if n != resource.RLIM_INFINITY) + resource.setrlimit(resource.RLIMIT_AS, (bound, hard)) + options = Options(args.wave64_emulate, args.loop_limit, args.descriptor_hash, args.compact_spirv) + options.apply() + try: + settings = recipe(options) + except ValueError as e: + ap.error(str(e)) rows = json.loads((src / "index.json").read_text(encoding="utf-8")) names = [] for row in rows: @@ -156,14 +257,15 @@ def main(): filename = row["file"] if Path(filename).name != filename or not filename.endswith(".dxbc") or "\\" in filename: ap.error("invalid compute filename in input index") + if os.name == "nt" and (any(ord(c)<32 or c in '<>:"|?*' for c in filename) or + (os.path.isreserved(filename) if hasattr(os.path, "isreserved") + else Path(filename).is_reserved())): + ap.error("invalid Windows compute filename in input index") names.append(filename[:-5]) - if not names or len(set(names)) != len(names): + if not names or len({os.path.normcase(n) for n in names}) != len(names): ap.error("expected unique compute filenames in the input index") out.mkdir(parents=True, exist_ok=True) - translator.DESCRIPTOR_HASH = args.descriptor_hash - translator.LOOP_LIMIT = args.loop_limit - translator.WAVE64_EMULATE = args.wave64_emulate - return build(src, out, sorted(names), settings, args.jobs, args.compact_spirv) + return build(src, out, sorted(names), settings, args.jobs, args.memory_mib) if __name__ == "__main__": diff --git a/tests/semantic/test_buffer_offset_wrap.py b/tests/semantic/test_buffer_offset_wrap.py new file mode 100644 index 0000000000..9f5707be2c --- /dev/null +++ b/tests/semantic/test_buffer_offset_wrap.py @@ -0,0 +1,109 @@ +"""A buffer offset that does not fit 32 bits is out of range in every OOB_SELECT mode. + +The hardware adds index * stride (a full product) and soffset to the 48-bit V# base without wrapping at 32 bits, so +an index of 0xFFFFFFFF with a 20-byte stride lands far outside the buffer and the access has no effect. A translator +that keeps the offset in 32 bits turns the same access into base - 20, which is inside a view that covers a whole +pool: OOB_SELECT 3 does not check the index and 2 checks nothing. (Rule and hardware observation: five-star-recomp, +commit b9b57e2. The expected memory below is written out by hand.) + + python -I tests/semantic/test_buffer_offset_wrap.py -v +""" +import os +import sys +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) + +from spirv_mini_interp import run_workgroup +from test_loop_ballot_barrier import _translate_cs + +BASE, OUTPUT = 0x4000, 0x8000 +STRIDE, BYTES = 20, 4096 +LANES = 32 +RAW, DISABLED, STRUCTURED_OFFSET = 0x31016FAC, 0x21016FAC, 0x01016FAC +SENTINEL, VALUE = 0xA5A5A5A5, 77 + + +def indexed(index, literal_word3=None): + """Store VALUE at `index` of the view in s[0:3], load it back and write what was read to the output view.""" + lines = [] + view = "s[0:3]" + if literal_word3 is not None: + # The same descriptor from immediates, which the translator folds: the mode is known when translating. + lines += [f"s_mov_b32 s8, {BASE:#x}", f"s_mov_b32 s9, {STRIDE << 16:#x}", f"s_mov_b32 s10, {BYTES:#x}", + f"s_mov_b32 s11, {literal_word3:#x}"] + view = "s[8:11]" + return lines + [ + f"v_mov_b32_e32 v1, {index}", + f"v_mov_b32_e32 v2, {VALUE}", + f"buffer_store_dword v2, v1, {view}, 0 idxen", + f"buffer_load_dword v3, v1, {view}, 0 idxen", + "v_lshlrev_b32_e32 v4, 2, v0", + "buffer_store_dword v3, v4, s[4:7], 0 offen", + "s_endpgm"] + + +SOFFSET = [ + # off = 0xFFFFFFF0 (32-bit, as the hardware forms it), then soffset 0x20 is added in 64 bits: 0x1_0000_0010. + "v_mov_b32_e32 v1, -16", + f"v_mov_b32_e32 v2, {VALUE}", + "s_mov_b32 s12, 32", + "buffer_store_dword v2, v1, s[0:3], s12 offen", + "buffer_load_dword v3, v1, s[0:3], s12 offen", + "v_lshlrev_b32_e32 v4, 2, v0", + "buffer_store_dword v3, v4, s[4:7], 0 offen", + "s_endpgm"] + + +class BufferOffsetWrapTests(unittest.TestCase): + def run_case(self, lines, word3, stride=STRIDE, records=BYTES): + module, _ = _translate_cs("cs_buffer_offset_wrap", lines, threads=LANES) + memory = {address: SENTINEL for address in range(BASE - 64, BASE + 128, 4)} + before = dict(memory) + result = run_workgroup( + module, LANES, LANES, + inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i, "%local_index": i}, + push_constants=[BASE, stride << 16, records, word3, OUTPUT, 0, LANES * 4, RAW] + [0] * 24, + memory=memory) + view = {address: result[address] for address in before} + return view, before, [result[OUTPUT + 4 * lane] for lane in range(LANES)] + + def test_index_inside_the_buffer_is_stored_and_read(self): + for name, word3, literal in (("raw", RAW, None), ("raw literal", RAW, RAW), ("disabled", DISABLED, None)): + with self.subTest(mode=name): + view, before, read = self.run_case(indexed(2, literal), word3) + before[BASE + 2 * STRIDE] = VALUE + self.assertEqual(view, before) + self.assertEqual(read, [VALUE] * LANES) + + def test_index_whose_product_with_the_stride_passes_32_bits_has_no_effect(self): + # 0xFFFFFFFF * 20 = 0x13_FFFF_FFEC; modulo 2^32 it would be the 20 bytes below the base. + for name, word3, literal in (("raw", RAW, None), ("raw literal", RAW, RAW), ("disabled", DISABLED, None), + ("disabled literal", DISABLED, DISABLED)): + with self.subTest(mode=name): + view, before, read = self.run_case(indexed(-1, literal), word3) + self.assertEqual(view, before) + self.assertEqual(read, [0] * LANES) + + def test_structured_modes_already_refuse_the_index(self): + view, before, read = self.run_case(indexed(-1), STRUCTURED_OFFSET, records=8) + self.assertEqual(view, before) + self.assertEqual(read, [0] * LANES) + + def test_soffset_is_added_without_wrapping(self): + # DISABLED checks only that the buffer is not empty; modulo 2^32 the access would land at base + 0x10. + view, before, read = self.run_case(SOFFSET, DISABLED, stride=0) + self.assertEqual(view, before) + self.assertEqual(read, [0] * LANES) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_descriptor_hash.py b/tests/semantic/test_descriptor_hash.py index 4ca3f3ac7c..af3ccd35fd 100644 --- a/tests/semantic/test_descriptor_hash.py +++ b/tests/semantic/test_descriptor_hash.py @@ -54,7 +54,7 @@ def readback_shader(mode): g.emit(f"{key} = OpLoad %uint {ptr}") keys.append(key) hashed = g.desc_hash(keys) - index = g.desc_lookup(keys) + index, _kind = g.desc_lookup(keys) # tagged: the probe also returns the entry's kind, unused here g.emit("%hp = OpAccessChain %heap_ptr %pc %c0") g.emit("%heap = OpLoad %ulong %hp") for i, value in enumerate((hashed, index)): diff --git a/tests/semantic/test_fspx_rules.py b/tests/semantic/test_fspx_rules.py index a0a3555982..cf2e7f30d1 100644 --- a/tests/semantic/test_fspx_rules.py +++ b/tests/semantic/test_fspx_rules.py @@ -157,7 +157,7 @@ def test_slist_as_vsharp_and_tsharp(self): f"v_mov_b32_e32 v6, {OUT:#x}", "global_store_dword v6, v4, s[0:1]", ]) - self.assertIn("OpFunctionCall %uint %desc_lookup_fn", spv) + self.assertRegex(spv, r"OpFunctionCall %\w+ %desc_lookup_fn") def test_slist_length_mismatch_rejected(self): with self.assertRaises(rdna2spirv.Unsupported): diff --git a/tests/semantic/test_loop_ballot_barrier.py b/tests/semantic/test_loop_ballot_barrier.py index c83dd5f534..9f5c6ffb2e 100644 --- a/tests/semantic/test_loop_ballot_barrier.py +++ b/tests/semantic/test_loop_ballot_barrier.py @@ -1059,11 +1059,11 @@ def expected_for(threads): configs = [ ("native_64", 64, 64, False, True), ("native_128", 128, 64, False, True), - # a reducible multi-block loop takes the structured emulation since #2089 (no round OpSwitch) ... + # Single-wave inline exchange barriers in this loop require a round fallback. ("emulate_64_sg32", 64, 32, True, True), ("emulate_128_sg32", 128, 32, True, True), ("emulate_40_partial_sg32", 40, 32, True, True), - # ... and --dispatch-loop keeps the round scheduler: both must give the native words + # Forced dispatch must produce the same per-lane reference words. ("emulate_64_sg32_rounds", 64, 32, True, False), ("emulate_128_sg32_rounds", 128, 32, True, False), ("emulate_40_partial_sg32_rounds", 40, 32, True, False), @@ -1073,8 +1073,10 @@ def expected_for(threads): spv, gen = _translate_cs("cs_div_loop_" + label, prog, threads=threads, emulate=emulate, structured=structured) if emulate: - self.assertEqual(gen.control_flow, - "emulated wave64 structured" if structured else "emulated wave64 rounds") + use_hybrid = structured and threads == 128 + expected_flow = "emulated wave64 structured" if use_hybrid else "emulated wave64 rounds" + self.assertEqual(gen.control_flow, expected_flow) + self.assertFalse(rdna2spirv.barriers_under_control_flow(spv)) mem = run_compute_workgroup(spv, threads, sg_sz, push_constants=VSHARP) want = expected_for(threads) for t in range(threads): diff --git a/tests/semantic/test_loop_iteration_guard.py b/tests/semantic/test_loop_iteration_guard.py index 27193f19db..a990031dd8 100644 --- a/tests/semantic/test_loop_iteration_guard.py +++ b/tests/semantic/test_loop_iteration_guard.py @@ -15,7 +15,7 @@ def module(lanes, limit, structured=True): with patch.object(rdna2spirv, "LOOP_LIMIT", limit): text, gen = _translate_cs("cs_guard", lines, threads=lanes, emulate=lanes == 64, structured=structured) assert gen.wave64 == (lanes == 64) and gen.emulate == (lanes == 64) - return text + return text, gen.control_flow def execute(text, lanes, bound): @@ -31,20 +31,37 @@ class LoopGuardTests(unittest.TestCase): def test_finite_and_nonterminating(self): for lanes in (32, 64): with self.subTest(lanes=lanes): - plain, guarded = module(lanes, 0), module(lanes, 16) + (plain, plain_flow), (guarded, flow) = module(lanes, 0), module(lanes, 16) + expected_flow = "structured" if lanes == 32 else "emulated wave64 rounds" + self.assertEqual((plain_flow, flow), (expected_flow, expected_flow)) self.assertNotIn("%loop_guard_", plain) self.assertIn("%loop_guard_", guarded) self.assertEqual(execute(plain, lanes, 6), [6] * lanes) self.assertEqual(execute(guarded, lanes, 6), [6] * lanes) - self.assertEqual(execute(guarded, lanes, 1), [32] * lanes) + # Round zero initializes the guest PC. Each remaining round adds two. + expected = 32 if lanes == 32 else 30 + self.assertEqual(execute(guarded, lanes, 1), [expected] * lanes) + + def test_round_budget_uses_the_scheduler_exit(self): + text, flow = module(64, 16) + self.assertEqual(flow, "emulated wave64 rounds") + # Counters and synchronization execute on the final round too. The guard + # augments the scheduler's termination condition at its original branch. + tail = text.split("%x_ran = OpLabel", 1)[1].split("%loop_exit = OpLabel", 1)[0] + counters, latch = tail.split("%loop_cont = OpLabel") + self.assertIn("OpAtomicIAdd", counters) + self.assertTrue(counters.rstrip().endswith("OpBranch %loop_cont")) + self.assertLess(latch.index("OpControlBarrier"), latch.index("%x_fin =")) + self.assertRegex(latch, r"OpLogicalOr %bool %x_fin (%loop_guard_\w+_full)") + self.assertRegex(latch, r"OpBranchConditional %loop_guard_\w+_take %loop_exit %loop_head\s*$") def test_dispatch_loop_also_stops(self): for lanes in (32, 64): with self.subTest(lanes=lanes): - guarded = module(lanes, 16, structured=False) + guarded, _ = module(lanes, 16, structured=False) self.assertEqual(execute(guarded, lanes, 6), [6] * lanes) words = execute(guarded, lanes, 1) - self.assertTrue(all(0 < v <= 32 and v % 2 == 0 for v in words)) + self.assertEqual(words, [30] * lanes) def test_inner_budget_resets_on_each_entry(self): diff --git a/tests/semantic/test_sampled_dynamic_index.py b/tests/semantic/test_sampled_dynamic_index.py index b6d841eba0..afc7963906 100644 --- a/tests/semantic/test_sampled_dynamic_index.py +++ b/tests/semantic/test_sampled_dynamic_index.py @@ -47,12 +47,24 @@ def uniform_descriptor_predicate(value, definitions): class SampledDynamicIndex(unittest.TestCase): def check_accesses(self, asm, sampled_bindings, storage_bindings=()): bindings = {var: int(binding) for var, binding in re.findall(r"OpDecorate (%\w+) Binding (\d+)", asm)} - lookups = set(re.findall(r"(%\w+) = OpFunctionCall %uint %desc_lookup_fn ", asm)) + lookups = set(re.findall(r"(%\w+) = OpFunctionCall %\w+ %desc_lookup_fn ", asm)) broadcasts = re.findall(r"(%\w+) = OpGroupNonUniformBroadcastFirst %uint %\w+ (%\w+)", asm) # a wave32 pixel shader in a 64-lane subgroup takes its own half's first lane with a shuffle (design.md, # "Execution model": shuffle sources keep the current half) broadcasts += re.findall(r"(%\w+) = OpGroupNonUniformShuffle %uint %\w+ (%\w+) %\w+", asm) lookup_indices = lookups | {result for result, source in broadcasts if source in lookups} + # The index a chain uses is that value, or the array's fallback chosen by the T# dimension check + # (an OpSelect against 0): follow the extracts and selects the probe's result feeds. + for _ in range(4): + more = {res for res, source in re.findall( + r"(%\w+) = Op(?:CompositeExtract %uint|GroupNonUniformBroadcastFirst %uint %\w+|" + r"GroupNonUniformShuffle %uint %\w+) (%\w+)", asm) if source in lookup_indices} + 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"} + if more <= lookup_indices: + break + lookup_indices |= more definitions = dict(re.findall(r"^\s*(%\w+) = (Op[^\n]+)$", asm, re.M)) zero = {var for var, op in definitions.items() if op == "OpConstant %uint 0"} # An unsupported tagged storage view selects the null descriptor. Only a uniform diff --git a/tests/semantic/test_tsharp_dimension.py b/tests/semantic/test_tsharp_dimension.py new file mode 100644 index 0000000000..364cbc5012 --- /dev/null +++ b/tests/semantic/test_tsharp_dimension.py @@ -0,0 +1,151 @@ +"""The T# dimension contract (docs/design.md, "Images and samplers (T# dimension)"). + +On RDNA2 the hardware addresses an image through the T#'s own TYPE, and the bindless set gives each image its index +in ITS dimension's array. An instruction that reads a T# of another dimension therefore must not index its own +array with that index blindly: a 2D-array or cube T# read by a 2D instruction is its slice 0 (the runtime binds that +view at the same index in the 2D array), while a 3D T# read by a 2D instruction, or any other mismatch, reads that +dimension's fallback. A store, atomic or coherent read through such a T# goes to the storage fallback, and an image +with only a sampled view has no storage index at all. + +The translator's side is: every entry of the descriptor table carries a kind word (one bit per array, sampled and +storage), the probe returns it next to the index, and every image access selects between the index and 0 on the bit +for the array its instruction reads. `--descriptor-table plain` keeps the old modules' bytes (no kind word read). + +These tests translate small pixel and compute programs with the real translator (support) and check the emitted +SPIR-V: the bit each instruction dimension tests, the storage rule, the fallback operand, and the plain layout. +""" +import os +import re +import sys +import unittest + +import support +import rdna2spirv + +EPILOGUE = ["exp mrt0 v0, v1, v2, v3 done vm", "s_endpgm"] +# dim -> (address registers, sampled bit, storage bit) +DIMS = {"2D": ("v[4:5]", 0, 8), "2D_ARRAY": ("v[4:6]", 1, 9), "CUBE": ("v[4:6]", 1, 9), + "3D": ("v[4:6]", 2, 10), "1D": ("v4", 3, 11)} +DESC = "s[0:7]" + + +def translate(lines, table=None): + saved = rdna2spirv.DESCRIPTOR_TABLE + if table is not None: + rdna2spirv.DESCRIPTOR_TABLE = table + try: + return support.translate_lines("ps_tsharpdim", ["v_mov_b32 v4, 1", "v_mov_b32 v5, 2", "v_mov_b32 v6, 0"] + + lines + EPILOGUE) + finally: + rdna2spirv.DESCRIPTOR_TABLE = saved + + +def uint_consts(text): + out = {} + for line in text.splitlines(): + m = re.match(r"\s*(%\w+) = OpConstant %uint (\d+)$", line) + if m: + out[m.group(1)] = int(m.group(2)) + return out + + +def one_bit_extracts(text): + """The offsets of every OpBitFieldUExtract of one bit with a literal offset: the kind word's bit tests.""" + consts = uint_consts(text) + offsets = [] + for line in text.splitlines(): + m = re.search(r"OpBitFieldUExtract %uint (.*)$", line) + if not m: + continue + parts = m.group(1).split() + if len(parts) != 3: + continue + off, width = consts.get(parts[1]), consts.get(parts[2]) + if width == 1 and off is not None: + offsets.append(off) + return offsets + + +def selects_with_zero(text): + """(id, operands) of every OpSelect of a uint that picks a zero constant.""" + consts = uint_consts(text) + out = [] + for line in text.splitlines(): + m = re.match(r"\s*(%\w+) = OpSelect %uint (.*)$", line) + if not m: + continue + parts = m.group(2).split() + if any(consts.get(p) == 0 for p in parts): + out.append((m.group(1), parts)) + return out + + +class KindBits(unittest.TestCase): + def test_dimension_tags(self): + self.assertEqual(rdna2spirv.Gen.DIM_TAGS, { + "dim:SQ_RSRC_IMG_2D": 0, "dim:SQ_RSRC_IMG_2D_ARRAY": 1, "dim:SQ_RSRC_IMG_CUBE": 1, + "dim:SQ_RSRC_IMG_3D": 2, "dim:SQ_RSRC_IMG_1D": 3, "dim:SQ_RSRC_IMG_1D_ARRAY": 4}) + + def test_each_sampled_dimension_reads_its_own_bit(self): + for dim, (addr, sampled_bit, _) in DIMS.items(): + with self.subTest(dim=dim): + spv = translate([f"image_load v[0:3], {addr}, {DESC} dmask:0xf dim:SQ_RSRC_IMG_{dim} unorm"]) + self.assertEqual(one_bit_extracts(spv), [sampled_bit]) + + def test_each_storage_dimension_requires_its_storage_bit(self): + for dim, (addr, _, storage_bit) in (DIMS | {"1D_ARRAY": ("v[4:5]", None, 12)}).items(): + with self.subTest(dim=dim): + spv = translate([f"image_store v[0:3], {addr}, {DESC} dmask:0xf dim:SQ_RSRC_IMG_{dim} unorm"]) + self.assertEqual(one_bit_extracts(spv), [storage_bit]) + + def test_atomics_use_the_storage_bit(self): + for dim, bit in (("2D", 8), ("3D", 10)): + with self.subTest(dim=dim): + spv = translate([f"image_atomic_add v0, {DIMS[dim][0]}, {DESC} dmask:0x1 dim:SQ_RSRC_IMG_{dim} unorm"]) + self.assertEqual(one_bit_extracts(spv), [bit]) + + def test_coherent_load_uses_the_storage_rule(self): + spv = translate(["image_load v[0:3], v[4:5], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_2D unorm glc dlc"]) + self.assertEqual(one_bit_extracts(spv), [8]) + + def test_gather_and_lod_reads_use_the_sampled_bit(self): + spv = translate(["image_gather4_lz v[0:3], v[4:5], s[0:7], s[8:11] dmask:0x1 dim:SQ_RSRC_IMG_2D"]) + self.assertEqual(one_bit_extracts(spv), [0]) + spv = translate(["image_get_lod v[0:1], v[4:5], s[0:7], s[8:11] dmask:0x3 dim:SQ_RSRC_IMG_2D_ARRAY"]) + self.assertEqual(one_bit_extracts(spv), [1]) + + def test_mismatch_reads_the_array_fallback(self): + # The index is used only when the entry names the instruction's array; otherwise index 0 of that array, + # whose element is the 1x1 fallback the runtime binds there. So the id the image array is indexed with is + # an OpSelect (bit test, index, 0). + for dim, (addr, bit, _) in DIMS.items(): + with self.subTest(dim=dim): + spv = translate([f"image_load v[0:3], {addr}, {DESC} dmask:0xf dim:SQ_RSRC_IMG_{dim} unorm"]) + self.assertIn(bit, one_bit_extracts(spv)) + zero_selects = selects_with_zero(spv) + self.assertTrue(zero_selects, spv) + ids = {i for i, _ in zero_selects} + indexed = [ln for ln in spv.splitlines() + if " = OpAccessChain %_ptr_UC_" in ln and " %images" in ln and ln.split()[-1] in ids] + self.assertTrue(indexed, spv) + + +class PlainLayout(unittest.TestCase): + def test_plain_reads_only_the_index(self): + spv = translate(["image_load v[0:3], v[4:5], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_2D unorm"], table="plain") + self.assertEqual(one_bit_extracts(spv), []) + self.assertNotIn("dl_kind", spv) + + def test_tagged_probe_returns_index_and_kind(self): + spv = translate(["image_load v[0:3], v[4:5], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_2D unorm"]) + self.assertIn("dl_kind", spv) + self.assertIn("%desc_hit", spv) # a uvec2 (dedupe_types may rename it later) + self.assertIn("OpCompositeConstruct %desc_hit", spv) + + def test_marker_is_recorded_per_module(self): + for table, expected in (("tagged", "tagged"), ("plain", None)): + with self.subTest(table=table): + spv = translate(["image_load v[0:3], v[4:5], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_2D unorm"], + table=table) + meta = rdna2spirv.shader_meta(rdna2spirv.translate.last_gen, spv) + self.assertEqual(meta.get("descriptor_table"), expected) diff --git a/tests/semantic/test_vcc_tuple_fallback.py b/tests/semantic/test_vcc_tuple_fallback.py index 9b614f3812..e0d232c3f1 100644 --- a/tests/semantic/test_vcc_tuple_fallback.py +++ b/tests/semantic/test_vcc_tuple_fallback.py @@ -137,7 +137,7 @@ def test_image_resource_in_vcc(self): ] for variant in PROGRAM_VARIANTS: with self.subTest(printed_as=variant): - self.assertIn("OpFunctionCall %uint %desc_lookup_fn", translate(program, variant)) + self.assertRegex(translate(program, variant), r"OpFunctionCall %\w+ %desc_lookup_fn") def test_junk_that_swallows_the_next_instructions(self): # The junk at the tuple's second word is longer than that word, so it covers the s_mov_b32 after the tuple diff --git a/tests/semantic/test_wave32_pixel_subgroup64.py b/tests/semantic/test_wave32_pixel_subgroup64.py index 4648aa889d..3447ab2d12 100644 --- a/tests/semantic/test_wave32_pixel_subgroup64.py +++ b/tests/semantic/test_wave32_pixel_subgroup64.py @@ -120,7 +120,7 @@ def test_descriptor_index_comes_from_a_running_lane_of_each_half(self): memory = {base + 32 * half + 4 * w: word for half, words in tsharp.items() for w, word in enumerate(words)} # The runtime's descriptor hash table: word 0 the slot mask, then 10-word slots (T# words at 1-8, the # bindless index at 9). Two slots and mask 1: every T# is found within two probes whatever its hash. - desc_map = [1, *tsharp[0], 1, 0, *tsharp[1], 2] + desc_map = [1, *tsharp[0], 1, 1, *tsharp[1], 2, 1] texels = {1: (0.25, 0.5, 0.75, 1.0), 2: (1.0, 0.75, 0.5, 0.25)} images = [None] + [(lambda coord, lod, t=texels[k]: t) for k in (1, 2)] for first_quad in ("absent", "helpers"): diff --git a/tests/semantic/test_wave64_emulate_opt.py b/tests/semantic/test_wave64_emulate_opt.py index 58b7c2c7e4..6593a668b7 100644 --- a/tests/semantic/test_wave64_emulate_opt.py +++ b/tests/semantic/test_wave64_emulate_opt.py @@ -1281,9 +1281,9 @@ def test_single_store_acyclic_fold_orders_war_and_raw(self): class StructuredEmulationTests(unittest.TestCase): """Structured --wave64-emulate (`inline_all` for <=64 threads, `structured_hybrid` for >64 threads).""" - def test_single_wave_inline_all_zero_switch_and_loop_carried_war(self): + def test_single_wave_round_fallback_and_loop_carried_war(self): # 64-thread and partial 40-thread shaders with live-out scalars, loop-carried store->load->store WAR/RAW, - # and v_readfirstlane emit 0 OpSwitch cases and 0 x_spills while staying bit-exact. + # and v_readfirstlane require uniform exchange barriers on both scheduling orders. insns = [ ("s_mov_b64 exec, -1", 4), ("s_mov_b32 s16, 10", 4), @@ -1314,11 +1314,10 @@ def test_single_wave_inline_all_zero_switch_and_loop_carried_war(self): for threads in (64, 40): with self.subTest(threads=threads): spv, gen = _translate_encoded(f"cs_inline_{threads}", insns, (threads, 1, 1), emulate=True) - self.assertEqual(gen.control_flow, "emulated wave64 structured") - self.assertEqual(gen.emulate_plan["mode"], "inline_all") - self.assertNotIn("OpSwitch", spv) - self.assertEqual(len(gen.x_spills), 0) - self.assertNotIn("OpGroupNonUniform", spv) + self.assertEqual(gen.control_flow, "emulated wave64 rounds") + self.assertIsNone(gen.emulate_plan) + self.assertIn("OpSwitch", spv) + self.assertFalse(rdna2spirv.barriers_under_control_flow(spv)) for rev in (False, True): mem, _ = run_emulated_workgroup(spv, (threads, 1, 1), push_constants=VSHARP + [0] * 28, reverse_order=rev) # Reference simulation diff --git a/tests/test_desc_cache.py b/tests/test_desc_cache.py index a8443efd00..584d9a94c4 100644 --- a/tests/test_desc_cache.py +++ b/tests/test_desc_cache.py @@ -21,7 +21,13 @@ sys.path.insert(0, os.path.join(ROOT, "tools")) import rdna2spirv # noqa: E402 -CALL = "OpFunctionCall %uint %desc_lookup_fn" +LOOKUP_FN = "%desc_lookup_fn" # the probe every image instruction calls + + +def lookup_calls(text): + """How many descriptor lookups the module calls. The probe's result type depends on the table entry + layout (`--descriptor-table`: a plain module gets the index only, a tagged one index and kind).""" + return sum(1 for line in text.splitlines() if "OpFunctionCall" in line and LOOKUP_FN in line) STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("> 16, words[i] & 0xffff + if not length or i + length > len(words): + raise ValueError("invalid SPIR-V instruction") + a = words[i + 1:i + length] + i += length + if op == 43: # OpConstant + constants[a[1]] = a[2] + elif op == 59 and a[2] == 9: # OpVariable, PushConstant + push.add(a[1]) + elif op == 61: # OpLoad + loads[a[1]] = a[2] + elif op == 65: # OpAccessChain + chains[a[1]] = a[2:] + elif op in (234, 239): # OpAtomicIAdd, OpAtomicUMax + dst = chains.get(a[2], []) + if len(dst) != 3 or constants.get(dst[1]) != 0: + continue + member = chains.get(loads.get(dst[0]), []) + if len(member) == 2 and member[0] in push and constants.get(member[1]) == 4: + word = constants[dst[2]] + if word >= 8: + found.add((word, op)) + return found + + +class TestIndirectClampTelemetry(unittest.TestCase): + def test_embedded_preclamp_mesh_counters(self): + src = Path(__file__).resolve().parents[1] / "runtime" / "src" + # Active mesh records + records requesting y/z > 1; max y and max z before clamping. + self.assertEqual(mesh_counter_ops((src / "indirect_clamp_spv.h").read_text(encoding="ascii")), + {(8, 234), (9, 234), (10, 239), (11, 239)}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_translate_pipeline_compute.py b/tests/test_translate_pipeline_compute.py index 1a241a15e6..a669bfb68b 100644 --- a/tests/test_translate_pipeline_compute.py +++ b/tests/test_translate_pipeline_compute.py @@ -13,31 +13,36 @@ ROOT = Path(__file__).resolve().parents[1] +def authored_pair(tmp): + root = Path(tmp) + src, out = root / "input", root / "output" + (src / "disasm").mkdir(parents=True) + (src / "fspx").mkdir() + rows = [] + for i in (0, 1): + name = f"cs_test_{i}" + rows.append({"file": name + ".dxbc", "stage": "cs"}) + code = struct.pack("> 28 & 3 + # The hardware adds the offset to the 48-bit base without wrapping at 32 bits: index * stride is a full + # product and soffset is added in 64 bits. An index of 0xFFFFFFFF with a 20-byte stride therefore lands tens + # of GiB past the base, outside every buffer, and the access has no effect. `total` is that offset modulo + # 2^32, which would put the same access 20 bytes below the base: inside a view that covers a whole pool, where + # OOB_SELECT 3 does not look at the index and 2 looks at nothing. So an offset that does not fit 32 bits is out + # of range in every mode (a load reads 0, a store or atomic is dropped). `fits` is None where the mode's own + # check already bounds the index and no soffset is added. The rule and its hardware observation are + # five-star-recomp's (ThatRecompDev, GPL-3, commit b9b57e2). + fits = None + + def u64(v): + t = self.tmp() + self.emit(f"{t} = OpUConvert %ulong {v}") + return t + + def add64(x, y): + t = self.tmp() + self.emit(f"{t} = OpIAdd %ulong {x} {y}") + return t + + if (idx is not None or not soff_zero) and not (mode in (0, 1) and soff_zero and swz_active is False): + if swz_active is False: + wide = u64(off) + else: + # the swizzled offset above, with the same terms in 64 bits + inner64, sh64 = self.tmp(), self.tmp() + self.emit(f"{inner64} = OpIMul %ulong {u64(msb)} {u64(stride)}") + inner64 = add64(inner64, u64(om4)) + self.emit(f"{sh64} = OpShiftLeftLogical %ulong {inner64} {L}") + wide = add64(add64(sh64, u64(l4)), u64(ol)) + if not soff_zero: + wide = add64(wide, u64(soff_v)) + if idx is not None and swz_active is False: + prod = self.tmp() + self.emit(f"{prod} = OpIMul %ulong {u64(idx)} {u64(stride)}") + wide = add64(wide, prod) + fits = self.tmp() + self.emit(f"{fits} = OpULessThanEqual %bool {wide} {self.cl(0xFFFFFFFF)}") + self.uses_long = True self.uses_psb = True l64, h64, sh, base, o64, addr = (self.tmp() for _ in range(6)) self.emit(f"{l64} = OpUConvert %ulong {d0}") @@ -4193,7 +4248,6 @@ def buffer_address(self, a, mods, parts=False, elem=None, fixed_fmt=None): self.emit(f"{base} = OpBitwiseOr %ulong {sh} {l64}") self.emit(f"{o64} = OpUConvert %ulong {total}") self.emit(f"{addr} = OpIAdd %ulong {base} {o64}") - mode = None if lit3 is None else lit3 >> 28 & 3 mode0_rule = mode in (None, 0) or (mode == 3 and sw3 is not False) need_raw = mode in (None, 3) and sw3 is not True need_p3 = mode in (None, 3) and sw3 is not False @@ -4276,7 +4330,16 @@ def raw_or_swizzled(e3_sw, end_bytes): return r def check_end(end_bytes): - """in-range bool of an access that ends end_bytes after its first byte.""" + """in-range bool of an access that ends end_bytes after its first byte: the mode's rule, and an offset + that fits 32 bits.""" + ok = mode_check_end(end_bytes) + if fits is None: + return ok + both = self.tmp() + self.emit(f"{both} = OpLogicalAnd %bool {ok} {fits}") + return both + + def mode_check_end(end_bytes): if mode == 1: return p1 if mode == 2: @@ -12789,35 +12852,48 @@ def store_slot(slot, val): # ---- images: T#/S# -> bindless index through a runtime-filled hash table ---- # Table layout (storage buffer, set 0 binding 2): uint mask; then entries of 10 uints: - # key[0..7] (descriptor dwords; S# uses key[0..3] and key[4..7] = 0xFFFFFFFF), index, pad. + # key[0..7] (descriptor dwords; S# uses key[0..3] and key[4..7] = 0xFFFFFFFF), index, kind. # Probes 8 slots from hash(key) & mask; a miss yields index 0 (the runtime puts a fallback there). + # 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): - """words: 8 uint ids. Returns a uint id with the bindless index. + """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 image instruction calls. Inlined at each use it was most of the code of texture-heavy shaders: 194 image instructions made over half of a 7 MB module.""" self.uses_tex = True + tagged = self.descriptor_table != "plain" if self.desc_fn is None: params = [f"%dl_w{i}" for i in range(8)] saved, self.body = self.body, [] result = self.desc_probe(params) lines, self.body = self.body, saved - self.desc_fn = (["%desc_lookup_fn = OpFunction %uint None %fn_desc_lookup"] + + ret = "%desc_hit" if tagged else "%uint" + self.desc_fn = ([f"%desc_lookup_fn = OpFunction {ret} None %fn_desc_lookup"] + [f"{p} = OpFunctionParameter %uint" for p in params] + ["%dl_entry = OpLabel"] + lines + [f" OpReturnValue {result}", "OpFunctionEnd"]) r = self.tmp() - self.emit(f"{r} = OpFunctionCall %uint %desc_lookup_fn " + " ".join(words)) + self.emit(f"{r} = OpFunctionCall {'%desc_hit' if tagged else '%uint'} %desc_lookup_fn " + " ".join(words)) + if tagged: + idx, kind = self.tmp(), self.tmp() + self.emit(f"{idx} = OpCompositeExtract %uint {r} 0") + self.emit(f"{kind} = OpCompositeExtract %uint {r} 1") + else: + idx, kind = r, None if self.emulate: - return r + 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. b = self.tmp() - self.g_shuffle(b, r, self.wave32_first_running_lane()) - return b + self.g_shuffle(b, idx, self.wave32_first_running_lane()) + if kind is not None: + k = self.tmp() + self.g_shuffle(k, kind, self.wave32_first_running_lane()) + kind = k + return b, kind # The descriptor words are SGPRs, so the index is the same in every invocation of the subgroup; the # broadcast is an identity on every driver and makes that uniformity explicit to the compiler. Mesa ANV # (26.2.7, Alder Lake Xe-LP) segfaults compiling a sampler index straight from the probe loop when one @@ -12825,9 +12901,13 @@ def desc_lookup(self, words): # subgroup operation (x_round), so it is left out there. Track this separately from uses_subgroup: this # operation needs GroupNonUniform + GroupNonUniformBallot, but no Shuffle capability or lane input. b = self.tmp() - self.emit(f"{b} = OpGroupNonUniformBroadcastFirst %uint {self.cu(3)} {r}") + self.emit(f"{b} = OpGroupNonUniformBroadcastFirst %uint {self.cu(3)} {idx}") self.uses_bcast_first = True - return b + if kind is not None: + k = self.tmp() + self.emit(f"{k} = OpGroupNonUniformBroadcastFirst %uint {self.cu(3)} {kind}") + kind = k + return b, kind def desc_hash(self, words): """Hash a T# or padded S# exactly as the runtime descriptor table does.""" @@ -12853,6 +12933,7 @@ def desc_hash(self, words): def desc_probe(self, words): """Probe up to eight slots for the full descriptor key.""" + tagged = self.descriptor_table != "plain" h = self.desc_hash(words) mp, mask = self.tmp(), self.tmp() self.emit(f"{mp} = OpAccessChain %_ptr_SB_uint %desc_map %c0 %c0") @@ -12864,8 +12945,11 @@ def desc_probe(self, words): # on the loop header's phi, which Mesa ANV 26.1.6 (Intel UHD 630, CFL GT2) miscompiles in ps_table_fetch # by hoisting the binding-table-index add above the loop (reading slot 0 / magenta before %dl_idx is set). kv, iv = "%dl_k", "%dl_idx" # slot number, and the result (0 until a slot matches) - self.body[0:0] = [f" {kv} = OpVariable %_ptr_Function_uint Function %c0", - f" {iv} = OpVariable %_ptr_Function_uint Function %c0"] + kvars = [f" {kv} = OpVariable %_ptr_Function_uint Function %c0", + f" {iv} = OpVariable %_ptr_Function_uint Function %c0"] + if tagged: + kvars.append(" %dl_kind = OpVariable %_ptr_Function_uint Function %c0") + self.body[0:0] = kvars self.emit("OpBranch %dl_head") self.body.append("%dl_head = OpLabel") self.emit("OpLoopMerge %dl_end %dl_cont DontUnroll") @@ -12893,6 +12977,13 @@ def desc_probe(self, words): self.emit(f"{p} = OpAccessChain %_ptr_SB_uint %desc_map %c0 {o}") self.emit(f"{v} = OpLoad %uint {p}") self.emit(f"OpStore {iv} {v}") + if tagged: + # The entry's last word: the arrays this index is bound in (the pad word a plain table leaves alone). + ko, kp, kk = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{ko} = OpIAdd %uint {base} {self.cu(10)}") + self.emit(f"{kp} = OpAccessChain %_ptr_SB_uint %desc_map %c0 {ko}") + self.emit(f"{kk} = OpLoad %uint {kp}") + self.emit(f"OpStore %dl_kind {kk}") self.emit("OpBranch %dl_end") # the first match breaks out of the probe loop directly self.body.append("%dl_next = OpLabel") self.emit("OpBranch %dl_cont") @@ -12905,7 +12996,12 @@ def desc_probe(self, words): self.emit(f"OpBranchConditional {more} %dl_head %dl_end") self.body.append("%dl_end = OpLabel") self.emit(f"{r} = OpLoad %uint {iv}") - return r + if not tagged: + return r + hit, kind = self.tmp(), self.tmp() + self.emit(f"{kind} = OpLoad %uint %dl_kind") + self.emit(f"{hit} = OpCompositeConstruct %desc_hit {r} {kind}") + return hit def desc_cache_ok(self): """True when the next instruction is emitted at the top level of the basic block, outside any selection or @@ -13380,11 +13476,12 @@ def gather_mip(image: str, cls: int, ty: str) -> str: 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. - The cache holds the id of the call's result per (first SGPR, n). It is dropped by store_reg when any - SGPR of the range is written (all writes to the %sgpr 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 the bindless index (a uint id).""" + The cache holds the ids of the call's result per (first SGPR, n): the index and, with --descriptor-table + tagged, the kind. It is dropped by store_reg when any SGPR of the range is written (all writes to the %sgpr + 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.""" if a["k"] == "slist" and len(a["r"]) >= n: words = self.sgpr_words(a, n) if n < 8: @@ -13405,6 +13502,41 @@ def desc_lookup_sgpr(self, a, n): self.desc_cache[key] = idx return idx + # 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, + "dim:SQ_RSRC_IMG_3D": 2, "dim:SQ_RSRC_IMG_1D": 3, "dim:SQ_RSRC_IMG_1D_ARRAY": 4} + + def desc_array_bit(self, kind, dim, base): + """A bool id: is bit `base + dim` of the descriptor's kind set (the index is bound in that array)?""" + bit = self.tmp() + self.emit(f"{bit} = OpBitFieldUExtract %uint {kind} {self.cu(base + self.DIM_TAGS[dim])} {self.cu(1)}") + out = self.tmp() + self.emit(f"{out} = OpINotEqual %bool {bit} {self.cu(0)}") + return out + + def desc_sampled_index(self, idx, kind, dim): + """The bindless index for the sampled array of `dim`: the lookup's index when the entry says it is bound + there, else 0 (that array's fallback, a 1x1 image of zeros). With --descriptor-table plain nothing is + emitted and the index is used as before.""" + if kind is None: + return idx + ok = self.desc_array_bit(kind, dim, DESC_SAMPLED_BIT) + out = self.tmp() + self.emit(f"{out} = OpSelect %uint {ok} {idx} {self.cu(0)}") + return out + + def desc_storage_index(self, idx, kind, dim): + """The bindless index for the storage array of `dim`, or 0 (its fallback, where stores land and are + dropped) when the entry says the index is not bound in it: an image whose T# is of another dimension, or + one with a sampled view only.""" + if kind is None: + return idx + ok = self.desc_array_bit(kind, dim, DESC_STORAGE_BIT) + out = self.tmp() + self.emit(f"{out} = OpSelect %uint {ok} {idx} {self.cu(0)}") + return out + def sgpr_word(self, a, i): if a["k"] == "sgpr": return self.load_reg("sgpr", a["r"] + i) @@ -13503,7 +13635,13 @@ def image_op(self, op, a, mods): if (dim != "dim:SQ_RSRC_IMG_2D" or dmask != 1 or len(addr) != (3 if a16 else 4) or any(m not in (dim, dm, "a16", "d16") for m in mods)): raise Unsupported(op + " needs scalar 2D depth comparison") - img_idx = self.desc_lookup_sgpr(a[2], 8) + img_idx, kind = self.desc_lookup_sgpr(a[2], 8) + # The T#'s own type decides which array holds this index. A read through another dimension's array (a + # slice-0 view of a 2D-array or cube T#, which the runtime binds in the 2D array) is valid only when the + # entry says so; otherwise the read is that array's fallback. A coherent read goes through the storage + # view the stores write, so it follows the storage arrays' rule instead. + img_idx = (self.desc_storage_index(img_idx, kind, view_dim) if coherent + else self.desc_sampled_index(img_idx, kind, dim)) img = None # a coherent image_load reads the storage view, not this sampled one if not (coherent or storage_only): ip, img = self.tmp(), self.tmp() @@ -13560,7 +13698,7 @@ def image_op(self, op, a, mods): lod=self.cu(0), d16=d16) return else: - smp_idx = self.desc_lookup_sgpr(a[3], 4) + smp_idx = self.desc_lookup_sgpr(a[3], 4)[0] sp, smp, si = self.tmp(), self.tmp(), self.tmp() self.dynamic_sampled_access(sp, "%_ptr_UC_smp", "%samplers", smp_idx) self.emit(f"{smp} = OpLoad %smp {sp}") @@ -14315,7 +14453,8 @@ def image_store(self, a, mods, dim): uv = vals sv = [self.as_int(v) for v in vals] coords = [self.as_int(c) for c in raw[:nc]] - idx = self.desc_lookup_sgpr(a[2], 8) + idx, kind = self.desc_lookup_sgpr(a[2], 8) + idx = self.desc_storage_index(idx, kind, view_dim) t1 = self.sgpr_word(a[2], 1) self.uses_store_views.add(di) for w in [16] + sum(self.int_format_masks(), []): # constants used by assemble's format masks @@ -14535,7 +14674,8 @@ def image_misc(self, op, a, mods): words = 2 if packed else ncoord + 1 if len(addr) < words: raise Unsupported("image_load_mip coords") - idx = self.desc_lookup_sgpr(a[2], 8) + idx, kind = self.desc_lookup_sgpr(a[2], 8) + idx = self.desc_sampled_index(idx, kind, dim) ip, img, iv = self.tmp(), self.tmp(), self.tmp() if is3d: self.uses_tex_3d = True @@ -14557,7 +14697,7 @@ def image_misc(self, op, a, mods): or ("a16" in mods and not is_atomic) or "d16" in mods): raise Unsupported(op + " " + dim.split("SQ_RSRC_IMG_")[-1]) vdata, addr = a[0], self.addr_regs(a[1]) - idx = self.desc_lookup_sgpr(a[2], 8) + idx, kind = self.desc_lookup_sgpr(a[2], 8) def atomic_coords(nc): raw = [self.load_reg("vgpr", r) for r in addr] @@ -14597,6 +14737,9 @@ def atomic_coords(nc): self.emit(f"{iv} = OpCompositeConstruct %v2int {coords[0]} {coords[1]}") ptr_ty, arr_var = "%_ptr_UC_simg", "%simages" run = self.active_b() + # A store, atomic or coherent read through a T# of another dimension, or through one whose image has + # no storage views, goes to that dimension's storage fallback: writes and atomics there are dropped. + idx = self.desc_storage_index(idx, kind, dim) if op in self.IMG_ATOMICS_EXTRA: self.emit_image_atomic_extra(op, ptr_ty, arr_var, idx, iv, vdata, mods, volume_active=run) @@ -14630,6 +14773,7 @@ def atomic_coords(nc): self.emit(f"{end} = OpLabel") return ip, img = self.tmp(), self.tmp() + idx = self.desc_sampled_index(idx, kind, dim) if array_query: self.uses_tex_array = True self.dynamic_sampled_access(ip, "%_ptr_UC_imga", "%images_arr", idx) @@ -16074,7 +16218,13 @@ def assemble(gen): types.append(f"{name} = OpConstant %uint {v}") written = dict(gen.consts) # what the module defines; insert_late_constants adds what assemble asks for later if gen.desc_fn: - types.append("%fn_desc_lookup = OpTypeFunction %uint " + " ".join(["%uint"] * 8)) + # --descriptor-table tagged: the probe also returns the entry's kind word, so the function returns (index, + # kind) as a uvec2. + if gen.descriptor_table != "plain": + types.append("%desc_hit = OpTypeVector %uint 2") + types.append("%fn_desc_lookup = OpTypeFunction %desc_hit " + " ".join(["%uint"] * 8)) + else: + types.append("%fn_desc_lookup = OpTypeFunction %uint " + " ".join(["%uint"] * 8)) if gen.tbuffer_norm_fns: types.append("%fn_tbuffer_norm = OpTypeFunction %uint %uint") if gen.fmt_fn or gen.fmt_enc_fn: @@ -17935,7 +18085,54 @@ def marker_wave64(path, name, stage, insns): return code_w64 or stage == "ms" # NGG mesh shaders here are wave64 (thread = wave id * 64 + lane) -def translate(path): +_FLOW = re.compile(r"(?m)^[ \t]*(?:(%[\w.]+)\s*=\s*)?(OpLabel|OpSelectionMerge|OpLoopMerge|OpBranch|" + r"OpBranchConditional|OpControlBarrier)\b([^;\n]*)") + + +def barriers_under_control_flow(text): + """Whether some OpControlBarrier is reached by only part of the workgroup. + + SPIR-V requires a workgroup-scope barrier to be reached by every invocation in uniform control flow. + NVIDIA's wait is for every thread (docs/design.md "Workgroup barriers"): a barrier one invocation never + reaches stands the whole group until the driver resets the card (Xid 109 / device lost). Emulated wave64 + exchanges (`Gen.x_round`, `x_order_barrier`) emit such barriers inline, so the inline structured form may + bury one inside a `%pc` guard, a lane-local region or a loop body; `Gen.x_scheduler` keeps one barrier at + the end of every round instead, in the loop's continue block. + + A barrier in a loop's continue block counts as uniform: every invocation runs the round loop.""" + label_at, constructs, pending = {}, [], [] + for match in _FLOW.finditer(text): + result, op, operands = match.groups() + args = operands.split() + if op == "OpLabel": + label_at[result] = match.start() + elif op in ("OpLoopMerge", "OpSelectionMerge"): + nxt = _FLOW.search(text, match.end()) + if nxt is None or nxt.group(2) not in ("OpBranch", "OpBranchConditional"): + continue # a switch head has no body label to compare + body = nxt.group(3).split()[0 if nxt.group(2) == "OpBranch" else 1] + pending.append((op, body, args[0], args[1] if op == "OpLoopMerge" else None)) + for op, body, merge, cont in pending: + if body in label_at and merge in label_at: + constructs.append({"kind": op, "cont": cont, + "start": label_at[body], "end": label_at[merge]}) + if not constructs: + return False + block_at = sorted((match.start(), match.group(1)) for match in _FLOW.finditer(text) + if match.group(2) == "OpLabel") + for match in _FLOW.finditer(text): + if match.group(2) != "OpControlBarrier": + continue + block = next((name for at, name in reversed(block_at) if at < match.start()), None) + inside = [c for c in constructs if c["start"] <= match.start() < c["end"]] + while inside and inside[-1]["kind"] == "OpLoopMerge" and inside[-1]["cont"] == block: + inside.pop() # the round barrier: the whole workgroup runs it + if inside: + return True + return False + + +def _translate(path): info = parse_file(path) stage = stage_of(info["name"], path) if stage not in ("vs", "ps", "cs", "ms", "gs"): @@ -18316,7 +18513,7 @@ def translate(path): end = next((k for k, ins in enumerate(insns) if base_op(ins["op"]) == "s_endpgm"), len(insns)) g.exec_changes = any(g.may_write_exec(ins) for ins in insns[:end]) g.insns(insns[:end]) - translate.last_gen = g + _translate.last_gen = g return finish_module(g) # ---- basic blocks ---- @@ -18389,7 +18586,7 @@ def target(ins): g.scc_live = wave64_emulate_opt.scc_live_outs(blocks, succ) folds, fold_chain, absorbed = wave64_emulate_opt.find_local_exec_folds( blocks, raw_edges, succ, g.lane_masks, g.scc_live, g.mask_writes) - if STRUCTURED: + if STRUCTURED and WAVE64_PLAN: g.emulate_plan = wave64_emulate_opt.plan_structured_emulation( blocks, raw_edges, succ, folds, fold_chain, absorbed, g.lane_masks, g.scc_live, g.x_lanes) g.fit_shared_memory() @@ -18641,13 +18838,35 @@ def emit_folded_region(fd): g.emulate_inline = False assert succ == g.succ, "the lane-mask analysis ran on a different graph" g.body = [] - translate.last_gen = g + _translate.last_gen = g return finish_module(g) _DEF = re.compile(r"(%\w+) = (Op\w+)(?: (%\w+))?") +def translate(path): + """translate() with one fallback: an emulated wave64 program whose inline structured form puts an + exchange barrier under control flow only some invocations take is translated again as the round loop + (`Gen.x_scheduler`, one OpControlBarrier per round in uniform control flow). + + A workgroup barrier has to be reached by every invocation. NVIDIA waits for every thread, so one that + an invocation never reaches stands the group until the driver resets the card (Xid 109, device lost). + A program that hangs costs a whole run; re-translating it costs one more pass offline.""" + global WAVE64_PLAN + asm = _translate(path) + gen = _translate.last_gen + if (gen is not None and getattr(gen, "emulate_plan", None) is not None + and barriers_under_control_flow(asm)): + WAVE64_PLAN = False + try: + asm = _translate(path) + finally: + WAVE64_PLAN = True + translate.last_gen = _translate.last_gen + return asm + + def finish_module(g): text = assemble(g) if OPT_SPIRV: @@ -19169,6 +19388,10 @@ def shader_meta(g, asm, src_path=None, fssm_path=None): "wave64_emulated": bool(g.wave64 and (g.stage in ("vs", "ps", "gs") or g.emulate))} if g.descriptor_hash != "fnv1a": m["descriptor_hash"] = g.descriptor_hash + if g.descriptor_table != "plain": + # 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 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). @@ -19558,7 +19781,7 @@ def _out_inside_input(src, out): def main(): - global MAX_SHARED_BYTES, MAX_STRUCTURED_DEPTH, LOOP_LIMIT, DESCRIPTOR_HASH + global MAX_SHARED_BYTES, MAX_STRUCTURED_DEPTH, LOOP_LIMIT, DESCRIPTOR_HASH, DESCRIPTOR_TABLE ap = argparse.ArgumentParser() ap.add_argument("src") ap.add_argument("--out", required=True) @@ -19626,6 +19849,10 @@ def main(): "for devices whose maxPushConstantsSize is below 144") ap.add_argument("--descriptor-hash", choices=DESCRIPTOR_HASHES, default="fnv1a", help="bindless descriptor table hash shared with the runtime (default: fnv1a)") + ap.add_argument("--descriptor-table", choices=DESCRIPTOR_TABLES, default="tagged", + help="descriptor table entry layout: 'tagged' also carries each image's array kind, recorded as " + "descriptor_table in the module meta (default: tagged; 'plain' is the old layout, for a " + "library that keeps the runtime's old behaviour)") ap.add_argument("--loop-limit", type=spirv_loop_guard.parse_limit, default=spirv_loop_guard.DEFAULT_LIMIT, help="maximum visits to each loop header, including dispatch loops (default %(default)s, 0 disables)") ap.add_argument("--max-structured-depth", type=_depth_arg, default=MAX_STRUCTURED_DEPTH, metavar="N", @@ -19655,6 +19882,7 @@ def main(): ap.error(f"cannot create {a.out}: {ancestor} is a file, not a folder") MAX_SHARED_BYTES = a.max_shared_memory DESCRIPTOR_HASH = a.descriptor_hash + DESCRIPTOR_TABLE = a.descriptor_table LOOP_LIMIT = a.loop_limit MAX_STRUCTURED_DEPTH = a.max_structured_depth global STRUCTURED, WAVE64_EMULATE, WAVE64_GRAPHICS, BARY_FALLBACK, TEXEL_OFFSET_FALLBACK, MESH_COMPUTE, FMA_KHR, SHADER_CLOCK, F16_HALVES, OPT_SPIRV From 86554c879894b3eb62921653fb27cecfc5dde5fa Mon Sep 17 00:00:00 2001 From: Jan Trencansky Date: Wed, 25 Nov 2026 17:23:18 -0500 Subject: [PATCH 02/10] Fix the build of three test targets and a BOM in a translator test Found building #2098 with clang-cl (Make generator); each also fails on the pull request's own head: - dxgi_swapchain_count_test: VulkanSwapchain takes a SubmitMutex& now; the test passed a std::mutex. - vk_store_test: kind_sampled_bit/kind_storage_bit come from descriptor_table.h, which it did not include. - d3d12_compute_journal_test listed gta6rt_indirect_count_shader's output among its sources, so Make had two rules for cs_indirect_dispatch_count.spv and the two glslangValidator runs raced ("Failed to open file"). It depends on that target now, and the second shader has a target of its own. - tests/semantic/test_tsharp_dimension.py began with a UTF-8 BOM, which test_ci_registration's ast.parse refuses. Co-Authored-By: Claude Opus 5.5 --- runtime/CMakeLists.txt | 7 +++++-- runtime/test/dxgi_swapchain_count_test.cpp | 4 ++-- runtime/test/vk_store_test.cpp | 1 + tests/semantic/test_tsharp_dimension.py | 2 +- 4 files changed, 9 insertions(+), 5 deletions(-) diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 5eb57c5df4..67fcf87864 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2929,8 +2929,11 @@ if(TARGET Vulkan::Headers) -o ${_journal_second_spv} ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_indirect_dispatch_count.comp DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_indirect_dispatch_count.comp COMMENT "Compiling the second authored compute journal control" VERBATIM) - add_executable(d3d12_compute_journal_test test/d3d12_compute_journal_test.cpp - ${_indirect_count_spv} ${_journal_second_spv}) + # The first shader comes from gta6rt_indirect_count_shader: naming its output here too would give Make a second + # rule for the same file, and the two glslangValidator runs raced ("Failed to open file"). + add_custom_target(gta6rt_compute_journal_shader DEPENDS ${_journal_second_spv}) + add_executable(d3d12_compute_journal_test test/d3d12_compute_journal_test.cpp) + add_dependencies(d3d12_compute_journal_test gta6rt_indirect_count_shader gta6rt_compute_journal_shader) target_link_libraries(d3d12_compute_journal_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_compute_journal_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_TEST_COUNTER_SPV="${_indirect_count_spv}" LEONIDA_TEST_COUNTER_V2_SPV="${_journal_second_spv}") diff --git a/runtime/test/dxgi_swapchain_count_test.cpp b/runtime/test/dxgi_swapchain_count_test.cpp index fbbca182ac..c0ca5f6ad0 100644 --- a/runtime/test/dxgi_swapchain_count_test.cpp +++ b/runtime/test/dxgi_swapchain_count_test.cpp @@ -267,7 +267,7 @@ int run_case(const char* label, std::uint32_t requested, std::uint32_t native, s g = Fake{}; g.min_image_count = minimum; g.returned_images = native; - std::mutex mutex; + leonida::SubmitMutex mutex; leonida::VulkanSwapchain swapchain(get_instance_proc, reinterpret_cast(1), reinterpret_cast(2), get_device_proc, reinterpret_cast(3), reinterpret_cast(4), 0, mutex, @@ -375,7 +375,7 @@ int run_failed_resize(const char* label, std::uint32_t requested, std::uint32_t g = Fake{}; g.min_image_count = 2; g.returned_images = native; - std::mutex mutex; + leonida::SubmitMutex mutex; leonida::VulkanSwapchain swapchain(get_instance_proc, reinterpret_cast(1), reinterpret_cast(2), get_device_proc, reinterpret_cast(3), reinterpret_cast(4), 0, mutex, diff --git a/runtime/test/vk_store_test.cpp b/runtime/test/vk_store_test.cpp index 13390e39e4..62e1271f2c 100644 --- a/runtime/test/vk_store_test.cpp +++ b/runtime/test/vk_store_test.cpp @@ -29,6 +29,7 @@ #include "vk_shader_fma.h" #include "vk_pc_tail.h" #include "spirv_capability.h" +#include "../src/descriptor_table.h" #include "../src/gfx10_descriptors.h" #include diff --git a/tests/semantic/test_tsharp_dimension.py b/tests/semantic/test_tsharp_dimension.py index 364cbc5012..5d45aec0b4 100644 --- a/tests/semantic/test_tsharp_dimension.py +++ b/tests/semantic/test_tsharp_dimension.py @@ -1,4 +1,4 @@ -"""The T# dimension contract (docs/design.md, "Images and samplers (T# dimension)"). +"""The T# dimension contract (docs/design.md, "Images and samplers (T# dimension)"). On RDNA2 the hardware addresses an image through the T#'s own TYPE, and the bindless set gives each image its index in ITS dimension's array. An instruction that reads a T# of another dimension therefore must not index its own From 6100d3c43cb2d1854886719ab4b948012be93ad1 Mon Sep 17 00:00:00 2001 From: Jan Trencansky Date: Wed, 25 Nov 2026 17:28:22 -0500 Subject: [PATCH 03/10] runtime/README.md: name the 29 switches #2098 reads tests/test_docs_env_vars.py failed: LEONIDA_TEXTURE_REFRESH_ASYNC, LEONIDA_SUBMIT_ASYNC, the LEONIDA_CONSOLE_HEAP_GPU family, the shadow GPU copies and the diagnostics this branch reads were in no document. One row each in "Switches of the D3D12 layer for a retail boot", from the comments at the code that reads them. Co-Authored-By: Claude Opus 5.5 --- runtime/README.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/runtime/README.md b/runtime/README.md index 16cd4f1549..3699dab3c4 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -399,6 +399,35 @@ 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_COMPILE_GATE` | unset | `1`: a compute pipeline build holds the device's submit lock for its driver calls, so no compute compile runs while a queue submits. Unset: the asynchronous workers compile while other queues submit. | +| `LEONIDA_FAST_PIPELINES` | unset | `graphics`, `compute` or `all` (`1` = all) creates those pipelines with `VK_PIPELINE_CREATE_DISABLE_OPTIMIZATION_BIT` (`shims/d3d12_pipeline_compile.h`): slower shaders, much shorter builds. Part of the compute journal key, so optimized and fast builds keep separate files. | +| `LEONIDA_GRAPHICS_COMPILE_WORKER` | on | 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. | +| `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_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. | +| `LEONIDA_CONSOLE_GPU_FILTER` | `LEONIDA_CONSOLE_RELEASE_FILTER`'s value | With `LEONIDA_CONSOLE_HEAP_GPU=1`, `1`: a released backing, an alias range that went or a word answered since asks for a rescan of only the slots it touches, not of every V# slot. Overflows and key resets still rescan everything. | +| `LEONIDA_CONSOLE_RELEASE_FILTER` | unset | `1`: when a backing is released, only the console-heap slots whose V#s point into it are fixed again (by actual Vulkan address), instead of every V# slot of the heap. The heap log line counts the sweeps, live slots, fixes and full fallbacks. | +| `LEONIDA_SHADOW_GPU` | unset | `1`: aliased pages of the slot-133 shadows are copied on the GPU at the start of a submission, from an import of the mapped title section (`VK_EXT_external_memory_host`, per 2 MiB window, kept while xmem's map journal shows no change over it). Destinations outside the arena and pages that do not import are copied by the CPU as before. | +| `LEONIDA_SHADOW_GPU_MB` | `1024` | With `LEONIDA_SHADOW_GPU=1`, the MiB of title memory imported for those copies at most. | +| `LEONIDA_SHADOW_JOIN` | unset | `1`: pieces of one shadow copy job that continue where the one before ended, in the pages and in the copy, are one copy (one GPU region); one the GPU refuses is copied by the CPU whole. | +| `LEONIDA_STRAY_RO_HEAL` | unset | `1`: a title write into a read-only page of title memory that no guard of ours owns (a guard left behind) makes the page writable again and retries the write, so the title goes on; a shadow may then miss that page's next writes for a frame. Unset: the first 32 such pages are logged. | +| `LEONIDA_PRELUDE_QUEUE_WAIT` | on | The prelude pass of a submission (the console-heap pass) waits for the last submission of another queue that recorded one (`src/vulkan_backend.h`). `0` (an experiment): no wait, so the queues do not serialise on each other's submissions; a list may read what the other pass has not written yet. | +| `LEONIDA_DEPTH_BOUNDS_SLOT70` | on | Slot 70 of the console command list is forwarded to `OMSetDepthBounds` (`shims/d3d12_xs_device.cpp`). `0` leaves the slot to the default thunk. | +| `LEONIDA_DESCRIPTOR_RING` | unset | *Diagnostic.* `1` records the descriptor-table slots each list binds (`shims/d3d12_com.cpp`), as `LEONIDA_DEVICE_FAULT=1` does; it takes a global lock on almost every table bind. | +| `LEONIDA_DESC_PROBE` | unset | *Diagnostic.* `1` logs which console-heap slots the API wrote and which the title wrote itself, what the title's records decode to and whether the GPU can see them. It hashes every slot of every bound table at each submission. The log quotes title data: keep it local. | +| `LEONIDA_DRAW_DIAG` | on with the local diagnostics or `LEONIDA_FSDRAW_PROBE` | *Diagnostic.* Logs the first 8 draws and one in 1,200 after them, with whether each was skipped for having no viewport, its pipeline, render target, viewport and scissor (`shims/d3d12_com.cpp`). `0` turns it off, any other value on. | +| `LEONIDA_FSDRAW_PROBE` | unset | *Diagnostic.* `1` keeps records of T#s registered, CBVs made, pipelines created and tables submitted, and logs full-screen draws with them (`src/fsdraw_probe.h`); `LEONIDA_COMPUTE_INPUTS` turns them on too. They take a lock at each of those events. | +| `LEONIDA_FSDRAW_SLOTS` | `4` | *Diagnostic.* With `LEONIDA_FSDRAW_PROBE=1`, how many slots of a descriptor table are shown. | +| `LEONIDA_COMPUTE_INPUT_LIMIT` | unset | *Diagnostic.* With the compute input probe (`LEONIDA_COMPUTE_INPUTS`), the first n matching dispatches are logged in full, then one in 1,000 (`shims/d3d12_compute_input_probe.h`). Unset or `0`: every one. | +| `LEONIDA_LOCK_TRACE` | unset | *Diagnostic.* `1` logs the first 256 texture `Map` calls that pass a read range (the title's texture lock passes the subresource's byte range there). | +| `LEONIDA_TRACE_TEXTURE` | unset | *Diagnostic.* `
[,
...]` (hex, the base a T# names): logs the resource id of an image registered at that address, so a draw's T# can be followed to the passes that write it. | +| `LEONIDA_MIRROR_LAG` | unset | *Diagnostic.* `1` measures how late a console fence's mirror shows a value the GPU has reached (`shims/d3d12_xs_device.cpp`). | +| `LEONIDA_MIRROR_EXACT` | unset | `1`: the device's fence-wait thread writes a console fence's mirror the moment the timeline reaches the next value, so the title sees a completion as soon as the runtime does; the thread-pool wait stays as the backstop for rewinds (`shims/d3d12_xs_device.cpp`). | +| `LEONIDA_INPUT_STATS` | unset | *Diagnostic.* `1`: every 10 s, how the title asked for input readings (by method and device argument) and what it got (`shims/gameinput.cpp`). | +| `LEONIDA_SAMPLE_FIND` | unset | *Diagnostic.* `[,...]` (hex, title function starts): every report of the thread sampler (`LEONIDA_SAMPLE_MS`) says which threads have the function on their stack (48 frames deep), how often, and their most frequent chain under it (`src/thread_sampler.h`). | The two serializer functions and `D3D12XboxCreateDevice` are the only `d3d12_xs` imports used by the shipped DLLs (measured; see `docs/design.md` and `docs/d3d12_vulkan.md`). The game executable's own From d86ac9813370b06493286ba3c6f33d438ccc89e9 Mon Sep 17 00:00:00 2001 From: Jan Trencansky Date: Wed, 25 Nov 2026 17:33:53 -0500 Subject: [PATCH 04/10] Fill a never-filled mapped texture before its first submission (async refresh) OreoFR's point on #2098 holds: with LEONIDA_TEXTURE_REFRESH_ASYNC=1 the before-execute hook only wakes the refresh worker (request_title_refresh), so a slot-133 texture the title maps, writes and uses in its next submission (a video plane) can be read empty by that submission while the worker has not come to it. The hook now first fills, on the submitting thread, the mapped textures that were never filled (mapped && !fills), with try_to_lock on the registry: the worker may hold it for a fill that needs this queue, so it does not wait. A fill that needs generic staging is left to the worker, as the pass does. Everything else stays on the worker. Test: d3d12_mapped_plane_async (d3d12_existing_heap_test --mapped-plane-async, which sets the switch itself) maps a written R8 plane and copies it to a readback buffer in the first submission, with host image copies and with the staged upload; every byte must be the written one. Co-Authored-By: Claude Opus 5.5 --- runtime/CMakeLists.txt | 3 ++ runtime/shims/d3d12_vulkan_device.cpp | 30 ++++++++++- runtime/test/d3d12_existing_heap_test.cpp | 65 ++++++++++++++++++++++- 3 files changed, 96 insertions(+), 2 deletions(-) diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 67fcf87864..0127d9ada9 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2744,6 +2744,9 @@ 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. + 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. add_test(NAME d3d12_existing_heap_no_write_watch COMMAND d3d12_existing_heap_test) set_tests_properties(d3d12_existing_heap_no_write_watch PROPERTIES SKIP_RETURN_CODE 77 diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index d0edaa26f9..bdf348567b 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -13651,7 +13651,10 @@ class Device final } const phases::Scope timed(phases::textures); if (async_texture_refresh()) { - if (!t_in_title_textures) request_title_refresh(); + if (!t_in_title_textures) { + fill_first_mapped_textures(); + request_title_refresh(); + } } else { refresh_title_textures(); } @@ -15049,6 +15052,31 @@ 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. diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp index 3d65fc7409..25fa1f6544 100644 --- a/runtime/test/d3d12_existing_heap_test.cpp +++ b/runtime/test/d3d12_existing_heap_test.cpp @@ -1402,6 +1402,58 @@ 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). +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; + void* pages = VirtualAlloc(nullptr, 65536, MEM_RESERVE, PAGE_NOACCESS); + EXPECT(pages); + EXPECT(VirtualAlloc(pages, size, MEM_COMMIT, PAGE_READWRITE) == pages); + std::memset(pages, 61, size); + GpuReader gpu; + EXPECT(!gpu.init(device, size)); + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = width; + desc.Height = height; + desc.Format = DXGI_FORMAT_R8_UNORM; + desc.SampleDesc.Count = desc.DepthOrArraySize = desc.MipLevels = 1; + leonida::title_xg_layouts::note({UINT(desc.Dimension), UINT(desc.Format), height, 1, 1, width}, 1); + Ref texture; + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, desc, 6, IID_PPV_ARGS(&texture.p)), S_OK); + void* mapped = nullptr; + EXPECT_HR(texture->Map(0, nullptr, &mapped), S_OK); + EXPECT(mapped == pages); + EXPECT_HR(gpu.allocator->Reset(), S_OK); + EXPECT_HR(gpu.list->Reset(gpu.allocator.p, nullptr), S_OK); + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Transition = {texture.p, 0, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE}; + gpu.list->ResourceBarrier(1, &barrier); + D3D12_TEXTURE_COPY_LOCATION src{texture.p, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + D3D12_TEXTURE_COPY_LOCATION dst{gpu.readback.p, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + dst.PlacedFootprint.Footprint = {desc.Format, width, height, 1, width}; + gpu.list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + EXPECT_HR(gpu.list->Close(), S_OK); + ID3D12CommandList* lists[]{gpu.list.p}; + gpu.queue->ExecuteCommandLists(1, lists); + EXPECT_HR(gpu.queue->Signal(gpu.fence.p, 1), S_OK); + EXPECT_HR(gpu.fence->SetEventOnCompletion(1, gpu.done), S_OK); + EXPECT(WaitForSingleObject(gpu.done, 30000) == WAIT_OBJECT_0); + void* read = nullptr; + EXPECT_HR(gpu.readback->Map(0, nullptr, &read), S_OK); + const auto* bytes = static_cast(read); + const bool filled = std::all_of(bytes, bytes + size, [](auto value) { return value == 61; }); + gpu.readback->Unmap(0, nullptr); + EXPECT(filled); + texture->Unmap(0, nullptr); + texture.p->Release(); + texture.p = nullptr; + VirtualFree(pages, 0, MEM_RELEASE); + return 0; +} + // Several threads write the same watched pages while submissions keep making them read-only again. Two threads that // fault on one page race: the first fault reopens it, a submission can protect it again before the second fault is // handled, and the second write must still be retried, not refused (refused, the process ends: seen natively). After @@ -1990,7 +2042,9 @@ void print_cases(const std::vector& cases, const char* who) { int main(int argc, char** argv) { const bool prefix_only = argc == 2 && std::strcmp(argv[1], "--host-prefix-only") == 0; - if (argc != 1 && !prefix_only) return 2; + 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; @@ -2018,6 +2072,15 @@ int main(int argc, char** argv) { const int result = check_host_prefix_buffers(ours.p); return result || vk.validation_errors() ? 1 : 0; } + if (async_plane) { + int result = vk.host_image_copy ? check_mapped_plane_first_use(ours.p) : 0; + auto no_host_copy = info; // the staged upload too + no_host_copy.host_image_copy = false; + Ref staged; + if (FAILED(rt::d3d12::create_vulkan_device(no_host_copy, IID_PPV_ARGS(&staged.p)))) return 1; + result += check_mapped_plane_first_use(staged.p); + return result || vk.validation_errors() ? 1 : 0; + } failures += check(ours.p, "vulkan"); const std::vector vulkan_cases = open_cases(ours.p); print_cases(vulkan_cases, "vulkan"); From b83ae01f5c16165a27c345adab88c8e189a6408a Mon Sep 17 00:00:00 2001 From: Jan Trencansky Date: Wed, 25 Nov 2026 18:05:25 -0500 Subject: [PATCH 05/10] Build pipelines through main's PipelineCompiles path again, not #2098's pre-pass At the maintainers' decision, main's compile path wins over #2098's second one. #2098 made every lazy PSO asynchronous (async_build = true) and built what a submission needs in a pre-pass of VulkanQueue::execute, one pipeline after another on the submitting thread, with a per-variant state machine (replay_get / replay_await) and a wait budget (LEONIDA_PIPELINE_WAIT_MS, LEONIDA_PIPELINE_WAIT_FRAME_MS). That bypassed PipelineCompiles and PipelineWorkers (parallel compiles with resource_mutex_ released, #1742) and the LargeModuleGate budget (#1889), which d3d12_pipeline_workers(_eager) and d3d12_big_compute_* check. Removed: the pre-pass (collect_pipeline_awaits, await_pipelines, PipelineAwait, ComputePipeline/GraphicsPipeline:: await), PipelineState's Build states, replay_get/replay_await, set_pipeline_build_hook, the wait budget and its 10 s line, and d3d12_pipeline_wait_test, which tested only that. PipelineState is wired as on main again: async_build = LEONIDA_ASYNC_PIPELINES, queue_build for asynchronous builds, build_compute / variant through PipelineCompiles otherwise. Kept from #2098, adapted to main's path: - the record-time build request (request_pipeline_build): queue_build without counting a skip; - compile-helper deferral: a compute build the helper is still making publishes nothing, so its next use asks again; - big warm-ups left to their first use while the title submits (LEONIDA_COMPUTE_WARMUP_LIVE_MAX_BYTES): src/pipeline_wait.h keeps only the last-submission time this reads, noted by VulkanQueue::execute. docs/d3d12_vulkan.md, "Pipelines still being built", says what is left. Co-Authored-By: Claude Opus 5.5 --- docs/d3d12_vulkan.md | 87 +--- runtime/CMakeLists.txt | 9 - runtime/shims/d3d12_com.h | 5 +- runtime/shims/d3d12_vulkan_device.cpp | 345 +++---------- runtime/src/pipeline_wait.h | 172 +------ runtime/src/submit_phases.h | 2 +- runtime/src/vulkan_backend.h | 27 +- runtime/src/vulkan_present.h | 1 - runtime/src/vulkan_replay.h | 130 ----- runtime/test/d3d12_pipeline_wait_test.cpp | 593 ---------------------- 10 files changed, 103 insertions(+), 1268 deletions(-) delete mode 100644 runtime/test/d3d12_pipeline_wait_test.cpp diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index d1af3a18ef..64e8d945ce 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2569,73 +2569,26 @@ Pipeline creation: they take 18.5 s and peak 202 MiB over. Not measured: other drivers, and the title. Tested by `big_compile_gate`, `replay_pipeline_compiles` and `d3d12_big_compute`. -**Pipelines still being built** (`runtime/src/pipeline_wait.h`, `PipelineState::replay_await` / `replay_get` in -`runtime/shims/d3d12_vulkan_device.cpp`). Lazy pipelines are built at first use, and on the 4070 Ti (NVIDIA 630.20) -a large compute pipeline takes the driver 3-10 s, some 37 s. Replay used to build or wait for them inside -`VulkanQueue::execute_now`'s prepare, holding `resource_mutex_` shared across the wait. A minidump of a native boot -just past the story load showed the cost: the submitting thread waited 9.5 s for a compute pipeline the warm-up -thread was building, a title thread creating a texture queued for the exclusive lock behind it, and every -submission behind that; per-submission replay time went 0.5 s, 2.8 s, 6 s, then submissions stopped. - -- **The pre-pass.** `VulkanQueue::execute` first collects, under a short shared `resource_mutex_` (only registry - lookups and a probe of each PSO's state), the pipelines the lists' `Dispatch`, `ExecuteIndirect` (dispatch) and - `Draw` commands need that are not built: each compute PSO once, each graphics PSO once per variant (the mask of - formatted slots the draw leaves unbound, `unbound_slots`, the same mask `prepare_draw` builds with). With the lock - released it asks for each of them, then waits for the ones still being built. No lock of the replay layer is held - while it waits; the PSOs stay alive because the lists hold them. Its time is the `pipes` column of the - `[rt] submit phases` line. -- **Budget.** `LEONIDA_PIPELINE_WAIT_MS` caps one submission's waiting, in all; 0 never waits, -1 waits for every - build (the old behaviour, without the lock). Unset, it is 24 with `LEONIDA_ASYNC_PIPELINES=1` and -1 without, so - the default mode never skips. The budget bounds waits for builds other threads run; a build the submitting thread - runs itself (synchronous mode) takes as long as it takes. `LEONIDA_PIPELINE_WAIT_FRAME_MS` (default 100, -1 off) caps - all submitting threads together between two presents (or per second without presents): a frame of many submissions - does not wait the per-submission budget each time. -- **Skip.** Prepare (`ComputePipeline::build`, `GraphicsPipeline::variant`) never waits for a build another thread - runs: a pipeline still in flight answers null, and the draw or dispatch is dropped as an unresolvable one is (a draw - emits nothing, not even its rendering scope; a dispatch, direct or indirect, binds and dispatches nothing). The - list's barriers, copies, clears, queries and descriptor binding all replay as recorded, so GPU state stays - consistent; what the skipped work would have written keeps its old contents. The build goes on, and a later - submission uses it. A skipped dispatch can lose a one-time update; a title whose progress waits on one keeps - waiting until the pipeline exists (then it runs), so a longer budget trades seconds of stall for fewer skips. -- **Who builds.** Each PSO variant has one state (idle, queued, running, done) under one mutex that no driver call - holds, and exactly one thread claims each build: a worker job that finds its variant claimed returns at once, so - nothing waits on a PSO's `variants_mutex_` behind a build. With `LEONIDA_ASYNC_PIPELINES=1` replay queues builds on - the compile worker at replay's priority (ahead of warm-ups), and does so at record time already: at - `SetPipelineState` for compute and at each draw for graphics, with the variant its bound targets give - (`request_pipeline_build`). Without it, the submitting thread builds a pipeline nobody has started in the pre-pass - (no lock held), and waits for one a warm-up is building (at most the budget, if one is set). After an exit stop - builds run in place; an unlimited wait looks again every 100 ms, so a queued job the stop dropped cannot leave it - waiting. A pipeline that cannot be built is not waited for again; its draws and dispatches are dropped (logged when - the build fails) where the list used to fail as a whole in synchronous mode; strict replay still fails it. - Builds keep the compile gate (`DriverTurn`, `SubmitMutex::CompileTurn`): a submission still waits at the gate for a - create already in the driver. -- **Warm-ups while the title submits.** That gate wait is what a long build costs the title, whoever asked for it: a - native boot's submissions waited 140 s in all at the gate behind compute warm-ups, and past the story load the - worker went through 694 warm-ups of modules over 128 KiB (those over 640 KiB take 4-25 s each) against 25 such - builds a dispatch asked for. So a warm-up of a module over `LEONIDA_COMPUTE_WARMUP_LIVE_MAX_BYTES` of SPIR-V - (default 128 KiB; 0: no limit) is not started while the title submits (a submission in the last second); the - pipeline is built at its first use instead. Smaller warm-ups, and every warm-up before the first submission, run - as before. -- **Log.** Every 10 s while anything happened: `[rt] pipeline waits t=..s: in 10.0 s N pipelines waited for (T ms in - all, L not built in time), D draws and C dispatches skipped, B pipelines still building; budget ...`. The first 32 - skipped pipelines are named once each (`[rt] pipeline-wait: ... skipped while it is being built`). -- **Measured** (native boots of the story load, RTX 4070 Ti, NVIDIA 630.20, `LEONIDA_RT_AS=off`). Before: within - 30 s of the loading screen ending the replay phase went from under 10 ms to 265 ms (max 26 s), 2.8 s and 6 s per - submission, and submissions stopped. With asynchronous builds: submissions kept 20-30/s (replay 4-6 ms) through the - end of the loading screen; in the 17 s after it 744 dispatches and 42 draws were skipped and 8 pipelines waited - for (172 ms in all). Three builds that missed the pipeline cache then took 4-10.5 s each, and the submissions - behind them waited at the compile gate (145 waits, 30 s in all, longest 10.5 s): the gate wait, not replay, is now - what a cold build costs. That boot then lost the device to a GPU hang in a compute dispatch (fault addresses of the - instruction-pointer kind, no invalid access); whether dispatches skipped before it fed it is open. Synchronous: - 34-40 submissions/s at 7-8 ms replay up to the end of the loading screen; past it, the boots ended in a title - crash seen in many boots without this change (a memset into reserved, uncommitted memory) or the early device - loss at 25-37 s (`vkQueueSubmit` 10 s in the driver with no pipeline create in it). -- **Test:** `d3d12_pipeline_wait_test async|sync` (ctest `d3d12_pipeline_wait_async`, `..._sync`) holds a build in - flight with a hook (`set_pipeline_build_hook`): with a 50 ms budget the submission returns within the budget and - its dispatch is skipped while the list's copies run; the next submission, once the build is let go, runs it; a 2 s - budget waits for a build let go 200 ms in and runs it; with -1 another thread creates and maps a buffer at once - while a submission waits; 0 skips without waiting; an exit stop during an unlimited wait builds in place - instead of waiting for a dropped job. RTX 4070 Ti, NVIDIA 630.20. +**Pipelines still being built** (`PipelineState::queue_build` in `runtime/shims/d3d12_vulkan_device.cpp`). Lazy +pipelines are built at first use, and on the 4070 Ti (NVIDIA 630.20) a large compute pipeline takes the driver 3-10 s, +some 37 s. A submission builds the ones it needs through `PipelineCompiles` and `PipelineWorkers` (above), with +`resource_mutex_` released while they compile and the large ones within the memory budget of `LargeModuleGate`. +#2098 had a second path here, a pre-pass in `VulkanQueue::execute` that built them one after another on the +submitting thread; at the maintainers' decision it was replaced by this one when #2098 was merged. + +- **Asynchronous builds** (`LEONIDA_ASYNC_PIPELINES=1`). Prepare asks `queue_build`, which answers the handle once + built and otherwise queues one compile-worker job at replay's priority and answers null: the draw or dispatch is + skipped, the list's other commands replay as recorded, and a later submission uses the pipeline. The job also starts + at record time already: at `SetPipelineState` for compute and at each draw for graphics, with the variant its bound + targets give (`request_pipeline_build`). A compute build the compile helper is still making (`LEONIDA_COMPILE_HELPER`) + publishes nothing, so its next use asks again. +- **Warm-ups while the title submits.** A compute warm-up holds the compile gate for its whole create, and every + submission waits behind it: a native boot's submissions waited 140 s in all at the gate behind compute warm-ups, and + past the story load the worker went through 694 warm-ups of modules over 128 KiB (those over 640 KiB take 4-25 s + each) against 25 such builds a dispatch asked for. So a warm-up of a module over + `LEONIDA_COMPUTE_WARMUP_LIVE_MAX_BYTES` of SPIR-V (default 128 KiB; 0: no limit) is not started while the title + submits (a submission in the last second, `src/pipeline_wait.h`); the pipeline is built at its first use instead. + Smaller warm-ups, and every warm-up before the first submission, run as before. **Open:** whether the game uses `D3D12_PIPELINE_STATE_STREAM_DESC` for mesh/RT and which subobject types appear. The trace will enumerate them. diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 0127d9ada9..715c3e8568 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -3754,15 +3754,6 @@ if(TARGET Vulkan::Headers) target_compile_options(d3d12_compile_teardown_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_compile_teardown COMMAND d3d12_compile_teardown_test) set_tests_properties(d3d12_compile_teardown PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 300) - # Bounded waits for pipelines still being built (src/pipeline_wait.h), with asynchronous builds and without. - add_executable(d3d12_pipeline_wait_test test/d3d12_pipeline_wait_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_TEST_CS}) - target_link_libraries(d3d12_pipeline_wait_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_pipeline_wait_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_TEST_CS_SPV="${LEONIDA_TEST_CS}") - target_compile_options(d3d12_pipeline_wait_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_pipeline_wait_async COMMAND d3d12_pipeline_wait_test async) - add_test(NAME d3d12_pipeline_wait_sync COMMAND d3d12_pipeline_wait_test sync) - set_tests_properties(d3d12_pipeline_wait_async d3d12_pipeline_wait_sync PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 300) # A buffer at the title's own VA (device slot 133) read by the same shader through a root view and a V#. add_executable(d3d12_title_va_test test/d3d12_title_va_test.cpp shims/d3d12_xs_device.cpp test/xmem_geometry_aliases_stub.cpp ${LEONIDA_TEST_CS}) diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index 239b46690e..81ec7db2c6 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -561,13 +561,10 @@ const RootArgumentLayout* root_signature_layout(ID3D12RootSignature* signature); std::uintptr_t compute_pipeline_id(ID3D12PipelineState* pipeline); std::uintptr_t graphics_pipeline_id(ID3D12PipelineState* pipeline); // Record time, for LEONIDA_ASYNC_PIPELINES=1: starts the pipeline's build on the compile worker before the list is -// submitted, without waiting (src/pipeline_wait.h). `id` is what compute_pipeline_id or graphics_pipeline_id gave (0: +// submitted, without waiting (PipelineState::queue_build). `id` is what compute_pipeline_id or graphics_pipeline_id gave (0: // nothing). Compute: at SetPipelineState; graphics: at each draw, with the render-target slots it binds (bit per slot) // and whether it binds a depth buffer. void request_pipeline_build(std::uintptr_t id, std::uint32_t bound_targets, bool depth_bound); -// Tests: `hook` runs on the thread that builds a pipeline for replay (the compile worker, or a submitting thread -// building in place), with the PSO, before the driver is called; a hook that blocks holds that build in flight. -void set_pipeline_build_hook(std::function hook); // What each stage of a Vulkan device's PSO asked for (src/subgroup_size.h), in creation order; null for another PSO. const std::vector* pipeline_subgroup_requests(ID3D12PipelineState* pipeline); // PSOs of any Vulkan device not yet deleted, counting one whose deletion waits for its running build (tests). diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index bdf348567b..5cef2b47f7 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -10004,10 +10004,6 @@ HRESULT parse_pipeline_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, Pipe // A pipeline state, compute (create_compute) or graphics (create_graphics): each shader is found by the SHA-256 of // its FSSM program in the translator's index, and the FSSM blob is copied into the arena as the shader's code base. std::atomic live_pipeline_state_count{0}; // live_pipeline_states() -// set_pipeline_build_hook (tests): called on the building thread with the PSO, once a replay build is claimed and -// before it calls the driver. -std::mutex pipeline_build_hook_mutex; -std::function pipeline_build_hook; // What the bindless set layout was made from, for a compute pipeline's journal name: a pipeline built against another // layout is another pipeline. Field by field, so padding never reaches the hash. @@ -10447,12 +10443,6 @@ class PipelineState final ~PipelineState() override { unregister(); PipelineCompiler::instance().cancel(compile_owner()); // nothing left in practice (last_release) - { - // Builds replay asked for that were dropped with the PSO leave pipeline_wait's count of those in flight. - std::lock_guard lock(builds_mutex()); - for (auto& [unbound, b] : builds_) - if (b.wanted) leonida::pipeline_wait::stats().building.fetch_sub(1, std::memory_order_relaxed); - } auto& vk = device_.context->vk; const VkDevice dev = device_.info.device; if (pipeline_.pipeline) vk.vkDestroyPipeline(dev, pipeline_.pipeline, nullptr); @@ -11338,15 +11328,11 @@ class PipelineState final // A cache-only create that the driver would have to compile stays null: the first draw builds it. if (!graphics_.pipeline && !(cache_only && compile_status == VK_PIPELINE_COMPILE_REQUIRED)) return E_FAIL; } // lazy: graphics_.pipeline stays null and the first draw builds it as variant 0 - // Replay asks through replay_get (prepare, never waiting on another thread's build) and replay_await (the - // submission's pre-pass, with no lock held): a null handle may mean the variant is still being built. - if (graphics_.pipeline) ready0_.store(graphics_.pipeline, std::memory_order_release); - graphics_.async_build = true; + graphics_.async_build = async_replay_compile(); graphics_.variant = [this](std::uint32_t unbound) { - return replay_pipeline("draw", [&] { return replay_get(false, unbound); }); - }; - graphics_.await = [this](std::uint32_t unbound, std::int64_t until, bool* pending) { - return replay_await(false, unbound, until, pending); + return replay_pipeline("draw", [&] { + return graphics_.async_build ? queue_build(false, unbound) : variant(unbound, "draw"); + }); }; graphics_.built = [this](std::uint32_t unbound) { std::unique_lock lock(variants_mutex_, std::try_to_lock); // held: another thread is compiling one @@ -11508,15 +11494,12 @@ class PipelineState final }; pipeline_.build_context = this; } else if (lazy_compute) { - // As for graphics: replay_get at prepare, replay_await in the submission's pre-pass; null may mean the - // pipeline is still being built, and the dispatch is skipped. - pipeline_.async_build = true; + pipeline_.async_build = async_replay_compile(); pipeline_.build = [](void* self) { auto* pso = static_cast(self); - return replay_pipeline("dispatch", [&] { return pso->replay_get(true, 0); }); - }; - pipeline_.await = [](void* self, std::int64_t until, bool* pending) { - return static_cast(self)->replay_await(true, 0, until, pending); + return replay_pipeline("dispatch", [&] { + return pso->pipeline_.async_build ? pso->queue_build(true, 0) : pso->build_compute("dispatch"); + }); }; pipeline_.build_context = this; pipeline_.built = [](void* self) { @@ -11579,7 +11562,7 @@ class PipelineState final return VK_NULL_HANDLE; } // LOCAL FIX (compile helper, d3d12_compile_helper.h): asynchronous builds and warm-ups only ask the helper and - // are deferred (build_claimed puts the variant back to idle, so its next use asks again). While the helper is + // are deferred (queue_build publishes nothing for them, so their next use asks again). While the helper is // still making the file this answers at once, without reading the module; a use asks with replay's priority. // Only replay's own and the warm-up's triggers may answer deferred: compute-create (LEONIDA_LAZY_COMPUTE=0) is // a create whose caller needs a pipeline now, so it waits for the file as a dispatch does in a strict replay @@ -11657,239 +11640,71 @@ class PipelineState final if (!queued) device_.next_checkpoint.store(now + 120000); // refused after an exit stop, or out of memory } - // Replay's builds of this pipeline, by variant (compute: 0; graphics: the unbound mask of - // leonida::GraphicsPipeline::variant), under builds_mutex() with builds_changed(); no driver call holds the lock. - // A variant is idle until something asks for it, queued once a compile-worker job for it is (a warm-up, or one at - // replay's priority), running once a thread has claimed it (the worker, or a submitting thread that builds it in - // place), and done with its handle (null: it cannot be built). Exactly one thread builds each variant: a worker job - // that finds its variant claimed returns at once, so a replay never waits on variants_mutex_ behind a build. - struct Build { - enum State : std::uint8_t { idle, queued, running, done } state = idle; - bool demanded = false; // a job at replay's priority (0) is queued: a warm-up queued by module size is not enough - bool wanted = false; // replay asked for it before it was done: counted in pipeline_wait's "still building" - VkPipeline handle = VK_NULL_HANDLE; - unsigned long long skips = 0; // draws or dispatches skipped while it was being built - }; - static std::mutex& builds_mutex() { - static std::mutex mutex; - return mutex; - } - static std::condition_variable& builds_changed() { - static std::condition_variable changed; - return changed; - } - - // A warm-up is speculative work at the large-compile gate: it waits behind the builds a submission needs. - VkPipeline build_variant(bool compute, std::uint32_t unbound, const char* trigger) { - return compute ? build_compute(trigger, std::strcmp(trigger, "warmup") ? Work::demand : Work::speculative) - : variant(unbound, trigger); - } - - // Takes the build for this thread unless another thread has it or it is done. - static bool claim_locked(Build& b) { - if (b.state == Build::running || b.state == Build::done) return false; - b.state = Build::running; - return true; - } - - static void want_locked(Build& b) { - if (b.wanted || b.state == Build::done) return; - b.wanted = true; - leonida::pipeline_wait::stats().building.fetch_add(1, std::memory_order_relaxed); - } - - // A claimed build's result, published for replay, and every waiter woken. - void finish_build(std::uint32_t unbound, VkPipeline built, bool compute) { - unsigned long long skipped = 0; - { - std::lock_guard lock(builds_mutex()); - Build& b = builds_[unbound]; - b.state = Build::done; - b.handle = built; - if (b.wanted) { - b.wanted = false; - leonida::pipeline_wait::stats().building.fetch_sub(1, std::memory_order_relaxed); - } - skipped = b.skips; - if (!unbound && built) ready0_.store(built, std::memory_order_release); - } - builds_changed().notify_all(); - if (skipped && trace_pipeline_compile()) - std::fprintf(stderr, "[rt] pipeline-deferred type=%s skipped=%llu ready=%d\n", compute ? "compute" : "graphics", - skipped, int(built != VK_NULL_HANDLE)); - } - - // Builds the claimed variant on this thread and publishes it. - VkPipeline build_claimed(bool compute, std::uint32_t unbound, const char* trigger) { - VkPipeline built = VK_NULL_HANDLE; - try { - std::function hook; - { - std::lock_guard lock(pipeline_build_hook_mutex); - hook = pipeline_build_hook; - } - if (hook) hook(static_cast(this)); - built = build_variant(compute, unbound, trigger); - } catch (const std::exception& e) { - std::fprintf(stderr, "[rt] pipeline build failed: %s\n", e.what()); - } catch (...) { - std::fprintf(stderr, "[rt] pipeline build failed\n"); // still finished below, or waiters would never be - } - if (compute && helper_deferred_.exchange(false)) { - defer_build(unbound); - return VK_NULL_HANDLE; + // Asynchronous builds (LEONIDA_ASYNC_PIPELINES=1): replay asks here at prepare, with the resource lock held. The + // handle once built; otherwise a compile-worker job is queued (once) and null answered, so the draw or dispatch is + // skipped and a later submission uses the pipeline. `warm_bytes`: a warm-up, queued by module size. `count_skip`: + // false for a request made at record time (request_early), which skips nothing. + VkPipeline queue_build(bool compute, std::uint32_t unbound, std::size_t warm_bytes = 0, bool count_skip = true) { + static std::mutex publication; // ready handles only; no compiler call holds this lock + const bool warm = warm_bytes != 0; + // After an exit stop (stop_pipeline_compiles) nothing is queued: a warm-up or an early request is skipped, + // and a draw or dispatch builds in place, as without LEONIDA_ASYNC_PIPELINES, rather than waiting for a build + // that never comes. + if (PipelineCompiler::instance().closed()) { + if (warm || !count_skip) return VK_NULL_HANDLE; + return compute ? build_compute("dispatch") : variant(unbound, "draw"); + } + std::lock_guard lock(publication); + if (!warm) { + if (!requested_) requested_ = std::make_unique(); + auto [it, inserted] = requested_->try_emplace(unbound); + if (!it->second.handle && count_skip) ++it->second.skips; + if (!inserted) return it->second.handle; } - finish_build(unbound, built, compute); - return built; - } - - // The compile helper is making the variant's journal file (build_compute): not done, so its next use asks again. - // Waiters are not woken for it: a bounded wait ends at its deadline, an unlimited one looks again every 100 ms. - void defer_build(std::uint32_t unbound) { - std::lock_guard lock(builds_mutex()); - Build& b = builds_[unbound]; - b.state = Build::idle; - b.demanded = false; - } - - // A compile-worker job for the variant at `priority` (0: replay asked for it; a module size: a warm-up). False when - // it could not be queued (refused after an exit stop, or out of memory). With builds_mutex() held. - bool queue_locked(Build& b, bool compute, std::uint32_t unbound, std::size_t priority) { bool queued = false; try { - const bool warm = priority != 0; - queued = PipelineCompiler::instance().submit(compile_owner(), &device_, priority, [this, compute, unbound, warm, - priority] { - { - std::lock_guard lock(builds_mutex()); - Build& b = builds_[unbound]; - if (warm && !b.demanded && b.state == Build::queued && warmup_waits_for_quiet(priority)) { - b.state = Build::idle; // left to its first use - return; + queued = PipelineCompiler::instance().submit(compile_owner(), &device_, warm_bytes, + [this, compute, warm, unbound, warm_bytes] { + // A big warm-up while the title submits is left to the pipeline's first use (warmup_waits_for_quiet). + if (warm && warmup_waits_for_quiet(warm_bytes)) return; + VkPipeline built{}; + try { + built = compute ? build_compute(warm ? "warmup" : "dispatch-worker", + warm ? Work::speculative : Work::demand) + : variant(unbound, "draw-worker"); + // The compile helper is still making the journal file (build_compute): not built, so nothing is + // published and the next use asks again. + const bool deferred = compute && helper_deferred_.exchange(false); + if (async_replay_compile()) { + unsigned long long skipped = 0; + { + std::lock_guard publish(publication); + if (!requested_) requested_ = std::make_unique(); + if (deferred) { + if (!warm) requested_->erase(unbound); + } else { + auto& entry = (*requested_)[unbound]; + if (!entry.handle) skipped = entry.skips; + entry.handle = built; + } + } + if (skipped && trace_pipeline_compile()) + std::fprintf(stderr, "[rt] pipeline-deferred type=%s skipped=%llu ready=%d\n", + compute ? "compute" : "graphics", skipped, int(built != VK_NULL_HANDLE)); } - if (!claim_locked(b)) return; // built, or being built by a submitting thread + } catch (const std::exception& e) { + std::fprintf(stderr, "[rt] pipeline compile worker failed: %s\n", e.what()); } - build_claimed(compute, unbound, compute ? (warm ? "warmup" : "dispatch-worker") : "draw-worker"); }, !compute); // a graphics build may also take the graphics worker } catch (...) { } - if (queued && b.state == Build::idle) b.state = Build::queued; - if (queued && !priority) b.demanded = true; - return queued; - } - - // Asynchronous builds: the handle once built; otherwise makes sure a job at replay's priority is on its way and - // answers null, with `pending` false only when nothing is on its way (it could not be queued). builds_mutex() held. - VkPipeline request_locked(Build& b, bool compute, std::uint32_t unbound, bool& pending) { - pending = false; - if (b.state == Build::done) return b.handle; - pending = b.state == Build::running || (b.state == Build::queued && b.demanded) || - queue_locked(b, compute, unbound, 0); - if (pending) want_locked(b); + // Not queued (refused by a stop that came after the check above, or out of memory): no request stays + // recorded, so the next use asks again instead of waiting for a build that never comes. + if (!queued && !warm) requested_->erase(unbound); return VK_NULL_HANDLE; } - // The first skips of each still-building variant are named (32 in all), the rest only counted (pipeline_wait.h). - void note_skip(bool compute, std::uint32_t unbound, bool first) const { - leonida::pipeline_wait::count_skip(compute); - static std::atomic logged{0}; - if (!first || logged.fetch_add(1, std::memory_order_relaxed) >= 32) return; - std::fprintf(stderr, "[rt] pipeline-wait: %s of %s pipeline %s (variant %u) skipped while it is being built, at " - "t=%.3f s\n", compute ? "dispatches" : "draws", compute ? "compute" : "graphics", - describe().c_str(), unbound, double(leonida::diagnostic_ms()) / 1000.0); - } - - std::string describe() const { - if (compute_entry_) return compute_entry_->name; - std::string names; - for (const StageSource& source : sources_) { - if (!source.entry) continue; - if (!names.empty()) names += '+'; - names += source.entry->name; - } - return names.empty() ? std::string("-") : names; - } - public: - // Prepare's handle for the variant (ComputePipeline::build, GraphicsPipeline::variant), called with the context's - // resource lock held: never waits for a build another thread runs. Asynchronous builds (LEONIDA_ASYNC_PIPELINES=1) - // queue one at replay's priority and answer null; the draw or dispatch is skipped and counted. Otherwise a variant - // nobody has started is built here, as before (the submission's pre-pass, replay_await, normally did it with no - // lock held), and one running elsewhere (a warm-up) answers null. After an exit stop it is built here. - VkPipeline replay_get(bool compute, std::uint32_t unbound) { - if (!unbound) - if (const VkPipeline ready = ready0_.load(std::memory_order_acquire)) return ready; - bool build_here = false, pending = false, first = false; - VkPipeline handle = VK_NULL_HANDLE; - { - std::lock_guard lock(builds_mutex()); - Build& b = builds_[unbound]; - if (b.state == Build::done) return b.handle; - const bool async = async_replay_compile() && !PipelineCompiler::instance().closed(); - if (!async && claim_locked(b)) { - build_here = true; - } else { - if (async) { - handle = request_locked(b, compute, unbound, pending); - } else { - pending = true; // claimed by another thread - want_locked(b); - } - if (pending) first = b.skips++ == 0; - } - } - if (build_here) return build_claimed(compute, unbound, compute ? "dispatch" : "draw"); - if (pending) note_skip(compute, unbound, first); - return handle; - } - - // The submission's pre-pass (ComputePipeline::await, GraphicsPipeline::await), with no lock of the replay layer - // held. `until` as in pipeline_wait.h: probe answers what is built and starts nothing; otherwise a variant nobody - // has started is queued at replay's priority (asynchronous builds) or built here, and one still in flight is - // waited for until `until`. `*pending`: the null answer means "not built yet" (false: built, or cannot be). - // An unlimited wait looks again every 100 ms, so a job dropped from the queue (an exit stop) cannot leave it - // waiting for a build nobody will run: after a stop the variant is built here. - VkPipeline replay_await(bool compute, std::uint32_t unbound, std::int64_t until, bool* pending_out) { - namespace wait = leonida::pipeline_wait; - const auto answer = [pending_out](VkPipeline handle, bool pending) { - if (pending_out) *pending_out = pending && !handle; - return handle; - }; - if (!unbound) - if (const VkPipeline ready = ready0_.load(std::memory_order_acquire)) return answer(ready, false); - std::unique_lock lock(builds_mutex()); - Build& b = builds_[unbound]; // a std::map node: the reference stays valid - for (;;) { - if (b.state == Build::done) return answer(b.handle, false); - if (until == wait::probe) return answer(VK_NULL_HANDLE, true); - const bool async = async_replay_compile() && !PipelineCompiler::instance().closed(); - bool pending = false; - if (!async) { - if (claim_locked(b)) { - lock.unlock(); - return answer(build_claimed(compute, unbound, compute ? "dispatch" : "draw"), false); - } - pending = true; // claimed by another thread (a warm-up): waited for below - want_locked(b); - } else { - request_locked(b, compute, unbound, pending); - } - if (!pending) { - // Refused by an exit stop that came after the closed() check above: round again to build it here. - if (async && PipelineCompiler::instance().closed()) continue; - return answer(VK_NULL_HANDLE, false); - } - if (until <= wait::now_ns()) return answer(VK_NULL_HANDLE, true); - const auto done = [&] { return b.state == Build::done; }; - const std::int64_t slice = until == wait::forever ? wait::now_ns() + 100000000 : until; - builds_changed().wait_until(lock, std::chrono::steady_clock::time_point(std::chrono::nanoseconds(slice)), - done); - if (b.state == Build::done) return answer(b.handle, false); - if (until != wait::forever && until <= wait::now_ns()) return answer(VK_NULL_HANDLE, true); - // An unlimited wait, still pending: ask again (after an exit stop the variant is built here). - } - } - // Record time (SetPipelineState for compute, a draw for graphics, with the render-target slots it binds and // whether it binds a depth buffer): asynchronous builds start on the compile worker before the list is submitted. // Never waits; nothing to do when the variant is the last one asked for here. @@ -11904,14 +11719,10 @@ class PipelineState final unbound |= leonida::GraphicsPipeline::unbound_depth; if (!unbound && graphics_.pipeline) return; } else if (!pipeline_.build || pipeline_.skipped) { - return; // an eager pipeline has no build; a built lazy one is caught by ready0_ below + return; // an eager pipeline has no build } - if (!unbound && ready0_.load(std::memory_order_relaxed)) return; if (early_.exchange(unbound + 1, std::memory_order_relaxed) == unbound + 1) return; - if (PipelineCompiler::instance().closed()) return; - std::lock_guard lock(builds_mutex()); - bool pending = false; - request_locked(builds_[unbound], !is_graphics_, unbound, pending); + queue_build(!is_graphics_, unbound, 0, false); } private: @@ -11930,7 +11741,7 @@ class PipelineState final }(); if (!limit || bytes <= limit || !leonida::pipeline_wait::title_submitting()) return false; if (compile_helper::wanted(bytes)) return false; // the helper compiles it, in its own process - if (leonida::pipeline_wait::stats().warmups_left.fetch_add(1, std::memory_order_relaxed) == 0) { + if (leonida::pipeline_wait::warmups_left().fetch_add(1, std::memory_order_relaxed) == 0) { static std::atomic logged{false}; if (!logged.exchange(true)) std::fprintf(stderr, "[rt] d3d12: compute warm-ups over %zu KiB are left to their first use while the " @@ -11940,14 +11751,6 @@ class PipelineState final return true; } - // A warm-up of the compute pipeline on the compile worker, queued by module size, unless something asked already. - void queue_warmup(std::size_t bytes) { - if (PipelineCompiler::instance().closed()) return; - std::lock_guard lock(builds_mutex()); - Build& b = builds_[0]; - if (b.state == Build::idle) queue_locked(b, true, 0, bytes); - } - static void warmup_enqueue(PipelineState* pso, std::size_t bytes) { static const std::size_t max_bytes = [] { char text[32]{}; @@ -11959,7 +11762,7 @@ class PipelineState final wchar_t v[2]{}; return !(GetEnvironmentVariableW(L"LEONIDA_COMPUTE_WARMUP", v, 2) == 1 && v[0] == L'0'); }(); - if (on && bytes && bytes <= max_bytes) pso->queue_warmup(bytes); + if (on && bytes && bytes <= max_bytes) pso->queue_build(true, 0, bytes); } // What a graphics pipeline is made from, so variants can be built at draw time. @@ -12284,10 +12087,11 @@ class PipelineState final unsigned rgba4_mask_ = 0; // graphics: the B4G4R4A4 targets stored as RGBA8 that the pixel shader is quantised for bool dual_source_ = false; // graphics: a SRC1 blend factor; the pixel shader's SV_Target1 is Location 0, Index 1 std::vector sources_; - std::map builds_; // under builds_mutex() - std::atomic ready0_{VK_NULL_HANDLE}; // variant 0 once built: read without the lock + struct Request { VkPipeline handle{}; unsigned long long skips = 0; }; + using Requests = std::map; + std::unique_ptr requested_; // Compile helper (build_compute, under variants_mutex_): the journal file asked for and not there yet; whether - // the helper gave up on this pipeline (it is then built here); a build just deferred (read by build_claimed). + // the helper gave up on this pipeline (it is then built here); a build just deferred (read by queue_build). std::filesystem::path helper_file_; bool helper_refused_ = false; std::atomic helper_deferred_{false}; @@ -19890,9 +19694,6 @@ bool save_pipeline_caches_at_exit(unsigned wait_ms) { HRESULT create_vulkan_device(const VulkanDeviceInfo& info, REFIID riid, void** out) { if (!out) return E_POINTER; *out = nullptr; - // An unset LEONIDA_PIPELINE_WAIT_MS: a bounded wait (then a skip) only where builds are asynchronous; without them - // a submission waits for every build, as before, but with no lock held (src/pipeline_wait.h). - leonida::pipeline_wait::default_submission_ms().store(async_replay_compile() ? 24 : -1); auto* device = new Device(info); if (!device->ok()) { device->Release(); @@ -20026,11 +19827,6 @@ std::uintptr_t graphics_pipeline_id(ID3D12PipelineState* pipeline) { return p && p->resolve_type(true) ? p->id() : 0; } -void set_pipeline_build_hook(std::function hook) { - std::lock_guard lock(pipeline_build_hook_mutex); - pipeline_build_hook = std::move(hook); -} - void request_pipeline_build(std::uintptr_t id, std::uint32_t bound_targets, bool depth_bound) { if (!id || !async_replay_compile()) return; // The id is the PSO's own ID3D12PipelineState pointer (PipelineState::id), which the list keeps a reference to. @@ -21446,7 +21242,6 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin chosen.limits.maxPushConstantsSize); } - leonida::pipeline_wait::default_submission_ms().store(async_replay_compile() ? 24 : -1); // as create_vulkan_device auto* device = new Device(info); device->own(owned); // destroyed with the device from here on, even on failure if (!device->ok()) { diff --git a/runtime/src/pipeline_wait.h b/runtime/src/pipeline_wait.h index b8ee526ca7..b9e7ba936a 100644 --- a/runtime/src/pipeline_wait.h +++ b/runtime/src/pipeline_wait.h @@ -1,131 +1,21 @@ #pragma once -// How long a submission waits for pipelines that are still being built (docs/d3d12_vulkan.md, "Pipelines still being -// built"). Before VulkanQueue::execute takes any lock of ours it asks for the pipelines its lists' draws and dispatches -// need (ComputePipeline::await, GraphicsPipeline::await) and waits for the ones being built, at most: -// LEONIDA_PIPELINE_WAIT_MS per submission, in all. 0: never waits; -1: waits for every build to finish (the -// behaviour before this existed, without a lock held). Unset: 24 ms with -// LEONIDA_ASYNC_PIPELINES=1, -1 without (nothing is skipped in the default mode). -// LEONIDA_PIPELINE_WAIT_FRAME_MS per frame (between two presents, or one second without a present), shared by every -// submitting thread (default 100). -1: no frame budget. -// A draw or dispatch whose pipeline is still not built when the wait ends is skipped by replay (recorded as nothing); -// the build goes on, and a later submission uses the pipeline. LEONIDA_STRICT_REPLAY=1 waits for every build. The -// budget bounds waits for builds other threads run: without asynchronous builds, a pipeline nobody has started is -// built by the submitting thread in place, however long that takes (with no lock of the replay layer held). -// Every 10 s while anything happened, one line counts the pipelines waited for, the time, the draws and dispatches -// skipped and the pipelines replay asked for that are still being built. -// No windows.h here: vulkan_replay.h includes this, and translation units without NOMINMAX include that. -#include +// When the title last submitted, for the compute warm-ups (runtime/shims/d3d12_vulkan_device.cpp, +// LEONIDA_COMPUTE_WARMUP_LIVE_MAX_BYTES): while the title submits, a warm-up of a big module is left to the pipeline's +// first use, since a create holds the compile gate for its whole length and every submission waits behind it. +// No windows.h here: vulkan_backend.h includes this, and translation units without NOMINMAX include that. #include #include #include -#include -#include -#include -#include namespace leonida::pipeline_wait { -// Times are steady-clock nanoseconds (submit_phases::now_ns). ComputePipeline::await / GraphicsPipeline::await read -// `until` as: `probe` - the handle if built, never starting anything; a time already past (`no_wait`) - start the build -// when nobody has, without waiting for one another thread runs; a later time - and wait for it until then; `forever`. -// Their `pending` answer says whether a null handle means "not built yet" (false: built, or it cannot be built). -inline constexpr std::int64_t probe = 0; -inline constexpr std::int64_t no_wait = 1; -inline constexpr std::int64_t forever = (std::numeric_limits::max)(); - -// The clock of submit_phases::now_ns. +// Steady-clock nanoseconds (the clock of submit_phases::now_ns). inline std::int64_t now_ns() { return std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()) .count(); } -inline int env_ms(const char* name, int fallback) { - const char* text = std::getenv(name); - if (!text || !*text) return fallback; - char* end = nullptr; - const long value = std::strtol(text, &end, 10); - if (end == text) return fallback; - return value < 0 ? -1 : int((std::min)(value, 600000)); -} - -// Milliseconds; -1 for no limit. Atomics so a test can change them (set_budgets). -inline constexpr int unset = -2; -inline std::atomic& submission_ms() { - static std::atomic value{env_ms("LEONIDA_PIPELINE_WAIT_MS", unset)}; - return value; -} -// What an unset LEONIDA_PIPELINE_WAIT_MS means; the D3D12 device sets it (24 with asynchronous builds, else -1). -inline std::atomic& default_submission_ms() { - static std::atomic value{24}; - return value; -} -inline int effective_submission_ms() { - const int value = submission_ms().load(std::memory_order_relaxed); - return value == unset ? default_submission_ms().load(std::memory_order_relaxed) : value; -} -inline std::atomic& frame_ms() { - static std::atomic value{env_ms("LEONIDA_PIPELINE_WAIT_FRAME_MS", 100)}; - return value; -} -inline void set_budgets(int submission, int frame) { - submission_ms().store(submission); - frame_ms().store(frame); -} - -// Presents, counted by the swap chain: a frame's budget starts again at each one. -inline std::atomic& presents() { - static std::atomic value{0}; - return value; -} -inline void note_present() { presents().fetch_add(1, std::memory_order_relaxed); } - -// What a waiting thread took of its frame's budget (take), and gives back unused (give_back). -struct Grant { - std::int64_t ns = 0; - std::uint64_t frame = 0; - bool limited = false; // false: the frame budget is off and nothing was taken from it -}; - -struct FrameBudget { - std::mutex mutex; - std::uint64_t frame = ~0ull; // the present count the budget belongs to - std::int64_t started = 0; // when it began: one second without a present starts a new one - std::int64_t spent = 0; -}; -inline FrameBudget& frame_budget() { - static FrameBudget value; - return value; -} - -// Up to `want` ns of the current frame's budget, which the caller may wait; the rest of the frame's budget stays for -// the other submitting threads. -inline Grant take(std::int64_t want) { - const int budget = frame_ms().load(std::memory_order_relaxed); - if (budget < 0) return {want, 0, false}; - FrameBudget& f = frame_budget(); - std::lock_guard lock(f.mutex); - const std::uint64_t frame = presents().load(std::memory_order_relaxed); - const std::int64_t now = now_ns(); - if (frame != f.frame || now - f.started >= 1000000000) { - f.frame = frame; - f.started = now; - f.spent = 0; - } - const std::int64_t left = (std::max)(0, std::int64_t(budget) * 1000000 - f.spent); - const std::int64_t granted = (std::min)(want, left); - f.spent += granted; - return {granted, f.frame, true}; -} -inline void give_back(const Grant& grant, std::int64_t unused) { - if (!grant.limited || unused <= 0) return; - FrameBudget& f = frame_budget(); - std::lock_guard lock(f.mutex); - if (f.frame == grant.frame) f.spent = (std::max)(0, f.spent - (std::min)(unused, grant.ns)); -} - -// The last submission (VulkanQueue::execute). While the title submits, compute warm-ups of big modules are left to -// their first use (LEONIDA_COMPUTE_WARMUP_LIVE_MAX_BYTES, runtime/shims/d3d12_vulkan_device.cpp): a create holds the -// compile gate for its whole length, and every submission waits behind it. +// The last submission (VulkanQueue::execute). inline std::atomic& last_submission() { static std::atomic value{0}; return value; @@ -136,54 +26,10 @@ inline bool title_submitting(std::int64_t within_ns = 1000000000) { return last && now_ns() - last < within_ns; } -struct Stats { - std::atomic waited{0}; // pipelines a submission waited for - std::atomic wait_ns{0}; // the time it waited for them - std::atomic late{0}; // waits that ended before the pipeline was built - std::atomic skipped_draws{0}; - std::atomic skipped_dispatches{0}; - std::atomic building{0}; // pipelines replay asked for that are still being built - std::atomic warmups_left{0}; // big warm-ups left to their first use while the title submits - std::atomic last_report{0}; -}; -inline Stats& stats() { - static Stats value; +// Big warm-ups left to their first use while the title submits. +inline std::atomic& warmups_left() { + static std::atomic value{0}; return value; } -inline void count_skip(bool dispatch) { - (dispatch ? stats().skipped_dispatches : stats().skipped_draws).fetch_add(1, std::memory_order_relaxed); -} - -// The 10 s line. One thread wins it; counted since the last line. `age` gives the process's age in seconds -// (submit_phases::process_age), read only when the line is printed. -template void maybe_report(Age&& age) { - constexpr std::int64_t period = 10000000000; - Stats& s = stats(); - const std::int64_t now = now_ns(); - std::int64_t last = s.last_report.load(std::memory_order_relaxed); - if (!last) { - s.last_report.compare_exchange_strong(last, now, std::memory_order_relaxed); - return; - } - if (now - last < period || !s.last_report.compare_exchange_strong(last, now, std::memory_order_relaxed)) return; - const std::uint64_t waited = s.waited.exchange(0, std::memory_order_relaxed); - const std::uint64_t wait_ns = s.wait_ns.exchange(0, std::memory_order_relaxed); - const std::uint64_t late = s.late.exchange(0, std::memory_order_relaxed); - const std::uint64_t draws = s.skipped_draws.exchange(0, std::memory_order_relaxed); - const std::uint64_t dispatches = s.skipped_dispatches.exchange(0, std::memory_order_relaxed); - const std::int64_t building = s.building.load(std::memory_order_relaxed); - const std::uint64_t left = s.warmups_left.exchange(0, std::memory_order_relaxed); - if (!waited && !draws && !dispatches && building <= 0 && !left) return; - std::fprintf(stderr, - "[rt] pipeline waits t=%.0fs: in %.1f s %llu pipelines waited for (%.0f ms in all, %llu not built in " - "time), %llu draws and %llu dispatches skipped, %lld pipelines still building; budget %d ms per " - "submission, %d ms per frame; %llu big warm-ups left to first use\n", - double(age()), double(now - last) * 1e-9, static_cast(waited), - double(wait_ns) * 1e-6, static_cast(late), static_cast(draws), - static_cast(dispatches), static_cast(building), - effective_submission_ms(), frame_ms().load(std::memory_order_relaxed), - static_cast(left)); -} - } // namespace leonida::pipeline_wait diff --git a/runtime/src/submit_phases.h b/runtime/src/submit_phases.h index 54171f60e7..8c697979a4 100644 --- a/runtime/src/submit_phases.h +++ b/runtime/src/submit_phases.h @@ -24,7 +24,7 @@ enum Phase : unsigned { shadows, // slot-133 shadow buffers and title windows (ShadowPages::refresh) geometry, // GeometryViews::refresh textures, // Device::refresh_title_textures - pipelines, // VulkanQueue::await_pipelines: asking for and waiting on pipelines still being built (pipeline_wait.h) + pipelines, // no longer timed (the pre-pass that waited for pipelines is gone); kept for the column order replay, // the rest of execute_now: preparing, recording and submitting the lists kCount }; diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index fb7bc24731..dd5a44ef7a 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -30,6 +30,7 @@ #include "resource_tiling.h" #include "pipeline_profile.h" #include "submit_phases.h" +#include "pipeline_wait.h" #include "title_va_alias.h" #include "xdxr_build.h" @@ -2715,27 +2716,6 @@ class VulkanQueue : private QueueHolds::Holder { return bind_tiles(dst, target->second, changes); } - // The pipelines the lists' draws and dispatches need that are not built yet are asked for (queued on the compile - // worker, or built here when builds are not asynchronous) and waited for at most the budget (pipeline_wait.h), - // holding none of our locks: a build that takes seconds no longer holds resource_mutex_ (shared) across its wait, - // where a title thread creating a resource queued behind it for the exclusive lock and every submission behind - // that. What is still being built after the wait is skipped by prepare and used by a later submission. - void await_pipelines(std::span lists) { - const submit_phases::Scope timed(submit_phases::pipelines); - pipeline_wait::note_submission(); - // The queue's scratch, kept for its capacity. Its own lock is a leaf: what runs under it takes resource_mutex_ - // (shared, for the lookups), a PSO's build state lock and the compile worker's queue lock, none of which is - // held by anything that takes this one. - std::lock_guard scratch(awaits_mutex_); - { - std::shared_lock lock(context_.resource_mutex_); // the registry lookups; no build or wait under it - collect_pipeline_awaits(lists, context_.replay_, awaits_, await_seen_); - } - if (!awaits_.empty()) leonida::await_pipelines(awaits_, pipeline_wait_budget_ns()); - awaits_.clear(); // the captured callbacks go before the lists' pipeline states may - pipeline_wait::maybe_report([] { return submit_phases::process_age(); }); - } - // 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 @@ -2748,7 +2728,7 @@ class VulkanQueue : private QueueHolds::Holder { using PinFn = std::function()>; ReplayResult execute(std::span lists, const PinFn& pin = {}) { - await_pipelines(lists); // before any lock of ours: prepare then never waits for a pipeline build + pipeline_wait::note_submission(); // big compute warm-ups are left to their first use while the title submits auto* diagnostics = context_.device_fault(); const auto execute_call = diagnostics ? diagnostics->next_execute_call() : 0; if (async_on()) { // copied and queued: the worker replays it (a failure is reported as a held one's) @@ -2909,9 +2889,6 @@ class VulkanQueue : private QueueHolds::Holder { std::vector khr_stage_pool_; std::vector khr_as_query_pool_; std::vector xdxr_ranges_; // stage_xdxr_table's snapshot, kept for its capacity - std::mutex awaits_mutex_; // await_pipelines' scratch (not thread_local, see there) - std::vector awaits_; - std::unordered_set await_seen_; void destroy_khr_stages(std::vector& stages) { for (const auto& stage : stages) { diff --git a/runtime/src/vulkan_present.h b/runtime/src/vulkan_present.h index 013c9467b0..81f3b57e1d 100644 --- a/runtime/src/vulkan_present.h +++ b/runtime/src/vulkan_present.h @@ -674,7 +674,6 @@ class VulkanPresenter { } if (submitted != VK_SUCCESS) return give_back(frame, submitted); ++frame_index_; - pipeline_wait::note_present(); // a new frame's budget for waits on pipelines still being built // 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. if (result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR) { diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 96d7f5ee38..fc8d27d3cd 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -48,7 +48,6 @@ #include "vulkan_indirect_dispatch_count.h" #include "vulkan_indirect_clamp.h" #include "xdxr_build.h" -#include "pipeline_wait.h" #include #include @@ -874,11 +873,6 @@ struct ComputePipeline { // first use is always built where prepare() meets it. Not used with async_build. See PipelineCompiles. VkPipeline (*built)(void*) = nullptr; bool large = false; // PipelineCompiles limits how many of these compile at once - // With `build`: the submission's pre-pass (await_pipelines) asks for the pipeline and waits for it with no lock of - // the replay layer held, up to `until_ns` (pipeline_wait.h: probe, no_wait, a steady-clock time, forever). The - // handle, or null with `*pending` saying whether it is still to be built (false: it cannot be). Null: the pre-pass - // leaves the pipeline to `build`. - VkPipeline (*await)(void* context, std::int64_t until_ns, bool* pending) = nullptr; bool skipped = false; // never built on request (LEONIDA_SKIP_COMPUTE): its dispatches are dropped std::uint64_t estimate = 0; // large: the bytes of memory its compile is expected to take }; @@ -912,27 +906,12 @@ struct GraphicsPipeline { // ComputePipeline::built. std::function built; bool large = false; // as ComputePipeline::large - // As ComputePipeline::await, for the variant with the `unbound` slots (unbound_slots). Null: left to `variant`. - std::function await; std::uint32_t samples = 1; // rasterizationSamples; every bound attachment must have this count 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 }; -// The slots a draw leaves unbound that `pipeline` has a format for: the variant prepare_draw builds the draw with -// (GraphicsPipeline::variant). A render target or depth buffer that does not resolve drops the draw instead. -inline std::uint32_t unbound_slots(const Draw& draw, const GraphicsPipeline& pipeline) { - std::uint32_t unbound = 0; - const std::uint32_t bound = draw.views ? draw.views->render_target_count : 0; - for (std::size_t slot = 0; slot < pipeline.color_formats.size() && slot < 8; ++slot) - if (pipeline.color_formats[slot] != VK_FORMAT_UNDEFINED && - !(slot < bound && draw.views->render_targets[slot].resource)) - unbound |= 1u << slot; - if (pipeline.depth_format != VK_FORMAT_UNDEFINED && !draw.depth.resource) unbound |= GraphicsPipeline::unbound_depth; - return unbound; -} - // The 144-byte push-constant block every translated shader declares: s0..s31, heap base, code base. struct ShaderUserData { std::uint32_t s[32]; @@ -2815,7 +2794,6 @@ ReplayResult prepare_draw(const Draw& draw, const IndirectDrawArgs* arguments, R // Slots the pipeline has a format for but the draw leaves unbound take a variant whose format there is // VK_FORMAT_UNDEFINED: D3D12 discards those writes, Vulkan wants the formats to match the attachments. - // The same mask as unbound_slots, which the submission's pre-pass asked for (await_pipelines). std::uint32_t unbound = 0; if (pipeline->rectangle_variant_topology && draw.topology == pipeline->rectangle_variant_topology) unbound |= GraphicsPipeline::rectangle_stage; @@ -3390,114 +3368,6 @@ inline bool zero_clear_unavailable(const PreparedList& prepared, const ReplayFun return false; } -// A pipeline a submission needs that may still be in the making (ComputePipeline::await / GraphicsPipeline::await), -// once per pipeline and variant: collected by collect_pipeline_awaits with the caller's resource lock held (the -// lookups read the registry), waited for by await_pipelines after it is released. The pipeline states stay alive -// meanwhile: the command lists that name them hold them (D3D12 lets them go only once the call has returned). -struct PipelineAwait { - std::uintptr_t id = 0; - std::uint32_t unbound = 0; - VkPipeline (*compute)(void*, std::int64_t, bool*) = nullptr; - void* context = nullptr; - std::function graphics; - VkPipeline handle = VK_NULL_HANDLE; - bool pending = true; // not built yet (false once built, or known not to build) - void call(std::int64_t until) { - handle = compute ? compute(context, until, &pending) : graphics(unbound, until, &pending); - if (handle) pending = false; - } -}; - -// The pipelines `lists` draw and dispatch with that are not built yet: every one whose handle replay asks for at -// prepare time (ComputePipeline::build, GraphicsPipeline::variant), probed without starting anything. `seen` is the -// caller's scratch (not a thread_local: one with a destructor in gta6rt.exe adds TLS callbacks to the image, which -// the loader's TLS index-0 move must not have, pe_loader.cpp reserve_tls_index0). -inline void collect_pipeline_awaits(std::span lists, const ReplayFunctions& vk, - std::vector& out, std::unordered_set& seen) { - out.clear(); - seen.clear(); - if (!vk.compute_pipeline && !vk.graphics_pipeline) return; - std::uint64_t last = ~0ull; - const auto first_time = [&](std::uintptr_t id, std::uint32_t unbound) { - const std::uint64_t key = std::uint64_t(id) ^ (std::uint64_t(unbound) << 52); - if (key == last) return false; - last = key; - return seen.insert(key).second; - }; - const auto compute = [&](std::uintptr_t id) { - if (!id || !vk.compute_pipeline || !first_time(id, 0)) return; - const ComputePipeline* pipeline = vk.compute_pipeline(id); - if (!pipeline || pipeline->pipeline || pipeline->skipped || !pipeline->await) return; - bool pending = false; - if (pipeline->await(pipeline->build_context, pipeline_wait::probe, &pending) || !pending) return; - PipelineAwait& a = out.emplace_back(); - a.id = id; - a.compute = pipeline->await; - a.context = pipeline->build_context; - }; - for (const CommandList* list : lists) { - for (const auto& command : list->commands()) { - if (const auto* dispatch = std::get_if(&command)) { - compute(dispatch->pipeline); - } else if (const auto* ind = std::get_if(&command)) { - if (ind->kind == IndirectKind::dispatch) compute(ind->pipeline); - } else if (const auto* draw = draw_command(command).state) { // direct and stateful indirect draws - if (!draw->pipeline || !vk.graphics_pipeline) continue; - const GraphicsPipeline* pipeline = vk.graphics_pipeline(draw->pipeline); - if (!pipeline || !pipeline->await) continue; - const std::uint32_t unbound = unbound_slots(*draw, *pipeline); - if ((!unbound && pipeline->pipeline) || !first_time(draw->pipeline, unbound)) continue; - bool pending = false; - if (pipeline->await(unbound, pipeline_wait::probe, &pending) || !pending) continue; - PipelineAwait& a = out.emplace_back(); - a.id = draw->pipeline; - a.unbound = unbound; - a.graphics = pipeline->await; - } - } - } -} - -// Asks for every pipeline in `awaits` (a build each nobody has started: queued on the compile worker, or built here -// when builds are not asynchronous), then waits for the ones still being built, together at most `budget_ns` -// (negative: as long as they take) and what the frame's budget has left (pipeline_wait::take). Holds no lock while it -// waits. The ones not built by then are skipped by replay. Returns how long it waited. -inline std::int64_t await_pipelines(std::vector& awaits, std::int64_t budget_ns) { - for (PipelineAwait& a : awaits) a.call(pipeline_wait::no_wait); - std::size_t pending = 0; - for (const PipelineAwait& a : awaits) pending += a.pending; - if (!pending || budget_ns == 0) return 0; - const pipeline_wait::Grant grant = - budget_ns < 0 ? pipeline_wait::Grant{pipeline_wait::forever, 0, false} : pipeline_wait::take(budget_ns); - if (grant.ns <= 0) return 0; - const std::int64_t start = pipeline_wait::now_ns(); - const std::int64_t until = budget_ns < 0 ? pipeline_wait::forever : start + grant.ns; - auto& stats = pipeline_wait::stats(); - for (PipelineAwait& a : awaits) { - if (!a.pending) continue; - if (until != pipeline_wait::forever && pipeline_wait::now_ns() >= until) { - stats.late.fetch_add(1, std::memory_order_relaxed); // no time left for it - continue; - } - const std::int64_t began = pipeline_wait::now_ns(); - a.call(until); - stats.waited.fetch_add(1, std::memory_order_relaxed); - stats.wait_ns.fetch_add(std::uint64_t(pipeline_wait::now_ns() - began), std::memory_order_relaxed); - if (a.pending) stats.late.fetch_add(1, std::memory_order_relaxed); - } - const std::int64_t waited = pipeline_wait::now_ns() - start; - if (grant.limited) pipeline_wait::give_back(grant, grant.ns - waited); - return waited; -} - -// The budget for one submission (pipeline_wait.h): nanoseconds, negative for no limit. Strict replay waits for every -// build, so nothing is skipped. -inline std::int64_t pipeline_wait_budget_ns() { - if (strict_replay()) return -1; - const int ms = pipeline_wait::effective_submission_ms(); - return ms < 0 ? -1 : std::int64_t(ms) * 1000000; -} - // Resolves and checks every command. Nothing is written to a command buffer. // Resolve maps a ResourceId to a const ResourceBinding* (nullptr: unknown). // statistics_helpers promises a statistics segment pool at QueryReplay::plan(). Keep the default for replay() diff --git a/runtime/test/d3d12_pipeline_wait_test.cpp b/runtime/test/d3d12_pipeline_wait_test.cpp deleted file mode 100644 index 14c9f1a4ce..0000000000 --- a/runtime/test/d3d12_pipeline_wait_test.cpp +++ /dev/null @@ -1,593 +0,0 @@ -// Bounded waits for pipelines still being built (src/pipeline_wait.h, docs/d3d12_vulkan.md "Pipelines still being -// built"). A build hook (set_pipeline_build_hook) holds one compute PSO's build in flight - claimed by the thread that -// builds it, before the driver call - so "still being built" is a state the test holds, not a race. Run as -// async LEONIDA_ASYNC_PIPELINES=1: the build is a compile-worker job, queued when SetPipelineState is recorded; -// sync asynchronous builds off: the build is the PSO's warm-up on the compile worker. -// Each case's list copies a sentinel into the output buffer, dispatches, and copies the output to a readback buffer: -// a skipped dispatch leaves the sentinel, so the rest of the list (barriers and copies) is seen to have run. -// skip budget 50 ms: ExecuteCommandLists returns within the budget, the dispatch is skipped and counted. -// later the build let go: the next submission runs the dispatch with the pipeline. -// in time budget 2 s, the build let go 200 ms into the wait: the submission waited, and the dispatch ran. -// no lock budget -1 (wait for the build): while a submission waits, another thread creates and maps a buffer at -// once (the wait holds no lock a resource creation needs); let go, the dispatch runs. -// zero budget 0: no wait, skipped at once. -// exit (async) budget -1 with the PSO's job still queued when the compiler stops for exit: the waiting -// submission builds the pipeline in place and runs instead of waiting for ever. -// No game data: the shader is test/glsl/cs_user_data.comp, the programs are made-up FSSM bytes. -#include "shader_fixture_path.h" -#include "test_temp_dir.h" -#include "vk_test_device.h" -#include "../shims/d3d12_com.h" -#include "../shims/d3d12_compile_exit.h" -#include "../shims/d3d12_pipeline_compile.h" -#include "../shims/d3d12_xs_device.h" -#include "../src/pipeline_wait.h" -#include "../src/shader_library.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifndef LEONIDA_TEST_CS_SPV -#error "LEONIDA_TEST_CS_SPV must name the compiled test shader" -#endif - -#define EXPECT(condition) do { \ - if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ -} while (0) - -namespace { - -using XboxComputePipelineFn = HRESULT(WINAPI*)(void* device, const D3D12_COMPUTE_PIPELINE_STATE_DESC*, std::uint64_t, - std::uint64_t, const IID*, void**); -using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slots 9/10: handle in RAX -using SerializeFn = HRESULT(WINAPI*)(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC*, ID3DBlob**, ID3DBlob**); -using Clock = std::chrono::steady_clock; - -constexpr unsigned kPrograms = 5; -constexpr std::uint32_t kSentinel = 0x5e5e5e5eu; - -void* slot(void* object, unsigned index) { return (*reinterpret_cast(object))[index]; } - -void put32(std::vector& out, std::uint32_t v) { - for (int i = 0; i < 4; ++i) out.push_back(std::uint8_t(v >> (8 * i))); -} - -std::vector zlib_stored(const std::vector& data) { - std::vector out = {0x78, 0x01, 0x01}; - const auto length = std::uint16_t(data.size()); - out.insert(out.end(), {std::uint8_t(length), std::uint8_t(length >> 8), std::uint8_t(~length), - std::uint8_t(~length >> 8)}); - out.insert(out.end(), data.begin(), data.end()); - std::uint32_t a = 1, b = 0; - for (const std::uint8_t x : data) { - a = (a + x) % 65521; - b = (b + a) % 65521; - } - const std::uint32_t adler = (b << 16) | a; - out.insert(out.end(), {std::uint8_t(adler >> 24), std::uint8_t(adler >> 16), std::uint8_t(adler >> 8), - std::uint8_t(adler)}); - return out; -} - -// DXBC { DXIL { stub, XDAT { 0x0D: XBCH + zlib(fssm) } } }, as in d3d12_compute_test. -std::vector shader_container(const std::vector& fssm) { - const auto stream = zlib_stored(fssm); - std::vector xbch = {'X', 'B', 'C', 'H'}; - for (const std::uint32_t v : {1u, std::uint32_t(stream.size()), 0u, std::uint32_t(fssm.size()), 0u}) put32(xbch, v); - xbch.insert(xbch.end(), stream.begin(), stream.end()); - std::vector dxil(16, 0); - dxil.insert(dxil.end(), {'X', 'D', 'A', 'T'}); - put32(dxil, 1); - put32(dxil, 12); - put32(dxil, 0x0d); - put32(dxil, 16 + 12 + 12); - put32(dxil, std::uint32_t(xbch.size())); - dxil.insert(dxil.end(), xbch.begin(), xbch.end()); - std::vector out = {'D', 'X', 'B', 'C'}; - out.resize(28, 0); - put32(out, 1); - put32(out, 36); - out.insert(out.end(), {'D', 'X', 'I', 'L'}); - put32(out, std::uint32_t(dxil.size())); - out.insert(out.end(), dxil.begin(), dxil.end()); - return out; -} - -// Program i: a made-up FSSM blob whose code word (dword 1, which the shader reads through its code base) differs. -std::uint32_t code_word(unsigned i) { return 9100 + i; } -std::vector program(unsigned i) { - std::vector fssm = {'F', 'S', 'S', 'M'}; - put32(fssm, code_word(i)); - for (std::uint32_t w = 0; w < 14; ++w) put32(fssm, 0xbf810000u + w); - return fssm; -} - -std::vector serialize(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC& desc) { - const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); - const auto fn = d3d12 ? reinterpret_cast( - reinterpret_cast(GetProcAddress(d3d12, "D3D12SerializeVersionedRootSignature"))) - : nullptr; - std::vector out; - ID3DBlob* blob = nullptr; - if (fn && SUCCEEDED(fn(&desc, &blob, nullptr)) && blob) { - const auto* p = static_cast(blob->GetBufferPointer()); - out.assign(p, p + blob->GetBufferSize()); - blob->Release(); - } - return out; -} - -D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes, D3D12_RESOURCE_FLAGS flags) { - D3D12_RESOURCE_DESC desc{}; - desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; - desc.Width = bytes; - desc.Height = 1; - desc.DepthOrArraySize = 1; - desc.MipLevels = 1; - desc.SampleDesc.Count = 1; - desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; - desc.Flags = flags; - return desc; -} - -struct Event { - HANDLE handle = CreateEventW(nullptr, TRUE, FALSE, nullptr); - Event() = default; - Event(const Event&) = delete; - Event& operator=(const Event&) = delete; - ~Event() { CloseHandle(handle); } - void set() const { SetEvent(handle); } - void reset() const { ResetEvent(handle); } - bool wait(DWORD ms = 30000) const { return WaitForSingleObject(handle, ms) == WAIT_OBJECT_0; } - bool is_set() const { return WaitForSingleObject(handle, 0) == WAIT_OBJECT_0; } -}; - -using rt::d3d12::PipelineCompiler; - -// Waits until the worker has run everything queued so far: a last-priority marker job. -bool drain(PipelineCompiler& compiler) { - Event done; - static const int marker = 0; - if (!compiler.submit(&marker, nullptr, SIZE_MAX, [&done] { done.set(); })) return false; - return done.wait(120000); -} - -// Holds the worker in a job of no device until open() (or the end of the scope). -struct Gate { - Event entered, opened, left; - explicit Gate(PipelineCompiler& compiler) { - static const int gate = 0; - compiler.submit(&gate, nullptr, 0, [this] { - entered.set(); - opened.wait(INFINITE); - left.set(); - }); - entered.wait(); - } - void open() { opened.set(); } - ~Gate() { - opened.set(); - left.wait(); - } -}; - -// Holds the build of `target` (once claimed, before the driver call) until let_go(). -struct Hold { - std::atomic target{nullptr}; - Event entered, proceed; - Hold() { - rt::d3d12::set_pipeline_build_hook([this](ID3D12PipelineState* pso) { - if (pso != target.load()) return; - entered.set(); - proceed.wait(INFINITE); - }); - } - void let_go() { proceed.set(); } - ~Hold() { - proceed.set(); - rt::d3d12::set_pipeline_build_hook(nullptr); - } -}; - -struct Outcome { - std::vector words; - long long execute_ms = 0; - leonida::ReplayResult result = leonida::ReplayResult::unsupported; -}; - -std::uint32_t expected(unsigned program_index, std::uint32_t i) { - static constexpr std::uint32_t table_values[4] = {1000, 2000, 3000, 4000}; - return 7 + 3 * i + table_values[i % 4] + code_word(program_index); -} - -struct Session { - ID3D12Device* device = nullptr; - ID3D12RootSignature* root = nullptr; - std::vector psos; - - int open(vktest::Device& d, const std::filesystem::path& library) { - rt::d3d12::VulkanDeviceInfo info{}; - info.get_instance_proc = d.instance_proc; - info.instance = d.instance; - info.physical = d.physical; - info.device = d.device; - info.queue = d.queue; - info.queue_family = d.family; - info.buffer_device_address = true; - info.subgroup = d.subgroup; - info.shader_dir = library.string(); - ID3D12Device* inner = nullptr; - EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); - const HRESULT proxied = rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device), false); - if (FAILED(proxied)) inner->Release(); - EXPECT(SUCCEEDED(proxied)); - rt::d3d12::set_device_outer(inner, device); - - D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, 1, 0, 0}; - D3D12_ROOT_PARAMETER params[3] = {}; - params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; - params[0].Constants = {0, 0, 2}; - params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; - params[1].Descriptor = {0, 0}; - params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; - params[2].DescriptorTable = {1, &range}; - D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; - root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; - root_desc.Desc_1_0 = {3, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; - const auto blob = serialize(root_desc); - EXPECT(!blob.empty()); - EXPECT(SUCCEEDED(device->CreateRootSignature(0, blob.data(), blob.size(), IID_PPV_ARGS(&root)))); - return 0; - } - - int add(unsigned program_index, ID3D12PipelineState*& pso) { - const auto container = shader_container(program(program_index)); - D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; - desc.pRootSignature = root; - desc.CS = {container.data(), container.size()}; - const IID iid = __uuidof(ID3D12PipelineState); - pso = nullptr; - EXPECT(SUCCEEDED(reinterpret_cast(slot(device, 62))( - device, &desc, 0, 0, &iid, reinterpret_cast(&pso)))); - psos.push_back(pso); - return 0; - } - - // A list: sentinel copy into the output, the dispatch, the output copied to readback. `before_execute` runs just - // before ExecuteCommandLists (after the list is recorded); only that call is timed. - int dispatch(ID3D12PipelineState* pso, Outcome& outcome, const std::function& before_execute = {}) { - constexpr UINT elements = 64, bytes = elements * 4; - static constexpr std::uint32_t table_values[4] = {1000, 2000, 3000, 4000}; - 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}; - const auto uav = buffer_desc(bytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); - const auto upload_desc = buffer_desc(512, D3D12_RESOURCE_FLAG_NONE); - const auto readback_desc = buffer_desc(bytes, D3D12_RESOURCE_FLAG_NONE); - ID3D12Resource *out = nullptr, *upload = nullptr, *readback = nullptr; - ID3D12DescriptorHeap* heap = nullptr; - ID3D12CommandQueue* queue = nullptr; - ID3D12CommandAllocator* allocator = nullptr; - ID3D12GraphicsCommandList* list = nullptr; - ID3D12Fence* fence = nullptr; - struct Releaser { - std::vector all; - ~Releaser() { - for (IUnknown** p : all) - if (*p) (*p)->Release(); - } - } releaser{{reinterpret_cast(&out), reinterpret_cast(&upload), - reinterpret_cast(&readback), reinterpret_cast(&heap), - reinterpret_cast(&queue), reinterpret_cast(&allocator), - reinterpret_cast(&list), reinterpret_cast(&fence)}}; - EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &uav, - D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&out)))); - EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &upload_desc, - D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, - IID_PPV_ARGS(&upload)))); - EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, - D3D12_RESOURCE_STATE_COPY_DEST, nullptr, - IID_PPV_ARGS(&readback)))); - // Bytes 0..15: the CBV's table values; 256..511: the sentinel the output starts as. - void* mapped = nullptr; - EXPECT(SUCCEEDED(upload->Map(0, nullptr, &mapped))); - std::memcpy(mapped, table_values, sizeof(table_values)); - for (UINT i = 0; i < elements; ++i) std::memcpy(static_cast(mapped) + 256 + 4 * i, &kSentinel, 4); - const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 8, - D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; - EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap)))); - const std::uint64_t cpu = reinterpret_cast(slot(heap, 9))(heap); - const std::uint64_t gpu = reinterpret_cast(slot(heap, 10))(heap); - EXPECT(cpu && gpu >= 0x10000 && gpu < (1ull << 32)); - const std::uint64_t target = upload->GetGPUVirtualAddress(); - std::memcpy(reinterpret_cast(cpu), &target, sizeof(target)); - - D3D12_COMMAND_QUEUE_DESC queue_desc{}; - EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue)))); - EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)))); - EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator, pso, - IID_PPV_ARGS(&list)))); - EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)))); - list->CopyBufferRegion(out, 0, upload, 256, bytes); - D3D12_RESOURCE_BARRIER barrier{}; - barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barrier.Transition = {out, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_COPY_DEST, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS}; - list->ResourceBarrier(1, &barrier); - list->SetDescriptorHeaps(1, &heap); - list->SetComputeRootSignature(root); - list->SetComputeRoot32BitConstant(0, 7, 0); - list->SetComputeRoot32BitConstant(0, 3, 1); - list->SetComputeRootUnorderedAccessView(1, out->GetGPUVirtualAddress()); - list->SetComputeRootDescriptorTable(2, D3D12_GPU_DESCRIPTOR_HANDLE{gpu}); - list->Dispatch(1, 1, 1); - barrier.Transition = {out, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, - D3D12_RESOURCE_STATE_COPY_SOURCE}; - list->ResourceBarrier(1, &barrier); - list->CopyBufferRegion(readback, 0, out, 0, bytes); - EXPECT(list->Close() == S_OK); - if (before_execute) before_execute(); - ID3D12CommandList* lists[] = {list}; - const auto start = Clock::now(); - queue->ExecuteCommandLists(1, lists); - outcome.execute_ms = std::chrono::duration_cast(Clock::now() - start).count(); - outcome.result = rt::d3d12::last_execute_result(queue); - EXPECT(outcome.result == leonida::ReplayResult::success); - EXPECT(SUCCEEDED(queue->Signal(fence, 1))); - EXPECT(SUCCEEDED(fence->SetEventOnCompletion(1, nullptr))); - void* results = nullptr; - EXPECT(SUCCEEDED(readback->Map(0, nullptr, &results))); - outcome.words.assign(elements, 0); - std::memcpy(outcome.words.data(), results, bytes); - return 0; - } - - ~Session() { - if (device) device->Release(); - if (root) root->Release(); - for (ID3D12PipelineState* pso : psos) pso->Release(); - } -}; - -bool ran(const Outcome& o, unsigned program_index) { - for (std::uint32_t i = 0; i < o.words.size(); ++i) - if (o.words[i] != expected(program_index, i)) return false; - return !o.words.empty(); -} -bool skipped(const Outcome& o) { - for (const std::uint32_t w : o.words) - if (w != kSentinel) return false; - return !o.words.empty(); -} - -std::uint64_t skips() { return leonida::pipeline_wait::stats().skipped_dispatches.load(); } - -} // namespace - -int main(int argc, char** argv) { - const bool async = argc > 1 && !std::strcmp(argv[1], "async"); - if (argc < 2 || (!async && std::strcmp(argv[1], "sync"))) { - std::fprintf(stderr, "usage: d3d12_pipeline_wait_test async|sync\n"); - return 2; - } - _putenv_s("LEONIDA_LAZY_COMPUTE", "1"); - _putenv_s("LEONIDA_COMPUTE_WARMUP", async ? "0" : "1"); - _putenv_s("LEONIDA_ASYNC_PIPELINES", async ? "1" : "0"); - _putenv_s("LEONIDA_STRICT_REPLAY", "0"); - const testfiles::ScratchDir scratch(async ? "leonida_pipeline_wait_async" : "leonida_pipeline_wait_sync"); - const auto library = scratch.path() / "spirv"; - std::filesystem::create_directories(library); - _putenv_s("LEONIDA_PIPELINE_CACHE_DIR", (scratch.path() / "cache").string().c_str()); - - vktest::Device d; - const auto device_status = d.initialize(); - if (device_status == vktest::DeviceStatus::unavailable) { - std::fprintf(stderr, "SKIP: no usable Vulkan 1.3 device\n"); - return 77; - } - EXPECT(device_status == vktest::DeviceStatus::ready); - { - std::ofstream index(library / "index.json", std::ios::binary); - index << "{"; - for (unsigned i = 0; i < kPrograms; ++i) { - const std::string name = "cs_wait_" + std::to_string(i); - EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), library / (name + ".spv"))); - index << (i ? ",\n" : "") << "\"" << name << "\": {\"stage\": \"cs\", \"fssm_sha256\": \"" - << leonida::sha256_hex(program(i)) << "\", \"bindings\": [], \"push_constant_bytes\": 144, " - << "\"local_size\": [64, 1, 1], \"uses_code_base\": true, \"wave64\": false}"; - } - index << "}"; - } - - auto& compiler = PipelineCompiler::instance(); - auto& stats = leonida::pipeline_wait::stats(); - Session s; - if (s.open(d, library)) return 1; - const char* mode = async ? "async" : "sync"; - - // A PSO whose build `hold` holds once claimed. Sync: its warm-up, queued behind a gate so the hold knows the PSO - // before the worker reaches it, is held at once. Async: its job is queued when the list records SetPipelineState, - // and held then (the caller waits for hold.entered before executing). - const auto held_pso = [&](unsigned program_index, Hold& hold, ID3D12PipelineState*& pso) -> int { - { - Gate gate(compiler); - if (s.add(program_index, pso)) return 1; - hold.target = pso; - } - if (!async) EXPECT(hold.entered.wait()); - return 0; - }; - const auto entered = [](Hold& hold) { return [&hold] { hold.entered.wait(); }; }; - - // --- skip: budget 50 ms --------------------------------------------------------------------------------------- - ID3D12PipelineState* first = nullptr; - { - Hold hold; - if (held_pso(0, hold, first)) return 1; - leonida::pipeline_wait::set_budgets(50, -1); - const std::uint64_t skips_before = skips(), waited_before = stats.waited.load(); - Outcome o; - if (s.dispatch(first, o, entered(hold))) return 1; - std::printf("%s skip: ExecuteCommandLists returned in %lld ms with the build held; dispatch %s\n", mode, - o.execute_ms, skipped(o) ? "skipped (sentinel kept, the copies ran)" : "NOT skipped"); - EXPECT(skipped(o)); - EXPECT(o.execute_ms < 50 + 450); - EXPECT(skips() == skips_before + 1); - EXPECT(stats.waited.load() == waited_before + 1); - EXPECT(stats.building.load() >= 1); - hold.let_go(); - EXPECT(drain(compiler)); - } - // --- later: the build finished in the background; the next submission uses it --------------------------------- - { - const std::uint64_t skips_before = skips(); - Outcome o; - if (s.dispatch(first, o)) return 1; - std::printf("%s later: ran with the pipeline built in the background (%lld ms)\n", mode, o.execute_ms); - EXPECT(ran(o, 0)); - EXPECT(skips() == skips_before); - } - // --- in time: budget 2 s, the build let go 200 ms into the wait ------------------------------------------------ - { - Hold hold; - ID3D12PipelineState* pso = nullptr; - if (held_pso(1, hold, pso)) return 1; - leonida::pipeline_wait::set_budgets(2000, -1); - const std::uint64_t skips_before = skips(); - Event executing; - Outcome o; - int status = 1; - std::thread title([&] { - status = s.dispatch(pso, o, [&] { - hold.entered.wait(); - executing.set(); - }); - }); - EXPECT(executing.wait()); - Sleep(200); - hold.let_go(); - title.join(); - EXPECT(status == 0); - std::printf("%s in time: waited %lld ms for a build let go 200 ms in; dispatch %s\n", mode, o.execute_ms, - ran(o, 1) ? "ran" : "did NOT run"); - EXPECT(ran(o, 1)); - EXPECT(o.execute_ms >= 150 && o.execute_ms < 2000); - EXPECT(skips() == skips_before); - } - // --- no lock: budget -1; a resource is created and mapped while a submission waits ----------------------------- - { - Hold hold; - ID3D12PipelineState* pso = nullptr; - if (held_pso(2, hold, pso)) return 1; - leonida::pipeline_wait::set_budgets(-1, -1); - Event executing, executed; - Outcome o; - int status = 1; - std::thread title([&] { - status = s.dispatch(pso, o, [&] { - hold.entered.wait(); - executing.set(); - }); - executed.set(); - }); - EXPECT(executing.wait()); - Sleep(200); - const auto start = Clock::now(); - ID3D12Resource* buffer = nullptr; - const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}; - const auto desc = buffer_desc(1 << 20, D3D12_RESOURCE_FLAG_NONE); - const HRESULT created = s.device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &desc, - D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, - IID_PPV_ARGS(&buffer)); - void* mapped = nullptr; - const HRESULT map = SUCCEEDED(created) ? buffer->Map(0, nullptr, &mapped) : E_FAIL; - const auto took = std::chrono::duration_cast(Clock::now() - start).count(); - if (buffer) buffer->Release(); - const bool still_waiting = !executed.is_set(); - hold.let_go(); - title.join(); - EXPECT(status == 0); - std::printf("%s no lock: a buffer was created and mapped in %lld ms while a submission waited (still waiting: " - "%s); the submission then ran the dispatch after %lld ms\n", - mode, static_cast(took), still_waiting ? "yes" : "no", o.execute_ms); - EXPECT(SUCCEEDED(created) && SUCCEEDED(map)); - EXPECT(took < 500); - EXPECT(still_waiting); - EXPECT(ran(o, 2)); - } - // --- zero: budget 0 ------------------------------------------------------------------------------------------- - { - Hold hold; - ID3D12PipelineState* pso = nullptr; - if (held_pso(3, hold, pso)) return 1; - leonida::pipeline_wait::set_budgets(0, -1); - const std::uint64_t skips_before = skips(), waited_before = stats.waited.load(); - Outcome o; - if (s.dispatch(pso, o, entered(hold))) return 1; - std::printf("%s zero: returned in %lld ms, dispatch %s\n", mode, o.execute_ms, - skipped(o) ? "skipped" : "NOT skipped"); - EXPECT(skipped(o)); - EXPECT(o.execute_ms < 200); - EXPECT(skips() == skips_before + 1); - EXPECT(stats.waited.load() == waited_before); - hold.let_go(); - EXPECT(drain(compiler)); - } - // A PSO never held: built (in place when synchronous) and run in its first submission. - { - ID3D12PipelineState* pso = nullptr; - if (s.add(4, pso)) return 1; - leonida::pipeline_wait::set_budgets(2000, -1); - Outcome o; - if (s.dispatch(pso, o)) return 1; - std::printf("%s first use: %s (%lld ms)\n", mode, ran(o, 4) ? "ran" : "did NOT run", o.execute_ms); - EXPECT(ran(o, 4)); - } - // --- exit (async): budget -1, the PSO's job still queued behind a gate when the compiler stops for exit (its queue - // dropped): the waiting submission does not wait for ever, it builds the pipeline in place and runs the dispatch. - if (async) { - leonida::pipeline_wait::set_budgets(-1, -1); - Event executing, executed; - Outcome o; - int status = 1; - { - Gate gate(compiler); // the worker is held, so the job SetPipelineState queues stays queued - ID3D12PipelineState* queued = nullptr; - if (s.add(1, queued)) return 1; // program 1 again: a second PSO, with its own build - std::thread title([&] { - status = s.dispatch(queued, o, [&] { executing.set(); }); - executed.set(); - }); - EXPECT(executing.wait()); - Sleep(200); - const bool waiting = !executed.is_set(); - const bool idle = rt::d3d12::stop_pipeline_compiles(100); // the gate's job is still running: false - const auto stopped = Clock::now(); - const bool finished = executed.wait(5000); - const auto after = std::chrono::duration_cast(Clock::now() - stopped).count(); - gate.open(); - title.join(); - std::printf("async exit: a submission waiting without limit for a queued build (waiting: %s) went on %lld " - "ms after the exit stop (worker idle: %s) and %s\n", - waiting ? "yes" : "no", static_cast(after), idle ? "yes" : "no", - ran(o, 1) ? "ran the dispatch" : "did NOT run the dispatch"); - EXPECT(waiting && !idle && finished); - EXPECT(status == 0); - EXPECT(ran(o, 1)); - } - } - EXPECT(stats.building.load() == 0); - std::printf("%s: all cases passed\n", mode); - return 0; -} From 7b1d71e218ab37a6a0620d7230e9f3965a493e55 Mon Sep 17 00:00:00 2001 From: Jan Trencansky Date: Wed, 25 Nov 2026 18:15:45 -0500 Subject: [PATCH 06/10] Leave the layer's below-arena V#s alone in the table scan #2098's scan_title_table nulls a table V# whose base nothing backs (rebase_title_vsharp's `unbacked`). A V# the layer wrote itself for one of its own buffers that the driver put below the arena holds the low 48 bits of a negative offset, which the shaders read sign-extended (vsharp_address accepts it). On the RDNA2 iGPU, upload buffers live in ReBAR memory below the arena, so the scan took such a V# for an unbacked title address and nulled it before the dispatch read it: d3d12_compute, d3d12_fspx_compute, d3d12_unmapped_vsharp, d3d12_graphics_indirect_heap_resources and d3d12_compile_teardown failed there and passed on lavapipe, where the buffers sit above the arena. rebase_title_vsharp now leaves a base with bit 47 set alone when its sign-extended offset is one of the layer's backings (gpu_backings), as vsharp_address reads it. Co-Authored-By: Claude Opus 5.5 --- runtime/shims/d3d12_vulkan_device.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 5cef2b47f7..3d9cefde8d 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -3280,6 +3280,14 @@ struct DeviceState { if (base < arena.size || (geometry.cap() && geometry.lookup(arena.address + base, host, remaining))) return false; const std::uint32_t stride = (w1 >> 16) & 0x3FFFu; const std::uint64_t span = std::uint64_t(w2) * (stride ? stride : 1); + // A V# the layer wrote for one of its own buffers that the driver put below the arena (an upload buffer in + // ReBAR memory, say): the low 48 bits of a negative offset, which the shaders read sign-extended + // (vsharp_address). Not the title's memory: left as it is, never nulled. + if (base & (1ull << 47)) { + std::lock_guard lock(backing_mutex); + if (gpu_backings.covers(arena.address + (base | ~((1ull << 48) - 1)), std::max(span, 1))) + return false; + } std::uint64_t to{}; if (geometry.cap()) { const leonida::gfx10::BufferWords words{w0, w1, w2, w3}; From fb60a1cf4a98819f33b9f421ca0d27bd15e7d8ac Mon Sep 17 00:00:00 2001 From: Jan Trencansky Date: Wed, 25 Nov 2026 18:20:18 -0500 Subject: [PATCH 07/10] d3d12_big_compute_warmup: run without the live warm-up limit main's warm-up test has the warm-up thread build every compute module after a submission. Its 132 KiB modules are over #2098's LEONIDA_COMPUTE_WARMUP_LIVE_MAX_BYTES (128 KiB by default), which leaves big warm-ups to their first use while the title submits, so four of them were never started and the test's "each once" check failed. The limit is a separate feature from the gate order the test checks; it is set to 0 for this test only. Co-Authored-By: Claude Opus 5.5 --- runtime/CMakeLists.txt | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 715c3e8568..eac63fe367 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2463,8 +2463,12 @@ if(TARGET Vulkan::Headers) PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 600 FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") set_tests_properties(d3d12_big_compute_budget PROPERTIES ENVIRONMENT "LEONIDA_BIG_COMPILE_BUDGET_MB=260") - set_tests_properties(d3d12_big_compute_tight d3d12_big_compute_warmup PROPERTIES - ENVIRONMENT "LEONIDA_BIG_COMPILE_BUDGET_MB=1") + set_tests_properties(d3d12_big_compute_tight PROPERTIES ENVIRONMENT "LEONIDA_BIG_COMPILE_BUDGET_MB=1") + # The warm-up thread builds every module after the submission here. Its 132 KiB modules are over the default + # LEONIDA_COMPUTE_WARMUP_LIVE_MAX_BYTES, which leaves big warm-ups to their first use while the title submits, so + # that limit is off for this test. + set_tests_properties(d3d12_big_compute_warmup PROPERTIES + ENVIRONMENT "LEONIDA_BIG_COMPILE_BUDGET_MB=1;LEONIDA_COMPUTE_WARMUP_LIVE_MAX_BYTES=0") set_tests_properties(d3d12_big_compute_eager PROPERTIES ENVIRONMENT "LEONIDA_BIG_COMPILE_BUDGET_MB=1;LEONIDA_LAZY_COMPUTE=0") set_tests_properties(d3d12_big_compute_serial PROPERTIES # neither of these two has a budget From 1f64d91c3f4a4ab60926cfa4836608055debb108 Mon Sep 17 00:00:00 2001 From: Jan Trencansky Date: Wed, 25 Nov 2026 18:21:39 -0500 Subject: [PATCH 08/10] xg_xs_test: a render target without a mode takes main's general layout model #2098 added a check that XGCreateTextureComputer refuses a render target with no layout mode (E_NOTIMPL). On main the second (general) layout model lays out the render targets xg_xs_layout.h does not, and xg_xs_test already expects S_OK for those ("the other render targets still use the general layout model"). The check now says the same for this one: the explicit-mode model refuses it and the general model makes the computer. Co-Authored-By: Claude Opus 5.5 --- runtime/test/xg_xs_test.cpp | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/runtime/test/xg_xs_test.cpp b/runtime/test/xg_xs_test.cpp index 2535b1a926..c5272e0155 100644 --- a/runtime/test/xg_xs_test.cpp +++ b/runtime/test/xg_xs_test.cpp @@ -779,9 +779,14 @@ int main() { check(slot(computer, 2)(computer, &l) == S_OK && l.size == 256 && l.alignment == 256, "explicit linear render target is one 256-byte row"); slot(computer, 1)(computer); - void* none = nullptr; + // Without a mode, the render target is not this model's (it leaves the mode to XG's Z/R choice): the general layout + // model lays it out, as it does the other render targets above. + void* general = nullptr; d.layout = 0; - check(create(&d, &none) == E_NOTIMPL, "a render target without a mode still needs SW_64KB_R_X, which XG lacks"); + Texture own{}; + check(!build_texture(d, own), "a render target without a mode is not the explicit-mode model's"); + check(create(&d, &general) == S_OK && general, "a render target without a mode uses the general layout model"); + if (general) slot(general, 1)(general); std::printf("%d checks, %d failures\n", g_checks, g_failures); return g_failures ? 1 : 0; } From 75f6890bb98214d5112c7eb1126f67f9e2948a0a Mon Sep 17 00:00:00 2001 From: Jan Trencansky Date: Wed, 25 Nov 2026 18:30:31 -0500 Subject: [PATCH 09/10] Keep the storage view's pNext chain alive for the 2D-array mirror view #2098's 2D mirror of a 2D-array image (BindlessSet::MirrorViews) copies storage_info, pNext chain and all, after the block that made the storage view. That chain (VkImageViewUsageCreateInfo, VkImageViewSlicedCreateInfoEXT) was declared inside the block, so the mirror's vkCreateImageView followed a dangling pointer into stale stack; winevulkan walked it without end. That was the 120 s hang of d3d12_existing_heap (and its two variants), d3d12_r9g9b9e5_uav, d3d12_depth_stencil_uav, xbox_depth_storage and xbox_d16s8_storage on lavapipe and the iGPU alike: each makes a UAV of a 2D-array (or cube) texture. The two structs are declared before the block now. Found with a winedbg backtrace of the hung test (bind_image_views_locked's make_mirror lambda, line 6604), then confirmed by disabling the mirror in a scratch tree: all six tests pass then too. Co-Authored-By: Claude Opus 5.5 --- runtime/shims/d3d12_vulkan_device.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 3d9cefde8d..c1df9365b7 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -6568,14 +6568,17 @@ struct DeviceState { leonida::StorageViews views{}; VkImageViewCreateInfo storage_info{}; bool storage_info_valid = false; + // storage_info's pNext chain: declared out here, since the 2D mirror below copies storage_info with its chain + // after this block. Declared inside it, the chain dangled and the driver followed it into stale stack (the + // 120 s hangs of d3d12_existing_heap, d3d12_r9g9b9e5_uav and the depth-storage tests). + VkImageViewUsageCreateInfo storage_usage{VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO}; + VkImageViewSlicedCreateInfoEXT sliced{VK_STRUCTURE_TYPE_IMAGE_VIEW_SLICED_CREATE_INFO_EXT}; if (storage) { storage_info = view_info; storage_info_valid = true; storage_info.components = {}; storage_info.format = storage_format; - VkImageViewUsageCreateInfo storage_usage{VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO}; storage_usage.usage = VK_IMAGE_USAGE_STORAGE_BIT; - VkImageViewSlicedCreateInfoEXT sliced{VK_STRUCTURE_TYPE_IMAGE_VIEW_SLICED_CREATE_INFO_EXT}; if (slices.count) { sliced.sliceOffset = slices.first; sliced.sliceCount = slices.count; From fc71534883424112a7ea08fefe5b820fc4ee58aa Mon Sep 17 00:00:00 2001 From: Jan Trencansky Date: Wed, 25 Nov 2026 18:37:48 -0500 Subject: [PATCH 10/10] Make the live compute warm-up limit opt-in; main's warm-up stays the default #2098's LEONIDA_COMPUTE_WARMUP_LIVE_MAX_BYTES defaulted to 128 KiB, so while the title submits it skipped exactly the large modules main's warm-up (#1889) exists to build, with LargeModuleGate already ordering them behind a submission's compiles. At the maintainers' decision ("main wins") it is opt-in now: unset or 0 is no limit, as on main; leaves warm-ups of modules over n bytes to their first use while the title submits, as #2098 measured with 131072. This reverts the test-side override of fb60a1cf4: d3d12_big_compute_warmup runs with main's environment again. The switch is documented in runtime/README.md beside the other #2098 switches, and in docs/d3d12_vulkan.md. Co-Authored-By: Claude Opus 5.5 --- docs/d3d12_vulkan.md | 9 +++++---- runtime/CMakeLists.txt | 8 ++------ runtime/README.md | 1 + runtime/shims/d3d12_vulkan_device.cpp | 14 +++++++------- runtime/src/pipeline_wait.h | 4 ++-- 5 files changed, 17 insertions(+), 19 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index ded40b8310..ff8fab023d 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2602,10 +2602,11 @@ submitting thread; at the maintainers' decision it was replaced by this one when - **Warm-ups while the title submits.** A compute warm-up holds the compile gate for its whole create, and every submission waits behind it: a native boot's submissions waited 140 s in all at the gate behind compute warm-ups, and past the story load the worker went through 694 warm-ups of modules over 128 KiB (those over 640 KiB take 4-25 s - each) against 25 such builds a dispatch asked for. So a warm-up of a module over - `LEONIDA_COMPUTE_WARMUP_LIVE_MAX_BYTES` of SPIR-V (default 128 KiB; 0: no limit) is not started while the title - submits (a submission in the last second, `src/pipeline_wait.h`); the pipeline is built at its first use instead. - Smaller warm-ups, and every warm-up before the first submission, run as before. + each) against 25 such builds a dispatch asked for (measured with a 128 KiB limit). With + `LEONIDA_COMPUTE_WARMUP_LIVE_MAX_BYTES=` a warm-up of a module over n bytes of SPIR-V is not started while the + title submits (a submission in the last second, `src/pipeline_wait.h`); the pipeline is built at its first use + instead. Opt-in: unset or 0, every warm-up runs, as on `main`, and `LargeModuleGate` (#1889) orders them behind a + submission's compiles. Smaller warm-ups, and every warm-up before the first submission, run as before. **Open:** whether the game uses `D3D12_PIPELINE_STATE_STREAM_DESC` for mesh/RT and which subobject types appear. The trace will enumerate them. diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 600a7dba0a..f4c1527220 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2490,12 +2490,8 @@ if(TARGET Vulkan::Headers) PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 600 FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") set_tests_properties(d3d12_big_compute_budget PROPERTIES ENVIRONMENT "LEONIDA_BIG_COMPILE_BUDGET_MB=260") - set_tests_properties(d3d12_big_compute_tight PROPERTIES ENVIRONMENT "LEONIDA_BIG_COMPILE_BUDGET_MB=1") - # The warm-up thread builds every module after the submission here. Its 132 KiB modules are over the default - # LEONIDA_COMPUTE_WARMUP_LIVE_MAX_BYTES, which leaves big warm-ups to their first use while the title submits, so - # that limit is off for this test. - set_tests_properties(d3d12_big_compute_warmup PROPERTIES - ENVIRONMENT "LEONIDA_BIG_COMPILE_BUDGET_MB=1;LEONIDA_COMPUTE_WARMUP_LIVE_MAX_BYTES=0") + set_tests_properties(d3d12_big_compute_tight d3d12_big_compute_warmup PROPERTIES + ENVIRONMENT "LEONIDA_BIG_COMPILE_BUDGET_MB=1") set_tests_properties(d3d12_big_compute_eager PROPERTIES ENVIRONMENT "LEONIDA_BIG_COMPILE_BUDGET_MB=1;LEONIDA_LAZY_COMPUTE=0") set_tests_properties(d3d12_big_compute_serial PROPERTIES # neither of these two has a budget diff --git a/runtime/README.md b/runtime/README.md index 6f21a4a88d..ec4c801452 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -409,6 +409,7 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `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` | unset | `1`: a compute pipeline build holds the device's submit lock for its driver calls, so no compute compile runs while a queue submits. Unset: the asynchronous workers compile while other queues submit. | | `LEONIDA_FAST_PIPELINES` | unset | `graphics`, `compute` or `all` (`1` = all) creates those pipelines with `VK_PIPELINE_CREATE_DISABLE_OPTIMIZATION_BIT` (`shims/d3d12_pipeline_compile.h`): slower shaders, much shorter builds. Part of the compute journal key, so optimized and fast builds keep separate files. | | `LEONIDA_GRAPHICS_COMPILE_WORKER` | on | 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. | diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 841a278bd5..e8676b32c7 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -11759,18 +11759,18 @@ class PipelineState final } private: - // A warm-up of a module over LEONIDA_COMPUTE_WARMUP_LIVE_MAX_BYTES of SPIR-V (default 128 KiB, 0: no limit) is not - // started while the title submits (a submission in the last second): it is left to the pipeline's first use. A - // create holds the compile gate (SubmitMutex::CompileTurn) for its whole length and every submission waits behind - // it; on NVIDIA 630.20 the modules over 640 KiB take 4-25 s each. Measured in a native boot past the story load: - // 694 warm-ups of modules over 128 KiB against 25 such builds a dispatch asked for, and one run's submissions - // waited 140 s in all at the gate behind warm-ups. + // LEONIDA_COMPUTE_WARMUP_LIVE_MAX_BYTES= (opt-in; unset or 0: no limit, the warm-up builds every module as on + // main): a warm-up of a module over n bytes of SPIR-V is not started while the title submits (a submission in the + // last second); it is left to the pipeline's first use. A create holds the compile gate (SubmitMutex::CompileTurn) + // for its whole length and every submission waits behind it; on NVIDIA 630.20 the modules over 640 KiB take 4-25 s + // each. Measured in a native boot past the story load (with 131072): 694 warm-ups of modules over 128 KiB against + // 25 such builds a dispatch asked for, and one run's submissions waited 140 s in all at the gate behind warm-ups. static bool warmup_waits_for_quiet(std::size_t bytes) { static const std::size_t limit = [] { char text[32]{}; const DWORD n = GetEnvironmentVariableA("LEONIDA_COMPUTE_WARMUP_LIVE_MAX_BYTES", text, sizeof(text)); return (n > 0 && n < sizeof(text)) ? static_cast(std::strtoull(text, nullptr, 10)) - : std::size_t{128} << 10; + : std::size_t{0}; }(); if (!limit || bytes <= limit || !leonida::pipeline_wait::title_submitting()) return false; if (compile_helper::wanted(bytes)) return false; // the helper compiles it, in its own process diff --git a/runtime/src/pipeline_wait.h b/runtime/src/pipeline_wait.h index b9e7ba936a..2d74d8581f 100644 --- a/runtime/src/pipeline_wait.h +++ b/runtime/src/pipeline_wait.h @@ -1,7 +1,7 @@ #pragma once // When the title last submitted, for the compute warm-ups (runtime/shims/d3d12_vulkan_device.cpp, -// LEONIDA_COMPUTE_WARMUP_LIVE_MAX_BYTES): while the title submits, a warm-up of a big module is left to the pipeline's -// first use, since a create holds the compile gate for its whole length and every submission waits behind it. +// LEONIDA_COMPUTE_WARMUP_LIVE_MAX_BYTES, opt-in): while the title submits, a warm-up of a big module is left to the +// pipeline's first use, since a create holds the compile gate for its whole length and every submission waits behind it. // No windows.h here: vulkan_backend.h includes this, and translation units without NOMINMAX include that. #include #include